1043 lines
46 KiB
Rust
1043 lines
46 KiB
Rust
mod base45;
|
||
mod direct_ap;
|
||
mod optical_cache;
|
||
mod pairing;
|
||
mod protocol;
|
||
mod qr;
|
||
mod receiver;
|
||
mod sender;
|
||
|
||
use eframe::egui::{self, FontData, FontDefinitions, FontFamily, TextureHandle, TextureOptions};
|
||
use optical_cache::OpticalPrefetcher;
|
||
use pairing::{PairingDirection, PairingPayload, WifiCredentials};
|
||
use protocol::{hex_sha256, TransferSource};
|
||
use receiver::{ReceiverEvent, ReceiverServer};
|
||
use sender::{SenderEvent, SenderServer};
|
||
use std::{
|
||
path::{Path, PathBuf},
|
||
sync::{mpsc, Arc},
|
||
time::{Duration, Instant},
|
||
};
|
||
|
||
// A lower-density symbol gains more from reliable 25~30 FPS recognition than
|
||
// a nominally larger page that is only decoded 10~18 times per second.
|
||
const DEFAULT_CHUNK_SIZE: u16 = 320;
|
||
const UI_FONT_NAME: &str = "qft-ui";
|
||
const APP_VERSION: &str = "0.4.6";
|
||
|
||
fn main() -> eframe::Result {
|
||
let options = eframe::NativeOptions {
|
||
viewport: egui::ViewportBuilder::default()
|
||
.with_title("QFT · 超速二维码文件传输")
|
||
.with_inner_size([1040.0, 800.0])
|
||
.with_min_inner_size([800.0, 640.0]),
|
||
..Default::default()
|
||
};
|
||
eframe::run_native(
|
||
"QFT",
|
||
options,
|
||
Box::new(|cc| Ok(Box::new(QftApp::new(cc)))),
|
||
)
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||
enum Screen {
|
||
Home,
|
||
OpticalSend,
|
||
PhoneToPc,
|
||
PcToPhone,
|
||
}
|
||
|
||
struct OpticalState {
|
||
source: Option<Arc<TransferSource>>,
|
||
prefetch: Option<OpticalPrefetcher>,
|
||
texture: Option<TextureHandle>,
|
||
page_index: u32,
|
||
round: u64,
|
||
playing: bool,
|
||
fps: f32,
|
||
cache_mib: usize,
|
||
control_width: f32,
|
||
qr_zoom: f32,
|
||
focus_qr: bool,
|
||
advanced_open: bool,
|
||
last_advance: Instant,
|
||
fps_window_started: Instant,
|
||
displayed_in_window: u32,
|
||
actual_page_fps: f64,
|
||
status: String,
|
||
}
|
||
|
||
struct ReceiveState {
|
||
save_dir: Option<PathBuf>,
|
||
use_direct_ap: bool,
|
||
server: Option<ReceiverServer>,
|
||
direct_ap: Option<direct_ap::DirectAp>,
|
||
events: Option<mpsc::Receiver<ReceiverEvent>>,
|
||
pair_texture: Option<TextureHandle>,
|
||
session_token: String,
|
||
status: String,
|
||
connected_device: String,
|
||
current_file: String,
|
||
received: u64,
|
||
total: u64,
|
||
last_saved: String,
|
||
last_sha256: String,
|
||
transfer_started: Option<Instant>,
|
||
rate_bps: f64,
|
||
}
|
||
|
||
struct SendState {
|
||
file: Option<PathBuf>,
|
||
file_size: u64,
|
||
sha256: Option<String>,
|
||
use_direct_ap: bool,
|
||
server: Option<SenderServer>,
|
||
direct_ap: Option<direct_ap::DirectAp>,
|
||
events: Option<mpsc::Receiver<SenderEvent>>,
|
||
pair_texture: Option<TextureHandle>,
|
||
session_token: String,
|
||
status: String,
|
||
connected_device: String,
|
||
}
|
||
|
||
struct QftApp {
|
||
screen: Screen,
|
||
font_status: String,
|
||
local_device: String,
|
||
optical: OpticalState,
|
||
receive: ReceiveState,
|
||
send: SendState,
|
||
}
|
||
|
||
impl QftApp {
|
||
fn new(cc: &eframe::CreationContext<'_>) -> Self {
|
||
cc.egui_ctx.set_pixels_per_point(1.0);
|
||
install_visuals(&cc.egui_ctx);
|
||
let font_status = match install_ttf_font(&cc.egui_ctx) {
|
||
Ok(path) => format!("字体:{}", path.display()),
|
||
Err(message) => format!("字体加载失败:{message}"),
|
||
};
|
||
Self {
|
||
screen: Screen::Home,
|
||
font_status,
|
||
local_device: protocol::local_device_name(),
|
||
optical: OpticalState {
|
||
source: None,
|
||
prefetch: None,
|
||
texture: None,
|
||
page_index: 0,
|
||
round: 0,
|
||
playing: false,
|
||
fps: 30.0,
|
||
cache_mib: 256,
|
||
control_width: 330.0,
|
||
qr_zoom: 1.0,
|
||
focus_qr: false,
|
||
advanced_open: false,
|
||
last_advance: Instant::now(),
|
||
fps_window_started: Instant::now(),
|
||
displayed_in_window: 0,
|
||
actual_page_fps: 0.0,
|
||
status: "选择文件后开始光学发送。v0.4 使用单个大二维码 + QFT2/Base45 低密度 450B 数据块,优先提高 Android 有效识别率。".into(),
|
||
},
|
||
receive: ReceiveState {
|
||
save_dir: None,
|
||
use_direct_ap: true,
|
||
server: None,
|
||
direct_ap: None,
|
||
events: None,
|
||
pair_texture: None,
|
||
session_token: String::new(),
|
||
status: "先选择接收文件夹,然后启动接收。".into(),
|
||
connected_device: "等待 Android 扫码".into(),
|
||
current_file: "—".into(),
|
||
received: 0,
|
||
total: 0,
|
||
last_saved: "—".into(),
|
||
last_sha256: String::new(),
|
||
transfer_started: None,
|
||
rate_bps: 0.0,
|
||
},
|
||
send: SendState {
|
||
file: None,
|
||
file_size: 0,
|
||
sha256: None,
|
||
use_direct_ap: true,
|
||
server: None,
|
||
direct_ap: None,
|
||
events: None,
|
||
pair_texture: None,
|
||
session_token: String::new(),
|
||
status: "选择文件后生成二维码;手机扫码会自动配网并开始下载。".into(),
|
||
connected_device: "等待 Android 扫码".into(),
|
||
},
|
||
}
|
||
}
|
||
|
||
fn header(&mut self, ui: &mut egui::Ui) {
|
||
ui.horizontal(|ui| {
|
||
ui.heading("QFT");
|
||
ui.label(format!("v{APP_VERSION}"));
|
||
ui.separator();
|
||
ui.label("扫码配对 · 本地直传 · 光学零网络");
|
||
let space = (ui.available_width() - 150.0).max(0.0);
|
||
ui.add_space(space);
|
||
if self.screen != Screen::Home && ui.button("← 返回首页").clicked() {
|
||
match self.screen {
|
||
Screen::PhoneToPc => self.stop_receiver(),
|
||
Screen::PcToPhone => self.stop_sender(),
|
||
Screen::OpticalSend => { self.optical.playing = false; self.optical.prefetch = None; },
|
||
Screen::Home => {}
|
||
}
|
||
self.screen = Screen::Home;
|
||
}
|
||
});
|
||
ui.separator();
|
||
}
|
||
|
||
fn home_ui(&mut self, ui: &mut egui::Ui) {
|
||
ui.add_space(22.0);
|
||
ui.vertical_centered(|ui| {
|
||
ui.heading("选择传输方向");
|
||
ui.label("两个方向采用不同链路,让速度、兼容性和“无需外网”同时成立。")
|
||
});
|
||
ui.add_space(24.0);
|
||
|
||
ui.columns(2, |cols| {
|
||
cols[0].group(|ui| {
|
||
ui.set_min_height(300.0);
|
||
ui.vertical_centered(|ui| {
|
||
ui.add_space(22.0);
|
||
ui.heading("电脑 → Android");
|
||
ui.label("光学传输");
|
||
ui.add_space(12.0);
|
||
ui.label("文件只经过:电脑屏幕 → 手机摄像头");
|
||
ui.label("不使用 Wi-Fi / 蓝牙 / 局域网 / 外网");
|
||
ui.add_space(24.0);
|
||
if ui.add_sized([220.0, 46.0], egui::Button::new("选择文件并开始光传")).clicked() {
|
||
self.screen = Screen::OpticalSend;
|
||
}
|
||
});
|
||
});
|
||
cols[1].group(|ui| {
|
||
ui.set_min_height(300.0);
|
||
ui.vertical_centered(|ui| {
|
||
ui.add_space(22.0);
|
||
ui.heading("Android → 电脑");
|
||
ui.label("扫码直连");
|
||
ui.add_space(12.0);
|
||
ui.label("电脑创建临时 QFT Wi-Fi Direct AP");
|
||
ui.label("Android 扫码配网后高速上传到指定文件夹");
|
||
ui.add_space(24.0);
|
||
if ui.add_sized([220.0, 46.0], egui::Button::new("电脑接收手机文件")).clicked() {
|
||
self.screen = Screen::PhoneToPc;
|
||
}
|
||
});
|
||
});
|
||
});
|
||
ui.add_space(18.0);
|
||
ui.group(|ui| {
|
||
ui.horizontal_wrapped(|ui| {
|
||
ui.heading("电脑 → Android · 扫码自动直传");
|
||
ui.separator();
|
||
ui.label("选择文件 · 生成 QFTSEND2 · 手机扫码后自动配网并下载到 Downloads/QFT");
|
||
if ui.add_sized([220.0, 42.0], egui::Button::new("直传文件到手机")).clicked() {
|
||
self.screen = Screen::PcToPhone;
|
||
}
|
||
});
|
||
});
|
||
ui.add_space(18.0);
|
||
ui.group(|ui| {
|
||
ui.label(format!("本机设备:{}", self.local_device));
|
||
ui.small(&self.font_status);
|
||
});
|
||
}
|
||
|
||
fn optical_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||
if self.optical.playing && self.optical.source.is_some() {
|
||
let interval = Duration::from_secs_f32(1.0 / self.optical.fps.max(1.0));
|
||
if self.optical.last_advance.elapsed() >= interval {
|
||
self.optical.last_advance = Instant::now();
|
||
self.optical_advance(ctx);
|
||
}
|
||
ctx.request_repaint_after((interval / 3).max(Duration::from_millis(1)));
|
||
}
|
||
|
||
ui.horizontal_wrapped(|ui| {
|
||
ui.heading("电脑 → Android · 单码锁定极速模式");
|
||
ui.separator();
|
||
ui.label("屏幕 → 摄像头 · 0 网络");
|
||
ui.separator();
|
||
if ui.button(if self.optical.focus_qr { "退出专注二维码" } else { "专注二维码" }).clicked() {
|
||
self.optical.focus_qr = !self.optical.focus_qr;
|
||
}
|
||
});
|
||
ui.add_space(8.0);
|
||
|
||
if self.optical.focus_qr {
|
||
ui.horizontal_wrapped(|ui| {
|
||
let enabled = self.optical.source.is_some();
|
||
if ui.add_enabled(enabled, egui::Button::new(if self.optical.playing { "暂停" } else { "播放" })).clicked() {
|
||
if !self.optical.playing && self.optical.prefetch.is_none() { self.restart_optical_pipeline(); }
|
||
self.optical.playing = !self.optical.playing;
|
||
self.optical.last_advance = Instant::now();
|
||
self.optical.fps_window_started = Instant::now();
|
||
self.optical.displayed_in_window = 0;
|
||
}
|
||
ui.label(format!("{:.0} FPS", self.optical.fps));
|
||
ui.add(egui::Slider::new(&mut self.optical.qr_zoom, 0.65..=1.0).text("二维码占比").show_value(false));
|
||
ui.small("控制区已收起,尽可能把屏幕面积留给二维码");
|
||
});
|
||
ui.separator();
|
||
self.optical_qr_panel(ui);
|
||
return;
|
||
}
|
||
|
||
let available = ui.available_size();
|
||
let min_qr_width = 360.0_f32.min(available.x * 0.55);
|
||
let max_control = (available.x - min_qr_width - 12.0).max(240.0);
|
||
self.optical.control_width = self.optical.control_width.clamp(240.0, max_control);
|
||
let split_height = ui.available_height().max(420.0);
|
||
|
||
ui.horizontal(|ui| {
|
||
ui.allocate_ui_with_layout(
|
||
egui::vec2(self.optical.control_width, split_height),
|
||
egui::Layout::top_down(egui::Align::Min),
|
||
|ui| {
|
||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||
self.optical_controls(ui, ctx);
|
||
});
|
||
},
|
||
);
|
||
|
||
let (bar_rect, bar_response) = ui.allocate_exact_size(
|
||
egui::vec2(8.0, split_height),
|
||
egui::Sense::drag(),
|
||
);
|
||
let bar_color = if bar_response.dragged() || bar_response.hovered() {
|
||
ui.visuals().widgets.active.bg_fill
|
||
} else {
|
||
ui.visuals().widgets.inactive.bg_fill
|
||
};
|
||
ui.painter().rect_filled(bar_rect.shrink2(egui::vec2(2.0, 0.0)), 3.0, bar_color);
|
||
if bar_response.dragged() {
|
||
let dx = ui.input(|i| i.pointer.delta().x);
|
||
self.optical.control_width = (self.optical.control_width + dx).clamp(240.0, max_control);
|
||
ctx.request_repaint();
|
||
}
|
||
bar_response.on_hover_text("拖动压缩/展开控制区,右侧二维码会自动放大");
|
||
|
||
ui.allocate_ui_with_layout(
|
||
egui::vec2(ui.available_width(), split_height),
|
||
egui::Layout::top_down(egui::Align::Center),
|
||
|ui| self.optical_qr_panel(ui),
|
||
);
|
||
});
|
||
}
|
||
|
||
fn optical_controls(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||
ui.group(|ui| {
|
||
ui.heading("发送控制");
|
||
ui.horizontal_wrapped(|ui| {
|
||
if ui.button("选择文件").clicked() { self.optical_pick_file(ctx); }
|
||
let enabled = self.optical.source.is_some();
|
||
if ui.add_enabled(enabled, egui::Button::new(if self.optical.playing { "暂停" } else { "开始播放" })).clicked() {
|
||
if !self.optical.playing && self.optical.prefetch.is_none() { self.restart_optical_pipeline(); }
|
||
self.optical.playing = !self.optical.playing;
|
||
self.optical.last_advance = Instant::now();
|
||
self.optical.fps_window_started = Instant::now();
|
||
self.optical.displayed_in_window = 0;
|
||
}
|
||
if ui.add_enabled(enabled, egui::Button::new("回到第1帧")).clicked() {
|
||
self.optical.playing = false;
|
||
self.restart_optical_pipeline();
|
||
let _ = self.optical_render_first(ctx);
|
||
}
|
||
});
|
||
|
||
ui.add_space(6.0);
|
||
ui.label("显示刷新率");
|
||
ui.add(egui::Slider::new(&mut self.optical.fps, 5.0..=60.0).suffix(" FPS").step_by(1.0));
|
||
ui.horizontal_wrapped(|ui| {
|
||
if ui.small_button("稳定 30").clicked() { self.optical.fps = 30.0; }
|
||
if ui.small_button("平衡 45").clicked() { self.optical.fps = 45.0; }
|
||
if ui.small_button("最高 60").clicked() { self.optical.fps = 60.0; }
|
||
});
|
||
ui.small("Android 会先全屏搜索一次,然后锁定单个二维码区域进行局部高频解码;60 FPS 是显示目标,实际有效识别率由手机相机决定。");
|
||
});
|
||
|
||
ui.add_space(8.0);
|
||
ui.group(|ui| {
|
||
ui.heading("二维码可读性");
|
||
ui.label(format!("单码 · 每块 {} B · QFT2/Base45 · QR-L · 完整静区", DEFAULT_CHUNK_SIZE));
|
||
ui.add(egui::Slider::new(&mut self.optical.qr_zoom, 0.65..=1.0).text("画面占比"));
|
||
ui.small("v0.4 已彻底删除 4 码模式;QFT2 使用 Base45 让 QR 进入字母数字模式,比旧 Base64 文本更低密度。默认 450 B 数据块仍保持较低 QR 版本,让 Android 更容易稳定锁定。");
|
||
});
|
||
|
||
ui.add_space(8.0);
|
||
ui.checkbox(&mut self.optical.advanced_open, "高级设置");
|
||
if self.optical.advanced_open {
|
||
ui.group(|ui| {
|
||
let old_cache = self.optical.cache_mib;
|
||
ui.label("预编码缓存");
|
||
ui.add(egui::Slider::new(&mut self.optical.cache_mib, 64..=optical_cache::MAX_MANAGED_CACHE_MIB)
|
||
.suffix(" MiB").step_by(64.0));
|
||
ui.small(format!(
|
||
"托管缓存最多 {} MiB;整进程设计预算约 {} MiB。缓存只影响二维码预编码是否跟得上,不会把整个文件读进内存。",
|
||
optical_cache::MAX_MANAGED_CACHE_MIB, optical_cache::HARD_PROCESS_BUDGET_MIB
|
||
));
|
||
if old_cache != self.optical.cache_mib {
|
||
self.optical.playing = false;
|
||
self.restart_optical_pipeline();
|
||
let _ = self.optical_render_first(ctx);
|
||
}
|
||
});
|
||
}
|
||
|
||
ui.add_space(8.0);
|
||
if let Some(source) = self.optical.source.as_ref() {
|
||
let m = &source.manifest;
|
||
let pages = source.total_playlist_frames().max(1);
|
||
let payload_rate = self.optical.fps as f64 * m.chunk_size as f64;
|
||
ui.group(|ui| {
|
||
ui.small("实时状态");
|
||
ui.heading(format!("{:.1} 页/s", self.optical.actual_page_fps));
|
||
ui.label(format!("理论载荷 ≈ {}/s", human_bytes(payload_rate as u64)));
|
||
let cap = self.optical.prefetch.as_ref().map(|p| p.capacity_pages).unwrap_or(0);
|
||
let page_mib = self.optical.prefetch.as_ref().map(|p| p.estimated_page_mib).unwrap_or(0.0);
|
||
ui.small(format!("预编码缓存:{} MiB · 最多 {cap} 帧 · {page_mib:.1} MiB/帧", self.optical.cache_mib));
|
||
ui.separator();
|
||
ui.label(format!("设备:{} → Android", m.sender_device));
|
||
ui.label(format!("文件:{} · {}", m.file_name, human_bytes(m.file_size)));
|
||
ui.label(format!("帧:{}/{} · 完整轮次:{}", self.optical.page_index + 1, pages, self.optical.round));
|
||
ui.small(format!("SHA-256:{}", hex_sha256(&m.sha256)));
|
||
});
|
||
}
|
||
ui.add_space(6.0);
|
||
ui.label(&self.optical.status);
|
||
}
|
||
|
||
fn optical_qr_panel(&mut self, ui: &mut egui::Ui) {
|
||
if let Some(texture) = &self.optical.texture {
|
||
let avail = ui.available_size();
|
||
let reserved = if self.optical.focus_qr { 4.0 } else { 28.0 };
|
||
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)));
|
||
if !self.optical.focus_qr {
|
||
ui.small("拖动左侧分隔条可继续放大二维码;也可点击顶部“专注二维码”占满可用区域。");
|
||
}
|
||
});
|
||
} else {
|
||
ui.vertical_centered(|ui| {
|
||
ui.add_space(120.0);
|
||
ui.heading("请选择一个文件");
|
||
ui.label("单个大二维码会在这里显示,Android 识别后自动锁定区域。");
|
||
});
|
||
}
|
||
}
|
||
|
||
fn receive_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||
self.poll_receiver_events();
|
||
ctx.request_repaint_after(Duration::from_millis(100));
|
||
|
||
ui.horizontal_wrapped(|ui| {
|
||
ui.heading("Android → 电脑 · 扫码直连");
|
||
ui.separator();
|
||
ui.label("UDP 快速发现 · 4/8/16 MiB 自适应分块 · 最高 8 路并行 · 不经过外网");
|
||
});
|
||
ui.add_space(10.0);
|
||
let running = self.receive.server.is_some();
|
||
|
||
ui.group(|ui| {
|
||
ui.heading("1 · 保存位置");
|
||
ui.horizontal_wrapped(|ui| {
|
||
if ui.add_enabled(!running, egui::Button::new("选择接收文件夹")).clicked() {
|
||
if let Some(dir) = rfd::FileDialog::new().pick_folder() {
|
||
self.receive.save_dir = Some(dir);
|
||
self.receive.status = "保存位置已选择,可以启动接收。".into();
|
||
}
|
||
}
|
||
ui.label(self.receive.save_dir.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| "尚未选择".into()));
|
||
});
|
||
});
|
||
ui.add_space(8.0);
|
||
|
||
ui.group(|ui| {
|
||
ui.heading("2 · 连接方式");
|
||
ui.add_enabled_ui(!running, |ui| {
|
||
ui.radio_value(&mut self.receive.use_direct_ap, true, "QFT Direct(推荐)· Windows 自动创建临时 Wi-Fi Direct AP");
|
||
ui.radio_value(&mut self.receive.use_direct_ap, false, "当前局域网(备用)· 手机和电脑已经在同一 Wi-Fi/LAN");
|
||
});
|
||
if self.receive.use_direct_ap {
|
||
ui.small("Android 10+ 使用 WifiNetworkSpecifier;Android 7~9 使用兼容配网。连接后先 UDP 广播发现,再并行探测网关/IP,避免“已连 Wi-Fi 找不到电脑”。");
|
||
if !running && ui.small_button("重置 QFT Direct 网络身份").clicked() {
|
||
match pairing::reset_direct_ap_credentials() {
|
||
Ok(()) => self.receive.status = "QFT Direct 网络身份已重置;下次启动接收会生成新的 SSID/密码,Android 需要重新批准一次。".into(),
|
||
Err(e) => self.receive.status = format!("重置 QFT Direct 网络身份失败:{e:#}"),
|
||
}
|
||
}
|
||
} else {
|
||
ui.small("二维码不携带 Wi-Fi 密码;Android 会先 UDP 快速发现电脑,再并行探测二维码内的本地 IP。");
|
||
}
|
||
if running { ui.small("接收运行中,停止接收后才能修改保存目录或连接方式。"); }
|
||
});
|
||
ui.add_space(8.0);
|
||
|
||
ui.group(|ui| {
|
||
ui.heading("3 · 启动并扫码");
|
||
ui.horizontal(|ui| {
|
||
if ui.add_enabled(!running && self.receive.save_dir.is_some(), egui::Button::new("启动接收并生成二维码")).clicked() {
|
||
self.start_receiver(ctx);
|
||
}
|
||
if ui.add_enabled(running, egui::Button::new("停止接收")).clicked() {
|
||
self.stop_receiver();
|
||
}
|
||
});
|
||
ui.label(&self.receive.status);
|
||
});
|
||
|
||
if self.receive.server.is_some() {
|
||
ui.add_space(10.0);
|
||
ui.columns(2, |cols| {
|
||
cols[0].group(|ui| {
|
||
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))); });
|
||
}
|
||
if let Some(ap) = &self.receive.direct_ap {
|
||
ui.label(format!("临时网络:{}", ap.ssid));
|
||
ui.small("网络身份会在这台电脑上复用以减少重复确认;每次接收仍会生成新的会话 Token。");
|
||
}
|
||
if !self.receive.session_token.is_empty() {
|
||
let short = &self.receive.session_token[..10.min(self.receive.session_token.len())];
|
||
ui.small(format!("临时会话:{short}… · 停止接收后立即失效"));
|
||
}
|
||
});
|
||
cols[1].group(|ui| {
|
||
ui.heading("接收状态 · Parallel v2");
|
||
ui.label(format!("电脑:{}", self.local_device));
|
||
ui.label(format!("手机:{}", self.receive.connected_device));
|
||
ui.separator();
|
||
ui.label(format!("当前文件:{}", self.receive.current_file));
|
||
let fraction = if self.receive.total == 0 { 0.0 } else { self.receive.received as f32 / self.receive.total as f32 };
|
||
ui.add(egui::ProgressBar::new(fraction.clamp(0.0, 1.0)).show_percentage());
|
||
ui.label(format!("已接收:{} / {}", human_bytes(self.receive.received), human_bytes(self.receive.total)));
|
||
if self.receive.rate_bps > 1.0 {
|
||
let eta = if self.receive.total > self.receive.received {
|
||
(self.receive.total - self.receive.received) as f64 / self.receive.rate_bps
|
||
} else { 0.0 };
|
||
ui.label(format!("速度:{}/s · 预计剩余:{}", human_bytes(self.receive.rate_bps as u64), human_duration(eta)));
|
||
}
|
||
ui.separator();
|
||
ui.label(format!("最近保存:{}", self.receive.last_saved));
|
||
if !self.receive.last_sha256.is_empty() { ui.small(format!("SHA-256:{}", self.receive.last_sha256)); }
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
fn pc_to_phone_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||
self.poll_sender_events();
|
||
ctx.request_repaint_after(Duration::from_millis(100));
|
||
let running = self.send.server.is_some();
|
||
ui.horizontal_wrapped(|ui| {
|
||
ui.heading("电脑 → Android · 扫码自动直传");
|
||
ui.separator();
|
||
ui.label("QFTSEND2 · 自动连接本地 Wi-Fi · 扫码后立即下载");
|
||
});
|
||
ui.add_space(10.0);
|
||
|
||
ui.group(|ui| {
|
||
ui.heading("1 · 选择发送文件");
|
||
ui.horizontal_wrapped(|ui| {
|
||
if ui.add_enabled(!running, egui::Button::new("选择文件")).clicked() {
|
||
if let Some(path) = rfd::FileDialog::new().pick_file() {
|
||
match TransferSource::open(&path, DEFAULT_CHUNK_SIZE) {
|
||
Ok(source) => {
|
||
self.send.file_size = source.manifest.file_size;
|
||
self.send.sha256 = Some(hex_sha256(&source.manifest.sha256));
|
||
self.send.file = Some(path);
|
||
self.send.status = "文件已就绪;生成二维码后,手机扫码会自动开始下载。".into();
|
||
}
|
||
Err(e) => self.send.status = format!("读取文件失败:{e:#}"),
|
||
}
|
||
}
|
||
}
|
||
if let Some(path) = &self.send.file {
|
||
ui.label(format!("{} · {}", path.display(), human_bytes(self.send.file_size)));
|
||
} else {
|
||
ui.label("尚未选择文件");
|
||
}
|
||
});
|
||
if let Some(sha) = &self.send.sha256 { ui.small(format!("SHA-256:{sha}")); }
|
||
});
|
||
ui.add_space(8.0);
|
||
|
||
ui.group(|ui| {
|
||
ui.heading("2 · 连接方式");
|
||
ui.add_enabled_ui(!running, |ui| {
|
||
ui.radio_value(&mut self.send.use_direct_ap, true, "QFT Direct(推荐)· Windows 自动创建临时 Wi-Fi");
|
||
ui.radio_value(&mut self.send.use_direct_ap, false, "当前局域网(备用)· 手机和电脑已在同一 Wi-Fi/LAN");
|
||
});
|
||
ui.small("手机扫描二维码后会自动请求连接;已经批准过同一台电脑的 QFT Direct 网络时,系统通常无需再次确认。");
|
||
});
|
||
ui.add_space(8.0);
|
||
|
||
ui.group(|ui| {
|
||
ui.heading("3 · 生成二维码并自动发送");
|
||
ui.horizontal_wrapped(|ui| {
|
||
if ui.add_enabled(!running && self.send.file.is_some(), egui::Button::new("启动直传并生成二维码")).clicked() {
|
||
self.start_sender(ctx);
|
||
}
|
||
if ui.add_enabled(running, egui::Button::new("停止直传")).clicked() { self.stop_sender(); }
|
||
});
|
||
ui.label(&self.send.status);
|
||
});
|
||
|
||
if self.send.server.is_some() {
|
||
ui.add_space(10.0);
|
||
ui.columns(2, |cols| {
|
||
cols[0].group(|ui| {
|
||
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))); });
|
||
}
|
||
if let Some(ap) = &self.send.direct_ap {
|
||
ui.label(format!("临时网络:{}", ap.ssid));
|
||
}
|
||
});
|
||
cols[1].group(|ui| {
|
||
ui.heading("发送状态");
|
||
ui.label(format!("电脑:{}", self.local_device));
|
||
ui.label(format!("手机:{}", self.send.connected_device));
|
||
ui.label(self.send.file.as_ref().map(|v| format!("文件:{}", v.display())).unwrap_or_default());
|
||
ui.small("二维码只在本次直传会话有效;停止直传后立即失效。");
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
fn optical_pick_file(&mut self, ctx: &egui::Context) {
|
||
let Some(path) = rfd::FileDialog::new().pick_file() else { return };
|
||
match TransferSource::open(&path, DEFAULT_CHUNK_SIZE) {
|
||
Ok(source) => {
|
||
self.optical.source = Some(Arc::new(source));
|
||
self.optical.playing = false;
|
||
self.optical.actual_page_fps = 0.0;
|
||
self.restart_optical_pipeline();
|
||
if let Err(e) = self.optical_render_first(ctx) {
|
||
self.optical.status = format!("生成二维码失败:{e:#}");
|
||
} else {
|
||
self.optical.status = "文件已载入。默认单个大二维码 · QFT2/Base45 450B 数据块 · 45 FPS;可按手机能力切到 30 或 60 FPS。".into();
|
||
}
|
||
}
|
||
Err(e) => self.optical.status = format!("读取文件失败:{e:#}"),
|
||
}
|
||
}
|
||
|
||
fn optical_canvas_side(&self) -> usize {
|
||
1024
|
||
}
|
||
|
||
fn restart_optical_pipeline(&mut self) {
|
||
self.optical.prefetch = None;
|
||
self.optical.page_index = 0;
|
||
self.optical.round = 0;
|
||
let Some(source) = self.optical.source.clone() else { return };
|
||
self.optical.prefetch = Some(OpticalPrefetcher::start(
|
||
source,
|
||
self.optical_canvas_side(),
|
||
self.optical.cache_mib,
|
||
));
|
||
}
|
||
|
||
fn optical_render_first(&mut self, ctx: &egui::Context) -> anyhow::Result<()> {
|
||
let Some(source) = self.optical.source.as_ref() else { return Ok(()) };
|
||
let text = source.text_frame(0)?;
|
||
let image = qr::render_qr_fitted(&text, self.optical_canvas_side())?;
|
||
self.set_optical_texture(ctx, image);
|
||
self.optical.page_index = 0;
|
||
self.optical.round = 0;
|
||
Ok(())
|
||
}
|
||
|
||
fn set_optical_texture(&mut self, ctx: &egui::Context, image: egui::ColorImage) {
|
||
if let Some(texture) = self.optical.texture.as_mut() {
|
||
// Reuse one GPU texture instead of allocating/freeing a texture ID
|
||
// for every 60 Hz optical page. This materially reduces GPU/driver
|
||
// churn and keeps the presentation path deterministic.
|
||
texture.set(image, TextureOptions::NEAREST);
|
||
} else {
|
||
self.optical.texture = Some(ctx.load_texture(
|
||
"qft-optical-frame", image, TextureOptions::NEAREST,
|
||
));
|
||
}
|
||
}
|
||
|
||
fn optical_advance(&mut self, ctx: &egui::Context) {
|
||
let next = match self.optical.prefetch.as_ref() {
|
||
Some(prefetch) => prefetch.try_next(),
|
||
None => {
|
||
self.restart_optical_pipeline();
|
||
return;
|
||
}
|
||
};
|
||
match next {
|
||
Ok(page) => {
|
||
self.set_optical_texture(ctx, page.image);
|
||
self.optical.page_index = page.page_index;
|
||
self.optical.round = page.round;
|
||
self.optical.displayed_in_window = self.optical.displayed_in_window.saturating_add(1);
|
||
let elapsed = self.optical.fps_window_started.elapsed();
|
||
if elapsed >= Duration::from_secs(1) {
|
||
self.optical.actual_page_fps = self.optical.displayed_in_window as f64 / elapsed.as_secs_f64().max(0.001);
|
||
self.optical.displayed_in_window = 0;
|
||
self.optical.fps_window_started = Instant::now();
|
||
}
|
||
self.optical.status = if self.optical.actual_page_fps + 3.0 < self.optical.fps as f64 && self.optical.actual_page_fps > 1.0 {
|
||
"实际页面速率低于目标:可降低 FPS 或把缓存调高;文件数据仍会循环补帧。".into()
|
||
} else {
|
||
"正在光学发送 · 单个大二维码,Android 锁定后仅在二维码 ROI 内高频解码。".into()
|
||
};
|
||
}
|
||
Err(std::sync::mpsc::TryRecvError::Empty) => {
|
||
self.optical.status = "预编码缓存正在补充,暂缓换页以避免显示空帧。".into();
|
||
}
|
||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||
self.optical.playing = false;
|
||
self.optical.status = "光学预编码线程已停止,请重新选择文件。".into();
|
||
}
|
||
}
|
||
}
|
||
|
||
fn start_receiver(&mut self, ctx: &egui::Context) {
|
||
let Some(save_dir) = self.receive.save_dir.clone() else { return };
|
||
self.stop_receiver();
|
||
self.receive.status = "正在初始化接收服务…".into();
|
||
let token = pairing::new_session_token();
|
||
let (tx, rx) = mpsc::channel();
|
||
let server = match ReceiverServer::start(save_dir, token.clone(), tx) {
|
||
Ok(v) => v,
|
||
Err(e) => { self.receive.status = format!("接收服务启动失败:{e:#}"); return; }
|
||
};
|
||
|
||
let mut direct_ap = None;
|
||
let wifi = if self.receive.use_direct_ap {
|
||
let (ssid, passphrase) = match pairing::load_or_create_direct_ap_credentials(&self.local_device) {
|
||
Ok(v) => v,
|
||
Err(e) => {
|
||
drop(server);
|
||
self.receive.status = format!("读取 QFT Direct 配网身份失败:{e:#}");
|
||
return;
|
||
}
|
||
};
|
||
match direct_ap::DirectAp::start(ssid.clone(), passphrase.clone()) {
|
||
Ok(ap) => {
|
||
direct_ap = Some(ap);
|
||
Some(WifiCredentials { ssid, passphrase, security: "WPA2".into() })
|
||
}
|
||
Err(e) => {
|
||
drop(server);
|
||
self.receive.status = format!("QFT Direct 启动失败:{e:#}\n可切换到“当前局域网”备用模式。 ");
|
||
return;
|
||
}
|
||
}
|
||
} else { None };
|
||
|
||
// Give the virtual adapter a moment to appear before enumerating addresses.
|
||
if direct_ap.is_some() { std::thread::sleep(Duration::from_millis(250)); }
|
||
let payload = PairingPayload {
|
||
v: 2,
|
||
session: token.clone(),
|
||
pc_name: self.local_device.clone(),
|
||
transport: "http-parallel-v2".into(),
|
||
port: server.port,
|
||
endpoints: pairing::local_ipv4_endpoints(server.port),
|
||
wifi,
|
||
direction: PairingDirection::Upload,
|
||
file_name: None,
|
||
file_size: None,
|
||
sha256: None,
|
||
};
|
||
let pair_text = match payload.encode_text() {
|
||
Ok(v) => v,
|
||
Err(e) => { self.receive.status = format!("配对信息生成失败:{e:#}"); return; }
|
||
};
|
||
let image = match qr::render_pair_qr(&pair_text, 520) {
|
||
Ok(v) => v,
|
||
Err(e) => { self.receive.status = format!("配对二维码生成失败:{e:#}"); return; }
|
||
};
|
||
|
||
let receiver_port = server.port;
|
||
self.receive.server = Some(server);
|
||
self.receive.direct_ap = direct_ap;
|
||
self.receive.events = Some(rx);
|
||
self.receive.pair_texture = Some(ctx.load_texture("qft-pair-code", image, TextureOptions::NEAREST));
|
||
self.receive.session_token = token;
|
||
self.receive.connected_device = "等待 Android 扫码".into();
|
||
self.receive.current_file = "—".into();
|
||
self.receive.received = 0;
|
||
self.receive.total = 0;
|
||
self.receive.last_saved = "—".into();
|
||
self.receive.last_sha256.clear();
|
||
self.receive.transfer_started = None;
|
||
self.receive.rate_bps = 0.0;
|
||
self.receive.status = if self.receive.use_direct_ap {
|
||
format!("接收已就绪 · TCP {} · UDP 发现 {}。Android 扫码后会自动配网并快速发现电脑。", receiver_port, receiver::DISCOVERY_PORT)
|
||
} else {
|
||
format!("接收已就绪 · TCP {} · UDP 发现 {}。Android 扫码后会自动发现同一局域网电脑。", receiver_port, receiver::DISCOVERY_PORT)
|
||
};
|
||
}
|
||
|
||
fn start_sender(&mut self, ctx: &egui::Context) {
|
||
let Some(file) = self.send.file.clone() else { return };
|
||
let Some(sha256) = self.send.sha256.clone() else { return };
|
||
let file_name = file.file_name().and_then(|v| v.to_str()).unwrap_or("qft-download.bin").to_owned();
|
||
self.stop_sender();
|
||
self.send.status = "正在初始化电脑发送服务…".into();
|
||
let token = pairing::new_session_token();
|
||
let (tx, rx) = mpsc::channel();
|
||
let server = match SenderServer::start(file, token.clone(), tx) {
|
||
Ok(v) => v,
|
||
Err(e) => { self.send.status = format!("发送服务启动失败:{e:#}"); return; }
|
||
};
|
||
|
||
let mut direct_ap = None;
|
||
let wifi = if self.send.use_direct_ap {
|
||
let (ssid, passphrase) = match pairing::load_or_create_direct_ap_credentials(&self.local_device) {
|
||
Ok(v) => v,
|
||
Err(e) => {
|
||
drop(server);
|
||
self.send.status = format!("读取 QFT Direct 配网身份失败:{e:#}");
|
||
return;
|
||
}
|
||
};
|
||
match direct_ap::DirectAp::start(ssid.clone(), passphrase.clone()) {
|
||
Ok(ap) => {
|
||
direct_ap = Some(ap);
|
||
Some(WifiCredentials { ssid, passphrase, security: "WPA2".into() })
|
||
}
|
||
Err(e) => {
|
||
drop(server);
|
||
self.send.status = format!("QFT Direct 启动失败:{e:#}\n可切换到“当前局域网”备用模式。");
|
||
return;
|
||
}
|
||
}
|
||
} else { None };
|
||
|
||
if direct_ap.is_some() { std::thread::sleep(Duration::from_millis(250)); }
|
||
let payload = PairingPayload {
|
||
v: 2,
|
||
session: token.clone(),
|
||
pc_name: self.local_device.clone(),
|
||
transport: "http-download-v2".into(),
|
||
port: server.port,
|
||
endpoints: pairing::local_ipv4_endpoints(server.port),
|
||
wifi,
|
||
direction: PairingDirection::Download,
|
||
file_name: Some(file_name),
|
||
file_size: Some(self.send.file_size),
|
||
sha256: Some(sha256),
|
||
};
|
||
let pair_text = match payload.encode_text() {
|
||
Ok(v) => v,
|
||
Err(e) => { self.send.status = format!("发送二维码信息生成失败:{e:#}"); return; }
|
||
};
|
||
let image = match qr::render_pair_qr(&pair_text, 520) {
|
||
Ok(v) => v,
|
||
Err(e) => { self.send.status = format!("发送二维码生成失败:{e:#}"); return; }
|
||
};
|
||
let port = server.port;
|
||
self.send.server = Some(server);
|
||
self.send.direct_ap = direct_ap;
|
||
self.send.events = Some(rx);
|
||
self.send.pair_texture = Some(ctx.load_texture("qft-send-code", image, TextureOptions::NEAREST));
|
||
self.send.session_token = token;
|
||
self.send.connected_device = "等待 Android 扫码".into();
|
||
self.send.status = if self.send.use_direct_ap {
|
||
format!("直传已就绪 · TCP {port} · 手机扫码后会自动配网并开始下载。")
|
||
} else {
|
||
format!("直传已就绪 · TCP {port} · 请让手机扫码并使用当前局域网。")
|
||
};
|
||
}
|
||
|
||
fn stop_sender(&mut self) {
|
||
self.send.events = None;
|
||
self.send.server = None;
|
||
self.send.direct_ap = None;
|
||
self.send.pair_texture = None;
|
||
self.send.session_token.clear();
|
||
self.send.connected_device = "等待 Android 扫码".into();
|
||
self.send.status = "直传已停止。".into();
|
||
}
|
||
|
||
fn poll_sender_events(&mut self) {
|
||
let mut pending = Vec::new();
|
||
if let Some(rx) = &self.send.events {
|
||
while let Ok(event) = rx.try_recv() { pending.push(event); }
|
||
}
|
||
for event in pending {
|
||
match event {
|
||
SenderEvent::ClientConnected { device } => {
|
||
self.send.connected_device = device;
|
||
self.send.status = "Android 已确认本次二维码会话,正在准备下载。".into();
|
||
}
|
||
SenderEvent::DownloadStarted { device, file_name, size } => {
|
||
self.send.connected_device = device;
|
||
self.send.status = format!("正在发送 {file_name} · {}", human_bytes(size));
|
||
}
|
||
SenderEvent::DownloadCompleted { device, file_name } => {
|
||
self.send.connected_device = device;
|
||
self.send.status = format!("发送完成:{file_name} 已由手机保存到 Downloads/QFT。");
|
||
}
|
||
SenderEvent::Error(message) => self.send.status = message,
|
||
}
|
||
}
|
||
}
|
||
|
||
fn stop_receiver(&mut self) {
|
||
self.receive.events = None;
|
||
self.receive.server = None;
|
||
self.receive.direct_ap = None;
|
||
self.receive.pair_texture = None;
|
||
self.receive.session_token.clear();
|
||
self.receive.connected_device = "等待 Android 扫码".into();
|
||
self.receive.current_file = "—".into();
|
||
self.receive.received = 0;
|
||
self.receive.total = 0;
|
||
self.receive.transfer_started = None;
|
||
self.receive.rate_bps = 0.0;
|
||
self.receive.status = "接收已停止。".into();
|
||
}
|
||
|
||
fn poll_receiver_events(&mut self) {
|
||
let mut pending = Vec::new();
|
||
if let Some(rx) = &self.receive.events {
|
||
while let Ok(event) = rx.try_recv() { pending.push(event); }
|
||
}
|
||
for event in pending {
|
||
match event {
|
||
ReceiverEvent::ClientConnected { device } => {
|
||
self.receive.connected_device = device;
|
||
self.receive.status = "Android 已连接到电脑。可以开始发送文件。".into();
|
||
}
|
||
ReceiverEvent::UploadStarted { device, file_name, size } => {
|
||
self.receive.connected_device = device;
|
||
self.receive.current_file = file_name;
|
||
self.receive.received = 0;
|
||
self.receive.total = size;
|
||
self.receive.transfer_started = Some(Instant::now());
|
||
self.receive.rate_bps = 0.0;
|
||
self.receive.status = "正在接收文件…".into();
|
||
}
|
||
ReceiverEvent::UploadProgress { device, file_name, received, size } => {
|
||
self.receive.connected_device = device;
|
||
self.receive.current_file = file_name;
|
||
self.receive.received = received;
|
||
self.receive.total = size;
|
||
if let Some(started) = self.receive.transfer_started {
|
||
let secs = started.elapsed().as_secs_f64().max(0.001);
|
||
self.receive.rate_bps = received as f64 / secs;
|
||
}
|
||
}
|
||
ReceiverEvent::UploadCompleted { device, file_name, saved_path, sha256 } => {
|
||
self.receive.connected_device = device;
|
||
self.receive.current_file = file_name;
|
||
self.receive.received = self.receive.total;
|
||
self.receive.last_saved = saved_path.display().to_string();
|
||
self.receive.last_sha256 = sha256;
|
||
if let Some(started) = self.receive.transfer_started {
|
||
let secs = started.elapsed().as_secs_f64().max(0.001);
|
||
self.receive.rate_bps = self.receive.total as f64 / secs;
|
||
}
|
||
self.receive.status = "文件接收完成。二维码会继续保持有效,可继续发送其他文件。".into();
|
||
}
|
||
ReceiverEvent::Error(message) => self.receive.status = message,
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
impl eframe::App for QftApp {
|
||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||
let ctx = ui.ctx().clone();
|
||
ui.spacing_mut().item_spacing = egui::vec2(10.0, 10.0);
|
||
ui.spacing_mut().button_padding = egui::vec2(14.0, 8.0);
|
||
egui::CentralPanel::default().show(ui, |ui| {
|
||
self.header(ui);
|
||
match self.screen {
|
||
Screen::Home => self.home_ui(ui),
|
||
Screen::OpticalSend => self.optical_ui(ui, &ctx),
|
||
Screen::PhoneToPc => self.receive_ui(ui, &ctx),
|
||
Screen::PcToPhone => self.pc_to_phone_ui(ui, &ctx),
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
fn install_visuals(ctx: &egui::Context) {
|
||
// eframe/egui 0.35 no longer exposes Context::style()/set_style().
|
||
// Keep theme initialization here; per-UI spacing is applied in App::ui.
|
||
ctx.set_visuals(egui::Visuals::dark());
|
||
}
|
||
|
||
fn install_ttf_font(ctx: &egui::Context) -> Result<PathBuf, String> {
|
||
let font_path = find_ttf_font().ok_or_else(|| {
|
||
"未找到可用 TTF。请把支持中文的字体复制到 windows/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();
|
||
fonts.font_data.insert(UI_FONT_NAME.to_owned(), Arc::new(FontData::from_owned(bytes)));
|
||
fonts.families.entry(FontFamily::Proportional).or_default().insert(0, UI_FONT_NAME.to_owned());
|
||
fonts.families.entry(FontFamily::Monospace).or_default().insert(0, UI_FONT_NAME.to_owned());
|
||
ctx.set_fonts(fonts);
|
||
Ok(font_path)
|
||
}
|
||
|
||
fn find_ttf_font() -> Option<PathBuf> {
|
||
let mut candidates = Vec::<PathBuf>::new();
|
||
if let Ok(explicit) = std::env::var("QFT_FONT_PATH") {
|
||
if !explicit.trim().is_empty() { candidates.push(PathBuf::from(explicit)); }
|
||
}
|
||
if let Ok(exe) = std::env::current_exe() {
|
||
if let Some(dir) = exe.parent() {
|
||
candidates.push(dir.join("qft-ui.ttf"));
|
||
candidates.push(dir.join("assets").join("qft-ui.ttf"));
|
||
}
|
||
}
|
||
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()))
|
||
}
|
||
|
||
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"))
|
||
}
|
||
|
||
fn human_duration(seconds: f64) -> String {
|
||
if !seconds.is_finite() || seconds <= 0.5 { return "<1 秒".into(); }
|
||
let total = seconds.ceil() as u64;
|
||
let minutes = total / 60;
|
||
let secs = total % 60;
|
||
if minutes > 0 { format!("{minutes} 分 {secs} 秒") } else { format!("{secs} 秒") }
|
||
}
|
||
|
||
fn human_bytes(v: u64) -> String {
|
||
const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
|
||
let mut n = v as f64;
|
||
let mut i = 0usize;
|
||
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]) }
|
||
}
|