diff --git a/Cargo.lock b/Cargo.lock index 6081eaa4..a75b21fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3381,6 +3381,7 @@ dependencies = [ "semver", "serde_json", "sha2", + "ttf-parser", "ureq", "web-time", "zip", diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index 2157fbea..0686b0f8 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -199,6 +199,20 @@ fn main() -> eframe::Result { let _ = Settings::default_location().set("telemetry_session_id", session.id()); let _ = session.record(telemetry::Level::Usage, "app_start", &[("version", env!("CARGO_PKG_VERSION"))]); } + // The interface records its usage events through this sink. Every event goes to the local log; + // it also goes to the telemetry session when one exists and its level allows the event. + let session = telemetry; + notecraft_ui_egui::usage::install(Box::new(move |level, event, fields| { + applog::info(&format!("event {event} {fields:?}")); + if let Some(session) = &session { + let level = match level { + notecraft_ui_egui::usage::Level::Usage => telemetry::Level::Usage, + notecraft_ui_egui::usage::Level::Warning => telemetry::Level::Warning, + notecraft_ui_egui::usage::Level::Error => telemetry::Level::Error, + }; + let _ = session.record(level, event, fields); + } + })); applog::info(&format!( "start: NoteCraft {} exe={:?} args={args:?} settings={:?}", env!("CARGO_PKG_VERSION"), diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 3023115d..28ebbe22 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -51,6 +51,7 @@ arboard = { workspace = true } [target.'cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))'.dependencies] fontdb = "0.23" +ttf-parser = "0.25.1" # File > About > "Check for updates": asks GitHub for the newest release, downloads the file for # this computer and checks it against the release's SHA-256 before running it. Nothing is sent # until the button is pressed. diff --git a/crates/ui-egui/src/combo.rs b/crates/ui-egui/src/combo.rs index f96ca897..0a4a606b 100644 --- a/crates/ui-egui/src/combo.rs +++ b/crates/ui-egui/src/combo.rs @@ -5,13 +5,19 @@ //! The arrow is a generous hit region with a tooltip and an accessible label. The list highlights //! the current value and scrolls to it once each time it opens. A typed value is applied when the //! box loses focus, if the caller accepts it. +//! +//! With `filter` on (the font name box), typing lists only the items that contain the text, Up and +//! Down move the highlight through them, and Enter applies the highlighted item (an item that +//! equals the typed text wins). Escape restores the shown value. -use egui::{Align, Area, Color32, Frame, Id, Order, ScrollArea, Shape, Stroke, Ui, WidgetInfo, WidgetType, vec2}; +use egui::{Align, Area, Color32, Frame, Id, Key, Modifiers, Order, Rect, ScrollArea, Shape, Stroke, Ui, WidgetInfo, WidgetType, vec2}; /// What the user chose this frame: a value picked from the list, or typed and accepted. #[derive(Debug, Default, PartialEq, Eq)] pub struct Outcome { pub chosen: Option, + /// The Add Font row was picked: the caller opens the file picker. + pub add_font: bool, } /// The parts of one combo box that the caller supplies. @@ -33,37 +39,206 @@ pub struct Spec<'a> { pub empty_note: Option<&'a str>, /// Whether a typed value is accepted when the box loses focus. pub accept: &'a dyn Fn(&str) -> bool, + /// Whether typing lists only the items that contain the text, with Up/Down/Enter to pick. + pub filter: bool, + /// Families used lately, most recent first. Shown under Recently Used Fonts above All Fonts + /// when the box is not being typed in. Empty for the size box. + pub recent: &'a [String], + /// The shown value is not an installed font: a warning mark shows beside the box, with the + /// tooltip `ui.font_missing`. + pub missing: bool, + /// Each family name is drawn in its own font, as a sample, once that font is loaded. The + /// fonts load as the rows come into view. + pub preview: bool, + /// The list grouped by script: each heading with its families. Empty when there is no + /// grouping (the size box, or while the catalog loads). + pub sections: &'a [(String, Vec)], + /// The label of the Add Font row under the list, or `None` when the box has none. + pub add_font: Option<&'a str>, + /// Which box this is, for usage events (for example "ribbon-family"). Never a name or a path. + pub usage: &'static str, + /// The theme of the surrounding window. The list takes the same popup look as the language + /// pickers, so its text is never the ribbon's foreground on a light list. + pub tokens: crate::theme::Tokens, +} + +/// A script heading in the font list: bold, on a band, so the list scrolls from one script to the +/// next and the eye finds each one. +fn section_heading(ui: &mut Ui, text: &str) { + ui.add_space(4.0); + egui::Frame::default().fill(ui.visuals().faint_bg_color).inner_margin(egui::Margin::symmetric(6, 2)).show(ui, |ui| { + ui.label(egui::RichText::new(text).strong()); + }); +} + +/// One row of a font list. Records a visible name so its font loads, and scrolls to the row when +/// asked to. +fn font_row(ui: &mut Ui, name: &str, current: bool, preview: bool, wanted: &mut Vec, scroll_to: bool) -> egui::Response { + // A fixed row height: a row drawn in its own font would otherwise change size as its font loads, + // and move under the pointer. + let height = ui.spacing().interact_size.y; + // The family list: names left-aligned and indented under their heading. The size list is drawn + // as it always was. + const INDENT: f32 = 24.0; + let row = if preview { + // A fixed-size slot: the name is laid out from the left inside it, so a taller face does not + // push the rows below it. + let width = ui.available_width().max(0.0); + ui.allocate_ui_with_layout(egui::vec2(width, height), egui::Layout::left_to_right(Align::Center), |ui| { + ui.add_space(INDENT); + ui.selectable_label(current, name_text(ui, name, preview)) + }) + .inner + } else { + ui.add_sized(egui::vec2(ui.available_width(), height), egui::Button::selectable(current, name_text(ui, name, preview)).truncate()) + }; + if preview && ui.is_rect_visible(row.rect) { + wanted.push(name.to_owned()); + } + if current && scroll_to { + row.scroll_to_me(Some(Align::Center)); + } + row +} + +/// The text of one list row: the name, drawn in its own font when `preview` is on and that font +/// is already registered. A font that is not registered yet draws in the interface font. +fn name_text(ui: &Ui, name: &str, preview: bool) -> egui::RichText { + let text = egui::RichText::new(name); + if preview { + let family = crate::fonts::named_family(name); + if ui.ctx().fonts(|fonts| fonts.definitions().families.contains_key(&family)) { + return text.family(family); + } + } + text } /// Shows the combo box and returns what was chosen this frame. pub fn show(ui: &mut Ui, text: Color32, spec: Spec<'_>) -> Outcome { let mut outcome = Outcome::default(); + // How the value was chosen, for usage events: typed, or picked from the list. + let mut how: &str = ""; let typed_id = spec.id.with("typed"); let open_id = spec.id.with("open"); let scroll_id = spec.id.with("scroll"); + let highlight_id = spec.id.with("highlight"); + let list_rect_id = spec.id.with("list-rect"); let mut typed = ui.data(|d| d.get_temp::(typed_id)).unwrap_or_else(|| spec.shown.to_owned()); - let cancelled = ui.input(|i| i.key_pressed(egui::Key::Escape)); - let entered = ui.input(|i| i.key_pressed(egui::Key::Enter)); + let mut highlight = ui.data(|d| d.get_temp::(highlight_id)).unwrap_or(0); + let was_focused = ui.memory(|m| m.has_focus(typed_id)); + // Up and Down are read before the box sees them, so the highlight moves and the caret does not. + let (down, up) = if spec.filter && was_focused { + ui.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::ArrowDown), i.consume_key(Modifiers::NONE, Key::ArrowUp))) + } else { + (false, false) + }; + let cancelled = ui.input(|i| i.key_pressed(Key::Escape)); + let entered = ui.input(|i| i.key_pressed(Key::Enter)); let value_box = ui.add(egui::TextEdit::singleline(&mut typed).id(typed_id).desired_width(spec.width)); + if spec.missing { + // An amber triangle inside the box's right edge, as WordCraft draws it. + let c = egui::pos2(value_box.rect.right() - 8.0, value_box.rect.center().y); + let points = vec![c + vec2(-5.0, 4.0), c + vec2(5.0, 4.0), c + vec2(0.0, -5.0)]; + ui.painter().add(Shape::convex_polygon(points, Color32::from_rgb(0xE0, 0x8A, 0x00), Stroke::NONE)); + let warning = value_box.rect.with_min_x(value_box.rect.right() - 18.0); + ui.interact(warning, value_box.id.with("missing"), egui::Sense::hover()).on_hover_text(crate::tl_id!("ui.font_missing")); + } value_box.widget_info(|| WidgetInfo::labeled(WidgetType::TextInput, true, spec.box_label)); - // Read the entry before resetting an unfocused box. Enter also loses focus; - // Escape cancels rather than applying the unfinished entry. + if value_box.changed() { + highlight = 0; + } + // Typing lists the matches while the box has focus and its text is not the shown value. + // A press on a row of the typed list takes focus from the box. The list must keep its matches + // until the button is released, or the row under the pointer changes before the click lands. + let last_typing: bool = ui.data(|d| d.get_temp(spec.id.with("last-typing"))).unwrap_or(false); + let list_under_pointer: bool = match (ui.input(|i| i.pointer.hover_pos()), ui.data(|d| d.get_temp::(list_rect_id))) { + (Some(p), Some(r)) => r.contains(p), + _ => false, + }; + let pressing_list = list_under_pointer && ui.input(|i| i.pointer.primary_down()); + // Armed by a press on the typed list; it stays armed through the release, so the release + // lands on the row that was pressed. + let armed: bool = ui.data(|d| d.get_temp(spec.id.with("press-armed"))).unwrap_or(false); + let released = ui.input(|i| i.pointer.primary_released()); + let keep_typing = (pressing_list && last_typing) || armed; + let typing = spec.filter && ((typed.trim() != spec.shown && (was_focused || value_box.has_focus())) || keep_typing); + // Typing lists the families whose names match, and also every family of a script whose heading + // matches (typing "arabic" lists the Arabic fonts). Each heading's families come first. + let query = typed.trim().to_lowercase(); + let mut heading_starts: Vec<(usize, &String)> = Vec::new(); + let hits: Vec<&String> = if typing { + let mut placed = std::collections::BTreeSet::new(); + let mut flat: Vec<&String> = Vec::new(); + if !query.is_empty() { + for (heading, names) in spec.sections { + if heading.to_lowercase().contains(&query) { + heading_starts.push((flat.len(), heading)); + for name in names { + if placed.insert(name.clone()) { + flat.push(name); + } + } + } + } + } + for index in crate::font_picker::matches(&typed, spec.items) { + let name = &spec.items[index]; + if !placed.contains(name) { + flat.push(name); + } + } + flat + } else { + Vec::new() + }; + if down { + highlight = (highlight + 1).min(hits.len().saturating_sub(1)); + } + if up { + highlight = highlight.saturating_sub(1); + } + highlight = highlight.min(hits.len().saturating_sub(1)); + + // Read the entry before resetting an unfocused box. Enter also loses focus; Escape cancels + // rather than applying the unfinished entry. if value_box.lost_focus() { - // Formatting may return focus to the page in this same frame. The key - // belongs to this field, not to the editor which happens to run next. + // Formatting may return focus to the page in this same frame. The key belongs to this + // field, not to the editor which happens to run next. if entered || cancelled { - ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, if cancelled { egui::Key::Escape } else { egui::Key::Enter })); + ui.input_mut(|i| i.consume_key(Modifiers::NONE, if cancelled { Key::Escape } else { Key::Enter })); } - let value = typed.trim(); - if !cancelled && value != spec.shown && (spec.accept)(value) { - outcome.chosen = Some(value.to_owned()); + // A press on the list is not a finished entry: the list's own click applies its row. + let list_rect: Option = ui.data(|d| d.get_temp(list_rect_id)); + let on_list = match (ui.input(|i| i.pointer.hover_pos()), list_rect) { + (Some(p), Some(r)) => r.contains(p), + _ => false, + }; + if !cancelled && !on_list { + let exact = spec.items.iter().find(|item| item.eq_ignore_ascii_case(typed.trim())); + // Enter takes the match. A click away takes only an exact family name: half-typed text + // ("geo") is not applied as a font just because the box lost focus. + let value: Option = match (spec.filter, entered, exact, hits.get(highlight)) { + (true, true, Some(item), _) => Some(item.clone()), + (true, true, None, Some(hit)) => Some((*hit).clone()), + (true, false, Some(item), _) => Some(item.clone()), + (true, false, None, _) => None, + _ => Some(typed.trim().to_owned()), + }; + if let Some(value) = value.filter(|value| value != spec.shown && (spec.accept)(value)) { + how = "typed"; + outcome.chosen = Some(value); + } } } - if !value_box.has_focus() { + if !value_box.has_focus() && !keep_typing { typed = spec.shown.to_owned(); } - ui.data_mut(|d| d.insert_temp(typed_id, typed)); + ui.data_mut(|d| { + d.insert_temp(typed_id, typed); + d.insert_temp(highlight_id, highlight); + }); let mut open = ui.data(|d| d.get_temp::(open_id)).unwrap_or(false); let mut scroll = ui.data(|d| d.get_temp::(scroll_id)).unwrap_or(false); @@ -82,34 +257,101 @@ pub fn show(ui: &mut Ui, text: Color32, spec: Spec<'_>) -> Outcome { if arrow.clicked() { open = !open; scroll = open; + if open { + crate::usage::record(crate::usage::Level::Usage, "combo_opened", &[("box", spec.usage)]); + } } - if open { + // The list: the matches while typing, otherwise all items when the arrow has opened it. + let show_list = typing || open; + let mut list_rect = None; + if show_list { + let rows: Vec<&String> = if typing { hits } else { spec.items.iter().collect() }; + // Recently used families go above the full list, when the box is not being typed in. + let recent_rows: Vec<&String> = if typing { Vec::new() } else { spec.recent.iter().collect() }; + // The script sections replace the one full list when the box is not being typed in. + let by_script = !typing && !spec.sections.is_empty(); + // Names whose rows are on screen this frame; their fonts load after the list is drawn. + let mut wanted: Vec = Vec::new(); let list = Area::new(spec.id.with("list")).order(Order::Foreground).fixed_pos(value_box.rect.left_bottom()).show(ui.ctx(), |ui| { + // The family list takes the picker colours, so its text reads on the light list. + if spec.preview { + crate::theme::picker_popup_style(spec.tokens).apply(ui.style_mut()); + } Frame::popup(ui.style()).show(ui, |ui| { ui.set_min_width(value_box.rect.width()); - if spec.items.is_empty() { + if rows.is_empty() { if let Some(note) = spec.empty_note { ui.label(note); } return; } ScrollArea::vertical().max_height(280.0).show(ui, |ui| { - for item in spec.items { - let current = item == spec.shown; - let row = ui.selectable_label(current, item); - if current && scroll { - row.scroll_to_me(Some(Align::Center)); + if !recent_rows.is_empty() { + ui.label(egui::RichText::new(crate::tl_id!("ui.recent_fonts")).small().weak()); + for item in &recent_rows { + let current = item.as_str() == spec.shown; + let row = font_row(ui, item, current, spec.preview, &mut wanted, scroll); + if row.clicked() { + how = "list"; + outcome.chosen = Some((*item).clone()); + open = false; + ui.memory_mut(|m| m.surrender_focus(typed_id)); + } } - if row.clicked() { - outcome.chosen = Some(item.clone()); + ui.separator(); + } + if by_script { + // One heading per script, so the list scrolls from language to language. + for (heading, names) in spec.sections { + section_heading(ui, heading); + for item in names { + let current = item.as_str() == spec.shown; + let row = font_row(ui, item, current, spec.preview, &mut wanted, scroll); + if row.clicked() { + how = "list"; + outcome.chosen = Some(item.clone()); + open = false; + ui.memory_mut(|m| m.surrender_focus(typed_id)); + } + } + } + } else { + if !recent_rows.is_empty() { + ui.label(egui::RichText::new(crate::tl_id!("ui.all_fonts")).small().weak()); + } + for (index, item) in rows.iter().enumerate() { + if let Some((_, heading)) = heading_starts.iter().find(|(start, _)| *start == index) { + section_heading(ui, heading); + } + let current = if typing { index == highlight } else { item.as_str() == spec.shown }; + let row = font_row(ui, item, current, spec.preview, &mut wanted, scroll || typing); + if row.clicked() { + how = "list"; + outcome.chosen = Some((*item).clone()); + open = false; + ui.memory_mut(|m| m.surrender_focus(typed_id)); + } + } + } + if let Some(label) = spec.add_font { + ui.separator(); + if ui.selectable_label(false, label).clicked() { + outcome.add_font = true; open = false; + ui.memory_mut(|m| m.surrender_focus(typed_id)); } } }); }); }); - if ui.input(|i| i.pointer.any_click()) && !list.response.hovered() && !arrow.hovered() { + if !wanted.is_empty() { + // Registers the fonts of the visible rows. Drawn in them from the next frame. + let names: std::collections::BTreeSet = wanted.into_iter().collect(); + crate::fonts::ensure_page_fonts(ui.ctx(), &names); + } + list_rect = Some(list.response.rect); + if !typing && ui.input(|i| i.pointer.any_click()) && !list.response.hovered() && !arrow.hovered() { open = false; } } @@ -117,6 +359,20 @@ pub fn show(ui: &mut Ui, text: Color32, spec: Spec<'_>) -> Outcome { ui.data_mut(|d| { d.insert_temp(scroll_id, scroll); d.insert_temp(open_id, open); + d.insert_temp(spec.id.with("last-typing"), typing); + d.insert_temp(spec.id.with("press-armed"), keep_typing && !released); + if let Some(r) = list_rect { + d.insert_temp(list_rect_id, r); + } else { + d.remove::(list_rect_id); + } }); + if let Some(name) = &outcome.chosen { + crate::usage::record( + crate::usage::Level::Usage, + "combo_chosen", + &[("box", spec.usage), ("how", how), ("chars", &name.chars().count().to_string())], + ); + } outcome } diff --git a/crates/ui-egui/src/floating.rs b/crates/ui-egui/src/floating.rs index ddc3e273..46635a64 100644 --- a/crates/ui-egui/src/floating.rs +++ b/crates/ui-egui/src/floating.rs @@ -115,6 +115,12 @@ pub struct FontBoxes { pub families: Vec, pub families_note: Option, pub sizes: Vec, + /// Recently used families, most recent first, shared with the ribbon's family box. + pub recent: Vec, + /// The family shown is not installed, so the box shows its warning mark. + pub family_missing: bool, + /// The installed families grouped by script, with a heading for each. + pub sections: std::sync::Arc)>>, } /// The egui memory key under which the ribbon stores the [`FontBoxes`] for this frame. @@ -207,9 +213,26 @@ pub fn show_bar(ctx: &Context, id: Id, anchor: Rect, bar: &Bar, t: &Tokens, acts items: &fonts.families, empty_note: fonts.families_note.as_deref(), accept: &|typed| notecraft_formats::markdown::valid_font_family(typed), + filter: true, + recent: &fonts.recent, + missing: fonts.family_missing, + preview: true, + sections: &fonts.sections, + add_font: Some(crate::tl_id!("ui.add_font")), + usage: "floating-family", + tokens: *t, }, ); + if families.add_font { + // The Add Font row: pick font files, install them, and read the list again. + if let Some(report) = crate::font_install::pick_and_install() + && !report.copied.is_empty() + { + crate::fonts::rescan_in_background(ui.ctx().clone()); + } + } if let Some(name) = families.chosen { + crate::ribbon::remember_family(ui.ctx(), &name); acts.push(Act::FontFamily(name)); picked = true; } @@ -224,7 +247,15 @@ pub fn show_bar(ctx: &Context, id: Id, anchor: Rect, bar: &Bar, t: &Tokens, acts width: 38.0, items: &fonts.sizes, empty_note: None, - accept: &|typed| typed.parse::().is_ok_and(|size| crate::ribbon::FONT_SIZES.contains(&size)), + accept: &|typed| crate::font_picker::size_is_usable(typed, &crate::ribbon::FONT_SIZES), + filter: false, + recent: &[], + missing: false, + preview: false, + sections: &[], + add_font: None, + usage: "floating-size", + tokens: *t, }, ); if let Some(chosen) = size.chosen.and_then(|typed| typed.parse::().ok()) { diff --git a/crates/ui-egui/src/font_install.rs b/crates/ui-egui/src/font_install.rs new file mode 100644 index 00000000..5bdce8d1 --- /dev/null +++ b/crates/ui-egui/src/font_install.rs @@ -0,0 +1,195 @@ +//! Adds font files to the user's own fonts folder, so the family list can show them. Only files +//! with a font extension are copied; anything else is reported and left alone. No egui in here. + +use std::path::{Path, PathBuf}; + +/// The extensions a font file may have. +const FONT_EXTENSIONS: [&str; 4] = ["ttf", "otf", "ttc", "otc"]; + +/// What one install did: the file names copied, and each file skipped with the reason. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Report { + pub copied: Vec, + pub skipped: Vec<(String, String)>, +} + +/// The fonts folder of the current user, where a font can be added without administrator rights. +pub fn user_fonts_dir() -> Option { + #[cfg(target_os = "windows")] + { + std::env::var_os("LOCALAPPDATA").map(|local| PathBuf::from(local).join("Microsoft").join("Windows").join("Fonts")) + } + #[cfg(target_os = "macos")] + { + std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Library").join("Fonts")) + } + #[cfg(target_os = "linux")] + { + std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local").join("share").join("fonts")) + } + #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))] + { + None + } +} + +/// True when the file name ends with a font extension (case does not matter). +pub fn is_font_file(path: &Path) -> bool { + path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| FONT_EXTENSIONS.iter().any(|known| known.eq_ignore_ascii_case(ext))) +} + +/// True when both paths name the same file on disk. A target that does not exist yet is never the +/// same file. +fn same_file(source: &Path, target: &Path) -> bool { + match (std::fs::canonicalize(source), std::fs::canonicalize(target)) { + (Ok(a), Ok(b)) => a == b, + _ => false, + } +} + +/// Copies each font file into `dir`, creating it when needed. A file that is not a font, or that +/// cannot be copied, is skipped and reported with its reason. +pub fn install(files: &[PathBuf], dir: &Path) -> Report { + let mut report = Report::default(); + let name_of = |path: &Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if let Err(error) = std::fs::create_dir_all(dir) { + for file in files { + report.skipped.push((name_of(file), format!("the fonts folder cannot be created: {error}"))); + } + return report; + } + for file in files { + let name = name_of(file); + if !is_font_file(file) { + report.skipped.push((name, "not a font file".to_owned())); + continue; + } + let target = dir.join(&name); + // The file is already in the fonts folder: copying it onto itself would empty it. + if same_file(file, &target) { + report.skipped.push((name, "already in the fonts folder".to_owned())); + continue; + } + // Another font with this name is installed: refuse rather than overwrite it. + if target.exists() { + report.skipped.push((name, "a different font with this name is already installed".to_owned())); + continue; + } + match std::fs::copy(file, &target) { + Ok(_) => report.copied.push(name), + Err(error) => report.skipped.push((name, error.to_string())), + } + } + report +} + +#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))] +/// Asks for font files (several may be picked), installs them in the user's fonts folder, and +/// reports what happened. `None` when the dialog was cancelled. Events and log lines go out here, +/// so every caller records the same things. +pub fn pick_and_install() -> Option { + let picked = rfd::FileDialog::new() + .set_title(crate::tl_id!("ui.add_font_dialog_title")) + .add_filter(crate::tl_id!("ui.font_files_filter").to_string(), &FONT_EXTENSIONS) + .pick_files(); + let Some(files) = picked else { + crate::usage::record(crate::usage::Level::Usage, "font_add_cancelled", &[]); + return None; + }; + let Some(dir) = user_fonts_dir() else { + crate::usage::record(crate::usage::Level::Error, "font_add_no_folder", &[]); + log::error!("Add font: this platform has no user fonts folder"); + return Some(Report { copied: Vec::new(), skipped: files.iter().map(|f| (f.display().to_string(), "no fonts folder".to_owned())).collect() }); + }; + let report = install(&files, &dir); + crate::usage::record( + crate::usage::Level::Usage, + "font_added", + &[("copied", &report.copied.len().to_string()), ("skipped", &report.skipped.len().to_string())], + ); + for (name, reason) in &report.skipped { + crate::usage::record(crate::usage::Level::Warning, "font_add_skipped", &[("reason", reason)]); + log::warn!("Add font: {name} was not added: {reason}"); + } + log::info!("Add font: {} added to {}", report.copied.len(), dir.display()); + Some(report) +} + +#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] +/// Adding fonts needs the file dialog, which only the desktop builds have. +pub fn pick_and_install() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("notecraft-font-install-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + dir + } + + #[test] + fn font_extensions_are_recognised_whatever_their_case() { + assert!(is_font_file(Path::new("A.TTF"))); + assert!(is_font_file(Path::new("b.otf"))); + assert!(is_font_file(Path::new("c.ttc"))); + assert!(!is_font_file(Path::new("notes.md"))); + assert!(!is_font_file(Path::new("noextension"))); + } + + #[test] + fn font_files_are_copied_and_other_files_are_reported() { + let source = scratch("source"); + let target = scratch("target").join("fonts"); + let font = source.join("Demo.ttf"); + let note = source.join("readme.txt"); + std::fs::write(&font, b"font bytes").expect("font"); + std::fs::write(¬e, b"not a font").expect("note"); + + let report = install(&[font, note], &target); + + assert_eq!(report.copied, vec!["Demo.ttf".to_owned()]); + assert_eq!(report.skipped, vec![("readme.txt".to_owned(), "not a font file".to_owned())]); + assert_eq!(std::fs::read(target.join("Demo.ttf")).expect("copied"), b"font bytes"); + } + + #[test] + fn a_font_already_in_the_folder_is_not_emptied() { + let folder = scratch("in-place"); + let font = folder.join("Kept.otf"); + std::fs::write(&font, b"keep these bytes").expect("font"); + + let report = install(std::slice::from_ref(&font), &folder); + + assert!(report.copied.is_empty()); + assert_eq!(report.skipped[0].1, "already in the fonts folder"); + assert_eq!(std::fs::read(&font).expect("still there"), b"keep these bytes"); + } + + #[test] + fn a_different_font_with_the_same_name_is_not_overwritten() { + let source = scratch("clash-source"); + let folder = scratch("clash-target"); + std::fs::write(folder.join("Same.ttf"), b"installed").expect("installed"); + let incoming = source.join("Same.ttf"); + std::fs::write(&incoming, b"incoming").expect("incoming"); + + let report = install(&[incoming], &folder); + + assert!(report.copied.is_empty()); + assert_eq!(std::fs::read(folder.join("Same.ttf")).expect("kept"), b"installed"); + } + + #[test] + fn a_missing_file_is_reported_with_its_reason() { + let target = scratch("missing"); + let report = install(&[PathBuf::from("does-not-exist.otf")], &target); + assert!(report.copied.is_empty()); + assert_eq!(report.skipped.len(), 1); + assert_eq!(report.skipped[0].0, "does-not-exist.otf"); + } +} diff --git a/crates/ui-egui/src/font_picker.rs b/crates/ui-egui/src/font_picker.rs new file mode 100644 index 00000000..fd9c2054 --- /dev/null +++ b/crates/ui-egui/src/font_picker.rs @@ -0,0 +1,218 @@ +//! Logic for the font name and size boxes, with no egui in it, so it can move to a shared library +//! later without changes. Ported from WordCraft's `widgets/combo.rs` (font matching and recents) +//! and its font dialog (size check). Keep this file free of UI types. + +/// The most recent families kept in the Recently Used list. +pub const RECENT_CAP: usize = 8; + +/// Indices of the `items` matching `query`, ignoring case: exact matches, then names starting with +/// it, then names containing it, each group in list order. A blank query matches everything. +/// (WordCraft's ranking; NoteCraft used list order only before this.) +pub fn matches(query: &str, items: &[String]) -> Vec { + let q = query.trim().to_lowercase(); + if q.is_empty() { + return (0..items.len()).collect(); + } + let (mut exact, mut prefix, mut inner) = (Vec::new(), Vec::new(), Vec::new()); + for (i, item) in items.iter().enumerate() { + let name = item.to_lowercase(); + if name == q { + exact.push(i); + } else if name.starts_with(&q) { + prefix.push(i); + } else if name.contains(&q) { + inner.push(i); + } + } + exact.extend(prefix); + exact.extend(inner); + exact +} + +/// Records `name` as the most recently used family: it moves to the front, appears once, and the +/// list keeps at most [`RECENT_CAP`] names. +pub fn remember(recent: &mut Vec, name: &str) { + recent.retain(|n| !n.eq_ignore_ascii_case(name)); + recent.insert(0, name.to_owned()); + recent.truncate(RECENT_CAP); +} + +/// True when `name` is not among the installed families, so the page will show a fallback font. +/// An empty name is not missing; it means "the default". +pub fn is_missing(name: &str, installed: &[String]) -> bool { + let name = name.trim(); + !name.is_empty() && !installed.iter().any(|f| f.eq_ignore_ascii_case(name)) +} + +/// A typed size the page can hold: a finite whole number of points from `sizes`. Text such as +/// "NaN", "inf" or "1.5" is refused, so a non-finite size never reaches the layout. +pub fn size_is_usable(text: &str, sizes: &[u8]) -> bool { + text.trim().parse::().is_ok_and(|size| sizes.contains(&size)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(list: &[&str]) -> Vec { + list.iter().map(|s| (*s).to_owned()).collect() + } + + #[test] + fn a_blank_query_matches_every_family_in_order() { + let items = names(&["Arial", "Georgia", "Verdana"]); + assert_eq!(matches(" ", &items), vec![0, 1, 2]); + } + + #[test] + fn exact_matches_come_first_then_prefixes_then_the_rest() { + let items = names(&["Courier New", "Arial Black", "Arial", "Arial Narrow", "Carial"]); + // "arial": exact "Arial" (2), prefixes "Arial Black" (1) and "Arial Narrow" (3), then + // "Carial" (4) because it only contains the query. + assert_eq!(matches("arial", &items), vec![2, 1, 3, 4]); + } + + #[test] + fn matching_ignores_case_and_surrounding_spaces() { + let items = names(&["Georgia", "Verdana"]); + assert_eq!(matches(" GEOR ", &items), vec![0]); + } + + #[test] + fn a_query_with_no_match_lists_nothing() { + let items = names(&["Arial"]); + assert!(matches("zzz", &items).is_empty()); + } + + #[test] + fn the_last_family_used_comes_first_and_appears_once() { + let mut recent = Vec::new(); + remember(&mut recent, "Arial"); + remember(&mut recent, "Georgia"); + remember(&mut recent, "arial"); + assert_eq!(recent, names(&["arial", "Georgia"])); + } + + #[test] + fn the_recent_list_keeps_only_the_latest_names() { + let mut recent = Vec::new(); + for i in 0..(RECENT_CAP + 3) { + remember(&mut recent, &format!("Font {i}")); + } + assert_eq!(recent.len(), RECENT_CAP); + assert_eq!(recent[0], format!("Font {}", RECENT_CAP + 2)); + } + + #[test] + fn a_family_that_is_not_installed_is_missing_but_the_default_is_not() { + let installed = names(&["Arial", "Georgia"]); + assert!(is_missing("Aptos", &installed)); + assert!(!is_missing("arial", &installed)); + assert!(!is_missing("", &installed)); + } + + #[test] + fn only_whole_sizes_from_the_list_are_usable() { + let sizes = [8u8, 11, 12, 72]; + assert!(size_is_usable(" 12 ", &sizes)); + assert!(!size_is_usable("NaN", &sizes)); + assert!(!size_is_usable("inf", &sizes)); + assert!(!size_is_usable("10.5", &sizes)); + assert!(!size_is_usable("13", &sizes)); + } +} + +/// A script the family list is grouped by. A font belongs under each script whose sample +/// character it draws. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Script { + Latin, + Greek, + Cyrillic, + Arabic, + Hebrew, + Devanagari, + Thai, + Han, + Kana, + Hangul, +} + +impl Script { + /// Every script, in the order the list shows them. + pub const ALL: [Script; 10] = [ + Script::Latin, + Script::Greek, + Script::Cyrillic, + Script::Arabic, + Script::Hebrew, + Script::Devanagari, + Script::Thai, + Script::Han, + Script::Kana, + Script::Hangul, + ]; + + /// One letter a font of this script must draw. + pub fn sample(self) -> char { + match self { + Script::Latin => 'A', + Script::Greek => '\u{03A9}', + Script::Cyrillic => '\u{0416}', + Script::Arabic => '\u{0627}', + Script::Hebrew => '\u{05D0}', + Script::Devanagari => '\u{0915}', + Script::Thai => '\u{0E01}', + Script::Han => '\u{4E2D}', + Script::Kana => '\u{3042}', + Script::Hangul => '\u{D55C}', + } + } +} + +/// The scripts a font covers, judged by whether it draws each script's sample character. +pub fn scripts_of(has_glyph: impl Fn(char) -> bool) -> Vec