Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(desktop): add a `WindowsBroker` and use the Automation API to read text from apps (#4174)

Elijah Potter64ad5bdaf440
diff --git a/Cargo.lock b/Cargo.lock
index 70600fecf..fb2818634 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4200,6 +4200,7 @@ dependencies = [
"egui_commonmark",
"harper-core",
"harper-dictionary-wordlist",
+ "is-macro",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"pollster",
@@ -4215,6 +4216,8 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
+ "uiautomation",
+ "windows 0.62.2",
"winit",
]
@@ -9933,6 +9936,29 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "uiautomation"
+version = "0.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c68495a701b9f2f21f29353ac446f0d27dd0d7ce97aa9ccf9061bca0446cd744"
+dependencies = [
+ "chrono",
+ "uiautomation_derive",
+ "windows 0.62.2",
+ "windows-core 0.62.2",
+]
+
+[[package]]
+name = "uiautomation_derive"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffcc4d404aa1c03a848f95cf5feadc3e63946d7f095bf388770b85550093d388"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "unic-char-property"
version = "0.9.0"
diff --git a/harper-desktop/src-tauri/Cargo.toml b/harper-desktop/src-tauri/Cargo.toml
index 84b25c5fe..0a4cba2d8 100644
--- a/harper-desktop/src-tauri/Cargo.toml
+++ b/harper-desktop/src-tauri/Cargo.toml
@@ -47,6 +47,7 @@ tauri-plugin-os = "2.3.2"
cached = "2.0.2"
tracing = "0.1.44"
tracing-subscriber = "0.3.23"
+is-macro = "0.3.7"
[target.'cfg(target_os = "macos")'.dependencies]
accessibility = "0.2.0"
@@ -65,9 +66,16 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = [
accessibility-sys = "0.2.0"
core-graphics = "0.25.0"
+[target.'cfg(target_os = "windows")'.dependencies]
+windows = { version = "0.62.2", features = ["Win32_UI_HiDpi"] }
+uiautomation = { version = "0.25.0", features = ["process"] }
+
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
tauri-plugin-autostart = "2.5.1"
tauri-plugin-updater = "2"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-updater = "2"
+
+[profile.release]
+debug = true
\ No newline at end of file
diff --git a/harper-desktop/src-tauri/src/highlighter/render_state.rs b/harper-desktop/src-tauri/src/highlighter/render_state.rs
index dc2a0573a..446a03fd0 100644
--- a/harper-desktop/src-tauri/src/highlighter/render_state.rs
+++ b/harper-desktop/src-tauri/src/highlighter/render_state.rs
@@ -122,10 +122,7 @@ impl RenderState {
self.highlighted_lint = None;
}
- /// Finds the interactive highlighter region under a screen-space cursor position.
- ///
- /// Cursor polling lives outside the renderer, but hit-testing belongs next to the rectangles and
- /// popup geometry being rendered so both paths use the same layout contract.
+ /// Checks if a given position touches a hit target.
pub fn hit_target_at_pos(&self, pos: egui::Pos2) -> HitTarget {
if self.popup_rect().is_some_and(|rect| rect.contains(pos)) {
return HitTarget::Popup;
diff --git a/harper-desktop/src-tauri/src/highlighter/window_manager.rs b/harper-desktop/src-tauri/src/highlighter/window_manager.rs
index 5214f6ed9..de6f3924d 100644
--- a/harper-desktop/src-tauri/src/highlighter/window_manager.rs
+++ b/harper-desktop/src-tauri/src/highlighter/window_manager.rs
@@ -177,6 +177,7 @@ impl WindowManagerApp {
};
let hit_target = self.render_state.hit_target_at_pos(cursor_pos);
+
self.hovered_lint = match hit_target {
HitTarget::Lint(index) => Some(index),
HitTarget::Popup | HitTarget::None => None,
diff --git a/harper-desktop/src-tauri/src/lib.rs b/harper-desktop/src-tauri/src/lib.rs
index 7bb6ddc06..0630b4163 100644
--- a/harper-desktop/src-tauri/src/lib.rs
+++ b/harper-desktop/src-tauri/src/lib.rs
@@ -45,6 +45,9 @@ pub mod rect;
#[cfg(target_os = "macos")]
mod mac_broker;
+#[cfg(target_os = "windows")]
+mod windows_broker;
+
#[derive(Parser)]
struct Args {
#[command(subcommand)]
@@ -343,7 +346,10 @@ pub fn run_highlighter(has_parent: bool) {
#[cfg(target_os = "macos")]
let broker = mac_broker::MacBroker::new(integrations);
- #[cfg(not(target_os = "macos"))]
+ #[cfg(target_os = "windows")]
+ let broker = windows_broker::WindowsBroker::new();
+
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
let broker = os_broker::NoopBroker;
if let Err(error) = Highlighter::new(
diff --git a/harper-desktop/src-tauri/src/windows_broker/automation_service.rs b/harper-desktop/src-tauri/src/windows_broker/automation_service.rs
new file mode 100644
index 000000000..4a385c873
--- /dev/null
+++ b/harper-desktop/src-tauri/src/windows_broker/automation_service.rs
@@ -0,0 +1,420 @@
+use std::fmt::Arguments;
+use std::iter::once;
+use std::sync::mpsc::{Receiver, Sender, SyncSender, TryRecvError, TrySendError, sync_channel};
+use std::thread::{JoinHandle, sleep};
+use std::time::{Duration, Instant};
+
+use crate::rect::Rect;
+use crate::windows_broker::get_focused_monitor_scale;
+use harper_core::Span;
+use is_macro::Is;
+use uiautomation::types::{TextPatternRangeEndpoint, TextUnit};
+use uiautomation::{UIAutomation, UIElement, patterns::UITextPattern};
+use windows::Win32::Foundation::HWND;
+use windows::Win32::Graphics::Gdi::{
+ MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, MonitorFromWindow,
+};
+use windows::Win32::UI::Accessibility::IUIAutomationTextRange;
+use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};
+use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
+
+/// Information about a worker thread.
+struct WorkerData {
+ thread_handle: JoinHandle<()>,
+ sender: SyncSender<(WorkerJob, Vec<JobArgument>)>,
+ receiver: Receiver<JobResult>,
+}
+
+#[derive(Debug, Is)]
+enum JobArgument {
+ Span(Span<char>),
+ Window(isize, bool),
+}
+
+/// The result of a job run by the worker thread.
+#[derive(Debug, Is)]
+enum JobResult {
+ String(String),
+ GroupedRects(Vec<Vec<Rect>>),
+ Err,
+}
+
+struct CachedTextElement {
+ window: isize,
+ element: UIElement,
+}
+
+struct WorkerState {
+ automation: UIAutomation,
+ cached_text_element: Option<CachedTextElement>,
+}
+
+impl WorkerState {
+ fn cached_element_for_window(&self, window: isize) -> Option<UIElement> {
+ self.cached_text_element
+ .as_ref()
+ .filter(|cached| cached.window == window)
+ .map(|cached| cached.element.clone())
+ }
+
+ fn clear_cached_element(&mut self) {
+ self.cached_text_element = None;
+ }
+}
+
+/// An actual function pointer to be run by the worker thread.
+type WorkerJob = fn(&mut WorkerState, Vec<JobArgument>) -> JobResult;
+
+/// Runs and communicates with a worker thread to interact with the Win32 Automation API to query the accessibility tree.
+/// Necessary because the API has very specific thread setting requirements to work.
+pub struct AutomationService {
+ worker_data: Option<WorkerData>,
+ // Needed to redirect focus to the last focused window when the focus arrives on the Harper highlighter window
+ last_focused_window: Option<isize>,
+}
+
+impl AutomationService {
+ pub fn create_and_start() -> Self {
+ let mut output = Self {
+ last_focused_window: None,
+ worker_data: None,
+ };
+
+ output.start_worker_thread();
+
+ output
+ }
+
+ /// Starts the worker thread if it is not already running.
+ /// Does nothing if the worker thread is already running.
+ fn start_worker_thread(&mut self) {
+ let (job_sender, job_receiver) = sync_channel::<(WorkerJob, Vec<JobArgument>)>(1);
+ let (result_sender, result_receiver) = sync_channel(1);
+
+ let handle = std::thread::spawn(move || {
+ let mut state = WorkerState {
+ automation: UIAutomation::new().unwrap(),
+ cached_text_element: None,
+ };
+
+ loop {
+ // Stop the thread if the other side of the channel has been closed (or dropped).
+ let job = match job_receiver.try_recv() {
+ Err(TryRecvError::Disconnected) => break,
+ Err(TryRecvError::Empty) => None,
+ Ok(job) => Some(job),
+ };
+
+ if let Some((job, arguments)) = job {
+ let result = job(&mut state, arguments);
+
+ // Stop the thread if the other side of the channel has been closed (or dropped).
+ if let Err(err) = result_sender.try_send(result) {
+ if let TrySendError::Disconnected(_) = err {
+ break;
+ }
+ }
+ }
+
+ sleep(Duration::from_millis(16));
+ }
+ });
+
+ self.worker_data = Some(WorkerData {
+ receiver: result_receiver,
+ sender: job_sender,
+ thread_handle: handle,
+ });
+ }
+
+ /// Stops the worker thread if it is running. This method does nothing if it is not running.
+ fn stop_worker_thread(&mut self) {
+ // This drops the inner fields, which closes the channel, which signals to the worker to stop running.
+ self.worker_data = None;
+ }
+
+ /// Attempts to run a worker job on the worker thread. Returns `None` if the worker thread does not exist.
+ fn run_worker_job(&self, job: WorkerJob, arguments: Vec<JobArgument>) -> Option<JobResult> {
+ let worker_data = self.worker_data.as_ref()?;
+ worker_data.sender.send((job, arguments)).unwrap();
+ Some(worker_data.receiver.recv().unwrap())
+ }
+
+ /// Grab text from the worker.
+ /// Attempts to get the most up-to-date information possible.
+ /// Returns `None` if the worker is not running.
+ pub fn get_text(&mut self) -> Option<String> {
+ let (window, use_cached_element) = self.resolve_focused_window()?;
+ let result = self.run_worker_job(
+ get_text_job,
+ vec![JobArgument::Window(window, use_cached_element)],
+ )?;
+
+ match result {
+ JobResult::String(text) => Some(text),
+ _ => {
+ self.last_focused_window = None;
+ None
+ }
+ }
+ }
+
+ /// Pass a collection of text spans to the worker and have it compute the associated bounding boxes for each span.
+ /// Each span may have multiple bounding boxes.
+ /// Input spans share the same index as their output bounding box.
+ pub fn get_bounding_boxes(
+ &mut self,
+ spans: impl IntoIterator<Item = Span<char>>,
+ ) -> Option<Vec<Vec<Rect>>> {
+ let (window, use_cached_element) = self.resolve_focused_window()?;
+
+ let result = self.run_worker_job(
+ get_bounding_rect_job,
+ once(JobArgument::Window(window, use_cached_element))
+ .chain(spans.into_iter().map(|s| JobArgument::Span(s)))
+ .collect(),
+ )?;
+
+ match result {
+ JobResult::GroupedRects(rects) => Some(rects),
+ _ => {
+ self.last_focused_window = None;
+ None
+ }
+ }
+ }
+
+ fn resolve_focused_window(&mut self) -> Option<(isize, bool)> {
+ let (focused_window, focused_process_id) = focused_window()?;
+
+ if focused_process_id == std::process::id() {
+ return self.last_focused_window.map(|window| (window, true));
+ }
+
+ self.last_focused_window = Some(focused_window);
+ Some((focused_window, false))
+ }
+}
+
+fn get_text(element: &UIElement) -> uiautomation::Result<String> {
+ let pattern: UITextPattern = element.get_pattern()?;
+ let range = pattern.get_document_range()?;
+ range.get_text(-1)
+}
+
+fn get_text_job(state: &mut WorkerState, args: Vec<JobArgument>) -> JobResult {
+ let Some(JobArgument::Window(window, use_cached_element)) = args.first() else {
+ return JobResult::Err;
+ };
+ let element = if *use_cached_element {
+ let Some(element) = state.cached_element_for_window(*window) else {
+ return JobResult::Err;
+ };
+ element
+ } else {
+ let Ok(element) = state.automation.get_focused_element() else {
+ state.clear_cached_element();
+ return JobResult::Err;
+ };
+ element
+ };
+
+ match get_text(&element) {
+ Ok(text) => {
+ state.cached_text_element = Some(CachedTextElement {
+ window: *window,
+ element,
+ });
+ JobResult::String(text)
+ }
+ Err(_) => {
+ state.clear_cached_element();
+ JobResult::Err
+ }
+ }
+}
+
+use std::{ffi::c_void, mem::size_of};
+
+use uiautomation::{Error, Result};
+use windows::Win32::System::{
+ Com::SAFEARRAY,
+ Ole::{
+ SafeArrayDestroy, SafeArrayGetDim, SafeArrayGetElement, SafeArrayGetElemsize,
+ SafeArrayGetLBound, SafeArrayGetUBound,
+ },
+};
+
+struct OwnedSafeArray(*mut SAFEARRAY);
+
+impl Drop for OwnedSafeArray {
+ fn drop(&mut self) {
+ if !self.0.is_null() {
+ unsafe {
+ let _ = SafeArrayDestroy(self.0);
+ }
+ }
+ }
+}
+
+fn bounding_rectangles_for_span(
+ element: &UIElement,
+ start: i32,
+ len: i32,
+) -> Result<Vec<(f64, f64, f64, f64)>> {
+ if start < 0 || len < 0 {
+ return Err(Error::new(
+ uiautomation::errors::ERR_INVALID_ARG,
+ "start and len must be non-negative",
+ ));
+ }
+
+ let pattern: UITextPattern = element.get_pattern()?;
+ let range = pattern.get_document_range()?;
+
+ range.move_endpoint_by_range(
+ TextPatternRangeEndpoint::End,
+ &range,
+ TextPatternRangeEndpoint::Start,
+ )?;
+
+ range.move_endpoint_by_unit(TextPatternRangeEndpoint::Start, TextUnit::Character, start)?;
+
+ range.move_endpoint_by_range(
+ TextPatternRangeEndpoint::End,
+ &range,
+ TextPatternRangeEndpoint::Start,
+ )?;
+
+ range.move_endpoint_by_unit(TextPatternRangeEndpoint::End, TextUnit::Character, len)?;
+
+ let raw: &IUIAutomationTextRange = range.as_ref();
+ let array = OwnedSafeArray(unsafe { raw.GetBoundingRectangles()? });
+
+ if array.0.is_null() {
+ return Ok(Vec::new());
+ }
+
+ let dim = unsafe { SafeArrayGetDim(array.0) };
+
+ if dim != 1 {
+ return Err(Error::new(
+ uiautomation::errors::ERR_FORMAT,
+ "bounding rectangles SAFEARRAY is not one-dimensional",
+ ));
+ }
+
+ let elem_size = unsafe { SafeArrayGetElemsize(array.0) };
+
+ if elem_size as usize != size_of::<f64>() {
+ return Err(Error::new(
+ uiautomation::errors::ERR_FORMAT,
+ "bounding rectangles SAFEARRAY does not contain f64-sized elements",
+ ));
+ }
+
+ let lower = unsafe { SafeArrayGetLBound(array.0, 1)? };
+ let upper = unsafe { SafeArrayGetUBound(array.0, 1)? };
+
+ if upper < lower {
+ return Ok(Vec::new());
+ }
+
+ let count = usize::try_from(i64::from(upper) - i64::from(lower) + 1)
+ .map_err(|_| Error::new(uiautomation::errors::ERR_FORMAT, "SAFEARRAY is too large"))?;
+
+ if count % 4 != 0 {
+ return Err(Error::new(
+ uiautomation::errors::ERR_FORMAT,
+ "bounding rectangles SAFEARRAY length is not divisible by four",
+ ));
+ }
+
+ let mut result = Vec::with_capacity(count / 4);
+
+ for rect in 0..count / 4 {
+ let mut values = [0.0_f64; 4];
+
+ for (component, value) in values.iter_mut().enumerate() {
+ let offset = rect
+ .checked_mul(4)
+ .and_then(|n| n.checked_add(component))
+ .ok_or_else(|| {
+ Error::new(uiautomation::errors::ERR_FORMAT, "SAFEARRAY index overflow")
+ })?;
+
+ let index = i64::from(lower)
+ .checked_add(i64::try_from(offset).map_err(|_| {
+ Error::new(uiautomation::errors::ERR_FORMAT, "SAFEARRAY index overflow")
+ })?)
+ .and_then(|n| i32::try_from(n).ok())
+ .ok_or_else(|| {
+ Error::new(uiautomation::errors::ERR_FORMAT, "SAFEARRAY index overflow")
+ })?;
+
+ unsafe {
+ SafeArrayGetElement(array.0, &index, value as *mut f64 as *mut c_void)?;
+ }
+ }
+
+ result.push((values[0], values[1], values[2], values[3]));
+ }
+
+ Ok(result)
+}
+
+fn get_bounding_rect_job(state: &mut WorkerState, arguments: Vec<JobArgument>) -> JobResult {
+ let Some(JobArgument::Window(window, _)) = arguments.first() else {
+ return JobResult::Err;
+ };
+ let Some(text_element) = state.cached_element_for_window(*window) else {
+ return JobResult::Err;
+ };
+
+ let effective_monitor_scale = get_focused_monitor_scale();
+
+ let mut rects = Vec::with_capacity(arguments.len() - 1);
+
+ for span in arguments.into_iter().skip(1) {
+ let span = span.expect_span();
+
+ let Ok(found_rects) =
+ bounding_rectangles_for_span(&text_element, span.start as i32, span.len() as i32)
+ else {
+ state.clear_cached_element();
+ return JobResult::Err;
+ };
+
+ rects.push(
+ found_rects
+ .iter()
+ .map(|(x, y, w, h)| {
+ Rect::new(
+ *x / effective_monitor_scale,
+ *y / effective_monitor_scale,
+ *w / effective_monitor_scale,
+ *h / effective_monitor_scale,
+ )
+ })
+ .collect(),
+ );
+ }
+
+ JobResult::GroupedRects(rects)
+}
+
+fn focused_window() -> Option<(isize, u32)> {
+ let hwnd: HWND = unsafe { GetForegroundWindow() };
+
+ if hwnd.0.is_null() {
+ return None;
+ }
+
+ let mut process_id = 0;
+
+ unsafe {
+ GetWindowThreadProcessId(hwnd, Some(&mut process_id));
+ }
+
+ Some((hwnd.0 as isize, process_id))
+}
diff --git a/harper-desktop/src-tauri/src/windows_broker/mod.rs b/harper-desktop/src-tauri/src/windows_broker/mod.rs
new file mode 100644
index 000000000..e959f2573
--- /dev/null
+++ b/harper-desktop/src-tauri/src/windows_broker/mod.rs
@@ -0,0 +1,109 @@
+use std::collections::{self, BTreeMap};
+
+use crate::windows_broker::automation_service::AutomationService;
+use crate::{os_broker::AccessibilityPermissionStatus, os_broker::OsBroker, rect::ActionableLint};
+use egui::Pos2;
+use harper_core::linting::Lint;
+use uiautomation::Result;
+use uiautomation::{UIAutomation, UIElement, UITreeWalker};
+use windows::Win32::Foundation::POINT;
+use windows::Win32::Graphics::Gdi::{MONITOR_DEFAULTTONEAREST, MonitorFromWindow};
+use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};
+use windows::Win32::UI::WindowsAndMessaging::{
+ GetCursorPos, GetForegroundWindow, GetPhysicalCursorPos,
+};
+mod automation_service;
+
+pub struct WindowsBroker {
+ service: AutomationService,
+}
+
+impl WindowsBroker {
+ pub fn new() -> Self {
+ Self {
+ service: AutomationService::create_and_start(),
+ }
+ }
+}
+
+impl OsBroker for WindowsBroker {
+ fn get_boxes(
+ &mut self,
+ lint_text: &mut dyn FnMut(&str) -> BTreeMap<String, Vec<Lint>>,
+ ) -> Vec<ActionableLint> {
+ let text = self.service.get_text();
+ if let Some(text) = text {
+ if text.len() > 16_000 {
+ return Vec::new();
+ }
+
+ let lints = lint_text(text.as_str());
+
+ let all_lint_iter = lints.values().map(|r| r.iter()).flatten();
+ let rects = self
+ .service
+ .get_bounding_boxes(all_lint_iter.map(|l| l.span));
+
+ lints
+ .into_iter()
+ .map(|(lint_id, lints)| lints.into_iter().map(move |l| (lint_id.clone(), l)))
+ .flatten()
+ .zip(rects.into_iter())
+ .map(|((lint_id, lint), rects)| {
+ let text = text.clone();
+ rects
+ .into_iter()
+ .map(|r| r.into_iter())
+ .flatten()
+ .map(move |r| {
+ ActionableLint::new(
+ r,
+ lint_id.clone(),
+ lint.clone(),
+ text.clone(),
+ |_| {},
+ )
+ })
+ })
+ .flatten()
+ .collect()
+ } else {
+ Vec::new()
+ }
+ }
+
+ fn cursor_position(&self) -> Option<Pos2> {
+ let mut point = POINT::default();
+
+ unsafe {
+ GetCursorPos(&mut point).unwrap();
+ }
+
+ let monitor_scale = get_focused_monitor_scale();
+
+ let pos = Pos2::new(
+ point.x as f32 / monitor_scale as f32,
+ point.y as f32 / monitor_scale as f32,
+ );
+ Some(pos)
+ }
+
+ fn accessibility_permission_status(&self) -> AccessibilityPermissionStatus {
+ AccessibilityPermissionStatus::Granted
+ }
+}
+
+fn get_focused_monitor_scale() -> f64 {
+ unsafe {
+ let window = GetForegroundWindow();
+ let monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST);
+
+ let mut x = 0;
+ let mut y = 0;
+
+ GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut x, &mut y);
+
+ let effective_scale = x as f64 / 96.;
+ effective_scale
+ }
+}
diff --git a/justfile b/justfile
index ea6d39438..c714125cd 100644
--- a/justfile
+++ b/justfile
@@ -201,6 +201,15 @@ build-desktop-linux: build-harperjs build-lint-framework build-components build-
pnpm install
pnpm tauri build -b deb,rpm,appimage
+# Build Harper Desktop Windows bundles.
+build-desktop-windows: build-harperjs build-lint-framework build-components build-harper-editor
+ #!/usr/bin/env bash
+ set -eo pipefail
+
+ cd "{{justfile_directory()}}/harper-desktop"
+ pnpm install
+ pnpm tauri build -b msi
+
# Build Harper Desktop for Apple Silicon only — faster than the universal recipe below.
build-desktop-macos-arm64: build-harperjs build-lint-framework build-components build-harper-editor
#!/usr/bin/env bash