Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
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
72 changes: 69 additions & 3 deletions crates/engine/src/cmd/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,19 +78,51 @@ pub fn runs_in_background(command: &str) -> Option<(&'static str, &'static str)>
IN_BACKGROUND.iter().find(|(c, ..)| *c == command).map(|(c, name, _)| (*c, *name))
}

/// Background exports that render map, layout, report, or scene text with installed fonts.
fn uses_fonts(command: &str) -> bool {
matches!(command, "share.exportMap" | "layout.export" | "report.export" | "map.exportOrbit" | "map.exportBlock")
}

#[cfg(test)]
thread_local! {
static TEST_CJK_SCAN_PENDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

fn cjk_scan_pending() -> bool {
#[cfg(test)]
if TEST_CJK_SCAN_PENDING.get() {
return true;
}
rustgis_render::fonts::cjk_roots_pending()
}

/// `command`'s export written here: it says what it wrote.
pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult {
let &(_, name, start) = IN_BACKGROUND.iter().find(|(c, ..)| *c == command).ok_or_else(|| format!("{command} isn't an export"))?;
if uses_fonts(command) && cjk_scan_pending() {
return Err("CJK font folder scan is still running; try exporting again in a moment".into());
}
let owner = s.continuation()?;
owner.check()?;
let current = owner.clone();
let still = std::sync::Arc::new(move || current.check().is_ok());
// The probe keeps authority checks at file commit even when the user cannot cancel this run.
let control = if s.stoppable { rustgis_analysis::control::Control::stoppable() } else { rustgis_analysis::control::Control::new() };
let wrote = crate::render::rustgis_tiles::cache::with_still(still, || {
let (mut wrote, pending_cjk) = crate::render::rustgis_tiles::cache::with_still(still, || {
let work = start(s, p)?;
written_under(name, &control, work)
if uses_fonts(command) {
let (res, hit) = rustgis_render::fonts::track_pending_cjk(|| written_under(name, &control, work));
Ok::<_, String>((res?, hit))
} else {
Ok((written_under(name, &control, work)?, false))
}
})?;
if pending_cjk {
wrote.diagnostics.push((
rustgis_data::diagnostics::Severity::Warning,
"CJK font folder scan started during this export; re-run it once the scan finishes if CJK text is missing.".into(),
));
}
s.check_continuation(&owner)
.map_err(|why| completion_with_notes(command, wrote.written_path.as_deref(), &wrote.completion_notes(), why))?;
said(s, wrote)
Expand Down Expand Up @@ -375,16 +407,27 @@ impl ExportRun {
/// Writes the file, or stages it if installing it needs the live session. `control` stops the
/// work and counts its progress (see [`rustgis_analysis::control`]). A cancelled export leaves
/// no file, or the one there before.
///
/// On Linux, font-drawing exports wait for any in-flight background CJK font-folder scan off
/// the UI thread so exported files do not omit CJK glyphs; that one-time bounded scan
/// (`MAX_DIRS = 2_000`, `MAX_FILES = 20_000`) does not observe `control` Cancel while waiting.
pub fn run(self, control: &std::sync::Arc<rustgis_analysis::control::Control>) -> Result<Wrote, String> {
let inputs = self.started.capture_inputs.then(rustgis_data::provenance::Capture::start);
let ExportRun { name, work, started } = self;
let command = started.command;
let owner = started.owner;
owner.check()?;
let current = owner.clone();
let still = std::sync::Arc::new(move || current.check().is_ok());
// A bug in a writer must not take the app down.
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
crate::render::rustgis_tiles::cache::with_still(still, || written_under(name, control, work))
crate::render::rustgis_tiles::cache::with_still(still, || {
if uses_fonts(command) {
rustgis_render::fonts::with_blocking_cjk_scan(|| written_under(name, control, work))
Comment thread
ninhhaidang marked this conversation as resolved.
Resolved
} else {
written_under(name, control, work)
}
})
}))
.unwrap_or_else(|_| Err(format!("{name} failed unexpectedly")))
.map(|w| Wrote { owner: Some(owner), crs_used: rustgis_data::raster::crs::take_used(), ..w });
Expand Down Expand Up @@ -521,4 +564,27 @@ mod tests {
});
assert!(written_under("Export Raster", &control, work).err().unwrap().contains("was cancelled"));
}

#[test]
fn write_here_rejects_font_exports_while_cjk_scan_is_pending() {
struct PendingGuard;
impl Drop for PendingGuard {
fn drop(&mut self) {
TEST_CJK_SCAN_PENDING.set(false);
}
}

let mut s = Session::new(crate::Project::default());
TEST_CJK_SCAN_PENDING.set(true);
let _guard = PendingGuard;

// Font-drawing synchronous exports fail fast rather than blocking the UI thread or writing missing glyphs.
let err = write_here(&mut s, &serde_json::json!({"path": "out.png"}), "share.exportMap").unwrap_err();
assert!(err.contains("CJK font folder scan is still running"), "{err}");

// Non-font exports (e.g. tables) are unaffected by a pending CJK scan and proceed to normal validation.
let table_err =
write_here(&mut s, &serde_json::json!({"layer": "NoSuchLayer", "path": "out.csv"}), "share.exportTable").unwrap_err();
assert!(!table_err.contains("CJK font folder scan"), "{table_err}");
}
}
45 changes: 45 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1901,6 +1901,12 @@ impl Session {
// A command may change a map's projection, or add layers to it.
if s.depth == 0 {
s.note_shown_systems();
if !ui_owns_cjk_scan_notice()
&& let Some(summary) = take_cjk_scan_summary_for_session()
&& let Some(msg) = summary.notice()
{
s.notify(msg, false);
}
}
// Native sessions without a drawing loop recover their own failed overviews.
// Named callers and sealed completions do not initiate unrelated maintenance.
Expand Down Expand Up @@ -4325,3 +4331,42 @@ impl Session {
self.project.gp_history.push(record);
}
}

/// Process-wide ownership of the one-shot CJK font-folder scan summary. Set by a UI front end so
/// neither the live session nor any temporary `Session::new` copy consumes the summary inside
/// [`Session::run`] before the UI can translate and emit it.
static UI_OWNS_CJK_SCAN_NOTICE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Marks this process as having a UI front end that takes and translates the one-shot CJK
/// font-folder scan summary itself, leaving it untouched in [`Session::run`].
pub fn claim_ui_cjk_scan_notice() {
UI_OWNS_CJK_SCAN_NOTICE.store(true, std::sync::atomic::Ordering::Release);
}

/// Whether a UI front end owns taking and translating the process-wide CJK scan summary.
pub fn ui_owns_cjk_scan_notice() -> bool {
#[cfg(test)]
if let Some(overridden) = TEST_UI_OWNS_CJK_SCAN_NOTICE.get() {
return overridden;
}
UI_OWNS_CJK_SCAN_NOTICE.load(std::sync::atomic::Ordering::Acquire)
}

#[cfg(test)]
thread_local! {
/// Thread-local override for [`take_cjk_scan_summary_for_session`] so tests can exercise
/// `Session::run`'s CJK scan notice wiring in parallel without mutating the global font cache.
static TEST_CJK_SCAN_SUMMARY: std::cell::RefCell<Option<Option<rustgis_render::fonts::CjkRootScanSummary>>> =
const { std::cell::RefCell::new(None) };
/// Thread-local override for [`ui_owns_cjk_scan_notice`] so parallel unit tests can cover
/// headless sessions even after another test claims UI ownership.
static TEST_UI_OWNS_CJK_SCAN_NOTICE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

fn take_cjk_scan_summary_for_session() -> Option<rustgis_render::fonts::CjkRootScanSummary> {
#[cfg(test)]
if let Some(summary) = TEST_CJK_SCAN_SUMMARY.with_borrow_mut(|slot| slot.as_mut().map(Option::take)) {
return summary;
}
rustgis_render::fonts::take_cjk_scan_summary()
}
87 changes: 87 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63093,3 +63093,90 @@ fn a_transparency_reads_back_without_float_noise() {
assert_eq!(crate::cmd::project::percent(33.3), json!(33.3));
assert_eq!(crate::cmd::project::percent(0.0), json!(0.0));
}

/// Headless sessions emit the CJK font-folder scan notice once through `Session::run` when a
/// fallback scan was lossy, stay silent when clean, and leave the summary untouched across every
/// `Session::new` copy once a UI shell claims process-wide ownership for translation.
#[test]
fn headless_session_run_emits_cjk_scan_notice_only_when_lossy() {
use rustgis_render::fonts::CjkRootScanSummary;

struct SummaryGuard;
impl SummaryGuard {
fn set(summary: Option<CjkRootScanSummary>) -> Self {
crate::TEST_CJK_SCAN_SUMMARY.with_borrow_mut(|slot| *slot = Some(summary));
Self
}
}
impl Drop for SummaryGuard {
fn drop(&mut self) {
crate::TEST_CJK_SCAN_SUMMARY.with_borrow_mut(|slot| *slot = None);
}
}

struct UiNoticeGuard;
impl UiNoticeGuard {
fn set(value: bool) -> Self {
crate::TEST_UI_OWNS_CJK_SCAN_NOTICE.set(Some(value));
Self
}
}
impl Drop for UiNoticeGuard {
fn drop(&mut self) {
crate::TEST_UI_OWNS_CJK_SCAN_NOTICE.set(None);
}
}

let lossy = CjkRootScanSummary {
truncated_dirs: 2,
unreadable_dirs: 1,
entry_errors: 0,
thread_spawn_failed: false,
sample_path: Some(std::path::PathBuf::from("/run/host/fonts")),
};

// Lossy summary on a headless session emits one English notice and consumes it; clean/absent stay silent.
{
let _ui_guard = UiNoticeGuard::set(false);
assert!(!crate::ui_owns_cjk_scan_notice());
let mut headless = Session::new(Project::default());
{
let _guard = SummaryGuard::set(Some(lossy.clone()));
let mark = headless.notice_mark();
headless.run("connection.list", &Value::Null).unwrap();
let notices = headless.notices_since(mark);
assert_eq!(notices.len(), 1, "{notices:?}");
assert!(!notices[0].error);
assert!(notices[0].text.contains("CJK font folder search stopped early"), "{}", notices[0].text);
assert!(notices[0].text.contains("2 folder(s) reached the scan limit"), "{}", notices[0].text);
assert!(notices[0].text.contains("1 unreadable folder(s)"), "{}", notices[0].text);
assert!(notices[0].text.contains("/run/host/fonts"), "{}", notices[0].text);

// One-shot: a subsequent command emits nothing.
let mark2 = headless.notice_mark();
headless.run("connection.list", &Value::Null).unwrap();
assert!(headless.notices_since(mark2).is_empty(), "{:?}", headless.notices_since(mark2));
}

for clean in [Some(CjkRootScanSummary::default()), None] {
let _guard = SummaryGuard::set(clean);
let mark = headless.notice_mark();
headless.run("connection.list", &Value::Null).unwrap();
assert!(headless.notices_since(mark).is_empty(), "clean scan must stay silent: {:?}", headless.notices_since(mark));
}
}

// Once a UI front end claims process-wide ownership, even a separate temporary Session::new
// copy leaves the summary untouched inside Session::run so ui-egui can translate it.
crate::claim_ui_cjk_scan_notice();
assert!(crate::ui_owns_cjk_scan_notice());
let mut copy = Session::new(Project::default());
{
let _guard = SummaryGuard::set(Some(lossy));
let mark = copy.notice_mark();
copy.run("connection.list", &Value::Null).unwrap();
assert!(copy.notices_since(mark).is_empty(), "{:?}", copy.notices_since(mark));
let still_pending = crate::TEST_CJK_SCAN_SUMMARY.with_borrow(|slot| slot.as_ref().and_then(Option::as_ref).is_some());
assert!(still_pending, "copy session must not consume the CJK scan summary once UI owns it");
}
}
32 changes: 31 additions & 1 deletion crates/render/src/families.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ pub fn warm_up() {
if WARMING.swap(true, Ordering::Relaxed) {
return;
}
crate::fonts::enable_async_cjk_scan();
#[cfg(not(target_arch = "wasm32"))]
if std::thread::Builder::new()
.name("font-index".into())
Expand Down Expand Up @@ -201,9 +202,14 @@ fn font_dirs() -> Vec<PathBuf> {
} else if cfg!(target_os = "android") {
// Android's app home has no system fonts; manufacturer faces can live on /product.
dirs.extend(crate::fonts::ANDROID_FONT_DIRS.iter().map(PathBuf::from));
} else if cfg!(target_os = "linux") {
dirs.extend(crate::fonts::linux_font_roots_with(
std::env::var_os("XDG_DATA_HOME").as_deref(),
home.as_deref().map(Path::as_os_str),
));
} else {
dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(PathBuf::from));
match std::env::var_os("XDG_DATA_HOME") {
match std::env::var_os("XDG_DATA_HOME").filter(|v| crate::fonts::is_posix_absolute(v)) {
Some(d) => dirs.push(PathBuf::from(d).join("fonts")),
None => dirs.extend(home.iter().map(|h| h.join(".local").join("share").join("fonts"))),
}
Expand Down Expand Up @@ -518,4 +524,28 @@ mod tests {
let table = [0u8, 0, 0, 1, 0, 18, 0, 3, 0, 1, 4, 9, 0, 1, 0xff, 0xff, 0, 0];
assert_eq!(name(&table, 1), None);
}

#[test]
fn linux_font_roots_include_flatpak_host_and_xdg_roots() {
use std::ffi::OsStr;

let dirs = crate::fonts::linux_font_roots_with(Some(OsStr::new("/xdg/data")), Some(OsStr::new("/home/alice")));
assert_eq!(
dirs,
vec![
PathBuf::from("/usr/share/fonts"),
PathBuf::from("/usr/local/share/fonts"),
PathBuf::from("/run/host/fonts"),
PathBuf::from("/run/host/local-fonts"),
PathBuf::from("/run/host/user-fonts"),
PathBuf::from("/xdg/data/fonts"),
PathBuf::from("/home/alice/.fonts"),
]
);
let fallback = crate::fonts::linux_font_roots_with(None, Some(OsStr::new("/home/alice")));
assert!(fallback.contains(&PathBuf::from("/home/alice/.local/share/fonts")));

let deduped = crate::fonts::linux_font_roots_with(Some(OsStr::new("/usr/share")), Some(OsStr::new("/home/alice")));
assert_eq!(deduped.iter().filter(|p| *p == &PathBuf::from("/usr/share/fonts")).count(), 1);
}
}
Loading
Loading