Skip to content

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

feat(desktop): add methods to query installed applications (#4214)

Elijah Pottera056c608daf0
diff --git a/Cargo.lock b/Cargo.lock
index d7ae1bf5b..dd3eefbfc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4219,6 +4219,7 @@ dependencies = [
"uiautomation",
"windows 0.62.2",
"winit",
+ "wintheon",
]
[[package]]
@@ -10874,7 +10875,7 @@ dependencies = [
"objc2-metal 0.3.2",
"objc2-quartz-core 0.3.2",
"once_cell",
- "ordered-float 4.6.0",
+ "ordered-float 5.5.0",
"parking_lot",
"portable-atomic",
"portable-atomic-util",
@@ -10964,6 +10965,16 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+[[package]]
+name = "wincorda"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a356fb015443d529bc912a8cb92d90487bfa6fab7af32949f544c1d59af201cb"
+dependencies = [
+ "thiserror 2.0.20",
+ "winapi",
+]
+
[[package]]
name = "window-vibrancy"
version = "0.6.0"
@@ -11577,6 +11588,20 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "wintheon"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55852331fd1934f900d4c7502016f6d26c25f90513e29eb21d80d81fc2a9dedc"
+dependencies = [
+ "png 0.18.1",
+ "thiserror 2.0.20",
+ "tracing",
+ "wincorda",
+ "windows 0.62.2",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "wit-bindgen"
version = "0.57.1"
diff --git a/harper-desktop/src-tauri/Cargo.toml b/harper-desktop/src-tauri/Cargo.toml
index cbaba376f..f930d19cf 100644
--- a/harper-desktop/src-tauri/Cargo.toml
+++ b/harper-desktop/src-tauri/Cargo.toml
@@ -69,6 +69,7 @@ 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"] }
+wintheon = "0.1.0"
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
tauri-plugin-autostart = "2.5.1"
diff --git a/harper-desktop/src-tauri/src/lib.rs b/harper-desktop/src-tauri/src/lib.rs
index 0630b4163..c0c65aea5 100644
--- a/harper-desktop/src-tauri/src/lib.rs
+++ b/harper-desktop/src-tauri/src/lib.rs
@@ -72,7 +72,10 @@ struct IntegrationView {
#[cfg(target_os = "macos")]
pub(crate) type PlatformBroker = mac_broker::MacBroker;
-#[cfg(not(target_os = "macos"))]
+#[cfg(target_os = "windows")]
+pub(crate) type PlatformBroker = windows_broker::WindowsBroker;
+
+#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) type PlatformBroker = os_broker::NoopBroker;
fn platform_broker() -> PlatformBroker {
@@ -343,14 +346,7 @@ pub fn run_highlighter(has_parent: bool) {
}
};
- #[cfg(target_os = "macos")]
- let broker = mac_broker::MacBroker::new(integrations);
-
- #[cfg(target_os = "windows")]
- let broker = windows_broker::WindowsBroker::new();
-
- #[cfg(not(any(target_os = "macos", target_os = "windows")))]
- let broker = os_broker::NoopBroker;
+ let broker = PlatformBroker::default();
if let Err(error) = Highlighter::new(
broker,
diff --git a/harper-desktop/src-tauri/src/mac_broker/app_catalog.rs b/harper-desktop/src-tauri/src/mac_broker/app_catalog.rs
index 2843f407d..14e7c5a20 100644
--- a/harper-desktop/src-tauri/src/mac_broker/app_catalog.rs
+++ b/harper-desktop/src-tauri/src/mac_broker/app_catalog.rs
@@ -1,4 +1,5 @@
-use std::{collections::BTreeSet, path::Path, process::Command};
+use cached::cached;
+use std::{collections::BTreeSet, path::Path, process::Command, sync::Arc};
use crate::os_broker::AppSearchResult;
@@ -28,7 +29,22 @@ fn display_name_from_app_path(path: &str) -> Option<String> {
}
}
-pub fn installed_application_bundle_ids() -> Result<Vec<String>, String> {
+/// Unfiltered.
+#[cached]
+pub fn installed_application_search_results() -> Result<Arc<Vec<AppSearchResult>>, String> {
+ let ids = installed_application_bundle_ids()?;
+
+ let mut results = Vec::with_capacity(ids.len());
+
+ for id in ids.iter() {
+ results.push(app_search_result_from_bundle_id(id));
+ }
+
+ Ok(Arc::new(results))
+}
+
+#[cached]
+pub fn installed_application_bundle_ids() -> Result<Arc<Vec<String>>, String> {
let output = Command::new("mdfind")
.arg(format!(
"kMDItemContentType == \"{APPLICATION_BUNDLE_CONTENT_TYPE}\""
@@ -45,7 +61,7 @@ pub fn installed_application_bundle_ids() -> Result<Vec<String>, String> {
.filter_map(|line| bundle_id_from_app_path(line.trim()))
.collect::<Vec<_>>();
- Ok(deduplicate_and_sort_bundle_ids(bundle_ids))
+ Ok(Arc::new(deduplicate_and_sort_bundle_ids(bundle_ids)))
}
/// Resolves a bundle identifier to an installed `.app` path using Spotlight metadata.
diff --git a/harper-desktop/src-tauri/src/mac_broker/app_search_index.rs b/harper-desktop/src-tauri/src/mac_broker/app_search_index.rs
deleted file mode 100644
index 3a0f70481..000000000
--- a/harper-desktop/src-tauri/src/mac_broker/app_search_index.rs
+++ /dev/null
@@ -1,62 +0,0 @@
-use std::collections::BTreeSet;
-
-use crate::os_broker::AppSearchResult;
-
-use super::app_catalog::{app_search_result_from_bundle_id, installed_application_bundle_ids};
-
-pub struct AppSearchIndex {
- index: Vec<AppSearchResult>,
-}
-
-impl AppSearchIndex {
- pub fn new() -> Self {
- Self { index: Vec::new() }
- }
-
- pub fn populate(&mut self) -> Result<(), String> {
- let installed_bundles = installed_application_bundle_ids()?;
-
- let mut seen_bundle_ids = BTreeSet::new();
-
- for bundle_id in installed_bundles {
- let result = app_search_result_from_bundle_id(&bundle_id);
-
- if seen_bundle_ids.insert(result.bundle_id.clone()) {
- self.index.push(result);
- }
- }
-
- Ok(())
- }
-
- pub fn is_empty(&self) -> bool {
- self.index.is_empty()
- }
-
- pub fn search(&self, query: &str) -> Vec<AppSearchResult> {
- let query = query.trim();
-
- if query.is_empty() {
- return self.index.to_vec();
- }
-
- if let Some(result) = self
- .index
- .iter()
- .find(|result| result.bundle_id == query)
- .cloned()
- {
- return vec![result];
- }
-
- let lower_query = query.to_lowercase();
- self.index
- .iter()
- .filter(|result| {
- result.name.to_lowercase().contains(&lower_query)
- || result.bundle_id.to_lowercase().contains(&lower_query)
- })
- .cloned()
- .collect()
- }
-}
diff --git a/harper-desktop/src-tauri/src/mac_broker/mod.rs b/harper-desktop/src-tauri/src/mac_broker/mod.rs
index a853178b9..85c87027d 100644
--- a/harper-desktop/src-tauri/src/mac_broker/mod.rs
+++ b/harper-desktop/src-tauri/src/mac_broker/mod.rs
@@ -3,7 +3,6 @@ mod accessibility_activation;
mod accessibility_text;
mod app_catalog;
mod app_icons;
-mod app_search_index;
mod core_foundation_utilities;
mod focused_window_pid;
mod window_stability;
@@ -43,7 +42,6 @@ use self::accessibility_activation::{
set_enhanced_user_interface_preserving_previous, verify_accessibility_activation,
};
use self::accessibility_text::RectCollector;
-use self::app_search_index::AppSearchIndex;
use self::window_stability::{
WINDOW_MOVEMENT_SETTLE_DURATION, WindowMovementState, frontmost_window_frame_for_pid,
settled_window_state, window_frame_changed,
@@ -59,7 +57,6 @@ pub struct MacBroker {
last_focused: Option<(pid_t, Instant)>,
integrations: Arc<Mutex<Vec<Integration>>>,
application_icon_cache: Mutex<HashMap<String, Vec<u8>>>,
- installed_app_search_index: Mutex<AppSearchIndex>,
window_movement: Option<WindowMovementState>,
accessibility_activation: Option<AccessibilityActivationState>,
}
@@ -70,7 +67,6 @@ impl MacBroker {
last_focused: None,
integrations,
application_icon_cache: Mutex::new(HashMap::new()),
- installed_app_search_index: Mutex::new(AppSearchIndex::new()),
window_movement: None,
accessibility_activation: None,
}
@@ -390,6 +386,11 @@ impl OsBroker for MacBroker {
app_catalog::integration_display_name(bundle_id)
}
+ fn installed_application_bundle_ids(&self) -> Result<Vec<String>, String> {
+ let ids = app_catalog::installed_application_bundle_ids()?;
+ Ok(ids.iter().cloned().collect())
+ }
+
fn application_icon_png(&self, bundle_id: &str) -> Result<Vec<u8>, String> {
let bundle_id = bundle_id.trim();
@@ -430,21 +431,32 @@ impl OsBroker for MacBroker {
Ok(())
}
- fn installed_application_bundle_ids(&self) -> Result<Vec<String>, String> {
- app_catalog::installed_application_bundle_ids()
- }
-
fn search_apps(&self, query: &str) -> Result<Vec<AppSearchResult>, String> {
- let mut lock = self
- .installed_app_search_index
- .lock()
- .map_err(|_| "Could not lock search index.".to_owned())?;
+ let list = app_catalog::installed_application_search_results()?;
- if lock.is_empty() {
- lock.populate()?;
+ let query = query.trim();
+
+ if query.is_empty() {
+ return Ok(list.to_vec());
+ }
+
+ if let Some(result) = list
+ .iter()
+ .find(|result| result.bundle_id == query)
+ .cloned()
+ {
+ return Ok(vec![result]);
}
- Ok(lock.search(query))
+ let lower_query = query.to_lowercase();
+ Ok(list
+ .iter()
+ .filter(|result| {
+ result.name.to_lowercase().contains(&lower_query)
+ || result.bundle_id.to_lowercase().contains(&lower_query)
+ })
+ .cloned()
+ .collect())
}
}
diff --git a/harper-desktop/src-tauri/src/windows_broker/mod.rs b/harper-desktop/src-tauri/src/windows_broker/mod.rs
index ac9ada350..51268528c 100644
--- a/harper-desktop/src-tauri/src/windows_broker/mod.rs
+++ b/harper-desktop/src-tauri/src/windows_broker/mod.rs
@@ -1,36 +1,51 @@
-use std::{cell::RefCell, collections::BTreeMap, rc::Rc};
-
use crate::windows_broker::automation_service::AutomationService;
use crate::{
os_broker::{AccessibilityPermissionStatus, AppSearchResult, OsBroker},
rect::ActionableLint,
};
+use cached::cached;
use egui::Pos2;
use harper_core::linting::Lint;
+use std::process::Command;
+use std::{
+ cell::RefCell,
+ collections::BTreeMap,
+ path::PathBuf,
+ rc::Rc,
+ sync::{Arc, Mutex},
+};
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};
+use wintheon::file::{IconSize, Priority};
+use wintheon::gather::Gatherer;
mod automation_service;
pub struct WindowsBroker {
- service: Rc<RefCell<AutomationService>>,
+ service: Arc<Mutex<AutomationService>>,
}
impl WindowsBroker {
pub fn new() -> Self {
Self {
- service: Rc::new(RefCell::new(AutomationService::create_and_start())),
+ service: Arc::new(Mutex::new(AutomationService::create_and_start())),
}
}
}
+impl Default for WindowsBroker {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
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.borrow_mut().get_text();
+ let text = self.service.lock().unwrap().get_text();
if let Some(text) = text {
if text.len() > 16_000 {
return Vec::new();
@@ -41,7 +56,8 @@ impl OsBroker for WindowsBroker {
let all_lint_iter = lints.values().map(|r| r.iter()).flatten();
let Some(rects) = self
.service
- .borrow_mut()
+ .lock()
+ .unwrap()
.get_bounding_boxes(all_lint_iter.map(|l| l.span))
else {
return Vec::new();
@@ -54,9 +70,9 @@ impl OsBroker for WindowsBroker {
.zip(rects)
.map(|((lint_id, lint), rects)| {
let text = text.clone();
- let service = Rc::clone(&self.service);
+ let service = self.service.clone();
rects.into_iter().map(move |r| {
- let service = Rc::clone(&service);
+ let service = service.clone();
let suggestion_text = text.clone();
let suggestion_span = lint.span;
ActionableLint::new(
@@ -65,7 +81,7 @@ impl OsBroker for WindowsBroker {
lint.clone(),
text.clone(),
move |suggestion| {
- service.borrow_mut().apply_suggestion(
+ service.lock().unwrap().apply_suggestion(
suggestion_text,
suggestion_span,
suggestion,
@@ -107,24 +123,71 @@ impl OsBroker for WindowsBroker {
}
fn integration_display_name(&self, bundle_id: &str) -> String {
+ if let Some(entry) = look_up_application(bundle_id) {
+ return entry.display_name;
+ }
+
bundle_id.to_string()
}
fn installed_application_bundle_ids(&self) -> Result<Vec<String>, String> {
- Ok(Vec::new())
+ let list = installed_applications_list();
+ Ok(list
+ .iter()
+ .map(|i| i.path.to_string_lossy().into_owned())
+ .collect())
}
- fn application_icon_png(&self, _bundle_id: &str) -> Result<Vec<u8>, String> {
- Err("Not supported".to_string())
+ fn application_icon_png(&self, bundle_id: &str) -> Result<Vec<u8>, String> {
+ if let Some(entry) = look_up_application(bundle_id) {
+ if let Some(png) = entry.icon_png {
+ return Ok(png);
+ } else {
+ return Err("Found application but it was missing an icon.".to_string());
+ }
+ } else {
+ return Err("Unable to locate application.".to_string());
+ }
}
- fn launch_app_bundle(&self, _bundle_id: &str) -> Result<(), String> {
+ fn launch_app_bundle(&self, bundle_id: &str) -> Result<(), String> {
+ Command::new(bundle_id)
+ .spawn()
+ .map_err(|err| err.to_string())?;
Ok(())
}
/// Search for an application in the OS' global list of installed apps.
- fn search_apps(&self, _query: &str) -> Result<Vec<AppSearchResult>, String> {
- Ok(Vec::new())
+ fn search_apps(&self, query: &str) -> Result<Vec<AppSearchResult>, String> {
+ let list = installed_applications_list();
+ let query = query.trim();
+
+ if query.is_empty() {
+ return Ok(list.iter().map(|entry| entry.to_search_result()).collect());
+ }
+
+ if let Some(result) = list
+ .iter()
+ .find(|result| result.path.to_string_lossy() == query)
+ .cloned()
+ {
+ return Ok(vec![result.to_search_result()]);
+ }
+
+ let lower_query = query.to_lowercase();
+ Ok(list
+ .iter()
+ .filter(|result| {
+ result.display_name.to_lowercase().contains(&lower_query)
+ || result
+ .path
+ .to_string_lossy()
+ .to_lowercase()
+ .contains(&lower_query)
+ })
+ .cloned()
+ .map(|entry| entry.to_search_result())
+ .collect())
}
}
@@ -142,3 +205,63 @@ fn get_focused_monitor_scale() -> f64 {
effective_scale
}
}
+
+#[derive(Debug, Clone)]
+struct ApplicationListEntry {
+ path: PathBuf,
+ /// The PNG bytes of an icon. 256 on a side, square.
+ icon_png: Option<Vec<u8>>,
+ display_name: String,
+}
+
+impl ApplicationListEntry {
+ fn to_search_result(&self) -> AppSearchResult {
+ AppSearchResult {
+ name: self.display_name.clone(),
+ bundle_id: self.path.to_string_lossy().to_owned().to_string(),
+ }
+ }
+}
+
+fn look_up_application(bundle_id: &str) -> Option<ApplicationListEntry> {
+ // In Windows, the application path is the bundle ID.
+ let list = installed_applications_list();
+ if let Some(entry) = list
+ .iter()
+ .find(|entry| entry.path.to_string_lossy() == bundle_id)
+ {
+ Some(entry.clone())
+ } else {
+ None
+ }
+}
+
+#[cached]
+fn installed_applications_list() -> Arc<Vec<ApplicationListEntry>> {
+ let mut list = Vec::new();
+
+ for res in gatherer().scan() {
+ if let Ok(app) = res {
+ let icon = if let Ok(icon) = app.entry.icon() {
+ icon.extract_icon_as_png_at(IconSize::Jumbo)
+ } else {
+ None
+ };
+
+ list.push(ApplicationListEntry {
+ path: app.entry.path().to_owned(),
+ icon_png: icon,
+ display_name: app.entry.display_name(),
+ })
+ }
+ }
+
+ Arc::new(list)
+}
+
+fn gatherer() -> Gatherer {
+ Gatherer::new()
+ .with_desktop(Priority(1.0))
+ .with_start_menu(Priority(1.5))
+ .with_windows_apps(Priority(2.0))
+}