V0.3.0版本优化传输速度和提示

This commit is contained in:
zhy
2026-08-10 15:45:04 +08:00
commit d885259e2b
58 changed files with 10284 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
# Windows v0.2.0 build / test
```powershell
cd E:\tools\qft_win_android_mvp\windows
cargo check
cargo run --release
```
新增:
- `windows = 0.62.2` / `Devices_WiFiDirect` / `Security_Credentials`
- `serde` / `serde_json`
- `if-addrs`
QFT Direct 真机要求:
- Windows 10/11
- Wi-Fi 已开启
- 适配器/驱动支持 Wi-Fi Direct
- Windows Mobile Hotspot 没有占用 Wi-Fi Direct group-owner 资源
首次使用会在 `%LOCALAPPDATA%\QFT\direct-ap.json` 创建随机 QFT Direct SSID/密码。它用于让 Android 记住同一台电脑的网络身份;每次“启动接收”仍会生成不同的 session token。
如果 QFT Direct 启动失败:
1. 关闭 Windows“移动热点”。
2. 确认 Wi-Fi 开启。
3. 再试一次。
4. 仍失败则在 QFT UI 切到 `当前局域网(备用)`。
如果 Android 已显示连接 QFT Wi-Fi、但无法找到 Windows:
- 允许 qft-windows.exe 通过 Windows Defender Firewall 的**专用网络**。
- Android v0.2.0 会优先探测 QFT Wi-Fi 返回的 gateway,不再依赖固定 Windows IP。
+21
View File
@@ -0,0 +1,21 @@
# Windows build fix v0.1.2
This patch updates the Windows sender for `eframe = 0.35.0` / `egui = 0.35.0`.
Changes:
- `eframe::App::update(ctx, frame)` -> `eframe::App::ui(ui, frame)`
- clone `egui::Context` from `ui.ctx()` for texture/repaint operations
- `egui::TopBottomPanel::top(...)` -> `egui::Panel::top(...)`
- `CentralPanel::show(ctx, ...)` -> `CentralPanel::show(ui, ...)`
- project `rust-version` corrected to `1.95` for egui/eframe 0.35 compatibility
No QFT protocol, QR framing, file chunking, or Android code was changed.
Verify on Windows:
```powershell
cd windows
cargo check
cargo run --release
```
+56
View File
@@ -0,0 +1,56 @@
# Windows UI / device identity update — v0.1.3
## 1. Chinese UI font
The Windows sender no longer relies on egui's default font for Chinese text.
It loads a TrueType font (`.ttf`) at runtime and installs it as the first
Proportional and Monospace font fallback.
Lookup order:
1. `QFT_FONT_PATH`
2. `qft-ui.ttf` next to the executable
3. `assets/qft-ui.ttf` next to the executable
4. `./assets/qft-ui.ttf` from the current working directory
5. common Windows Chinese `.ttf` files
For development, the most deterministic setup is to put your own Chinese-capable
TTF at:
```text
windows/assets/qft-ui.ttf
```
No font file is bundled by this project.
## 2. Device display
The Windows sender now displays:
```text
本机设备:DESKTOP-XXXX
传输设备:DESKTOP-XXXX → Android 光学接收端 · 正在传输
```
The MANIFEST payload now appends:
```text
sender_device_len: u16
sender_device_utf8: bytes
```
The Android app displays both endpoints, for example:
```text
传输设备:DESKTOP-XXXX → Xiaomi 15
```
The field is appended to the end of the old MANIFEST payload, so the new Android
parser remains compatible with v0.1/v0.1.2 manifests.
## Important limitation
Windows -> Android is intentionally a one-way optical channel. The Android phone
does not send any ACK or identity back to Windows, so the Windows sender cannot
automatically know the exact receiving phone model. The Android side can show
both the sender PC name and its own local device model.
+20
View File
@@ -0,0 +1,20 @@
# QFT Windows v0.2.2 build fix
This patch fixes the five `cargo check` errors reported against eframe/egui 0.35.0.
## Fixed
1. Added semicolons after `ui.small(...)` calls that were used as the final expression of `if/else` blocks. `ui.small()` returns `egui::Response`, while those blocks must evaluate to `()`.
2. Removed the obsolete `Context::style()` and `Context::set_style()` calls. Those APIs are not available in egui 0.35.
3. Preserved the intended spacing by applying it through `Ui::spacing_mut()` inside `eframe::App::ui`.
4. Bumped Windows application/package version to 0.2.2.
## Verify on Windows
```powershell
cd E:\tools\qft_win_android_mvp\windows
cargo check
cargo run --release
```
The Android/Windows transfer protocol, Wi-Fi Direct pairing flow, receiver service and optical transport are unchanged by this patch.
+4567
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "qft-windows"
version = "0.3.0"
edition = "2024"
rust-version = "1.95"
[dependencies]
eframe = "0.35.0"
rfd = "0.17.2"
qrcode = { version = "0.14.1", default-features = false }
base64 = "0.22.1"
crc32fast = "1.5.0"
sha2 = "0.10.9"
rand = "0.9.2"
anyhow = "1.0.99"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.143"
if-addrs = "0.13.4"
rayon = "1.11.0"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62.2", features = [
"Devices_WiFiDirect",
"Security_Credentials",
] }
+17
View File
@@ -0,0 +1,17 @@
QFT Windows UI font
Place a Chinese-capable TrueType font here and name it:
qft-ui.ttf
The application loads TTF at runtime. It does not embed/distribute font files.
Lookup order:
1. QFT_FONT_PATH environment variable
2. qft-ui.ttf beside the executable
3. assets/qft-ui.ttf beside the executable
4. ./assets/qft-ui.ttf from the current working directory
5. common Windows CJK .ttf files (for example C:\Windows\Fonts\simhei.ttf)
Example PowerShell:
$env:QFT_FONT_PATH = 'D:\fonts\my-cjk-font.ttf'
cargo run --release
+79
View File
@@ -0,0 +1,79 @@
use anyhow::{bail, Context, Result};
#[cfg(windows)]
use windows::{
core::HSTRING,
Devices::WiFiDirect::{
WiFiDirectAdvertisementPublisher, WiFiDirectAdvertisementPublisherStatus,
},
Security::Credentials::PasswordCredential,
};
pub struct DirectAp {
pub ssid: String,
#[cfg(windows)]
publisher: WiFiDirectAdvertisementPublisher,
}
impl DirectAp {
pub fn start(ssid: String, passphrase: String) -> Result<Self> {
#[cfg(not(windows))]
{
let _ = (ssid, passphrase);
bail!("QFT Direct AP 仅支持 Windows")
}
#[cfg(windows)]
{
let publisher = WiFiDirectAdvertisementPublisher::new()
.context("创建 Wi-Fi Direct publisher 失败")?;
let ad = publisher.Advertisement()
.context("读取 Wi-Fi Direct advertisement 失败")?;
ad.SetIsAutonomousGroupOwnerEnabled(true)
.context("启用 Autonomous Group Owner 失败")?;
let legacy = ad.LegacySettings()
.context("读取 LegacySettings 失败")?;
legacy.SetIsEnabled(true)
.context("启用 Wi-Fi Direct Legacy AP 失败")?;
legacy.SetSsid(&HSTRING::from(&ssid))
.context("设置 QFT SSID 失败")?;
let credential = PasswordCredential::new()
.context("创建 Wi-Fi Direct 密码对象失败")?;
credential.SetPassword(&HSTRING::from(&passphrase))
.context("设置 QFT 热点密码失败")?;
legacy.SetPassphrase(&credential)
.context("应用 QFT 热点密码失败")?;
publisher.Start().context("启动 QFT Wi-Fi Direct AP 失败")?;
// Publisher startup is asynchronous. Do not expose the pairing QR until
// Windows reports Started; otherwise Android can scan a network that is
// not yet discoverable.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
let status = publisher.Status().context("读取 AP 状态失败")?;
if status == WiFiDirectAdvertisementPublisherStatus::Started {
break;
}
if status == WiFiDirectAdvertisementPublisherStatus::Aborted {
bail!("Wi-Fi Direct AP 启动被系统中止。请确认 Windows Wi-Fi 已开启,且系统移动热点未占用 Wi-Fi Direct。")
}
if std::time::Instant::now() >= deadline {
bail!("Wi-Fi Direct AP 启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。")
}
std::thread::sleep(std::time::Duration::from_millis(80));
}
Ok(Self { ssid, publisher })
}
}
}
impl Drop for DirectAp {
fn drop(&mut self) {
#[cfg(windows)]
{
let _ = self.publisher.Stop();
}
}
}
+736
View File
@@ -0,0 +1,736 @@
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]) }
}
+128
View File
@@ -0,0 +1,128 @@
use crate::{protocol::TransferSource, qr};
use eframe::egui::ColorImage;
use rayon::prelude::*;
use std::{
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, Receiver, TryRecvError, TrySendError},
Arc,
},
thread::{self, JoinHandle},
time::Duration,
};
/// Keep the managed pre-render cache comfortably below the user's 1.1 GiB
/// whole-process ceiling. egui, GPU staging, Rust stacks and OS buffers still
/// need headroom, so QFT never intentionally reserves the entire 1.1 GiB.
pub const HARD_PROCESS_BUDGET_MIB: usize = 1100;
pub const MAX_MANAGED_CACHE_MIB: usize = 768;
const MIN_CACHE_MIB: usize = 64;
const MAX_CACHE_PAGES: usize = 192;
const PREENCODE_BATCH: usize = 8;
pub struct EncodedPage {
pub page_index: u32,
pub round: u64,
pub image: ColorImage,
}
pub struct OpticalPrefetcher {
rx: Receiver<EncodedPage>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
pub capacity_pages: usize,
pub cache_mib: usize,
pub estimated_page_mib: f64,
}
impl OpticalPrefetcher {
pub fn start(
source: Arc<TransferSource>,
lanes: usize,
canvas_side: usize,
requested_cache_mib: usize,
) -> Self {
let cache_mib = requested_cache_mib.clamp(MIN_CACHE_MIB, MAX_MANAGED_CACHE_MIB);
// ColorImage uses Color32 pixels: approximately four bytes per pixel.
let bytes_per_page = canvas_side.saturating_mul(canvas_side).saturating_mul(4).max(1);
let budget_bytes = cache_mib.saturating_mul(1024 * 1024);
let capacity_pages = (budget_bytes / bytes_per_page).clamp(4, MAX_CACHE_PAGES);
let estimated_page_mib = bytes_per_page as f64 / (1024.0 * 1024.0);
let (tx, rx) = mpsc::sync_channel::<EncodedPage>(capacity_pages);
let stop = Arc::new(AtomicBool::new(false));
let stop_worker = stop.clone();
// Render several consecutive pages in one Rayon batch. At 4 QR/page this
// lets all CPU cores work across both pages and QR lanes and is much more
// likely to keep a 60 Hz presentation queue full than a single-page loop.
let thread = thread::spawn(move || {
let total_pages = source.total_pages(lanes).max(1);
let mut next_page = 0u32;
let mut next_round = 0u64;
while !stop_worker.load(Ordering::Relaxed) {
let mut plan = Vec::with_capacity(PREENCODE_BATCH);
for order in 0..PREENCODE_BATCH {
plan.push((order, next_page, next_round));
next_page += 1;
if next_page >= total_pages {
next_page = 0;
next_round = next_round.saturating_add(1);
}
}
let mut rendered: Vec<(usize, EncodedPage)> = plan
.into_par_iter()
.filter_map(|(order, page_index, round)| {
if stop_worker.load(Ordering::Relaxed) { return None; }
let texts = source.text_page(page_index, lanes).ok()?;
let image = qr::render_qr_grid(&texts, canvas_side).ok()?;
Some((order, EncodedPage { page_index, round, image }))
})
.collect();
rendered.sort_unstable_by_key(|(order, _)| *order);
if rendered.is_empty() {
thread::sleep(Duration::from_millis(3));
continue;
}
// Reorder the parallel batch explicitly before queueing.
for (_, mut item) in rendered {
loop {
match tx.try_send(item) {
Ok(()) => break,
Err(TrySendError::Full(returned)) => {
item = returned;
if stop_worker.load(Ordering::Relaxed) { return; }
thread::sleep(Duration::from_millis(1));
}
Err(TrySendError::Disconnected(_)) => return,
}
}
}
}
});
Self {
rx,
stop,
thread: Some(thread),
capacity_pages,
cache_mib,
estimated_page_mib,
}
}
pub fn try_next(&self) -> Result<EncodedPage, TryRecvError> {
self.rx.try_recv()
}
}
impl Drop for OpticalPrefetcher {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.thread.take() {
let _ = handle.join();
}
}
}
+178
View File
@@ -0,0 +1,178 @@
use anyhow::{Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
fs,
net::{IpAddr, Ipv4Addr},
path::PathBuf,
};
pub const PAIR_PREFIX: &str = "QFTPAIR2:";
#[derive(Clone, Debug)]
pub struct PairingPayload {
pub v: u8,
pub session: String,
pub pc_name: String,
pub transport: String,
pub port: u16,
pub endpoints: Vec<String>,
pub wifi: Option<WifiCredentials>,
}
#[derive(Clone, Debug)]
pub struct WifiCredentials {
pub ssid: String,
pub passphrase: String,
pub security: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct DirectApIdentity {
version: u8,
ssid: String,
passphrase: String,
}
impl PairingPayload {
/// v2 intentionally uses short JSON keys. The Direct-AP QR no longer carries
/// a long transport string/security object and only keeps a small endpoint
/// fallback list. This materially lowers QR density and speeds phone scan.
pub fn encode_text(&self) -> Result<String> {
// Direct-AP pairing carries one short endpoint hint for the immediate
// happy path, while Android still treats the connected gateway + UDP
// discovery as authoritative fallbacks. One endpoint keeps QFTPAIR2
// compact but avoids a full discovery round on common Windows APs.
let endpoints: Vec<&str> = if self.wifi.is_some() {
self.endpoints.iter().take(1).map(String::as_str).collect()
} else {
self.endpoints.iter().take(3).map(String::as_str).collect()
};
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
let value = json!({
"v": 2,
"s": self.session,
"n": self.pc_name,
"p": self.port,
"e": endpoints,
"w": wifi,
});
let json = serde_json::to_vec(&value).context("serialize pairing payload")?;
Ok(format!("{PAIR_PREFIX}{}", URL_SAFE_NO_PAD.encode(json)))
}
}
pub fn new_session_token() -> String {
let mut bytes = [0u8; 16];
rand::rng().fill_bytes(&mut bytes);
URL_SAFE_NO_PAD.encode(bytes)
}
/// Keep one random AP identity per Windows device so Android can remember the
/// user's approval for that exact local-only network. The AP itself is only
/// active while QFT receive mode is running; the file-transfer session token is
/// regenerated every time receive mode starts.
pub fn load_or_create_direct_ap_credentials(pc_name: &str) -> Result<(String, String)> {
let path = direct_ap_identity_path();
if let Ok(bytes) = fs::read(&path) {
if let Ok(identity) = serde_json::from_slice::<DirectApIdentity>(&bytes) {
if identity.version == 1
&& !identity.ssid.trim().is_empty()
&& (8..=63).contains(&identity.passphrase.len())
{
return Ok((identity.ssid, identity.passphrase));
}
}
}
let (ssid, passphrase) = new_direct_ap_credentials(pc_name);
let identity = DirectApIdentity {
version: 1,
ssid: ssid.clone(),
passphrase: passphrase.clone(),
};
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("创建 QFT 配置目录 {} 失败", parent.display()))?;
}
let tmp = path.with_extension("json.tmp");
let json = serde_json::to_vec_pretty(&identity)?;
fs::write(&tmp, json)
.with_context(|| format!("保存 QFT Direct 身份 {} 失败", tmp.display()))?;
if path.exists() {
let _ = fs::remove_file(&path);
}
fs::rename(&tmp, &path)
.with_context(|| format!("完成 QFT Direct 身份保存 {} 失败", path.display()))?;
Ok((ssid, passphrase))
}
pub fn reset_direct_ap_credentials() -> Result<()> {
let path = direct_ap_identity_path();
if path.exists() {
fs::remove_file(&path)
.with_context(|| format!("删除 QFT Direct 身份 {} 失败", path.display()))?;
}
Ok(())
}
fn direct_ap_identity_path() -> PathBuf {
if let Ok(root) = std::env::var("LOCALAPPDATA") {
if !root.trim().is_empty() {
return PathBuf::from(root).join("QFT").join("direct-ap.json");
}
}
PathBuf::from(".qft").join("direct-ap.json")
}
fn new_direct_ap_credentials(pc_name: &str) -> (String, String) {
let suffix = new_session_token();
let suffix = &suffix[..6.min(suffix.len())];
let base: String = pc_name
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.take(10)
.collect();
let base = if base.is_empty() { "PC" } else { &base };
let ssid = format!("QFT-{base}-{suffix}");
let mut random = [0u8; 12];
rand::rng().fill_bytes(&mut random);
let password = URL_SAFE_NO_PAD.encode(random);
(ssid, password[..16.min(password.len())].to_owned())
}
pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
let mut ips = Vec::<Ipv4Addr>::new();
if let Ok(addrs) = if_addrs::get_if_addrs() {
for iface in addrs {
let IpAddr::V4(ip) = iface.ip() else { continue };
if ip.is_loopback() || ip.is_unspecified() || ip.is_link_local() {
continue;
}
if !ips.contains(&ip) {
ips.push(ip);
}
}
}
for fallback in [
Ipv4Addr::new(192, 168, 137, 1),
Ipv4Addr::new(192, 168, 49, 1),
] {
if !ips.contains(&fallback) {
ips.push(fallback);
}
}
ips.sort_by_key(|ip| {
if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 }
else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 }
else if ip.is_private() { 2 }
else { 3 }
});
ips.into_iter()
.map(|ip| format!("http://{ip}:{port}"))
.collect()
}
+274
View File
@@ -0,0 +1,274 @@
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use crc32fast::hash as crc32;
use rand::RngCore;
use rayon::prelude::*;
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::Read,
path::{Path, PathBuf},
};
pub const PREFIX: &str = "QFT1:";
pub const VERSION: u8 = 1;
#[derive(Clone, Copy, Debug)]
#[repr(u8)]
pub enum FrameKind {
Manifest = 1,
Data = 2,
End = 3,
}
#[derive(Clone, Debug)]
pub struct Manifest {
pub session_id: u64,
pub sender_device: String,
pub file_name: String,
pub file_size: u64,
pub chunk_size: u16,
pub total_chunks: u32,
pub sha256: [u8; 32],
}
pub struct TransferSource {
path: PathBuf,
file: File,
pub manifest: Manifest,
}
impl TransferSource {
pub fn open(path: impl AsRef<Path>, chunk_size: u16) -> Result<Self> {
if chunk_size == 0 {
bail!("chunk_size must be > 0");
}
let path = path.as_ref().to_path_buf();
let file = File::open(&path).context("open input file")?;
let file_size = file.metadata()?.len();
let total_chunks_u64 = if file_size == 0 {
0
} else {
(file_size + chunk_size as u64 - 1) / chunk_size as u64
};
if total_chunks_u64 > u32::MAX as u64 {
bail!("file requires too many chunks");
}
// Keep a single read-only file handle and use positioned reads for each
// optical chunk. This avoids mapping/touching a multi-GB file into the
// process working set, so the bounded QR prefetch cache remains the
// dominant managed memory consumer.
let sha256 = hash_file_streaming(&file)?;
let mut rng = rand::rng();
let session_id = rng.next_u64();
let file_name = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("qft.bin")
.to_owned();
let sender_device = local_device_name();
Ok(Self {
path,
file,
manifest: Manifest {
session_id,
sender_device,
file_name,
file_size,
chunk_size,
total_chunks: total_chunks_u64 as u32,
sha256,
},
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn total_playlist_frames(&self) -> u32 {
self.manifest.total_chunks.saturating_add(2)
}
pub fn total_pages(&self, lanes: usize) -> u32 {
let lanes = lanes.max(1) as u32;
let frames = self.total_playlist_frames();
(frames + lanes - 1) / lanes
}
/// Returns 1..=4 QFT text frames for one visual page. QR encodes are generated
/// in parallel by rayon; file bytes are read with positioned reads so workers
/// do not contend on a shared seek cursor and large files are not memory-mapped.
pub fn text_page(&self, page_index: u32, lanes: usize) -> Result<Vec<String>> {
let lanes = lanes.clamp(1, 4);
let total = self.total_playlist_frames();
let start = page_index.saturating_mul(lanes as u32);
if start >= total {
bail!("page index out of range");
}
let indices: Vec<u32> = (0..lanes)
.map(|lane| start + lane as u32)
.filter(|idx| *idx < total)
.collect();
indices
.into_par_iter()
.map(|idx| self.text_frame(idx))
.collect()
}
/// playlist_index: 0=manifest, 1..=N=data, N+1=end
pub fn text_frame(&self, playlist_index: u32) -> Result<String> {
let n = self.manifest.total_chunks;
if playlist_index == 0 {
return Ok(encode_manifest(&self.manifest));
}
if playlist_index >= 1 && playlist_index <= n {
return self.encode_data(playlist_index - 1);
}
if playlist_index == n + 1 {
return Ok(encode_frame(
FrameKind::End,
self.manifest.session_id,
0,
n,
&[],
));
}
bail!("playlist index out of range")
}
fn encode_data(&self, seq: u32) -> Result<String> {
let offset = seq as u64 * self.manifest.chunk_size as u64;
let remaining = self.manifest.file_size.saturating_sub(offset);
let len = remaining.min(self.manifest.chunk_size as u64) as usize;
let mut payload = vec![0u8; len];
if len > 0 {
read_exact_at(&self.file, &mut payload, offset)?;
}
Ok(encode_frame(
FrameKind::Data,
self.manifest.session_id,
seq,
self.manifest.total_chunks,
&payload,
))
}
}
fn encode_manifest(m: &Manifest) -> String {
let name = m.file_name.as_bytes();
let name_len = name.len().min(u16::MAX as usize) as u16;
let device = m.sender_device.as_bytes();
let device_len = device.len().min(u16::MAX as usize) as u16;
let mut payload = Vec::with_capacity(
8 + 2 + 32 + 2 + name_len as usize + 2 + device_len as usize,
);
payload.extend_from_slice(&m.file_size.to_be_bytes());
payload.extend_from_slice(&m.chunk_size.to_be_bytes());
payload.extend_from_slice(&m.sha256);
payload.extend_from_slice(&name_len.to_be_bytes());
payload.extend_from_slice(&name[..name_len as usize]);
payload.extend_from_slice(&device_len.to_be_bytes());
payload.extend_from_slice(&device[..device_len as usize]);
encode_frame(
FrameKind::Manifest,
m.session_id,
0,
m.total_chunks,
&payload,
)
}
pub fn encode_frame(
kind: FrameKind,
session_id: u64,
seq: u32,
total_chunks: u32,
payload: &[u8],
) -> String {
assert!(payload.len() <= u16::MAX as usize);
let mut binary = Vec::with_capacity(28 + payload.len());
binary.extend_from_slice(b"QFT1");
binary.push(VERSION);
binary.push(kind as u8);
binary.extend_from_slice(&session_id.to_be_bytes());
binary.extend_from_slice(&seq.to_be_bytes());
binary.extend_from_slice(&total_chunks.to_be_bytes());
binary.extend_from_slice(&(payload.len() as u16).to_be_bytes());
binary.extend_from_slice(payload);
let crc = crc32(&binary);
binary.extend_from_slice(&crc.to_be_bytes());
format!("{PREFIX}{}", URL_SAFE_NO_PAD.encode(binary))
}
pub fn hex_sha256(bytes: &[u8; 32]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(64);
for &b in bytes {
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
}
out
}
pub fn local_device_name() -> String {
let raw = std::env::var("COMPUTERNAME")
.or_else(|_| std::env::var("HOSTNAME"))
.unwrap_or_else(|_| "Windows-PC".to_owned());
let cleaned: String = raw
.chars()
.filter(|ch| !ch.is_control())
.take(64)
.collect();
if cleaned.trim().is_empty() {
"Windows-PC".to_owned()
} else {
cleaned
}
}
fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
let mut input = file.try_clone().context("clone input for sha256")?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 4 * 1024 * 1024];
loop {
let n = input.read(&mut buf).context("read input for sha256")?;
if n == 0 { break; }
hasher.update(&buf[..n]);
}
Ok(hasher.finalize().into())
}
fn read_exact_at(file: &File, mut out: &mut [u8], mut offset: u64) -> Result<()> {
while !out.is_empty() {
let n = read_at_once(file, out, offset)?;
if n == 0 { bail!("unexpected EOF at offset {offset}"); }
offset = offset.saturating_add(n as u64);
let (_, rest) = out.split_at_mut(n);
out = rest;
}
Ok(())
}
#[cfg(windows)]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::windows::fs::FileExt;
file.seek_read(out, offset)
}
#[cfg(unix)]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::unix::fs::FileExt;
file.read_at(out, offset)
}
#[cfg(not(any(windows, unix)))]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::io::{Seek, SeekFrom};
let mut cloned = file.try_clone()?;
cloned.seek(SeekFrom::Start(offset))?;
cloned.read(out)
}
+103
View File
@@ -0,0 +1,103 @@
use anyhow::{Context, Result};
use eframe::egui::ColorImage;
use qrcode::{types::Color, EcLevel, QrCode};
use rayon::prelude::*;
const QUIET_MODULES: usize = 4;
/// Render exact black/white pixels with an explicit quiet zone.
pub fn render_qr(text: &str, scale: usize) -> Result<ColorImage> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L)
.context("QR payload too large")?;
let modules = code.width();
let scale = scale.max(1);
let side_modules = modules + QUIET_MODULES * 2;
let side_px = side_modules * scale;
let gray = render_code_gray(&code, side_px);
Ok(ColorImage::from_gray([side_px, side_px], &gray))
}
/// Render 1..=4 independent QR symbols into one fixed-size optical page.
/// A 2x2 page quadruples the number of logical QFT frames presented per
/// display refresh while keeping every symbol standards-compliant.
pub fn render_qr_grid(texts: &[String], canvas_side: usize) -> Result<ColorImage> {
let count = texts.len().clamp(1, 4);
if count == 1 {
return render_qr_fitted(&texts[0], canvas_side.max(320));
}
let canvas_side = canvas_side.max(640);
let gutter = (canvas_side / 64).clamp(12, 24);
let cell = (canvas_side - gutter * 3) / 2;
let rendered: Vec<(usize, Vec<u8>)> = texts[..count]
.par_iter()
.map(|text| render_qr_gray_fitted(text, cell))
.collect::<Result<Vec<_>>>()?;
let mut canvas = vec![255u8; canvas_side * canvas_side];
for (index, (side, gray)) in rendered.into_iter().enumerate() {
let col = index % 2;
let row = index / 2;
let cell_x = gutter + col * (cell + gutter);
let cell_y = gutter + row * (cell + gutter);
let x0 = cell_x + (cell.saturating_sub(side)) / 2;
let y0 = cell_y + (cell.saturating_sub(side)) / 2;
for y in 0..side {
let dst = (y0 + y) * canvas_side + x0;
let src = y * side;
canvas[dst..dst + side].copy_from_slice(&gray[src..src + side]);
}
}
Ok(ColorImage::from_gray([canvas_side, canvas_side], &canvas))
}
/// Pairing QR favors scan reliability over maximum capacity. QFTPAIR2 is kept
/// deliberately short, so medium error correction still yields a low-version
/// symbol that phones acquire faster at imperfect angles.
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)
.context("pair QR payload too large")?;
let modules = code.width() + QUIET_MODULES * 2;
let scale = (target_side / modules).max(1);
let side = modules * scale;
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
}
pub fn render_qr_fitted(text: &str, target_side: usize) -> Result<ColorImage> {
let (side, gray) = render_qr_gray_fitted(text, target_side)?;
Ok(ColorImage::from_gray([side, side], &gray))
}
fn render_qr_gray_fitted(text: &str, target_side: usize) -> Result<(usize, Vec<u8>)> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L)
.context("QR payload too large")?;
let modules = code.width() + QUIET_MODULES * 2;
let scale = (target_side / modules).max(1);
let side = modules * scale;
Ok((side, render_code_gray(&code, side)))
}
fn render_code_gray(code: &QrCode, side_px: usize) -> Vec<u8> {
let modules = code.width();
let side_modules = modules + QUIET_MODULES * 2;
let scale = (side_px / side_modules).max(1);
let actual_side = side_modules * scale;
let mut gray = vec![255u8; actual_side * actual_side];
let colors = code.to_colors();
for y in 0..modules {
for x in 0..modules {
if colors[y * modules + x] != Color::Dark {
continue;
}
let x0 = (x + QUIET_MODULES) * scale;
let y0 = (y + QUIET_MODULES) * scale;
for py in y0..y0 + scale {
let row = py * actual_side;
gray[row + x0..row + x0 + scale].fill(0);
}
}
}
gray
}
+540
View File
@@ -0,0 +1,540 @@
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::RngCore;
use serde_json::json;
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::{self, File, OpenOptions},
io::{BufRead, BufReader, Read, Seek, SeekFrom, Write},
net::{TcpListener, TcpStream, UdpSocket},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, Ordering},
mpsc::Sender,
Arc, Mutex,
},
thread::{self, JoinHandle},
time::{Duration, Instant},
};
pub const PREFERRED_PORT: u16 = 39393;
pub const DISCOVERY_PORT: u16 = 39392;
pub const PARALLEL_CHUNK_SIZE: u64 = 8 * 1024 * 1024;
const IO_BUFFER: usize = 1024 * 1024;
#[derive(Clone, Debug)]
pub enum ReceiverEvent {
ClientConnected { device: String },
UploadStarted { device: String, file_name: String, size: u64 },
UploadProgress { device: String, file_name: String, received: u64, size: u64 },
UploadCompleted { device: String, file_name: String, saved_path: PathBuf, sha256: String },
Error(String),
}
#[derive(Debug)]
struct UploadSession {
device: String,
file_name: String,
size: u64,
chunk_size: u64,
total_chunks: u32,
part_path: PathBuf,
final_path: PathBuf,
received: Vec<bool>,
received_bytes: u64,
}
type SessionMap = Arc<Mutex<HashMap<String, Arc<Mutex<UploadSession>>>>>;
pub struct ReceiverServer {
pub port: u16,
stop: Arc<AtomicBool>,
tcp_thread: Option<JoinHandle<()>>,
udp_thread: Option<JoinHandle<()>>,
}
impl ReceiverServer {
pub fn start(save_dir: PathBuf, session_token: String, events: Sender<ReceiverEvent>) -> Result<Self> {
fs::create_dir_all(&save_dir).context("创建接收目录失败")?;
let listener = TcpListener::bind(("0.0.0.0", PREFERRED_PORT))
.or_else(|_| TcpListener::bind(("0.0.0.0", 0)))
.context("启动本地接收端口失败")?;
let port = listener.local_addr()?.port();
listener.set_nonblocking(true)?;
let stop = Arc::new(AtomicBool::new(false));
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
let stop_tcp = stop.clone();
let sessions_tcp = sessions.clone();
let token_tcp = session_token.clone();
let dir_tcp = save_dir.clone();
let events_tcp = events.clone();
let tcp_thread = thread::spawn(move || {
while !stop_tcp.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, _)) => {
let dir = dir_tcp.clone();
let token = token_tcp.clone();
let tx = events_tcp.clone();
let sessions = sessions_tcp.clone();
thread::spawn(move || {
if let Err(e) = handle_client(stream, &dir, &token, &tx, &sessions) {
let _ = tx.send(ReceiverEvent::Error(format!("接收失败:{e:#}")));
}
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(12));
}
Err(e) => {
let _ = events_tcp.send(ReceiverEvent::Error(format!("监听端口失败:{e}")));
break;
}
}
}
});
let stop_udp = stop.clone();
let token_udp = session_token;
let udp_thread = thread::spawn(move || {
let socket = match UdpSocket::bind(("0.0.0.0", DISCOVERY_PORT)) {
Ok(v) => v,
Err(e) => {
let _ = events.send(ReceiverEvent::Error(format!(
"快速发现端口 {DISCOVERY_PORT} 不可用:{e}。仍可使用网关/IP 探测。"
)));
return;
}
};
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
let expected = format!("QFTDISC2:{token_udp}");
let response = format!("QFTHERE2:{token_udp}:{port}");
let mut buf = [0u8; 512];
while !stop_udp.load(Ordering::Relaxed) {
match socket.recv_from(&mut buf) {
Ok((n, peer)) => {
if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) {
let _ = socket.send_to(response.as_bytes(), peer);
}
}
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
Err(_) => break,
}
}
});
Ok(Self {
port,
stop,
tcp_thread: Some(tcp_thread),
udp_thread: Some(udp_thread),
})
}
}
impl Drop for ReceiverServer {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.tcp_thread.take() {
let _ = handle.join();
}
if let Some(handle) = self.udp_thread.take() {
let _ = handle.join();
}
}
}
fn handle_client(
mut stream: TcpStream,
save_dir: &Path,
token: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
let cloned = stream.try_clone()?;
let mut reader = BufReader::with_capacity(64 * 1024, cloned);
let mut request_line = String::new();
reader.read_line(&mut request_line)?;
if request_line.len() > 8192 { bail!("请求行过长") }
let mut headers = HashMap::<String, String>::new();
loop {
let mut line = String::new();
let n = reader.read_line(&mut line)?;
if n == 0 { bail!("连接提前关闭") }
if line == "\r\n" || line == "\n" { break }
if line.len() > 16 * 1024 { bail!("请求头过长") }
if let Some((k, v)) = line.split_once(':') {
headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned());
}
}
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("");
let path = parts.next().unwrap_or("");
let supplied = headers.get("x-qft-token").map(String::as_str).unwrap_or("");
if supplied != token {
return write_response(&mut stream, 403, "text/plain", b"invalid session");
}
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
let _ = events.send(ReceiverEvent::ClientConnected { device: device.clone() });
if method == "GET" && path == "/qft/ping" {
let body = json!({"ok": true, "protocol": 2, "parallel": true}).to_string();
return write_response(&mut stream, 200, "application/json", body.as_bytes());
}
if method == "POST" && path == "/qft/upload/init" {
return init_parallel_upload(&mut stream, save_dir, &headers, &device, events, sessions);
}
if method == "POST" && path.starts_with("/qft/upload/chunk/") {
return receive_parallel_chunk(&mut stream, &mut reader, path, &headers, events, sessions);
}
if method == "POST" && path.starts_with("/qft/upload/finish/") {
return finish_parallel_upload(&mut stream, path, events, sessions);
}
// Compatibility path for old clients and content providers that cannot seek.
if method == "POST" && path == "/qft/upload" {
return receive_legacy_stream(&mut stream, &mut reader, save_dir, &headers, &device, events);
}
write_response(&mut stream, 404, "text/plain", b"not found")
}
fn init_parallel_upload(
stream: &mut TcpStream,
save_dir: &Path,
headers: &HashMap<String, String>,
device: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let file_name = decode_header(headers.get("x-qft-filename"))
.map(sanitize_file_name)
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "qft-upload.bin".to_owned());
let size: u64 = headers.get("x-qft-size")
.context("缺少 X-QFT-Size")?
.parse().context("X-QFT-Size 无效")?;
let chunk_size = headers.get("x-qft-chunk-size")
.and_then(|v| v.parse::<u64>().ok())
.map(|v| v.clamp(1024 * 1024, 16 * 1024 * 1024))
.unwrap_or(PARALLEL_CHUNK_SIZE);
let total_chunks_u64 = if size == 0 { 0 } else { (size + chunk_size - 1) / chunk_size };
if total_chunks_u64 > u32::MAX as u64 { bail!("文件分块数过大") }
let total_chunks = total_chunks_u64 as u32;
let upload_id = random_id();
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
let final_path = unique_path_reserved(save_dir, &file_name, map.values());
let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin");
let part_path = final_path.with_file_name(format!("{final_name}.{upload_id}.qftpart"));
let part = File::create(&part_path)
.with_context(|| format!("创建临时文件 {}", part_path.display()))?;
part.set_len(size)?;
drop(part);
let session = UploadSession {
device: device.to_owned(),
file_name: file_name.clone(),
size,
chunk_size,
total_chunks,
part_path,
final_path,
received: vec![false; total_chunks as usize],
received_bytes: 0,
};
map.insert(upload_id.clone(), Arc::new(Mutex::new(session)));
drop(map);
let _ = events.send(ReceiverEvent::UploadStarted {
device: device.to_owned(),
file_name,
size,
});
let body = json!({
"ok": true,
"upload_id": upload_id,
"chunk_size": chunk_size,
"total_chunks": total_chunks,
}).to_string();
write_response(stream, 200, "application/json", body.as_bytes())
}
fn receive_parallel_chunk(
stream: &mut TcpStream,
reader: &mut BufReader<TcpStream>,
path: &str,
headers: &HashMap<String, String>,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let suffix = path.trim_start_matches("/qft/upload/chunk/");
let (upload_id, index_text) = suffix.split_once('/').context("chunk 路径无效")?;
let index: u32 = index_text.parse().context("chunk index 无效")?;
let content_len: u64 = headers.get("content-length")
.context("缺少 Content-Length")?
.parse().context("Content-Length 无效")?;
let session_arc = {
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.get(upload_id).cloned().context("上传会话不存在或已完成")?
};
let (part_path, offset, expected_len, device, file_name, size, already) = {
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if index >= session.total_chunks { bail!("chunk index 越界") }
let offset = index as u64 * session.chunk_size;
let expected = (session.size - offset).min(session.chunk_size);
(
session.part_path.clone(),
offset,
expected,
session.device.clone(),
session.file_name.clone(),
session.size,
session.received[index as usize],
)
};
if content_len != expected_len { bail!("chunk 长度不匹配:{content_len} != {expected_len}") }
if already {
drain_exact(reader, content_len)?;
return write_response(stream, 200, "application/json", b"{\"ok\":true,\"duplicate\":true}");
}
let mut out = OpenOptions::new().write(true).open(&part_path)?;
out.seek(SeekFrom::Start(offset))?;
copy_exact(reader, &mut out, content_len)?;
out.flush()?;
let received = {
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if !session.received[index as usize] {
session.received[index as usize] = true;
session.received_bytes = session.received_bytes.saturating_add(content_len);
}
session.received_bytes
};
let _ = events.send(ReceiverEvent::UploadProgress { device, file_name, received, size });
write_response(stream, 200, "application/json", b"{\"ok\":true}")
}
fn finish_parallel_upload(
stream: &mut TcpStream,
path: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let upload_id = path.trim_start_matches("/qft/upload/finish/");
let session_arc = {
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.get(upload_id).cloned().context("上传会话不存在或已完成")?
};
let (device, file_name, size, part_path, final_path) = {
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if session.received.iter().any(|v| !*v) {
let missing = session.received.iter().filter(|v| !**v).count();
let body = json!({"ok": false, "missing": missing}).to_string();
return write_response(stream, 409, "application/json", body.as_bytes());
}
(
session.device.clone(), session.file_name.clone(), session.size,
session.part_path.clone(), session.final_path.clone(),
)
};
let sha = hash_file(&part_path)?;
if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") }
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
{
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.remove(upload_id);
}
let _ = events.send(ReceiverEvent::UploadCompleted {
device, file_name, saved_path: final_path, sha256: sha.clone(),
});
let body = json!({"ok": true, "sha256": sha, "size": size}).to_string();
write_response(stream, 200, "application/json", body.as_bytes())
}
fn receive_legacy_stream(
stream: &mut TcpStream,
reader: &mut BufReader<TcpStream>,
save_dir: &Path,
headers: &HashMap<String, String>,
device: &str,
events: &Sender<ReceiverEvent>,
) -> Result<()> {
let file_name = decode_header(headers.get("x-qft-filename"))
.map(sanitize_file_name)
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "qft-upload.bin".to_owned());
let size: u64 = headers.get("content-length")
.context("缺少 Content-Length")?
.parse().context("Content-Length 无效")?;
let declared_size = headers.get("x-qft-size")
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(size);
if declared_size != size { bail!("文件大小头与 Content-Length 不一致") }
let final_path = unique_path(save_dir, &file_name);
let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin");
let part_path = final_path.with_file_name(format!("{final_name}.qftpart"));
let mut out = File::create(&part_path).with_context(|| format!("创建临时文件 {}", part_path.display()))?;
let _ = events.send(ReceiverEvent::UploadStarted { device: device.to_owned(), file_name: file_name.clone(), size });
let mut remaining = size;
let mut received = 0u64;
let mut buf = vec![0u8; IO_BUFFER];
let mut hasher = Sha256::new();
let mut last_report = Instant::now();
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
let n = reader.read(&mut buf[..want])?;
if n == 0 { bail!("上传中连接提前关闭:{received}/{size}") }
out.write_all(&buf[..n])?;
hasher.update(&buf[..n]);
received += n as u64;
remaining -= n as u64;
if last_report.elapsed() >= Duration::from_millis(100) || remaining == 0 {
let _ = events.send(ReceiverEvent::UploadProgress {
device: device.to_owned(), file_name: file_name.clone(), received, size,
});
last_report = Instant::now();
}
}
out.sync_all()?;
drop(out);
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
let sha = hex(&hasher.finalize());
let _ = events.send(ReceiverEvent::UploadCompleted {
device: device.to_owned(), file_name, saved_path: final_path, sha256: sha,
});
write_response(stream, 200, "application/json", b"{\"ok\":true,\"legacy\":true}")
}
fn copy_exact(reader: &mut impl Read, writer: &mut impl Write, mut remaining: u64) -> Result<()> {
let mut buf = vec![0u8; IO_BUFFER];
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
let n = reader.read(&mut buf[..want])?;
if n == 0 { bail!("chunk 上传中连接提前关闭") }
writer.write_all(&buf[..n])?;
remaining -= n as u64;
}
Ok(())
}
fn drain_exact(reader: &mut impl Read, remaining: u64) -> Result<()> {
copy_exact(reader, &mut std::io::sink(), remaining)
}
fn hash_file(path: &Path) -> Result<String> {
let mut input = File::open(path)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 4 * 1024 * 1024];
loop {
let n = input.read(&mut buf)?;
if n == 0 { break }
hasher.update(&buf[..n]);
}
Ok(hex(&hasher.finalize()))
}
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
let reason = match code {
200 => "OK", 400 => "Bad Request", 403 => "Forbidden", 404 => "Not Found",
409 => "Conflict", _ => "Error",
};
write!(stream,
"HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len())?;
stream.write_all(body)?;
stream.flush()?;
Ok(())
}
fn decode_header(value: Option<&String>) -> Option<String> {
let raw = value?;
let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?;
String::from_utf8(bytes).ok()
}
fn sanitize_file_name(name: String) -> String {
let cleaned: String = name.chars()
.map(|c| if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') { '_' } else { c })
.collect();
cleaned.trim().trim_matches('.').chars().take(180).collect()
}
fn unique_path(dir: &Path, name: &str) -> PathBuf {
let base = Path::new(name);
let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload");
let ext = base.extension().and_then(|s| s.to_str());
let mut candidate = dir.join(name);
let mut n = 1;
while candidate.exists() {
let next = match ext {
Some(ext) => format!("{stem} ({n}).{ext}"),
None => format!("{stem} ({n})"),
};
candidate = dir.join(next);
n += 1;
}
candidate
}
fn unique_path_reserved<'a>(
dir: &Path,
name: &str,
sessions: impl Iterator<Item = &'a Arc<Mutex<UploadSession>>>,
) -> PathBuf {
let reserved: Vec<PathBuf> = sessions
.filter_map(|s| s.lock().ok().map(|v| v.final_path.clone()))
.collect();
let base = Path::new(name);
let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload");
let ext = base.extension().and_then(|s| s.to_str());
let mut n = 0u32;
loop {
let next_name = if n == 0 {
name.to_owned()
} else {
match ext {
Some(ext) => format!("{stem} ({n}).{ext}"),
None => format!("{stem} ({n})"),
}
};
let candidate = dir.join(next_name);
if !candidate.exists() && !reserved.contains(&candidate) {
return candidate;
}
n += 1;
}
}
fn random_id() -> String {
let mut bytes = [0u8; 12];
rand::rng().fill_bytes(&mut bytes);
URL_SAFE_NO_PAD.encode(bytes)
}
fn hex(bytes: &[u8]) -> String {
const H: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
out
}