mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-02 10:38:15 -06:00
ribbon-w6: net change of 4 commits
- ribbon-w6: written by an agent - ribbon-w6: finished by an agent - ribbon-w6: finished by an agent - ribbon-w6: review fixes (review-1)
This commit is contained in:
@@ -9,6 +9,7 @@ description = "DeckCraft fonts: font database (craft-fonts + system), substitute
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft = { workspace = true, features = ["font-catalog"] }
|
||||
kurbo = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
harfrust = { workspace = true }
|
||||
|
||||
+277
-436
@@ -1,10 +1,10 @@
|
||||
//! Font database: bundled OFL fonts, user fonts, the installed system fonts (cataloged the first
|
||||
//! time a lookup needs them, native only), outline cache.
|
||||
//! Document font shaping and outlines over the shared font catalogue.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use craft::font_catalog::{Catalog, FontEnv, Limits, Os, Source};
|
||||
use kurbo::BezPath;
|
||||
use skrifa::instance::{Location, LocationRef, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
@@ -170,7 +170,7 @@ pub const MISSING_FONT_FAMILY: &str = "Calibri";
|
||||
#[derive(Clone)]
|
||||
enum FontBytes {
|
||||
Static(&'static [u8]),
|
||||
Owned(Arc<Vec<u8>>),
|
||||
Owned(Arc<[u8]>),
|
||||
}
|
||||
|
||||
/// One loaded font face.
|
||||
@@ -279,7 +279,7 @@ impl FontFace {
|
||||
pub fn data(&self) -> &[u8] {
|
||||
match &self.bytes {
|
||||
FontBytes::Static(b) => b,
|
||||
FontBytes::Owned(v) => v.as_slice(),
|
||||
FontBytes::Owned(v) => v,
|
||||
}
|
||||
}
|
||||
pub fn skrifa(&self) -> Option<skrifa::FontRef<'_>> {
|
||||
@@ -357,47 +357,37 @@ impl FontFace {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Debug)]
|
||||
struct CatalogEntry {
|
||||
family: String,
|
||||
style: String,
|
||||
path: std::path::PathBuf,
|
||||
}
|
||||
|
||||
/// Process-wide font database.
|
||||
pub struct FontDb {
|
||||
faces: RwLock<Vec<Arc<FontFace>>>,
|
||||
outlines: Mutex<OutlineCache>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock<Vec<CatalogEntry>>,
|
||||
/// The folders the system font scan reads (the platform's font folders for [`FontDb::global`]).
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
font_dirs: Vec<std::path::PathBuf>,
|
||||
/// Set once the font folders have been scanned. Lookups by family name wait for the first
|
||||
/// scan, so what they find doesn't depend on what ran before them.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
cataloged: std::sync::OnceLock<()>,
|
||||
catalog: Arc<Catalog>,
|
||||
scope: CatalogScope,
|
||||
/// Families (lower case) whose cataloged files have all been loaded: a family's files load
|
||||
/// together, so a lookup never settles for the one face another name loaded ("Segoe UI
|
||||
/// Semibold" loads a face of the family "Segoe UI").
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
loaded_families: Mutex<std::collections::HashSet<String>>,
|
||||
loaded_families: Mutex<(u64, std::collections::HashSet<String>)>,
|
||||
/// System fallback state: enabled, and characters no system font covers.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
sys: Mutex<SysFallback>,
|
||||
/// Held while installed fonts are loaded, so threads that need the same family wait for one
|
||||
/// load instead of racing it: what a lookup finds doesn't depend on which thread got there
|
||||
/// first.
|
||||
/// Serializes broad coverage searches so parallel misses do not repeat file loads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
loading: Mutex<()>,
|
||||
}
|
||||
|
||||
enum CatalogScope {
|
||||
Process,
|
||||
Isolated,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Default)]
|
||||
struct SysFallback {
|
||||
enabled: bool,
|
||||
misses: std::collections::HashSet<char>,
|
||||
plain_misses: std::collections::HashSet<char>,
|
||||
color_misses: std::collections::HashSet<char>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
/// Does face `index` of `data` carry colour glyph tables?
|
||||
@@ -509,212 +499,6 @@ fn instance_legacy_names(family: &str, style: &str) -> Option<(String, String)>
|
||||
Some((format!("{family} {weight}"), if style_italic(style) { "Italic" } else { "Regular" }.into()))
|
||||
}
|
||||
|
||||
/// The tables skrifa reads glyph outlines from: `glyf` (TrueType), `CFF `, `CFF2` and `VARC`. For a
|
||||
/// face with none of them (bitmaps only, or outlines in Apple's `hvgl` table), [`FontDb::outline`]
|
||||
/// returns an empty path for every glyph.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];
|
||||
|
||||
/// (family, style) of every face in the font file at `path`, reading only its table directories
|
||||
/// and `name` tables: a scan opens hundreds of font files, many of them megabytes long. A
|
||||
/// variable font is cataloged under its default style; its named instances appear once it loads.
|
||||
/// Faces with none of the [`OUTLINE_TABLES`] are left out.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_face_names(path: &std::path::Path) -> Vec<(String, String)> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
/// Caps on what a (possibly damaged) file can make the scan read.
|
||||
const MAX_FACES: u32 = 256;
|
||||
const MAX_NAME_TABLE: u32 = 1 << 20;
|
||||
let Ok(mut file) = std::fs::File::open(path) else { return vec![] };
|
||||
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
|
||||
let mut buf = vec![0; len];
|
||||
file.seek(SeekFrom::Start(offset)).ok()?;
|
||||
file.read_exact(&mut buf).ok()?;
|
||||
Some(buf)
|
||||
};
|
||||
let be32 = |b: &[u8], at: usize| b.get(at..at + 4).and_then(|s| s.try_into().ok()).map(u32::from_be_bytes);
|
||||
let Some(head) = read_at(0, 12) else { return vec![] };
|
||||
// A collection lists where each face's table directory starts.
|
||||
let starts: Vec<u32> = if head.starts_with(b"ttcf") {
|
||||
let n = be32(&head, 8).unwrap_or(0).min(MAX_FACES) as usize;
|
||||
read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default()
|
||||
} else {
|
||||
vec![0]
|
||||
};
|
||||
starts
|
||||
.into_iter()
|
||||
.filter_map(|start| {
|
||||
let dir = read_at(start.into(), 12)?;
|
||||
let tables = u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?) as usize;
|
||||
let records = read_at(u64::from(start) + 12, tables * 16)?;
|
||||
if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
|
||||
return None;
|
||||
}
|
||||
let rec = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(b"name"))?;
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);
|
||||
if len > MAX_NAME_TABLE {
|
||||
return None;
|
||||
}
|
||||
let table = read_at(offset.into(), len as usize)?;
|
||||
// A one-table font holding just the `name` table, to read it as the font itself would.
|
||||
let mut font = Vec::with_capacity(28 + table.len());
|
||||
font.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
|
||||
font.extend_from_slice(&[0, 1, 0, 16, 0, 0, 0, 0]);
|
||||
font.extend_from_slice(b"name");
|
||||
for v in [0, 28, len] {
|
||||
font.extend_from_slice(&u32::to_be_bytes(v));
|
||||
}
|
||||
font.extend_from_slice(&table);
|
||||
let f = skrifa::FontRef::new(&font).ok()?;
|
||||
let (family, style) = face_names(&f)?;
|
||||
// Cataloged under its Windows family too, so "Segoe UI Semibold" finds the file.
|
||||
let legacy = legacy_names(&f, &family);
|
||||
Some(std::iter::once((family, style)).chain(legacy))
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Folder depth below a font folder that the system scan descends.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SCAN_DEPTH: usize = 12;
|
||||
/// Directory entries the system scan looks at in all.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SCAN_ENTRIES: usize = 200_000;
|
||||
/// The largest font file read (the biggest CJK collections are a few hundred MB).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const MAX_FONT_FILE: u64 = 512 << 20;
|
||||
|
||||
/// A regular file of a size a font can have.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn font_file_ok(meta: &std::fs::Metadata) -> bool {
|
||||
meta.is_file() && meta.len() > 12 && meta.len() <= MAX_FONT_FILE
|
||||
}
|
||||
|
||||
/// The platform's font folders (the system's and the user's), scanned by [`FontDb::global`].
|
||||
/// Empty on wasm.
|
||||
pub fn system_font_dirs() -> Vec<std::path::PathBuf> {
|
||||
let mut dirs: Vec<std::path::PathBuf> = Vec::new();
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return dirs;
|
||||
}
|
||||
let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
|
||||
if cfg!(target_os = "macos") {
|
||||
dirs.extend(["/System/Library/Fonts", "/Library/Fonts"].map(Into::into));
|
||||
if let Some(h) = &home {
|
||||
dirs.push(h.join("Library/Fonts"));
|
||||
// Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them.
|
||||
dirs.push(h.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts"));
|
||||
}
|
||||
// Fonts Office installs inside its apps.
|
||||
for app in ["Microsoft PowerPoint", "Microsoft Word", "Microsoft Excel"] {
|
||||
dirs.push(std::path::PathBuf::from(format!("/Applications/{app}.app/Contents/Resources/DFonts")));
|
||||
}
|
||||
// Fonts macOS ships as assets (PingFang, Yu Mincho, …): com_apple_MobileAsset_Font<N>.
|
||||
for parent in ["/System/Library/AssetsV2", "/System/Library/AssetsV2/PreinstalledAssetsV2/InstallWithOs"] {
|
||||
let Ok(entries) = std::fs::read_dir(parent) else { continue };
|
||||
for e in entries.flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with("com_apple_MobileAsset_Font") {
|
||||
dirs.push(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if cfg!(windows) {
|
||||
let root = std::env::var_os("WINDIR").map(std::path::PathBuf::from).unwrap_or_else(|| "C:\\Windows".into());
|
||||
dirs.push(root.join("Fonts"));
|
||||
if let Some(l) = std::env::var_os("LOCALAPPDATA") {
|
||||
let l = std::path::PathBuf::from(l);
|
||||
dirs.push(l.join("Microsoft\\Windows\\Fonts"));
|
||||
// Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them;
|
||||
// DeckCraft never ships or needs them.
|
||||
dirs.push(l.join("Microsoft\\FontCache\\4\\CloudFonts"));
|
||||
}
|
||||
} else {
|
||||
dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));
|
||||
if let Some(h) = &home {
|
||||
dirs.push(h.join(".fonts"));
|
||||
dirs.push(h.join(".local/share/fonts"));
|
||||
}
|
||||
let env = |k: &str| std::env::var_os(k).map(|v| v.to_string_lossy().into_owned());
|
||||
dirs.extend(xdg_font_dirs(env("XDG_DATA_HOME").as_deref(), env("XDG_DATA_DIRS").as_deref(), home.as_deref()));
|
||||
// Inside Flatpak the host's fonts are mounted here.
|
||||
dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into));
|
||||
// Folders fontconfig is configured with (NixOS, Guix, custom setups).
|
||||
for conf in fontconfig_files() {
|
||||
if let Ok(text) = std::fs::read_to_string(&conf) {
|
||||
dirs.extend(fontconfig_dirs(&text, env("XDG_DATA_HOME").as_deref(), home.as_deref()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
dirs.retain(|d| seen.insert(d.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
/// `<data dir>/fonts` for `XDG_DATA_HOME` (default `~/.local/share`) and each `XDG_DATA_DIRS`
|
||||
/// entry (default `/usr/local/share:/usr/share`).
|
||||
fn xdg_font_dirs(data_home: Option<&str>, data_dirs: Option<&str>, home: Option<&std::path::Path>) -> Vec<std::path::PathBuf> {
|
||||
let mut v = vec![];
|
||||
match data_home.filter(|d| !d.is_empty()) {
|
||||
Some(d) => v.push(std::path::Path::new(d).join("fonts")),
|
||||
None => {
|
||||
if let Some(h) = home {
|
||||
v.push(h.join(".local/share/fonts"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let dirs = data_dirs.filter(|d| !d.is_empty()).unwrap_or("/usr/local/share:/usr/share");
|
||||
v.extend(dirs.split(':').filter(|d| d.starts_with('/')).take(64).map(|d| std::path::Path::new(d).join("fonts")));
|
||||
v
|
||||
}
|
||||
|
||||
/// The fontconfig configuration files: `/etc/fonts/fonts.conf` and `/etc/fonts/conf.d/*.conf`.
|
||||
fn fontconfig_files() -> Vec<std::path::PathBuf> {
|
||||
let mut v = vec![std::path::PathBuf::from("/etc/fonts/fonts.conf"), std::path::PathBuf::from("/etc/fonts/local.conf")];
|
||||
if let Ok(entries) = std::fs::read_dir("/etc/fonts/conf.d") {
|
||||
let mut files: Vec<_> = entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "conf")).collect();
|
||||
files.sort();
|
||||
files.truncate(512);
|
||||
v.extend(files);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The `<dir>` folders of a fontconfig file (`prefix="xdg"` is under `XDG_DATA_HOME`, a leading
|
||||
/// `~` under home; relative and `cachedir` entries are skipped).
|
||||
fn fontconfig_dirs(text: &str, data_home: Option<&str>, home: Option<&std::path::Path>) -> Vec<std::path::PathBuf> {
|
||||
let mut v = vec![];
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find("<dir") {
|
||||
let after = &rest[start + 4..];
|
||||
// `<dir>` or `<dir …>`, not `<dirname>`.
|
||||
if !(after.starts_with('>') || after.starts_with(' ')) {
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
let Some(gt) = after.find('>') else { break };
|
||||
let attrs = &after[..gt];
|
||||
let body = &after[gt + 1..];
|
||||
let Some(end) = body.find("</dir>") else { break };
|
||||
let path = body[..end].trim();
|
||||
rest = &body[end..];
|
||||
if attrs.trim_end().ends_with('/') || path.is_empty() || v.len() >= 64 {
|
||||
continue;
|
||||
}
|
||||
let p = if attrs.contains("prefix=\"xdg\"") {
|
||||
let base = data_home.filter(|d| !d.is_empty()).map(std::path::PathBuf::from).or_else(|| home.map(|h| h.join(".local/share")));
|
||||
base.map(|b| b.join(path))
|
||||
} else if let Some(r) = path.strip_prefix("~/") {
|
||||
home.map(|h| h.join(r))
|
||||
} else if path.starts_with('/') {
|
||||
Some(std::path::PathBuf::from(path))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
v.extend(p);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// One face found in a font file: index, family, style and (variable fonts) the named instance's
|
||||
/// axis settings.
|
||||
@@ -832,7 +616,7 @@ fn line_split(f: &skrifa::FontRef, ascent: f64, descent: f64, upem: f64) -> f64
|
||||
fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords: Vec<([u8; 4], f32)>) -> Option<FontFace> {
|
||||
let data: &[u8] = match &bytes {
|
||||
FontBytes::Static(b) => b,
|
||||
FontBytes::Owned(v) => v.as_slice(),
|
||||
FontBytes::Owned(v) => v,
|
||||
};
|
||||
let f = skrifa::FontRef::from_index(data, index).ok()?;
|
||||
let settings: Vec<(skrifa::Tag, f32)> = coords.iter().map(|(t, v)| (skrifa::Tag::new(t), *v)).collect();
|
||||
@@ -936,12 +720,20 @@ fn style_italic(style: &str) -> bool {
|
||||
}
|
||||
|
||||
impl FontDb {
|
||||
/// A database holding the bundled fonts, then the craft-fonts Japanese faces (Mincho first,
|
||||
/// so they are the fallback for Japanese text after the requested and bundled fonts; empty
|
||||
/// without `CRAFT_FONTS_DIR`), whose system font scan reads `font_dirs`.
|
||||
/// An isolated database of bundled fonts and fonts discovered only in `font_dirs`.
|
||||
/// Neither platform services nor the process catalogue contribute fixture fonts.
|
||||
pub fn with_font_dirs(font_dirs: Vec<std::path::PathBuf>) -> Self {
|
||||
let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
catalog.set_app_dirs(font_dirs.clone());
|
||||
catalog.set_confined_dirs(font_dirs);
|
||||
Self::with_catalog(catalog, CatalogScope::Isolated)
|
||||
}
|
||||
|
||||
fn with_catalog(catalog: Arc<Catalog>, scope: CatalogScope) -> Self {
|
||||
let mut faces = Vec::new();
|
||||
for data in bundled() {
|
||||
// Registration also makes the bundled faces available to the browser's picker.
|
||||
let _ = catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default());
|
||||
for (i, family, style, coords) in enumerate_faces(data) {
|
||||
if let Some(f) = make_face(FontBytes::Static(data), i, family, style, coords) {
|
||||
faces.push(Arc::new(f));
|
||||
@@ -951,13 +743,9 @@ impl FontDb {
|
||||
Self {
|
||||
faces: RwLock::new(faces),
|
||||
outlines: Mutex::new(OutlineCache::default()),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock::new(Vec::new()),
|
||||
font_dirs,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
cataloged: std::sync::OnceLock::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
loaded_families: Mutex::new(std::collections::HashSet::new()),
|
||||
catalog,
|
||||
scope,
|
||||
loaded_families: Mutex::new((0, std::collections::HashSet::new())),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
sys: Mutex::new(SysFallback { enabled: true, ..Default::default() }),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -987,30 +775,20 @@ impl FontDb {
|
||||
false
|
||||
}
|
||||
|
||||
/// Process-wide database: the bundled fonts, then the installed system fonts, cataloged the
|
||||
/// first time a lookup by family name needs them (or ahead of time by
|
||||
/// [`FontDb::scan_in_background`]).
|
||||
/// The document adapter over the same process catalogue used by the font picker.
|
||||
pub fn global() -> &'static FontDb {
|
||||
static DB: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
|
||||
DB.get_or_init(|| FontDb::with_font_dirs(system_font_dirs()))
|
||||
DB.get_or_init(|| FontDb::with_catalog(Catalog::global().clone(), CatalogScope::Process))
|
||||
}
|
||||
|
||||
pub(crate) fn read_faces(&self) -> std::sync::RwLockReadGuard<'_, Vec<Arc<FontFace>>> {
|
||||
self.faces.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The system font catalog, scanned first if it hasn't been yet.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_catalog(&self) -> std::sync::RwLockReadGuard<'_, Vec<CatalogEntry>> {
|
||||
self.ensure_catalog();
|
||||
self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Family names available (loaded plus cataloged system fonts), sorted and deduplicated.
|
||||
pub fn families(&self) -> Vec<String> {
|
||||
let mut v: Vec<String> = self.read_faces().iter().map(|f| f.family.clone()).collect();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
v.extend(self.read_catalog().iter().map(|c| c.family.clone()));
|
||||
v.extend(self.catalog.families().iter().cloned());
|
||||
v.sort_by_key(|a| a.to_lowercase());
|
||||
v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
|
||||
v
|
||||
@@ -1024,10 +802,9 @@ impl FontDb {
|
||||
.filter(|f| f.family.eq_ignore_ascii_case(family) && !f.style.contains('{'))
|
||||
.map(|f| (f.italic, f.weight, f.style.clone()))
|
||||
.collect();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
for c in self.read_catalog().iter() {
|
||||
if c.family.eq_ignore_ascii_case(family) && !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) {
|
||||
v.push((style_italic(&c.style), style_weight(&c.style), c.style.clone()));
|
||||
for c in self.catalog.styles(family) {
|
||||
if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) {
|
||||
v.push((c.italic, c.weight, c.style));
|
||||
}
|
||||
}
|
||||
v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2)));
|
||||
@@ -1038,7 +815,11 @@ impl FontDb {
|
||||
/// Add a user font (TTF/OTF/TTC bytes). Returns the number of faces added (0 if unparseable or
|
||||
/// every face was already present).
|
||||
pub fn add_font(&self, bytes: Vec<u8>) -> usize {
|
||||
self.add_fonts(vec![bytes])
|
||||
let added = self.add_fonts(vec![bytes.clone()]);
|
||||
if added > 0 {
|
||||
let _ = self.catalog.add_bytes(bytes, Source::User, &Limits::default());
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
/// Add font files together: lookups see all of their faces or none, never part of a family.
|
||||
@@ -1049,7 +830,7 @@ impl FontDb {
|
||||
};
|
||||
let mut new = Vec::new();
|
||||
for bytes in files {
|
||||
let data = Arc::new(bytes);
|
||||
let data: Arc<[u8]> = bytes.into();
|
||||
for (i, family, style, coords) in enumerate_faces(&data) {
|
||||
if present(&self.read_faces(), &family, &style) {
|
||||
continue;
|
||||
@@ -1071,110 +852,71 @@ impl FontDb {
|
||||
added
|
||||
}
|
||||
|
||||
/// Catalog the installed fonts unless that has been done: the first caller scans the font
|
||||
/// folders, any other waits for that scan to finish.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ensure_catalog(&self) {
|
||||
self.cataloged.get_or_init(|| {
|
||||
self.scan_font_dirs();
|
||||
});
|
||||
}
|
||||
|
||||
/// Catalog the installed fonts on a background thread, so the first lookup by family name
|
||||
/// (opening a file, the font menus) doesn't wait for the scan. A no-op once they are
|
||||
/// cataloged, and on wasm.
|
||||
/// Starts the catalogue's shared background discovery.
|
||||
pub fn scan_in_background(&'static self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.cataloged.get().is_none() {
|
||||
// A failed spawn leaves the scan to the first lookup that needs it.
|
||||
let _ = std::thread::Builder::new().name("font-scan".into()).spawn(move || self.ensure_catalog());
|
||||
}
|
||||
self.catalog.scan_in_background();
|
||||
}
|
||||
|
||||
/// Scan the font folders again (fonts installed or removed since), cataloging the faces
|
||||
/// found (native only). Font data is loaded when a cataloged family is first resolved.
|
||||
/// Refresh the shared discovery lifecycle, or only this database's isolated catalogue.
|
||||
/// Font data is loaded when a catalogued family is first resolved.
|
||||
/// Returns the number of faces cataloged.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_system_fonts(&self) -> usize {
|
||||
// Families load again from the new catalog when next looked up.
|
||||
self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
// The first scan, or a rescan once it is done (never both at once).
|
||||
let mut first = None;
|
||||
self.cataloged.get_or_init(|| first = Some(self.scan_font_dirs()));
|
||||
first.unwrap_or_else(|| self.scan_font_dirs())
|
||||
let count = match self.scope {
|
||||
CatalogScope::Process => {
|
||||
craft::font_catalog::app::rescan_now();
|
||||
self.catalog.faces().len()
|
||||
}
|
||||
CatalogScope::Isolated => self.catalog.rescan(),
|
||||
};
|
||||
self.invalidate_catalog();
|
||||
count
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scan_font_dirs(&self) -> usize {
|
||||
let mut found = Vec::new();
|
||||
let mut stack: Vec<(std::path::PathBuf, usize)> = self.font_dirs.iter().map(|d| (d.clone(), 0)).collect();
|
||||
// Each folder once, however links lead back to it.
|
||||
let mut visited = std::collections::HashSet::new();
|
||||
let mut entries = 0usize;
|
||||
while let Some((d, depth)) = stack.pop() {
|
||||
if !visited.insert(std::fs::canonicalize(&d).unwrap_or_else(|_| d.clone())) {
|
||||
continue;
|
||||
}
|
||||
let Ok(rd) = std::fs::read_dir(&d) else { continue };
|
||||
for e in rd.flatten() {
|
||||
// A link to `/` or a vast tree mustn't turn start-up into a disk crawl.
|
||||
entries += 1;
|
||||
if entries > MAX_SCAN_ENTRIES {
|
||||
log::warn!("font scan stopped after {MAX_SCAN_ENTRIES} entries");
|
||||
stack.clear();
|
||||
break;
|
||||
}
|
||||
let p = e.path();
|
||||
// Follows links: what matters is what the entry leads to.
|
||||
let Ok(meta) = std::fs::metadata(&p) else { continue };
|
||||
if meta.is_dir() {
|
||||
if depth < MAX_SCAN_DEPTH {
|
||||
stack.push((p, depth + 1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let ext = p.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase);
|
||||
if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {
|
||||
continue;
|
||||
}
|
||||
// Only regular files: opening a FIFO named like a font blocks until something
|
||||
// writes to it (start-up hung), and a device never ends.
|
||||
if !font_file_ok(&meta) {
|
||||
continue;
|
||||
}
|
||||
for (family, style) in file_face_names(&p) {
|
||||
found.push(CatalogEntry { family, style, path: p.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = found.len();
|
||||
log::debug!("cataloged {n} system font faces");
|
||||
*self.catalog.write().unwrap_or_else(std::sync::PoisonError::into_inner) = found;
|
||||
n
|
||||
/// Invalidates derived family lookups and coverage misses after catalogue changes.
|
||||
pub fn invalidate_catalog(&self) {
|
||||
*self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = (self.catalog.generation(), std::collections::HashSet::new());
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.refresh_misses(true);
|
||||
}
|
||||
|
||||
/// Load the files of the installed `family` (faces already loaded are kept). Returns whether
|
||||
/// it is loaded.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_cataloged(&self, family: &str) -> bool {
|
||||
let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
self.load_family(family, &loading)
|
||||
let loaded = self.catalog.load_family(family);
|
||||
for face in loaded.iter() {
|
||||
self.add_catalog_face(&face.info, &face.data);
|
||||
}
|
||||
self.is_loaded(family)
|
||||
}
|
||||
|
||||
/// [`FontDb::load_cataloged`] for a caller already holding `loading`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_family(&self, family: &str, _loading: &std::sync::MutexGuard<'_, ()>) -> bool {
|
||||
// Not skipped when some face of the family is loaded: a lookup by a Windows family name
|
||||
// loads only that style's file, and the family's other files must still load later.
|
||||
let paths: Vec<std::path::PathBuf> = {
|
||||
let cat = self.read_catalog();
|
||||
let mut p: Vec<_> = cat.iter().filter(|c| c.family.eq_ignore_ascii_case(family)).map(|c| c.path.clone()).collect();
|
||||
p.sort();
|
||||
p.dedup();
|
||||
p
|
||||
fn add_catalog_face(&self, info: &craft::font_catalog::FaceInfo, data: &craft::font_catalog::FontData) {
|
||||
let present = |faces: &[Arc<FontFace>]| {
|
||||
faces.iter().any(|f| f.family.eq_ignore_ascii_case(&info.family) && f.style.eq_ignore_ascii_case(&info.style))
|
||||
};
|
||||
self.add_fonts(paths.iter().filter(|p| std::fs::metadata(p).is_ok_and(|m| font_file_ok(&m))).filter_map(|p| std::fs::read(p).ok()).collect());
|
||||
self.is_loaded(family)
|
||||
if present(&self.read_faces()) {
|
||||
return;
|
||||
}
|
||||
let Some(face) =
|
||||
make_face(FontBytes::Owned(data.bytes.clone()), data.index, info.family.clone(), info.style.clone(), info.variations.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !present(&faces) {
|
||||
faces.push(Arc::new(face));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn refresh_misses(&self, force: bool) {
|
||||
let generation = self.catalog.generation();
|
||||
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if force || sys.generation != generation {
|
||||
sys.generation = generation;
|
||||
sys.misses.clear();
|
||||
sys.plain_misses.clear();
|
||||
sys.color_misses.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a family + style to a face, falling back to the closest style of the family, then to
|
||||
@@ -1223,16 +965,24 @@ impl FontDb {
|
||||
// Every installed file of the family first, so the best style is among the candidates. The
|
||||
// lock is held while the files load, so another thread looking up the family waits for
|
||||
// them rather than finding none and falling back to another family.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let mut loaded = self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// Snapshot discovery before recording its generation, including the first lazy scan.
|
||||
let _ = self.catalog.families();
|
||||
let generation = self.catalog.generation();
|
||||
if loaded.0 != generation {
|
||||
*loaded = (generation, std::collections::HashSet::new());
|
||||
}
|
||||
let key = family.to_lowercase();
|
||||
if !loaded.contains(&key) {
|
||||
if !loaded.1.contains(&key) {
|
||||
self.load_cataloged(family);
|
||||
loaded.insert(key);
|
||||
loaded.1.insert(key);
|
||||
}
|
||||
}
|
||||
self.find(family, style)
|
||||
self.find(family, style).or_else(|| {
|
||||
let (info, _) = self.catalog.resolve(family, base_style(style))?;
|
||||
self.find(&info.family, if style.contains('{') { style } else { &info.style })
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `family` available (loaded, or installed on the system)?
|
||||
@@ -1240,11 +990,7 @@ impl FontDb {
|
||||
if self.is_loaded(family) {
|
||||
return true;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.read_catalog().iter().any(|c| c.family.eq_ignore_ascii_case(family)) {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
self.catalog.family(family).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn is_loaded(&self, family: &str) -> bool {
|
||||
@@ -1394,6 +1140,8 @@ impl FontDb {
|
||||
if c.is_control() || c.is_whitespace() {
|
||||
return false;
|
||||
}
|
||||
let cataloged = self.catalog.families();
|
||||
self.refresh_misses(false);
|
||||
let seen = self.read_faces().len();
|
||||
{
|
||||
let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
@@ -1402,8 +1150,7 @@ impl FontDb {
|
||||
}
|
||||
}
|
||||
let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c) && accept(f));
|
||||
let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();
|
||||
let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let _loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// Another thread may have loaded a face for `c` (faces are only ever added), or found
|
||||
// there is none, while this one waited.
|
||||
if self.read_faces().len() != seen && covered(self) {
|
||||
@@ -1414,26 +1161,14 @@ impl FontDb {
|
||||
}
|
||||
for fam in SYSTEM_FALLBACKS {
|
||||
if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) {
|
||||
self.load_family(fam, &loading);
|
||||
self.load_cataloged(fam);
|
||||
if covered(self) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut paths: Vec<std::path::PathBuf> =
|
||||
self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().map(|e| e.path.clone()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = std::fs::read(&p) else { continue };
|
||||
let hit =
|
||||
enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));
|
||||
if hit && self.add_font(data) > 0 && covered(self) {
|
||||
return true;
|
||||
}
|
||||
if self.load_covering(c, 40 << 20, accept) {
|
||||
return true;
|
||||
}
|
||||
if remember_miss {
|
||||
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).misses.insert(c);
|
||||
@@ -1484,8 +1219,7 @@ impl FontDb {
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let cataloged: Vec<String> =
|
||||
if self.system_fallback_enabled() { self.read_catalog().iter().map(|e| e.family.clone()).collect() } else { Vec::new() };
|
||||
let cataloged = if self.system_fallback_enabled() { self.catalog.families().to_vec() } else { Vec::new() };
|
||||
for fam in SYSTEM_FALLBACKS.iter().filter(|f| f.contains("Symbol")) {
|
||||
if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) {
|
||||
self.load_cataloged(fam);
|
||||
@@ -1506,67 +1240,67 @@ impl FontDb {
|
||||
/// Load an installed font without colour tables covering `c`. True if one was loaded.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_plain_fallback(&self, c: char) -> bool {
|
||||
static MISSES: Mutex<Option<std::collections::HashSet<char>>> = Mutex::new(None);
|
||||
if c.is_control() || c.is_whitespace() {
|
||||
return false;
|
||||
}
|
||||
if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled {
|
||||
return false;
|
||||
}
|
||||
if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) {
|
||||
return false;
|
||||
}
|
||||
let mut paths: Vec<std::path::PathBuf> = self.read_catalog().iter().map(|e| e.path.clone()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = std::fs::read(&p) else { continue };
|
||||
let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| {
|
||||
!has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())
|
||||
});
|
||||
if hit && self.add_font(data) > 0 {
|
||||
return true;
|
||||
let _ = self.catalog.families();
|
||||
self.refresh_misses(false);
|
||||
{
|
||||
let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !sys.enabled || sys.plain_misses.contains(&c) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c);
|
||||
if self.load_covering(c, 40 << 20, &|f| !f.is_color()) {
|
||||
return true;
|
||||
}
|
||||
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).plain_misses.insert(c);
|
||||
false
|
||||
}
|
||||
|
||||
/// Load an installed colour font covering `c`. True if one was loaded.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_color_fallback(&self, c: char) -> bool {
|
||||
static MISSES: Mutex<Option<std::collections::HashSet<char>>> = Mutex::new(None);
|
||||
if c.is_control() || c.is_whitespace() {
|
||||
return false;
|
||||
}
|
||||
let _ = self.catalog.families();
|
||||
self.refresh_misses(false);
|
||||
{
|
||||
let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !sys.enabled {
|
||||
if !sys.enabled || sys.color_misses.contains(&c) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) {
|
||||
return false;
|
||||
if self.load_covering(c, 64 << 20, &FontFace::is_color) {
|
||||
return true;
|
||||
}
|
||||
let mut paths: Vec<std::path::PathBuf> = self.read_catalog().iter().map(|e| e.path.clone()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
if std::fs::metadata(&p).map(|m| m.len() > 64 << 20).unwrap_or(true) {
|
||||
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).color_misses.insert(c);
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_covering(&self, c: char, max_bytes: u64, accept: &impl Fn(&FontFace) -> bool) -> bool {
|
||||
let faces = self.catalog.faces();
|
||||
let mut candidates: Vec<_> = faces.iter().collect();
|
||||
candidates.sort_by(|a, b| a.path.cmp(&b.path).then(a.index.cmp(&b.index)));
|
||||
// Keep one file alive between adjacent faces so the catalogue's weak byte cache shares
|
||||
// a collection or variable font's data instead of reading it once per named instance.
|
||||
let mut previous_bytes = None;
|
||||
for info in candidates {
|
||||
if info.file_bytes.is_some_and(|size| size > max_bytes) {
|
||||
continue;
|
||||
}
|
||||
let Ok(data) = std::fs::read(&p) else { continue };
|
||||
let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| {
|
||||
has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())
|
||||
});
|
||||
if hit && self.add_font(data) > 0 {
|
||||
let Ok(data) = self.catalog.load(info) else { continue };
|
||||
let _ = previous_bytes.replace(data.bytes.clone());
|
||||
if !skrifa::FontRef::from_index(&data.bytes, data.index).is_ok_and(|font| font.charmap().map(c).is_some()) {
|
||||
continue;
|
||||
}
|
||||
self.add_catalog_face(info, &data);
|
||||
if self.read_faces().iter().any(|face| face.covers(c) && accept(face)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c);
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1645,10 +1379,65 @@ impl OutlinePen for FlipPen {
|
||||
|
||||
#[cfg(test)]
|
||||
mod font_dir_tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn assert_fixture_discovered_after_rescan(env: FontEnv, directory: &Path) {
|
||||
let catalog = Arc::new(Catalog::new(env.clone()).with_font_service(false));
|
||||
catalog.set_confined_dirs(vec![env.root]);
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
assert!(!db.has_family("DeckCraft Legacy"));
|
||||
let missing = db.face("DeckCraft Legacy", "Regular");
|
||||
std::fs::create_dir_all(directory).unwrap();
|
||||
let file = directory.join("regular.ttf");
|
||||
std::fs::write(&file, include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap();
|
||||
db.load_system_fonts();
|
||||
let (info, _) = catalog.resolve("DeckCraft Legacy", "Regular").unwrap();
|
||||
assert!(db.families().contains(&info.family));
|
||||
let face = db.face(&info.family, &info.style);
|
||||
assert_ne!(face.family, missing.family);
|
||||
assert_eq!(face.family, info.family);
|
||||
assert_eq!(face.style, info.style);
|
||||
assert!(face.covers('A'));
|
||||
assert!(!db.outline(&face, face.glyph_for('A')).elements().is_empty());
|
||||
let loaded = db.read_faces().len();
|
||||
db.load_system_fonts();
|
||||
assert_eq!(db.face(&info.family, &info.style).id(), face.id());
|
||||
assert_eq!(db.read_faces().len(), loaded);
|
||||
std::fs::remove_file(file).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_font_registration_is_shared_with_the_adapter_catalogue_and_is_idempotent() {
|
||||
let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
let bytes = include_bytes!("../tests/fixtures/legacy-semibold.ttf");
|
||||
assert!(catalog.family("DeckCraft Legacy Semibold").is_none());
|
||||
assert!(db.add_font(bytes.to_vec()) > 0);
|
||||
let (info, _) = catalog.resolve("DeckCraft Legacy Semibold", "Regular").unwrap();
|
||||
let face = db.face("DeckCraft Legacy Semibold", "Regular");
|
||||
assert_eq!(face.family, info.family);
|
||||
assert_eq!(face.style, info.style);
|
||||
let before = catalog.faces().len();
|
||||
assert_eq!(db.add_font(bytes.to_vec()), 0);
|
||||
assert_eq!(catalog.faces().len(), before);
|
||||
assert_eq!(db.face(&info.family, &info.style).id(), face.id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalogue_added_bytes_resolve_without_a_directory_scan() {
|
||||
let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
let family = "DeckCraft Legacy";
|
||||
let missing = db.face(family, "Regular");
|
||||
let infos = catalog.add_bytes(include_bytes!("../tests/fixtures/legacy-regular.ttf").to_vec(), Source::User, &Limits::default()).unwrap();
|
||||
let resolved = db.face(family, "Regular");
|
||||
assert_ne!(resolved.family, missing.family);
|
||||
assert!(infos.iter().any(|info| info.family == resolved.family && info.style == resolved.style));
|
||||
assert!(resolved.covers('A'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_collection_offsets_do_not_consume_face_cap() {
|
||||
let mut entries = vec![(0, 7); MAX_COLLECTION_FACES as usize];
|
||||
@@ -1718,13 +1507,24 @@ mod font_dir_tests {
|
||||
|
||||
#[test]
|
||||
fn xdg_data_dirs_contribute_their_fonts_folders() {
|
||||
let home = Path::new("/home/ann");
|
||||
assert_eq!(
|
||||
xdg_font_dirs(None, None, Some(home)),
|
||||
[home.join(".local/share/fonts"), "/usr/local/share/fonts".into(), "/usr/share/fonts".into()]
|
||||
);
|
||||
let v = xdg_font_dirs(Some("/data/ann"), Some("/nix/profile/share:relative:/var/lib/flatpak/exports/share"), Some(home));
|
||||
assert_eq!(v, [PathBuf::from("/data/ann/fonts"), "/nix/profile/share/fonts".into(), "/var/lib/flatpak/exports/share/fonts".into()]);
|
||||
let root = std::env::temp_dir().join(format!("deckcraft-fonts-xdg-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let home = root.join("home/ann");
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), home: Some(home.clone()), ..FontEnv::default() };
|
||||
for directory in [home.join(".local/share/fonts"), root.join("usr/local/share/fonts"), root.join("usr/share/fonts")] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &directory);
|
||||
}
|
||||
let data_home = root.join("data/ann");
|
||||
let env = FontEnv {
|
||||
xdg_data_home: Some(data_home.clone()),
|
||||
xdg_data_dirs: Some(std::env::join_paths(["/nix/profile/share", "relative", "/var/lib/flatpak/exports/share"]).unwrap()),
|
||||
..env
|
||||
};
|
||||
for directory in [data_home.join("fonts"), root.join("nix/profile/share/fonts"), root.join("var/lib/flatpak/exports/share/fonts")] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &directory);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1739,23 +1539,64 @@ mod font_dir_tests {
|
||||
<dirname>ignored</dirname>
|
||||
<dir>/nix/store/abc-fonts/share/fonts</dir>
|
||||
</fontconfig>"#;
|
||||
let home = Path::new("/home/ann");
|
||||
let v = fontconfig_dirs(conf, None, Some(home));
|
||||
assert_eq!(
|
||||
v,
|
||||
[PathBuf::from("/usr/share/fonts"), home.join(".local/share/fonts"), home.join(".fonts"), "/nix/store/abc-fonts/share/fonts".into()]
|
||||
);
|
||||
assert!(fontconfig_dirs("<dir>/never closed", None, Some(home)).is_empty());
|
||||
let root = std::env::temp_dir().join(format!("deckcraft-fontconfig-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let home = root.join("home/ann");
|
||||
let file = root.join("fonts.conf");
|
||||
std::fs::write(&file, conf).unwrap();
|
||||
let env = FontEnv {
|
||||
os: Os::Unix,
|
||||
root: root.clone(),
|
||||
home: Some(home.clone()),
|
||||
fontconfig_file: Some(file.clone()),
|
||||
..FontEnv::default()
|
||||
};
|
||||
for directory in [
|
||||
root.join("usr/share/fonts"),
|
||||
home.join(".local/share/fonts"),
|
||||
home.join(".fonts"),
|
||||
root.join("relative/fonts"),
|
||||
root.join("nix/store/abc-fonts/share/fonts"),
|
||||
] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &directory);
|
||||
}
|
||||
std::fs::write(&file, "<dir>/never closed").unwrap();
|
||||
let relative = root.join("relative/fonts");
|
||||
std::fs::write(relative.join("regular.ttf"), include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap();
|
||||
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
|
||||
catalog.set_confined_dirs(vec![root.clone()]);
|
||||
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
|
||||
assert!(!db.has_family("DeckCraft Legacy"));
|
||||
let missing = db.face("DeckCraft Legacy", "Regular");
|
||||
std::fs::write(&file, conf).unwrap();
|
||||
db.load_system_fonts();
|
||||
let (info, _) = catalog.resolve("DeckCraft Legacy", "Regular").unwrap();
|
||||
let face = db.face(&info.family, &info.style);
|
||||
assert_ne!(face.family, missing.family);
|
||||
assert_eq!(face.family, info.family);
|
||||
assert_eq!(face.style, info.style);
|
||||
assert!(face.covers('A'));
|
||||
assert!(!db.outline(&face, face.glyph_for('A')).elements().is_empty());
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn linux_dirs_include_flatpak_host_fonts_without_duplicates() {
|
||||
let d = system_font_dirs();
|
||||
assert!(d.contains(&PathBuf::from("/run/host/user-fonts")));
|
||||
let mut u = d.clone();
|
||||
u.sort();
|
||||
u.dedup();
|
||||
assert_eq!(u.len(), d.len());
|
||||
let root = std::env::temp_dir().join(format!("deckcraft-fonts-flatpak-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let file = root.join("fonts.conf");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"<fontconfig><dir>/run/host/user-fonts</dir><dir>/run/host/user-fonts</dir></fontconfig>",
|
||||
)
|
||||
.unwrap();
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), flatpak: true, fontconfig_file: Some(file), ..FontEnv::default() };
|
||||
for directory in ["run/host/fonts", "run/host/local-fonts", "run/host/user-fonts"] {
|
||||
assert_fixture_discovered_after_rescan(env.clone(), &root.join(directory));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +111,31 @@ fn concurrent_lookups_all_find_an_installed_family() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn catalog_rescan_discovers_new_families_and_retries_missing_styles() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-fonts-rescan-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let isolated = FontDb::with_font_dirs(Vec::new());
|
||||
assert!(!db.has_family("DeckCraft Legacy"));
|
||||
let missing = db.face("DeckCraft Legacy", "Semibold");
|
||||
std::fs::write(dir.join("regular.ttf"), include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap();
|
||||
db.load_system_fonts();
|
||||
assert!(db.families().iter().any(|family| family == "DeckCraft Legacy"));
|
||||
let regular = db.face("DeckCraft Legacy", "Semibold");
|
||||
assert_ne!(regular.family, missing.family);
|
||||
assert!(!isolated.has_family(®ular.family));
|
||||
std::fs::write(dir.join("semibold.ttf"), include_bytes!("../tests/fixtures/legacy-semibold.ttf")).unwrap();
|
||||
db.load_system_fonts();
|
||||
let semibold = db.face("DeckCraft Legacy", "Semibold");
|
||||
assert_eq!(semibold.family, regular.family);
|
||||
assert!(semibold.weight > regular.weight);
|
||||
assert_ne!(semibold.id(), regular.id());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_family_names_find_their_faces() {
|
||||
// Documents name fonts by their Windows family ("Segoe UI Semibold"); the font's
|
||||
@@ -410,7 +435,8 @@ fn the_font_scan_skips_fifos_folders_and_link_loops() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("sub")).unwrap();
|
||||
std::fs::copy(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/legacy-semibold.ttf"), dir.join("sub/real.ttf")).unwrap();
|
||||
let fifo = std::process::Command::new("mkfifo").arg(dir.join("trap.ttf")).status().is_ok_and(|s| s.success());
|
||||
// Hosts without mkfifo still exercise the other hostile directory entries.
|
||||
let _ = std::process::Command::new("mkfifo").arg(dir.join("trap.ttf")).status();
|
||||
std::fs::create_dir(dir.join("folder.ttf")).unwrap();
|
||||
std::fs::write(dir.join("empty.otf"), b"").unwrap();
|
||||
std::os::unix::fs::symlink(&dir, dir.join("sub/loop")).unwrap();
|
||||
@@ -418,11 +444,16 @@ fn the_font_scan_skips_fifos_folders_and_link_loops() {
|
||||
let scan_dir = dir.clone();
|
||||
std::thread::spawn(move || {
|
||||
let db = FontDb::with_font_dirs(vec![scan_dir]);
|
||||
let _ = tx.send(db.load_system_fonts());
|
||||
db.load_system_fonts();
|
||||
// Bundled faces also belong to the catalogue, so its size cannot prove discovery.
|
||||
let found = db.has_family("DeckCraft Legacy Semibold");
|
||||
let face = db.face("DeckCraft Legacy Semibold", "Regular");
|
||||
let drawable = face.covers('A') && !db.outline(&face, face.glyph_for('A')).elements().is_empty();
|
||||
let _ = tx.send((found, drawable));
|
||||
});
|
||||
let n = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the font scan hung");
|
||||
assert!(n >= 1, "the real font was found");
|
||||
assert!(fifo || n >= 1);
|
||||
let (found, drawable) = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the font scan hung");
|
||||
assert!(found, "the real font was found");
|
||||
assert!(drawable, "the discovered face supplies a drawable glyph");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
/// Returns the shared font catalogue.
|
||||
#[allow(dead_code)] // P3(ribbon-w6): rb.A18
|
||||
pub fn catalog() -> &'static std::sync::Arc<craft::font_catalog::Catalog> {
|
||||
todo!("rb.A18")
|
||||
craft::font_catalog::Catalog::global()
|
||||
}
|
||||
|
||||
/// Returns the presentation theme font rows.
|
||||
#[allow(dead_code)] // P3(ribbon-w6): rb.A18
|
||||
pub fn theme_font_rows(app: &crate::SlideApp) -> Vec<craft::font_manager::picker::HostFontRow> {
|
||||
let _ = app;
|
||||
todo!("rb.A18")
|
||||
use craft::font_manager::picker::HostFontRow;
|
||||
|
||||
let Some(master) = app.session.active().and_then(|state| state.doc.masters.first()) else { return Vec::new() };
|
||||
// The key is the family the engine accepts; the role belongs only to its display label.
|
||||
[(&master.theme.fonts.major.latin, "Headings"), (&master.theme.fonts.minor.latin, "Body")]
|
||||
.into_iter()
|
||||
.map(|(family, role)| HostFontRow::face(family.clone(), format!("{family} ({role})"), None))
|
||||
.collect()
|
||||
}
|
||||
|
||||
+456
-479
@@ -1,517 +1,494 @@
|
||||
// P3(ribbon-w6): rb.A16
|
||||
//! Home ribbon controls over the registered command surface.
|
||||
|
||||
use craft::font_manager::picker::{FontPicker, FontPickerKind, HostFontGroup};
|
||||
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
|
||||
use craft::ui::buttons::{Arrangement, Button, IconButton, PopupMark, SplitButton, SplitMenu, ToggleButton};
|
||||
use craft::ui::contract::{Bind, Entry, Gap, PopupKind, Props, Show, ShowContainer, TooltipSpec, Trigger};
|
||||
use craft::ui::controls::disclosure::DisclosureGlyph;
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::primitives::{IconMark, IconSpec};
|
||||
use craft::ui::runtime::commands::{self, CommandRef};
|
||||
use craft::ui::runtime::env::{Env, Word};
|
||||
use craft::ui::style::DataColor;
|
||||
use craft::ui::text::{NumberField, NumberPick};
|
||||
use egui::{Color32, Ui};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::arrange::arrange_menu;
|
||||
use super::galleries::{cref_param, effects_menu, outline_menu_base, quick_styles, shapes_gallery, smartart_gallery};
|
||||
use super::{
|
||||
Color32, CornerRadius, Icon, Rect, Sense, SlideApp, Stroke, Tokens, Ui, Value, big, big_button, big_button_ex, color_split, dropdown, enabled,
|
||||
fmt_state, group, icon_toggle, json, pos2, rows, run, scheme, small, small_button, small_button_ex, small_button_named, toggle, vec2, widgets,
|
||||
};
|
||||
use super::galleries::{self, cref_param, effects_menu, layout_gallery, outline_menu, quick_styles, shapes_gallery, smartart_gallery};
|
||||
use super::{fonts, fmt_state};
|
||||
use crate::SlideApp;
|
||||
use crate::icons::Icon;
|
||||
use crate::panels::color_row::{color_menu, take_color_answer};
|
||||
|
||||
// ---------- Home ----------
|
||||
const HIGHLIGHT_KEY: &str = "ribbon.home.highlight";
|
||||
const FONT_COLOR_KEY: &str = "ribbon.home.fontColor";
|
||||
const SHAPE_FILL_KEY: &str = "ribbon.home.shapeFill";
|
||||
const SHAPE_OUTLINE_KEY: &str = "ribbon.home.shapeOutline";
|
||||
|
||||
fn clipboard_group(app: &mut SlideApp, ui: &mut Ui) {
|
||||
group(ui, |ui| {
|
||||
let (main, arrow) = big_button_ex(ui, Icon::Paste, "Paste", enabled(app, "edit.paste"), true, false);
|
||||
if main.on_hover_text("Paste (⌘V)").clicked() {
|
||||
run(app, "edit.paste", json!({}));
|
||||
}
|
||||
if let Some(a) = arrow {
|
||||
egui::Popup::menu(&a).show(|ui| {
|
||||
if ui.button("Paste").clicked() {
|
||||
run(app, "edit.paste", json!({}));
|
||||
}
|
||||
if ui.button("Paste and Match Formatting").clicked() {
|
||||
run(app, "edit.pasteText", json!({}));
|
||||
}
|
||||
if ui.button("Paste Special…").clicked() {
|
||||
run(app, "app.pasteSpecial", json!({}));
|
||||
}
|
||||
if ui.button("Paste Formatting").clicked() {
|
||||
run(app, "format.painterApply", json!({}));
|
||||
}
|
||||
});
|
||||
}
|
||||
rows(ui, |ui| {
|
||||
small(app, ui, Icon::Cut, "Cut", "edit.cut", json!({}));
|
||||
small(app, ui, Icon::Copy, "Copy", "edit.copy", json!({}));
|
||||
let on = app.session.painter.is_some();
|
||||
let en = enabled(app, "format.painter");
|
||||
let r = small_button(ui, Icon::FormatPainter, "Format", en, on).on_hover_text("Format Painter (double-click to keep it on)");
|
||||
if r.double_clicked() {
|
||||
run(app, "format.painter", json!({"sticky": true}));
|
||||
} else if r.clicked() {
|
||||
if on {
|
||||
app.session.painter = None;
|
||||
} else {
|
||||
run(app, "format.painter", json!({}));
|
||||
}
|
||||
/// Shows a painter whose single click toggles and whose double click keeps it armed.
|
||||
pub(super) fn painter_toggle(app: &mut SlideApp, ui: &mut Ui, icon: Icon, label: &str, cmd: &str, armed: bool, tooltip: &str) {
|
||||
let output = ToggleButton::new(label.to_owned(), Bind::given(armed))
|
||||
.icon(icon.id())
|
||||
.enabled(commands::resolve(ui.ctx(), cmd).enabled)
|
||||
.tooltip(TooltipSpec::new(tooltip.to_owned()))
|
||||
.show(ui);
|
||||
let params = match output.clicks {
|
||||
2 => json!({"sticky": true}),
|
||||
1 if armed => json!({"on": false}),
|
||||
1 => json!({}),
|
||||
_ => return,
|
||||
};
|
||||
let _ = app.run(cmd, params);
|
||||
}
|
||||
|
||||
fn clipboard(app: &mut SlideApp, ui: &mut Ui) {
|
||||
let entries = [
|
||||
("edit.paste", "Paste"),
|
||||
("edit.pasteText", "Paste and Match Formatting"),
|
||||
("app.pasteSpecial", "Paste Special…"),
|
||||
("format.painterApply", "Paste Formatting"),
|
||||
]
|
||||
.map(|(command, label)| Entry::new(command, Word::plain(label)).enabled(commands::resolve(ui.ctx(), command).enabled));
|
||||
let output = SplitButton::command("edit.paste", SplitMenu::Entries(&entries))
|
||||
.label(Word::plain("Paste"))
|
||||
.icon(Icon::Paste.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.show(ui);
|
||||
if let Some(command) = output.chosen {
|
||||
let _ = app.run(command, json!({}));
|
||||
}
|
||||
Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
Button::command("edit.cut").label(Word::plain("Cut")).icon(Icon::Cut.id()).show(ui);
|
||||
Button::command("edit.copy").label(Word::plain("Copy")).icon(Icon::Copy.id()).show(ui);
|
||||
let armed = app.session.painter.is_some();
|
||||
let tooltip = Env::of(ui).view().resolve(&Word::plain("Format Painter (double-click to keep it on)").into());
|
||||
painter_toggle(app, ui, Icon::FormatPainter, "Format", "format.painter", armed, tooltip.as_str());
|
||||
});
|
||||
}
|
||||
|
||||
fn slides(app: &mut SlideApp, ui: &mut Ui) {
|
||||
SplitButton::<()>::command(
|
||||
"slide.new",
|
||||
SplitMenu::Body(Box::new(|ui, cx| {
|
||||
layout_gallery(app, ui, cx, "slide.new");
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command("slide.duplicate").label(Word::plain("Duplicate Selected Slides")).show(ui);
|
||||
if MenuItem::new(Word::plain("Slides from Outline…")).show(ui).ran {
|
||||
app.open_dialog("outline", json!({}));
|
||||
}
|
||||
let desktop = app.host.files().can_pick();
|
||||
let reuse = [
|
||||
Entry::new(false, Word::plain("Reuse Slides…")),
|
||||
Entry::new(true, Word::plain("Reuse Slides (Keep Source Formatting)…")),
|
||||
]
|
||||
.map(|entry| {
|
||||
if desktop { entry } else { entry.disabled_reason(Word::plain("Choosing a presentation to reuse needs the desktop app")) }
|
||||
});
|
||||
if let Some(keep) = Menu::inline(Word::plain("Reuse Slides")).pick(ui, &reuse).picked {
|
||||
let _ = app.run("app.reuseSlidesDialog", json!({"keepFormatting": keep}));
|
||||
}
|
||||
})),
|
||||
)
|
||||
.label(Word::plain("New Slide"))
|
||||
.icon(Icon::NewSlide.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.show(ui);
|
||||
Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
let layout = Button::new(Word::plain("Layout"))
|
||||
.icon(Icon::Layout.id())
|
||||
.trailing_icon(DisclosureGlyph::menu_button())
|
||||
.popup(PopupKind::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "slide.layout").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Layout")).opened_by(&layout.response, Trigger::Click).show(ui, |ui, cx| layout_gallery(app, ui, cx, "slide.layout"));
|
||||
Button::command("slide.reset").label(Word::plain("Reset")).icon(Icon::ResetSlide.id()).show(ui);
|
||||
let section = Button::new(Word::plain("Section"))
|
||||
.icon(Icon::Section.id())
|
||||
.trailing_icon(DisclosureGlyph::menu_button())
|
||||
.popup(PopupKind::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "section.add").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Section")).opened_by(§ion.response, Trigger::Click).show(ui, |ui, _| {
|
||||
MenuItem::command("section.add").label(Word::plain("Add Section")).show(ui);
|
||||
MenuItem::command("section.removeAll").label(Word::plain("Remove All Sections")).show(ui);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn layout_menu(app: &mut SlideApp, ui: &mut Ui, cmd: &str) {
|
||||
let layouts: Vec<(String, deckcraft_model::LayoutId)> = app
|
||||
.session
|
||||
.active()
|
||||
.and_then(|d| d.doc.masters.first().map(|m| m.layouts.iter().map(|l| (l.name.clone(), l.id)).collect()))
|
||||
.unwrap_or_default();
|
||||
egui::Grid::new(("layouts", cmd)).spacing(vec2(6.0, 6.0)).show(ui, |ui| {
|
||||
for (k, (name, id)) in layouts.iter().enumerate() {
|
||||
let idx = app.session.active().and_then(|d| d.doc.masters.first().and_then(|m| m.layouts.iter().position(|l| l.id == *id)));
|
||||
let resp = ui.vertical(|ui| {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(96.0, 54.0), Sense::click());
|
||||
if let (Some(d), Some(li)) = (app.session.active(), idx) {
|
||||
let img = deckcraft_render::render_layout(
|
||||
&d.doc,
|
||||
0,
|
||||
Some(li),
|
||||
&deckcraft_render::RenderOpts {
|
||||
scale: 192.0 / d.doc.slide_size.width.max(1.0),
|
||||
edit: true,
|
||||
size: Some((192, 108)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let tex = crate::textures::upload_editor(ui.ctx(), format!("layout-{li}"), crate::textures::to_color_image(&img, false));
|
||||
let at = crate::textures::device_pixel_rect(rect, ui.ctx().pixels_per_point());
|
||||
ui.painter().image(tex.id(), at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
fn font(app: &mut SlideApp, ui: &mut Ui, state: &Value) {
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
let family = state["font"].as_str().unwrap_or_default().to_owned();
|
||||
let theme = fonts::theme_font_rows(app);
|
||||
let groups = [HostFontGroup::new(None, &theme)];
|
||||
let actions = [Word::plain("Rescan Installed Fonts").into()];
|
||||
let picked = FontPicker::new(Word::plain("Font"), Bind::given(family), fonts::catalog())
|
||||
.kind(FontPickerKind::Plain)
|
||||
.host(&groups)
|
||||
.actions(&actions)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.font").enabled)
|
||||
.show(ui);
|
||||
if let Some(family) = picked.host_picked.as_ref().or(picked.picked.as_ref()).or_else(|| picked.edit.events.committed()) {
|
||||
let _ = app.run("format.font", json!({"family": family}));
|
||||
}
|
||||
// Actions have their own index: action 0 is Rescan even with two theme faces and many families.
|
||||
if picked.action == Some(0) {
|
||||
let _ = app.run("font.rescan", json!({}));
|
||||
}
|
||||
let presets: Vec<_> = deckcraft_engine::cmd::format::SIZES
|
||||
.iter()
|
||||
.map(|size| Entry::new(NumberPick::Number(*size), size.to_string()))
|
||||
.collect();
|
||||
let size = NumberField::new(Word::plain("Font size"), Bind::given(state["size"].as_f64()))
|
||||
.presets(&presets)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.size").enabled)
|
||||
.show(ui);
|
||||
if let Some(Some(size)) = size.events.committed() {
|
||||
let _ = app.run("format.size", json!({"size": size}));
|
||||
}
|
||||
for (command, label, icon) in [
|
||||
("format.grow", "Increase Font Size", Icon::FontGrow),
|
||||
("format.shrink", "Decrease Font Size", Icon::FontShrink),
|
||||
("format.clear", "Clear All Formatting", Icon::ClearFormatting),
|
||||
] {
|
||||
IconButton::command(icon.id(), command).label(Word::plain(label)).show(ui);
|
||||
}
|
||||
});
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
for (command, label, icon) in [
|
||||
("format.bold", "Bold", Icon::Bold),
|
||||
("format.italic", "Italic", Icon::Italic),
|
||||
("format.underline", "Underline", Icon::Underline),
|
||||
("format.strikethrough", "Strikethrough", Icon::Strikethrough),
|
||||
("format.superscript", "Superscript", Icon::Superscript),
|
||||
("format.subscript", "Subscript", Icon::Subscript),
|
||||
] {
|
||||
ToggleButton::command(CommandRef::new(command)).label(Word::plain(label)).icon(icon.id()).icon_only().show(ui);
|
||||
}
|
||||
let spacing = IconButton::new(Icon::CharSpacing.id())
|
||||
.label(Word::plain("Character Spacing"))
|
||||
.popup(PopupKind::Menu)
|
||||
.popup_mark(PopupMark::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.spacing").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Character Spacing")).opened_by(&spacing.response, Trigger::Click).show(ui, |ui, _| {
|
||||
for (label, pt) in [("Very Tight", -3.0), ("Tight", -1.5), ("Normal", 0.0), ("Loose", 3.0), ("Very Loose", 6.0)] {
|
||||
MenuItem::command(CommandRef::with_params("format.spacing", json!({"pt": pt}))).label(Word::plain(label)).show(ui);
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.painter().rect_stroke(
|
||||
rect,
|
||||
CornerRadius::ZERO,
|
||||
Stroke::new(if resp.hovered() { 2.0 } else { 1.0 }, if resp.hovered() { t.accent } else { t.border }),
|
||||
egui::StrokeKind::Outside,
|
||||
);
|
||||
ui.add_sized(vec2(96.0, 14.0), egui::Label::new(egui::RichText::new(name).size(10.5)).truncate());
|
||||
resp
|
||||
});
|
||||
if resp.inner.clicked() {
|
||||
run(app, cmd, json!({"layout": id.0}));
|
||||
ui.close();
|
||||
}
|
||||
if k % 4 == 3 {
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Render the Home Slides group: New Slide, Layout, Reset, and Section controls.
|
||||
fn slides_group(app: &mut SlideApp, ui: &mut Ui) {
|
||||
group(ui, |ui| {
|
||||
let (main, arrow) = big_button_ex(ui, Icon::NewSlide, "New\nSlide", enabled(app, "slide.new"), true, false);
|
||||
if main.on_hover_text("New Slide (⇧⌘N)").clicked() {
|
||||
run(app, "slide.new", json!({}));
|
||||
}
|
||||
if let Some(a) = arrow {
|
||||
egui::Popup::menu(&a).width(420.0).show(|ui| new_slide_menu(app, ui));
|
||||
}
|
||||
rows(ui, |ui| {
|
||||
let (main, arrow) = small_button_ex(ui, Icon::Layout, "Layout", enabled(app, "slide.layout"), false, true);
|
||||
if let Some(arrow) = arrow {
|
||||
widgets::split_menu(&main, &arrow, |ui| layout_menu(app, ui, "slide.layout"));
|
||||
}
|
||||
small(app, ui, Icon::ResetSlide, "Reset", "slide.reset", json!({}));
|
||||
let (main, arrow) = small_button_ex(ui, Icon::Section, "Section", enabled(app, "section.add"), false, true);
|
||||
if let Some(arrow) = arrow {
|
||||
widgets::split_menu(&main, &arrow, |ui| section_menu(app, ui));
|
||||
}
|
||||
let case = IconButton::new(Icon::ChangeCase.id())
|
||||
.label(Word::plain("Change Case"))
|
||||
.popup(PopupKind::Menu)
|
||||
.popup_mark(PopupMark::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.case").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Change Case")).opened_by(&case.response, Trigger::Click).show(ui, |ui, _| {
|
||||
for (label, mode) in [
|
||||
("Sentence case.", "sentence"),
|
||||
("lowercase", "lower"),
|
||||
("UPPERCASE", "upper"),
|
||||
("Capitalize Each Word", "title"),
|
||||
("tOGGLE cASE", "toggle"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("format.case", json!({"mode": mode}))).label(Word::plain(label)).show(ui);
|
||||
}
|
||||
});
|
||||
text_color(app, ui, TextColor::Highlight);
|
||||
text_color(app, ui, TextColor::Font);
|
||||
Button::command("format.fontDialog").label(Word::plain("Font…")).show(ui);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The New Slide button's menu: layouts, duplication, outline import and slide reuse.
|
||||
fn new_slide_menu(app: &mut SlideApp, ui: &mut Ui) {
|
||||
layout_menu(app, ui, "slide.new");
|
||||
ui.separator();
|
||||
if ui.button("Duplicate Selected Slides").clicked() {
|
||||
run(app, "slide.duplicate", json!({}));
|
||||
}
|
||||
if ui.button("Slides from Outline…").clicked() {
|
||||
app.dialog = Some(crate::dialogs::Dialog::new("outline"));
|
||||
}
|
||||
let desktop = app.services.pick_open.is_some();
|
||||
for (label, keep) in [("Reuse Slides…", false), ("Reuse Slides (Keep Source Formatting)…", true)] {
|
||||
let r = ui.add_enabled(desktop, egui::Button::new(label));
|
||||
if r.clicked() {
|
||||
run(app, "app.reuseSlidesDialog", json!({"keepFormatting": keep}));
|
||||
}
|
||||
r.on_disabled_hover_text("Choosing a presentation to reuse needs the desktop app");
|
||||
#[derive(Clone, Copy)]
|
||||
enum TextColor {
|
||||
Highlight,
|
||||
Font,
|
||||
}
|
||||
|
||||
impl TextColor {
|
||||
fn apply(self, app: &mut SlideApp, pick: Option<deckcraft_model::ColorRef>) {
|
||||
let command = match self {
|
||||
Self::Highlight => "format.highlight",
|
||||
Self::Font => "format.color",
|
||||
};
|
||||
let _ = app.run(command, json!({"color": pick.as_ref().map(cref_param)}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Section split button's menu.
|
||||
fn section_menu(app: &mut SlideApp, ui: &mut Ui) {
|
||||
if ui.button("Add Section").clicked() {
|
||||
run(app, "section.add", json!({}));
|
||||
}
|
||||
if ui.button("Remove All Sections").clicked() {
|
||||
run(app, "section.removeAll", json!({}));
|
||||
}
|
||||
fn text_color(app: &mut SlideApp, ui: &mut Ui, target: TextColor) {
|
||||
let (key, label, command, icon, color, none) = match target {
|
||||
TextColor::Highlight => (
|
||||
HIGHLIGHT_KEY, "Text Highlight Color", "format.highlight", Icon::Highlight, Color32::YELLOW, Some("No Color"),
|
||||
),
|
||||
TextColor::Font => (FONT_COLOR_KEY, "Font Color", "format.color", Icon::FontColor, Color32::from_rgb(0xC0, 0, 0), None),
|
||||
};
|
||||
let hex = format!("#{:02X}{:02X}{:02X}", color.r(), color.g(), color.b());
|
||||
SplitButton::<()>::command(
|
||||
CommandRef::with_params(command, json!({"color": hex})),
|
||||
SplitMenu::Body(Box::new(|ui, cx| {
|
||||
if let Some(pick) = color_menu(app, ui, cx, key, none) {
|
||||
target.apply(app, pick);
|
||||
}
|
||||
})),
|
||||
)
|
||||
.label(Word::plain(label))
|
||||
.icon(IconSpec::from(icon.id()).with_mark(IconMark::bar(DataColor::new(color))))
|
||||
.icon_only()
|
||||
.show(ui);
|
||||
}
|
||||
|
||||
pub fn font_families(app: &SlideApp) -> Vec<String> {
|
||||
let mut v = vec![];
|
||||
if let Some(m) = app.session.active().and_then(|d| d.doc.masters.first()) {
|
||||
v.push(m.theme.fonts.major.latin.clone());
|
||||
v.push(m.theme.fonts.minor.latin.clone());
|
||||
}
|
||||
v.extend(deckcraft_fonts::FontDb::global().families());
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
fn font_group(app: &mut SlideApp, ui: &mut Ui, st: &Value) {
|
||||
let en = enabled(app, "format.bold");
|
||||
group(ui, |ui| {
|
||||
rows(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 3.0;
|
||||
let font = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let size = st.get("size").and_then(Value::as_f64);
|
||||
let fams = font_families(app);
|
||||
let theme_fonts: Vec<String> = fams.iter().take(2).cloned().collect();
|
||||
dropdown(ui, "Font", &font, 150.0, en, |ui| {
|
||||
for (k, f) in fams.iter().enumerate() {
|
||||
let label = if k == 0 && theme_fonts.len() == 2 {
|
||||
format!("{f} (Headings)")
|
||||
} else if k == 1 && theme_fonts.len() == 2 {
|
||||
format!("{f} (Body)")
|
||||
fn paragraph(app: &mut SlideApp, ui: &mut Ui) {
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
for (command, label, icon, tab) in [
|
||||
("format.bullets", "Bullets", Icon::Bullets, "bulleted"),
|
||||
("format.numbering", "Numbering", Icon::Numbering, "numbered"),
|
||||
] {
|
||||
SplitButton::<()>::command(
|
||||
command,
|
||||
SplitMenu::Body(Box::new(|ui, cx| {
|
||||
MenuItem::command(CommandRef::with_params(command, json!({"on": false}))).label(Word::plain("None")).show(ui);
|
||||
if tab == "bulleted" {
|
||||
let bullet = cx.env.resolve(&Word::plain("Bullet").into());
|
||||
for ch in ["•", "○", "■", "□", "◆", "➢", "✓", "–", "★"] {
|
||||
MenuItem::command(CommandRef::with_params(command, json!({"on": true, "char": ch})))
|
||||
.label(format!("{ch} {}", bullet.as_str()))
|
||||
.show(ui);
|
||||
}
|
||||
} else {
|
||||
f.clone()
|
||||
};
|
||||
if ui.button(egui::RichText::new(label)).clicked() {
|
||||
run(app, "format.font", json!({"family": f}));
|
||||
ui.close();
|
||||
for (label, scheme) in [
|
||||
("1. 2. 3.", "arabicPeriod"),
|
||||
("1) 2) 3)", "arabicParenR"),
|
||||
("I. II. III.", "romanUcPeriod"),
|
||||
("i. ii. iii.", "romanLcPeriod"),
|
||||
("A. B. C.", "alphaUcPeriod"),
|
||||
("a) b) c)", "alphaLcParenR"),
|
||||
("a. b. c.", "alphaLcPeriod"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params(command, json!({"on": true, "scheme": scheme}))).label(label).show(ui);
|
||||
}
|
||||
}
|
||||
if k == 1 {
|
||||
ui.separator();
|
||||
Divider::horizontal().show(ui);
|
||||
if MenuItem::new(Word::plain("Bullets and Numbering…")).show(ui).ran {
|
||||
app.open_dialog("bullets", json!({"tab": tab}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
// Fonts installed while DeckCraft runs (e.g. into ~/.local/share/fonts).
|
||||
if ui.button("Rescan Installed Fonts").clicked() {
|
||||
run(app, "font.rescan", json!({}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
let size_text = size.map(|s| widgets::fmt_num(s, "")).unwrap_or_default();
|
||||
dropdown(ui, "Font size", &size_text, 52.0, en, |ui| {
|
||||
for s in deckcraft_engine::cmd::format::SIZES.iter() {
|
||||
if ui.button(widgets::fmt_num(*s, "")).clicked() {
|
||||
run(app, "format.size", json!({"size": s}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
toggle(app, ui, Icon::FontGrow, "Increase Font Size", "format.grow", false);
|
||||
toggle(app, ui, Icon::FontShrink, "Decrease Font Size", "format.shrink", false);
|
||||
toggle(app, ui, Icon::ClearFormatting, "Clear All Formatting", "format.clear", false);
|
||||
});
|
||||
ui.add_space(3.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 1.0;
|
||||
let b = |k: &str| st.get(k).and_then(Value::as_bool).unwrap_or(false);
|
||||
toggle(app, ui, Icon::Bold, "Bold", "format.bold", b("bold"));
|
||||
toggle(app, ui, Icon::Italic, "Italic", "format.italic", b("italic"));
|
||||
toggle(app, ui, Icon::Underline, "Underline", "format.underline", b("underline"));
|
||||
toggle(app, ui, Icon::Strikethrough, "Strikethrough", "format.strikethrough", b("strike"));
|
||||
toggle(app, ui, Icon::Superscript, "Superscript", "format.superscript", b("superscript"));
|
||||
toggle(app, ui, Icon::Subscript, "Subscript", "format.subscript", b("subscript"));
|
||||
let r = icon_toggle(ui, Icon::CharSpacing, "Character Spacing", en, false);
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for (label, pt) in [("Very Tight", -3.0), ("Tight", -1.5), ("Normal", 0.0), ("Loose", 3.0), ("Very Loose", 6.0)] {
|
||||
if ui.button(label).clicked() {
|
||||
run(app, "format.spacing", json!({"pt": pt}));
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = icon_toggle(ui, Icon::ChangeCase, "Change Case", en, false);
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for (label, mode) in [
|
||||
("Sentence case.", "sentence"),
|
||||
("lowercase", "lower"),
|
||||
("UPPERCASE", "upper"),
|
||||
("Capitalize Each Word", "title"),
|
||||
("tOGGLE cASE", "toggle"),
|
||||
] {
|
||||
if ui.button(label).clicked() {
|
||||
run(app, "format.case", json!({"mode": mode}));
|
||||
}
|
||||
}
|
||||
});
|
||||
let sc = scheme(app);
|
||||
let (m, a) = color_split(ui, Icon::Highlight, "Text Highlight Color", Color32::from_rgb(255, 230, 0), en);
|
||||
if m.clicked() {
|
||||
run(app, "format.highlight", json!({"color": "#FFFF00"}));
|
||||
})),
|
||||
)
|
||||
.label(Word::plain(label))
|
||||
.icon(icon.id())
|
||||
.icon_only()
|
||||
.show(ui);
|
||||
}
|
||||
IconButton::command(Icon::DecreaseIndent.id(), "format.outdent").label(Word::plain("Decrease List Level")).show(ui);
|
||||
IconButton::command(Icon::IncreaseIndent.id(), "format.indent").label(Word::plain("Increase List Level")).show(ui);
|
||||
let spacing = IconButton::new(Icon::LineSpacing.id())
|
||||
.label(Word::plain("Line Spacing"))
|
||||
.popup(PopupKind::Menu)
|
||||
.popup_mark(PopupMark::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.lineSpacing").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Line Spacing")).opened_by(&spacing.response, Trigger::Click).show(ui, |ui, _| {
|
||||
for lines in [1.0, 1.5, 2.0, 2.5, 3.0] {
|
||||
MenuItem::command(CommandRef::with_params("format.lineSpacing", json!({"lines": lines})))
|
||||
.label(format!("{lines:.1}"))
|
||||
.show(ui);
|
||||
}
|
||||
widgets::color_popup(&a).show(|ui| {
|
||||
if let Some(c) = widgets::color_grid(ui, &sc, Some("No Color")) {
|
||||
run(app, "format.highlight", json!({"color": c.map(|c| serde_json::to_value(cref_param(&c)).unwrap_or_default())}));
|
||||
}
|
||||
});
|
||||
let (m, a) = color_split(ui, Icon::FontColor, "Font Color", Color32::from_rgb(0xD8, 0x3F, 0x3F), en);
|
||||
if m.clicked() {
|
||||
run(app, "format.color", json!({"color": "#C00000"}));
|
||||
}
|
||||
widgets::color_popup(&a).show(|ui| {
|
||||
if let Some(Some(c)) = widgets::color_grid(ui, &sc, None) {
|
||||
run(app, "format.color", json!({"color": cref_param(&c)}));
|
||||
}
|
||||
});
|
||||
if ui.add_enabled(en, egui::Button::new("Font…").min_size(vec2(52.0, 22.0))).on_hover_text("Font").clicked() {
|
||||
run(app, "format.fontDialog", json!({}));
|
||||
MenuItem::command("format.paragraphDialog").label(Word::plain("Line Spacing Options…")).show(ui);
|
||||
if MenuItem::new(Word::plain("Tabs…")).show(ui).ran {
|
||||
app.open_dialog("tabs", json!({}));
|
||||
}
|
||||
});
|
||||
let columns = IconButton::new(Icon::Columns.id())
|
||||
.label(Word::plain("Columns"))
|
||||
.popup(PopupKind::Menu)
|
||||
.popup_mark(PopupMark::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.columns").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Columns")).opened_by(&columns.response, Trigger::Click).show(ui, |ui, _| {
|
||||
for (count, label) in [(1, "1 Column"), (2, "2 Columns"), (3, "3 Columns")] {
|
||||
MenuItem::command(CommandRef::with_params("format.columns", json!({"count": count, "spacing": 18})))
|
||||
.label(Word::plain(label))
|
||||
.show(ui);
|
||||
}
|
||||
MenuItem::command("format.columns").label(Word::plain("More Columns…")).show(ui);
|
||||
});
|
||||
});
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
for (command, label, icon) in [
|
||||
("format.alignLeft", "Align Left", Icon::AlignLeft),
|
||||
("format.alignCenter", "Center", Icon::AlignCenter),
|
||||
("format.alignRight", "Align Right", Icon::AlignRight),
|
||||
("format.justify", "Justify", Icon::Justify),
|
||||
] {
|
||||
ToggleButton::command(CommandRef::new(command)).label(Word::plain(label)).icon(icon.id()).icon_only().show(ui);
|
||||
}
|
||||
let direction = IconButton::new(Icon::TextDirection.id())
|
||||
.label(Word::plain("Text Direction"))
|
||||
.popup(PopupKind::Menu)
|
||||
.popup_mark(PopupMark::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.direction").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Text Direction")).opened_by(&direction.response, Trigger::Click).show(ui, |ui, _| {
|
||||
for (label, dir) in [
|
||||
("Horizontal", "horizontal"),
|
||||
("Rotate all text 90°", "rotate90"),
|
||||
("Rotate all text 270°", "rotate270"),
|
||||
("Stacked", "stacked"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("format.direction", json!({"dir": dir}))).label(Word::plain(label)).show(ui);
|
||||
}
|
||||
});
|
||||
let anchor = IconButton::new(Icon::AlignText.id())
|
||||
.label(Word::plain("Align Text"))
|
||||
.popup(PopupKind::Menu)
|
||||
.popup_mark(PopupMark::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "format.anchor").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Align Text")).opened_by(&anchor.response, Trigger::Click).show(ui, |ui, _| {
|
||||
for (label, anchor) in [("Top", "top"), ("Middle", "middle"), ("Bottom", "bottom")] {
|
||||
MenuItem::command(CommandRef::with_params("format.anchor", json!({"anchor": anchor}))).label(Word::plain(label)).show(ui);
|
||||
}
|
||||
});
|
||||
let diagram = IconButton::new(Icon::SmartArt.id())
|
||||
.label(Word::plain("Convert to Diagram"))
|
||||
.popup(PopupKind::Menu)
|
||||
.popup_mark(PopupMark::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "smartArt.fromText").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Convert to Diagram")).opened_by(&diagram.response, Trigger::Click).show(ui, |ui, cx| {
|
||||
smartart_gallery(app, ui, cx, "smartArt.fromText", json!({}), "", ("", ""), None);
|
||||
});
|
||||
Button::command("format.paragraphDialog").label(Word::plain("Paragraph…")).show(ui);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Render paragraph formatting controls using the current paragraph state.
|
||||
fn paragraph_group(app: &mut SlideApp, ui: &mut Ui, st: &Value) {
|
||||
let en = enabled(app, "format.bullets");
|
||||
group(ui, |ui| {
|
||||
rows(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 1.0;
|
||||
let b = |k: &str| st.get(k).and_then(Value::as_bool).unwrap_or(false);
|
||||
let (m, a) = small_button_named(ui, Icon::Bullets, "", "Bullets", en, b("bullets"), true);
|
||||
if m.on_hover_text("Bullets").clicked() {
|
||||
run(app, "format.bullets", json!({}));
|
||||
fn drawing(app: &mut SlideApp, ui: &mut Ui) {
|
||||
let shapes = Button::new(Word::plain("Shapes"))
|
||||
.icon(Icon::Shapes.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.trailing_icon(DisclosureGlyph::menu_button())
|
||||
.popup(PopupKind::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "shape.insert").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Shapes")).opened_by(&shapes.response, Trigger::Click).show(ui, |ui, cx| {
|
||||
if let Some(preset) = shapes_gallery(ui, cx) {
|
||||
let _ = app.run("tool.set", json!({"kind": "shape", "preset": preset}));
|
||||
}
|
||||
});
|
||||
Button::command("insert.textBox").label(Word::plain("Text Box")).icon(Icon::TextBox.id()).arrangement(Arrangement::Stacked).show(ui);
|
||||
let arrange = Button::new(Word::plain("Arrange"))
|
||||
.icon(Icon::Arrange.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.trailing_icon(DisclosureGlyph::menu_button())
|
||||
.popup(PopupKind::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "shape.fill").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Arrange")).opened_by(&arrange.response, Trigger::Click).show(ui, |ui, cx| arrange_menu(app, ui, cx));
|
||||
let styles = Button::new(Word::plain("Quick Styles"))
|
||||
.icon(Icon::QuickStyles.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.trailing_icon(DisclosureGlyph::menu_button())
|
||||
.popup(PopupKind::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "shape.fill").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Quick Styles")).opened_by(&styles.response, Trigger::Click).show(ui, |ui, cx| quick_styles(app, ui, cx));
|
||||
Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
let last = app.last_fill.clone();
|
||||
SplitButton::<()>::command(
|
||||
CommandRef::with_params("shape.fill", json!({"color": last})),
|
||||
SplitMenu::Body(Box::new(|ui, cx| {
|
||||
if let Some(pick) = color_menu(app, ui, cx, SHAPE_FILL_KEY, Some("No Fill")) {
|
||||
apply_fill(app, pick);
|
||||
}
|
||||
if let Some(a) = a {
|
||||
egui::Popup::menu(&a).show(|ui| {
|
||||
if ui.button("None").clicked() {
|
||||
run(app, "format.bullets", json!({"on": false}));
|
||||
}
|
||||
for ch in ["•", "○", "■", "□", "◆", "➢", "✓", "–", "★"] {
|
||||
if ui.button(egui::RichText::new(format!("{ch} Bullet")).size(14.0)).clicked() {
|
||||
run(app, "format.bullets", json!({"on": true, "char": ch}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Bullets and Numbering…").clicked() {
|
||||
let mut dlg = crate::dialogs::Dialog::new("bullets");
|
||||
dlg.fields.insert("tab".into(), "bulleted".into());
|
||||
app.dialog = Some(dlg);
|
||||
}
|
||||
});
|
||||
}
|
||||
let (m, a) = small_button_named(ui, Icon::Numbering, "", "Numbering", en, b("numbering"), true);
|
||||
if m.on_hover_text("Numbering").clicked() {
|
||||
run(app, "format.numbering", json!({}));
|
||||
}
|
||||
if let Some(a) = a {
|
||||
egui::Popup::menu(&a).show(|ui| {
|
||||
if ui.button("None").clicked() {
|
||||
run(app, "format.numbering", json!({"on": false}));
|
||||
}
|
||||
for (label, sch) in [
|
||||
("1. 2. 3.", "arabicPeriod"),
|
||||
("1) 2) 3)", "arabicParenR"),
|
||||
("I. II. III.", "romanUcPeriod"),
|
||||
("i. ii. iii.", "romanLcPeriod"),
|
||||
("A. B. C.", "alphaUcPeriod"),
|
||||
("a) b) c)", "alphaLcParenR"),
|
||||
("a. b. c.", "alphaLcPeriod"),
|
||||
] {
|
||||
if ui.button(label).clicked() {
|
||||
run(app, "format.numbering", json!({"on": true, "scheme": sch}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Bullets and Numbering…").clicked() {
|
||||
let mut dlg = crate::dialogs::Dialog::new("bullets");
|
||||
dlg.fields.insert("tab".into(), "numbered".into());
|
||||
app.dialog = Some(dlg);
|
||||
}
|
||||
});
|
||||
}
|
||||
toggle(app, ui, Icon::DecreaseIndent, "Decrease List Level", "format.outdent", false);
|
||||
toggle(app, ui, Icon::IncreaseIndent, "Increase List Level", "format.indent", false);
|
||||
let r = icon_toggle(ui, Icon::LineSpacing, "Line Spacing", en, false);
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for v in [1.0, 1.5, 2.0, 2.5, 3.0] {
|
||||
if ui.button(format!("{v:.1}")).clicked() {
|
||||
run(app, "format.lineSpacing", json!({"lines": v}));
|
||||
}
|
||||
}
|
||||
if ui.button("Line Spacing Options…").clicked() {
|
||||
run(app, "format.paragraphDialog", json!({}));
|
||||
}
|
||||
if ui.button("Tabs…").clicked() {
|
||||
app.dialog = Some(crate::dialogs::Dialog::new("tabs"));
|
||||
}
|
||||
});
|
||||
let r = icon_toggle(ui, Icon::Columns, "Columns", en, false);
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for n in 1..=3 {
|
||||
if ui.button(format!("{n} Column{}", if n > 1 { "s" } else { "" })).clicked() {
|
||||
run(app, "format.columns", json!({"count": n, "spacing": 18}));
|
||||
}
|
||||
}
|
||||
if ui.button("More Columns…").clicked() {
|
||||
run(app, "format.columns", json!({}));
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(3.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 1.0;
|
||||
let al = st.get("align").and_then(Value::as_str).unwrap_or("");
|
||||
toggle(app, ui, Icon::AlignLeft, "Align Left", "format.alignLeft", al == "l");
|
||||
toggle(app, ui, Icon::AlignCenter, "Center", "format.alignCenter", al == "ctr");
|
||||
toggle(app, ui, Icon::AlignRight, "Align Right", "format.alignRight", al == "r");
|
||||
toggle(app, ui, Icon::Justify, "Justify", "format.justify", al == "just");
|
||||
let r = icon_toggle(ui, Icon::TextDirection, "Text Direction", en, false);
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for (l, d) in [
|
||||
("Horizontal", "horizontal"),
|
||||
("Rotate all text 90°", "rotate90"),
|
||||
("Rotate all text 270°", "rotate270"),
|
||||
("Stacked", "stacked"),
|
||||
] {
|
||||
if ui.button(l).clicked() {
|
||||
run(app, "format.direction", json!({"dir": d}));
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = icon_toggle(ui, Icon::AlignText, "Align Text", en, false);
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for (l, a) in [("Top", "top"), ("Middle", "middle"), ("Bottom", "bottom")] {
|
||||
if ui.button(l).clicked() {
|
||||
run(app, "format.anchor", json!({"anchor": a}));
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = icon_toggle(ui, Icon::SmartArt, "Convert to Diagram", enabled(app, "smartArt.fromText"), false);
|
||||
// P3(ribbon-w6): rb.A16
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
craft::ui::contract::ShowContainer::show(craft::ui::layout_components::Stack::new(), ui, |ui, cx| {
|
||||
smartart_gallery(app, ui, cx, "smartArt.fromText", json!({}), "", ("", ""), None)
|
||||
})
|
||||
.inner
|
||||
.unwrap_or_default()
|
||||
});
|
||||
if ui.add_enabled(en, egui::Button::new("Paragraph…").min_size(vec2(88.0, 22.0))).on_hover_text("Paragraph").clicked() {
|
||||
run(app, "format.paragraphDialog", json!({}));
|
||||
}
|
||||
});
|
||||
});
|
||||
})),
|
||||
)
|
||||
.label(Word::plain("Shape Fill"))
|
||||
.icon(Icon::ShapeFill.id())
|
||||
.show(ui);
|
||||
let last = app.last_outline.clone();
|
||||
SplitButton::<()>::command(
|
||||
CommandRef::with_params("shape.line", json!({"color": last})),
|
||||
SplitMenu::Body(Box::new(|ui, cx| outline_menu(app, ui, cx, SHAPE_OUTLINE_KEY))),
|
||||
)
|
||||
.label(Word::plain("Shape Outline"))
|
||||
.icon(Icon::ShapeOutline.id())
|
||||
.show(ui);
|
||||
let effects = Button::new(Word::plain("Shape Effects"))
|
||||
.icon(Icon::ShapeEffects.id())
|
||||
.trailing_icon(DisclosureGlyph::menu_button())
|
||||
.popup(PopupKind::Menu)
|
||||
.enabled(commands::resolve(ui.ctx(), "shape.fill").enabled)
|
||||
.show(ui);
|
||||
Menu::new(Word::plain("Shape Effects")).opened_by(&effects.response, Trigger::Click).show(ui, |ui, cx| effects_menu(app, ui, cx));
|
||||
});
|
||||
}
|
||||
|
||||
/// Render drawing controls for shapes, text, arrange, quick styles, fill, and outline.
|
||||
fn drawing_group(app: &mut SlideApp, ui: &mut Ui) {
|
||||
group(ui, |ui| {
|
||||
let en = enabled(app, "shape.insert");
|
||||
let r = big_button(ui, Icon::Shapes, "Shapes", en).on_hover_text("Shapes");
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
// P3(ribbon-w6): rb.A16
|
||||
if let Some(p) = craft::ui::contract::ShowContainer::show(craft::ui::layout_components::Stack::new(), ui, |ui, cx| shapes_gallery(ui, cx))
|
||||
.inner
|
||||
.flatten()
|
||||
fn apply_fill(app: &mut SlideApp, pick: Option<deckcraft_model::ColorRef>) {
|
||||
let params = match pick {
|
||||
Some(color) => {
|
||||
let color = cref_param(&color);
|
||||
app.last_fill = color.clone();
|
||||
json!({"color": color})
|
||||
}
|
||||
None => json!({"none": true}),
|
||||
};
|
||||
let _ = app.run("shape.fill", params);
|
||||
}
|
||||
|
||||
/// Opens the Home tab's groups in document-editing order.
|
||||
pub(crate) fn home(app: &mut SlideApp, row: &mut RibbonRow<'_>) {
|
||||
// Answers are taken outside group bodies because those bodies also run for measurement.
|
||||
for (key, target) in [(HIGHLIGHT_KEY, TextColor::Highlight), (FONT_COLOR_KEY, TextColor::Font)] {
|
||||
if let Some(pick) = take_color_answer(app, key) {
|
||||
target.apply(app, pick);
|
||||
}
|
||||
}
|
||||
let state = fmt_state(app);
|
||||
row.group(RibbonGroup::new("home.clipboard", Word::plain("Clipboard"), Icon::Paste.id().into()), |ui| clipboard(app, ui));
|
||||
row.group(RibbonGroup::new("home.slides", Word::plain("Slides"), Icon::NewSlide.id().into()), |ui| slides(app, ui));
|
||||
row.group(RibbonGroup::new("home.font", Word::plain("Font"), Icon::Fonts.id().into()), |ui| font(app, ui, &state));
|
||||
row.group(RibbonGroup::new("home.paragraph", Word::plain("Paragraph"), Icon::AlignLeft.id().into()), |ui| paragraph(app, ui));
|
||||
row.group(RibbonGroup::new("home.picture", Word::plain("Picture"), Icon::Picture.id().into()), |ui| {
|
||||
Button::command("app.insertPictureDialog")
|
||||
.label(Word::plain("Picture"))
|
||||
.icon(Icon::Picture.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.show(ui);
|
||||
});
|
||||
if let Some(pick) = take_color_answer(app, SHAPE_FILL_KEY) {
|
||||
apply_fill(app, pick);
|
||||
}
|
||||
galleries::apply_line_answer(app, SHAPE_OUTLINE_KEY);
|
||||
row.group(RibbonGroup::new("home.drawing", Word::plain("Drawing"), Icon::Shapes.id().into()), |ui| drawing(app, ui));
|
||||
row.group(RibbonGroup::new("home.editing", Word::plain("Editing"), Icon::Search.id().into()), |ui| {
|
||||
Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
Button::command("app.find").label(Word::plain("Find")).icon(Icon::Search.id()).show(ui);
|
||||
Button::command("app.replace").label(Word::plain("Replace")).icon(Icon::Spelling.id()).show(ui);
|
||||
if Button::new(Word::plain("Replace Fonts…"))
|
||||
.icon(Icon::Fonts.id())
|
||||
.enabled(commands::resolve(ui.ctx(), "font.replace").enabled)
|
||||
.show(ui)
|
||||
.clicked()
|
||||
{
|
||||
app.session.set_tool(deckcraft_engine::ToolKind::Shape { preset: p.to_string() });
|
||||
}
|
||||
});
|
||||
big(app, ui, Icon::TextBox, "Text Box", "insert.textBox", json!({}));
|
||||
let sel = enabled(app, "shape.fill");
|
||||
let r = big_button(ui, Icon::Arrange, "Arrange", sel);
|
||||
// P3(ribbon-w6): rb.A16
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
craft::ui::contract::ShowContainer::show(craft::ui::layout_components::Stack::new(), ui, |ui, cx| arrange_menu(app, ui, cx))
|
||||
.inner
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let r = big_button(ui, Icon::QuickStyles, "Quick\nStyles", sel);
|
||||
// P3(ribbon-w6): rb.A16
|
||||
egui::Popup::menu(&r).width(330.0).show(|ui| {
|
||||
craft::ui::contract::ShowContainer::show(craft::ui::layout_components::Stack::new(), ui, |ui, cx| quick_styles(app, ui, cx))
|
||||
.inner
|
||||
.unwrap_or_default()
|
||||
});
|
||||
rows(ui, |ui| {
|
||||
let sc = scheme(app);
|
||||
let (m, a) = small_button_ex(ui, Icon::ShapeFill, "Shape Fill", sel, false, true);
|
||||
if m.clicked() {
|
||||
let c = app.last_fill.clone();
|
||||
run(app, "shape.fill", json!({"color": c}));
|
||||
}
|
||||
if let Some(a) = a {
|
||||
widgets::color_popup(&a).show(|ui| {
|
||||
if let Some(c) = widgets::color_grid(ui, &sc, Some("No Fill")) {
|
||||
match c {
|
||||
Some(c) => {
|
||||
app.last_fill = cref_param(&c);
|
||||
run(app, "shape.fill", json!({"color": cref_param(&c)}));
|
||||
}
|
||||
None => run(app, "shape.fill", json!({"none": true})),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let (m, a) = small_button_ex(ui, Icon::ShapeOutline, "Shape Outline", sel, false, true);
|
||||
if m.clicked() {
|
||||
let c = app.last_outline.clone();
|
||||
run(app, "shape.line", json!({"color": c}));
|
||||
}
|
||||
if let Some(a) = a {
|
||||
// P3(ribbon-w6): rb.A16
|
||||
widgets::color_popup(&a).show(|ui| outline_menu_base(app, ui, &sc));
|
||||
}
|
||||
let (main, arrow) = small_button_ex(ui, Icon::ShapeEffects, "Shape Effects", sel, false, true);
|
||||
if let Some(arrow) = arrow {
|
||||
// P3(ribbon-w6): rb.A16
|
||||
widgets::split_menu(&main, &arrow, |ui| {
|
||||
craft::ui::contract::ShowContainer::show(craft::ui::layout_components::Stack::new(), ui, |ui, cx| effects_menu(app, ui, cx))
|
||||
.inner
|
||||
.unwrap_or_default()
|
||||
});
|
||||
app.open_dialog("replaceFonts", json!({}));
|
||||
}
|
||||
});
|
||||
Button::command(CommandRef::with_params("view.pane", json!({"pane": "selection"})))
|
||||
.label(Word::plain("Selection Pane"))
|
||||
.icon(Icon::SelectionPane.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.show(ui);
|
||||
});
|
||||
row.group(RibbonGroup::new("home.designer", Word::plain("Design Ideas"), Icon::DesignIdeas.id().into()), |ui| {
|
||||
Button::command(CommandRef::with_params("view.pane", json!({"pane": "designer"})))
|
||||
.label(Word::plain("Design Ideas"))
|
||||
.icon(Icon::DesignIdeas.id())
|
||||
.arrangement(Arrangement::Stacked)
|
||||
.show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
// P3(ribbon-w6): rb.A4
|
||||
pub(super) fn home_base(app: &mut SlideApp, ui: &mut Ui) {
|
||||
let st = fmt_state(app);
|
||||
clipboard_group(app, ui);
|
||||
slides_group(app, ui);
|
||||
font_group(app, ui, &st);
|
||||
paragraph_group(app, ui, &st);
|
||||
group(ui, |ui| {
|
||||
big(app, ui, Icon::Picture, "Picture", "app.insertPictureDialog", json!({}));
|
||||
});
|
||||
drawing_group(app, ui);
|
||||
// Editing, as in PowerPoint: Find, Replace and Replace Fonts, then the Selection Pane.
|
||||
group(ui, |ui| {
|
||||
ui.vertical(|ui| {
|
||||
small(app, ui, Icon::Search, "Find", "app.find", json!({}));
|
||||
small(app, ui, Icon::Spelling, "Replace", "app.replace", json!({}));
|
||||
if small_button(ui, Icon::Fonts, "Replace Fonts…", enabled(app, "font.replace"), false).clicked() {
|
||||
app.dialog = Some(crate::dialogs::Dialog::new("replaceFonts"));
|
||||
}
|
||||
});
|
||||
// Also under Arrange, but that is disabled until something is selected (#132).
|
||||
big(app, ui, Icon::SelectionPane, "Selection\nPane", "view.pane", json!({"pane": "selection"}));
|
||||
});
|
||||
group(ui, |ui| {
|
||||
big(app, ui, Icon::DesignIdeas, "Design\nIdeas", "view.pane", json!({"pane": "designer"}));
|
||||
});
|
||||
}
|
||||
|
||||
/// Shows a command-bound painter toggle.
|
||||
#[allow(dead_code)] // P3(ribbon-w6): rb.A19
|
||||
pub(super) fn painter_toggle(app: &mut SlideApp, ui: &mut Ui, icon: Icon, label: &str, cmd: &str, armed: bool) {
|
||||
let _ = (app, ui, icon, label, cmd, armed);
|
||||
todo!("rb.A19")
|
||||
}
|
||||
|
||||
/// Opens this tab's ribbon groups.
|
||||
#[allow(dead_code)] // P3(ribbon-w6): rb.A4
|
||||
pub(crate) fn home(app: &mut SlideApp, row: &mut craft::menu::ribbon::RibbonRow<'_>) {
|
||||
let _ = (app, row);
|
||||
todo!("rb.A4")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user