fix direct connection startup and drag stability

This commit is contained in:
zhy200308
2026-08-12 14:28:49 +08:00
parent 8b3f5c0216
commit 1c5e015285
9 changed files with 164 additions and 59 deletions
+2 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 22
versionName = "0.4.10"
versionCode = 23
versionName = "0.4.11"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -202,7 +202,7 @@ class MainActivity : ComponentActivity() {
) { showReceivedFiles() })
root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.4.10 · Android 7+ 到最新", 12f, MUTED))
root.addView(text("QFT v0.4.11 · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
@@ -636,15 +636,15 @@ class MainActivity : ComponentActivity() {
transferExecutor.execute {
if (attempt != pairConnectionAttempt) return@execute
val dedicatedWifi = pair.wifi != null
val gateways = if (dedicatedWifi) {
runOnUiThread { updateConnectingStatus("专用 Wi-Fi 已连接 · 正在读取实际网关…") }
wifiConnector.awaitGatewayEndpoints(network, pair.port, timeoutMs = 3_500L)
} else {
wifiConnector.gatewayEndpoints(network, pair.port)
}
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
val routedEndpoints = if (dedicatedWifi) emptyList() else {
wifiConnector.endpointsOnNetwork(network, pair.endpoints, pair.port)
}
var subnet = if (dedicatedWifi) {
wifiConnector.subnetEndpoints(network, pair.port)
} else {
emptyList()
}
val directCandidates = EndpointRouting.afterConnection(
dedicatedWifi = dedicatedWifi,
gatewayEndpoints = gateways,
@@ -655,22 +655,30 @@ class MainActivity : ComponentActivity() {
// 不使用二维码地址,也不猜测 192.168.137/49 网段。
runOnUiThread {
updateConnectingStatus(
if (dedicatedWifi) "已取得专用网络网关 · 正在认证电脑…"
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证网关和电脑…"
else "网络已就绪 · 正在连接同网段电脑…"
)
}
val direct = UploadClient.probeEndpoints(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = directCandidates,
connectMs = if (dedicatedWifi) 650 else 400,
readMs = if (dedicatedWifi) 850 else 600,
)
val direct = if (dedicatedWifi) {
UploadClient.probeConnectedNetwork(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = directCandidates + subnet,
)
} else {
UploadClient.probeEndpoints(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = directCandidates,
connectMs = 400,
readMs = 600,
)
}
// 直连不通才退回发现流程:UDP 广播 → 子网扫描
// 网关/子网并行快探不通才退回 UDP,并刷新路由后再恢复。
var discovered: String? = null
var subnet: List<String> = emptyList()
if (direct == null) {
runOnUiThread {
updateConnectingStatus(
@@ -684,7 +692,11 @@ class MainActivity : ComponentActivity() {
hosts = wifiConnector.discoveryHosts(network),
deviceName = receiverDeviceLabel,
)
subnet = wifiConnector.subnetEndpoints(network, pair.port)
// LinkProperties may have gained routes while the first
// scan was running; refresh the actual connected subnet.
if (dedicatedWifi) {
subnet = wifiConnector.subnetEndpoints(network, pair.port)
}
runOnUiThread {
updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
@@ -1096,38 +1108,48 @@ class MainActivity : ComponentActivity() {
file: SelectedFile,
container: LinearLayout,
) {
var downRawY = 0f
var startIndex = -1
handle.setOnTouchListener { view, event ->
if (uploadRunning) return@setOnTouchListener false
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
view.parent?.requestDisallowInterceptTouchEvent(true)
downRawY = event.rawY
startIndex = selectedFiles.indexOfFirst { it.uri == file.uri }
row.alpha = 0.72f
row.translationZ = dp(8).toFloat()
true
}
MotionEvent.ACTION_MOVE -> {
val location = IntArray(2)
container.getLocationOnScreen(location)
val y = event.rawY - location[1]
var target = container.childCount - 1
for (index in 0 until container.childCount) {
val child = container.getChildAt(index)
if (y < child.top + child.height / 2f) {
target = index
break
}
}
val current = selectedFiles.indexOfFirst { it.uri == file.uri }
if (moveQueueItem(selectedFiles, current, target)) {
container.removeView(row)
container.addView(row, target)
}
// Never remove/reinsert the touched View here. Several OEM
// frameworks crash when a Button is detached while its
// dispatchTouchEvent is still on the stack. Move only the
// visual row; commit the list order once on ACTION_UP.
row.translationY = event.rawY - downRawY
true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
view.parent?.requestDisallowInterceptTouchEvent(false)
row.alpha = 1f
view.performClick()
renderSelectedFiles()
row.translationZ = 0f
val averageHeight = (0 until container.childCount)
.map { container.getChildAt(it).height.coerceAtLeast(1) }
.average()
.takeIf { it.isFinite() && it > 0.0 }
?: row.height.coerceAtLeast(1).toDouble()
val deltaRows = kotlin.math.round(row.translationY.toDouble() / averageHeight).toInt()
row.translationY = 0f
if (
event.actionMasked == MotionEvent.ACTION_UP &&
startIndex >= 0 &&
selectedFiles.isNotEmpty()
) {
val target = (startIndex + deltaRows).coerceIn(0, selectedFiles.lastIndex)
moveQueueItem(selectedFiles, startIndex, target)
view.performClick()
}
container.post { renderSelectedFiles() }
true
}
else -> false
@@ -163,11 +163,34 @@ object UploadClient {
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.distinct()
val scan = subnetEndpoints
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.filterNot { it in fast }
.distinct()
if (dedicatedWifi) {
// The group-owner route may remain absent on some Huawei/Windows
// combinations even though DHCP already supplied a usable /24.
// Probe gateway and the real connected subnet together, repeating
// while Windows finishes accepting the Wi-Fi Direct peer.
val candidates = (fast + scan).distinct()
val deadline = android.os.SystemClock.elapsedRealtime() + 6_000L
while (candidates.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(
network, pairing, deviceName, candidates,
workers = 48, connectMs = 180, readMs = 220,
)?.let { return it }
try { Thread.sleep(80) } catch (_: InterruptedException) { return null }
}
return null
}
// Give a newly associated Direct network enough time for ARP, the group
// owner route and Windows' new-network firewall profile to settle. A
// successful candidate still returns immediately, so this extends only
// the failure/recovery path.
val fastWindowMs = if (dedicatedWifi) 4_000L else 1_050L
val fastWindowMs = 1_050L
val fastDeadline = android.os.SystemClock.elapsedRealtime() + fastWindowMs
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260)
@@ -178,11 +201,6 @@ object UploadClient {
// Stage 2: actual connected subnet fallback. This specifically fixes the
// case where Windows Wi-Fi Direct is up but uses an unexpected gateway
// address. Up to /24 is scanned concurrently and still session-authenticated.
val scan = subnetEndpoints
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.filterNot { it in fast }
.distinct()
if (scan.isNotEmpty()) {
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 48, connectMs = 180, readMs = 220)
?.let { return it }
@@ -190,7 +208,7 @@ object UploadClient {
// One final pass covers a route/firewall transition that completed while
// the actual connected subnet fallback was running.
val deadline = android.os.SystemClock.elapsedRealtime() + if (dedicatedWifi) 1_200L else 500L
val deadline = android.os.SystemClock.elapsedRealtime() + 500L
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260)
?.let { return it }
@@ -223,6 +241,26 @@ object UploadClient {
readMs = readMs,
)
/**
* Dedicated Wi-Fi fast path. The Windows group owner is normally the first
* host in the actual connected subnet, so scan it immediately instead of
* waiting several seconds for Android to publish a default gateway route.
*/
fun probeConnectedNetwork(
network: Network?,
pairing: PairingPayload,
deviceName: String,
endpoints: List<String>,
): String? = probeCandidatesParallel(
network = network,
pairing = pairing,
deviceName = deviceName,
candidates = endpoints.distinct(),
workers = 48,
connectMs = 180,
readMs = 220,
)
private fun probeCandidatesParallel(
network: Network?,
pairing: PairingPayload,
@@ -113,11 +113,22 @@ class WifiConnector(context: Context) {
@Suppress("MissingPermission")
private fun connectModern(run: Int, wifi: WifiCredentials) {
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
notifyStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
// Ask the radio for a fresh scan immediately before presenting the
// NetworkSpecifier chooser. Some OEMs otherwise reuse an old scan cache
// and keep showing “searching” even though Windows has just started the
// QFT SSID. Android may throttle this call; requestNetwork still runs.
try {
val scanStarted = wifiManager.startScan()
Log.i(TAG, "attempt=$run active scan requested=$scanStarted")
} catch (e: Exception) {
Log.w(TAG, "attempt=$run active scan unavailable: ${e.message}")
}
notifyStatus("正在刷新 Wi-Fi 列表并连接 ${wifi.ssid}…")
val specifier = try {
WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.setIsHiddenSsid(false)
.build()
} catch (e: Exception) {
notifyUnavailable("配网参数无效:${e.message}")
@@ -224,7 +235,7 @@ class WifiConnector(context: Context) {
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
}, 8_000)
}, 4_000)
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke(
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +
+1 -1
View File
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qft-desktop"
version = "0.4.15"
version = "0.4.16"
dependencies = [
"anyhow",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "qft-desktop"
version = "0.4.15"
version = "0.4.16"
edition = "2024"
rust-version = "1.95"
+1 -1
View File
@@ -157,7 +157,7 @@ impl DirectAp {
if std::time::Instant::now() >= deadline {
bail!("Wi-Fi Direct AP 或连接监听器启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。")
}
std::thread::sleep(std::time::Duration::from_millis(80));
std::thread::sleep(std::time::Duration::from_millis(25));
};
let _ = publisher.RemoveStatusChanged(status_token);
+37 -7
View File
@@ -681,11 +681,12 @@ impl QftApp {
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)));
if let Some(label) = receive_rate_text(
self.receive.received,
self.receive.total,
self.receive.rate_bps,
) {
ui.label(label);
}
ui.separator();
ui.label(format!("最近保存:{}", self.receive.last_saved));
@@ -1070,7 +1071,6 @@ impl QftApp {
// 先创建专用网络,再绑定 0.0.0.0。虽然 Windows 理论上会把既有的
// INADDR_ANY socket 应用于后出现的网卡,但实机上 WFP/新网络配置文件
// 初始化存在竞态;服务后绑定可消除这一不必要的不确定性。
if direct_ap.is_some() { std::thread::sleep(Duration::from_millis(500)); }
let server = match ReceiverServer::start(save_dir, token.clone(), tx) {
Ok(v) => v,
Err(e) => {
@@ -1164,7 +1164,6 @@ impl QftApp {
}
} else { None };
if direct_ap.is_some() { std::thread::sleep(Duration::from_millis(500)); }
let server = match SenderServer::start(file, token.clone(), tx) {
Ok(v) => v,
Err(e) => {
@@ -1594,6 +1593,14 @@ impl QftApp {
fn ensure_direct_firewall_ready(&mut self) -> Result<(), String> {
self.pc.firewall_probe = None;
self.pc.firewall_probing = false;
// The exact executable and fixed-port rules were already verified in
// this process. Avoid starting another PowerShell (typically 1–2 s)
// every time the user starts the next Direct session; “重新检测” remains
// available if rules are changed externally while QFT is open.
if matches!(self.pc.firewall, firewall::FirewallStatus::Allowed) {
self.pc.firewall_note = "当前程序路径和直传端口已确认放行".into();
return Ok(());
}
let mut status = firewall::status();
if matches!(status, firewall::FirewallStatus::Allowed) {
self.pc.firewall = status;
@@ -1934,6 +1941,19 @@ fn human_duration(seconds: f64) -> String {
if minutes > 0 { format!("{minutes} 分 {secs} 秒") } else { format!("{secs} 秒") }
}
fn receive_rate_text(received: u64, total: u64, rate_bps: f64) -> Option<String> {
if rate_bps <= 1.0 {
return None;
}
let rate = human_bytes(rate_bps as u64);
if total > received {
let eta = (total - received) as f64 / rate_bps;
Some(format!("速度:{rate}/s · 预计剩余:{}", human_duration(eta)))
} else {
Some(format!("平均速度:{rate}/s"))
}
}
/// 把逻辑点尺寸吸附到物理像素整数上。
///
/// 二维码纹理用 NEAREST 采样:绘制尺寸若落在半个物理像素上,
@@ -2042,6 +2062,16 @@ fn human_bytes(v: u64) -> String {
mod font_tests {
use super::*;
#[test]
fn completed_receive_rate_never_shows_an_eta() {
let running = receive_rate_text(900, 1_000, 100.0).unwrap();
assert!(running.contains("预计剩余"));
let completed = receive_rate_text(1_000, 1_000, 100.0).unwrap();
assert_eq!(completed, "平均速度:100 B/s");
assert!(!completed.contains("预计剩余"));
}
#[test]
fn detects_ttc_collections_not_just_ttf() {
// 旧实现只看扩展名,把 macOS/Linux 清一色的 .ttc 全拒了
+5 -1
View File
@@ -16,6 +16,9 @@ assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'su
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload
assert 'MAX_WORKERS = 8' in download and 'bytes=$start-$end' in download and 'completionMapFile' in download
assert 'requestNetwork(request, cb)' in wifi and 'delivered.set(false)' in wifi
assert 'wifiManager.startScan()' in wifi and '.setIsHiddenSsid(false)' in wifi
assert 'probeConnectedNetwork' in upload and 'workers = 48' in upload
assert 'awaitGatewayEndpoints' not in main
assert 'if (mode == ScannerMode.PAIR) Size(960, 720) else Size(640, 480)' in main and 'Size(960, 540)' not in main
assert 'Camera2Interop.Extender' in main and 'CONTROL_AE_TARGET_FPS_RANGE' in main and 'STRATEGY_KEEP_ONLY_LATEST' in main
assert '设备拒绝显式高帧率请求' in main and 'fallbackAnalysis' in main
@@ -27,7 +30,8 @@ assert 'lockedCenterInView' in overlay and 'postInvalidateDelayed' in overlay an
assert 'assembler.acceptText(code.text)' in main and 'acceptBinary' not in main
assert 'showFileSelection' not in main and 'pickFiles.launch(arrayOf("*/*"))' in main
assert 'installFileQueueDrag' in main and 'uploadRunning' in main and 'moveQueueItem' in queue
assert 'row.translationY' in main and 'container.removeView(row)' not in main
assert 'BB8' in base45 or 'ALPHABET' in base45
all_kotlin='\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt'))
assert 'java.util.Base64' not in all_kotlin
print('PASS Android static guards: API24+, fast-pair/640x480 optical ROI, inline sortable upload queue, QFT2/Base45, dynamic lock/refocus, legacy/new Wi-Fi compatibility')
print('PASS Android static guards: API24+, fast-pair/subnet discovery, crash-safe sortable upload queue, QFT2/Base45, dynamic lock/refocus, legacy/new Wi-Fi compatibility')