Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f248deac17 | |||
| 1c5e015285 | |||
| 8b3f5c0216 | |||
| d7a29e035f | |||
| 144b7d1a8e | |||
| c1a4dbbd7a | |||
| 65223dafe4 | |||
| eccd93266e | |||
| f9e25819ee | |||
| 9c16cc1690 | |||
| 2bb6ce63ae | |||
| 4c294d4270 | |||
| 7b18c6a661 | |||
| b2edb3048a | |||
| 13624d9747 | |||
| 6abd932872 | |||
| f62fe8d23b | |||
| ae2c36fa54 | |||
| dec132cf3e | |||
| 22c7d7f22d | |||
| b5d124abe5 | |||
| 0281382c39 | |||
| ae41267221 |
@@ -1,4 +1,4 @@
|
||||
# QFT v0.4.7 implementation status
|
||||
# QFT v0.4.16 implementation status
|
||||
|
||||
## Windows → Android optical
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
- [x] wait for actual IPv4/link route before discovery
|
||||
- [x] UDP QFTDISC2 receiver discovery
|
||||
- [x] QR endpoint + gateway + directed broadcast + subnet fallback
|
||||
- [x] dedicated Wi-Fi immediate parallel gateway + actual-subnet probe
|
||||
- [x] HTTP bound to selected Android Network
|
||||
- [x] local cleartext network security config
|
||||
- [x] local/private IPv4 + session-token validation
|
||||
@@ -49,6 +50,8 @@
|
||||
- [x] Windows positioned concurrent writes
|
||||
- [x] temporary `.qftpart`, final SHA-256 and rename
|
||||
- [x] accepted sockets return to timeout-bound blocking I/O before file transfer
|
||||
- [x] inline Android file selection + removable, pre-transfer sortable queue
|
||||
- [x] crash-safe drag commit without detaching the active touched view
|
||||
- [x] loopback UDP + HTTP + out-of-order parallel integration test
|
||||
- [ ] physical Windows Wi-Fi Direct adapter / driver / firewall matrix
|
||||
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
# QFT · 超速二维码文件传输 v0.4.7
|
||||
# QFT · 超速二维码文件传输 v0.4.16
|
||||
|
||||
Windows + Android 双向候选版。v0.4 的核心目标不是继续堆“4 码理论吞吐”,而是解决 Android 端实际识别慢的问题:**删除 2×2/4 通道,改成一个大二维码 + 动态 ROI 锁定 + 高频局部解码**。
|
||||
Windows + Android 双向正式版。v0.4 的核心目标不是继续堆“4 码理论吞吐”,而是解决 Android 端实际识别慢的问题:**删除 2×2/4 通道,改成一个大二维码 + 动态 ROI 锁定 + 高频局部解码**。
|
||||
|
||||
v0.4.7 提供两套互不依赖的传输方式:
|
||||
v0.4.16 提供两套互不依赖的传输方式:
|
||||
|
||||
- **电脑 → 手机(纯光学)**:文件数据只经过 Windows 屏幕 → Android 摄像头;Wi‑Fi、蓝牙、局域网和互联网都不参与文件数据传输。
|
||||
- **扫码本地直传(双向)**:Windows 为“手机上传”和“电脑下发”分别生成方向明确的二维码。Android 扫码后连接 QFT 本地网络、通过 UDP/网关/子网探测定位电脑,并按二维码指定方向自动进入选文件上传或接收下载;文件数据不经过外网。
|
||||
|
||||
### v0.4.7 直传稳定性与并发策略
|
||||
### v0.4.16 直传稳定性与并发策略
|
||||
|
||||
- **双向均使用并行分块**:每个可分块文件以 8 路为目标并发数;分块大小根据文件大小自适应,范围为 **64 KiB–16 MiB**。小于一个最小分块的文件会自然只有一个请求。
|
||||
- **手机 → 电脑**:Android 使用 offset 定位的 Parallel v2 上传;Windows 对每块进行定位写入,重复块与完成请求可安全重试,最终以 SHA-256 校验后原子改名。
|
||||
- **电脑 → 手机**:Windows 支持精确的 HTTP `Range`(`206 Partial Content`);Android 对未完成块创建多个独立 Range 请求,并用 `.qftpart` 与完成位图恢复中断传输。每块最多重试 5 次,完成后校验 SHA-256 再保存至 `Downloads/QFT`。
|
||||
- **连接稳定性**:Windows 监听器保持非阻塞以便及时停止服务,但已连接的文件套接字会切换为带读写超时的阻塞模式,避免 Windows `WSAEWOULDBLOCK (10035)` 造成大文件中途失败。
|
||||
|
||||
> v0.4.7 已完成协议、图像合成解码、ROI、双向并发传输、UDP 发现、内存预算和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
|
||||
> v0.4.16 已完成协议、图像合成解码、ROI、双向并发传输、专用 Wi-Fi 快速发现、队列拖动稳定性和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
|
||||
|
||||
## v0.4.8:跨平台桌面端 + 电脑 ↔ 电脑互传
|
||||
|
||||
### macOS:请用 QFT.app 启动,不要直接跑裸二进制
|
||||
### macOS:请用 QFT超速文件传输.app 启动,不要直接跑裸二进制
|
||||
|
||||
`./package.sh` 在 macOS 上会同时产出 `QFT-Desktop`(裸二进制)和 `QFT.app`,
|
||||
**推荐用 `QFT.app`**。
|
||||
`./package.sh` 在 macOS 上会同时产出 `QFT超速文件传输`(裸二进制)和
|
||||
`QFT超速文件传输.app`,**推荐使用 `.app` 版本**。
|
||||
|
||||
直接运行裸二进制时,AppKit 的部分行为会不稳定——最典型的是点「选择文件」时
|
||||
`+[NSOpenPanel openPanel]` 返回 NULL:
|
||||
@@ -256,7 +256,7 @@ APK:
|
||||
|
||||
## 一键打包
|
||||
|
||||
脚本只打包 `desktop/` 下的 Rust 桌面端:执行 `cargo test` 和 `cargo build --release`,随后把 Rust 二进制、协议说明和 SHA-256 校验文件收集到带时间戳的 `dist/QFT-Rust-*` 目录并生成压缩包。脚本不检查、下载或调用 Android SDK、Java、Gradle:
|
||||
脚本执行锁定依赖的 Rust 测试和正式构建,随后把桌面程序、中文说明、协议及 SHA-256 校验收集到带时间戳的 `dist/QFT-正式版-*` 目录。脚本不会安装、下载或调用 Android SDK、Java、Gradle;如果已经在 Windows 上构建好 APK,则会自动将它收集进同一个中文正式包:
|
||||
|
||||
```bat
|
||||
package.bat
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# QFT 超速文件传输 v0.4.16 正式版
|
||||
|
||||
这是 Windows 与 Android 双端统一版本号的中文正式版。
|
||||
|
||||
## 本版重点
|
||||
|
||||
- Windows 扫码直传默认保持普通并排布局,专注二维码模式改为用户手动进入。
|
||||
- 优化直传控制、防火墙、二维码、连接状态区域布局,减少无效留白。
|
||||
- Windows 自动创建 QFT 专用 Wi-Fi Direct 网络,二维码不再强制携带电脑既有网卡地址。
|
||||
- Android 连接专用 Wi-Fi 后立即并行探测实际网关与当前子网,缩短“搜索电脑”时间。
|
||||
- Windows 已确认防火墙规则后复用检测结果,并移除专用网络启动后的固定等待。
|
||||
- Android 文件选择直接打开系统文件选择器,支持队列删除和传输前拖动排序。
|
||||
- Android 拖动采用松手后一次性提交顺序,修复部分厂商系统点击拖动闪退。
|
||||
- PC 接收完成后不再残留“预计剩余 <1 秒”,改为显示最终平均速度。
|
||||
|
||||
## 版本信息
|
||||
|
||||
- Windows 桌面端:`0.4.16`
|
||||
- Android 端:`0.4.16`(versionCode 23)
|
||||
- 最低 Android 版本:Android 7.0(API 24)
|
||||
- Windows:Windows 10/11 x64,使用 QFT Direct 时需要支持 Wi-Fi Direct 的无线网卡
|
||||
|
||||
## 中文封版打包
|
||||
|
||||
- Windows:运行 `package.bat`。
|
||||
- macOS/Linux:运行 `./package.sh`。
|
||||
- 打包脚本会执行 Rust 锁定依赖测试与正式构建,生成中文文件名、中文说明和 SHA-256 校验文件。
|
||||
- 脚本不会安装、下载或调用 Android SDK/Gradle;如果 Windows 上已经生成 APK,会自动收集到同一个正式包中。
|
||||
|
||||
## 验证状态
|
||||
|
||||
- Rust Windows 目标 `cargo check` 通过。
|
||||
- Rust 桌面端 71 项自动测试通过。
|
||||
- Android 配对协议、并行传输及兼容性静态检查通过。
|
||||
- Windows Wi-Fi Direct 与 Android 相机属于硬件链路,最终安装包仍应在目标 Windows 电脑和实际 Android 手机上完成一次扫码传输验收。
|
||||
+11
-9
@@ -1,12 +1,12 @@
|
||||
# QFT v0.4.7 test report
|
||||
# QFT v0.4.16 test report
|
||||
|
||||
Date: 2026-08-10
|
||||
Date: 2026-08-12
|
||||
|
||||
This report separates **tests actually executed in the current environment** from **physical hardware acceptance that cannot be simulated here**.
|
||||
|
||||
## What this RC changes
|
||||
## What this release changes
|
||||
|
||||
The v0.4.7 optical path is deliberately simpler than v0.3:
|
||||
The v0.4.16 optical path is deliberately simpler than v0.3:
|
||||
|
||||
- 2×2 / 4-channel QR removed;
|
||||
- one large QR only;
|
||||
@@ -21,6 +21,8 @@ The v0.4.7 optical path is deliberately simpler than v0.3:
|
||||
- Windows draggable split pane / focus-QR mode.
|
||||
|
||||
Android→Windows QFTPAIR2/discovery/parallel upload remains and is regression-tested.
|
||||
The release also adds immediate gateway/subnet probing after dedicated Wi-Fi association,
|
||||
crash-safe Android queue reordering, and a completed PC receive state without stale ETA text.
|
||||
|
||||
## Executed and passed
|
||||
|
||||
@@ -152,7 +154,7 @@ The guard models the Windows single-QR 1024×1024 RGBA pre-render queue:
|
||||
|
||||
This is a design-budget check, not an OS-enforced RSS hard cap. GPU/runtime allocators can add platform-specific memory.
|
||||
|
||||
## Important implementation decisions validated during v0.4.7
|
||||
## Important implementation decisions validated during v0.4.16
|
||||
|
||||
### QFT2 uses Result.text, not ZXing rawBytes
|
||||
|
||||
@@ -160,7 +162,7 @@ The active path is Base45 text. Android reconstructs the QFT binary frame from `
|
||||
|
||||
### Duplicate camera hits are not duplicate assembler work
|
||||
|
||||
At 45/60 display FPS, a camera can observe the same displayed QR in multiple exposures. v0.4.7 still counts every successful decode in diagnostics, but only a changed QFT2 text fingerprint is delivered to `SessionAssembler`.
|
||||
At 45/60 display FPS, a camera can observe the same displayed QR in multiple exposures. v0.4.16 still counts every successful decode in diagnostics, but only a changed QFT2 text fingerprint is delivered to `SessionAssembler`.
|
||||
|
||||
### AF/AE does not run on a fixed periodic timer
|
||||
|
||||
@@ -168,16 +170,16 @@ The scanner performs initial focus/metering, then re-meters after first lock or
|
||||
|
||||
## Not executable in this environment
|
||||
|
||||
The current generation environment does not contain the Windows MSVC Rust toolchain, Android SDK, a physical Android camera, a Windows display or a Windows Wi-Fi Direct adapter. Therefore the following are **not claimed as passed here**:
|
||||
The current generation environment does not contain the Windows MSVC Rust toolchain, Android SDK, a physical Android camera, a Windows display or a Windows Wi-Fi Direct adapter. The Windows GNU target `cargo check`, native desktop release build and 71 Rust tests passed, but the following are **not claimed as passed here**:
|
||||
|
||||
1. Windows `cargo check/test/build --release` for v0.4.7.
|
||||
1. Linking and running the final Windows `.exe` on a real Windows host.
|
||||
2. Android Gradle `:app:testDebugUnitTest :app:assembleDebug` against the real Android SDK.
|
||||
3. Actual 30/45/60 displayed FPS → CameraX/ZXing effective new-frame throughput.
|
||||
4. Lock acquisition/reacquisition timing on Android 7 and different phone camera pipelines.
|
||||
5. PreviewView overlay mapping on every OEM sensor/crop/rotation combination.
|
||||
6. Real Windows QFT Direct adapter / driver / firewall behavior.
|
||||
|
||||
The package remains an **RC** until those physical checks pass.
|
||||
The source is sealed as **v0.4.16**. The Windows executable and Android APK still require the physical acceptance below before public binary distribution.
|
||||
|
||||
## Required physical acceptance
|
||||
|
||||
|
||||
+9
-3
@@ -1,5 +1,11 @@
|
||||
QFT v0.4.7 test results
|
||||
UTC 2026-08-10T08:45:56Z
|
||||
QFT v0.4.16 test results
|
||||
Updated 2026-08-12 Asia/Shanghai
|
||||
|
||||
== v0.4.16 release increment ==
|
||||
PASS Windows GNU target cargo check
|
||||
PASS native desktop cargo test: 71 passed, 0 failed
|
||||
PASS native desktop cargo build --release --locked
|
||||
PASS Chinese release package generation with SHA-256 manifest
|
||||
|
||||
== protocol_selftest.py ==
|
||||
PASS QFT2/Base45 single-QR: 1200123 bytes, 2667 chunks, 22% frame loss, recovered in 6 rounds; QR-L v15 vs legacy Base64 v18, 12px/module@1024, text=722 chars, theoretical payload=26.4 KiB/s
|
||||
@@ -16,7 +22,7 @@ PASS loopback Parallel v2 integration: UDP discovery + HTTP auth + 6 out-of-orde
|
||||
== memory_budget_selftest.py ==
|
||||
PASS memory budget: single-QR cache=192 frames/768.0 MiB + 96 MiB transient allowance < 1100 MiB
|
||||
== android_compat_selftest.py ==
|
||||
PASS Android static guards: API24+, 640x480 single-QR ROI, reusable luma buffer, QFT2/Base45 text parse, dynamic lock/refocus, Camera2 FPS request, legacy/new Wi-Fi compatibility
|
||||
PASS Android static guards: API24+, fast-pair/subnet discovery, crash-safe sortable upload queue, QFT2/Base45, dynamic lock/refocus, legacy/new Wi-Fi compatibility
|
||||
== single_channel_guard_selftest.py ==
|
||||
PASS single-channel guard: one large QFT2/Base45 QR, 450B chunks, no 2x2/4-lane path, Android locked-ROI text decode only
|
||||
== kotlin_host_smoke.py ==
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
|
||||
Write-Host "== QFT v0.4.7 Windows host verification ==" -ForegroundColor Cyan
|
||||
Write-Host "== QFT v0.4.16 Windows host verification ==" -ForegroundColor Cyan
|
||||
|
||||
if (Get-Command python -ErrorAction SilentlyContinue) {
|
||||
Write-Host "[1/4] Core protocol/selftests"
|
||||
|
||||
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "com.qft.optical"
|
||||
minSdk = 24
|
||||
targetSdk = 35
|
||||
versionCode = 19
|
||||
versionName = "0.4.7"
|
||||
versionCode = 23
|
||||
versionName = "0.4.16"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
@@ -36,6 +36,10 @@ android {
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<!-- WifiLock 需要:传输期间阻止 Wi-Fi 进入省电休眠 -->
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
|
||||
|
||||
@@ -584,6 +584,11 @@ object DownloadClient {
|
||||
} finally {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
// Flushing every parallel range serializes the workers on Android's
|
||||
// storage barrier and can make Wi-Fi look much slower than it is. One
|
||||
// barrier after all ranges preserves the completed-file durability;
|
||||
// SHA-256 still rejects and re-downloads an interrupted/corrupt cache.
|
||||
RandomAccessFile(partial, "rw").use { it.fd.sync() }
|
||||
if (!ledger.allComplete()) {
|
||||
error("并行下载未完成:${ledger.bytesComplete()}/$expectedSize")
|
||||
}
|
||||
@@ -691,7 +696,6 @@ object DownloadClient {
|
||||
while (bytes.hasRemaining()) channel.write(bytes)
|
||||
received += n.toLong()
|
||||
}
|
||||
channel.force(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.qft.optical
|
||||
|
||||
import java.net.URI
|
||||
|
||||
/** Pure IPv4 routing helpers kept Android-free so candidate selection is testable. */
|
||||
object EndpointRouting {
|
||||
/**
|
||||
* A dedicated QFT Wi-Fi must never reuse QR/LAN adapter addresses. Its only
|
||||
* direct candidates are gateways supplied by Android for that exact Network.
|
||||
* Current-LAN fallback mode may additionally use advertised same-subnet IPs.
|
||||
*/
|
||||
fun afterConnection(
|
||||
dedicatedWifi: Boolean,
|
||||
gatewayEndpoints: List<String>,
|
||||
routedAdvertisedEndpoints: List<String>,
|
||||
): List<String> = if (dedicatedWifi) {
|
||||
gatewayEndpoints.distinct()
|
||||
} else {
|
||||
(gatewayEndpoints + routedAdvertisedEndpoints).distinct()
|
||||
}
|
||||
|
||||
/** Same isolation rule for retry/recovery after the first gateway probe. */
|
||||
fun forRecovery(
|
||||
dedicatedWifi: Boolean,
|
||||
discoveredEndpoint: String?,
|
||||
gatewayEndpoints: List<String>,
|
||||
advertisedEndpoints: List<String>,
|
||||
): List<String> {
|
||||
val candidates = listOfNotNull(discoveredEndpoint) + gatewayEndpoints
|
||||
return (candidates + if (dedicatedWifi) emptyList() else advertisedEndpoints).distinct()
|
||||
}
|
||||
|
||||
fun onAnySubnet(
|
||||
endpoints: List<String>,
|
||||
expectedPort: Int,
|
||||
localLinks: List<Pair<String, Int>>,
|
||||
): List<String> {
|
||||
val subnets = localLinks.mapNotNull { (address, prefix) ->
|
||||
ipv4(address)?.let { it to prefix.coerceIn(0, 32) }
|
||||
}
|
||||
if (subnets.isEmpty()) return emptyList()
|
||||
|
||||
return endpoints.filter { endpoint ->
|
||||
val uri = try { URI(endpoint) } catch (_: Exception) { return@filter false }
|
||||
if (uri.scheme != "http" || uri.port != expectedPort) return@filter false
|
||||
val candidate = ipv4(uri.host ?: return@filter false) ?: return@filter false
|
||||
subnets.any { (local, prefix) -> sameSubnet(local, candidate, prefix) }
|
||||
}.distinct()
|
||||
}
|
||||
|
||||
private fun sameSubnet(a: Long, b: Long, prefix: Int): Boolean {
|
||||
if (prefix == 0) return true
|
||||
val mask = (0xFFFF_FFFFL shl (32 - prefix)) and 0xFFFF_FFFFL
|
||||
return (a and mask) == (b and mask)
|
||||
}
|
||||
|
||||
private fun ipv4(value: String): Long? {
|
||||
val parts = value.split('.')
|
||||
if (parts.size != 4) return null
|
||||
var result = 0L
|
||||
for (part in parts) {
|
||||
val octet = part.toIntOrNull()?.takeIf { it in 0..255 } ?: return null
|
||||
result = (result shl 8) or octet.toLong()
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import android.util.Size
|
||||
import android.view.Gravity
|
||||
import android.view.MotionEvent
|
||||
import android.view.ScaleGestureDetector
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import android.widget.FrameLayout
|
||||
@@ -79,15 +80,17 @@ class MainActivity : ComponentActivity() {
|
||||
@Volatile private var connectedNetwork: Network? = null
|
||||
private var connectedBaseUrl: String? = null
|
||||
private val selectedFiles = mutableListOf<SelectedFile>()
|
||||
private var managingFilesForPair: PairingPayload? = null
|
||||
private var managingFilesForBaseUrl: String? = null
|
||||
private var sendStatusText: TextView? = null
|
||||
private var sendFilesText: TextView? = null
|
||||
private var sendFilesContainer: LinearLayout? = null
|
||||
private var sendAddButton: Button? = null
|
||||
private var sendClearButton: Button? = null
|
||||
private var sendProgress: ProgressBar? = null
|
||||
private var sendButton: Button? = null
|
||||
private var connectingStatusText: TextView? = null
|
||||
private var downloadStatusText: TextView? = null
|
||||
@Volatile private var downloadRunning = false
|
||||
@Volatile private var uploadRunning = false
|
||||
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
|
||||
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
|
||||
@Volatile private var transferAbortReason: String? = null
|
||||
@@ -117,18 +120,16 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||
if (uploadRunning) {
|
||||
sendStatusText?.text = "传输已经开始,当前队列已锁定"
|
||||
return@registerForActivityResult
|
||||
}
|
||||
var unknown = 0
|
||||
for (uri in uris) {
|
||||
val file = UploadClient.describeFile(contentResolver, uri)
|
||||
if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
|
||||
}
|
||||
renderSelectedFiles()
|
||||
val pair = managingFilesForPair
|
||||
val baseUrl = managingFilesForBaseUrl
|
||||
if (pair != null && baseUrl != null) {
|
||||
showFileSelection(pair, baseUrl)
|
||||
return@registerForActivityResult
|
||||
}
|
||||
if (unknown > 0) {
|
||||
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
|
||||
} else if (selectedFiles.isNotEmpty()) {
|
||||
@@ -151,6 +152,7 @@ class MainActivity : ComponentActivity() {
|
||||
stopCamera()
|
||||
scannerMode = ScannerMode.NONE
|
||||
pairConsumed.set(false)
|
||||
wifiConnector.releaseHighPerfLock()
|
||||
wifiConnector.release()
|
||||
pendingPair = null
|
||||
connectedNetwork = null
|
||||
@@ -158,8 +160,14 @@ class MainActivity : ComponentActivity() {
|
||||
downloadRunning = false
|
||||
downloadStatusText = null
|
||||
selectedFiles.clear()
|
||||
managingFilesForPair = null
|
||||
managingFilesForBaseUrl = null
|
||||
uploadRunning = false
|
||||
sendFilesContainer = null
|
||||
sendAddButton = null
|
||||
sendClearButton = null
|
||||
sendFilesText = null
|
||||
sendStatusText = null
|
||||
sendProgress = null
|
||||
sendButton = null
|
||||
|
||||
val root = pageColumn()
|
||||
root.addView(text("QFT", 30f, Color.WHITE, true))
|
||||
@@ -194,7 +202,7 @@ class MainActivity : ComponentActivity() {
|
||||
) { showReceivedFiles() })
|
||||
root.addView(space(22))
|
||||
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
||||
root.addView(text("QFT v0.4.7 · Android 7+ 到最新", 12f, MUTED))
|
||||
root.addView(text("QFT v0.4.16 · Android 7+ 到最新", 12f, MUTED))
|
||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||
}
|
||||
|
||||
@@ -309,10 +317,10 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
currentAnalyzer = analyzer
|
||||
|
||||
// v0.4 single large QR is intentionally analyzed at 640x480. With the
|
||||
// QR occupying most of the view this still leaves several camera
|
||||
// pixels/module, while substantially reducing Y-copy + ZXing work.
|
||||
val targetSize = Size(640, 480)
|
||||
// Pairing QR codes carry network/file metadata and can be much denser
|
||||
// than one optical QFT2 frame. Give PAIR_FAST more sensor pixels per
|
||||
// module; the continuous optical path stays at 640x480 to preserve FPS.
|
||||
val targetSize = if (mode == ScannerMode.PAIR) Size(960, 720) else Size(640, 480)
|
||||
val analysisBuilder = ImageAnalysis.Builder()
|
||||
.setTargetResolution(targetSize)
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
@@ -604,6 +612,14 @@ class MainActivity : ComponentActivity() {
|
||||
private fun connectPair(pair: PairingPayload) {
|
||||
val attempt = ++pairConnectionAttempt
|
||||
transferAbortReason = null
|
||||
connectedBaseUrl = null
|
||||
// 携带 Wi-Fi 身份的 QFT Direct 会无条件先连接那张专用网络。
|
||||
// 不再尝试二维码/电脑当前 LAN 地址;“当前局域网”仍是桌面端用户
|
||||
// 明确选择的独立备用模式(wifi == null)。
|
||||
connectViaWifi(pair, attempt)
|
||||
}
|
||||
|
||||
private fun connectViaWifi(pair: PairingPayload, attempt: Long) {
|
||||
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
|
||||
wifiConnector.connect(
|
||||
pairing = pair,
|
||||
@@ -619,28 +635,79 @@ class MainActivity : ComponentActivity() {
|
||||
if (connectedBaseUrl != null) return@available
|
||||
transferExecutor.execute {
|
||||
if (attempt != pairConnectionAttempt) return@execute
|
||||
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
|
||||
val discovered = UploadClient.discoverUdp(
|
||||
network = network,
|
||||
pairing = pair,
|
||||
hosts = wifiConnector.discoveryHosts(network),
|
||||
val dedicatedWifi = pair.wifi != null
|
||||
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,
|
||||
routedAdvertisedEndpoints = routedEndpoints,
|
||||
)
|
||||
|
||||
// Direct AP 的网关由这次专用连接的 LinkProperties 给出,
|
||||
// 不使用二维码地址,也不猜测 192.168.137/49 网段。
|
||||
runOnUiThread {
|
||||
updateConnectingStatus(
|
||||
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
|
||||
else "UDP 未响应 · 正在并行探测网关与本地 IP…"
|
||||
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证网关和电脑…"
|
||||
else "网络已就绪 · 正在连接同网段电脑…"
|
||||
)
|
||||
}
|
||||
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
|
||||
val subnet = wifiConnector.subnetEndpoints(network, pair.port)
|
||||
if (discovered == null) {
|
||||
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,并刷新路由后再恢复。
|
||||
var discovered: String? = null
|
||||
if (direct == null) {
|
||||
runOnUiThread {
|
||||
updateConnectingStatus("正在并行探测网关;必要时自动扫描当前 QFT 子网…")
|
||||
updateConnectingStatus(
|
||||
if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…"
|
||||
else "同网段地址未应答 · 正在 UDP 快速发现电脑…"
|
||||
)
|
||||
}
|
||||
discovered = UploadClient.discoverUdp(
|
||||
network = network,
|
||||
pairing = pair,
|
||||
hosts = wifiConnector.discoveryHosts(network),
|
||||
deviceName = receiverDeviceLabel,
|
||||
)
|
||||
// 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 找到电脑 · 正在验证接收服务…"
|
||||
else "仅在当前连接的 QFT 子网内并行查找电脑…"
|
||||
)
|
||||
}
|
||||
}
|
||||
val base = UploadClient.probeRobust(
|
||||
|
||||
val base = direct ?: UploadClient.probeRobust(
|
||||
network = network,
|
||||
pairing = pair,
|
||||
pairing = pair.copy(endpoints = routedEndpoints),
|
||||
deviceName = receiverDeviceLabel,
|
||||
preferredEndpoints = gateways,
|
||||
discoveredEndpoint = discovered,
|
||||
@@ -648,8 +715,31 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
runOnUiThread {
|
||||
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||||
// 如果 Wi-Fi 波动后系统已交付了新的 Network,旧探测结果
|
||||
// 不得覆盖新连接或短暂显示失败页。
|
||||
if (connectedNetwork != network) return@runOnUiThread
|
||||
if (base == null) {
|
||||
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
|
||||
// 把手机实际所处的网络写进报错。否则"找不到"这三个字
|
||||
// 无法区分:手机在别的网段?没拿到网关?还是对端真的没开。
|
||||
val diagnosis = buildString {
|
||||
append(
|
||||
if (dedicatedWifi) {
|
||||
"QFT 专用 Wi-Fi 已连接,但在该专用网络的实际网关和子网内未找到服务。\n\n"
|
||||
} else {
|
||||
"Wi-Fi 已连接,但在当前局域网内未找到 QFT 服务。\n\n"
|
||||
}
|
||||
)
|
||||
append("手机侧:").append(wifiConnector.describeNetwork(network)).append("\n")
|
||||
append("连接模式:")
|
||||
append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码/电脑本地网卡地址)" else "当前局域网备用模式")
|
||||
append("\n探测过的网关地址:")
|
||||
append(gateways.joinToString("、").ifEmpty { "(无)" })
|
||||
append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n")
|
||||
append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;")
|
||||
append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;")
|
||||
append("③ 手机是否仍连接二维码内的 QFT 专用网络。")
|
||||
}
|
||||
showPairError(pair, diagnosis)
|
||||
} else {
|
||||
connectedBaseUrl = base
|
||||
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||
@@ -740,12 +830,34 @@ class MainActivity : ComponentActivity() {
|
||||
})
|
||||
root.addView(space(14))
|
||||
root.addView(card().apply {
|
||||
addView(text("选择文件", 17f, Color.WHITE, true))
|
||||
addView(text("传输队列", 17f, Color.WHITE, true))
|
||||
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
|
||||
addView(sendFilesText, matchWrap(top = 8))
|
||||
addView(button("选择文件(可多选)").apply {
|
||||
setOnClickListener { showFileSelection(pair, baseUrl) }
|
||||
}, matchWrap(top = 12))
|
||||
sendFilesContainer = LinearLayout(this@MainActivity).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
}
|
||||
addView(sendFilesContainer, matchWrap(top = 6))
|
||||
val actions = LinearLayout(this@MainActivity).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
}
|
||||
sendAddButton = button("添加文件").apply {
|
||||
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
|
||||
}
|
||||
sendClearButton = button("清空").apply {
|
||||
setOnClickListener {
|
||||
if (!uploadRunning) {
|
||||
selectedFiles.clear()
|
||||
renderSelectedFiles()
|
||||
}
|
||||
}
|
||||
}
|
||||
actions.addView(sendAddButton, LinearLayout.LayoutParams(0, dp(48), 1f).apply {
|
||||
marginEnd = dp(8)
|
||||
})
|
||||
actions.addView(sendClearButton, LinearLayout.LayoutParams(dp(96), dp(48)))
|
||||
addView(actions, matchWrap(top = 12))
|
||||
addView(text("按住“拖动”上下移动可调整发送优先级;传输开始后队列会锁定。", 12f, MUTED), matchWrap(top = 8))
|
||||
})
|
||||
root.addView(space(14))
|
||||
root.addView(card().apply {
|
||||
@@ -755,10 +867,9 @@ class MainActivity : ComponentActivity() {
|
||||
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
|
||||
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
|
||||
sendButton = button("选择传输文件").apply {
|
||||
isEnabled = connectedBaseUrl != null
|
||||
isEnabled = false
|
||||
setOnClickListener {
|
||||
if (selectedFiles.isEmpty()) showFileSelection(pair, baseUrl)
|
||||
else startUploads(pair, baseUrl)
|
||||
startUploads(pair, baseUrl)
|
||||
}
|
||||
}
|
||||
addView(sendButton, matchWrap(top = 14))
|
||||
@@ -800,11 +911,31 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
downloadRunning = true
|
||||
transferAbortReason = null
|
||||
// 传输期间阻止 Wi-Fi 进入省电休眠。Android 默认会在包间隙让
|
||||
// Wi-Fi 芯片休眠,对持续大流量传输会明显压低吞吐。
|
||||
wifiConnector.acquireHighPerfLock()
|
||||
val linkAtStart = wifiConnector.describeLink()
|
||||
transferExecutor.execute {
|
||||
// 「传输 / 校验 / 保存」三个阶段各自的速率含义不同,
|
||||
// 每进入一个新阶段就重新计时,否则显示出来的速率毫无意义。
|
||||
var phaseLabel = "正在接收"
|
||||
// 「传输 / 校验 / 保存」三个阶段各自的速率含义完全不同,混在一起
|
||||
// 平均出来的数字毫无意义。逐段记账,结束后一并列出——
|
||||
// 这样"到底是哪一段慢"一眼就能看出来,不必再靠猜。
|
||||
val phases = java.util.Collections.synchronizedList(
|
||||
mutableListOf<Triple<String, Long, Long>>() // 名称、毫秒、字节
|
||||
)
|
||||
var phaseLabel = "接收"
|
||||
var phaseStartedAt = android.os.SystemClock.elapsedRealtime()
|
||||
// 并行下载的进度回调来自多个 worker 线程(DownloadClient 里
|
||||
// pool.submit 的闭包),普通 var 记账会有竞态,必须用原子变量。
|
||||
val phaseFirstBytes = java.util.concurrent.atomic.AtomicLong(-1L)
|
||||
val phaseLastBytes = java.util.concurrent.atomic.AtomicLong(0L)
|
||||
|
||||
fun closePhase() {
|
||||
val millis = android.os.SystemClock.elapsedRealtime() - phaseStartedAt
|
||||
val first = phaseFirstBytes.get().coerceAtLeast(0L)
|
||||
val bytes = (phaseLastBytes.get() - first).coerceAtLeast(0L)
|
||||
if (millis > 0L && bytes > 0L) phases += Triple(phaseLabel, millis, bytes)
|
||||
}
|
||||
|
||||
try {
|
||||
val saved = DownloadClient.download(
|
||||
context = this@MainActivity,
|
||||
@@ -815,23 +946,49 @@ class MainActivity : ComponentActivity() {
|
||||
deviceName = receiverDeviceLabel,
|
||||
abortReason = { transferAbortReason },
|
||||
onPhase = { label ->
|
||||
phaseLabel = label
|
||||
closePhase()
|
||||
// 去掉文案里的修饰,只留阶段名,汇总表才对得齐
|
||||
phaseLabel = label.removePrefix("正在").removeSuffix("…")
|
||||
.substringBefore("到 ").substringBefore("文件完整性").ifBlank { label }
|
||||
phaseStartedAt = android.os.SystemClock.elapsedRealtime()
|
||||
phaseFirstBytes.set(-1L)
|
||||
phaseLastBytes.set(0L)
|
||||
runOnUiThread { status.text = label }
|
||||
},
|
||||
) { received, expected ->
|
||||
phaseFirstBytes.compareAndSet(-1L, received)
|
||||
phaseLastBytes.set(received)
|
||||
runOnUiThread {
|
||||
val fraction = if (expected <= 0) 0 else ((received * 1000L) / expected).toInt().coerceIn(0, 1000)
|
||||
val elapsed = (android.os.SystemClock.elapsedRealtime() - phaseStartedAt).coerceAtLeast(1L)
|
||||
val rate = received * 1000.0 / elapsed
|
||||
val done = (received - phaseFirstBytes.get().coerceAtLeast(0L)).coerceAtLeast(0L)
|
||||
val rate = done * 1000.0 / elapsed
|
||||
bar.progress = fraction
|
||||
status.text = "$phaseLabel ${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
|
||||
}
|
||||
}
|
||||
closePhase()
|
||||
|
||||
val summary = buildString {
|
||||
append("接收完成:已保存到 Downloads/QFT/").append(saved.name)
|
||||
var totalMillis = 0L
|
||||
for ((label, millis, bytes) in phases) {
|
||||
totalMillis += millis
|
||||
append("\n").append(label).append(" ")
|
||||
append(humanDuration(millis / 1000.0)).append(" · ")
|
||||
append(humanBytes((bytes * 1000.0 / millis).toLong())).append("/s")
|
||||
}
|
||||
if (phases.size > 1 && totalMillis > 0L) {
|
||||
append("\n合计 ").append(humanDuration(totalMillis / 1000.0)).append(" · ")
|
||||
append(humanBytes((saved.size * 1000.0 / totalMillis).toLong())).append("/s")
|
||||
}
|
||||
// 带上链路协商速率:判断"慢"是软件问题还是链路上限的唯一依据
|
||||
append("\n").append(linkAtStart)
|
||||
}
|
||||
runOnUiThread {
|
||||
bar.progress = 1000
|
||||
status.setTextColor(SUCCESS)
|
||||
status.text = "接收完成:已保存到 Downloads/QFT/${saved.name}"
|
||||
status.text = summary
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
runOnUiThread {
|
||||
@@ -842,6 +999,8 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
} finally {
|
||||
downloadRunning = false
|
||||
// 无论成功失败都要释放,否则 Wi-Fi 会一直停留在高功耗模式
|
||||
wifiConnector.releaseHighPerfLock()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -889,95 +1048,128 @@ class MainActivity : ComponentActivity() {
|
||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||
}
|
||||
|
||||
private fun showFileSelection(pair: PairingPayload, baseUrl: String) {
|
||||
managingFilesForPair = pair
|
||||
managingFilesForBaseUrl = baseUrl
|
||||
val root = pageColumn()
|
||||
root.addView(text("选择发送文件", 28f, Color.WHITE, true))
|
||||
root.addView(text("可多次添加文件,并在列表中单独移除。", 14f, MUTED))
|
||||
root.addView(space(14))
|
||||
val total = selectedFiles.sumOf { it.size }
|
||||
root.addView(card().apply {
|
||||
addView(text("已选 ${selectedFiles.size} 个 · ${humanBytes(total)}", 16f, ACCENT, true))
|
||||
if (selectedFiles.isEmpty()) {
|
||||
addView(text("请先选择需要传输的文件", 14f, WARNING), matchWrap(top = 8))
|
||||
} else {
|
||||
selectedFiles.toList().forEach { file ->
|
||||
val row = LinearLayout(this@MainActivity).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
}
|
||||
row.addView(
|
||||
text("${file.name}\n${humanBytes(file.size)}", 14f, Color.WHITE),
|
||||
LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) },
|
||||
)
|
||||
row.addView(button("移除").apply {
|
||||
setOnClickListener {
|
||||
selectedFiles.removeAll { it.uri == file.uri }
|
||||
showFileSelection(pair, baseUrl)
|
||||
}
|
||||
}, LinearLayout.LayoutParams(dp(82), dp(44)))
|
||||
addView(row, matchWrap(top = 10))
|
||||
}
|
||||
}
|
||||
})
|
||||
root.addView(space(14))
|
||||
root.addView(button("添加文件(可多选)").apply {
|
||||
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
|
||||
})
|
||||
if (selectedFiles.isNotEmpty()) {
|
||||
root.addView(space(10))
|
||||
root.addView(button("清空选择").apply {
|
||||
setOnClickListener {
|
||||
selectedFiles.clear()
|
||||
showFileSelection(pair, baseUrl)
|
||||
}
|
||||
})
|
||||
}
|
||||
root.addView(space(10))
|
||||
root.addView(button("完成并返回传输").apply {
|
||||
isEnabled = selectedFiles.isNotEmpty()
|
||||
setOnClickListener {
|
||||
managingFilesForPair = null
|
||||
managingFilesForBaseUrl = null
|
||||
showSendReady(pair, baseUrl)
|
||||
}
|
||||
})
|
||||
root.addView(space(10))
|
||||
root.addView(button("取消并返回传输").apply {
|
||||
setOnClickListener {
|
||||
managingFilesForPair = null
|
||||
managingFilesForBaseUrl = null
|
||||
showSendReady(pair, baseUrl)
|
||||
}
|
||||
})
|
||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||
}
|
||||
|
||||
private fun renderSelectedFiles() {
|
||||
val total = selectedFiles.sumOf { it.size }
|
||||
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
||||
"请先选择需要传输的文件"
|
||||
} else {
|
||||
buildString {
|
||||
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
|
||||
if (selectedFiles.size > 8) append("…另外 ${selectedFiles.size - 8} 个文件\n")
|
||||
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
|
||||
}.trim()
|
||||
"已选 ${selectedFiles.size} 个 · ${humanBytes(total)} · 按列表顺序发送"
|
||||
}
|
||||
sendFilesText?.setTextColor(if (selectedFiles.isEmpty()) WARNING else ACCENT)
|
||||
|
||||
val container = sendFilesContainer
|
||||
container?.removeAllViews()
|
||||
selectedFiles.toList().forEachIndexed { index, file ->
|
||||
val row = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
setPadding(0, dp(4), 0, dp(4))
|
||||
}
|
||||
val drag = button("拖动").apply {
|
||||
isEnabled = !uploadRunning
|
||||
textSize = 12f
|
||||
}
|
||||
row.addView(drag, LinearLayout.LayoutParams(dp(76), dp(44)).apply {
|
||||
marginEnd = dp(8)
|
||||
})
|
||||
row.addView(
|
||||
text("${index + 1}. ${file.name}\n${humanBytes(file.size)}", 14f, Color.WHITE),
|
||||
LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) },
|
||||
)
|
||||
row.addView(button("删除").apply {
|
||||
isEnabled = !uploadRunning
|
||||
textSize = 12f
|
||||
setOnClickListener {
|
||||
if (!uploadRunning) {
|
||||
selectedFiles.removeAll { it.uri == file.uri }
|
||||
renderSelectedFiles()
|
||||
}
|
||||
}
|
||||
}, LinearLayout.LayoutParams(dp(76), dp(44)))
|
||||
container?.addView(row, matchWrap(top = if (index == 0) 2 else 4))
|
||||
if (container != null && !uploadRunning) {
|
||||
installFileQueueDrag(drag, row, file, container)
|
||||
}
|
||||
}
|
||||
|
||||
sendAddButton?.isEnabled = !uploadRunning
|
||||
sendClearButton?.isEnabled = !uploadRunning && selectedFiles.isNotEmpty()
|
||||
sendButton?.text = when {
|
||||
uploadRunning -> "传输中 · 队列已锁定"
|
||||
selectedFiles.isEmpty() -> "请先添加文件"
|
||||
else -> "开始传输 ${selectedFiles.size} 个文件"
|
||||
}
|
||||
sendButton?.isEnabled = connectedBaseUrl != null && selectedFiles.isNotEmpty() && !uploadRunning
|
||||
}
|
||||
|
||||
private fun installFileQueueDrag(
|
||||
handle: View,
|
||||
row: View,
|
||||
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 -> {
|
||||
// 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
|
||||
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
|
||||
}
|
||||
}
|
||||
sendButton?.text = if (selectedFiles.isEmpty()) "选择传输文件" else "开始传输"
|
||||
sendButton?.isEnabled = connectedBaseUrl != null
|
||||
}
|
||||
|
||||
private fun startUploads(pair: PairingPayload, baseUrl: String) {
|
||||
if (uploadRunning) return
|
||||
if (selectedFiles.isEmpty()) {
|
||||
sendStatusText?.setTextColor(WARNING)
|
||||
sendStatusText?.text = "请先选择需要传输的文件"
|
||||
showFileSelection(pair, baseUrl)
|
||||
pickFiles.launch(arrayOf("*/*"))
|
||||
return
|
||||
}
|
||||
val files = selectedFiles.toList()
|
||||
sendButton?.isEnabled = false
|
||||
uploadRunning = true
|
||||
transferAbortReason = null
|
||||
renderSelectedFiles()
|
||||
wifiConnector.acquireHighPerfLock()
|
||||
transferExecutor.execute {
|
||||
try {
|
||||
files.forEachIndexed { index, file ->
|
||||
@@ -1012,12 +1204,16 @@ class MainActivity : ComponentActivity() {
|
||||
runOnUiThread {
|
||||
sendProgress?.progress = 1000
|
||||
sendStatusText?.text = "全部完成 · 已发送 ${files.size} 个文件"
|
||||
sendButton?.isEnabled = true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
runOnUiThread {
|
||||
sendStatusText?.text = "传输失败:${e.message}"
|
||||
sendButton?.isEnabled = true
|
||||
}
|
||||
} finally {
|
||||
wifiConnector.releaseHighPerfLock()
|
||||
runOnUiThread {
|
||||
uploadRunning = false
|
||||
renderSelectedFiles()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,26 +124,29 @@ class QrAnalyzer(
|
||||
return null
|
||||
}
|
||||
|
||||
// Acquisition is center-first, but unlike the old path it establishes
|
||||
// a QR ROI immediately after the first hit. Full-frame work is only a
|
||||
// recovery path for deliberately off-center QR codes.
|
||||
val center = LockRect.centeredSearch(image.width, image.height, 0.82f)
|
||||
// Pairing needs one reliable first hit, not sustained decode FPS. Keep a
|
||||
// generous center crop so a large desktop QR is not clipped at the quiet
|
||||
// zone, and prefer Hybrid thresholding on every frame: it is markedly
|
||||
// more tolerant of monitor glare, PWM bands and uneven exposure.
|
||||
val center = LockRect.centeredSearch(image.width, image.height, 0.92f)
|
||||
val centered = grayBuffer.capture(image, center)
|
||||
decodeDense(centered, hybrid = false)?.let { result ->
|
||||
decodeDense(centered, hybrid = true)?.let { result ->
|
||||
updatePairRegion(result, centered)
|
||||
return result
|
||||
}
|
||||
|
||||
if (frameCounter % 3L == 0L) {
|
||||
decodeDense(centered, hybrid = true)?.let { result ->
|
||||
// Global thresholding remains a cheap fallback for very clean displays,
|
||||
// but no longer delays the robust path until the third camera frame.
|
||||
if (frameCounter % 2L == 0L) {
|
||||
decodeDense(centered, hybrid = false)?.let { result ->
|
||||
updatePairRegion(result, centered)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
if (frameCounter % 4L == 0L) {
|
||||
if (frameCounter % 3L == 0L) {
|
||||
val full = grayBuffer.capture(image)
|
||||
decodeDense(full, hybrid = false)?.let { result ->
|
||||
decodeDense(full, hybrid = true)?.let { result ->
|
||||
updatePairRegion(result, full)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.qft.optical
|
||||
|
||||
/** Move one item while preserving every other item's relative order. */
|
||||
internal fun <T> moveQueueItem(items: MutableList<T>, from: Int, to: Int): Boolean {
|
||||
if (from !in items.indices || to !in items.indices || from == to) return false
|
||||
items.add(to, items.removeAt(from))
|
||||
return true
|
||||
}
|
||||
@@ -30,6 +30,37 @@ data class SelectedFile(
|
||||
val uploadKey: String = UUID.randomUUID().toString(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Wait for completed probes, rather than counting empty queue polls as failed
|
||||
* addresses. This matters immediately after joining QFT Direct: the first ARP
|
||||
* and Windows firewall transition can take longer than a short poll slice even
|
||||
* though the authenticated HTTP request is already reaching the desktop.
|
||||
*/
|
||||
internal fun <T> awaitFirstNonNull(
|
||||
completion: ExecutorCompletionService<T?>,
|
||||
submitted: Int,
|
||||
timeoutMs: Long,
|
||||
): T? {
|
||||
val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs.coerceAtLeast(0L))
|
||||
var completed = 0
|
||||
while (completed < submitted) {
|
||||
val remainingNanos = deadline - System.nanoTime()
|
||||
if (remainingNanos <= 0L) return null
|
||||
val future = completion.poll(remainingNanos, TimeUnit.NANOSECONDS) ?: return null
|
||||
completed += 1
|
||||
try {
|
||||
future.get()?.let { return it }
|
||||
} catch (_: Exception) {
|
||||
// One broken address must not discard successful probes still queued.
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
internal fun directDiscoveryRequest(session: String, deviceName: String): ByteArray =
|
||||
"QFTDISC2:$session:${Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8))}"
|
||||
.toByteArray(Charsets.US_ASCII)
|
||||
|
||||
object UploadClient {
|
||||
private const val TAG = "QftUpload"
|
||||
private const val DISCOVERY_PORT = 39392
|
||||
@@ -69,6 +100,7 @@ object UploadClient {
|
||||
network: Network?,
|
||||
pairing: PairingPayload,
|
||||
hosts: List<InetAddress>,
|
||||
deviceName: String,
|
||||
): String? {
|
||||
if (hosts.isEmpty()) return null
|
||||
val socket = DatagramSocket()
|
||||
@@ -76,7 +108,7 @@ object UploadClient {
|
||||
network?.bindSocket(socket)
|
||||
socket.broadcast = true
|
||||
socket.soTimeout = 160
|
||||
val request = "QFTDISC2:${pairing.session}".toByteArray(Charsets.US_ASCII)
|
||||
val request = directDiscoveryRequest(pairing.session, deviceName)
|
||||
// Two directed/broadcast bursts fit within the initial routing
|
||||
// window while keeping service discovery below 600 ms.
|
||||
repeat(2) {
|
||||
@@ -117,18 +149,49 @@ object UploadClient {
|
||||
discoveredEndpoint: String? = null,
|
||||
subnetEndpoints: List<String> = emptyList(),
|
||||
): String? {
|
||||
val common = listOf(
|
||||
"http://192.168.137.1:${pairing.port}",
|
||||
"http://192.168.49.1:${pairing.port}",
|
||||
val dedicatedWifi = pairing.wifi != null
|
||||
// Direct mode must use only facts obtained from the dedicated Network:
|
||||
// its actual gateway and an authenticated UDP reply. Never inject LAN,
|
||||
// VPN or guessed Windows ICS addresses into this candidate list.
|
||||
val fast = EndpointRouting.forRecovery(
|
||||
dedicatedWifi = dedicatedWifi,
|
||||
discoveredEndpoint = discoveredEndpoint,
|
||||
gatewayEndpoints = preferredEndpoints,
|
||||
advertisedEndpoints = pairing.endpoints,
|
||||
)
|
||||
val fast = (listOfNotNull(discoveredEndpoint) + preferredEndpoints + pairing.endpoints + common)
|
||||
.map { it.trim().removeSuffix("/") }
|
||||
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
||||
.distinct()
|
||||
|
||||
// Stage 1: QR-carried endpoints and actual gateway. This is the normal
|
||||
// path and must complete well inside the 10-second pairing budget.
|
||||
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 1_050
|
||||
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 = 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)
|
||||
?.let { return it }
|
||||
@@ -138,19 +201,14 @@ 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 }
|
||||
}
|
||||
|
||||
// One short final pass covers a just-finished ARP/Windows firewall
|
||||
// transition without adding the former two-second tail latency.
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 500
|
||||
// One final pass covers a route/firewall transition that completed while
|
||||
// the actual connected subnet fallback was running.
|
||||
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 }
|
||||
@@ -159,6 +217,50 @@ object UploadClient {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 在指定网络(`network` 为 null 表示系统默认网络)上并发探测一组地址,
|
||||
* 返回第一个应答的。
|
||||
*
|
||||
* Direct 模式只传入专用网络的实际网关;当前局域网备用模式传入经过
|
||||
* 同网段过滤的二维码地址。调用方必须显式绑定对应的 Network。
|
||||
*/
|
||||
fun probeEndpoints(
|
||||
network: Network?,
|
||||
pairing: PairingPayload,
|
||||
deviceName: String,
|
||||
endpoints: List<String>,
|
||||
connectMs: Int,
|
||||
readMs: Int,
|
||||
): String? = probeCandidatesParallel(
|
||||
network = network,
|
||||
pairing = pairing,
|
||||
deviceName = deviceName,
|
||||
candidates = endpoints,
|
||||
workers = endpoints.size.coerceAtMost(8).coerceAtLeast(1),
|
||||
connectMs = connectMs,
|
||||
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,
|
||||
@@ -179,15 +281,11 @@ object UploadClient {
|
||||
return try {
|
||||
val overallMs = (connectMs + readMs + 150).toLong() *
|
||||
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + overallMs.coerceAtMost(2_400L)
|
||||
repeat(candidates.size) {
|
||||
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
|
||||
if (remaining <= 0) return null
|
||||
val future = completion.poll(remaining.coerceAtMost(350L), TimeUnit.MILLISECONDS) ?: return@repeat
|
||||
val result = future.get()
|
||||
if (result != null) return result
|
||||
}
|
||||
null
|
||||
awaitFirstNonNull(
|
||||
completion = completion,
|
||||
submitted = candidates.size,
|
||||
timeoutMs = overallMs.coerceAtMost(2_400L),
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} finally {
|
||||
|
||||
@@ -20,7 +20,11 @@ import java.net.InetAddress
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
class WifiConnector(context: Context) {
|
||||
private companion object { const val TAG = "QftWifi" }
|
||||
private companion object {
|
||||
const val TAG = "QftWifi"
|
||||
/** 超过这个时长仍未出结果的配网请求视为卡死,重试时不再复用 */
|
||||
const val REUSE_WINDOW_MS = 20_000L
|
||||
}
|
||||
private val appContext = context.applicationContext
|
||||
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
@@ -65,7 +69,13 @@ class WifiConnector(context: Context) {
|
||||
|
||||
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
|
||||
// 千万不要 unregister 再重新 requestNetwork。
|
||||
if (wifi != null && callback != null && pendingSsid == wifi.ssid &&
|
||||
// 复用必须有时间上限。系统偶尔会让一个 WifiNetworkSpecifier 请求
|
||||
// 既不回 onAvailable 也不回 onUnavailable 地一直挂着;若无条件复用,
|
||||
// 用户每次点「重试连接」都只是再等一次那个死掉的请求,表现就是
|
||||
// 「配网越来越慢、几分钟都没反应」。超窗就推倒重来。
|
||||
val reusable = pendingStartedAt > 0L &&
|
||||
SystemClock.elapsedRealtime() - pendingStartedAt < REUSE_WINDOW_MS
|
||||
if (wifi != null && callback != null && pendingSsid == wifi.ssid && reusable &&
|
||||
pendingTerminal?.get() == false) {
|
||||
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
|
||||
listener = Listener(onStatus, onAvailable, onUnavailable)
|
||||
@@ -103,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}")
|
||||
@@ -214,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。若弹窗里一直没出现这个名字," +
|
||||
@@ -306,17 +327,133 @@ class WifiConnector(context: Context) {
|
||||
|
||||
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true
|
||||
|
||||
fun endpointsOnNetwork(network: Network?, endpoints: List<String>, port: Int): List<String> {
|
||||
if (network == null) return emptyList()
|
||||
val links = connectivity.getLinkProperties(network)?.linkAddresses
|
||||
?.mapNotNull { link ->
|
||||
val address = link.address as? Inet4Address ?: return@mapNotNull null
|
||||
val text = address.hostAddress ?: return@mapNotNull null
|
||||
text to link.prefixLength
|
||||
}
|
||||
.orEmpty()
|
||||
return EndpointRouting.onAnySubnet(endpoints, port, links)
|
||||
}
|
||||
|
||||
/**
|
||||
* 传输期间持有的 Wi-Fi 高性能锁。
|
||||
*
|
||||
* Android 默认会让 Wi-Fi 芯片在包间隙进入省电休眠,代价是额外的唤醒
|
||||
* 延迟。对于持续大流量传输,这会明显压低吞吐——这是 Android 上最常见
|
||||
* 也最容易被忽略的一项限速。锁只在传输期间持有,结束立即释放。
|
||||
*/
|
||||
private var transferLock: WifiManager.WifiLock? = null
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
fun acquireHighPerfLock() {
|
||||
if (transferLock != null) return
|
||||
val mode = if (Build.VERSION.SDK_INT >= 29) {
|
||||
WifiManager.WIFI_MODE_FULL_LOW_LATENCY
|
||||
} else {
|
||||
WifiManager.WIFI_MODE_FULL_HIGH_PERF
|
||||
}
|
||||
transferLock = try {
|
||||
wifiManager.createWifiLock(mode, "qft:transfer").apply {
|
||||
setReferenceCounted(false)
|
||||
acquire()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "无法获取 Wi-Fi 高性能锁:${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseHighPerfLock() {
|
||||
try { transferLock?.takeIf { it.isHeld }?.release() } catch (_: Exception) {}
|
||||
transferLock = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前 Wi-Fi 链路的协商速率与信号强度。
|
||||
*
|
||||
* 判断"传输慢"到底是软件问题还是链路本身的上限,这两个数字是唯一
|
||||
* 依据:协商 866 Mbps 却只跑到 136 Mbps 说明有优化空间;
|
||||
* 协商本来就只有 150 Mbps 就已经接近满速,改代码也没用。
|
||||
*/
|
||||
@Suppress("DEPRECATION", "MissingPermission")
|
||||
fun describeLink(): String = try {
|
||||
val info = wifiManager.connectionInfo
|
||||
if (info == null || info.linkSpeed <= 0) {
|
||||
"链路信息不可用"
|
||||
} else {
|
||||
val band = if (Build.VERSION.SDK_INT >= 21 && info.frequency >= 4900) "5GHz" else "2.4GHz"
|
||||
"链路 ${info.linkSpeed} Mbps · $band · 信号 ${info.rssi} dBm"
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
"链路信息读取失败:${e.message}"
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前网络的自述:本机地址/掩码、网关、SSID。
|
||||
*
|
||||
* 「找不到接收服务」是最难远程排查的一类失败——光看这句话,无法区分
|
||||
* 手机在哪个网段、有没有拿到网关、还是对端真的没开。把这些直接写进
|
||||
* 报错里,用户截个图就能定位,不必再来回猜。
|
||||
*/
|
||||
fun describeNetwork(network: Network?): String {
|
||||
if (network == null) return "未绑定到任何网络"
|
||||
val props = connectivity.getLinkProperties(network)
|
||||
?: return "已连接,但系统尚未提供链路信息"
|
||||
val addresses = props.linkAddresses
|
||||
.filter { it.address is Inet4Address }
|
||||
.joinToString("、") { "${it.address.hostAddress}/${it.prefixLength}" }
|
||||
.ifEmpty { "(尚未取得 IPv4)" }
|
||||
val gateways = props.routes
|
||||
.mapNotNull { (it.gateway as? Inet4Address)?.hostAddress }
|
||||
.distinct()
|
||||
.joinToString("、")
|
||||
.ifEmpty { "(无)" }
|
||||
@Suppress("DEPRECATION", "MissingPermission")
|
||||
val ssid = try {
|
||||
normalizeSsid(wifiManager.connectionInfo?.ssid).takeIf { it.isNotBlank() && it != "<unknown ssid>" }
|
||||
} catch (_: Exception) { null } ?: "未知"
|
||||
return "本机 $addresses · 网关 $gateways · Wi-Fi $ssid"
|
||||
}
|
||||
|
||||
fun gatewayEndpoints(network: Network?, port: Int): List<String> {
|
||||
if (network == null) return emptyList()
|
||||
val props = connectivity.getLinkProperties(network) ?: return emptyList()
|
||||
return props.routes
|
||||
.asSequence()
|
||||
.mapNotNull { it.gateway as? Inet4Address }
|
||||
// 默认路由的网关可能是 0.0.0.0(直连链路,无下一跳),
|
||||
// 回环和组播地址也不可能是对端。全都探测一遍纯属浪费时间,
|
||||
// 而且会把真正的候选挤到后面。
|
||||
.filterNot { it.isAnyLocalAddress || it.isLoopbackAddress || it.isMulticastAddress }
|
||||
.map { "http://${it.hostAddress}:$port" }
|
||||
.distinct()
|
||||
.toList()
|
||||
}
|
||||
|
||||
/**
|
||||
* WifiNetworkSpecifier may report IPv4 a few callbacks before DHCP routes
|
||||
* include the group-owner gateway. Wait on the transfer worker for the route
|
||||
* belonging to this exact Network instead of guessing Windows ICS ranges.
|
||||
*/
|
||||
fun awaitGatewayEndpoints(network: Network?, port: Int, timeoutMs: Long): List<String> {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs.coerceAtLeast(0L)
|
||||
do {
|
||||
gatewayEndpoints(network, port).takeIf { it.isNotEmpty() }?.let { return it }
|
||||
if (SystemClock.elapsedRealtime() >= deadline || Thread.currentThread().isInterrupted) break
|
||||
try {
|
||||
Thread.sleep(100)
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
break
|
||||
}
|
||||
} while (true)
|
||||
return gatewayEndpoints(network, port)
|
||||
}
|
||||
|
||||
fun discoveryHosts(network: Network?): List<InetAddress> {
|
||||
val out = mutableListOf<InetAddress>()
|
||||
if (network != null) {
|
||||
|
||||
@@ -4,9 +4,138 @@ import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.concurrent.Callable
|
||||
import java.util.concurrent.ExecutorCompletionService
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.zip.CRC32
|
||||
|
||||
class ProtocolTest {
|
||||
@Test
|
||||
fun directDiscoveryCarriesTheAndroidDeviceName() {
|
||||
val request = directDiscoveryRequest(
|
||||
session = "abcdefghijklmnopqrstuvwxyz012345",
|
||||
deviceName = "HUAWEI CDY-AN90",
|
||||
).toString(Charsets.US_ASCII)
|
||||
val encoded = request.substringAfterLast(':')
|
||||
|
||||
assertTrue(request.startsWith("QFTDISC2:abcdefghijklmnopqrstuvwxyz012345:"))
|
||||
assertEquals("HUAWEI CDY-AN90", Base64Url.decode(encoded)?.toString(Charsets.UTF_8))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dedicatedWifiNeverProbesQrOrComputerLanAddresses() {
|
||||
assertEquals(
|
||||
listOf("http://192.168.137.1:39393"),
|
||||
EndpointRouting.afterConnection(
|
||||
dedicatedWifi = true,
|
||||
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
|
||||
routedAdvertisedEndpoints = listOf(
|
||||
"http://192.168.8.162:39393",
|
||||
"http://192.168.49.1:39393",
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dedicatedWifiRecoveryStillRejectsAdvertisedAndGuessedAddresses() {
|
||||
assertEquals(
|
||||
listOf("http://192.168.137.1:39393"),
|
||||
EndpointRouting.forRecovery(
|
||||
dedicatedWifi = true,
|
||||
discoveredEndpoint = null,
|
||||
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
|
||||
advertisedEndpoints = listOf(
|
||||
"http://192.168.8.162:39393",
|
||||
"http://192.168.49.1:39393",
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun currentLanModeCanUseSameSubnetAdvertisedAddresses() {
|
||||
assertEquals(
|
||||
listOf("http://192.168.8.1:39393", "http://192.168.8.162:39393"),
|
||||
EndpointRouting.afterConnection(
|
||||
dedicatedWifi = false,
|
||||
gatewayEndpoints = listOf("http://192.168.8.1:39393"),
|
||||
routedAdvertisedEndpoints = listOf("http://192.168.8.162:39393"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun probeCompletionWaitsForARealResultInsteadOfConsumingAnEmptyPoll() {
|
||||
val pool = Executors.newSingleThreadExecutor()
|
||||
try {
|
||||
val completion = ExecutorCompletionService<String?>(pool)
|
||||
completion.submit(Callable {
|
||||
Thread.sleep(380)
|
||||
"http://192.168.137.1:39393"
|
||||
})
|
||||
|
||||
assertEquals(
|
||||
"http://192.168.137.1:39393",
|
||||
awaitFirstNonNull(completion, submitted = 1, timeoutMs = 800),
|
||||
)
|
||||
} finally {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun probeCompletionKeepsWaitingAfterAnEarlierAddressFails() {
|
||||
val pool = Executors.newFixedThreadPool(2)
|
||||
try {
|
||||
val completion = ExecutorCompletionService<String?>(pool)
|
||||
completion.submit(Callable { null })
|
||||
completion.submit(Callable {
|
||||
Thread.sleep(30)
|
||||
"http://192.168.137.1:39393"
|
||||
})
|
||||
|
||||
assertEquals(
|
||||
"http://192.168.137.1:39393",
|
||||
awaitFirstNonNull(completion, submitted = 2, timeoutMs = 500),
|
||||
)
|
||||
} finally {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routeCandidatesOnlyKeepEndpointsOnTheActiveSubnet() {
|
||||
val endpoints = listOf(
|
||||
"http://192.168.137.1:39393",
|
||||
"http://192.168.49.1:39393",
|
||||
"http://192.168.1.20:39393",
|
||||
"http://10.20.30.40:39393",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("http://192.168.1.20:39393"),
|
||||
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
||||
)
|
||||
assertEquals(
|
||||
listOf("http://10.20.30.40:39393"),
|
||||
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("10.20.99.2" to 16)),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routeCandidatesRejectWrongPortsAndMalformedAddresses() {
|
||||
val endpoints = listOf(
|
||||
"http://192.168.1.20:39394",
|
||||
"http://192.168.1.999:39393",
|
||||
"http://192.168.1.30:39393",
|
||||
)
|
||||
assertEquals(
|
||||
listOf("http://192.168.1.30:39393"),
|
||||
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parsesPcToPhoneAutomaticDownloadPairing() {
|
||||
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":["http://192.168.49.1:39393"],"d":"d","f":"sample.bin","z":42,"h":"${"00".repeat(32)}"}"""
|
||||
@@ -17,6 +146,18 @@ class ProtocolTest {
|
||||
assertEquals(42L, payload.fileSize)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parsesDedicatedWifiPairingWithoutAdvertisedComputerAddresses() {
|
||||
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":[],"w":["QFT-DESKTOP-abc123","0123456789abcdef"]}"""
|
||||
val payload = PairingProtocol.parse(
|
||||
PairingProtocol.PREFIX_V2 + Base64Url.encode(json.toByteArray()),
|
||||
)!!
|
||||
|
||||
assertNotNull(payload.wifi)
|
||||
assertEquals("QFT-DESKTOP-abc123", payload.wifi?.ssid)
|
||||
assertTrue(payload.endpoints.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun base45KnownVectors() {
|
||||
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.qft.optical
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TransferQueueTest {
|
||||
@Test
|
||||
fun movesFilesInBothDirectionsWithoutLosingItems() {
|
||||
val queue = mutableListOf("A", "B", "C", "D")
|
||||
assertTrue(moveQueueItem(queue, 0, 2))
|
||||
assertEquals(listOf("B", "C", "A", "D"), queue)
|
||||
assertTrue(moveQueueItem(queue, 3, 1))
|
||||
assertEquals(listOf("B", "D", "C", "A"), queue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsInvalidOrNoOpMoves() {
|
||||
val queue = mutableListOf("A", "B")
|
||||
assertFalse(moveQueueItem(queue, -1, 0))
|
||||
assertFalse(moveQueueItem(queue, 0, 2))
|
||||
assertFalse(moveQueueItem(queue, 1, 1))
|
||||
assertEquals(listOf("A", "B"), queue)
|
||||
}
|
||||
}
|
||||
Generated
+1
-1
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qft-desktop"
|
||||
version = "0.4.8"
|
||||
version = "0.4.16"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "qft-desktop"
|
||||
version = "0.4.8"
|
||||
version = "0.4.16"
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
|
||||
@@ -23,6 +23,7 @@ whoami = "1.6"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Devices_Enumeration",
|
||||
"Devices_WiFiDirect",
|
||||
"Security_Credentials",
|
||||
] }
|
||||
|
||||
+123
-9
@@ -7,15 +7,64 @@ use anyhow::Context;
|
||||
use windows::{
|
||||
core::HSTRING,
|
||||
Devices::WiFiDirect::{
|
||||
WiFiDirectAdvertisementPublisher, WiFiDirectAdvertisementPublisherStatus,
|
||||
WiFiDirectAdvertisementListenStateDiscoverability, WiFiDirectAdvertisementPublisher,
|
||||
WiFiDirectAdvertisementPublisherStatus,
|
||||
WiFiDirectAdvertisementPublisherStatusChangedEventArgs, WiFiDirectConnectionListener,
|
||||
WiFiDirectConnectionRequestedEventArgs, WiFiDirectDevice,
|
||||
},
|
||||
Foundation::TypedEventHandler,
|
||||
Security::Credentials::PasswordCredential,
|
||||
};
|
||||
|
||||
#[cfg(windows)]
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[cfg(windows)]
|
||||
fn create_connection_listener(
|
||||
connected_devices: &Arc<Mutex<Vec<WiFiDirectDevice>>>,
|
||||
) -> windows::core::Result<(WiFiDirectConnectionListener, i64)> {
|
||||
let callback_devices = Arc::clone(connected_devices);
|
||||
let listener = WiFiDirectConnectionListener::new()?;
|
||||
let handler = TypedEventHandler::<
|
||||
WiFiDirectConnectionListener,
|
||||
WiFiDirectConnectionRequestedEventArgs,
|
||||
>::new(move |_sender, args| {
|
||||
let request = args.ok()?.GetConnectionRequest()?;
|
||||
let device_id = request.DeviceInformation()?.Id()?;
|
||||
let operation = WiFiDirectDevice::FromIdAsync(&device_id)?;
|
||||
let devices = Arc::clone(&callback_devices);
|
||||
|
||||
// Do not block the WinRT event thread while Windows completes the peer
|
||||
// connection. `join` also keeps the async operation alive until it
|
||||
// yields the device we must retain.
|
||||
std::thread::spawn(move || {
|
||||
if let Ok(device) = operation.join() {
|
||||
if let Ok(mut devices) = devices.lock() {
|
||||
devices.retain(|known| known.DeviceId().ok() != device.DeviceId().ok());
|
||||
devices.push(device);
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
});
|
||||
let token = listener.ConnectionRequested(&handler)?;
|
||||
Ok((listener, token))
|
||||
}
|
||||
|
||||
pub struct DirectAp {
|
||||
pub ssid: String,
|
||||
#[cfg(windows)]
|
||||
publisher: WiFiDirectAdvertisementPublisher,
|
||||
/// Legacy AP 只负责让普通 Wi-Fi 客户端关联和取得 DHCP 地址;Windows
|
||||
/// 还要求应用接受 Wi-Fi Direct connection request,数据通道才会真正建立。
|
||||
#[cfg(windows)]
|
||||
connection_listener: WiFiDirectConnectionListener,
|
||||
#[cfg(windows)]
|
||||
connection_requested_token: i64,
|
||||
/// 必须长期持有 `WiFiDirectDevice`。对象一旦被释放,Windows 会拆掉该
|
||||
/// peer 的 Wi-Fi Direct 会话,表现为手机仍连着 SSID、却访问不到网关端口。
|
||||
#[cfg(windows)]
|
||||
connected_devices: Arc<Mutex<Vec<WiFiDirectDevice>>>,
|
||||
}
|
||||
|
||||
impl DirectAp {
|
||||
@@ -32,6 +81,16 @@ impl DirectAp {
|
||||
.context("创建 Wi-Fi Direct publisher 失败")?;
|
||||
let ad = publisher.Advertisement()
|
||||
.context("读取 Wi-Fi Direct advertisement 失败")?;
|
||||
// WinRT defaults this property to `None`, which still lets the
|
||||
// publisher report `Started` but does not make the AP discoverable.
|
||||
// Android then waits in the system Wi-Fi picker until it times out,
|
||||
// exactly as if the hotspot had never been started. Intensive keeps
|
||||
// the legacy SSID discoverable even when the desktop window is not
|
||||
// foregrounded during the phone-side connection flow.
|
||||
ad.SetListenStateDiscoverability(
|
||||
WiFiDirectAdvertisementListenStateDiscoverability::Intensive,
|
||||
)
|
||||
.context("启用 QFT Wi-Fi Direct 可发现性失败")?;
|
||||
ad.SetIsAutonomousGroupOwnerEnabled(true)
|
||||
.context("启用 Autonomous Group Owner 失败")?;
|
||||
let legacy = ad.LegacySettings()
|
||||
@@ -47,27 +106,74 @@ impl DirectAp {
|
||||
legacy.SetPassphrase(&credential)
|
||||
.context("应用 QFT 热点密码失败")?;
|
||||
|
||||
// Follow Microsoft's Legacy AP lifecycle exactly: install the
|
||||
// connection listener from the publisher's Started callback. QFT
|
||||
// keeps a stable SSID/password, so Android can auto-reassociate as
|
||||
// soon as the AP appears; polling first and adding the listener
|
||||
// afterwards can miss that one connection request.
|
||||
type ListenerResult = std::result::Result<
|
||||
(WiFiDirectConnectionListener, i64),
|
||||
String,
|
||||
>;
|
||||
let connected_devices = Arc::new(Mutex::new(Vec::<WiFiDirectDevice>::new()));
|
||||
let listener_state = Arc::new(Mutex::new(None::<ListenerResult>));
|
||||
let callback_devices = Arc::clone(&connected_devices);
|
||||
let callback_state = Arc::clone(&listener_state);
|
||||
let status_handler = TypedEventHandler::<
|
||||
WiFiDirectAdvertisementPublisher,
|
||||
WiFiDirectAdvertisementPublisherStatusChangedEventArgs,
|
||||
>::new(move |_sender, args| {
|
||||
if args.ok()?.Status()? == WiFiDirectAdvertisementPublisherStatus::Started {
|
||||
let result = create_connection_listener(&callback_devices)
|
||||
.map_err(|error| error.to_string());
|
||||
if let Ok(mut state) = callback_state.lock() {
|
||||
if state.is_none() {
|
||||
*state = Some(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
let status_token = publisher
|
||||
.StatusChanged(&status_handler)
|
||||
.context("监听 Wi-Fi Direct AP 启动状态失败")?;
|
||||
|
||||
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;
|
||||
let (connection_listener, connection_requested_token) = loop {
|
||||
if let Ok(mut state) = listener_state.lock() {
|
||||
if let Some(result) = state.take() {
|
||||
break result.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
}
|
||||
let status = publisher.Status().context("读取 AP 状态失败")?;
|
||||
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 移动热点后重试。")
|
||||
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);
|
||||
|
||||
Ok(Self { ssid, publisher })
|
||||
// This is not optional bookkeeping. Microsoft's Legacy AP sample
|
||||
// creates the connection listener after the publisher reaches
|
||||
// Started, accepts each request with FromIdAsync, and retains the
|
||||
// resulting WiFiDirectDevice. Without these steps Android still
|
||||
// associates and receives 192.168.137.x via DHCP, but TCP/UDP to
|
||||
// 192.168.137.1 never reaches the desktop process.
|
||||
Ok(Self {
|
||||
ssid,
|
||||
publisher,
|
||||
connection_listener,
|
||||
connection_requested_token,
|
||||
connected_devices,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,6 +182,14 @@ impl Drop for DirectAp {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = self
|
||||
.connection_listener
|
||||
.RemoveConnectionRequested(self.connection_requested_token);
|
||||
if let Ok(mut devices) = self.connected_devices.lock() {
|
||||
for device in devices.drain(..) {
|
||||
let _ = device.Close();
|
||||
}
|
||||
}
|
||||
let _ = self.publisher.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
+505
-47
@@ -6,10 +6,11 @@
|
||||
//!
|
||||
//! 三条设计约束:
|
||||
//! 1. **只在确实缺规则时申请**。每次启动都弹 UAC 是骚扰。
|
||||
//! 2. **被拒绝就记住**。写一个标记文件,之后只在界面上留一个手动按钮,
|
||||
//! 不再自动弹窗。
|
||||
//! 3. **规则尽量窄**。只放行本程序这一个可执行文件,绝不整体关闭防火墙。
|
||||
//! 但**不能按网络配置文件收窄**——见下方 `grant()` 里的说明。
|
||||
//! 2. **没有放行就不宣称 Direct 已就绪**。用户明确点击“启动直传/接收”时,
|
||||
//! 可以走一次标准 UAC;拒绝或复检失败就停止启动,不生成不可用二维码。
|
||||
//! 3. **规则尽量窄**。程序规则之外只开放 QFT 固定的 TCP/UDP 两个端口,
|
||||
//! 绝不整体关闭防火墙;但**不能按网络配置文件收窄**——见下方
|
||||
//! `grant()` 里的说明。
|
||||
//!
|
||||
//! 提权本身由操作系统的标准机制完成(Windows 的 UAC、macOS 的
|
||||
//! 授权对话框),程序不接触也不存储任何凭据。
|
||||
@@ -21,6 +22,14 @@ use std::path::PathBuf;
|
||||
// 仅 Windows 分支使用;其余平台整段被 cfg 编译掉
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
pub const RULE_NAME: &str = "QFT Desktop";
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
const DIRECT_TCP_RULE: &str = "QFT-Desktop-Direct-TCP-v2";
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
const DIRECT_UDP_RULE: &str = "QFT-Desktop-Direct-UDP-v2";
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
const DIRECT_TCP_PORT: u16 = 39393;
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
const DIRECT_UDP_PORT: u16 = 39392;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum FirewallStatus {
|
||||
@@ -28,6 +37,20 @@ pub enum FirewallStatus {
|
||||
Allowed,
|
||||
/// 缺少放行规则,入站很可能被拦
|
||||
Missing,
|
||||
/// 规则本身没问题,但系统层面的策略让任何放行规则都不生效。
|
||||
///
|
||||
/// 对应 Windows 的「阻止所有传入连接,包括位于允许应用列表中的应用」
|
||||
/// (`BlockInboundAlways`)。这一项打开时,用户点多少次「放行防火墙」
|
||||
/// 都不会有任何变化——必须先把它关掉,所以要单独报出来。
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
BlockedByPolicy(String),
|
||||
/// 存在针对本程序的「阻止」入站规则,压过了我们的放行规则。
|
||||
///
|
||||
/// 通常是用户在 Windows「安全警报」弹窗上点了取消后系统自动建的,
|
||||
/// 规则名是程序名而非 `QFT Desktop`。这一类提权后可以自动清掉,
|
||||
/// 所以和 [`BlockedByPolicy`](Self::BlockedByPolicy) 分开表示。
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
BlockedByRule(String),
|
||||
/// 查不出来(命令不可用、输出无法解析等),不要据此吓唬用户
|
||||
Unknown(String),
|
||||
/// 本平台不做自动放行(目前只有 Linux 会返回)
|
||||
@@ -37,7 +60,32 @@ pub enum FirewallStatus {
|
||||
|
||||
impl FirewallStatus {
|
||||
pub fn needs_action(&self) -> bool {
|
||||
matches!(self, Self::Missing)
|
||||
matches!(
|
||||
self,
|
||||
Self::Missing | Self::BlockedByPolicy(_) | Self::BlockedByRule(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// 提权后加/删规则能否解决。
|
||||
///
|
||||
/// `BlockedByPolicy` 是系统级开关,我们不去动它——那属于用户的安全设置,
|
||||
/// 只做提示,由用户自己决定是否关闭。
|
||||
pub fn fixable_by_grant(&self) -> bool {
|
||||
matches!(self, Self::Missing | Self::BlockedByRule(_))
|
||||
}
|
||||
|
||||
/// 给界面用的一句话说明。
|
||||
pub fn detail(&self) -> String {
|
||||
match self {
|
||||
Self::Allowed => "入站已放行".into(),
|
||||
Self::Missing => "缺少放行规则,手机可能连不上".into(),
|
||||
Self::BlockedByPolicy(reason) | Self::Unknown(reason) => reason.clone(),
|
||||
Self::BlockedByRule(names) => format!(
|
||||
"存在阻止本程序入站的规则({names}),它的优先级高于放行规则。\
|
||||
点「放行防火墙」会连同这些阻止规则一起清掉。"
|
||||
),
|
||||
Self::Unsupported(reason) => (*reason).to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,37 +95,196 @@ fn current_exe() -> Result<PathBuf> {
|
||||
|
||||
// ---------------------------------------------------------------- Windows
|
||||
|
||||
/// 探测脚本。刻意用 PowerShell 而不是 netsh:
|
||||
///
|
||||
/// `netsh advfirewall show` 的**值**也会跟随系统语言本地化(中文 Windows 上
|
||||
/// 是「允许 / 阻止 / 任何 / 是」),按英文关键字匹配在中文系统上必然误判;
|
||||
/// 而 `Get-NetFirewallRule` 返回的是枚举,`Allow`/`Block`/`Any`/`True`
|
||||
/// 在任何语言下都是这几个字面量。
|
||||
///
|
||||
/// 输出被压成一行一条的管道分隔记录,便于用纯函数解析、也便于在非 Windows
|
||||
/// 上对解析逻辑写测试。
|
||||
/// 注意查询是**按程序路径**做的,不是只按规则显示名。
|
||||
///
|
||||
/// 用户在 Windows 弹出「安全警报」时点了「取消」,系统会自己建一条针对该
|
||||
/// 可执行文件的**阻止**规则,名字是程序名而不是我们的 `QFT Desktop`。
|
||||
/// 只按显示名查完全看不到它,却又是它压着我们的放行规则——
|
||||
/// 表现就是「点了放行、界面显示已放行,手机依然连不上」。
|
||||
fn probe_script(exe: &str) -> String {
|
||||
format!(
|
||||
r#"
|
||||
$ErrorActionPreference='SilentlyContinue'
|
||||
$exe = '{exe}'
|
||||
Get-NetFirewallProfile | ForEach-Object {{
|
||||
"PROFILE|$($_.Name)|$($_.Enabled)|$($_.DefaultInboundAction)|$($_.AllowInboundRules)"
|
||||
}}
|
||||
# 只查询当前 exe 路径。同名旧规则可能属于上一次构建目录;把它算成有效
|
||||
# 会让界面显示绿色,但当前 qft-desktop.exe 的入站仍被全部拦截。
|
||||
Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Sort-Object -Property Name -Unique | ForEach-Object {{
|
||||
"RULE|$($_.Enabled)|$($_.Direction)|$($_.Action)|$($_.Profile)|$($_.DisplayName)"
|
||||
}}
|
||||
Get-NetFirewallRule -Name '{DIRECT_TCP_RULE}','{DIRECT_UDP_RULE}' | ForEach-Object {{
|
||||
$rule = $_
|
||||
$filter = $rule | Get-NetFirewallPortFilter
|
||||
"PORT|$($rule.Enabled)|$($rule.Direction)|$($rule.Action)|$($rule.Profile)|$($filter.Protocol)|$($filter.LocalPort)|$($rule.Name)"
|
||||
}}
|
||||
"#,
|
||||
// PowerShell 单引号字符串里只需把单引号写成两个,反斜杠不转义,
|
||||
// 正好适合 Windows 路径
|
||||
exe = exe.replace('\'', "''"),
|
||||
)
|
||||
}
|
||||
|
||||
/// 解析 [`PROBE_SCRIPT`] 的输出。放在这里而不是内联,是为了能在任意平台
|
||||
/// 上用真实样本做测试——Windows 专有逻辑最容易腐烂在没人跑的地方。
|
||||
///
|
||||
/// 判定顺序是有讲究的:
|
||||
/// 1. **先看系统级策略**。`AllowInboundRules=False` 对应「阻止所有传入连接,
|
||||
/// 包括位于允许应用列表中的应用」。这项打开时用户点多少次放行都没有
|
||||
/// 任何变化,必须先报出来,否则会得出「规则已就绪」的错误结论。
|
||||
/// 2. **再看有没有阻止规则**。Windows 里 Block 永远压过 Allow,旧版本残留
|
||||
/// 的阻止规则会让新加的放行规则彻底失效,而界面上两条都显示「已启用」。
|
||||
/// 3. **最后才看放行规则**,且必须是 `Any` profile——手机连的那块 Direct AP
|
||||
/// 虚拟网卡会被判为「公用网络」,只覆盖专用/域的规则在它上面不适用。
|
||||
pub fn classify_probe(probe_output: &str) -> FirewallStatus {
|
||||
let mut any_firewall_on = false;
|
||||
let mut blanket_block: Vec<&str> = Vec::new();
|
||||
let mut has_block_rule = false;
|
||||
let mut blocking_rules: Vec<&str> = Vec::new();
|
||||
let mut has_usable_allow = false;
|
||||
let mut has_direct_tcp = false;
|
||||
let mut has_direct_udp = false;
|
||||
|
||||
for line in probe_output.lines() {
|
||||
let fields: Vec<&str> = line.trim().split('|').collect();
|
||||
match fields.as_slice() {
|
||||
["PROFILE", name, enabled, _default_inbound, allow_inbound] => {
|
||||
let on = enabled.eq_ignore_ascii_case("true");
|
||||
any_firewall_on |= on;
|
||||
// AllowInboundRules 还可能是 NotConfigured,那不算封禁
|
||||
if on && allow_inbound.eq_ignore_ascii_case("false") {
|
||||
blanket_block.push(name);
|
||||
}
|
||||
}
|
||||
["RULE", enabled, direction, action, profile, display_name] => {
|
||||
if !direction.eq_ignore_ascii_case("inbound") {
|
||||
continue;
|
||||
}
|
||||
// 只有启用中的阻止规则才真正生效
|
||||
if action.eq_ignore_ascii_case("block") && enabled.eq_ignore_ascii_case("true") {
|
||||
has_block_rule = true;
|
||||
blocking_rules.push(*display_name);
|
||||
} else if enabled.eq_ignore_ascii_case("true")
|
||||
&& action.eq_ignore_ascii_case("allow")
|
||||
&& profile.eq_ignore_ascii_case("any")
|
||||
{
|
||||
has_usable_allow = true;
|
||||
}
|
||||
}
|
||||
["PORT", enabled, direction, action, profile, protocol, local_port, _name] => {
|
||||
let usable = enabled.eq_ignore_ascii_case("true")
|
||||
&& direction.eq_ignore_ascii_case("inbound")
|
||||
&& action.eq_ignore_ascii_case("allow")
|
||||
&& profile.eq_ignore_ascii_case("any");
|
||||
let port = local_port.parse::<u16>().ok();
|
||||
if usable
|
||||
&& (protocol.eq_ignore_ascii_case("tcp") || *protocol == "6")
|
||||
&& port == Some(DIRECT_TCP_PORT)
|
||||
{
|
||||
has_direct_tcp = true;
|
||||
}
|
||||
if usable
|
||||
&& (protocol.eq_ignore_ascii_case("udp") || *protocol == "17")
|
||||
&& port == Some(DIRECT_UDP_PORT)
|
||||
{
|
||||
has_direct_udp = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if !blanket_block.is_empty() {
|
||||
return FirewallStatus::BlockedByPolicy(format!(
|
||||
"{} 配置文件启用了「阻止所有传入连接,包括位于允许应用列表中的应用」。\
|
||||
这一项打开时,放行规则不起任何作用,必须先在\
|
||||
「Windows 安全中心 → 防火墙和网络保护」里把它关掉。",
|
||||
blanket_block.join("、")
|
||||
));
|
||||
}
|
||||
if has_block_rule {
|
||||
// 这类规则多半是用户在「安全警报」弹窗上点了取消后由系统自动建的,
|
||||
// 名字五花八门,所以把实际名字列出来,用户手动排查时才有的放矢。
|
||||
return FirewallStatus::BlockedByRule(blocking_rules.join("、"));
|
||||
}
|
||||
// 防火墙整个关着时入站不会被拦,没必要要求存在规则
|
||||
if !any_firewall_on || (has_usable_allow && has_direct_tcp && has_direct_udp) {
|
||||
FirewallStatus::Allowed
|
||||
} else {
|
||||
FirewallStatus::Missing
|
||||
}
|
||||
}
|
||||
|
||||
/// 生成提权后要执行的放行脚本。
|
||||
///
|
||||
/// 不加 `#[cfg]`,好让脚本文本在任何平台上都能被测试——这段脚本上一版
|
||||
/// 里混进了一个 `\` 续行(bash 语法,PowerShell 用反引号 `),
|
||||
/// 结果脚本在用户机器上直接语法错误,而外层 `Start-Process -Wait` 返回的
|
||||
/// 是启动器的退出码,程序还以为放行成功了。所以现在:
|
||||
/// **一条命令占一行,绝不使用任何续行**,并且由脚本自己写一个成功标记,
|
||||
/// 让调用方能验证它是真的跑完了。
|
||||
fn grant_script(exe: &str, marker: &str) -> String {
|
||||
let exe = exe.replace('\'', "''");
|
||||
let marker = marker.replace('\'', "''");
|
||||
format!(
|
||||
"$ErrorActionPreference = 'Stop'\r\n\
|
||||
$exe = '{exe}'\r\n\
|
||||
$marker = '{marker}'\r\n\
|
||||
# 先清掉一切针对本程序的入站阻止规则。Windows 在用户点掉「安全警报」\r\n\
|
||||
# 弹窗时会自动建这种规则,名字是程序名,且优先级高于任何放行规则。\r\n\
|
||||
$blocking = Get-NetFirewallApplicationFilter -Program $exe -ErrorAction SilentlyContinue | Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }}\r\n\
|
||||
if ($blocking) {{ $blocking | Remove-NetFirewallRule -ErrorAction SilentlyContinue }}\r\n\
|
||||
# 重建放行规则。Profile Any 是刻意的:Windows 把没见过的网络\r\n\
|
||||
# (尤其是 Direct AP 虚拟网卡)默认归为公用网络。\r\n\
|
||||
Remove-NetFirewallRule -DisplayName '{RULE_NAME}' -ErrorAction SilentlyContinue\r\n\
|
||||
New-NetFirewallRule -DisplayName '{RULE_NAME}' -Direction Inbound -Program $exe -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
|
||||
# 两条窄端口规则不依赖 exe 路径字符串的 WFP 归一化结果,专门兜住\r\n\
|
||||
# Wi-Fi Direct 虚拟网卡上的 TCP/UDP 数据通道。\r\n\
|
||||
Remove-NetFirewallRule -Name '{DIRECT_TCP_RULE}','{DIRECT_UDP_RULE}' -ErrorAction SilentlyContinue\r\n\
|
||||
New-NetFirewallRule -Name '{DIRECT_TCP_RULE}' -DisplayName 'QFT Direct TCP' -Direction Inbound -Protocol TCP -LocalPort {DIRECT_TCP_PORT} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
|
||||
New-NetFirewallRule -Name '{DIRECT_UDP_RULE}' -DisplayName 'QFT Direct UDP' -Direction Inbound -Protocol UDP -LocalPort {DIRECT_UDP_PORT} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
|
||||
# 只有真的建成了才写标记,调用方据此判断成败\r\n\
|
||||
Set-Content -Path $marker -Value 'ok' -Encoding ASCII\r\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn status() -> FirewallStatus {
|
||||
fn run_powershell(script: &str) -> std::io::Result<std::process::Output> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
|
||||
let output = std::process::Command::new("netsh")
|
||||
.args([
|
||||
"advfirewall",
|
||||
"firewall",
|
||||
"show",
|
||||
"rule",
|
||||
&format!("name={RULE_NAME}"),
|
||||
])
|
||||
std::process::Command::new("powershell")
|
||||
.args(["-NoProfile", "-NonInteractive", "-Command", script])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output();
|
||||
.output()
|
||||
}
|
||||
|
||||
match output {
|
||||
Ok(out) if out.status.success() => {
|
||||
// 光有同名规则还不够:规则若绑在不适用于当前网络的 profile 上,
|
||||
// 会出现「显示已启用但照样被拦」。所以要求它是 profile=any。
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn status() -> FirewallStatus {
|
||||
let exe = match current_exe() {
|
||||
Ok(path) => path.display().to_string(),
|
||||
Err(e) => return FirewallStatus::Unknown(format!("{e}")),
|
||||
};
|
||||
match run_powershell(&probe_script(&exe)) {
|
||||
Ok(out) => {
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let any_profile = text.contains("Any") || text.contains("任何");
|
||||
if any_profile {
|
||||
FirewallStatus::Allowed
|
||||
} else {
|
||||
FirewallStatus::Missing
|
||||
if text.trim().is_empty() {
|
||||
return FirewallStatus::Unknown(
|
||||
"防火墙查询没有返回任何内容,可能是 PowerShell 执行策略受限".into(),
|
||||
);
|
||||
}
|
||||
classify_probe(&text)
|
||||
}
|
||||
// netsh 在找不到规则时退出码非 0
|
||||
Ok(_) => FirewallStatus::Missing,
|
||||
Err(e) => FirewallStatus::Unknown(format!("无法执行 netsh:{e}")),
|
||||
Err(e) => FirewallStatus::Unknown(format!("无法执行 PowerShell:{e}")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,15 +305,19 @@ pub fn grant() -> Result<()> {
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
|
||||
let exe = current_exe()?;
|
||||
let script = std::env::temp_dir().join(format!("qft-firewall-{}.bat", std::process::id()));
|
||||
let content = format!(
|
||||
"@echo off\r\n\
|
||||
netsh advfirewall firewall delete rule name=\"{RULE_NAME}\" >nul 2>&1\r\n\
|
||||
netsh advfirewall firewall add rule name=\"{RULE_NAME}\" dir=in action=allow \
|
||||
program=\"{}\" enable=yes profile=any\r\n",
|
||||
exe.display()
|
||||
);
|
||||
std::fs::write(&script, content).context("写入临时放行脚本失败")?;
|
||||
let temp = std::env::temp_dir();
|
||||
let pid = std::process::id();
|
||||
// 写成 .ps1 文件而不是把命令塞进 -ArgumentList:程序路径里带空格时,
|
||||
// 经过 PowerShell 再到子进程会被重新分词,引号层层嵌套极易出错。
|
||||
// 脚本文件里的单引号字符串不会被二次解析。
|
||||
let script = temp.join(format!("qft-firewall-{pid}.ps1"));
|
||||
let marker = temp.join(format!("qft-firewall-{pid}.ok"));
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
std::fs::write(
|
||||
&script,
|
||||
grant_script(&exe.display().to_string(), &marker.display().to_string()),
|
||||
)
|
||||
.context("写入临时放行脚本失败")?;
|
||||
|
||||
let status = std::process::Command::new("powershell")
|
||||
.args([
|
||||
@@ -115,7 +326,7 @@ pub fn grant() -> Result<()> {
|
||||
"Hidden",
|
||||
"-Command",
|
||||
&format!(
|
||||
"Start-Process -FilePath cmd -ArgumentList '/c','\"{}\"' -Verb RunAs -WindowStyle Hidden -Wait",
|
||||
"Start-Process -FilePath powershell -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','\"{}\"' -Verb RunAs -WindowStyle Hidden -Wait",
|
||||
script.display()
|
||||
),
|
||||
])
|
||||
@@ -123,9 +334,18 @@ pub fn grant() -> Result<()> {
|
||||
.status();
|
||||
|
||||
let _ = std::fs::remove_file(&script);
|
||||
// 外层退出码只能说明「UAC 弹窗流程本身」没出错,说明不了脚本跑没跑通:
|
||||
// Start-Process -Wait 返回的是启动器的退出码,不是被提权进程的。
|
||||
// 上一版就是因此把一个语法错误的脚本误报成了放行成功。
|
||||
let succeeded = marker.exists();
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
match status {
|
||||
// 用户在 UAC 上点了「否」时 Start-Process 会失败,退出码非 0
|
||||
Ok(s) if s.success() => Ok(()),
|
||||
Ok(s) if s.success() && succeeded => Ok(()),
|
||||
Ok(s) if s.success() => bail!(
|
||||
"提权成功但放行脚本没有跑完,规则未生效。请点「复制手动放行命令」,\
|
||||
在管理员 PowerShell 里执行并把报错发出来"
|
||||
),
|
||||
Ok(_) => bail!("未获得管理员授权,防火墙规则没有添加"),
|
||||
Err(e) => bail!("调用提权失败:{e}"),
|
||||
}
|
||||
@@ -222,11 +442,32 @@ pub fn manual_instructions(port: u16) -> String {
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// -Profile Any 是必须的。这里早先写的是 Private,Domain,与本模块
|
||||
// grant() 的注释自相矛盾,照抄的用户会重建出一条在公用网络上
|
||||
// (也就是 Direct AP 虚拟网卡上)根本不适用的规则。
|
||||
// 剪贴板里**只放命令**,不放任何说明文字。用户是整段粘进 PowerShell 的,
|
||||
// 混在里面的中文散文会被当成 cmdlet 名逐行报错,把真正的报错淹没掉。
|
||||
// 同理绝不使用 `\` 续行——那是 bash 语法,PowerShell 用反引号;
|
||||
// 一条命令就写一行,宁可长。
|
||||
format!(
|
||||
"以管理员身份打开 PowerShell,执行:\n\n\
|
||||
New-NetFirewallRule -DisplayName \"{RULE_NAME}\" -Direction Inbound \\\n\
|
||||
\x20 -Program \"{exe}\" -Action Allow -Profile Private,Domain\n\n\
|
||||
或在「允许应用通过 Windows Defender 防火墙」里勾选该程序的专用网络。"
|
||||
concat!(
|
||||
"# 在管理员 PowerShell 中整段粘贴执行\n",
|
||||
"$exe = \"{exe}\"\n",
|
||||
"Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} | Remove-NetFirewallRule\n",
|
||||
"Remove-NetFirewallRule -DisplayName \"{RULE_NAME}\" -ErrorAction SilentlyContinue\n",
|
||||
"New-NetFirewallRule -DisplayName \"{RULE_NAME}\" -Direction Inbound -Program $exe -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
|
||||
"Remove-NetFirewallRule -Name \"{DIRECT_TCP_RULE}\",\"{DIRECT_UDP_RULE}\" -ErrorAction SilentlyContinue\n",
|
||||
"New-NetFirewallRule -Name \"{DIRECT_TCP_RULE}\" -DisplayName \"QFT Direct TCP\" -Direction Inbound -Protocol TCP -LocalPort {port} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
|
||||
"New-NetFirewallRule -Name \"{DIRECT_UDP_RULE}\" -DisplayName \"QFT Direct UDP\" -Direction Inbound -Protocol UDP -LocalPort {udp_port} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
|
||||
"Get-NetFirewallProfile | Select-Object Name,Enabled,AllowInboundRules\n",
|
||||
"Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Select-Object DisplayName,Enabled,Direction,Action,Profile\n",
|
||||
),
|
||||
exe = exe,
|
||||
RULE_NAME = RULE_NAME,
|
||||
DIRECT_TCP_RULE = DIRECT_TCP_RULE,
|
||||
DIRECT_UDP_RULE = DIRECT_UDP_RULE,
|
||||
port = port,
|
||||
udp_port = port.saturating_sub(1),
|
||||
)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -263,12 +504,21 @@ mod tests {
|
||||
FirewallStatus::Allowed
|
||||
| FirewallStatus::Missing
|
||||
| FirewallStatus::Unsupported(_) => {}
|
||||
FirewallStatus::Unknown(reason) => assert!(!reason.is_empty(), "未知原因不能为空"),
|
||||
FirewallStatus::Unknown(reason)
|
||||
| FirewallStatus::BlockedByPolicy(reason)
|
||||
| FirewallStatus::BlockedByRule(reason) => {
|
||||
assert!(!reason.is_empty(), "原因说明不能为空")
|
||||
}
|
||||
}
|
||||
// 只有 Missing 才该触发后续动作
|
||||
// Allowed / Unknown / Unsupported 都不该催促用户去点按钮
|
||||
assert_eq!(
|
||||
value.needs_action(),
|
||||
matches!(value, FirewallStatus::Missing)
|
||||
matches!(
|
||||
value,
|
||||
FirewallStatus::Missing
|
||||
| FirewallStatus::BlockedByPolicy(_)
|
||||
| FirewallStatus::BlockedByRule(_)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -283,10 +533,218 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// 探测脚本的输出形状是固定的,解析逻辑在任何平台上都能测。
|
||||
// Windows 专有代码最容易腐烂在没人跑的地方,这几个用例就是防这个的。
|
||||
const PROFILES_OK: &str = "PROFILE|Domain|True|Block|True\n\
|
||||
PROFILE|Private|True|Block|True\n\
|
||||
PROFILE|Public|True|Block|True";
|
||||
const DIRECT_PORTS_OK: &str = "PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
|
||||
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
|
||||
|
||||
#[test]
|
||||
fn allow_rule_must_cover_any_profile() {
|
||||
let only_private = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Domain, Private|QFT Desktop");
|
||||
assert_eq!(classify_probe(&only_private), FirewallStatus::Missing);
|
||||
|
||||
let any = format!(
|
||||
"{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop\n{DIRECT_PORTS_OK}"
|
||||
);
|
||||
assert_eq!(classify_probe(&any), FirewallStatus::Allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_allow_rule_does_not_count() {
|
||||
let text = format!("{PROFILES_OK}\nRULE|False|Inbound|Allow|Any|QFT Desktop");
|
||||
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_program_rule_without_direct_ports_is_migrated() {
|
||||
let old = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop");
|
||||
assert_eq!(classify_probe(&old), FirewallStatus::Missing);
|
||||
|
||||
let only_tcp = format!("{old}\n{}", DIRECT_PORTS_OK.lines().next().unwrap());
|
||||
assert_eq!(classify_probe(&only_tcp), FirewallStatus::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outbound_rules_are_irrelevant() {
|
||||
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Allow|Any|QFT Desktop");
|
||||
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||||
// 出站的阻止规则同样不该被误判成入站被拦
|
||||
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Block|Any|随便什么");
|
||||
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||||
}
|
||||
|
||||
/// 这是「点了放行还是连不上」最常见的成因:用户在安全警报弹窗上点了取消,
|
||||
/// 系统按程序路径建了一条阻止规则,名字和我们的规则完全不同。
|
||||
#[test]
|
||||
fn auto_created_block_rule_beats_our_allow_rule() {
|
||||
let text = format!(
|
||||
"{PROFILES_OK}\n\
|
||||
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||
RULE|True|Inbound|Block|Public|qft-desktop.exe"
|
||||
);
|
||||
match classify_probe(&text) {
|
||||
FirewallStatus::BlockedByRule(names) => {
|
||||
assert!(names.contains("qft-desktop.exe"), "要报出实际规则名:{names}");
|
||||
}
|
||||
other => panic!("阻止规则必须压过放行规则,实际判定为 {other:?}"),
|
||||
}
|
||||
// 这一类是可以靠提权自动清掉的
|
||||
assert!(classify_probe(&text).fixable_by_grant());
|
||||
assert!(classify_probe(&text).needs_action());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_block_rule_is_harmless() {
|
||||
let text = format!(
|
||||
"{PROFILES_OK}\n\
|
||||
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||
RULE|False|Inbound|Block|Public|qft-desktop.exe\n\
|
||||
{DIRECT_PORTS_OK}"
|
||||
);
|
||||
assert_eq!(classify_probe(&text), FirewallStatus::Allowed);
|
||||
}
|
||||
|
||||
/// 「阻止所有传入连接」打开时,加多少放行规则都没用,
|
||||
/// 必须报成另一种状态,否则用户会一直点那个不起作用的按钮。
|
||||
#[test]
|
||||
fn blanket_inbound_block_is_reported_separately() {
|
||||
let text = "PROFILE|Domain|True|Block|True\n\
|
||||
PROFILE|Private|True|Block|True\n\
|
||||
PROFILE|Public|True|Block|False\n\
|
||||
RULE|True|Inbound|Allow|Any|QFT Desktop";
|
||||
match classify_probe(text) {
|
||||
FirewallStatus::BlockedByPolicy(reason) => {
|
||||
assert!(reason.contains("Public"), "要指出是哪个配置文件:{reason}");
|
||||
}
|
||||
other => panic!("应报告系统级封禁,实际为 {other:?}"),
|
||||
}
|
||||
// 这一类我们不去动,属于用户的安全设置
|
||||
assert!(!classify_probe(text).fixable_by_grant());
|
||||
assert!(classify_probe(text).needs_action());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blanket_block_on_a_disabled_profile_is_ignored() {
|
||||
// 防火墙本身关着的配置文件,AllowInboundRules 是什么都无所谓
|
||||
let text = "PROFILE|Domain|True|Block|True\n\
|
||||
PROFILE|Private|True|Block|True\n\
|
||||
PROFILE|Public|False|Block|False\n\
|
||||
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||
PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
|
||||
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
|
||||
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn firewall_entirely_off_needs_no_rule() {
|
||||
let text = "PROFILE|Domain|False|Block|True\n\
|
||||
PROFILE|Private|False|Block|True\n\
|
||||
PROFILE|Public|False|Block|True";
|
||||
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_configured_inbound_setting_is_not_a_blanket_block() {
|
||||
let text = "PROFILE|Public|True|Block|NotConfigured\n\
|
||||
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||
PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
|
||||
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
|
||||
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_status_has_a_non_empty_detail() {
|
||||
for value in [
|
||||
FirewallStatus::Allowed,
|
||||
FirewallStatus::Missing,
|
||||
FirewallStatus::BlockedByPolicy("策略".into()),
|
||||
FirewallStatus::BlockedByRule("规则名".into()),
|
||||
FirewallStatus::Unknown("原因".into()),
|
||||
FirewallStatus::Unsupported("不支持"),
|
||||
] {
|
||||
assert!(!value.detail().trim().is_empty(), "{value:?} 缺少说明文案");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_instructions_never_recreate_the_profile_bug() {
|
||||
let text = manual_instructions(39393);
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(
|
||||
text.contains("-Profile Any"),
|
||||
"手动命令必须覆盖所有网络类型,否则在公用网络上无效:{text}"
|
||||
);
|
||||
assert!(
|
||||
!text.contains("Private,Domain"),
|
||||
"照抄这条命令会重建出在 Direct AP 网卡上不适用的规则:{text}"
|
||||
);
|
||||
// 用户是整段粘进 PowerShell 的,任何非命令行都会被当成 cmdlet 报错
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
assert!(
|
||||
line.is_empty()
|
||||
|| line.starts_with('#')
|
||||
|| line.starts_with('$')
|
||||
|| line.starts_with("Get-")
|
||||
|| line.starts_with("New-")
|
||||
|| line.starts_with("Remove-"),
|
||||
"剪贴板里只能有命令和注释,这一行会被 PowerShell 当成 cmdlet:{line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = text;
|
||||
}
|
||||
|
||||
/// `\` 续行是 bash 语法,PowerShell 用反引号。上一版在提权脚本和手动
|
||||
/// 命令里都写了 `\`,导致脚本在用户机器上直接语法错误,而外层退出码
|
||||
/// 又是 0,程序还误报了「放行成功」。
|
||||
#[test]
|
||||
fn generated_scripts_use_no_backslash_continuation() {
|
||||
let script = grant_script(r"C:\Program Files\QFT\qft-desktop.exe", r"C:\Temp\qft.ok");
|
||||
for (index, line) in script.lines().enumerate() {
|
||||
assert!(
|
||||
!line.trim_end().ends_with('\\'),
|
||||
"第 {} 行用了 bash 的 `\\` 续行,PowerShell 不认:{line}",
|
||||
index + 1
|
||||
);
|
||||
}
|
||||
assert!(!manual_instructions(39393).contains("\\\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grant_script_quotes_paths_and_reports_success() {
|
||||
let script = grant_script(r"C:\Program Files\QFT\qft-desktop.exe", r"C:\Temp\qft.ok");
|
||||
// 带空格的路径必须整体在单引号里,否则会被重新分词
|
||||
assert!(script.contains(r"$exe = 'C:\Program Files\QFT\qft-desktop.exe'"));
|
||||
// 必须写成功标记,否则调用方无法区分「跑通了」和「脚本报错了」
|
||||
assert!(script.contains("Set-Content -Path $marker"));
|
||||
assert!(script.contains("-Profile Any"));
|
||||
assert!(script.contains("-EdgeTraversalPolicy Allow"));
|
||||
assert!(script.contains("-Protocol TCP -LocalPort 39393"));
|
||||
assert!(script.contains("-Protocol UDP -LocalPort 39392"));
|
||||
// 单引号要按 PowerShell 的规则翻倍转义
|
||||
let tricky = grant_script("C:\\o'brien\\qft.exe", "C:\\t.ok");
|
||||
assert!(tricky.contains("'C:\\o''brien\\qft.exe'"), "{tricky}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_never_counts_a_same_named_rule_for_an_old_executable() {
|
||||
let script = probe_script(r"C:\new-build\qft-desktop.exe");
|
||||
assert!(script.contains("Get-NetFirewallApplicationFilter -Program $exe"));
|
||||
assert!(
|
||||
!script.contains("Get-NetFirewallRule -DisplayName"),
|
||||
"只按同名规则查询会把旧构建路径误判为已放行:{script}"
|
||||
);
|
||||
assert!(script.contains("Get-NetFirewallRule -Name 'QFT-Desktop-Direct-TCP-v2'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_is_read_only_and_repeatable() {
|
||||
// 检测必须无副作用:连续调用结果一致,且不改动任何系统设置
|
||||
assert_eq!(status(), status());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+635
-168
File diff suppressed because it is too large
Load Diff
+203
-37
@@ -50,18 +50,16 @@ struct DirectApIdentity {
|
||||
}
|
||||
|
||||
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.
|
||||
/// v2 intentionally uses short JSON keys. A Direct-AP QR carries only the
|
||||
/// dedicated Wi-Fi identity, session and port: Android must join that Wi-Fi
|
||||
/// and obtain the desktop gateway from the resulting route table. Existing
|
||||
/// LAN/virtual-adapter addresses are deliberately excluded so they cannot
|
||||
/// bypass or delay dedicated pairing.
|
||||
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()
|
||||
Vec::new()
|
||||
} else {
|
||||
self.endpoints.iter().take(3).map(String::as_str).collect()
|
||||
self.endpoints.iter().take(4).map(String::as_str).collect()
|
||||
};
|
||||
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
|
||||
let mut value = json!({
|
||||
@@ -96,6 +94,24 @@ pub fn new_session_token() -> String {
|
||||
URL_SAFE_NO_PAD.encode(bytes)
|
||||
}
|
||||
|
||||
/// Decode an authenticated Direct discovery datagram. `Some(None)` preserves
|
||||
/// compatibility with older Android builds that did not include a device name.
|
||||
pub fn discovery_device(text: &str, session: &str) -> Option<Option<String>> {
|
||||
let prefix = format!("QFTDISC2:{session}");
|
||||
if text == prefix {
|
||||
return Some(None);
|
||||
}
|
||||
let encoded = text.strip_prefix(&(prefix + ":"))?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
|
||||
let name = String::from_utf8(bytes).ok()?;
|
||||
let clean: String = name
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(80)
|
||||
.collect();
|
||||
(!clean.trim().is_empty()).then_some(Some(clean))
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -187,9 +203,10 @@ pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
|
||||
}
|
||||
ips.sort_by_key(|ip| {
|
||||
let o = ip.octets();
|
||||
if is_likely_virtual(*ip) {
|
||||
return 4;
|
||||
}
|
||||
match (o[0], o[1]) {
|
||||
// Windows 的 ICS / Wi-Fi Direct 固定网段,最可能是 QFT 自己拉起来的
|
||||
(192, 168) if o[2] == 137 || o[2] == 49 => 0,
|
||||
(192, 168) => 1,
|
||||
(10, _) => 2,
|
||||
(172, 16..=31) => 3,
|
||||
@@ -199,35 +216,37 @@ pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
|
||||
ips
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
/// 供二维码使用的端点列表。
|
||||
///
|
||||
/// Direct AP 模式不广播任何电脑现有网卡地址。手机必须先加入二维码中的
|
||||
/// 专用 Wi-Fi,再从 Android 为该连接提供的实际路由表读取网关。这样不会
|
||||
/// 猜测 192.168.137.1/49.1,也不会误连 LAN、VPN、WSL 或虚拟机网卡。
|
||||
pub fn qr_endpoints(port: u16, direct_ap_active: bool) -> Vec<String> {
|
||||
if direct_ap_active {
|
||||
return Vec::new();
|
||||
}
|
||||
local_ipv4_endpoints(port)
|
||||
}
|
||||
|
||||
for fallback in [
|
||||
Ipv4Addr::new(192, 168, 137, 1),
|
||||
Ipv4Addr::new(192, 168, 49, 1),
|
||||
] {
|
||||
if !ips.contains(&fallback) {
|
||||
ips.push(fallback);
|
||||
}
|
||||
fn is_likely_virtual(ip: Ipv4Addr) -> bool {
|
||||
let o = ip.octets();
|
||||
if o[3] != 1 {
|
||||
return false;
|
||||
}
|
||||
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()
|
||||
match (o[0], o[1]) {
|
||||
// VMware Workstation 常用 192.168.(1..=254).1 里的高位段;
|
||||
// 这里只挑实测遇到的与常见默认值,避免误伤家用 192.168.0/1.1
|
||||
(192, 168) => matches!(o[2], 30 | 31 | 56 | 99 | 100 | 152 | 174 | 226),
|
||||
// WSL2 / Hyper-V 默认在 172.16-31 段
|
||||
(172, 16..=31) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
|
||||
// 备用 LAN 模式也只广播系统中真实存在的私有地址,不再追加
|
||||
// 192.168.137.1/49.1 等猜测值。Android 随后还会按实际子网过滤。
|
||||
local_ipv4_addresses().into_iter()
|
||||
.map(|ip| format!("http://{ip}:{port}"))
|
||||
.collect()
|
||||
}
|
||||
@@ -236,6 +255,18 @@ pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn discovery_request_reports_android_name_and_accepts_legacy_format() {
|
||||
let session = "abcdefghijklmnopqrstuvwxyz012345";
|
||||
let name = URL_SAFE_NO_PAD.encode("HUAWEI CDY-AN90".as_bytes());
|
||||
assert_eq!(
|
||||
discovery_device(&format!("QFTDISC2:{session}:{name}"), session),
|
||||
Some(Some("HUAWEI CDY-AN90".into()))
|
||||
);
|
||||
assert_eq!(discovery_device(&format!("QFTDISC2:{session}"), session), Some(None));
|
||||
assert_eq!(discovery_device("QFTDISC2:wrong", session), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_pairing_uses_dedicated_short_prefix() {
|
||||
let payload = PairingPayload {
|
||||
@@ -256,3 +287,138 @@ mod tests {
|
||||
assert!(text.len() < 800);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod endpoint_order_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn current_lan_endpoints_are_all_real_private_interfaces() {
|
||||
let endpoints = local_ipv4_endpoints(39393);
|
||||
let real: Vec<Ipv4Addr> = local_ipv4_addresses();
|
||||
let expected: Vec<String> = real
|
||||
.iter()
|
||||
.map(|address| format!("http://{address}:39393"))
|
||||
.collect();
|
||||
assert_eq!(endpoints, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_pairing_excludes_every_preexisting_computer_address() {
|
||||
let payload = PairingPayload {
|
||||
v: 2,
|
||||
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
|
||||
pc_name: "PC".into(),
|
||||
transport: "http-parallel-v2".into(),
|
||||
port: 39393,
|
||||
endpoints: vec![
|
||||
"http://192.168.137.1:39393".into(),
|
||||
"http://192.168.8.68:39393".into(),
|
||||
],
|
||||
wifi: Some(WifiCredentials {
|
||||
ssid: "QFT-PC-abc".into(),
|
||||
passphrase: "0123456789ab".into(),
|
||||
security: "WPA2".into(),
|
||||
}),
|
||||
direction: PairingDirection::Upload,
|
||||
file_name: None,
|
||||
file_size: None,
|
||||
sha256: None,
|
||||
};
|
||||
let text = payload.encode_text().unwrap();
|
||||
let json = String::from_utf8(
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(text.trim_start_matches(PAIR_PREFIX))
|
||||
.unwrap(),
|
||||
).unwrap();
|
||||
assert!(!json.contains("192.168.8.68"), "Direct 二维码不得携带 LAN 地址:{json}");
|
||||
assert!(!json.contains("192.168.137.1"), "Direct 二维码不得猜测 AP 网关:{json}");
|
||||
assert!(json.contains("\"e\":[]"), "Direct 二维码端点必须为空:{json}");
|
||||
assert!(json.contains("QFT-PC-abc"), "专用 Wi-Fi 身份必须保留:{json}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod qr_endpoint_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn direct_ap_never_advertises_guessed_or_local_addresses() {
|
||||
let endpoints = qr_endpoints(39393, true);
|
||||
assert!(endpoints.is_empty(), "Direct 模式只能由手机读取实际网关:{endpoints:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_ap_encoding_stays_address_free_even_with_input_endpoints() {
|
||||
let payload = PairingPayload {
|
||||
v: 2,
|
||||
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
|
||||
pc_name: "PC".into(),
|
||||
transport: "http-parallel-v2".into(),
|
||||
port: 39393,
|
||||
endpoints: vec![
|
||||
"http://192.168.137.1:39393".into(),
|
||||
"http://10.20.30.40:39393".into(),
|
||||
],
|
||||
wifi: Some(WifiCredentials {
|
||||
ssid: "QFT-PC-abc".into(),
|
||||
passphrase: "0123456789ab".into(),
|
||||
security: "WPA2".into(),
|
||||
}),
|
||||
direction: PairingDirection::Upload,
|
||||
file_name: None,
|
||||
file_size: None,
|
||||
sha256: None,
|
||||
};
|
||||
let text = payload.encode_text().unwrap();
|
||||
let json = String::from_utf8(
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(text.trim_start_matches(PAIR_PREFIX))
|
||||
.unwrap(),
|
||||
).unwrap();
|
||||
assert!(!json.contains("192.168.137.1"), "不得携带猜测网关:{json}");
|
||||
assert!(!json.contains("10.20.30.40"), "不得携带本地网卡:{json}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_direct_ap_no_guessed_addresses_are_added() {
|
||||
let endpoints = qr_endpoints(39393, false);
|
||||
let real = local_ipv4_addresses();
|
||||
for guessed in ["192.168.137.1", "192.168.49.1"] {
|
||||
if !real.iter().any(|ip| ip.to_string() == guessed) {
|
||||
assert!(
|
||||
!endpoints.iter().any(|endpoint| endpoint.contains(guessed)),
|
||||
"不存在的地址不得加入二维码:{endpoints:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod virtual_adapter_tests {
|
||||
use super::*;
|
||||
|
||||
/// 实测中这三个虚拟网卡地址把 Direct AP 网关挤出了二维码。
|
||||
#[test]
|
||||
fn known_virtual_ranges_are_recognised() {
|
||||
for ip in ["192.168.30.1", "192.168.31.1", "172.21.96.1", "172.17.0.1"] {
|
||||
assert!(is_likely_virtual(ip.parse().unwrap()), "{ip} 应被识别为虚拟网卡");
|
||||
}
|
||||
}
|
||||
|
||||
/// 家用路由器最常见的网关不能被误伤,否则真实局域网地址反被降权。
|
||||
#[test]
|
||||
fn common_home_gateways_are_not_treated_as_virtual() {
|
||||
for ip in ["192.168.0.1", "192.168.1.1", "192.168.8.1", "10.0.0.1"] {
|
||||
assert!(!is_likely_virtual(ip.parse().unwrap()), "{ip} 不应被当作虚拟网卡");
|
||||
}
|
||||
}
|
||||
|
||||
/// 只有 .1 结尾才可能是虚拟网关;普通主机地址一律不降权。
|
||||
#[test]
|
||||
fn only_gateway_addresses_are_considered() {
|
||||
assert!(!is_likely_virtual("192.168.30.55".parse().unwrap()));
|
||||
assert!(!is_likely_virtual("172.21.96.200".parse().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,14 +163,11 @@ pub const fn platform_tag() -> &'static str {
|
||||
/// 只有 Windows 走 WiFi Direct;macOS 无公开 API,Linux 各发行版
|
||||
/// NetworkManager 行为差异过大,都不做——UI 据此隐藏入口,
|
||||
/// 而不是让用户点进去再失败。
|
||||
// UI 尚未据此隐藏 Direct AP 入口,留待 P1.7 收尾
|
||||
#[allow(dead_code)]
|
||||
pub enum DirectApSupport {
|
||||
Supported,
|
||||
Unsupported(&'static str),
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub const fn direct_ap_support() -> DirectApSupport {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
@@ -183,7 +180,6 @@ pub const fn direct_ap_support() -> DirectApSupport {
|
||||
}
|
||||
|
||||
impl DirectApSupport {
|
||||
#[allow(dead_code)]
|
||||
pub const fn is_supported(&self) -> bool {
|
||||
matches!(self, DirectApSupport::Supported)
|
||||
}
|
||||
|
||||
+15
-2
@@ -3,6 +3,7 @@ use eframe::egui::ColorImage;
|
||||
use qrcode::{types::Color, EcLevel, QrCode};
|
||||
|
||||
const QUIET_MODULES: usize = 4;
|
||||
const PAIR_EC_LEVEL: EcLevel = EcLevel::L;
|
||||
|
||||
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
|
||||
/// characters, allowing the QR encoder to choose a compact alphanumeric data
|
||||
@@ -16,9 +17,11 @@ pub fn render_qr_fitted(text: &str, target_side: usize) -> Result<ColorImage> {
|
||||
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
||||
}
|
||||
|
||||
/// Pairing QR stays static and uses M error correction for first-scan reliability.
|
||||
/// Pairing happens from a clean, static desktop display. QR-L keeps long
|
||||
/// QFTSEND2 payloads several versions smaller than QR-M, giving the camera
|
||||
/// materially more pixels per module; the full quiet zone remains intact.
|
||||
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
||||
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)
|
||||
let code = QrCode::with_error_correction_level(text.as_bytes(), PAIR_EC_LEVEL)
|
||||
.context("pair QR payload too large")?;
|
||||
let modules = code.width() + QUIET_MODULES * 2;
|
||||
let scale = (target_side / modules).max(1);
|
||||
@@ -26,6 +29,16 @@ pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
||||
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pairing_qr_uses_low_density_error_correction() {
|
||||
assert_eq!(PAIR_EC_LEVEL, EcLevel::L);
|
||||
}
|
||||
}
|
||||
|
||||
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
|
||||
let qr_width = code.width();
|
||||
let modules = qr_width + QUIET_MODULES * 2;
|
||||
|
||||
+15
-6
@@ -27,6 +27,7 @@ const IO_BUFFER: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ReceiverEvent {
|
||||
TransportConnected { peer: String },
|
||||
ClientConnected { device: String },
|
||||
UploadStarted { device: String, file_name: String, size: u64 },
|
||||
UploadProgress { device: String, file_name: String, received: u64, size: u64 },
|
||||
@@ -96,7 +97,8 @@ impl ReceiverServer {
|
||||
let tcp_thread = thread::spawn(move || {
|
||||
while !stop_tcp.load(Ordering::Relaxed) {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
Ok((mut stream, peer)) => {
|
||||
let _ = events_tcp.send(ReceiverEvent::TransportConnected { peer: peer.to_string() });
|
||||
let dir = dir_tcp.clone();
|
||||
let token = token_tcp.clone();
|
||||
let tx = events_tcp.clone();
|
||||
@@ -139,7 +141,6 @@ impl ReceiverServer {
|
||||
}
|
||||
};
|
||||
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
|
||||
let expected = format!("QFTDISC2:{token_udp}");
|
||||
let response = format!("QFTHERE2:{token_udp}:{port}");
|
||||
// PC↔PC 的对端不知道令牌,需要先能把本机列出来
|
||||
let announce = crate::discovery::browse_reply(&crate::discovery::NodeAnnounce {
|
||||
@@ -153,12 +154,17 @@ impl ReceiverServer {
|
||||
match socket.recv_from(&mut buf) {
|
||||
Ok((n, peer)) => {
|
||||
match std::str::from_utf8(&buf[..n]).ok() {
|
||||
Some(text) if text == expected => {
|
||||
let _ = socket.send_to(response.as_bytes(), peer);
|
||||
}
|
||||
Some(text) if text == crate::discovery::BROWSE_QUERY => {
|
||||
let _ = socket.send_to(&announce, peer);
|
||||
}
|
||||
Some(text) => {
|
||||
if let Some(device) = crate::pairing::discovery_device(text, &token_udp) {
|
||||
if let Some(device) = device {
|
||||
let _ = events.send(ReceiverEvent::ClientConnected { device });
|
||||
}
|
||||
let _ = socket.send_to(response.as_bytes(), peer);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -452,7 +458,6 @@ fn receive_parallel_chunk(
|
||||
let mut out = OpenOptions::new().write(true).open(&part_path)?;
|
||||
out.seek(SeekFrom::Start(offset))?;
|
||||
copy_exact(reader, &mut out, content_len)?;
|
||||
out.sync_data()?;
|
||||
|
||||
let received = {
|
||||
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
|
||||
@@ -503,6 +508,10 @@ fn finish_parallel_upload(
|
||||
)
|
||||
};
|
||||
|
||||
// Per-chunk FlushFileBuffers serializes otherwise independent upload lanes
|
||||
// and is especially costly on Windows. The in-memory session cannot resume
|
||||
// across a desktop-process crash anyway, so commit once after all chunks.
|
||||
OpenOptions::new().write(true).open(&part_path)?.sync_data()?;
|
||||
let sha = hash_file(&part_path)?;
|
||||
if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") }
|
||||
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
|
||||
|
||||
+148
-14
@@ -22,6 +22,7 @@ const IO_BUFFER: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SenderEvent {
|
||||
TransportConnected { peer: String },
|
||||
ClientConnected { device: String },
|
||||
DownloadStarted { device: String, file_name: String, size: u64 },
|
||||
DownloadCompleted { device: String, file_name: String },
|
||||
@@ -61,7 +62,8 @@ impl SenderServer {
|
||||
let tcp_thread = thread::spawn(move || {
|
||||
while !tcp_stop.load(Ordering::Relaxed) {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
Ok((mut stream, peer)) => {
|
||||
let _ = tcp_events.send(SenderEvent::TransportConnected { peer: peer.to_string() });
|
||||
let token = tcp_token.clone();
|
||||
let path = file_path.clone();
|
||||
let name = file_name.clone();
|
||||
@@ -93,15 +95,20 @@ impl SenderServer {
|
||||
}
|
||||
};
|
||||
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
|
||||
let expected = format!("QFTDISC2:{session_token}");
|
||||
let response = format!("QFTHERE2:{session_token}:{port}");
|
||||
let mut buf = [0u8; 512];
|
||||
while !udp_stop.load(Ordering::Relaxed) {
|
||||
match socket.recv_from(&mut buf) {
|
||||
Ok((n, peer)) if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) => {
|
||||
Ok((n, peer)) => {
|
||||
let Some(device) = std::str::from_utf8(&buf[..n])
|
||||
.ok()
|
||||
.and_then(|text| crate::pairing::discovery_device(text, &session_token))
|
||||
else { continue };
|
||||
if let Some(device) = device {
|
||||
let _ = events.send(SenderEvent::ClientConnected { device });
|
||||
}
|
||||
let _ = socket.send_to(response.as_bytes(), peer);
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
@@ -138,14 +145,47 @@ fn handle_client(
|
||||
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
|
||||
let cloned = stream.try_clone()?;
|
||||
let mut reader = BufReader::with_capacity(32 * 1024, cloned);
|
||||
|
||||
// 同一条连接上循环处理请求。此前每个响应都写死 Connection: close,
|
||||
// 于是并行下载的每个分块都要新建一次 TCP —— 1 GB 是 64 次,
|
||||
// 10 GB 是 640 次,既慢又是"短连接频繁断开"的直接来源。
|
||||
loop {
|
||||
match serve_one(stream, &mut reader, file_path, file_name, size, token, events)? {
|
||||
KeepAlive::Continue => {}
|
||||
KeepAlive::Close => return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个请求的处理结果:是否可以在同一条连接上继续。
|
||||
enum KeepAlive {
|
||||
Continue,
|
||||
Close,
|
||||
}
|
||||
|
||||
fn serve_one(
|
||||
stream: &mut TcpStream,
|
||||
reader: &mut BufReader<TcpStream>,
|
||||
file_path: &PathBuf,
|
||||
file_name: &str,
|
||||
size: u64,
|
||||
token: &str,
|
||||
events: &Sender<SenderEvent>,
|
||||
) -> Result<KeepAlive> {
|
||||
let mut request_line = String::new();
|
||||
reader.read_line(&mut request_line)?;
|
||||
// 读到 0 字节说明对端正常关闭了连接,这是 keep-alive 下的常态,不是错误
|
||||
if reader.read_line(&mut request_line)? == 0 {
|
||||
return Ok(KeepAlive::Close);
|
||||
}
|
||||
if request_line.trim().is_empty() {
|
||||
return Ok(KeepAlive::Close);
|
||||
}
|
||||
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 n == 0 { return Ok(KeepAlive::Close) }
|
||||
if line == "\r\n" || line == "\n" { break }
|
||||
if line.len() > 16 * 1024 { bail!("请求头过长") }
|
||||
if let Some((k, v)) = line.split_once(':') {
|
||||
@@ -155,17 +195,29 @@ fn handle_client(
|
||||
let mut parts = request_line.split_whitespace();
|
||||
let method = parts.next().unwrap_or("");
|
||||
let path = parts.next().unwrap_or("");
|
||||
let version = parts.next().unwrap_or("HTTP/1.1");
|
||||
// HTTP/1.1 默认复用;客户端显式要求 close 或用 1.0 时才断开
|
||||
let keep_alive = version.eq_ignore_ascii_case("HTTP/1.1")
|
||||
&& !headers
|
||||
.get("connection")
|
||||
.map(|v| v.eq_ignore_ascii_case("close"))
|
||||
.unwrap_or(false);
|
||||
let connection_header = if keep_alive { "keep-alive" } else { "close" };
|
||||
|
||||
if headers.get("x-qft-token").map(String::as_str).unwrap_or("") != token {
|
||||
return write_response(stream, 403, "text/plain", b"invalid session");
|
||||
write_response(stream, 403, "text/plain", b"invalid session")?;
|
||||
return Ok(KeepAlive::Close);
|
||||
}
|
||||
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
|
||||
let _ = events.send(SenderEvent::ClientConnected { device: device.clone() });
|
||||
if method == "GET" && path == "/qft/ping" {
|
||||
let body = json!({"ok": true, "protocol": 2, "direction": "download"}).to_string();
|
||||
return write_response(stream, 200, "application/json", body.as_bytes());
|
||||
write_response(stream, 200, "application/json", body.as_bytes())?;
|
||||
return Ok(if keep_alive { KeepAlive::Continue } else { KeepAlive::Close });
|
||||
}
|
||||
if method != "GET" || path != "/qft/download" {
|
||||
return write_response(stream, 404, "text/plain", b"not found");
|
||||
write_response(stream, 404, "text/plain", b"not found")?;
|
||||
return Ok(KeepAlive::Close);
|
||||
}
|
||||
|
||||
let mut input = File::open(file_path)
|
||||
@@ -180,12 +232,12 @@ fn handle_client(
|
||||
let _ = events.send(SenderEvent::DownloadStarted { device: device.clone(), file_name: file_name.to_owned(), size });
|
||||
if headers.get("range").is_none() {
|
||||
write!(stream,
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nAccept-Ranges: bytes\r\nConnection: {connection_header}\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
||||
)?;
|
||||
} else {
|
||||
write!(stream,
|
||||
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{end}/{}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{end}/{}\r\nAccept-Ranges: bytes\r\nConnection: {connection_header}\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||
size,
|
||||
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
||||
)?;
|
||||
@@ -203,7 +255,7 @@ fn handle_client(
|
||||
}
|
||||
stream.flush()?;
|
||||
let _ = events.send(SenderEvent::DownloadCompleted { device, file_name: file_name.to_owned() });
|
||||
Ok(())
|
||||
Ok(if keep_alive { KeepAlive::Continue } else { KeepAlive::Close })
|
||||
}
|
||||
|
||||
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
|
||||
@@ -328,7 +380,7 @@ mod tests {
|
||||
|
||||
let mut client = TcpStream::connect(address).unwrap();
|
||||
client.write_all(
|
||||
b"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\n\r\n",
|
||||
b"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nConnection: close\r\n\r\n",
|
||||
).unwrap();
|
||||
client.flush().unwrap();
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
@@ -346,7 +398,7 @@ mod tests {
|
||||
let mut stream = TcpStream::connect(address).unwrap();
|
||||
write!(
|
||||
stream,
|
||||
"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\n{}\r\n",
|
||||
"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nConnection: close\r\n{}\r\n",
|
||||
range.map(|v| format!("Range: {v}\r\n")).unwrap_or_default(),
|
||||
).unwrap();
|
||||
stream.flush().unwrap();
|
||||
@@ -365,3 +417,85 @@ mod tests {
|
||||
bytes.windows(4).position(|v| v == b"\r\n\r\n").unwrap() + 4
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod keep_alive_tests {
|
||||
use super::{handle_client, SenderEvent};
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::mpsc,
|
||||
thread,
|
||||
};
|
||||
|
||||
/// 在**同一条** TCP 上连发多个 Range 请求,全部必须成功。
|
||||
///
|
||||
/// 此前每个响应都写死 Connection: close,并行下载的每个分块都要
|
||||
/// 重建一次 TCP —— 1 GB 64 次、10 GB 640 次,既是"短连接频繁断开"
|
||||
/// 的来源,也白白付出握手与慢启动的代价。
|
||||
#[test]
|
||||
fn serves_multiple_ranges_on_one_connection() {
|
||||
let path = std::env::temp_dir().join(format!("qft-keepalive-{}.bin", std::process::id()));
|
||||
let payload: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
|
||||
fs::write(&path, &payload).unwrap();
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let (events, _rx) = mpsc::channel::<SenderEvent>();
|
||||
let served = path.clone();
|
||||
let server = thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
handle_client(&mut stream, &served, "p.bin", payload.len() as u64, "tok", &events)
|
||||
});
|
||||
|
||||
let mut stream = TcpStream::connect(address).unwrap();
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
|
||||
// 三段互不重叠的 Range,全部走同一条连接
|
||||
for (start, end) in [(0u64, 1023u64), (1024, 2047), (2048, 4095)] {
|
||||
write!(
|
||||
stream,
|
||||
"GET /qft/download HTTP/1.1\r\nHost: x\r\nX-QFT-Token: tok\r\nRange: bytes={start}-{end}\r\n\r\n"
|
||||
).unwrap();
|
||||
stream.flush().unwrap();
|
||||
|
||||
let mut status = String::new();
|
||||
reader.read_line(&mut status).unwrap();
|
||||
assert!(status.starts_with("HTTP/1.1 206"), "第 {start} 段状态行:{status}");
|
||||
|
||||
let mut length = 0usize;
|
||||
let mut keep_alive = false;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
if line == "\r\n" { break }
|
||||
if let Some((name, value)) = line.split_once(':') {
|
||||
match name.trim().to_ascii_lowercase().as_str() {
|
||||
"content-length" => length = value.trim().parse().unwrap(),
|
||||
"connection" => keep_alive = value.trim().eq_ignore_ascii_case("keep-alive"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(keep_alive, "响应必须声明 keep-alive,否则客户端会关掉连接");
|
||||
assert_eq!(length as u64, end - start + 1, "Content-Length 应等于该段长度");
|
||||
|
||||
let mut body = vec![0u8; length];
|
||||
reader.read_exact(&mut body).unwrap();
|
||||
let expected: Vec<u8> = (start..=end).map(|i| ((i as u32) % 251) as u8).collect();
|
||||
assert_eq!(body, expected, "第 {start} 段内容不符");
|
||||
}
|
||||
|
||||
// 显式要求关闭时应断开,服务端随之正常收尾
|
||||
write!(stream, "GET /qft/ping HTTP/1.1\r\nHost: x\r\nX-QFT-Token: tok\r\nConnection: close\r\n\r\n").unwrap();
|
||||
stream.flush().unwrap();
|
||||
let mut rest = Vec::new();
|
||||
reader.read_to_end(&mut rest).unwrap();
|
||||
let text = String::from_utf8_lossy(&rest);
|
||||
assert!(text.contains("Connection: close"), "显式 close 时应回 close:{text}");
|
||||
|
||||
server.join().unwrap().unwrap();
|
||||
fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
+59
-20
@@ -1,46 +1,85 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
chcp 65001 >nul
|
||||
setlocal EnableExtensions DisableDelayedExpansion
|
||||
cd /d "%~dp0"
|
||||
|
||||
echo == QFT Rust one-click package ==
|
||||
echo == QFT 正式版中文打包 ==
|
||||
|
||||
where cargo >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo ERROR: Rust cargo was not found in PATH.
|
||||
echo 错误:PATH 中未找到 Rust cargo。
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [1/3] Testing and building the Rust Windows release...
|
||||
pushd windows
|
||||
cargo test
|
||||
echo [1/4] 测试并构建 Windows 正式版...
|
||||
pushd desktop
|
||||
cargo test --locked
|
||||
if errorlevel 1 (popd & exit /b 1)
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
if errorlevel 1 (popd & exit /b 1)
|
||||
popd
|
||||
|
||||
for /f "tokens=3" %%V in ('findstr /R /C:"^version =" "windows\Cargo.toml"') do set "QFT_VERSION=%%~V"
|
||||
for /f "tokens=3" %%V in ('findstr /R /C:"^version =" "desktop\Cargo.toml"') do set "QFT_VERSION=%%~V"
|
||||
for /f "tokens=3" %%V in ('findstr /R /C:"^[ ]*versionName =" "android\app\build.gradle.kts"') do set "QFT_ANDROID_VERSION=%%~V"
|
||||
for /f "tokens=3" %%V in ('findstr /R /C:"^[ ]*versionCode =" "android\app\build.gradle.kts"') do set "QFT_ANDROID_CODE=%%V"
|
||||
for /f "usebackq delims=" %%T in (`powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"`) do set "QFT_STAMP=%%T"
|
||||
for /f "usebackq delims=" %%C in (`git rev-parse --short HEAD 2^>nul`) do set "QFT_RELEASE_COMMIT=%%C"
|
||||
if not defined QFT_VERSION set "QFT_VERSION=unknown"
|
||||
set "QFT_PACKAGE=QFT-Rust-%QFT_VERSION%-%QFT_STAMP%-windows"
|
||||
if not defined QFT_ANDROID_VERSION set "QFT_ANDROID_VERSION=unknown"
|
||||
if not defined QFT_ANDROID_CODE set "QFT_ANDROID_CODE=unknown"
|
||||
if not defined QFT_RELEASE_COMMIT set "QFT_RELEASE_COMMIT=unknown"
|
||||
if /I "%QFT_ANDROID_VERSION%"=="%QFT_VERSION%" goto versions_ok
|
||||
echo 错误:PC 版本 %QFT_VERSION% 与 Android 版本 %QFT_ANDROID_VERSION% 不一致,拒绝封版。
|
||||
exit /b 1
|
||||
|
||||
:versions_ok
|
||||
set "QFT_PACKAGE=QFT-正式版-v%QFT_VERSION%-Windows-%QFT_STAMP%"
|
||||
set "QFT_PACKAGE_DIR=%CD%\dist\%QFT_PACKAGE%"
|
||||
|
||||
echo [2/3] Collecting Rust artifacts...
|
||||
echo [2/4] 收集正式版文件...
|
||||
mkdir "%QFT_PACKAGE_DIR%" || exit /b 1
|
||||
copy /y "windows\target\release\qft-windows.exe" "%QFT_PACKAGE_DIR%\QFT-Windows.exe" >nul || exit /b 1
|
||||
copy /y "README.md" "%QFT_PACKAGE_DIR%\README.md" >nul || exit /b 1
|
||||
copy /y "TEST_REPORT.md" "%QFT_PACKAGE_DIR%\TEST_REPORT.md" >nul || exit /b 1
|
||||
copy /y "docs\PROTOCOL.md" "%QFT_PACKAGE_DIR%\PROTOCOL.md" >nul || exit /b 1
|
||||
copy /y "desktop\target\release\qft-desktop.exe" "%QFT_PACKAGE_DIR%\QFT超速文件传输.exe" >nul || exit /b 1
|
||||
copy /y "README.md" "%QFT_PACKAGE_DIR%\使用说明.md" >nul || exit /b 1
|
||||
copy /y "TEST_REPORT.md" "%QFT_PACKAGE_DIR%\测试报告.md" >nul || exit /b 1
|
||||
copy /y "docs\PROTOCOL.md" "%QFT_PACKAGE_DIR%\传输协议.md" >nul || exit /b 1
|
||||
copy /y "RELEASE_NOTES_%QFT_VERSION%.md" "%QFT_PACKAGE_DIR%\版本说明.md" >nul || exit /b 1
|
||||
|
||||
echo [3/3] Writing SHA-256 checksums and ZIP archive...
|
||||
rem 仅收集已经由用户在 Windows 上构建好的 APK,不调用 Gradle/Android SDK。
|
||||
set "QFT_APK=%QFT_ANDROID_APK%"
|
||||
if defined QFT_APK goto apk_resolved
|
||||
if exist "android\app\build\outputs\apk\release\app-release.apk" set "QFT_APK=android\app\build\outputs\apk\release\app-release.apk"
|
||||
if defined QFT_APK goto apk_resolved
|
||||
if exist "android\app\build\outputs\apk\debug\app-debug.apk" set "QFT_APK=android\app\build\outputs\apk\debug\app-debug.apk"
|
||||
|
||||
:apk_resolved
|
||||
if not defined QFT_APK goto apk_missing
|
||||
if not exist "%QFT_APK%" goto apk_missing
|
||||
copy /y "%QFT_APK%" "%QFT_PACKAGE_DIR%\QFT安卓端-v%QFT_VERSION%.apk" >nul || exit /b 1
|
||||
echo 已收集 Android APK:%QFT_APK%
|
||||
goto apk_done
|
||||
|
||||
:apk_missing
|
||||
echo 提示:未发现已构建 APK,本次生成 Windows 桌面端正式包。
|
||||
echo 如需合并 APK,请先在 Windows 构建,或设置 QFT_ANDROID_APK 后重跑本脚本。
|
||||
|
||||
:apk_done
|
||||
echo [3/4] 写入版本信息与 SHA-256 校验...
|
||||
powershell -NoProfile -Command ^
|
||||
"$dir = [IO.Path]::GetFullPath('%QFT_PACKAGE_DIR%');" ^
|
||||
"$meta = @('QFT 超速文件传输 正式版', '产品版本:v%QFT_VERSION%', 'Android versionCode:%QFT_ANDROID_CODE%', '封版提交:%QFT_RELEASE_COMMIT%', '打包时间:%QFT_STAMP%', '平台:Windows x64');" ^
|
||||
"[IO.File]::WriteAllLines((Join-Path $dir '版本信息.txt'), $meta, [Text.UTF8Encoding]::new($false));" ^
|
||||
"$lines = Get-ChildItem -LiteralPath $dir -File ^| Where-Object Name -ne 'SHA256校验.txt' ^| Sort-Object Name ^| ForEach-Object { '{0} {1}' -f (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLower(), $_.Name };" ^
|
||||
"[IO.File]::WriteAllLines((Join-Path $dir 'SHA256校验.txt'), $lines, [Text.UTF8Encoding]::new($false))"
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
echo [4/4] 创建中文 ZIP 正式包...
|
||||
powershell -NoProfile -Command ^
|
||||
"$dir = [IO.Path]::GetFullPath('%QFT_PACKAGE_DIR%');" ^
|
||||
"$lines = Get-ChildItem -LiteralPath $dir -File ^| Sort-Object Name ^| ForEach-Object { '{0} {1}' -f (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLower(), $_.Name };" ^
|
||||
"[IO.File]::WriteAllLines((Join-Path $dir 'SHA256SUMS.txt'), $lines, [Text.UTF8Encoding]::new($false));" ^
|
||||
"Compress-Archive -LiteralPath $dir -DestinationPath ($dir + '.zip') -Force"
|
||||
if errorlevel 1 exit /b 1
|
||||
|
||||
echo.
|
||||
echo PACKAGE COMPLETE
|
||||
echo Folder: %QFT_PACKAGE_DIR%
|
||||
echo ZIP: %QFT_PACKAGE_DIR%.zip
|
||||
echo 封版打包完成
|
||||
echo 文件夹:%QFT_PACKAGE_DIR%
|
||||
echo 压缩包:%QFT_PACKAGE_DIR%.zip
|
||||
exit /b 0
|
||||
|
||||
+55
-20
@@ -4,7 +4,7 @@ set -eu
|
||||
QFT_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
cd "$QFT_ROOT"
|
||||
|
||||
echo "== QFT Rust one-click package =="
|
||||
echo "== QFT 正式版中文打包 =="
|
||||
if ! command -v cargo >/dev/null 2>&1; then
|
||||
# rustup 装在 keg-only 目录里时不会自动进 PATH,这里兜一下,
|
||||
# 避免用户明明装了工具链却被告知"没装"。
|
||||
@@ -23,35 +23,43 @@ command -v cargo >/dev/null 2>&1 || {
|
||||
exit 1
|
||||
}
|
||||
|
||||
echo "[1/3] Testing and building the Rust desktop release..."
|
||||
echo "[1/4] 测试并构建桌面正式版..."
|
||||
(
|
||||
cd desktop
|
||||
cargo test
|
||||
cargo build --release
|
||||
cargo test --locked
|
||||
cargo build --release --locked
|
||||
)
|
||||
|
||||
QFT_VERSION=$(awk -F'"' '/^\[package\]/{package=1; next} package && /^version[[:space:]]*=/{print $2; exit} /^\[/{package=0}' desktop/Cargo.toml)
|
||||
[ -n "$QFT_VERSION" ] || QFT_VERSION=unknown
|
||||
QFT_STAMP=$(date '+%Y%m%d-%H%M%S')
|
||||
QFT_PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
|
||||
QFT_PACKAGE="QFT-Rust-${QFT_VERSION}-${QFT_STAMP}-${QFT_PLATFORM}"
|
||||
QFT_ARCH=$(uname -m)
|
||||
QFT_PACKAGE="QFT-正式版-v${QFT_VERSION}-${QFT_PLATFORM}-${QFT_ARCH}-${QFT_STAMP}"
|
||||
QFT_PACKAGE_DIR="$QFT_ROOT/dist/$QFT_PACKAGE"
|
||||
|
||||
echo "[2/3] Collecting Rust artifacts..."
|
||||
ANDROID_VERSION=$(awk -F'"' '/versionName[[:space:]]*=/{print $2; exit}' android/app/build.gradle.kts)
|
||||
ANDROID_VERSION_CODE=$(awk '/versionCode[[:space:]]*=/{print $3; exit}' android/app/build.gradle.kts)
|
||||
[ "$ANDROID_VERSION" = "$QFT_VERSION" ] || {
|
||||
echo "错误:PC 版本 $QFT_VERSION 与 Android 版本 $ANDROID_VERSION 不一致,拒绝封版。" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
echo "[2/4] 收集正式版文件..."
|
||||
mkdir -p "$QFT_PACKAGE_DIR"
|
||||
if [ -f "desktop/target/release/qft-desktop.exe" ]; then
|
||||
cp "desktop/target/release/qft-desktop.exe" "$QFT_PACKAGE_DIR/QFT-Windows.exe"
|
||||
cp "desktop/target/release/qft-desktop.exe" "$QFT_PACKAGE_DIR/QFT超速文件传输.exe"
|
||||
elif [ -f "desktop/target/release/qft-desktop" ]; then
|
||||
cp "desktop/target/release/qft-desktop" "$QFT_PACKAGE_DIR/QFT-Desktop"
|
||||
cp "desktop/target/release/qft-desktop" "$QFT_PACKAGE_DIR/QFT超速文件传输"
|
||||
# macOS 上额外产出 .app 包。AppKit 的若干行为(其中就包括
|
||||
# NSOpenPanel)依赖应用被正确注册为 GUI 程序,直接跑裸二进制时
|
||||
# openPanel 会偶发返回 NULL 并导致崩溃。
|
||||
if [ "$QFT_PLATFORM" = "darwin" ]; then
|
||||
QFT_APP="$QFT_PACKAGE_DIR/QFT.app"
|
||||
QFT_APP="$QFT_PACKAGE_DIR/QFT超速文件传输.app"
|
||||
mkdir -p "$QFT_APP/Contents/MacOS"
|
||||
cp "desktop/target/release/qft-desktop" "$QFT_APP/Contents/MacOS/QFT"
|
||||
chmod +x "$QFT_APP/Contents/MacOS/QFT"
|
||||
cat > "$QFT_APP/Contents/Info.plist" <<'PLIST'
|
||||
cat > "$QFT_APP/Contents/Info.plist" <<PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
@@ -61,35 +69,62 @@ elif [ -f "desktop/target/release/qft-desktop" ]; then
|
||||
<key>CFBundleIdentifier</key><string>com.qft.desktop</string>
|
||||
<key>CFBundleExecutable</key><string>QFT</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key><string>0.5.0</string>
|
||||
<key>CFBundleShortVersionString</key><string>${QFT_VERSION}</string>
|
||||
<key>CFBundleVersion</key><string>1</string>
|
||||
<key>NSHighResolutionCapable</key><true/>
|
||||
<key>LSMinimumSystemVersion</key><string>11.0</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
echo " 已生成 QFT.app(推荐用它启动,比裸二进制稳定)"
|
||||
echo " 已生成 QFT超速文件传输.app(推荐使用)"
|
||||
fi
|
||||
else
|
||||
echo "ERROR: desktop release binary was not produced." >&2
|
||||
exit 1
|
||||
fi
|
||||
cp README.md TEST_REPORT.md "$QFT_PACKAGE_DIR/"
|
||||
cp docs/PROTOCOL.md "$QFT_PACKAGE_DIR/PROTOCOL.md"
|
||||
cp README.md "$QFT_PACKAGE_DIR/使用说明.md"
|
||||
cp TEST_REPORT.md "$QFT_PACKAGE_DIR/测试报告.md"
|
||||
cp docs/PROTOCOL.md "$QFT_PACKAGE_DIR/传输协议.md"
|
||||
cp "RELEASE_NOTES_${QFT_VERSION}.md" "$QFT_PACKAGE_DIR/版本说明.md"
|
||||
|
||||
echo "[3/3] Writing SHA-256 checksums and archive..."
|
||||
# 只收集已经存在的 APK,不检查、下载或调用 Android SDK/Gradle。
|
||||
QFT_APK=${QFT_ANDROID_APK:-}
|
||||
if [ -z "$QFT_APK" ] && [ -f android/app/build/outputs/apk/release/app-release.apk ]; then
|
||||
QFT_APK=android/app/build/outputs/apk/release/app-release.apk
|
||||
fi
|
||||
if [ -z "$QFT_APK" ] && [ -f android/app/build/outputs/apk/debug/app-debug.apk ]; then
|
||||
QFT_APK=android/app/build/outputs/apk/debug/app-debug.apk
|
||||
fi
|
||||
if [ -n "$QFT_APK" ] && [ -f "$QFT_APK" ]; then
|
||||
cp "$QFT_APK" "$QFT_PACKAGE_DIR/QFT安卓端-v${QFT_VERSION}.apk"
|
||||
echo " 已收集 Android APK:$QFT_APK"
|
||||
else
|
||||
echo " 提示:未发现已构建 APK,本次只生成当前桌面平台正式包。"
|
||||
fi
|
||||
|
||||
echo "[3/4] 写入 SHA-256 校验..."
|
||||
QFT_RELEASE_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || printf 'unknown')
|
||||
{
|
||||
printf '%s\n' "QFT 超速文件传输 正式版"
|
||||
printf '%s\n' "产品版本:v${QFT_VERSION}"
|
||||
printf '%s\n' "Android versionCode:${ANDROID_VERSION_CODE}"
|
||||
printf '%s\n' "封版提交:${QFT_RELEASE_COMMIT}"
|
||||
printf '%s\n' "打包时间:${QFT_STAMP}"
|
||||
printf '%s\n' "平台:${QFT_PLATFORM} ${QFT_ARCH}"
|
||||
} > "$QFT_PACKAGE_DIR/版本信息.txt"
|
||||
(
|
||||
cd "$QFT_PACKAGE_DIR"
|
||||
# 只对普通文件求校验和:.app 是目录,直接喂给 sha256sum 会报错
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
find . -type f ! -name SHA256SUMS.txt | sort | xargs sha256sum > SHA256SUMS.txt
|
||||
find . -type f ! -name SHA256校验.txt | sort | xargs sha256sum > SHA256校验.txt
|
||||
else
|
||||
find . -type f ! -name SHA256SUMS.txt | sort | xargs shasum -a 256 > SHA256SUMS.txt
|
||||
find . -type f ! -name SHA256校验.txt | sort | xargs shasum -a 256 > SHA256校验.txt
|
||||
fi
|
||||
)
|
||||
echo "[4/4] 创建中文压缩包..."
|
||||
tar -C "$QFT_ROOT/dist" -czf "$QFT_PACKAGE_DIR.tar.gz" "$QFT_PACKAGE"
|
||||
|
||||
echo
|
||||
echo "PACKAGE COMPLETE"
|
||||
echo "Folder: $QFT_PACKAGE_DIR"
|
||||
echo "Archive: $QFT_PACKAGE_DIR.tar.gz"
|
||||
echo "封版打包完成"
|
||||
echo "文件夹:$QFT_PACKAGE_DIR"
|
||||
echo "压缩包:$QFT_PACKAGE_DIR.tar.gz"
|
||||
|
||||
@@ -6,6 +6,7 @@ gradle=(ROOT/'android/app/build.gradle.kts').read_text(); manifest=(ROOT/'androi
|
||||
wifi=(ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text(); upload=(ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text()
|
||||
download=(ROOT/'android/app/src/main/java/com/qft/optical/DownloadClient.kt').read_text()
|
||||
main=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text(); analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
|
||||
queue=(ROOT/'android/app/src/main/java/com/qft/optical/TransferQueue.kt').read_text()
|
||||
gray=(ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text(); protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text(); base45=(ROOT/'android/app/src/main/java/com/qft/optical/Base45.kt').read_text(); overlay=(ROOT/'android/app/src/main/java/com/qft/optical/QrLockOverlay.kt').read_text(); security=(ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text()
|
||||
assert re.search(r'minSdk\s*=\s*24',gradle)
|
||||
assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest
|
||||
@@ -15,7 +16,10 @@ 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 'val targetSize = Size(640, 480)' in main and 'Size(960, 540)' not in main
|
||||
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
|
||||
assert 'OPTICAL_LOCKED' in analyzer and 'OPTICAL_MULTI' not in analyzer and 'QRCodeReader' in analyzer and 'MultiFormatReader' not in analyzer
|
||||
@@ -24,7 +28,10 @@ assert 'GrayFrameBuffer' in gray and 'scratch = ByteArray(0)' in gray
|
||||
assert 'Base45.decode' in protocol and 'QFT2' in protocol and 'looksLikeBinaryFrame' not in protocol
|
||||
assert 'lockedCenterInView' in overlay and 'postInvalidateDelayed' in overlay and 'maybeRefocusLockedQr' in main
|
||||
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+, 640x480 single-QR ROI, reusable luma buffer, QFT2/Base45 text parse, dynamic lock/refocus, Camera2 FPS request, 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')
|
||||
|
||||
@@ -26,10 +26,10 @@ with tempfile.TemporaryDirectory() as td:
|
||||
import java.util.zip.CRC32
|
||||
fun b45e(data: ByteArray): String { val a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; val o=StringBuilder(); var i=0; while(i+1<data.size){val v=(data[i].toInt() and 255)*256+(data[i+1].toInt() and 255);o.append(a[v%45]).append(a[(v/45)%45]).append(a[v/2025]);i+=2};if(i<data.size){val v=data[i].toInt() and 255;o.append(a[v%45]).append(a[v/45])};return o.toString() }
|
||||
fun fr(p:ByteArray):String { val b=ByteBuffer.allocate(24+p.size+4).order(ByteOrder.BIG_ENDIAN);b.put("QFT2".toByteArray()).put(2).put(2).putLong(7L).putInt(9).putInt(11).putShort(p.size.toShort()).put(p);val n=b.position();val c=CRC32().apply{update(b.array(),0,n)}.value;b.putInt(c.toInt());return "QFT2:"+b45e(b.array()) }
|
||||
fun main(){check(Base45.decode("BB8")!!.contentEquals("AB".toByteArray()));check(Base45.decode("%69 VD92EX0")!!.contentEquals("Hello!!".toByteArray()));val p="hello-qft2".toByteArray();val f=QftProtocol.parseText(fr(p))!!;check(f.kind==FrameKind.DATA&&f.sessionId==7L&&f.seq==9L&&f.payload.contentEquals(p));val c=LockRect(100,100,300,300).smoothToward(LockRect(140,130,340,340),.25f);check(c.left in 101..139);println("PASS Kotlin QFT2/Base45 protocol + ROI lock smoothing")}
|
||||
fun main(){check(Base45.decode("BB8")!!.contentEquals("AB".toByteArray()));check(Base45.decode("%69 VD92EX0")!!.contentEquals("Hello!!".toByteArray()));val p="hello-qft2".toByteArray();val f=QftProtocol.parseText(fr(p))!!;check(f.kind==FrameKind.DATA&&f.sessionId==7L&&f.seq==9L&&f.payload.contentEquals(p));val c=LockRect(100,100,300,300).smoothToward(LockRect(140,130,340,340),.25f);check(c.left in 101..139);val q=mutableListOf("A","B","C");check(moveQueueItem(q,0,2));check(q==listOf("B","C","A"));println("PASS Kotlin QFT2/Base45 protocol + ROI lock + transfer queue")}
|
||||
'''))
|
||||
jar=td/'smoke.jar'
|
||||
run([kotlinc, str(K/'Base45.kt'), str(K/'Base64Url.kt'), str(K/'Protocol.kt'), str(K/'LockRect.kt'), str(smoke), '-include-runtime', '-d', str(jar)])
|
||||
run([kotlinc, str(K/'Base45.kt'), str(K/'Base64Url.kt'), str(K/'Protocol.kt'), str(K/'LockRect.kt'), str(K/'TransferQueue.kt'), str(smoke), '-include-runtime', '-d', str(jar)])
|
||||
p=subprocess.run(['java','-jar',str(jar)],text=True,capture_output=True,env={**os.environ,'TERM':'xterm'},check=True)
|
||||
print(p.stdout.strip())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user