Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
refactor(desktop): misc. changes and documentation (#3594)
Elijah Potter5f9aa2055e51
diff --git a/AGENTS.md b/AGENTS.mdindex 146e96543..a73e1d21b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -71,6 +71,7 @@ Agents should remind humans of this when possible.- `packages/web/src/routes/docs/contributors/author-a-rule/+page.md`: Step-by-step workflow for implementing and testing new grammar rules.- `packages/web/src/routes/docs/contributors/visual-studio-code/+page.md`: How to run, debug, test, and package the VS Code extension locally.- `packages/web/src/routes/docs/contributors/chrome-extension/+page.md`: Internal architecture and local development notes for the browser extensions.+- `packages/web/src/routes/docs/contributors/desktop/+page.md`: Placeholder for Harper Desktop contributor documentation.- `packages/web/src/routes/docs/contributors/website/+page.md`: Local development, preview, and validation for writewithharper.com (SvelteKit/SveltePress).- `packages/web/src/routes/docs/contributors/wordpress/+page.md`: How to build and run the WordPress plugin locally.- `packages/web/src/routes/docs/contributors/obsidian/+page.md`: Obsidian-plugin contributor workflow and plugin-specific constraints.diff --git a/harper-desktop/src-tauri/src/commands.rs b/harper-desktop/src-tauri/src/commands.rsnew file mode 100644index 000000000..ddcc33f32--- /dev/null+++ b/harper-desktop/src-tauri/src/commands.rs@@ -0,0 +1,342 @@+//! This module centralizes all the Rust commands to be made available to the JavaScript+//! environment. Use [`application_message_handler`] to load them into the Tauri runtime.++use crate::config::Config;+use crate::highlighter_service::HighlighterService;+use crate::os_broker::{AccessibilityPermissionStatus, OsBroker};+use crate::{IntegrationView, accessibility_allows_highlighter_start, platform_broker};+use harper_core::{+ Dialect, DictWordMetadata, IgnoredLints,+ linting::FlatConfig,+ spell::{Dictionary, MutableDictionary},+};+use std::sync::Arc;+use tauri::ipc::Invoke;+use tauri::{Runtime, State};+use tokio::sync::Mutex;++pub fn application_message_handler<R: Runtime>() -> impl Fn(Invoke<R>) -> bool {+ tauri::generate_handler![+ get_lint_config,+ get_dialect,+ get_debounce_ms,+ set_debounce_ms,+ get_auto_update,+ set_auto_update,+ get_last_update_check,+ set_last_update_check,+ set_dialect,+ set_lint_config,+ get_dictionary,+ set_dictionary,+ ignore_lint,+ add_to_dictionary,+ get_integrations,+ add_integration,+ remove_integration,+ set_integration_enabled,+ get_accessibility_permission_status,+ request_accessibility_permission,+ start_highlighter_service,+ stop_highlighter_service,+ launch_app,+ ]+}++#[tauri::command]+async fn get_lint_config(config: State<'_, Arc<Mutex<Config>>>) -> Result<FlatConfig, String> {+ let mut lint_config = config.lock().await.lint_config.clone();+ lint_config.fill_with_curated();++ Ok(lint_config)+}++#[tauri::command]+async fn get_dialect(config: State<'_, Arc<Mutex<Config>>>) -> Result<Dialect, String> {+ Ok(config.lock().await.dialect)+}++#[tauri::command]+async fn get_debounce_ms(config: State<'_, Arc<Mutex<Config>>>) -> Result<u64, String> {+ Ok(config.lock().await.debounce_ms)+}++#[tauri::command]+async fn set_debounce_ms(+ debounce_ms: u64,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config.debounce_ms = debounce_ms;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn get_auto_update(config: State<'_, Arc<Mutex<Config>>>) -> Result<bool, String> {+ Ok(config.lock().await.auto_update)+}++#[tauri::command]+async fn set_auto_update(+ auto_update: bool,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config.auto_update = auto_update;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn get_last_update_check(+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<Option<u64>, String> {+ Ok(config.lock().await.last_update_check)+}++#[tauri::command]+async fn set_last_update_check(+ last_update_check: Option<u64>,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config.last_update_check = last_update_check;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn set_dialect(+ dialect: Dialect,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config.dialect = dialect;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn set_lint_config(+ lint_config: FlatConfig,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut lint_config = lint_config;+ lint_config.fill_with_curated();++ let mut config = config.lock().await;+ config.lint_config = lint_config;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn get_dictionary(config: State<'_, Arc<Mutex<Config>>>) -> Result<Vec<String>, String> {+ let mut words = config+ .lock()+ .await+ .mutable_dictionary+ .words_iter()+ .map(|word| word.iter().collect::<String>())+ .collect::<Vec<_>>();+ words.sort();++ Ok(words)+}++#[tauri::command]+async fn set_dictionary(+ words: Vec<String>,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut dictionary = MutableDictionary::new();+ dictionary.extend_words(words.into_iter().map(|word| {+ (+ word.chars().collect::<Vec<_>>(),+ DictWordMetadata::default(),+ )+ }));++ let mut config = config.lock().await;+ config.mutable_dictionary = dictionary;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn ignore_lint(+ ignored_lints: String,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let ignored_lints =+ serde_json::from_str::<IgnoredLints>(&ignored_lints).map_err(|error| error.to_string())?;++ let mut config = config.lock().await;+ config.ignored_lints.append(ignored_lints);+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn add_to_dictionary(+ word: String,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config+ .mutable_dictionary+ .append_word_str(&word, DictWordMetadata::default());+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn get_integrations(+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<Vec<IntegrationView>, String> {+ let integrations = config.lock().await.integrations.clone();+ let broker = platform_broker();++ Ok(integrations+ .into_iter()+ .map(|integration| IntegrationView {+ display_name: broker.integration_display_name(&integration.bundle_id),+ bundle_id: integration.bundle_id,+ enabled: integration.enabled,+ })+ .collect())+}++#[tauri::command]+async fn add_integration(+ bundle_id: String,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config.add_integration(bundle_id);+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn remove_integration(+ bundle_id: String,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config.remove_integration(&bundle_id);+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+async fn set_integration_enabled(+ bundle_id: String,+ enabled: bool,+ config: State<'_, Arc<Mutex<Config>>>,+) -> Result<(), String> {+ let mut config = config.lock().await;+ config.set_integration_enabled(&bundle_id, enabled);+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;++ Ok(())+}++#[tauri::command]+fn get_accessibility_permission_status() -> AccessibilityPermissionStatus {+ platform_broker().accessibility_permission_status()+}++#[tauri::command]+fn request_accessibility_permission() -> AccessibilityPermissionStatus {+ platform_broker().request_accessibility_permission()+}++#[tauri::command]+pub(crate) async fn start_highlighter_service(+ config: State<'_, Arc<Mutex<Config>>>,+ highlighter_service: State<'_, HighlighterService>,+) -> Result<bool, String> {+ {+ let mut config = config.lock().await;+ config.highlighter_service_enabled = true;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;+ }++ if accessibility_allows_highlighter_start() {+ highlighter_service+ .start()+ .map_err(|error| error.to_string())?;+ }++ Ok(highlighter_service.is_running())+}++#[tauri::command]+pub(crate) async fn stop_highlighter_service(+ config: State<'_, Arc<Mutex<Config>>>,+ highlighter_service: State<'_, HighlighterService>,+) -> Result<bool, String> {+ {+ let mut config = config.lock().await;+ config.highlighter_service_enabled = false;+ config+ .save_to_system()+ .await+ .map_err(|error| error.to_string())?;+ }++ Ok(highlighter_service.stop())+}++#[tauri::command]+fn launch_app(bundle_id: String) -> Result<(), String> {+ platform_broker().launch_app_bundle(&bundle_id)+}diff --git a/harper-desktop/src-tauri/src/communication/mod.rs b/harper-desktop/src-tauri/src/communication/mod.rsindex 86838a698..f35674339 100644--- a/harper-desktop/src-tauri/src/communication/mod.rs+++ b/harper-desktop/src-tauri/src/communication/mod.rs@@ -1,3 +1,6 @@+//! Contains the protocol for the communication between the highlighter [`Client`] and the main+//! process [`Server`].+mod client;mod error;mod framing;diff --git a/harper-desktop/src-tauri/src/highlighter_service.rs b/harper-desktop/src-tauri/src/highlighter_service.rsdeleted file mode 100644index 64b8ef9ad..000000000--- a/harper-desktop/src-tauri/src/highlighter_service.rs+++ /dev/null@@ -1,263 +0,0 @@-use crate::communication::Server;-use crate::config::Config;-use crate::highlighter_process::HighlighterProcess;-use std::{- io,- sync::{Arc, Mutex as StdMutex},- thread::{self, JoinHandle},-};-use tokio::{- io::{AsyncRead, AsyncWrite},- runtime::Builder,- sync::{Mutex, oneshot},-};--/// Owns the optional highlighter worker for the Tauri app.-///-/// This service gives app and tray code a small start/stop/toggle API without exposing the worker-/// thread, child process, or IPC server details.-pub struct HighlighterService {- config: Arc<Mutex<Config>>,- worker: StdMutex<Option<HighlighterWorker>>,-}--impl HighlighterService {- /// Creates a service controller around shared app config.- ///- /// The service keeps the config so each newly started highlighter process serves IPC from the- /// same state used by Tauri commands.- pub fn new(config: Arc<Mutex<Config>>) -> Self {- Self {- config,- worker: StdMutex::new(None),- }- }-- /// Starts the highlighter worker if it is not already running.- ///- /// This is idempotent so callers can request startup from app boot or tray actions without- /// risking duplicate child processes. Returns whether the service is running.- pub fn start(&self) -> io::Result<bool> {- self.reap_finished_worker();-- let mut worker = self- .worker- .lock()- .expect("highlighter service lock poisoned");- if worker.is_some() {- return Ok(true);- }-- *worker = Some(HighlighterWorker::spawn(self.config.clone())?);-- Ok(true)- }-- /// Stops the highlighter worker if one is running.- ///- /// This takes ownership of the current worker before shutting it down so future status checks see- /// the service as stopped immediately. Returns whether the service is running.- pub fn stop(&self) -> bool {- let worker = self- .worker- .lock()- .expect("highlighter service lock poisoned")- .take();-- if let Some(mut worker) = worker {- worker.stop();- }-- false- }-- /// Starts or stops the worker based on the current state.- ///- /// The tray menu uses this as its single action for the highlighter service. Returns whether the- /// service is running after the toggle completes.- pub fn toggle(&self) -> io::Result<bool> {- if self.is_running() {- Ok(self.stop())- } else {- self.start()- }- }-- /// Reports whether a live worker is currently owned by the service.- ///- /// This first reaps any worker whose thread has already exited so stale finished workers do not- /// appear as active. Returns whether the service is running.- pub fn is_running(&self) -> bool {- self.reap_finished_worker();-- self.worker- .lock()- .expect("highlighter service lock poisoned")- .is_some()- }-- /// Joins and removes a worker whose thread has already exited.- ///- /// The worker can finish without an explicit stop if the child highlighter exits or closes its- /// IPC pipe. Reaping keeps the service state accurate and prevents leaking join handles.- fn reap_finished_worker(&self) {- let worker = {- let mut worker = self- .worker- .lock()- .expect("highlighter service lock poisoned");- if worker.as_ref().is_some_and(HighlighterWorker::is_finished) {- worker.take()- } else {- None- }- };-- if let Some(mut worker) = worker {- worker.stop();- }- }-}--impl Drop for HighlighterService {- /// Stops the worker when the Tauri-managed service is dropped.- ///- /// This ties child-process cleanup to service ownership during application shutdown.- fn drop(&mut self) {- let worker = self- .worker- .get_mut()- .expect("highlighter service lock poisoned");-- if let Some(mut worker) = worker.take() {- worker.stop();- }- }-}--/// Runtime resources for one running highlighter service instance.-///-/// A worker owns the shutdown signal and OS thread that hosts the Tokio runtime, child highlighter-/// process, and Tauri-side IPC server.-struct HighlighterWorker {- shutdown_sender: Option<oneshot::Sender<()>>,- thread: Option<JoinHandle<()>>,-}--impl HighlighterWorker {- /// Spawns the service thread, child highlighter process, and IPC server.- ///- /// The startup channel makes this method synchronous from the caller's perspective: it only- /// returns success after the child process and server pipes are ready.- fn spawn(config: Arc<Mutex<Config>>) -> io::Result<Self> {- let (shutdown_sender, shutdown_receiver) = oneshot::channel();- let (startup_sender, startup_receiver) = std::sync::mpsc::sync_channel(1);-- let thread = thread::Builder::new()- .name("harper-highlighter-service".to_string())- .spawn(move || {- let runtime = match Builder::new_current_thread().enable_all().build() {- Ok(runtime) => runtime,- Err(error) => {- let _ = startup_sender.send(Err(io::Error::other(error)));- return;- }- };-- runtime.block_on(async move {- let mut highlighter_process = match HighlighterProcess::spawn() {- Ok(process) => process,- Err(error) => {- let _ = startup_sender.send(Err(error));- return;- }- };-- let mut server = match highlighter_process.create_server(config) {- Ok(server) => server,- Err(error) => {- let _ = startup_sender.send(Err(error));- return;- }- };-- let _ = startup_sender.send(Ok(()));- run_server_until_shutdown(&mut server, shutdown_receiver).await;- highlighter_process.terminate().await;- });- })?;-- match startup_receiver.recv() {- Ok(Ok(())) => Ok(Self {- shutdown_sender: Some(shutdown_sender),- thread: Some(thread),- }),- Ok(Err(error)) => {- let _ = thread.join();- Err(error)- }- Err(_) => {- let _ = thread.join();- Err(io::Error::other(- "highlighter service exited before reporting startup status",- ))- }- }- }-- /// Reports whether the worker thread has exited.- ///- /// The service uses this to lazily clean up workers that ended because the child process exited- /// or IPC reached EOF.- fn is_finished(&self) -> bool {- self.thread.as_ref().is_some_and(JoinHandle::is_finished)- }-- /// Requests shutdown and joins the worker thread.- ///- /// Sending the shutdown signal lets the async server loop break before the worker terminates and- /// reaps the child process.- fn stop(&mut self) {- if let Some(shutdown_sender) = self.shutdown_sender.take() {- let _ = shutdown_sender.send(());- }-- if let Some(thread) = self.thread.take()- && let Err(error) = thread.join()- {- eprintln!("highlighter service thread panicked: {error:?}");- }- }-}--impl Drop for HighlighterWorker {- /// Ensures a worker cannot be dropped while its thread and child process are still running.- fn drop(&mut self) {- self.stop();- }-}--/// Serves highlighter IPC requests until shutdown or child EOF.-///-/// This exists so the worker thread can race normal protocol handling against the service shutdown-/// signal without making the highlighter process aware of tray-service state.-async fn run_server_until_shutdown<R, W>(- server: &mut Server<R, W>,- mut shutdown_receiver: oneshot::Receiver<()>,-) where- R: AsyncRead + Unpin,- W: AsyncWrite + Unpin,-{- loop {- tokio::select! {- _ = &mut shutdown_receiver => break,- request = server.receive_request() => {- match request {- Ok(Some(_)) => {}- Ok(None) => break,- Err(error) => eprintln!("failed to receive highlighter request: {error}"),- }- }- }- }-}diff --git a/harper-desktop/src-tauri/src/highlighter_process.rs b/harper-desktop/src-tauri/src/highlighter_service/highlighter_process.rssimilarity index 85%rename from harper-desktop/src-tauri/src/highlighter_process.rsrename to harper-desktop/src-tauri/src/highlighter_service/highlighter_process.rsindex ceb6b04db..eea7bce98 100644--- a/harper-desktop/src-tauri/src/highlighter_process.rs+++ b/harper-desktop/src-tauri/src/highlighter_service/highlighter_process.rs@@ -6,10 +6,7 @@ use std::sync::Arc;use tokio::process::{Child, ChildStdin, ChildStdout, Command};use tokio::sync::Mutex;-/// Owns the highlighter child process while the Tauri app is running.-///-/// This type exists so child-process cleanup is tied to Rust ownership: keeping it in scope keeps the-/// highlighter alive, and controlled shutdown can terminate and reap the child before exit.+/// Represents a highlighter process.pub struct HighlighterProcess {child: Child,}diff --git a/harper-desktop/src-tauri/src/highlighter_service/highlighter_worker.rs b/harper-desktop/src-tauri/src/highlighter_service/highlighter_worker.rsnew file mode 100644index 000000000..fed8ae436--- /dev/null+++ b/harper-desktop/src-tauri/src/highlighter_service/highlighter_worker.rs@@ -0,0 +1,127 @@+use super::highlighter_process::HighlighterProcess;+use crate::{communication::Server, config::Config};+use std::{+ io,+ sync::Arc,+ thread::{self, JoinHandle},+};+use tokio::io::AsyncWrite;+use tokio::{+ io::AsyncRead,+ runtime::Builder,+ sync::{Mutex, oneshot},+};++/// Represents a thread that manages the communication and state for a highlighter process.+pub struct HighlighterWorker {+ shutdown_sender: Option<oneshot::Sender<()>>,+ thread: Option<JoinHandle<()>>,+}++impl HighlighterWorker {+ /// Spawns a new highlighter process and thread to manage it.+ pub fn spawn(config: Arc<Mutex<Config>>) -> io::Result<Self> {+ let (shutdown_sender, shutdown_receiver) = oneshot::channel();+ let (startup_sender, startup_receiver) = std::sync::mpsc::sync_channel(1);++ // Start a thread to manage communication with the new process.+ let thread = thread::Builder::new()+ .name("harper-highlighter-service".to_string())+ .spawn(move || {+ let runtime = match Builder::new_current_thread().enable_all().build() {+ Ok(runtime) => runtime,+ Err(error) => {+ let _ = startup_sender.send(Err(io::Error::other(error)));+ return;+ }+ };++ runtime.block_on(async move {+ let mut highlighter_process = match HighlighterProcess::spawn() {+ Ok(process) => process,+ Err(error) => {+ let _ = startup_sender.send(Err(error));+ return;+ }+ };++ let mut server = match highlighter_process.create_server(config) {+ Ok(server) => server,+ Err(error) => {+ let _ = startup_sender.send(Err(error));+ return;+ }+ };++ let _ = startup_sender.send(Ok(()));+ run_server_until_shutdown(&mut server, shutdown_receiver).await;+ highlighter_process.terminate().await;+ });+ })?;++ match startup_receiver.recv() {+ Ok(Ok(())) => Ok(Self {+ shutdown_sender: Some(shutdown_sender),+ thread: Some(thread),+ }),+ Ok(Err(error)) => {+ let _ = thread.join();+ Err(error)+ }+ Err(_) => {+ let _ = thread.join();+ Err(io::Error::other(+ "highlighter service exited before reporting startup status",+ ))+ }+ }+ }++ /// Reports whether the worker thread has exited.+ pub fn is_finished(&self) -> bool {+ self.thread.as_ref().is_some_and(JoinHandle::is_finished)+ }++ /// Requests shutdown and joins the worker thread.+ pub fn stop(&mut self) {+ if let Some(shutdown_sender) = self.shutdown_sender.take() {+ let _ = shutdown_sender.send(());+ }++ if let Some(thread) = self.thread.take()+ && let Err(error) = thread.join()+ {+ eprintln!("highlighter service thread panicked: {error:?}");+ }+ }+}++impl Drop for HighlighterWorker {+ /// Ensures a worker cannot be dropped while its thread and child process are still running.+ fn drop(&mut self) {+ self.stop();+ }+}++/// Serves highlighter IPC requests until shutdown or child EOF.+/// This is the content of the thread the above struct represents.+async fn run_server_until_shutdown<R, W>(+ server: &mut Server<R, W>,+ mut shutdown_receiver: oneshot::Receiver<()>,+) where+ R: AsyncRead + Unpin,+ W: AsyncWrite + Unpin,+{+ loop {+ tokio::select! {+ _ = &mut shutdown_receiver => break,+ request = server.receive_request() => {+ match request {+ Ok(Some(_)) => {}+ Ok(None) => break,+ Err(error) => eprintln!("failed to receive highlighter request: {error}"),+ }+ }+ }+ }+}diff --git a/harper-desktop/src-tauri/src/highlighter_service/mod.rs b/harper-desktop/src-tauri/src/highlighter_service/mod.rsnew file mode 100644index 000000000..891f4d9c2--- /dev/null+++ b/harper-desktop/src-tauri/src/highlighter_service/mod.rs@@ -0,0 +1,117 @@+mod highlighter_process;+mod highlighter_worker;++use crate::config::Config;+use highlighter_worker::HighlighterWorker;+use std::{+ io,+ sync::{Arc, Mutex as StdMutex},+};+use tokio::sync::Mutex;++/// Wraps around a [`HighlighterWorker`] and turns it into a service that is easier to manage.+/// We can start and stop it and simply provide a shared `Config` object that we can update whenever.+/// The service will sync the changes to the underlying highlighter process.+pub struct HighlighterService {+ config: Arc<Mutex<Config>>,+ worker: StdMutex<Option<HighlighterWorker>>,+}++impl HighlighterService {+ /// Create a new highlighter process service, without starting it.+ /// The provided config pointer will be automatically synced to the new process when changes are+ /// made.+ pub fn new(config: Arc<Mutex<Config>>) -> Self {+ Self {+ config,+ worker: StdMutex::new(None),+ }+ }++ /// Starts the highlighter worker if it is not already running.+ pub fn start(&self) -> io::Result<bool> {+ self.reap_finished_worker();++ let mut worker = self+ .worker+ .lock()+ .expect("highlighter service lock poisoned");+ if worker.is_some() {+ return Ok(true);+ }++ *worker = Some(HighlighterWorker::spawn(self.config.clone())?);++ Ok(true)+ }++ /// Stops the highlighter worker if one is running.+ pub fn stop(&self) -> bool {+ let worker = self+ .worker+ .lock()+ .expect("highlighter service lock poisoned")+ .take();++ if let Some(mut worker) = worker {+ worker.stop();+ }++ false+ }++ /// Starts or stops the worker based on the current state.+ ///+ /// The tray menu uses this as its single action for the highlighter service. Returns whether the+ /// service is running after the toggle completes.+ pub fn toggle(&self) -> io::Result<bool> {+ if self.is_running() {+ Ok(self.stop())+ } else {+ self.start()+ }+ }++ /// Reports whether a live worker is currently owned by the service.+ pub fn is_running(&self) -> bool {+ self.reap_finished_worker();++ self.worker+ .lock()+ .expect("highlighter service lock poisoned")+ .is_some()+ }++ /// Joins and removes a worker whose thread has already exited.+ fn reap_finished_worker(&self) {+ let worker = {+ let mut worker = self+ .worker+ .lock()+ .expect("highlighter service lock poisoned");+ if worker.as_ref().is_some_and(HighlighterWorker::is_finished) {+ worker.take()+ } else {+ None+ }+ };++ if let Some(mut worker) = worker {+ worker.stop();+ }+ }+}++impl Drop for HighlighterService {+ /// Stops the worker when the Tauri-managed service is dropped.+ fn drop(&mut self) {+ let worker = self+ .worker+ .get_mut()+ .expect("highlighter service lock poisoned");++ if let Some(mut worker) = worker.take() {+ worker.stop();+ }+ }+}diff --git a/harper-desktop/src-tauri/src/lib.rs b/harper-desktop/src-tauri/src/lib.rsindex a18d5ca40..b54b6f337 100644--- a/harper-desktop/src-tauri/src/lib.rs+++ b/harper-desktop/src-tauri/src/lib.rs@@ -6,13 +6,13 @@ use crate::debounce::{DebounceState, DebounceStatus};use clap::{Parser, Subcommand};use harper_core::{Dialect, DictWordMetadata, Document, IgnoredLints,- linting::{FlatConfig, Lint, LintGroup},- spell::{Dictionary, MutableDictionary},+ linting::{Lint, LintGroup},+ spell::MutableDictionary,};use serde::Serialize;use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};use tauri::{- Manager, State, WebviewUrl, WebviewWindowBuilder, WindowEvent,+ Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent,image::Image,menu::{HELP_SUBMENU_ID, Menu, MenuItem, PredefinedMenuItem},tray::{MouseButton, TrayIconBuilder, TrayIconEvent},@@ -27,11 +27,11 @@ use tokio::{};pub mod color;+mod commands;pub mod communication;pub mod config;mod debounce;pub mod highlighter;-pub mod highlighter_process;pub mod highlighter_service;pub mod lint_kind_color;mod os_broker;@@ -256,304 +256,6 @@ fn start_highlighter_service_if_enabled_and_permitted(}}-#[tauri::command]-async fn get_lint_config(config: State<'_, Arc<Mutex<Config>>>) -> Result<FlatConfig, String> {- let mut lint_config = config.lock().await.lint_config.clone();- lint_config.fill_with_curated();-- Ok(lint_config)-}--#[tauri::command]-async fn get_dialect(config: State<'_, Arc<Mutex<Config>>>) -> Result<Dialect, String> {- Ok(config.lock().await.dialect)-}--#[tauri::command]-async fn get_debounce_ms(config: State<'_, Arc<Mutex<Config>>>) -> Result<u64, String> {- Ok(config.lock().await.debounce_ms)-}--#[tauri::command]-async fn set_debounce_ms(- debounce_ms: u64,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config.debounce_ms = debounce_ms;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn get_auto_update(config: State<'_, Arc<Mutex<Config>>>) -> Result<bool, String> {- Ok(config.lock().await.auto_update)-}--#[tauri::command]-async fn set_auto_update(- auto_update: bool,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config.auto_update = auto_update;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn get_last_update_check(- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<Option<u64>, String> {- Ok(config.lock().await.last_update_check)-}--#[tauri::command]-async fn set_last_update_check(- last_update_check: Option<u64>,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config.last_update_check = last_update_check;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn set_dialect(- dialect: Dialect,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config.dialect = dialect;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn set_lint_config(- lint_config: FlatConfig,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut lint_config = lint_config;- lint_config.fill_with_curated();-- let mut config = config.lock().await;- config.lint_config = lint_config;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn get_dictionary(config: State<'_, Arc<Mutex<Config>>>) -> Result<Vec<String>, String> {- let mut words = config- .lock()- .await- .mutable_dictionary- .words_iter()- .map(|word| word.iter().collect::<String>())- .collect::<Vec<_>>();- words.sort();-- Ok(words)-}--#[tauri::command]-async fn set_dictionary(- words: Vec<String>,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut dictionary = MutableDictionary::new();- dictionary.extend_words(words.into_iter().map(|word| {- (- word.chars().collect::<Vec<_>>(),- DictWordMetadata::default(),- )- }));-- let mut config = config.lock().await;- config.mutable_dictionary = dictionary;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn ignore_lint(- ignored_lints: String,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let ignored_lints =- serde_json::from_str::<IgnoredLints>(&ignored_lints).map_err(|error| error.to_string())?;-- let mut config = config.lock().await;- config.ignored_lints.append(ignored_lints);- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn add_to_dictionary(- word: String,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config- .mutable_dictionary- .append_word_str(&word, DictWordMetadata::default());- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn get_integrations(- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<Vec<IntegrationView>, String> {- let integrations = config.lock().await.integrations.clone();- let broker = platform_broker();-- Ok(integrations- .into_iter()- .map(|integration| IntegrationView {- display_name: broker.integration_display_name(&integration.bundle_id),- bundle_id: integration.bundle_id,- enabled: integration.enabled,- })- .collect())-}--#[tauri::command]-async fn add_integration(- bundle_id: String,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config.add_integration(bundle_id);- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn remove_integration(- bundle_id: String,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config.remove_integration(&bundle_id);- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-async fn set_integration_enabled(- bundle_id: String,- enabled: bool,- config: State<'_, Arc<Mutex<Config>>>,-) -> Result<(), String> {- let mut config = config.lock().await;- config.set_integration_enabled(&bundle_id, enabled);- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;-- Ok(())-}--#[tauri::command]-fn get_accessibility_permission_status() -> AccessibilityPermissionStatus {- platform_broker().accessibility_permission_status()-}--#[tauri::command]-fn request_accessibility_permission() -> AccessibilityPermissionStatus {- platform_broker().request_accessibility_permission()-}--#[tauri::command]-async fn start_highlighter_service(- config: State<'_, Arc<Mutex<Config>>>,- highlighter_service: State<'_, HighlighterService>,-) -> Result<bool, String> {- {- let mut config = config.lock().await;- config.highlighter_service_enabled = true;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;- }-- if accessibility_allows_highlighter_start() {- highlighter_service- .start()- .map_err(|error| error.to_string())?;- }-- Ok(highlighter_service.is_running())-}--#[tauri::command]-async fn stop_highlighter_service(- config: State<'_, Arc<Mutex<Config>>>,- highlighter_service: State<'_, HighlighterService>,-) -> Result<bool, String> {- {- let mut config = config.lock().await;- config.highlighter_service_enabled = false;- config- .save_to_system()- .await- .map_err(|error| error.to_string())?;- }-- Ok(highlighter_service.stop())-}--#[tauri::command]-fn launch_app(bundle_id: String) -> Result<(), String> {- platform_broker().launch_app_bundle(&bundle_id)-}-#[cfg(target_os = "macos")]fn platform_broker() -> impl OsBroker {mac_broker::MacBroker::default()@@ -621,31 +323,7 @@ pub fn run_tauri() {)).plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_os::init())- .invoke_handler(tauri::generate_handler![- get_lint_config,- get_dialect,- get_debounce_ms,- set_debounce_ms,- get_auto_update,- set_auto_update,- get_last_update_check,- set_last_update_check,- set_dialect,- set_lint_config,- get_dictionary,- set_dictionary,- ignore_lint,- add_to_dictionary,- get_integrations,- add_integration,- remove_integration,- set_integration_enabled,- get_accessibility_permission_status,- request_accessibility_permission,- start_highlighter_service,- stop_highlighter_service,- launch_app,- ])+ .invoke_handler(commands::application_message_handler()).menu(desktop_app_menu).on_menu_event(|app, event| {if event.id().as_ref() == REPORT_ISSUE_MENU_ID {@@ -681,15 +359,17 @@ pub fn run_tauri() {let highlighter_service = app.state::<HighlighterService>();let toggle_result = if highlighter_service.is_running() {- tauri::async_runtime::block_on(stop_highlighter_service(+ tauri::async_runtime::block_on(commands::stop_highlighter_service(app.state::<Arc<Mutex<Config>>>(),highlighter_service,))} else {- let result = tauri::async_runtime::block_on(start_highlighter_service(- app.state::<Arc<Mutex<Config>>>(),- highlighter_service,- ));+ let result = tauri::async_runtime::block_on(+ commands::start_highlighter_service(+ app.state::<Arc<Mutex<Config>>>(),+ highlighter_service,+ ),+ );if matches!(result, Ok(false))&& !accessibility_allows_highlighter_start()diff --git a/packages/web/src/routes/docs/contributors/desktop/+page.md b/packages/web/src/routes/docs/contributors/desktop/+page.mdnew file mode 100644index 000000000..04d4d2eb7--- /dev/null+++ b/packages/web/src/routes/docs/contributors/desktop/+page.md@@ -0,0 +1,62 @@+---+title: Harper Desktop+---++Harper Desktop aims to (eventually) serve the needs of users on a variety of platforms.+One day, we hope for it to include support for macOS, Windows, and Linux.+Right now, it just supports macOS.+Because we hope to add new platforms, there are structures in the code that would not make sense for an app specifically designed with only one operating system in mind.++This document will serve to give a tour of how the code for the Desktop app is structured and, more importantly, why it is structured that way.++## The Processes++When running, the Harper Desktop app will start two distinct processes.+I will give a brief overview here, then go into more detail in later sections.++The first is a conventional [Tauri](https://tauri.app/) app, with an event loop we do not have control over.+When running the Harper Desktop binary with no arguments, this "main" process is what is kicked off.+If you have not worked with a Tauri app before, I suggest you take a look at their documentation for more details.+In this main process, we try to follow their conventions whenever possible.++When the "Harper Service" is started (which happens when the main process starts, unless the user has disabled it) the main process will kick off a second "highlighter" process by running the same binary with the `highlighter` argument.+This second process is what actually reads and writes text from user applications (using a platform's Accessibility API), performs linting, and renders highlights and suggestion popups over the top of their screen.+We need to separate this highlighter service process from the main process because it needs to maintain it's own custom event loop, which was not possible with Tauri.+It also needs to be able to place itself it special "modes" within the operating system, which allow it open windows without taskbar icons or frames.++## The Main Process++As I said above, the main process is a conventional Tauri app.+It holds one primary responsibility, which is to manage configuration and state for the rest of the app.+Everything else it does is supplemental.+That means that it:++- Loads configuration from disk at startup.+- Saves configuration to disk whenever it changes.+- Exposes UI for adjusting the configuration to the user's preference.++The most important module in the Desktop app is likely `config`, which contains a central record of the entire application's state.+Much of the "fluff" code in the project serves to shuffle copies of this config to various parts of the app, including, but not limited to, the settings page WebView, the highlighter process, and to disk.++## The Highlighter Process++This process is much more interesting.+To reiterate: this process's job is to read text from the screen, lint it, and display highlights and suggestion popups.+There are three main components to this:++- Its communication with the main thread.+- Its communication with the operating system via the accessibility API.+- Its communication with the user via an invisible window which it renders on top of every other window on the user's desktop.++It communicates with the main process using the protocol defined in the `communication` module.+It does so to receive updates to it's internal lint configuration so that it matches the main process's state as closely as possible.+When the user changes a setting via a Tauri window, that setting is propagated from the WebView to the main process, which is then shared to the highlighter.+The latter step happens in the `communication` module.++The communication with the operating system happens inside of a `Broker`, which is an interface that exposes any and all platform-specific functions Harper needs.+Right now, there is only one implementation of `Broker`: `MacBroker`.++Finally, the communication with the user happens via a `winit` window, to which we render [`egui`](https://github.com/emilk/egui) elements.+The exact structure of the relevant modules for this is likely subject to change and may vary by platform, so I will forgo including additional information here to avoid misleading you.++I want to emphasize this point: the highlighter process does not store any canonical state. Any updates to its state must be synchronized to the main process as soon as possible.diff --git a/packages/web/vite.config.ts b/packages/web/vite.config.tsindex f5d971956..5682d7c08 100644--- a/packages/web/vite.config.ts+++ b/packages/web/vite.config.ts@@ -195,6 +195,10 @@ export default defineConfig(async () => {title: 'Chrome Extension',to: '/docs/contributors/chrome-extension',},+ {+ title: 'Harper Desktop',+ to: '/docs/contributors/desktop',+ },{title: 'Website',to: '/docs/contributors/website',