Skip to content

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

fix(desktop): hide highlights while windows move (#3419)

Elijah Potter59a32819a922
diff --git a/harper-desktop/src-tauri/src/mac_broker.rs b/harper-desktop/src-tauri/src/mac_broker.rs
index ae9483c39..1a9e477b4 100644
--- a/harper-desktop/src-tauri/src/mac_broker.rs
+++ b/harper-desktop/src-tauri/src/mac_broker.rs
@@ -10,21 +10,38 @@ use accessibility_sys::{
kAXValueTypeCFRange, kAXValueTypeCGRect, pid_t,
};
use core::{ffi::c_void, mem::MaybeUninit};
+use core_foundation::array::CFArray;
use core_foundation::base::{CFRange, CFType, TCFType};
use core_foundation::boolean::CFBoolean;
use core_foundation::dictionary::CFDictionary;
-use core_foundation::string::CFString;
+use core_foundation::number::CFNumber;
+use core_foundation::string::{CFString, CFStringRef};
use core_graphics::event::CGEvent;
use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
+use core_graphics::window::{
+ kCGNullWindowID, kCGWindowAlpha, kCGWindowBounds, kCGWindowLayer,
+ kCGWindowListExcludeDesktopElements, kCGWindowListOptionOnScreenOnly, kCGWindowOwnerPID,
+};
use harper_core::linting::{Lint, Suggestion};
use objc2_app_kit::NSRunningApplication;
use objc2_foundation::NSRect;
-use std::{cell::RefCell, collections::BTreeMap, error::Error as StdError, ptr, rc::Rc};
+use std::{
+ cell::RefCell,
+ collections::BTreeMap,
+ error::Error as StdError,
+ ptr,
+ rc::Rc,
+ time::{Duration, Instant},
+};
use crate::config::{Config, Integration};
use crate::os_broker::{AccessibilityPermissionStatus, OsBroker};
use crate::rect::{ActionableLint, Rect};
+const WINDOW_MOVEMENT_SETTLE_DURATION: Duration = Duration::from_millis(150);
+const WINDOW_FRAME_TOLERANCE: f64 = 0.5;
+type WindowInfo = CFDictionary<CFString, CFType>;
+
/// macOS implementation of the OS data the highlighter needs.
///
/// `MacBroker` owns focus memory because clicking the overlay can make the highlighter process the
@@ -33,6 +50,14 @@ use crate::rect::{ActionableLint, Rect};
pub struct MacBroker {
last_focused: Option<pid_t>,
integrations: Rc<RefCell<Vec<Integration>>>,
+ window_movement: Option<WindowMovementState>,
+}
+
+#[derive(Debug, Clone)]
+struct WindowMovementState {
+ pid: pid_t,
+ frame: Rect,
+ last_changed_at: Instant,
}
impl MacBroker {
@@ -40,6 +65,7 @@ impl MacBroker {
Self {
last_focused: None,
integrations,
+ window_movement: None,
}
}
@@ -54,6 +80,32 @@ impl MacBroker {
Ok(Some(focused_pid))
}
}
+
+ fn window_is_moving(&mut self, pid: pid_t) -> bool {
+ let Some(frame) = frontmost_window_frame_for_pid(pid) else {
+ self.window_movement = None;
+ return true;
+ };
+
+ let now = Instant::now();
+ let Some(state) = &mut self.window_movement else {
+ self.window_movement = Some(settled_window_state(pid, frame, now));
+ return false;
+ };
+
+ if state.pid != pid {
+ *state = settled_window_state(pid, frame, now);
+ return false;
+ }
+
+ if window_frame_changed(state.frame, frame) {
+ state.frame = frame;
+ state.last_changed_at = now;
+ return true;
+ }
+
+ now.duration_since(state.last_changed_at) < WINDOW_MOVEMENT_SETTLE_DURATION
+ }
}
impl Default for MacBroker {
@@ -69,14 +121,23 @@ impl OsBroker for MacBroker {
) -> Vec<ActionableLint> {
let pid = match self.target_pid() {
Ok(Some(pid)) => pid,
- Ok(None) => return Vec::new(),
+ Ok(None) => {
+ self.window_movement = None;
+ return Vec::new();
+ }
Err(err) => {
+ self.window_movement = None;
eprintln!("Unable to identify focused window: {err}");
return Vec::new();
}
};
if !is_pid_approved(pid, &self.integrations.borrow()) {
+ self.window_movement = None;
+ return Vec::new();
+ }
+
+ if self.window_is_moving(pid) {
return Vec::new();
}
@@ -158,6 +219,104 @@ fn bundle_identifier_for_pid(pid: pid_t) -> Result<Option<String>, Box<dyn StdEr
Ok(Some(bundle_identifier.to_string()))
}
+fn window_frame_changed(previous: Rect, current: Rect) -> bool {
+ !nearly_equal(previous.x, current.x)
+ || !nearly_equal(previous.y, current.y)
+ || !nearly_equal(previous.width, current.width)
+ || !nearly_equal(previous.height, current.height)
+}
+
+fn settled_window_state(pid: pid_t, frame: Rect, now: Instant) -> WindowMovementState {
+ WindowMovementState {
+ pid,
+ frame,
+ last_changed_at: now
+ .checked_sub(WINDOW_MOVEMENT_SETTLE_DURATION)
+ .unwrap_or(now),
+ }
+}
+
+fn nearly_equal(left: f64, right: f64) -> bool {
+ (left - right).abs() <= WINDOW_FRAME_TOLERANCE
+}
+
+fn frontmost_window_frame_for_pid(pid: pid_t) -> Option<Rect> {
+ let window_infos = core_graphics::window::copy_window_info(
+ kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
+ kCGNullWindowID,
+ )?;
+ let window_infos =
+ unsafe { CFArray::<WindowInfo>::wrap_under_get_rule(window_infos.as_concrete_TypeRef()) };
+
+ window_infos
+ .iter()
+ .filter(|window_info| window_pid(window_info) == Some(pid))
+ .filter(|window_info| window_layer(window_info) == Some(0))
+ .filter(|window_info| window_alpha(window_info).is_some_and(|alpha| alpha > 0.0))
+ .find_map(|window_info| window_bounds(&window_info))
+}
+
+fn window_pid(window_info: &WindowInfo) -> Option<pid_t> {
+ dictionary_i64(window_info, unsafe { kCGWindowOwnerPID }).map(|value| value as pid_t)
+}
+
+fn window_layer(window_info: &WindowInfo) -> Option<i64> {
+ dictionary_i64(window_info, unsafe { kCGWindowLayer })
+}
+
+fn window_alpha(window_info: &WindowInfo) -> Option<f64> {
+ dictionary_f64(window_info, unsafe { kCGWindowAlpha })
+}
+
+fn window_bounds(window_info: &WindowInfo) -> Option<Rect> {
+ let bounds = dictionary_dictionary(window_info, unsafe { kCGWindowBounds })?;
+
+ Some(Rect {
+ x: dictionary_f64(
+ &bounds,
+ CFString::from_static_string("X").as_concrete_TypeRef(),
+ )?,
+ y: dictionary_f64(
+ &bounds,
+ CFString::from_static_string("Y").as_concrete_TypeRef(),
+ )?,
+ width: dictionary_f64(
+ &bounds,
+ CFString::from_static_string("Width").as_concrete_TypeRef(),
+ )?,
+ height: dictionary_f64(
+ &bounds,
+ CFString::from_static_string("Height").as_concrete_TypeRef(),
+ )?,
+ })
+}
+
+fn dictionary_i64(dictionary: &WindowInfo, key: CFStringRef) -> Option<i64> {
+ dictionary_number(dictionary, key)?.to_i64()
+}
+
+fn dictionary_f64(dictionary: &WindowInfo, key: CFStringRef) -> Option<f64> {
+ dictionary_number(dictionary, key)?.to_f64()
+}
+
+fn dictionary_number(dictionary: &WindowInfo, key: CFStringRef) -> Option<CFNumber> {
+ let value = dictionary_value(dictionary, key)?;
+
+ Some(unsafe { CFNumber::wrap_under_get_rule(value.as_CFTypeRef() as _) })
+}
+
+fn dictionary_dictionary(dictionary: &WindowInfo, key: CFStringRef) -> Option<WindowInfo> {
+ let value = dictionary_value(dictionary, key)?;
+
+ Some(unsafe { WindowInfo::wrap_under_get_rule(value.as_CFTypeRef() as _) })
+}
+
+fn dictionary_value(dictionary: &WindowInfo, key: CFStringRef) -> Option<CFType> {
+ let key = unsafe { CFString::wrap_under_get_rule(key) };
+
+ dictionary.find(&key).map(|value| value.clone())
+}
+
fn ax_element_attribute(
element: &AXUIElement,
name: &str,
diff --git a/harper-desktop/src/lib/settings/pages/GeneralPage.svelte b/harper-desktop/src/lib/settings/pages/GeneralPage.svelte
index ec7c7c911..d8141549e 100644
--- a/harper-desktop/src/lib/settings/pages/GeneralPage.svelte
+++ b/harper-desktop/src/lib/settings/pages/GeneralPage.svelte
@@ -13,7 +13,6 @@ const DialectValue = {
} as const;
let menuBar = true;
-let menuBarClick = 'open-settings';
let launchAtStartup = false;
let autoUpdate = true;
let dialect = 'american';
@@ -208,22 +207,6 @@ function settingsValueToDialect(value: string): Dialect {
</button>
</div>
- <div class="inline-row">
- <label for="menu-bar-click">Click the icon to:</label>
- <select
- id="menu-bar-click"
- class="select"
- disabled
- title="Not wired yet"
- bind:value={menuBarClick}
- >
- <option value="open-settings">Open settings</option>
- <option value="show-menu">Show a menu</option>
- <option value="toggle-pause">Pause or resume</option>
- <option value="quick-review">Open quick review</option>
- </select>
- </div>
-
<div class="row">
<div>
<strong>Launch Harper at startup</strong>
diff --git a/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte b/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte
index 88d15fd87..f769eeb67 100644
--- a/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte
+++ b/harper-desktop/src/lib/settings/pages/IntegrationsPage.svelte
@@ -115,29 +115,6 @@ function closeAppPicker() {
</script>
<section>
- <div class="stanza">
- <div class="eyebrow">App integrations</div>
- <div class="row top">
- <div>
- <strong>Watch everywhere</strong>
- <p>Harper checks writing in any app that supports text input.</p>
- </div>
- <button
- class="toggle"
- type="button"
- role="switch"
- aria-checked="false"
- aria-label="Toggle watch everywhere"
- disabled
- title="Not wired yet"
- >
- <span></span>
- </button>
- </div>
- </div>
-
- <div class="divider"></div>
-
<div class="stanza">
<div class="eyebrow">Selected apps</div>
<p class="section-copy">Harper will only watch the apps you enable here.</p>
diff --git a/harper-desktop/src/lib/settings/pages/RulesPage.svelte b/harper-desktop/src/lib/settings/pages/RulesPage.svelte
index e37cda2c5..e50bb203d 100644
--- a/harper-desktop/src/lib/settings/pages/RulesPage.svelte
+++ b/harper-desktop/src/lib/settings/pages/RulesPage.svelte
@@ -228,6 +228,14 @@ function isRuleEnabled(rule: RuleItem) {
return lintConfig?.[rule.id] ?? defaultLintConfig?.[rule.id] ?? false;
}
+function allKnownRuleIds() {
+ return new Set([
+ ...Object.keys(defaultLintConfig ?? {}),
+ ...Object.keys(lintConfig ?? {}),
+ ...displayedRules.map((rule) => rule.id),
+ ]);
+}
+
async function setRuleOverride(ruleId: string, value: RuleOverride) {
const nextRules = { ...rules };
@@ -288,19 +296,17 @@ async function resetRules() {
}
async function disableRules() {
- const nextRules = Object.fromEntries(
- displayedRules.map((rule) => [rule.id, 'off' as RuleOverride]),
- );
+ const nextLintConfig = { ...(lintConfig ?? defaultLintConfig ?? {}) };
- if (!lintConfig) {
- rules = nextRules;
- return;
+ for (const ruleId of allKnownRuleIds()) {
+ nextLintConfig[ruleId] = false;
}
- const nextLintConfig = { ...lintConfig };
+ const nextRules = rulesFromLintConfig(nextLintConfig, defaultLintConfig ?? {});
- for (const rule of displayedRules) {
- nextLintConfig[rule.id] = false;
+ if (!lintConfig) {
+ rules = nextRules;
+ return;
}
await saveLintConfig(nextLintConfig, nextRules);