Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/system-fonts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
### Changes
- **Fonts installed on your computer** - The Font menu in Settings > Appearance now lists every font installed on the machine, each name drawn in its own face. A monospace font sets the whole app; any other font sets the interface and leaves data and code in the pairing's code font. The Separate fonts pickers list them too.
- **Font pairings name their faces** - Each pairing in the Font menu now says which two fonts it sets, for example "Inter + Source Code Pro".

### Fixes
- **The SQL editor and terminal follow the Font setting** - They were pinned to JetBrains Mono, so picking Source Code Pro or Fira Code changed the data grid but not the editor.
54 changes: 54 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ tauri-build = { version = "2.6.2", features = [] }
[dependencies]
serde_json = { version = "1.0", features = ["preserve_order", "raw_value"] }
serde = { version = "1.0", features = ["derive"] }
# Lists the installed font families for the font pickers (system_fonts.rs).
fontdb = "0.24"
ttf-parser = "0.25"
log = "0.4"
tauri = { version = "2.11.2", features = ["macos-private-api", "image-png"] }
tauri-plugin-opener = "2"
Expand Down
2 changes: 2 additions & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ mod proc;
pub(crate) mod proxy;
mod providers;
mod secrets;
mod system_fonts;
mod sync;
mod updates;
mod quit;
Expand Down Expand Up @@ -966,6 +967,7 @@ pub fn run() {
secrets::conn_secrets_write,
secrets::conn_secrets_read_fresh,
secrets::conn_secrets_merge,
system_fonts::system_fonts,
metrics::get_app_metrics,
metrics::set_process_title,
commands::enable_autostart,
Expand Down
118 changes: 118 additions & 0 deletions src-tauri/src/system_fonts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
//! The font families installed on this machine, for the font pickers in
//! Settings > Appearance. The webview can draw any installed family by name, but
//! WebKit has no API to list them (`queryLocalFonts` is Chromium-only), so the
//! list comes from here: fontdb finds the files in the OS font folders (and,
//! on Linux, the fontconfig setup), ttf-parser reads what each one can draw.

use serde::Serialize;
use std::collections::BTreeMap;
use std::sync::OnceLock;

#[derive(Clone, Serialize)]
pub struct SystemFont {
pub family: String,
/// Every face of the family is fixed-width.
pub mono: bool,
}

static FONTS: OnceLock<Vec<SystemFont>> = OnceLock::new();

/// What a face can draw, read from its tables: `None` when it cannot be read
/// or has no Unicode Latin letters (emoji, symbol, dingbat and CJK-only faces,
/// which would draw a font's name in pictures), else whether it is fixed-width.
/// The fixed-pitch flag alone is wrong both ways (FreeMono lacks it), so equal
/// advances for `i` and `M` count too.
fn latin_face(data: &[u8], index: u32) -> Option<bool> {
let face = ttf_parser::Face::parse(data, index).ok()?;
// glyph_index only reads Unicode cmap subtables: a symbol-encoded font
// (Standard Symbols, the URW dingbats) has none for these.
let glyph = |c: char| face.glyph_index(c);
let (i, m) = (glyph('i')?, glyph('M')?);
glyph('0')?;
// Some symbol fonts map ASCII too, to other shapes (Standard Symbols puts
// alpha at `a`). A named glyph for `a` must be named for it; a font without
// glyph names (post table version 3) is taken at its cmap's word.
let a = glyph('a')?;
if let Some(name) = face.glyph_name(a) {
if !(name == "a" || name.starts_with("a.") || name.eq_ignore_ascii_case("uni0061")) {
return None;
}
}
let advance = |g| face.glyph_hor_advance(g).unwrap_or(0);
Some(face.is_monospaced() || (advance(i) > 0 && advance(i) == advance(m)))
}

fn scan() -> Vec<SystemFont> {
let mut db = fontdb::Database::new();
db.load_system_fonts();
// Family name -> fixed-width, judged from its first readable face (the
// regular one in practice; a family's faces share their pitch).
let mut by_family: BTreeMap<String, Option<bool>> = BTreeMap::new();
for face in db.faces() {
// The first name is the English (or only) one, the one CSS matches.
let Some((family, _)) = face.families.first() else { continue };
let family = family.trim();
// Dot-prefixed families are macOS's private system faces (.SF NS, ...):
// WebKit refuses them by name, and SF Pro is offered as "System UI".
if family.is_empty() || family.starts_with('.') {
continue;
}
if matches!(by_family.get(family), Some(Some(_))) {
continue;
}
let judged = db.with_face_data(face.id, latin_face).flatten();
by_family.insert(family.to_string(), judged);
}
by_family
.into_iter()
.filter_map(|(family, mono)| mono.map(|mono| SystemFont { family, mono }))
.collect()
}

fn sorted(mut fonts: Vec<SystemFont>) -> Vec<SystemFont> {
fonts.sort_by_cached_key(|f| f.family.to_lowercase());
fonts
}

/// Installed families, sorted by name. Scanned once per launch: reading every
/// font file's header takes a few hundred ms on a machine with many fonts.
#[tauri::command]
pub async fn system_fonts() -> Result<Vec<SystemFont>, String> {
if let Some(f) = FONTS.get() {
return Ok(f.clone());
}
let fonts = tauri::async_runtime::spawn_blocking(|| sorted(scan()))
.await
.map_err(|e| format!("Could not list the installed fonts: {e}"))?;
Ok(FONTS.get_or_init(|| fonts).clone())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn sorts_by_name_ignoring_case() {
let fonts = sorted(vec![
SystemFont { family: "ubuntu".into(), mono: false },
SystemFont { family: "Adwaita Mono".into(), mono: true },
SystemFont { family: "Liberation Mono".into(), mono: true },
]);
let names: Vec<_> = fonts.iter().map(|f| f.family.as_str()).collect();
assert_eq!(names, ["Adwaita Mono", "Liberation Mono", "ubuntu"]);
}

#[test]
fn scan_lists_only_faces_that_draw_latin() {
let fonts = scan();
assert!(fonts.iter().all(|f| !f.family.starts_with('.') && !f.family.is_empty()));
// Where this machine has them: symbol and emoji faces are left out, and
// FreeMono (no fixed-pitch flag) still counts as fixed-width.
for hidden in ["Standard Symbols PS", "D050000L", "Noto Color Emoji"] {
assert!(fonts.iter().all(|f| f.family != hidden), "{hidden} listed");
}
if let Some(free) = fonts.iter().find(|f| f.family == "FreeMono") {
assert!(free.mono);
}
}
}
18 changes: 9 additions & 9 deletions src/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,11 @@
--editor-font-size: 13px;
/* 1.5 ratio - matches VS Code / Cursor's default editor line height. */
--editor-line-height: 20px;
/* Dedicated code font for the code editors, kept independent of the app's UI /
data-grid mono (`--font-mono`) - same separation VS Code makes between its
"editor font" and everything else. JetBrains Mono is a true code typeface:
heavier, even rhythm, designed ligatures. */
--editor-font-family: "JetBrains Mono Variable", "Geist Mono Variable", ui-monospace, monospace;
/* No --editor-font-family here: the SQL editor and the terminal read
`var(--editor-font-family, var(--font-mono))`, so they follow the font
picked in Settings like the data grid does. Separate fonts sets it when the
editor gets a face of its own. (It used to pin JetBrains Mono, so picking
Source Code Pro or Fira Code left the editor and terminal in another face.) */

/* ── Elevation system ──────────────────────────────────────────────────────
Layered shadows for raised surfaces (menus, popovers, dialogs, cards).
Expand Down Expand Up @@ -548,10 +548,10 @@ html[data-os="linux"] { --window-radius: 8px; }
and Linux. System fonts (SF Pro, Segoe UI, desktop sans) and native OS
smoothing already render at their designed weight, so never synthesize
weights on them. */
html[data-os="windows"][data-smoothing="grayscale"]:not([data-font="apple"]) {
html[data-os="windows"][data-smoothing="grayscale"]:not([data-font="apple"]):not([data-font="custom"]) {
font-weight: 430;
}
html[data-os="linux"][data-smoothing="grayscale"]:not([data-font="apple"]) {
html[data-os="linux"][data-smoothing="grayscale"]:not([data-font="apple"]):not([data-font="custom"]) {
font-weight: 450;
}
/* Small UI text: let the face's own kerning and contextual forms apply on
Expand Down Expand Up @@ -706,7 +706,7 @@ html[data-os="linux"] { --window-radius: 8px; }
font-optical-sizing: auto;
}

html[data-os='windows'][data-smoothing='grayscale']:not([data-font='apple']) :is(
html[data-os='windows'][data-smoothing='grayscale']:not([data-font='apple']):not([data-font='custom']) :is(
[data-slot='context-menu-content'],
[data-slot='dropdown-menu-content'],
[data-slot='select-content'],
Expand All @@ -719,7 +719,7 @@ html[data-os="linux"] { --window-radius: 8px; }
font-weight: 430;
}

html[data-os='linux'][data-smoothing='grayscale']:not([data-font='apple']) :is(
html[data-os='linux'][data-smoothing='grayscale']:not([data-font='apple']):not([data-font='custom']) :is(
[data-slot='context-menu-content'],
[data-slot='dropdown-menu-content'],
[data-slot='select-content'],
Expand Down
11 changes: 8 additions & 3 deletions src/lib/components/SelectMenu.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
// regardless of how many items it holds (see `searchThreshold` there).
// Drop-in replacement for bits-ui <Select> in the common case.
//
// <SelectMenu value={x} onValueChange={setX} items={[{value,label,icon?,hint?}]} />
// <SelectMenu value={x} onValueChange={setX} items={[{value,label,icon?,hint?,desc?,font?}]} />
//
// `desc` is muted text after the label (a row's detail); `font` draws the
// label in that CSS font-family, as font pickers show each face in itself.
//
// For custom leading visuals (font preview, variable-weight icon, brand icon)
// pass a `lead` snippet - it receives the full item and renders both the
Expand Down Expand Up @@ -63,14 +66,16 @@
>
<span class="flex min-w-0 items-center gap-2">
{#if lead && selected}{@render lead(selected)}{:else if selected?.icon}<Icon name={selected.icon} class="size-3.5 shrink-0 text-muted-foreground" />{/if}
<span class="truncate font-medium">{selected?.label ?? placeholder}</span>
<span class="truncate font-medium" style:font-family={selected?.font}>{selected?.label ?? placeholder}</span>
</span>
<Icon name="chevron-down" class="size-3.5 shrink-0 text-muted-foreground" />
</button>
{/snippet}
{#snippet item(it)}
{#if lead}{@render lead(it)}{:else if it.icon}<Icon name={it.icon} class="size-4 shrink-0 text-muted-foreground" />{/if}
<span class="min-w-0 flex-1 truncate">{it.label}</span>
<!-- Fixed line height, label top-aligned: a face with tall metrics drawn
in its own font would otherwise make its row taller than the rest. -->
<span class="min-w-0 flex-1 truncate leading-5"><span class="align-top" style:font-family={it.font}>{it.label}</span>{#if it.desc}<span class="ml-2 text-muted-foreground">{it.desc}</span>{/if}</span>
{#if it.hint}<span class="shrink-0 text-ui-3xs text-muted-foreground">{it.hint}</span>{/if}
{#if String(it.value) === String(value)}<Icon name="check" class="ml-auto size-3.5 shrink-0 text-primary" />{/if}
{/snippet}
Expand Down
Loading
Loading