Files
QFT/windows/src/main.rs
T
2026-08-10 15:45:04 +08:00

737 lines
33 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
mod direct_ap;
mod optical_cache;
mod pairing;
mod protocol;
mod qr;
mod receiver;
use eframe::egui::{self, FontData, FontDefinitions, FontFamily, TextureHandle, TextureOptions};
use optical_cache::OpticalPrefetcher;
use pairing::{PairingPayload, WifiCredentials};
use protocol::{hex_sha256, TransferSource};
use receiver::{ReceiverEvent, ReceiverServer};
use std::{
path::{Path, PathBuf},
sync::{mpsc, Arc},
time::{Duration, Instant},
};
const DEFAULT_CHUNK_SIZE: u16 = 900;
const UI_FONT_NAME: &str = "qft-ui";
const APP_VERSION: &str = "0.3.0-rc3";
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,
}
struct OpticalState {
source: Option<Arc<TransferSource>>,
prefetch: Option<OpticalPrefetcher>,
texture: Option<TextureHandle>,
page_index: u32,
round: u64,
playing: bool,
fps: f32,
lanes: usize,
cache_mib: usize,
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 QftApp {
screen: Screen,
font_status: String,
local_device: String,
optical: OpticalState,
receive: ReceiveState,
}
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: 60.0,
lanes: 4,
cache_mib: 384,
last_advance: Instant::now(),
fps_window_started: Instant::now(),
displayed_in_window: 0,
actual_page_fps: 0.0,
status: "选择文件后开始光学发送。默认 4 码/页 · 60 FPS,缓存不足时会自动停在当前页等待。".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,
},
}
}
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::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.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);
}
// Keep the UI scheduler hot enough for a 60 Hz display without busy-spinning.
ctx.request_repaint_after((interval / 3).max(Duration::from_millis(1)));
}
ui.horizontal_wrapped(|ui| {
ui.heading("电脑 → Android · 光学极速模式");
ui.separator();
ui.label("屏幕 → 摄像头 · 0 网络");
});
ui.add_space(8.0);
ui.group(|ui| {
ui.horizontal_wrapped(|ui| {
if ui.button("选择文件").clicked() { self.optical_pick_file(ctx); }
ui.label("刷新率");
ui.add(egui::Slider::new(&mut self.optical.fps, 1.0..=60.0).suffix(" FPS").step_by(1.0));
if ui.small_button("15").clicked() { self.optical.fps = 15.0; }
if ui.small_button("30").clicked() { self.optical.fps = 30.0; }
if ui.small_button("60").clicked() { self.optical.fps = 60.0; }
if ui.small_button("极速预设").clicked() {
self.optical.fps = 60.0;
self.optical.lanes = 4;
self.optical.cache_mib = 384;
self.optical.playing = false;
self.restart_optical_pipeline();
let _ = self.optical_render_first(ctx);
}
});
let old_lanes = self.optical.lanes;
let old_cache = self.optical.cache_mib;
ui.horizontal_wrapped(|ui| {
ui.label("视觉并行");
ui.radio_value(&mut self.optical.lanes, 1, "1 码/页 · 兼容");
ui.radio_value(&mut self.optical.lanes, 4, "4 码/页 · 极速");
ui.separator();
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!(
"QFT 只允许预编码缓存使用最多 {} MiB,为进程/GPU/系统缓冲预留空间,目标整进程不超过约 {} MiB。",
optical_cache::MAX_MANAGED_CACHE_MIB, optical_cache::HARD_PROCESS_BUDGET_MIB
));
if old_lanes != self.optical.lanes || old_cache != self.optical.cache_mib {
self.optical.playing = false;
self.restart_optical_pipeline();
let _ = self.optical_render_first(ctx);
}
let enabled = self.optical.source.is_some();
ui.horizontal_wrapped(|ui| {
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(8.0);
if let Some(source) = self.optical.source.as_ref() {
let m = &source.manifest;
let pages = source.total_pages(self.optical.lanes);
let logical_fps = self.optical.fps as f64 * self.optical.lanes as f64;
let payload_rate = logical_fps * m.chunk_size as f64;
ui.columns(3, |cols| {
cols[0].group(|ui| {
ui.small("传输");
ui.heading(format!("{:.0} FPS", self.optical.fps));
ui.label(format!("{} 码/页 · {:.0} 逻辑帧/s", self.optical.lanes, logical_fps));
});
cols[1].group(|ui| {
ui.small("实测显示");
ui.heading(format!("{:.1} 页/s", self.optical.actual_page_fps));
ui.label(format!("理论载荷 ≈ {}/s", human_bytes(payload_rate as u64)));
});
cols[2].group(|ui| {
ui.small("内存策略");
ui.heading(format!("{} MiB", self.optical.cache_mib));
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.label(format!("预编码最多 {cap} 页 · {page_mib:.1} MiB/页 · 定位读取"));
});
});
ui.add_space(6.0);
ui.label(format!("传输设备:{} → Android 光学接收端", m.sender_device));
ui.label(format!("文件:{} · {}", m.file_name, human_bytes(m.file_size)));
ui.small(format!("源路径:{}", source.path().display()));
ui.label(format!("数据块:{} · 当前页:{}/{} · 完整轮次:{}", m.total_chunks, self.optical.page_index + 1, pages, self.optical.round));
ui.small(format!("SHA-256:{}", hex_sha256(&m.sha256)));
}
ui.label(&self.optical.status);
ui.separator();
if let Some(texture) = &self.optical.texture {
let avail = ui.available_size();
let side = avail.x.min(avail.y).min(680.0).max(320.0);
ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); });
} else {
ui.vertical_centered(|ui| {
ui.add_space(100.0);
ui.heading("请选择一个文件");
ui.label("极速模式会在后台并行预编码二维码;手机仍可处于飞行模式。")
});
}
}
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 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 = "文件已载入。默认 4 码/页 · 60 FPS;低端手机若有效 QR/s 明显偏低,可降到 30 FPS。".into();
}
}
Err(e) => self.optical.status = format!("读取文件失败:{e:#}"),
}
}
fn optical_canvas_side(&self) -> usize {
if self.optical.lanes == 4 { 960 } else { 760 }
}
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.lanes,
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 texts = source.text_page(0, self.optical.lanes)?;
let image = qr::render_qr_grid(&texts, 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 {
"正在光学发送 · 4 码模式会把一页拆成四个独立 QR 并行解码。".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,
};
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 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),
}
});
}
}
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]) }
}