mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-21 20:40:02 +00:00
Merge pull request #3347 from storytold/stack/u8
Land #3313, #3300, #3316, #1873: arrowheads in DIMSTYLE, single-instance tests, Thai in the MTEXT editor, DIMPOST on angular dimensions
This commit is contained in:
@@ -331,16 +331,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, and its socket path.
|
||||
/// A fresh folder for one test, and its socket path. Both names stay short: a Windows socket path
|
||||
/// holds at most 107 bytes, and a long `%TEMP%` already uses most of them.
|
||||
#[cfg(windows)]
|
||||
fn socket_dir(test: &str) -> (Cleanup, PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-single-instance-{}-{test}", std::process::id()));
|
||||
let dir = std::env::temp_dir().join(format!("cc-si-{}-{test}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("instance-test.sock");
|
||||
let path = dir.join("t.sock");
|
||||
(Cleanup(dir), path)
|
||||
}
|
||||
|
||||
/// Whether a socket can be bound at `path` here. It can't when `%TEMP%` is too long or lives
|
||||
/// under a redirected `%LOCALAPPDATA%`; the socket tests then skip instead of failing.
|
||||
#[cfg(windows)]
|
||||
fn can_bind(path: &std::path::Path) -> bool {
|
||||
let bound = uds_windows::UnixListener::bind(path)
|
||||
.map(drop)
|
||||
.map_err(|e| {
|
||||
// Straight to stderr: the test harness hides `eprintln!` from a test that passes.
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr(), "skipping: no AF_UNIX socket at {}: {e}", path.display());
|
||||
})
|
||||
.is_ok();
|
||||
let _ = std::fs::remove_file(path);
|
||||
bound
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_test_socket_path_stays_far_below_the_limit() {
|
||||
// Its own folder, with a name as long as the longest one used here: `socket_dir` empties the
|
||||
// folder, and the launches test may be using "together" at the same moment.
|
||||
let (_dir, path) = socket_dir("lengthck");
|
||||
let added = path.as_os_str().len() - std::env::temp_dir().as_os_str().len();
|
||||
assert!(added <= 40, "{added} bytes on top of %TEMP%");
|
||||
}
|
||||
|
||||
/// The whole exchange over a real socket: a stale socket file is taken over, a later launch
|
||||
/// hands its files to that listener, one that asked for its own window gets it, and a request
|
||||
/// naming a relative path is refused.
|
||||
@@ -348,6 +375,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_later_launch_hands_its_files_to_the_first() {
|
||||
let (dir, path) = socket_dir("handoff");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
drop(uds_windows::UnixListener::bind(&path).unwrap());
|
||||
assert!(path.exists(), "the stale socket file stays behind");
|
||||
|
||||
@@ -369,6 +399,9 @@ mod tests {
|
||||
fn launches_at_once_open_one_window() {
|
||||
const LAUNCHES: usize = 6;
|
||||
let (dir, path) = socket_dir("together");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
let start = Arc::new(std::sync::Barrier::new(LAUNCHES));
|
||||
let launches: Vec<_> = (0..LAUNCHES)
|
||||
.map(|i| {
|
||||
|
||||
@@ -317,6 +317,23 @@ fn tolerance_justification_angular_zeros_and_arc_symbol() {
|
||||
assert_eq!(dim_lines(&g1).len(), dim_lines(&g2).len() + 1, "the symbol drawn over the text");
|
||||
}
|
||||
|
||||
/// DIMPOST frames the angle too, as AutoCAD 2026 does to its own angular dimensions (#1653).
|
||||
#[test]
|
||||
fn dimpost_applies_to_angular_dimensions() {
|
||||
let mut s = Session::new();
|
||||
set(&mut s, "DIMPOST", json!("<> m"));
|
||||
set(&mut s, "DIMADEC", json!(1));
|
||||
// Vertex and two points.
|
||||
s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "90.0° m");
|
||||
// Two lines picked: the same suffix.
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [5, 8.660254037844387]] })).unwrap();
|
||||
let h: Vec<String> = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).map(|e| e.handle.hex()).collect();
|
||||
s.execute("dimangular", &json!({ "lines": h, "at": [4, 1] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "60.0° m");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetypes_and_lineweights_of_dimension_and_extension_lines() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -477,6 +477,18 @@ mod tests {
|
||||
ttf::fallback_for('\u{0E01}').filter(|f| ['\u{0E14}', '\u{0E34}', '\u{0E4C}', '\u{0E33}', '\u{0E10}'].iter().all(|c| f.has_glyph(*c)))
|
||||
}
|
||||
|
||||
/// A Thai face's letters are measured in ems: ก has neither ascender nor descender, ไ rises
|
||||
/// above it, and a space or an unmapped character has no height.
|
||||
#[test]
|
||||
fn thai_glyph_heights_are_measured_in_ems() {
|
||||
let Some(face) = thai_face() else { return };
|
||||
let ko = face.glyph_height('ก').unwrap_or_default();
|
||||
assert!((0.2..1.0).contains(&ko), "ก is {ko} em");
|
||||
assert!(face.glyph_height('ไ').is_some_and(|h| h > ko), "ไ is taller than ก");
|
||||
assert_eq!(face.glyph_height(' '), None);
|
||||
assert_eq!(face.glyph_height('\u{10fffd}'), None);
|
||||
}
|
||||
|
||||
/// Lowest point of the glyph that shows `c`.
|
||||
fn bottom_of(sh: &Shaped, c: char) -> Option<f64> {
|
||||
let t = sh.text.iter().find(|t| t.ch == c)?;
|
||||
|
||||
@@ -95,6 +95,17 @@ impl Face {
|
||||
Some(s.chars().filter(|c| !c.is_control()).take(80).collect::<String>()).filter(|s| !s.trim().is_empty())
|
||||
})
|
||||
}
|
||||
/// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the
|
||||
/// face doesn't map `c` or its glyph has no outline (a space, or one too big to keep).
|
||||
pub fn glyph_height(&self, c: char) -> Option<f64> {
|
||||
let g = glyph(self, c);
|
||||
if !g.mapped {
|
||||
return None;
|
||||
}
|
||||
let (low, high) = g.contours.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), p| (low.min(p.y), high.max(p.y)));
|
||||
let height = (high - low) / f64::from(UPEM);
|
||||
(height.is_finite() && height > 0.0).then_some(height)
|
||||
}
|
||||
|
||||
/// The glyph ids the face's character map gives `chars` (`None` for an unmapped one).
|
||||
pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec<Option<u32>> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The anonymous `*D` block written for a dimension (what other programs draw) holds its text at
|
||||
//! the height it is drawn at: the dimension's overrides and DIMSCALE (0 = the drawing's) count
|
||||
//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646).
|
||||
//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646), and
|
||||
//! the style's DIMPOST reaches angular dimensions' blocks too (#1653).
|
||||
|
||||
use cadcraft_doc::{Common, DimKind, DimStyle, Dimension, Drawing, EntityKind, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
@@ -130,3 +131,98 @@ fn dwg_angular_block_text_keeps_the_decimal_separator() {
|
||||
assert_eq!(texts, [expected], "DIMDSEP override: {separator_override:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The group 1 (contents) values of every MTEXT in the BLOCKS section, in file order.
|
||||
fn block_mtext_contents(dxf: &str) -> Vec<String> {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
let t: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
|
||||
let blocks = t.iter().position(|&(c, v)| c == "2" && v == "BLOCKS").unwrap();
|
||||
let end_blocks = blocks + t[blocks..].iter().position(|&(c, v)| c == "0" && v == "ENDSEC").unwrap();
|
||||
let mut out = Vec::new();
|
||||
let mut i = blocks;
|
||||
while let Some(k) = t[i..end_blocks].iter().position(|&(c, v)| c == "0" && v == "MTEXT") {
|
||||
let start = i + k;
|
||||
let end = t[start + 1..end_blocks].iter().position(|&(c, _)| c == "0").map_or(end_blocks, |n| start + 1 + n);
|
||||
// Contents are group 1 (the last chunk) after any 250-char group 3 chunks.
|
||||
out.push(t[start + 1..end].iter().filter(|&&(c, _)| c == "3" || c == "1").map(|&(_, v)| v).collect());
|
||||
i = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An angular dimension whose style sets DIMPOST `post` and one decimal place for angles.
|
||||
fn posted_angular_drawing(kind: DimKind, points: [Vec3; 5], post: &str) -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.dim_styles.iter_mut().for_each(|s| {
|
||||
s.post = post.into();
|
||||
s.angular_decimals = 1;
|
||||
});
|
||||
let [p13, p14, p15, p16, defpt] = points;
|
||||
let dm = Dimension {
|
||||
kind,
|
||||
defpt,
|
||||
text_mid: Vec3::ZERO,
|
||||
p13,
|
||||
p14,
|
||||
p15,
|
||||
p16,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 0.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: None,
|
||||
overrides: Default::default(),
|
||||
assoc: Vec::new(),
|
||||
marks: Default::default(),
|
||||
insertion_point: Vec3::ZERO,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The DXF text of the drawing's one dimension block.
|
||||
fn dxf_block_text(d: &Drawing) -> String {
|
||||
let mut texts = block_mtext_contents(&cadcraft_io::write_dxf(d));
|
||||
assert_eq!(texts.len(), 1, "{texts:?}");
|
||||
texts.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimpost_reaches_three_point_and_two_line_angular_dimension_blocks() {
|
||||
// Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt.
|
||||
let three_point = posted_angular_drawing(
|
||||
DimKind::Angular3P,
|
||||
[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
// The DXF is ASCII: the degree sign is its `\U+00B0` escape.
|
||||
assert_eq!(dxf_block_text(&three_point), "90.0\\U+00B0 m");
|
||||
// Lines p13-p14 (along +X) and defpt-p15 (45°), the arc through p16.
|
||||
let two_line = posted_angular_drawing(
|
||||
DimKind::Angular,
|
||||
[Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0), Vec3::new(15.0, 15.0, 0.0), Vec3::new(4.0, 1.5, 0.0), Vec3::new(-5.0, -5.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
assert_eq!(dxf_block_text(&two_line), "45.0\\U+00B0 m");
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn dwg_angular_block_text_keeps_dimpost() {
|
||||
use cadcraft_io::{SaveOptions, Version};
|
||||
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
|
||||
// Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt.
|
||||
let d = posted_angular_drawing(
|
||||
DimKind::Angular3P,
|
||||
[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
let dwg = cadcraft_io::write_with(&d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap();
|
||||
let from_dwg = String::from_utf8(craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let mut texts = block_mtext_contents(&from_dwg);
|
||||
assert_eq!(texts.len(), 1, "{texts:?}");
|
||||
assert_eq!(texts.remove(0), "90.0° m");
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! fixed-length extension lines (DIMFXL/DIMFXLON), text placement (DIMTAD, DIMTVP, DIMJUST,
|
||||
//! DIMTIH/DIMTOH, DIMGAP, DIMTMOVE) and text formatting (DIMLUNIT, DIMDEC, DIMZIN, DIMRND,
|
||||
//! DIMPOST, DIMTOL/DIMLIM with DIMTZIN and DIMTOLJ, DIMALT with DIMALTU/DIMALTZ/DIMALTRND,
|
||||
//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL).
|
||||
//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL). DIMPOST wraps angles as well, as
|
||||
//! AutoCAD does (#1653).
|
||||
|
||||
use cadcraft_doc::{DimKind, DimStyle, Dimension};
|
||||
use cadcraft_fonts::{MTextParams, TextFont};
|
||||
|
||||
@@ -67,7 +67,7 @@ fn tol_height_code(st: &DimStyle) -> String {
|
||||
}
|
||||
|
||||
/// Apply measurement placeholders or append a dimension suffix, bounding the resulting UTF-8 text.
|
||||
fn post(template: &str, meas: &str) -> String {
|
||||
pub(super) fn post(template: &str, meas: &str) -> String {
|
||||
if template.contains("<>") {
|
||||
bounded_replace(template, meas)
|
||||
} else {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::text::{apply_override, inspected, linear_text};
|
||||
use super::text::{apply_override, inspected, linear_text, post};
|
||||
use super::{Arrowhead, DimConfig, DimGeometry, DimKind, Vec2, ext_line, readable};
|
||||
use crate::units::format_angle_with_separator;
|
||||
use cadcraft_geom::{Arc, ccw_sweep};
|
||||
@@ -178,8 +178,9 @@ pub(super) fn draw_angular(config: &DimConfig<'_>, g: &mut DimGeometry, text_ang
|
||||
g.measurement = sweep;
|
||||
// DIMAZIN 1 / 2 suppress leading / trailing zeros (DIMZIN's bits 4 / 8).
|
||||
let azin = (st.angular_zero_suppression & 3) * 4;
|
||||
let txt = format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator);
|
||||
// DIMPOST is a linear-dimension prefix/suffix; angles have their own format only.
|
||||
// DIMPOST wraps the angle too, as AutoCAD 2026 does to its own 2-line and 3-point
|
||||
// angular dimensions ("36.9° m" for a style with "<> m"; issue #1653, after #376).
|
||||
let txt = post(&st.post, &format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator));
|
||||
g.mtext = inspected(apply_override(&txt, d), d);
|
||||
let mut pts = Vec::new();
|
||||
arc.tessellate(r * 1e-3, &mut pts);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Dimension text formatting (issue #373): DIMRND rounds the measurement only, tolerances use
|
||||
//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST is not added to angles.
|
||||
//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST wraps angles too (#1653).
|
||||
|
||||
use cadcraft_doc::{DimKind, DimStyle, Dimension};
|
||||
use cadcraft_geom::Vec3;
|
||||
@@ -60,18 +60,23 @@ fn dimrnd_rounds_neither_tolerances_nor_alternate_units() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimpost_is_not_added_to_angular_dimensions() {
|
||||
fn dimpost_applies_to_angular_dimensions_too() {
|
||||
let mut a = linear(0.0);
|
||||
a.kind = DimKind::Angular3P;
|
||||
a.p15 = Vec3::ZERO;
|
||||
a.p13 = Vec3::new(10.0, 0.0, 0.0);
|
||||
a.p14 = Vec3::new(0.0, 10.0, 0.0);
|
||||
a.defpt = Vec3::new(3.0, 3.0, 0.0);
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°");
|
||||
// Linear dimensions keep it, and an angular text override still wraps the angle.
|
||||
// AutoCAD 2026 applies the style's DIMPOST to angular dimensions it builds: with "<> m"
|
||||
// its own 2-line and 3-point dimensions read "36.9° m" (#1653, follow-up to #373/#376).
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm");
|
||||
// A prefix before `<>` works as on a linear dimension.
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "A=<>"})), "A=90°");
|
||||
// Linear dimensions keep it, and an angular text override wraps the posted angle, as for
|
||||
// a linear dimension.
|
||||
assert_eq!(text(&linear(10.0), serde_json::json!({"DIMPOST": "<>mm", "DIMDEC": 1})), "10.0mm");
|
||||
a.text = "<> TYP".into();
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90° TYP");
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm TYP");
|
||||
}
|
||||
|
||||
fn angular(radians: f64) -> Dimension {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Drawing text in the interface. egui's bundled faces and the fonts
|
||||
//! [`crate::theme::install_fonts`] loads cover the interface's own languages, but the interface
|
||||
//! also shows drawing text, which can be in any script the drawing uses: MTEXT contents in the
|
||||
//! in-place editor, layer, layout and block names, a prompt that quotes a text. A character none
|
||||
//! of those fonts has would be a box, while the canvas draws it from a fallback font.
|
||||
//!
|
||||
//! An egui font provider closes that gap: egui asks it once per family and character no
|
||||
//! installed font has, and it answers with the face drawing text takes for that character
|
||||
//! ([`cadcraft_fonts::ttf::fallback_for`]), so the interface shows what the canvas shows. The
|
||||
//! provider hands egui the font table's own bytes: nothing is bundled, read again or copied.
|
||||
//!
|
||||
//! A fallback face is sized to the interface text, not to its own em: the Thai faces drawings use
|
||||
//! (Cordia New, Angsana New) draw their letters small for their size, so their consonants are
|
||||
//! scaled up to the interface's x-height ([`scale`]). Its glyphs sit on the interface text's
|
||||
//! baseline, and a line with them grows to fit their stacked marks.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_fonts::ttf::Face;
|
||||
|
||||
/// Let egui ask the drawing-text fallback for characters no interface font has. Once per
|
||||
/// context: providers outlive the `set_fonts` of [`crate::theme::install_fonts`], so a second
|
||||
/// call (a language change) adds nothing.
|
||||
pub(crate) fn install(ctx: &egui::Context) {
|
||||
let id = egui::Id::unique("cadcraft::drawing_fonts");
|
||||
let installed = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::<bool>(id), true));
|
||||
if !installed {
|
||||
ctx.add_font_provider(Arc::new(|request: &egui::FallbackRequest<'_>| font_for(request.cluster, cadcraft_fonts::ttf::fallback_for)));
|
||||
}
|
||||
}
|
||||
|
||||
/// How tall a lowercase x is in the interface faces, in ems (Ubuntu Light, egui's bundled face,
|
||||
/// 0.52; Segoe UI 0.50). A Thai consonant without ascender or descender (ก) is about as tall in
|
||||
/// the Thai faces made for screens (Leelawadee UI 0.51, Tahoma and Noto Sans Thai 0.56).
|
||||
const X_HEIGHT: f64 = 0.52;
|
||||
/// The most a fallback face is scaled up, so a face with an odd or tiny reference letter never
|
||||
/// draws huge text. Cordia New needs 1.28, Angsana New 1.30.
|
||||
const MAX_SCALE: f64 = 1.5;
|
||||
|
||||
/// The font for the first character of `cluster`: the face `fallback` finds for it, if any.
|
||||
fn font_for(cluster: &str, fallback: impl Fn(char) -> Option<Face>) -> Option<egui::FontInsert> {
|
||||
let c = cluster.chars().next()?;
|
||||
fallback(c).map(|face| font_insert(&face, c))
|
||||
}
|
||||
|
||||
/// The letter of `c`'s script that the interface's x-height measures: a Thai consonant without
|
||||
/// ascender or descender, else the face's own Latin x.
|
||||
fn reference_letter(c: char) -> char {
|
||||
if ('\u{0e00}'..='\u{0e7f}').contains(&c) { 'ก' } else { 'x' }
|
||||
}
|
||||
|
||||
/// How much a face is scaled up whose reference letter is `height` ems tall: to [`X_HEIGHT`],
|
||||
/// at most [`MAX_SCALE`]. A face that is already big enough, or whose letter has no height, keeps
|
||||
/// its size.
|
||||
fn scale(height: Option<f64>) -> f32 {
|
||||
height.filter(|h| h.is_finite() && *h > 0.0).map_or(1.0, |h| (X_HEIGHT / h).clamp(1.0, MAX_SCALE) as f32)
|
||||
}
|
||||
|
||||
/// `face`, found for character `c`, as an egui font: the font table's bytes, shared rather than
|
||||
/// copied, under a name that is the same for every character of the face, so egui loads the face
|
||||
/// once (sized by the first character's script); scaled to the interface text and on its baseline.
|
||||
fn font_insert(face: &Face, c: char) -> egui::FontInsert {
|
||||
let name = format!("drawing-text-{:p}-{}-{}", Arc::as_ptr(&face.bytes), face.bytes.len(), face.index);
|
||||
let tweak = egui::FontTweak {
|
||||
scale: scale(face.glyph_height(reference_letter(c))),
|
||||
fallback_align: egui::epaint::text::FallbackAlign::Baseline,
|
||||
..Default::default()
|
||||
};
|
||||
egui::FontInsert::new(&name, egui::FontData::from_blob(face.bytes.clone(), face.index).tweak(tweak), Vec::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A face from one of egui's bundled fonts (there are no font files in this repository).
|
||||
fn bundled_face() -> Face {
|
||||
let defs = egui::FontDefinitions::default();
|
||||
let bytes = defs.font_data.get("Hack").map(|d| d.bytes().to_vec()).unwrap_or_default();
|
||||
Face::new(Arc::new(bytes), 0).expect("egui bundles Hack")
|
||||
}
|
||||
|
||||
/// Every character of a face names the same font, whose bytes are the face's own (not a
|
||||
/// copy); a character without a fallback face, or no character, gets no font.
|
||||
#[test]
|
||||
fn a_fallback_face_is_one_shared_font() {
|
||||
let face = bundled_face();
|
||||
let fallback = |c: char| (c != '\u{e000}').then(|| face.clone());
|
||||
let a = font_for("ก", fallback).expect("a font");
|
||||
let b = font_for("ขั", fallback).expect("a font");
|
||||
assert_eq!(a.name, b.name);
|
||||
assert!(std::ptr::eq(a.data.bytes().as_ptr(), face.bytes.as_ptr()), "the font table's bytes, not a copy");
|
||||
assert_eq!(a.data.index, face.index);
|
||||
assert!(font_for("\u{e000}", fallback).is_none());
|
||||
assert!(font_for("", fallback).is_none());
|
||||
let other = Face::new(Arc::new(face.bytes.as_ref().clone()), 0).expect("a second copy parses");
|
||||
assert_ne!(font_insert(&other, 'ก').name, a.name, "another file is another font");
|
||||
assert_eq!(a.data.tweak.fallback_align, egui::epaint::text::FallbackAlign::Baseline, "on the interface text's baseline");
|
||||
}
|
||||
|
||||
/// A face whose reference letter is short is scaled up to the interface's x-height, at most
|
||||
/// by half; one that is tall enough, or can't be measured, keeps its size.
|
||||
#[test]
|
||||
fn short_faces_are_scaled_to_the_interface_x_height() {
|
||||
assert_eq!(reference_letter('ค'), 'ก');
|
||||
assert_eq!(reference_letter('\u{0e4c}'), 'ก', "a Thai mark measures by the consonant too");
|
||||
assert_eq!(reference_letter('א'), 'x');
|
||||
// Cordia New's ก is 0.405 em.
|
||||
assert!((f64::from(scale(Some(0.405))) * 0.405 - X_HEIGHT).abs() < 1e-6);
|
||||
assert_eq!(scale(Some(0.56)), 1.0, "never scaled down");
|
||||
assert_eq!(scale(Some(0.01)), MAX_SCALE as f32);
|
||||
for unmeasured in [None, Some(0.0), Some(-1.0), Some(f64::NAN), Some(f64::INFINITY)] {
|
||||
assert_eq!(scale(unmeasured), 1.0, "{unmeasured:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every Thai face found here (Cordia New, Angsana New on Windows; Noto Sans Thai from
|
||||
/// craft-fonts in CI) draws ก at least as tall as the interface's x-height, and is never shrunk.
|
||||
#[test]
|
||||
fn thai_faces_draw_their_consonants_at_the_interface_x_height() {
|
||||
let names = ["Cordia New", "Angsana New", "Browallia New", "Noto Sans Thai", "IBM Plex Sans Thai", "Leelawadee UI", "Tahoma"];
|
||||
let faces = names.iter().filter_map(|n| cadcraft_fonts::ttf::find(n)).chain(cadcraft_fonts::ttf::fallback_for('ก'));
|
||||
for face in faces.filter(|f| f.has_glyph('ก')) {
|
||||
let height = face.glyph_height('ก').unwrap_or_default();
|
||||
let drawn = height * f64::from(font_insert(&face, 'ก').data.tweak.scale);
|
||||
let family = face.family_name();
|
||||
assert!(drawn >= X_HEIGHT - 1e-6, "{family:?}: ก drawn {drawn} em");
|
||||
assert!(drawn <= height.max(X_HEIGHT) + 1e-6, "{family:?}: ก drawn {drawn} em, not shrunk or overshot");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ pub mod control;
|
||||
pub mod credits;
|
||||
pub mod dialogs;
|
||||
pub mod docking;
|
||||
mod drawing_fonts;
|
||||
pub mod fault;
|
||||
// The Find and Replace window behind the FIND command.
|
||||
pub mod finddlg;
|
||||
@@ -1065,6 +1066,7 @@ impl CadApp {
|
||||
let ctx = &ctx;
|
||||
let language = self.language();
|
||||
if self.fonts_language != Some(language) {
|
||||
drawing_fonts::install(ctx);
|
||||
theme::install_fonts(ctx, language);
|
||||
self.fonts_language = Some(language);
|
||||
}
|
||||
|
||||
@@ -658,6 +658,11 @@ fn fields(ui: &mut egui::Ui, d: &Drawing, st: &mut State) {
|
||||
combo(ui, egui::Id::unique(id), &cur, options)
|
||||
}
|
||||
});
|
||||
let new = new.map(|v| match (p.field, v.as_str()) {
|
||||
// An empty per-end name inherits DIMBLK.
|
||||
("arrowBlock1" | "arrowBlock2", Some("")) => json!("_CLOSEDFILLED"),
|
||||
_ => v,
|
||||
});
|
||||
if let Some(v) = new.filter(|v| *v != cur) {
|
||||
st.values.insert(p.field.into(), v);
|
||||
}
|
||||
|
||||
@@ -882,4 +882,40 @@ mod tests {
|
||||
assert!((big - 2.0 * height).abs() < 1e-9, "{big} for a {height} text");
|
||||
assert_eq!(st.fmt.fmt_at(5).height, None, "the rest keeps the text's height");
|
||||
}
|
||||
|
||||
/// A Thai MTEXT, which the canvas draws from a Thai fallback font, opens in the editor in
|
||||
/// letters, not boxes: the app's interface fonts take the face drawing text takes for a
|
||||
/// character they lack. Both interface families do, so Thai typed at the command line or in a
|
||||
/// layer name (proportional) and a FIND result (monospace) are letters too (#2949). Runs where
|
||||
/// a Thai face is found (CI embeds craft-fonts' Noto Sans Thai).
|
||||
#[test]
|
||||
fn thai_text_opens_in_the_editor_without_boxes() {
|
||||
let thai = "แบบขยายผนังห้องน้ำ ชั้นที่ ๒";
|
||||
let letters: Vec<char> = thai.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
if letters.iter().any(|c| cadcraft_fonts::ttf::fallback_for(*c).is_none()) {
|
||||
return;
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("mtext", serde_json::json!({ "at": [0, 20], "text": thai, "height": 2.5, "width": 40 })).unwrap();
|
||||
app.start("textedit");
|
||||
app.session.input(cadcraft_engine::Input::Point(cadcraft_geom::Vec2::new(1.0, 19.0))).unwrap();
|
||||
// Real app frames: the fonts are the ones the app installs.
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() };
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(input.clone(), |ui| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
assert_eq!(ctx.data_mut(|d| d.get_temp::<State>(state_id())).expect("editor open").fmt.text(), thai);
|
||||
let mut missing = Vec::new();
|
||||
ctx.fonts_mut(|f| {
|
||||
for font in [FontId::proportional(MIN_PX), FontId::monospace(MIN_PX)] {
|
||||
missing.extend(letters.iter().filter(|c| !f.has_glyph(&font, **c)).map(|c| format!("{:?} {c}", font.family)));
|
||||
}
|
||||
});
|
||||
assert!(missing.is_empty(), "drawn as boxes: {missing:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +95,31 @@ fn modify_edits_the_style() {
|
||||
assert_eq!(h.state().ui.dialog.as_deref(), Some("dimstyle"), "back to the list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modify_keeps_closed_filled_per_end_arrowheads() {
|
||||
let mut h = manager(|app| {
|
||||
app.run("dimstyle", json!({ "name": "Standard", "DIMBLK": "_DOT" })).unwrap();
|
||||
});
|
||||
click(&mut h, "Modify...");
|
||||
click(&mut h, "Symbols and Arrows");
|
||||
for label in ["Arrow 1", "Arrow 2"] {
|
||||
h.get(by().label(label).role(egui::accesskit::Role::ComboBox)).click();
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Closed filled");
|
||||
}
|
||||
click(&mut h, "OK");
|
||||
let style = h.state().session.doc().unwrap().dim_style("Standard").unwrap();
|
||||
assert_eq!(style.arrow_block, "_DOT");
|
||||
assert_eq!(style.arrow_block1, "_CLOSEDFILLED");
|
||||
assert_eq!(style.arrow_block2, "_CLOSEDFILLED");
|
||||
|
||||
click(&mut h, "Modify...");
|
||||
click(&mut h, "Symbols and Arrows");
|
||||
for label in ["Arrow 1", "Arrow 2"] {
|
||||
h.get(by().label(label).role(egui::accesskit::Role::ComboBox).value("Closed filled"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_leaves_the_style_alone() {
|
||||
let mut h = manager(|_| {});
|
||||
|
||||
Reference in New Issue
Block a user