feat: 提交0.4加速版二维码直传与自动配网优化

This commit is contained in:
zhy
2026-08-10 20:29:01 +08:00
parent 241e22abea
commit 0b7ffd2dab
17 changed files with 1462 additions and 111 deletions
+242 -4
View File
@@ -5,21 +5,25 @@ 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::{PairingPayload, WifiCredentials};
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},
};
const DEFAULT_CHUNK_SIZE: u16 = 450;
// 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.0-rc2";
const APP_VERSION: &str = "0.4.0-rc6";
fn main() -> eframe::Result {
let options = eframe::NativeOptions {
@@ -41,6 +45,7 @@ enum Screen {
Home,
OpticalSend,
PhoneToPc,
PcToPhone,
}
struct OpticalState {
@@ -82,12 +87,27 @@ struct ReceiveState {
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 {
@@ -109,7 +129,7 @@ impl QftApp {
page_index: 0,
round: 0,
playing: false,
fps: 45.0,
fps: 30.0,
cache_mib: 256,
control_width: 330.0,
qr_zoom: 1.0,
@@ -139,6 +159,19 @@ impl QftApp {
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(),
},
}
}
@@ -153,6 +186,7 @@ impl QftApp {
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 => {}
}
@@ -203,6 +237,17 @@ impl QftApp {
});
});
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);
@@ -495,6 +540,88 @@ impl QftApp {
}
}
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) {
@@ -632,6 +759,10 @@ impl QftApp {
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,
@@ -663,6 +794,112 @@ impl QftApp {
};
}
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;
@@ -737,6 +974,7 @@ impl eframe::App for QftApp {
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),
}
});
}