Skip to content

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

feat(desktop): better search and icons for app modal (#3704)

Elijah Potter5a1de1597556
diff --git a/Cargo.lock b/Cargo.lock
index 6f35afa71..be970d698 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4257,6 +4257,7 @@ version = "2.4.0"
dependencies = [
"accessibility",
"accessibility-sys",
+ "base64 0.22.1",
"clap",
"core-foundation 0.10.1",
"core-graphics 0.25.0",
diff --git a/harper-desktop/src-tauri/Cargo.toml b/harper-desktop/src-tauri/Cargo.toml
index 5760e50ed..c7a71654d 100644
--- a/harper-desktop/src-tauri/Cargo.toml
+++ b/harper-desktop/src-tauri/Cargo.toml
@@ -23,6 +23,7 @@ tauri = { version = "=2.11.1", features = ["image-png", "tray-icon"] }
tauri-plugin-opener = "=2.5.4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+base64 = "0.22.1"
winit = "0.30.13"
thiserror = "2.0.18"
egui = "0.34.1"
diff --git a/harper-desktop/src-tauri/src/commands.rs b/harper-desktop/src-tauri/src/commands.rs
index 677e0afcb..c63d7efd1 100644
--- a/harper-desktop/src-tauri/src/commands.rs
+++ b/harper-desktop/src-tauri/src/commands.rs
@@ -4,15 +4,18 @@
use crate::config::Config;
use crate::highlighter_service::HighlighterService;
use crate::os_broker::{AccessibilityPermissionStatus, AppSearchResult, OsBroker};
-use crate::{IntegrationView, accessibility_allows_highlighter_start, platform_broker};
+use crate::{
+ IntegrationView, PlatformBroker, accessibility_allows_highlighter_start, platform_broker,
+};
+use base64::{Engine as _, engine::general_purpose};
use harper_core::{
Dialect, DictWordMetadata, IgnoredLints,
linting::FlatConfig,
spell::{Dictionary, MutableDictionary},
};
-use std::sync::Arc;
+use std::sync::{Arc, Mutex as StdMutex};
use tauri::ipc::Invoke;
-use tauri::{Runtime, State};
+use tauri::{Manager, Runtime, State};
use tokio::sync::Mutex;
pub fn application_message_handler<R: Runtime>() -> impl Fn(Invoke<R>) -> bool {
@@ -35,6 +38,8 @@ pub fn application_message_handler<R: Runtime>() -> impl Fn(Invoke<R>) -> bool {
add_integration,
remove_integration,
set_integration_enabled,
+ get_installed_application_bundle_ids,
+ get_application_icon_data_url,
get_accessibility_permission_status,
request_accessibility_permission,
start_highlighter_service,
@@ -227,9 +232,12 @@ async fn add_to_dictionary(
#[tauri::command]
async fn get_integrations(
config: State<'_, Arc<Mutex<Config>>>,
+ broker: State<'_, StdMutex<PlatformBroker>>,
) -> Result<Vec<IntegrationView>, String> {
let integrations = config.lock().await.integrations.clone();
- let broker = platform_broker();
+ let broker = broker
+ .lock()
+ .map_err(|error| format!("Failed to read platform broker: {error}"))?;
Ok(integrations
.into_iter()
@@ -287,6 +295,35 @@ async fn set_integration_enabled(
Ok(())
}
+#[tauri::command]
+fn get_installed_application_bundle_ids(
+ broker: State<'_, StdMutex<PlatformBroker>>,
+) -> Result<Vec<String>, String> {
+ broker
+ .lock()
+ .map_err(|error| format!("Failed to read platform broker: {error}"))?
+ .installed_application_bundle_ids()
+}
+
+#[tauri::command]
+async fn get_application_icon_data_url<R: Runtime>(
+ bundle_id: String,
+ app_handle: tauri::AppHandle<R>,
+) -> Result<String, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let broker = app_handle.state::<StdMutex<PlatformBroker>>();
+ let icon_png = broker
+ .lock()
+ .map_err(|error| format!("Failed to read platform broker: {error}"))?
+ .application_icon_png(&bundle_id)?;
+ let encoded = general_purpose::STANDARD.encode(icon_png);
+
+ Ok(format!("data:image/png;base64,{encoded}"))
+ })
+ .await
+ .map_err(|error| format!("Failed to load application icon: {error}"))?
+}
+
#[tauri::command]
fn get_accessibility_permission_status() -> AccessibilityPermissionStatus {
platform_broker().accessibility_permission_status()
@@ -343,6 +380,12 @@ fn launch_app(bundle_id: String) -> Result<(), String> {
}
#[tauri::command]
-fn search_apps(query: String) -> Result<Vec<AppSearchResult>, String> {
- platform_broker().search_apps(&query)
+fn search_apps(
+ query: String,
+ broker: State<'_, StdMutex<PlatformBroker>>,
+) -> Result<Vec<AppSearchResult>, String> {
+ broker
+ .lock()
+ .map_err(|error| format!("Failed to read platform broker: {error}"))?
+ .search_apps(&query)
}
diff --git a/harper-desktop/src-tauri/src/lib.rs b/harper-desktop/src-tauri/src/lib.rs
index b54b6f337..878f41e42 100644
--- a/harper-desktop/src-tauri/src/lib.rs
+++ b/harper-desktop/src-tauri/src/lib.rs
@@ -10,7 +10,12 @@ use harper_core::{
spell::MutableDictionary,
};
use serde::Serialize;
-use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
+use std::{
+ cell::RefCell,
+ rc::Rc,
+ sync::{Arc, Mutex as StdMutex},
+ time::Duration,
+};
use tauri::{
Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent,
image::Image,
@@ -257,13 +262,27 @@ fn start_highlighter_service_if_enabled_and_permitted(
}
#[cfg(target_os = "macos")]
-fn platform_broker() -> impl OsBroker {
- mac_broker::MacBroker::default()
-}
+pub(crate) type PlatformBroker = mac_broker::MacBroker;
#[cfg(not(target_os = "macos"))]
-fn platform_broker() -> impl OsBroker {
- os_broker::NoopBroker
+pub(crate) type PlatformBroker = os_broker::NoopBroker;
+
+fn platform_broker() -> PlatformBroker {
+ PlatformBroker::default()
+}
+
+fn warm_app_search_cache(app: tauri::AppHandle) {
+ tauri::async_runtime::spawn_blocking(move || {
+ let broker = app.state::<StdMutex<PlatformBroker>>();
+ let result = broker
+ .lock()
+ .map_err(|error| format!("failed to read platform broker: {error}"))
+ .and_then(|broker| broker.search_apps("").map(|_| ()));
+
+ if let Err(error) = result {
+ eprintln!("failed to warm app search cache: {error}");
+ }
+ });
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
@@ -317,6 +336,7 @@ pub fn run_tauri() {
tauri::Builder::default()
.manage(config)
.manage(highlighter_service)
+ .manage(StdMutex::new(platform_broker()))
.plugin(tauri_plugin_autostart::init(
tauri_plugin_autostart::MacosLauncher::LaunchAgent,
None,
@@ -349,6 +369,8 @@ pub fn run_tauri() {
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
+ warm_app_search_cache(app.handle().clone());
+
let tray = TrayIconBuilder::with_id(TRAY_MENU_BAR_ID)
.menu(&menu.menu)
.icon(menu_bar_icon(is_service_running)?)
@@ -464,7 +486,7 @@ pub fn run_highlighter() {
let ignored_lints = Rc::new(RefCell::new(startup_config.ignored_lints));
let user_dictionary = Rc::new(RefCell::new(startup_config.mutable_dictionary));
let dialect = Rc::new(RefCell::new(startup_config.dialect));
- let integrations = Rc::new(RefCell::new(startup_config.integrations));
+ let integrations = Arc::new(StdMutex::new(startup_config.integrations));
let debounce_ms = Rc::new(RefCell::new(startup_config.debounce_ms));
let linter = Rc::new(RefCell::new(startup_linter));
@@ -637,7 +659,7 @@ fn apply_highlighter_config(
ignored_lints: &Rc<RefCell<IgnoredLints>>,
user_dictionary: &Rc<RefCell<MutableDictionary>>,
dialect: &Rc<RefCell<Dialect>>,
- integrations: &Rc<RefCell<Vec<Integration>>>,
+ integrations: &Arc<StdMutex<Vec<Integration>>>,
debounce_ms: &Rc<RefCell<u64>>,
linter: &Rc<RefCell<LintGroup>>,
) {
@@ -645,7 +667,10 @@ fn apply_highlighter_config(
*ignored_lints.borrow_mut() = config.ignored_lints;
*user_dictionary.borrow_mut() = config.mutable_dictionary;
*dialect.borrow_mut() = config.dialect;
- *integrations.borrow_mut() = config.integrations;
+ match integrations.lock() {
+ Ok(mut integrations) => *integrations = config.integrations,
+ Err(error) => eprintln!("failed to update integrations: {error}"),
+ }
*debounce_ms.borrow_mut() = config.debounce_ms;
*linter.borrow_mut() = linter_config;
}
diff --git a/harper-desktop/src-tauri/src/mac_broker.rs b/harper-desktop/src-tauri/src/mac_broker.rs
index 38f4f0deb..6593d71ab 100644
--- a/harper-desktop/src-tauri/src/mac_broker.rs
+++ b/harper-desktop/src-tauri/src/mac_broker.rs
@@ -28,17 +28,20 @@ use objc2_app_kit::{NSRunningApplication, NSWorkspace};
use objc2_foundation::NSRect;
use std::{
cell::{Cell, RefCell},
- collections::BTreeMap,
+ collections::{BTreeMap, BTreeSet, HashMap},
error::Error as StdError,
- path::Path,
+ fs,
+ path::{Path, PathBuf},
process::Command,
ptr,
- rc::Rc,
+ sync::{Arc, Mutex},
time::{Duration, Instant},
};
use crate::config::{Config, Integration};
-use crate::os_broker::{AccessibilityPermissionStatus, AppSearchResult, OsBroker};
+use crate::os_broker::{
+ AccessibilityPermissionStatus, AppSearchResult, OsBroker, in_memory_app_search_results,
+};
use crate::rect::{ActionableLint, Rect};
const WINDOW_MOVEMENT_SETTLE_DURATION: Duration = Duration::from_millis(150);
@@ -48,6 +51,7 @@ const ACCESSIBILITY_ACTIVATION_SLOW_VERIFICATION_RETRY_INTERVAL: Duration = Dura
const ACCESSIBILITY_ACTIVATION_FAST_VERIFICATION_ATTEMPTS: u8 = 20;
const CHROMIUM_ACCESSIBILITY_SETTLE_DURATION: Duration = Duration::from_secs(3);
const WINDOW_FRAME_TOLERANCE: f64 = 0.5;
+const APPLICATION_BUNDLE_CONTENT_TYPE: &str = "com.apple.application-bundle";
type WindowInfo = CFDictionary<CFString, CFType>;
/// macOS implementation of the OS data the highlighter needs.
@@ -57,7 +61,9 @@ type WindowInfo = CFDictionary<CFString, CFType>;
/// targeting the app the user was reviewing.
pub struct MacBroker {
last_focused: Option<pid_t>,
- integrations: Rc<RefCell<Vec<Integration>>>,
+ integrations: Arc<Mutex<Vec<Integration>>>,
+ application_icon_cache: Mutex<HashMap<String, Vec<u8>>>,
+ installed_app_search_results: Mutex<Option<Vec<AppSearchResult>>>,
window_movement: Option<WindowMovementState>,
accessibility_activation: Option<AccessibilityActivationState>,
}
@@ -99,10 +105,12 @@ enum AccessibilityActivationVerification {
}
impl MacBroker {
- pub fn new(integrations: Rc<RefCell<Vec<Integration>>>) -> Self {
+ pub fn new(integrations: Arc<Mutex<Vec<Integration>>>) -> Self {
Self {
last_focused: None,
integrations,
+ application_icon_cache: Mutex::new(HashMap::new()),
+ installed_app_search_results: Mutex::new(None),
window_movement: None,
accessibility_activation: None,
}
@@ -302,7 +310,7 @@ impl MacBroker {
impl Default for MacBroker {
fn default() -> Self {
- Self::new(Rc::new(RefCell::new(Config::curated_integrations())))
+ Self::new(Arc::new(Mutex::new(Config::curated_integrations())))
}
}
@@ -346,7 +354,17 @@ impl OsBroker for MacBroker {
}
};
- if !Config::is_integration_enabled_in(&self.integrations.borrow(), &bundle_identifier) {
+ let integration_enabled = match self.integrations.lock() {
+ Ok(integrations) => {
+ Config::is_integration_enabled_in(&integrations, &bundle_identifier)
+ }
+ Err(error) => {
+ eprintln!("Unable to read integrations: {error}");
+ false
+ }
+ };
+
+ if !integration_enabled {
self.window_movement = None;
self.reset_accessibility_activation();
return Vec::new();
@@ -402,6 +420,36 @@ impl OsBroker for MacBroker {
system_integration_display_name(bundle_id)
}
+ fn installed_application_bundle_ids(&self) -> Result<Vec<String>, String> {
+ installed_application_bundle_ids()
+ }
+
+ fn application_icon_png(&self, bundle_id: &str) -> Result<Vec<u8>, String> {
+ let bundle_id = bundle_id.trim();
+
+ if bundle_id.is_empty() {
+ return Err("Bundle ID cannot be empty.".to_string());
+ }
+
+ if let Some(icon_png) = self
+ .application_icon_cache
+ .lock()
+ .map_err(|error| format!("Failed to read application icon cache: {error}"))?
+ .get(bundle_id)
+ .cloned()
+ {
+ return Ok(icon_png);
+ }
+
+ let icon_png = application_icon_png(bundle_id)?;
+ self.application_icon_cache
+ .lock()
+ .map_err(|error| format!("Failed to update application icon cache: {error}"))?
+ .insert(bundle_id.to_string(), icon_png.clone());
+
+ Ok(icon_png)
+ }
+
fn launch_app_bundle(&self, bundle_id: &str) -> Result<(), String> {
let bundle_id = bundle_id.trim();
@@ -420,110 +468,183 @@ impl OsBroker for MacBroker {
fn search_apps(&self, query: &str) -> Result<Vec<AppSearchResult>, String> {
let query = query.trim();
+ let installed_apps = self.installed_app_search_results()?;
+
+ let in_memory_results = in_memory_app_search_results(&installed_apps, query);
- if query.is_empty() {
- return Ok(Vec::new());
+ if query.is_empty()
+ || in_memory_results
+ .iter()
+ .any(|result| result.bundle_id == query)
+ {
+ return Ok(in_memory_results);
}
- // Search for apps by display name using mdfind
- // Use case-insensitive search and ensure we only get .app bundles
- let escaped_query = query.replace('\\', "\\\\").replace('"', "\\\"");
- let output = Command::new("mdfind")
- .arg(format!(
- "kMDItemContentType == 'com.apple.application-bundle' && kMDItemDisplayName == '*{escaped_query}*'cd"
- ))
- .output()
- .map_err(|error| format!("Failed to execute mdfind: {error}"))?;
-
- if !output.status.success() {
- return Err(format!(
- "mdfind failed: {}",
- String::from_utf8_lossy(&output.stderr)
- ));
+ if let Some(app_path) = application_path_for_bundle_id(query) {
+ return Ok(vec![
+ app_search_result_from_app_path(&app_path)
+ .unwrap_or_else(|| app_search_result_from_bundle_id(self, query)),
+ ]);
}
- let mut results = Vec::new();
- let mut seen_bundle_ids = std::collections::HashSet::new();
+ Ok(in_memory_results)
+ }
+}
- for line in String::from_utf8_lossy(&output.stdout).lines() {
- let line = line.trim();
+impl MacBroker {
+ fn installed_app_search_results(&self) -> Result<Vec<AppSearchResult>, String> {
+ if let Some(results) = self
+ .installed_app_search_results
+ .lock()
+ .map_err(|error| format!("Failed to read app search cache: {error}"))?
+ .clone()
+ {
+ return Ok(results);
+ }
- // Skip if not an .app bundle
- if !line.ends_with(".app") {
- continue;
- }
+ let results = discover_app_search_results()?;
+ *self
+ .installed_app_search_results
+ .lock()
+ .map_err(|error| format!("Failed to update app search cache: {error}"))? =
+ Some(results.clone());
- if let Some(display_name) = display_name_from_app_path(line) {
- // Skip if display name looks like a bundle ID (contains dots)
- if display_name.contains('.') {
- continue;
- }
+ Ok(results)
+ }
+}
- if let Some(bundle_id) = bundle_id_from_app_path(line) {
- // Skip if we've already seen this bundle ID (deduplication)
- if seen_bundle_ids.contains(&bundle_id) {
- continue;
- }
+fn app_search_result_from_bundle_id(broker: &MacBroker, bundle_id: &str) -> AppSearchResult {
+ AppSearchResult {
+ name: broker.integration_display_name(bundle_id),
+ bundle_id: bundle_id.to_string(),
+ }
+}
- // Skip if bundle ID looks like a path or is invalid
- if bundle_id.contains('/') || bundle_id.is_empty() {
- continue;
- }
+fn app_search_result_from_app_path(path: &str) -> Option<AppSearchResult> {
+ let display_name = display_name_from_app_path(path)?;
- seen_bundle_ids.insert(bundle_id.clone());
- results.push(AppSearchResult {
- name: display_name,
- bundle_id,
- });
- }
- }
- }
+ if display_name.contains('.') {
+ return None;
+ }
- Ok(results)
+ let bundle_id = bundle_id_from_app_path(path)?;
+
+ if bundle_id.contains('/') || bundle_id.is_empty() {
+ return None;
}
+
+ Some(AppSearchResult {
+ name: display_name,
+ bundle_id,
+ })
}
-fn bundle_id_from_app_path(path: &str) -> Option<String> {
- let output = Command::new("mdls")
- .arg("-name")
- .arg("kMDItemCFBundleIdentifier")
- .arg(path)
+fn discover_app_search_results() -> Result<Vec<AppSearchResult>, String> {
+ let output = Command::new("mdfind")
+ .arg(format!(
+ "kMDItemContentType == '{APPLICATION_BUNDLE_CONTENT_TYPE}'"
+ ))
.output()
- .ok()?;
+ .map_err(|error| format!("Failed to execute mdfind: {error}"))?;
if !output.status.success() {
- return None;
+ return Err(format!(
+ "mdfind failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ ));
}
- let output = String::from_utf8_lossy(&output.stdout);
+ let mut results = Vec::new();
+ let mut seen_bundle_ids = BTreeSet::new();
- // Parse the output from mdls which looks like:
- // kMDItemCFBundleIdentifier = "com.example.app"
- let bundle_id = output
- .lines()
- .find(|line| line.contains("kMDItemCFBundleIdentifier"))
- .and_then(|line| {
- line.split('=')
- .nth(1)
- .map(|s| s.trim().trim_matches('"').to_string())
- })?;
-
- // Filter out null or empty bundle IDs
- if bundle_id.is_empty() || bundle_id == "(null)" || bundle_id == "null" {
- return None;
+ for line in String::from_utf8_lossy(&output.stdout).lines() {
+ let line = line.trim();
+
+ if !line.ends_with(".app") {
+ continue;
+ }
+
+ let Some(result) = app_search_result_from_app_path(line) else {
+ continue;
+ };
+
+ if seen_bundle_ids.insert(result.bundle_id.clone()) {
+ results.push(result);
+ }
}
- Some(bundle_id)
+ Ok(results)
}
fn system_integration_display_name(bundle_id: &str) -> Option<String> {
+ application_path_for_bundle_id(bundle_id).and_then(|path| display_name_from_app_path(&path))
+}
+
+fn installed_application_bundle_ids() -> Result<Vec<String>, String> {
+ let output = Command::new("mdfind")
+ .arg(format!(
+ "kMDItemContentType == \"{APPLICATION_BUNDLE_CONTENT_TYPE}\""
+ ))
+ .output()
+ .map_err(|error| format!("Failed to list installed applications: {error}"))?;
+
+ if !output.status.success() {
+ return Err("Failed to list installed applications with Spotlight.".to_string());
+ }
+
+ let bundle_ids = String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| bundle_id_from_app_path(line.trim()))
+ .collect::<Vec<_>>();
+
+ Ok(deduplicate_and_sort_bundle_ids(bundle_ids))
+}
+
+fn application_icon_png(bundle_id: &str) -> Result<Vec<u8>, String> {
+ let bundle_id = bundle_id.trim();
+
+ if bundle_id.is_empty() {
+ return Err("Bundle ID cannot be empty.".to_string());
+ }
+
+ let app_path = application_path_for_bundle_id(bundle_id)
+ .ok_or_else(|| format!("No application found for bundle ID {bundle_id}."))?;
+ let icon_path = icon_path_for_app(&app_path)
+ .ok_or_else(|| format!("No application icon found for bundle ID {bundle_id}."))?;
+ let output_path = std::env::temp_dir().join(format!(
+ "harper-{bundle_id}-icon-{}.png",
+ std::process::id()
+ ));
+
+ let output = Command::new("sips")
+ .arg("-s")
+ .arg("format")
+ .arg("png")
+ .arg(&icon_path)
+ .arg("--out")
+ .arg(&output_path)
+ .output()
+ .map_err(|error| format!("Failed to convert icon for {bundle_id}: {error}"))?;
+
+ if !output.status.success() {
+ return Err(format!("Failed to convert icon for {bundle_id} to PNG."));
+ }
+
+ let bytes = fs::read(&output_path)
+ .map_err(|error| format!("Failed to read converted icon for {bundle_id}: {error}"))?;
+ let _ = fs::remove_file(output_path);
+
+ Ok(bytes)
+}
+
+fn application_path_for_bundle_id(bundle_id: &str) -> Option<String> {
let bundle_id = bundle_id.trim();
if bundle_id.is_empty() {
return None;
}
- let predicate_bundle_id = bundle_id.replace('\\', "\\\\").replace('"', "\\\"");
+ let predicate_bundle_id = escape_spotlight_string(bundle_id);
let output = Command::new("mdfind")
.arg(format!(
"kMDItemCFBundleIdentifier == \"{predicate_bundle_id}\""
@@ -537,8 +658,89 @@ fn system_integration_display_name(bundle_id: &str) -> Option<String> {
String::from_utf8_lossy(&output.stdout)
.lines()
- .filter_map(|line| display_name_from_app_path(line.trim()))
- .next()
+ .map(str::trim)
+ .find(|line| !line.is_empty() && line.ends_with(".app"))
+ .map(ToString::to_string)
+}
+
+fn bundle_id_from_app_path(path: &str) -> Option<String> {
+ if path.is_empty() {
+ return None;
+ }
+
+ let output = Command::new("mdls")
+ .arg("-raw")
+ .arg("-name")
+ .arg("kMDItemCFBundleIdentifier")
+ .arg(path)
+ .output()
+ .ok()?;
+
+ if !output.status.success() {
+ return None;
+ }
+
+ let bundle_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
+
+ if bundle_id.is_empty() || bundle_id == "(null)" {
+ None
+ } else {
+ Some(bundle_id)
+ }
+}
+
+fn icon_path_for_app(app_path: &str) -> Option<PathBuf> {
+ let resources_path = Path::new(app_path).join("Contents/Resources");
+ let icon_file = app_icon_file(app_path)?;
+ let icon_path = resources_path.join(&icon_file);
+
+ if icon_path.exists() {
+ return Some(icon_path);
+ }
+
+ let icon_path = resources_path.join(format!("{icon_file}.icns"));
+
+ if icon_path.exists() {
+ Some(icon_path)
+ } else {
+ None
+ }
+}
+
+fn app_icon_file(app_path: &str) -> Option<String> {
+ let info_plist_path = Path::new(app_path).join("Contents/Info.plist");
+ let output = Command::new("/usr/libexec/PlistBuddy")
+ .arg("-c")
+ .arg("Print :CFBundleIconFile")
+ .arg(info_plist_path)
+ .output()
+ .ok()?;
+
+ if !output.status.success() {
+ return None;
+ }
+
+ let icon_file = String::from_utf8_lossy(&output.stdout).trim().to_string();
+
+ if icon_file.is_empty() {
+ None
+ } else {
+ Some(icon_file)
+ }
+}
+
+fn escape_spotlight_string(value: &str) -> String {
+ value.replace('\\', "\\\\").replace('"', "\\\"")
+}
+
+fn deduplicate_and_sort_bundle_ids(bundle_ids: Vec<String>) -> Vec<String> {
+ bundle_ids
+ .into_iter()
+ .map(|bundle_id| bundle_id.trim().to_string())
+ .filter(|bundle_id| !bundle_id.is_empty() && bundle_id != "(null)")
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect()
}
fn display_name_from_app_path(path: &str) -> Option<String> {
@@ -1269,6 +1471,34 @@ mod tests {
);
}
+ #[test]
+ fn deduplicates_and_sorts_bundle_ids() {
+ assert_eq!(
+ deduplicate_and_sort_bundle_ids(vec![
+ "com.example.Beta".to_string(),
+ " com.example.Alpha ".to_string(),
+ "com.example.Beta".to_string(),
+ "".to_string(),
+ "(null)".to_string(),
+ ]),
+ vec!["com.example.Alpha", "com.example.Beta"]
+ );
+ }
+
+ #[test]
+ fn escapes_spotlight_strings() {
+ assert_eq!(
+ escape_spotlight_string(r#"com.example.\"quoted\""#),
+ r#"com.example.\\\"quoted\\\""#
+ );
+ }
+
+ #[test]
+ fn empty_bundle_id_has_no_application_path() {
+ assert_eq!(application_path_for_bundle_id(""), None);
+ assert_eq!(application_path_for_bundle_id(" "), None);
+ }
+
#[test]
fn verification_retry_slows_after_fast_attempts() {
assert_eq!(
diff --git a/harper-desktop/src-tauri/src/os_broker.rs b/harper-desktop/src-tauri/src/os_broker.rs
index 5b5cf3966..9fefa5b5e 100644
--- a/harper-desktop/src-tauri/src/os_broker.rs
+++ b/harper-desktop/src-tauri/src/os_broker.rs
@@ -43,6 +43,22 @@ pub trait OsBroker {
.unwrap_or_else(|| fallback_integration_display_name(bundle_id))
}
+ /// Returns the bundle identifiers for installed graphical applications.
+ ///
+ /// Implementations should return stable bundle ID strings, sorted and deduplicated where
+ /// possible. Platforms that do not support bundle IDs should return an error.
+ fn installed_application_bundle_ids(&self) -> Result<Vec<String>, String> {
+ Err("Listing installed application bundle IDs is only supported on macOS.".to_string())
+ }
+
+ /// Returns the application icon for `bundle_id` encoded as PNG bytes.
+ ///
+ /// The broker returns raw bytes so callers can choose their own transport format, such as a
+ /// Tauri command converting them into a data URL.
+ fn application_icon_png(&self, _bundle_id: &str) -> Result<Vec<u8>, String> {
+ Err("Reading application icons by bundle ID is only supported on macOS.".to_string())
+ }
+
fn launch_app_bundle(&self, _bundle_id: &str) -> Result<(), String> {
Err("Launching apps by bundle ID is only supported on macOS.".to_string())
}
@@ -58,6 +74,36 @@ pub struct AppSearchResult {
pub bundle_id: String,
}
+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+pub(crate) fn in_memory_app_search_results(
+ installed_apps: &[AppSearchResult],
+ query: &str,
+) -> Vec<AppSearchResult> {
+ let query = query.trim();
+
+ if query.is_empty() {
+ return installed_apps.to_vec();
+ }
+
+ if let Some(result) = installed_apps
+ .iter()
+ .find(|result| result.bundle_id == query)
+ .cloned()
+ {
+ return vec![result];
+ }
+
+ let lower_query = query.to_lowercase();
+ installed_apps
+ .iter()
+ .filter(|result| {
+ result.name.to_lowercase().contains(&lower_query)
+ || result.bundle_id.to_lowercase().contains(&lower_query)
+ })
+ .cloned()
+ .collect()
+}
+
fn fallback_integration_display_name(bundle_id: &str) -> String {
let trimmed = bundle_id.trim();
@@ -78,6 +124,7 @@ fn fallback_integration_display_name(bundle_id: &str) -> String {
/// This lets the highlighter compile on non-macOS platforms while making it explicit that there is
/// currently no accessibility or cursor integration there.
#[cfg(not(target_os = "macos"))]
+#[derive(Default)]
pub struct NoopBroker;
#[cfg(not(target_os = "macos"))]
@@ -96,7 +143,28 @@ impl OsBroker for NoopBroker {
#[cfg(test)]
mod tests {
- use super::fallback_integration_display_name;
+ use super::{AppSearchResult, fallback_integration_display_name, in_memory_app_search_results};
+
+ #[test]
+ fn exact_bundle_id_search_returns_the_matching_app() {
+ let results = in_memory_app_search_results(
+ &[
+ AppSearchResult {
+ name: "TextEdit".to_string(),
+ bundle_id: "com.apple.TextEdit".to_string(),
+ },
+ AppSearchResult {
+ name: "TextEdit Helper".to_string(),
+ bundle_id: "com.example.TextEditHelper".to_string(),
+ },
+ ],
+ "com.apple.TextEdit",
+ );
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].name, "TextEdit");
+ assert_eq!(results[0].bundle_id, "com.apple.TextEdit");
+ }
#[test]
fn fallback_handles_empty_bundle_ids() {
diff --git a/harper-desktop/src/lib/client.ts b/harper-desktop/src/lib/client.ts
index 596ffdeb2..0aa8f32a9 100644
--- a/harper-desktop/src/lib/client.ts
+++ b/harper-desktop/src/lib/client.ts
@@ -40,8 +40,15 @@ export interface Integration {
display_name: string;
}
+export interface AppSearchResult {
+ name: string;
+ bundle_id: string;
+}
+
export type AccessibilityPermissionStatus = 'Granted' | 'NotGranted' | 'Unsupported';
+/** Provides an easy-to-use interface for interacting with the main Rust Tauri process.
+ * Relevant because that is where the canonical state is stored. */
export class Client {
static async getLintConfig(): Promise<LintConfig> {
return await invoke<LintConfig>('get_lint_config');
@@ -153,6 +160,18 @@ export class Client {
await invoke('set_integration_enabled', { bundleId, enabled });
}
+ static async getInstalledApplicationBundleIds(): Promise<string[]> {
+ return await invoke<string[]>('get_installed_application_bundle_ids');
+ }
+
+ static async getApplicationIconDataUrl(bundleId: string): Promise<string> {
+ return await invoke<string>('get_application_icon_data_url', { bundleId });
+ }
+
+ static async searchApps(query: string): Promise<AppSearchResult[]> {
+ return await invoke<AppSearchResult[]>('search_apps', { query });
+ }
+
static async launchApp(bundleId: string): Promise<void> {
await invoke('launch_app', { bundleId });
}
@@ -182,18 +201,20 @@ export class Client {
}
}
-function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
+async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error(message)), timeoutMs);
});
- return Promise.race([promise, timeout]).finally(() => {
+ try {
+ return await Promise.race([promise, timeout]);
+ } finally {
if (timeoutId) {
clearTimeout(timeoutId);
}
- });
+ }
}
function rustDialectToDialect(dialect: RustDialect): Dialect {
diff --git a/harper-desktop/src/lib/settings/components/AppIcon.svelte b/harper-desktop/src/lib/settings/components/AppIcon.svelte
new file mode 100644
index 000000000..0b9b2aaba
--- /dev/null
+++ b/harper-desktop/src/lib/settings/components/AppIcon.svelte
@@ -0,0 +1,75 @@
+<script lang="ts">
+import { onDestroy, onMount } from 'svelte';
+import { Client } from '$lib/client';
+
+export let bundleId = '';
+export let name: string | undefined = undefined;
+export let className = '';
+
+let element: HTMLDivElement;
+let iconDataUrl = '';
+let iconRequestId = 0;
+let isVisible = false;
+let observer: IntersectionObserver | undefined;
+
+$: fallbackLabel = fallbackInitial(name ?? bundleId);
+$: if (isVisible) {
+ void loadIcon(bundleId);
+}
+
+onMount(() => {
+ if (!('IntersectionObserver' in window)) {
+ isVisible = true;
+ return;
+ }
+
+ observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ isVisible = true;
+ observer?.disconnect();
+ observer = undefined;
+ }
+ },
+ { rootMargin: '80px' },
+ );
+
+ observer.observe(element);
+});
+
+onDestroy(() => {
+ observer?.disconnect();
+});
+
+async function loadIcon(nextBundleId: string) {
+ const requestId = ++iconRequestId;
+ const trimmedBundleId = nextBundleId.trim();
+ iconDataUrl = '';
+
+ if (!trimmedBundleId) {
+ return;
+ }
+
+ try {
+ const nextIconDataUrl = await Client.getApplicationIconDataUrl(trimmedBundleId);
+
+ if (requestId === iconRequestId && bundleId.trim() === trimmedBundleId) {
+ iconDataUrl = nextIconDataUrl;
+ }
+ } catch {
+ // Keep the fallback when an app icon cannot be loaded.
+ }
+}
+
+function fallbackInitial(value: string) {
+ return Array.from(value.trim())[0]?.toUpperCase() ?? '?';
+}
+</script>
+
+<div bind:this={element} class={`app-icon ${className}`} style="--app-tint: #6b6f78" aria-hidden="true">
+ {#if iconDataUrl}
+ <img src={iconDataUrl} alt="" />
+ {:else}
+ {fallbackLabel}
+ {/if}
+</div>
diff --git a/harper-desktop/src/lib/settings/components/AppPickerModal.svelte b/harper-desktop/src/lib/settings/components/AppPickerModal.svelte
index 43254e8d2..42acb4b0a 100644
--- a/harper-desktop/src/lib/settings/components/AppPickerModal.svelte
+++ b/harper-desktop/src/lib/settings/components/AppPickerModal.svelte
@@ -1,5 +1,7 @@
<script lang="ts">
-import { invoke } from '@tauri-apps/api/core';
+import { onMount } from 'svelte';
+import { type AppSearchResult, Client } from '$lib/client';
+import AppIcon from './AppIcon.svelte';
export let bundleId = '';
export let existingBundleIds: string[];
@@ -7,31 +9,43 @@ export let isSaving = false;
export let close: () => void;
export let add: (bundleId: string) => void;
-let searchResults: Array<{ name: string; bundle_id: string }> = [];
+let searchResults: AppSearchResult[] = [];
let isSearching = false;
let debounceTimeout: number | null = null;
+let searchRequestId = 0;
$: trimmedBundleId = bundleId.trim();
$: isDuplicate = existingBundleIds.includes(trimmedBundleId);
$: canAdd = Boolean(trimmedBundleId) && !isDuplicate && !isSaving;
+onMount(() => {
+ const initialSearch = window.setTimeout(() => {
+ void performSearch(bundleId);
+ }, 0);
+
+ return () => window.clearTimeout(initialSearch);
+});
+
async function performSearch(query: string) {
- if (!query.trim()) {
- searchResults = [];
- return;
- }
+ const requestId = ++searchRequestId;
isSearching = true;
try {
- const results = await invoke<Array<{ name: string; bundle_id: string }>>('search_apps', {
- query,
- });
- searchResults = results;
+ const results = await Client.searchApps(query);
+
+ if (requestId === searchRequestId && query === bundleId) {
+ searchResults = results;
+ }
} catch (error) {
console.error('Search failed:', error);
- searchResults = [];
+
+ if (requestId === searchRequestId) {
+ searchResults = [];
+ }
} finally {
- isSearching = false;
+ if (requestId === searchRequestId) {
+ isSearching = false;
+ }
}
}
@@ -50,7 +64,7 @@ function handleInput(event: Event) {
function selectApp(selectedBundleId: string) {
bundleId = selectedBundleId;
- searchResults = [];
+ void performSearch(bundleId);
}
function submit() {
@@ -119,8 +133,11 @@ function submit() {
}
}}
>
- <div class="app-result-name">{result.name}</div>
- <div class="app-result-bundle-id">{result.bundle_id}</div>
+ <AppIcon bundleId={result.bundle_id} name={result.name} />
+ <div class="app-result-copy">
+ <div class="app-result-name">{result.name}</div>
+ <div class="app-result-bundle-id">{result.bundle_id}</div>
+ </div>
</div>
{/each}
{:else if trimmedBundleId}
diff --git a/harper-desktop/src/lib/settings/pages/GettingStartedPage.svelte b/harper-desktop/src/lib/settings/pages/GettingStartedPage.svelte
index 3568054f1..826e5a7ee 100644
--- a/harper-desktop/src/lib/settings/pages/GettingStartedPage.svelte
+++ b/harper-desktop/src/lib/settings/pages/GettingStartedPage.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { type AccessibilityPermissionStatus, Client, type Integration } from '$lib/client';
+import AppIcon from '../components/AppIcon.svelte';
import { createInitialSettingsState, type SectionId, type SettingsState } from '../settings-data';
type SetupStep = {
@@ -370,7 +371,7 @@ function buildSetupSteps(
</div>
{:else if step.id === "integration" && accessibilityStatus === "Granted" && isLoadingIntegrations}
<div class="detected-app">
- <div class="app-tile" style="--app-tint: #5a5f68">T</div>
+ <AppIcon bundleId="com.apple.TextEdit" name="TextEdit" />
<div class="grow">
<strong>Checking TextEdit</strong>
<p>Loading integration state...</p>
@@ -378,7 +379,7 @@ function buildSetupSteps(
</div>
{:else if step.id === "integration" && accessibilityStatus === "Granted" && isTextEditEnabled}
<div class="detected-app">
- <div class="app-tile" style="--app-tint: #5a5f68">T</div>
+ <AppIcon bundleId="com.apple.TextEdit" name="TextEdit" />
<div class="grow">
<strong>TextEdit enabled</strong>
<p>Harper is configured to check TextEdit.</p>
@@ -386,7 +387,7 @@ function buildSetupSteps(
</div>
{:else if step.id === "integration" && accessibilityStatus === "Granted"}
<div class="detected-app">
- <div class="app-tile" style="--app-tint: #5a5f68">T</div>
+ <AppIcon bundleId="com.apple.TextEdit" name="TextEdit" />
<div class="grow">
<strong>TextEdit detected</strong>
<p>A good starter app for trying Harper.</p>
diff --git a/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte b/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte
index c47905166..353cd909e 100644
--- a/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte
+++ b/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { Client, type Integration } from '$lib/client';
+import AppIcon from '../components/AppIcon.svelte';
import AppPickerModal from '../components/AppPickerModal.svelte';
interface IntegrationRow extends Integration {
@@ -8,13 +9,13 @@ interface IntegrationRow extends Integration {
}
let integrations: Integration[] = [];
+let integrationApps: IntegrationRow[] = [];
let integrationsError = '';
let isIntegrationsLoading = true;
let isIntegrationsSaving = false;
let appPickerOpen = false;
let newBundleId = '';
-$: integrationApps = integrations.map(toIntegrationRow);
$: existingBundleIds = integrations.map((integration) => integration.bundle_id);
onMount(() => {
@@ -27,6 +28,7 @@ async function loadIntegrations() {
try {
integrations = await Client.getIntegrations();
+ integrationApps = integrations.map(toIntegrationRow);
} catch (error) {
integrationsError = `Unable to load integrations: ${error}`;
} finally {
@@ -43,10 +45,14 @@ function toIntegrationRow(integration: Integration): IntegrationRow {
async function setIntegrationEnabled(bundleId: string, enabled: boolean) {
const previousIntegrations = integrations;
+ const previousIntegrationApps = integrationApps;
integrations = integrations.map((integration) =>
integration.bundle_id === bundleId ? { ...integration, enabled } : integration,
);
+ integrationApps = integrationApps.map((app) =>
+ app.bundle_id === bundleId ? { ...app, enabled } : app,
+ );
isIntegrationsSaving = true;
integrationsError = '';
@@ -54,6 +60,7 @@ async function setIntegrationEnabled(bundleId: string, enabled: boolean) {
await Client.setIntegrationEnabled(bundleId, enabled);
} catch (error) {
integrations = previousIntegrations;
+ integrationApps = previousIntegrationApps;
integrationsError = `Unable to update integration: ${error}`;
} finally {
isIntegrationsSaving = false;
@@ -62,8 +69,10 @@ async function setIntegrationEnabled(bundleId: string, enabled: boolean) {
async function removeIntegration(bundleId: string) {
const previousIntegrations = integrations;
+ const previousIntegrationApps = integrationApps;
integrations = integrations.filter((integration) => integration.bundle_id !== bundleId);
+ integrationApps = integrationApps.filter((app) => app.bundle_id !== bundleId);
isIntegrationsSaving = true;
integrationsError = '';
@@ -71,6 +80,7 @@ async function removeIntegration(bundleId: string) {
await Client.removeIntegration(bundleId);
} catch (error) {
integrations = previousIntegrations;
+ integrationApps = previousIntegrationApps;
integrationsError = `Unable to remove integration: ${error}`;
} finally {
isIntegrationsSaving = false;
@@ -88,11 +98,13 @@ async function addIntegration(bundleId: string) {
}
const previousIntegrations = integrations;
+ const previousIntegrationApps = integrationApps;
integrations = [
...integrations,
{ bundle_id: trimmedBundleId, enabled: true, display_name: trimmedBundleId },
];
+ integrationApps = integrations.map(toIntegrationRow);
isIntegrationsSaving = true;
integrationsError = '';
@@ -102,6 +114,7 @@ async function addIntegration(bundleId: string) {
closeAppPicker();
} catch (error) {
integrations = previousIntegrations;
+ integrationApps = previousIntegrationApps;
integrationsError = `Unable to add integration: ${error}`;
} finally {
isIntegrationsSaving = false;
@@ -133,7 +146,7 @@ function closeAppPicker() {
{:else}
{#each integrationApps as app}
<div class="app-row">
- <div class="app-tile" style="--app-tint: #6b6f78">{app.name[0]}</div>
+ <AppIcon bundleId={app.bundle_id} name={app.name} />
<div class="grow">
<strong>{app.name}</strong>
<p>{app.bundle_id}</p>
diff --git a/harper-desktop/src/lib/settings/settings.css b/harper-desktop/src/lib/settings/settings.css
index 5f2cb8d12..ab1988a9b 100644
--- a/harper-desktop/src/lib/settings/settings.css
+++ b/harper-desktop/src/lib/settings/settings.css
@@ -748,7 +748,8 @@ em,
}
.pack-icon,
-.app-tile {
+.app-tile,
+.app-icon {
display: grid;
place-items: center;
color: #fff;
@@ -772,12 +773,21 @@ em,
flex-basis: 16px;
}
-.app-tile {
+.app-tile,
+.app-icon {
width: 28px;
height: 28px;
flex: 0 0 28px;
border-radius: 7px;
background: var(--app-tint);
+ overflow: hidden;
+}
+
+.app-tile img,
+.app-icon img {
+ width: 24px;
+ height: 24px;
+ object-fit: contain;
}
.pack-title {
@@ -921,8 +931,8 @@ em,
.app-result {
display: flex;
- flex-direction: column;
- gap: 2px;
+ align-items: center;
+ gap: 10px;
padding: 10px 12px;
border-radius: 6px;
cursor: pointer;
@@ -937,6 +947,10 @@ em,
outline-offset: -2px;
}
+.app-result-copy {
+ min-width: 0;
+}
+
.app-result-name {
font-weight: 600;
color: var(--settings-ink);