Skip to content

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

fix(desktop): lagging status indicator (#3779)

Elijah Potter607d0f80af18
diff --git a/Cargo.lock b/Cargo.lock
index 570909ad7..68d9288c3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4315,6 +4315,8 @@ dependencies = [
"tauri-plugin-updater",
"thiserror 2.0.18",
"tokio",
+ "tracing",
+ "tracing-subscriber",
"winit",
]
diff --git a/harper-desktop/src-tauri/Cargo.toml b/harper-desktop/src-tauri/Cargo.toml
index f7251dffe..bf85d9ac7 100644
--- a/harper-desktop/src-tauri/Cargo.toml
+++ b/harper-desktop/src-tauri/Cargo.toml
@@ -15,11 +15,11 @@ name = "harper_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
-tauri-build = { version = "=2.6.1", features = [] }
+tauri-build = { version = "2.6.1", features = [] }
[dependencies]
-tauri = { version = "=2.11.1", features = ["image-png", "tray-icon"] }
-tauri-plugin-opener = "=2.5.4"
+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"
@@ -37,6 +37,8 @@ egui_commonmark = "0.23.0"
tokio = { version = "1.52.2", features = ["full"] }
tauri-plugin-os = "2.3.2"
cached = "2.0.2"
+tracing = "0.1.44"
+tracing-subscriber = "0.3.23"
[target.'cfg(target_os = "macos")'.dependencies]
accessibility = "0.2.0"
diff --git a/harper-desktop/src-tauri/src/commands.rs b/harper-desktop/src-tauri/src/commands.rs
index 3b5fd615b..c2c729a84 100644
--- a/harper-desktop/src-tauri/src/commands.rs
+++ b/harper-desktop/src-tauri/src/commands.rs
@@ -4,9 +4,7 @@
use crate::config::Config;
use crate::highlighter_service::HighlighterService;
use crate::os_broker::{AccessibilityPermissionStatus, AppSearchResult, OsBroker};
-use crate::{
- IntegrationView, PlatformBroker, accessibility_allows_highlighter_start, platform_broker,
-};
+use crate::{IntegrationView, PlatformBroker, platform_broker};
use base64::{Engine as _, engine::general_purpose};
use harper_core::{
Dialect, DictWordMetadata, IgnoredLints,
@@ -337,11 +335,9 @@ pub(crate) async fn start_highlighter_service(
.map_err(|error| error.to_string())?;
}
- if accessibility_allows_highlighter_start() {
- highlighter_service
- .start()
- .map_err(|error| error.to_string())?;
- }
+ highlighter_service
+ .start()
+ .map_err(|error| error.to_string())?;
Ok(highlighter_service.is_running())
}
diff --git a/harper-desktop/src-tauri/src/config/error.rs b/harper-desktop/src-tauri/src/config/error.rs
new file mode 100644
index 000000000..f4dee6a85
--- /dev/null
+++ b/harper-desktop/src-tauri/src/config/error.rs
@@ -0,0 +1,12 @@
+use std::io;
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum Error {
+ #[error("system config directory is unavailable")]
+ ConfigDirUnavailable,
+ #[error("failed to serialize or deserialize config")]
+ Serde(#[from] serde_json::Error),
+ #[error("failed to access config file")]
+ Io(#[from] io::Error),
+}
diff --git a/harper-desktop/src-tauri/src/config/integration.rs b/harper-desktop/src-tauri/src/config/integration.rs
new file mode 100644
index 000000000..56b0eaa33
--- /dev/null
+++ b/harper-desktop/src-tauri/src/config/integration.rs
@@ -0,0 +1,31 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Integration {
+ pub bundle_id: String,
+ pub enabled: bool,
+}
+
+impl Integration {
+ pub fn curated_integrations() -> Vec<Self> {
+ [
+ "com.apple.TextEdit",
+ "com.apple.mail",
+ "com.apple.MobileSMS",
+ "com.apple.Notes",
+ "com.tinyspeck.slackmacgap",
+ "com.hnc.Discord",
+ ]
+ .into_iter()
+ .map(|bundle_id| Integration {
+ bundle_id: bundle_id.to_string(),
+ enabled: true,
+ })
+ .collect()
+ }
+ pub fn is_integration_enabled_in(integrations: &[Self], bundle_id: &str) -> bool {
+ integrations
+ .iter()
+ .any(|integration| integration.bundle_id == bundle_id && integration.enabled)
+ }
+}
diff --git a/harper-desktop/src-tauri/src/config.rs b/harper-desktop/src-tauri/src/config/mod.rs
similarity index 79%
rename from harper-desktop/src-tauri/src/config.rs
rename to harper-desktop/src-tauri/src/config/mod.rs
index 92c2b93fe..66e228de3 100644
--- a/harper-desktop/src-tauri/src/config.rs
+++ b/harper-desktop/src-tauri/src/config/mod.rs
@@ -1,25 +1,16 @@
+mod error;
+mod integration;
+
+pub use error::Error;
use harper_core::{
Dialect, IgnoredLints,
linting::{FlatConfig, LintGroup},
spell::{FstDictionary, MergedDictionary, MutableDictionary},
};
use harper_dictionary_wordlist::{load_dict, save_dict};
-use serde::{
- Deserialize, Serialize,
- de::{DeserializeOwned, Error},
-};
+pub use integration::Integration;
+use serde::de::{DeserializeOwned, Error as _};
use std::{fs, io, path::PathBuf, sync::Arc};
-use thiserror::Error;
-
-#[derive(Debug, Error)]
-pub enum ConfigError {
- #[error("system config directory is unavailable")]
- ConfigDirUnavailable,
- #[error("failed to serialize or deserialize config")]
- Serde(#[from] serde_json::Error),
- #[error("failed to access config file")]
- Io(#[from] io::Error),
-}
/// User-controlled app state needed by Tauri commands and the highlighter process.
pub struct Config {
@@ -34,12 +25,6 @@ pub struct Config {
pub highlighter_service_enabled: bool,
}
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct Integration {
- pub bundle_id: String,
- pub enabled: bool,
-}
-
impl Config {
pub fn new() -> Self {
Self {
@@ -47,7 +32,7 @@ impl Config {
dialect: Self::detect_system_dialect(),
ignored_lints: IgnoredLints::new(),
lint_config: FlatConfig::new_curated(),
- integrations: Self::curated_integrations(),
+ integrations: Integration::curated_integrations(),
debounce_ms: 0,
auto_update: true,
last_update_check: None,
@@ -55,34 +40,14 @@ impl Config {
}
}
- pub fn detect_system_dialect() -> Dialect {
+ fn detect_system_dialect() -> Dialect {
tauri_plugin_os::locale()
.and_then(|bcp47| Dialect::try_from_bcp47(&bcp47))
.unwrap_or(Dialect::American)
}
- pub fn curated_integrations() -> Vec<Integration> {
- [
- "com.apple.TextEdit",
- "com.apple.mail",
- "com.apple.MobileSMS",
- "com.apple.Notes",
- "com.tinyspeck.slackmacgap",
- "com.hnc.Discord",
- ]
- .into_iter()
- .map(|bundle_id| Integration {
- bundle_id: bundle_id.to_string(),
- enabled: true,
- })
- .collect()
- }
-
pub fn is_integration_enabled(&self, bundle_id: &str) -> bool {
- Self::is_integration_enabled_in(&self.integrations, bundle_id)
- }
-
- pub fn is_integration_enabled_in(integrations: &[Integration], bundle_id: &str) -> bool {
+ let integrations: &[Integration] = &self.integrations;
integrations
.iter()
.any(|integration| integration.bundle_id == bundle_id && integration.enabled)
@@ -122,10 +87,10 @@ impl Config {
}
}
- pub async fn save_to_system(&self) -> Result<(), ConfigError> {
- let folder_path = Self::folder_path().ok_or(ConfigError::ConfigDirUnavailable)?;
- let main_path = Self::main_path().ok_or(ConfigError::ConfigDirUnavailable)?;
- let dictionary_path = Self::dictionary_path().ok_or(ConfigError::ConfigDirUnavailable)?;
+ pub async fn save_to_system(&self) -> Result<(), Error> {
+ let folder_path = Self::folder_path().ok_or(Error::ConfigDirUnavailable)?;
+ let main_path = Self::main_path().ok_or(Error::ConfigDirUnavailable)?;
+ let dictionary_path = Self::dictionary_path().ok_or(Error::ConfigDirUnavailable)?;
fs::create_dir_all(folder_path)?;
fs::write(main_path, self.serialize_main()?)?;
@@ -134,8 +99,8 @@ impl Config {
Ok(())
}
- pub fn main_config_exists() -> Result<bool, ConfigError> {
- let main_path = Self::main_path().ok_or(ConfigError::ConfigDirUnavailable)?;
+ pub fn main_config_exists() -> Result<bool, Error> {
+ let main_path = Self::main_path().ok_or(Error::ConfigDirUnavailable)?;
match fs::metadata(main_path) {
Ok(_) => Ok(true),
@@ -144,9 +109,9 @@ impl Config {
}
}
- pub async fn load_from_system() -> Result<Self, ConfigError> {
- let main_path = Self::main_path().ok_or(ConfigError::ConfigDirUnavailable)?;
- let dictionary_path = Self::dictionary_path().ok_or(ConfigError::ConfigDirUnavailable)?;
+ pub async fn load_from_system() -> Result<Self, Error> {
+ let main_path = Self::main_path().ok_or(Error::ConfigDirUnavailable)?;
+ let dictionary_path = Self::dictionary_path().ok_or(Error::ConfigDirUnavailable)?;
let serialized = fs::read_to_string(main_path)?;
let mut config = Self::deserialize_main(&serialized)?;
config.lint_config.fill_with_curated();
@@ -165,7 +130,7 @@ impl Config {
Arc::new(dictionary)
}
- pub fn create_dictionary(&self) -> Arc<MergedDictionary> {
+ fn create_dictionary(&self) -> Arc<MergedDictionary> {
Self::dictionary_from_user_dictionary(self.mutable_dictionary.clone())
}
@@ -216,7 +181,7 @@ impl Config {
ignored_lints: deserialize_field(object, "ignored_lints")?,
lint_config: deserialize_field(object, "lint_config")?,
integrations: deserialize_optional_field(object, "integrations")?
- .unwrap_or_else(Self::curated_integrations),
+ .unwrap_or_else(Integration::curated_integrations),
debounce_ms: deserialize_optional_field(object, "debounce_ms")?.unwrap_or(0),
auto_update: deserialize_optional_field(object, "auto_update")?.unwrap_or(true),
last_update_check: deserialize_optional_field::<Option<u64>>(
@@ -322,33 +287,6 @@ mod tests {
);
}
- #[test]
- fn new_uses_curated_integrations() {
- let config = Config::new();
-
- assert_eq!(config.integrations, Config::curated_integrations());
- assert!(config.is_integration_enabled("com.apple.TextEdit"));
- assert!(config.is_integration_enabled("com.apple.mail"));
- assert!(config.is_integration_enabled("com.apple.MobileSMS"));
- assert!(config.is_integration_enabled("com.apple.Notes"));
- assert!(config.is_integration_enabled("com.tinyspeck.slackmacgap"));
- assert!(config.is_integration_enabled("com.hnc.Discord"));
- }
-
- #[test]
- fn deserialize_main_uses_curated_integrations_when_missing() {
- let config = Config::new();
- let mut value =
- serde_json::from_str::<serde_json::Value>(&config.serialize_main().unwrap()).unwrap();
- value.as_object_mut().unwrap().remove("integrations");
-
- let deserialized = Config::deserialize_main(&value.to_string()).unwrap();
-
- assert_eq!(deserialized.integrations, Config::curated_integrations());
- assert!(deserialized.is_integration_enabled("com.tinyspeck.slackmacgap"));
- assert!(deserialized.is_integration_enabled("com.hnc.Discord"));
- }
-
#[test]
fn deserialize_main_uses_zero_debounce_when_missing() {
let config = Config::new();
diff --git a/harper-desktop/src-tauri/src/lib.rs b/harper-desktop/src-tauri/src/lib.rs
index 79f5c2a0d..ed76125dd 100644
--- a/harper-desktop/src-tauri/src/lib.rs
+++ b/harper-desktop/src-tauri/src/lib.rs
@@ -1,6 +1,9 @@
+mod tray;
+mod windows;
+
use self::highlighter::Highlighter;
use self::highlighter_service::HighlighterService;
-use self::menu_bar_icon::menu_bar_icon;
+use self::tray::set_up_tray_menu;
use crate::communication::{Client, ProtocolError};
use crate::config::{Config, Integration};
use crate::debounce::{DebounceState, DebounceStatus};
@@ -11,17 +14,15 @@ use harper_core::{
spell::MutableDictionary,
};
use serde::Serialize;
+use std::io::stderr;
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex as StdMutex},
};
-use tauri::{
- Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent,
- menu::{HELP_SUBMENU_ID, Menu, MenuItem, PredefinedMenuItem},
- tray::{MouseButton, TrayIconBuilder, TrayIconEvent},
-};
-use tauri_plugin_opener::OpenerExt;
+use tauri::Manager as _;
+use tracing::{Level, error};
+use tracing_subscriber::FmtSubscriber;
use crate::os_broker::{AccessibilityPermissionStatus, OsBroker};
use tokio::{
@@ -38,7 +39,6 @@ mod debounce;
pub mod highlighter;
pub mod highlighter_service;
pub mod lint_kind_color;
-mod menu_bar_icon;
mod os_broker;
pub mod rect;
@@ -59,15 +59,6 @@ enum Command {
},
}
-const EDITOR_WINDOW_LABEL: &str = "main";
-const SETTINGS_WINDOW_LABEL: &str = "settings";
-const TRAY_MENU_BAR_ID: &str = "harper-menu-bar";
-const TOGGLE_SERVICE_MENU_ID: &str = "toggle-service";
-const OPEN_EDITOR_MENU_ID: &str = "open-editor";
-const SETTINGS_MENU_ID: &str = "settings";
-const REPORT_ISSUE_MENU_ID: &str = "report-issue";
-const QUIT_MENU_ID: &str = "quit";
-
#[derive(Debug, Clone, Serialize)]
struct IntegrationView {
bundle_id: String,
@@ -75,165 +66,6 @@ struct IntegrationView {
display_name: String,
}
-struct TrayMenu {
- menu: Menu<tauri::Wry>,
- service_toggle: MenuItem<tauri::Wry>,
-}
-
-fn service_menu_text(is_running: bool) -> &'static str {
- match is_running {
- true => "Stop Harper Service",
- false => "Start Harper Service",
- }
-}
-
-fn show_editor_window(app: &tauri::AppHandle) -> tauri::Result<()> {
- if let Some(window) = app.get_webview_window(EDITOR_WINDOW_LABEL) {
- window.show()?;
- window.set_focus()?;
- return Ok(());
- }
-
- let window = WebviewWindowBuilder::new(
- app,
- EDITOR_WINDOW_LABEL,
- WebviewUrl::App("index.html".into()),
- )
- .title("Harper")
- .inner_size(800.0, 600.0)
- .build()?;
- window.set_focus()?;
-
- Ok(())
-}
-
-fn show_settings_window(app: &tauri::AppHandle) -> tauri::Result<()> {
- if let Some(window) = app.get_webview_window(SETTINGS_WINDOW_LABEL) {
- window.show()?;
- window.set_focus()?;
- return Ok(());
- }
-
- WebviewWindowBuilder::new(
- app,
- SETTINGS_WINDOW_LABEL,
- WebviewUrl::App("index.html".into()),
- )
- .title("Harper Settings")
- .inner_size(920.0, 680.0)
- .min_inner_size(780.0, 520.0)
- .center()
- .build()?;
-
- Ok(())
-}
-
-fn open_issue_report(app: &tauri::AppHandle) {
- if let Err(error) = app.opener().open_url(
- "https://github.com/Automattic/harper/issues/new/choose",
- None::<&str>,
- ) {
- eprintln!("failed to open issue report URL: {error}");
- }
-}
-
-fn desktop_app_menu(app: &tauri::AppHandle) -> tauri::Result<Menu<tauri::Wry>> {
- let menu = Menu::default(app)?;
-
- if let Some(help_menu) = menu
- .get(HELP_SUBMENU_ID)
- .and_then(|item| item.as_submenu().cloned())
- {
- if !help_menu.items()?.is_empty() {
- help_menu.append(&PredefinedMenuItem::separator(app)?)?;
- }
-
- help_menu.append(&MenuItem::with_id(
- app,
- REPORT_ISSUE_MENU_ID,
- "Report an Issue",
- true,
- None::<&str>,
- )?)?;
- }
-
- Ok(menu)
-}
-
-fn tray_menu(app: &tauri::App, is_running: bool) -> tauri::Result<TrayMenu> {
- let service_toggle = MenuItem::with_id(
- app,
- TOGGLE_SERVICE_MENU_ID,
- service_menu_text(is_running),
- true,
- None::<&str>,
- )?;
- let open_editor =
- MenuItem::with_id(app, OPEN_EDITOR_MENU_ID, "Open Editor", true, None::<&str>)?;
- let separator = PredefinedMenuItem::separator(app)?;
- let settings = MenuItem::with_id(app, SETTINGS_MENU_ID, "Settings", true, None::<&str>)?;
- let report_issue = MenuItem::with_id(
- app,
- REPORT_ISSUE_MENU_ID,
- "Report an Issue",
- true,
- None::<&str>,
- )?;
- let quit = MenuItem::with_id(app, QUIT_MENU_ID, "Quit", true, None::<&str>)?;
-
- let menu = Menu::with_items(
- app,
- &[
- &service_toggle,
- &open_editor,
- &separator,
- &settings,
- &report_issue,
- &quit,
- ],
- )?;
-
- Ok(TrayMenu {
- menu,
- service_toggle,
- })
-}
-
-fn update_service_tray_state(
- app: &tauri::AppHandle,
- service_toggle: &MenuItem<tauri::Wry>,
- is_running: bool,
-) -> tauri::Result<()> {
- service_toggle.set_text(service_menu_text(is_running))?;
-
- if let Some(tray) = app.tray_by_id(TRAY_MENU_BAR_ID) {
- tray.set_icon(Some(menu_bar_icon(is_running)?))?;
- }
-
- Ok(())
-}
-
-fn should_hide_window_on_close(label: &str) -> bool {
- label == EDITOR_WINDOW_LABEL || label == SETTINGS_WINDOW_LABEL
-}
-
-fn accessibility_allows_highlighter_start() -> bool {
- platform_broker().accessibility_permission_status() == AccessibilityPermissionStatus::Granted
-}
-
-fn start_highlighter_service_if_enabled_and_permitted(
- highlighter_service: &HighlighterService,
- highlighter_service_enabled: bool,
-) {
- if !highlighter_service_enabled || !accessibility_allows_highlighter_start() {
- return;
- }
-
- if let Err(error) = highlighter_service.start() {
- eprintln!("failed to start highlighter service: {error}");
- }
-}
-
#[cfg(target_os = "macos")]
pub(crate) type PlatformBroker = mac_broker::MacBroker;
@@ -260,6 +92,15 @@ fn warm_app_search_cache(app: tauri::AppHandle) {
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
+ let subscriber = FmtSubscriber::builder()
+ .map_writer(move |_| stderr)
+ .with_ansi(false)
+ .with_max_level(Level::WARN)
+ .finish();
+
+ tracing::subscriber::set_global_default(subscriber)
+ .expect("Unable to set up tracing subscriber.");
+
let args = Args::parse();
match args.command {
@@ -269,10 +110,12 @@ pub fn run() {
}
pub fn run_tauri() {
- let config_runtime = Builder::new_current_thread()
+ let async_runtime = Builder::new_multi_thread()
.enable_all()
.build()
.expect("failed to build config runtime");
+
+ // Infer
let is_first_launch = match Config::main_config_exists() {
Ok(exists) => !exists,
Err(error) => {
@@ -284,13 +127,13 @@ pub fn run_tauri() {
let config = if is_first_launch {
let config = Config::new();
- if let Err(error) = config_runtime.block_on(config.save_to_system()) {
+ if let Err(error) = async_runtime.block_on(config.save_to_system()) {
eprintln!("failed to save initial config: {error}");
}
config
} else {
- match config_runtime.block_on(Config::load_from_system()) {
+ match async_runtime.block_on(Config::load_from_system()) {
Ok(config) => config,
Err(error) => {
eprintln!("failed to load config, using defaults: {error}");
@@ -298,18 +141,24 @@ pub fn run_tauri() {
}
}
};
+
let highlighter_service_enabled = config.highlighter_service_enabled;
let config = Arc::new(Mutex::new(config));
+
let highlighter_service = HighlighterService::new(config.clone());
- start_highlighter_service_if_enabled_and_permitted(
- &highlighter_service,
- highlighter_service_enabled,
- );
+ if platform_broker().accessibility_permission_status() == AccessibilityPermissionStatus::Granted
+ && highlighter_service_enabled
+ {
+ let _ = highlighter_service
+ .start()
+ .inspect_err(|err| error!("Unable to start highlighter: {err}"));
+ }
tauri::Builder::default()
.manage(config)
.manage(highlighter_service)
.manage(StdMutex::new(platform_broker()))
+ .manage(async_runtime)
.plugin(tauri_plugin_autostart::init(
tauri_plugin_autostart::MacosLauncher::LaunchAgent,
None,
@@ -317,117 +166,15 @@ pub fn run_tauri() {
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_os::init())
.invoke_handler(commands::application_message_handler())
- .menu(desktop_app_menu)
- .on_menu_event(|app, event| {
- if event.id().as_ref() == REPORT_ISSUE_MENU_ID {
- open_issue_report(app);
- }
- })
- .on_window_event(|window, event| {
- if should_hide_window_on_close(window.label())
- && let WindowEvent::CloseRequested { api, .. } = event
- {
- api.prevent_close();
-
- if let Err(error) = window.hide() {
- eprintln!("failed to hide {} window: {error}", window.label());
- }
- }
- })
.setup(move |app| {
- let is_service_running = app.state::<HighlighterService>().is_running();
- let menu = tray_menu(app, is_service_running)?;
- let service_toggle = menu.service_toggle.clone();
-
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
+ set_up_tray_menu(app.handle())?;
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)?)
- .tooltip("Harper Desktop")
- .show_menu_on_left_click(false)
- .on_menu_event(move |app, event| match event.id().as_ref() {
- TOGGLE_SERVICE_MENU_ID => {
- let highlighter_service = app.state::<HighlighterService>();
-
- let toggle_result = if highlighter_service.is_running() {
- tauri::async_runtime::block_on(commands::stop_highlighter_service(
- app.state::<Arc<Mutex<Config>>>(),
- highlighter_service,
- ))
- } else {
- 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()
- && let Err(error) = show_settings_window(app)
- {
- eprintln!("failed to show settings window: {error}");
- }
-
- result
- };
-
- match toggle_result {
- Ok(status) => {
- if let Err(error) =
- update_service_tray_state(app, &service_toggle, status)
- {
- eprintln!("failed to update service tray state: {error}");
- }
- }
- Err(error) => {
- eprintln!("failed to toggle highlighter service: {error}");
-
- let is_running = app.state::<HighlighterService>().is_running();
- if let Err(error) =
- update_service_tray_state(app, &service_toggle, is_running)
- {
- eprintln!("failed to update service tray state: {error}");
- }
- }
- }
- }
- OPEN_EDITOR_MENU_ID => {
- if let Err(error) = show_editor_window(app) {
- eprintln!("failed to show editor window: {error}");
- }
- }
- SETTINGS_MENU_ID => {
- if let Err(error) = show_settings_window(app) {
- eprintln!("failed to show settings window: {error}");
- }
- }
- REPORT_ISSUE_MENU_ID => open_issue_report(app),
- QUIT_MENU_ID => app.exit(0),
- _ => {}
- })
- .on_tray_icon_event(|tray, event| {
- if let TrayIconEvent::Click {
- button: MouseButton::Left,
- ..
- } = event
- {
- let app = tray.app_handle().clone();
-
- if let Err(error) = show_settings_window(&app) {
- eprintln!("failed to show settings window: {error}");
- }
- }
- });
-
- tray.build(app)?;
-
if is_first_launch {
- show_settings_window(app.handle())?;
+ windows::show_settings_window(app.handle())?;
}
Ok(())
@@ -585,7 +332,10 @@ pub fn run_highlighter(has_parent: bool) {
&refresh_debounce_ms,
&refresh_linter,
),
- Err(error) => eprintln!("failed to refresh highlighter config: {error}"),
+ Err(error) => {
+ eprintln!("failed to refresh highlighter config: {error}");
+ std::process::exit(1);
+ }
}
};
diff --git a/harper-desktop/src-tauri/src/mac_broker/mod.rs b/harper-desktop/src-tauri/src/mac_broker/mod.rs
index efb41bdf3..f8a160a17 100644
--- a/harper-desktop/src-tauri/src/mac_broker/mod.rs
+++ b/harper-desktop/src-tauri/src/mac_broker/mod.rs
@@ -279,7 +279,7 @@ impl MacBroker {
impl Default for MacBroker {
fn default() -> Self {
- Self::new(Arc::new(Mutex::new(Config::curated_integrations())))
+ Self::new(Arc::new(Mutex::new(Integration::curated_integrations())))
}
}
@@ -325,7 +325,7 @@ impl OsBroker for MacBroker {
let integration_enabled = match self.integrations.lock() {
Ok(integrations) => {
- Config::is_integration_enabled_in(&integrations, &bundle_identifier)
+ Integration::is_integration_enabled_in(&integrations, &bundle_identifier)
}
Err(error) => {
eprintln!("Unable to read integrations: {error}");
diff --git a/harper-desktop/src-tauri/src/menu_bar_icon.rs b/harper-desktop/src-tauri/src/menu_bar_icon.rs
deleted file mode 100644
index fe6dcdfc1..000000000
--- a/harper-desktop/src-tauri/src/menu_bar_icon.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-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);
- }
- }
-}
diff --git a/harper-desktop/src-tauri/src/tray.rs b/harper-desktop/src-tauri/src/tray.rs
new file mode 100644
index 000000000..840ae0f8a
--- /dev/null
+++ b/harper-desktop/src-tauri/src/tray.rs
@@ -0,0 +1,111 @@
+use std::time::Duration;
+
+use tauri::image::Image;
+use tauri::tray::TrayIconBuilder;
+use tokio::time::sleep;
+use tracing::error;
+
+use tauri::menu::{Menu, MenuBuilder};
+use tauri::{AppHandle, Manager, Runtime, State};
+use tokio::runtime::Runtime as AsyncRuntime;
+
+use crate::highlighter_service::HighlighterService;
+use crate::windows::{open_issue_report, show_editor_window, show_settings_window};
+
+/// Defines the layout of the tray menu.
+fn tray_menu<R: Runtime, M: Manager<R>>(manager: &M) -> tauri::Result<Menu<R>> {
+ MenuBuilder::new(manager)
+ .text("toggle-service", "Toggle Service")
+ .text("open-editor", "Open Editor")
+ .text("settings", "Settings")
+ .text("report-issue", "Report Issue")
+ .text("quit", "Quit")
+ .build()
+}
+
+pub fn set_up_tray_menu(app: &AppHandle) -> tauri::Result<()> {
+ let highlighter_service: State<HighlighterService> = app.state();
+ let async_runtime: State<AsyncRuntime> = app.state();
+
+ let tray_icon = TrayIconBuilder::new()
+ .icon(menu_bar_icon(highlighter_service.is_running())?)
+ .menu(&tray_menu(app)?)
+ .on_menu_event(move |app, event| {
+ let event_id = event.id().0.as_str();
+
+ match event_id {
+ "toggle-service" => {
+ let service: State<HighlighterService> = app.state();
+
+ let _ = service
+ .toggle()
+ .inspect_err(|err| error!("Could not toggle highlighter: {err}"));
+ }
+ "open-editor" => {
+ let _ = show_editor_window(app)
+ .inspect_err(|err| error!("Could not open the editor window: {err}"));
+ }
+ "settings" => {
+ let _ = show_settings_window(app)
+ .inspect_err(|err| error!("Could not open the settings window: {err}"));
+ }
+ "report-issue" => open_issue_report(app),
+ "quit" => app.exit(0),
+ _ => error!("Encountered unexpected event: `{event_id}`"),
+ };
+ })
+ .build(app)?;
+
+ let app = app.clone();
+ async_runtime.spawn(async move {
+ loop {
+ sleep(Duration::from_millis(250)).await;
+
+ {
+ let highlighter_service: State<HighlighterService> = app.state();
+ let is_running = highlighter_service.is_running();
+
+ let Ok(new_icon) = menu_bar_icon(is_running) else {
+ error!("Unable to generate new menu bar icon.");
+ continue;
+ };
+
+ let _ = tray_icon
+ .set_icon(Some(new_icon))
+ .inspect_err(|err| error!("Unable to set new icon: {err}"));
+ }
+ }
+ });
+
+ Ok(())
+}
+
+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);
+ }
+ }
+}
diff --git a/harper-desktop/src-tauri/src/windows.rs b/harper-desktop/src-tauri/src/windows.rs
new file mode 100644
index 000000000..fb91d32e5
--- /dev/null
+++ b/harper-desktop/src-tauri/src/windows.rs
@@ -0,0 +1,51 @@
+//! Functions to manage the main windows involved in Harper Desktop
+
+use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};
+use tauri_plugin_opener::OpenerExt;
+use tracing::error;
+
+/// Open the editor window, focusing it if it already exists.
+pub fn show_editor_window(app: &tauri::AppHandle) -> tauri::Result<()> {
+ if let Some(window) = app.get_webview_window("editor") {
+ window.show()?;
+ window.set_focus()?;
+ return Ok(());
+ }
+
+ let window = WebviewWindowBuilder::new(app, "editor", WebviewUrl::App("index.html".into()))
+ .title("Harper")
+ .inner_size(800.0, 600.0)
+ .build()?;
+ window.set_focus()?;
+
+ Ok(())
+}
+
+/// Open the settings window, focusing it if it already exists.
+pub fn show_settings_window(app: &tauri::AppHandle) -> tauri::Result<()> {
+ if let Some(window) = app.get_webview_window("settings") {
+ window.show()?;
+ window.set_focus()?;
+ return Ok(());
+ }
+
+ WebviewWindowBuilder::new(app, "settings", WebviewUrl::App("index.html".into()))
+ .title("Harper Settings")
+ .inner_size(920.0, 680.0)
+ .min_inner_size(780.0, 520.0)
+ .center()
+ .build()?;
+
+ Ok(())
+}
+
+/// Open the browser to an issue report page.
+pub fn open_issue_report(app: &AppHandle) {
+ let _ = app
+ .opener()
+ .open_url(
+ "https://github.com/Automattic/harper/issues/new/choose",
+ None::<&str>,
+ )
+ .inspect_err(|err| error!("failed to open issue report URL: {err}"));
+}