Skip to content

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

18.3 KB
Raw Blame
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

mod debug_broker;
mod tray;
mod windows;

use self::debug_broker::DebugBroker;
use self::highlighter::Highlighter;
use self::highlighter_service::HighlighterService;
use self::tray::set_up_tray_menu;
use crate::args::{Args, Command};
use crate::communication::{Client, ProtocolError};
use crate::config::{Config, Integration};
use crate::debounce::{DebounceState, DebounceStatus};
use clap::Parser;
use harper_core::{
    Dialect, DictWordMetadata, Document, IgnoredLints,
    linting::{Lint, LintGroup},
    spell::MutableDictionary,
};
use serde::Serialize;
use std::collections::BTreeMap;
use std::io::stderr;
use std::{
    cell::RefCell,
    rc::Rc,
    sync::{Arc, Mutex as StdMutex, RwLock},
};
use tauri::Manager as _;
use tracing::{Level, error};
use tracing_subscriber::FmtSubscriber;

use crate::os_broker::{AccessibilityPermissionStatus, OsBroker};
use tokio::{
    io::{Stdin, Stdout},
    runtime::{Builder, Runtime},
    sync::Mutex,
};

mod args;
pub mod color;
mod commands;
pub mod communication;
pub mod config;
mod debounce;
mod desktop_updater;
pub mod highlighter;
pub mod highlighter_service;
pub mod lint_kind_color;
mod os_broker;
pub mod rect;

#[cfg(target_os = "macos")]
mod mac_broker;

#[cfg(target_os = "windows")]
mod windows_broker;

#[derive(Debug, Clone, Serialize)]
struct IntegrationView {
    bundle_id: String,
    enabled: bool,
    display_name: String,
}

#[cfg(target_os = "macos")]
pub(crate) type PlatformBroker = mac_broker::MacBroker;

#[cfg(target_os = "windows")]
pub(crate) type PlatformBroker = windows_broker::WindowsBroker;

#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) type PlatformBroker = os_broker::NoopBroker;

/// Creates the process-local platform broker.
///
/// The Tauri process stores its single broker as managed state, while the highlighter subprocess
/// creates its own broker because it is a separate process.
fn platform_broker(
    is_integration_enabled: impl FnMut(&str) -> bool + Send + Sync + 'static,
) -> PlatformBroker {
    #[cfg(any(target_os = "macos", target_os = "windows"))]
    {
        PlatformBroker::new(is_integration_enabled)
    }

    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    {
        let _ = is_integration_enabled;
        PlatformBroker::default()
    }
}

fn warm_app_search_cache(app: tauri::AppHandle) {
    tauri::async_runtime::spawn_blocking(move || {
        let broker = app.state::<RwLock<PlatformBroker>>();
        let result = broker
            .read()
            .map_err(|error| format!("failed to read platform broker: {error}"))
            .and_then(|broker| broker.search_apps("").map(|_| ()));

        if let Err(error) = result {
            eprintln!("failed to warm app search cache: {error}");
        }
    });
}

pub fn main() {
    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 {
        Some(Command::Highlighter { no_parent }) => run_highlighter(!no_parent),
        Some(Command::PopupDebug) => popup_debug(),
        None => run_tauri(),
    }
}

pub fn run_tauri() {
    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) => {
            eprintln!("failed to check config existence: {error}");
            false
        }
    };

    let config = if is_first_launch {
        let config = Config::new();

        if let Err(error) = async_runtime.block_on(config.save_to_system()) {
            eprintln!("failed to save initial config: {error}");
        }

        config
    } else {
        match async_runtime.block_on(Config::load_from_system()) {
            Ok(config) => config,
            Err(error) => {
                eprintln!("failed to load config, using defaults: {error}");
                Config::new()
            }
        }
    };

    let broker = platform_broker(|_| false);

    let should_start_highlighter = config.highlighter_service_enabled
        && broker.accessibility_permission_status() == AccessibilityPermissionStatus::Granted;
    let config = Arc::new(Mutex::new(config));

    tauri::Builder::default()
        .manage(config.clone())
        .manage(desktop_updater::DesktopUpdater::default())
        .manage(RwLock::new(broker))
        .manage(async_runtime)
        .plugin(tauri_plugin_autostart::init(
            tauri_plugin_autostart::MacosLauncher::LaunchAgent,
            None,
        ))
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_os::init())
        .invoke_handler(commands::application_message_handler())
        .setup(move |app| {
            app.handle()
                .plugin(tauri_plugin_updater::Builder::new().build())?;

            let highlighter_service = HighlighterService::new(config, app.handle().clone());
            if should_start_highlighter {
                let _ = highlighter_service
                    .start()
                    .inspect_err(|err| error!("Unable to start highlighter: {err}"));
            }
            app.manage(highlighter_service);

            set_up_tray_menu(app.handle())?;
            warm_app_search_cache(app.handle().clone());
            desktop_updater::start_auto_updates(app.handle().clone());

            if is_first_launch {
                windows::show_settings_window(app.handle())?;
            }

            #[cfg(target_os = "macos")]
            windows::sync_dock_visibility(app.handle(), None)?;

            Ok(())
        })
        .build(tauri::generate_context!())
        .expect("error while building tauri application")
        .run(|_app, event| {
            #[cfg(target_os = "macos")]
            if let tauri::RunEvent::WindowEvent {
                label,
                event: tauri::WindowEvent::Destroyed,
                ..
            } = &event
            {
                let _ = windows::sync_dock_visibility(_app, Some(label))
                    .inspect_err(|err| error!("Could not update Dock visibility: {err}"));
            }

            // Keep the tray and service alive after the last window closes, but allow Quit.
            if let tauri::RunEvent::ExitRequested {
                code: None, api, ..
            } = event
            {
                api.prevent_exit();
            }
        });
}

pub fn popup_debug() {
    let highlighter = Highlighter::new(
        DebugBroker,
        |_| BTreeMap::new(),
        |_, _| {},
        |_| {},
        |_| {},
        || {},
        || {},
    )
    .unwrap();
    highlighter.run_window_for_each_monitor().unwrap();
}

/// 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 = Arc::new(StdMutex::new(Client::current_process()));
    let sync_runtime = Arc::new(
        Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("failed to build highlighter protocol runtime"),
    );

    let startup_config = if has_parent {
        fetch_highlighter_config(
            &mut client.lock().expect("IPC client lock poisoned"),
            &sync_runtime,
        )
    } else {
        Ok(Config::default())
    };

    let startup_config = match startup_config {
        Ok(config) => config,
        Err(error) => {
            eprintln!("failed to hydrate highlighter config, using defaults: {error}");
            Config::new()
        }
    };

    let startup_linter = startup_config.create_linter();
    let ignored_lints = Rc::new(RefCell::new(startup_config.ignored_lints));
    let user_dictionary = Rc::new(RefCell::new(startup_config.mutable_dictionary));
    let dialect = Rc::new(RefCell::new(startup_config.dialect));
    let integrations = Arc::new(StdMutex::new(IntegrationState {
        integrations: startup_config.integrations,
        auto_enable_new_apps: startup_config.auto_enable_new_apps,
    }));
    let debounce_ms = Rc::new(RefCell::new(startup_config.debounce_ms));
    let linter = Rc::new(RefCell::new(startup_linter));

    let integration_client = client.clone();
    let integration_runtime = sync_runtime.clone();
    let is_integration_enabled = integration_callback(integrations.clone(), move |bundle_id| {
        if !has_parent {
            return true;
        }
        match integration_runtime.block_on(
            integration_client
                .lock()
                .expect("IPC client lock poisoned")
                .resolve_integration(bundle_id),
        ) {
            Ok(enabled) => enabled,
            Err(error) => {
                eprintln!("failed to register integration: {error}");
                false
            }
        }
    });
    let broker = platform_broker(is_integration_enabled);

    let lint_ignored_lints = ignored_lints.clone();
    let lint_linter = linter.clone();
    let lint_user_dictionary = user_dictionary.clone();
    let lint_debounce_ms = debounce_ms.clone();
    let lint_debounce_state = Rc::new(RefCell::new(DebounceState::default()));

    let ignore_client = client.clone();
    let ignore_runtime = sync_runtime.clone();
    let ignore_ignored_lints = ignored_lints.clone();

    let dictionary_client = client.clone();
    let dictionary_runtime = sync_runtime.clone();
    let dictionary_user_dictionary = user_dictionary.clone();
    let dictionary_linter = linter.clone();
    let dictionary_dialect = dialect.clone();
    let dictionary_debounce_ms = debounce_ms.clone();

    let disable_client = client.clone();
    let disable_runtime = sync_runtime.clone();
    let disable_linter = linter.clone();

    let settings_client = client.clone();
    let settings_runtime = sync_runtime.clone();

    let refresh_client = client.clone();
    let refresh_runtime = sync_runtime.clone();
    let refresh_ignored_lints = ignored_lints.clone();
    let refresh_user_dictionary = user_dictionary.clone();
    let refresh_dialect = dialect.clone();
    let refresh_integrations = integrations.clone();
    let refresh_debounce_ms = debounce_ms.clone();
    let refresh_linter = linter.clone();

    let lint_text = move |text: &str| {
        let debounce_ms = *lint_debounce_ms.borrow();
        let mut debounce_state = lint_debounce_state.borrow_mut();

        match debounce_state.status(text, debounce_ms) {
            DebounceStatus::Cached(lints) => return lints,
            DebounceStatus::Ready => {}
        }

        let dictionary =
            Config::dictionary_from_user_dictionary(lint_user_dictionary.borrow().clone());
        let doc = Document::new_markdown_default(text, &dictionary);
        let mut organized_lints = lint_linter.borrow_mut().organized_lints(&doc);

        for lints in organized_lints.values_mut() {
            lint_ignored_lints.borrow().remove_ignored(lints, &doc);
        }

        debounce_state.store_lints(text, debounce_ms, &organized_lints);

        organized_lints
    };

    let ignore_lint = move |lint: &Lint, document: &Document| {
        {
            ignore_ignored_lints
                .borrow_mut()
                .ignore_lint(lint, document);
        }

        let snapshot = ignore_ignored_lints.borrow().clone();
        if let Err(error) = ignore_runtime.block_on(
            ignore_client
                .lock()
                .expect("IPC client lock poisoned")
                .ignore_lint(&snapshot),
        ) {
            eprintln!("failed to sync ignored lints: {error}");
        }
    };

    let add_to_dictionary = move |word: &str| {
        dictionary_user_dictionary
            .borrow_mut()
            .append_word_str(word, DictWordMetadata::default());

        let lint_config = dictionary_linter.borrow().config.clone();
        let config = Config {
            mutable_dictionary: dictionary_user_dictionary.borrow().clone(),
            dialect: *dictionary_dialect.borrow(),
            ignored_lints: IgnoredLints::new(),
            lint_config,
            integrations: Vec::new(),
            auto_enable_new_apps: false,
            onboarding_completed: false,
            debounce_ms: *dictionary_debounce_ms.borrow(),
            auto_update: true,
            last_update_check: None,
            highlighter_service_enabled: true,
        };
        *dictionary_linter.borrow_mut() = config.create_linter();

        if let Err(error) = dictionary_runtime.block_on(
            dictionary_client
                .lock()
                .expect("IPC client lock poisoned")
                .add_to_dictionary(word),
        ) {
            eprintln!("failed to sync dictionary update: {error}");
        }
    };

    let disable_rule = move |rule_name: &str| match disable_runtime.block_on(
        disable_client
            .lock()
            .expect("IPC client lock poisoned")
            .disable_rule(rule_name),
    ) {
        Ok(config) => disable_linter.borrow_mut().config = config,
        Err(error) => eprintln!("failed to disable rule {rule_name}: {error}"),
    };

    let open_settings = move || {
        if !has_parent {
            eprintln!("cannot open settings without a parent app");
            return;
        }

        if let Err(error) = settings_runtime.block_on(
            settings_client
                .lock()
                .expect("IPC client lock poisoned")
                .open_settings(),
        ) {
            eprintln!("failed to request settings window: {error}");
        }
    };

    let refresh_config = move || {
        if !has_parent {
            return;
        }

        match fetch_highlighter_config(
            &mut refresh_client.lock().expect("IPC client lock poisoned"),
            &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}");
                std::process::exit(1);
            }
        }
    };

    if let Err(error) = Highlighter::new(
        broker,
        lint_text,
        ignore_lint,
        add_to_dictionary,
        disable_rule,
        refresh_config,
        open_settings,
    )
    .and_then(Highlighter::run_window_for_each_monitor)
    {
        eprintln!("failed to run highlighter: {error}");
    }
}

/// Highlighter-local app policy snapshot, replaced on each config poll.
/// Also caches discovery decisions (including denials) until the next poll to avoid per-frame IPC.
struct IntegrationState {
    integrations: Vec<Integration>,
    auto_enable_new_apps: bool,
}

/// Builds the broker's policy callback. Known apps are checked locally; only unknown apps with
/// automatic enablement on reach `resolve`, which persists registration in the parent process.
/// Harper itself is excluded from discovery, but explicitly configured entries are respected.
/// Standalone callers can approve registration locally without IPC.
fn integration_callback(
    state: Arc<StdMutex<IntegrationState>>,
    mut resolve: impl FnMut(&str) -> bool + Send + Sync + 'static,
) -> impl FnMut(&str) -> bool + Send + Sync + 'static {
    move |bundle_id| {
        let bundle_id = bundle_id.trim();
        if bundle_id.is_empty() {
            return false;
        }
        let mut state = state.lock().expect("integration state lock poisoned");
        if let Some(integration) = state
            .integrations
            .iter()
            .find(|item| item.bundle_id == bundle_id)
        {
            return integration.enabled;
        }
        if !state.auto_enable_new_apps || PlatformBroker::is_harper_desktop(bundle_id) {
            return false;
        }
        let enabled = resolve(bundle_id);
        state.integrations.push(Integration {
            bundle_id: bundle_id.to_owned(),
            enabled,
        });
        enabled
    }
}

fn fetch_highlighter_config(
    client: &mut Client<Stdin, Stdout>,
    runtime: &Runtime,
) -> Result<Config, ProtocolError> {
    runtime.block_on(async {
        let dialect = client.get_dialect().await?;
        let mutable_dictionary = client.get_dictionary().await?;
        let ignored_lints = client.get_ignored_lints().await?;
        let lint_config = client.get_lint_config().await?;
        let integrations = client.get_integrations().await?;
        let auto_enable_new_apps = client.get_auto_enable_new_apps().await?;
        let debounce_ms = client.get_debounce_ms().await?;

        Ok(Config {
            dialect,
            mutable_dictionary,
            ignored_lints,
            lint_config,
            integrations,
            auto_enable_new_apps,
            onboarding_completed: false,
            debounce_ms,
            auto_update: true,
            last_update_check: None,
            highlighter_service_enabled: true,
        })
    })
}

fn apply_highlighter_config(
    config: Config,
    ignored_lints: &Rc<RefCell<IgnoredLints>>,
    user_dictionary: &Rc<RefCell<MutableDictionary>>,
    dialect: &Rc<RefCell<Dialect>>,
    integrations: &Arc<StdMutex<IntegrationState>>,
    debounce_ms: &Rc<RefCell<u64>>,
    linter: &Rc<RefCell<LintGroup>>,
) {
    if config.mutable_dictionary != *user_dictionary.borrow()
        || config.dialect != *dialect.borrow()
        || config.lint_config != linter.borrow().config
    {
        *linter.borrow_mut() = config.create_linter();
    }
    *ignored_lints.borrow_mut() = config.ignored_lints;
    *user_dictionary.borrow_mut() = config.mutable_dictionary;
    *dialect.borrow_mut() = config.dialect;
    match integrations.lock() {
        Ok(mut integrations) => {
            *integrations = IntegrationState {
                integrations: config.integrations,
                auto_enable_new_apps: config.auto_enable_new_apps,
            }
        }
        Err(error) => eprintln!("failed to update integrations: {error}"),
    }
    *debounce_ms.borrow_mut() = config.debounce_ms;
}