feat(client): redesign native UI, themes, settings and avatars

Separate conversation drafts and voice view state, add native settings and restricted CSS themes, implement validated avatar cropping, and refresh dependencies with documented desktop compatibility backports.
This commit is contained in:
Loki 2026-10-24 14:23:48 +02:00
parent 44d284a568
commit 8e5ab56611
Signed by: boba
GPG key ID: 253067914055423B
276 changed files with 53546 additions and 3399 deletions

View file

@ -0,0 +1,20 @@
# Maintenance backport verification
Verified with local Rust1.99.0 on Linux.
- `cargo check --workspace`: passed.
- `cargo test --workspace --locked`: 49passed (34library,15binary),0failed.
- `cargo build --workspace --locked`: passed.
- `cargo clippy --all-targets --locked -- -D warnings`: passed.
- `cargo fmt --check` and `git diff --check`: passed.
- `cargo audit --no-fetch --json`:0knownvulnerabilities,0warnings.
- Private real D-Bus integration in `desktop-smoke`:1passed; no manual zbus executor ticks.
- Native software-rendered shell/settings/light/dark/black/custom/profile/avatar screens generated by actual UI smoke; avatar rendering visually inspected.
All five original unmaintained package names (bincode, ttf-parser, zbus_names, zvariant, zvariant_derive) are absent from Cargo.lock. No advisory ignores, packageversion spoofing, or dropped accessibility/portal/Wayland functionality.
Independent read-only review checked buildervalidation, wire decoding equivalence, original Linux-only target scope, and CSD feature preservation. Tests confirm proxy calls/eventroundtrip and invalidpathrejection on an isolated D-Bus daemon.
Limitations: no real screenreader/assistive-technology acceptance run, no manual live portal chooser test, no Windows/macOS build or Rust1.94 test in this task. Keep monitoring maintained parents and remove local backports once equivalent upstream releases are available.
Focused follow-up: full preserved atspi-common upstream library suite1141passed/0failed/0ignored after migrating its test-only APIs/imports; reproducible with `python3 patches/test-upstream.py`. Official Slint archive includesnestedLICENSES; COPYING byte-matches officialGPL-3.0-only exactrevision, applicableGPLchoiceexplicit. Reviewdiffs regenerated.

29
patches/README.md Normal file
View file

@ -0,0 +1,29 @@
# Maintained upstream compatibility backports
These patches migrate maintained UI/accessibility callers to maintained zbus 6 after zvariant/zbus_names merged upstream. They preserve accessibility, portal, and Wayland support. They do not vendor unmaintained codecs or suppress RustSec. Each directory retains the source license and VNOX-PATCH.md provenance.
Slint's Wayland CSD selects supported crossfont, adding native FreeType/fontconfig build dependencies on Linux. Use `libfreetype6-dev libfontconfig1-dev` on Debian/Ubuntu.
All patch changes must be removed when compatible upstream releases incorporate the migration. The compatibility baseline remains the published version, not a forged new version.
## Verification and removal policy
`upstream-sources.json` records exact published archive digests and upstream revisions; `changes/*.patch` contains concise diffs against those sources. These wrappers are local maintenance backports; they do not imply upstream has released these exact changes.
The Slint migration preserves its original Linux-only D-Bus target scope. zbus6 stores invalid builder arguments until build(), owns its runtime, and object_server.at returns None on successful insertion. The AccessKit port respects those semantics.
`typed-index-collections` is held at compatible 3.2.3 as a build dependency because later compatible releases add unused optional bincode integration to the lockfile. That pin removes an unused capability rather than replacing a serializer or ignoring an advisory.
Run root `cargo check --workspace`, `cargo test --workspace --locked`, `cargo clippy --all-targets --locked -- -D warnings`, `cargo audit --no-fetch`. Run a real isolated D-Bus integration check with:
```sh
dbus-run-session -- cargo test --manifest-path patches/desktop-smoke/Cargo.toml --target-dir target
```
The smoke check covers maintained runtime progress without manual executor ticks, AT-SPI proxy calls and event serialization, duplicate interface registration, and deferred invalid-path rejection. It does not replace a real assistive-technology or cross-platform acceptance test.
## Preserved upstream tests
Run `python3 patches/test-upstream.py` to compile and run the full preserved atspi-common library suite from exact patched sources and XML fixtures in a temporary standalone workspace. Cargo otherwise cannot run dev-dependency tests for a dependency excluded from the application workspace. No tests are filtered or ignored. Verified: **1141 passed, 0 failed, 0 ignored**. Test-only imports and message builders were migrated to zbus6 rather than hiding their build failures.
Slint's original archive license texts are preserved under its patch's `LICENSES/`; `COPYING` additionally records the exact-revision official GPL3 text selected for this GPL Vnox distribution. See its VNOX-PATCH.md for provenance and checksum.

View file

@ -0,0 +1,528 @@
# Changelog
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.12.2 to 0.12.3
* accesskit_consumer bumped from 0.17.0 to 0.17.1
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.19.0 to 0.19.1
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.0 to 0.16.1
* accesskit_consumer bumped from 0.24.0 to 0.24.1
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.2 to 0.16.3
* accesskit_consumer bumped from 0.24.2 to 0.24.3
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.17.0 to 0.17.1
* accesskit_consumer bumped from 0.25.0 to 0.26.0
## [0.19.1](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.19.0...accesskit_atspi_common-v0.19.1) (2026-07-14)
### Bug Fixes
* Update Tree::toolkit_name call sites in the adapters ([27734d8](https://github.com/AccessKit/accesskit/commit/27734d8409d9e03f51caefe1c13ae4ff74e3c6b2))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.37.0 to 0.38.0
## [0.19.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.18.1...accesskit_atspi_common-v0.19.0) (2026-06-12)
### ⚠ BREAKING CHANGES
* Trim trait bounds on iterator return types ([#721](https://github.com/AccessKit/accesskit/issues/721))
### Features
* Implement the cache object on Unix ([#719](https://github.com/AccessKit/accesskit/issues/719)) ([61bdabd](https://github.com/AccessKit/accesskit/commit/61bdabdb70016068c21e31bf42b36bc4209232cd))
### Bug Fixes
* Compute index in parent for tree roots on Unix ([#718](https://github.com/AccessKit/accesskit/issues/718)) ([7d8c55e](https://github.com/AccessKit/accesskit/commit/7d8c55e55cce4b88c289e96fccb67a38d0afa27f))
### Code Refactoring
* Trim trait bounds on iterator return types ([#721](https://github.com/AccessKit/accesskit/issues/721)) ([4023b41](https://github.com/AccessKit/accesskit/commit/4023b414c3c1318ec2780b13a4e9f70713703862))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.24.0 to 0.24.1
* accesskit_consumer bumped from 0.36.0 to 0.37.0
## [0.18.1](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.18.0...accesskit_atspi_common-v0.18.1) (2026-05-11)
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.35.0 to 0.36.0
## [0.18.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.17.0...accesskit_atspi_common-v0.18.0) (2026-03-04)
### Features
* Implement text attributes for AT-SPI ([#695](https://github.com/AccessKit/accesskit/issues/695)) ([33fc4f0](https://github.com/AccessKit/accesskit/commit/33fc4f06699da335f9b2de3ab381cc940314e9c1))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.34.0 to 0.35.0
## [0.17.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.16.1...accesskit_atspi_common-v0.17.0) (2026-02-01)
### ⚠ BREAKING CHANGES
* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683))
### Bug Fixes
* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683)) ([f8c22cb](https://github.com/AccessKit/accesskit/commit/f8c22cbb53ce6b1859adeff3c0b7154ad9e1f25e))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.23.0 to 0.24.0
* accesskit_consumer bumped from 0.33.1 to 0.34.0
## [0.16.1](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.16.0...accesskit_atspi_common-v0.16.1) (2026-01-18)
### Bug Fixes
* Emit initial focus event for active descendant node ([#681](https://github.com/AccessKit/accesskit/issues/681)) ([13a37d1](https://github.com/AccessKit/accesskit/commit/13a37d144e2fafceaf26e7645f6acc679ccb2f34))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.33.0 to 0.33.1
## [0.16.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.15.0...accesskit_atspi_common-v0.16.0) (2026-01-15)
### ⚠ BREAKING CHANGES
* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655))
### Features
* Implement the `url` property ([#669](https://github.com/AccessKit/accesskit/issues/669)) ([6202e63](https://github.com/AccessKit/accesskit/commit/6202e63c667e73216a306b3dd45ff25c364a4f45))
* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655)) ([c16eb80](https://github.com/AccessKit/accesskit/commit/c16eb80c49d14f39e8a7defb1694bf22b8ceed6f))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.22.0 to 0.23.0
* accesskit_consumer bumped from 0.32.0 to 0.33.0
## [0.15.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.14.2...accesskit_atspi_common-v0.15.0) (2025-12-23)
### ⚠ BREAKING CHANGES
* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642))
* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626))
### Features
* Add GridCell role ([#643](https://github.com/AccessKit/accesskit/issues/643)) ([1e5abca](https://github.com/AccessKit/accesskit/commit/1e5abca737d1ee942c0804fec2c06d3cb08faa94))
* Implement BrailleLabel and BrailleRoleDescription roles ([#638](https://github.com/AccessKit/accesskit/issues/638)) ([0fdcebb](https://github.com/AccessKit/accesskit/commit/0fdcebb55e308e039ec99fbc31e94e8087a69f2d))
* Rename HeaderAsNonLandmark to SectionHeader, FooterAsNonLandmark to SectionFooter ([#635](https://github.com/AccessKit/accesskit/issues/635)) ([dd69526](https://github.com/AccessKit/accesskit/commit/dd695260877cb862ece4c2b7d8607308f5fed608))
### Bug Fixes
* Bump atspi crates ([dbf81c9](https://github.com/AccessKit/accesskit/commit/dbf81c968739187a9f4c3c105d0618c0f9db3135))
* Expose dialogs in the platform adapters ([1576a94](https://github.com/AccessKit/accesskit/commit/1576a940ec3e9066fc5e181419dae6899bf2db46))
* Replace thiserror with manual trait implementations ([#652](https://github.com/AccessKit/accesskit/issues/652)) ([b42c5e2](https://github.com/AccessKit/accesskit/commit/b42c5e25659aeb74d7f534ef2a8745d80227c1e3))
### Code Refactoring
* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642)) ([4d46c27](https://github.com/AccessKit/accesskit/commit/4d46c2740631c5fe4f057707b949d12b26931d0b))
* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626)) ([ea23ec4](https://github.com/AccessKit/accesskit/commit/ea23ec424c7dbb8841e03d71b6a15b74264850a9))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.21.1 to 0.22.0
* accesskit_consumer bumped from 0.31.0 to 0.32.0
## [0.14.2](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.14.1...accesskit_atspi_common-v0.14.2) (2025-10-20)
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.30.1 to 0.31.0
## [0.14.1](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.14.0...accesskit_atspi_common-v0.14.1) (2025-10-02)
### Bug Fixes
* Fix clippy warnings introduced in 1.89 ([#606](https://github.com/AccessKit/accesskit/issues/606)) ([b2c07d6](https://github.com/AccessKit/accesskit/commit/b2c07d654a8ce6f01e61a79c91f2f9d5a96afdc9))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.21.0 to 0.21.1
* accesskit_consumer bumped from 0.30.0 to 0.30.1
## [0.14.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.13.0...accesskit_atspi_common-v0.14.0) (2025-07-16)
### ⚠ BREAKING CHANGES
* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594))
### Features
* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594)) ([1d9b74c](https://github.com/AccessKit/accesskit/commit/1d9b74c057051509b3ffbf63afeacfb16f544ff8))
* Let parents declare actions supported on their children ([#593](https://github.com/AccessKit/accesskit/issues/593)) ([70b534b](https://github.com/AccessKit/accesskit/commit/70b534bed168a84b84cc35199588aa8ab784fb43))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.20.0 to 0.21.0
* accesskit_consumer bumped from 0.29.0 to 0.30.0
## [0.13.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.12.0...accesskit_atspi_common-v0.13.0) (2025-06-26)
### ⚠ BREAKING CHANGES
* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589))
### Bug Fixes
* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589)) ([2887cdd](https://github.com/AccessKit/accesskit/commit/2887cddde817ba3851688068d8d10de5cef7c624))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.19.0 to 0.20.0
* accesskit_consumer bumped from 0.28.0 to 0.29.0
## [0.12.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.11.0...accesskit_atspi_common-v0.12.0) (2025-05-06)
### ⚠ BREAKING CHANGES
* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550))
### Features
* Expose tabs in consumer and atspi-common ([b1fb5b3](https://github.com/AccessKit/accesskit/commit/b1fb5b3de12c001e34021263038b66a6e3a7dd1e))
### Bug Fixes
* Fix a compilation error in atspi-common `Event::new` ([#537](https://github.com/AccessKit/accesskit/issues/537)) ([23b4d8d](https://github.com/AccessKit/accesskit/commit/23b4d8d49fed378899855a40e63aff10e829f6e8))
### Code Refactoring
* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550)) ([56abf17](https://github.com/AccessKit/accesskit/commit/56abf17356e4c7f13f64aaeaca6a63c8f7ede553))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.18.0 to 0.19.0
* accesskit_consumer bumped from 0.27.0 to 0.28.0
## [0.11.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.10.1...accesskit_atspi_common-v0.11.0) (2025-03-06)
### ⚠ BREAKING CHANGES
* Optimize simple string getters ([#493](https://github.com/AccessKit/accesskit/issues/493))
* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492))
### Features
* Add list box support to the `consumer` and `atspi-common` crates ([d6dca15](https://github.com/AccessKit/accesskit/commit/d6dca15d5c298c797ab7a702f0186043eac33c5c))
* Expose the `is_required` property ([#497](https://github.com/AccessKit/accesskit/issues/497)) ([46ed99b](https://github.com/AccessKit/accesskit/commit/46ed99bb958ddb32cbf1bee2fcfb7b328bcbe0ab))
### Bug Fixes
* Derive `Debug` for adapters ([#513](https://github.com/AccessKit/accesskit/issues/513)) ([753d904](https://github.com/AccessKit/accesskit/commit/753d90473cf57682568c7a17c82474c8e5d00b25))
* Remove unnecessary explicit lifetimes ([#488](https://github.com/AccessKit/accesskit/issues/488)) ([d2bcd6d](https://github.com/AccessKit/accesskit/commit/d2bcd6d3048d23df4e132bee6171eb247b2dc2c8))
* Update zbus to 5.0 ([#519](https://github.com/AccessKit/accesskit/issues/519)) ([4c10b80](https://github.com/AccessKit/accesskit/commit/4c10b801b6924c7010b83f4eb44c8c350c860cf6))
### Code Refactoring
* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492)) ([089794c](https://github.com/AccessKit/accesskit/commit/089794c8f74957e91a19ae3df508e2a892f39ebc))
* Optimize simple string getters ([#493](https://github.com/AccessKit/accesskit/issues/493)) ([484fd7c](https://github.com/AccessKit/accesskit/commit/484fd7cbfb778222369d3f57d31dd998f6fa80d8))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.17.1 to 0.18.0
* accesskit_consumer bumped from 0.26.0 to 0.27.0
## [0.10.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.9.3...accesskit_atspi_common-v0.10.0) (2024-10-31)
### ⚠ BREAKING CHANGES
* Rename `name` to `label` and use `value` for label content ([#475](https://github.com/AccessKit/accesskit/issues/475))
* Rename `Role::InlineTextBox` to `TextRun` ([#473](https://github.com/AccessKit/accesskit/issues/473))
* Drop `DefaultActionVerb` ([#472](https://github.com/AccessKit/accesskit/issues/472))
* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468))
### Features
* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468)) ([2fa0d3f](https://github.com/AccessKit/accesskit/commit/2fa0d3f5b2b7ac11ef1751c133706f29e548bd6d))
### Code Refactoring
* Drop `DefaultActionVerb` ([#472](https://github.com/AccessKit/accesskit/issues/472)) ([ef3b003](https://github.com/AccessKit/accesskit/commit/ef3b0038224459094f650368412650bc3b69526b))
* Rename `name` to `label` and use `value` for label content ([#475](https://github.com/AccessKit/accesskit/issues/475)) ([e0053a5](https://github.com/AccessKit/accesskit/commit/e0053a5399929e8e0d4f07aa18de604ed8766ace))
* Rename `Role::InlineTextBox` to `TextRun` ([#473](https://github.com/AccessKit/accesskit/issues/473)) ([29fa341](https://github.com/AccessKit/accesskit/commit/29fa34125a811bd3a0f9da579a9f35c9da90bf29))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.3 to 0.17.0
* accesskit_consumer bumped from 0.24.3 to 0.25.0
## [0.9.2](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.9.1...accesskit_atspi_common-v0.9.2) (2024-10-07)
### Bug Fixes
* Update minimum supported Rust version to 1.75 ([#457](https://github.com/AccessKit/accesskit/issues/457)) ([fc622fe](https://github.com/AccessKit/accesskit/commit/fc622fe7657c80a4eedad6f6cded11d2538b54d5))
* Update to zbus v4 ([#456](https://github.com/AccessKit/accesskit/issues/456)) ([95db8f1](https://github.com/AccessKit/accesskit/commit/95db8f1c5f7f56598eab6910a990ccbf9d864dda))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.1 to 0.16.2
* accesskit_consumer bumped from 0.24.1 to 0.24.2
## [0.9.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.8.0...accesskit_atspi_common-v0.9.0) (2024-06-29)
### ⚠ BREAKING CHANGES
* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434))
### Bug Fixes
* Correctly handle recursive filtering ([#438](https://github.com/AccessKit/accesskit/issues/438)) ([72f9b42](https://github.com/AccessKit/accesskit/commit/72f9b424a5c6e7914df8bf31eeb2fc61be35f47b))
* Smarter calculation of AT-SPI extents for the window ([#435](https://github.com/AccessKit/accesskit/issues/435)) ([7f40fbc](https://github.com/AccessKit/accesskit/commit/7f40fbc811f863e99088cd7eb725994d0f79263f))
### Code Refactoring
* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434)) ([7086bc0](https://github.com/AccessKit/accesskit/commit/7086bc0fad446d3ed4a0fd5eff641a1e75f6c599))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.15.0 to 0.16.0
* accesskit_consumer bumped from 0.23.0 to 0.24.0
## [0.8.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.7.0...accesskit_atspi_common-v0.8.0) (2024-06-15)
### Features
* Feature-gate the `accesskit_atspi_common::simplified` module ([#430](https://github.com/AccessKit/accesskit/issues/430)) ([50341f1](https://github.com/AccessKit/accesskit/commit/50341f10cf32ef16c904d54725f717a585d21043))
### Bug Fixes
* Avoid unnecessary repeated checks for text changes ([#432](https://github.com/AccessKit/accesskit/issues/432)) ([0e89671](https://github.com/AccessKit/accesskit/commit/0e89671fc0cf831d2c86a2cacf0195e247560753))
## [0.7.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.6.0...accesskit_atspi_common-v0.7.0) (2024-06-09)
### Features
* Add `author_id` property ([#424](https://github.com/AccessKit/accesskit/issues/424)) ([0d1c56f](https://github.com/AccessKit/accesskit/commit/0d1c56f0bdde58715e1c69f6015df600cb7cb8c1))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.14.0 to 0.15.0
* accesskit_consumer bumped from 0.22.0 to 0.23.0
## [0.6.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.5.0...accesskit_atspi_common-v0.6.0) (2024-05-27)
### Features
* Expose the `orientation` property ([#421](https://github.com/AccessKit/accesskit/issues/421)) ([590aada](https://github.com/AccessKit/accesskit/commit/590aada070dc812f9b8f171fb9e43ac984fad2a1))
### Bug Fixes
* Fix a logic error in suffix calculation for text changes ([#423](https://github.com/AccessKit/accesskit/issues/423)) ([1121723](https://github.com/AccessKit/accesskit/commit/1121723983cb2fa64b5053626ec64afb851ff6c4))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.21.0 to 0.22.0
## [0.5.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.4.2...accesskit_atspi_common-v0.5.0) (2024-05-26)
### Features
* Add basic text support on Unix ([#362](https://github.com/AccessKit/accesskit/issues/362)) ([52540f8](https://github.com/AccessKit/accesskit/commit/52540f82cf9fc148358351ed486bab3e7e91f1d6))
* Expose the `placeholder` property ([#417](https://github.com/AccessKit/accesskit/issues/417)) ([8f4a0a1](https://github.com/AccessKit/accesskit/commit/8f4a0a1c10f83fcc8580a37d8013fec2d110865b))
### Bug Fixes
* Don't fire events for filtered children on Unix ([#414](https://github.com/AccessKit/accesskit/issues/414)) ([2bcb1b6](https://github.com/AccessKit/accesskit/commit/2bcb1b63e88b801b194a4db50059fa063efbee64))
* Improve how coordinates are computed on Unix ([#420](https://github.com/AccessKit/accesskit/issues/420)) ([fc5125e](https://github.com/AccessKit/accesskit/commit/fc5125e27f8f4f655e1de5049d0d53536284d9a0))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.20.0 to 0.21.0
## [0.4.2](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.4.1...accesskit_atspi_common-v0.4.2) (2024-05-13)
### Bug Fixes
* Fix platform adapters to support copy-on-write tree snapshots again ([#411](https://github.com/AccessKit/accesskit/issues/411)) ([d3a130a](https://github.com/AccessKit/accesskit/commit/d3a130a5ec8ae1d9edf0bf85a44f35f0e365242c))
* Return to handling focus events directly, after generic node changes ([#409](https://github.com/AccessKit/accesskit/issues/409)) ([cd2e35e](https://github.com/AccessKit/accesskit/commit/cd2e35e43817405199ae6acd64ef90aee445be0b))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.19.1 to 0.20.0
## [0.4.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.3.0...accesskit_atspi_common-v0.4.0) (2024-04-30)
### ⚠ BREAKING CHANGES
* Clean up table roles and properties ([#393](https://github.com/AccessKit/accesskit/issues/393))
* Rename `Checked` to `Toggled`; drop `ToggleButton` role ([#388](https://github.com/AccessKit/accesskit/issues/388))
### Features
* Implement the `description` property ([#382](https://github.com/AccessKit/accesskit/issues/382)) ([d49f406](https://github.com/AccessKit/accesskit/commit/d49f40660b5dc23ed074cd72a91e511b130756ae))
### Bug Fixes
* Increase minimum supported Rust version to `1.70` ([#396](https://github.com/AccessKit/accesskit/issues/396)) ([a8398b8](https://github.com/AccessKit/accesskit/commit/a8398b847aa003de91042ac45e33126fc2cae053))
### Code Refactoring
* Clean up table roles and properties ([#393](https://github.com/AccessKit/accesskit/issues/393)) ([e34dad9](https://github.com/AccessKit/accesskit/commit/e34dad94448a5321ece9def3f2e054aa5f62dd79))
* Rename `Checked` to `Toggled`; drop `ToggleButton` role ([#388](https://github.com/AccessKit/accesskit/issues/388)) ([6bc040b](https://github.com/AccessKit/accesskit/commit/6bc040b7cf75cdbd6a019cc380d8dbce804b3c81))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.13.0 to 0.14.0
* accesskit_consumer bumped from 0.18.0 to 0.19.0
## [0.3.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.2.0...accesskit_atspi_common-v0.3.0) (2024-04-14)
### ⚠ BREAKING CHANGES
* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375))
### Code Refactoring
* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375)) ([9baebdc](https://github.com/AccessKit/accesskit/commit/9baebdceed7300389b6768815d7ae48f1ce401e4))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.12.3 to 0.13.0
* accesskit_consumer bumped from 0.17.1 to 0.18.0
## [0.2.0](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.1.2...accesskit_atspi_common-v0.2.0) (2024-03-11)
### Features
* Expose root node ID in `accesskit_atspi_common::Adapter` ([#370](https://github.com/AccessKit/accesskit/issues/370)) ([a43b497](https://github.com/AccessKit/accesskit/commit/a43b497afbbbcf90e9d15259635a329164d6a791))
## [0.1.1](https://github.com/AccessKit/accesskit/compare/accesskit_atspi_common-v0.1.0...accesskit_atspi_common-v0.1.1) (2024-02-24)
### Bug Fixes
* Add missing README ([#357](https://github.com/AccessKit/accesskit/issues/357)) ([e8cf48e](https://github.com/AccessKit/accesskit/commit/e8cf48e21be0146768b2d14289164d192823fd1f))
## 0.1.0 (2024-02-24)
### Features
* Factor out core AT-SPI translation layer ([#352](https://github.com/AccessKit/accesskit/issues/352)) ([8c0ab58](https://github.com/AccessKit/accesskit/commit/8c0ab58d441c0d4484e0bc31a554bdfb3f088cd6))

View file

@ -0,0 +1,64 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.85"
name = "accesskit_atspi_common"
version = "0.19.1"
authors = ["The AccessKit contributors"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "AccessKit UI accessibility infrastructure: core AT-SPI translation layer"
readme = "README.md"
keywords = [
"gui",
"ui",
"accessibility",
]
categories = ["gui"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/AccessKit/accesskit"
resolver = "2"
[features]
simplified-api = []
[lib]
name = "accesskit_atspi_common"
path = "src/lib.rs"
[dependencies.accesskit]
version = "0.24.1"
[dependencies.accesskit_consumer]
version = "0.38.0"
[dependencies.atspi-common]
version = "0.13"
default-features = false
[dependencies.phf]
version = "0.13.1"
features = ["macros"]
[dependencies.serde]
version = "1.0"
[dependencies.zbus]
version = "6.1"
default-features = false
features = ["default-rt", "proxy", "service", "object-manager"]

View file

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View file

@ -0,0 +1,23 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,3 @@
# AccessKit common AT-SPI translation layer
This crate contains common logic for translating between AccessKit and AT-SPI. It is shared by the AccessKit Unix adapter and the new, experimental GNOME accessibility stack (code-named Newton) which is based on pushing AccessKit tree updates to the assistive technology.

View file

@ -0,0 +1,9 @@
# Vnox maintenance patch: accesskit_atspi_common 0.19.1
Source: published crates.io accesskit_atspi_common 0.19.1, original licenses included.
This is a maintained-parent compatibility backport, not a fork of an unmaintained D-Bus codec. Vnox updates dependencies/imports to maintained zbus 6, which merged zvariant and zbus_names. The original package version identifies its API baseline; no version is spoofed to suppress RustSec.
The Slint Winit patch additionally uses Winit's supported crossfont CSD backend to avoid the unmaintained ttf-parser chain while retaining Wayland client-side title decorations.
Remove this patch once upstream publishes the equivalent migration. Changes must be tested with full client build, native rendering, accessibility/portal interfaces and RustSec audit.

View file

@ -0,0 +1,14 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use serde::{Deserialize, Serialize};
use zbus::wire::Type;
#[derive(Deserialize, Serialize, Type)]
pub struct Action {
pub localized_name: String,
pub description: String,
pub key_binding: String,
}

View file

@ -0,0 +1,822 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
// Derived from Chromium's accessibility abstraction.
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.chromium file.
use crate::{
AdapterCallback, CacheEvent, Event, ObjectEvent, WindowEvent,
context::{ActionHandlerNoMut, ActionHandlerWrapper, AppContext, Context},
filters::filter,
node::{NodeIdOrRoot, NodeWrapper, PlatformNode, PlatformRoot},
util::WindowBounds,
};
use accesskit::{ActionHandler, Role, TreeUpdate};
use accesskit_consumer::{FilterResult, Node, NodeId, Tree, TreeChangeHandler, TreeState};
use atspi_common::{InterfaceSet, Politeness, State};
use std::fmt::{Debug, Formatter};
use std::{
collections::HashSet,
sync::{
Arc, RwLock,
atomic::{AtomicUsize, Ordering},
},
};
struct AdapterChangeHandler<'a> {
adapter: &'a Adapter,
added_nodes: HashSet<NodeId>,
removed_nodes: HashSet<NodeId>,
checked_text_change: HashSet<NodeId>,
selection_changed: HashSet<NodeId>,
}
impl<'a> AdapterChangeHandler<'a> {
fn new(adapter: &'a Adapter) -> Self {
Self {
adapter,
added_nodes: HashSet::new(),
removed_nodes: HashSet::new(),
checked_text_change: HashSet::new(),
selection_changed: HashSet::new(),
}
}
fn add_node(&mut self, node: &Node) {
let id = node.id();
if self.added_nodes.contains(&id) {
return;
}
self.added_nodes.insert(id);
let role = node.role();
let is_root = node.is_root();
let wrapper = NodeWrapper(node);
let interfaces = wrapper.interfaces();
self.adapter.register_interfaces(node.id(), interfaces);
self.adapter.emit_cache_added(node.id());
if is_root && role == Role::Window {
let adapter_index = self
.adapter
.context
.read_app_context()
.adapter_index(self.adapter.id)
.unwrap();
self.adapter.window_created(adapter_index, node.id());
}
let live = wrapper.live();
if live != Politeness::None {
if let Some(name) = wrapper.name() {
self.adapter
.emit_object_event(node.id(), ObjectEvent::Announcement(name, live));
}
}
if let Some(true) = node.is_selected() {
self.enqueue_selection_changed_if_needed(node);
}
}
fn add_subtree(&mut self, node: &Node) {
self.add_node(node);
for child in node.filtered_children(&filter) {
self.add_subtree(&child);
}
}
fn remove_node(&mut self, node: &Node) {
let id = node.id();
if self.removed_nodes.contains(&id) {
return;
}
self.removed_nodes.insert(id);
let role = node.role();
let is_root = node.is_root();
let wrapper = NodeWrapper(node);
if is_root && role == Role::Window {
self.adapter.window_destroyed(node.id());
}
self.adapter
.emit_object_event(node.id(), ObjectEvent::StateChanged(State::Defunct, true));
self.adapter.emit_cache_removed(node.id());
self.adapter
.unregister_interfaces(node.id(), wrapper.interfaces());
if let Some(true) = node.is_selected() {
self.enqueue_selection_changed_if_needed(node);
}
}
fn remove_subtree(&mut self, node: &Node) {
for child in node.filtered_children(&filter) {
self.remove_subtree(&child);
}
self.remove_node(node);
}
fn emit_text_change_if_needed_parent(&mut self, old_node: &Node, new_node: &Node) {
if !new_node.supports_text_ranges() || !old_node.supports_text_ranges() {
return;
}
let id = new_node.id();
if self.checked_text_change.contains(&id) {
return;
}
self.checked_text_change.insert(id);
let old_text = old_node.document_range().text();
let new_text = new_node.document_range().text();
let mut old_chars = old_text.chars();
let mut new_chars = new_text.chars();
let mut prefix_usv_count = 0;
let mut prefix_byte_count = 0;
loop {
match (old_chars.next(), new_chars.next()) {
(Some(old_char), Some(new_char)) if old_char == new_char => {
prefix_usv_count += 1;
prefix_byte_count += new_char.len_utf8();
}
(None, None) => return,
_ => break,
}
}
let suffix_byte_count = old_text[prefix_byte_count..]
.chars()
.rev()
.zip(new_text[prefix_byte_count..].chars().rev())
.take_while(|(old_char, new_char)| old_char == new_char)
.fold(0, |count, (c, _)| count + c.len_utf8());
let old_content = &old_text[prefix_byte_count..old_text.len() - suffix_byte_count];
if let Ok(length) = old_content.chars().count().try_into() {
if length > 0 {
self.adapter.emit_object_event(
id,
ObjectEvent::TextRemoved {
start_index: prefix_usv_count,
length,
content: old_content.to_string(),
},
);
}
}
let new_content = &new_text[prefix_byte_count..new_text.len() - suffix_byte_count];
if let Ok(length) = new_content.chars().count().try_into() {
if length > 0 {
self.adapter.emit_object_event(
id,
ObjectEvent::TextInserted {
start_index: prefix_usv_count,
length,
content: new_content.to_string(),
},
);
}
}
}
fn emit_text_change_if_needed(&mut self, old_node: &Node, new_node: &Node) {
if let Role::TextRun | Role::GenericContainer = new_node.role() {
if let (Some(old_parent), Some(new_parent)) = (
old_node.filtered_parent(&filter),
new_node.filtered_parent(&filter),
) {
self.emit_text_change_if_needed_parent(&old_parent, &new_parent);
}
} else {
self.emit_text_change_if_needed_parent(old_node, new_node);
}
}
fn emit_text_selection_change(&self, old_node: Option<&Node>, new_node: &Node) {
if !new_node.supports_text_ranges() {
return;
}
let Some(old_node) = old_node else {
if let Some(selection) = new_node.text_selection() {
if !selection.is_degenerate() {
self.adapter
.emit_object_event(new_node.id(), ObjectEvent::TextSelectionChanged);
}
}
if let Some(selection_focus) = new_node.text_selection_focus() {
if let Ok(offset) = selection_focus.to_global_usv_index().try_into() {
self.adapter
.emit_object_event(new_node.id(), ObjectEvent::CaretMoved(offset));
}
}
return;
};
if !old_node.is_focused() || new_node.raw_text_selection() == old_node.raw_text_selection()
{
return;
}
if let Some(selection) = new_node.text_selection() {
if !selection.is_degenerate()
|| old_node
.text_selection()
.map(|selection| !selection.is_degenerate())
.unwrap_or(false)
{
self.adapter
.emit_object_event(new_node.id(), ObjectEvent::TextSelectionChanged);
}
}
let old_caret_position = old_node
.raw_text_selection()
.map(|selection| selection.focus);
let new_caret_position = new_node
.raw_text_selection()
.map(|selection| selection.focus);
if old_caret_position != new_caret_position {
if let Some(selection_focus) = new_node.text_selection_focus() {
if let Ok(offset) = selection_focus.to_global_usv_index().try_into() {
self.adapter
.emit_object_event(new_node.id(), ObjectEvent::CaretMoved(offset));
}
}
}
}
fn enqueue_selection_changed_if_needed_parent(&mut self, node: Node) {
if !node.is_container_with_selectable_children() {
return;
}
let id = node.id();
if self.selection_changed.contains(&id) {
return;
}
self.selection_changed.insert(id);
}
fn enqueue_selection_changed_if_needed(&mut self, node: &Node) {
if !node.is_item_like() {
return;
}
if let Some(node) = node.selection_container(&filter) {
self.enqueue_selection_changed_if_needed_parent(node);
}
}
fn emit_selection_changed(&mut self) {
for id in self.selection_changed.iter() {
if self.removed_nodes.contains(id) {
continue;
}
self.adapter
.emit_object_event(*id, ObjectEvent::SelectionChanged);
}
}
}
impl TreeChangeHandler for AdapterChangeHandler<'_> {
fn node_added(&mut self, node: &Node) {
if filter(node) == FilterResult::Include {
self.add_node(node);
}
}
fn node_updated(&mut self, old_node: &Node, new_node: &Node) {
self.emit_text_change_if_needed(old_node, new_node);
let filter_old = filter(old_node);
let filter_new = filter(new_node);
if filter_new != filter_old {
if filter_new == FilterResult::Include {
if filter_old == FilterResult::ExcludeSubtree {
self.add_subtree(new_node);
} else {
self.add_node(new_node);
}
} else if filter_old == FilterResult::Include {
if filter_new == FilterResult::ExcludeSubtree {
self.remove_subtree(old_node);
} else {
self.remove_node(old_node);
}
}
} else if filter_new == FilterResult::Include {
let old_wrapper = NodeWrapper(old_node);
let new_wrapper = NodeWrapper(new_node);
let old_interfaces = old_wrapper.interfaces();
let new_interfaces = new_wrapper.interfaces();
let kept_interfaces = old_interfaces & new_interfaces;
self.adapter
.unregister_interfaces(new_wrapper.id(), old_interfaces ^ kept_interfaces);
self.adapter
.register_interfaces(new_node.id(), new_interfaces ^ kept_interfaces);
let bounds = *self.adapter.context.read_root_window_bounds();
new_wrapper.notify_changes(&bounds, self.adapter, &old_wrapper);
self.emit_text_selection_change(Some(old_node), new_node);
if new_node.is_selected() != old_node.is_selected() {
self.enqueue_selection_changed_if_needed(new_node);
}
}
}
fn focus_moved(&mut self, old_node: Option<&Node>, new_node: Option<&Node>) {
if let (None, Some(new_node)) = (old_node, new_node) {
if let Some(root_window) = root_window(new_node.tree_state) {
self.adapter.window_activated(&NodeWrapper(&root_window));
}
} else if let (Some(old_node), None) = (old_node, new_node) {
if let Some(root_window) = root_window(old_node.tree_state) {
self.adapter.window_deactivated(&NodeWrapper(&root_window));
}
}
if let Some(node) = new_node {
self.adapter
.emit_object_event(node.id(), ObjectEvent::StateChanged(State::Focused, true));
self.emit_text_selection_change(None, node);
}
if let Some(node) = old_node {
self.adapter
.emit_object_event(node.id(), ObjectEvent::StateChanged(State::Focused, false));
}
}
fn node_removed(&mut self, node: &Node) {
if filter(node) == FilterResult::Include {
self.remove_node(node);
}
}
}
static NEXT_ADAPTER_ID: AtomicUsize = AtomicUsize::new(0);
/// If you use this function, you must ensure that only one adapter at a time
/// has a given ID.
pub fn next_adapter_id() -> usize {
NEXT_ADAPTER_ID.fetch_add(1, Ordering::Relaxed)
}
pub struct Adapter {
id: usize,
callback: Box<dyn AdapterCallback + Send + Sync>,
context: Arc<Context>,
}
impl Debug for Adapter {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Adapter")
.field("id", &self.id)
.field("callback", &"AdapterCallback")
.field("context", &self.context)
.finish()
}
}
impl Adapter {
pub fn new(
app_context: &Arc<RwLock<AppContext>>,
callback: impl 'static + AdapterCallback + Send + Sync,
initial_state: TreeUpdate,
is_window_focused: bool,
root_window_bounds: WindowBounds,
action_handler: impl 'static + ActionHandler + Send,
) -> Self {
let id = next_adapter_id();
Self::with_id(
id,
app_context,
callback,
initial_state,
is_window_focused,
root_window_bounds,
action_handler,
)
}
pub fn with_id(
id: usize,
app_context: &Arc<RwLock<AppContext>>,
callback: impl 'static + AdapterCallback + Send + Sync,
initial_state: TreeUpdate,
is_window_focused: bool,
root_window_bounds: WindowBounds,
action_handler: impl 'static + ActionHandler + Send,
) -> Self {
Self::with_wrapped_action_handler(
id,
app_context,
callback,
initial_state,
is_window_focused,
root_window_bounds,
Arc::new(ActionHandlerWrapper::new(action_handler)),
)
}
/// This is an implementation detail of `accesskit_unix`, required for
/// robust state transitions with minimal overhead.
pub fn with_wrapped_action_handler(
id: usize,
app_context: &Arc<RwLock<AppContext>>,
callback: impl 'static + AdapterCallback + Send + Sync,
initial_state: TreeUpdate,
is_window_focused: bool,
root_window_bounds: WindowBounds,
action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>,
) -> Self {
let tree = Tree::new(initial_state, is_window_focused);
let focus_id = tree.state().focus().map(|node| node.id());
let context = Context::new(app_context, tree, action_handler, root_window_bounds);
context.write_app_context().push_adapter(id, &context);
let adapter = Self {
id,
callback: Box::new(callback),
context,
};
adapter.register_tree();
if let Some(id) = focus_id {
adapter.emit_object_event(id, ObjectEvent::StateChanged(State::Focused, true));
}
adapter
}
fn register_tree(&self) {
fn add_children(node: Node<'_>, to_add: &mut Vec<(NodeId, InterfaceSet)>) {
for child in node.filtered_children(&filter) {
let child_id = child.id();
let wrapper = NodeWrapper(&child);
let interfaces = wrapper.interfaces();
to_add.push((child_id, interfaces));
add_children(child, to_add);
}
}
let mut objects_to_add = Vec::new();
let (adapter_index, root_id) = {
let tree = self.context.read_tree();
let tree_state = tree.state();
let mut app_context = self.context.write_app_context();
app_context.toolkit_name = Some(tree_state.toolkit_name().to_string());
app_context.toolkit_version = tree_state.toolkit_version().map(|s| s.to_string());
let adapter_index = app_context.adapter_index(self.id).unwrap();
let root = tree_state.root();
let root_id = root.id();
let wrapper = NodeWrapper(&root);
objects_to_add.push((root_id, wrapper.interfaces()));
add_children(root, &mut objects_to_add);
(adapter_index, root_id)
};
for (id, interfaces) in objects_to_add {
self.register_interfaces(id, interfaces);
if id == root_id {
self.window_created(adapter_index, id);
}
}
}
pub fn platform_node(&self, id: NodeId) -> PlatformNode {
PlatformNode::new(&self.context, self.id, id)
}
pub fn root_id(&self) -> NodeId {
self.context.read_tree().state().root_id()
}
pub fn platform_root(&self) -> PlatformRoot {
PlatformRoot::new(&self.context.app_context)
}
fn register_interfaces(&self, id: NodeId, new_interfaces: InterfaceSet) {
self.callback.register_interfaces(self, id, new_interfaces);
}
fn unregister_interfaces(&self, id: NodeId, old_interfaces: InterfaceSet) {
self.callback
.unregister_interfaces(self, id, old_interfaces);
}
pub(crate) fn emit_object_event(&self, target: NodeId, event: ObjectEvent) {
let target = NodeIdOrRoot::Node(target);
self.callback
.emit_event(self, Event::Object { target, event });
}
fn emit_root_object_event(&self, event: ObjectEvent) {
let target = NodeIdOrRoot::Root;
self.callback
.emit_event(self, Event::Object { target, event });
}
fn emit_cache_added(&self, target: NodeId) {
self.callback
.emit_event(self, Event::Cache(CacheEvent::Added(target)));
}
fn emit_cache_removed(&self, target: NodeId) {
self.callback
.emit_event(self, Event::Cache(CacheEvent::Removed(target)));
}
pub fn set_root_window_bounds(&mut self, new_bounds: WindowBounds) {
let mut bounds = self.context.root_window_bounds.write().unwrap();
*bounds = new_bounds;
}
pub fn update(&mut self, update: TreeUpdate) {
let mut handler = AdapterChangeHandler::new(self);
let mut tree = self.context.tree.write().unwrap();
tree.update_and_process_changes(update, &mut handler);
drop(tree);
handler.emit_selection_changed();
}
pub fn update_window_focus_state(&mut self, is_focused: bool) {
let mut handler = AdapterChangeHandler::new(self);
let mut tree = self.context.tree.write().unwrap();
tree.update_host_focus_state_and_process_changes(is_focused, &mut handler);
}
fn window_created(&self, adapter_index: usize, window: NodeId) {
self.emit_root_object_event(ObjectEvent::ChildAdded(adapter_index, window));
}
fn window_activated(&self, window: &NodeWrapper<'_>) {
self.callback.emit_event(
self,
Event::Window {
target: window.id(),
name: window.name().unwrap_or_default(),
event: WindowEvent::Activated,
},
);
self.emit_object_event(window.id(), ObjectEvent::StateChanged(State::Active, true));
self.emit_root_object_event(ObjectEvent::ActiveDescendantChanged(window.id()));
}
fn window_deactivated(&self, window: &NodeWrapper<'_>) {
self.callback.emit_event(
self,
Event::Window {
target: window.id(),
name: window.name().unwrap_or_default(),
event: WindowEvent::Deactivated,
},
);
self.emit_object_event(window.id(), ObjectEvent::StateChanged(State::Active, false));
}
fn window_destroyed(&self, window: NodeId) {
self.emit_root_object_event(ObjectEvent::ChildRemoved(window));
}
pub fn id(&self) -> usize {
self.id
}
pub fn is_window_focused(&self) -> bool {
self.context.read_tree().state().is_host_focused()
}
pub fn root_window_bounds(&self) -> WindowBounds {
*self.context.read_root_window_bounds()
}
/// This is an implementation detail of `accesskit_unix`, required for
/// robust state transitions with minimal overhead.
pub fn wrapped_action_handler(&self) -> Arc<dyn ActionHandlerNoMut + Send + Sync> {
Arc::clone(&self.context.action_handler)
}
}
fn root_window(current_state: &TreeState) -> Option<Node<'_>> {
const WINDOW_ROLES: &[Role] = &[Role::AlertDialog, Role::Dialog, Role::Window];
let root = current_state.root();
if WINDOW_ROLES.contains(&root.role()) {
Some(root)
} else {
None
}
}
impl Drop for Adapter {
fn drop(&mut self) {
let root_id = self.context.read_tree().state().root_id();
self.window_destroyed(root_id);
// Note: We deliberately do the following here, not in a Drop
// implementation on context, because AppContext owns a second
// strong reference to Context, and we need that to be released.
self.context.write_app_context().remove_adapter(self.id);
}
}
#[cfg(test)]
mod tests {
use super::Adapter;
use crate::{AdapterCallback, AppContext, CacheEvent, Event, InterfaceSet, WindowBounds};
use accesskit::{
ActionHandler, ActionRequest, Node, NodeId as LocalNodeId, Role, Tree, TreeId, TreeUpdate,
};
use accesskit_consumer::NodeId;
use std::sync::{Arc, Mutex};
#[derive(Clone, Copy, Debug, PartialEq)]
enum CacheOp {
Added(NodeId),
Removed(NodeId),
}
struct CapturingCallback {
ops: Arc<Mutex<Vec<CacheOp>>>,
}
impl AdapterCallback for CapturingCallback {
fn register_interfaces(&self, _: &Adapter, _: NodeId, _: InterfaceSet) {}
fn unregister_interfaces(&self, _: &Adapter, _: NodeId, _: InterfaceSet) {}
fn emit_event(&self, _: &Adapter, event: Event) {
let mut ops = self.ops.lock().unwrap();
match event {
Event::Cache(CacheEvent::Added(id)) => ops.push(CacheOp::Added(id)),
Event::Cache(CacheEvent::Removed(id)) => ops.push(CacheOp::Removed(id)),
_ => {}
}
}
}
struct NoOpActionHandler;
impl ActionHandler for NoOpActionHandler {
fn do_action(&mut self, _request: ActionRequest) {}
}
fn with_children(role: Role, children: &[LocalNodeId]) -> Node {
let mut node = Node::new(role);
node.set_children(children.to_vec());
node
}
fn build(initial: TreeUpdate) -> (Adapter, Arc<Mutex<Vec<CacheOp>>>) {
let ops = Arc::new(Mutex::new(Vec::new()));
let app_context = AppContext::new(None);
let adapter = Adapter::new(
&app_context,
CapturingCallback { ops: ops.clone() },
initial,
false,
WindowBounds::default(),
NoOpActionHandler,
);
(adapter, ops)
}
fn initial_tree() -> TreeUpdate {
TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1)]),
),
(LocalNodeId(1), Node::new(Role::Button)),
],
tree: Some(Tree::new(LocalNodeId(0))),
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
}
}
fn update(nodes: Vec<(LocalNodeId, Node)>) -> TreeUpdate {
TreeUpdate {
nodes,
tree: None,
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
}
}
#[test]
fn no_cache_events_on_construction() {
let (_adapter, ops) = build(initial_tree());
assert!(ops.lock().unwrap().is_empty());
}
#[test]
fn add_node_emits_one_added() {
let (mut adapter, ops) = build(initial_tree());
ops.lock().unwrap().clear();
adapter.update(update(vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(LocalNodeId(2), Node::new(Role::Button)),
]));
let ops = ops.lock().unwrap();
assert_eq!(ops.len(), 1);
assert!(matches!(ops[0], CacheOp::Added(_)));
}
#[test]
fn remove_node_emits_removed_for_same_id() {
let (mut adapter, ops) = build(initial_tree());
adapter.update(update(vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(LocalNodeId(2), Node::new(Role::Button)),
]));
let added_id = match ops.lock().unwrap().as_slice() {
[CacheOp::Added(id)] => *id,
other => panic!("expected exactly one Added, got {other:?}"),
};
ops.lock().unwrap().clear();
adapter.update(update(vec![(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1)]),
)]));
assert_eq!(*ops.lock().unwrap(), vec![CacheOp::Removed(added_id)]);
}
#[test]
fn subtree_add_emits_added_per_node() {
let (mut adapter, ops) = build(initial_tree());
ops.lock().unwrap().clear();
adapter.update(update(vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(
LocalNodeId(2),
with_children(Role::Group, &[LocalNodeId(3), LocalNodeId(4)]),
),
(LocalNodeId(3), Node::new(Role::Button)),
(LocalNodeId(4), Node::new(Role::Button)),
]));
let ops = ops.lock().unwrap();
assert_eq!(ops.len(), 3);
assert!(ops.iter().all(|op| matches!(op, CacheOp::Added(_))));
}
#[test]
fn subtree_remove_emits_removed_per_node() {
let (mut adapter, ops) = build(initial_tree());
adapter.update(update(vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(
LocalNodeId(2),
with_children(Role::Group, &[LocalNodeId(3), LocalNodeId(4)]),
),
(LocalNodeId(3), Node::new(Role::Button)),
(LocalNodeId(4), Node::new(Role::Button)),
]));
ops.lock().unwrap().clear();
adapter.update(update(vec![(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1)]),
)]));
let ops = ops.lock().unwrap();
assert_eq!(ops.len(), 3);
assert!(ops.iter().all(|op| matches!(op, CacheOp::Removed(_))));
}
#[test]
fn filter_transition_into_tree_emits_added() {
let mut hidden = Node::new(Role::Button);
hidden.set_hidden();
let (mut adapter, ops) = build(TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(LocalNodeId(1), Node::new(Role::Button)),
(LocalNodeId(2), hidden),
],
tree: Some(Tree::new(LocalNodeId(0))),
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
});
ops.lock().unwrap().clear();
adapter.update(update(vec![(LocalNodeId(2), Node::new(Role::Button))]));
let ops = ops.lock().unwrap();
assert_eq!(ops.len(), 1);
assert!(matches!(ops[0], CacheOp::Added(_)));
}
#[test]
fn filter_transition_out_of_tree_emits_removed() {
let (mut adapter, ops) = build(initial_tree());
ops.lock().unwrap().clear();
let mut hidden = Node::new(Role::Button);
hidden.set_hidden();
adapter.update(update(vec![(LocalNodeId(1), hidden)]));
let ops = ops.lock().unwrap();
assert_eq!(ops.len(), 1);
assert!(matches!(ops[0], CacheOp::Removed(_)));
}
}

View file

@ -0,0 +1,15 @@
// Copyright 2023 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_consumer::NodeId;
use atspi_common::InterfaceSet;
use crate::{Adapter, Event};
pub trait AdapterCallback {
fn register_interfaces(&self, adapter: &Adapter, id: NodeId, interfaces: InterfaceSet);
fn unregister_interfaces(&self, adapter: &Adapter, id: NodeId, interfaces: InterfaceSet);
fn emit_event(&self, adapter: &Adapter, event: Event);
}

View file

@ -0,0 +1,122 @@
// Copyright 2023 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit::{ActionHandler, ActionRequest};
use accesskit_consumer::Tree;
use std::fmt::{Debug, Formatter};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use crate::WindowBounds;
/// This is an implementation detail of `accesskit_unix`, required for robust
/// state transitions with minimal overhead.
pub trait ActionHandlerNoMut {
fn do_action(&self, request: ActionRequest);
}
/// This is an implementation detail of `accesskit_unix`, required for robust
/// state transitions with minimal overhead.
pub struct ActionHandlerWrapper<H: ActionHandler + Send>(Mutex<H>);
impl<H: 'static + ActionHandler + Send> ActionHandlerWrapper<H> {
pub fn new(inner: H) -> Self {
Self(Mutex::new(inner))
}
}
impl<H: ActionHandler + Send> ActionHandlerNoMut for ActionHandlerWrapper<H> {
fn do_action(&self, request: ActionRequest) {
self.0.lock().unwrap().do_action(request)
}
}
pub(crate) struct Context {
pub(crate) app_context: Arc<RwLock<AppContext>>,
pub(crate) tree: RwLock<Tree>,
pub(crate) action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>,
pub(crate) root_window_bounds: RwLock<WindowBounds>,
}
impl Debug for Context {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Context")
.field("app_context", &self.app_context)
.field("tree", &self.tree)
.field("action_handler", &"ActionHandler")
.field("root_window_bounds", &self.root_window_bounds)
.finish()
}
}
impl Context {
pub(crate) fn new(
app_context: &Arc<RwLock<AppContext>>,
tree: Tree,
action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>,
root_window_bounds: WindowBounds,
) -> Arc<Self> {
Arc::new(Self {
app_context: Arc::clone(app_context),
tree: RwLock::new(tree),
action_handler,
root_window_bounds: RwLock::new(root_window_bounds),
})
}
pub(crate) fn read_tree(&self) -> RwLockReadGuard<'_, Tree> {
self.tree.read().unwrap()
}
pub(crate) fn read_root_window_bounds(&self) -> RwLockReadGuard<'_, WindowBounds> {
self.root_window_bounds.read().unwrap()
}
pub fn do_action(&self, request: ActionRequest) {
self.action_handler.do_action(request);
}
pub(crate) fn read_app_context(&self) -> RwLockReadGuard<'_, AppContext> {
self.app_context.read().unwrap()
}
pub(crate) fn write_app_context(&self) -> RwLockWriteGuard<'_, AppContext> {
self.app_context.write().unwrap()
}
}
#[derive(Debug)]
pub struct AppContext {
pub(crate) name: Option<String>,
pub(crate) toolkit_name: Option<String>,
pub(crate) toolkit_version: Option<String>,
pub(crate) id: Option<i32>,
pub(crate) adapters: Vec<(usize, Arc<Context>)>,
}
impl AppContext {
pub fn new(name: Option<String>) -> Arc<RwLock<Self>> {
Arc::new(RwLock::new(Self {
name,
toolkit_name: None,
toolkit_version: None,
id: None,
adapters: Vec::new(),
}))
}
pub(crate) fn adapter_index(&self, id: usize) -> Result<usize, usize> {
self.adapters.binary_search_by(|adapter| adapter.0.cmp(&id))
}
pub(crate) fn push_adapter(&mut self, id: usize, context: &Arc<Context>) {
self.adapters.push((id, Arc::clone(context)));
}
pub(crate) fn remove_adapter(&mut self, id: usize) {
if let Ok(index) = self.adapter_index(id) {
self.adapters.remove(index);
}
}
}

View file

@ -0,0 +1,33 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use std::fmt;
#[derive(Debug)]
pub enum Error {
Defunct,
UnsupportedInterface,
TooManyChildren,
IndexOutOfRange,
TooManyCharacters,
UnsupportedTextGranularity,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Defunct => "defunct",
Self::UnsupportedInterface => "unsupported interface",
Self::TooManyChildren => "too many children",
Self::IndexOutOfRange => "index out of range",
Self::TooManyCharacters => "too many characters",
Self::UnsupportedTextGranularity => "unsupported text granularity",
})
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;

View file

@ -0,0 +1,69 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_consumer::NodeId;
use atspi_common::{Politeness, Role, State};
use crate::{NodeIdOrRoot, Rect};
#[derive(Debug)]
pub enum Event {
Object {
target: NodeIdOrRoot,
event: ObjectEvent,
},
Window {
target: NodeId,
name: String,
event: WindowEvent,
},
Cache(CacheEvent),
}
#[derive(Debug)]
pub enum CacheEvent {
Added(NodeId),
Removed(NodeId),
}
#[derive(Debug)]
pub enum Property {
Name(String),
Description(String),
Parent(NodeIdOrRoot),
Role(Role),
Value(f64),
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug)]
pub enum ObjectEvent {
ActiveDescendantChanged(NodeId),
Announcement(String, Politeness),
BoundsChanged(Rect),
CaretMoved(i32),
ChildAdded(usize, NodeId),
ChildRemoved(NodeId),
PropertyChanged(Property),
SelectionChanged,
StateChanged(State, bool),
TextInserted {
start_index: i32,
length: i32,
content: String,
},
TextRemoved {
start_index: i32,
length: i32,
content: String,
},
TextSelectionChanged,
}
#[derive(Debug)]
pub enum WindowEvent {
Activated,
Deactivated,
}

View file

@ -0,0 +1,6 @@
// Copyright 2023 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
pub(crate) use accesskit_consumer::common_filter as filter;

View file

@ -0,0 +1,33 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
mod action;
mod adapter;
mod callback;
mod context;
mod error;
mod events;
mod filters;
mod node;
mod rect;
#[cfg(feature = "simplified-api")]
pub mod simplified;
mod text_attributes;
mod util;
pub use accesskit_consumer::NodeId;
pub use atspi_common::{
CoordType, Granularity, InterfaceSet, Layer, RelationType, Role, ScrollType, State, StateSet,
};
pub use action::*;
pub use adapter::{Adapter, next_adapter_id};
pub use callback::AdapterCallback;
pub use context::{ActionHandlerNoMut, ActionHandlerWrapper, AppContext};
pub use error::*;
pub use events::*;
pub use node::{CacheNode, NodeIdOrRoot, PlatformNode, PlatformRoot};
pub use rect::*;
pub use util::WindowBounds;

1944
patches/accesskit_atspi_common/src/node.rs vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use serde::{Deserialize, Serialize};
use zbus::wire::{OwnedVariant as OwnedValue, Type, Variant as Value};
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, OwnedValue, Type, Value,
)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
}
impl Rect {
pub const INVALID: Rect = Rect {
x: -1,
y: -1,
width: -1,
height: -1,
};
}
impl From<accesskit::Rect> for Rect {
fn from(value: accesskit::Rect) -> Rect {
Rect {
x: value.x0 as i32,
y: value.y0 as i32,
width: value.width() as i32,
height: value.height() as i32,
}
}
}

View file

@ -0,0 +1,901 @@
// Copyright 2024 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
//! API that corresponds more closely to the libatspi client API,
//! intended to be used by bindings to languages with less rich
//! type systems.
use std::collections::HashMap;
use crate::{
Adapter, CacheEvent, Event as EventEnum, NodeIdOrRoot, ObjectEvent, PlatformNode, PlatformRoot,
Property, WindowEvent,
};
pub use crate::{
CoordType, Error, Granularity, Layer, Rect, RelationType, Result, Role, ScrollType, StateSet,
};
#[derive(Clone, Hash, PartialEq)]
pub enum Accessible {
Node(PlatformNode),
Root(PlatformRoot),
}
impl Accessible {
pub fn role(&self) -> Result<Role> {
match self {
Self::Node(node) => node.role(),
Self::Root(root) => Ok(root.role()),
}
}
pub fn localized_role_name(&self) -> Result<String> {
match self {
Self::Node(node) => node.localized_role_name(),
Self::Root(_) => Ok("".into()),
}
}
pub fn name(&self) -> Result<String> {
match self {
Self::Node(node) => node.name(),
Self::Root(root) => root.name(),
}
}
pub fn description(&self) -> Result<String> {
match self {
Self::Node(node) => node.description(),
Self::Root(root) => root.description(),
}
}
pub fn state(&self) -> StateSet {
match self {
Self::Node(node) => node.state(),
Self::Root(root) => root.state(),
}
}
pub fn attributes(&self) -> Result<HashMap<&'static str, String>> {
match self {
Self::Node(node) => node.attributes(),
Self::Root(_) => Ok(HashMap::new()),
}
}
pub fn parent(&self) -> Result<Option<Self>> {
match self {
Self::Node(node) => match node.parent()? {
NodeIdOrRoot::Node(id) => Ok(Some(Self::Node(node.relative(id)))),
NodeIdOrRoot::Root => node.root().map(|root| Some(Self::Root(root))),
},
Self::Root(_) => Ok(None),
}
}
pub fn index_in_parent(&self) -> Result<i32> {
match self {
Self::Node(node) => node.index_in_parent(),
Self::Root(root) => Ok(root.index_in_parent()),
}
}
pub fn child_count(&self) -> Result<i32> {
match self {
Self::Node(node) => node.child_count(),
Self::Root(root) => root.child_count(),
}
}
pub fn accessible_id(&self) -> Result<String> {
match self {
Self::Node(node) => node.accessible_id(),
Self::Root(_) => Ok(String::new()),
}
}
pub fn child_at_index(&self, index: usize) -> Result<Option<Self>> {
match self {
Self::Node(node) => node
.child_at_index(index)
.map(|id| id.map(|id| Self::Node(node.relative(id)))),
Self::Root(root) => root
.child_at_index(index)
.map(|child| child.map(Self::Node)),
}
}
pub fn map_children<T, I>(&self, f: impl Fn(Self) -> I) -> Result<T>
where
T: FromIterator<I>,
{
match self {
Self::Node(node) => node.map_children(|id| f(Self::Node(node.relative(id)))),
Self::Root(root) => root.map_children(|node| f(Self::Node(node))),
}
}
pub fn relation_set(&self) -> Result<HashMap<RelationType, Vec<Self>>> {
match self {
Self::Node(node) => node.relation_set(|id| Self::Node(node.relative(id))),
Self::Root(_) => Ok(HashMap::new()),
}
}
pub fn application(&self) -> Result<Self> {
match self {
Self::Node(node) => node.root().map(Self::Root),
Self::Root(root) => Ok(Self::Root(root.clone())),
}
}
pub fn toolkit_name(&self) -> Result<String> {
match self {
Self::Node(node) => node.toolkit_name(),
Self::Root(root) => root.toolkit_name(),
}
}
pub fn toolkit_version(&self) -> Result<String> {
match self {
Self::Node(node) => node.toolkit_version(),
Self::Root(root) => root.toolkit_version(),
}
}
pub fn supports_action(&self) -> Result<bool> {
match self {
Self::Node(node) => node.supports_action(),
Self::Root(_) => Ok(false),
}
}
pub fn n_actions(&self) -> Result<i32> {
match self {
Self::Node(node) => node.n_actions(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn action_name(&self, index: i32) -> Result<String> {
match self {
Self::Node(node) => node.action_name(index),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn do_action(&self, index: i32) -> Result<bool> {
match self {
Self::Node(node) => node.do_action(index),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn supports_component(&self) -> Result<bool> {
match self {
Self::Node(node) => node.supports_component(),
Self::Root(_) => Ok(false),
}
}
pub fn contains(&self, x: i32, y: i32, coord_type: CoordType) -> Result<bool> {
match self {
Self::Node(node) => node.contains(x, y, coord_type),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn accessible_at_point(
&self,
x: i32,
y: i32,
coord_type: CoordType,
) -> Result<Option<Self>> {
match self {
Self::Node(node) => node
.accessible_at_point(x, y, coord_type)
.map(|id| id.map(|id| Self::Node(node.relative(id)))),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn extents(&self, coord_type: CoordType) -> Result<Rect> {
match self {
Self::Node(node) => node.extents(coord_type),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn layer(&self) -> Result<Layer> {
match self {
Self::Node(node) => node.layer(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn grab_focus(&self) -> Result<bool> {
match self {
Self::Node(node) => node.grab_focus(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn scroll_to(&self, scroll_type: ScrollType) -> Result<bool> {
match self {
Self::Node(node) => node.scroll_to(scroll_type),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn scroll_to_point(&self, coord_type: CoordType, x: i32, y: i32) -> Result<bool> {
match self {
Self::Node(node) => node.scroll_to_point(coord_type, x, y),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn supports_hyperlink(&self) -> Result<bool> {
match self {
Self::Node(node) => node.supports_hyperlink(),
Self::Root(_) => Ok(false),
}
}
pub fn n_anchors(&self) -> Result<i32> {
match self {
Self::Node(node) => node.n_anchors(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn hyperlink_start_index(&self) -> Result<i32> {
match self {
Self::Node(node) => node.hyperlink_start_index(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn hyperlink_end_index(&self) -> Result<i32> {
match self {
Self::Node(node) => node.hyperlink_end_index(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn hyperlink_object(&self, index: i32) -> Result<Option<Self>> {
match self {
Self::Node(node) => node
.hyperlink_object(index)
.map(|id| id.map(|id| Self::Node(node.relative(id)))),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn uri(&self, index: i32) -> Result<String> {
match self {
Self::Node(node) => node.uri(index),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn hyperlink_is_valid(&self) -> Result<bool> {
match self {
Self::Node(node) => node.hyperlink_is_valid(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn supports_selection(&self) -> Result<bool> {
match self {
Self::Node(node) => node.supports_selection(),
Self::Root(_) => Ok(false),
}
}
pub fn n_selected_children(&self) -> Result<i32> {
match self {
Self::Node(node) => node.n_selected_children(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn selected_child(&self, selected_child_index: usize) -> Result<Option<Self>> {
match self {
Self::Node(node) => node
.selected_child(selected_child_index)
.map(|id| id.map(|id| Self::Node(node.relative(id)))),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn select_child(&self, child_index: usize) -> Result<bool> {
match self {
Self::Node(node) => node.select_child(child_index),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn deselect_selected_child(&self, selected_child_index: usize) -> Result<bool> {
match self {
Self::Node(node) => node.deselect_selected_child(selected_child_index),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn is_child_selected(&self, child_index: usize) -> Result<bool> {
match self {
Self::Node(node) => node.is_child_selected(child_index),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn select_all(&self) -> Result<bool> {
match self {
Self::Node(node) => node.select_all(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn clear_selection(&self) -> Result<bool> {
match self {
Self::Node(node) => node.clear_selection(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn deselect_child(&self, child_index: usize) -> Result<bool> {
match self {
Self::Node(node) => node.deselect_child(child_index),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn supports_text(&self) -> Result<bool> {
match self {
Self::Node(node) => node.supports_text(),
Self::Root(_) => Ok(false),
}
}
pub fn character_count(&self) -> Result<i32> {
match self {
Self::Node(node) => node.character_count(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn caret_offset(&self) -> Result<i32> {
match self {
Self::Node(node) => node.caret_offset(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn string_at_offset(
&self,
offset: i32,
granularity: Granularity,
) -> Result<(String, i32, i32)> {
match self {
Self::Node(node) => node.string_at_offset(offset, granularity),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn text(&self, start_offset: i32, end_offset: i32) -> Result<String> {
match self {
Self::Node(node) => node.text(start_offset, end_offset),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn set_caret_offset(&self, offset: i32) -> Result<bool> {
match self {
Self::Node(node) => node.set_caret_offset(offset),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn text_attribute_value(&self, offset: i32, attribute_name: &str) -> Result<String> {
match self {
Self::Node(node) => node.text_attribute_value(offset, attribute_name),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn text_attributes(
&self,
offset: i32,
) -> Result<(HashMap<&'static str, String>, i32, i32)> {
match self {
Self::Node(node) => node.text_attributes(offset),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn default_text_attributes(&self) -> Result<HashMap<&'static str, String>> {
match self {
Self::Node(node) => node.default_text_attributes(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn character_extents(&self, offset: i32, coord_type: CoordType) -> Result<Rect> {
match self {
Self::Node(node) => node.character_extents(offset, coord_type),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn offset_at_point(&self, x: i32, y: i32, coord_type: CoordType) -> Result<i32> {
match self {
Self::Node(node) => node.offset_at_point(x, y, coord_type),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn n_selections(&self) -> Result<i32> {
match self {
Self::Node(node) => node.n_selections(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn selection(&self, selection_num: i32) -> Result<(i32, i32)> {
match self {
Self::Node(node) => node.selection(selection_num),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn add_selection(&self, start_offset: i32, end_offset: i32) -> Result<bool> {
match self {
Self::Node(node) => node.add_selection(start_offset, end_offset),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn remove_selection(&self, selection_num: i32) -> Result<bool> {
match self {
Self::Node(node) => node.remove_selection(selection_num),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn set_selection(
&self,
selection_num: i32,
start_offset: i32,
end_offset: i32,
) -> Result<bool> {
match self {
Self::Node(node) => node.set_selection(selection_num, start_offset, end_offset),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn range_extents(
&self,
start_offset: i32,
end_offset: i32,
coord_type: CoordType,
) -> Result<Rect> {
match self {
Self::Node(node) => node.range_extents(start_offset, end_offset, coord_type),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn text_attribute_run(
&self,
offset: i32,
include_defaults: bool,
) -> Result<(HashMap<&'static str, String>, i32, i32)> {
match self {
Self::Node(node) => node.text_attribute_run(offset, include_defaults),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn scroll_substring_to(
&self,
start_offset: i32,
end_offset: i32,
scroll_type: ScrollType,
) -> Result<bool> {
match self {
Self::Node(node) => node.scroll_substring_to(start_offset, end_offset, scroll_type),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn scroll_substring_to_point(
&self,
start_offset: i32,
end_offset: i32,
coord_type: CoordType,
x: i32,
y: i32,
) -> Result<bool> {
match self {
Self::Node(node) => {
node.scroll_substring_to_point(start_offset, end_offset, coord_type, x, y)
}
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn supports_value(&self) -> Result<bool> {
match self {
Self::Node(node) => node.supports_value(),
Self::Root(_) => Ok(false),
}
}
pub fn minimum_value(&self) -> Result<f64> {
match self {
Self::Node(node) => node.minimum_value(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn maximum_value(&self) -> Result<f64> {
match self {
Self::Node(node) => node.maximum_value(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn minimum_increment(&self) -> Result<f64> {
match self {
Self::Node(node) => node.minimum_increment(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn current_value(&self) -> Result<f64> {
match self {
Self::Node(node) => node.current_value(),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
pub fn set_current_value(&self, value: f64) -> Result<()> {
match self {
Self::Node(node) => node.set_current_value(value),
Self::Root(_) => Err(Error::UnsupportedInterface),
}
}
}
pub struct Cache {
root: PlatformRoot,
}
impl Cache {
pub fn new(root: PlatformRoot) -> Self {
Self { root }
}
pub fn items(&self) -> Result<Vec<Accessible>> {
let descendants: Vec<Accessible> = self
.root
.map_descendants(|node, _, _| Accessible::Node(node))?;
let mut items = Vec::with_capacity(descendants.len() + 1);
items.push(Accessible::Root(self.root.clone()));
items.extend(descendants);
Ok(items)
}
}
#[derive(PartialEq)]
pub enum EventData {
U32(u32),
F64(f64),
String(String),
Rect(Rect),
Accessible(Accessible),
}
#[derive(PartialEq)]
pub struct Event {
pub kind: String,
pub source: Accessible,
pub detail1: i32,
pub detail2: i32,
pub data: Option<EventData>,
}
impl Event {
pub fn new(adapter: &Adapter, event: EventEnum) -> Self {
match event {
EventEnum::Object { target, event } => {
let source = match target {
NodeIdOrRoot::Node(target) => Accessible::Node(adapter.platform_node(target)),
NodeIdOrRoot::Root => Accessible::Root(adapter.platform_root()),
};
match event {
ObjectEvent::ActiveDescendantChanged(child) => {
let child = Accessible::Node(adapter.platform_node(child));
Self {
kind: "object:active-descendant-changed".into(),
source,
detail1: 0,
detail2: 0,
data: Some(EventData::Accessible(child)),
}
}
ObjectEvent::Announcement(message, politeness) => Self {
kind: "object:announcement".into(),
source,
detail1: politeness as i32,
detail2: 0,
data: Some(EventData::String(message)),
},
ObjectEvent::BoundsChanged(bounds) => Self {
kind: "object:bounds-changed".into(),
source,
detail1: 0,
detail2: 0,
data: Some(EventData::Rect(bounds)),
},
ObjectEvent::CaretMoved(offset) => Self {
kind: "object:text-caret-moved".into(),
source,
detail1: offset,
detail2: 0,
data: None,
},
ObjectEvent::ChildAdded(index, child) => {
let child = Accessible::Node(adapter.platform_node(child));
Self {
kind: "object:children-changed:add".into(),
source,
detail1: index as i32,
detail2: 0,
data: Some(EventData::Accessible(child)),
}
}
ObjectEvent::ChildRemoved(child) => {
let child = Accessible::Node(adapter.platform_node(child));
Self {
kind: "object:children-changed:remove".into(),
source,
detail1: -1,
detail2: 0,
data: Some(EventData::Accessible(child)),
}
}
ObjectEvent::PropertyChanged(property) => Self {
kind: match property {
Property::Name(_) => "object:property-change:accessible-name",
Property::Description(_) => {
"object:property-change:accessible-description"
}
Property::Parent(_) => "object:property-change:accessible-parent",
Property::Role(_) => "object:property-change:accessible-role",
Property::Value(_) => "object:property-change:accessible-value",
}
.into(),
source,
detail1: 0,
detail2: 0,
data: Some(match property {
Property::Name(value) => EventData::String(value),
Property::Description(value) => EventData::String(value),
Property::Parent(parent) => {
let parent = match parent {
NodeIdOrRoot::Node(parent) => {
Accessible::Node(adapter.platform_node(parent))
}
NodeIdOrRoot::Root => Accessible::Root(adapter.platform_root()),
};
EventData::Accessible(parent)
}
Property::Role(value) => EventData::U32(value as u32),
Property::Value(value) => EventData::F64(value),
}),
},
ObjectEvent::SelectionChanged => Self {
kind: "object:selection-changed".into(),
source,
detail1: 0,
detail2: 0,
data: None,
},
ObjectEvent::StateChanged(state, value) => Self {
kind: format!("object:state-changed:{}", state.to_static_str()),
source,
detail1: value as i32,
detail2: 0,
data: None,
},
ObjectEvent::TextInserted {
start_index,
length,
content,
} => Self {
kind: "object:text-changed:insert".into(),
source,
detail1: start_index,
detail2: length,
data: Some(EventData::String(content)),
},
ObjectEvent::TextRemoved {
start_index,
length,
content,
} => Self {
kind: "object:text-changed:delete".into(),
source,
detail1: start_index,
detail2: length,
data: Some(EventData::String(content)),
},
ObjectEvent::TextSelectionChanged => Self {
kind: "object:text-selection-changed".into(),
source,
detail1: 0,
detail2: 0,
data: None,
},
}
}
EventEnum::Window {
target,
name,
event,
} => {
let kind = match event {
WindowEvent::Activated => "window:activate",
WindowEvent::Deactivated => "window:deactivate",
};
let source = Accessible::Node(adapter.platform_node(target));
Self {
kind: kind.into(),
source,
detail1: 0,
detail2: 0,
data: Some(EventData::String(name)),
}
}
EventEnum::Cache(cache_event) => {
let (kind, target) = match cache_event {
CacheEvent::Added(target) => ("cache:add", target),
CacheEvent::Removed(target) => ("cache:remove", target),
};
Self {
kind: kind.into(),
source: Accessible::Node(adapter.platform_node(target)),
detail1: 0,
detail2: 0,
data: None,
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::{Accessible, Cache, Event as SimplifiedEvent};
use crate::{Adapter, AdapterCallback, AppContext, Event, WindowBounds};
use accesskit::{
ActionHandler, ActionRequest, Node, NodeId as LocalNodeId, Role, Tree, TreeId, TreeUpdate,
};
use accesskit_consumer::NodeId;
use atspi_common::InterfaceSet;
use std::sync::{Arc, Mutex};
struct NoOpActionHandler;
impl ActionHandler for NoOpActionHandler {
fn do_action(&mut self, _request: ActionRequest) {}
}
struct CacheKindCallback {
kinds: Arc<Mutex<Vec<String>>>,
}
impl AdapterCallback for CacheKindCallback {
fn register_interfaces(&self, _: &Adapter, _: NodeId, _: InterfaceSet) {}
fn unregister_interfaces(&self, _: &Adapter, _: NodeId, _: InterfaceSet) {}
fn emit_event(&self, adapter: &Adapter, event: Event) {
if matches!(event, Event::Cache(_)) {
let simplified = SimplifiedEvent::new(adapter, event);
self.kinds.lock().unwrap().push(simplified.kind);
}
}
}
struct NoOpCallback;
impl AdapterCallback for NoOpCallback {
fn register_interfaces(&self, _: &Adapter, _: NodeId, _: InterfaceSet) {}
fn unregister_interfaces(&self, _: &Adapter, _: NodeId, _: InterfaceSet) {}
fn emit_event(&self, _: &Adapter, _: Event) {}
}
fn with_children(role: Role, children: &[LocalNodeId]) -> Node {
let mut node = Node::new(role);
node.set_children(children.to_vec());
node
}
fn initial_tree() -> TreeUpdate {
TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1)]),
),
(LocalNodeId(1), Node::new(Role::Button)),
],
tree: Some(Tree::new(LocalNodeId(0))),
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
}
}
#[test]
fn cache_events_map_to_kind_strings() {
let kinds = Arc::new(Mutex::new(Vec::new()));
let app_context = AppContext::new(None);
let mut adapter = Adapter::new(
&app_context,
CacheKindCallback {
kinds: kinds.clone(),
},
initial_tree(),
false,
WindowBounds::default(),
NoOpActionHandler,
);
adapter.update(TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(LocalNodeId(2), Node::new(Role::Button)),
],
tree: None,
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
});
adapter.update(TreeUpdate {
nodes: vec![(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1)]),
)],
tree: None,
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
});
assert_eq!(*kinds.lock().unwrap(), vec!["cache:add", "cache:remove"]);
}
fn build_cache() -> (Adapter, Cache) {
let app_context = AppContext::new(None);
let adapter = Adapter::new(
&app_context,
NoOpCallback,
initial_tree(),
false,
WindowBounds::default(),
NoOpActionHandler,
);
let cache = Cache::new(adapter.platform_root());
(adapter, cache)
}
#[test]
fn items_prepends_application_root() {
let (_adapter, cache) = build_cache();
let items = cache.items().unwrap();
assert_eq!(items.len(), 3);
assert!(matches!(items[0], Accessible::Root(_)));
}
}

View file

@ -0,0 +1,79 @@
// Copyright 2026 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit::{Color, TextAlign, TextDecorationStyle};
use accesskit_consumer::Node;
use phf::phf_map;
fn color_to_string(color: Color) -> String {
format!("{},{},{}", color.red, color.green, color.blue)
}
fn family_name(node: &Node) -> Option<String> {
node.font_family().map(String::from)
}
fn size(node: &Node) -> Option<String> {
node.font_size().map(|value| value.to_string())
}
fn weight(node: &Node) -> Option<String> {
node.font_weight().map(|value| value.to_string())
}
fn style(node: &Node) -> Option<String> {
node.is_italic().then(|| "italic".into())
}
fn strikethrough(node: &Node) -> Option<String> {
node.strikethrough().map(|_| "true".into())
}
fn underline(node: &Node) -> Option<String> {
node.underline().map(|deco| {
match deco.style {
TextDecorationStyle::Double => "double",
_ => "single",
}
.into()
})
}
fn bg_color(node: &Node) -> Option<String> {
node.background_color().map(color_to_string)
}
fn fg_color(node: &Node) -> Option<String> {
node.foreground_color().map(color_to_string)
}
fn language(node: &Node) -> Option<String> {
node.language().map(String::from)
}
fn justification(node: &Node) -> Option<String> {
node.text_align().map(|align| {
match align {
TextAlign::Left => "left",
TextAlign::Center => "center",
TextAlign::Right => "right",
TextAlign::Justify => "fill",
}
.into()
})
}
pub(crate) const ATTRIBUTE_GETTERS: phf::Map<&'static str, fn(&Node) -> Option<String>> = phf_map! {
"family-name" => family_name,
"size" => size,
"weight" => weight,
"style" => style,
"strikethrough" => strikethrough,
"underline" => underline,
"bg-color" => bg_color,
"fg-color" => fg_color,
"language" => language,
"justification" => justification,
};

View file

@ -0,0 +1,134 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit::{Point, Rect, ScrollHint};
use accesskit_consumer::{Node, TextPosition, TextRange};
use atspi_common::{CoordType, Granularity, ScrollType};
use crate::Error;
#[derive(Clone, Copy, Default, Debug)]
pub struct WindowBounds {
pub outer: Rect,
pub inner: Rect,
}
impl WindowBounds {
pub fn new(outer: Rect, inner: Rect) -> Self {
Self { outer, inner }
}
pub(crate) fn accesskit_point_to_atspi_point(
&self,
point: Point,
parent: Option<Node>,
coord_type: CoordType,
) -> Point {
let origin = self.origin(parent, coord_type);
Point::new(origin.x + point.x, origin.y + point.y)
}
pub(crate) fn atspi_point_to_accesskit_point(
&self,
point: Point,
parent: Option<Node>,
coord_type: CoordType,
) -> Point {
let origin = self.origin(parent, coord_type);
Point::new(point.x - origin.x, point.y - origin.y)
}
fn origin(&self, parent: Option<Node>, coord_type: CoordType) -> Point {
match coord_type {
CoordType::Screen => self.inner.origin(),
CoordType::Window => Point::ZERO,
CoordType::Parent => {
if let Some(parent) = parent {
let parent_origin = parent.bounding_box().unwrap_or_default().origin();
Point::new(-parent_origin.x, -parent_origin.y)
} else {
self.inner.origin()
}
}
}
}
}
pub(crate) fn text_position_from_offset<'a>(
node: &'a Node,
offset: i32,
) -> Option<TextPosition<'a>> {
let index = offset.try_into().ok()?;
node.text_position_from_global_usv_index(index)
}
pub(crate) fn text_range_from_offset<'a>(
node: &'a Node,
offset: i32,
granularity: Granularity,
) -> Result<TextRange<'a>, Error> {
let start_offset = text_position_from_offset(node, offset).ok_or(Error::IndexOutOfRange)?;
let start = match granularity {
Granularity::Char => start_offset,
Granularity::Line if start_offset.is_line_start() => start_offset,
Granularity::Line => start_offset.backward_to_line_start(),
Granularity::Paragraph if start_offset.is_paragraph_start() => start_offset,
Granularity::Paragraph => start_offset.backward_to_paragraph_start(),
Granularity::Sentence => return Err(Error::UnsupportedTextGranularity),
Granularity::Word if start_offset.is_word_start() => start_offset,
Granularity::Word => start_offset.backward_to_word_start(),
};
let end = match granularity {
Granularity::Char if start_offset.is_document_end() => start_offset,
Granularity::Char => start.forward_to_character_end(),
Granularity::Line => start.forward_to_line_end(),
Granularity::Paragraph => start.forward_to_paragraph_end(),
Granularity::Sentence => return Err(Error::UnsupportedTextGranularity),
Granularity::Word => start.forward_to_word_end(),
};
let mut range = start.to_degenerate_range();
range.set_end(end);
Ok(range)
}
pub(crate) fn text_range_from_offsets<'a>(
node: &'a Node,
start_offset: i32,
end_offset: i32,
) -> Option<TextRange<'a>> {
let start = text_position_from_offset(node, start_offset)?;
let end = if end_offset == -1 {
node.document_range().end()
} else {
text_position_from_offset(node, end_offset)?
};
let mut range = start.to_degenerate_range();
range.set_end(end);
Some(range)
}
pub(crate) fn text_range_bounds_from_offsets(
node: &Node,
start_offset: i32,
end_offset: i32,
) -> Option<Rect> {
text_range_from_offsets(node, start_offset, end_offset)?
.bounding_boxes()
.into_iter()
.reduce(|rect1, rect2| rect1.union(rect2))
}
pub(crate) fn atspi_scroll_type_to_scroll_hint(scroll_type: ScrollType) -> Option<ScrollHint> {
match scroll_type {
ScrollType::TopLeft => Some(ScrollHint::TopLeft),
ScrollType::BottomRight => Some(ScrollHint::BottomRight),
ScrollType::TopEdge => Some(ScrollHint::TopEdge),
ScrollType::BottomEdge => Some(ScrollHint::BottomEdge),
ScrollType::LeftEdge => Some(ScrollHint::LeftEdge),
ScrollType::RightEdge => Some(ScrollHint::RightEdge),
ScrollType::Anywhere => None,
}
}

633
patches/accesskit_unix/CHANGELOG.md vendored Normal file
View file

@ -0,0 +1,633 @@
# Changelog
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.12.0 to 0.12.1
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.10.0 to 0.10.1
* accesskit_consumer bumped from 0.14.0 to 0.14.1
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.10.1 to 0.11.0
* accesskit_consumer bumped from 0.14.1 to 0.14.2
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.11.0 to 0.11.1
* accesskit_consumer bumped from 0.15.0 to 0.15.1
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.11.1 to 0.11.2
* accesskit_consumer bumped from 0.15.1 to 0.15.2
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.12.0 to 0.12.1
* accesskit_consumer bumped from 0.16.0 to 0.16.1
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.1.0 to 0.1.1
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.12.2 to 0.12.3
* accesskit_atspi_common bumped from 0.1.1 to 0.1.2
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.1.2 to 0.2.0
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.4.0 to 0.4.1
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.4.1 to 0.4.2
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.5.0 to 0.6.0
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.7.0 to 0.8.0
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.2 to 0.16.3
* accesskit_atspi_common bumped from 0.9.2 to 0.9.3
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.17.0 to 0.17.1
* accesskit_atspi_common bumped from 0.10.0 to 0.10.1
## [0.22.1](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.22.0...accesskit_unix-v0.22.1) (2026-07-14)
### Bug Fixes
* Don't panic on recoverable D-Bus errors on Unix ([#741](https://github.com/AccessKit/accesskit/issues/741)) ([a7d6545](https://github.com/AccessKit/accesskit/commit/a7d65458bd8d81ded693c7b8eae451e1e16aaa01))
* Set the desktop as the app's parent on Unix ([#740](https://github.com/AccessKit/accesskit/issues/740)) ([e1f63ac](https://github.com/AccessKit/accesskit/commit/e1f63acbb2c36e3cae741871300aeb121c9e6274))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.19.0 to 0.19.1
## [0.22.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.21.1...accesskit_unix-v0.22.0) (2026-06-12)
### Features
* Implement the cache object on Unix ([#719](https://github.com/AccessKit/accesskit/issues/719)) ([61bdabd](https://github.com/AccessKit/accesskit/commit/61bdabdb70016068c21e31bf42b36bc4209232cd))
### Bug Fixes
* Watch the IsEnabled property to lazily activate on Unix ([#715](https://github.com/AccessKit/accesskit/issues/715)) ([e7299a7](https://github.com/AccessKit/accesskit/commit/e7299a753d78e8b00dd75e1d2182abb517648f98))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.24.0 to 0.24.1
* accesskit_atspi_common bumped from 0.18.1 to 0.19.0
## [0.21.1](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.21.0...accesskit_unix-v0.21.1) (2026-05-11)
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.18.0 to 0.18.1
## [0.21.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.20.0...accesskit_unix-v0.21.0) (2026-03-04)
### Features
* Implement text attributes for AT-SPI ([#695](https://github.com/AccessKit/accesskit/issues/695)) ([33fc4f0](https://github.com/AccessKit/accesskit/commit/33fc4f06699da335f9b2de3ab381cc940314e9c1))
### Bug Fixes
* Correctly register interfaces on Unix after Hyperlink was added ([#694](https://github.com/AccessKit/accesskit/issues/694)) ([b5979a4](https://github.com/AccessKit/accesskit/commit/b5979a4c88f5d9084f70525cf24f3a37c0988f57))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.17.0 to 0.18.0
## [0.20.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.19.1...accesskit_unix-v0.20.0) (2026-02-01)
### ⚠ BREAKING CHANGES
* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683))
### Bug Fixes
* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683)) ([f8c22cb](https://github.com/AccessKit/accesskit/commit/f8c22cbb53ce6b1859adeff3c0b7154ad9e1f25e))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.23.0 to 0.24.0
* accesskit_atspi_common bumped from 0.16.1 to 0.17.0
## [0.19.1](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.19.0...accesskit_unix-v0.19.1) (2026-01-18)
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.16.0 to 0.16.1
## [0.19.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.18.0...accesskit_unix-v0.19.0) (2026-01-15)
### ⚠ BREAKING CHANGES
* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655))
### Features
* Implement the `url` property ([#669](https://github.com/AccessKit/accesskit/issues/669)) ([6202e63](https://github.com/AccessKit/accesskit/commit/6202e63c667e73216a306b3dd45ff25c364a4f45))
* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655)) ([c16eb80](https://github.com/AccessKit/accesskit/commit/c16eb80c49d14f39e8a7defb1694bf22b8ceed6f))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.22.0 to 0.23.0
* accesskit_atspi_common bumped from 0.15.0 to 0.16.0
## [0.18.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.17.2...accesskit_unix-v0.18.0) (2025-12-23)
### ⚠ BREAKING CHANGES
* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642))
* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626))
### Features
* Add GridCell role ([#643](https://github.com/AccessKit/accesskit/issues/643)) ([1e5abca](https://github.com/AccessKit/accesskit/commit/1e5abca737d1ee942c0804fec2c06d3cb08faa94))
* Implement BrailleLabel and BrailleRoleDescription roles ([#638](https://github.com/AccessKit/accesskit/issues/638)) ([0fdcebb](https://github.com/AccessKit/accesskit/commit/0fdcebb55e308e039ec99fbc31e94e8087a69f2d))
### Bug Fixes
* Activate when an assistive technology is actually running on Unix ([#628](https://github.com/AccessKit/accesskit/issues/628)) ([ec67fdf](https://github.com/AccessKit/accesskit/commit/ec67fdf1ec549913437a601fcd1fa142ec52c47d))
* Bump atspi crates ([dbf81c9](https://github.com/AccessKit/accesskit/commit/dbf81c968739187a9f4c3c105d0618c0f9db3135))
### Code Refactoring
* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642)) ([4d46c27](https://github.com/AccessKit/accesskit/commit/4d46c2740631c5fe4f057707b949d12b26931d0b))
* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626)) ([ea23ec4](https://github.com/AccessKit/accesskit/commit/ea23ec424c7dbb8841e03d71b6a15b74264850a9))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.21.1 to 0.22.0
* accesskit_atspi_common bumped from 0.14.2 to 0.15.0
## [0.17.2](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.17.1...accesskit_unix-v0.17.2) (2025-10-20)
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.14.1 to 0.14.2
## [0.17.1](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.17.0...accesskit_unix-v0.17.1) (2025-10-02)
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.21.0 to 0.21.1
* accesskit_atspi_common bumped from 0.14.0 to 0.14.1
## [0.17.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.16.0...accesskit_unix-v0.17.0) (2025-07-16)
### ⚠ BREAKING CHANGES
* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594))
### Features
* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594)) ([1d9b74c](https://github.com/AccessKit/accesskit/commit/1d9b74c057051509b3ffbf63afeacfb16f544ff8))
* Let parents declare actions supported on their children ([#593](https://github.com/AccessKit/accesskit/issues/593)) ([70b534b](https://github.com/AccessKit/accesskit/commit/70b534bed168a84b84cc35199588aa8ab784fb43))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.20.0 to 0.21.0
* accesskit_atspi_common bumped from 0.13.0 to 0.14.0
## [0.16.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.15.0...accesskit_unix-v0.16.0) (2025-06-26)
### ⚠ BREAKING CHANGES
* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589))
### Bug Fixes
* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589)) ([2887cdd](https://github.com/AccessKit/accesskit/commit/2887cddde817ba3851688068d8d10de5cef7c624))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.19.0 to 0.20.0
* accesskit_atspi_common bumped from 0.12.0 to 0.13.0
## [0.15.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.14.0...accesskit_unix-v0.15.0) (2025-05-06)
### ⚠ BREAKING CHANGES
* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550))
### Bug Fixes
* Expose tabs in the platform adapters ([341a11b](https://github.com/AccessKit/accesskit/commit/341a11bca2c8a29682c11ddcfe91fa58776ea11d))
* Mention caveats with window bounds under Wayland ([#559](https://github.com/AccessKit/accesskit/issues/559)) ([b0cf01a](https://github.com/AccessKit/accesskit/commit/b0cf01a26ded03d722818a193fa6902f69bbc102))
### Code Refactoring
* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550)) ([56abf17](https://github.com/AccessKit/accesskit/commit/56abf17356e4c7f13f64aaeaca6a63c8f7ede553))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.18.0 to 0.19.0
* accesskit_atspi_common bumped from 0.11.0 to 0.12.0
## [0.14.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.13.1...accesskit_unix-v0.14.0) (2025-03-06)
### ⚠ BREAKING CHANGES
* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492))
### Bug Fixes
* Add list box support to the platform adapters ([6c622cf](https://github.com/AccessKit/accesskit/commit/6c622cff4c0c989d9a5f16b775adff9cdacf534c))
* Derive `Debug` for adapters ([#513](https://github.com/AccessKit/accesskit/issues/513)) ([753d904](https://github.com/AccessKit/accesskit/commit/753d90473cf57682568c7a17c82474c8e5d00b25))
* Don't enable the `zbus/tokio` feature on Unix ([#521](https://github.com/AccessKit/accesskit/issues/521)) ([9dfad97](https://github.com/AccessKit/accesskit/commit/9dfad9796f71563a78bc6a7d5f01b111d80e63e6))
* Fix some clippy warnings ([#509](https://github.com/AccessKit/accesskit/issues/509)) ([579b9c1](https://github.com/AccessKit/accesskit/commit/579b9c12dd8abc44ecab41fa3c326a1d8999871d))
* Update zbus to 5.0 ([#519](https://github.com/AccessKit/accesskit/issues/519)) ([4c10b80](https://github.com/AccessKit/accesskit/commit/4c10b801b6924c7010b83f4eb44c8c350c860cf6))
### Code Refactoring
* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492)) ([089794c](https://github.com/AccessKit/accesskit/commit/089794c8f74957e91a19ae3df508e2a892f39ebc))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.17.1 to 0.18.0
* accesskit_atspi_common bumped from 0.10.1 to 0.11.0
## [0.13.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.12.3...accesskit_unix-v0.13.0) (2024-10-31)
### ⚠ BREAKING CHANGES
* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468))
### Features
* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468)) ([2fa0d3f](https://github.com/AccessKit/accesskit/commit/2fa0d3f5b2b7ac11ef1751c133706f29e548bd6d))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.3 to 0.17.0
* accesskit_atspi_common bumped from 0.9.3 to 0.10.0
## [0.12.2](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.12.1...accesskit_unix-v0.12.2) (2024-10-07)
### Bug Fixes
* Update minimum supported Rust version to 1.75 ([#457](https://github.com/AccessKit/accesskit/issues/457)) ([fc622fe](https://github.com/AccessKit/accesskit/commit/fc622fe7657c80a4eedad6f6cded11d2538b54d5))
* Update to zbus v4 ([#456](https://github.com/AccessKit/accesskit/issues/456)) ([95db8f1](https://github.com/AccessKit/accesskit/commit/95db8f1c5f7f56598eab6910a990ccbf9d864dda))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.1 to 0.16.2
* accesskit_atspi_common bumped from 0.9.1 to 0.9.2
## [0.12.1](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.12.0...accesskit_unix-v0.12.1) (2024-09-24)
### Bug Fixes
* Return a null object for AT-SPI application's parent ([#454](https://github.com/AccessKit/accesskit/issues/454)) ([8a84abf](https://github.com/AccessKit/accesskit/commit/8a84abf81eaf22dd3672813ca36f1a422b5c0f1e))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.16.0 to 0.16.1
* accesskit_atspi_common bumped from 0.9.0 to 0.9.1
## [0.12.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.11.1...accesskit_unix-v0.12.0) (2024-06-29)
### ⚠ BREAKING CHANGES
* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434))
### Code Refactoring
* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434)) ([7086bc0](https://github.com/AccessKit/accesskit/commit/7086bc0fad446d3ed4a0fd5eff641a1e75f6c599))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.15.0 to 0.16.0
* accesskit_atspi_common bumped from 0.8.0 to 0.9.0
## [0.11.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.10.1...accesskit_unix-v0.11.0) (2024-06-09)
### Features
* Add `author_id` property ([#424](https://github.com/AccessKit/accesskit/issues/424)) ([0d1c56f](https://github.com/AccessKit/accesskit/commit/0d1c56f0bdde58715e1c69f6015df600cb7cb8c1))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.14.0 to 0.15.0
* accesskit_atspi_common bumped from 0.6.0 to 0.7.0
## [0.10.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.9.2...accesskit_unix-v0.10.0) (2024-05-26)
### Features
* Add basic text support on Unix ([#362](https://github.com/AccessKit/accesskit/issues/362)) ([52540f8](https://github.com/AccessKit/accesskit/commit/52540f82cf9fc148358351ed486bab3e7e91f1d6))
* Expose the `placeholder` property ([#417](https://github.com/AccessKit/accesskit/issues/417)) ([8f4a0a1](https://github.com/AccessKit/accesskit/commit/8f4a0a1c10f83fcc8580a37d8013fec2d110865b))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_atspi_common bumped from 0.4.2 to 0.5.0
## [0.9.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.8.0...accesskit_unix-v0.9.0) (2024-04-30)
### ⚠ BREAKING CHANGES
* Force a semver-breaking release ([#398](https://github.com/AccessKit/accesskit/issues/398))
### Bug Fixes
* Force a semver-breaking release ([#398](https://github.com/AccessKit/accesskit/issues/398)) ([87b8b92](https://github.com/AccessKit/accesskit/commit/87b8b92b74a102c7cae48e013d2c2ae1cc2f9598))
* Increase minimum supported Rust version to `1.70` ([#396](https://github.com/AccessKit/accesskit/issues/396)) ([a8398b8](https://github.com/AccessKit/accesskit/commit/a8398b847aa003de91042ac45e33126fc2cae053))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.13.0 to 0.14.0
* accesskit_atspi_common bumped from 0.3.0 to 0.4.0
## [0.8.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.7.5...accesskit_unix-v0.8.0) (2024-04-14)
### ⚠ BREAKING CHANGES
* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375))
### Code Refactoring
* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375)) ([9baebdc](https://github.com/AccessKit/accesskit/commit/9baebdceed7300389b6768815d7ae48f1ce401e4))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.12.3 to 0.13.0
* accesskit_atspi_common bumped from 0.2.0 to 0.3.0
## [0.7.2](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.7.1...accesskit_unix-v0.7.2) (2024-02-24)
### Bug Fixes
* Don't emit focus event twice on Unix ([#354](https://github.com/AccessKit/accesskit/issues/354)) ([b39216c](https://github.com/AccessKit/accesskit/commit/b39216cb31df692fef377f9b3c3c718fd225cc3c))
* Use the new accesskit_atspi_common crate in the Unix adapter ([#356](https://github.com/AccessKit/accesskit/issues/356)) ([b2a468c](https://github.com/AccessKit/accesskit/commit/b2a468ccb91ee4e6d3435e73eb00c65cbe75060a))
## [0.7.1](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.7.0...accesskit_unix-v0.7.1) (2024-01-11)
### Bug Fixes
* Make full use of tokio ecosystem if the tokio feature is enabled on Unix ([#336](https://github.com/AccessKit/accesskit/issues/336)) ([c034802](https://github.com/AccessKit/accesskit/commit/c0348024665a615a30fd8fe2f02e8c93cf9c6332))
* Run our own async executor on Unix ([#337](https://github.com/AccessKit/accesskit/issues/337)) ([8f937ba](https://github.com/AccessKit/accesskit/commit/8f937baaa510dd96da196501822b82f75f05b595))
## [0.7.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.6.2...accesskit_unix-v0.7.0) (2024-01-03)
### ⚠ BREAKING CHANGES
* Lazily activate Unix adapters ([#324](https://github.com/AccessKit/accesskit/issues/324))
### Features
* Support custom role descriptions ([#316](https://github.com/AccessKit/accesskit/issues/316)) ([c8d1a56](https://github.com/AccessKit/accesskit/commit/c8d1a5638fa6c33adfa059815c04f7e043c56026))
### Bug Fixes
* Lazily activate Unix adapters ([#324](https://github.com/AccessKit/accesskit/issues/324)) ([54ed036](https://github.com/AccessKit/accesskit/commit/54ed036c99d87428a8eb5bb03fd77e9e31562d4c))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.12.1 to 0.12.2
* accesskit_consumer bumped from 0.16.1 to 0.17.0
## [0.6.2](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.6.1...accesskit_unix-v0.6.2) (2023-12-14)
### Bug Fixes
* Bump async-channel dependency to `2.1.1` ([#321](https://github.com/AccessKit/accesskit/issues/321)) ([99120b8](https://github.com/AccessKit/accesskit/commit/99120b828d65306ab71d41f71979dc67e8b0bf6b))
## [0.6.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.5.2...accesskit_unix-v0.6.0) (2023-09-27)
### ⚠ BREAKING CHANGES
* Allow providing app_name, toolkit_name and toolkit_version in Tree, remove parameters from unix adapter constructor ([#291](https://github.com/AccessKit/accesskit/issues/291))
* Make `ActionHandler::do_action` take `&mut self` ([#296](https://github.com/AccessKit/accesskit/issues/296))
* Clean up roles and properties ([#289](https://github.com/AccessKit/accesskit/issues/289))
* Decouple in-tree focus from host window/view focus ([#278](https://github.com/AccessKit/accesskit/issues/278))
* Switch to simple unsigned 64-bit integer for node IDs ([#276](https://github.com/AccessKit/accesskit/issues/276))
### Features
* Add role for terminals ([#282](https://github.com/AccessKit/accesskit/issues/282)) ([ddbef37](https://github.com/AccessKit/accesskit/commit/ddbef37158b57f56217317b480e40d58f83a9c24))
* Allow providing app_name, toolkit_name and toolkit_version in Tree, remove parameters from unix adapter constructor ([#291](https://github.com/AccessKit/accesskit/issues/291)) ([5313860](https://github.com/AccessKit/accesskit/commit/531386023257150f49b5e4be942f359855fb7cb6))
* Support live regions on Unix ([#299](https://github.com/AccessKit/accesskit/issues/299)) ([8d52a5f](https://github.com/AccessKit/accesskit/commit/8d52a5fc4271a3b5edcc602b23fd7b920446eab0))
* Support multiple top-level windows on Unix ([#292](https://github.com/AccessKit/accesskit/issues/292)) ([43ecf4b](https://github.com/AccessKit/accesskit/commit/43ecf4b3ab96d9e8f7d2c2222c7e664c4f4f4abf))
### Bug Fixes
* Don't require tokio rt-multi-thread feature ([#290](https://github.com/AccessKit/accesskit/issues/290)) ([cf61e47](https://github.com/AccessKit/accesskit/commit/cf61e477adff26b032fa0b24502c0ae0a96c1987))
* Use common filters across platform adapters ([#287](https://github.com/AccessKit/accesskit/issues/287)) ([09c1204](https://github.com/AccessKit/accesskit/commit/09c12045ff4ccdb22f0cf643077a27465013572d))
### Code Refactoring
* Clean up roles and properties ([#289](https://github.com/AccessKit/accesskit/issues/289)) ([4fc9c55](https://github.com/AccessKit/accesskit/commit/4fc9c55c91812472593923d93ff89d75ff305ee4))
* Decouple in-tree focus from host window/view focus ([#278](https://github.com/AccessKit/accesskit/issues/278)) ([d360d20](https://github.com/AccessKit/accesskit/commit/d360d20cf951e7643b81a5303006c9f7daa5bd56))
* Make `ActionHandler::do_action` take `&mut self` ([#296](https://github.com/AccessKit/accesskit/issues/296)) ([4fc7846](https://github.com/AccessKit/accesskit/commit/4fc7846d732d61fb45c023060ebab96801a0053e))
* Switch to simple unsigned 64-bit integer for node IDs ([#276](https://github.com/AccessKit/accesskit/issues/276)) ([3eadd48](https://github.com/AccessKit/accesskit/commit/3eadd48ec47854faa94a94ebf910ec08f514642f))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.11.2 to 0.12.0
* accesskit_consumer bumped from 0.15.2 to 0.16.0
## [0.5.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.4.0...accesskit_unix-v0.5.0) (2023-05-21)
### Features
* Add features for async runtimes on Unix ([#248](https://github.com/AccessKit/accesskit/issues/248)) ([b56b4ea](https://github.com/AccessKit/accesskit/commit/b56b4ea7c967ee5a1dae21a2fa0dcd385346031e))
## [0.4.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.3.3...accesskit_unix-v0.4.0) (2023-03-30)
### ⚠ BREAKING CHANGES
* Force a semver-breaking version bump in downstream crates ([#234](https://github.com/AccessKit/accesskit/issues/234))
### Bug Fixes
* Force a semver-breaking version bump in downstream crates ([#234](https://github.com/AccessKit/accesskit/issues/234)) ([773389b](https://github.com/AccessKit/accesskit/commit/773389bff857fa18edf15de426e029251fc34591))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.14.2 to 0.15.0
## [0.3.1](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.3.0...accesskit_unix-v0.3.1) (2023-02-20)
### Bug Fixes
* Update atspi dependency ([#217](https://github.com/AccessKit/accesskit/issues/217)) ([93f2dc9](https://github.com/AccessKit/accesskit/commit/93f2dc9bf0a57a8b7592c3a4cf4aa3885a3356f2))
## [0.3.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.2.0...accesskit_unix-v0.3.0) (2023-02-12)
### ⚠ BREAKING CHANGES
* Move thread synchronization into platform adapters; drop parking_lot ([#212](https://github.com/AccessKit/accesskit/issues/212))
### Code Refactoring
* Move thread synchronization into platform adapters; drop parking_lot ([#212](https://github.com/AccessKit/accesskit/issues/212)) ([5df52e5](https://github.com/AccessKit/accesskit/commit/5df52e5545faddf6a51905409013c2f5be23981e))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.9.0 to 0.10.0
* accesskit_consumer bumped from 0.13.0 to 0.14.0
## [0.2.0](https://github.com/AccessKit/accesskit/compare/accesskit_unix-v0.1.1...accesskit_unix-v0.2.0) (2023-02-05)
### ⚠ BREAKING CHANGES
* Make `Node` opaque and optimize it for size ([#205](https://github.com/AccessKit/accesskit/issues/205))
### Code Refactoring
* Make `Node` opaque and optimize it for size ([#205](https://github.com/AccessKit/accesskit/issues/205)) ([4811152](https://github.com/AccessKit/accesskit/commit/48111521439b76c1a8687418a4b20f9b705eac6d))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit bumped from 0.8.1 to 0.9.0
* accesskit_consumer bumped from 0.12.1 to 0.13.0
## 0.1.0 (2023-01-05)
### Features
* Basic Unix platform adapter ([#198](https://github.com/AccessKit/accesskit/issues/198)) ([1cea32e](https://github.com/AccessKit/accesskit/commit/1cea32e44ee743b778ac941ceff9087ae745cb37))
### Dependencies
* The following workspace dependencies were updated
* dependencies
* accesskit_consumer bumped from 0.11.0 to 0.12.0

104
patches/accesskit_unix/Cargo.toml vendored Normal file
View file

@ -0,0 +1,104 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.85"
name = "accesskit_unix"
version = "0.22.1"
authors = ["The AccessKit contributors"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "AccessKit UI accessibility infrastructure: Linux adapter"
readme = "README.md"
keywords = [
"gui",
"ui",
"accessibility",
]
categories = ["gui"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/AccessKit/accesskit"
resolver = "2"
[features]
async-io = [
"dep:async-channel",
"dep:async-executor",
"dep:async-task",
"dep:futures-util",
]
default = ["async-io"]
tokio = [
"dep:tokio",
"dep:tokio-stream",
]
[lib]
name = "accesskit_unix"
path = "src/lib.rs"
[dependencies.accesskit]
version = "0.24.1"
[dependencies.accesskit_atspi_common]
version = "0.19.1"
[dependencies.async-channel]
version = "2.1.1"
optional = true
[dependencies.async-executor]
version = "1.5.0"
optional = true
[dependencies.async-task]
version = "4.3.0"
optional = true
[dependencies.atspi]
version = "0.29"
features = ["proxies"]
default-features = false
[dependencies.futures-lite]
version = "2.3"
[dependencies.futures-util]
version = "0.3.27"
optional = true
[dependencies.serde]
version = "1.0"
[dependencies.tokio]
version = "1.32.0"
features = [
"macros",
"net",
"rt",
"sync",
"time",
]
optional = true
[dependencies.tokio-stream]
version = "0.1.14"
optional = true
[dependencies.zbus]
version = "6.1"
features = ["default-rt", "proxy", "service", "object-manager"]
default-features = false

176
patches/accesskit_unix/LICENSE-APACHE vendored Normal file
View file

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

23
patches/accesskit_unix/LICENSE-MIT vendored Normal file
View file

@ -0,0 +1,23 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

10
patches/accesskit_unix/README.md vendored Normal file
View file

@ -0,0 +1,10 @@
# AccessKit Unix adapter
This is the Unix adapter for [AccessKit](https://accesskit.dev/). It exposes an AccessKit accessibility tree through the AT-SPI protocol.
## Compatibility with async runtimes
While this crate's API is purely blocking, it internally spawns asynchronous tasks on an executor.
- If you use tokio, make sure to enable the `tokio` feature of this crate.
- If you use another async runtime or if you don't use one at all, the default feature will suit your needs.

9
patches/accesskit_unix/VNOX-PATCH.md vendored Normal file
View file

@ -0,0 +1,9 @@
# Vnox maintenance patch: accesskit_unix 0.22.1
Source: published crates.io accesskit_unix 0.22.1, original licenses included.
This is a maintained-parent compatibility backport, not a fork of an unmaintained D-Bus codec. Vnox updates dependencies/imports to maintained zbus 6, which merged zvariant and zbus_names. The original package version identifies its API baseline; no version is spoofed to suppress RustSec.
The Slint Winit patch additionally uses Winit's supported crossfont CSD backend to avoid the unmaintained ttf-parser chain while retaining Wayland client-side title decorations.
Remove this patch once upstream publishes the equivalent migration. Changes must be tested with full client build, native rendering, accessibility/portal interfaces and RustSec audit.

271
patches/accesskit_unix/src/adapter.rs vendored Normal file
View file

@ -0,0 +1,271 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit::{ActionHandler, ActivationHandler, DeactivationHandler, Rect, TreeUpdate};
use accesskit_atspi_common::{
ActionHandlerNoMut, ActionHandlerWrapper, Adapter as AdapterImpl, AdapterCallback, CacheEvent,
Event, NodeId, PlatformNode, WindowBounds, next_adapter_id,
};
#[cfg(not(feature = "tokio"))]
use async_channel::Sender;
use atspi::InterfaceSet;
use std::fmt::{Debug, Formatter};
use std::sync::{Arc, Mutex};
#[cfg(feature = "tokio")]
use tokio::sync::mpsc::UnboundedSender as Sender;
use crate::context::{get_or_init_app_context, get_or_init_messages};
pub(crate) struct Callback {
messages: Sender<Message>,
}
impl Callback {
pub(crate) fn new() -> Self {
let messages = get_or_init_messages();
Self { messages }
}
fn send_message(&self, message: Message) {
#[cfg(not(feature = "tokio"))]
let _ = self.messages.try_send(message);
#[cfg(feature = "tokio")]
let _ = self.messages.send(message);
}
}
impl AdapterCallback for Callback {
fn register_interfaces(&self, adapter: &AdapterImpl, id: NodeId, interfaces: InterfaceSet) {
let node = adapter.platform_node(id);
self.send_message(Message::RegisterInterfaces { node, interfaces });
}
fn unregister_interfaces(&self, adapter: &AdapterImpl, id: NodeId, interfaces: InterfaceSet) {
self.send_message(Message::UnregisterInterfaces {
adapter_id: adapter.id(),
node_id: id,
interfaces,
})
}
fn emit_event(&self, adapter: &AdapterImpl, event: Event) {
match event {
Event::Cache(CacheEvent::Added(id)) => {
let node = adapter.platform_node(id);
self.send_message(Message::EmitCacheAdd { node });
}
Event::Cache(CacheEvent::Removed(id)) => {
self.send_message(Message::EmitCacheRemove {
adapter_id: adapter.id(),
node_id: id,
});
}
event => {
self.send_message(Message::EmitEvent {
adapter_id: adapter.id(),
event,
});
}
}
}
}
pub(crate) enum AdapterState {
Inactive {
is_window_focused: bool,
root_window_bounds: WindowBounds,
action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>,
},
Pending {
is_window_focused: bool,
root_window_bounds: WindowBounds,
action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>,
},
Active(AdapterImpl),
}
impl Debug for AdapterState {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
AdapterState::Inactive {
is_window_focused,
root_window_bounds,
action_handler: _,
} => f
.debug_struct("Inactive")
.field("is_window_focused", is_window_focused)
.field("root_window_bounds", root_window_bounds)
.field("action_handler", &"ActionHandler")
.finish(),
AdapterState::Pending {
is_window_focused,
root_window_bounds,
action_handler: _,
} => f
.debug_struct("Pending")
.field("is_window_focused", is_window_focused)
.field("root_window_bounds", root_window_bounds)
.field("action_handler", &"ActionHandler")
.finish(),
AdapterState::Active(r#impl) => f.debug_tuple("Active").field(r#impl).finish(),
}
}
}
#[derive(Debug)]
pub struct Adapter {
messages: Sender<Message>,
id: usize,
state: Arc<Mutex<AdapterState>>,
}
impl Adapter {
/// Create a new Unix adapter.
///
/// All of the handlers will always be called from another thread.
pub fn new(
activation_handler: impl 'static + ActivationHandler + Send,
action_handler: impl 'static + ActionHandler + Send,
deactivation_handler: impl 'static + DeactivationHandler + Send,
) -> Self {
let id = next_adapter_id();
let messages = get_or_init_messages();
let state = Arc::new(Mutex::new(AdapterState::Inactive {
is_window_focused: false,
root_window_bounds: Default::default(),
action_handler: Arc::new(ActionHandlerWrapper::new(action_handler)),
}));
let adapter = Self {
id,
messages,
state: Arc::clone(&state),
};
adapter.send_message(Message::AddAdapter {
id,
activation_handler: Box::new(activation_handler),
deactivation_handler: Box::new(deactivation_handler),
state,
});
adapter
}
pub(crate) fn send_message(&self, message: Message) {
#[cfg(not(feature = "tokio"))]
let _ = self.messages.try_send(message);
#[cfg(feature = "tokio")]
let _ = self.messages.send(message);
}
/// Set the bounds of the top-level window. The outer bounds contain any
/// window decoration and borders.
///
/// # Caveats
///
/// Since an application can not get the position of its window under
/// Wayland, calling this method only makes sense under X11.
pub fn set_root_window_bounds(&mut self, outer: Rect, inner: Rect) {
let new_bounds = WindowBounds::new(outer, inner);
let mut state = self.state.lock().unwrap();
match &mut *state {
AdapterState::Inactive {
root_window_bounds, ..
} => {
*root_window_bounds = new_bounds;
}
AdapterState::Pending {
root_window_bounds, ..
} => {
*root_window_bounds = new_bounds;
}
AdapterState::Active(r#impl) => r#impl.set_root_window_bounds(new_bounds),
}
}
/// If and only if the tree has been initialized, call the provided function
/// and apply the resulting update. Note: If the caller's implementation of
/// [`ActivationHandler::request_initial_tree`] initially returned `None`,
/// the [`TreeUpdate`] returned by the provided function must contain
/// a full tree.
pub fn update_if_active(&mut self, update_factory: impl FnOnce() -> TreeUpdate) {
let mut state = self.state.lock().unwrap();
match &mut *state {
AdapterState::Inactive { .. } => (),
AdapterState::Pending {
is_window_focused,
root_window_bounds,
action_handler,
} => {
let initial_state = update_factory();
let r#impl = AdapterImpl::with_wrapped_action_handler(
self.id,
get_or_init_app_context(),
Callback::new(),
initial_state,
*is_window_focused,
*root_window_bounds,
Arc::clone(action_handler),
);
*state = AdapterState::Active(r#impl);
}
AdapterState::Active(r#impl) => r#impl.update(update_factory()),
}
}
/// Update the tree state based on whether the window is focused.
pub fn update_window_focus_state(&mut self, is_focused: bool) {
let mut state = self.state.lock().unwrap();
match &mut *state {
AdapterState::Inactive {
is_window_focused, ..
} => {
*is_window_focused = is_focused;
}
AdapterState::Pending {
is_window_focused, ..
} => {
*is_window_focused = is_focused;
}
AdapterState::Active(r#impl) => r#impl.update_window_focus_state(is_focused),
}
}
}
impl Drop for Adapter {
fn drop(&mut self) {
self.send_message(Message::RemoveAdapter { id: self.id });
}
}
pub(crate) enum Message {
AddAdapter {
id: usize,
activation_handler: Box<dyn ActivationHandler + Send>,
deactivation_handler: Box<dyn DeactivationHandler + Send>,
state: Arc<Mutex<AdapterState>>,
},
RemoveAdapter {
id: usize,
},
RegisterInterfaces {
node: PlatformNode,
interfaces: InterfaceSet,
},
UnregisterInterfaces {
adapter_id: usize,
node_id: NodeId,
interfaces: InterfaceSet,
},
EmitEvent {
adapter_id: usize,
event: Event,
},
EmitCacheAdd {
node: PlatformNode,
},
EmitCacheRemove {
adapter_id: usize,
node_id: NodeId,
},
}

461
patches/accesskit_unix/src/atspi/bus.rs vendored Normal file
View file

@ -0,0 +1,461 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use crate::{
atspi::{ObjectId, cache_path, interfaces::*},
context::get_or_init_app_context,
};
use accesskit_atspi_common::{
NodeId, NodeIdOrRoot, ObjectEvent, PlatformNode, PlatformRoot, Property, WindowEvent,
};
use atspi::{
Interface, InterfaceSet, ObjectRefOwned,
events::EventBodyBorrowed,
proxy::{bus::BusProxy, socket::SocketProxy},
};
use std::{
env::var,
sync::{Arc, OnceLock},
};
use zbus::{
Address, Connection, Result,
connection::Builder,
names::{BusName, InterfaceName, MemberName, OwnedUniqueName},
wire::{Str, Variant as Value},
};
pub(crate) struct Bus {
conn: Connection,
socket_proxy: SocketProxy<'static>,
desktop: Arc<OnceLock<ObjectRefOwned>>,
}
impl Bus {
pub(crate) async fn new(
session_bus: &Connection,
) -> zbus::Result<Self> {
let address = match var("AT_SPI_BUS_ADDRESS") {
Ok(address) if !address.is_empty() => address,
_ => BusProxy::new(session_bus).await?.get_address().await?,
};
let address: Address = address.as_str().try_into()?;
// zbus 6 selects and drives its maintained default runtime.
let conn = Builder::address(address).build().await?;
let socket_proxy = SocketProxy::new(&conn).await?;
let mut bus = Bus {
conn,
socket_proxy,
desktop: Arc::new(OnceLock::new()),
};
bus.register_root_node().await?;
Ok(bus)
}
fn unique_name(&self) -> &OwnedUniqueName {
self.conn.unique_name().unwrap()
}
async fn register_root_node(&mut self) -> Result<()> {
let node = PlatformRoot::new(get_or_init_app_context());
let path = ObjectId::Root.path();
if self
.conn
.object_server()
.at(path.clone(), ApplicationInterface(node.clone()))
.await?
.is_none()
{
let desktop = self
.socket_proxy
.embed(&(self.unique_name().as_str(), ObjectId::Root.path().into()))
.await?;
let _ = self.desktop.set(desktop);
self.conn
.object_server()
.at(
path,
RootAccessibleInterface::new(
self.unique_name().to_owned(),
node.clone(),
Arc::clone(&self.desktop),
),
)
.await?;
self.conn
.object_server()
.at(
cache_path(),
CacheInterface::new(
self.unique_name().to_owned(),
node,
Arc::clone(&self.desktop),
),
)
.await?;
}
Ok(())
}
pub(crate) async fn register_interfaces(
&self,
node: PlatformNode,
new_interfaces: InterfaceSet,
) -> zbus::Result<()> {
let path = ObjectId::from(&node).path();
let bus_name = self.unique_name().to_owned();
if new_interfaces.contains(Interface::Accessible) {
self.register_interface(
&path,
NodeAccessibleInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Action) {
self.register_interface(&path, ActionInterface::new(node.clone()))
.await?;
}
if new_interfaces.contains(Interface::Component) {
self.register_interface(
&path,
ComponentInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Hyperlink) {
self.register_interface(
&path,
HyperlinkInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Selection) {
self.register_interface(
&path,
SelectionInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Text) {
self.register_interface(&path, TextInterface::new(node.clone()))
.await?;
}
if new_interfaces.contains(Interface::Value) {
self.register_interface(&path, ValueInterface::new(node.clone()))
.await?;
}
Ok(())
}
async fn register_interface<T>(&self, path: &str, interface: T) -> Result<bool>
where
T: zbus::object_server::Interface,
{
map_or_ignoring_recoverable_error(
self.conn.object_server().at(path, interface).await,
false,
|result| result.is_none(),
)
}
pub(crate) async fn unregister_interfaces(
&self,
adapter_id: usize,
node_id: NodeId,
old_interfaces: InterfaceSet,
) -> zbus::Result<()> {
let path = ObjectId::Node {
adapter: adapter_id,
node: node_id,
}
.path();
if old_interfaces.contains(Interface::Accessible) {
self.unregister_interface::<NodeAccessibleInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Action) {
self.unregister_interface::<ActionInterface>(&path).await?;
}
if old_interfaces.contains(Interface::Component) {
self.unregister_interface::<ComponentInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Hyperlink) {
self.unregister_interface::<HyperlinkInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Selection) {
self.unregister_interface::<SelectionInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Text) {
self.unregister_interface::<TextInterface>(&path).await?;
}
if old_interfaces.contains(Interface::Value) {
self.unregister_interface::<ValueInterface>(&path).await?;
}
Ok(())
}
async fn unregister_interface<T>(&self, path: &str) -> Result<bool>
where
T: zbus::object_server::Interface,
{
map_or_ignoring_recoverable_error(
self.conn.object_server().remove::<T, _>(path).await,
false,
|result| result,
)
}
pub(crate) async fn emit_object_event(
&self,
adapter_id: usize,
target: NodeIdOrRoot,
event: ObjectEvent,
) -> Result<()> {
let target = match target {
NodeIdOrRoot::Node(node) => ObjectId::Node {
adapter: adapter_id,
node,
},
NodeIdOrRoot::Root => ObjectId::Root,
};
let interface = "org.a11y.atspi.Event.Object";
let signal = match event {
ObjectEvent::ActiveDescendantChanged(_) => "ActiveDescendantChanged",
ObjectEvent::Announcement(_, _) => "Announcement",
ObjectEvent::BoundsChanged(_) => "BoundsChanged",
ObjectEvent::CaretMoved(_) => "TextCaretMoved",
ObjectEvent::ChildAdded(_, _) | ObjectEvent::ChildRemoved(_) => "ChildrenChanged",
ObjectEvent::PropertyChanged(_) => "PropertyChange",
ObjectEvent::SelectionChanged => "SelectionChanged",
ObjectEvent::StateChanged(_, _) => "StateChanged",
ObjectEvent::TextInserted { .. } | ObjectEvent::TextRemoved { .. } => "TextChanged",
ObjectEvent::TextSelectionChanged => "TextSelectionChanged",
};
match event {
ObjectEvent::ActiveDescendantChanged(child) => {
let child = ObjectId::Node {
adapter: adapter_id,
node: child,
};
let mut body = EventBodyBorrowed::default();
body.any_data = child.to_address(self.unique_name().inner()).into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::Announcement(message, politeness) => {
let mut body = EventBodyBorrowed::default();
body.detail1 = politeness as i32;
body.any_data = message.into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::BoundsChanged(bounds) => {
let mut body = EventBodyBorrowed::default();
body.any_data = Value::from(bounds);
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::CaretMoved(offset) => {
let mut body = EventBodyBorrowed::default();
body.detail1 = offset;
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::ChildAdded(index, child) => {
let child = ObjectId::Node {
adapter: adapter_id,
node: child,
};
let mut body = EventBodyBorrowed::default();
body.kind = "add";
body.detail1 = index as i32;
body.any_data = child.to_address(self.unique_name().inner()).into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::ChildRemoved(child) => {
let child = ObjectId::Node {
adapter: adapter_id,
node: child,
};
let mut body = EventBodyBorrowed::default();
body.kind = "remove";
body.detail1 = -1;
body.any_data = child.to_address(self.unique_name().inner()).into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::PropertyChanged(property) => {
let mut body = EventBodyBorrowed::default();
body.kind = match property {
Property::Name(_) => "accessible-name",
Property::Description(_) => "accessible-description",
Property::Parent(_) => "accessible-parent",
Property::Role(_) => "accessible-role",
Property::Value(_) => "accessible-value",
};
body.any_data = match property {
Property::Name(value) => Str::from(value).into(),
Property::Description(value) => Str::from(value).into(),
Property::Parent(parent) => {
let parent = match parent {
NodeIdOrRoot::Node(node) => ObjectId::Node {
adapter: adapter_id,
node,
},
NodeIdOrRoot::Root => ObjectId::Root,
};
parent.to_address(self.unique_name().inner()).into()
}
Property::Role(value) => Value::U32(value as u32),
Property::Value(value) => Value::F64(value),
};
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::SelectionChanged => {
self.emit_event(target, interface, signal, EventBodyBorrowed::default())
.await
}
ObjectEvent::StateChanged(state, value) => {
let mut body = EventBodyBorrowed::default();
body.kind = state.to_static_str();
body.detail1 = value as i32;
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::TextInserted {
start_index,
length,
content,
} => {
let mut body = EventBodyBorrowed::default();
body.kind = "insert";
body.detail1 = start_index;
body.detail2 = length;
body.any_data = content.into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::TextRemoved {
start_index,
length,
content,
} => {
let mut body = EventBodyBorrowed::default();
body.kind = "delete";
body.detail1 = start_index;
body.detail2 = length;
body.any_data = content.into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::TextSelectionChanged => {
self.emit_event(target, interface, signal, EventBodyBorrowed::default())
.await
}
}
}
pub(crate) async fn emit_window_event(
&self,
adapter_id: usize,
target: NodeId,
window_name: String,
event: WindowEvent,
) -> Result<()> {
let target = ObjectId::Node {
adapter: adapter_id,
node: target,
};
let signal = match event {
WindowEvent::Activated => "Activate",
WindowEvent::Deactivated => "Deactivate",
};
let mut body = EventBodyBorrowed::default();
body.any_data = window_name.into();
self.emit_event(target, "org.a11y.atspi.Event.Window", signal, body)
.await
}
pub(crate) async fn emit_cache_add(&self, node: PlatformNode) -> Result<()> {
let Ok(item) = cache_item_for_node(self.unique_name().inner(), &node) else {
return Ok(());
};
self.emit_cache_signal("AddAccessible", &item).await
}
pub(crate) async fn emit_cache_remove(&self, adapter_id: usize, node_id: NodeId) -> Result<()> {
let reference = object_ref(
self.unique_name().inner(),
ObjectId::Node {
adapter: adapter_id,
node: node_id,
},
);
self.emit_cache_signal("RemoveAccessible", &reference).await
}
async fn emit_cache_signal<B>(&self, signal_name: &str, body: &B) -> Result<()>
where
B: serde::Serialize + zbus::wire::DynamicType,
{
map_or_ignoring_recoverable_error(
self.conn
.emit_signal(
Option::<BusName>::None,
cache_path(),
InterfaceName::from_str_unchecked("org.a11y.atspi.Cache"),
MemberName::from_str_unchecked(signal_name),
body,
)
.await,
(),
|_| (),
)
}
async fn emit_event(
&self,
target: ObjectId,
interface: &str,
signal_name: &str,
body: EventBodyBorrowed<'_>,
) -> Result<()> {
map_or_ignoring_recoverable_error(
self.conn
.emit_signal(
Option::<BusName>::None,
target.path(),
InterfaceName::from_str_unchecked(interface),
MemberName::from_str_unchecked(signal_name),
&body,
)
.await,
(),
|_| (),
)
}
}
pub(crate) fn zbus_error_is_unrecoverable(error: &zbus::Error) -> bool {
matches!(
error,
zbus::Error::InterfaceExists(..) | zbus::Error::MissingParameter(..)
)
}
pub(crate) fn map_or_ignoring_recoverable_error<T, U, F>(
result: zbus::Result<T>,
default: U,
f: F,
) -> zbus::Result<U>
where
F: FnOnce(T) -> U,
{
match result {
Ok(result) => Ok(f(result)),
Err(error) if zbus_error_is_unrecoverable(&error) => Err(error),
Err(_) => Ok(default),
}
}

View file

@ -0,0 +1,246 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
};
use accesskit_atspi_common::{NodeIdOrRoot, PlatformNode, PlatformRoot};
use atspi::{InterfaceSet, ObjectRefOwned, RelationType, Role, StateSet};
use zbus::{fdo, interface, names::OwnedUniqueName};
use super::map_root_error;
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct NodeAccessibleInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl NodeAccessibleInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Accessible")]
impl NodeAccessibleInterface {
#[zbus(property)]
fn name(&self) -> fdo::Result<String> {
self.node.name().map_err(self.map_error())
}
#[zbus(property)]
fn description(&self) -> fdo::Result<String> {
self.node.description().map_err(self.map_error())
}
#[zbus(property)]
fn parent(&self) -> fdo::Result<OwnedObjectAddress> {
self.node.parent().map_err(self.map_error()).map(|parent| {
match parent {
NodeIdOrRoot::Node(node) => ObjectId::Node {
adapter: self.node.adapter_id(),
node,
},
NodeIdOrRoot::Root => ObjectId::Root,
}
.to_address(self.bus_name.inner())
})
}
#[zbus(property)]
fn child_count(&self) -> fdo::Result<i32> {
self.node.child_count().map_err(self.map_error())
}
#[zbus(property)]
fn locale(&self) -> &str {
""
}
#[zbus(property)]
fn accessible_id(&self) -> fdo::Result<String> {
self.node.accessible_id().map_err(self.map_error())
}
fn get_child_at_index(&self, index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let index = index
.try_into()
.map_err(|_| fdo::Error::InvalidArgs("Index can't be negative.".into()))?;
let child = self
.node
.child_at_index(index)
.map_err(self.map_error())?
.map(|child| ObjectId::Node {
adapter: self.node.adapter_id(),
node: child,
});
Ok(super::optional_object_address(&self.bus_name, child))
}
fn get_children(&self) -> fdo::Result<Vec<OwnedObjectAddress>> {
self.node
.map_children(|child| {
ObjectId::Node {
adapter: self.node.adapter_id(),
node: child,
}
.to_address(self.bus_name.inner())
})
.map_err(self.map_error())
}
fn get_index_in_parent(&self) -> fdo::Result<i32> {
self.node.index_in_parent().map_err(self.map_error())
}
fn get_relation_set(&self) -> fdo::Result<Vec<(RelationType, Vec<OwnedObjectAddress>)>> {
self.node
.relation_set(|relation| {
ObjectId::Node {
adapter: self.node.adapter_id(),
node: relation,
}
.to_address(self.bus_name.inner())
})
.map(|set| {
set.into_iter()
.collect::<Vec<(RelationType, Vec<OwnedObjectAddress>)>>()
})
.map_err(self.map_error())
}
fn get_role(&self) -> fdo::Result<Role> {
self.node.role().map_err(self.map_error())
}
fn get_localized_role_name(&self) -> fdo::Result<String> {
self.node.localized_role_name().map_err(self.map_error())
}
fn get_state(&self) -> StateSet {
self.node.state()
}
fn get_attributes(&self) -> fdo::Result<HashMap<&str, String>> {
self.node.attributes().map_err(self.map_error())
}
fn get_application(&self) -> (OwnedObjectAddress,) {
(ObjectId::Root.to_address(self.bus_name.inner()),)
}
fn get_interfaces(&self) -> fdo::Result<InterfaceSet> {
self.node.interfaces().map_err(self.map_error())
}
}
pub(crate) struct RootAccessibleInterface {
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
}
impl RootAccessibleInterface {
pub fn new(
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
) -> Self {
Self {
bus_name,
root,
desktop,
}
}
}
#[interface(name = "org.a11y.atspi.Accessible")]
impl RootAccessibleInterface {
#[zbus(property)]
fn name(&self) -> fdo::Result<String> {
self.root.name().map_err(map_root_error)
}
#[zbus(property)]
fn description(&self) -> fdo::Result<String> {
self.root.description().map_err(map_root_error)
}
#[zbus(property)]
fn parent(&self) -> OwnedObjectAddress {
self.desktop
.get()
.cloned()
.unwrap_or_default()
.into_inner()
.into()
}
#[zbus(property)]
fn child_count(&self) -> fdo::Result<i32> {
self.root.child_count().map_err(map_root_error)
}
#[zbus(property)]
fn locale(&self) -> &str {
""
}
#[zbus(property)]
fn accessible_id(&self) -> &str {
""
}
fn get_child_at_index(&self, index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let index = index
.try_into()
.map_err(|_| fdo::Error::InvalidArgs("Index can't be negative.".into()))?;
let child = self
.root
.child_id_at_index(index)
.map_err(map_root_error)?
.map(|(adapter, node)| ObjectId::Node { adapter, node });
Ok(super::optional_object_address(&self.bus_name, child))
}
fn get_children(&self) -> fdo::Result<Vec<OwnedObjectAddress>> {
self.root
.map_child_ids(|(adapter, node)| {
ObjectId::Node { adapter, node }.to_address(self.bus_name.inner())
})
.map_err(map_root_error)
}
fn get_index_in_parent(&self) -> i32 {
self.root.index_in_parent()
}
fn get_relation_set(&self) -> Vec<(RelationType, Vec<OwnedObjectAddress>)> {
Vec::new()
}
fn get_role(&self) -> Role {
self.root.role()
}
fn get_state(&self) -> StateSet {
self.root.state()
}
fn get_application(&self) -> (OwnedObjectAddress,) {
(ObjectId::Root.to_address(self.bus_name.inner()),)
}
fn get_interfaces(&self) -> InterfaceSet {
self.root.interfaces()
}
}

View file

@ -0,0 +1,51 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{Action, PlatformNode};
use zbus::{fdo, interface};
pub(crate) struct ActionInterface(PlatformNode);
impl ActionInterface {
pub fn new(node: PlatformNode) -> Self {
Self(node)
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.0, error)
}
}
#[interface(name = "org.a11y.atspi.Action")]
impl ActionInterface {
#[zbus(property)]
fn n_actions(&self) -> fdo::Result<i32> {
self.0.n_actions().map_err(self.map_error())
}
fn get_description(&self, _index: i32) -> &str {
""
}
fn get_name(&self, index: i32) -> fdo::Result<String> {
self.0.action_name(index).map_err(self.map_error())
}
fn get_localized_name(&self, index: i32) -> fdo::Result<String> {
self.0.action_name(index).map_err(self.map_error())
}
fn get_key_binding(&self, _index: i32) -> &str {
""
}
fn get_actions(&self) -> fdo::Result<Vec<Action>> {
self.0.actions().map_err(self.map_error())
}
fn do_action(&self, index: i32) -> fdo::Result<bool> {
self.0.do_action(index).map_err(self.map_error())
}
}

View file

@ -0,0 +1,39 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformRoot;
use zbus::{fdo, interface};
use super::map_root_error;
pub(crate) struct ApplicationInterface(pub PlatformRoot);
#[interface(name = "org.a11y.atspi.Application")]
impl ApplicationInterface {
#[zbus(property)]
fn toolkit_name(&self) -> fdo::Result<String> {
self.0.toolkit_name().map_err(map_root_error)
}
#[zbus(property)]
fn version(&self) -> fdo::Result<String> {
self.0.toolkit_version().map_err(map_root_error)
}
#[zbus(property)]
fn atspi_version(&self) -> &str {
"2.1"
}
#[zbus(property)]
fn id(&self) -> fdo::Result<i32> {
self.0.id().map_err(map_root_error)
}
#[zbus(property)]
fn set_id(&mut self, id: i32) -> fdo::Result<()> {
self.0.set_id(id).map_err(map_root_error)
}
}

View file

@ -0,0 +1,314 @@
// Copyright 2026 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{CacheNode, Error, NodeIdOrRoot, PlatformNode, PlatformRoot};
use atspi::{CacheItem, ObjectRef, ObjectRefOwned};
use std::sync::{Arc, OnceLock};
use zbus::{
fdo, interface,
names::{OwnedUniqueName, UniqueName},
};
use super::map_root_error;
use crate::atspi::ObjectId;
pub(crate) fn object_ref(bus_name: &UniqueName, id: ObjectId) -> ObjectRefOwned {
ObjectRef::new_owned(bus_name.to_owned(), id.path())
}
pub(crate) fn cache_item_for_node(
bus_name: &UniqueName,
node: &PlatformNode,
) -> Result<CacheItem, Error> {
Ok(cache_item(bus_name, node.cache_node()?))
}
fn cache_item(bus_name: &UniqueName, node: CacheNode) -> CacheItem {
let parent = match node.parent {
NodeIdOrRoot::Root => ObjectId::Root,
NodeIdOrRoot::Node(node_id) => ObjectId::Node {
adapter: node.adapter_id,
node: node_id,
},
};
CacheItem {
object: object_ref(
bus_name,
ObjectId::Node {
adapter: node.adapter_id,
node: node.id,
},
),
app: object_ref(bus_name, ObjectId::Root),
parent: object_ref(bus_name, parent),
index: node.index_in_parent,
children: node.child_count,
ifaces: node.interfaces,
short_name: node.name,
role: node.role,
name: node.description,
states: node.states,
}
}
fn application_cache_item(
bus_name: &UniqueName,
root: &PlatformRoot,
desktop: ObjectRefOwned,
) -> Result<CacheItem, Error> {
Ok(CacheItem {
object: object_ref(bus_name, ObjectId::Root),
app: object_ref(bus_name, ObjectId::Root),
parent: desktop,
index: root.index_in_parent(),
children: root.child_count()?,
ifaces: root.interfaces(),
short_name: root.name()?,
role: root.role(),
name: root.description()?,
states: root.state(),
})
}
pub(crate) struct CacheInterface {
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
}
impl CacheInterface {
pub fn new(
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
) -> Self {
Self {
bus_name,
root,
desktop,
}
}
fn items(&self) -> Result<Vec<CacheItem>, Error> {
let bus_name = self.bus_name.inner();
let descendants: Vec<CacheItem> = self
.root
.map_descendant_cache_nodes(|node| cache_item(bus_name, node))?;
let desktop = self.desktop.get().cloned().unwrap_or_default();
let mut items = Vec::with_capacity(descendants.len() + 1);
items.push(application_cache_item(bus_name, &self.root, desktop)?);
items.extend(descendants);
Ok(items)
}
}
#[interface(name = "org.a11y.atspi.Cache")]
impl CacheInterface {
fn get_items(&self) -> fdo::Result<Vec<CacheItem>> {
self.items().map_err(map_root_error)
}
}
#[cfg(test)]
mod tests {
use super::{CacheInterface, object_ref};
use crate::atspi::ObjectId;
use accesskit::{
ActionHandler, ActionRequest, Node, NodeId as LocalNodeId, Role, Tree, TreeId, TreeUpdate,
};
use accesskit_atspi_common::{
Adapter, AdapterCallback, AppContext, Event, NodeId, PlatformRoot, WindowBounds,
};
use atspi::{Interface, ObjectRefOwned, Role as AtspiRole};
use std::sync::{Arc, OnceLock};
use zbus::names::{OwnedUniqueName, UniqueName};
struct NoOpActionHandler;
impl ActionHandler for NoOpActionHandler {
fn do_action(&mut self, _request: ActionRequest) {}
}
struct NoOpCallback;
impl AdapterCallback for NoOpCallback {
fn register_interfaces(&self, _: &Adapter, _: NodeId, _: atspi::InterfaceSet) {}
fn unregister_interfaces(&self, _: &Adapter, _: NodeId, _: atspi::InterfaceSet) {}
fn emit_event(&self, _: &Adapter, _: Event) {}
}
fn with_children(role: Role, children: &[LocalNodeId]) -> Node {
let mut node = Node::new(role);
node.set_children(children.to_vec());
node
}
const BUS_NAME: &str = ":1.0";
fn root_for(update: TreeUpdate) -> (Adapter, PlatformRoot) {
let app_context = AppContext::new(None);
let adapter = Adapter::new(
&app_context,
NoOpCallback,
update,
false,
WindowBounds::default(),
NoOpActionHandler,
);
let root = adapter.platform_root();
(adapter, root)
}
fn bus_name() -> OwnedUniqueName {
OwnedUniqueName::try_from(BUS_NAME).unwrap()
}
fn cache(update: TreeUpdate) -> (Adapter, CacheInterface) {
let (adapter, root) = root_for(update);
let desktop = Arc::new(OnceLock::new());
desktop.set(desktop_ref()).unwrap();
(adapter, CacheInterface::new(bus_name(), root, desktop))
}
fn window_with_button() -> TreeUpdate {
TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1)]),
),
(LocalNodeId(1), Node::new(Role::Button)),
],
tree: Some(Tree::new(LocalNodeId(0))),
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
}
}
fn root_ref() -> ObjectRefOwned {
object_ref(
&UniqueName::from_static_str_unchecked(BUS_NAME),
ObjectId::Root,
)
}
fn desktop_ref() -> ObjectRefOwned {
ObjectRefOwned::from_static_str_unchecked(":1.1", "/org/a11y/atspi/accessible/root")
}
#[test]
fn get_items_prepends_application_root() {
let (_adapter, iface) = cache(window_with_button());
let items = iface.items().unwrap();
let [app, _window, _button] = items.as_slice() else {
panic!("expected application root, window, and button");
};
assert_eq!(app.object, root_ref());
assert_eq!(app.app, root_ref());
assert_eq!(app.parent, desktop_ref());
assert_eq!(app.index, -1);
assert_eq!(app.children, 1);
assert_eq!(app.role, AtspiRole::Application);
assert!(app.ifaces.contains(Interface::Application));
}
#[test]
fn top_window_parent_is_application_root() {
let (_adapter, iface) = cache(window_with_button());
let items = iface.items().unwrap();
let [_app, window, _button] = items.as_slice() else {
panic!("expected application root, window, and button");
};
assert_eq!(window.parent, root_ref());
assert_eq!(window.index, 0);
assert!(
window
.object
.path_as_str()
.starts_with("/org/a11y/atspi/accessible/")
);
assert_eq!(window.object.name_as_str(), Some(BUS_NAME));
}
#[test]
fn filtered_child_excluded_from_items_and_counts() {
let mut hidden = Node::new(Role::Button);
hidden.set_hidden();
let update = TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(LocalNodeId(1), Node::new(Role::Button)),
(LocalNodeId(2), hidden),
],
tree: Some(Tree::new(LocalNodeId(0))),
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
};
let (_adapter, iface) = cache(update);
let items = iface.items().unwrap();
let [app_root, window, _visible_button] = items.as_slice() else {
panic!("expected application root, window, and visible button only");
};
assert_eq!(app_root.children, 1);
assert_eq!(window.children, 1);
}
#[test]
fn object_ref_encodes_bus_name_and_node_path() {
let (_adapter, root) = root_for(window_with_button());
let (adapter_id, node_id) = root.child_id_at_index(0).unwrap().unwrap();
let expected_path = ObjectId::Node {
adapter: adapter_id,
node: node_id,
}
.path();
let reference = object_ref(
&UniqueName::from_static_str_unchecked(BUS_NAME),
ObjectId::Node {
adapter: adapter_id,
node: node_id,
},
);
assert_eq!(reference.name_as_str(), Some(BUS_NAME));
assert_eq!(reference.path_as_str(), expected_path.as_str());
}
#[test]
fn multi_adapter_windows_have_distinct_indices() {
let app_context = AppContext::new(None);
let _a0 = Adapter::new(
&app_context,
NoOpCallback,
window_with_button(),
false,
WindowBounds::default(),
NoOpActionHandler,
);
let _a1 = Adapter::new(
&app_context,
NoOpCallback,
window_with_button(),
false,
WindowBounds::default(),
NoOpActionHandler,
);
let iface = CacheInterface::new(
bus_name(),
PlatformRoot::new(&app_context),
Arc::new(OnceLock::new()),
);
let items = iface.items().unwrap();
let app_root = &items[0];
assert_eq!(app_root.children, 2);
let windows = items.iter().filter(|item| item.parent == root_ref());
let mut window_indices: Vec<i32> = windows.map(|item| item.index).collect();
window_indices.sort();
assert_eq!(window_indices, vec![0, 1]);
}
}

View file

@ -0,0 +1,76 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{PlatformNode, Rect};
use atspi::{CoordType, Layer, ScrollType};
use zbus::{fdo, interface, names::OwnedUniqueName};
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct ComponentInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl ComponentInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Component")]
impl ComponentInterface {
fn contains(&self, x: i32, y: i32, coord_type: CoordType) -> fdo::Result<bool> {
self.node
.contains(x, y, coord_type)
.map_err(self.map_error())
}
fn get_accessible_at_point(
&self,
x: i32,
y: i32,
coord_type: CoordType,
) -> fdo::Result<(OwnedObjectAddress,)> {
let accessible = self
.node
.accessible_at_point(x, y, coord_type)
.map_err(self.map_error())?
.map(|node| ObjectId::Node {
adapter: self.node.adapter_id(),
node,
});
Ok(super::optional_object_address(&self.bus_name, accessible))
}
fn get_extents(&self, coord_type: CoordType) -> fdo::Result<(Rect,)> {
self.node
.extents(coord_type)
.map(|rect| (rect,))
.map_err(self.map_error())
}
fn get_layer(&self) -> fdo::Result<Layer> {
self.node.layer().map_err(self.map_error())
}
fn grab_focus(&self) -> fdo::Result<bool> {
self.node.grab_focus().map_err(self.map_error())
}
fn scroll_to(&self, scroll_type: ScrollType) -> fdo::Result<bool> {
self.node.scroll_to(scroll_type).map_err(self.map_error())
}
fn scroll_to_point(&self, coord_type: CoordType, x: i32, y: i32) -> fdo::Result<bool> {
self.node
.scroll_to_point(coord_type, x, y)
.map_err(self.map_error())
}
}

View file

@ -0,0 +1,63 @@
// Copyright 2026 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformNode;
use zbus::{fdo, interface, names::OwnedUniqueName};
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct HyperlinkInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl HyperlinkInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Hyperlink")]
impl HyperlinkInterface {
#[zbus(property)]
fn n_anchors(&self) -> fdo::Result<i32> {
self.node.n_anchors().map_err(self.map_error())
}
#[zbus(property)]
fn start_index(&self) -> fdo::Result<i32> {
self.node.hyperlink_start_index().map_err(self.map_error())
}
#[zbus(property)]
fn end_index(&self) -> fdo::Result<i32> {
self.node.hyperlink_end_index().map_err(self.map_error())
}
fn get_object(&self, index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let object = self
.node
.hyperlink_object(index)
.map_err(self.map_error())?
.map(|node| ObjectId::Node {
adapter: self.node.adapter_id(),
node,
});
Ok(super::optional_object_address(&self.bus_name, object))
}
#[zbus(name = "GetURI")]
fn get_uri(&self, index: i32) -> fdo::Result<String> {
self.node.uri(index).map_err(self.map_error())
}
fn is_valid(&self) -> fdo::Result<bool> {
self.node.hyperlink_is_valid().map_err(self.map_error())
}
}

View file

@ -0,0 +1,41 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
mod accessible;
mod action;
mod application;
mod cache;
mod component;
mod hyperlink;
mod selection;
mod text;
mod value;
use crate::atspi::{ObjectId, OwnedObjectAddress};
use zbus::{fdo, names::UniqueName};
fn map_root_error(error: accesskit_atspi_common::Error) -> fdo::Error {
crate::util::map_error(ObjectId::Root, error)
}
fn optional_object_address(
bus_name: &UniqueName,
object_id: Option<ObjectId>,
) -> (OwnedObjectAddress,) {
match object_id {
Some(id) => (id.to_address(bus_name),),
None => (OwnedObjectAddress::null(),),
}
}
pub(crate) use accessible::*;
pub(crate) use action::*;
pub(crate) use application::*;
pub(crate) use cache::*;
pub(crate) use component::*;
pub(crate) use hyperlink::*;
pub(crate) use selection::*;
pub(crate) use text::*;
pub(crate) use value::*;

View file

@ -0,0 +1,82 @@
// Copyright 2024 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformNode;
use zbus::{fdo, interface, names::OwnedUniqueName};
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct SelectionInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl SelectionInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Selection")]
impl SelectionInterface {
#[zbus(property)]
fn n_selected_children(&self) -> fdo::Result<i32> {
self.node.n_selected_children().map_err(self.map_error())
}
fn get_selected_child(&self, selected_child_index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let child = self
.node
.selected_child(map_child_index(selected_child_index)?)
.map_err(self.map_error())?
.map(|child| ObjectId::Node {
adapter: self.node.adapter_id(),
node: child,
});
Ok(super::optional_object_address(&self.bus_name, child))
}
fn select_child(&self, child_index: i32) -> fdo::Result<bool> {
self.node
.select_child(map_child_index(child_index)?)
.map_err(self.map_error())
}
fn deselect_selected_child(&self, selected_child_index: i32) -> fdo::Result<bool> {
self.node
.deselect_selected_child(map_child_index(selected_child_index)?)
.map_err(self.map_error())
}
fn is_child_selected(&self, child_index: i32) -> fdo::Result<bool> {
self.node
.is_child_selected(map_child_index(child_index)?)
.map_err(self.map_error())
}
fn select_all(&self) -> fdo::Result<bool> {
self.node.select_all().map_err(self.map_error())
}
fn clear_selection(&self) -> fdo::Result<bool> {
self.node.clear_selection().map_err(self.map_error())
}
fn deselect_child(&self, child_index: i32) -> fdo::Result<bool> {
self.node
.deselect_child(map_child_index(child_index)?)
.map_err(self.map_error())
}
}
fn map_child_index(index: i32) -> fdo::Result<usize> {
index
.try_into()
.map_err(|_| fdo::Error::InvalidArgs("Index can't be negative.".into()))
}

View file

@ -0,0 +1,163 @@
// Copyright 2024 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{PlatformNode, Rect};
use atspi::{CoordType, Granularity, ScrollType};
use std::collections::HashMap;
use zbus::{fdo, interface};
pub(crate) struct TextInterface {
node: PlatformNode,
}
impl TextInterface {
pub fn new(node: PlatformNode) -> Self {
Self { node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Text")]
impl TextInterface {
#[zbus(property)]
fn character_count(&self) -> fdo::Result<i32> {
self.node.character_count().map_err(self.map_error())
}
#[zbus(property)]
fn caret_offset(&self) -> fdo::Result<i32> {
self.node.caret_offset().map_err(self.map_error())
}
fn get_string_at_offset(
&self,
offset: i32,
granularity: Granularity,
) -> fdo::Result<(String, i32, i32)> {
self.node
.string_at_offset(offset, granularity)
.map_err(self.map_error())
}
fn get_text(&self, start_offset: i32, end_offset: i32) -> fdo::Result<String> {
self.node
.text(start_offset, end_offset)
.map_err(self.map_error())
}
fn set_caret_offset(&self, offset: i32) -> fdo::Result<bool> {
self.node.set_caret_offset(offset).map_err(self.map_error())
}
fn get_attribute_value(&self, offset: i32, attribute_name: &str) -> fdo::Result<String> {
self.node
.text_attribute_value(offset, attribute_name)
.map_err(self.map_error())
}
fn get_attributes(
&self,
offset: i32,
) -> fdo::Result<(HashMap<&'static str, String>, i32, i32)> {
self.node.text_attributes(offset).map_err(self.map_error())
}
fn get_default_attributes(&self) -> fdo::Result<HashMap<&'static str, String>> {
self.node
.default_text_attributes()
.map_err(self.map_error())
}
fn get_character_extents(&self, offset: i32, coord_type: CoordType) -> fdo::Result<Rect> {
self.node
.character_extents(offset, coord_type)
.map_err(self.map_error())
}
fn get_offset_at_point(&self, x: i32, y: i32, coord_type: CoordType) -> fdo::Result<i32> {
self.node
.offset_at_point(x, y, coord_type)
.map_err(self.map_error())
}
fn get_n_selections(&self) -> fdo::Result<i32> {
self.node.n_selections().map_err(self.map_error())
}
fn get_selection(&self, selection_num: i32) -> fdo::Result<(i32, i32)> {
self.node.selection(selection_num).map_err(self.map_error())
}
fn add_selection(&self, start_offset: i32, end_offset: i32) -> fdo::Result<bool> {
self.node
.add_selection(start_offset, end_offset)
.map_err(self.map_error())
}
fn remove_selection(&self, selection_num: i32) -> fdo::Result<bool> {
self.node
.remove_selection(selection_num)
.map_err(self.map_error())
}
fn set_selection(
&self,
selection_num: i32,
start_offset: i32,
end_offset: i32,
) -> fdo::Result<bool> {
self.node
.set_selection(selection_num, start_offset, end_offset)
.map_err(self.map_error())
}
fn get_range_extents(
&self,
start_offset: i32,
end_offset: i32,
coord_type: CoordType,
) -> fdo::Result<Rect> {
self.node
.range_extents(start_offset, end_offset, coord_type)
.map_err(self.map_error())
}
fn get_attribute_run(
&self,
offset: i32,
include_defaults: bool,
) -> fdo::Result<(HashMap<&'static str, String>, i32, i32)> {
self.node
.text_attribute_run(offset, include_defaults)
.map_err(self.map_error())
}
fn scroll_substring_to(
&self,
start_offset: i32,
end_offset: i32,
scroll_type: ScrollType,
) -> fdo::Result<bool> {
self.node
.scroll_substring_to(start_offset, end_offset, scroll_type)
.map_err(self.map_error())
}
fn scroll_substring_to_point(
&self,
start_offset: i32,
end_offset: i32,
coord_type: CoordType,
x: i32,
y: i32,
) -> fdo::Result<bool> {
self.node
.scroll_substring_to_point(start_offset, end_offset, coord_type, x, y)
.map_err(self.map_error())
}
}

View file

@ -0,0 +1,49 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformNode;
use zbus::{fdo, interface};
pub(crate) struct ValueInterface {
node: PlatformNode,
}
impl ValueInterface {
pub fn new(node: PlatformNode) -> Self {
Self { node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Value")]
impl ValueInterface {
#[zbus(property)]
fn minimum_value(&self) -> fdo::Result<f64> {
self.node.minimum_value().map_err(self.map_error())
}
#[zbus(property)]
fn maximum_value(&self) -> fdo::Result<f64> {
self.node.maximum_value().map_err(self.map_error())
}
#[zbus(property)]
fn minimum_increment(&self) -> fdo::Result<f64> {
self.node.minimum_increment().map_err(self.map_error())
}
#[zbus(property)]
fn current_value(&self) -> fdo::Result<f64> {
self.node.current_value().map_err(self.map_error())
}
#[zbus(property)]
fn set_current_value(&mut self, value: f64) -> fdo::Result<()> {
self.node.set_current_value(value).map_err(self.map_error())
}
}

13
patches/accesskit_unix/src/atspi/mod.rs vendored Normal file
View file

@ -0,0 +1,13 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
mod bus;
pub(crate) mod interfaces;
mod object_address;
mod object_id;
pub(crate) use bus::*;
pub(crate) use object_address::OwnedObjectAddress;
pub(crate) use object_id::{ObjectId, cache_path};

View file

@ -0,0 +1,45 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use atspi::ObjectRef;
use serde::{Deserialize, Serialize};
use zbus::{
names::UniqueName,
wire::{ObjectPath, OwnedObjectPath, OwnedVariant as OwnedValue, Type, Variant as Value},
};
// https://gnome.pages.gitlab.gnome.org/at-spi2-core/libatspi/const.DBUS_PATH_NULL.html
const NULL_PATH: &str = "/org/a11y/atspi/null";
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, OwnedValue, Type, Value)]
pub(crate) struct OwnedObjectAddress {
bus_name: String,
path: OwnedObjectPath,
}
impl OwnedObjectAddress {
pub(crate) fn new(bus_name: &UniqueName, path: OwnedObjectPath) -> Self {
Self {
bus_name: bus_name.to_string(),
path,
}
}
pub(crate) fn null() -> Self {
Self {
bus_name: String::new(),
path: ObjectPath::from_str_unchecked(NULL_PATH).into(),
}
}
}
impl<'a> From<ObjectRef<'a>> for OwnedObjectAddress {
fn from(object: ObjectRef<'a>) -> Self {
Self {
bus_name: object.name().map(|s| s.to_string()).unwrap_or_default(),
path: object.path().to_owned().into(),
}
}
}

View file

@ -0,0 +1,79 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use crate::atspi::OwnedObjectAddress;
use accesskit_atspi_common::{NodeId, PlatformNode};
use serde::{Serialize, Serializer};
use zbus::{
names::UniqueName,
wire::{ObjectPath, OwnedObjectPath, Signature, Structure, Type},
};
const ACCESSIBLE_PATH_PREFIX: &str = "/org/a11y/atspi/accessible/";
const ROOT_PATH: &str = "/org/a11y/atspi/accessible/root";
const CACHE_PATH: &str = "/org/a11y/atspi/cache";
pub(crate) fn cache_path() -> OwnedObjectPath {
ObjectPath::from_str_unchecked(CACHE_PATH).into()
}
#[derive(Debug, PartialEq)]
pub(crate) enum ObjectId {
Root,
Node { adapter: usize, node: NodeId },
}
impl ObjectId {
pub(crate) fn to_address(&self, bus_name: &UniqueName) -> OwnedObjectAddress {
OwnedObjectAddress::new(bus_name, self.path())
}
pub(crate) fn path(&self) -> OwnedObjectPath {
match self {
Self::Root => ObjectPath::from_str_unchecked(ROOT_PATH),
Self::Node { adapter, node } => ObjectPath::from_string_unchecked(format!(
"{}{}/{}",
ACCESSIBLE_PATH_PREFIX,
adapter,
u128::from(*node)
)),
}
.into()
}
}
impl Serialize for ObjectId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Root => serializer.serialize_str("root"),
Self::Node { node, .. } => serializer.serialize_str(&u128::from(*node).to_string()),
}
}
}
impl Type for ObjectId {
const SIGNATURE: &'static Signature = <&str>::SIGNATURE;
}
impl From<ObjectId> for Structure<'_> {
fn from(id: ObjectId) -> Self {
Self::from((match id {
ObjectId::Root => "root".into(),
ObjectId::Node { node, .. } => u128::from(node).to_string(),
},))
}
}
impl From<&PlatformNode> for ObjectId {
fn from(node: &PlatformNode) -> Self {
Self::Node {
adapter: node.adapter_id(),
node: node.id(),
}
}
}

283
patches/accesskit_unix/src/context.rs vendored Normal file
View file

@ -0,0 +1,283 @@
// Copyright 2023 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit::{ActivationHandler, DeactivationHandler};
use accesskit_atspi_common::{Adapter as AdapterImpl, AppContext, Event};
#[cfg(not(feature = "tokio"))]
use async_channel::{Receiver, Sender};
use atspi::proxy::bus::StatusProxy;
#[cfg(not(feature = "tokio"))]
use futures_util::{StreamExt, pin_mut as pin, select};
use std::{
sync::{Arc, Mutex, OnceLock, RwLock},
thread,
};
#[cfg(feature = "tokio")]
use tokio::{
pin, select,
sync::mpsc::{UnboundedReceiver as Receiver, UnboundedSender as Sender},
};
#[cfg(feature = "tokio")]
use tokio_stream::{StreamExt, wrappers::UnboundedReceiverStream};
use zbus::{Connection, connection::Builder, proxy::PropertyChanged};
use crate::{
adapter::{AdapterState, Callback, Message},
atspi::{Bus, map_or_ignoring_recoverable_error, zbus_error_is_unrecoverable},
util::block_on,
};
static APP_CONTEXT: OnceLock<Arc<RwLock<AppContext>>> = OnceLock::new();
static MESSAGES: OnceLock<Sender<Message>> = OnceLock::new();
fn app_name() -> Option<String> {
std::env::current_exe().ok().and_then(|path| {
path.file_name()
.map(|name| name.to_string_lossy().to_string())
})
}
pub(crate) fn get_or_init_app_context<'a>() -> &'a Arc<RwLock<AppContext>> {
APP_CONTEXT.get_or_init(|| AppContext::new(app_name()))
}
pub(crate) fn get_or_init_messages() -> Sender<Message> {
MESSAGES
.get_or_init(|| {
#[cfg(not(feature = "tokio"))]
let (tx, rx) = async_channel::unbounded();
#[cfg(feature = "tokio")]
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
thread::spawn(|| {
// zbus 6's default runtime drives its connection tasks itself.
// Only this AccessKit event loop remains on our dedicated thread.
block_on(async {
if let Ok(session_bus) = Builder::session().build().await {
if let Err(error) = run_event_loop(session_bus, rx).await {
if zbus_error_is_unrecoverable(&error) {
panic!("Accessibility event loop failed: {error}");
}
}
}
})
});
tx
})
.clone()
}
struct AdapterEntry {
id: usize,
activation_handler: Box<dyn ActivationHandler>,
deactivation_handler: Box<dyn DeactivationHandler>,
state: Arc<Mutex<AdapterState>>,
}
fn activate_adapter(entry: &mut AdapterEntry) {
let mut state = entry.state.lock().unwrap();
if let AdapterState::Inactive {
is_window_focused,
root_window_bounds,
action_handler,
} = &*state
{
*state = match entry.activation_handler.request_initial_tree() {
Some(initial_state) => {
let r#impl = AdapterImpl::with_wrapped_action_handler(
entry.id,
get_or_init_app_context(),
Callback::new(),
initial_state,
*is_window_focused,
*root_window_bounds,
Arc::clone(action_handler),
);
AdapterState::Active(r#impl)
}
None => AdapterState::Pending {
is_window_focused: *is_window_focused,
root_window_bounds: *root_window_bounds,
action_handler: Arc::clone(action_handler),
},
};
}
}
fn deactivate_adapter(entry: &mut AdapterEntry) {
let mut state = entry.state.lock().unwrap();
match &*state {
AdapterState::Inactive { .. } => (),
AdapterState::Pending {
is_window_focused,
root_window_bounds,
action_handler,
} => {
*state = AdapterState::Inactive {
is_window_focused: *is_window_focused,
root_window_bounds: *root_window_bounds,
action_handler: Arc::clone(action_handler),
};
drop(state);
entry.deactivation_handler.deactivate_accessibility();
}
AdapterState::Active(r#impl) => {
*state = AdapterState::Inactive {
is_window_focused: r#impl.is_window_focused(),
root_window_bounds: r#impl.root_window_bounds(),
action_handler: r#impl.wrapped_action_handler(),
};
drop(state);
entry.deactivation_handler.deactivate_accessibility();
}
}
}
async fn bus_after_status_change(
change: Option<PropertyChanged<'_, bool>>,
session_bus: &Connection,
) -> zbus::Result<Option<Bus>> {
let enabled = match change {
Some(change) => change.get().await?,
None => false,
};
if enabled {
map_or_ignoring_recoverable_error(Bus::new(session_bus).await, None, Some)
} else {
Ok(None)
}
}
fn sync_adapters(adapters: &mut [AdapterEntry], atspi_bus: &Option<Bus>) {
let active = atspi_bus.is_some();
for entry in adapters {
if active {
activate_adapter(entry);
} else {
deactivate_adapter(entry);
}
}
}
async fn run_event_loop(
session_bus: Connection,
rx: Receiver<Message>,
) -> zbus::Result<()> {
let status = StatusProxy::new(&session_bus).await?;
let changes = status.receive_is_enabled_changed().await.fuse();
pin!(changes);
#[cfg(not(feature = "tokio"))]
let messages = rx.fuse();
#[cfg(feature = "tokio")]
let messages = UnboundedReceiverStream::new(rx).fuse();
pin!(messages);
let mut atspi_bus = None;
let mut adapters: Vec<AdapterEntry> = Vec::new();
loop {
select! {
change = changes.next() => {
atspi_bus = bus_after_status_change(change, &session_bus).await?;
sync_adapters(&mut adapters, &atspi_bus);
}
message = messages.next() => {
if let Some(message) = message {
process_adapter_message(&atspi_bus, &mut adapters, message).await?;
}
}
}
}
}
async fn process_adapter_message(
atspi_bus: &Option<Bus>,
adapters: &mut Vec<AdapterEntry>,
message: Message,
) -> zbus::Result<()> {
match message {
Message::AddAdapter {
id,
activation_handler,
deactivation_handler,
state,
} => {
adapters.push(AdapterEntry {
id,
activation_handler,
deactivation_handler,
state,
});
if atspi_bus.is_some() {
let entry = adapters.last_mut().unwrap();
activate_adapter(entry);
}
}
Message::RemoveAdapter { id } => {
if let Ok(index) = adapters.binary_search_by(|entry| entry.id.cmp(&id)) {
adapters.remove(index);
}
}
Message::RegisterInterfaces { node, interfaces } => {
if let Some(bus) = atspi_bus {
bus.register_interfaces(node, interfaces).await?
}
}
Message::UnregisterInterfaces {
adapter_id,
node_id,
interfaces,
} => {
if let Some(bus) = atspi_bus {
bus.unregister_interfaces(adapter_id, node_id, interfaces)
.await?
}
}
Message::EmitEvent {
adapter_id,
event: Event::Object { target, event },
} => {
if let Some(bus) = atspi_bus {
bus.emit_object_event(adapter_id, target, event).await?
}
}
Message::EmitEvent {
adapter_id,
event:
Event::Window {
target,
name,
event,
},
} => {
if let Some(bus) = atspi_bus {
bus.emit_window_event(adapter_id, target, name, event)
.await?;
}
}
Message::EmitEvent {
event: Event::Cache(_),
..
} => unreachable!("cache events are sent as EmitCacheAdd/EmitCacheRemove"),
Message::EmitCacheAdd { node } => {
if let Some(bus) = atspi_bus {
bus.emit_cache_add(node).await?;
}
}
Message::EmitCacheRemove {
adapter_id,
node_id,
} => {
if let Some(bus) = atspi_bus {
bus.emit_cache_remove(adapter_id, node_id).await?;
}
}
}
Ok(())
}

158
patches/accesskit_unix/src/executor.rs vendored Normal file
View file

@ -0,0 +1,158 @@
// Copyright 2024 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
// Derived from zbus.
// Copyright 2024 Zeeshan Ali Khan.
// Licensed under the MIT license (found in the LICENSE-MIT file).
#[cfg(not(feature = "tokio"))]
use async_executor::Executor as AsyncExecutor;
#[cfg(not(feature = "tokio"))]
use async_task::Task as AsyncTask;
#[cfg(feature = "tokio")]
use std::marker::PhantomData;
#[cfg(not(feature = "tokio"))]
use std::sync::Arc;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
#[cfg(feature = "tokio")]
use tokio::task::JoinHandle;
/// A wrapper around the underlying runtime/executor.
///
/// This is used to run asynchronous tasks internally and allows integration with various runtimes.
/// See [`crate::Connection::executor`] for an example of integration with external runtimes.
///
/// **Note:** You can (and should) completely ignore this type when building with `tokio` feature
/// enabled.
#[cfg(not(feature = "tokio"))]
#[derive(Debug, Clone)]
pub(crate) struct Executor<'a> {
executor: Arc<AsyncExecutor<'a>>,
}
#[cfg(feature = "tokio")]
#[derive(Debug, Clone)]
pub(crate) struct Executor<'a> {
phantom: PhantomData<&'a ()>,
}
impl Executor<'_> {
/// Spawns a task onto the executor.
pub(crate) fn spawn<T: Send + 'static>(
&self,
future: impl Future<Output = T> + Send + 'static,
#[allow(unused)] name: &str,
) -> Task<T> {
#[cfg(not(feature = "tokio"))]
{
Task(Some(self.executor.spawn(future)))
}
#[cfg(feature = "tokio")]
{
Task(Some(tokio::task::spawn(future)))
}
}
/// Create a new `Executor`.
pub(crate) fn new() -> Self {
#[cfg(not(feature = "tokio"))]
{
Self {
executor: Arc::new(AsyncExecutor::new()),
}
}
#[cfg(feature = "tokio")]
{
Self {
phantom: PhantomData,
}
}
}
/// Runs the executor until the given future completes.
///
/// With `tokio` feature enabled, it just awaits on the `future`.
pub(crate) async fn run<T>(&self, future: impl Future<Output = T>) -> T {
#[cfg(not(feature = "tokio"))]
{
self.executor.run(future).await
}
#[cfg(feature = "tokio")]
{
future.await
}
}
}
/// A wrapper around the task API of the underlying runtime/executor.
///
/// This follows the semantics of `async_task::Task` on drop:
///
/// * it will be cancelled, rather than detached. For detaching, use the `detach` method.
/// * errors from the task cancellation will will be ignored. If you need to know about task errors,
/// convert the task to a `FallibleTask` using the `fallible` method.
#[cfg(not(feature = "tokio"))]
#[derive(Debug)]
pub(crate) struct Task<T>(Option<AsyncTask<T>>);
#[cfg(feature = "tokio")]
#[derive(Debug)]
pub(crate) struct Task<T>(Option<JoinHandle<T>>);
impl<T> Task<T> {
/// Detaches the task to let it keep running in the background.
#[allow(unused_mut)]
#[allow(unused)]
pub(crate) fn detach(mut self) {
#[cfg(not(feature = "tokio"))]
{
self.0.take().expect("async_task::Task is none").detach()
}
#[cfg(feature = "tokio")]
{
self.0.take().expect("tokio::task::JoinHandle is none");
}
}
}
impl<T> Drop for Task<T> {
fn drop(&mut self) {
#[cfg(feature = "tokio")]
{
if let Some(join_handle) = self.0.take() {
join_handle.abort();
}
}
}
}
impl<T> Future for Task<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[cfg(not(feature = "tokio"))]
{
Pin::new(&mut self.get_mut().0.as_mut().expect("async_task::Task is none")).poll(cx)
}
#[cfg(feature = "tokio")]
{
Pin::new(
&mut self
.get_mut()
.0
.as_mut()
.expect("tokio::task::JoinHandle is none"),
)
.poll(cx)
.map(|r| r.expect("tokio::task::JoinHandle error"))
}
}
}

26
patches/accesskit_unix/src/lib.rs vendored Normal file
View file

@ -0,0 +1,26 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
/// ## Compatibility with async runtimes
///
/// While this crate's API is purely blocking, it internally spawns asynchronous tasks on an executor.
///
/// - If you use tokio, make sure to enable the `tokio` feature of this crate.
/// - If you use another async runtime or if you don't use one at all, the default feature will suit your needs.
#[cfg(all(not(feature = "async-io"), not(feature = "tokio")))]
compile_error!("Either \"async-io\" (default) or \"tokio\" feature must be enabled.");
#[cfg(all(feature = "async-io", feature = "tokio"))]
compile_error!(
"Both \"async-io\" (default) and \"tokio\" features cannot be enabled at the same time."
);
mod adapter;
mod atspi;
mod context;
mod util;
pub use adapter::Adapter;

42
patches/accesskit_unix/src/util.rs vendored Normal file
View file

@ -0,0 +1,42 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{Error as InternalError, PlatformNode};
use zbus::fdo::Error as FdoError;
use crate::atspi::ObjectId;
#[cfg(not(feature = "tokio"))]
pub(crate) fn block_on<F: std::future::Future>(future: F) -> F::Output {
futures_lite::future::block_on(future)
}
#[cfg(feature = "tokio")]
pub(crate) fn block_on<F: std::future::Future>(future: F) -> F::Output {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.build()
.expect("launch of single-threaded tokio runtime");
runtime.block_on(future)
}
pub(crate) fn map_error(source: ObjectId, error: InternalError) -> FdoError {
match error {
InternalError::Defunct | InternalError::UnsupportedInterface => {
FdoError::UnknownObject(source.path().to_string())
}
InternalError::TooManyChildren => FdoError::Failed("Too many children.".into()),
InternalError::IndexOutOfRange => FdoError::Failed("Index is too big.".into()),
InternalError::TooManyCharacters => FdoError::Failed("Too many characters.".into()),
InternalError::UnsupportedTextGranularity => {
FdoError::Failed("Unsupported text granularity.".into())
}
}
}
pub(crate) fn map_error_from_node(source: &PlatformNode, error: InternalError) -> FdoError {
map_error(ObjectId::from(source), error)
}

110
patches/atspi-common/Cargo.toml vendored Normal file
View file

@ -0,0 +1,110 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.77.2"
name = "atspi-common"
version = "0.13.0"
build = false
include = [
"LICENSE-*",
"README.md",
"src/**/*",
"xml/*",
]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Primitive types used for sending and receiving Linux accessibility events."
readme = "README.md"
keywords = [
"Accessibility",
"Macros",
]
categories = [
"accessibility",
"api-bindings",
]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/odilia-app/atspi"
[features]
default = [
"wrappers",
"zbus",
]
wrappers = []
zbus = []
[lib]
name = "atspi_common"
path = "src/lib.rs"
[dependencies.enumflags2]
version = "0.7.9"
[dependencies.serde]
version = "1.0.200"
[dependencies.static_assertions]
version = "1.1.0"
[dependencies.zbus]
version = "6.1"
features = ["default-rt", "proxy", "service", "object-manager"]
default-features = false
[dependencies.zbus-lockstep]
version = "0.5.1"
[dependencies.zbus-lockstep-macros]
version = "0.5.1"
[dev-dependencies.assert_matches]
version = "1.5.0"
[dev-dependencies.rename-item]
version = "0.1.0"
[dev-dependencies.serde_plain]
version = "1.0.1"
[dev-dependencies.static_assertions]
version = "1.1.0"
[dev-dependencies.tokio]
version = "1.38.2"
features = [
"macros",
"rt-multi-thread",
]
default-features = false
[dev-dependencies.tokio-stream]
version = "0.1.1"
features = ["time"]
default-features = false
[dev-dependencies.tokio-test]
version = "0.4.2"
[dev-dependencies.zbus]
version = "6.1"
features = ["default-rt", "proxy", "service", "object-manager"]
default-features = false
[dev-dependencies.zbus_xml]
version = "6"

201
patches/atspi-common/LICENSE-APACHE2.txt vendored Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

19
patches/atspi-common/LICENSE-MIT.txt vendored Normal file
View file

@ -0,0 +1,19 @@
Copyright (c) 2022 Tait Hoyem <tait@tait.tech>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

13
patches/atspi-common/README.md vendored Normal file
View file

@ -0,0 +1,13 @@
# `atspi-common`
Common data structures for the `atspi` crate.
This crate is meant to only contain the absolute lowest common denominator for libraries to talk to each other about `atspi` information;
therefore, it attempts to be able to compile on basically any architecture (including WASM).
Please use the internal documentation to learn how to use these data structures.
## Feature Flags
- `default`: `zbus`, `wrappers`
- `zbus`: include support for serializing/deserializing from `zbus::Message`s over DBus.
- `wrappers`: container enum types that group events by AT-SPI interface, as well as `Event` wrapper that contains any possible event.

9
patches/atspi-common/VNOX-PATCH.md vendored Normal file
View file

@ -0,0 +1,9 @@
# Vnox maintenance patch: atspi-common 0.13.0
Source: published crates.io atspi-common 0.13.0, original licenses included.
This is a maintained-parent compatibility backport, not a fork of an unmaintained D-Bus codec. Vnox updates dependencies/imports to maintained zbus 6, which merged zvariant and zbus_names. The original package version identifies its API baseline; no version is spoofed to suppress RustSec.
The Slint Winit patch additionally uses Winit's supported crossfont CSD backend to avoid the unmaintained ttf-parser chain while retaining Wayland client-side title decorations.
Remove this patch once upstream publishes the equivalent migration. Changes must be tested with full client build, native rendering, accessibility/portal interfaces and RustSec audit.

28
patches/atspi-common/src/action.rs vendored Normal file
View file

@ -0,0 +1,28 @@
use serde::{Deserialize, Serialize};
use zbus::wire::Type;
/// An action which may be triggered through the accessibility API.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct Action {
/// The name of the action
pub name: String,
/// Description of the action
pub description: String,
// TODO: should be an enum/stricter type; this is why it's in its own file.
/// The keybinding(s) used to trigger it (without the AT).
pub keybinding: String,
}
#[cfg(test)]
mod test {
use super::Action;
use zbus_lockstep::method_return_signature;
use zbus::wire::Type;
#[test]
fn validate_action_signature() {
// signature is of type `a(sss)`, where `(sss)` is the type we're validating.
let action_signature =
method_return_signature!(member: "GetActions", interface: "org.a11y.atspi.Action");
assert_eq!(Vec::<Action>::SIGNATURE, &action_signature);
}
}

122
patches/atspi-common/src/cache.rs vendored Normal file
View file

@ -0,0 +1,122 @@
//! Common types for `org.a11y.atspi.Cache` events.
//!
use crate::{object_ref::ObjectRefOwned, InterfaceSet, ObjectRef, Role, StateSet};
use serde::{Deserialize, Serialize};
use zbus_lockstep_macros::validate;
use zbus::wire::Type;
/// The item type provided by `Cache:Add` signals
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Debug, Serialize, Deserialize, Type, PartialEq, Eq, Hash)]
#[validate(signal: "AddAccessible")]
pub struct CacheItem {
/// The accessible object (within the application) (so)
pub object: ObjectRefOwned,
/// The application (root object(?) (so)
pub app: ObjectRefOwned,
/// The parent object. (so)
pub parent: ObjectRefOwned,
/// The accessbile index in parent. i
pub index: i32,
/// Child count of the accessible i
pub children: i32,
/// The exposed interface(s) set. as
pub ifaces: InterfaceSet,
/// The short localized name. s
pub short_name: String,
/// `ObjectRef` role. u
pub role: Role,
/// More detailed localized name.
pub name: String,
/// The states applicable to the accessible. au
pub states: StateSet,
}
impl Default for CacheItem {
fn default() -> Self {
Self {
object: ObjectRefOwned::from_static_str_unchecked(
":0.0",
"/org/a11y/atspi/accessible/object",
),
app: ObjectRefOwned::from_static_str_unchecked(
":0.0",
"/org/a11y/atspi/accessible/application",
),
parent: ObjectRefOwned::from_static_str_unchecked(
":0.0",
"/org/a11y/atspi/accessible/parent",
),
index: 0,
children: 0,
ifaces: InterfaceSet::empty(),
short_name: String::default(),
role: Role::Invalid,
name: String::default(),
states: StateSet::empty(),
}
}
}
/// The item type provided by `Cache:Add` signals
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Debug, Serialize, Deserialize, Type, PartialEq, Eq, Hash)]
pub struct LegacyCacheItem {
/// The accessible object (within the application) (so)
pub object: ObjectRefOwned,
/// The application (root object(?) (so)
pub app: ObjectRefOwned,
/// The parent object. (so)
pub parent: ObjectRefOwned,
/// List of references to the accessible's children. a(so)
pub children: Vec<ObjectRefOwned>,
/// The exposed interface(s) set. as
pub ifaces: InterfaceSet,
/// The short localized name. s
pub short_name: String,
/// `ObjectRef` role. u
pub role: Role,
/// More detailed localized name.
pub name: String,
/// The states applicable to the accessible. au
pub states: StateSet,
}
impl Default for LegacyCacheItem {
fn default() -> Self {
Self {
object: ObjectRef::from_static_str_unchecked(
":0.0",
"/org/a11y/atspi/accessible/object",
)
.into(),
app: ObjectRef::from_static_str_unchecked(
":0.0",
"/org/a11y/atspi/accessible/application",
)
.into(),
parent: ObjectRef::from_static_str_unchecked(
":0.0",
"/org/a11y/atspi/accessible/parent",
)
.into(),
children: Vec::new(),
ifaces: InterfaceSet::empty(),
short_name: String::default(),
role: Role::Invalid,
name: String::default(),
states: StateSet::empty(),
}
}
}
#[cfg(test)]
#[test]
fn zvariant_type_signature_of_legacy_cache_item() {
use std::str::FromStr;
assert_eq!(
*<LegacyCacheItem as Type>::SIGNATURE,
zbus::wire::Signature::from_str("((so)(so)(so)a(so)assusau)").unwrap()
);
}

210
patches/atspi-common/src/error.rs vendored Normal file
View file

@ -0,0 +1,210 @@
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
#[non_exhaustive]
/// An error type that can describe atspi and `std` and different `zbus` errors.
pub enum AtspiError {
/// Converting one type into another failure
Conversion(&'static str),
/// When testing on either variant, we might find the we are not interested in.
CacheVariantMismatch,
/// On specific types, if the event / message member does not match the Event's name.
MemberMatch(String),
/// On specific types, if the event / message member does not match the Event's name.
InterfaceMatch(String),
/// On specific types, if the kind (string variant) does not match the Event's kind.
KindMatch(String),
/// When an interface is not available.
InterfaceNotAvailable(&'static str),
/// To indicate a match or equality test on a signal body signature failed.
SignatureMatch(String),
/// When matching on an unknown interface
UnknownInterface,
/// No interface on event.
MissingInterface,
/// No member on event.
MissingMember,
/// No path on event.
MissingPath,
/// When matching on an unknown role
UnknownRole(u32),
/// No name on bus.
MissingName,
/// The signal that was encountered is unknown.
UnknownSignal,
/// Other errors.
Owned(String),
/// Null-reference error. This is used when an `ObjectRef` is expected to be non-null, but it is null.
NullRef(&'static str),
/// A `zbus` or `zbus::Fdo` error. variant.
Zbus(String),
/// A `zbus_names` error variant
ZBusNames(zbus::Error),
/// A `zbus_names` error variant
Zvariant(zbus::Error),
/// Failed to parse a string into an enum variant
ParseError(&'static str),
/// Failed to get the ID of a path.
PathConversionError(ObjectPathConversionError),
/// Std i/o error variant.
IO(std::io::Error),
/// Failed to convert an integer into another type of integer (usually i32 -> usize).
IntConversionError(std::num::TryFromIntError),
/// An infallible error; this is just something to satisfy the compiler.
Infallible,
}
impl std::error::Error for AtspiError {}
impl std::fmt::Display for AtspiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Conversion(e) => f.write_str(&format!("atspi: conversion failure: {e}")),
Self::MemberMatch(e) => {
f.write_str("atspi: member mismatch in conversion: ")?;
e.fmt(f)
}
Self::InterfaceMatch(e) => {
f.write_str("atspi: interface mismatch in conversion: ")?;
e.fmt(f)
}
Self::KindMatch(e) => {
f.write_str(format!("atspi: kind mismatch in conversion: {e}").as_str())
}
Self::SignatureMatch(e) => {
f.write_str(format!("atspi: body signature mismatch in conversion: {e:?}").as_str())
}
Self::InterfaceNotAvailable(e) => {
f.write_str(format!("atspi: interface not available: {e}").as_str())
}
Self::UnknownInterface => f.write_str("Unknown interface."),
Self::MissingInterface => f.write_str("Missing interface."),
Self::MissingMember => f.write_str("Missing member."),
Self::MissingPath => f.write_str("Missing path."),
Self::UnknownRole(e) => {
f.write_str("atspi: Unknown role: ")?;
e.fmt(f)
}
Self::UnknownSignal => f.write_str("atspi: Unknown signal"),
Self::CacheVariantMismatch => f.write_str("atspi: Cache variant mismatch"),
Self::Owned(e) => {
f.write_str("atspi: other error: ")?;
e.fmt(f)
}
Self::NullRef(e) => {
f.write_str("atspi: null reference: ")?;
f.write_str(e)
}
Self::Zbus(e) => {
f.write_str("ZBus Error: ")?;
e.fmt(f)
}
Self::Zvariant(e) => {
f.write_str("Zvariant error: ")?;
e.fmt(f)
}
Self::ZBusNames(e) => {
f.write_str("ZBus_names Error: ")?;
e.fmt(f)
}
Self::ParseError(e) => f.write_str(e),
Self::PathConversionError(e) => {
f.write_str("ID cannot be extracted from the path: ")?;
e.fmt(f)
}
Self::IO(e) => {
f.write_str("std IO Error: ")?;
e.fmt(f)
}
Self::IntConversionError(e) => {
f.write_str("Integer conversion error: ")?;
e.fmt(f)
}
Self::MissingName => f.write_str("Missing name for a bus."),
Self::Infallible => {
f.write_str("Infallible; only to trick the compiler. This should never happen.")
}
}
}
}
impl From<std::convert::Infallible> for AtspiError {
fn from(_e: std::convert::Infallible) -> Self {
Self::Infallible
}
}
impl From<std::num::TryFromIntError> for AtspiError {
fn from(e: std::num::TryFromIntError) -> Self {
Self::IntConversionError(e)
}
}
#[cfg(feature = "zbus")]
impl From<zbus::fdo::Error> for AtspiError {
fn from(e: zbus::fdo::Error) -> Self {
Self::Zbus(format!("{e:?}"))
}
}
impl From<zbus::Error> for AtspiError {
fn from(e: zbus::Error) -> Self {
Self::Zbus(format!("{e:?}"))
}
}
impl From<std::io::Error> for AtspiError {
fn from(e: std::io::Error) -> Self {
Self::IO(e)
}
}
impl From<ObjectPathConversionError> for AtspiError {
fn from(e: ObjectPathConversionError) -> AtspiError {
Self::PathConversionError(e)
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Debug)]
pub enum ObjectPathConversionError {
NoIdAvailable,
ParseError(<i64 as std::str::FromStr>::Err),
}
impl std::fmt::Display for ObjectPathConversionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoIdAvailable => f.write_str("No ID available in the path."),
Self::ParseError(e) => {
f.write_str("Failure to parse: ")?;
e.fmt(f)
}
}
}
}
impl std::error::Error for ObjectPathConversionError {}

168
patches/atspi-common/src/events/cache.rs vendored Normal file
View file

@ -0,0 +1,168 @@
use crate::cache::{CacheItem, LegacyCacheItem};
#[cfg(feature = "zbus")]
use crate::error::AtspiError;
#[cfg(feature = "zbus")]
use crate::object_ref::ObjectRef;
#[cfg(feature = "zbus")]
use crate::EventProperties;
use crate::{
events::{DBusInterface, DBusMatchRule, DBusMember, RegistryEventString},
object_ref::ObjectRefOwned,
};
use serde::{Deserialize, Serialize};
#[cfg(feature = "zbus")]
use zbus::message::{Body as DbusBody, Header};
#[cfg(feature = "zbus")]
use super::{MessageConversion, MessageConversionExt};
/// Type that contains the `zbus::Message` for meta information and
/// the [`crate::cache::LegacyCacheItem`]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, Eq, Hash)]
pub struct LegacyAddAccessibleEvent {
/// The [`ObjectRef`] the event applies to.
pub item: ObjectRefOwned,
/// A cache item to add to the internal cache.
pub node_added: LegacyCacheItem,
}
impl_event_type_properties_for_event!(LegacyAddAccessibleEvent);
event_test_cases!(LegacyAddAccessibleEvent, Explicit);
impl_from_dbus_message!(LegacyAddAccessibleEvent, Explicit);
impl_event_properties!(LegacyAddAccessibleEvent);
impl_to_dbus_message!(LegacyAddAccessibleEvent);
impl_member_interface_registry_string_and_match_rule_for_event!(
LegacyAddAccessibleEvent,
"AddAccessible",
"org.a11y.atspi.Cache",
"cache:add",
"type='signal',interface='org.a11y.atspi.Cache',member='AddAccessible'"
);
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for LegacyAddAccessibleEvent {
type Body<'msg> = LegacyCacheItem;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
Ok(Self { item: item.into(), node_added: body.deserialize_ignore_signature::<Self::Body<'_>>()? })
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
self.node_added.clone()
}
}
/// Type that contains the `zbus::Message` for meta information and
/// the [`crate::cache::CacheItem`]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, Eq, Hash)]
pub struct AddAccessibleEvent {
/// The [`ObjectRef`] the event applies to.
pub item: ObjectRefOwned,
/// A cache item to add to the internal cache.
pub node_added: CacheItem,
}
impl_event_type_properties_for_event!(AddAccessibleEvent);
event_test_cases!(AddAccessibleEvent, Explicit);
impl_member_interface_registry_string_and_match_rule_for_event!(
AddAccessibleEvent,
"AddAccessible",
"org.a11y.atspi.Cache",
"cache:add",
"type='signal',interface='org.a11y.atspi.Cache',member='AddAccessible'"
);
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for AddAccessibleEvent {
type Body<'msg> = CacheItem;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
Ok(Self { item: item.into(), node_added: body.deserialize_ignore_signature::<Self::Body<'_>>()? })
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
self.node_added.clone()
}
}
impl_msg_conversion_ext_for_target_type_with_specified_body_type!(target: AddAccessibleEvent, body: CacheItem);
impl_from_dbus_message!(AddAccessibleEvent, Explicit);
impl_event_properties!(AddAccessibleEvent);
impl_to_dbus_message!(AddAccessibleEvent);
/// `Cache::RemoveAccessible` signal event type.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, Eq, Hash)]
pub struct RemoveAccessibleEvent {
/// The application that emitted the signal TODO Check Me
/// The [`ObjectRef`] the event applies to.
pub item: ObjectRefOwned,
/// The node that was removed from the application tree TODO Check Me
pub node_removed: ObjectRefOwned,
}
impl_event_type_properties_for_event!(RemoveAccessibleEvent);
event_test_cases!(RemoveAccessibleEvent, Explicit);
impl_member_interface_registry_string_and_match_rule_for_event!(
RemoveAccessibleEvent,
"RemoveAccessible",
"org.a11y.atspi.Cache",
"cache:remove",
"type='signal',interface='org.a11y.atspi.Cache',member='RemoveAccessible'"
);
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for RemoveAccessibleEvent {
type Body<'msg> = ObjectRefOwned;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
Ok(Self {
item: item.into(),
node_removed: body.deserialize_ignore_signature::<Self::Body<'_>>()?,
})
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
self.node_removed.clone()
}
}
#[cfg(feature = "zbus")]
impl MessageConversionExt<'_, LegacyCacheItem> for LegacyAddAccessibleEvent {
fn try_from_message(msg: &zbus::Message, hdr: &Header) -> Result<Self, AtspiError> {
<LegacyAddAccessibleEvent as MessageConversionExt<crate::LegacyCacheItem>>::validate_interface(hdr)?;
<LegacyAddAccessibleEvent as MessageConversionExt<crate::LegacyCacheItem>>::validate_member(hdr)?;
<LegacyAddAccessibleEvent as MessageConversionExt<crate::LegacyCacheItem>>::validate_body(
msg,
)?;
<LegacyAddAccessibleEvent as MessageConversion>::from_message_unchecked(msg, hdr)
}
}
impl_msg_conversion_ext_for_target_type_with_specified_body_type!(target: RemoveAccessibleEvent, body: ObjectRefOwned);
impl_from_dbus_message!(RemoveAccessibleEvent, Explicit);
impl_event_properties!(RemoveAccessibleEvent);
impl_to_dbus_message!(RemoveAccessibleEvent);

View file

@ -0,0 +1,166 @@
use crate::events::{DBusInterface, DBusMatchRule, DBusMember, RegistryEventString};
use crate::object_ref::ObjectRefOwned;
#[cfg(feature = "zbus")]
use crate::EventProperties;
#[cfg(feature = "zbus")]
use crate::AtspiError;
#[cfg(feature = "zbus")]
use zbus::message::Header;
/// An event triggered by the completion of a document load action.
/// For example: a web page has finished loading its initial payload, or
/// `LibreOffice` has loaded a document from disk.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct LoadCompleteEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
/// An event triggered by a reloading of a document.
/// For example: pressing F5, or `Control + r` will reload a page in a web browser.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct ReloadEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
/// An event triggered by the cancelling of a document load.
/// For example: during the loading of a large web page, a user may press `Escape` to stop loading the page.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct LoadStoppedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct ContentChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct AttributesChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
/// The focused page has changed.
///
/// This event is usually sent only by document readers, signaling
/// that the _physical page equivalent is now different.
/// This event does not encode _which_ page is the new one, only that a new page is now the primary
/// one.
///
/// See `atspi_proxies::document::DocumentProxy::current_page_number` to actively find the
/// page number.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct PageChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_member_interface_registry_string_and_match_rule_for_event!(
LoadCompleteEvent,
"LoadComplete",
"org.a11y.atspi.Event.Document",
"document:load-complete",
"type='signal',interface='org.a11y.atspi.Event.Document',member='LoadComplete'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
ReloadEvent,
"Reload",
"org.a11y.atspi.Event.Document",
"document:reload",
"type='signal',interface='org.a11y.atspi.Event.Document',member='LoadStopped'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
LoadStoppedEvent,
"LoadStopped",
"org.a11y.atspi.Event.Document",
"document:load-stopped",
"type='signal',interface='org.a11y.atspi.Event.Document',member='LoadStopped'"
);
// TODO confirm registry event string, not found in grep at at-spi2-core
impl_member_interface_registry_string_and_match_rule_for_event!(
ContentChangedEvent,
"ContentChanged",
"org.a11y.atspi.Event.Document",
"document:content-changed",
"type='signal',interface='org.a11y.atspi.Event.Document',member='ContentChanged'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
AttributesChangedEvent,
"AttributesChanged",
"org.a11y.atspi.Event.Document",
"document:attributes-changed",
"type='signal',interface='org.a11y.atspi.Event.Document',member='AttributesChanged'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
PageChangedEvent,
"PageChanged",
"org.a11y.atspi.Event.Document",
"document:page-changed",
"type='signal',interface='org.a11y.atspi.Event.Document',member='PageChanged'"
);
impl_event_type_properties_for_event!(LoadCompleteEvent);
event_test_cases!(LoadCompleteEvent);
impl_to_dbus_message!(LoadCompleteEvent);
impl_from_dbus_message!(LoadCompleteEvent);
impl_event_properties!(LoadCompleteEvent);
impl_from_object_ref!(LoadCompleteEvent);
impl_event_type_properties_for_event!(ReloadEvent);
event_test_cases!(ReloadEvent);
impl_to_dbus_message!(ReloadEvent);
impl_from_dbus_message!(ReloadEvent);
impl_event_properties!(ReloadEvent);
impl_from_object_ref!(ReloadEvent);
impl_event_type_properties_for_event!(LoadStoppedEvent);
event_test_cases!(LoadStoppedEvent);
impl_to_dbus_message!(LoadStoppedEvent);
impl_from_dbus_message!(LoadStoppedEvent);
impl_event_properties!(LoadStoppedEvent);
impl_from_object_ref!(LoadStoppedEvent);
impl_event_type_properties_for_event!(ContentChangedEvent);
event_test_cases!(ContentChangedEvent);
impl_to_dbus_message!(ContentChangedEvent);
impl_from_dbus_message!(ContentChangedEvent);
impl_event_properties!(ContentChangedEvent);
impl_from_object_ref!(ContentChangedEvent);
impl_event_type_properties_for_event!(AttributesChangedEvent);
event_test_cases!(AttributesChangedEvent);
impl_to_dbus_message!(AttributesChangedEvent);
impl_from_dbus_message!(AttributesChangedEvent);
impl_event_properties!(AttributesChangedEvent);
impl_from_object_ref!(AttributesChangedEvent);
impl_event_type_properties_for_event!(PageChangedEvent);
event_test_cases!(PageChangedEvent);
impl_to_dbus_message!(PageChangedEvent);
impl_from_dbus_message!(PageChangedEvent);
impl_event_properties!(PageChangedEvent);
impl_from_object_ref!(PageChangedEvent);
impl_msg_conversion_ext_for_target_type!(LoadCompleteEvent);
impl_msg_conversion_ext_for_target_type!(ReloadEvent);
impl_msg_conversion_ext_for_target_type!(LoadStoppedEvent);
impl_msg_conversion_ext_for_target_type!(ContentChangedEvent);
impl_msg_conversion_ext_for_target_type!(AttributesChangedEvent);
impl_msg_conversion_ext_for_target_type!(PageChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(LoadCompleteEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ReloadEvent);
impl_msg_conversion_for_types_built_from_object_ref!(LoadStoppedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ContentChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(AttributesChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(PageChangedEvent);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,36 @@
#[cfg(feature = "zbus")]
use crate::error::AtspiError;
#[cfg(feature = "zbus")]
use crate::EventProperties;
use crate::{
events::{DBusInterface, DBusMatchRule, DBusMember, RegistryEventString},
object_ref::ObjectRefOwned,
};
#[cfg(feature = "zbus")]
use zbus::message::Header;
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct FocusEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(FocusEvent);
impl_member_interface_registry_string_and_match_rule_for_event! {
FocusEvent,
"Focus",
"org.a11y.atspi.Event.Focus",
"focus:",
"type='signal',interface='org.a11y.atspi.Event.Focus',member='Focus'"
}
impl_msg_conversion_ext_for_target_type!(FocusEvent);
impl_msg_conversion_for_types_built_from_object_ref!(FocusEvent);
event_test_cases!(FocusEvent);
impl_to_dbus_message!(FocusEvent);
impl_from_dbus_message!(FocusEvent);
impl_event_properties!(FocusEvent);
impl_from_object_ref!(FocusEvent);

View file

@ -0,0 +1,77 @@
#[cfg(feature = "zbus")]
use super::event_body::EventBody;
#[cfg(feature = "zbus")]
use crate::error::AtspiError;
use crate::{
events::{DBusInterface, DBusMatchRule, DBusMember, EventBodyOwned, RegistryEventString},
object_ref::ObjectRefOwned,
};
#[cfg(feature = "zbus")]
use crate::{events::MessageConversion, EventProperties, ObjectRef};
#[cfg(feature = "zbus")]
use zbus::message::{Body as DbusBody, Header};
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct ModifiersEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
pub previous_modifiers: i32,
pub current_modifiers: i32,
}
impl_event_type_properties_for_event!(ModifiersEvent);
impl_member_interface_registry_string_and_match_rule_for_event! {
ModifiersEvent,
"Modifiers",
"org.a11y.atspi.Event.Keyboard",
"keyboard:modifiers",
"type='signal',interface='org.a11y.atspi.Event.Keyboard',member='Modifiers'"
}
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for ModifiersEvent {
type Body<'msg> = EventBody<'msg>;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
let body = body.deserialize_ignore_signature::<Self::Body<'_>>()?;
Ok(Self {
item: item.into(),
previous_modifiers: body.detail1(),
current_modifiers: body.detail2(),
})
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
EventBodyOwned {
detail1: self.previous_modifiers,
detail2: self.current_modifiers,
..Default::default()
}
.into()
}
}
impl_msg_conversion_ext_for_target_type!(ModifiersEvent);
event_test_cases!(ModifiersEvent);
impl_to_dbus_message!(ModifiersEvent);
impl_from_dbus_message!(ModifiersEvent);
impl_event_properties!(ModifiersEvent);
impl From<ModifiersEvent> for EventBodyOwned {
fn from(event: ModifiersEvent) -> Self {
EventBodyOwned {
detail1: event.previous_modifiers,
detail2: event.current_modifiers,
..Default::default()
}
}
}

27
patches/atspi-common/src/events/mod.rs vendored Normal file
View file

@ -0,0 +1,27 @@
pub mod cache;
pub mod document;
pub mod event_body;
#[cfg(feature = "wrappers")]
pub mod event_wrappers;
pub mod focus;
pub mod keyboard;
pub mod mouse;
pub mod object;
pub mod registry;
pub mod terminal;
pub mod traits;
pub mod window;
pub use event_body::{
EventBody, EventBodyBorrowed, EventBodyOwned, EventBodyQtBorrowed, EventBodyQtOwned,
};
#[cfg(feature = "wrappers")]
pub use event_wrappers::{
CacheEvents, DocumentEvents, Event, EventListenerEvents, FocusEvents, KeyboardEvents,
MouseEvents, ObjectEvents, TerminalEvents, WindowEvents,
};
pub use traits::{
DBusInterface, DBusMatchRule, DBusMember, DBusProperties, EventProperties, EventTypeProperties,
RegistryEventString,
};
#[cfg(feature = "zbus")]
pub use traits::{MessageConversion, MessageConversionExt};

213
patches/atspi-common/src/events/mouse.rs vendored Normal file
View file

@ -0,0 +1,213 @@
#[cfg(feature = "zbus")]
use crate::events::MessageConversion;
use crate::events::{
DBusInterface, DBusMatchRule, DBusMember, EventBody, EventBodyOwned, RegistryEventString,
};
use crate::object_ref::ObjectRefOwned;
#[cfg(feature = "zbus")]
use crate::EventProperties;
#[cfg(feature = "zbus")]
use crate::{error::AtspiError, ObjectRef};
#[cfg(feature = "zbus")]
use zbus::message::{Body as DbusBody, Header};
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct AbsEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
pub x: i32,
pub y: i32,
}
impl_event_type_properties_for_event!(AbsEvent);
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct RelEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
pub x: i32,
pub y: i32,
}
impl_event_type_properties_for_event!(RelEvent);
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct ButtonEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
pub detail: String,
pub mouse_x: i32,
pub mouse_y: i32,
}
impl_event_type_properties_for_event!(ButtonEvent);
impl_member_interface_registry_string_and_match_rule_for_event! {
AbsEvent,
"Abs",
"org.a11y.atspi.Event.Mouse",
"mouse:abs",
"type='signal',interface='org.a11y.atspi.Event.Mouse',member='Abs'"
}
impl_member_interface_registry_string_and_match_rule_for_event! {
RelEvent,
"Rel",
"org.a11y.atspi.Event.Mouse",
"mouse:rel",
"type='signal',interface='org.a11y.atspi.Event.Mouse',member='Rel'"
}
impl_member_interface_registry_string_and_match_rule_for_event! {
ButtonEvent,
"Button",
"org.a11y.atspi.Event.Mouse",
"mouse:button",
"type='signal',interface='org.a11y.atspi.Event.Mouse',member='Button'"
}
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for AbsEvent {
type Body<'a> = EventBody<'a>;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
let body = body.deserialize_ignore_signature::<Self::Body<'_>>()?;
Ok(Self { item: item.into(), x: body.detail1(), y: body.detail2() })
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
EventBodyOwned { detail1: self.x, detail2: self.y, ..Default::default() }.into()
}
}
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for RelEvent {
type Body<'a> = EventBody<'a>;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
let body = body.deserialize_ignore_signature::<Self::Body<'_>>()?;
Ok(Self { item: item.into(), x: body.detail1(), y: body.detail2() })
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
EventBodyOwned { detail1: self.x, detail2: self.y, ..Default::default() }.into()
}
}
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for ButtonEvent {
type Body<'a> = EventBody<'a>;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
let mut body = body.deserialize_ignore_signature::<Self::Body<'_>>()?;
Ok(Self {
item: item.into(),
detail: body.take_kind(),
mouse_x: body.detail1(),
mouse_y: body.detail2(),
})
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
EventBodyOwned::from(self).into()
}
}
event_test_cases!(AbsEvent);
impl_to_dbus_message!(AbsEvent);
impl_from_dbus_message!(AbsEvent);
impl_event_properties!(AbsEvent);
impl From<AbsEvent> for EventBodyOwned {
fn from(event: AbsEvent) -> Self {
EventBodyOwned { detail1: event.x, detail2: event.y, ..Default::default() }
}
}
impl From<&AbsEvent> for EventBodyOwned {
fn from(event: &AbsEvent) -> Self {
EventBodyOwned { detail1: event.x, detail2: event.y, ..Default::default() }
}
}
impl From<AbsEvent> for EventBody<'_> {
fn from(event: AbsEvent) -> Self {
EventBodyOwned::from(event).into()
}
}
event_test_cases!(RelEvent);
impl_to_dbus_message!(RelEvent);
impl_from_dbus_message!(RelEvent);
impl_event_properties!(RelEvent);
impl From<RelEvent> for EventBodyOwned {
fn from(event: RelEvent) -> Self {
EventBodyOwned { detail1: event.x, detail2: event.y, ..Default::default() }
}
}
impl From<&RelEvent> for EventBodyOwned {
fn from(event: &RelEvent) -> Self {
EventBodyOwned { detail1: event.x, detail2: event.y, ..Default::default() }
}
}
impl From<RelEvent> for EventBody<'_> {
fn from(event: RelEvent) -> Self {
EventBodyOwned::from(event).into()
}
}
event_test_cases!(ButtonEvent);
impl_to_dbus_message!(ButtonEvent);
impl_from_dbus_message!(ButtonEvent);
impl_event_properties!(ButtonEvent);
impl From<ButtonEvent> for EventBodyOwned {
fn from(event: ButtonEvent) -> Self {
EventBodyOwned {
kind: event.detail,
detail1: event.mouse_x,
detail2: event.mouse_y,
..Default::default()
}
}
}
impl From<ButtonEvent> for EventBody<'_> {
fn from(event: ButtonEvent) -> Self {
EventBodyOwned::from(event).into()
}
}
impl From<&ButtonEvent> for EventBodyOwned {
fn from(event: &ButtonEvent) -> Self {
EventBodyOwned {
kind: event.detail.clone(),
detail1: event.mouse_x,
detail2: event.mouse_y,
..Default::default()
}
}
}
impl_msg_conversion_ext_for_target_type!(AbsEvent);
impl_msg_conversion_ext_for_target_type!(RelEvent);
impl_msg_conversion_ext_for_target_type!(ButtonEvent);

1237
patches/atspi-common/src/events/object.rs vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,231 @@
//! This module contains the events that are emitted by the registry daemon.
//! The events are [`EventListenerRegisteredEvent`] and [`EventListenerDeregisteredEvent`].
#[cfg(feature = "zbus")]
use crate::object_ref::ObjectRef;
#[cfg(feature = "zbus")]
use crate::{error::AtspiError, events::MessageConversion, EventProperties};
use serde::{Deserialize, Serialize};
#[cfg(feature = "zbus")]
use zbus::message::{Body as DbusBody, Header};
use zbus_lockstep_macros::validate;
use zbus::names::{OwnedUniqueName, UniqueName};
use zbus::wire::Type;
use crate::{
events::{DBusInterface, DBusMatchRule, DBusMember, RegistryEventString},
object_ref::ObjectRefOwned,
};
/// An event that is emitted by the registry daemon, to inform that an event has been deregistered
/// to no longer listen for.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, Eq, Hash)]
pub struct EventListenerDeregisteredEvent {
/// The [`ObjectRef`] the event applies to.
pub item: ObjectRefOwned,
/// A list of events that have been deregistered via the registry interface.
/// See `atspi-connection`.
pub deregistered_event: EventListeners,
}
impl_event_type_properties_for_event!(EventListenerDeregisteredEvent);
event_test_cases!(EventListenerDeregisteredEvent, Explicit);
// The registry string cannot be found in upstrream at-spi2-core.
impl_member_interface_registry_string_and_match_rule_for_event!(
EventListenerDeregisteredEvent,
"EventListenerDeregistered",
"org.a11y.atspi.Registry",
"registry:event-listener-deregistered",
"type='signal',interface='org.a11y.atspi.Registry',member='EventListenerDeregistered'"
);
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for EventListenerDeregisteredEvent {
type Body<'a> = EventListeners;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
let deregistered_event = body.deserialize_ignore_signature::<Self::Body<'_>>()?;
Ok(Self { item: item.into(), deregistered_event })
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
self.deregistered_event.clone()
}
}
impl_msg_conversion_ext_for_target_type_with_specified_body_type!(target: EventListenerDeregisteredEvent, body: EventListeners);
impl_from_dbus_message!(EventListenerDeregisteredEvent, Explicit);
impl_event_properties!(EventListenerDeregisteredEvent);
impl_to_dbus_message!(EventListenerDeregisteredEvent);
/// An event that is emitted by the regostry daemon to signal that an event has been registered to listen for.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, Eq, Hash)]
pub struct EventListenerRegisteredEvent {
/// The [`ObjectRef`] the event applies to.
pub item: ObjectRefOwned,
/// A list of events that have been registered via the registry interface.
/// See `atspi-connection`.
pub registered_event: EventListeners,
}
impl_event_type_properties_for_event!(EventListenerRegisteredEvent);
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for EventListenerRegisteredEvent {
type Body<'a> = EventListeners;
fn from_message_unchecked_parts(
item: ObjectRef,
registered_event: DbusBody,
) -> Result<Self, AtspiError> {
let registered_event = registered_event.deserialize_ignore_signature()?;
Ok(Self { item: item.into(), registered_event })
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
self.registered_event.clone()
}
}
impl_msg_conversion_ext_for_target_type_with_specified_body_type!(target: EventListenerRegisteredEvent, body: EventListeners);
impl_from_dbus_message!(EventListenerRegisteredEvent, Explicit);
impl_event_properties!(EventListenerRegisteredEvent);
impl_to_dbus_message!(EventListenerRegisteredEvent);
event_test_cases!(EventListenerRegisteredEvent, Explicit);
// The registry string cannot be found in upstrream at-spi2-core.
impl_member_interface_registry_string_and_match_rule_for_event!(
EventListenerRegisteredEvent,
"EventListenerRegistered",
"org.a11y.atspi.Registry",
"registry:event-listener-registered",
"type='signal',interface='org.a11y.atspi.Registry',member='EventListenerRegistered'"
);
/// Signal type emitted by `EventListenerRegistered` and `EventListenerDeregistered` signals,
/// which belong to the `Registry` interface, implemented by the registry-daemon.
#[validate(signal: "EventListenerRegistered")]
#[derive(Debug, Clone, Serialize, Deserialize, Type, PartialEq, Eq, Hash)]
pub struct EventListeners {
pub bus_name: OwnedUniqueName,
// TODO: `path` should be a `zbus::wire::ObjectPath` but that requires changing the signature with an attribute
// and `Serialize`/`Deserialize` impls.
pub path: String,
}
impl Default for EventListeners {
fn default() -> Self {
Self {
bus_name: UniqueName::from_static_str_unchecked(":0.0").into(),
path: String::from("/org/a11y/atspi/null"),
}
}
}
#[cfg(test)]
mod event_listener_tests {
use super::*;
#[test]
fn test_event_listener_default_no_panic() {
let el = EventListeners::default();
assert_eq!(el.bus_name.as_str(), ":0.0");
assert_eq!(el.path.as_str(), "/org/a11y/atspi/null");
}
}
pub mod socket {
//! This module contains the event that is emitted by the registry daemon's `Socket` interface.
#[cfg(feature = "zbus")]
use crate::events::MessageConversion;
use crate::events::{DBusInterface, DBusMatchRule, DBusMember, RegistryEventString};
use crate::object_ref::ObjectRefOwned;
#[cfg(feature = "zbus")]
use crate::AtspiError;
#[cfg(feature = "zbus")]
use crate::EventProperties;
#[cfg(feature = "zbus")]
use crate::ObjectRef;
#[cfg(feature = "zbus")]
use zbus::message::{Body as DbusBody, Header};
use serde::{Deserialize, Serialize};
/// An event that is emitted when the registry daemon has started.
///
/// The accessibility registry emits this signal early during startup,
/// when it has registered with the `DBus` daemon and is available for
/// calls from applications.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, Eq, Hash)]
pub struct AvailableEvent {
/// The emitting [`ObjectRef`].
pub item: ObjectRefOwned,
/// The [`ObjectRef`] for the Registry's root object.
pub socket: ObjectRefOwned,
}
impl_event_type_properties_for_event!(AvailableEvent);
event_test_cases!(AvailableEvent, Explicit);
// We cannot register at Registry for this event, as it is emitted by the Registry itself at early startup.
// So, we do not have a registry event string for this event.
// The `Available` event is unconditionally emitted:
// [at-spi2-core/registryd/registry.c:1437](https://github.com/GNOME/at-spi2-core/blob/019d1a4013216d7d01040cf4eb3b8647bffc0dc9/registryd/registry.c#L1437)
impl_member_interface_registry_string_and_match_rule_for_event!(
AvailableEvent,
"Available",
"org.a11y.atspi.Socket",
"",
"type='signal',interface='org.a11y.atspi.Socket',member='Available'"
);
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for AvailableEvent {
type Body<'a> = ObjectRef<'a>;
fn from_message_unchecked_parts(
item: ObjectRef<'_>,
body: DbusBody,
) -> Result<Self, AtspiError> {
let socket = body.deserialize_ignore_signature::<Self::Body<'_>>()?;
Ok(Self { item: item.into(), socket: socket.into() })
}
fn from_message_unchecked(
msg: &zbus::Message,
header: &Header,
) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
self.socket.clone().into_inner()
}
}
impl_msg_conversion_ext_for_target_type_with_specified_body_type!(target: AvailableEvent, body: ObjectRef<'a>);
impl_from_dbus_message!(AvailableEvent, Explicit);
impl_event_properties!(AvailableEvent);
impl_to_dbus_message!(AvailableEvent);
}

View file

@ -0,0 +1,139 @@
#[cfg(feature = "zbus")]
use crate::error::AtspiError;
#[cfg(feature = "zbus")]
use crate::EventProperties;
use crate::{
events::{DBusInterface, DBusMatchRule, DBusMember, RegistryEventString},
object_ref::ObjectRefOwned,
};
#[cfg(feature = "zbus")]
use zbus::message::Header;
/// A line of text has been changed.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct LineChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(LineChangedEvent);
/// The width of a terminal emulator has changed sufficiently such that the number of characters
/// able to fit on one *visual* line has changed.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct ColumnCountChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(ColumnCountChangedEvent);
/// The height of a terminal emulator has changed sufficiently such that the number of lines
/// able to fit within the terminal has changed.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct LineCountChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(LineCountChangedEvent);
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct ApplicationChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(ApplicationChangedEvent);
/// The width of a terminal emulator has changed sufficiently such that the number of characters
/// able to fit on one *visual* line has changed.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct CharWidthChangedEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(CharWidthChangedEvent);
impl_member_interface_registry_string_and_match_rule_for_event!(
LineChangedEvent,
"LineChanged",
"org.a11y.atspi.Event.Terminal",
"terminal:line-changed",
"type='signal',interface='org.a11y.atspi.Event.Terminal',member='LineChanged'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
ColumnCountChangedEvent,
"ColumncountChanged",
"org.a11y.atspi.Event.Terminal",
"terminal:columncount-changed",
"type='signal',interface='org.a11y.atspi.Event.Terminal',member='ColumncountChanged'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
LineCountChangedEvent,
"LinecountChanged",
"org.a11y.atspi.Event.Terminal",
"terminal:linecount-changed",
"type='signal',interface='org.a11y.atspi.Event.Terminal',member='LinecountChanged'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
ApplicationChangedEvent,
"ApplicationChanged",
"org.a11y.atspi.Event.Terminal",
"terminal:application-changed",
"type='signal',interface='org.a11y.atspi.Event.Terminal',member='ApplicationChanged'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
CharWidthChangedEvent,
"CharwidthChanged",
"org.a11y.atspi.Event.Terminal",
"terminal:char-width-changed",
"type='signal',interface='org.a11y.atspi.Event.Terminal',member='CharwidthChanged'"
);
event_test_cases!(LineChangedEvent);
impl_to_dbus_message!(LineChangedEvent);
impl_from_dbus_message!(LineChangedEvent);
impl_event_properties!(LineChangedEvent);
impl_from_object_ref!(LineChangedEvent);
event_test_cases!(ColumnCountChangedEvent);
impl_to_dbus_message!(ColumnCountChangedEvent);
impl_from_dbus_message!(ColumnCountChangedEvent);
impl_event_properties!(ColumnCountChangedEvent);
impl_from_object_ref!(ColumnCountChangedEvent);
event_test_cases!(LineCountChangedEvent);
impl_to_dbus_message!(LineCountChangedEvent);
impl_from_dbus_message!(LineCountChangedEvent);
impl_event_properties!(LineCountChangedEvent);
impl_from_object_ref!(LineCountChangedEvent);
event_test_cases!(ApplicationChangedEvent);
impl_to_dbus_message!(ApplicationChangedEvent);
impl_from_dbus_message!(ApplicationChangedEvent);
impl_event_properties!(ApplicationChangedEvent);
impl_from_object_ref!(ApplicationChangedEvent);
event_test_cases!(CharWidthChangedEvent);
impl_to_dbus_message!(CharWidthChangedEvent);
impl_from_dbus_message!(CharWidthChangedEvent);
impl_event_properties!(CharWidthChangedEvent);
impl_from_object_ref!(CharWidthChangedEvent);
impl_msg_conversion_ext_for_target_type!(LineChangedEvent);
impl_msg_conversion_ext_for_target_type!(ColumnCountChangedEvent);
impl_msg_conversion_ext_for_target_type!(LineCountChangedEvent);
impl_msg_conversion_ext_for_target_type!(ApplicationChangedEvent);
impl_msg_conversion_ext_for_target_type!(CharWidthChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(LineChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ColumnCountChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(LineCountChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ApplicationChangedEvent);
impl_msg_conversion_for_types_built_from_object_ref!(CharWidthChangedEvent);

View file

@ -0,0 +1,239 @@
#[cfg(feature = "zbus")]
use crate::AtspiError;
use crate::ObjectRef;
#[cfg(feature = "zbus")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "zbus")]
use zbus::message::{Body as DbusBody, Header};
use zbus::names::UniqueName;
use zbus::wire::ObjectPath;
#[cfg(feature = "zbus")]
use zbus::wire::Type;
/// Describes properties of a specific event _type_.
///
/// - `DBus` member name
/// - `DBus` interface name
///
/// Together, the member and interface name can describe a specific event _type_.
/// Likewise, the path and sender bus name collectively make up an [`ObjectRef`], which is a way to uniquely identify an individual accessible item available to `atspi`.
/// The latter is available via the [`EventProperties`] trait.
///
/// This can also be generalized, for example this is implemented for [`crate::Event`] by dispatching to the matching variants.
/// NOTE: to use `EventProperties` on wrapper types, like `Event`, you must enable the "enum-dispatch" feature.
///
/// This trait *is* object-safe.
pub trait EventTypeProperties {
fn member(&self) -> &'static str;
fn interface(&self) -> &'static str;
fn match_rule(&self) -> &'static str;
fn registry_string(&self) -> &'static str;
}
/// `EventProperties` allows access to the internals of an event, specifically:
///
/// - The `DBUs` name which sent the event.
/// - The `ObjectPath`, a unique id for a given application.
/// - Collectively, this is called an [`ObjectRef`].
///
/// This trait *is* object-safe.
pub trait EventProperties {
fn sender(&self) -> UniqueName<'_>;
fn path(&self) -> ObjectPath<'_>;
fn object_ref(&self) -> ObjectRef<'_> {
ObjectRef::new(self.sender(), self.path())
}
}
assert_obj_safe!(EventTypeProperties);
assert_obj_safe!(EventProperties);
/// A way to convert a [`zbus::Message`] without checking its interface.
#[cfg(all(feature = "zbus", feature = "wrappers"))]
pub(crate) trait EventWrapperMessageConversion {
/// # Errors
/// Will fail if no matching member or body signature is found.
fn try_from_message_interface_checked(
msg: &zbus::Message,
hdr: &Header,
) -> Result<Self, AtspiError>
where
Self: Sized;
}
// TODO: Document why this can't be `TryFrom<&zbus::Message>`.
#[cfg(all(feature = "zbus", feature = "wrappers"))]
pub(crate) trait TryFromMessage {
fn try_from_message(msg: &zbus::Message) -> Result<Self, AtspiError>
where
Self: Sized;
}
/// The `DBus` member for the event.
/// For example, for an [`crate::events::object::TextChangedEvent`] this should be `"TextChanged"`
pub trait DBusMember {
/// The event's `DBus` member.
const DBUS_MEMBER: &'static str;
}
/// The `DBus` interface name for an event - or a wrapper type.
/// For example, for any event within the "Object" interface, this should be "org.a11y.atspi.Event.Object".
pub trait DBusInterface {
/// A static interface string for `DBus`.
/// This should usually be a string that looks like this: `"org.a11y.atspi.Event.*"`;
const DBUS_INTERFACE: &'static str;
}
/// A static `DBus` match rule string.
/// This should usually be a string that looks like this:
/// `"type='signal',interface='org.a11y.atspi.Event.Object',member='PropertyChange'"`;
// We cannot concat! consts, so we (at time of writing) need to have a separate trait for this.
// Otherwise composing from `DBusMember` and `DBusInterface` would be preferred.
pub trait DBusMatchRule {
/// A static match rule string for `DBus`.
const MATCH_RULE_STRING: &'static str;
}
/// A static `Registry` event string for registering with the `RegistryProxy` for receiving events.
pub trait RegistryEventString {
/// A registry event string for registering for event receiving via the `RegistryProxy`.
/// This should be deprecated in favour of composing the string from [`DBusMember::DBUS_MEMBER`] and [`DBusInterface::DBUS_INTERFACE`].
const REGISTRY_EVENT_STRING: &'static str;
}
/// A 'alias'-trait that combines all the `DBus` related traits.
pub trait DBusProperties: DBusMember + DBusInterface + DBusMatchRule + RegistryEventString {}
#[cfg(feature = "zbus")]
pub trait MessageConversionExt<'a, B>: 'a + MessageConversion<'a, Body<'a> = B>
where
B: Type + Serialize + Deserialize<'a>,
{
/// Convert a [`zbus::Message`] into this event type.
/// Does all the validation for you.
///
/// # Errors
///
/// - The message does not have an interface: [`type@AtspiError::MissingInterface`]
/// - The message interface does not match the one for the event: [`type@AtspiError::InterfaceMatch`]
/// - The message does not have an member: [`type@AtspiError::MissingMember`]
/// - The message member does not match the one for the event: [`type@AtspiError::MemberMatch`]
/// - The message signature does not match the one for the event: [`type@AtspiError::SignatureMatch`]
///
/// See [`MessageConversion::from_message_unchecked`] for info on panic condition that should never
/// happen.
fn try_from_message(msg: &'a zbus::Message, hdr: &Header) -> Result<Self, AtspiError>
where
Self: Sized + 'a;
/// Validate the interface string via [`zbus::message::Header::interface`] against `Self`'s assignment of [`DBusInterface::DBUS_INTERFACE`]
///
/// # Errors
///
/// - [`type@AtspiError::MissingInterface`] if there is no interface
/// - [`type@AtspiError::InterfaceMatch`] if the interfaces do not match
fn validate_interface(header: &Header) -> Result<(), AtspiError> {
let interface = header.interface().ok_or(AtspiError::MissingInterface)?;
if interface != Self::DBUS_INTERFACE {
return Err(AtspiError::InterfaceMatch(format!(
"The interface {} does not match the signal's interface: {}",
interface,
Self::DBUS_INTERFACE,
)));
}
Ok(())
}
/// Validate the member string via [`zbus::message::Header::member`] against `Self`'s assignment of [`DBusMember::DBUS_MEMBER`]
///
/// # Errors
///
/// - [`type@AtspiError::MissingMember`] if there is no member
/// - [`type@AtspiError::MemberMatch`] if the members do not match
fn validate_member(hdr: &Header) -> Result<(), AtspiError> {
let member = hdr.member().ok_or(AtspiError::MissingMember)?;
if member != Self::DBUS_MEMBER {
return Err(AtspiError::MemberMatch(format!(
"The member {} does not match the signal's member: {}",
// unwrap is safe here because of guard above
member,
Self::DBUS_MEMBER,
)));
}
Ok(())
}
/// Validate the body signature against the [`zbus::wire::Signature`] of [`MessageConversion::Body`]
///
/// # Errors
///
/// - [`type@AtspiError::SignatureMatch`] if the signatures do not match
fn validate_body(msg: &zbus::Message) -> Result<(), AtspiError> {
let body = msg.body();
let body_signature = body.signature();
let expected_signature = B::SIGNATURE;
if body_signature != expected_signature {
return Err(AtspiError::SignatureMatch(format!(
"The message signature {} does not match the signal's body signature: {}",
body_signature,
&expected_signature.to_string(),
)));
}
Ok(())
}
}
#[cfg(feature = "zbus")]
pub trait MessageConversion<'a>: DBusProperties {
/// What is the body type of this event.
type Body<'msg>: Type + Deserialize<'msg> + Serialize
where
Self: 'msg;
/// Build an event from a [`zbus::Message`] reference.
/// This function will not check for any of the following error conditions:
///
/// - That the message has an interface: [`type@AtspiError::MissingInterface`]
/// - That the message interface matches the one for the event: [`type@AtspiError::InterfaceMatch`]
/// - That the message has an member: [`type@AtspiError::MissingMember`]
/// - That the message member matches the one for the event: [`type@AtspiError::MemberMatch`]
/// - That the message signature matches the one for the event: [`type@AtspiError::SignatureMatch`]
///
/// Therefore, this should only be used when one has checked the above conditions.
/// These must be checked manually.
/// Alternatively, there is the [`MessageConversionExt::try_from_message`] that will check these
/// conditions for you.
///
/// This type also implements `TryFrom<&zbus::Message>`; consider using this if you are not an
/// internal developer.
///
/// # Errors
///
/// It is possible to get a [`type@AtspiError::Zvariant`] error if you do not check the proper
/// conditions before calling this.
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError>
where
Self: Sized + 'a;
/// Build an event from an [`ObjectRef`] and [`Self::Body`].
/// This function will not check for any of the following error conditions:
///
/// - That the message has an interface: [`type@AtspiError::MissingInterface`]
/// - That the message interface matches the one for the event: [`type@AtspiError::InterfaceMatch`]
/// - That the message has an member: [`type@AtspiError::MissingMember`]
/// - That the message member matches the one for the event: [`type@AtspiError::MemberMatch`]
///
/// Therefore, this should only be used when one has checked the above conditions.
///
/// # Errors
///
/// Some [`Self::Body`] types may fallibly convert data fields contained in the body.
/// If this happens, then the function will return an error.
fn from_message_unchecked_parts(obj_ref: ObjectRef, body: DbusBody) -> Result<Self, AtspiError>
where
Self: Sized;
/// The body of the object.
fn body(&self) -> Self::Body<'_>;
}

View file

@ -0,0 +1,504 @@
#[cfg(feature = "zbus")]
use crate::error::AtspiError;
#[cfg(feature = "zbus")]
use crate::events::EventBody;
#[cfg(feature = "zbus")]
use crate::events::MessageConversion;
use crate::events::{
DBusInterface, DBusMatchRule, DBusMember, EventBodyOwned, RegistryEventString,
};
use crate::object_ref::ObjectRefOwned;
#[cfg(feature = "zbus")]
use crate::{EventProperties, ObjectRef};
use serde::Deserialize;
use serde::Serialize;
#[cfg(feature = "zbus")]
use zbus::message::{Body as DbusBody, Header};
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct PropertyChangeEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
pub property: String,
}
impl_event_type_properties_for_event!(PropertyChangeEvent);
/// The window has been minimized.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct MinimizeEvent {
/// The application which has been minimized.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(MinimizeEvent);
/// The window has been maximized.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct MaximizeEvent {
/// The application which has been maximized.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(MaximizeEvent);
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct RestoreEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(RestoreEvent);
/// A window has been closed.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct CloseEvent {
/// The application which has been closed.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(CloseEvent);
/// A new window has been created.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct CreateEvent {
/// An application to query for additional events from.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(CreateEvent);
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct ReparentEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(ReparentEvent);
/// A new virtual desktop has been created.
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub struct DesktopCreateEvent {
/// A reference to a new desktop
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(DesktopCreateEvent);
/// A virtual desktop has been deleted.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct DesktopDestroyEvent {
/// A reference to the destroyed desktop.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(DesktopDestroyEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct DestroyEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(DestroyEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct ActivateEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(ActivateEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct DeactivateEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(DeactivateEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct RaiseEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(RaiseEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct LowerEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(LowerEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct MoveEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(MoveEvent);
/// A window has been resized.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct ResizeEvent {
/// The application which has been resized.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(ResizeEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct ShadeEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(ShadeEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct UUshadeEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(UUshadeEvent);
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Eq, Hash, Default)]
pub struct RestyleEvent {
/// The [`crate::ObjectRef`] which the event applies to.
pub item: ObjectRefOwned,
}
impl_event_type_properties_for_event!(RestyleEvent);
impl_member_interface_registry_string_and_match_rule_for_event!(
PropertyChangeEvent,
"PropertyChange",
"org.a11y.atspi.Event.Window",
"window:property-change",
"type='signal',interface='org.a11y.atspi.Event.Window',member='PropertyChange'"
);
#[cfg(feature = "zbus")]
impl MessageConversion<'_> for PropertyChangeEvent {
type Body<'a> = EventBody<'a>;
fn from_message_unchecked_parts(item: ObjectRef, body: DbusBody) -> Result<Self, AtspiError> {
let mut body = body.deserialize_ignore_signature::<Self::Body<'_>>()?;
Ok(Self { item: item.into(), property: body.take_kind() })
}
fn from_message_unchecked(msg: &zbus::Message, header: &Header) -> Result<Self, AtspiError> {
let item = header.try_into()?;
let body = msg.body();
Self::from_message_unchecked_parts(item, body)
}
fn body(&self) -> Self::Body<'_> {
EventBody::Owned(EventBodyOwned { kind: self.property.clone(), ..Default::default() })
}
}
impl_member_interface_registry_string_and_match_rule_for_event!(
MinimizeEvent,
"Minimize",
"org.a11y.atspi.Event.Window",
"window:minimize",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Minimize'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
MaximizeEvent,
"Maximize",
"org.a11y.atspi.Event.Window",
"window:maximize",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Maximize'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
RestoreEvent,
"Restore",
"org.a11y.atspi.Event.Window",
"window:restore",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Restore'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
CloseEvent,
"Close",
"org.a11y.atspi.Event.Window",
"window:close",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Close'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
CreateEvent,
"Create",
"org.a11y.atspi.Event.Window",
"window:create",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Create'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
ReparentEvent,
"Reparent",
"org.a11y.atspi.Event.Window",
"window:reparent",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Reparent'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
DesktopCreateEvent,
"DesktopCreate",
"org.a11y.atspi.Event.Window",
"window:desktop-create",
"type='signal',interface='org.a11y.atspi.Event.Window',member='DesktopCreate'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
DesktopDestroyEvent,
"DesktopDestroy",
"org.a11y.atspi.Event.Window",
"window:desktop-destroy",
"type='signal',interface='org.a11y.atspi.Event.Window',member='DesktopDestroy'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
DestroyEvent,
"Destroy",
"org.a11y.atspi.Event.Window",
"window:destroy",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Destroy'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
ActivateEvent,
"Activate",
"org.a11y.atspi.Event.Window",
"window:activate",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Activate'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
DeactivateEvent,
"Deactivate",
"org.a11y.atspi.Event.Window",
"window:deactivate",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Deactivate'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
RaiseEvent,
"Raise",
"org.a11y.atspi.Event.Window",
"window:raise",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Raise'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
LowerEvent,
"Lower",
"org.a11y.atspi.Event.Window",
"window:lower",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Lower'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
MoveEvent,
"Move",
"org.a11y.atspi.Event.Window",
"window:move",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Move'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
ResizeEvent,
"Resize",
"org.a11y.atspi.Event.Window",
"window:resize",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Resize'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
ShadeEvent,
"Shade",
"org.a11y.atspi.Event.Window",
"window:shade",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Shade'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
UUshadeEvent,
"uUshade",
"org.a11y.atspi.Event.Window",
"window:uushade",
"type='signal',interface='org.a11y.atspi.Event.Window',member='uUshade'"
);
impl_member_interface_registry_string_and_match_rule_for_event!(
RestyleEvent,
"Restyle",
"org.a11y.atspi.Event.Window",
"window:restyle",
"type='signal',interface='org.a11y.atspi.Event.Window',member='Restyle'"
);
event_test_cases!(PropertyChangeEvent);
impl_to_dbus_message!(PropertyChangeEvent);
impl_from_dbus_message!(PropertyChangeEvent);
impl_event_properties!(PropertyChangeEvent);
impl From<PropertyChangeEvent> for EventBodyOwned {
fn from(event: PropertyChangeEvent) -> Self {
EventBodyOwned { kind: event.property, ..Default::default() }
}
}
event_test_cases!(MinimizeEvent);
impl_to_dbus_message!(MinimizeEvent);
impl_from_dbus_message!(MinimizeEvent);
impl_event_properties!(MinimizeEvent);
impl_from_object_ref!(MinimizeEvent);
event_test_cases!(MaximizeEvent);
impl_to_dbus_message!(MaximizeEvent);
impl_from_dbus_message!(MaximizeEvent);
impl_event_properties!(MaximizeEvent);
impl_from_object_ref!(MaximizeEvent);
event_test_cases!(RestoreEvent);
impl_to_dbus_message!(RestoreEvent);
impl_from_dbus_message!(RestoreEvent);
impl_event_properties!(RestoreEvent);
impl_from_object_ref!(RestoreEvent);
event_test_cases!(CloseEvent);
impl_to_dbus_message!(CloseEvent);
impl_from_dbus_message!(CloseEvent);
impl_event_properties!(CloseEvent);
impl_from_object_ref!(CloseEvent);
event_test_cases!(CreateEvent);
impl_to_dbus_message!(CreateEvent);
impl_from_dbus_message!(CreateEvent);
impl_event_properties!(CreateEvent);
impl_from_object_ref!(CreateEvent);
event_test_cases!(ReparentEvent);
impl_to_dbus_message!(ReparentEvent);
impl_from_dbus_message!(ReparentEvent);
impl_event_properties!(ReparentEvent);
impl_from_object_ref!(ReparentEvent);
event_test_cases!(DesktopCreateEvent);
impl_to_dbus_message!(DesktopCreateEvent);
impl_from_dbus_message!(DesktopCreateEvent);
impl_event_properties!(DesktopCreateEvent);
impl_from_object_ref!(DesktopCreateEvent);
event_test_cases!(DesktopDestroyEvent);
impl_to_dbus_message!(DesktopDestroyEvent);
impl_from_dbus_message!(DesktopDestroyEvent);
impl_event_properties!(DesktopDestroyEvent);
impl_from_object_ref!(DesktopDestroyEvent);
event_test_cases!(DestroyEvent);
impl_to_dbus_message!(DestroyEvent);
impl_from_dbus_message!(DestroyEvent);
impl_event_properties!(DestroyEvent);
impl_from_object_ref!(DestroyEvent);
event_test_cases!(ActivateEvent);
impl_to_dbus_message!(ActivateEvent);
impl_from_dbus_message!(ActivateEvent);
impl_event_properties!(ActivateEvent);
impl_from_object_ref!(ActivateEvent);
event_test_cases!(DeactivateEvent);
impl_to_dbus_message!(DeactivateEvent);
impl_from_dbus_message!(DeactivateEvent);
impl_event_properties!(DeactivateEvent);
impl_from_object_ref!(DeactivateEvent);
event_test_cases!(RaiseEvent);
impl_to_dbus_message!(RaiseEvent);
impl_from_dbus_message!(RaiseEvent);
impl_event_properties!(RaiseEvent);
impl_from_object_ref!(RaiseEvent);
event_test_cases!(LowerEvent);
impl_to_dbus_message!(LowerEvent);
impl_from_dbus_message!(LowerEvent);
impl_event_properties!(LowerEvent);
impl_from_object_ref!(LowerEvent);
event_test_cases!(MoveEvent);
impl_to_dbus_message!(MoveEvent);
impl_from_dbus_message!(MoveEvent);
impl_event_properties!(MoveEvent);
impl_from_object_ref!(MoveEvent);
event_test_cases!(ResizeEvent);
impl_to_dbus_message!(ResizeEvent);
impl_from_dbus_message!(ResizeEvent);
impl_event_properties!(ResizeEvent);
impl_from_object_ref!(ResizeEvent);
event_test_cases!(ShadeEvent);
impl_to_dbus_message!(ShadeEvent);
impl_from_dbus_message!(ShadeEvent);
impl_event_properties!(ShadeEvent);
impl_from_object_ref!(ShadeEvent);
event_test_cases!(UUshadeEvent);
impl_to_dbus_message!(UUshadeEvent);
impl_from_dbus_message!(UUshadeEvent);
impl_event_properties!(UUshadeEvent);
impl_from_object_ref!(UUshadeEvent);
event_test_cases!(RestyleEvent);
impl_to_dbus_message!(RestyleEvent);
impl_from_dbus_message!(RestyleEvent);
impl_event_properties!(RestyleEvent);
impl_from_object_ref!(RestyleEvent);
impl_msg_conversion_ext_for_target_type!(PropertyChangeEvent);
impl_msg_conversion_ext_for_target_type!(MinimizeEvent);
impl_msg_conversion_ext_for_target_type!(MaximizeEvent);
impl_msg_conversion_ext_for_target_type!(RestoreEvent);
impl_msg_conversion_ext_for_target_type!(CloseEvent);
impl_msg_conversion_ext_for_target_type!(CreateEvent);
impl_msg_conversion_ext_for_target_type!(ReparentEvent);
impl_msg_conversion_ext_for_target_type!(DesktopCreateEvent);
impl_msg_conversion_ext_for_target_type!(DesktopDestroyEvent);
impl_msg_conversion_ext_for_target_type!(DestroyEvent);
impl_msg_conversion_ext_for_target_type!(ActivateEvent);
impl_msg_conversion_ext_for_target_type!(DeactivateEvent);
impl_msg_conversion_ext_for_target_type!(RaiseEvent);
impl_msg_conversion_ext_for_target_type!(LowerEvent);
impl_msg_conversion_ext_for_target_type!(MoveEvent);
impl_msg_conversion_ext_for_target_type!(ResizeEvent);
impl_msg_conversion_ext_for_target_type!(ShadeEvent);
impl_msg_conversion_ext_for_target_type!(UUshadeEvent);
impl_msg_conversion_ext_for_target_type!(RestyleEvent);
impl_msg_conversion_for_types_built_from_object_ref!(MinimizeEvent);
impl_msg_conversion_for_types_built_from_object_ref!(MaximizeEvent);
impl_msg_conversion_for_types_built_from_object_ref!(RestoreEvent);
impl_msg_conversion_for_types_built_from_object_ref!(CloseEvent);
impl_msg_conversion_for_types_built_from_object_ref!(CreateEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ReparentEvent);
impl_msg_conversion_for_types_built_from_object_ref!(DesktopCreateEvent);
impl_msg_conversion_for_types_built_from_object_ref!(DesktopDestroyEvent);
impl_msg_conversion_for_types_built_from_object_ref!(DestroyEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ActivateEvent);
impl_msg_conversion_for_types_built_from_object_ref!(DeactivateEvent);
impl_msg_conversion_for_types_built_from_object_ref!(RaiseEvent);
impl_msg_conversion_for_types_built_from_object_ref!(LowerEvent);
impl_msg_conversion_for_types_built_from_object_ref!(MoveEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ResizeEvent);
impl_msg_conversion_for_types_built_from_object_ref!(ShadeEvent);
impl_msg_conversion_for_types_built_from_object_ref!(UUshadeEvent);
impl_msg_conversion_for_types_built_from_object_ref!(RestyleEvent);

308
patches/atspi-common/src/interface.rs vendored Normal file
View file

@ -0,0 +1,308 @@
//! Conversion functions and types representing a set of [`Interface`]s.
//!
//! Each `AccessibleProxy` will implement some set of these interfaces,
//! represented by a [`InterfaceSet`].
use enumflags2::{bitflags, BitFlag, BitFlags};
use serde::{
de::{self, Deserializer, Visitor},
ser::{self, Serializer},
Deserialize, Serialize,
};
use std::fmt;
use zbus::wire::{Signature, Type};
/// AT-SPI interfaces an accessible object can implement.
#[bitflags]
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Interface {
/// Interface to indicate implementation of `AccessibleProxy`.
#[serde(rename = "org.a11y.atspi.Accessible")]
Accessible,
/// Interface to indicate implementation of `ActionProxy`.
#[serde(rename = "org.a11y.atspi.Action")]
Action,
/// Interface to indicate implementation of `ApplicationProxy`.
#[serde(rename = "org.a11y.atspi.Application")]
Application,
/// Interface to indicate implementation of `CacheProxy`.
#[serde(rename = "org.a11y.atspi.Cache")]
Cache,
/// Interface to indicate implementation of `CollectionProxy`.
#[serde(rename = "org.a11y.atspi.Collection")]
Collection,
/// Interface to indicate implementation of `ComponentProxy`.
#[serde(rename = "org.a11y.atspi.Component")]
Component,
/// Interface to indicate implementation of `DocumentProxy`.
#[serde(rename = "org.a11y.atspi.Document")]
Document,
/// Interface to indicate implementation of `DeviceEventControllerProxy`.
#[serde(rename = "org.a11y.atspi.DeviceEventController")]
DeviceEventController,
/// Interface to indicate implementation of `DeviceEventListenerProxy`.
#[serde(rename = "org.a11y.atspi.DeviceEventListener")]
DeviceEventListener,
/// Interface to indicate implementation of `EditableTextProxy`.
#[serde(rename = "org.a11y.atspi.EditableText")]
EditableText,
/// Interface to indicate implementation of `HyperlinkProxy`.
#[serde(rename = "org.a11y.atspi.Hyperlink")]
Hyperlink,
/// Interface to indicate implementation of `HypertextProxy`.
#[serde(rename = "org.a11y.atspi.Hypertext")]
Hypertext,
/// Interface to indicate implementation of `ImageProxy`.
#[serde(rename = "org.a11y.atspi.Image")]
Image,
/// Interface to indicate implementation of `RegistryProxy`.
#[serde(rename = "org.a11y.atspi.Registry")]
Registry,
/// Interface to indicate implementation of `SelectionProxy`.
#[serde(rename = "org.a11y.atspi.Selection")]
Selection,
/// Interface to indicate implementation of `SocketProxy`.
#[serde(rename = "org.a11y.atspi.Socket")]
Socket,
/// Interface to indicate implementation of `TableProxy`.
#[serde(rename = "org.a11y.atspi.Table")]
Table,
/// Interface to indicate implementation of `TableCellProxy`.
#[serde(rename = "org.a11y.atspi.TableCell")]
TableCell,
/// Interface to indicate implementation of `TextProxy`.
#[serde(rename = "org.a11y.atspi.Text")]
Text,
/// Interface to indicate implementation of `ValueProxy`.
#[serde(rename = "org.a11y.atspi.Value")]
Value,
}
/// A collection type which encodes the AT-SPI interfaces an accessible object has implemented.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct InterfaceSet(BitFlags<Interface>);
impl InterfaceSet {
pub fn new<B: Into<BitFlags<Interface>>>(value: B) -> Self {
Self(value.into())
}
#[must_use]
pub fn empty() -> InterfaceSet {
InterfaceSet(Interface::empty())
}
#[must_use]
pub fn bits(&self) -> u32 {
self.0.bits()
}
#[must_use]
pub fn all() -> InterfaceSet {
InterfaceSet(Interface::all())
}
pub fn contains<B: Into<BitFlags<Interface>>>(self, other: B) -> bool {
self.0.contains(other)
}
pub fn insert<B: Into<BitFlags<Interface>>>(&mut self, other: B) {
self.0.insert(other);
}
#[must_use]
pub fn iter(&self) -> enumflags2::Iter<Interface> {
self.0.iter()
}
}
impl IntoIterator for InterfaceSet {
type IntoIter = enumflags2::Iter<Interface>;
type Item = Interface;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl IntoIterator for &InterfaceSet {
type IntoIter = enumflags2::Iter<Interface>;
type Item = Interface;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl Default for InterfaceSet {
fn default() -> Self {
Self::empty()
}
}
impl<'de> de::Deserialize<'de> for InterfaceSet {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct InterfaceSetVisitor;
impl<'de> Visitor<'de> for InterfaceSetVisitor {
type Value = InterfaceSet;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a sequence comprised of valid AT-SPI interface names")
}
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
match <Vec<Interface> as Deserialize>::deserialize(deserializer) {
Ok(interfaces) => Ok(InterfaceSet(BitFlags::from_iter(interfaces))),
Err(e) => Err(e),
}
}
}
deserializer.deserialize_newtype_struct("InterfaceSet", InterfaceSetVisitor)
}
}
impl ser::Serialize for InterfaceSet {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer
.serialize_newtype_struct("InterfaceSet", &self.0.iter().collect::<Vec<Interface>>())
}
}
impl Type for InterfaceSet {
const SIGNATURE: &'static Signature = <Vec<String> as Type>::SIGNATURE;
}
impl FromIterator<Interface> for InterfaceSet {
fn from_iter<T: IntoIterator<Item = Interface>>(iter: T) -> Self {
Self(BitFlags::from_iter(iter))
}
}
impl<'a> FromIterator<&'a Interface> for InterfaceSet {
fn from_iter<I: IntoIterator<Item = &'a Interface>>(iter: I) -> Self {
InterfaceSet(iter.into_iter().copied().collect())
}
}
impl From<Interface> for InterfaceSet {
fn from(value: Interface) -> Self {
Self(value.into())
}
}
impl std::ops::BitAnd for InterfaceSet {
type Output = InterfaceSet;
fn bitand(self, other: Self) -> Self::Output {
InterfaceSet(self.0 & other.0)
}
}
impl std::ops::BitXor for InterfaceSet {
type Output = InterfaceSet;
fn bitxor(self, other: Self) -> Self::Output {
InterfaceSet(self.0 ^ other.0)
}
}
impl std::ops::BitOr for InterfaceSet {
type Output = InterfaceSet;
fn bitor(self, other: Self) -> Self::Output {
InterfaceSet(self.0 | other.0)
}
}
#[cfg(test)]
mod tests {
use super::{Interface, InterfaceSet};
use zbus::wire::serialized::Data;
use zbus::wire::{serialized::Context, to_bytes, LE};
#[test]
fn serialize_empty_interface_set() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &InterfaceSet::empty()).unwrap();
assert_eq!(encoded.bytes(), &[0, 0, 0, 0]);
}
#[test]
fn deserialize_empty_interface_set() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &InterfaceSet::empty()).unwrap();
let (decoded, _) = encoded.deserialize::<InterfaceSet>().unwrap();
assert_eq!(decoded, InterfaceSet::empty());
}
#[test]
fn serialize_interface_set_accessible() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &InterfaceSet::new(Interface::Accessible)).unwrap();
assert_eq!(
encoded.bytes(),
&[
30, 0, 0, 0, 25, 0, 0, 0, 111, 114, 103, 46, 97, 49, 49, 121, 46, 97, 116, 115,
112, 105, 46, 65, 99, 99, 101, 115, 115, 105, 98, 108, 101, 0
]
);
}
#[test]
fn deserialize_interface_set_accessible() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(
&[
30, 0, 0, 0, 25, 0, 0, 0, 111, 114, 103, 46, 97, 49, 49, 121, 46, 97, 116, 115,
112, 105, 46, 65, 99, 99, 101, 115, 115, 105, 98, 108, 101, 0,
],
ctxt,
);
let (ifaceset, _) = data.deserialize::<InterfaceSet>().unwrap();
assert_eq!(ifaceset, InterfaceSet::new(Interface::Accessible));
}
#[test]
fn can_handle_multiple_interfaces() {
let ctxt = Context::new(LE, 0);
let object =
InterfaceSet::new(Interface::Accessible | Interface::Action | Interface::Component);
let encoded = to_bytes(ctxt, &object).unwrap();
let (decoded, _) = encoded.deserialize::<InterfaceSet>().unwrap();
assert!(object == decoded);
}
// The order of appearance of the interfaces is equal to the order in the enum.
#[test]
fn iterator_on_interface_set() {
let set =
InterfaceSet::new(Interface::Accessible | Interface::Action | Interface::Component);
let mut iter = set.into_iter();
assert_eq!(iter.next(), Some(Interface::Accessible));
assert_eq!(iter.next(), Some(Interface::Action));
assert_eq!(iter.next(), Some(Interface::Component));
assert_eq!(iter.next(), None);
}
#[test]
fn iterator_on_interface_set_ref() {
let set = InterfaceSet::new(Interface::Text | Interface::Collection | Interface::Component);
let mut iter = (&set).into_iter();
assert_eq!(iter.next(), Some(Interface::Collection));
assert_eq!(iter.next(), Some(Interface::Component));
assert_eq!(iter.next(), Some(Interface::Text));
}
}

278
patches/atspi-common/src/lib.rs vendored Normal file
View file

@ -0,0 +1,278 @@
#![deny(clippy::all, clippy::pedantic, clippy::cargo, unsafe_code, rustdoc::all)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::multiple_crate_versions)]
//! # atspi-common
//!
//! Defines all common types, events, and data structures for `atspi-proxies` and `atspi-connection`.
//! Since `atspi-proxies` and `atspi-connection` are downstream crates, the documentation can not link to it directly.
//! Any type ending in `*Proxy` is in `atspi-proxies`.
//!
#[macro_use]
extern crate static_assertions;
#[macro_use]
pub(crate) mod macros;
pub mod action;
#[cfg(feature = "wrappers")]
pub use crate::events::event_wrappers::{
CacheEvents, DocumentEvents, Event, EventListenerEvents, FocusEvents, KeyboardEvents,
MouseEvents, ObjectEvents, TerminalEvents, WindowEvents,
};
pub use action::Action;
pub mod object_match;
pub use object_match::{MatchType, ObjectMatchRule, SortOrder, TreeTraversalType};
pub mod object_ref;
pub use object_ref::{ObjectRef, ObjectRefOwned};
pub mod operation;
pub use operation::Operation;
pub mod interface;
pub use interface::{Interface, InterfaceSet};
pub mod state;
pub use state::{State, StateSet};
pub mod cache;
pub use cache::{CacheItem, LegacyCacheItem};
pub mod error;
pub use error::AtspiError;
pub mod events;
pub use events::{EventProperties, EventTypeProperties};
mod role;
pub use role::Role;
mod relation_type;
pub use relation_type::RelationType;
use serde::{Deserialize, Serialize};
use zbus::wire::Type;
pub type Result<T> = std::result::Result<T, AtspiError>;
/// Describes a selection of text, including selections across object boundaries.
///
/// For example, selecting from the beginning of a paragraph to half way through a link would cause
/// the start and end object references to be different.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct TextSelection {
/// starting object reference
start_obj: ObjectRefOwned,
/// text offset within `start_obj`
start_idx: i32,
/// ending object reference
end_obj: ObjectRefOwned,
/// text offset within `end_obj`
end_idx: i32,
/// is the `start_obj` active;
///
/// This is the same as querying for the [`StateSet`], then checking if [`State::Active`] is contained.
/// See `atspi_proxies::accessible::AccessibleProxy` for more information on checking state.
start_is_active: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[repr(u32)]
/// The coordinate type encodes the frame of reference.
pub enum CoordType {
/// In relation to the entire screen.
Screen,
/// In relation to only the window.
Window,
/// In relation to the parent of the element being checked.
Parent,
}
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Serialize, Deserialize, Type)]
#[repr(u32)]
/// Enumeration used by `TextProxy` to indicate how to treat characters intersecting bounding boxes.
pub enum ClipType {
/// No characters/glyphs are omitted.
Neither,
/// Characters/glyphs clipped by the minimum coordinate are omitted.
Min,
/// Characters/glyphs which intersect the maximum coordinate are omitted.
Max,
/// Only glyphs falling entirely within the region bounded by min and max are retained.
Both,
}
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Serialize, Deserialize, Type)]
#[repr(u32)]
/// Level of granularity to get text of, in relation to a cursor position.
pub enum Granularity {
/// Gives the character at the index of the cursor. With a line-style cursor (which is standard) this will get the character that appears after the cursor.
Char,
/// Gives the entire word in front of, or which contains, the cursor. TODO: confirm that it always chooses the word in front of the cursor.
Word,
/// Gives entire sentence in front of, or which contains, the cursor. TODO: confirm that it always chooses the sentence after the cursor.
Sentence,
/// Gives the line, as seen visually of which the cursor is situated within.
Line,
/// Gives the entire block of text, regardless of where the cursor lies within it.
Paragraph,
}
/// Indicates relative stacking order of a `atspi_proxies::component::ComponentProxy` with respect to the
/// onscreen visual representation of the UI.
///
/// The layer index, in combination with the component's extents,
/// can be used to compute the visibility of all or part of a component.
/// This is important in programmatic determination of region-of-interest for magnification,
/// and in flat screen review models of the screen, as well as for other uses.
/// Objects residing in two of the `Layer` categories support further z-ordering information,
/// with respect to their peers in the same layer:
/// namely, [`Layer::Window`] and [`Layer::Mdi`].
/// Relative stacking order for other objects within the same layer is not available;
/// the recommended heuristic is first child paints first. In other words,
/// assume that the first siblings in the child list are subject to being
/// overpainted by later siblings if their bounds intersect.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub enum Layer {
/// Indicates an error condition or uninitialized value.
Invalid,
/// Reserved for the desktop background; this is the bottom-most layer,
/// over which everything else is painted.
Background,
/// The 'background' layer for most content renderers and
/// UI `atspi_proxies::component::ComponentProxy` containers.
Canvas,
/// The layer in which the majority of ordinary 'foreground' widgets reside.
Widget,
/// A special layer between [`Layer::Canvas`] and [`Layer::Widget`], in which the
/// 'pseudo windows' (e.g. the Multiple-Document Interface frames) reside.
///
/// See `atspi_proxies::component::ComponentProxy::get_mdizorder`.
Mdi,
/// A layer for popup window content, above [`Layer::Widget`].
Popup,
/// The topmost layer.
Overlay,
/// The layer in which a toplevel window background usually resides.
Window,
}
/// Enumeration used by interface the [`crate::interface::Interface::Accessible`] to specify where an object should be placed on the screen when using `scroll_to`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub enum ScrollType {
/// Scroll the object to the top left corner of the window.
TopLeft,
/// Scroll the object to the bottom right corner of the window.
BottomRight,
/// Scroll the object to the top edge of the window.
TopEdge,
/// Scroll the object to the bottom edge of the window.
BottomEdge,
/// Scroll the object to the left edge of the window.
LeftEdge,
/// Scroll the object to the right edge of the window.
RightEdge,
/// Scroll the object to application-dependent position on the window.
Anywhere,
}
/// Enumeration used to indicate a type of live region and how assertive it
/// should be in terms of speaking notifications.
///
/// Currently, this is only used
/// for `Announcement` events, but it may be used for additional purposes
/// in the future.
/// The argument in the `Announcement` event is named `politeness`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[repr(i32)]
pub enum Politeness {
/// No live region.
#[default]
None = 0,
/// This live region should be considered polite.
Polite = 1,
/// This live region should be considered assertive.
Assertive = 2,
}
impl TryFrom<i32> for Politeness {
type Error = AtspiError;
fn try_from(value: i32) -> std::result::Result<Self, Self::Error> {
match value {
0 => Ok(Politeness::None),
1 => Ok(Politeness::Polite),
2 => Ok(Politeness::Assertive),
_ => Err(AtspiError::Conversion("Unknown Politeness variant")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
use zbus_lockstep::{
method_args_signature, method_return_signature, signal_body_type_signature,
};
use zbus::wire::Signature;
#[test]
fn convert_i32_to_live() {
assert_eq!(Politeness::None, Politeness::try_from(0).unwrap());
assert_eq!(Politeness::Polite, Politeness::try_from(1).unwrap());
assert_eq!(Politeness::Assertive, Politeness::try_from(2).unwrap());
assert!(Politeness::try_from(3).is_err());
assert!(Politeness::try_from(-1).is_err());
}
#[test]
fn validate_live_signature() {
let signature = signal_body_type_signature!("Announcement");
let politeness_signature_str = &signature.to_string_no_parens();
let politeness_signature = Signature::from_str(&politeness_signature_str.as_str()[1..2])
.expect("Valid signature pattern");
assert_eq!(*<Politeness as Type>::SIGNATURE, politeness_signature);
}
#[test]
fn validate_scroll_type_signature() {
let signature = method_args_signature!(member: "ScrollTo", interface: "org.a11y.atspi.Component", argument: "type");
assert_eq!(*<ScrollType as Type>::SIGNATURE, signature);
}
#[test]
fn validate_layer_signature() {
let signature = method_return_signature!("GetLayer");
assert_eq!(*<Layer as Type>::SIGNATURE, signature);
}
#[test]
fn validate_granularity_signature() {
let signature = method_args_signature!(member: "GetStringAtOffset", interface: "org.a11y.atspi.Text", argument: "granularity");
assert_eq!(*<Granularity as Type>::SIGNATURE, signature);
}
#[test]
fn validate_clip_type_signature() {
let signature = method_args_signature!(member: "GetTextAtOffset", interface: "org.a11y.atspi.Text", argument: "type");
assert_eq!(*<ClipType as Type>::SIGNATURE, signature);
}
#[test]
fn validate_coord_type_signature() {
let signature = method_args_signature!(member: "GetImagePosition", interface: "org.a11y.atspi.Image", argument: "coordType");
assert_eq!(*<CoordType as Type>::SIGNATURE, signature);
}
#[test]
fn validate_match_type_signature() {
let rule_signature = method_args_signature!(member: "GetMatchesTo", interface: "org.a11y.atspi.Collection", argument: "rule");
let match_type_signature_str = rule_signature.to_string();
let match_type_signature = Signature::from_str(&match_type_signature_str.as_str()[3..4])
.expect("Valid signature pattern");
assert_eq!(*<MatchType as Type>::SIGNATURE, match_type_signature);
}
#[test]
fn validate_text_selection_signature() {
let selection_signature = method_args_signature!(member: "GetTextSelections", interface: "org.a11y.atspi.Document", argument: "selections");
let selection_signature_str = selection_signature.to_string();
let selection_signature = Signature::from_str(&selection_signature_str.as_str()[1..])
.expect("Valid signature pattern");
// this signature is written: `a(...)`, where `(...)` is the signature we want to compare against
assert_eq!(*<TextSelection as Type>::SIGNATURE, selection_signature);
}
}

1174
patches/atspi-common/src/macros.rs vendored Normal file

File diff suppressed because it is too large Load diff

304
patches/atspi-common/src/object_match.rs vendored Normal file
View file

@ -0,0 +1,304 @@
use std::{borrow::Borrow, collections::HashMap, marker::PhantomData};
use serde::{Deserialize, Serialize};
use zbus::wire::{Signature, Type};
use crate::{Interface, InterfaceSet, Role, State, StateSet};
/// Defines how an object-tree is to be traversed.
/// Used in `CollectionProxy`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[repr(u32)]
pub enum TreeTraversalType {
/// When traversing the tree, restrict to children of the current object.
RestrictChildren,
/// When traversing the tree, restrict to siblings of the current object.
RestrictSibling,
/// Traverse the tree in order of appearance.
#[default]
Inorder,
}
/// Definition of match rules for accessible objects.
/// Rule(s) against which we can match an object or a collection thereof.
///
/// # Examples
/// ```rust
/// # use zbus::MatchRule;
/// let builder = MatchRule::builder();
/// ```
///
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ObjectMatchRule {
pub states: StateSet,
pub states_mt: MatchType,
pub attr: HashMap<String, String>,
pub attr_mt: MatchType,
pub roles: Vec<Role>,
pub roles_mt: MatchType,
pub ifaces: InterfaceSet,
pub ifaces_mt: MatchType,
pub invert: bool,
// Private phantom, gets compiled away.
// Here to ensure the builder is the only route to obtain a `MatchRule`
#[serde(skip)]
_marker: std::marker::PhantomData<()>,
}
/// !!! WARNING !!! :
///
/// State and Role are defined as u32 in Accessible.xml but as i32 in Collection.xml
///
/// The signature on `StateSet` is defined inconsistently in the XMLs:
///
/// - `Accessible.xml`: `GetState type="au"`
/// - `Collection.xml`: `GetMatches` argument `name="rule" type="(aiia{ss}iaiiasib)"`
///
/// The latter starts with ai, which is a signature for an array of signed ints i32.
///
/// <https://gitlab.gnome.org/federico/at-spi2-core/-/commit/4885efedeef71e0df8210622771a0b1bb10e194d>
impl Type for ObjectMatchRule {
const SIGNATURE: &'static Signature = &Signature::static_structure(&[
<Vec<i32>>::SIGNATURE,
&Signature::I32,
<HashMap<&str, &str>>::SIGNATURE,
&Signature::I32,
<Vec<i32>>::SIGNATURE,
&Signature::I32,
<Vec<&str>>::SIGNATURE,
&Signature::I32,
&Signature::Bool,
]);
}
impl ObjectMatchRule {
/// Create a new `MatchRuleBuilder`
#[must_use]
pub fn builder() -> ObjectMatchRuleBuilder {
ObjectMatchRuleBuilder::default()
}
}
/// The 'builder' type for `MatchRule`.
/// Use its methods to set match criteria.
#[derive(Debug, Clone, Default)]
pub struct ObjectMatchRuleBuilder {
states: StateSet,
states_mt: MatchType,
attr: HashMap<String, String>,
attr_mt: MatchType,
roles: Vec<Role>,
roles_mt: MatchType,
ifaces: InterfaceSet,
ifaces_mt: MatchType,
invert: bool,
}
impl ObjectMatchRuleBuilder {
/// Insert a `StateSet` to the builder
#[must_use]
pub fn states<I>(mut self, states: I, mt: MatchType) -> Self
where
I: IntoIterator,
I::Item: Borrow<State>,
{
self.states = states.into_iter().map(|state| *state.borrow()).collect();
self.states_mt = mt;
self
}
/// Insert a map of attributes
#[must_use]
pub fn attributes(mut self, attributes: HashMap<String, String>, mt: MatchType) -> Self {
self.attr = attributes;
self.attr_mt = mt;
self
}
/// Insert a slice of `Role`s
#[must_use]
pub fn roles(mut self, roles: &[Role], mt: MatchType) -> Self {
self.roles = roles.into();
self.roles_mt = mt;
self
}
/// Insert an `InterfaceSet` from a collection of `Interface`s
#[must_use]
pub fn interfaces<I>(mut self, interfaces: I, mt: MatchType) -> Self
where
I: IntoIterator,
I::Item: Borrow<Interface>,
{
self.ifaces = interfaces.into_iter().map(|iface| *iface.borrow()).collect();
self.ifaces_mt = mt;
self
}
/// Sets the inversion of the `MatchRule`, defaults to `false`, no inversion.
#[must_use]
pub fn invert(mut self, invert: bool) -> Self {
self.invert = invert;
self
}
/// Builds the [`ObjectMatchRule`]
///
/// [`ObjectMatchRule``]: crate::object_match::ObjectMatchRule
#[must_use]
pub fn build(self) -> ObjectMatchRule {
ObjectMatchRule {
states: self.states,
states_mt: self.states_mt,
attr: self.attr,
attr_mt: self.attr_mt,
roles: self.roles,
roles_mt: self.roles_mt,
ifaces: self.ifaces,
ifaces_mt: self.ifaces_mt,
invert: self.invert,
_marker: PhantomData,
}
}
}
/// Enumeration used by [`ObjectMatchRule`] to specify how to interpret [`ObjectRef`] objects.
///
/// [`ObjectRef`]: crate::object_ref::ObjectRef
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type, Default)]
#[repr(i32)]
pub enum MatchType {
#[default]
/// Invalidates match criterion. Meanting: the search of this property will not be performed.
Invalid,
/// All of the criteria must be met.
All,
/// Any of the criteria must criteria must be met.
Any,
/// None of the criteria must be met.
NA,
/// Same as [`Self::All`] if the criterion item is non-empty - All of the criteria must be met.
/// For empty criteria this rule requires the returned value to also have empty set.
Empty,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[repr(u32)]
/// Enumeration used by interface `CollectionProxy` to specify the way [`ObjectRef`]
/// objects should be sorted.
///
/// # Note
///
/// Only `Canonical` and `ReverseCanonical` are currently implemented in the known implementation of `Collection`.
///
/// see: [issue 140. "Are all the AtspiCollectionSortOrder types really a thing?"](https://gitlab.gnome.org/GNOME/at-spi2-core/-/issues/140)
///
/// [`ObjectRef`]: crate::object_ref::ObjectRef
pub enum SortOrder {
/// Invalid sort order
///
/// Unimplemented
Invalid,
/// Canonical sort order
Canonical,
/// Flow sort order
///
/// Unimplemented
Flow,
/// Tab sort order
///
/// Unimplemented
Tab,
/// Reverse canonical sort order
ReverseCanonical,
/// Reverse flow sort order
///
/// Unimplemented
ReverseFlow,
/// Reverse tab sort order
///
/// Unimplemented
ReverseTab,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{SortOrder, State};
use std::str::FromStr;
use zbus_lockstep::method_args_signature;
#[test]
fn validate_match_rule_signature() {
let signature = method_args_signature!(member: "GetMatchesTo", interface: "org.a11y.atspi.Collection", argument: "rule");
assert_eq!(*<ObjectMatchRule as Type>::SIGNATURE, signature);
}
#[test]
fn validate_match_type_signature() {
let rule_signature = method_args_signature!(member: "GetMatchesTo", interface: "org.a11y.atspi.Collection", argument: "rule");
// The match type signature is the fourth element in the signature
let match_type_signature_str = rule_signature.to_string();
let match_type_signature = Signature::from_str(&match_type_signature_str.as_str()[3..4])
.expect("Valid signature pattern");
assert_eq!(*<MatchType as Type>::SIGNATURE, match_type_signature);
}
#[test]
fn validate_tree_traversal_type_signature() {
let signature = method_args_signature!(member: "GetMatchesTo", interface: "org.a11y.atspi.Collection", argument: "tree");
assert_eq!(*<TreeTraversalType as Type>::SIGNATURE, signature);
}
#[test]
fn validate_sort_order_signature() {
let signature = method_args_signature!(member: "GetMatches", interface: "org.a11y.atspi.Collection", argument: "sortby");
assert_eq!(*<SortOrder as Type>::SIGNATURE, signature);
}
#[test]
fn create_empty_object_match_rule() {
let rule = ObjectMatchRule::builder().build();
assert_eq!(rule.states, StateSet::default());
assert_eq!(rule.attr, HashMap::new());
assert_eq!(rule.roles, Vec::new());
assert_eq!(rule.ifaces, InterfaceSet::default());
assert!(!rule.invert);
}
#[test]
fn create_object_match_rule() {
let rule = ObjectMatchRule::builder()
.states(StateSet::new(State::Active), MatchType::All)
.attributes(
[("name".to_string(), "value".to_string())].iter().cloned().collect(),
MatchType::Any,
)
.roles(&[Role::Alert], MatchType::All)
.interfaces([Interface::Action], MatchType::Any)
.invert(true)
.build();
assert_eq!(rule.states, StateSet::new(State::Active));
assert_eq!(
rule.attr,
[("name".to_string(), "value".to_string())].iter().cloned().collect()
);
assert_eq!(rule.roles, vec![Role::Alert]);
assert_eq!(rule.ifaces, InterfaceSet::new(Interface::Action));
assert!(rule.invert);
}
}

871
patches/atspi-common/src/object_ref.rs vendored Normal file
View file

@ -0,0 +1,871 @@
use crate::AtspiError;
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use zbus_lockstep_macros::validate;
use zbus::names::{BusName, UniqueName};
use zbus::wire::{ObjectPath, Structure, Type};
const NULL_PATH_STR: &str = "/org/a11y/atspi/null";
const NULL_OBJECT_PATH: &ObjectPath<'static> =
&ObjectPath::from_static_str_unchecked(NULL_PATH_STR);
#[cfg(test)]
pub(crate) const TEST_OBJECT_BUS_NAME: &str = ":0.0";
#[cfg(test)]
pub(crate) const TEST_OBJECT_PATH_STR: &str = "/org/a11y/atspi/test/default";
#[cfg(test)]
pub(crate) const TEST_DEFAULT_OBJECT_REF: ObjectRef<'static> =
ObjectRef::from_static_str_unchecked(TEST_OBJECT_BUS_NAME, TEST_OBJECT_PATH_STR);
/// A unique identifier for an object in the accessibility tree.
///
/// A ubiquitous type used to refer to an object in the accessibility tree.
///
/// In AT-SPI2, objects in the applications' UI object tree are uniquely identified
/// using an application's bus name and object path. "(so)"
///
/// Emitted by `RemoveAccessible` and `Available`
#[validate(signal: "Available")]
#[derive(Clone, Debug, Eq, Type)]
#[zvariant(signature = "(so)")]
pub enum ObjectRef<'o> {
Null,
Owned { name: UniqueName<'static>, path: ObjectPath<'static> },
Borrowed { name: UniqueName<'o>, path: ObjectPath<'o> },
}
impl<'o> ObjectRef<'o> {
/// Create a new `ObjectRef::Borrowed` from a `UniqueName` and `ObjectPath`.
#[must_use]
pub fn new(name: UniqueName<'o>, path: ObjectPath<'o>) -> Self {
Self::new_borrowed(name, path)
}
/// Create a new, owned `ObjectRef`.
///
/// # Example
/// ```rust
/// use zbus::names::UniqueName;
/// use zbus::wire::ObjectPath;
/// use atspi_common::ObjectRef;
///
/// let name = UniqueName::from_static_str_unchecked(":1.23");
/// let path = ObjectPath::from_static_str_unchecked("/org/a11y/example/path/007");
///
/// let object_ref = ObjectRef::new_owned(name, path);
/// # assert_eq!(object_ref.name_as_str(), Some(":1.23"));
/// # assert_eq!(object_ref.path_as_str(), "/org/a11y/example/path/007");
/// ```
pub fn new_owned<N, P>(name: N, path: P) -> ObjectRefOwned
where
N: Into<UniqueName<'static>>,
P: Into<ObjectPath<'static>>,
{
let name: UniqueName<'static> = name.into();
let path: ObjectPath<'static> = path.into();
ObjectRefOwned(ObjectRef::Owned { name, path })
}
/// Create a new, borrowed `ObjectRef`.
///
/// # Example
/// ```rust
/// use zbus::names::UniqueName;
/// use zbus::wire::ObjectPath;
/// use atspi_common::ObjectRef;
///
/// let name = UniqueName::from_static_str_unchecked(":1.23");
/// let path = ObjectPath::from_static_str_unchecked("/org/a11y/example/path/007");
///
/// let object_ref = ObjectRef::new_borrowed(name, path);
/// # assert_eq!(object_ref.name_as_str(), Some(":1.23"));
/// # assert_eq!(object_ref.path_as_str(), "/org/a11y/example/path/007");
/// ```
pub fn new_borrowed<N, P>(name: N, path: P) -> ObjectRef<'o>
where
N: Into<UniqueName<'o>>,
P: Into<ObjectPath<'o>>,
{
let name: UniqueName<'o> = name.into();
let path: ObjectPath<'o> = path.into();
ObjectRef::Borrowed { name, path }
}
/// Create a new `ObjectRef`, from `BusName` and `ObjectPath`.
///
/// # Errors
/// Will fail if the `sender` is not a `UniqueName`.
pub fn try_from_bus_name_and_path(
sender: BusName<'o>,
path: ObjectPath<'o>,
) -> Result<Self, AtspiError> {
// Check whether `BusName` matches `UniqueName`
if let BusName::Unique(unique_sender) = sender {
Ok(ObjectRef::new(unique_sender, path))
} else {
Err(AtspiError::ParseError("Expected UniqueName"))
}
}
/// Create a new `ObjectRef`, unchecked.
///
/// # Safety
/// The caller must ensure that the strings are valid.
#[must_use]
pub const fn from_static_str_unchecked(name: &'static str, path: &'static str) -> Self {
let name = UniqueName::from_static_str_unchecked(name);
let path = ObjectPath::from_static_str_unchecked(path);
ObjectRef::Owned { name, path }
}
/// Returns `true` if the object reference is `Null`, otherwise returns `false`.
///
/// Toolkits may use the `Null` object reference to indicate that an object is not available or does not exist.
/// For example, when calling `Accessible::get_parent` on an object that has no parent,
/// it may return a `Null` object reference.
#[must_use]
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
/// Returns the name of the object reference.
/// If the object reference is `Null`, it returns `None`.
/// If the object reference is `Owned` or `Borrowed`, it returns the name.
///
/// # Example
/// ```rust
/// use zbus::names::UniqueName;
/// use zbus::wire::ObjectPath;
/// use atspi_common::ObjectRef;
///
/// let name = UniqueName::from_static_str_unchecked(":1.23");
/// let path = ObjectPath::from_static_str_unchecked("/org/a11y/example/path/007");
/// let object_ref = ObjectRef::new_borrowed(name, path);
///
/// // Check the name of the object reference
/// assert!(object_ref.name().is_some());
/// assert_eq!(object_ref.name().unwrap().as_str(), ":1.23");
/// ```
#[must_use]
pub fn name(&self) -> Option<&UniqueName<'o>> {
match self {
Self::Owned { name: own_name, .. } => Some(own_name),
Self::Borrowed { name: borrow_name, .. } => Some(borrow_name),
Self::Null => None,
}
}
/// Returns the path of the object reference.\
///
/// # Example
/// ```rust
/// use zbus::names::UniqueName;
/// use zbus::wire::ObjectPath;
/// use atspi_common::ObjectRef;
///
/// let name = UniqueName::from_static_str_unchecked(":1.23");
/// let path = ObjectPath::from_static_str_unchecked("/org/a11y/example/path/007");
/// let object_ref = ObjectRef::new_borrowed(name, path);
///
/// // Check the path of the object reference
/// assert_eq!(object_ref.path().as_str(), "/org/a11y/example/path/007");
/// ```
#[must_use]
pub fn path(&self) -> &ObjectPath<'o> {
match self {
Self::Owned { path: own_path, .. } => own_path,
Self::Borrowed { path: borrow_path, .. } => borrow_path,
Self::Null => NULL_OBJECT_PATH,
}
}
/// Converts the `ObjectRef` into an owned instance, consuming `self`.\
/// If the object reference is `Null`, it returns `ObjectRef::Null`.\
/// If the object reference is `Owned`, it returns the same `ObjectRef::Owned`.\
/// If the object reference is `Borrowed`, it converts the name and path to owned versions and returns `ObjectRef::Owned`.
///
/// # Extending lifetime 'magic' (from 'o -> 'static')
///
/// `ObjectRef<'_>` leans on the implementation of `UniqueName` and `ObjectPath` to
/// convert the inner types to `'static`.
/// These types have an `Inner` enum that can contain an `Owned`, `Borrowed`, or `Static` `Str` type.
/// The `Str`type is either a `&'static str` (static), `&str` (borrowed), or an `Arc<str>` (owned).
///
/// # Example
/// ```rust
/// use zbus::names::UniqueName;
/// use zbus::wire::ObjectPath;
/// use atspi_common::ObjectRef;
///
/// let name = UniqueName::from_static_str_unchecked(":1.23");
/// let path = ObjectPath::from_static_str_unchecked("/org/a11y/example/path/007");
/// let object_ref = ObjectRef::new_borrowed(name, path);
///
/// // Check whether the object reference can be converted to an owned version
/// assert!(!object_ref.is_null());
/// let object_ref = object_ref.into_owned();
/// assert!(matches!(object_ref, ObjectRef::Owned { .. }));
/// ```
#[must_use]
pub fn into_owned(self) -> ObjectRef<'static> {
match self {
Self::Null => ObjectRef::Null,
Self::Owned { name, path } => ObjectRef::Owned { name, path },
Self::Borrowed { name, path } => {
ObjectRef::Owned { name: name.to_owned(), path: path.to_owned() }
}
}
}
/// Returns the name of the object reference as a string slice.
#[must_use]
pub fn name_as_str(&self) -> Option<&str> {
match self {
ObjectRef::Null => None,
ObjectRef::Owned { name, .. } | ObjectRef::Borrowed { name, .. } => Some(name.as_str()),
}
}
/// Returns the path of the object reference as a string slice.
#[must_use]
pub fn path_as_str(&self) -> &str {
match self {
ObjectRef::Null => NULL_PATH_STR,
ObjectRef::Owned { path, .. } | ObjectRef::Borrowed { path, .. } => path.as_str(),
}
}
}
// Event tests lean on the `Default` implementation of `ObjectRef`.
// This is a workaround for the fact that `ObjectRef::Null` in
// `#[cfg(test)]` context is inconvenient.
// Events are guaranteed to have a non-null `ObjectRef` on their `item` field, because we receive signals over
// regular (non-p2p) DBus. Which means the `Message` `Header` has valid `Sender` and `Path` fields which
// are used to construct the `ObjectRef` from a `Message`.
#[cfg(test)]
impl Default for ObjectRef<'_> {
/// Returns a non-Null object reference. (test implementation)
fn default() -> Self {
TEST_DEFAULT_OBJECT_REF
}
}
#[cfg(not(test))]
impl Default for ObjectRef<'_> {
/// Returns a `Null` object reference.
fn default() -> Self {
ObjectRef::Null
}
}
/// A wrapper around the static variant of `ObjectRef`.
/// This is guaranteed to have a `'static` lifetime.
#[validate(signal: "Available")]
#[derive(Clone, Debug, Default, Eq, Type)]
pub struct ObjectRefOwned(pub(crate) ObjectRef<'static>);
impl From<ObjectRef<'_>> for ObjectRefOwned {
/// Convert an `ObjectRef<'_>` into an `ObjectRefOwned`.
///
/// # Extending lifetime 'magic' (from 'o -> 'static')
///
/// `ObjectRef<'_>` leans on the implementation of `UniqueName` and `ObjectPath` to
/// convert the inner types to `'static`.
/// These types have an `Inner` enum that can contain an `Owned`, `Borrowed`, or `Static` `Str` type.
/// The `Str`type is either a `&'static str` (static), `&str` (borrowed), or an `Arc<str>` (owned).
fn from(object_ref: ObjectRef<'_>) -> Self {
ObjectRefOwned(object_ref.into_owned())
}
}
impl ObjectRefOwned {
/// Create a new `ObjectRefOwned` from an `ObjectRef<'static>`.
#[must_use]
pub const fn new(object_ref: ObjectRef<'static>) -> Self {
Self(object_ref)
}
/// Create a new `ObjectRefOwned` from `&'static str` unchecked.
///
/// # Safety
/// The caller must ensure that the strings are valid.
#[must_use]
pub const fn from_static_str_unchecked(name: &'static str, path: &'static str) -> Self {
let name = UniqueName::from_static_str_unchecked(name);
let path = ObjectPath::from_static_str_unchecked(path);
ObjectRefOwned(ObjectRef::Owned { name, path })
}
/// Returns `true` if the object reference is `Null`, otherwise returns `false`.
#[must_use]
pub fn is_null(&self) -> bool {
matches!(self.0, ObjectRef::Null)
}
/// Returns the inner `ObjectRef`, consuming `self`.
#[must_use]
pub fn into_inner(self) -> ObjectRef<'static> {
self.0
}
/// Returns the name of the object reference.
/// If the object reference is `Null`, it returns `None`.
/// If the object reference is `Owned` or `Borrowed`, it returns the name.
///
/// # Example
/// ```rust
/// use zbus::names::UniqueName;
/// use zbus::wire::ObjectPath;
/// use atspi_common::ObjectRef;
///
/// let name = UniqueName::from_static_str_unchecked(":1.23");
/// let path = ObjectPath::from_static_str_unchecked("/org/a11y/example/path/007");
/// let object_ref = ObjectRef::new_borrowed(name, path);
///
/// // Check the name of the object reference
/// assert!(object_ref.name().is_some());
/// assert_eq!(object_ref.name_as_str().unwrap(), ":1.23");
/// ```
#[must_use]
pub fn name(&self) -> Option<&UniqueName<'static>> {
match &self.0 {
ObjectRef::Owned { name, .. } | ObjectRef::Borrowed { name, .. } => Some(name),
ObjectRef::Null => None,
}
}
/// Returns the path of the object reference.\
/// If the object reference is `Null`, it returns the null-path.
///
/// # Example
/// ```rust
/// use zbus::names::UniqueName;
/// use zbus::wire::ObjectPath;
/// use atspi_common::ObjectRef;
///
/// let name = UniqueName::from_static_str_unchecked(":1.23");
/// let path = ObjectPath::from_static_str_unchecked("/org/a11y/example/path/007");
/// let object_ref = ObjectRef::new_borrowed(name, path);
///
/// assert_eq!(object_ref.path_as_str(), "/org/a11y/example/path/007");
/// ```
#[must_use]
pub fn path(&self) -> &ObjectPath<'static> {
match &self.0 {
ObjectRef::Owned { path, .. } | ObjectRef::Borrowed { path, .. } => path,
ObjectRef::Null => NULL_OBJECT_PATH,
}
}
/// Returns the name of the object reference as a string slice.
#[must_use]
pub fn name_as_str(&self) -> Option<&str> {
match &self.0 {
ObjectRef::Null => None,
ObjectRef::Owned { name, .. } | ObjectRef::Borrowed { name, .. } => Some(name.as_str()),
}
}
/// Returns the path of the object reference as a string slice.
#[must_use]
pub fn path_as_str(&self) -> &str {
match &self.0 {
ObjectRef::Null => NULL_PATH_STR,
ObjectRef::Owned { path, .. } | ObjectRef::Borrowed { path, .. } => path.as_str(),
}
}
}
impl Serialize for ObjectRef<'_> {
/// `ObjectRef`'s wire format is `(&str, ObjectPath)`.
/// The `Null` variant, the "Null object", is serialized as `("", ObjectPath("/org/a11y/atspi/null"))`.
/// Both `Owned` and `Borrowed` variants are serialized as `(&str, ObjectPath)` with the object's\
/// unique name and path.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match &self {
ObjectRef::Null => ("", NULL_OBJECT_PATH).serialize(serializer),
ObjectRef::Owned { name, path } | ObjectRef::Borrowed { name, path } => {
(name.as_str(), path).serialize(serializer)
}
}
}
}
impl Serialize for ObjectRefOwned {
/// `ObjectRefOwned` is serialized as the inner `ObjectRef`.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de: 'o, 'o> Deserialize<'de> for ObjectRef<'o> {
/// `ObjectRef`'s wire format is `(&str, ObjectPath)`.
/// An empty `&str` with a "/org/a11y/atspi/null" path is considered a `Null` object,
/// this is deserialized as `ObjectRef::Null`.\
/// Any other valid `(&str, ObjectPath)` will deserialize into `ObjectRef::Borrowed`.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ObjectRefVisitor;
impl<'de> serde::de::Visitor<'de> for ObjectRefVisitor {
type Value = ObjectRef<'de>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a tuple of (&str, ObjectPath)")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let name: &str = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
let path: ObjectPath<'de> = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;
if path == *NULL_OBJECT_PATH {
Ok(ObjectRef::Null)
} else {
assert!(
!name.is_empty(),
"A non-null ObjectRef requires a name and a path but got: (\"\", {path})"
);
Ok(ObjectRef::Borrowed {
name: UniqueName::try_from(name).map_err(serde::de::Error::custom)?,
path,
})
}
}
}
deserializer.deserialize_tuple(2, ObjectRefVisitor)
}
}
impl<'de> Deserialize<'de> for ObjectRefOwned {
/// `ObjectRefOwned` is deserialized as "Owned" variant `ObjectRef<'static>`.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let object_ref: ObjectRef<'_> = Deserialize::deserialize(deserializer)?;
Ok(object_ref.into())
}
}
impl PartialEq for ObjectRef<'_> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
// Match order is relevant here. Null == Null, but Null != any other object.
(ObjectRef::Null, ObjectRef::Null) => true,
(ObjectRef::Null, _) | (_, ObjectRef::Null) => false,
_ => self.name() == other.name() && self.path() == other.path(),
}
}
}
// `Hash` requires that hashes are equal if values are equal.
// If a == b, then a.hash() == b.hash() must hold true.
//
// Because PartialEq treats Owned and Borrowed variants with identical (name, path) as equal,
// we must implement Hash manually to ignore the variant discriminant and preserve hash/equality
// consistency.
impl Hash for ObjectRef<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
ObjectRef::Null => {
// Hashing a Null object reference.
"Null".hash(state);
}
ObjectRef::Owned { name, path } | ObjectRef::Borrowed { name, path } => {
name.as_str().hash(state);
path.as_str().hash(state);
}
}
}
}
impl Hash for ObjectRefOwned {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl PartialEq for ObjectRefOwned {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl PartialEq<ObjectRef<'_>> for ObjectRefOwned {
fn eq(&self, other: &ObjectRef<'_>) -> bool {
self.0 == *other
}
}
impl PartialEq<ObjectRefOwned> for ObjectRef<'_> {
fn eq(&self, other: &ObjectRefOwned) -> bool {
*self == other.0
}
}
#[cfg(feature = "zbus")]
impl<'m: 'o, 'o> TryFrom<&'m zbus::message::Header<'_>> for ObjectRef<'o> {
type Error = crate::AtspiError;
// Construct an ObjectRef<'o> by reborrowing from the Header’s data.
// 'm: 'o, 'm outlives 'o, so the references returned by this function
// are guaranteed to be valid for the lifetime of the header.
/// Construct an `ObjectRef` from a `zbus::message::Header`.
///
/// # Header fields
///
/// `Path` is a mandatory field on method calls and signals,
/// `Sender` is an optional field, see:
/// [DBus specification - header fields](<https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-header-fields>)).,
///
/// ```quote
/// On a message bus, this header field is controlled by the message bus,
/// so it is as reliable and trustworthy as the message bus itself.
/// Otherwise, (eg. P2P) this header field is controlled by the message sender,
/// unless there is out-of-band information that indicates otherwise.
/// ```
///
/// While unlikely, it is possible that `Sender` or `Path` are not set on the header.
/// This could happen if the server implementation does not set these fields for any reason.
///
/// # Errors
/// Will return an `AtspiError::ParseError` if the header does not contain a valid path or sender.
fn try_from(header: &'m zbus::message::Header) -> Result<Self, Self::Error> {
let path = header.path().ok_or(crate::AtspiError::MissingPath)?;
let name = header.sender().ok_or(crate::AtspiError::MissingName)?;
Ok(ObjectRef::Borrowed { name: name.clone(), path: path.clone() })
}
}
#[cfg(feature = "zbus")]
impl<'m> TryFrom<&'m zbus::message::Header<'_>> for ObjectRefOwned {
type Error = crate::AtspiError;
/// Construct an `ObjectRefOwned` from a `zbus::message::Header`.
fn try_from(header: &'m zbus::message::Header) -> Result<Self, Self::Error> {
let path = header.path().ok_or(crate::AtspiError::MissingPath)?;
let name = header.sender().ok_or(crate::AtspiError::MissingName)?;
let object_ref =
ObjectRef::Owned { name: name.clone().into_owned(), path: path.clone().into_owned() };
Ok(ObjectRefOwned(object_ref))
}
}
impl<'v> TryFrom<zbus::wire::Variant<'v>> for ObjectRef<'v> {
type Error = zbus::wire::Error;
fn try_from(value: zbus::wire::Variant<'v>) -> Result<Self, Self::Error> {
// Relies on the generic `Value` to tuple conversion `(UniqueName, ObjectPath)`.
let (name, path): (UniqueName, ObjectPath) = value.try_into()?;
Ok(ObjectRef::new_borrowed(name, path))
}
}
impl<'v> TryFrom<zbus::wire::Variant<'v>> for ObjectRefOwned {
type Error = zbus::wire::Error;
fn try_from(value: zbus::wire::Variant<'v>) -> Result<Self, Self::Error> {
// Relies on the generic `Value` to tuple conversion `(UniqueName, ObjectPath)`.
let (name, path): (UniqueName, ObjectPath) = value.try_into()?;
Ok(ObjectRef::new_borrowed(name, path).into())
}
}
impl TryFrom<zbus::wire::OwnedVariant> for ObjectRef<'static> {
type Error = zbus::wire::Error;
fn try_from(value: zbus::wire::OwnedVariant) -> Result<Self, Self::Error> {
let (name, path): (UniqueName<'static>, ObjectPath<'static>) = value.try_into()?;
Ok(ObjectRef::Owned { name, path })
}
}
impl TryFrom<zbus::wire::OwnedVariant> for ObjectRefOwned {
type Error = zbus::wire::Error;
fn try_from(value: zbus::wire::OwnedVariant) -> Result<Self, Self::Error> {
let (name, path): (UniqueName<'static>, ObjectPath<'static>) = value.try_into()?;
let obj = ObjectRef::Owned { name, path };
Ok(ObjectRefOwned(obj))
}
}
impl<'reference: 'structure, 'object: 'structure, 'structure> From<&'reference ObjectRef<'object>>
for zbus::wire::Structure<'structure>
{
fn from(obj: &'reference ObjectRef<'object>) -> Self {
match obj {
ObjectRef::Null => ("", NULL_OBJECT_PATH).into(),
ObjectRef::Borrowed { name, path } => Structure::from((name.clone(), path)),
ObjectRef::Owned { name, path } => Structure::from((name.as_str(), path.as_ref())),
}
}
}
impl<'o> From<ObjectRef<'o>> for zbus::wire::Structure<'o> {
fn from(obj: ObjectRef<'o>) -> Self {
match obj {
ObjectRef::Null => Structure::from(("", NULL_OBJECT_PATH)),
ObjectRef::Borrowed { name, path } | ObjectRef::Owned { name, path } => {
Structure::from((name, path))
}
}
}
}
impl From<ObjectRefOwned> for zbus::wire::Structure<'_> {
fn from(obj: ObjectRefOwned) -> Self {
let object_ref = obj.into_inner();
object_ref.into()
}
}
#[cfg(test)]
mod tests {
use std::hash::{DefaultHasher, Hash, Hasher};
use super::ObjectRef;
use crate::object_ref::{NULL_OBJECT_PATH, NULL_PATH_STR};
use zbus::{names::UniqueName, wire::ObjectPath};
use zbus::wire::{serialized::Context, to_bytes, OwnedVariant as OwnedValue, Variant as Value, LE};
const TEST_OBJECT_PATH: &str = "/org/a11y/atspi/path/007";
#[test]
fn owned_object_ref_creation() {
let name = UniqueName::from_static_str_unchecked(":1.23");
let path = ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH);
let object_ref = ObjectRef::new_owned(name, path);
assert_eq!(object_ref.name_as_str(), Some(":1.23"));
assert_eq!(object_ref.path_as_str(), TEST_OBJECT_PATH);
}
#[test]
fn borrowed_object_ref_creation() {
let object_ref = ObjectRef::new_borrowed(
UniqueName::from_static_str(":1.23").unwrap(),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
assert_eq!(object_ref.name_as_str(), Some(":1.23"));
assert_eq!(object_ref.path_as_str(), TEST_OBJECT_PATH);
}
#[test]
fn null_object_ref() {
let null_object_ref: ObjectRef = ObjectRef::Null;
assert!(null_object_ref.is_null());
assert!(null_object_ref.name().is_none());
assert_eq!(null_object_ref.path(), NULL_OBJECT_PATH);
}
#[test]
fn object_ref_into_owned() {
let borrowed_object_ref = ObjectRef::new_borrowed(
UniqueName::from_static_str(":1.23").unwrap(),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
let owned_object_ref = borrowed_object_ref.into_owned();
assert!(matches!(owned_object_ref, ObjectRef::Owned { .. }));
assert_eq!(owned_object_ref.name_as_str(), Some(":1.23"));
assert_eq!(owned_object_ref.path_as_str(), TEST_OBJECT_PATH);
}
#[test]
fn object_ref_into_name_and_path() {
let object_ref = ObjectRef::new_borrowed(
UniqueName::from_static_str(":1.23").unwrap(),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
let name = object_ref.name().unwrap();
let path = object_ref.path();
assert_eq!(name.as_str(), ":1.23");
assert_eq!(path.as_str(), TEST_OBJECT_PATH);
}
#[test]
fn serialization_null_object_ref() {
let null_object_ref: ObjectRef = ObjectRef::Null;
assert!(null_object_ref.is_null());
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &null_object_ref).unwrap();
let (obj, _) = encoded.deserialize::<ObjectRef>().unwrap();
assert!(obj.is_null());
assert!(obj.name().is_none());
assert_eq!(obj.path(), NULL_OBJECT_PATH);
}
#[test]
fn serialization_owned_object_ref() {
let name = UniqueName::from_static_str_unchecked(":1.23");
let path = ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH);
let object_ref = ObjectRef::new_owned(name, path);
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &object_ref).unwrap();
let (obj, _) = encoded.deserialize::<ObjectRef>().unwrap();
// Deserialization alwayys results in a borrowed object reference.
// On the wire the distinction between owned and borrowed is not preserved.
// As borrowed is the cheaper option, we always deserialize to that.
assert!(matches!(obj, ObjectRef::Borrowed { .. }));
assert_eq!(obj.name().unwrap().as_str(), ":1.23");
assert_eq!(obj.path_as_str(), TEST_OBJECT_PATH);
}
#[test]
fn serialization_borrowed_object_ref() {
let object_ref = ObjectRef::new_borrowed(
UniqueName::from_static_str(":1.23").unwrap(),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &object_ref).unwrap();
let (obj, _) = encoded.deserialize::<ObjectRef>().unwrap();
assert!(matches!(obj, ObjectRef::Borrowed { .. }));
assert_eq!(obj.name().unwrap().as_str(), ":1.23");
assert_eq!(obj.path_as_str(), TEST_OBJECT_PATH);
}
#[test]
fn object_ref_equality() {
let object_ref1 = ObjectRef::new_borrowed(
UniqueName::from_static_str(":1.23").unwrap(),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
let object_ref2 = ObjectRef::new_borrowed(
UniqueName::from_static_str(":1.23").unwrap(),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
assert_eq!(object_ref1, object_ref2);
let object_ref3 = ObjectRef::new_borrowed(
UniqueName::from_static_str(":1.24").unwrap(),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
assert_ne!(object_ref1, object_ref3);
let object_ref4 = ObjectRef::new_owned(
UniqueName::from_static_str_unchecked(":1.23"),
ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH),
);
assert_eq!(object_ref1, object_ref4);
let null_object_ref: ObjectRef = ObjectRef::Null;
assert_ne!(object_ref1, null_object_ref);
assert_ne!(null_object_ref, object_ref1);
let null_object_ref2: ObjectRef = ObjectRef::Null;
assert_eq!(null_object_ref, null_object_ref2);
}
#[test]
fn try_from_value_for_objectref() {
let name = UniqueName::from_static_str_unchecked(":0.0");
let path = ObjectPath::from_static_str_unchecked("/org/a11y/atspi/testpath");
let objref = ObjectRef::new_borrowed(name, path);
let value: Value = objref.into();
let objref_2: ObjectRef = value.try_into().unwrap();
assert_eq!(objref_2.name().unwrap().as_str(), ":0.0");
assert_eq!(objref_2.path_as_str(), "/org/a11y/atspi/testpath");
}
#[test]
fn try_from_owned_value_for_objectref() {
let name = UniqueName::from_static_str_unchecked(":0.0");
let path = ObjectPath::from_static_str_unchecked("/org/a11y/atspi/testpath");
let objref = ObjectRef::new_borrowed(name, path);
let value: Value = objref.into();
let value: OwnedValue = value.try_into().unwrap();
let objref_2: ObjectRef = value.try_into().unwrap();
assert_eq!(objref_2.name_as_str(), Some(":0.0"));
assert_eq!(objref_2.path_as_str(), "/org/a11y/atspi/testpath");
}
// Must fail test:
#[test]
fn must_fail_test_try_from_invalid_value_for_object_ref() {
let value = zbus::wire::Variant::from((42, true));
let obj: Result<ObjectRef, _> = value.try_into();
assert!(obj.is_err());
}
#[test]
fn hash_and_object_coherence() {
let name = UniqueName::from_static_str_unchecked(":1.23");
let path = ObjectPath::from_static_str_unchecked(TEST_OBJECT_PATH);
let object_ref1 = ObjectRef::new_borrowed(&name, &path);
let object_ref2 = ObjectRef::new_borrowed(name, path);
let mut hasher1 = DefaultHasher::new();
let mut hasher2 = DefaultHasher::new();
assert_eq!(object_ref1, object_ref2);
object_ref1.hash(&mut hasher1);
object_ref2.hash(&mut hasher2);
assert_eq!(hasher1.finish(), hasher2.finish());
}
#[test]
#[should_panic(expected = "assertion failed: matches!(obj, ObjectRef::Borrowed { .. })")]
fn valid_name_null_path_object_ref() {
let object_ref = ObjectRef::from_static_str_unchecked("1.23", NULL_PATH_STR);
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &object_ref).unwrap();
let (obj, _) = encoded.deserialize::<ObjectRef>().unwrap();
assert!(matches!(obj, ObjectRef::Borrowed { .. }));
}
// Check that the Deserialize implementation correctly panics
#[test]
#[should_panic(
expected = r#"A non-null ObjectRef requires a name and a path but got: ("", /org/a11y/atspi/path/007)"#
)]
fn empty_name_valid_path_object_ref() {
let object_ref = ObjectRef::from_static_str_unchecked("", TEST_OBJECT_PATH);
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &object_ref).unwrap();
let (_obj, _) = encoded.deserialize::<ObjectRef>().unwrap();
}
}

39
patches/atspi-common/src/operation.rs vendored Normal file
View file

@ -0,0 +1,39 @@
use crate::AtspiError;
use std::{fmt, str::FromStr};
/// An operation can either be [`Self::Insert`] or [`Self::Delete`].
/// These correspond to methods available on [`Vec`].
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize, Eq, Hash, Default)]
pub enum Operation {
#[default]
#[serde(rename = "add")]
#[serde(alias = "add/system")]
#[serde(alias = "insert")]
#[serde(alias = "insert/system")]
Insert,
#[serde(rename = "delete")]
#[serde(alias = "delete/system")]
#[serde(alias = "remove")]
#[serde(alias = "remove/system")]
Delete,
}
impl FromStr for Operation {
type Err = AtspiError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"add" | "add/system" | "insert" | "insert/system" => Ok(Operation::Insert),
"delete" | "delete/system" | "remove" | "remove/system" => Ok(Operation::Delete),
_ => Err(AtspiError::KindMatch(format!("{s} is not a type of Operation"))),
}
}
}
impl fmt::Display for Operation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Operation::Insert => write!(f, "insert"),
Operation::Delete => write!(f, "delete"),
}
}
}

View file

@ -0,0 +1,121 @@
use serde::{Deserialize, Serialize};
use zbus::wire::Type;
/// Describes a relationship between one object and another.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type, Hash)]
pub enum RelationType {
/// Not a meaningful relationship; clients should not normally encounter this value.
Null = 0,
/// Object is a label for one or more other objects.
LabelFor,
/// Object is labelled by one or more other objects.
LabelledBy,
/// Object is an interactive object which modifies the state,
/// onscreen location, or other attributes of one or more target objects.
ControllerFor,
/// Object state, position, etc. is modified/controlled by user interaction
/// with one or more other objects.
/// For instance a viewport or scroll pane may be `ControlledBy` scrollbars.
ControlledBy,
/// Object has a grouping relationship (e.g. 'same group as') to one or more other objects.
MemberOf,
/// Object is a tooltip associated with another object.
TooltipFor,
/// Object is a child of the target.
NodeChildOf,
/// Object is a parent of the target.
NodeParentOf,
/// Used to indicate that a relationship exists, but its type is not
/// specified in the enumeration.
Extended,
/// Object renders content which flows logically to another object.
/// For instance, text in a paragraph may flow to another object
/// which is not the 'next sibling' in the accessibility hierarchy.
FlowsTo,
/// Reciprocal of `FlowsTo`.
FlowsFrom,
/// Object is visually and semantically considered a subwindow of another object,
/// even though it is not the object's child.
/// Useful when dealing with embedded applications and other cases where the
/// widget hierarchy does not map cleanly to the onscreen presentation.
SubwindowOf,
/// Similar to `SubwindowOf`, but specifically used for cross-process embedding.
Embeds,
/// Reciprocal of `Embeds`. Used to denote content rendered by embedded renderers
/// that live in a separate process space from the embedding context.
EmbeddedBy,
///Denotes that the object is a transient window or frame associated with another
/// onscreen object. Similar to `TooltipFor`, but more general.
/// Useful for windows which are technically toplevels but which, for one or more reasons,
/// do not explicitly cause their associated window to lose 'window focus'.
/// Creation of an [`crate::Role::Window`] object with the `PopupFor` relation usually requires
/// some presentation action on the part of assistive technology clients,
/// even though the previous toplevel [`crate::Role::Frame`] object may still be the active window.
PopupFor,
/// This is the reciprocal relation to `PopupFor`.
ParentWindowOf,
/// Reciprocal of `DescribedBy`. Indicates that this object provides descriptive information
/// about the target object(s). See also `DetailsFor` and `ErrorFor`.
DescriptionFor,
/// Reciprocal of `DescriptionFor`.
/// Indicates that one or more target objects provide descriptive information
/// about this object. This relation type is most appropriate for information
/// that is not essential as its presentation may be user-configurable and/or
/// limited to an on-demand mechanism such as an assistive technology command.
/// For brief, essential information such as can be found in a widget's on-screen
/// label, use `LabelledBy`. For an on-screen error message, use `ErrorMessage`.
/// For lengthy extended descriptive information contained in an on-screen object,
/// consider using `Details` as assistive technologies may provide a means
/// for the user to navigate to objects containing detailed descriptions so that
/// their content can be more closely reviewed.
DescribedBy,
/// Reciprocal of `DetailsFor`.
/// Indicates that this object has a detailed or extended description,
/// the contents of which can be found in the target object(s).
/// This relation type is most appropriate for information that is sufficiently lengthy
/// as to make navigation to the container of that information desirable.
/// For less verbose information suitable for announcement only, see `DescribedBy`.
/// If the detailed information describes an error condition, `ErrorFor` should be used instead.
/// Included in upstream [AT-SPI2-CORE](https://gitlab.gnome.org/GNOME/at-spi2-core) since 2.26.
Details,
/// Reciprocal of `Details`.
/// Indicates that this object provides a detailed or extended description about the target
/// object(s). See also `DescriptionFor` and `ErrorFor`.
/// Included in upstream [AT-SPI2-CORE](https://gitlab.gnome.org/GNOME/at-spi2-core) since 2.26.
DetailsFor,
/// Reciprocal of `ErrorFor`.
/// Indicates that this object has one or more errors, the nature of which is
/// described in the contents of the target object(s). Objects that have this
/// relation type should also contain [`crate::state::State::InvalidEntry`] when their
/// `GetState` method is called.
///
/// Included in upstream [AT-SPI2-CORE](https://gitlab.gnome.org/GNOME/at-spi2-core) since 2.26.
ErrorMessage,
/// Reciprocal of `ErrorMessage`.
/// Indicates that this object contains an error message describing an invalid condition
/// in the target object(s).
/// Included in upstream [AT-SPI2-CORE](https://gitlab.gnome.org/GNOME/at-spi2-core) since 2.26.
ErrorFor,
}

651
patches/atspi-common/src/role.rs vendored Normal file
View file

@ -0,0 +1,651 @@
use serde::{Deserialize, Serialize};
use zbus::wire::Type;
use crate::AtspiError;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type, Hash)]
/// An accessible object role.
///
/// To think of it in terms of HTML, any semantic element likely has a corollary in this enum.
/// For example: `<button>`, `<input>`, `<form>` or `<h4>`.
/// Non-semantic elements like `<span>`, `<div>` and `<b>` will not be represented here, and this information is not passed through via the atspi library.
/// TODO: add examples for GTK/Qt libraries in addition to HTML examples.
#[repr(u32)]
pub enum Role {
/// A role indicating an error condition, such as uninitialized Role data, or an error deserializing.
Invalid,
/// Object is a label indicating the keyboard accelerators for the parent.
AcceleratorLabel,
/// Object is used to alert the user about something.
Alert,
/// Object contains a dynamic or moving image of some kind.
Animation,
/// Object is a 2d directional indicator.
Arrow,
/// Object contains one or more dates, usually arranged into a 2d list.
Calendar,
/// Object that can be drawn into and is used to trap events.
Canvas,
/// A choice that can be checked or unchecked and provides a separate indicator for the current state.
CheckBox,
/// A menu item that behaves like a check box. See [`Self::CheckBox`].
CheckMenuItem,
/// A specialized dialog that lets the user choose a color.
ColorChooser,
/// The header for a column of data.
ColumnHeader,
/// A list of choices the user can select from.
ComboBox,
/// An object which allows entry of a date.
DateEditor,
/// An inconifed internal frame within a [`Role::DesktopFrame`].
DesktopIcon,
/// A pane that supports internal frames and iconified versions of those internal frames.
DesktopFrame,
/// An object that allows a value to be changed via rotating a visual element, or which displays a value via such a rotating element.
Dial,
/// A top level window with title bar and a border.
Dialog,
/// A pane that allows the user to navigate through and select the contents of a directory.
DirectoryPane,
/// An object used for drawing custom user interface elements.
DrawingArea,
/// A specialized dialog that displays the files in the directory and lets the user select a file, browse a different directory, or specify a filename.
FileChooser,
/// A object that fills up space in a user interface.
Filler,
/// Don't use, reserved for future use.
FocusTraversable,
/// Allows selection of a display font.
FontChooser,
/// A top level window with a title bar, border, menubar, etc.
Frame,
/// A pane that is guaranteed to be painted on top of all panes beneath it.
GlassPane,
/// A document container for HTML, whose children represent the document content.
HTMLContainer,
/// A small fixed size picture, typically used to decorate components.
Icon,
/// An image, typically static.
Image,
/// A frame-like object that is clipped by a desktop pane.
InternalFrame,
/// An object used to present an icon or short string in an interface.
Label,
/// A specialized pane that allows its children to be drawn in layers, providing a form of stacking order.
LayeredPane,
/// An object that presents a list of objects to the user and * allows the user to select one or more of them.
List,
/// An object that represents an element of a list.
ListItem,
/// An object usually found inside a menu bar that contains a list of actions the user can choose from.
Menu,
/// An object usually drawn at the top of the primary dialog box of an application that contains a list of menus the user can choose from.
MenuBar,
/// An object usually contained in a menu that presents an action the user can choose.
MenuItem,
/// A specialized pane whose primary use is inside a dialog.
OptionPane,
/// An object that is a child of a page tab list.
PageTab,
/// An object that presents a series of panels (or page tabs), one at a time,through some mechanism provided by the object.
PageTabList,
/// A generic container that is often used to group objects.
Panel,
/// A text object uses for passwords, or other places where the text content is not shown visibly to the user.
PasswordText,
/// A temporary window that is usually used to offer the user a list of choices, and then hides when the user selects one of those choices.
PopupMenu,
/// An object used to indicate how much of a task has been completed.
ProgressBar,
/// An object the user can manipulate to tell the application to do something.
Button,
/// A specialized check box that will cause other radio buttons in the same group to become unchecked when this one is checked.
RadioButton,
/// Object is both a menu item and a "radio button". See [`Self::RadioButton`].
RadioMenuItem,
/// A specialized pane that has a glass pane and a layered pane as its children.
RootPane,
/// The header for a row of data.
RowHeader,
/// An object usually used to allow a user to incrementally view a large amount of data by moving the bounds of a viewport along a one-dimensional axis.
ScrollBar,
/// A scroll pane: the pane in which the scrollable content is contained within.
/// An object that allows a user to incrementally view a large amount of information.
/// [`Self::ScrollPane`] objects are usually accompanied by [`Self::ScrollBar`] controllers,
/// on which the [`crate::RelationType::ControllerFor`] and [`crate::RelationType::ControlledBy`] reciprocal relations are set.
ScrollPane,
/// An object usually contained in a menu to provide a visible and logical separation of the contents in a menu.
Separator,
/// An object that allows the user to select from a bounded range.
/// Unlike [`Self::ScrollBar`], [`Self::Slider`] objects need not control 'viewport'-like objects.
Slider,
/// An object which allows one of a set of choices to be selected, and which displays the current choice.
SpinButton,
/// A specialized panel that presents two other panels at the same time.
SplitPane,
/// Object displays non-quantitative status information (c.f. [`Self::ProgressBar`])
StatusBar,
/// An object used to represent information in terms of rows and columns.
Table,
/// A 'cell' or discrete child within a Table.
/// Note: Table cells need not have [`Self::TableCell`], other [`crate::Role`] values are valid as well.
TableCell,
/// An object which labels a particular column in an [`Self::Table`].
TableColumnHeader,
/// An object which labels a particular row in a [`Self::Table`].
/// `TableProxy` rows and columns may also be labelled via the
/// [`crate::RelationType::LabelFor`]/[`crate::RelationType::LabelledBy`] relationships.
/// See: `AccessibleProxy::get_relation_type`.
TableRowHeader,
/// Object allows menu to be removed from menubar and shown in its own window.
TearoffMenuItem,
/// An object that emulates a terminal.
Terminal,
/// An interactive widget that supports multiple lines of text and optionally accepts user input,
/// but whose purpose is not to solicit user input.
/// Thus [`Self::Text`] is appropriate for the text view in a plain text editor but inappropriate for an input field in a dialog box or web form.
/// For widgets whose purpose is to solicit input from the user, see [`Self::Entry`] and [`Self::PasswordText`].
/// For generic objects which display a brief amount of textual information, see [`Self::Static`].
Text,
/// A specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state.
ToggleButton,
/// A bar or palette usually composed of push buttons or toggle buttons.
ToolBar,
/// An object that provides information about another object.
ToolTip,
/// An object used to repsent hierarchical information to the user.
Tree,
/// An object that presents both tabular and hierarchical info to the user.
TreeTable,
/// When the role cannot be accurately reported, this role will be set.
Unknown,
/// An object usually used in a scroll pane, or to otherwise clip a larger object or content renderer to a specific onscreen viewport.
Viewport,
/// A top level window with no title or border.
Window,
/// means that the role for this item is known, but not included in the core enumeration.
Extended,
/// An object that serves as a document header.
Header,
/// An object that serves as a document footer.
Footer,
/// An object which is contains a single paragraph of text content. See also [`Self::Text`].
Paragraph,
/// An object which describes margins and tab stops, etc. for text objects which it controls (should have [`crate::RelationType::ControllerFor`] relation to such).
Ruler,
/// An object corresponding to the toplevel accessible of an application, which may contain [`Self::Frame`] objects or other accessible objects.
/// Children of objects with the [`Self::DesktopFrame`] role are generally [`Self::Application`] objects.
Application,
/// The object is a dialog or list containing items for insertion into an entry widget, for instance a list of words for completion of a text entry.
Autocomplete,
/// The object is an editable text object in a toolbar.
Editbar,
/// The object is an embedded component container.
/// This role is a "grouping" hint that the contained objects share a context which is different from the container in which this accessible is embedded.
/// In particular, it is used for some kinds of document embedding, and for embedding of out-of-process component, "panel applets", etc.
Embedded,
/// The object is a component whose textual content may be entered or modified by the user, provided [`crate::State::Editable`] is present.
/// A readonly [`Self::Entry`] object (i.e. where [`crate::State::Editable`] is not present) implies a read-only 'text field' in a form, as opposed to a title, label, or caption.
Entry,
/// The object is a graphical depiction of quantitative data.
/// It may contain multiple subelements whose attributes and/or description may be queried to obtain both the quantitative data and information about how the data is being presented.
/// The [`crate::RelationType::LabelledBy`] relation is particularly important in interpreting objects of this type, as is the accessible description property.
/// See [`Self::Caption`].
CHART,
/// The object contains descriptive information, usually textual, about another user interface element such as a table, chart, or image.
Caption,
/// The object is a visual frame or container which
/// contains a view of document content. [`Self::DocumentFrame`]s may occur within
/// another `DocumentProxy` instance, in which case the second document may be
/// said to be embedded in the containing instance.
/// HTML frames are often [`Self::DocumentFrame`]: Either this object, or a singleton descendant,
/// should implement the [`crate::Interface::Document`] interface.
DocumentFrame,
/// Heading: this is a heading with a level (usually 1-6). This is represented by `<h1>` through `<h6>` in HTML.
/// The object serves as a heading for content which follows it in a document.
/// The 'heading level' of the heading, if available, may be obtained by querying the object's attributes.
Heading,
/// The object is a containing instance which encapsulates a page of information.
/// [`Self::Page`] is used in documents and content which support a paginated navigation model.
Page,
/// The object is a containing instance of document content which constitutes a particular 'logical' section of the document.
/// The type of content within a section, and the nature of the section division itself, may be obtained by querying the object's attributes.
/// Sections may be nested.
Section,
/// The object is redundant with another object in the hierarchy, and is exposed for purely technical reasons.
/// Objects of this role should be ignored by clients, if they are encountered at all.
RedundantObject,
/// The object is a containing instance of document content which has within it components with which the user can interact in order to input information;
/// i.e. the object is a container for pushbuttons, comboboxes, text input fields, and other 'GUI' components.
/// [`Self::Form`] should not, in general, be used for toplevel GUI containers or dialogs, but should be reserved for 'GUI' containers which occur within document content, for instance within Web documents, presentations, or text documents.
/// Unlike other GUI containers and dialogs which occur inside application instances, [`Self::Form`] containers' components are associated with the current document, rather than the current foreground application or viewer instance.
Form,
/// The object is a hypertext anchor, i.e. a "link" in a hypertext document.
/// Such objects are distinct from 'inline' content which may also use the [`crate::Interface::Hypertext`]/[`crate::Interface::Hyperlink`] interfaces to indicate the range/location within a text object where an inline or embedded object lies.
Link,
/// The object is a window or similar viewport which is used to allow composition or input of a 'complex character', in other words it is an "input method window".
InputMethodWindow,
/// A row in a table.
TableRow,
/// An object that represents an element of a tree.
TreeItem,
/// A document frame which contains a spreadsheet.
DocumentSpreadsheet,
/// A document frame which contains a presentation or slide content.
DocumentPresentation,
/// A document frame which contains textual content, such as found in a word processing application.
DocumentText,
/// A document frame which contains HTML or other markup suitable for display in a web browser.
DocumentWeb,
/// A document frame which contains email content to be displayed or composed either in plain text or HTML.
DocumentEmail,
/// An object found within a document and designed to present a comment, note, or other annotation.
/// In some cases, this object might not be visible until activated.
Comment,
/// A non-collapsible list of choices the user can select from.
ListBox,
/// A group of related widgets. This group typically has a label.
Grouping,
/// An image map object. Usually a graphic with multiple hotspots, where each hotspot can be activated resulting in the loading of another document or section of a document.
ImageMap,
/// A transitory object designed to present a message to the user, typically at the desktop level rather than inside a particular application.
Notification,
/// An object designed to present a message to the user within an existing window.
InfoBar,
/// A bar that serves as a level indicator to, for instance, show the strength of a password or the state of a battery.
LevelBar,
/// A bar that serves as the title of a window or a dialog.
TitleBar,
/// An object which contains a text section that is quoted from another source.
BlockQuote,
/// An object which represents an audio element.
Audio,
/// An object which represents a video element.
Video,
/// A definition of a term or concept.
Definition,
/// A section of a page that consists of a composition that forms an independent part of a document, page, or site.
/// Examples: A blog entry, a news story, a forum post.
Article,
/// A region of a web page intended as a navigational landmark. This is designed to allow Assistive Technologies to provide quick navigation among key regions within a document.
Landmark,
/// A text widget or container holding log content, such as chat history and error logs. In this role there is a relationship between the arrival of new items in the log and the reading order.
/// The log contains a meaningful sequence and new information is added only to the end of the log, not at arbitrary points.
Log,
/// A container where non-essential information changes frequently.
/// Common usages of marquee include stock tickers and ad banners.
/// The primary difference between a marquee and a log is that logs usually have a meaningful order or sequence of important content changes.
Marquee,
/// A text widget or container that holds a mathematical expression.
Math,
/// A rating system, generally out of five stars, but it does not need to be that way. There is no tag nor role for this in HTML, however.
/// A widget whose purpose is to display a rating, such as the number of stars associated with a song in a media player.
/// Objects of this role should also implement [`crate::Interface::Value`].
Rating,
/// An object containing a numerical counter which indicates an amount of elapsed time from a start point, or the time remaining until an end point.
Timer,
/// A generic non-container object whose purpose is to display a brief amount of information to the user and whose role is known by the implementor but lacks semantic value for the user.
/// Examples in which [`Self::Static`] is appropriate include the message displayed in a message box and an image used as an alternative means to display text.
/// [`Self::Static`] should not be applied to widgets which are traditionally interactive, objects which display a significant amount of content, or any object which has an accessible relation pointing to another object.
/// The displayed information, as a general rule, should be exposed through the accessible name of the object.
/// For labels which describe another widget, see [`Self::Label`].
/// For text views, see [`Self::Text`].
/// For generic containers, see [`Self::Panel`]. For objects whose role is not known by the implementor, see [`Self::Unknown`].
Static,
/// An object that represents a mathematical fraction.
MathFraction,
/// An object that represents a mathematical expression displayed with a radical.
MathRoot,
/// An object that contains text that is displayed as a subscript.
Subscript,
/// An object that contains text that is displayed as a superscript.
Superscript,
/// An object that represents a list of term-value groups.
/// A term-value group represents an individual description and consist of one or more names ([`Self::DescriptionTerm`]) followed by one or more values ([`Self::DescriptionValue`]).
/// For each list, there should not be more than one group with the same term name.
DescriptionList,
/// An object that represents a term or phrase with a corresponding definition.
DescriptionTerm,
/// An object that represents the description, definition, or value of a term.
DescriptionValue,
/// An object that contains the text of a footnote.
Footnote,
/// Content previously deleted or proposed to be deleted, e.g. in revision history or a content view providing suggestions from reviewers.
ContentDeletion,
/// Content previously inserted or proposed to be inserted, e.g. in revision history or a content view providing suggestions from reviewers.
ContentInsertion,
/// A run of content that is marked or highlighted, such as for reference purposes, or to call it out as having a special purpose.
/// If the marked content has an associated section in the document elaborating on the reason for the mark, then [`crate::RelationType::Details`] should be used on the mark to point to that associated section.
/// In addition, the reciprocal relation [`crate::RelationType::DetailsFor`] should be used on the associated content section to point back to the mark.
Mark,
/// A container for content that is called out as a proposed change from the current version of the document, such as by a reviewer of the content.
/// An object with this role should include children with [`Self::ContentDeletion`] and/or [`Self::ContentInsertion`], in any order, to indicate what the actual change is.
Suggestion,
/// A specialized push button to open a menu.
PushButtonMenu,
}
impl TryFrom<u32> for Role {
type Error = AtspiError;
#[allow(clippy::too_many_lines)]
fn try_from(value: u32) -> Result<Self, Self::Error> {
#[allow(clippy::enum_glob_use)]
use Role::*;
let res = match value {
0 => Invalid,
1 => AcceleratorLabel,
2 => Alert,
3 => Animation,
4 => Arrow,
5 => Calendar,
6 => Canvas,
7 => CheckBox,
8 => CheckMenuItem,
9 => ColorChooser,
10 => ColumnHeader,
11 => ComboBox,
12 => DateEditor,
13 => DesktopIcon,
14 => DesktopFrame,
15 => Dial,
16 => Dialog,
17 => DirectoryPane,
18 => DrawingArea,
19 => FileChooser,
20 => Filler,
21 => FocusTraversable,
22 => FontChooser,
23 => Frame,
24 => GlassPane,
25 => HTMLContainer,
26 => Icon,
27 => Image,
28 => InternalFrame,
29 => Label,
30 => LayeredPane,
31 => List,
32 => ListItem,
33 => Menu,
34 => MenuBar,
35 => MenuItem,
36 => OptionPane,
37 => PageTab,
38 => PageTabList,
39 => Panel,
40 => PasswordText,
41 => PopupMenu,
42 => ProgressBar,
43 => Button,
44 => RadioButton,
45 => RadioMenuItem,
46 => RootPane,
47 => RowHeader,
48 => ScrollBar,
49 => ScrollPane,
50 => Separator,
51 => Slider,
52 => SpinButton,
53 => SplitPane,
54 => StatusBar,
55 => Table,
56 => TableCell,
57 => TableColumnHeader,
58 => TableRowHeader,
59 => TearoffMenuItem,
60 => Terminal,
61 => Text,
62 => ToggleButton,
63 => ToolBar,
64 => ToolTip,
65 => Tree,
66 => TreeTable,
67 => Unknown,
68 => Viewport,
69 => Window,
70 => Extended,
71 => Header,
72 => Footer,
73 => Paragraph,
74 => Ruler,
75 => Application,
76 => Autocomplete,
77 => Editbar,
78 => Embedded,
79 => Entry,
80 => CHART,
81 => Caption,
82 => DocumentFrame,
83 => Heading,
84 => Page,
85 => Section,
86 => RedundantObject,
87 => Form,
88 => Link,
89 => InputMethodWindow,
90 => TableRow,
91 => TreeItem,
92 => DocumentSpreadsheet,
93 => DocumentPresentation,
94 => DocumentText,
95 => DocumentWeb,
96 => DocumentEmail,
97 => Comment,
98 => ListBox,
99 => Grouping,
100 => ImageMap,
101 => Notification,
102 => InfoBar,
103 => LevelBar,
104 => TitleBar,
105 => BlockQuote,
106 => Audio,
107 => Video,
108 => Definition,
109 => Article,
110 => Landmark,
111 => Log,
112 => Marquee,
113 => Math,
114 => Rating,
115 => Timer,
116 => Static,
117 => MathFraction,
118 => MathRoot,
119 => Subscript,
120 => Superscript,
121 => DescriptionList,
122 => DescriptionTerm,
123 => DescriptionValue,
124 => Footnote,
125 => ContentDeletion,
126 => ContentInsertion,
127 => Mark,
128 => Suggestion,
129 => PushButtonMenu,
_ => return Err(AtspiError::UnknownRole(value)),
};
Ok(res)
}
}
const ROLE_NAMES: &[&str] = &[
"invalid",
"accelerator label",
"alert",
"animation",
"arrow",
"calendar",
"canvas",
"check box",
"check menu item",
"color chooser",
"column header",
"combo box",
"date editor",
"desktop icon",
"desktop frame",
"dial",
"dialog",
"directory pane",
"drawing area",
"file chooser",
"filler",
"focus traversable",
"font chooser",
"frame",
"glass pane",
"html container",
"icon",
"image",
"internal frame",
"label",
"layered pane",
"list",
"list item",
"menu",
"menu bar",
"menu item",
"option pane",
"page tab",
"page tab list",
"panel",
"password text",
"popup menu",
"progress bar",
"button",
"radio button",
"radio menu item",
"root pane",
"row header",
"scroll bar",
"scroll pane",
"separator",
"slider",
"spin button",
"split pane",
"status bar",
"table",
"table cell",
"table column header",
"table row header",
"tearoff menu item",
"terminal",
"text",
"toggle button",
"tool bar",
"tool tip",
"tree",
"tree table",
"unknown",
"viewport",
"window",
"extended",
"header",
"footer",
"paragraph",
"ruler",
"application",
"autocomplete",
"editbar",
"embedded",
"entry",
"chart",
"caption",
"document frame",
"heading",
"page",
"section",
"redundant object",
"form",
"link",
"input method window",
"table row",
"tree item",
"document spreadsheet",
"document presentation",
"document text",
"document web",
"document email",
"comment",
"list box",
"grouping",
"image map",
"notification",
"info bar",
"level bar",
"title bar",
"block quote",
"audio",
"video",
"definition",
"article",
"landmark",
"log",
"marquee",
"math",
"rating",
"timer",
"static",
"math fraction",
"math root",
"subscript",
"superscript",
"description list",
"description term",
"description value",
"footnote",
"content deletion",
"content insertion",
"mark",
"suggestion",
"push button menu",
];
impl Role {
/// Get a readable, English name from the role.
#[must_use]
pub fn name(&self) -> &'static str {
ROLE_NAMES[*self as usize]
}
}
impl std::fmt::Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
#[cfg(test)]
pub mod tests {
use super::Role;
use zbus::wire::serialized::Context;
use zbus::wire::{to_bytes, LE};
const HIGHEST_ROLE_VALUE: u32 = 129;
#[test]
fn test_serialization_matches_from_impl() {
let ctxt = Context::new(LE, 0);
for role_num in 1..=HIGHEST_ROLE_VALUE {
let from_role = Role::try_from(role_num)
.unwrap_or_else(|_| panic!("Unable to convert {role_num} into Role"));
let encoded = to_bytes(ctxt, &from_role)
.unwrap_or_else(|_| panic!("Unable to encode {from_role}"));
println!("ENCODED: {encoded:?}");
let (zbus_role, _) = encoded
.deserialize()
.unwrap_or_else(|_| panic!("Unable to decode {encoded:?}"));
assert_eq!(from_role, zbus_role, "The serde `Data::deserialize` and `From<u32>` impls produced different results. The number used was {role_num}, it produced a Role of {from_role}, but the from_slice(...) implementation produced {zbus_role}");
assert_eq!(
from_role as u32, role_num,
"The role number {role_num} does not match the representation of the role {}",
from_role as u32
);
}
}
}

719
patches/atspi-common/src/state.rs vendored Normal file
View file

@ -0,0 +1,719 @@
use enumflags2::{bitflags, BitFlag, BitFlags, FromBitsError};
use serde::{
de::{self, Deserializer, Visitor},
ser::{SerializeSeq, Serializer},
Deserialize, Serialize,
};
use std::{convert::Infallible, fmt, str::FromStr};
use zbus::wire::{Signature, Type};
/// Used by various interfaces indicating every possible state
/// of an accessibility object.
#[bitflags]
#[non_exhaustive]
#[repr(u64)]
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "kebab-case")]
pub enum State {
/// Indicates an invalid state - probably an error condition.
#[default]
Invalid,
/// Indicates a window is currently the active window, or
/// an object is the active subelement within a container or table.
///
/// `Active` should not be used for objects which have
/// [`State::Focusable`] or [`State::Selectable`]: Those objects should use
/// [`State::Focused`] and [`State::Selected`] respectively.
///
/// `Active` is a means to indicate that an object which is not
/// focusable and not selectable is the currently-active item within its
/// parent container.
Active,
/// Indicates that the object is armed.
Armed,
/// Indicates the current object is busy, i.e. onscreen
/// representation is in the process of changing, or the object is
/// temporarily unavailable for interaction due to activity already in progress.
Busy,
/// Indicates this object is currently checked.
Checked,
/// Indicates this object is collapsed.
Collapsed,
/// Indicates that this object no longer has a valid
/// backing widget (for instance, if its peer object has been destroyed).
Defunct,
/// Indicates the user can change the contents of this object.
Editable,
/// Indicates that this object is enabled, i.e. that it
/// currently reflects some application state. Objects that are "greyed out"
/// may lack this state, and may lack the [`State::Sensitive`] if direct
/// user interaction cannot cause them to acquire `Enabled`.
///
/// See [`State::Sensitive`].
Enabled,
/// Indicates this object allows progressive
/// disclosure of its children.
Expandable,
/// Indicates this object is expanded.
Expanded,
/// Indicates this object can accept keyboard focus,
/// which means all events resulting from typing on the keyboard will
/// normally be passed to it when it has focus.
Focusable,
/// Indicates this object currently has the keyboard focus.
Focused,
/// Indicates that the object has an associated tooltip.
HasTooltip,
/// Indicates the orientation of this object is horizontal.
Horizontal,
/// Indicates this object is minimized and is
/// represented only by an icon.
Iconified,
/// Indicates something must be done with this object
/// before the user can interact with an object in a different window.
Modal,
/// Indicates this (text) object can contain multiple
/// lines of text.
MultiLine,
/// Indicates this object allows more than one of
/// its children to be selected at the same time, or in the case of text
/// objects, that the object supports non-contiguous text selections.
Multiselectable,
/// Indicates this object paints every pixel within its
/// rectangular region. It also indicates an alpha value of unity, if it
/// supports alpha blending.
Opaque,
/// Indicates this object is currently pressed.
Pressed,
/// Indicates the size of this object's size is not fixed.
Resizable,
/// Indicates this object is the child of an object
/// that allows its children to be selected and that this child is one of
/// those children that can be selected.
Selectable,
/// Indicates this object is the child of an object that
/// allows its children to be selected and that this child is one of those
/// children that has been selected.
Selected,
/// Indicates this object is sensitive, e.g. to user
/// interaction. `Sensitive` usually accompanies.
/// [`State::Enabled`] for user-actionable controls, but may be found in the
/// absence of [`State::Enabled`] if the current visible state of the control
/// is "disconnected" from the application state. In such cases, direct user
/// interaction can often result in the object gaining `Sensitive`,
/// for instance if a user makes an explicit selection using an object whose
/// current state is ambiguous or undefined.
///
/// See [`State::Enabled`], [`State::Indeterminate`].
Sensitive,
/// Indicates this object, the object's parent, the
/// object's parent's parent, and so on, are all 'shown' to the end-user,
/// i.e. subject to "exposure" if blocking or obscuring objects do not
/// interpose between this object and the top of the window stack.
Showing,
/// Indicates this (text) object can contain only a
/// single line of text.
SingleLine,
/// Indicates that the information returned for this object
/// may no longer be synchronized with the application state. This can occur
/// if the object has [`State::Transient`], and can also occur towards the
/// end of the object peer's lifecycle.
Stale,
/// Indicates this object is transient.
Transient,
/// Indicates the orientation of this object is vertical;
/// for example this state may appear on such objects as scrollbars, text
/// objects (with vertical text flow), separators, etc.
Vertical,
/// Indicates this object is visible, e.g. has been
/// explicitly marked for exposure to the user. `Visible` is no
/// guarantee that the object is actually unobscured on the screen, only that
/// it is 'potentially' visible, barring obstruction, being scrolled or clipped
/// out of the field of view, or having an ancestor container that has not yet
/// made visible. A widget is potentially onscreen if it has both
/// `Visible` and [`State::Showing`]. The absence of
/// `Visible` and [`State::Showing`] is
/// semantically equivalent to saying that an object is 'hidden'.
Visible,
/// Indicates that "active-descendant-changed"
/// event is sent when children become 'active' (i.e. are selected or
/// navigated to onscreen). Used to prevent need to enumerate all children
/// in very large containers, like tables. The presence of
/// `ManagesDescendants` is an indication to the client that the
/// children should not, and need not, be enumerated by the client.
/// Objects implementing this state are expected to provide relevant state
/// notifications to listening clients, for instance notifications of
/// visibility changes and activation of their contained child objects, without
/// the client having previously requested references to those children.
ManagesDescendants,
/// Indicates that a check box or other boolean
/// indicator is in a state other than checked or not checked.
///
/// This usually means that the boolean value reflected or controlled by the
/// object does not apply consistently to the entire current context.
/// For example, a checkbox for the "Bold" attribute of text may have
/// `Indeterminate` if the currently selected text contains a mixture
/// of weight attributes. In many cases interacting with a
/// `Indeterminate` object will cause the context's corresponding
/// boolean attribute to be homogenized, whereupon the object will lose
/// `Indeterminate` and a corresponding state-changed event will be
/// fired.
Indeterminate,
/// Indicates that user interaction with this object is
/// 'required' from the user, for instance before completing the
/// processing of a form.
Required,
/// Indicates that an object's onscreen content
/// is truncated, e.g. a text value in a spreadsheet cell.
Truncated,
/// Indicates this object's visual representation is
/// dynamic, not static. This state may be applied to an object during an
/// animated 'effect' and be removed from the object once its visual
/// representation becomes static. Some applications, notably content viewers,
/// may not be able to detect all kinds of animated content. Therefore the
/// absence of this state should not be taken as
/// definitive evidence that the object's visual representation is
/// static; this state is advisory.
Animated,
/// This object has indicated an error condition
/// due to failure of input validation. For instance, a form control may
/// acquire this state in response to invalid or malformed user input.
InvalidEntry,
/// This state indicates that the object
/// in question implements some form of typeahead or
/// pre-selection behavior whereby entering the first character of one or more
/// sub-elements causes those elements to scroll into view or become
/// selected. Subsequent character input may narrow the selection further as
/// long as one or more sub-elements match the string. This state is normally
/// only useful and encountered on objects that implement [`crate::interface::Interface::Selection`].
/// In some cases the typeahead behavior may result in full or partial
/// completion of the data in the input field, in which case
/// these input events may trigger text-changed events from the source.
SupportsAutocompletion,
/// Indicates that the object in
/// question supports text selection. It should only be exposed on objects
/// which implement the [`crate::interface::Interface::Text`] interface, in order to distinguish this state
/// from [`State::Selectable`], which infers that the object in question is a
/// selectable child of an object which implements [`crate::interface::Interface::Selection`]. While
/// similar, text selection and subelement selection are distinct operations.
SelectableText,
/// Indicates that the object in question is
/// the 'default' interaction object in a dialog, i.e. the one that gets
/// activated if the user presses "Enter" when the dialog is initially
/// posted.
IsDefault,
/// Indicates that the object (typically a
/// hyperlink) has already been activated or invoked, with the result that
/// some backing data has been downloaded or rendered.
Visited,
/// Indicates this object has the potential to
/// be checked, such as a checkbox or toggle-able table cell.
Checkable,
/// Indicates that the object has a popup
/// context menu or sub-level menu which may or may not be
/// showing. This means that activation renders conditional content.
/// Note that ordinary tooltips are not considered popups in this
/// context.
HasPopup,
/// Indicates that an object which is [`State::Enabled`] and
/// [`State::Sensitive`] has a value which can be read, but not modified, by the
/// user.
ReadOnly,
}
impl State {
// "Matches on enums with undeclared discriminants (such that the compiler can choose sequential values)
// are optimized down to a jump table"
// https://users.rust-lang.org/t/match-statement-efficiency/4488/2
/// Returns the state as a static string.
#[must_use]
pub fn to_static_str(&self) -> &'static str {
match self {
State::Invalid => "invalid",
State::Active => "active",
State::Armed => "armed",
State::Busy => "busy",
State::Checked => "checked",
State::Collapsed => "collapsed",
State::Defunct => "defunct",
State::Editable => "editable",
State::Enabled => "enabled",
State::Expandable => "expandable",
State::Expanded => "expanded",
State::Focusable => "focusable",
State::Focused => "focused",
State::HasTooltip => "has-tooltip",
State::Horizontal => "horizontal",
State::Iconified => "iconified",
State::Modal => "modal",
State::MultiLine => "multi-line",
State::Multiselectable => "multiselectable",
State::Opaque => "opaque",
State::Pressed => "pressed",
State::Resizable => "resizable",
State::Selectable => "selectable",
State::Selected => "selected",
State::Sensitive => "sensitive",
State::Showing => "showing",
State::SingleLine => "single-line",
State::Stale => "stale",
State::Transient => "transient",
State::Vertical => "vertical",
State::Visible => "visible",
State::ManagesDescendants => "manages-descendants",
State::Indeterminate => "indeterminate",
State::Required => "required",
State::Truncated => "truncated",
State::Animated => "animated",
State::InvalidEntry => "invalid-entry",
State::SupportsAutocompletion => "supports-autocompletion",
State::SelectableText => "selectable-text",
State::IsDefault => "is-default",
State::Visited => "visited",
State::Checkable => "checkable",
State::HasPopup => "has-popup",
State::ReadOnly => "read-only",
}
}
}
impl fmt::Display for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.to_static_str())
}
}
impl From<String> for State {
fn from(string: String) -> State {
(&*string).into()
}
}
impl FromStr for State {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(s.into())
}
}
impl From<&str> for State {
fn from(string: &str) -> State {
match string {
"active" => State::Active,
"armed" => State::Armed,
"busy" => State::Busy,
"checked" => State::Checked,
"collapsed" => State::Collapsed,
"defunct" => State::Defunct,
"editable" => State::Editable,
"enabled" => State::Enabled,
"expandable" => State::Expandable,
"expanded" => State::Expanded,
"focusable" => State::Focusable,
"focused" => State::Focused,
"has-tooltip" => State::HasTooltip,
"horizontal" => State::Horizontal,
"iconified" => State::Iconified,
"modal" => State::Modal,
"multi-line" => State::MultiLine,
"multiselectable" => State::Multiselectable,
"opaque" => State::Opaque,
"pressed" => State::Pressed,
"resizable" => State::Resizable,
"selectable" => State::Selectable,
"selected" => State::Selected,
"sensitive" => State::Sensitive,
"showing" => State::Showing,
"single-line" => State::SingleLine,
"stale" => State::Stale,
"transient" => State::Transient,
"vertical" => State::Vertical,
"visible" => State::Visible,
"manages-descendants" => State::ManagesDescendants,
"indeterminate" => State::Indeterminate,
"required" => State::Required,
"truncated" => State::Truncated,
"animated" => State::Animated,
"invalid-entry" => State::InvalidEntry,
"supports-autocompletion" => State::SupportsAutocompletion,
"selectable-text" => State::SelectableText,
"is-default" => State::IsDefault,
"visited" => State::Visited,
"checkable" => State::Checkable,
"has-popup" => State::HasPopup,
"read-only" => State::ReadOnly,
_ => State::Invalid,
}
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
/// The bitflag representation of all states an object may have.
pub struct StateSet(BitFlags<State>);
impl StateSet {
/// Create a new `StateSet`.
///
/// ## Example
/// ```rust
/// # use atspi_common::{State, StateSet};
/// let states = State::Focusable | State::Sensitive | State::Active;
/// let set = StateSet::new(states);
///
/// assert!(set.contains(State::Active));
/// assert!(!set.contains(State::Busy));
/// ```
pub fn new<B: Into<BitFlags<State>>>(value: B) -> Self {
Self(value.into())
}
/// Returns the `StateSet` that corresponds to the provided `u64`s bit pattern.
/// # Errors
/// When the argument encodes an undefined [`State`].
pub fn from_bits(bits: u64) -> Result<StateSet, FromBitsError<State>> {
Ok(StateSet(BitFlags::from_bits(bits)?))
}
#[must_use]
/// Create an empty `StateSet`
pub fn empty() -> StateSet {
StateSet(State::empty())
}
#[must_use]
/// Returns the state as represented by a u64.
pub fn bits(&self) -> u64 {
self.0.bits()
}
/// Whether the `StateSet` contains a [`State`].
pub fn contains<B: Into<BitFlags<State>>>(self, other: B) -> bool {
self.0.contains(other)
}
/// Removes a [`State`] (optionally) previously contained in the `StateSet`.
pub fn remove<B: Into<BitFlags<State>>>(&mut self, other: B) {
self.0.remove(other);
}
/// Inserts a [`State`] in the `StateSet`.
pub fn insert<B: Into<BitFlags<State>>>(&mut self, other: B) {
self.0.insert(other);
}
/// Returns an iterator that yields each set [`State`].
#[must_use]
pub fn iter(self) -> enumflags2::Iter<State> {
self.0.iter()
}
#[must_use]
/// Checks if all states are unset.
pub fn is_empty(self) -> bool {
self.0.is_empty()
}
/// Returns true if at least one flag is shared.
pub fn intersects<B: Into<BitFlags<State>>>(self, other: B) -> bool {
self.0.intersects(other)
}
/// Toggles the matching bits.
pub fn toggle<B: Into<BitFlags<State>>>(&mut self, other: B) {
self.0.toggle(other);
}
}
impl IntoIterator for StateSet {
type IntoIter = enumflags2::Iter<State>;
type Item = State;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl IntoIterator for &StateSet {
type IntoIter = enumflags2::Iter<State>;
type Item = State;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl FromIterator<State> for StateSet {
fn from_iter<I: IntoIterator<Item = State>>(iter: I) -> Self {
StateSet(iter.into_iter().collect())
}
}
impl<'a> FromIterator<&'a State> for StateSet {
fn from_iter<I: IntoIterator<Item = &'a State>>(iter: I) -> Self {
StateSet(iter.into_iter().copied().collect())
}
}
impl<'de> Deserialize<'de> for StateSet {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct StateSetVisitor;
impl<'de> Visitor<'de> for StateSetVisitor {
type Value = StateSet;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.write_str("a sequence comprised of two u32 that represents a valid StateSet")
}
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
match <Vec<u32> as Deserialize>::deserialize(deserializer) {
Ok(states) if states.len() == 2 => {
let mut bits = u64::from(states[0]);
bits |= (u64::from(states[1])) << 32;
StateSet::from_bits(bits).map_err(|_| de::Error::custom("invalid state"))
}
Ok(states) => Err(de::Error::invalid_length(states.len(), &"array of size 2")),
Err(e) => Err(e),
}
}
}
deserializer.deserialize_newtype_struct("StateSet", StateSetVisitor)
}
}
impl Serialize for StateSet {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(2))?;
let bits = self.bits();
// This cast is safe and truncation is intentional.
//The shift is sound provided that `State` is `#[repr(u64)]`
#[allow(clippy::cast_possible_truncation)]
seq.serialize_element(&(bits as u32))?;
seq.serialize_element(&((bits >> 32) as u32))?;
seq.end()
}
}
impl Type for StateSet {
const SIGNATURE: &'static Signature = <Vec<u32> as Type>::SIGNATURE;
}
impl From<State> for StateSet {
fn from(value: State) -> Self {
Self(value.into())
}
}
impl std::ops::BitXor for StateSet {
type Output = StateSet;
fn bitxor(self, other: Self) -> Self::Output {
StateSet(self.0 ^ other.0)
}
}
impl std::ops::BitXorAssign for StateSet {
fn bitxor_assign(&mut self, other: Self) {
self.0 = self.0 ^ other.0;
}
}
impl std::ops::BitOr for StateSet {
type Output = StateSet;
fn bitor(self, other: Self) -> Self::Output {
StateSet(self.0 | other.0)
}
}
impl std::ops::BitOrAssign for StateSet {
fn bitor_assign(&mut self, other: Self) {
self.0 = self.0 | other.0;
}
}
impl std::ops::BitAnd for StateSet {
type Output = StateSet;
fn bitand(self, other: Self) -> Self::Output {
StateSet(self.0 & other.0)
}
}
impl std::ops::BitAndAssign for StateSet {
fn bitand_assign(&mut self, other: Self) {
self.0 = self.0 & other.0;
}
}
#[cfg(test)]
mod tests {
use super::{State, StateSet};
use zbus::wire::serialized::{Context, Data};
use zbus::wire::{to_bytes, LE};
#[test]
fn serialize_empty_state_set() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &StateSet::empty()).unwrap();
assert_eq!(encoded.bytes(), &[8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn deserialize_empty_state_set() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(&[8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ctxt);
let (decoded, _) = data.deserialize::<StateSet>().unwrap();
assert_eq!(decoded, StateSet::empty());
}
#[test]
fn serialize_state_set_invalid() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &StateSet::new(State::Invalid)).unwrap();
assert_eq!(encoded.bytes(), &[8, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn deserialize_state_set_invalid() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(&[8, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], ctxt);
let (decoded, _) = data.deserialize::<StateSet>().unwrap();
assert_eq!(decoded, StateSet::new(State::Invalid));
}
#[test]
fn serialize_state_set_manages_descendants() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &StateSet::new(State::ManagesDescendants)).unwrap();
assert_eq!(encoded.bytes(), &[8, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0]);
}
#[test]
fn deserialize_state_set_manages_descendants() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(&[8, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0], ctxt);
let (decoded, _) = data.deserialize::<StateSet>().unwrap();
assert_eq!(decoded, StateSet::new(State::ManagesDescendants));
}
#[test]
fn serialize_state_set_indeterminate() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &StateSet::new(State::Indeterminate)).unwrap();
assert_eq!(encoded.bytes(), &[8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]);
}
#[test]
fn deserialize_state_set_indeterminate() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(&[8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], ctxt);
let (decoded, _) = data.deserialize::<StateSet>().unwrap();
assert_eq!(decoded, StateSet::new(State::Indeterminate));
}
#[test]
fn serialize_state_set_focusable_focused() {
let ctxt = Context::new(LE, 0);
let encoded = to_bytes(ctxt, &StateSet::new(State::Focusable | State::Focused)).unwrap();
assert_eq!(encoded.bytes(), &[8, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn deserialize_state_set_focusable_focused() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(&[8, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0], ctxt);
let (decoded, _) = data.deserialize::<StateSet>().unwrap();
assert_eq!(decoded, StateSet::new(State::Focusable | State::Focused));
}
#[test]
fn cannot_deserialize_state_set_invalid_length() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(&[4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ctxt);
let decode_result = data.deserialize::<StateSet>();
assert!(decode_result.is_err());
}
#[test]
fn cannot_deserialize_state_set_invalid_flag() {
let ctxt = Context::new(LE, 0);
let data = Data::new::<&[u8]>(&[8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32], ctxt);
let decode_result = data.deserialize::<StateSet>();
assert!(decode_result.is_err());
}
#[test]
fn convert_state_direct_string() {
for state in
StateSet::from_bits(0b1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111).unwrap()
{
let state_str: String = state.to_string();
let state_two: State = state_str.clone().into();
assert_eq!(
state, state_two,
"The {state:?} was serialized as {state_str}, which deserializes to {state_two:?}"
);
}
}
#[test]
fn convert_state_direct_string_is_equal_to_serde_output() {
for state in
StateSet::from_bits(0b1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111).unwrap()
{
let serde_state_str: String = serde_plain::to_string(&state).unwrap();
let state_str: String = state.to_string();
assert_eq!(serde_state_str, state_str);
let state_two: State = serde_plain::from_str(&state_str).unwrap();
assert_eq!(state, state_two, "The {state:?} was serialized as {state_str}, which deserializes to {state_two:?} (serde)");
}
}
#[test]
fn collect_stateset_from_owned_states() {
let states = vec![State::Active, State::Focused, State::Focusable];
let set = StateSet::from_iter(states);
assert!(set.contains(State::Active));
assert!(set.contains(State::Focused));
assert!(set.contains(State::Focusable));
}
#[test]
fn collect_stateset_from_borrowed_states() {
// &[T].iter() yields &T
let states = &[State::Active, State::Focused, State::Focusable];
let set = states.iter().collect::<StateSet>();
assert!(set.contains(State::Active));
assert!(set.contains(State::Focused));
assert!(set.contains(State::Focusable));
}
#[test]
fn into_iterator_owned_stateset() {
let set = StateSet::new(State::Active | State::Focused | State::Focusable);
let states: Vec<State> = set.into_iter().collect();
assert_eq!(states.len(), 3);
assert!(states.contains(&State::Active));
assert!(states.contains(&State::Focused));
assert!(states.contains(&State::Focusable));
}
#[test]
fn into_iterator_borrowed_stateset() {
let set = StateSet::new(State::Active | State::Focused | State::Focusable);
let states: Vec<State> = (&set).into_iter().collect();
assert_eq!(states.len(), 3);
assert!(states.contains(&State::Active));
assert!(states.contains(&State::Focused));
assert!(states.contains(&State::Focusable));
}
}

1013
patches/atspi-common/xml/Accessible.xml vendored Normal file

File diff suppressed because it is too large Load diff

128
patches/atspi-common/xml/Action.xml vendored Normal file
View file

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<node xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
<!--
org.a11y.atspi.Action:
@short_description: Allows exploring and invoking the actions of a user-actionable UI component.
For example, a button may expose a "click" action; a popup menu may expose an "open"
action. Components which are not "passive" providers of UI information should
implement this interface, unless there is a more specialized interface for
interaction like org.a11y.atspi.Text or org.a11y.atspi.Value.
-->
<interface name="org.a11y.atspi.Action">
<!--
NActions: returns the number of available actions.
By convention, if there is more than one action available, the first one is
considered the "default" action of the object.
-->
<property name="NActions" type="i" access="read"/>
<!--
GetDescription:
@index: 0-based index of the action to query.
Returns: The localized description for the action at the specified @index. For
example, a screen reader will read out this description when the user asks for
extra detail on an action. For example, "Clicks the button" for the "click"
action of a button.
-->
<method name="GetDescription">
<arg type="i" name="index" direction="in"/>
<arg type="s" direction="out"/>
</method>
<!--
GetName:
@index: 0-based index of the action to query.
Returns: Machine-readable name for the action at the specified @index.
-->
<method name="GetName">
<arg type="i" name="index" direction="in"/>
<arg type="s" direction="out"/>
</method>
<!--
GetLocalizedName:
@index: 0-based index of the action to query.
Returns: A short, localized name for the action at the specified @index. This is
what screen readers will read out during normal navigation. For example, "Click"
for a button.
-->
<method name="GetLocalizedName">
<arg type="i" name="index" direction="in"/>
<arg type="s" direction="out"/>
</method>
<!--
GetKeyBinding:
@index: 0-based index of the action to query.
Gets the keybinding which can be used to activate this action, if one
exists. The string returned should contain localized, human-readable,
key sequences as they would appear when displayed on screen. It must
be in the format "mnemonic;sequence;shortcut".
- The mnemonic key activates the object if it is presently enabled onscreen.
This typically corresponds to the underlined letter within the widget.
Example: "n" in a traditional "New..." menu item or the "a" in "Apply" for
a button.
- The sequence is the full list of keys which invoke the action even if the
relevant element is not currently shown on screen. For instance, for a menu
item the sequence is the keybindings used to open the parent menus before
invoking. The sequence string is colon-delimited. Example: "Alt+F:N" in a
traditional "New..." menu item.
- The shortcut, if it exists, will invoke the same action without showing
the component or its enclosing menus or dialogs. Example: "Ctrl+N" in a
traditional "New..." menu item.
Example: For a traditional "New..." menu item, the expected return value
would be: "N;Alt+F:N;Ctrl+N" for the English locale and "N;Alt+D:N;Strg+N"
for the German locale. If, hypothetically, this menu item lacked a mnemonic,
it would be represented by ";;Ctrl+N" and ";;Strg+N" respectively.
If there is no key binding for this action, return "".
-->
<method name="GetKeyBinding">
<arg type="i" name="index" direction="in"/>
<arg type="s" direction="out"/>
</method>
<!--
GetActions:
Returns: an array of (localized_name, localized description, keybinding) for the
actions that an object supports. See the GetKeyBinding method for a description
of that field's syntax.
This is equivalent to using the methods GetLocalizedName, GetDescription,
GetKeyBinding for each action, but with a single call and thus less DBus traffic.
By convention, if there is more than one action available, the first one is
considered the "default" action of the object.
-->
<method name="GetActions">
<arg direction="out" type="a(sss)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiActionArray"/>
</method>
<!--
DoAction:
@index: 0-based index of the action to perform.
Performs the specified action on the object.
Returns: true on success, false otherwise.
-->
<method name="DoAction">
<arg direction="in" name="index" type="i"/>
<arg direction="out" type="b"/>
</method>
</interface>
</node>

View file

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<node xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
<!--
org.a11y.atspi.Application:
@short_description: Interface that must be implemented by the root object of an application.
-->
<interface name="org.a11y.atspi.Application">
<!--
ToolkitName: name of the toolkit used to implement the application's user interface.
-->
<property name="ToolkitName" type="s" access="read"/>
<!--
Version: version of the toolkit used to implement the application's user interface.
-->
<property name="Version" type="s" access="read"/>
<!--
AtspiVersion: You should return "2.1" here.
This was intended to be the version of the atspi interfaces
that the application supports, but atspi will probably move to
using versioned interface names instead. Just return "2.1" here.
-->
<property name="AtspiVersion" type="s" access="read"/>
<!--
Id: set to an arbitrary numerical id when an application registers with the registry.
When a freshly-started application uses the
org.a11y.atspi.Socket.Embed method to register with the
accessibility registry, the registry will set a numerical id
on the application.
Per https://gitlab.gnome.org/GNOME/at-spi2-core/-/issues/82 it
may turn out that this id is not actually used subsequently.
This is a remnant of the time when registryd actually had to
make up identifiers for each application. With DBus, however,
it is the bus that assigns unique names to applications that
connect to it.
Your application or toolkit can remember the Id passed when
the accessibility registry sets this property, and return it
back when the property is read.
-->
<property name="Id" type="i" access="readwrite"/>
<!-- This method is not used.
See https://gitlab.gnome.org/GNOME/orca/-/issues/260
-->
<method name="GetLocale">
<arg direction="in" name="lctype" type="u"/>
<arg direction="out" type="s"/>
</method>
</interface>
</node>

106
patches/atspi-common/xml/Cache.xml vendored Normal file
View file

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<!--
org.a11y.atspi.Cache:
@short_description: Interface to query accessible objects in bulk.
The application should expose this interface at the /org/a11y/atspi/cache object
path.
The org.a11y.atspi.Accessible interface has methods like GetChildren and
GetChildAtIndex, but these only transfer an object's DBus id. The caller has to
then query the object's properties individually. Transferring objects one by one and
then their properties produces a lot of traffic in the accessibility bus.
So, this Cache interface can be used to query objects in bulk. Assistive tech
should try to do a bulk query of all the objects in a new window with the GetItems
method, and then update them dynamically from the AddAccessible and RemoveAccessible
signals.
FIXME: Does GetItems only get called if an application implements
GetApplicationBusAddress? GTK4 doesn't implement that, but it implements GetItems -
does that ever get called?
-->
<interface name="org.a11y.atspi.Cache">
<!--
GetItems: bulk query an application's accessible objects.
Returns: an array with one element for each available object. Each element's
fields are like this:
- (so): accessible object reference - DBus name and object
path. The rest of the fields refer to this main object.
- (so): application reference - DBus name and object path. This is the owner of
the main object; the root path of the application that registered via
the Embed method of the org.a11y.atspi.Socket interface.
- (so): parent object reference - DBus name and object path.
If the main object has no parent:
- If it is a control, or a window, return the parent application.
- If the object has the application role, return a null reference. FIXME:
atk-adaptor/adaptors/cache-adaptor.c:append_cache_item() returns a
reference to the registry in this case (the one it obtained from the
initial Socket::Embed call); GTK4 returns a null reference.
- Otherwise, return a null reference ("" for the application name name and
"/org/a11y/atspi/null" for the object path).
- i: index in parent, or -1 for transient widgets/menu items. Equivalent to the
GetIndexInParent method of the org.a11y.atspi.Accessible interface.
- i: child count of main object, or -1 for defunct/menus. Equivalent to the
ChildCount property of the org.a11y.atspi.Accessible interface.
- as: array of names of the interfaces that the main object supports. Equivalent
to the GetInterfaces method of the org.a11y.atspi.Accessible interface.
- s: human-readable, localized, short name for the main object. Equivalent to the
Name property of the org.a11y.atspi.Accessible interface.
- u: role. Equivalent to the GetRole method of the org.a11y.atspi.Accessible interface.
- s: human-readable, localized description of the object in more detail.
Equivalent to the Description property of the org.a11y.atspi.Accessible interface.
- au: Set of states currently held by an object. Equivalent to the GetState
method of the org.a11y.atspi.Accessible interface.
Deprecation note: The signature for the return value of this method changed in
2015, in commit b2c8c4c7. It used to be "a((so)(so)(so)a(so)assusau)". The
"a(so)" instead of "ii" is a list of references to child objects. The
implementation in atspi-misc.c can handle either version, although the intention
is to deprecate the code that handles the old version. Qt still uses this old
signature and should be changed to the new scheme (see qspi_struct_marshallers.cpp
in the Qt source code).
-->
<method name="GetItems">
<arg direction="out" name="nodes" type="a((so)(so)(so)iiassusau)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAccessibleCacheArray"/>
</method>
<!--
AddAccessible: to be emitted when a new object is added.
See the GetItems method for a description of the signature.
-->
<signal name="AddAccessible">
<arg name="nodeAdded" type="((so)(so)(so)iiassusau)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiAccessibleCacheItem"/>
</signal>
<!--
RemoveAccessible: to be emitted when an object is no longer available.
@nodeRemoved: (so) string for the application name and object path.
-->
<signal name="RemoveAccessible">
<arg name="nodeRemoved" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/>
</signal>
</interface>
</node>

48
patches/atspi-common/xml/Collection.xml vendored Normal file
View file

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Collection">
<method name="GetMatches">
<arg direction="in" name="rule" type="(aiia{ss}iaiiasib)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiMatchRule"/>
<arg direction="in" name="sortby" type="u"/>
<arg direction="in" name="count" type="i"/>
<arg direction="in" name="traverse" type="b"/>
<arg direction="out" type="a(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiReferenceSet"/>
</method>
<method name="GetMatchesTo">
<arg direction="in" name="current_object" type="o"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/>
<arg direction="in" name="rule" type="(aiia{ss}iaiiasib)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QSpiMatchRule"/>
<arg direction="in" name="sortby" type="u"/>
<arg direction="in" name="tree" type="u"/>
<arg direction="in" name="limit_scope" type="b"/>
<arg direction="in" name="count" type="i"/>
<arg direction="in" name="traverse" type="b"/>
<arg direction="out" type="a(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiReferenceSet"/>
</method>
<method name="GetMatchesFrom">
<arg direction="in" name="current_object" type="o"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/>
<arg direction="in" name="rule" type="(aiia{ss}iaiiasib)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QSpiMatchRule"/>
<arg direction="in" name="sortby" type="u"/>
<arg direction="in" name="tree" type="u"/>
<arg direction="in" name="count" type="i"/>
<arg direction="in" name="traverse" type="b"/>
<arg direction="out" type="a(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiReferenceSet"/>
</method>
<method name="GetActiveDescendant">
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiReferenceSet"/>
</method>
</interface>
</node>

320
patches/atspi-common/xml/Component.xml vendored Normal file
View file

@ -0,0 +1,320 @@
<?xml version="1.0" encoding="UTF-8"?>
<node xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
<!--
org.a11y.atspi.Component:
@short_description: Interface for GUI components like widgets or other visible elements.
-->
<interface name="org.a11y.atspi.Component">
<!--
Contains:
@x: X coordinate of point.
@y: Y coordinate of point.
@coord_type: Whether the coordinates are relative to the screen or to the
component's top level window; see the description.
Queries whether a point (x, y) is inside the component.
The @coord_type values are as follows, and correspond to AtkCoordType:
0 - Coordinates are relative to the screen.
1 - Coordinates are relative to the component's toplevel window.
2 - Coordinates are relative to the component's immediate parent.
-->
<method name="Contains">
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="in" name="coord_type" type="u"/>
<arg direction="out" type="b"/>
</method>
<!--
GetAccessibleAtPoint:
@x: X coordinate of point.
@y: Y coordinate of point.
@coord_type: Whether the coordinates are relative to the screen or to the
component's top level window; see the description.
Gets a reference to the accessible object that contains an (x, y) pair of
coordinates.
The @coord_type values are as follows, and correspond to AtkCoordType:
0 - Coordinates are relative to the screen.
1 - Coordinates are relative to the component's toplevel window.
2 - Coordinates are relative to the component's immediate parent.
Returns: A DBus name and object reference (so) for the sought object, or a null
object reference "/org/a11y/atspi/null" if there is no object at the specified
coordinates.
-->
<method name="GetAccessibleAtPoint">
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="in" name="coord_type" type="u"/>
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<!--
GetExtents:
@coord_type: Whether the coordinates are relative to the screen or to the
component's top level window; see the description.
Queries the pixel extents of a component.
The @coord_type values are as follows, and correspond to AtkCoordType:
0 - Coordinates are relative to the screen.
1 - Coordinates are relative to the component's toplevel window.
2 - Coordinates are relative to the component's immediate parent.
Returns: a tuple (x, y, width, height) corresponding to the rectangle for the
component's extents.
-->
<method name="GetExtents">
<arg direction="in" name="coord_type" type="u"/>
<arg direction="out" type="(iiii)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiRect"/>
</method>
<!--
GetPosition:
@coord_type: Whether the coordinates are relative to the screen or to the
component's top level window; see the description.
Queries the upper-left position of a component.
The @coord_type values are as follows, and correspond to AtkCoordType:
0 - Coordinates are relative to the screen.
1 - Coordinates are relative to the component's toplevel window.
2 - Coordinates are relative to the component's immediate parent.
Returns: (x, y) coordinates of the component's upper-left corner.
-->
<method name="GetPosition">
<arg direction="in" name="coord_type" type="u"/>
<arg direction="out" name="x" type="i"/>
<arg direction="out" name="y" type="i"/>
</method>
<!--
GetSize:
Queries the pixel size of a component.
Returns: (width, height) of the component's rectangular area.
-->
<method name="GetSize">
<arg direction="out" name="width" type="i"/>
<arg direction="out" name="height" type="i"/>
</method>
<!--
GetLayer:
Queries the UI layer at which a component is rendered, which can help in
determining when components occlude one another.
The layer of a component indicates its relative stacking order with respect to the
onscreen visual representation of the UI. The layer index, in combination
with the component's extents, can be used to compute the visibility of
all or part of a component. This is important in programmatic determination of
region-of-interest for magnification, and in flat screen review models of the
screen, as well as for other uses. Objects residing in two of the
Layer categories support further z-ordering information, with
respect to their peers in the same layer: namely, WINDOW and
MDI. Relative stacking order for other objects within the same layer
is not available; the recommended heuristic is first child paints first. In other
words, assume that the first siblings in the child list are subject to being
overpainted by later siblings if their bounds intersect. The order of layers, from
bottom to top, is as follows:
0 - INVALID: Error condition.
1 - BACKGROUND: Reserved for the desktop background; this is the bottom-most
layer, over which everything else is painted.
2 - CANVAS: The 'background' layer for most content renderers and UI component containers.
3 - WIDGET: The layer in which the majority of ordinary 'foreground' widgets reside.
4 - MDI: A special layer between CANVAS and WIDGET, in which the 'pseudo-windows'
(e.g. the Multiple-Document Interface frames) reside. See the GetMDIZOrder
method.
5 - POPUP: Layer for popup window content, above WIDGET.
6 - OVERLAY: The topmost layer.
7 - WINDOW: The layer in which a toplevel window background usually resides.
-->
<method name="GetLayer">
<arg direction="out" type="u"/>
</method>
<!--
GetMDIZOrder:
Queries the Z stacking order of a component which is in the MDI or WINDOW layer,
per the GetLayer method. Bigger z-order numbers are nearer the top.
Returns: The z order of the component, or -1 if it is not in the MDI layer.
-->
<method name="GetMDIZOrder">
<arg direction="out" type="n"/>
</method>
<!--
GrabFocus:
Attempts to set the keyboard input focus to the component.
Returns: true if successful, or false otherwise.
-->
<method name="GrabFocus">
<arg direction="out" type="b"/>
</method>
<!--
GetAlpha:
Gets the opacity/alpha value of a component, if alpha blending is in use.
Returns: opacity value in the [0.0, 1.0] range. 0 is fully transparent and 1 is fully opaque.
-->
<method name="GetAlpha">
<arg direction="out" type="d"/>
</method>
<!--
SetExtents:
@x: the new horizontal position to which the component should be moved.
@y: the new vertical position to which the component should be moved.
@width: the width to which the component should be resized.
@height: the height to which the component should be resized.
@coord_type: Whether the coordinates are relative to the screen or to the
component's top level window; see the description.
Moves and resizes the component.
The @coord_type values are as follows, and correspond to AtkCoordType:
0 - Coordinates are relative to the screen.
1 - Coordinates are relative to the component's toplevel window.
2 - Coordinates are relative to the component's immediate parent.
Returns: true if successful, or false otherwise.
-->
<method name="SetExtents">
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="in" name="width" type="i"/>
<arg direction="in" name="height" type="i"/>
<arg direction="in" name="coord_type" type="u"/>
<arg direction="out" type="b"/>
</method>
<!--
SetPosition:
@x: the new horizontal position to which the component should be moved.
@y: the new vertical position to which the component should be moved.
@coord_type: Whether the coordinates are relative to the screen or to the
component's top level window; see the description.
Moves the component to the specified position.
The @coord_type values are as follows, and correspond to AtkCoordType:
0 - Coordinates are relative to the screen.
1 - Coordinates are relative to the component's toplevel window.
2 - Coordinates are relative to the component's immediate parent.
Returns: true if successful, or false otherwise.
-->
<method name="SetPosition">
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="in" name="coord_type" type="u"/>
<arg direction="out" type="b"/>
</method>
<!--
SetSize:
@width: the width to which the component should be resized.
@height: the height to which the component should be resized.
Resizes the component to the given pixel dimensions.
Returns: true if successful, or false otherwise.
-->
<method name="SetSize">
<arg direction="in" name="width" type="i"/>
<arg direction="in" name="height" type="i"/>
<arg direction="out" type="b"/>
</method>
<!--
ScrollTo:
@type: How to position the component within its parent; see the description.
Makes the component visible on the screen by scrolling all necessary parents.
The @type corresponds to AtkScrollType:
0 - TOP_LEFT: Scroll the object vertically and horizontally to bring
its top left corner to the top left corner of the window.
1 - BOTTOM_RIGHT: Scroll the object vertically and horizontally to
bring its bottom right corner to the bottom right corner of the window.
2 - TOP_EDGE: Scroll the object vertically to bring its top edge to
the top edge of the window.
3 - BOTTOM_EDGE: Scroll the object vertically to bring its bottom
edge to the bottom edge of the window.
4 - LEFT_EDGE: Scroll the object vertically and horizontally to bring
its left edge to the left edge of the window.
5 - RIGHT_EDGE: Scroll the object vertically and horizontally to
bring its right edge to the right edge of the window.
6 - ANYWHERE: Scroll the object vertically and horizontally so that
as much as possible of the object becomes visible. The exact placement is
determined by the application.
Returns: true if successful, or false otherwise.
-->
<method name="ScrollTo">
<arg direction="in" name="type" type="u"/>
<arg direction="out" type="b"/>
</method>
<!--
ScrollToPoint:
@coord_type: Whether the coordinates are relative to the screen or to the
component's top level window; see the description.
@x: X coordinate within the component to make visible.
@y: Y coordinate within the component to make visible.
Similar to the ScrollTo method, but makes a specific point from the component
visible in its parent.
The @coord_type values are as follows, and correspond to AtkCoordType:
0 - Coordinates are relative to the screen.
1 - Coordinates are relative to the component's toplevel window.
2 - Coordinates are relative to the component's immediate parent.
Returns: true if successful, or false otherwise.
-->
<method name="ScrollToPoint">
<arg direction="in" name="coord_type" type="u"/>
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="out" type="b"/>
</method>
</interface>
</node>

View file

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<node xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
<!--
org.a11y.atspi.DeviceEventController:
@short_description: Legacy interface for keystroke listeners and generation of keyboard/mouse events
This interface is being replaced by the functions in atspi-device-listener.h.
-->
<interface name="org.a11y.atspi.DeviceEventController">
<!--
RegisterKeystrokeListener:
@listener: path of object to be notified when the following keys are pressed
@keys: array of (key_code, key_sym, key_string, unused)
@mask: modifier mask in X11 style (see Xlib.h)
@types: mask of press/release; see the description below.
@mode: struct of flags (synchronous, preemptive, global), see the description below.
The @types can be a mask of the following:
* KEY_PRESS = 1 << 0
* KEY_RELEASE = 1 << 1
Note that Orca always passes (KEY_PRESS | KEY_RELEASE).
The @mode is composed of three flags (see AtspiKeyListenerSyncType):
* synchronous: Events are delivered synchronously, before
the currently focused application sees them. If false,
events may be delivered asynchronously, which means in some
cases they may already have been delivered to the
application before the AT client receives the notification.
* preemptive: (called CANCONSUME in AtspiKeyListenerSyncType)
Events may be consumed by the AT client. Requires the synchronous flag to be set.
* global: (called ALL_WINDOWS in AtspiKeyListenerSyncType)
Events are received not from the application toolkit layer,
but from the device driver or windowing system subsystem.
Returns: boolean indicating whether the operation was successful. This is always
TRUE for non-global listeners (c.f. @mode), and may be FALSE for global listeners
if the underlying XGrabKey() failed (see spi_dec_x11_grab_key).
-->
<method name="RegisterKeystrokeListener">
<arg direction="in" name="listener" type="o"/>
<arg direction="in" name="keys" type="a(iisi)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QSpiKeyTypeArray"/>
<arg direction="in" name="mask" type="u"/>
<arg direction="in" name="types" type="u"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In3" value="QSpiEventTypeArray"/>
<arg direction="in" name="mode" type="(bbb)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In4" value="QSpiEventMode"/>
<arg direction="out" type="b"/>
</method>
<method name="DeregisterKeystrokeListener">
<arg direction="in" name="listener" type="o"/>
<arg direction="in" name="keys" type="a(iisi)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QSpiKeyTypeArray"/>
<arg direction="in" name="mask" type="u"/>
<arg direction="in" name="type" type="u"/>
</method>
<method name="GetKeystrokeListeners">
<arg direction="out" type="a(souua(iisi)u(bbb))"/>
</method>
<method name="GenerateKeyboardEvent">
<arg direction="in" name="keycode" type="i"/>
<arg direction="in" name="keystring" type="s"/>
<arg direction="in" name="type" type="u"/>
</method>
<method name="GenerateMouseEvent">
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="in" name="eventName" type="s"/>
</method>
<method name="NotifyListenersSync">
<arg direction="in" name="event" type="(uiuuisb)"/>
<arg direction="out" type="b"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiDeviceEvent"/>
</method>
<method name="NotifyListenersAsync">
<arg direction="in" name="event" type="(uiuuisb)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiDeviceEvent"/>
</method>
</interface>
</node>

View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.DeviceEventListener">
<method name="NotifyEvent">
<arg direction="in" name="event" type="(uiuuisb)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiDeviceEvent"/>
<arg direction="out" type="b"/>
</method>
<signal name="KeystrokeListenerRegistered">
<arg name="listener" type="(souua(iisi)u(bbb))"/>
</signal>
<signal name="KeystrokeListenerDeregistered">
<arg name="listener" type="(souua(iisi)u(bbb))"/>
</signal>
</interface>
</node>

33
patches/atspi-common/xml/Document.xml vendored Normal file
View file

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Document">
<property name="CurrentPageNumber" type="i" access="read"/>
<property name="PageCount" type="i" access="read"/>
<method name="GetLocale">
<arg direction="out" type="s"/>
</method>
<method name="GetAttributeValue">
<arg direction="in" name="attributename" type="s"/>
<arg direction="out" type="s"/>
</method>
<method name="GetAttributes">
<arg direction="out" type="a{ss}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAttributeSet"/>
</method>
<method name="GetTextSelections">
<arg direction="out" name="selections" type="a((so)i(so)ib)"/>
</method>
<method name="SetTextSelections">
<arg direction="in" name="selections" type="a((so)i(so)ib)"/>
<arg direction="out" type="b"/>
</method>
</interface>
</node>

View file

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.EditableText">
<method name="SetTextContents">
<arg direction="in" name="newContents" type="s"/>
<arg direction="out" type="b"/>
</method>
<method name="InsertText">
<arg direction="in" name="position" type="i"/>
<arg direction="in" name="text" type="s"/>
<arg direction="in" name="length" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="CopyText">
<arg direction="in" name="startPos" type="i"/>
<arg direction="in" name="endPos" type="i"/>
</method>
<method name="CutText">
<arg direction="in" name="startPos" type="i"/>
<arg direction="in" name="endPos" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="DeleteText">
<arg direction="in" name="startPos" type="i"/>
<arg direction="in" name="endPos" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="PasteText">
<arg direction="in" name="position" type="i"/>
<arg direction="out" type="b"/>
</method>
</interface>
</node>

490
patches/atspi-common/xml/Event.xml vendored Normal file
View file

@ -0,0 +1,490 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Event.Object">
<signal name="PropertyChange">
<arg name="property" type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg name="value" type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="BoundsChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="LinkSelected">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="StateChanged">
<arg name="state" type="s"/>
<arg name="enabled" type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ChildrenChanged">
<arg name="operation" type="s"/>
<arg name="index_in_parent" type="i"/>
<arg type="i"/>
<arg name="child" type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="VisibleDataChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="SelectionChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ModelChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ActiveDescendantChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg name="child" type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Announcement">
<arg type="s"/>
<!-- politeness should be 1 (ATSPI_LIVE_POLITE) or 2
(ATSPI_LIVE_ASSERTIVE) -->
<arg type="i" name="politeness"/>
<arg type="i"/>
<!-- The variant should enclose a string with the text to be announced -->
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="AttributesChanged">
<!-- name specifies the name of the attribute that has changed, when available -->
<arg name="name" type="s"/>
<arg type="i"/>
<arg type="i"/>
<!-- The variant should include a string with the attribute's new value, when available -->
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<!-- Table events. TODO: move to Table interface? -->
<signal name="RowInserted">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="RowReordered">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="RowDeleted">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ColumnInserted">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ColumnReordered">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ColumnDeleted">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<!-- Text events. TODO: move to Text interface? -->
<signal name="TextBoundsChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="TextSelectionChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="TextChanged">
<arg name="detail" type="s"/>
<arg name="start_pos" type="i"/>
<arg name="length" type="i"/>
<arg name="text" type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="TextAttributesChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="TextCaretMoved">
<arg type="s"/>
<arg name="position" type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
</interface>
<interface name="org.a11y.atspi.Event.Window">
<signal name="PropertyChange">
<arg name="property" type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Minimize">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Maximize">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Restore">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Close">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Create">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Reparent">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="DesktopCreate">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="DesktopDestroy">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Destroy">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Activate">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Deactivate">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Raise">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Lower">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Move">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Resize">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Shade">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="uUshade">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Restyle">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
</interface>
<interface name="org.a11y.atspi.Event.Mouse">
<signal name="Abs">
<arg type="s"/>
<arg name="x" type="i"/>
<arg name="y" type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Rel">
<arg type="s"/>
<arg name="x" type="i"/>
<arg name="y" type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Button">
<arg name="detail" type="s"/>
<arg name="mouse_x" type="i"/>
<arg name="mouse_y" type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
</interface>
<interface name="org.a11y.atspi.Event.Keyboard">
<signal name="Modifiers">
<arg type="s"/>
<arg name="previous_modifiers" type="i"/>
<arg name="current_modifiers" type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
</interface>
<interface name="org.a11y.atspi.Event.Terminal">
<signal name="LineChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ColumncountChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="LinecountChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ApplicationChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="CharwidthChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
</interface>
<interface name="org.a11y.atspi.Event.Document">
<signal name="LoadComplete">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="Reload">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="LoadStopped">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="ContentChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="AttributesChanged">
<!-- name specifies the name of the attribute that has changed, when available -->
<arg name="name" type="s"/>
<arg type="i"/>
<arg type="i"/>
<!-- The variant should include a string with the attribute's new value, when available -->
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
<signal name="PageChanged">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
</interface>
<interface name="org.a11y.atspi.Event.Focus">
<!-- Focus is deprecated in favor of StateChanged with focus passed as its first argument -->
<signal name="Focus">
<arg type="s"/>
<arg type="i"/>
<arg type="i"/>
<arg type="v"/>
<arg name="properties" type="a{sv}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiEvent"/>
</signal>
</interface>
</node>

27
patches/atspi-common/xml/Hyperlink.xml vendored Normal file
View file

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Hyperlink">
<property name="NAnchors" type="n" access="read"/>
<property name="StartIndex" type="i" access="read"/>
<property name="EndIndex" type="i" access="read"/>
<method name="GetObject">
<arg direction="in" name="i" type="i"/>
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<method name="GetURI">
<arg direction="in" name="i" type="i"/>
<arg direction="out" type="s"/>
</method>
<method name="IsValid">
<arg direction="out" type="b"/>
</method>
</interface>
</node>

21
patches/atspi-common/xml/Hypertext.xml vendored Normal file
View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Hypertext">
<method name="GetNLinks">
<arg direction="out" type="i"/>
</method>
<method name="GetLink">
<arg direction="in" name="linkIndex" type="i"/>
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<method name="GetLinkIndex">
<arg direction="in" name="characterIndex" type="i"/>
<arg direction="out" type="i"/>
</method>
</interface>
</node>

27
patches/atspi-common/xml/Image.xml vendored Normal file
View file

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Image">
<property name="ImageDescription" type="s" access="read"/>
<property name="ImageLocale" type="s" access="read"/>
<method name="GetImageExtents">
<arg direction="in" name="coordType" type="u"/>
<arg direction="out" type="(iiii)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiRect"/>
</method>
<method name="GetImagePosition">
<arg direction="in" name="coordType" type="u"/>
<arg direction="out" name="x" type="i"/>
<arg direction="out" name="y" type="i"/>
</method>
<method name="GetImageSize">
<arg direction="out" name="width" type="i"/>
<arg direction="out" name="height" type="i"/>
</method>
</interface>
</node>

30
patches/atspi-common/xml/Registry.xml vendored Normal file
View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Registry">
<method name="RegisterEvent">
<arg direction="in" name="event" type="s"/>
<arg direction="in" name="properties" type="as"/>
<arg direction="in" name="app_bus_name" type="s"/>
</method>
<method name="DeregisterEvent">
<arg direction="in" name="event" type="s"/>
</method>
<method name="GetRegisteredEvents">
<arg direction="out" name="events" type="a(ss)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiEventListenerArray"/>
</method>
<signal name="EventListenerRegistered">
<arg name="bus" type="s"/>
<arg name="path" type="s"/>
</signal>
<signal name="EventListenerDeregistered">
<arg name="bus" type="s"/>
<arg name="path" type="s"/>
</signal>
</interface>
</node>

42
patches/atspi-common/xml/Selection.xml vendored Normal file
View file

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Selection">
<property name="NSelectedChildren" type="i" access="read"/>
<method name="GetSelectedChild">
<arg direction="in" name="selectedChildIndex" type="i"/>
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<method name="SelectChild">
<arg direction="in" name="childIndex" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="DeselectSelectedChild">
<arg direction="in" name="selectedChildIndex" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="IsChildSelected">
<arg direction="in" name="childIndex" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="SelectAll">
<arg direction="out" type="b"/>
</method>
<method name="ClearSelection">
<arg direction="out" type="b"/>
</method>
<method name="DeselectChild">
<arg direction="in" name="childIndex" type="i"/>
<arg direction="out" type="b"/>
</method>
</interface>
</node>

73
patches/atspi-common/xml/Socket.xml vendored Normal file
View file

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<node xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
<!--
org.a11y.atspi.Socket:
@short_description: Interface to register an application on the registry.
-->
<interface name="org.a11y.atspi.Socket">
<!--
Embed:
@plug: a string for the unique bus name of the application, and an object path
for the application's' root object.
This is the entry point for an application that wants to register itself against
the accessibility registry. The application's root object, which it passes in
@plug, must support the org.a11y.atspi.Application interface.
When an application calls this method on the registry, the following handshake happens:
* Application calls this method on the registry to identify itself.
* The registry sets the "Id" property on the org.a11y.atspi.Application interface on the @plug object.
* The Embed method returns with the bus name and object path for the registry's root object.
Returns: the bus name and object path of the registry's root object.
-->
<method name="Embed">
<arg direction="in" name="plug" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/>
<arg direction="out" name="socket" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<!--
Embedded:
@path: the object path of the socket.
This method is called by a socket to inform the plug that it is being
embedded. The plug should register the embedding socket as its parent.
-->
<method name="Embedded">
<arg direction="in" name="path" type="s"/>
</method>
<!--
Unembed:
@plug: a string for the unique bus name of the application, and an object path
for the application's' root object.
Unregisters an application from the accesibility registry. It is not necessary to
call this method; the accessibility registry detects when an application
disconnects from the bus.
-->
<method name="Unembed">
<arg direction="in" name="plug" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/>
</method>
<!--
Available:
@socket: application and object path for the registry's root object.
The accessibility registry emits this signal early during startup, when it has
registered with the DBus daemon and is available for calls from applications.
-->
<signal name="Available">
<arg name="socket" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/>
</signal>
</interface>
</node>

135
patches/atspi-common/xml/Table.xml vendored Normal file
View file

@ -0,0 +1,135 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Table">
<property name="NRows" type="i" access="read"/>
<property name="NColumns" type="i" access="read"/>
<property name="Caption" type="(so)" access="read">
<annotation name="org.qtproject.QtDBus.QtTypeName" value="QSpiObjectReference"/>
</property>
<property name="Summary" type="(so)" access="read">
<annotation name="org.qtproject.QtDBus.QtTypeName" value="QSpiObjectReference"/>
</property>
<property name="NSelectedRows" type="i" access="read"/>
<property name="NSelectedColumns" type="i" access="read"/>
<method name="GetAccessibleAt">
<arg direction="in" name="row" type="i"/>
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<method name="GetIndexAt">
<arg direction="in" name="row" type="i"/>
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="i"/>
</method>
<method name="GetRowAtIndex">
<arg direction="in" name="index" type="i"/>
<arg direction="out" type="i"/>
</method>
<method name="GetColumnAtIndex">
<arg direction="in" name="index" type="i"/>
<arg direction="out" type="i"/>
</method>
<method name="GetRowDescription">
<arg direction="in" name="row" type="i"/>
<arg direction="out" type="s"/>
</method>
<method name="GetColumnDescription">
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="s"/>
</method>
<method name="GetRowExtentAt">
<arg direction="in" name="row" type="i"/>
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="i"/>
</method>
<method name="GetColumnExtentAt">
<arg direction="in" name="row" type="i"/>
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="i"/>
</method>
<method name="GetRowHeader">
<arg direction="in" name="row" type="i"/>
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<method name="GetColumnHeader">
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/>
</method>
<method name="GetSelectedRows">
<arg direction="out" type="ai"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiIntList"/>
</method>
<method name="GetSelectedColumns">
<arg direction="out" type="ai"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiIntList"/>
</method>
<method name="IsRowSelected">
<arg direction="in" name="row" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="IsColumnSelected">
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="IsSelected">
<arg direction="in" name="row" type="i"/>
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="AddRowSelection">
<arg direction="in" name="row" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="AddColumnSelection">
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="RemoveRowSelection">
<arg direction="in" name="row" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="RemoveColumnSelection">
<arg direction="in" name="column" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="GetRowColumnExtentsAtIndex">
<arg direction="in" name="index" type="i"/>
<arg direction="out" type="b"/>
<arg direction="out" name="row" type="i"/>
<arg direction="out" name="col" type="i"/>
<arg direction="out" name="row_extents" type="i"/>
<arg direction="out" name="col_extents" type="i"/>
<arg direction="out" name="is_selected" type="b"/>
</method>
</interface>
</node>

45
patches/atspi-common/xml/TableCell.xml vendored Normal file
View file

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.TableCell">
<property access="read" name="ColumnSpan" type="i" />
<property access="read" name="Position" type="(ii)">
<annotation name="org.qtproject.QtDBus.QtTypeName" value="QPoint"/>
</property>
<property access="read" name="RowSpan" type="i" />
<property access="read" name="Table" type="(so)" >
<annotation name="org.qtproject.QtDBus.QtTypeName" value="QSpiObjectReference"/>
</property>
<method name="GetRowColumnSpan">
<arg direction="out" type="b" />
<arg direction="out" name="row" type="i" />
<arg direction="out" name="col" type="i" />
<arg direction="out" name="row_extents" type="i" />
<arg direction="out" name="col_extents" type="i" />
</method>
<!--
GetColumnHeaderCells:
Returns a list of the table cell's column header cells.
-->
<method name="GetColumnHeaderCells">
<arg direction="out" type="a(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReferenceArray"/>
</method>
<!--
GetRowHeaderCells:
Returns a list of the table cell's row header cells.
-->
<method name="GetRowHeaderCells">
<arg direction="out" type="a(so)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReferenceArray"/>
</method>
</interface>
</node>

179
patches/atspi-common/xml/Text.xml vendored Normal file
View file

@ -0,0 +1,179 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Text">
<property name="CharacterCount" type="i" access="read"/>
<property name="CaretOffset" type="i" access="read"/>
<method name="GetStringAtOffset">
<arg direction="in" name="offset" type="i"/>
<arg direction="in" name="granularity" type="u"/>
<arg direction="out" type="s"/>
<arg direction="out" name="startOffset" type="i"/>
<arg direction="out" name="endOffset" type="i"/>
</method>
<method name="GetText">
<arg direction="in" name="startOffset" type="i"/>
<arg direction="in" name="endOffset" type="i"/>
<arg direction="out" type="s"/>
</method>
<method name="SetCaretOffset">
<arg direction="in" name="offset" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="GetTextBeforeOffset">
<arg direction="in" name="offset" type="i"/>
<arg direction="in" name="type" type="u"/>
<arg direction="out" type="s"/>
<arg direction="out" name="startOffset" type="i"/>
<arg direction="out" name="endOffset" type="i"/>
</method>
<!--
GetTextAtOffset:
Returns the text at the given offset.
Deprecated: Use GetStringAtOffset.
-->
<method name="GetTextAtOffset">
<arg direction="in" name="offset" type="i"/>
<arg direction="in" name="type" type="u"/>
<arg direction="out" type="s"/>
<arg direction="out" name="startOffset" type="i"/>
<arg direction="out" name="endOffset" type="i"/>
</method>
<method name="GetTextAfterOffset">
<arg direction="in" name="offset" type="i"/>
<arg direction="in" name="type" type="u"/>
<arg direction="out" type="s"/>
<arg direction="out" name="startOffset" type="i"/>
<arg direction="out" name="endOffset" type="i"/>
</method>
<method name="GetCharacterAtOffset">
<arg direction="in" name="offset" type="i"/>
<arg direction="out" type="i"/>
</method>
<method name="GetAttributeValue">
<arg direction="in" name="offset" type="i"/>
<arg direction="in" name="attributeName" type="s"/>
<arg direction="out" type="s"/>
</method>
<method name="GetAttributes">
<arg direction="in" name="offset" type="i"/>
<arg direction="out" type="a{ss}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAttributeSet"/>
<arg direction="out" name="startOffset" type="i"/>
<arg direction="out" name="endOffset" type="i"/>
</method>
<method name="GetDefaultAttributes">
<arg direction="out" type="a{ss}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAttributeSet"/>
</method>
<method name="GetCharacterExtents">
<arg direction="in" name="offset" type="i"/>
<arg direction="in" name="coordType" type="u"/>
<arg direction="out" name="x" type="i"/>
<arg direction="out" name="y" type="i"/>
<arg direction="out" name="width" type="i"/>
<arg direction="out" name="height" type="i"/>
</method>
<method name="GetOffsetAtPoint">
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="in" name="coordType" type="u"/>
<arg direction="out" type="i"/>
</method>
<method name="GetNSelections">
<arg direction="out" type="i"/>
</method>
<method name="GetSelection">
<arg direction="in" name="selectionNum" type="i"/>
<arg direction="out" name="startOffset" type="i"/>
<arg direction="out" name="endOffset" type="i"/>
</method>
<method name="AddSelection">
<arg direction="in" name="startOffset" type="i"/>
<arg direction="in" name="endOffset" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="RemoveSelection">
<arg direction="in" name="selectionNum" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="SetSelection">
<arg direction="in" name="selectionNum" type="i"/>
<arg direction="in" name="startOffset" type="i"/>
<arg direction="in" name="endOffset" type="i"/>
<arg direction="out" type="b"/>
</method>
<method name="GetRangeExtents">
<arg direction="in" name="startOffset" type="i"/>
<arg direction="in" name="endOffset" type="i"/>
<arg direction="in" name="coordType" type="u"/>
<arg direction="out" name="x" type="i"/>
<arg direction="out" name="y" type="i"/>
<arg direction="out" name="width" type="i"/>
<arg direction="out" name="height" type="i"/>
</method>
<method name="GetBoundedRanges">
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="in" name="width" type="i"/>
<arg direction="in" name="height" type="i"/>
<arg direction="in" name="coordType" type="u"/>
<arg direction="in" name="xClipType" type="u"/>
<arg direction="in" name="yClipType" type="u"/>
<arg direction="out" type="a(iisv)"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiRangeList"/>
</method>
<method name="GetAttributeRun">
<arg direction="in" name="offset" type="i"/>
<arg direction="in" name="includeDefaults" type="b"/>
<arg direction="out" type="a{ss}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAttributeSet"/>
<arg direction="out" name="startOffset" type="i"/>
<arg direction="out" name="endOffset" type="i"/>
</method>
<method name="GetDefaultAttributeSet">
<arg direction="out" type="a{ss}"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAttributeSet"/>
</method>
<method name="ScrollSubstringTo">
<arg direction="in" name="startOffset" type="i"/>
<arg direction="in" name="endOffset" type="i"/>
<arg direction="in" name="type" type="u"/>
<arg direction="out" type="b"/>
</method>
<method name="ScrollSubstringToPoint">
<arg direction="in" name="startOffset" type="i"/>
<arg direction="in" name="endOffset" type="i"/>
<arg direction="in" name="type" type="u"/>
<arg direction="in" name="x" type="i"/>
<arg direction="in" name="y" type="i"/>
<arg direction="out" type="b"/>
</method>
</interface>
</node>

16
patches/atspi-common/xml/Value.xml vendored Normal file
View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<node>
<interface name="org.a11y.atspi.Value">
<property name="MinimumValue" type="d" access="read"/>
<property name="MaximumValue" type="d" access="read"/>
<property name="MinimumIncrement" type="d" access="read"/>
<property name="CurrentValue" type="d" access="readwrite"/>
<property name="Text" type="s" access="read"/>
</interface>
</node>

View file

@ -0,0 +1,100 @@
import xml.etree.ElementTree as ET
tree = ET.parse("../xml/Event.xml")
root = tree.getroot()
RUST_TYPE_FROM_DBUS_TYPE = {
"s": "String",
"i": "i32",
"u": "u32",
"v": "&zvariant::OwnedValue",
"a{sv}": "&std::collections::HashMap<String, zvariant::OwnedValue>",
"o": "OwnedPath"
}
ARG_IDENT_FROM_NUMBER = [
"kind",
"detail1",
"detail2",
"any_data",
"properties"
]
# will store lists of members with their various details. Will output a markdown table.
interfaces = []
def print_interface_table(signals):
print(f"/// Event table for the contained types:\n///")
print(f"/// Interface|Member|Kind|Detail 1|Detail 2|Any Data|Properties")
print(f"/// |:--|---|---|---|---|---|---|")
for signal in signals:
interface = signal["interface"].replace("Event", "")
member = signal["member"]
kind = signal["kind"]["name"] or " "
detail1 = signal["detail1"]["name"] or " "
detail2 = signal["detail2"]["name"] or " "
data = signal["any_data"]["name"] or " "
properties = signal["properties"]["name"]
print(f"/// |{interface}|{member}|{kind}|{detail1}|{detail2}|{data}|{properties}|")
def impl_functions(signal):
iface = signal["interface"].replace("Event", "")
impl_member = signal["member"]
print(f"impl {impl_member}Event {{")
for (zbus_name, struct_name) in signal.items():
if zbus_name in ARG_IDENT_FROM_NUMBER and struct_name["name"]:
rust_type = RUST_TYPE_FROM_DBUS_TYPE[struct_name["type"]]
print(f"\t#[must_use]")
print(f"\tpub fn {struct_name['name']}(&self) -> {rust_type} {{")
if rust_type == "String":
print(f"\t\tself.0.{zbus_name}().to_string()")
else:
print(f"\t\tself.0.{zbus_name}()")
print(f"}}")
print(f"}}")
for interface in root:
interface_name = interface.attrib["name"].split(".")[-1]
enum_name = interface_name + "Event"
print(f"pub mod {interface_name.lower()} {{")
print("use zbus::zvariant;")
enum = f"pub enum {enum_name}s {{\n"
# will contain all the attributes to use for markdown table
signals = []
structs = []
for signal in interface:
signal_identities = dict()
variant_name = signal.attrib["name"]
signal_identities["interface"] = enum_name
signal_identities["member"] = variant_name
enum += f"\t{variant_name}({variant_name}Event),\n"
struct = f"//#[derive(Debug, Clone)]\n"
struct += f"pub struct {variant_name}Event(crate::events::AtspiEvent);"
for (argi, arg) in enumerate(signal):
# ignore <annotation> tags for QSPI
if arg.tag != "arg":
continue
signal_identities[ARG_IDENT_FROM_NUMBER[argi]] = {"name":None,"type":None}
# skip getting additional info if the name of the arg is not specified (trhis means it is not used)
if "name" not in arg.attrib:
continue
field_name = arg.attrib["name"]
field_type = arg.attrib["type"]
rust_type = RUST_TYPE_FROM_DBUS_TYPE[field_type]
signal_identities[ARG_IDENT_FROM_NUMBER[argi]] = arg.attrib
# do not put struct items, use methods instead
#struct += f"\t{field_name}: {rust_type},\n"
signals.append(signal_identities)
#struct += "}"
structs.append(struct)
enum += "}"
interfaces.append(signals)
for (struct, signal) in zip(structs, signals):
print(struct)
impl_functions(signal)
print_interface_table(signals)
print(enum)
# close the module
print("}")

View file

@ -0,0 +1,96 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
version = "1.1"
elementFormDefault = "qualified"
xmlns:dbus="dbus">
<xsd:element name="node">
<xsd:complexType>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="node"/>
<xsd:element ref="interface"/>
</xsd:choice>
<xsd:attribute name="name" type="xsd:string" use="optional"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="interface">
<xsd:complexType>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="method"/>
<xsd:element ref="signal"/>
<xsd:element ref="property"/>
<xsd:element ref="annotation"/>
</xsd:choice>
<xsd:attribute name="name" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="method">
<xsd:complexType>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="arg"/>
<xsd:element ref="annotation"/>
</xsd:choice>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<!--<xsd:attribute name="name" type="xsd:string" use="required"/>-->
</xsd:complexType>
</xsd:element>
<xsd:element name="signal">
<xsd:complexType>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="arg"/>
<xsd:element ref="annotation"/>
</xsd:choice>
<xsd:attribute name="name" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
<xsd:simpleType name="direction">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="in"/>
<xsd:enumeration value="out"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="type">
<xsd:restriction base="xsd:string">
<xsd:pattern value = "[abdeghinoqstuxy(){}]+"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:element name="arg">
<xsd:complexType>
<xsd:attribute name="direction" type="direction" default="in"/>
<xsd:attribute name="name" type="xsd:string" use="optional"/>
<xsd:attribute name="type" type="type"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="property">
<xsd:complexType>
<xsd:sequence minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="annotation"/>
</xsd:sequence>
<xsd:attribute name="access" use="required">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="read"/>
<xsd:enumeration value="write"/>
<xsd:enumeration value="readwrite"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:attribute name="type" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="annotation">
<xsd:complexType>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:attribute name="value" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>

1560
patches/atspi-common/xml/schemas/Types.xml vendored Normal file

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more