diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 0283554..6310a1b 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -156,7 +156,9 @@ struct QftApp { impl QftApp { fn new(cc: &eframe::CreationContext<'_>) -> Self { - cc.egui_ctx.set_pixels_per_point(1.0); + // 不要写死 pixels_per_point。此前固定为 1.0,在 Retina/HiDPI 上会让 + // 整个界面缩成实际尺寸的一半;缩放由 eframe 从系统取。 + // 二维码需要的像素级精确由 snap_to_physical 在绘制时保证。 install_visuals(&cc.egui_ctx); let font_status = match install_ttf_font(&cc.egui_ctx) { Ok(path) => format!("字体:{}", path.display()), @@ -500,7 +502,8 @@ impl QftApp { let base = avail.x.min((avail.y - reserved).max(220.0)).max(220.0); let side = (base * self.optical.qr_zoom).clamp(220.0, base); ui.vertical_centered(|ui| { - ui.image((texture.id(), egui::vec2(side, side))); + let side = snap_to_physical(side, ui.ctx().pixels_per_point()); + ui.image((texture.id(), egui::vec2(side, side))); if !self.optical.focus_qr { ui.small("拖动左侧分隔条可继续放大二维码;也可点击顶部“专注二维码”占满可用区域。"); } @@ -581,7 +584,8 @@ impl QftApp { ui.heading("手机扫码 · QFTPAIR2"); if let Some(texture) = &self.receive.pair_texture { let side = ui.available_width().min(420.0).max(260.0); - ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); }); + ui.vertical_centered(|ui| { let side = snap_to_physical(side, ui.ctx().pixels_per_point()); + ui.image((texture.id(), egui::vec2(side, side))); }); } if let Some(ap) = &self.receive.direct_ap { ui.label(format!("临时网络:{}", ap.ssid)); @@ -680,7 +684,8 @@ impl QftApp { ui.heading("手机扫码 · QFTSEND2"); if let Some(texture) = &self.send.pair_texture { let side = ui.available_width().min(420.0).max(260.0); - ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); }); + ui.vertical_centered(|ui| { let side = snap_to_physical(side, ui.ctx().pixels_per_point()); + ui.image((texture.id(), egui::vec2(side, side))); }); } if let Some(ap) = &self.send.direct_ap { ui.label(format!("临时网络:{}", ap.ssid)); @@ -1415,7 +1420,7 @@ fn install_visuals(ctx: &egui::Context) { fn install_ttf_font(ctx: &egui::Context) -> Result { let font_path = find_ttf_font().ok_or_else(|| { - "未找到可用 TTF。请把支持中文的字体复制到 windows/assets/qft-ui.ttf,或设置 QFT_FONT_PATH。".to_owned() + "未找到任何可用的中文字体。请把字体复制到 desktop/assets/qft-ui.ttf,或用 QFT_FONT_PATH 指定。".to_owned() })?; let bytes = std::fs::read(&font_path).map_err(|e| format!("读取 {} 失败:{e}", font_path.display()))?; let mut fonts = FontDefinitions::default(); @@ -1438,18 +1443,31 @@ fn find_ttf_font() -> Option { } } candidates.push(PathBuf::from("assets").join("qft-ui.ttf")); - if cfg!(target_os = "windows") { - candidates.extend([ - PathBuf::from(r"C:\Windows\Fonts\simhei.ttf"), - PathBuf::from(r"C:\Windows\Fonts\Deng.ttf"), - PathBuf::from(r"C:\Windows\Fonts\msyh.ttf"), - ]); - } - candidates.into_iter().find(|path| is_ttf_file(path.as_path())) + // 仓库不带字体,最终依赖系统自带的中文字体 + candidates.extend(platform::system_font_candidates()); + candidates.into_iter().find(|path| is_font_file(path.as_path())) } -fn is_ttf_file(path: &Path) -> bool { - path.is_file() && path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("ttf")) +/// 按文件魔数判断是否为可用字体,而不是看扩展名。 +/// +/// 旧实现只接受 `.ttf`,于是 macOS 的 PingFang.ttc、新版 Windows 的 +/// msyh.ttc、Linux 的 NotoSansCJK.ttc 全部被拒,界面只能显示豆腐块。 +fn is_font_file(path: &Path) -> bool { + if !path.is_file() { + return false; + } + let Ok(mut file) = std::fs::File::open(path) else { return false }; + let mut magic = [0u8; 4]; + if std::io::Read::read_exact(&mut file, &mut magic).is_err() { + return false; + } + matches!( + &magic, + b"ttcf" // TrueType 集合 + | b"OTTO" // CFF / OpenType + | [0x00, 0x01, 0x00, 0x00] // TrueType + | b"true" // 旧版 Apple TrueType + ) } fn human_duration(seconds: f64) -> String { @@ -1460,6 +1478,17 @@ fn human_duration(seconds: f64) -> String { if minutes > 0 { format!("{minutes} 分 {secs} 秒") } else { format!("{secs} 秒") } } +/// 把逻辑点尺寸吸附到物理像素整数上。 +/// +/// 二维码纹理用 NEAREST 采样:绘制尺寸若落在半个物理像素上, +/// 相邻模块占用的物理像素数会一宽一窄,边缘出现锯齿,手机更难解码。 +fn snap_to_physical(points: f32, pixels_per_point: f32) -> f32 { + if pixels_per_point <= 0.0 { + return points; + } + ((points * pixels_per_point).round() / pixels_per_point).max(1.0) +} + fn human_bytes(v: u64) -> String { const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; let mut n = v as f64; @@ -1467,3 +1496,79 @@ fn human_bytes(v: u64) -> String { while n >= 1024.0 && i < UNITS.len() - 1 { n /= 1024.0; i += 1; } if i == 0 { format!("{} {}", v, UNITS[i]) } else { format!("{n:.2} {}", UNITS[i]) } } + +#[cfg(test)] +mod font_tests { + use super::*; + + #[test] + fn detects_ttc_collections_not_just_ttf() { + // 旧实现只看扩展名,把 macOS/Linux 清一色的 .ttc 全拒了 + for candidate in platform::system_font_candidates() { + if candidate.exists() { + assert!( + is_font_file(&candidate), + "系统字体 {} 应被识别为可用字体", + candidate.display() + ); + } + } + assert!(!is_font_file(Path::new("/etc/hosts")), "非字体文件不应通过"); + assert!(!is_font_file(Path::new("/no/such/file")), "不存在的路径不应通过"); + } + + #[test] + fn a_usable_cjk_font_exists_on_this_platform() { + let found = find_ttf_font(); + assert!( + found.is_some(), + "本平台未找到任何中文字体,界面会显示豆腐块。候选:{:?}", + platform::system_font_candidates() + ); + } + + /// 真正的验收:把找到的字体装进 egui,渲染一个汉字并确认它有宽度。 + /// 只检查"文件存在"是不够的——.ttc 若解析失败,字形宽度会是 0。 + #[test] + fn renders_chinese_glyphs_with_nonzero_width() { + let ctx = egui::Context::default(); + let path = find_ttf_font().expect("应能找到字体"); + install_ttf_font(&ctx).expect("字体应能装载"); + // egui 0.35:用 begin_pass/end_pass 触发一次布局,字体才会真正加载 + ctx.begin_pass(Default::default()); + let _ = ctx.end_pass(); + + let font_id = egui::FontId::proportional(16.0); + let width_cjk = ctx.fonts_mut(|f| f.glyph_width(&font_id, '中')); + let width_latin = ctx.fonts_mut(|f| f.glyph_width(&font_id, 'A')); + + assert!( + width_cjk > 0.0, + "字体 {} 无法渲染汉字'中'(宽度 {width_cjk}),界面会是豆腐块", + path.display() + ); + assert!(width_latin > 0.0, "拉丁字母也应有宽度"); + // 中文是全宽字形,应明显宽于拉丁字母 + assert!( + width_cjk > width_latin, + "汉字宽度 {width_cjk} 应大于拉丁字母 {width_latin}" + ); + } + + #[test] + fn qr_side_snaps_to_whole_physical_pixels() { + // 2x 屏:逻辑点 × 2 必须落在整数物理像素上 + for ppp in [1.0_f32, 1.5, 2.0, 3.0] { + for desired in [220.4_f32, 317.7, 480.1, 733.3] { + let snapped = snap_to_physical(desired, ppp); + let physical = snapped * ppp; + assert!( + (physical - physical.round()).abs() < 1e-3, + "ppp={ppp} desired={desired} → {snapped} 点 = {physical} 物理像素,未落在整数上" + ); + assert!((snapped - desired).abs() <= 1.0, "吸附不应改变尺寸超过 1 点"); + } + } + assert_eq!(snap_to_physical(100.0, 0.0), 100.0, "非法 ppp 时原样返回"); + } +} diff --git a/desktop/src/platform.rs b/desktop/src/platform.rs index 5f051b1..e58037f 100644 --- a/desktop/src/platform.rs +++ b/desktop/src/platform.rs @@ -63,13 +63,21 @@ pub fn device_name() -> String { sanitize_device_name(&raw) } -/// 设备名会进入配对二维码与 mDNS TXT,必须去掉控制字符并限长。 +/// 设备名会进入配对二维码、mDNS TXT 与对端的设备列表, +/// 必须去掉控制字符、去掉 mDNS 的 `.local` 后缀并限长。 pub fn sanitize_device_name(raw: &str) -> String { let cleaned: String = raw .chars() .filter(|ch| !ch.is_control()) .take(64) .collect(); + // macOS/Linux 取到的常是 mDNS 主机名(如 zdeMacBook-Air.local), + // 后缀对用户没有意义,列在对方设备列表里只会更长更难认。 + let cleaned = cleaned + .strip_suffix(".local") + .or_else(|| cleaned.strip_suffix(".lan")) + .unwrap_or(&cleaned) + .to_owned(); let trimmed = cleaned.trim(); if trimmed.is_empty() { default_device_name().to_owned() @@ -93,6 +101,47 @@ const fn default_device_name() -> &'static str { } } +/// 系统自带的中文字体候选,按优先级排列。 +/// +/// 仓库不附带第三方字体,界面文字全是中文,找不到字体就会满屏豆腐块。 +/// 注意 macOS 与多数 Linux 发行版的中文字体是 **`.ttc` 字体集合**, +/// 只按 `.ttf` 扩展名筛选会把它们全部漏掉。 +pub fn system_font_candidates() -> Vec { + #[cfg(target_os = "macos")] + { + vec![ + PathBuf::from("/System/Library/Fonts/PingFang.ttc"), + PathBuf::from("/System/Library/Fonts/Hiragino Sans GB.ttc"), + PathBuf::from("/System/Library/Fonts/STHeiti Medium.ttc"), + PathBuf::from("/System/Library/Fonts/STHeiti Light.ttc"), + PathBuf::from("/Library/Fonts/Arial Unicode.ttf"), + ] + } + #[cfg(target_os = "windows")] + { + vec![ + // 新版 Windows 的微软雅黑是 .ttc,旧的筛选逻辑正好漏掉它 + PathBuf::from(r"C:\Windows\Fonts\msyh.ttc"), + PathBuf::from(r"C:\Windows\Fonts\msyh.ttf"), + PathBuf::from(r"C:\Windows\Fonts\simhei.ttf"), + PathBuf::from(r"C:\Windows\Fonts\Deng.ttf"), + PathBuf::from(r"C:\Windows\Fonts\simsun.ttc"), + ] + } + #[cfg(all(unix, not(target_os = "macos")))] + { + vec![ + PathBuf::from("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"), + PathBuf::from("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf"), + PathBuf::from("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc"), + PathBuf::from("/usr/share/fonts/opentype/source-han-sans/SourceHanSansSC-Regular.otf"), + PathBuf::from("/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc"), + PathBuf::from("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc"), + PathBuf::from("/usr/share/fonts/truetype/arphic/uming.ttc"), + ] + } +} + /// 本机所属平台,用于 mDNS TXT 与 UI 图标。 pub const fn platform_tag() -> &'static str { #[cfg(target_os = "windows")] @@ -225,6 +274,11 @@ mod tests { assert_eq!(sanitize_device_name(" "), default_device_name()); assert_eq!(sanitize_device_name("\n\t"), default_device_name()); assert_eq!(sanitize_device_name(&"x".repeat(200)).chars().count(), 64); + // mDNS 后缀不该出现在设备列表里 + assert_eq!(sanitize_device_name("zdeMacBook-Air.local"), "zdeMacBook-Air"); + assert_eq!(sanitize_device_name("ubuntu-dev.lan"), "ubuntu-dev"); + // 只去掉结尾的后缀,名字中间含 .local 的不动 + assert_eq!(sanitize_device_name("my.local.pc"), "my.local.pc"); } #[test]