0f0dbaef47
三个问题一起处理。 1. 提权改为手动 上一版会在点「启动接收」时自动弹 UAC。实际用下来太侵入——多数人 只是想收个文件,却先被要求管理员授权。现在: - 检测保持自动,但**只读**,无任何副作用 - 提权只在用户点「放行防火墙(需要管理员授权)」时发生 - 按钮无条件保留,不再只在"检测到被拦"时出现:检测可能不准, 而用户遇到「对方连不上」时需要有地方可点 - 同时移除了拒绝标记的持久化——提权已不自动发生,无需记忆 2. Windows 构建报 os error 5 error: failed to remove file `...\target\release\qft-desktop.exe` Caused by: 拒绝访问。 (os error 5) 原因是 QFT 窗口还开着,运行中的 exe 锁住了产物文件,而 cargo 的报错 完全看不出这一层。VERIFY_WINDOWS_HOST.ps1 现在会在构建前检测 qft-desktop 进程,列出 PID 并询问是否结束;README 也补了说明 (含 Defender 扫描导致的偶发同类报错)。 3. 构建警告 15 → 5 长期堆积的警告会训练人忽略所有警告,所以逐条处理: - 真实问题:if 条件多余的括号,已修 - 为后续里程碑准备但尚未接线的 API(client::ping、download_file、 platform::direct_ap_support/ensure_dir),加 #[allow(dead_code)] 并注明将在哪个阶段使用 - 仅特定平台构造的项(firewall::RULE_NAME 只用于 Windows, FirewallStatus::Unsupported 只在 Linux 返回),改用 #[cfg_attr(not(...), allow(dead_code))],避免无条件放行 剩余 5 个均为本次改动之前既有(cache_mib、v/transport、security、 path),不属本次范围,未改动。 验证:cargo test 35/35,release 构建 5 个警告且全部是既有的。
298 lines
9.7 KiB
Rust
298 lines
9.7 KiB
Rust
//! 平台差异的唯一收敛点。
|
||
//!
|
||
//! 约定:除本文件与 `direct_ap.rs` 外,其余模块不得出现 `#[cfg(target_os = ...)]`。
|
||
//! 新增平台差异时先在这里补一个函数,不要就地 cfg —— 否则跨平台移植会重新变成
|
||
//! 满仓库找 cfg 的考古工作。
|
||
|
||
use std::path::{Path, PathBuf};
|
||
|
||
/// QFT 的持久化配置目录(Direct AP 身份、信任库等)。
|
||
///
|
||
/// - Windows: `%LOCALAPPDATA%\QFT`
|
||
/// - macOS: `~/Library/Application Support/QFT`
|
||
/// - Linux: `$XDG_CONFIG_HOME/qft`,未设置时 `~/.config/qft`
|
||
pub fn config_dir() -> PathBuf {
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
if let Some(root) = non_empty_env("LOCALAPPDATA") {
|
||
return PathBuf::from(root).join("QFT");
|
||
}
|
||
}
|
||
#[cfg(target_os = "macos")]
|
||
{
|
||
if let Some(home) = home_dir() {
|
||
return home.join("Library").join("Application Support").join("QFT");
|
||
}
|
||
}
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
{
|
||
if let Some(root) = non_empty_env("XDG_CONFIG_HOME") {
|
||
return PathBuf::from(root).join("qft");
|
||
}
|
||
if let Some(home) = home_dir() {
|
||
return home.join(".config").join("qft");
|
||
}
|
||
}
|
||
// 环境变量全都拿不到时退回当前目录下的隐藏目录,保证功能不中断
|
||
PathBuf::from(".qft")
|
||
}
|
||
|
||
/// 接收文件的默认保存目录。
|
||
pub fn default_download_dir() -> PathBuf {
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
{
|
||
// Linux 桌面环境会把"下载"本地化(中文系统是 ~/下载),
|
||
// 目录名记录在 user-dirs.dirs 里,直接拼 "Downloads" 会建出一个用户看不见的目录。
|
||
if let Some(dir) = xdg_user_dir("XDG_DOWNLOAD_DIR") {
|
||
return dir;
|
||
}
|
||
}
|
||
if let Some(home) = home_dir() {
|
||
let downloads = home.join("Downloads");
|
||
if downloads.is_dir() {
|
||
return downloads;
|
||
}
|
||
return home;
|
||
}
|
||
PathBuf::from(".")
|
||
}
|
||
|
||
/// 展示给对端的本机名称。
|
||
pub fn device_name() -> String {
|
||
let raw = whoami::fallible::hostname().unwrap_or_else(|_| whoami::devicename());
|
||
sanitize_device_name(&raw)
|
||
}
|
||
|
||
/// 设备名会进入配对二维码、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()
|
||
} else {
|
||
trimmed.to_owned()
|
||
}
|
||
}
|
||
|
||
const fn default_device_name() -> &'static str {
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
"Windows-PC"
|
||
}
|
||
#[cfg(target_os = "macos")]
|
||
{
|
||
"Mac"
|
||
}
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
{
|
||
"Linux-PC"
|
||
}
|
||
}
|
||
|
||
/// 系统自带的中文字体候选,按优先级排列。
|
||
///
|
||
/// 仓库不附带第三方字体,界面文字全是中文,找不到字体就会满屏豆腐块。
|
||
/// 注意 macOS 与多数 Linux 发行版的中文字体是 **`.ttc` 字体集合**,
|
||
/// 只按 `.ttf` 扩展名筛选会把它们全部漏掉。
|
||
pub fn system_font_candidates() -> Vec<PathBuf> {
|
||
#[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")]
|
||
{
|
||
"windows"
|
||
}
|
||
#[cfg(target_os = "macos")]
|
||
{
|
||
"macos"
|
||
}
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
{
|
||
"linux"
|
||
}
|
||
}
|
||
|
||
/// 本机能否开启 QFT Direct 临时热点。
|
||
///
|
||
/// 只有 Windows 走 WiFi Direct;macOS 无公开 API,Linux 各发行版
|
||
/// NetworkManager 行为差异过大,都不做——UI 据此隐藏入口,
|
||
/// 而不是让用户点进去再失败。
|
||
// UI 尚未据此隐藏 Direct AP 入口,留待 P1.7 收尾
|
||
#[allow(dead_code)]
|
||
pub enum DirectApSupport {
|
||
Supported,
|
||
Unsupported(&'static str),
|
||
}
|
||
|
||
#[allow(dead_code)]
|
||
pub const fn direct_ap_support() -> DirectApSupport {
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
DirectApSupport::Supported
|
||
}
|
||
#[cfg(not(target_os = "windows"))]
|
||
{
|
||
DirectApSupport::Unsupported("本平台不支持 QFT Direct 热点,请让两台设备连接同一个 Wi-Fi")
|
||
}
|
||
}
|
||
|
||
impl DirectApSupport {
|
||
#[allow(dead_code)]
|
||
pub const fn is_supported(&self) -> bool {
|
||
matches!(self, DirectApSupport::Supported)
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 内部工具
|
||
|
||
fn non_empty_env(key: &str) -> Option<String> {
|
||
std::env::var(key).ok().filter(|v| !v.trim().is_empty())
|
||
}
|
||
|
||
fn home_dir() -> Option<PathBuf> {
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
if let Some(profile) = non_empty_env("USERPROFILE") {
|
||
return Some(PathBuf::from(profile));
|
||
}
|
||
let drive = non_empty_env("HOMEDRIVE")?;
|
||
let path = non_empty_env("HOMEPATH")?;
|
||
return Some(PathBuf::from(format!("{drive}{path}")));
|
||
}
|
||
#[cfg(unix)]
|
||
{
|
||
non_empty_env("HOME").map(PathBuf::from)
|
||
}
|
||
}
|
||
|
||
/// 解析 `~/.config/user-dirs.dirs` 里形如
|
||
/// `XDG_DOWNLOAD_DIR="$HOME/下载"` 的一行。
|
||
#[cfg(all(unix, not(target_os = "macos")))]
|
||
fn xdg_user_dir(key: &str) -> Option<PathBuf> {
|
||
let home = home_dir()?;
|
||
let config = non_empty_env("XDG_CONFIG_HOME")
|
||
.map(PathBuf::from)
|
||
.unwrap_or_else(|| home.join(".config"));
|
||
let text = std::fs::read_to_string(config.join("user-dirs.dirs")).ok()?;
|
||
for line in text.lines() {
|
||
let line = line.trim();
|
||
if line.starts_with('#') {
|
||
continue;
|
||
}
|
||
let (name, value) = line.split_once('=')?;
|
||
if name.trim() != key {
|
||
continue;
|
||
}
|
||
let value = value.trim().trim_matches('"');
|
||
let expanded = if let Some(rest) = value.strip_prefix("$HOME/") {
|
||
home.join(rest)
|
||
} else if value == "$HOME" {
|
||
home.clone()
|
||
} else {
|
||
PathBuf::from(value)
|
||
};
|
||
if expanded.is_dir() {
|
||
return Some(expanded);
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// 确保目录存在,返回其路径。调用方负责处理失败。
|
||
#[allow(dead_code)] // 由 client 的下载路径使用,该路径尚未接线
|
||
pub fn ensure_dir(path: &Path) -> std::io::Result<()> {
|
||
if path.is_dir() {
|
||
return Ok(());
|
||
}
|
||
std::fs::create_dir_all(path)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn config_dir_is_absolute_or_local_fallback() {
|
||
let dir = config_dir();
|
||
// 要么是绝对路径(拿到了环境变量),要么是约定的本地兜底
|
||
assert!(dir.is_absolute() || dir == PathBuf::from(".qft"), "{dir:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn device_name_is_never_empty_and_bounded() {
|
||
let name = device_name();
|
||
assert!(!name.is_empty());
|
||
assert!(name.chars().count() <= 64);
|
||
assert!(!name.chars().any(char::is_control));
|
||
}
|
||
|
||
#[test]
|
||
fn sanitize_strips_control_chars_and_falls_back() {
|
||
assert_eq!(sanitize_device_name(" ok-name \n"), "ok-name");
|
||
assert_eq!(sanitize_device_name("a\u{0}b"), "ab");
|
||
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]
|
||
fn platform_tag_matches_direct_ap_capability() {
|
||
// Direct AP 目前只有 Windows 支持,两个常量必须保持一致
|
||
assert_eq!(
|
||
direct_ap_support().is_supported(),
|
||
platform_tag() == "windows"
|
||
);
|
||
}
|
||
}
|