ui_automation/
ui_automation.rs

1// Copyright (C) 2024 Tristan Gerritsen <tristan@thewoosh.org>
2// All Rights Reserved.
3
4use std::sync::Arc;
5
6use crate::{create_backend, Application, Backend, Position, UIResult};
7
8/// The top-level access to the UI.
9///
10/// ```
11/// # use ui_automation::UIAutomation;
12/// let automation = UIAutomation::new();
13///
14/// for app in automation.applications() {
15///     println!("Window \"{}\"", app.name());
16/// }
17/// ```
18#[derive(Debug, Clone)]
19pub struct UIAutomation {
20    backend: Arc<dyn Backend>,
21}
22
23impl UIAutomation {
24    pub fn new() -> Self {
25        Self::try_new().unwrap()
26    }
27
28    #[must_use]
29    pub fn backend_name(&self) -> &str {
30        self.backend.name()
31    }
32
33    pub fn mouse_position(&self) -> Position {
34        self.backend.get_mouse_position().unwrap_or_default()
35    }
36
37    pub fn set_cursor_position(&self, position: impl Into<Position>) {
38        self.backend.set_mouse_position(position.into()).unwrap();
39    }
40
41    pub fn applications(&self) -> Vec<Application> {
42        self.try_applications().unwrap()
43    }
44
45    pub fn try_new() -> UIResult<Self> {
46        Ok(Self {
47            backend: create_backend()?,
48        })
49    }
50
51    pub fn try_mouse_position(&self) -> UIResult<Position> {
52        self.backend.get_mouse_position()
53    }
54
55    pub fn try_set_cursor_position(&self, position: impl Into<Position>) -> UIResult<()> {
56        self.backend.set_mouse_position(position.into())
57    }
58
59    pub fn try_applications(&self) -> UIResult<Vec<Application>> {
60        self.backend.applications(self.backend.clone())
61    }
62}