Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(desktop): make the popup appear similar to the Chrome Extension's (#4610)
Elijah Potterc25b8ed62308
diff --git a/harper-desktop/src-tauri/src/communication/client.rs b/harper-desktop/src-tauri/src/communication/client.rsindex 4e418c5d7..44ca22534 100644--- a/harper-desktop/src-tauri/src/communication/client.rs+++ b/harper-desktop/src-tauri/src/communication/client.rs@@ -29,6 +29,10 @@ where}}+ pub async fn open_settings(&mut self) -> Result<(), ProtocolError> {+ self.send_ack_request(Request::OpenSettings).await+ }+pub async fn get_lint_config(&mut self) -> Result<FlatConfig, ProtocolError> {match self.send_request(Request::GetLintConfig).await? {Response::GetLintConfig { config } => Ok(config),diff --git a/harper-desktop/src-tauri/src/communication/message.rs b/harper-desktop/src-tauri/src/communication/message.rsindex 7dce346a7..5978b8f2f 100644--- a/harper-desktop/src-tauri/src/communication/message.rs+++ b/harper-desktop/src-tauri/src/communication/message.rs@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};/// Canonical client-to-server protocol message sent by the highlighter process.#[derive(Debug, Clone, Serialize, Deserialize)]pub enum Request {+ OpenSettings,GetLintConfig,GetDictionary,GetDialect,diff --git a/harper-desktop/src-tauri/src/communication/server.rs b/harper-desktop/src-tauri/src/communication/server.rsindex ad974870b..893944244 100644--- a/harper-desktop/src-tauri/src/communication/server.rs+++ b/harper-desktop/src-tauri/src/communication/server.rs@@ -43,6 +43,7 @@ whereasync fn handle_request(&self, request: &Request) -> Response {match request {+ Request::OpenSettings => Response::Ack,Request::GetLintConfig => Response::GetLintConfig {config: self.config.lock().await.lint_config.clone(),},diff --git a/harper-desktop/src-tauri/src/highlighter/mod.rs b/harper-desktop/src-tauri/src/highlighter/mod.rsindex 4db973fff..eb37f8361 100644--- a/harper-desktop/src-tauri/src/highlighter/mod.rs+++ b/harper-desktop/src-tauri/src/highlighter/mod.rs@@ -17,14 +17,14 @@ type IgnoreLint = Box<dyn FnMut(&Lint, &Document)>;type AddToDictionary = Box<dyn FnMut(&str)>;type DisableRule = Box<dyn FnMut(&str)>;type RefreshConfig = Box<dyn FnMut()>;+type OpenSettings = Box<dyn FnMut()>;/// Public entry point for the screen highlighter system.///-/// `Highlighter` owns the shared egui context and delegates native window/event-loop work to the-/// window manager. Keeping this as the top-level type gives future callers one place to configure-/// or update highlighter state without depending on the windowing implementation.+/// `Highlighter` delegates native window/event-loop work to the window manager. Keeping this as the+/// top-level type gives future callers one place to configure or update highlighter state without+/// depending on the windowing implementation.pub struct Highlighter {- context: egui::Context,window_manager: WindowManager,}@@ -36,17 +36,17 @@ impl Highlighter {add_to_dictionary: impl FnMut(&str) + 'static,disable_rule: impl FnMut(&str) + 'static,refresh_config: impl FnMut() + 'static,+ open_settings: impl FnMut() + 'static,) -> Result<Self, Error> {- let context = egui::Context::default();let lint_text: LintText = Box::new(lint_text);let ignore_lint: IgnoreLint = Box::new(ignore_lint);let add_to_dictionary: AddToDictionary = Box::new(add_to_dictionary);let disable_rule: DisableRule = Box::new(disable_rule);let refresh_config: RefreshConfig = Box::new(refresh_config);+ let open_settings: OpenSettings = Box::new(open_settings);Ok(Self {window_manager: WindowManager::new(- context.clone(),Box::new(os_broker),WindowManagerCallbacks {lint_text,@@ -54,21 +54,14 @@ impl Highlighter {add_to_dictionary,disable_rule,refresh_config,+ open_settings,},)?,- context,})}pub fn run_window_for_each_monitor(self) -> Result<(), Error> {- let Self {- context,- window_manager,- } = self;-- drop(context);-- window_manager.run_window_for_each_monitor()+ self.window_manager.run_window_for_each_monitor()}pub fn set_rects(&mut self, rects: Vec<ActionableLint>) {diff --git a/harper-desktop/src-tauri/src/highlighter/render_state.rs b/harper-desktop/src-tauri/src/highlighter/render_state.rsdeleted file mode 100644index d0141f71a..000000000--- a/harper-desktop/src-tauri/src/highlighter/render_state.rs+++ /dev/null@@ -1,772 +0,0 @@-use egui_commonmark::{CommonMarkCache, CommonMarkViewer};-use harper_core::{- Document,- linting::{Lint, LintKind, Suggestion},-};--use super::{AddToDictionary, DisableRule, IgnoreLint};-use crate::{- lint_kind_color::lint_kind_color,- rect::{ActionableLint, Rect},-};--const CARD_WIDTH: f32 = 440.0;-const CARD_HEIGHT: f32 = 178.0;-const CARD_OFFSET_Y: f32 = 8.0;-const HEADER_HEIGHT: f32 = 46.0;-const FOOTER_HEIGHT: f32 = 43.0;--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum HitTarget {- Lint(usize),- Popup,- None,-}--enum LintCardAction {- Close,- ApplySuggestion(Suggestion),- IgnoreLint,- AddToDictionary,- DisableRule,-}--#[derive(Debug, Clone, Copy)]-struct PopupStyle {- color: egui::Color32,- background: egui::Color32,- foreground: egui::Color32,-}--#[derive(Debug, Clone, Copy)]-enum Glyph {- Close,- Settings,- Disable,- Plus,-}--/// Stores highlighter-specific drawing state and renders it into an egui frame.-///-/// `Window` owns the native window and GPU plumbing; `RenderState` owns the content we want to draw-/// into that plumbing. This keeps future highlight rectangles, styling, and animation state out of-/// the platform/rendering infrastructure.-pub struct RenderState {- /// Last successful accessibility read, retained when a later read fails.- last_lints: Option<Vec<ActionableLint>>,-- /// Index of the lint whose suggestion popup is currently visible.- ///- /// `None` means no popup should be rendered.- highlighted_lint: Option<usize>,-- /// Cache for markdown-rendered lint messages so popup redraws do not repeatedly rebuild markdown- /// resources from scratch.- markdown_cache: CommonMarkCache,-- /// Called when the user dismisses a lint so app-level ignored-lint state can be updated.- ignore_lint: IgnoreLint,-- /// Called when the user adds a spelling lint's source text to the local dictionary.- add_to_dictionary: AddToDictionary,-- /// Called when the user disables the rule that produced the selected lint.- disable_rule: DisableRule,-}--impl RenderState {- /// Creates render state through `set_lints` so initial lint data gets the same stale-popup guard- /// used by later accessibility refreshes.- pub fn new(- rects: Vec<ActionableLint>,- ignore_lint: IgnoreLint,- add_to_dictionary: AddToDictionary,- disable_rule: DisableRule,- ) -> Self {- let mut state = Self {- last_lints: None,- highlighted_lint: None,- markdown_cache: CommonMarkCache::default(),- ignore_lint,- add_to_dictionary,- disable_rule,- };- state.set_lints(rects);- state- }-- /// Saves successful accessibility reads while retaining the previous lints after a failed read.- pub fn set_lints(&mut self, lints: Vec<ActionableLint>) {- self.last_lints = Some(lints);-- if self- .highlighted_lint- .is_some_and(|index| index >= self.lints().len())- {- self.highlighted_lint = None;- }- }-- fn lints(&self) -> &[ActionableLint] {- self.last_lints.as_deref().unwrap_or_default()- }-- /// Updates which lint owns the suggestion popup without exposing render-state internals.- ///- /// Window/input code decides what the user interacted with, while `RenderState` owns the popup- /// selection. Filtering invalid indexes here keeps stale cursor state from selecting a lint that- /// disappeared after the latest accessibility read.- pub fn set_highlighted_lint(&mut self, highlighted_lint: Option<usize>) {- self.highlighted_lint = highlighted_lint.filter(|index| *index < self.lints().len());- }-- /// Centralizes the close behavior so the popup close button only has to clear the selected lint.- pub fn close_popup(&mut self) {- self.highlighted_lint = None;- }-- /// Checks if a given position touches a hit target.- pub fn hit_target_at_pos(&self, pos: egui::Pos2) -> HitTarget {- if self.popup_rect().is_some_and(|rect| rect.contains(pos)) {- return HitTarget::Popup;- }-- self.lints()- .iter()- .position(|positioned_lint| {- rect_bounds(&positioned_lint.rect.with_friendly_padding()).contains(pos)- })- .map_or(HitTarget::None, HitTarget::Lint)- }-- /// Computes popup hit-test bounds from our layout contract instead of waiting for egui to report- /// rendered bounds, which keeps hit-testing available before the next render pass completes.- pub fn popup_rect(&self) -> Option<egui::Rect> {- self.highlighted_lint- .and_then(|index| self.lints().get(index))- .map(|positioned_lint| popup_rect_for_lint(&positioned_lint.rect))- }-- /// Draws highlights and the active popup from the same state used by hit-testing so visible- /// regions and clickable regions do not drift apart.- pub fn render(&mut self, ui: &mut egui::Ui) {- for positioned_lint in self.lints() {- draw_highlight(ui, &positioned_lint.rect, &positioned_lint.lint);- }-- if let Some(index) = self.highlighted_lint- && let Some(positioned_lint) = self.lints().get(index)- {- let rect = positioned_lint.rect;- let lint = positioned_lint.lint.clone();- let source_text = positioned_lint.source_text.clone();-- match render_lint_card(ui, &rect, &lint, &source_text, &mut self.markdown_cache) {- Some(LintCardAction::Close) => self.close_popup(),- Some(LintCardAction::ApplySuggestion(suggestion)) => {- if let Some(actionable_lint) = self- .last_lints- .as_mut()- .and_then(|lints| lints.get_mut(index))- {- actionable_lint.apply_suggestion(suggestion);- }-- self.close_popup();- }- Some(LintCardAction::IgnoreLint) => {- if let Some((lint, source_text)) =- self.lints().get(index).map(|actionable_lint| {- (- actionable_lint.lint.clone(),- actionable_lint.source_text.clone(),- )- })- {- let document = Document::new_markdown_default_curated(&source_text);- (self.ignore_lint)(&lint, &document);- }-- self.close_popup();- }- Some(LintCardAction::AddToDictionary) => {- if let Some((lint, source_text)) =- self.lints().get(index).map(|actionable_lint| {- (- actionable_lint.lint.clone(),- actionable_lint.source_text.clone(),- )- })- {- let document = Document::new_markdown_default_curated(&source_text);- let word = lint.get_str(document.get_source());- (self.add_to_dictionary)(&word);- }-- self.close_popup();- }- Some(LintCardAction::DisableRule) => {- if let Some(rule_name) = self- .lints()- .get(index)- .map(|actionable_lint| actionable_lint.rule_name.clone())- {- (self.disable_rule)(&rule_name);- }-- self.close_popup();- }- None => {}- }- }- }-}--/// Draws the always-visible lint marker without making the renderer responsible for popup state.-fn draw_highlight(ui: &mut egui::Ui, rect: &Rect, lint: &Lint) {- let rect_bounds = rect_bounds(rect);- let color = lint_color(lint);- let [r, g, b, _] = color.to_array();- let fill_color = egui::Color32::from_rgba_unmultiplied(r, g, b, 24);- let underline_color = egui::Color32::from_rgba_unmultiplied(r, g, b, 255);- let underline_height = rect_bounds.height().min(2.0);-- ui.painter().rect_filled(rect_bounds, 0.0, fill_color);- ui.painter().rect_filled(- egui::Rect::from_min_max(- egui::pos2(rect_bounds.left(), rect_bounds.bottom() - underline_height),- rect_bounds.right_bottom(),- ),- 0.0,- underline_color,- );-}--/// Renders the suggestion popup and returns whether the explicit close control was clicked.-fn render_lint_card(- ui: &mut egui::Ui,- rect: &Rect,- lint: &Lint,- source_text: &str,- markdown_cache: &mut CommonMarkCache,-) -> Option<LintCardAction> {- let popup_rect = popup_rect_for_lint(rect);-- egui::Area::new(egui::Id::new("harper-lint-card"))- .order(egui::Order::Foreground)- .fixed_pos(popup_rect.min)- .show(ui.ctx(), |ui| {- let mut action = None;-- egui::Frame::new()- .fill(hex(0xff, 0xfd, 0xfa))- .stroke(egui::Stroke::new(- 1.0_f32,- egui::Color32::from_rgba_unmultiplied(0, 0, 0, 20),- ))- .corner_radius(egui::CornerRadius::same(12))- .inner_margin(egui::Margin::same(0))- .shadow(egui::Shadow {- offset: [0, 14],- blur: 32,- spread: 0,- color: egui::Color32::from_rgba_unmultiplied(20, 12, 2, 56),- })- .show(ui, |ui| {- ui.set_width(CARD_WIDTH);- ui.set_min_height(CARD_HEIGHT);- ui.set_max_height(CARD_HEIGHT);-- render_popover_header(ui, lint, &mut action);- render_popover_body(ui, lint, markdown_cache, &mut action);- render_popover_footer(ui, lint, source_text, &mut action);- });- action- })- .inner-}--/// Renders the top bar from the prototype, including no-op utility icons and the real close action.-fn render_popover_header(ui: &mut egui::Ui, lint: &Lint, action: &mut Option<LintCardAction>) {- let style = popup_style_for_lint_kind(lint.lint_kind);-- egui::Frame::new()- .fill(blend(style.background, hex(0xff, 0xfd, 0xfa), 0.42))- .stroke(egui::Stroke::new(- 1.0_f32,- egui::Color32::from_rgba_unmultiplied(0, 0, 0, 15),- ))- .corner_radius(egui::CornerRadius {- nw: 12,- ne: 12,- sw: 0,- se: 0,- })- .inner_margin(egui::Margin::symmetric(10, 10))- .show(ui, |ui| {- ui.set_width(CARD_WIDTH - 20.0);- ui.set_height(HEADER_HEIGHT - 20.0);- ui.horizontal(|ui| {- lint_kind_badge(ui, lint, style);- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if icon_button(ui, Glyph::Close, "Close this suggestion popup.").clicked() {- *action = Some(LintCardAction::Close);- }- icon_button(ui, Glyph::Settings, "Open Harper settings.");- if icon_button(ui, Glyph::Disable, "Disable this rule.").clicked() {- *action = Some(LintCardAction::DisableRule);- }- });- });- });-}--/// Renders the markdown explanation and horizontal suggestion chip row from the prototype body.-fn render_popover_body(- ui: &mut egui::Ui,- lint: &Lint,- markdown_cache: &mut CommonMarkCache,- action: &mut Option<LintCardAction>,-) {- egui::Frame::new()- .fill(hex(0xff, 0xfd, 0xfa))- .inner_margin(egui::Margin::symmetric(16, 12))- .show(ui, |ui| {- ui.set_width(CARD_WIDTH - 32.0);- ui.set_min_height(CARD_HEIGHT - HEADER_HEIGHT - FOOTER_HEIGHT - 24.0);- ui.spacing_mut().item_spacing = egui::vec2(8.0, 8.0);-- render_lint_message(ui, markdown_cache, &lint.message);-- if !lint.suggestions.is_empty() {- ui.add_space(6.0);- ui.horizontal_wrapped(|ui| {- ui.spacing_mut().item_spacing = egui::vec2(8.0, 8.0);-- for (index, suggestion) in lint.suggestions.iter().enumerate() {- if suggestion_option(ui, lint.lint_kind, suggestion, index == 0).clicked() {- *action = Some(LintCardAction::ApplySuggestion(suggestion.clone()));- }- }- });- }- });-}--/// Renders the footer controls as visual stubs so the popup matches the target component before those-/// actions have real behavior.-fn render_popover_footer(- ui: &mut egui::Ui,- lint: &Lint,- source_text: &str,- action: &mut Option<LintCardAction>,-) {- egui::Frame::new()- .fill(egui::Color32::from_rgba_unmultiplied(0, 0, 0, 5))- .stroke(egui::Stroke::new(- 1.0_f32,- egui::Color32::from_rgba_unmultiplied(0, 0, 0, 15),- ))- .inner_margin(egui::Margin::symmetric(10, 8))- .show(ui, |ui| {- ui.set_width(CARD_WIDTH - 20.0);- ui.set_height(FOOTER_HEIGHT - 16.0);- ui.horizontal(|ui| {- if is_spelling_kind(lint.lint_kind) {- let source_chars = source_text.chars().collect::<Vec<_>>();- let word = lint.get_str(&source_chars);- if ghost_button(- ui,- Some(Glyph::Plus),- "Add to dictionary",- format!("Add \"{word}\" to your personal dictionary."),- )- .clicked()- {- *action = Some(LintCardAction::AddToDictionary);- }- }- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if ghost_button(ui, None, "Dismiss", "Ignore this suggestion").clicked() {- *action = Some(LintCardAction::IgnoreLint);- }- });- });- });-}--/// Renders Harper's markdown-formatted lint message in the popup instead of showing raw markdown-/// markers to the user.-fn render_lint_message(ui: &mut egui::Ui, cache: &mut CommonMarkCache, message: &str) {- ui.scope(|ui| {- ui.visuals_mut().code_bg_color = hex(0xf3, 0xf4, 0xf6);- ui.visuals_mut().extreme_bg_color = hex(0xf8, 0xfa, 0xfc);- ui.visuals_mut().override_text_color = Some(hex(0x37, 0x41, 0x51));- ui.visuals_mut().text_edit_bg_color = Some(hex(0xf8, 0xfa, 0xfc));- CommonMarkViewer::new()- .default_width(Some(ui.available_width() as usize))- .show(ui, cache, message);- });-}--/// Keeps the lint type visually attached to the popup without duplicating lint-kind formatting in-/// the window manager.-fn lint_kind_badge(ui: &mut egui::Ui, lint: &Lint, style: PopupStyle) {- egui::Frame::new()- .fill(style.background)- .corner_radius(egui::CornerRadius::same(20))- .inner_margin(egui::Margin::symmetric(8, 3))- .show(ui, |ui| {- ui.horizontal(|ui| {- ui.spacing_mut().item_spacing = egui::vec2(6.0, 0.0);- let (dot_rect, _) =- ui.allocate_exact_size(egui::vec2(6.0, 6.0), egui::Sense::hover());- ui.painter()- .circle_filled(dot_rect.center(), 3.0, style.color);- ui.label(- egui::RichText::new(lint.lint_kind.to_string().to_uppercase())- .strong()- .size(11.0_f32)- .color(style.foreground),- );- });- });-}--/// Renders a suggestion as a compact button so later replacement behavior can attach to one place.-fn suggestion_option(- ui: &mut egui::Ui,- lint_kind: LintKind,- suggestion: &Suggestion,- primary: bool,-) -> egui::Response {- let lint_color = lint_kind_color32(lint_kind);- let fill = if primary {- lint_color- } else {- blend(lint_color, hex(0xff, 0xfd, 0xfa), 0.88)- };- let text_color = if primary {- hex(0xff, 0xfd, 0xfa)- } else {- hex(0x0a, 0x0a, 0x0a)- };- let stroke = if primary {- egui::Stroke::NONE- } else {- egui::Stroke::new(1.0_f32, blend(lint_color, hex(0xff, 0xfd, 0xfa), 0.64))- };-- ui.scope(|ui| {- ui.spacing_mut().button_padding = egui::vec2(16.0, 10.0);- let stroke_width = stroke.width;- ui.visuals_mut().widgets.inactive.expansion = 0.0;- ui.visuals_mut().widgets.hovered.expansion = 0.0;- ui.visuals_mut().widgets.active.expansion = 0.0;- ui.visuals_mut().widgets.inactive.bg_stroke.width = stroke_width;- ui.visuals_mut().widgets.hovered.bg_stroke.width = stroke_width;- ui.visuals_mut().widgets.active.bg_stroke.width = stroke_width;-- let button = egui::Button::new(- egui::RichText::new(suggestion_text(suggestion))- .size(13.5)- .color(text_color),- )- .fill(fill)- .stroke(stroke)- .corner_radius(egui::CornerRadius::same(8))- .min_size(egui::vec2(0.0, 38.0));-- hover_text(ui.add(button), suggestion_hover_text(suggestion))- })- .inner-}--/// Renders the prototype's square icon-only controls without coupling their visual treatment to any-/// behavior beyond the response returned to the caller.-fn icon_button(ui: &mut egui::Ui, glyph: Glyph, text: &str) -> egui::Response {- let (rect, response) = ui.allocate_exact_size(egui::vec2(26.0, 26.0), egui::Sense::click());- let background = if response.hovered() {- egui::Color32::from_rgba_unmultiplied(0, 0, 0, 15)- } else {- egui::Color32::TRANSPARENT- };- let color = if response.hovered() {- hex(0x00, 0x00, 0x00)- } else {- hex(0x6b, 0x72, 0x80)- };-- ui.painter().rect_filled(rect, 6.0, background);- draw_glyph(ui, rect.shrink(6.0), glyph, color);-- hover_text(response, text)-}--/// Renders footer controls as no-op buttons so future actions can be wired without changing layout.-fn ghost_button(- ui: &mut egui::Ui,- glyph: Option<Glyph>,- label: &str,- text: impl Into<String>,-) -> egui::Response {- let label = if glyph.is_some() {- format!("+ {label}")- } else {- label.to_string()- };-- ui.scope(|ui| {- ui.spacing_mut().button_padding = egui::vec2(8.0, 6.0);- let response = ui.add(- egui::Button::new(- egui::RichText::new(label)- .size(12.0)- .color(hex(0x4b, 0x55, 0x63)),- )- .fill(egui::Color32::TRANSPARENT)- .stroke(egui::Stroke::NONE)- .corner_radius(egui::CornerRadius::same(6)),- );-- hover_text(response, text)- })- .inner-}--/// Applies tooltip styling that visually belongs with the suggestion popup instead of egui defaults.-fn hover_text(response: egui::Response, hover_text: impl Into<String>) -> egui::Response {- let hover_text = hover_text.into();-- let mut tooltip = egui::Tooltip::for_enabled(&response);- tooltip.popup = tooltip.popup.frame(- egui::Frame::new()- .fill(hex(0xff, 0xfd, 0xfa))- .stroke(egui::Stroke::new(- 1.0_f32,- egui::Color32::from_rgba_unmultiplied(0, 0, 0, 20),- ))- .corner_radius(egui::CornerRadius::same(8))- .inner_margin(egui::Margin::symmetric(8, 6))- .shadow(egui::Shadow {- offset: [0, 8],- blur: 18,- spread: 0,- color: egui::Color32::from_rgba_unmultiplied(20, 12, 2, 42),- }),- );- tooltip.show(|ui| {- ui.set_max_width(260.0);- ui.label(- egui::RichText::new(hover_text)- .size(12.0)- .color(hex(0x4b, 0x55, 0x63)),- );- });-- response-}--/// Draws the small SVG-inspired line icons from the prototype using egui painter primitives.-fn draw_glyph(ui: &egui::Ui, rect: egui::Rect, glyph: Glyph, color: egui::Color32) {- match glyph {- Glyph::Close => draw_close_icon(ui, rect, color),- Glyph::Settings => draw_settings_icon(ui, rect, color),- Glyph::Disable => draw_disable_icon(ui, rect, color),- Glyph::Plus => draw_plus_icon(ui, rect, color),- }-}--/// Draws the close glyph separately from button behavior so icon styling can change without touching-/// the popup's interaction contract.-fn draw_close_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.6_f32, color);-- ui.painter()- .line_segment([rect.left_top(), rect.right_bottom()], stroke);- ui.painter()- .line_segment([rect.right_top(), rect.left_bottom()], stroke);-}--fn draw_settings_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.5_f32, color);- let center = rect.center();- let radius = rect.width().min(rect.height()) * 0.32;-- ui.painter().circle_stroke(center, radius, stroke);- ui.painter().circle_stroke(center, radius * 0.38, stroke);-- for angle in [0.0_f32, 60.0, 120.0, 180.0, 240.0, 300.0] {- let radians = angle.to_radians();- let dir = egui::vec2(radians.cos(), radians.sin());- ui.painter().line_segment(- [center + dir * radius, center + dir * (radius + 2.8)],- stroke,- );- }-}--fn draw_disable_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.5_f32, color);-- ui.painter().circle_stroke(- rect.center(),- rect.width().min(rect.height()) * 0.45,- stroke,- );- ui.painter()- .line_segment([rect.left_bottom(), rect.right_top()], stroke);-}--fn draw_plus_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {- let stroke = egui::Stroke::new(1.6_f32, color);-- ui.painter().line_segment(- [- egui::pos2(rect.center().x, rect.top()),- egui::pos2(rect.center().x, rect.bottom()),- ],- stroke,- );- ui.painter().line_segment(- [- egui::pos2(rect.left(), rect.center().y),- egui::pos2(rect.right(), rect.center().y),- ],- stroke,- );-}--fn is_spelling_kind(lint_kind: LintKind) -> bool {- match lint_kind {- LintKind::Eggcorn | LintKind::Malapropism | LintKind::Spelling | LintKind::Typo => true,- LintKind::Agreement- | LintKind::BoundaryError- | LintKind::Capitalization- | LintKind::Enhancement- | LintKind::Formatting- | LintKind::Grammar- | LintKind::Miscellaneous- | LintKind::Nonstandard- | LintKind::Punctuation- | LintKind::Readability- | LintKind::Redundancy- | LintKind::Regionalism- | LintKind::Repetition- | LintKind::Style- | LintKind::Usage- | LintKind::WordChoice- | LintKind::WordOrder => false,- }-}--fn popup_style_for_lint_kind(lint_kind: LintKind) -> PopupStyle {- let color = lint_kind_color32(lint_kind);-- match lint_kind {- LintKind::Eggcorn | LintKind::Malapropism | LintKind::Spelling | LintKind::Typo => {- PopupStyle {- color,- background: hex(0xff, 0xee, 0xf2),- foreground: hex(0xbe, 0x12, 0x3c),- }- }- LintKind::Agreement- | LintKind::BoundaryError- | LintKind::Grammar- | LintKind::Repetition => PopupStyle {- color,- background: hex(0xff, 0xf7, 0xed),- foreground: hex(0xc2, 0x41, 0x0c),- },- LintKind::Capitalization => PopupStyle {- color,- background: hex(0xf3, 0xee, 0xff),- foreground: hex(0x5b, 0x21, 0xb6),- },- LintKind::Formatting | LintKind::Punctuation | LintKind::Readability => PopupStyle {- color,- background: hex(0xef, 0xf6, 0xff),- foreground: hex(0x1d, 0x4e, 0xd8),- },- LintKind::Enhancement- | LintKind::Miscellaneous- | LintKind::Nonstandard- | LintKind::Redundancy- | LintKind::Regionalism- | LintKind::Style- | LintKind::Usage- | LintKind::WordChoice- | LintKind::WordOrder => PopupStyle {- color,- background: hex(0xf3, 0xf4, 0xf6),- foreground: hex(0x37, 0x41, 0x51),- },- }-}--/// Converts Harper suggestion variants into button text.-fn suggestion_text(suggestion: &Suggestion) -> String {- match suggestion {- Suggestion::ReplaceWith(chars) | Suggestion::InsertAfter(chars) => chars.iter().collect(),- Suggestion::Remove => "Remove".to_owned(),- }-}--fn suggestion_hover_text(suggestion: &Suggestion) -> String {- match suggestion {- Suggestion::Remove => "Remove".to_owned(),- Suggestion::ReplaceWith(chars) | Suggestion::InsertAfter(chars) => {- format!("Replace with \"{}\"", chars.iter().collect::<String>())- }- }-}--/// Converts accessibility rectangles into egui rectangles so rendering and hit-testing use the same-/// screen-space geometry.-fn rect_bounds(rect: &Rect) -> egui::Rect {- egui::Rect::from_min_size(- egui::pos2(rect.x as f32, rect.y as f32),- egui::vec2(rect.width as f32, rect.height as f32),- )-}--/// Defines popup geometry ahead of rendering so the transparent overlay can enable or disable native-/// hit-testing based on our intended layout, not a previous frame's measured egui output.-fn popup_rect_for_lint(rect: &Rect) -> egui::Rect {- egui::Rect::from_min_size(- egui::pos2(- rect.x as f32,- rect.y as f32 + rect.height as f32 + CARD_OFFSET_Y,- ),- egui::vec2(CARD_WIDTH, CARD_HEIGHT),- )-}--/// Maps Harper lint kinds to egui colors at the drawing boundary so shared color data stays UI-toolkit-/// agnostic.-fn lint_color(lint: &Lint) -> egui::Color32 {- lint_kind_color32(lint.lint_kind)-}--fn lint_kind_color32(lint_kind: LintKind) -> egui::Color32 {- let color = lint_kind_color(lint_kind);-- egui::Color32::from_rgb(color.r, color.g, color.b)-}--fn hex(r: u8, g: u8, b: u8) -> egui::Color32 {- egui::Color32::from_rgb(r, g, b)-}--fn blend(from: egui::Color32, to: egui::Color32, to_weight: f32) -> egui::Color32 {- let from_weight = 1.0_f32 - to_weight;- let [fr, fg, fb, _] = from.to_array();- let [tr, tg, tb, _] = to.to_array();-- egui::Color32::from_rgb(- ((f32::from(fr) * from_weight) + (f32::from(tr) * to_weight)) as u8,- ((f32::from(fg) * from_weight) + (f32::from(tg) * to_weight)) as u8,- ((f32::from(fb) * from_weight) + (f32::from(tb) * to_weight)) as u8,- )-}diff --git a/harper-desktop/src-tauri/src/highlighter/render_state/draw_highlight.rs b/harper-desktop/src-tauri/src/highlighter/render_state/draw_highlight.rsnew file mode 100644index 000000000..3f6b4bb29--- /dev/null+++ b/harper-desktop/src-tauri/src/highlighter/render_state/draw_highlight.rs@@ -0,0 +1,32 @@+//! Draws lint highlights without owning popup selection or application state.++use harper_core::linting::Lint;++use super::{lint_kind_color32, rect_bounds};+use crate::rect::Rect;++/// Draws the always-visible lint marker without making the renderer responsible for popup state.+pub fn draw_highlight(ui: &mut egui::Ui, rect: &Rect, lint: &Lint) {+ let rect_bounds = rect_bounds(rect);+ let color = lint_color(lint);+ let [r, g, b, _] = color.to_array();+ let fill_color = egui::Color32::from_rgba_unmultiplied(r, g, b, 24);+ let underline_color = egui::Color32::from_rgba_unmultiplied(r, g, b, 255);+ let underline_height = rect_bounds.height().min(2.0);++ ui.painter().rect_filled(rect_bounds, 0.0, fill_color);+ ui.painter().rect_filled(+ egui::Rect::from_min_max(+ egui::pos2(rect_bounds.left(), rect_bounds.bottom() - underline_height),+ rect_bounds.right_bottom(),+ ),+ 0.0,+ underline_color,+ );+}++/// Maps Harper lint kinds to egui colors at the drawing boundary so shared color data stays UI-toolkit+/// agnostic.+fn lint_color(lint: &Lint) -> egui::Color32 {+ lint_kind_color32(lint.lint_kind)+}diff --git a/harper-desktop/src-tauri/src/highlighter/render_state/mod.rs b/harper-desktop/src-tauri/src/highlighter/render_state/mod.rsnew file mode 100644index 000000000..0bc49fc89--- /dev/null+++ b/harper-desktop/src-tauri/src/highlighter/render_state/mod.rs@@ -0,0 +1,296 @@+mod draw_highlight;+mod popup_layout;+mod render_lint_card;++use std::time::Instant;++use egui_commonmark::CommonMarkCache;+use harper_core::{Document, linting::LintKind};++use self::{+ draw_highlight::draw_highlight,+ popup_layout::{PopupLayout, approach},+ render_lint_card::{+ FIRST_ROW_OFFSET, LintCardAction, popup_layout_for_lint, render_lint_card, row_count,+ sidebar_target,+ },+};+use super::{AddToDictionary, DisableRule, IgnoreLint, OpenSettings};+use crate::{+ lint_kind_color::lint_kind_color,+ rect::{ActionableLint, Rect},+};++/// A lint marker, popup, or empty overlay region found during cursor hit-testing.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum HitTarget {+ Lint(usize),+ Popup,+ None,+}++/// Stores highlighter-specific drawing state and renders it into an egui frame.+///+/// `Window` owns the native window and GPU plumbing; `RenderState` owns the content we want to draw+/// into that plumbing. This keeps future highlight rectangles, styling, and animation state out of+/// the platform/rendering infrastructure.+pub struct RenderState {+ /// Last successful accessibility read, retained when a later read fails.+ last_lints: Option<Vec<ActionableLint>>,++ /// Index of the lint whose suggestion popup is currently visible.+ highlighted_lint: Option<usize>,++ /// Index of the suggestion row that the user hovered last in the visible popup.+ shown_suggestion: Option<usize>,++ /// The flyout card's drawn offset from the list card's top, in points.+ current_sidebar_position: f32,++ /// When `render` last ran, used to move the sidebar at a speed that follows real time.+ last_render: Option<Instant>,++ /// Cache for markdown-rendered lint messages so popup redraws do not repeatedly rebuild markdown+ /// resources from scratch.+ markdown_cache: CommonMarkCache,++ /// Called when the user dismisses a lint so app-level ignored-lint state can be updated.+ ignore_lint: IgnoreLint,++ /// Called when the user adds a spelling lint's source text to the local dictionary.+ add_to_dictionary: AddToDictionary,++ /// Called when the user disables the rule that produced the selected lint.+ disable_rule: DisableRule,++ open_settings: OpenSettings,+}++impl RenderState {+ /// Creates render state through `set_lints` so initial lint data gets the same stale-popup guard+ /// used by later accessibility refreshes.+ pub fn new(+ rects: Vec<ActionableLint>,+ ignore_lint: IgnoreLint,+ add_to_dictionary: AddToDictionary,+ disable_rule: DisableRule,+ open_settings: OpenSettings,+ ) -> Self {+ let mut state = Self {+ last_lints: None,+ highlighted_lint: None,+ shown_suggestion: None,+ current_sidebar_position: FIRST_ROW_OFFSET,+ last_render: None,+ markdown_cache: CommonMarkCache::default(),+ ignore_lint,+ add_to_dictionary,+ disable_rule,+ open_settings,+ };+ state.set_lints(rects);+ state+ }++ /// Saves successful accessibility reads while retaining the previous lints after a failed read.+ ///+ /// Closes the popup when its lint disappeared, and forgets the shown suggestion when the+ /// refreshed lint has fewer rows.+ pub fn set_lints(&mut self, lints: Vec<ActionableLint>) {+ self.last_lints = Some(lints);++ if self+ .highlighted_lint+ .is_some_and(|index| index >= self.lints().len())+ {+ self.close_popup();+ }++ let row_count = self+ .highlighted_lint+ .and_then(|index| self.lints().get(index))+ .map(|positioned_lint| row_count(&positioned_lint.lint));+ self.shown_suggestion = self+ .shown_suggestion+ .filter(|index| row_count.is_some_and(|row_count| *index < row_count));+ }++ fn lints(&self) -> &[ActionableLint] {+ self.last_lints.as_deref().unwrap_or_default()+ }++ /// Updates which lint owns the suggestion popup without exposing render-state internals.+ ///+ /// Window/input code decides what the user interacted with, while `RenderState` owns the popup+ /// selection. Filtering invalid indexes here keeps stale cursor state from selecting a lint that+ /// disappeared after the latest accessibility read.+ ///+ /// Like the Chrome extension, each new selection starts again from the first suggestion row.+ pub fn set_highlighted_lint(&mut self, highlighted_lint: Option<usize>) {+ self.highlighted_lint = highlighted_lint.filter(|index| *index < self.lints().len());+ self.shown_suggestion = None;+ self.current_sidebar_position = FIRST_ROW_OFFSET;+ }++ /// Centralizes the close behavior so the popup close button only has to clear the selected lint.+ pub fn close_popup(&mut self) {+ self.highlighted_lint = None;+ self.shown_suggestion = None;+ self.current_sidebar_position = FIRST_ROW_OFFSET;+ }++ /// Checks if a given position touches a hit target.+ pub fn hit_target_at_pos(&self, pos: egui::Pos2) -> HitTarget {+ if self+ .popup_layout()+ .is_some_and(|layout| layout.contains(pos))+ {+ return HitTarget::Popup;+ }++ self.lints()+ .iter()+ .position(|positioned_lint| {+ rect_bounds(&positioned_lint.rect.with_friendly_padding()).contains(pos)+ })+ .map_or(HitTarget::None, HitTarget::Lint)+ }++ /// Computes popup hit-test bounds from our layout contract instead of waiting for egui to report+ /// rendered bounds, which keeps hit-testing available before the next render pass completes.+ pub fn popup_layout(&self) -> Option<PopupLayout> {+ self.highlighted_lint+ .and_then(|index| self.lints().get(index))+ .map(|positioned_lint| {+ popup_layout_for_lint(+ &positioned_lint.rect,+ &positioned_lint.lint,+ self.current_sidebar_position,+ )+ })+ }++ /// Draws highlights and the active popup from the same state used by hit-testing so visible+ /// regions and clickable regions do not drift apart.+ ///+ /// Each call also moves the sidebar toward its target by the time since the previous call.+ pub fn render(&mut self, ui: &mut egui::Ui) {+ let now = Instant::now();+ let time_since_last_render = self+ .last_render+ .map_or(0.0, |last_render| (now - last_render).as_secs_f32());+ self.last_render = Some(now);++ if let Some(positioned_lint) = self+ .highlighted_lint+ .and_then(|index| self.lints().get(index))+ {+ let target = sidebar_target(&positioned_lint.lint, self.shown_suggestion);+ self.current_sidebar_position = approach(+ self.current_sidebar_position,+ target,+ time_since_last_render,+ );+ }++ for positioned_lint in self.lints() {+ draw_highlight(ui, &positioned_lint.rect, &positioned_lint.lint);+ }++ if let Some(index) = self.highlighted_lint+ && let Some(positioned_lint) = self.lints().get(index)+ {+ let rect = positioned_lint.rect;+ let lint = positioned_lint.lint.clone();+ let source_text = positioned_lint.source_text.clone();++ match render_lint_card(+ ui,+ &rect,+ &lint,+ &source_text,+ self.shown_suggestion,+ self.current_sidebar_position,+ &mut self.markdown_cache,+ ) {+ Some(LintCardAction::Close) => self.close_popup(),+ Some(LintCardAction::OpenSettings) => {+ (self.open_settings)();+ self.close_popup();+ }+ Some(LintCardAction::HoverSuggestion(suggestion)) => {+ self.shown_suggestion = Some(suggestion);+ }+ Some(LintCardAction::ApplySuggestion(suggestion)) => {+ if let Some(actionable_lint) = self+ .last_lints+ .as_mut()+ .and_then(|lints| lints.get_mut(index))+ {+ actionable_lint.apply_suggestion(suggestion);+ }++ self.close_popup();+ }+ Some(LintCardAction::IgnoreLint) => {+ if let Some((lint, source_text)) =+ self.lints().get(index).map(|actionable_lint| {+ (+ actionable_lint.lint.clone(),+ actionable_lint.source_text.clone(),+ )+ })+ {+ let document = Document::new_markdown_default_curated(&source_text);+ (self.ignore_lint)(&lint, &document);+ }++ self.close_popup();+ }+ Some(LintCardAction::AddToDictionary) => {+ if let Some((lint, source_text)) =+ self.lints().get(index).map(|actionable_lint| {+ (+ actionable_lint.lint.clone(),+ actionable_lint.source_text.clone(),+ )+ })+ {+ let document = Document::new_markdown_default_curated(&source_text);+ let word = lint.get_str(document.get_source());+ (self.add_to_dictionary)(&word);+ }++ self.close_popup();+ }+ Some(LintCardAction::DisableRule) => {+ if let Some(rule_name) = self+ .lints()+ .get(index)+ .map(|actionable_lint| actionable_lint.rule_name.clone())+ {+ (self.disable_rule)(&rule_name);+ }++ self.close_popup();+ }+ None => {}+ }+ }+ }+}++/// Converts accessibility rectangles into egui rectangles so rendering and hit-testing use the same+/// screen-space geometry.+fn rect_bounds(rect: &Rect) -> egui::Rect {+ egui::Rect::from_min_size(+ egui::pos2(rect.x as f32, rect.y as f32),+ egui::vec2(rect.width as f32, rect.height as f32),+ )+}++fn lint_kind_color32(lint_kind: LintKind) -> egui::Color32 {+ let color = lint_kind_color(lint_kind);++ egui::Color32::from_rgb(color.r, color.g, color.b)+}diff --git a/harper-desktop/src-tauri/src/highlighter/render_state/popup_layout.rs b/harper-desktop/src-tauri/src/highlighter/render_state/popup_layout.rsnew file mode 100644index 000000000..fef95fc4a--- /dev/null+++ b/harper-desktop/src-tauri/src/highlighter/render_state/popup_layout.rs@@ -0,0 +1,276 @@+//! Places the suggestion list card and the lint flyout card on screen.+//!+//! The geometry is a pure function of its inputs, so drawing and hit-testing compute the same+//! rectangles without measuring a rendered frame.++use crate::rect::Rect;++/// Space between the list card and the flyout card.+pub const PANEL_GAP: f32 = 6.0;+/// Minimum space between either card and the viewport edge.+pub const VIEWPORT_MARGIN: f32 = 8.0;+/// Space between the lint highlight and the list card.+pub const ANCHOR_GAP: f32 = 3.0;++/// A viewport with no edges, so the cards are never clamped, flipped, or stacked.+///+/// The highlighter does not yet know which monitor a popup is on. Until it does, both drawing and+/// hit-testing use this value, so the later change only has to replace it in one place.+pub const UNBOUNDED_VIEWPORT: egui::Rect = egui::Rect::EVERYTHING;++/// The time constant, in seconds, of the sidebar's movement toward its target.+///+/// After this time, the sidebar has moved about 63% of the distance. After three times this value,+/// it has moved about 95%.+pub const SIDEBAR_SMOOTHING: f32 = 0.05;++/// The distance, in points, below which the sidebar jumps to its target.+///+/// Without this, the exponential movement would continue below a visible distance forever.+pub const SIDEBAR_SNAP_DISTANCE: f32 = 0.5;++/// The screen-space rectangles of the two popup cards.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct PopupLayout {+ /// The card with the suggestion rows and the footer.+ pub list: egui::Rect,+ /// The card with the lint kind, the explanation, and the lint actions.+ pub flyout: egui::Rect,+}++impl PopupLayout {+ /// Checks if a position is on either card.+ ///+ /// The gap between the cards is not part of the popup, so clicks there go to the editor.+ pub fn contains(&self, pos: egui::Pos2) -> bool {+ self.list.contains(pos) || self.flyout.contains(pos)+ }+}++/// Computes the card positions with the algorithm from `popupPosition` in the Chrome extension's+/// `packages/lint-framework/src/lint/SuggestionBox.ts`.+///+/// - The list card goes below the anchor, or above it when there is not sufficient space below.+/// - The flyout card goes to the right of the list, or to the left when there is not sufficient+/// space on the right.+/// - When the viewport is too narrow for the two cards side by side, the flyout goes below the list.+/// - Both cards stay at least [`VIEWPORT_MARGIN`] from the viewport edges.+///+/// One difference from the Chrome extension: when the cards are side by side, the flyout's top+/// moves down by `sidebar_offset`, the distance from the list card's top. The caller animates this+/// value toward the suggestion row that the user hovered last. The flyout stays clamped to the+/// viewport while it moves.+pub fn popup_layout(+ anchor: &Rect,+ viewport: egui::Rect,+ list: egui::Vec2,+ flyout: egui::Vec2,+ sidebar_offset: f32,+) -> PopupLayout {+ let margin = VIEWPORT_MARGIN;+ let anchor_top = anchor.y as f32;+ let anchor_bottom = anchor_top + anchor.height as f32;++ let stacked = list.x + PANEL_GAP + flyout.x + margin * 2.0 > viewport.width();+ let height = if stacked {+ list.y + PANEL_GAP + flyout.y+ } else {+ list.y+ };++ let below = anchor_bottom + ANCHOR_GAP;+ let flipped = below + height + margin > viewport.max.y;+ let top = clamp(+ if flipped {+ anchor_top - height - ANCHOR_GAP+ } else {+ below+ },+ viewport.min.y + margin,+ viewport.max.y - height - margin,+ );++ let left = clamp(+ anchor.x as f32,+ viewport.min.x + margin,+ viewport.max.x - list.x - margin,+ );+ let opens_left = left + list.x + PANEL_GAP + flyout.x + margin > viewport.max.x;+ let left = if opens_left && !stacked {+ clamp(+ left,+ viewport.min.x + margin + flyout.x + PANEL_GAP,+ viewport.max.x - list.x - margin,+ )+ } else {+ left+ };++ let flyout_left = if stacked {+ left+ } else if opens_left {+ left - flyout.x - PANEL_GAP+ } else {+ left + list.x + PANEL_GAP+ };+ let flyout_top = if stacked {+ top + list.y + PANEL_GAP+ } else {+ clamp(+ top + sidebar_offset,+ viewport.min.y + margin,+ viewport.max.y - flyout.y - margin,+ )+ };++ PopupLayout {+ list: egui::Rect::from_min_size(egui::pos2(left, top), list),+ flyout: egui::Rect::from_min_size(egui::pos2(flyout_left, flyout_top), flyout),+ }+}++/// Moves `current` toward `target` by an exponential lerp over `dt` seconds.+///+/// The lerp factor is `1 - exp(-dt / SIDEBAR_SMOOTHING)`. Because two steps of `dt / 2` give the same+/// result as one step of `dt`, the speed does not depend on the frame rate or on how many windows+/// call this in each frame. The result never goes past `target`, and it snaps to `target` within+/// [`SIDEBAR_SNAP_DISTANCE`].+pub fn approach(current: f32, target: f32, dt: f32) -> f32 {+ let factor = 1.0 - (-dt.max(0.0) / SIDEBAR_SMOOTHING).exp();+ let next = current + (target - current) * factor;++ if (target - next).abs() < SIDEBAR_SNAP_DISTANCE {+ target+ } else {+ next+ }+}++/// Clamps like the Chrome extension: when `max < min`, the result is `min`.+fn clamp(value: f32, min: f32, max: f32) -> f32 {+ value.min(max.max(min)).max(min)+}++#[cfg(test)]+mod tests {+ use super::*;++ const LIST: egui::Vec2 = egui::vec2(212.0, 100.0);+ const FLYOUT: egui::Vec2 = egui::vec2(192.0, 150.0);++ fn viewport(width: f32, height: f32) -> egui::Rect {+ egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height))+ }++ fn anchor() -> Rect {+ Rect::new(50.0, 40.0, 30.0, 12.0)+ }++ #[test]+ fn opens_right_below_anchor() {+ let layout = popup_layout(&anchor(), viewport(1000.0, 1000.0), LIST, FLYOUT, 0.0);++ assert_eq!(layout.list.min, egui::pos2(50.0, 40.0 + 12.0 + ANCHOR_GAP));+ assert_eq!(layout.list.size(), LIST);+ assert_eq!(+ layout.flyout.min,+ egui::pos2(50.0 + LIST.x + PANEL_GAP, layout.list.top())+ );+ assert_eq!(layout.flyout.size(), FLYOUT);+ }++ #[test]+ fn flyout_follows_sidebar_offset() {+ for sidebar_offset in [0.0, 30.0, 95.0] {+ let layout = popup_layout(+ &anchor(),+ viewport(1000.0, 1000.0),+ LIST,+ FLYOUT,+ sidebar_offset,+ );++ assert_eq!(layout.flyout.top(), layout.list.top() + sidebar_offset);+ }+ }++ #[test]+ fn unbounded_viewport_opens_right_below_anchor() {+ let bounded = popup_layout(&anchor(), viewport(1000.0, 1000.0), LIST, FLYOUT, 30.0);+ let unbounded = popup_layout(&anchor(), UNBOUNDED_VIEWPORT, LIST, FLYOUT, 30.0);++ assert_eq!(bounded, unbounded);+ }++ #[test]+ fn unbounded_viewport_does_not_clamp_far_anchors() {+ let anchor = Rect::new(-5000.0, 90000.0, 30.0, 12.0);+ let layout = popup_layout(&anchor, UNBOUNDED_VIEWPORT, LIST, FLYOUT, 0.0);++ assert_eq!(layout.list.min, egui::pos2(-5000.0, 90012.0 + ANCHOR_GAP));+ }++ #[test]+ fn opens_left_near_right_edge() {+ let anchor = Rect::new(700.0, 40.0, 30.0, 12.0);+ let layout = popup_layout(&anchor, viewport(1000.0, 1000.0), LIST, FLYOUT, 0.0);++ assert_eq!(layout.list.left(), 700.0);+ assert_eq!(layout.flyout.right(), 700.0 - PANEL_GAP);+ }++ #[test]+ fn opening_left_shifts_list_to_fit_flyout() {+ let layout = popup_layout(&anchor(), viewport(450.0, 1000.0), LIST, FLYOUT, 0.0);++ assert_eq!(layout.flyout.left(), VIEWPORT_MARGIN);+ assert_eq!(layout.flyout.right(), layout.list.left() - PANEL_GAP);+ }++ #[test]+ fn flips_above_anchor_near_bottom() {+ let anchor = Rect::new(50.0, 950.0, 30.0, 12.0);+ let layout = popup_layout(&anchor, viewport(1000.0, 1000.0), LIST, FLYOUT, 0.0);++ assert_eq!(layout.list.bottom(), 950.0 - ANCHOR_GAP);+ }++ #[test]+ fn flyout_clamps_to_viewport_bottom() {+ let layout = popup_layout(&anchor(), viewport(1000.0, 250.0), LIST, FLYOUT, 90.0);++ assert_eq!(layout.flyout.bottom(), 250.0 - VIEWPORT_MARGIN);+ }++ #[test]+ fn stacks_on_narrow_viewport() {+ let layout = popup_layout(&anchor(), viewport(400.0, 1000.0), LIST, FLYOUT, 60.0);++ assert_eq!(layout.flyout.left(), layout.list.left());+ assert_eq!(layout.flyout.top(), layout.list.bottom() + PANEL_GAP);+ }++ #[test]+ fn clamps_list_to_viewport_margins() {+ let anchor = Rect::new(-20.0, -40.0, 30.0, 12.0);+ let layout = popup_layout(&anchor, viewport(1000.0, 1000.0), LIST, FLYOUT, 0.0);++ assert_eq!(+ layout.list.min,+ egui::pos2(VIEWPORT_MARGIN, VIEWPORT_MARGIN)+ );+ }++ #[test]+ fn contains_cards_but_not_gap() {+ let layout = popup_layout(&anchor(), viewport(1000.0, 1000.0), LIST, FLYOUT, 0.0);+ let gap = egui::pos2(+ layout.list.right() + PANEL_GAP / 2.0,+ layout.list.center().y,+ );++ assert!(layout.contains(layout.list.center()));+ assert!(layout.contains(layout.flyout.center()));+ assert!(!layout.contains(gap));+ }+}diff --git a/harper-desktop/src-tauri/src/highlighter/render_state/render_lint_card.rs b/harper-desktop/src-tauri/src/highlighter/render_state/render_lint_card.rsnew file mode 100644index 000000000..abcad467f--- /dev/null+++ b/harper-desktop/src-tauri/src/highlighter/render_state/render_lint_card.rs@@ -0,0 +1,895 @@+//! Renders the lint card and defines its shared drawing and hit-test geometry.++use std::hash::Hash;++use egui_commonmark::{CommonMarkCache, CommonMarkViewer};+use harper_core::linting::{Lint, LintKind, Suggestion};++use super::lint_kind_color32;+use super::popup_layout::{PopupLayout, UNBOUNDED_VIEWPORT, popup_layout};+use crate::rect::Rect;++const LIST_WIDTH: f32 = 210.0;+const FLYOUT_WIDTH: f32 = 190.0;+const DIVIDER_WIDTH: f32 = 1.0;+const BORDER_WIDTH: f32 = 1.0;+const LIST_CARD_WIDTH: f32 = LIST_WIDTH + 2.0 * BORDER_WIDTH;+const FLYOUT_CARD_WIDTH: f32 = FLYOUT_WIDTH + 2.0 * BORDER_WIDTH;+/// The maximum height of either card. Content that does not fit scrolls.+const CARD_HEIGHT: f32 = 400.0;+const CARD_CORNER_RADIUS: u8 = 8;+const ROW_HEIGHT: f32 = 30.0;+const LIST_PADDING_Y: f32 = 4.0;+const FOOTER_ROW_HEIGHT: f32 = 28.0;+/// The space above the footer, the footer divider, the space below it, and the footer row.+const LIST_FOOTER_HEIGHT: f32 = 4.0 + DIVIDER_WIDTH + 4.0 + FOOTER_ROW_HEIGHT;+/// The distance from the list card's top to the first suggestion row's top.+///+/// This is also the sidebar's starting position, so a new popup opens with the sidebar aligned to+/// the first row and does not slide.+pub const FIRST_ROW_OFFSET: f32 = BORDER_WIDTH + LIST_PADDING_Y;+const KIND_HEADER_HEIGHT: f32 = 34.0;+const DISABLE_ROW_HEIGHT: f32 = 33.0;+const BUTTON_MIN_HEIGHT: f32 = 24.0;++const POPUP_BACKGROUND: egui::Color32 = egui::Color32::from_rgb(0xff, 0xff, 0xff);+const POPUP_BORDER: egui::Color32 = egui::Color32::from_rgb(0xd0, 0xd7, 0xde);+const POPUP_SHADOW: egui::Color32 = egui::Color32::from_rgba_unmultiplied_const(140, 149, 159, 77);+const DIVIDER_COLOR: egui::Color32 = egui::Color32::from_rgb(0xea, 0xee, 0xf2);+const HOVER_BACKGROUND: egui::Color32 = egui::Color32::from_black_alpha(11);+const TEXT_COLOR: egui::Color32 = egui::Color32::from_rgb(0x1f, 0x23, 0x28);+const MUTED_TEXT_COLOR: egui::Color32 = egui::Color32::from_rgb(0x57, 0x60, 0x6a);+const SUBTLE_TEXT_COLOR: egui::Color32 = egui::Color32::from_rgb(0x8b, 0x94, 0x9e);+const DISMISS_BACKGROUND: egui::Color32 = egui::Color32::from_rgb(0xe5, 0xe5, 0xe5);+const BUTTON_BACKGROUND: egui::Color32 = egui::Color32::from_rgb(0xef, 0xef, 0xef);+const BUTTON_TEXT_COLOR: egui::Color32 = egui::Color32::from_rgb(0x00, 0x00, 0x00);++/// An action selected in the lint card, returned for `RenderState` to apply.+///+/// The renderer reports intent without updating application state or invoking callbacks.+pub enum LintCardAction {+ Close,+ OpenSettings,+ /// The pointer is on the suggestion row at this index. The flyout card aligns with that row.+ ///+ /// When the lint has no suggestions, index `0` is the "No replacements" row.+ HoverSuggestion(usize),+ ApplySuggestion(Suggestion),+ IgnoreLint,+ AddToDictionary,+ DisableRule,+}++#[derive(Debug, Clone, Copy)]+enum Glyph {+ Sliders,+ BookDown,+}++/// The visible content of a [`flyout_button`].+#[derive(Debug, Clone, Copy)]+enum ButtonContent<'a> {+ Text(&'a str),+ Glyph(Glyph),+}++/// Renders the suggestion popup and returns the action the user picked, if any.+///+/// The layout copies the Chrome extension's suggestion popup: the suggestion list and the lint+/// explanation are two separate floating cards. [`popup_layout_for_lint`] places them, so+/// hit-testing and drawing agree without measuring the popup.+///+/// `sidebar_position` is the flyout card's current offset from the list card's top. The caller+/// animates it toward [`sidebar_target`]. `shown_suggestion` only selects the highlighted row.+pub fn render_lint_card(+ ui: &mut egui::Ui,+ rect: &Rect,+ lint: &Lint,+ source_text: &str,+ shown_suggestion: Option<usize>,+ sidebar_position: f32,+ markdown_cache: &mut CommonMarkCache,+) -> Option<LintCardAction> {+ let layout = popup_layout_for_lint(rect, lint, sidebar_position);+ let problem_text = problem_text(lint, source_text);+ let span = (lint.span.start, lint.span.end);++ let list_action = show_card(ui.ctx(), "harper-lint-card-list", span, layout.list, |ui| {+ let mut action = None;+ render_suggestion_list(+ ui,+ lint,+ &problem_text,+ shown_suggestion.unwrap_or(0),+ &mut action,+ );+ action+ });++ let flyout_action = show_card(+ ui.ctx(),+ "harper-lint-card-flyout",+ span,+ layout.flyout,+ |ui| {+ let mut action = None;+ render_flyout(ui, lint, markdown_cache, &mut action);+ action+ },+ );++ list_action.or(flyout_action)+}++/// Renders one floating card at `rect.min`, with content that scrolls when it is taller than+/// `rect`.+///+/// `rect` is the card's maximum bounds. The card shrinks to fit shorter content, but its available+/// space is reset each frame so a previous short card cannot constrain a longer message.+fn show_card<R>(+ ctx: &egui::Context,+ name: &'static str,+ id_salt: impl Hash,+ rect: egui::Rect,+ add_contents: impl FnOnce(&mut egui::Ui) -> R,+) -> R {+ egui::Area::new(egui::Id::new(name))+ .order(egui::Order::Foreground)+ .fixed_pos(rect.min)+ .show(ctx, |ui| {+ ui.set_max_size(rect.size());+ card_frame()+ .show(ui, |ui| {+ ui.spacing_mut().item_spacing = egui::Vec2::ZERO;++ egui::ScrollArea::vertical()+ .id_salt((name, id_salt))+ .max_height(rect.height() - 2.0 * BORDER_WIDTH)+ .show(ui, |ui| {+ ui.set_width(rect.width() - 2.0 * BORDER_WIDTH);+ add_contents(ui)+ })+ .inner+ })+ .inner+ })+ .inner+}++/// The background, border, rounded corners, and shadow shared by both popup cards and tooltips,+/// like the Chrome extension's `.harper-container` and `.harper-flyout`.+fn card_frame() -> egui::Frame {+ egui::Frame::new()+ .fill(POPUP_BACKGROUND)+ .stroke(egui::Stroke::new(BORDER_WIDTH, POPUP_BORDER))+ .corner_radius(egui::CornerRadius::same(CARD_CORNER_RADIUS))+ .shadow(egui::Shadow {+ offset: [0, 4],+ blur: 12,+ spread: 0,+ color: POPUP_SHADOW,+ })+}++/// Renders the list card: one row for each suggestion, then the footer.+///+/// Clicking a row applies its suggestion. Hovering a row reports its index, so the flyout card can+/// align with it. When the lint has no suggestions, one "No replacements" row takes their place,+/// as in the Chrome extension. Clicking that row does nothing.+///+/// The row at `selected` keeps the hover background, like the Chrome extension's+/// `.harper-selected` row.+fn render_suggestion_list(+ ui: &mut egui::Ui,+ lint: &Lint,+ problem_text: &str,+ selected: usize,+ action: &mut Option<LintCardAction>,+) {+ ui.add_space(LIST_PADDING_Y);++ if lint.suggestions.is_empty()+ && suggestion_row(+ ui,+ lint.lint_kind,+ "No replacements",+ format!("No replacements for \"{problem_text}\""),+ selected == 0,+ )+ .hovered()+ {+ *action = Some(LintCardAction::HoverSuggestion(0));+ }++ for (index, suggestion) in lint.suggestions.iter().enumerate() {+ let row = suggestion_row(+ ui,+ lint.lint_kind,+ &suggestion_text(suggestion),+ suggestion_hover_text(suggestion, problem_text),+ selected == index,+ );++ if row.clicked() {+ *action = Some(LintCardAction::ApplySuggestion(suggestion.clone()));+ } else if row.hovered() {+ *action = Some(LintCardAction::HoverSuggestion(index));+ }+ }++ render_list_footer(ui, action);+ ui.add_space(LIST_PADDING_Y);+}++/// Renders one suggestion row: a swatch in the lint color, the label, and a chevron.+///+/// The row's rectangle is allocated before anything is painted, so the hover background can come+/// from this frame's response. A `selected` row gets the same background without the hover.+fn suggestion_row(+ ui: &mut egui::Ui,+ lint_kind: LintKind,+ label: &str,+ hover: impl Into<String>,+ selected: bool,+) -> egui::Response {+ let (rect, response) =+ ui.allocate_exact_size(egui::vec2(LIST_WIDTH, ROW_HEIGHT), egui::Sense::click());+ let painter = ui.painter();++ if selected || response.hovered() {+ painter.rect_filled(rect, 0.0, HOVER_BACKGROUND);+ }++ let swatch = egui::Rect::from_min_size(+ egui::pos2(rect.left() + 10.0, rect.center().y - 8.0),+ egui::vec2(3.0, 16.0),+ );+ painter.rect_filled(swatch, 2.0, lint_kind_color32(lint_kind));++ let chevron = single_line_galley(ui, "›", 12.0, f32::INFINITY);+ let chevron_left = rect.right() - 8.0 - chevron.size().x;+ let label_left = swatch.right() + 8.0;+ let label = single_line_galley(ui, label, 13.0, chevron_left - 8.0 - label_left);++ paint_text(painter, label_left, rect.center().y, label, TEXT_COLOR);+ paint_text(+ painter,+ chevron_left,+ rect.center().y,+ chevron,+ SUBTLE_TEXT_COLOR,+ );++ hover_text(+ response.on_hover_cursor(egui::CursorIcon::PointingHand),+ hover,+ )+}++/// Renders the list footer: a "Go to Harper settings" row and the close button.+///+/// The close button sits over the footer's right edge, where+/// the footer leaves 26 points of padding for it.+fn render_list_footer(ui: &mut egui::Ui, action: &mut Option<LintCardAction>) {+ ui.add_space(4.0);++ let (rect, _) = ui.allocate_exact_size(+ egui::vec2(LIST_WIDTH, DIVIDER_WIDTH + 4.0 + FOOTER_ROW_HEIGHT),+ egui::Sense::hover(),+ );+ ui.painter().hline(+ rect.x_range(),+ rect.top() + DIVIDER_WIDTH / 2.0,+ egui::Stroke::new(DIVIDER_WIDTH, DIVIDER_COLOR),+ );++ let settings_rect = egui::Rect::from_min_max(+ egui::pos2(rect.left(), rect.bottom() - FOOTER_ROW_HEIGHT),+ egui::pos2(rect.right() - 26.0, rect.bottom()),+ );+ let settings = ui.interact(+ settings_rect,+ ui.id().with("harper-lint-card-settings"),+ egui::Sense::click(),+ );++ if settings.hovered() {+ ui.painter()+ .rect_filled(settings_rect, 0.0, HOVER_BACKGROUND);+ }++ let icon_rect = egui::Rect::from_min_size(+ egui::pos2(settings_rect.left() + 10.0, settings_rect.center().y - 7.0),+ egui::vec2(14.0, 14.0),+ );+ draw_glyph(ui, icon_rect, Glyph::Sliders, MUTED_TEXT_COLOR);++ let label_left = icon_rect.right() + 6.0;+ let label = single_line_galley(+ ui,+ "Go to Harper settings",+ 12.0,+ settings_rect.right() - 10.0 - label_left,+ );+ paint_text(+ ui.painter(),+ label_left,+ settings_rect.center().y,+ label,+ MUTED_TEXT_COLOR,+ );++ if hover_text(+ settings.on_hover_cursor(egui::CursorIcon::PointingHand),+ "Click to go to Harper settings",+ )+ .clicked()+ {+ *action = Some(LintCardAction::OpenSettings);+ }++ let close_label = single_line_galley(ui, "×", 20.0, f32::INFINITY);+ let close_size = egui::vec2(close_label.size().x + 8.0, 20.0);+ let close_rect = egui::Rect::from_min_size(+ egui::pos2(+ rect.right() - 4.0 - close_size.x,+ rect.top() + DIVIDER_WIDTH + 6.0,+ ),+ close_size,+ );+ let close = ui.interact(+ close_rect,+ ui.id().with("harper-lint-card-close"),+ egui::Sense::click(),+ );+ let close_color = if close.hovered() {+ TEXT_COLOR+ } else {+ MUTED_TEXT_COLOR+ };+ paint_text(+ ui.painter(),+ close_rect.center().x - close_label.size().x / 2.0,+ close_rect.center().y,+ close_label,+ close_color,+ );++ if hover_text(+ close.on_hover_cursor(egui::CursorIcon::PointingHand),+ "Close",+ )+ .clicked()+ {+ *action = Some(LintCardAction::Close);+ }+}++/// Renders the flyout card: the lint kind, the explanation, and the actions for the whole lint.+///+/// The content does not depend on which suggestion row is hovered. Only the card's position does,+/// and [`popup_layout_for_lint`] controls that.+fn render_flyout(+ ui: &mut egui::Ui,+ lint: &Lint,+ markdown_cache: &mut CommonMarkCache,+ action: &mut Option<LintCardAction>,+) {+ render_kind_header(ui, lint.lint_kind);++ egui::Frame::new()+ .inner_margin(egui::Margin::symmetric(10, 8))+ .show(ui, |ui| {+ ui.set_width(FLYOUT_WIDTH - 20.0);+ render_lint_message(ui, markdown_cache, &lint.message, lint.lint_kind);+ });++ egui::Frame::new()+ .inner_margin(egui::Margin {+ left: 10,+ right: 10,+ top: 0,+ bottom: 8,+ })+ .show(ui, |ui| {+ ui.set_width(FLYOUT_WIDTH - 20.0);+ ui.horizontal_wrapped(|ui| {+ ui.spacing_mut().item_spacing = egui::vec2(6.0, 6.0);++ if flyout_button(+ ui,+ ButtonContent::Text("Dismiss"),+ DISMISS_BACKGROUND,+ "Ignore this lint",+ )+ .clicked()+ {+ *action = Some(LintCardAction::IgnoreLint);+ }++ if is_spelling_kind(lint.lint_kind)+ && flyout_button(+ ui,+ ButtonContent::Glyph(Glyph::BookDown),+ BUTTON_BACKGROUND,+ "Add word to user dictionary",+ )+ .clicked()+ {+ *action = Some(LintCardAction::AddToDictionary);+ }+ });+ });++ if disable_rule_row(ui).clicked() {+ *action = Some(LintCardAction::DisableRule);+ }+}++/// Renders the lint kind above the explanation, underlined in the lint color.+fn render_kind_header(ui: &mut egui::Ui, lint_kind: LintKind) {+ const BORDER_HEIGHT: f32 = 2.0;++ let (rect, _) = ui.allocate_exact_size(+ egui::vec2(FLYOUT_WIDTH, KIND_HEADER_HEIGHT),+ egui::Sense::hover(),+ );+ let border_top = rect.bottom() - BORDER_HEIGHT;+ let label = single_line_galley(ui, &lint_kind.to_string(), 12.0, FLYOUT_WIDTH - 20.0);++ paint_text(+ ui.painter(),+ rect.left() + 10.0,+ (rect.top() + border_top) / 2.0,+ label,+ TEXT_COLOR,+ );+ ui.painter().rect_filled(+ egui::Rect::from_min_max(egui::pos2(rect.left(), border_top), rect.right_bottom()),+ 0.0,+ lint_kind_color32(lint_kind),+ );+}++/// Renders the full-width row that disables the rule that produced the lint.+fn disable_rule_row(ui: &mut egui::Ui) -> egui::Response {+ let (rect, response) = ui.allocate_exact_size(+ egui::vec2(FLYOUT_WIDTH, DISABLE_ROW_HEIGHT),+ egui::Sense::click(),+ );++ if response.hovered() {+ // This row can touch the card's bottom corners, so keep the hover inside the curves.+ let corner_radius = egui::CornerRadius {+ sw: CARD_CORNER_RADIUS - 1,+ se: CARD_CORNER_RADIUS - 1,+ ..Default::default()+ };+ ui.painter()+ .rect_filled(rect, corner_radius, HOVER_BACKGROUND);+ }++ ui.painter().hline(+ rect.x_range(),+ rect.top() + DIVIDER_WIDTH / 2.0,+ egui::Stroke::new(DIVIDER_WIDTH, DIVIDER_COLOR),+ );++ let color = if response.hovered() {+ MUTED_TEXT_COLOR+ } else {+ SUBTLE_TEXT_COLOR+ };+ let label = single_line_galley(ui, "Disable this rule", 11.0, FLYOUT_WIDTH - 20.0);+ paint_text(+ ui.painter(),+ rect.left() + 10.0,+ (rect.top() + DIVIDER_WIDTH + rect.bottom()) / 2.0,+ label,+ color,+ );++ hover_text(+ response.on_hover_cursor(egui::CursorIcon::PointingHand),+ "Disable the rule that produced this lint",+ )+}++/// Renders a compact button in the style of the Chrome extension's `.harper-btn`.+///+/// The fill darkens on hover, like the CSS `brightness(0.92)` filter.+fn flyout_button(+ ui: &mut egui::Ui,+ content: ButtonContent,+ fill: egui::Color32,+ hover: impl Into<String>,+) -> egui::Response {+ const GLYPH_SIZE: f32 = 18.0;++ let galley = match content {+ ButtonContent::Text(text) => Some(single_line_galley(ui, text, 12.0, f32::INFINITY)),+ ButtonContent::Glyph(_) => None,+ };+ let content_size = galley+ .as_ref()+ .map_or(egui::vec2(GLYPH_SIZE, GLYPH_SIZE), |galley| galley.size());+ let size = egui::vec2(+ content_size.x + 16.0,+ (content_size.y + 6.0).max(BUTTON_MIN_HEIGHT),+ );++ let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click());+ let fill = if response.hovered() {+ brightness(fill, 0.92)+ } else {+ fill+ };+ ui.painter().rect_filled(rect, 6.0, fill);++ let content_rect = egui::Rect::from_center_size(rect.center(), content_size);+ match (content, galley) {+ (ButtonContent::Glyph(glyph), _) => {+ draw_glyph(ui, content_rect, glyph, BUTTON_TEXT_COLOR);+ }+ (ButtonContent::Text(_), Some(galley)) => {+ ui.painter()+ .galley(content_rect.min, galley, BUTTON_TEXT_COLOR);+ }+ (ButtonContent::Text(_), None) => {}+ }++ hover_text(+ response.on_hover_cursor(egui::CursorIcon::PointingHand),+ hover,+ )+}++/// Renders Harper's markdown-formatted lint message in the popup instead of showing raw markdown+/// markers to the user.+///+/// Inline code gets a background tinted with the lint color. The Chrome extension underlines it+/// instead, but `egui_commonmark` cannot underline inline code.+fn render_lint_message(+ ui: &mut egui::Ui,+ cache: &mut CommonMarkCache,+ message: &str,+ lint_kind: LintKind,+) {+ ui.scope(|ui| {+ let [r, g, b, _] = lint_kind_color32(lint_kind).to_array();+ let style = ui.style_mut();+ style+ .text_styles+ .insert(egui::TextStyle::Body, egui::FontId::proportional(12.0));+ style+ .text_styles+ .insert(egui::TextStyle::Monospace, egui::FontId::monospace(12.0));+ style.spacing.item_spacing = egui::vec2(0.0, 3.0);+ style.visuals.override_text_color = Some(MUTED_TEXT_COLOR);+ style.visuals.code_bg_color = egui::Color32::from_rgba_unmultiplied(r, g, b, 40);++ CommonMarkViewer::new()+ .default_width(Some(ui.available_width() as usize))+ .show(ui, cache, message);+ });+}++/// Applies tooltip styling that visually belongs with the suggestion popup instead of egui defaults.+fn hover_text(response: egui::Response, hover_text: impl Into<String>) -> egui::Response {+ let hover_text = hover_text.into();++ let mut tooltip = egui::Tooltip::for_enabled(&response);+ tooltip.popup = tooltip+ .popup+ .frame(card_frame().inner_margin(egui::Margin::symmetric(8, 6)));+ tooltip.show(|ui| {+ ui.set_max_width(260.0);+ ui.label(+ egui::RichText::new(hover_text)+ .size(12.0)+ .color(MUTED_TEXT_COLOR),+ );+ });++ response+}++/// Lays out one line of text, cut off with an ellipsis when it is wider than `max_width`.+///+/// The galley uses a placeholder color, so [`paint_text`] can choose the color when it paints.+fn single_line_galley(+ ui: &egui::Ui,+ text: &str,+ size: f32,+ max_width: f32,+) -> std::sync::Arc<egui::Galley> {+ let mut job = egui::text::LayoutJob::single_section(+ text.to_owned(),+ egui::TextFormat::simple(egui::FontId::proportional(size), egui::Color32::PLACEHOLDER),+ );+ job.wrap = egui::text::TextWrapping::truncate_at_width(max_width.max(0.0));++ ui.painter().layout_job(job)+}++/// Paints a galley with its left edge at `left`, centered vertically on `center_y`.+fn paint_text(+ painter: &egui::Painter,+ left: f32,+ center_y: f32,+ galley: std::sync::Arc<egui::Galley>,+ color: egui::Color32,+) {+ let pos = egui::pos2(left, center_y - galley.size().y / 2.0);+ painter.galley(pos, galley, color);+}++/// Draws the small SVG-inspired line icons from the Chrome extension using egui painter primitives.+fn draw_glyph(ui: &egui::Ui, rect: egui::Rect, glyph: Glyph, color: egui::Color32) {+ match glyph {+ Glyph::Sliders => draw_sliders_icon(ui, rect, color),+ Glyph::BookDown => draw_book_down_icon(ui, rect, color),+ }+}++/// Draws Font Awesome's `faSliders`: three horizontal tracks, each with a knob.+fn draw_sliders_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {+ let stroke = egui::Stroke::new(1.5_f32, color);+ let knob_radius = rect.height() * 0.15;++ for (track_y, knob_x) in [(0.19, 0.375), (0.5, 0.625), (0.81, 0.3125)] {+ let y = rect.top() + rect.height() * track_y;+ ui.painter().hline(rect.x_range(), y, stroke);+ ui.painter().circle_filled(+ egui::pos2(rect.left() + rect.width() * knob_x, y),+ knob_radius,+ color,+ );+ }+}++/// Draws Lucide's `book-down` icon from its 24×24 SVG path.+fn draw_book_down_icon(ui: &egui::Ui, rect: egui::Rect, color: egui::Color32) {+ const ARC_STEPS: usize = 8;++ let scale = rect.width().min(rect.height()) / 24.0;+ let origin = rect.center() - egui::vec2(12.0, 12.0) * scale;+ let point = |x: f32, y: f32| origin + egui::vec2(x, y) * scale;+ let arc = |center_x: f32, center_y: f32, radius: f32, from_degrees: f32, to_degrees: f32| {+ (0..=ARC_STEPS)+ .map(|step| {+ let t = step as f32 / ARC_STEPS as f32;+ let angle = (from_degrees + (to_degrees - from_degrees) * t).to_radians();+ point(+ center_x + radius * angle.cos(),+ center_y + radius * angle.sin(),+ )+ })+ .collect::<Vec<_>>()+ };+ let stroke = egui::Stroke::new(scale.max(1.0), color);++ let mut outline = vec![point(4.0, 19.5)];+ outline.extend(arc(6.5, 4.5, 2.5, 180.0, 270.0));+ outline.extend(arc(19.0, 3.0, 1.0, 270.0, 360.0));+ outline.extend(arc(19.0, 21.0, 1.0, 0.0, 90.0));+ outline.extend(arc(6.5, 19.5, 2.5, 90.0, 270.0));+ outline.push(point(20.0, 17.0));++ ui.painter().add(egui::Shape::line(outline, stroke));+ ui.painter()+ .line_segment([point(12.0, 13.0), point(12.0, 7.0)], stroke);+ ui.painter().add(egui::Shape::line(+ vec![point(9.0, 10.0), point(12.0, 13.0), point(15.0, 10.0)],+ stroke,+ ));+}++fn is_spelling_kind(lint_kind: LintKind) -> bool {+ match lint_kind {+ LintKind::Eggcorn | LintKind::Malapropism | LintKind::Spelling | LintKind::Typo => true,+ LintKind::Agreement+ | LintKind::BoundaryError+ | LintKind::Capitalization+ | LintKind::Enhancement+ | LintKind::Formatting+ | LintKind::Grammar+ | LintKind::Miscellaneous+ | LintKind::Nonstandard+ | LintKind::Punctuation+ | LintKind::Readability+ | LintKind::Redundancy+ | LintKind::Regionalism+ | LintKind::Repetition+ | LintKind::Style+ | LintKind::Usage+ | LintKind::WordChoice+ | LintKind::WordOrder => false,+ }+}++/// Converts Harper suggestion variants into row labels. Like the Chrome extension, it falls back to+/// the kind of edit when the replacement text is empty.+fn suggestion_text(suggestion: &Suggestion) -> String {+ match suggestion {+ Suggestion::ReplaceWith(chars) | Suggestion::InsertAfter(chars) if !chars.is_empty() => {+ chars.iter().collect()+ }+ Suggestion::ReplaceWith(_) => "Replace".to_owned(),+ Suggestion::InsertAfter(_) => "Insert After".to_owned(),+ Suggestion::Remove => "Remove".to_owned(),+ }+}++/// Describes the edit that a suggestion row makes, with the same wording as the Chrome extension.+fn suggestion_hover_text(suggestion: &Suggestion, problem_text: &str) -> String {+ match suggestion {+ Suggestion::ReplaceWith(chars) => format!(+ "Click to replace \"{problem_text}\" with \"{}\"",+ chars.iter().collect::<String>()+ ),+ Suggestion::InsertAfter(chars) => format!(+ "Click to insert \"{}\" after \"{problem_text}\"",+ chars.iter().collect::<String>()+ ),+ Suggestion::Remove => format!("Click to remove \"{problem_text}\""),+ }+}++/// Gets the text that the lint flags, for use in popup labels and tooltips.+fn problem_text(lint: &Lint, source_text: &str) -> String {+ let source_chars = source_text.chars().collect::<Vec<_>>();+ lint.get_str(&source_chars)+}++/// Defines popup geometry ahead of rendering so the transparent overlay can enable or disable native+/// hit-testing based on our intended layout, not a previous frame's measured egui output.+///+/// The list card's size comes from its fixed row geometry. The flyout card's content is markdown,+/// so its bounds always have the maximum size. A flyout with less content is drawn smaller, and the+/// overlay catches clicks on the transparent space below it instead of the editor.+///+/// `sidebar_position` is the flyout card's current offset from the list card's top, not its target,+/// so hit-testing follows the card while it moves.+pub fn popup_layout_for_lint(rect: &Rect, lint: &Lint, sidebar_position: f32) -> PopupLayout {+ popup_layout(+ rect,+ UNBOUNDED_VIEWPORT,+ egui::vec2(LIST_CARD_WIDTH, list_card_height(row_count(lint))),+ egui::vec2(FLYOUT_CARD_WIDTH, CARD_HEIGHT),+ sidebar_position,+ )+}++/// Computes the sidebar position that aligns the flyout card with the row at `shown_suggestion`.+///+/// The sidebar moves toward this value on each frame, but does not jump to it.+pub fn sidebar_target(lint: &Lint, shown_suggestion: Option<usize>) -> f32 {+ row_offset(shown_suggestion, list_card_height(row_count(lint)))+}++/// Counts the list card's suggestion rows, including the "No replacements" row.+pub fn row_count(lint: &Lint) -> usize {+ lint.suggestions.len().max(1)+}++/// Computes the list card's height from its fixed row and footer heights.+fn list_card_height(row_count: usize) -> f32 {+ let content = 2.0 * LIST_PADDING_Y + row_count as f32 * ROW_HEIGHT + LIST_FOOTER_HEIGHT;++ (2.0 * BORDER_WIDTH + content).min(CARD_HEIGHT)+}++/// Computes the distance from the list card's top to the top of the row at `shown_suggestion`.+///+/// `None` gives the first row. Like the Chrome extension, this ignores the list's scroll position,+/// but the result never goes past the last row position that fits in the card.+fn row_offset(shown_suggestion: Option<usize>, list_height: f32) -> f32 {+ let offset = FIRST_ROW_OFFSET + shown_suggestion.unwrap_or(0) as f32 * ROW_HEIGHT;++ offset.min(list_height - BORDER_WIDTH - ROW_HEIGHT).max(0.0)+}++/// Scales a color's channels, like the CSS `brightness()` filter.+fn brightness(color: egui::Color32, factor: f32) -> egui::Color32 {+ let [r, g, b, a] = color.to_array();+ let scale = |channel: u8| (f32::from(channel) * factor).round().clamp(0.0, 255.0) as u8;++ egui::Color32::from_rgba_premultiplied(scale(r), scale(g), scale(b), a)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn list_card_height_counts_rows_and_footer() {+ assert_eq!(list_card_height(1), 2.0 + 8.0 + 30.0 + 37.0);+ assert_eq!(list_card_height(3), 2.0 + 8.0 + 90.0 + 37.0);+ }++ #[test]+ fn list_card_height_caps_at_max() {+ assert_eq!(list_card_height(100), CARD_HEIGHT);+ }++ #[test]+ fn row_offset_starts_at_first_row() {+ let list_height = list_card_height(3);++ assert_eq!(row_offset(None, list_height), FIRST_ROW_OFFSET);+ assert_eq!(+ row_offset(Some(0), list_height),+ row_offset(None, list_height)+ );+ }++ #[test]+ fn row_offset_steps_by_row_height() {+ let list_height = list_card_height(3);++ assert_eq!(+ row_offset(Some(2), list_height),+ FIRST_ROW_OFFSET + 2.0 * ROW_HEIGHT+ );+ }++ #[test]+ fn row_offset_stays_inside_scrolled_list() {+ let list_height = list_card_height(100);++ assert_eq!(+ row_offset(Some(99), list_height),+ CARD_HEIGHT - BORDER_WIDTH - ROW_HEIGHT+ );+ }++ #[test]+ fn suggestion_text_uses_replacement() {+ assert_eq!(+ suggestion_text(&Suggestion::ReplaceWith("their".chars().collect())),+ "their"+ );+ assert_eq!(+ suggestion_text(&Suggestion::InsertAfter(",".chars().collect())),+ ","+ );+ }++ #[test]+ fn suggestion_text_falls_back_to_edit_kind() {+ assert_eq!(+ suggestion_text(&Suggestion::ReplaceWith(Vec::new())),+ "Replace"+ );+ assert_eq!(+ suggestion_text(&Suggestion::InsertAfter(Vec::new())),+ "Insert After"+ );+ assert_eq!(suggestion_text(&Suggestion::Remove), "Remove");+ }++ #[test]+ fn suggestion_hover_text_describes_edit() {+ assert_eq!(+ suggestion_hover_text(&Suggestion::ReplaceWith("their".chars().collect()), "there"),+ "Click to replace \"there\" with \"their\""+ );+ assert_eq!(+ suggestion_hover_text(&Suggestion::InsertAfter(",".chars().collect()), "However"),+ "Click to insert \",\" after \"However\""+ );+ assert_eq!(+ suggestion_hover_text(&Suggestion::Remove, "the"),+ "Click to remove \"the\""+ );+ }++ #[test]+ fn brightness_darkens_opaque_colors() {+ assert_eq!(+ brightness(egui::Color32::from_rgb(100, 200, 0), 0.5),+ egui::Color32::from_rgb(50, 100, 0)+ );+ }+}diff --git a/harper-desktop/src-tauri/src/highlighter/window.rs b/harper-desktop/src-tauri/src/highlighter/window.rsindex 1a7bdb87f..95651ef0a 100644--- a/harper-desktop/src-tauri/src/highlighter/window.rs+++ b/harper-desktop/src-tauri/src/highlighter/window.rs@@ -18,6 +18,10 @@ use super::render_state::RenderState;/// `Window` owns the native winit window plus egui/wgpu integration required to render into it. It/// deliberately does not own highlighter drawing decisions; those are supplied by `RenderState`/// during each redraw.+///+/// Each window owns its own egui context. A painter only receives the texture updates (such as+/// font atlas changes) from passes run on its own window, so windows that share one context end+/// up drawing with incomplete textures.pub struct Window {inner: Arc<WinitWindow>,egui_state: egui_winit::State,@@ -26,11 +30,8 @@ pub struct Window {}impl Window {- pub async fn new(- event_loop: &ActiveEventLoop,- monitor: MonitorHandle,- context: egui::Context,- ) -> Result<Self, Error> {+ pub async fn new(event_loop: &ActiveEventLoop, monitor: MonitorHandle) -> Result<Self, Error> {+ let context = egui::Context::default();let position = monitor.position();let size = monitor.size();let window = Arc::new(diff --git a/harper-desktop/src-tauri/src/highlighter/window_manager.rs b/harper-desktop/src-tauri/src/highlighter/window_manager.rsindex 8600586ed..7fe5cd0e9 100644--- a/harper-desktop/src-tauri/src/highlighter/window_manager.rs+++ b/harper-desktop/src-tauri/src/highlighter/window_manager.rs@@ -11,6 +11,7 @@ use super::AddToDictionary;use super::DisableRule;use super::Error;use super::IgnoreLint;+use super::OpenSettings;use super::RefreshConfig;use super::render_state::{HitTarget, RenderState};use super::window::Window;@@ -26,7 +27,6 @@ const CONFIG_POLL_INTERVAL: Duration = Duration::from_secs(1);/// dispatch out of the public highlighter API.pub struct WindowManager {event_loop: EventLoop<()>,- context: egui::Context,rects: Vec<ActionableLint>,os_broker: Box<dyn OsBroker>,lint_text: LintText,@@ -34,6 +34,7 @@ pub struct WindowManager {add_to_dictionary: AddToDictionary,disable_rule: DisableRule,refresh_config: RefreshConfig,+ open_settings: OpenSettings,}pub struct WindowManagerCallbacks {@@ -42,13 +43,13 @@ pub struct WindowManagerCallbacks {pub add_to_dictionary: AddToDictionary,pub disable_rule: DisableRule,pub refresh_config: RefreshConfig,+ pub open_settings: OpenSettings,}impl WindowManager {/// Creates the event loop before windows exist because winit requires window creation to happen/// from inside that loop's lifecycle callbacks.pub fn new(- context: egui::Context,os_broker: Box<dyn OsBroker>,callbacks: WindowManagerCallbacks,) -> Result<Self, Error> {@@ -61,7 +62,6 @@ impl WindowManager {Ok(Self {event_loop: event_loop_builder.build()?,- context,rects: Vec::new(),os_broker,lint_text: callbacks.lint_text,@@ -69,6 +69,7 @@ impl WindowManager {add_to_dictionary: callbacks.add_to_dictionary,disable_rule: callbacks.disable_rule,refresh_config: callbacks.refresh_config,+ open_settings: callbacks.open_settings,})}@@ -81,7 +82,6 @@ impl WindowManager {/// event loop until the overlay exits.pub fn run_window_for_each_monitor(self) -> Result<(), Error> {let mut app = WindowManagerApp::new(- self.context,self.rects,self.os_broker,WindowManagerCallbacks {@@ -90,6 +90,7 @@ impl WindowManager {add_to_dictionary: self.add_to_dictionary,disable_rule: self.disable_rule,refresh_config: self.refresh_config,+ open_settings: self.open_settings,},);@@ -106,7 +107,6 @@ impl WindowManager {}struct WindowManagerApp {- context: egui::Context,windows: Vec<Window>,render_state: RenderState,os_broker: Box<dyn OsBroker>,@@ -122,19 +122,18 @@ impl WindowManagerApp {/// Builds the mutable application state consumed by winit callbacks after `WindowManager` gives/// up direct control of the event loop.fn new(- context: egui::Context,rects: Vec<ActionableLint>,os_broker: Box<dyn OsBroker>,callbacks: WindowManagerCallbacks,) -> Self {Self {- context,windows: Vec::new(),render_state: RenderState::new(rects,callbacks.ignore_lint,callbacks.add_to_dictionary,callbacks.disable_rule,+ callbacks.open_settings,),os_broker,lint_text: callbacks.lint_text,@@ -235,7 +234,7 @@ impl ApplicationHandler for WindowManagerApp {let monitors = event_loop.available_monitors().collect::<Vec<_>>();for monitor in monitors {- match pollster::block_on(Window::new(event_loop, monitor, self.context.clone())) {+ match pollster::block_on(Window::new(event_loop, monitor)) {Ok(window) => self.windows.push(window),Err(error) => {self.error = Some(error);diff --git a/harper-desktop/src-tauri/src/highlighter_service/highlighter_worker.rs b/harper-desktop/src-tauri/src/highlighter_service/highlighter_worker.rsindex fed8ae436..e86310fe5 100644--- a/harper-desktop/src-tauri/src/highlighter_service/highlighter_worker.rs+++ b/harper-desktop/src-tauri/src/highlighter_service/highlighter_worker.rs@@ -1,5 +1,9 @@use super::highlighter_process::HighlighterProcess;-use crate::{communication::Server, config::Config};+use crate::{+ communication::{Request, Server},+ config::Config,+ windows::show_settings_window,+};use std::{io,sync::Arc,@@ -20,7 +24,7 @@ pub struct HighlighterWorker {impl HighlighterWorker {/// Spawns a new highlighter process and thread to manage it.- pub fn spawn(config: Arc<Mutex<Config>>) -> io::Result<Self> {+ pub fn spawn(config: Arc<Mutex<Config>>, app: tauri::AppHandle) -> io::Result<Self> {let (shutdown_sender, shutdown_receiver) = oneshot::channel();let (startup_sender, startup_receiver) = std::sync::mpsc::sync_channel(1);@@ -54,7 +58,7 @@ impl HighlighterWorker {};let _ = startup_sender.send(Ok(()));- run_server_until_shutdown(&mut server, shutdown_receiver).await;+ run_server_until_shutdown(&mut server, shutdown_receiver, &app).await;highlighter_process.terminate().await;});})?;@@ -108,6 +112,7 @@ impl Drop for HighlighterWorker {async fn run_server_until_shutdown<R, W>(server: &mut Server<R, W>,mut shutdown_receiver: oneshot::Receiver<()>,+ app: &tauri::AppHandle,) whereR: AsyncRead + Unpin,W: AsyncWrite + Unpin,@@ -117,6 +122,16 @@ async fn run_server_until_shutdown<R, W>(_ = &mut shutdown_receiver => break,request = server.receive_request() => {match request {+ Ok(Some(Request::OpenSettings)) => {+ let settings_app = app.clone();+ if let Err(error) = app.run_on_main_thread(move || {+ if let Err(error) = show_settings_window(&settings_app) {+ eprintln!("failed to open settings window: {error}");+ }+ }) {+ eprintln!("failed to schedule settings window: {error}");+ }+ }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.rsindex 891f4d9c2..60ba0ea27 100644--- a/harper-desktop/src-tauri/src/highlighter_service/mod.rs+++ b/harper-desktop/src-tauri/src/highlighter_service/mod.rs@@ -14,6 +14,7 @@ use tokio::sync::Mutex;/// The service will sync the changes to the underlying highlighter process.pub struct HighlighterService {config: Arc<Mutex<Config>>,+ app: tauri::AppHandle,worker: StdMutex<Option<HighlighterWorker>>,}@@ -21,9 +22,10 @@ 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 {+ pub fn new(config: Arc<Mutex<Config>>, app: tauri::AppHandle) -> Self {Self {config,+ app,worker: StdMutex::new(None),}}@@ -40,7 +42,10 @@ impl HighlighterService {return Ok(true);}- *worker = Some(HighlighterWorker::spawn(self.config.clone())?);+ *worker = Some(HighlighterWorker::spawn(+ self.config.clone(),+ self.app.clone(),+ )?);Ok(true)}diff --git a/harper-desktop/src-tauri/src/main.rs b/harper-desktop/src-tauri/src/main.rsindex 3842af8b4..81ed6b092 100644--- a/harper-desktop/src-tauri/src/main.rs+++ b/harper-desktop/src-tauri/src/main.rs@@ -160,22 +160,13 @@ pub fn run_tauri() {let broker = platform_broker(|_| false);- let highlighter_service_enabled = config.highlighter_service_enabled;+ let should_start_highlighter = config.highlighter_service_enabled+ && broker.accessibility_permission_status() == AccessibilityPermissionStatus::Granted;let config = Arc::new(Mutex::new(config));- let highlighter_service = HighlighterService::new(config.clone());- if 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(config.clone()).manage(desktop_updater::DesktopUpdater::default())- .manage(highlighter_service).manage(RwLock::new(broker)).manage(async_runtime).plugin(tauri_plugin_autostart::init(@@ -189,6 +180,14 @@ pub fn run_tauri() {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());@@ -234,6 +233,7 @@ pub fn popup_debug() {|_| {},|_| {},|| {},+ || {},).unwrap();highlighter.run_window_for_each_monitor().unwrap();@@ -320,6 +320,9 @@ pub fn run_highlighter(has_parent: bool) {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();@@ -411,6 +414,22 @@ pub fn run_highlighter(has_parent: bool) {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;@@ -443,6 +462,7 @@ pub fn run_highlighter(has_parent: bool) {add_to_dictionary,disable_rule,refresh_config,+ open_settings,).and_then(Highlighter::run_window_for_each_monitor){