Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix(desktop): improve battery life (#3753)
Elijah Potteredff5176c59b
diff --git a/Cargo.lock b/Cargo.lockindex 814527f81..570909ad7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1059,8 +1059,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "53b6f5d101f0f6322c8646a45b7c581a673e476329040d97565815c2461dd0c4"dependencies = ["ahash",- "cached_proc_macro",- "cached_proc_macro_types",+ "cached_proc_macro 0.27.0",+ "cached_proc_macro_types 0.1.1","hashbrown 0.16.1","once_cell","parking_lot",@@ -1068,6 +1068,21 @@ dependencies = ["web-time",]+[[package]]+name = "cached"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc0df7748fe2f601e376916ab19e7bfc2c74461b8abe3bce2ce20036ad8de38f"+dependencies = [+ "ahash",+ "cached_proc_macro 2.0.0",+ "cached_proc_macro_types 1.0.0",+ "hashbrown 0.16.1",+ "parking_lot",+ "thiserror 2.0.18",+ "web-time",+]+[[package]]name = "cached_proc_macro"version = "0.27.0"@@ -1080,12 +1095,30 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "cached_proc_macro"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66e734c52502e6cf54dce2ba07108906b04b8fe57f4f5e3ef7d58267b4abf060"+dependencies = [+ "darling 0.20.11",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "cached_proc_macro_types"version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ade8366b8bd5ba243f0a58f036cc0ca8a2f069cff1a2351ef1cac6b083e16fc0"+[[package]]+name = "cached_proc_macro_types"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26cf465651fa6ad902a2d327ba60c3a6bc61c6a2f4ad70d091cf20dfda0074ef"+[[package]]name = "cairo-rs"version = "0.18.5"@@ -4219,7 +4252,7 @@ dependencies = ["ammonia","bitflags 2.11.0","blanket",- "cached",+ "cached 0.59.0","criterion","foldhash 0.2.0","fst",@@ -4258,6 +4291,7 @@ dependencies = ["accessibility","accessibility-sys","base64 0.22.1",+ "cached 2.0.2","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.tomlindex c7a71654d..b5f2aed08 100644--- a/harper-desktop/src-tauri/Cargo.toml+++ b/harper-desktop/src-tauri/Cargo.toml@@ -37,6 +37,7 @@ harper-dictionary-wordlist = { path = "../../harper-dictionary-wordlist" }egui_commonmark = "0.23.0"tokio = { version = "1.52.2", features = ["full"] }tauri-plugin-os = "2.3.2"+cached = "2.0.2"[target.'cfg(target_os = "macos")'.dependencies]accessibility = "0.2.0"diff --git a/harper-desktop/src-tauri/src/highlighter/mod.rs b/harper-desktop/src-tauri/src/highlighter/mod.rsindex 422f836ab..4db973fff 100644--- a/harper-desktop/src-tauri/src/highlighter/mod.rs+++ b/harper-desktop/src-tauri/src/highlighter/mod.rs@@ -4,18 +4,15 @@ mod window;mod window_manager;use std::collections::BTreeMap;-use std::time::Duration;pub use error::Error;-use window_manager::{WindowManager, WindowManagerCallbacks, WindowManagerIntervals};+use window_manager::{WindowManager, WindowManagerCallbacks};use harper_core::{Document, linting::Lint};use crate::os_broker::{LintText, OsBroker};use crate::rect::ActionableLint;-const DEFAULT_READ_INTERVAL: Duration = Duration::from_millis(100);-type IgnoreLint = Box<dyn FnMut(&Lint, &Document)>;type AddToDictionary = Box<dyn FnMut(&str)>;type DisableRule = Box<dyn FnMut(&str)>;@@ -58,20 +55,11 @@ impl Highlighter {disable_rule,refresh_config,},- WindowManagerIntervals {- read: DEFAULT_READ_INTERVAL,- config_poll: Duration::from_secs(1),- },)?,context,})}- pub fn with_read_interval(mut self, read_interval: Duration) -> Self {- self.window_manager.set_read_interval(read_interval);- self- }-pub fn run_window_for_each_monitor(self) -> Result<(), Error> {let Self {context,diff --git a/harper-desktop/src-tauri/src/highlighter/window_manager.rs b/harper-desktop/src-tauri/src/highlighter/window_manager.rsindex 9b0bfca31..5214f6ed9 100644--- a/harper-desktop/src-tauri/src/highlighter/window_manager.rs+++ b/harper-desktop/src-tauri/src/highlighter/window_manager.rs@@ -3,6 +3,7 @@ use std::time::{Duration, Instant};use winit::application::ApplicationHandler;use winit::event::{ElementState, MouseButton, WindowEvent};use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};+use winit::monitor::MonitorHandle;#[cfg(target_os = "macos")]use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};use winit::window::WindowId;@@ -17,6 +18,9 @@ use super::window::Window;use crate::os_broker::{LintText, OsBroker};use crate::rect::ActionableLint;+const DEFAULT_READ_INTERVAL: Duration = Duration::from_nanos(16_666_667);+const CONFIG_POLL_INTERVAL: Duration = Duration::from_secs(1);+/// Owns the winit event loop and the overlay windows created for each monitor.////// `WindowManager` is intentionally separate from `Highlighter` because winit event-loop ownership@@ -32,8 +36,6 @@ pub struct WindowManager {add_to_dictionary: AddToDictionary,disable_rule: DisableRule,refresh_config: RefreshConfig,- read_interval: Duration,- config_poll_interval: Duration,}pub struct WindowManagerCallbacks {@@ -44,11 +46,6 @@ pub struct WindowManagerCallbacks {pub refresh_config: RefreshConfig,}-pub struct WindowManagerIntervals {- pub read: Duration,- pub config_poll: Duration,-}-impl WindowManager {/// Creates the event loop before windows exist because winit requires window creation to happen/// from inside that loop's lifecycle callbacks.@@ -56,7 +53,6 @@ impl WindowManager {context: egui::Context,os_broker: Box<dyn OsBroker>,callbacks: WindowManagerCallbacks,- intervals: WindowManagerIntervals,) -> Result<Self, Error> {let mut event_loop_builder = EventLoop::builder();@@ -75,8 +71,6 @@ impl WindowManager {add_to_dictionary: callbacks.add_to_dictionary,disable_rule: callbacks.disable_rule,refresh_config: callbacks.refresh_config,- read_interval: intervals.read,- config_poll_interval: intervals.config_poll,})}@@ -85,11 +79,6 @@ impl WindowManager {self.rects = rects;}- /// Lets callers tune OS polling without exposing the window-manager internals that schedule it.- pub fn set_read_interval(&mut self, read_interval: Duration) {- self.read_interval = read_interval;- }-/// Transfers ownership into winit's application handler because `run_app` owns the process-level/// event loop until the overlay exits.pub fn run_window_for_each_monitor(self) -> Result<(), Error> {@@ -104,14 +93,11 @@ impl WindowManager {disable_rule: self.disable_rule,refresh_config: self.refresh_config,},- WindowManagerIntervals {- read: self.read_interval,- config_poll: self.config_poll_interval,- },);- self.event_loop- .set_control_flow(ControlFlow::WaitUntil(Instant::now() + self.read_interval));+ self.event_loop.set_control_flow(ControlFlow::WaitUntil(+ Instant::now() + DEFAULT_READ_INTERVAL,+ ));let result = self.event_loop.run_app(&mut app);if let Some(error) = app.error {@@ -129,7 +115,6 @@ struct WindowManagerApp {os_broker: Box<dyn OsBroker>,lint_text: LintText,read_interval: Duration,- config_poll_interval: Duration,last_read: Instant,last_config_poll: Instant,refresh_config: RefreshConfig,@@ -146,9 +131,8 @@ impl WindowManagerApp {rects: Vec<ActionableLint>,os_broker: Box<dyn OsBroker>,callbacks: WindowManagerCallbacks,- intervals: WindowManagerIntervals,) -> Self {- let read_interval = intervals.read;+ let read_interval = DEFAULT_READ_INTERVAL;Self {context,windows: Vec::new(),@@ -161,7 +145,6 @@ impl WindowManagerApp {os_broker,lint_text: callbacks.lint_text,read_interval,- config_poll_interval: intervals.config_poll,last_read: Instant::now() - read_interval,last_config_poll: Instant::now(),refresh_config: callbacks.refresh_config,@@ -235,6 +218,13 @@ impl WindowManagerApp {}}+fn monitor_refresh_interval(monitor: &MonitorHandle) -> Option<Duration> {+ monitor+ .refresh_rate_millihertz()+ .filter(|refresh_rate| *refresh_rate > 0)+ .map(|refresh_rate| Duration::from_nanos(1_000_000_000_000 / u64::from(refresh_rate)))+}+impl ApplicationHandler for WindowManagerApp {fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {let now = Instant::now();@@ -244,7 +234,7 @@ impl ApplicationHandler for WindowManagerApp {self.last_read = now;}- if now.duration_since(self.last_config_poll) >= self.config_poll_interval {+ if now.duration_since(self.last_config_poll) >= CONFIG_POLL_INTERVAL {self.refresh_config();self.last_config_poll = now;}@@ -252,7 +242,7 @@ impl ApplicationHandler for WindowManagerApp {self.update_cursor_hittest(event_loop);let next_read = self.last_read + self.read_interval;- let next_config_poll = self.last_config_poll + self.config_poll_interval;+ let next_config_poll = self.last_config_poll + CONFIG_POLL_INTERVAL;event_loop.set_control_flow(ControlFlow::WaitUntil(next_read.min(next_config_poll)));}@@ -261,7 +251,13 @@ impl ApplicationHandler for WindowManagerApp {return;}- for monitor in event_loop.available_monitors() {+ let monitors = event_loop.available_monitors().collect::<Vec<_>>();++ if let Some(refresh_interval) = monitors.iter().filter_map(monitor_refresh_interval).min() {+ self.read_interval = refresh_interval;+ }++ for monitor in monitors {match pollster::block_on(Window::new(event_loop, monitor, self.context.clone())) {Ok(window) => self.windows.push(window),Err(error) => {diff --git a/harper-desktop/src-tauri/src/lib.rs b/harper-desktop/src-tauri/src/lib.rsindex 878f41e42..79f5c2a0d 100644--- a/harper-desktop/src-tauri/src/lib.rs+++ b/harper-desktop/src-tauri/src/lib.rs@@ -1,5 +1,6 @@use self::highlighter::Highlighter;use self::highlighter_service::HighlighterService;+use self::menu_bar_icon::menu_bar_icon;use crate::communication::{Client, ProtocolError};use crate::config::{Config, Integration};use crate::debounce::{DebounceState, DebounceStatus};@@ -14,11 +15,9 @@ use std::{cell::RefCell,rc::Rc,sync::{Arc, Mutex as StdMutex},- time::Duration,};use tauri::{Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent,- image::Image,menu::{HELP_SUBMENU_ID, Menu, MenuItem, PredefinedMenuItem},tray::{MouseButton, TrayIconBuilder, TrayIconEvent},};@@ -39,6 +38,7 @@ mod debounce;pub mod highlighter;pub mod highlighter_service;pub mod lint_kind_color;+mod menu_bar_icon;mod os_broker;pub mod rect;@@ -53,7 +53,10 @@ struct Args {#[derive(Subcommand)]enum Command {- Highlighter,+ Highlighter {+ #[arg(long)]+ no_parent: bool,+ },}const EDITOR_WINDOW_LABEL: &str = "main";@@ -84,36 +87,6 @@ fn service_menu_text(is_running: bool) -> &'static str {}}-fn service_status_color(is_running: bool) -> [u8; 4] {- match is_running {- true => [34, 197, 94, 255],- false => [239, 68, 68, 255],- }-}--fn menu_bar_icon(is_running: bool) -> tauri::Result<Image<'static>> {- let icon = Image::from_bytes(include_bytes!("../icons/menu-bar-icon.png"))?;- let width = icon.width();- let height = icon.height();- let mut rgba = icon.rgba().to_vec();-- draw_status_line(&mut rgba, width, height, service_status_color(is_running));-- Ok(Image::new_owned(rgba, width, height))-}--fn draw_status_line(rgba: &mut [u8], width: u32, height: u32, color: [u8; 4]) {- let line_height = (height.min(width) / 14).max(3);- let start_y = height.saturating_sub(line_height);-- for y in start_y..height {- for x in 0..width {- let index = ((y * width + x) * 4) as usize;- rgba[index..index + 4].copy_from_slice(&color);- }- }-}-fn show_editor_window(app: &tauri::AppHandle) -> tauri::Result<()> {if let Some(window) = app.get_webview_window(EDITOR_WINDOW_LABEL) {window.show()?;@@ -290,7 +263,7 @@ pub fn run() {let args = Args::parse();match args.command {- Some(Command::Highlighter) => run_highlighter(),+ Some(Command::Highlighter { no_parent }) => run_highlighter(!no_parent),None => run_tauri(),}}@@ -463,7 +436,9 @@ pub fn run_tauri() {.expect("error while running tauri application");}-pub fn run_highlighter() {+/// Run as a highlighter process.+/// Can configure whether to run standalone, or with a parent Tauri process+pub fn run_highlighter(has_parent: bool) {let client = Rc::new(RefCell::new(Client::current_process()));let sync_runtime = Rc::new(Builder::new_current_thread()@@ -472,7 +447,11 @@ pub fn run_highlighter() {.expect("failed to build highlighter protocol runtime"),);- let startup_config = fetch_highlighter_config(&mut client.borrow_mut(), &sync_runtime);+ let startup_config = if has_parent {+ fetch_highlighter_config(&mut client.borrow_mut(), &sync_runtime)+ } else {+ Ok(Config::default())+ };let startup_config = match startup_config {Ok(config) => config,@@ -591,20 +570,23 @@ pub fn run_highlighter() {Err(error) => eprintln!("failed to disable rule {rule_name}: {error}"),};- let refresh_config = move || match fetch_highlighter_config(- &mut refresh_client.borrow_mut(),- &refresh_runtime,- ) {- Ok(config) => apply_highlighter_config(- config,- &refresh_ignored_lints,- &refresh_user_dictionary,- &refresh_dialect,- &refresh_integrations,- &refresh_debounce_ms,- &refresh_linter,- ),- Err(error) => eprintln!("failed to refresh highlighter config: {error}"),+ let refresh_config = move || {+ if !has_parent {+ return;+ }++ match fetch_highlighter_config(&mut refresh_client.borrow_mut(), &refresh_runtime) {+ Ok(config) => apply_highlighter_config(+ config,+ &refresh_ignored_lints,+ &refresh_user_dictionary,+ &refresh_dialect,+ &refresh_integrations,+ &refresh_debounce_ms,+ &refresh_linter,+ ),+ Err(error) => eprintln!("failed to refresh highlighter config: {error}"),+ }};#[cfg(target_os = "macos")]@@ -621,7 +603,6 @@ pub fn run_highlighter() {disable_rule,refresh_config,)- .map(|highlighter| highlighter.with_read_interval(Duration::from_millis(16))).and_then(Highlighter::run_window_for_each_monitor){eprintln!("failed to run highlighter: {error}");diff --git a/harper-desktop/src-tauri/src/mac_broker/focused_window_pid.rs b/harper-desktop/src-tauri/src/mac_broker/focused_window_pid.rsindex 668b40dee..e4dcace03 100644--- a/harper-desktop/src-tauri/src/mac_broker/focused_window_pid.rs+++ b/harper-desktop/src-tauri/src/mac_broker/focused_window_pid.rs@@ -9,6 +9,7 @@ use std::error::Error as StdError;use super::core_foundation_utilities::ax_element_attribute;/// Pretty self-explanatory. Grabs the PID of the currently focused window.+/// Can be expensive. Do not perform in a hot loop.pub fn focused_window_pid() -> Result<pid_t, Box<dyn StdError>> {let system = AXUIElement::system_wide();let app = match ax_element_attribute(&system, kAXFocusedApplicationAttribute) {diff --git a/harper-desktop/src-tauri/src/mac_broker/mod.rs b/harper-desktop/src-tauri/src/mac_broker/mod.rsindex 5c3edc189..2ae5b2273 100644--- a/harper-desktop/src-tauri/src/mac_broker/mod.rs+++ b/harper-desktop/src-tauri/src/mac_broker/mod.rs@@ -1,3 +1,4 @@+use cached::cached;mod accessibility_activation;mod accessibility_text;mod app_catalog;@@ -54,7 +55,8 @@ use self::window_stability::{/// focused application. Remembering the last non-highlighter PID lets accessibility reads continue/// targeting the app the user was reviewing.pub struct MacBroker {- last_focused: Option<pid_t>,+ /// The PID of the most recently focused PID, along with the time the measurement was taken.+ 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>,@@ -75,14 +77,21 @@ impl MacBroker {}/// The process ID of the currently focused window.+ /// In the interest of performance, the returned value may be slightly stale.fn target_pid(&mut self) -> Result<Option<pid_t>, Box<dyn StdError>> {+ if let Some((last_focused, measurement_time)) = self.last_focused {+ if Instant::now().duration_since(measurement_time).as_secs() < 3 {+ return Ok(Some(last_focused));+ }+ }+let focused_pid = focused_window_pid::focused_window_pid()?;let current_pid = std::process::id() as pid_t;if focused_pid == current_pid {- Ok(self.last_focused)+ Ok(self.last_focused.map(|v| v.0))} else {- self.last_focused = Some(focused_pid);+ self.last_focused = Some((focused_pid, Instant::now()));Ok(Some(focused_pid))}}@@ -435,6 +444,7 @@ impl OsBroker for MacBroker {}}+#[cached(max_size = 1_000)]fn bundle_identifier_for_pid(pid: pid_t) -> Result<Option<String>, Box<dyn StdError>> {let Some(app) = NSRunningApplication::runningApplicationWithProcessIdentifier(pid) else {return Ok(None);diff --git a/harper-desktop/src-tauri/src/menu_bar_icon.rs b/harper-desktop/src-tauri/src/menu_bar_icon.rsnew file mode 100644index 000000000..fe6dcdfc1--- /dev/null+++ b/harper-desktop/src-tauri/src/menu_bar_icon.rs@@ -0,0 +1,31 @@+use tauri::image::Image;++fn service_status_color(is_running: bool) -> [u8; 4] {+ match is_running {+ true => [34, 197, 94, 255],+ false => [239, 68, 68, 255],+ }+}++pub fn menu_bar_icon(is_running: bool) -> tauri::Result<Image<'static>> {+ let icon = Image::from_bytes(include_bytes!("../icons/menu-bar-icon.png"))?;+ let width = icon.width();+ let height = icon.height();+ let mut rgba = icon.rgba().to_vec();++ draw_status_line(&mut rgba, width, height, service_status_color(is_running));++ Ok(Image::new_owned(rgba, width, height))+}++fn draw_status_line(rgba: &mut [u8], width: u32, height: u32, color: [u8; 4]) {+ let line_height = (height.min(width) / 14).max(3);+ let start_y = height.saturating_sub(line_height);++ for y in start_y..height {+ for x in 0..width {+ let index = ((y * width + x) * 4) as usize;+ rgba[index..index + 4].copy_from_slice(&color);+ }+ }+}