Files
LTEDongle/flasher/src/main.rs
T

1702 lines
62 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.
#![windows_subsystem = "windows"]
use fltk::app::{self, MouseButton};
use fltk::button::{Button, CheckButton};
use fltk::enums::{Align, Color, Event, Font, FrameType, LabelType, Shortcut};
use fltk::table::{TableContext, TableRow, TableRowSelectFlag, TableRowSelectMode};
use fltk::frame::Frame;
use fltk::group::{Group, Tabs};
use fltk::menu::{CMenuItem, MenuFlag, MenuItem};
use fltk::misc::InputChoice;
use fltk::prelude::*;
use fltk::window::Window;
mod adb;
mod profile;
use profile::{chip_matches, display, load_all, remember, remembered, Profile};
use std::collections::VecDeque;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::os::windows::process::CommandExt;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
const COLUMNS: [&str; 7] = ["", "序列号", "芯片型号", "端口", "硬盘", "状态", "进度"];
const ADB_COLUMNS: [&str; 8] = ["序列号", "芯片型号", "端口", "CPU", "内存", "硬盘", "系统版本", "标记"];
const DONE: &str = "写入完成,设备正在重启进入系统";
const WAIT: &str = "请拔出设备后重新按复位键接入电脑";
const INSTALLING_DRIVER: &str = "正在安装驱动,请稍后";
const UNPLUGGED: &str = "设备已拔出,操作失败";
const MISMATCH: &str = "不是所选型号";
const CREATE_NO_WINDOW: u32 = 0x08000000;
fn command(program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = Command::new(program);
cmd.creation_flags(CREATE_NO_WINDOW);
cmd
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum JobKind {
Info,
Backup,
Flash,
}
struct Device {
location: String,
port_num: String,
service: String,
instance_id: String,
serial: String,
chip: String,
disk: String,
status: String,
rate: String,
progress: i32,
bytes_done: u64,
bytes_total: u64,
pending: Option<JobKind>,
queued: bool,
present: bool,
checked: bool,
info_done: bool,
mismatch: bool,
missing_scans: u8,
}
enum EventMsg {
Serial(String, String),
Chip(String, String),
Disk(String, String),
Progress(String, i32),
Bytes(String, u64, u64),
Status(String, String),
Rate(String, String),
Finished(String, &'static str),
Failed(String, String),
Driver(String),
}
struct WorkerOut {
serial: String,
disk: String,
chip: String,
}
struct Job {
location: String,
kind: JobKind,
resume: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ClaimStage {
Wait,
Marking,
Confirm,
}
#[derive(Clone)]
struct Claim {
location: String,
chip_serial: String,
model_id: String,
boot_host: String,
boot_model: String,
seen: Vec<String>,
stage: ClaimStage,
since: Instant,
token: String,
}
fn app_dir() -> PathBuf {
if let Ok(exe) = std::env::current_exe() {
let mut dir = exe.parent().map(|path| path.to_path_buf());
for _ in 0..4 {
if let Some(path) = &dir {
if path.join("runtime").join("worker.py").is_file() {
return path.clone();
}
dir = path.parent().map(|parent| parent.to_path_buf());
}
}
}
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn python() -> PathBuf {
let bundled = app_dir().join("runtime").join("python").join("python.exe");
if bundled.is_file() {
return bundled;
}
app_dir().join("runtime").join("python").join("Scripts").join("python.exe")
}
fn worker_script() -> PathBuf {
app_dir().join("runtime").join("worker.py")
}
fn backup_root() -> PathBuf {
app_dir().join("backup")
}
fn stamp() -> String {
let output = command("powershell")
.args(["-NoProfile", "-Command", "Get-Date -Format yyyyMMdd-HHmmss"])
.output();
if let Ok(output) = output {
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !text.is_empty() {
return text;
}
}
"unknown-time".into()
}
fn port_num(location: &str) -> String {
let Some(rest) = location.split("Port_#").nth(1) else {
return String::new();
};
let raw = rest.split('.').next().unwrap_or("");
let trimmed = raw.trim_start_matches('0');
if trimmed.is_empty() { "0".into() } else { trimmed.into() }
}
fn is_winusb(service: &str) -> bool {
service.eq_ignore_ascii_case("WinUSB")
}
fn task_running(dev: &Device) -> bool {
dev.queued
|| dev.status == WAIT
|| dev.status == "正在识别"
|| dev.status == "备份中"
|| dev.status == "正在备份整盘"
|| dev.status == "写入中"
|| dev.status == INSTALLING_DRIVER
|| dev.status.starts_with("正在写入")
|| dev.status.starts_with("正在写回")
}
fn scan_ports(vid: &str, pid: &str) -> Result<Vec<(String, String, String, String)>, String> {
let script = r#"
$pattern = "VID_$($env:FLASHER_VID)&PID_$($env:FLASHER_PID)"
Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -match ([regex]::Escape($pattern)) } | ForEach-Object {
$loc = ''
$svc = ''
$usb = ''
try {
$props = Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LocationInfo,DEVPKEY_Device_Service,DEVPKEY_Device_LocationPaths
foreach ($p in $props) {
if ($p.KeyName -eq 'DEVPKEY_Device_LocationInfo') { $loc = [string]$p.Data }
if ($p.KeyName -eq 'DEVPKEY_Device_Service') { $svc = [string]$p.Data }
if ($p.KeyName -eq 'DEVPKEY_Device_LocationPaths') {
foreach ($item in @($p.Data)) {
$text = [string]$item
if ($text -match 'USBROOT') {
$nums = [regex]::Matches($text, 'USB\((\d+)\)') | ForEach-Object { $_.Groups[1].Value }
$usb = ($nums -join '.')
}
}
}
}
} catch {}
if (-not $svc) { $svc = [string]$_.Service }
if (-not $loc) { $loc = $_.InstanceId }
Write-Output ($loc + "`t" + $svc + "`t" + $_.InstanceId + "`t" + $usb)
}
"#;
let output = command("powershell")
.args(["-NoProfile", "-Command", script])
.env("FLASHER_VID", vid)
.env("FLASHER_PID", pid)
.output()
.map_err(|err| err.to_string())?;
if !output.status.success() && output.stdout.is_empty() {
let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if err.is_empty() { "扫描设备失败".into() } else { err });
}
Ok(String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| {
let mut parts = line.split('\t');
let location = parts.next()?.trim().to_string();
if location.is_empty() {
return None;
}
let service = parts.next().unwrap_or("").trim().to_string();
let instance_id = parts.next().unwrap_or("").trim().to_string();
let usb_path = parts.next().unwrap_or("").trim().to_string();
Some((location, service, instance_id, usb_path))
})
.collect())
}
fn confirm_port(location: &str, vid: &str, pid: &str) -> Result<(), String> {
match scan_ports(vid, pid) {
Ok(found) if found.iter().any(|(loc, _, _, _)| loc == location) => Ok(()),
Ok(_) => Err("设备已拔出".into()),
Err(_) => Ok(()),
}
}
fn run_powershell(args: &[String]) -> Result<Vec<String>, String> {
let output = command("powershell")
.args(args)
.output()
.map_err(|err| err.to_string())?;
let lines: Vec<String> = String::from_utf8_lossy(&output.stdout)
.lines()
.map(|line| line.trim().to_string())
.filter(|line| !line.is_empty())
.collect();
if output.status.success() || lines.iter().any(|line| line.starts_with("DRIVER\t")) {
Ok(lines)
} else {
let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(if err.is_empty() { "驱动检查失败".into() } else { err })
}
}
fn driver_message(kind: &str, extra: &str) -> String {
match kind {
"READY" => "驱动:已就绪".into(),
"INSTALLED" => "驱动:已安装".into(),
"MISSING" => "驱动:未安装".into(),
"FAIL" if extra == "cancel" => "驱动:安装被取消".into(),
"FAIL" if extra.is_empty() => "驱动:安装失败".into(),
"FAIL" => format!("驱动:安装失败({extra})"),
_ => "驱动:检查失败".into(),
}
}
fn driver_text(lines: &[String]) -> Option<(String, String)> {
let line = lines.iter().rev().find(|line| line.starts_with("DRIVER\t"))?;
let mut parts = line.splitn(3, '\t');
parts.next();
Some((parts.next().unwrap_or("").to_string(), parts.next().unwrap_or("").to_string()))
}
fn ensure_driver(tx: mpsc::Sender<EventMsg>, driver_dir: PathBuf) {
let _ = tx.send(EventMsg::Driver("驱动:正在检查".into()));
let script = driver_dir.join("ensure-driver.ps1");
let script = script.to_string_lossy().to_string();
let checked = run_powershell(&[
"-NoProfile".into(),
"-ExecutionPolicy".into(),
"Bypass".into(),
"-File".into(),
script.clone(),
]);
let Ok(lines) = checked else {
let _ = tx.send(EventMsg::Driver("驱动:检查失败".into()));
return;
};
let Some((kind, text)) = driver_text(&lines) else {
let _ = tx.send(EventMsg::Driver("驱动:检查失败".into()));
return;
};
if kind == "READY" {
let _ = tx.send(EventMsg::Driver("驱动:已就绪".into()));
return;
}
if kind != "MISSING" {
let _ = tx.send(EventMsg::Driver(driver_message(&kind, &text)));
return;
}
let _ = tx.send(EventMsg::Driver("驱动:正在安装".into()));
match run_powershell(&[
"-NoProfile".into(),
"-ExecutionPolicy".into(),
"Bypass".into(),
"-File".into(),
script,
"-Install".into(),
]) {
Ok(lines) => {
let text = driver_text(&lines)
.map(|(kind, extra)| driver_message(&kind, &extra))
.unwrap_or_else(|| "驱动:安装没有返回结果".into());
let _ = tx.send(EventMsg::Driver(text));
}
Err(err) => {
let _ = tx.send(EventMsg::Driver(format!("驱动:{err}")));
}
}
}
fn switch_driver(instance_id: &str) -> Result<(), String> {
let script = app_dir().join("drivers").join("switch-winusb.ps1");
let output = command("powershell")
.args([
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
&script.to_string_lossy(),
"-InstanceId",
instance_id,
])
.output()
.map_err(|err| err.to_string())?;
if output.status.success() {
Ok(())
} else {
Err(format!(
"{}{}",
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
))
}
}
fn apply_line(line: &str, out: &mut WorkerOut, tx: &mpsc::Sender<EventMsg>, location: &str) -> Result<(), String> {
let mut parts = line.splitn(3, '\t');
if parts.next() != Some("FLASHER") {
return Ok(());
}
let key = parts.next().unwrap_or("");
let value = parts.next().unwrap_or("").to_string();
match key {
"SERIAL" => {
out.serial = value.clone();
let _ = tx.send(EventMsg::Serial(location.to_string(), value));
}
"CHIP" => {
out.chip = value.clone();
let _ = tx.send(EventMsg::Chip(location.to_string(), value));
}
"DISK" => {
out.disk = value.clone();
let _ = tx.send(EventMsg::Disk(location.to_string(), value));
}
"PROGRESS" => {
if let Ok(n) = value.parse::<i32>() {
let _ = tx.send(EventMsg::Progress(location.to_string(), n));
}
}
"BYTES" => {
let mut nums = value.split('\t');
if let (Some(done), Some(total)) = (nums.next(), nums.next()) {
if let (Ok(done), Ok(total)) = (done.parse::<u64>(), total.parse::<u64>()) {
let _ = tx.send(EventMsg::Bytes(location.to_string(), done, total));
}
}
}
"STATUS" => {
let _ = tx.send(EventMsg::Status(location.to_string(), value));
}
"RATE" => {
let _ = tx.send(EventMsg::Rate(location.to_string(), value));
}
"FAIL" => return Err(value),
_ => {}
}
Ok(())
}
fn profile_args(profile: &Profile, args: &[&str]) -> Vec<String> {
let mut out = Vec::new();
if let Some(cmd) = args.first() {
out.push((*cmd).to_string());
out.push("--profile".into());
out.push(profile.conf_path.display().to_string());
out.extend(args.iter().skip(1).map(|arg| (*arg).to_string()));
}
out
}
fn run_worker(args: &[String], tx: &mpsc::Sender<EventMsg>, location: &str) -> Result<WorkerOut, String> {
let mut child = command(python())
.arg(worker_script())
.args(args)
.env("PYTHONUTF8", "1")
.env("PYTHONIOENCODING", "utf-8")
.current_dir(app_dir().join("runtime"))
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|err| format!("无法启动 edl:{err}"))?;
let stdout = child.stdout.take().ok_or("没有读取到 edl 输出")?;
let (line_tx, line_rx) = mpsc::channel::<String>();
thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if line_tx.send(line).is_err() {
break;
}
}
});
let limit = if args.iter().any(|arg| arg == "--full") {
Duration::from_secs(45 * 60)
} else if args.first().map(String::as_str) == Some("flash") {
Duration::from_secs(20 * 60)
} else {
Duration::from_secs(90)
};
let mut out = WorkerOut { serial: String::new(), disk: String::new(), chip: String::new() };
let mut last = Instant::now();
loop {
match line_rx.recv_timeout(Duration::from_secs(1)) {
Ok(line) => {
if let Err(err) = apply_line(&line, &mut out, tx, location) {
let _ = child.kill();
let _ = child.wait();
return Err(err);
}
if line.starts_with("FLASHER\t") {
last = Instant::now();
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if last.elapsed() > limit {
let _ = child.kill();
let _ = child.wait();
return Err("等待 9008 超时".into());
}
if child.try_wait().map_err(|err| err.to_string())?.is_some() {
while let Ok(line) = line_rx.try_recv() {
if let Err(err) = apply_line(&line, &mut out, tx, location) {
let _ = child.kill();
let _ = child.wait();
return Err(err);
}
}
break;
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
let status = child.wait().map_err(|err| err.to_string())?;
if status.success() {
Ok(out)
} else {
Err("edl 异常退出".into())
}
}
fn execute(location: &str, port: &str, known_serial: &str, kind: JobKind, full: bool, parts: bool, resume: bool, profile: &Profile, tx: &mpsc::Sender<EventMsg>) -> Result<&'static str, String> {
confirm_port(location, &profile.vid, &profile.pid)?;
let _ = tx.send(EventMsg::Status(location.to_string(), "正在识别".into()));
let info = run_worker(&profile_args(profile, &["info", "--port", port]), tx, location)?;
if resume && !known_serial.is_empty() && !info.serial.is_empty() && info.serial != known_serial {
return Err("插回的不是原来的芯片,已停止原来的任务".into());
}
if kind == JobKind::Info {
return Ok("info");
}
if !chip_matches(&info.chip, &profile.chip) {
return Err(if info.chip.is_empty() { "未能确认芯片型号".into() } else { MISMATCH.into() });
}
let chip_serial = if !info.serial.is_empty() {
info.serial.clone()
} else {
known_serial.to_string()
};
let backup_efs = kind == JobKind::Backup || parts;
let do_backup = backup_efs || full;
let mut restore_dir = String::new();
if do_backup {
confirm_port(location, &profile.vid, &profile.pid)?;
let serial = if !info.serial.is_empty() {
info.serial
} else if !known_serial.is_empty() {
known_serial.to_string()
} else {
format!("port-{port}")
};
let folder = backup_root().join(&serial).join(stamp());
std::fs::create_dir_all(&folder).map_err(|err| err.to_string())?;
let dest = folder.to_string_lossy().to_string();
let mut backup_args = vec!["backup", "--port", port, "--dest", dest.as_str()];
if full {
backup_args.push("--full");
}
if !backup_efs {
backup_args.push("--no-efs");
}
let status = if full && !backup_efs { "正在备份整盘" } else { "备份中" };
let _ = tx.send(EventMsg::Status(location.to_string(), status.into()));
run_worker(&profile_args(profile, &backup_args), tx, location)?;
if kind == JobKind::Backup {
return Ok("backup");
}
if backup_efs {
restore_dir = dest;
}
}
confirm_port(location, &profile.vid, &profile.pid)?;
let _ = tx.send(EventMsg::Status(location.to_string(), "写入中".into()));
let _ = tx.send(EventMsg::Progress(location.to_string(), 0));
let mut flash_args = vec!["flash", "--port", port, "--chip", chip_serial.as_str()];
if !restore_dir.is_empty() {
flash_args.push("--dest");
flash_args.push(restore_dir.as_str());
}
run_worker(&profile_args(profile, &flash_args), tx, location)?;
Ok("flash")
}
fn can_operate(dev: &Device) -> bool {
dev.info_done && !dev.mismatch && !dev.chip.is_empty() && !task_running(dev)
}
fn fill_models(choice: &mut InputChoice, profiles: &[Profile], query: &str) {
choice.clear();
let query = query.trim().to_lowercase();
for profile in profiles {
let line = display(profile);
if query.is_empty() || line.to_lowercase().contains(&query) {
choice.add(&line);
}
}
}
fn main() {
let root = app_dir();
let profiles = load_all(&root).unwrap_or_else(|err| {
eprintln!("{err}");
Vec::new()
});
if profiles.is_empty() {
let app = app::App::default();
let mut window = Window::default().with_size(480, 120).with_label("Flasher");
let mut frame = Frame::default().with_size(460, 80).with_pos(10, 20).with_label("没有找到型号配置");
frame.set_label_size(16);
window.end();
window.show();
app.run().unwrap();
return;
}
let selected_index = remembered(&root, &profiles);
let selected = Arc::new(Mutex::new(profiles[selected_index].clone()));
let devices = Arc::new(Mutex::new(Vec::<Device>::new()));
let adb_devices = Arc::new(Mutex::new(Vec::<adb::AdbDevice>::new()));
let adb_refresh = Arc::new(AtomicBool::new(true));
let claims = Arc::new(Mutex::new(Vec::<Claim>::new()));
let (adb_tx, adb_rx) = mpsc::channel::<Vec<adb::AdbDevice>>();
let queue: Arc<Mutex<VecDeque<Job>>> = Arc::new(Mutex::new(VecDeque::new()));
let full_disk = Arc::new(Mutex::new(false));
let backup_parts = Arc::new(Mutex::new(true));
let refresh_now = Arc::new(AtomicBool::new(false));
let model_guard = Arc::new(AtomicBool::new(false));
let (tx, rx) = mpsc::channel::<EventMsg>();
let (scan_tx, scan_rx) = mpsc::channel::<(Option<Vec<(String, String, String, String)>>, bool)>();
{
let devices = Arc::clone(&devices);
let queue = Arc::clone(&queue);
let full_disk = Arc::clone(&full_disk);
let backup_parts = Arc::clone(&backup_parts);
let tx = tx.clone();
let selected = Arc::clone(&selected);
thread::spawn(move || loop {
let next = queue.lock().unwrap().pop_front();
let Some(Job { location, kind, resume }) = next else {
thread::sleep(Duration::from_millis(200));
continue;
};
let (port, service, serial, instance_id) = {
let list = devices.lock().unwrap();
match list.iter().find(|d| d.location == location) {
Some(d) => {
let route = if d.port_num.contains('.') || !d.port_num.is_empty() {
d.port_num.clone()
} else {
port_num(&d.location)
};
(route, d.service.clone(), d.serial.clone(), d.instance_id.clone())
}
None => {
let _ = tx.send(EventMsg::Failed(location, "设备已不在列表中".into()));
continue;
}
}
};
let profile = selected.lock().unwrap().clone();
if confirm_port(&location, &profile.vid, &profile.pid).is_err() {
let _ = tx.send(EventMsg::Failed(location, "设备已拔出".into()));
continue;
}
if !is_winusb(&service) {
let _ = tx.send(EventMsg::Status(location.clone(), INSTALLING_DRIVER.into()));
if let Err(err) = switch_driver(&instance_id) {
let _ = tx.send(EventMsg::Failed(location, err));
continue;
}
if let Some(dev) = devices.lock().unwrap().iter_mut().find(|d| d.location == location) {
dev.pending = Some(kind);
dev.queued = false;
dev.status = WAIT.into();
}
let _ = tx.send(EventMsg::Status(location, WAIT.into()));
continue;
}
let full = *full_disk.lock().unwrap();
let parts = *backup_parts.lock().unwrap();
match execute(&location, &port, &serial, kind, full, parts, resume, &profile, &tx) {
Ok(done) => {
let _ = tx.send(EventMsg::Finished(location, done));
}
Err(err) => {
let unplugged = err == "设备已拔出" || confirm_port(&location, &profile.vid, &profile.pid).is_err();
let still_there = devices
.lock()
.unwrap()
.iter()
.find(|d| d.location == location)
.is_some_and(|d| d.present);
if unplugged {
let _ = tx.send(EventMsg::Failed(location, "设备已拔出".into()));
} else if still_there {
let _ = tx.send(EventMsg::Failed(location, err));
} else if let Some(dev) = devices.lock().unwrap().iter_mut().find(|d| d.location == location) {
dev.pending = Some(kind);
dev.queued = false;
dev.status = WAIT.into();
let _ = tx.send(EventMsg::Status(location, WAIT.into()));
}
}
}
});
}
let app = app::App::default().with_scheme(app::Scheme::Gtk);
if let Ok(font) = Font::load_font("C:/Windows/Fonts/msyh.ttc") {
Font::set_font(Font::Helvetica, &font);
}
let initial = selected.lock().unwrap().clone();
let mut window = Window::default()
.with_size(980, 640)
.with_label(&format!("{} Flasher", initial.id));
let mut model_label = Frame::default().with_pos(16, 14).with_size(48, 32).with_label("型号");
model_label.set_label_size(15);
model_label.set_align(Align::Left | Align::Inside);
let mut model_choice = InputChoice::new(64, 12, 340, 32, "");
model_choice.set_text_size(15);
fill_models(&mut model_choice, &profiles, "");
model_choice.set_value(&display(&initial));
let mut driver_label = Frame::default()
.with_pos(416, 16)
.with_size(400, 28)
.with_label("驱动:正在检查");
driver_label.set_label_size(15);
driver_label.set_align(Align::Left | Align::Inside);
let mut refresh_btn = Button::default()
.with_pos(836, 14)
.with_size(128, 32)
.with_label("刷新设备");
refresh_btn.set_label_size(15);
let mut tabs = Tabs::new(8, 52, 964, 576, "");
let mut page_edl = Group::new(8, 52, 964, 576, "9008设备");
page_edl.set_label_size(15);
let mut hint = Frame::default()
.with_pos(16, 500)
.with_size(460, 56)
.with_label(&initial.hint);
hint.set_label_size(15);
hint.set_align(Align::Left | Align::Inside | Align::Wrap);
let mut table = TableRow::new(16, 88, 948, 400, "");
table.set_cols(COLUMNS.len() as i32);
table.set_rows(0);
table.set_col_header(true);
table.set_col_header_height(28);
table.set_row_header(false);
table.set_row_height_all(28);
table.set_col_resize(true);
table.set_col_resize_min(48);
table.set_type(TableRowSelectMode::Single);
for (index, width) in [46, 110, 110, 190, 90, 230, 160].into_iter().enumerate() {
table.set_col_width(index as i32, width);
}
table.end();
let devices_draw = Arc::clone(&devices);
table.draw_cell(move |table, ctx, row, col, x, y, w, h| {
match ctx {
TableContext::ColHeader => {
fltk::draw::push_clip(x, y, w, h);
fltk::draw::draw_box(FrameType::ThinUpBox, x, y, w, h, Color::FrameDefault);
fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120));
fltk::draw::draw_rect(x, y, w, h);
if col == 0 {
let list = devices_draw.lock().unwrap();
let all = !list.is_empty() && list.iter().all(|dev| dev.checked);
draw_mark(all, x, y, w, h);
} else {
fltk::draw::set_draw_color(Color::Foreground);
fltk::draw::set_font(Font::Helvetica, 15);
let title = COLUMNS.get(col as usize).copied().unwrap_or("");
fltk::draw::draw_text2(title, x, y, w, h, Align::Center);
}
fltk::draw::pop_clip();
}
TableContext::Cell => {
let selected = table.row_selected(row);
let background = if selected { Color::Selection } else { Color::White };
fltk::draw::push_clip(x, y, w, h);
fltk::draw::draw_box(FrameType::FlatBox, x, y, w, h, background);
fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120));
fltk::draw::draw_rect(x, y, w, h);
if col == 0 {
let checked = devices_draw.lock().unwrap().get(row as usize).is_some_and(|dev| dev.checked);
draw_mark(checked, x, y, w, h);
} else {
fltk::draw::set_draw_color(if selected { Color::White } else { Color::Foreground });
fltk::draw::set_font(Font::Helvetica, 15);
let text = cell_text(&devices_draw, row, col);
fltk::draw::draw_text2(&text, x, y, w, h, Align::Center);
}
fltk::draw::pop_clip();
}
_ => {}
}
});
let mut parts = CheckButton::default()
.with_pos(490, 496)
.with_size(300, 28)
.with_label("刷机前备份基带四分区");
parts.set_label_size(15);
parts.set_value(true);
let mut full = CheckButton::default()
.with_pos(490, 528)
.with_size(300, 28)
.with_label("同时备份整盘 eMMC");
full.set_label_size(15);
let mut batch_btn = Button::default()
.with_pos(804, 496)
.with_size(160, 60)
.with_label("批量刷机");
batch_btn.set_label_size(15);
batch_btn.deactivate();
page_edl.end();
let mut page_adb = Group::new(8, 52, 964, 576, "ADB设备");
page_adb.set_label_size(15);
let mut adb_table = TableRow::new(16, 88, 948, 520, "");
adb_table.set_cols(ADB_COLUMNS.len() as i32);
adb_table.set_rows(0);
adb_table.set_col_header(true);
adb_table.set_col_header_height(28);
adb_table.set_row_header(false);
adb_table.set_row_height_all(28);
adb_table.set_col_resize(true);
adb_table.set_col_resize_min(48);
adb_table.set_type(TableRowSelectMode::Single);
for (index, width) in [130, 100, 180, 52, 80, 90, 196, 90].into_iter().enumerate() {
adb_table.set_col_width(index as i32, width);
}
adb_table.end();
let adb_draw = Arc::clone(&adb_devices);
adb_table.draw_cell(move |table, ctx, row, col, x, y, w, h| {
match ctx {
TableContext::ColHeader => {
fltk::draw::push_clip(x, y, w, h);
fltk::draw::draw_box(FrameType::ThinUpBox, x, y, w, h, Color::FrameDefault);
fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120));
fltk::draw::draw_rect(x, y, w, h);
fltk::draw::set_draw_color(Color::Foreground);
fltk::draw::set_font(Font::Helvetica, 15);
let title = ADB_COLUMNS.get(col as usize).copied().unwrap_or("");
fltk::draw::draw_text2(title, x, y, w, h, Align::Center);
fltk::draw::pop_clip();
}
TableContext::Cell => {
let selected = table.row_selected(row);
let background = if selected { Color::Selection } else { Color::White };
fltk::draw::push_clip(x, y, w, h);
fltk::draw::draw_box(FrameType::FlatBox, x, y, w, h, background);
fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120));
fltk::draw::draw_rect(x, y, w, h);
fltk::draw::set_draw_color(if selected { Color::White } else { Color::Foreground });
fltk::draw::set_font(Font::Helvetica, 15);
let text = adb_cell(&adb_draw, row, col);
fltk::draw::draw_text2(&text, x, y, w, h, Align::Center);
fltk::draw::pop_clip();
}
_ => {}
}
});
page_adb.end();
tabs.end();
// 分页标签画在容器顶部。不主动缩小子页面时,页面会盖住标签。
let (area_x, mut area_y, area_w, mut area_h) = tabs.client_area();
if area_y <= 52 {
area_y = 84;
area_h = 544;
}
page_edl.resize(area_x, area_y, area_w, area_h);
page_adb.resize(area_x, area_y, area_w, area_h);
window.end();
window.show();
{
let mut model_label = model_label.clone();
let mut model_choice = model_choice.clone();
tabs.set_callback(move |tabs| {
let on_adb = tabs.value().is_some_and(|group| group.label() == "ADB设备");
if on_adb {
model_label.hide();
model_choice.hide();
} else {
model_label.show();
model_choice.show();
}
});
}
{
let profiles = profiles.clone();
let selected = Arc::clone(&selected);
let devices = Arc::clone(&devices);
let queue = Arc::clone(&queue);
let refresh_now = Arc::clone(&refresh_now);
let model_guard = Arc::clone(&model_guard);
let mut window = window.clone();
let mut hint = hint.clone();
let tx = tx.clone();
let root = root.clone();
model_choice.set_callback(move |choice| {
if model_guard.load(Ordering::SeqCst) {
return;
}
let text = choice.value().unwrap_or_default();
if let Some(profile) = profiles.iter().find(|item| display(item) == text || item.id.eq_ignore_ascii_case(text.trim())).cloned() {
if profile.id == selected.lock().unwrap().id {
return;
}
if devices.lock().unwrap().iter().any(task_running) {
let current = selected.lock().unwrap().clone();
model_guard.store(true, Ordering::SeqCst);
choice.set_value(&display(&current));
model_guard.store(false, Ordering::SeqCst);
return;
}
remember(&root, &profile.id);
window.set_label(&format!("{} Flasher", profile.id));
hint.set_label(&profile.hint);
hint.redraw();
*selected.lock().unwrap() = profile.clone();
devices.lock().unwrap().clear();
queue.lock().unwrap().clear();
refresh_now.store(true, Ordering::SeqCst);
let tx = tx.clone();
let driver_dir = profile.driver_dir.clone();
thread::spawn(move || ensure_driver(tx, driver_dir));
return;
}
let query = text.trim().to_string();
if query.is_empty() {
let current = selected.lock().unwrap().clone();
model_guard.store(true, Ordering::SeqCst);
fill_models(choice, &profiles, "");
choice.set_value(&display(&current));
model_guard.store(false, Ordering::SeqCst);
return;
}
model_guard.store(true, Ordering::SeqCst);
fill_models(choice, &profiles, &query);
choice.set_value(&query);
model_guard.store(false, Ordering::SeqCst);
});
}
{
let full_disk = Arc::clone(&full_disk);
full.set_callback(move |button| *full_disk.lock().unwrap() = button.value());
}
{
let backup_parts = Arc::clone(&backup_parts);
parts.set_callback(move |button| *backup_parts.lock().unwrap() = button.value());
}
{
let refresh_now = Arc::clone(&refresh_now);
let adb_refresh = Arc::clone(&adb_refresh);
refresh_btn.set_callback(move |button| {
button.deactivate();
refresh_now.store(true, Ordering::SeqCst);
adb_refresh.store(true, Ordering::SeqCst);
});
}
{
let devices = Arc::clone(&devices);
let queue = Arc::clone(&queue);
batch_btn.set_callback(move |_| enqueue_checked(&queue, &devices));
}
{
let refresh_now = Arc::clone(&refresh_now);
let selected = Arc::clone(&selected);
thread::spawn(move || loop {
let manual = refresh_now.swap(false, Ordering::SeqCst);
let (vid, pid) = {
let profile = selected.lock().unwrap();
(profile.vid.clone(), profile.pid.clone())
};
let found = scan_ports(&vid, &pid).ok();
if scan_tx.send((found, manual)).is_err() {
break;
}
let mut waited = 0;
while waited < 1500 {
if refresh_now.load(Ordering::SeqCst) {
break;
}
thread::sleep(Duration::from_millis(100));
waited += 100;
}
});
}
{
let adb_refresh = Arc::clone(&adb_refresh);
let claims = Arc::clone(&claims);
let tx = tx.clone();
thread::spawn(move || loop {
let _manual = adb_refresh.swap(false, Ordering::SeqCst);
let found = adb::list_devices();
advance_claims(&found, &claims, &tx);
if adb_tx.send(found).is_err() {
break;
}
let mut waited = 0;
while waited < 2000 {
if adb_refresh.load(Ordering::SeqCst) {
break;
}
thread::sleep(Duration::from_millis(100));
waited += 100;
}
});
}
{
let tx = tx.clone();
let driver_dir = selected.lock().unwrap().driver_dir.clone();
thread::spawn(move || ensure_driver(tx, driver_dir));
}
table.handle({
let devices = Arc::clone(&devices);
let queue = Arc::clone(&queue);
move |table, ev| {
if ev == Event::Released && app::event_button() == MouseButton::Left as i32 {
let Some((ctx, row, col, _)) = table.cursor2rowcol() else {
return false;
};
if col != 0 {
return false;
}
if ctx == TableContext::ColHeader {
toggle_all(&devices);
table.redraw();
return true;
}
if ctx == TableContext::Cell && row >= 0 {
toggle_row(&devices, row);
table.redraw();
return true;
}
return false;
}
if ev != Event::Released || app::event_button() != MouseButton::Right as i32 {
return false;
}
let (pointer_x, pointer_y) = (app::event_x(), app::event_y());
let Some((ctx, row, _, _)) = table.cursor2rowcol() else {
return false;
};
if ctx != TableContext::Cell || row < 0 {
return false;
}
let _ = table.select_row(row, TableRowSelectFlag::Select);
let location = devices.lock().unwrap().get(row as usize).map(|dev| dev.location.clone());
let Some(location) = location else { return true };
let is_busy = devices.lock().unwrap().iter().find(|dev| dev.location == location).is_some_and(|dev| {
task_running(dev) || dev.mismatch || !dev.info_done || dev.chip.is_empty()
});
popup_menu(&queue, &devices, &location, is_busy, pointer_x, pointer_y);
true
}
});
adb_table.handle({
let adb_devices = Arc::clone(&adb_devices);
let devices = Arc::clone(&devices);
let selected = Arc::clone(&selected);
let adb_refresh = Arc::clone(&adb_refresh);
move |table, ev| {
if ev != Event::Released || app::event_button() != MouseButton::Right as i32 {
return false;
}
let (pointer_x, pointer_y) = (app::event_x(), app::event_y());
let Some((ctx, row, _, _)) = table.cursor2rowcol() else {
return false;
};
if ctx != TableContext::Cell || row < 0 {
return false;
}
let _ = table.select_row(row, TableRowSelectFlag::Select);
let Some(device) = adb_devices.lock().unwrap().get(row as usize).cloned() else {
return true;
};
adb_popup(&device, &devices, &selected, &adb_refresh, pointer_x, pointer_y);
true
}
});
app::add_timeout3(0.5, {
let devices = Arc::clone(&devices);
let queue = Arc::clone(&queue);
let mut table = table.clone();
let mut driver_label = driver_label.clone();
let mut refresh_btn = refresh_btn.clone();
let mut batch_btn = batch_btn.clone();
let mut model_choice = model_choice.clone();
let mut adb_table = adb_table.clone();
let adb_devices = Arc::clone(&adb_devices);
let claims = Arc::clone(&claims);
let selected = Arc::clone(&selected);
move |handle| {
while let Ok((found, manual)) = scan_rx.try_recv() {
let Some(found) = found else {
if manual {
refresh_btn.activate();
}
continue;
};
apply_found(&found, &devices, &queue);
if manual {
let alive = {
let mut list = devices.lock().unwrap();
let claimed = claims.lock().unwrap().iter().map(|claim| claim.location.clone()).collect::<Vec<_>>();
list.retain(|dev| dev.present || claimed.iter().any(|location| location == &dev.location));
for dev in list.iter_mut() {
let retry = dev.serial.is_empty()
&& (dev.status.starts_with("失败")
|| dev.status.starts_with("重新进入")
|| dev.status == UNPLUGGED);
if retry && !task_running(dev) {
dev.info_done = false;
dev.status = "9008".into();
}
}
list.iter().map(|dev| dev.location.clone()).collect::<Vec<_>>()
};
queue.lock().unwrap().retain(|job| alive.iter().any(|loc| loc == &job.location));
refresh_btn.activate();
}
}
while let Ok(found) = adb_rx.try_recv() {
*adb_devices.lock().unwrap() = found;
refresh_adb_table(&mut adb_table, &adb_devices);
refresh_btn.activate();
}
while let Ok(msg) = rx.try_recv() {
if let EventMsg::Driver(text) = msg {
driver_label.set_label(&text);
driver_label.redraw();
} else {
let flashed = match &msg {
EventMsg::Finished(location, "flash") => Some(location.clone()),
_ => None,
};
let chip = selected.lock().unwrap().chip.clone();
apply(&devices, msg, &chip);
if let Some(location) = flashed {
begin_claim(&location, &devices, &adb_devices, &claims, &selected);
}
}
}
refresh_table(&mut table, &devices);
ensure_identify(&queue, &devices);
let busy = devices.lock().unwrap().iter().any(task_running);
if busy {
model_choice.deactivate();
} else {
model_choice.activate();
}
let can_batch = devices.lock().unwrap().iter().any(|dev| dev.checked && can_operate(dev));
if can_batch {
batch_btn.activate();
} else {
batch_btn.deactivate();
}
app::repeat_timeout3(0.2, handle);
}
});
app.run().unwrap();
}
fn toggle_row(devices: &Arc<Mutex<Vec<Device>>>, row: i32) {
let mut list = devices.lock().unwrap();
if let Some(dev) = list.get_mut(row as usize) {
if dev.mismatch {
return;
}
dev.checked = !dev.checked;
}
}
fn toggle_all(devices: &Arc<Mutex<Vec<Device>>>) {
let mut list = devices.lock().unwrap();
let check = list.iter().any(|dev| can_operate(dev) && !dev.checked);
for dev in list.iter_mut() {
if can_operate(dev) || !check {
dev.checked = check && can_operate(dev);
}
}
}
fn enqueue_checked(queue: &Arc<Mutex<VecDeque<Job>>>, devices: &Arc<Mutex<Vec<Device>>>) {
let locations: Vec<String> = devices
.lock()
.unwrap()
.iter()
.filter(|dev| dev.checked && can_operate(dev))
.map(|dev| dev.location.clone())
.collect();
for location in locations {
enqueue(queue, devices, &location, JobKind::Flash);
}
}
fn job_status(kind: JobKind) -> &'static str {
match kind {
JobKind::Info => "正在识别",
JobKind::Backup => "备份中",
JobKind::Flash => "写入中",
}
}
fn ensure_identify(queue: &Arc<Mutex<VecDeque<Job>>>, devices: &Arc<Mutex<Vec<Device>>>) {
let locations: Vec<String> = devices
.lock()
.unwrap()
.iter()
.filter(|dev| {
dev.present
&& dev.serial.is_empty()
&& !dev.info_done
&& !dev.status.starts_with("失败")
&& dev.status != DONE
&& !task_running(dev)
})
.map(|dev| dev.location.clone())
.collect();
for location in locations {
enqueue(queue, devices, &location, JobKind::Info);
}
}
fn enqueue(queue: &Arc<Mutex<VecDeque<Job>>>, devices: &Arc<Mutex<Vec<Device>>>, location: &str, kind: JobKind) {
let mut list = devices.lock().unwrap();
let Some(dev) = list.iter_mut().find(|d| d.location == location) else { return };
if task_running(dev) {
return;
}
if kind != JobKind::Info && (dev.mismatch || !dev.info_done || dev.chip.is_empty()) {
return;
}
dev.queued = true;
dev.pending = Some(kind);
dev.progress = 0;
dev.bytes_done = 0;
dev.bytes_total = 0;
dev.rate.clear();
dev.status = job_status(kind).into();
queue.lock().unwrap().push_back(Job { location: location.to_string(), kind, resume: false });
}
fn popup_menu(queue: &Arc<Mutex<VecDeque<Job>>>, devices: &Arc<Mutex<Vec<Device>>>, location: &str, is_busy: bool, x: i32, y: i32) {
let flag = if is_busy { MenuFlag::Inactive } else { MenuFlag::Normal };
let item = |text| CMenuItem {
text: Some(text),
flags: flag,
shortcut: Shortcut::None,
cb: None,
labeltype: LabelType::Normal,
labelfont: Font::Helvetica,
labelsize: 15,
labelcolor: Color::Foreground,
};
let menu = MenuItem::new_from_cmenu(&[item("备份"), item("刷机")]);
let Some(item) = menu.popup(x, y) else { return };
if is_busy {
return;
}
match item.label().unwrap_or_default().as_str() {
"备份" => enqueue(queue, devices, location, JobKind::Backup),
"刷机" => enqueue(queue, devices, location, JobKind::Flash),
_ => {}
}
}
fn apply_found(found: &[(String, String, String, String)], devices: &Arc<Mutex<Vec<Device>>>, queue: &Arc<Mutex<VecDeque<Job>>>) {
let mut list = devices.lock().unwrap();
for (location, service, instance_id, usb_path) in found {
let route = if usb_path.is_empty() { port_num(location) } else { usb_path.clone() };
if let Some(dev) = list.iter_mut().find(|d| &d.location == location) {
dev.service = service.clone();
dev.instance_id = instance_id.clone();
dev.port_num = route;
if dev.status == WAIT && is_winusb(service) {
if let Some(kind) = dev.pending.take() {
if !dev.queued {
dev.queued = true;
dev.status = job_status(kind).into();
queue.lock().unwrap().push_back(Job {
location: dev.location.clone(),
kind,
resume: true,
});
}
}
}
} else {
list.push(Device {
location: location.clone(),
port_num: route,
service: service.clone(),
instance_id: instance_id.clone(),
serial: String::new(),
chip: String::new(),
disk: String::new(),
status: "9008".into(),
rate: String::new(),
progress: 0,
bytes_done: 0,
bytes_total: 0,
pending: None,
queued: false,
present: true,
checked: false,
info_done: false,
mismatch: false,
missing_scans: 0,
});
}
}
for dev in list.iter_mut() {
let present = found.iter().any(|(location, _, _, _)| location == &dev.location);
dev.present = present;
if present {
let returned = dev.missing_scans > 0;
dev.missing_scans = 0;
if !task_running(dev) && (dev.status == UNPLUGGED || (returned && dev.serial.is_empty())) {
if dev.serial.is_empty() {
dev.info_done = false;
}
dev.status = "9008".into();
dev.progress = 0;
}
} else {
dev.missing_scans = dev.missing_scans.saturating_add(1);
}
}
}
fn adb_key(device: &adb::AdbDevice) -> String {
format!("{}:{}", device.transport, device.serial)
}
fn same_port(left: &str, right: &str) -> bool {
if left.is_empty() || right.is_empty() {
return false;
}
if left.eq_ignore_ascii_case(right) {
return true;
}
let left_bits = port_bits(left);
let right_bits = port_bits(right);
!left_bits.is_empty() && left_bits == right_bits
}
fn port_bits(text: &str) -> Vec<String> {
let mut bits = Vec::new();
for token in ["Port_#", "Hub_#"] {
if let Some(rest) = text.split(token).nth(1) {
let number: String = rest.chars().take_while(|ch| ch.is_ascii_digit()).collect();
if !number.is_empty() {
bits.push(format!("{token}{number}"));
}
}
}
bits
}
fn begin_claim(
location: &str,
devices: &Arc<Mutex<Vec<Device>>>,
adb_devices: &Arc<Mutex<Vec<adb::AdbDevice>>>,
claims: &Arc<Mutex<Vec<Claim>>>,
selected: &Arc<Mutex<Profile>>,
) {
let profile = selected.lock().unwrap().clone();
let mut list = devices.lock().unwrap();
let Some(dev) = list.iter_mut().find(|dev| dev.location == location) else {
return;
};
if dev.serial.is_empty() {
return;
}
if profile.boot_host.is_empty() || profile.boot_model.is_empty() {
dev.status = "配置没有开机特征,未自动标记".into();
return;
}
let seen = adb_devices.lock().unwrap().iter().map(adb_key).collect();
let chip_serial = dev.serial.clone();
let location = dev.location.clone();
dev.status = "等待开机后的 ADB".into();
let mut claims = claims.lock().unwrap();
claims.retain(|claim| claim.location != location);
claims.push(Claim {
location,
chip_serial,
model_id: profile.id,
boot_host: profile.boot_host,
boot_model: profile.boot_model,
seen,
stage: ClaimStage::Wait,
since: Instant::now(),
token: String::new(),
});
}
fn advance_claims(found: &[adb::AdbDevice], claims: &Arc<Mutex<Vec<Claim>>>, tx: &mpsc::Sender<EventMsg>) {
let jobs = {
let mut list = claims.lock().unwrap();
let mut jobs = Vec::new();
let mut index = 0;
while index < list.len() {
if list[index].stage == ClaimStage::Marking {
index += 1;
continue;
}
if list[index].stage == ClaimStage::Confirm {
let linked = found.iter().any(|device| {
device.serial.eq_ignore_ascii_case(&list[index].chip_serial)
&& device.mark_chip.eq_ignore_ascii_case(&list[index].chip_serial)
});
if linked {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "已接上 ADB".into()));
list.remove(index);
continue;
}
if list[index].since.elapsed() > Duration::from_secs(180) {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "未重新识别到新序列号".into()));
list.remove(index);
continue;
}
index += 1;
continue;
}
if list[index].since.elapsed() > Duration::from_secs(180) {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "开机后未对上同一USB口".into()));
list.remove(index);
continue;
}
let hits: Vec<adb::AdbDevice> = found
.iter()
.filter(|device| {
same_port(&device.port, &list[index].location)
&& !list[index].seen.iter().any(|key| key == &adb_key(device))
})
.cloned()
.collect();
if hits.len() > 1 {
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "同一USB口对应多台ADB,已停止".into()));
list.remove(index);
continue;
}
if hits.is_empty() {
index += 1;
continue;
}
let device = &hits[0];
if device.host.is_empty() || device.board_model.is_empty() {
index += 1;
continue;
}
if !device.host.eq_ignore_ascii_case(&list[index].boot_host)
|| device.board_model.trim() != list[index].boot_model.trim()
{
let _ = tx.send(EventMsg::Status(list[index].location.clone(), "开机特征不符,未写标记".into()));
list.remove(index);
continue;
}
list[index].stage = ClaimStage::Marking;
jobs.push((list[index].clone(), device.clone()));
index += 1;
}
jobs
};
for (claim, device) in jobs {
let _ = tx.send(EventMsg::Status(claim.location.clone(), "正在写入标记".into()));
match adb::mark(&device, &claim.chip_serial, &claim.model_id) {
Ok(token) => {
let _ = tx.send(EventMsg::Status(claim.location.clone(), "正在重启以应用新序列号".into()));
let _ = adb::reboot(&device);
if let Some(slot) = claims.lock().unwrap().iter_mut().find(|item| item.location == claim.location) {
slot.token = token;
slot.stage = ClaimStage::Confirm;
slot.since = Instant::now();
}
}
Err(err) => {
let _ = tx.send(EventMsg::Status(claim.location.clone(), format!("标记失败:{err}")));
claims.lock().unwrap().retain(|item| item.location != claim.location);
}
}
}
}
fn adb_cell(devices: &Mutex<Vec<adb::AdbDevice>>, row: i32, col: i32) -> String {
let list = devices.lock().unwrap();
let Some(dev) = list.get(row as usize) else {
return String::new();
};
let text = match col {
0 => dev.serial.clone(),
1 => dev.chip.clone(),
2 => dev.port.clone(),
3 => dev.cores.clone(),
4 => dev.memory.clone(),
5 => dev.disk.clone(),
6 => dev.system.clone(),
7 => dev.marked.clone(),
_ => String::new(),
};
if text.is_empty() { "-".into() } else { text }
}
fn refresh_adb_table(table: &mut TableRow, devices: &Arc<Mutex<Vec<adb::AdbDevice>>>) {
let count = devices.lock().unwrap().len() as i32;
if table.rows() != count {
table.set_rows(count);
}
table.redraw();
}
fn chip_serial_for_port(devices: &Arc<Mutex<Vec<Device>>>, port: &str) -> String {
if port.is_empty() {
return String::new();
}
let list = devices.lock().unwrap();
let matched: Vec<_> = list
.iter()
.filter(|dev| dev.location == port && !dev.serial.is_empty())
.map(|dev| dev.serial.clone())
.collect();
if matched.len() == 1 {
matched[0].clone()
} else {
String::new()
}
}
fn adb_popup(
device: &adb::AdbDevice,
devices: &Arc<Mutex<Vec<Device>>>,
selected: &Arc<Mutex<Profile>>,
adb_refresh: &Arc<AtomicBool>,
x: i32,
y: i32,
) {
let item = |text| CMenuItem {
text: Some(text),
flags: MenuFlag::Normal,
shortcut: Shortcut::None,
cb: None,
labeltype: LabelType::Normal,
labelfont: Font::Helvetica,
labelsize: 15,
labelcolor: Color::Foreground,
};
let menu = MenuItem::new_from_cmenu(&[item("校准标记"), item("重启系统")]);
let Some(item) = menu.popup(x, y) else { return };
match item.label().unwrap_or_default().as_str() {
"校准标记" => {
let chip = chip_serial_for_port(devices, &device.port);
let model = selected.lock().unwrap().id.clone();
let device = device.clone();
let adb_refresh = Arc::clone(adb_refresh);
thread::spawn(move || {
let _ = adb::mark(&device, &chip, &model);
adb_refresh.store(true, Ordering::SeqCst);
});
}
"重启系统" => {
let device = device.clone();
let adb_refresh = Arc::clone(adb_refresh);
thread::spawn(move || {
let _ = adb::reboot(&device);
adb_refresh.store(true, Ordering::SeqCst);
});
}
_ => {}
}
}
fn cell_text(devices: &Mutex<Vec<Device>>, row: i32, col: i32) -> String {
let list = devices.lock().unwrap();
let Some(dev) = list.get(row as usize) else {
return String::new();
};
match col {
1 if dev.serial.is_empty() => "-".into(),
1 => dev.serial.clone(),
2 if dev.chip.is_empty() => "-".into(),
2 => dev.chip.clone(),
3 => dev.location.clone(),
4 if dev.disk.is_empty() => "-".into(),
4 => dev.disk.clone(),
5 if dev.rate.is_empty() => dev.status.clone(),
5 => format!("{} {}", dev.status, dev.rate),
6 if dev.bytes_total > 0 && dev.status.contains('备') => {
format!("{}/{}", format_amount(dev.bytes_done), format_amount(dev.bytes_total))
}
6 => format!("{}%", dev.progress),
_ => String::new(),
}
}
fn draw_mark(checked: bool, x: i32, y: i32, w: i32, h: i32) {
let size = 16;
let left = x + (w - size) / 2;
let top = y + (h - size) / 2;
fltk::draw::draw_box(FrameType::ThinDownBox, left, top, size, size, Color::White);
if checked {
fltk::draw::draw_check(left, top, size, size, Color::Black);
}
}
fn format_amount(bytes: u64) -> String {
const KB: f64 = 1024.0;
const MB: f64 = 1024.0 * 1024.0;
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
let value = bytes as f64;
let (scaled, unit) = if value >= GB {
(value / GB, "GB")
} else if value >= MB {
(value / MB, "MB")
} else if value >= KB {
(value / KB, "KB")
} else {
return format!("{bytes}B");
};
if scaled >= 100.0 || (scaled - scaled.round()).abs() < 0.05 {
format!("{:.0}{unit}", scaled)
} else {
format!("{:.1}{unit}", scaled)
}
}
fn refresh_table(table: &mut TableRow, devices: &Arc<Mutex<Vec<Device>>>) {
let count = devices.lock().unwrap().len() as i32;
if table.rows() != count {
table.set_rows(count);
}
table.redraw();
}
fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg, expected_chip: &str) {
let mut list = devices.lock().unwrap();
match msg {
EventMsg::Serial(location, serial) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.serial = serial;
}
}
EventMsg::Chip(location, chip) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.chip = chip;
}
}
EventMsg::Disk(location, disk) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.disk = disk;
}
}
EventMsg::Progress(location, value) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.progress = value;
}
}
EventMsg::Bytes(location, done, total) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.bytes_done = done;
dev.bytes_total = total;
if total > 0 {
dev.progress = ((done.saturating_mul(100)) / total).min(100) as i32;
}
}
}
EventMsg::Status(location, status) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.status = status;
dev.rate.clear();
dev.bytes_done = 0;
dev.bytes_total = 0;
}
}
EventMsg::Rate(location, rate) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.rate = rate;
}
}
EventMsg::Finished(location, kind) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.queued = false;
dev.pending = None;
dev.rate.clear();
dev.bytes_done = 0;
dev.bytes_total = 0;
if kind == "info" {
dev.info_done = true;
dev.progress = 0;
if dev.chip.is_empty() {
dev.mismatch = true;
dev.checked = false;
dev.status = "重新进入9008后可读序列号".into();
} else if !chip_matches(&dev.chip, expected_chip) {
dev.mismatch = true;
dev.checked = false;
dev.status = MISMATCH.into();
} else {
dev.mismatch = false;
dev.status = "9008".into();
}
} else {
dev.progress = 100;
dev.status = if kind == "flash" { DONE.into() } else { "备份完成".into() };
}
}
}
EventMsg::Failed(location, err) => {
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
dev.queued = false;
dev.pending = None;
dev.rate.clear();
dev.bytes_done = 0;
dev.bytes_total = 0;
dev.info_done = true;
if err == "设备已拔出" {
dev.present = false;
dev.status = UNPLUGGED.into();
} else if err == MISMATCH {
dev.mismatch = true;
dev.checked = false;
dev.status = MISMATCH.into();
} else if err == "未能确认芯片型号" {
dev.mismatch = true;
dev.checked = false;
dev.status = "重新进入9008后可读序列号".into();
} else {
dev.status = format!("失败:{err}");
}
}
}
EventMsg::Driver(_) => {}
}
}