4 Commits

Author SHA1 Message Date
zhy e326611c82 发布 0.4.6 封版 2026-08-11 10:53:59 +08:00
zhy 34b8fdf050 合并直传接收与文件选择优化 2026-08-11 10:21:45 +08:00
zhy e9e51a4941 修复直传接收并优化文件选择提示 2026-08-11 10:21:37 +08:00
zhy200308 b444a39a63 修复传输问题 2026-08-11 09:44:26 +08:00
23 changed files with 703 additions and 160 deletions
+2
View File
@@ -1,6 +1,8 @@
# Rust
/target
**/target
windows/target-*/
**/__pycache__/
# Android
.gradle/
**/build/
+1 -1
View File
@@ -1,4 +1,4 @@
# QFT v0.4.0-rc2 implementation status
# QFT v0.4.6 implementation status
## Windows → Android optical
+2 -2
View File
@@ -1,4 +1,4 @@
# QFT · 超速二维码文件传输 v0.4.0-rc2
# QFT · 超速二维码文件传输 v0.4.6
Windows + Android 双向候选版。v0.4 的核心目标不是继续堆“4 码理论吞吐”,而是解决 Android 端实际识别慢的问题:**删除 2×2/4 通道,改成一个大二维码 + 动态 ROI 锁定 + 高频局部解码**。
@@ -7,7 +7,7 @@ Windows + Android 双向候选版。v0.4 的核心目标不是继续堆“4 码
- **Windows → Android:纯光学**。文件数据只经过 Windows 屏幕 → Android 摄像头;Wi‑Fi、蓝牙、局域网和互联网都不参与文件数据传输。
- **Android → Windows:扫码本地直连**。Windows 选择保存目录并启动 QFT Direct/LAN 接收服务;Android 扫码、配网、自动发现电脑,然后并行分块上传,不经过外网。
> rc2 已完成协议、图像合成解码、ROI、并行上传、UDP 发现、内存预算和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
> v0.4.6 已完成协议、图像合成解码、ROI、并行上传、UDP 发现、内存预算和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
## v0.4 光学链路改动
+5 -5
View File
@@ -1,4 +1,4 @@
# QFT v0.4.0-rc2 test report
# QFT v0.4.6 test report
Date: 2026-08-10
@@ -6,7 +6,7 @@ This report separates **tests actually executed in the current environment** fro
## What this RC changes
The rc2 optical path is deliberately simpler than v0.3:
The v0.4.6 optical path is deliberately simpler than v0.3:
- 2×2 / 4-channel QR removed;
- one large QR only;
@@ -152,7 +152,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 rc2
## Important implementation decisions validated during v0.4.6
### QFT2 uses Result.text, not ZXing rawBytes
@@ -160,7 +160,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. rc2 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.6 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
@@ -170,7 +170,7 @@ The scanner performs initial focus/metering, then re-meters after first lock or
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**:
1. Windows `cargo check/test/build --release` for rc2.
1. Windows `cargo check/test/build --release` for v0.4.6.
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.
+1 -1
View File
@@ -1,4 +1,4 @@
QFT v0.4.0-rc2 test results
QFT v0.4.6 test results
UTC 2026-08-10T08:45:56Z
== protocol_selftest.py ==
+1 -1
View File
@@ -1,7 +1,7 @@
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Host "== QFT v0.4.0-rc2 Windows host verification ==" -ForegroundColor Cyan
Write-Host "== QFT v0.4.6 Windows host verification ==" -ForegroundColor Cyan
if (Get-Command python -ErrorAction SilentlyContinue) {
Write-Host "[1/4] Core protocol/selftests"
+3 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 16
versionName = "0.4.0-rc8"
versionCode = 18
versionName = "0.4.6"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -40,6 +40,7 @@ android {
dependencies {
implementation("androidx.activity:activity-ktx:1.10.1")
implementation("androidx.core:core-ktx:1.15.0")
implementation("androidx.camera:camera-core:1.4.2")
implementation("androidx.camera:camera-camera2:1.4.2")
implementation("androidx.camera:camera-lifecycle:1.4.2")
+9
View File
@@ -19,6 +19,15 @@
android:label="QFT"
android:supportsRtl="true"
android:theme="@style/QftTheme">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/qft_file_paths" />
</provider>
<activity
android:name=".MainActivity"
android:exported="true"
@@ -25,6 +25,11 @@ object DownloadClient {
private const val TAG = "QftDownload"
private const val BUFFER_SIZE = 1024 * 1024
private const val ATTEMPTS = 5
/** 整份重下的轮数。仅在 SHA-256 不匹配(缓存已损坏)时才会用到第二轮。 */
private const val VERIFY_ROUNDS = 2
/** 落盘阶段的失败与「下载失败」是两回事,用独立异常类型区分。 */
class SaveFailure(message: String, cause: Throwable?) : Exception(message, cause)
fun download(
context: Context,
@@ -33,6 +38,11 @@ object DownloadClient {
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
/** 返回非 null 表示应立刻中止(例如 QFT 临时网络已断开),并以该原因报错。 */
abortReason: () -> String? = { null },
/** 阶段提示。传输完成后还有校验与落盘两步,必须让 UI 有反馈,
* 否则用户看到的就是「进度条停在 100% 然后报错」。 */
onPhase: (String) -> Unit = {},
onProgress: (received: Long, total: Long) -> Unit,
): DownloadedFile {
require(pairing.direction == TransferDirection.DOWNLOAD_TO_PHONE)
@@ -43,24 +53,68 @@ object DownloadClient {
partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") }
if (partial.length() > expectedSize) partial.delete()
// 落盘时缓存文件与目标文件同时存在,需要约 2 倍空间。
// 不预检的话,这里会在下载 100% 之后才失败,用户看到的是「快结束时失败」。
ensureSpaceForTransfer(partial, expectedSize)
repeat(VERIFY_ROUNDS) { round ->
receiveUntilComplete(network, baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
onPhase("正在校验文件完整性…")
val actual = sha256(partial, onProgress)
if (actual.equals(expectedSha, ignoreCase = true)) {
onPhase("正在保存到 Downloads/QFT…")
ensureSpaceForSave(partial, expectedSize)
val result = try {
saveToDownloads(resolver, partial, expectedName, expectedSize, onProgress)
} catch (e: Exception) {
// 这一步失败与网络无关,重下多少次都没用,直接如实报错
throw SaveFailure("文件已完整收到,但保存到 Downloads/QFT 失败:${failureDetail(e)}", e)
}
partial.delete()
Log.i(TAG, "completed size=$expectedSize")
return result
}
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
partial.delete()
if (round + 1 >= VERIFY_ROUNDS) {
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
}
onPhase("校验未通过,正在重新完整下载…")
}
error("下载未能完成")
}
/** 传输阶段:断点续传 + 有限重试。只有这一段的失败才算「下载失败」。 */
private fun receiveUntilComplete(
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
var last: Exception? = null
repeat(ATTEMPTS) { attempt ->
abortReason()?.let { throw IllegalStateException(it, last) }
try {
Log.i(TAG, "attempt=${attempt + 1}/$ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl")
if (partial.length() < expectedSize) {
receiveAttempt(network, baseUrl, pairing, deviceName, partial, expectedSize, onProgress)
receiveAttempt(network, baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
}
if (partial.length() != expectedSize) {
error("下载提前结束:${partial.length()}/$expectedSize")
}
verifySha256(partial, expectedSha)
val result = saveToDownloads(resolver, partial, expectedName, expectedSize)
partial.delete()
Log.i(TAG, "completed size=$expectedSize")
return result
return
} catch (e: Exception) {
last = e
Log.w(TAG, "attempt=${attempt + 1}/$ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e)
abortReason()?.let { throw IllegalStateException(it, e) }
if (attempt + 1 < ATTEMPTS) {
try {
Thread.sleep(250L * (attempt + 1))
@@ -71,7 +125,28 @@ object DownloadClient {
}
}
}
throw IllegalStateException("从电脑下载失败,已重试 $ATTEMPTS 次:${failureDetail(last)}", last)
val progressed = partial.length()
throw IllegalStateException(
"从电脑下载失败,已重试 $ATTEMPTS 次(已收到 ${progressed}/$expectedSize 字节):${failureDetail(last)}",
last,
)
}
/** 传输 + 落盘阶段合计需要的可用空间。 */
private fun ensureSpaceForTransfer(partial: File, expectedSize: Long) {
val root = partial.parentFile ?: return
val needed = (expectedSize - partial.length()).coerceAtLeast(0L) + expectedSize
val usable = root.usableSpace
if (usable in 1 until needed) {
error("存储空间不足:本次接收约需 ${needed / 1024 / 1024} MB(含保存时的临时副本),当前可用 ${usable / 1024 / 1024} MB")
}
}
private fun ensureSpaceForSave(partial: File, expectedSize: Long) {
val usable = partial.parentFile?.usableSpace ?: return
if (usable in 1 until expectedSize) {
error("存储空间不足:保存副本还需 ${expectedSize / 1024 / 1024} MB,当前可用 ${usable / 1024 / 1024} MB")
}
}
private fun receiveAttempt(
@@ -81,6 +156,7 @@ object DownloadClient {
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
val requestedOffset = partial.length().coerceIn(0L, expectedSize)
@@ -132,6 +208,9 @@ object DownloadClient {
FileOutputStream(partial, offset > 0L).use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
// 网络已断开时立刻收手:否则会在 readTimeout 上白等 12 秒,
// 再乘以 5 次重试,用户等一分钟才看到错误。
abortReason()?.let { error(it) }
val n = input.read(buffer)
if (n < 0) break
if (n == 0) continue
@@ -154,28 +233,38 @@ object DownloadClient {
}
}
private fun verifySha256(file: File, expectedSha: String) {
/** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 100%。 */
private fun sha256(file: File, onProgress: (Long, Long) -> Unit): String {
val digest = MessageDigest.getInstance("SHA-256")
val total = file.length()
var done = 0L
var lastReport = 0L
FileInputStream(file).use { input ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val n = input.read(buffer)
if (n < 0) break
if (n > 0) digest.update(buffer, 0, n)
if (n > 0) {
digest.update(buffer, 0, n)
done += n.toLong()
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 80L) {
onProgress(done, total)
lastReport = now
}
}
val actual = digest.digest().toHex()
if (!actual.equals(expectedSha, ignoreCase = true)) {
file.delete()
error("文件校验失败,已清除不完整缓存;请重试")
}
}
onProgress(total, total)
return digest.digest().toHex()
}
private fun saveToDownloads(
resolver: ContentResolver,
partial: File,
expectedName: String,
expectedSize: Long,
onProgress: (Long, Long) -> Unit,
): DownloadedFile {
var target: DownloadTarget? = null
try {
@@ -185,12 +274,18 @@ object DownloadClient {
createdTarget.output.use { output ->
val buffer = ByteArray(BUFFER_SIZE)
var copied = 0L
var lastReport = 0L
while (true) {
val n = input.read(buffer)
if (n < 0) break
if (n == 0) continue
output.write(buffer, 0, n)
copied += n.toLong()
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 80L) {
onProgress(copied, expectedSize)
lastReport = now
}
}
output.flush()
if (copied != expectedSize) error("保存下载文件时大小发生变化")
@@ -79,6 +79,8 @@ class MainActivity : ComponentActivity() {
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 sendProgress: ProgressBar? = null
@@ -86,6 +88,9 @@ class MainActivity : ComponentActivity() {
private var connectingStatusText: TextView? = null
private var downloadStatusText: TextView? = null
@Volatile private var downloadRunning = false
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
@Volatile private var transferAbortReason: String? = null
@Volatile private var pairConnectionAttempt = 0L
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
@@ -112,13 +117,18 @@ class MainActivity : ComponentActivity() {
}
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
selectedFiles.clear()
var unknown = 0
for (uri in uris) {
val file = UploadClient.describeFile(contentResolver, uri)
if (file != null) selectedFiles += file else unknown++
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()) {
@@ -147,6 +157,8 @@ class MainActivity : ComponentActivity() {
downloadRunning = false
downloadStatusText = null
selectedFiles.clear()
managingFilesForPair = null
managingFilesForBaseUrl = null
val root = pageColumn()
root.addView(text("QFT", 30f, Color.WHITE, true))
@@ -172,9 +184,16 @@ class MainActivity : ComponentActivity() {
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
buttonLabel = "扫描电脑二维码",
) { requestScanner(ScannerMode.PAIR) })
root.addView(space(16))
root.addView(modeCard(
title = "接收文件柜",
badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等",
body = "查看 QFT 已接收的文件;点击后将使用手机中可用的阅读器或播放器打开。",
buttonLabel = "打开文件柜",
) { showReceivedFiles() })
root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.4.0-rc2 · Android 7+ 到最新", 12f, MUTED))
root.addView(text("QFT v0.4.6 · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
@@ -643,6 +662,10 @@ class MainActivity : ComponentActivity() {
// HTTP/timeout cause instead of replacing it with this generic
// message mid-retry.
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) {
// 让下载线程立刻收手并如实报告断网,而不是继续跑完
// 5 次「重试 → 12 秒超时」,最后给出一个与真因无关的
// 「下载失败,已重试 N 次」。
transferAbortReason = message
downloadStatusText?.apply {
text = "QFT 本地网络已断开,正在结束当前下载请求…"
setTextColor(WARNING)
@@ -716,22 +739,25 @@ class MainActivity : ComponentActivity() {
root.addView(space(14))
root.addView(card().apply {
addView(text("选择文件", 17f, Color.WHITE, true))
sendFilesText = text("尚未选择文件", 14f, MUTED)
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
addView(sendFilesText, matchWrap(top = 8))
addView(button("选择文件(可多选)").apply {
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
setOnClickListener { showFileSelection(pair, baseUrl) }
}, matchWrap(top = 12))
})
root.addView(space(14))
root.addView(card().apply {
addView(text("传输进度", 17f, Color.WHITE, true))
sendStatusText = text("选择文件后点击开始传输", 14f, MUTED)
sendStatusText = text("请先选择需要传输的文件,再点击“开始传输”", 14f, WARNING)
addView(sendStatusText, matchWrap(top = 8))
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 = selectedFiles.isNotEmpty()
setOnClickListener { startUploads(pair, baseUrl) }
sendButton = button("选择传输文件").apply {
isEnabled = connectedBaseUrl != null
setOnClickListener {
if (selectedFiles.isEmpty()) showFileSelection(pair, baseUrl)
else startUploads(pair, baseUrl)
}
}
addView(sendButton, matchWrap(top = 14))
})
@@ -765,9 +791,13 @@ class MainActivity : ComponentActivity() {
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
downloadRunning = true
transferAbortReason = null
transferExecutor.execute {
// 「传输 / 校验 / 保存」三个阶段各自的速率含义不同,
// 每进入一个新阶段就重新计时,否则显示出来的速率毫无意义。
var phaseLabel = "正在接收"
var phaseStartedAt = android.os.SystemClock.elapsedRealtime()
try {
val startedAt = android.os.SystemClock.elapsedRealtime()
val saved = DownloadClient.download(
context = this@MainActivity,
resolver = contentResolver,
@@ -775,13 +805,19 @@ class MainActivity : ComponentActivity() {
baseUrl = baseUrl,
pairing = pair,
deviceName = receiverDeviceLabel,
abortReason = { transferAbortReason },
onPhase = { label ->
phaseLabel = label
phaseStartedAt = android.os.SystemClock.elapsedRealtime()
runOnUiThread { status.text = label }
},
) { received, expected ->
runOnUiThread {
val fraction = if (expected <= 0) 0 else ((received * 1000L) / expected).toInt().coerceIn(0, 1000)
val elapsed = (android.os.SystemClock.elapsedRealtime() - startedAt).coerceAtLeast(1L)
val elapsed = (android.os.SystemClock.elapsedRealtime() - phaseStartedAt).coerceAtLeast(1L)
val rate = received * 1000.0 / elapsed
bar.progress = fraction
status.text = "${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
status.text = "$phaseLabel ${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
}
}
runOnUiThread {
@@ -792,7 +828,9 @@ class MainActivity : ComponentActivity() {
} catch (e: Exception) {
runOnUiThread {
downloadRunning = false
showPairError(pair, "从电脑接收失败:${e.message}")
// 落盘失败时文件其实已经完整收到了,别再说「接收失败」误导用户
val prefix = if (e is DownloadClient.SaveFailure) "保存失败" else "从电脑接收失败"
showPairError(pair, "$prefix:${e.message}")
}
} finally {
downloadRunning = false
@@ -800,10 +838,118 @@ class MainActivity : ComponentActivity() {
}
}
private fun showReceivedFiles(message: String? = null) {
val root = pageColumn()
root.addView(text("接收文件柜", 28f, Color.WHITE, true))
root.addView(text("QFT 已保存到 Downloads/QFT 的文件", 14f, MUTED))
message?.let { root.addView(text(it, 13f, WARNING), matchWrap(top = 10)) }
root.addView(space(16))
val files = try {
ReceivedFileCabinet.list(this)
} catch (e: Exception) {
emptyList()
}
if (files.isEmpty()) {
root.addView(card().apply {
addView(text("文件柜为空", 17f, Color.WHITE, true))
addView(text("完成电脑下发或光学接收后,文件会自动出现在这里。", 14f, MUTED), matchWrap(top = 8))
})
} else {
root.addView(text("共 ${files.size} 个文件", 13f, ACCENT, true))
files.forEach { file ->
val entry = card()
entry.addView(text(file.name, 16f, Color.WHITE, true))
entry.addView(
text("${humanBytes(file.size)} · ${file.mimeType.ifBlank { "未知格式" }}", 12f, MUTED),
matchWrap(top = 5),
)
entry.addView(button("打开文件").apply {
setOnClickListener {
try {
ReceivedFileCabinet.open(this@MainActivity, file)
} catch (e: Exception) {
showReceivedFiles("无法打开 ${file.name}:请安装支持该格式的阅读器。")
}
}
}, matchWrap(top = 10))
root.addView(entry, matchWrap(bottom = 10))
}
}
root.addView(space(12))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
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") }
@@ -811,11 +957,17 @@ class MainActivity : ComponentActivity() {
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
}.trim()
}
sendButton?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null
sendButton?.text = if (selectedFiles.isEmpty()) "选择传输文件" else "开始传输"
sendButton?.isEnabled = connectedBaseUrl != null
}
private fun startUploads(pair: PairingPayload, baseUrl: String) {
if (selectedFiles.isEmpty()) return
if (selectedFiles.isEmpty()) {
sendStatusText?.setTextColor(WARNING)
sendStatusText?.text = "请先选择需要传输的文件"
showFileSelection(pair, baseUrl)
return
}
val files = selectedFiles.toList()
sendButton?.isEnabled = false
transferExecutor.execute {
@@ -0,0 +1,102 @@
package com.qft.optical
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import java.io.File
data class ReceivedFile(
val uri: Uri,
val name: String,
val size: Long,
val mimeType: String,
val modifiedAtSeconds: Long,
)
/** Lists only the files QFT has finished writing to Downloads/QFT. */
object ReceivedFileCabinet {
private const val RELATIVE_QFT_PATH = "Download/QFT/"
fun list(context: Context): List<ReceivedFile> =
if (Build.VERSION.SDK_INT >= 29) listModern(context.contentResolver) else listLegacy(context)
fun open(context: Context, file: ReceivedFile) {
val resolvedMime = mimeFor(file.name, file.mimeType)
val intent = Intent(Intent.ACTION_VIEW)
.setDataAndType(file.uri, resolvedMime)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(Intent.createChooser(intent, "打开 ${file.name}"))
}
private fun listModern(resolver: ContentResolver): List<ReceivedFile> {
val projection = arrayOf(
MediaStore.Downloads._ID,
MediaStore.Downloads.DISPLAY_NAME,
MediaStore.Downloads.SIZE,
MediaStore.Downloads.MIME_TYPE,
MediaStore.Downloads.DATE_MODIFIED,
)
val out = mutableListOf<ReceivedFile>()
resolver.query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
projection,
"${MediaStore.Downloads.RELATIVE_PATH}=? AND ${MediaStore.Downloads.IS_PENDING}=0",
arrayOf(RELATIVE_QFT_PATH),
"${MediaStore.Downloads.DATE_MODIFIED} DESC",
)?.use { cursor ->
val idIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID)
val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.SIZE)
val mimeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.MIME_TYPE)
val timeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DATE_MODIFIED)
while (cursor.moveToNext()) {
val id = cursor.getLong(idIndex)
val name = cursor.getString(nameIndex).orEmpty().ifBlank { "未命名文件" }
out += ReceivedFile(
uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, id),
name = name,
size = cursor.getLong(sizeIndex).coerceAtLeast(0L),
mimeType = cursor.getString(mimeIndex).orEmpty(),
modifiedAtSeconds = cursor.getLong(timeIndex),
)
}
}
return out
}
@Suppress("DEPRECATION")
private fun listLegacy(context: Context): List<ReceivedFile> {
val directory = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"QFT",
)
return directory.listFiles()
?.asSequence()
?.filter { it.isFile }
?.sortedByDescending { it.lastModified() }
?.map { file ->
ReceivedFile(
uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file),
name = file.name,
size = file.length().coerceAtLeast(0L),
mimeType = mimeFor(file.name, ""),
modifiedAtSeconds = file.lastModified() / 1000L,
)
}
?.toList()
.orEmpty()
}
private fun mimeFor(name: String, supplied: String): String {
if (supplied.isNotBlank() && supplied != "application/octet-stream") return supplied
val extension = name.substringAfterLast('.', "").lowercase()
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
}
}
@@ -5,6 +5,7 @@ import android.database.Cursor
import android.net.Network
import android.net.Uri
import android.provider.OpenableColumns
import android.util.Log
import org.json.JSONObject
import java.io.FileInputStream
import java.net.DatagramPacket
@@ -28,12 +29,16 @@ data class SelectedFile(
)
object UploadClient {
private const val TAG = "QftUpload"
private const val DISCOVERY_PORT = 39392
private const val CHUNK_SMALL = 4L * 1024L * 1024L
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
private const val CHUNK_LARGE = 16L * 1024L * 1024L
private const val MAX_WORKERS = 8
private const val STREAM_BUFFER = 1024 * 1024
// A single request is materially more reliable for small files on Wi-Fi
// Direct, and a 4 MiB parallel chunk gives no throughput benefit there.
private const val PARALLEL_MIN_FILE_SIZE = 32L * 1024L * 1024L
// QFT Direct can briefly reset a TCP flow while the Android network route
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
// the Windows receiver treats a repeated chunk as an idempotent success.
@@ -222,7 +227,7 @@ object UploadClient {
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
if (pairing.version >= 2 && isSeekable(resolver, file)) {
if (pairing.version >= 2 && file.size >= PARALLEL_MIN_FILE_SIZE && isSeekable(resolver, file)) {
try {
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
return
@@ -236,6 +241,7 @@ object UploadClient {
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
}
}
Log.i(TAG, "using single-stream upload: size=${file.size}, endpoint=$baseUrl")
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
}
@@ -248,6 +254,11 @@ object UploadClient {
return block()
} catch (e: Throwable) {
last = e
Log.w(
TAG,
"$label: attempt=${attempt + 1}/$LOCAL_REQUEST_ATTEMPTS, ${failureSummary(e)}",
e,
)
if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) {
try { Thread.sleep(120L * (attempt + 1)) } catch (_: InterruptedException) {
Thread.currentThread().interrupt()
@@ -256,7 +267,23 @@ object UploadClient {
}
}
}
throw IllegalStateException("$label after $LOCAL_REQUEST_ATTEMPTS attempts", last)
val failure = last ?: IllegalStateException("unknown local request failure")
throw IllegalStateException(
"$label,已重试 $LOCAL_REQUEST_ATTEMPTS 次:${failureSummary(failure)}",
failure,
)
}
private fun failureSummary(error: Throwable): String {
val chain = ArrayList<String>(3)
var current: Throwable? = error
while (current != null && chain.size < 3) {
val type = current.javaClass.simpleName.ifBlank { current.javaClass.name }
val detail = current.message?.replace(Regex("\\s+"), " ")?.take(240)
chain += if (detail.isNullOrBlank()) type else "$type: $detail"
current = current.cause
}
return chain.joinToString(" <- ")
}
private fun uploadParallel(
@@ -268,7 +295,9 @@ object UploadClient {
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
Log.i(TAG, "parallel init: size=${file.size}, endpoint=$baseUrl")
val init = initUpload(network, baseUrl, pairing, deviceName, file)
Log.i(TAG, "parallel init complete: chunks=${init.totalChunks}, chunkSize=${init.chunkSize}")
if (init.totalChunks == 0) {
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
onProgress(0, 0)
@@ -362,6 +391,7 @@ object UploadClient {
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
buffer: ByteBuffer,
) = retryLocalRequest("分块 $index 上传失败") {
Log.d(TAG, "chunk start: index=$index, bytes=$length, endpoint=$baseUrl")
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
try {
conn.requestMethod = "POST"
@@ -391,6 +421,7 @@ object UploadClient {
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
}
try { conn.inputStream.close() } catch (_: Exception) {}
Log.d(TAG, "chunk complete: index=$index, bytes=$length")
} finally {
conn.disconnect()
}
@@ -30,49 +30,79 @@ class WifiConnector(context: Context) {
private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null
/**
* 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。
* 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的
* WifiNetworkSpecifier 请求,不必 unregister —— 在系统选网弹窗还开着的
* 时候 unregister,Android 会弹「该应用已取消选择设备的请求」。
*/
private class Listener(
val onStatus: (String) -> Unit,
val onAvailable: (Network?) -> Unit,
val onUnavailable: (String) -> Unit,
)
private var listener: Listener? = null
private var pendingSsid: String? = null
private var pendingDelivered: AtomicBoolean? = null
private var pendingTerminal: AtomicBoolean? = null
private var pendingStartedAt = 0L
// 所有对外回调都只走这三个入口。直接调用捕获来的闭包会在「复用挂起请求」
// 时通知到上一次的界面,是很难查的一类 bug。
private fun notifyStatus(message: String) { listener?.onStatus?.invoke(message) }
private fun notifyAvailable(network: Network?) { listener?.onAvailable?.invoke(network) }
private fun notifyUnavailable(message: String) { listener?.onUnavailable?.invoke(message) }
fun connect(
pairing: PairingPayload,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
val wifi = pairing.wifi
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
// 千万不要 unregister 再重新 requestNetwork。
if (wifi != null && callback != null && pendingSsid == wifi.ssid &&
pendingTerminal?.get() == false && pendingDelivered?.get() == false) {
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
listener = Listener(onStatus, onAvailable, onUnavailable)
notifyStatus("系统配网请求仍在进行中,正在继续等待…")
scheduleWaitHints(generation, wifi.ssid)
return
}
release(restoreLegacy = false)
generation++
val run = generation
val wifi = pairing.wifi
listener = Listener(onStatus, onAvailable, onUnavailable)
if (wifi == null) {
onStatus("正在使用当前局域网发现电脑…")
notifyStatus("正在使用当前局域网发现电脑…")
val wifiNetwork = bestWifiNetwork()
onAvailable(wifiNetwork ?: connectivity.activeNetwork)
notifyAvailable(wifiNetwork ?: connectivity.activeNetwork)
return
}
if (Build.VERSION.SDK_INT >= 29) {
connectModern(run, wifi, onStatus, onAvailable, onUnavailable)
connectModern(run, wifi)
} else {
connectLegacy(run, wifi, onStatus, onAvailable, onUnavailable)
connectLegacy(run, wifi)
}
}
@RequiresApi(29)
@Suppress("MissingPermission")
private fun connectModern(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("正在请求连接 ${wifi.ssid}…")
private fun connectModern(run: Int, wifi: WifiCredentials) {
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
onStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
notifyStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
val specifier = try {
WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.build()
} catch (e: Exception) {
onUnavailable("配网参数无效:${e.message}")
notifyUnavailable("配网参数无效:${e.message}")
return
}
val request = NetworkRequest.Builder()
@@ -86,16 +116,22 @@ class WifiConnector(context: Context) {
// launching a duplicate probe/download for the same Wi-Fi connection.
val delivered = AtomicBoolean(false)
val terminal = AtomicBoolean(false)
pendingSsid = wifi.ssid
pendingDelivered = delivered
pendingTerminal = terminal
pendingStartedAt = SystemClock.elapsedRealtime()
val startedAt = pendingStartedAt
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (run != generation || terminal.get()) return
Log.i(TAG, "attempt=$run framework onAvailable network=$network")
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, onStatus) {
notifyStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, ::notifyStatus) {
if (run == generation && !terminal.get() && delivered.compareAndSet(false, true)) {
Log.i(TAG, "attempt=$run route ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
notifyAvailable(network)
}
}
}
@@ -104,21 +140,33 @@ class WifiConnector(context: Context) {
if (run != generation || terminal.get() || delivered.get()) return
if (hasIpv4(linkProperties) && delivered.compareAndSet(false, true)) {
Log.i(TAG, "attempt=$run IPv4 ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
notifyAvailable(network)
}
}
override fun onUnavailable() {
if (run != generation || !terminal.compareAndSet(false, true)) return
Log.w(TAG, "attempt=$run framework onUnavailable")
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。")
val waited = SystemClock.elapsedRealtime() - startedAt
Log.w(TAG, "attempt=$run framework onUnavailable after ${waited}ms")
// Android 不区分「用户点了取消」和「始终没扫到这个热点」,
// 只能用等待时长推断,给出真正能指导用户下一步的提示。
notifyUnavailable(
if (waited < 4_000L) {
"已取消系统配网。请重新点击「重试连接」,并在系统弹窗里选择 ${wifi.ssid} 后点连接。"
} else {
"系统始终没有搜索到热点 ${wifi.ssid}。请确认:" +
"① 电脑上 QFT 接收页仍开着且显示 Direct 已启动;" +
"② 手机 Wi-Fi 列表里能看到这个名字;" +
"③ 电脑与手机距离不要太远。"
}
)
}
override fun onLost(network: Network) {
if (run != generation || !delivered.get() || !terminal.compareAndSet(false, true)) return
Log.w(TAG, "attempt=$run network lost network=$network")
if (run == generation && delivered.get()) onUnavailable("QFT 临时网络已断开")
notifyUnavailable("QFT 临时网络已断开")
}
}
callback = cb
@@ -130,26 +178,37 @@ class WifiConnector(context: Context) {
// system sheet; otherwise keep this request alive while our page
// continues to show connection progress.
connectivity.requestNetwork(request, cb)
handler.postDelayed({
if (run == generation && !terminal.get() && !delivered.get()) {
onStatus("仍在等待系统完成配网…")
}
}, 8_000)
scheduleWaitHints(run, wifi.ssid)
} catch (e: Exception) {
callback = null
onUnavailable("系统配网请求失败:${e.message}")
pendingSsid = null
notifyUnavailable("系统配网请求失败:${e.message}")
}
}
/**
* 弹窗久久不出结果时逐级给出更具体的提示。
* 截图里那种「弹窗一直转圈」的情况,光说「仍在等待系统完成配网」
* 完全没有指导意义——真正的原因通常是电脑侧热点没起来。
*/
private fun scheduleWaitHints(run: Int, ssid: String) {
fun pending(): Boolean =
run == generation && pendingTerminal?.get() == false && pendingDelivered?.get() == false
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
}, 8_000)
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke(
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +
"多半是电脑侧热点没启动——请检查 Windows 上 QFT 接收页是否显示 Direct 已就绪。"
)
}, 20_000)
}
@Suppress("DEPRECATION", "MissingPermission")
private fun connectLegacy(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
private fun connectLegacy(run: Int, wifi: WifiCredentials) {
notifyStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
try {
if (!wifiManager.isWifiEnabled) {
wifiManager.isWifiEnabled = true
@@ -168,13 +227,13 @@ class WifiConnector(context: Context) {
wifiManager.addNetwork(config)
}
if (targetId < 0) {
onUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
notifyUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
return
}
legacyTargetNetworkId = targetId
wifiManager.disconnect()
if (!wifiManager.enableNetwork(targetId, true)) {
onUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
notifyUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
return
}
wifiManager.reconnect()
@@ -186,20 +245,20 @@ class WifiConnector(context: Context) {
if (matches) {
val network = bestWifiNetwork()
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
onStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
notifyAvailable(network)
return
}
}
if (SystemClock.elapsedRealtime() - started > 15_000) {
onUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
notifyUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
} else {
handler.postDelayed({ poll() }, 250)
}
}
handler.postDelayed({ poll() }, 250)
} catch (e: Exception) {
onUnavailable("Android 7~9 配网失败:${e.message}")
notifyUnavailable("Android 7~9 配网失败:${e.message}")
}
}
@@ -316,6 +375,10 @@ class WifiConnector(context: Context) {
try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {}
}
callback = null
listener = null
pendingSsid = null
pendingDelivered = null
pendingTerminal = null
handler.removeCallbacksAndMessages(null)
if (restoreLegacy && Build.VERSION.SDK_INT < 29) {
val previous = legacyPreviousNetworkId
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="qft_downloads" path="Download/QFT/" />
</paths>
+2 -2
View File
@@ -1,4 +1,4 @@
# QFT protocol notes — v0.4.0-rc2
# QFT protocol notes — v0.4.6
## 1. Windows → Android optical: QFT2
@@ -36,7 +36,7 @@ senderLen 2 u16 BE
senderDevice N UTF-8
```
### Optical parameters in rc2
### Optical parameters in v0.4.6
- one QR per display frame;
- DATA payload: **450 B**;
+76 -64
View File
@@ -7,35 +7,35 @@
objects = {
/* Begin PBXBuildFile section */
0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */; };
38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5459D124A555B0E4121361E5 /* PairingProtocol.swift */; };
4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */; };
554512A1FC8A6F66E2784787 /* QFTApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 453B172D654B3AEDE4E36D1E /* QFTApp.swift */; };
6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */; };
78FD5CF5E04D7E2483B90BAA /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */; };
978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA81C375609633BD8DB42F3 /* DownloadClient.swift */; };
A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD16686BB19417EDC0B611A /* PeerLink.swift */; };
BDCF0D82F0BD0328770A8ABD /* ScannerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3B15455554D7647B44D5038 /* ScannerView.swift */; };
C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C628A05E9C83375781E165EB /* Assets.xcassets */; };
E26487D1146FDF6DD5F92D80 /* TransferModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3017489412A6FCAE8995B32E /* TransferModel.swift */; };
EE5510DAC5BBB7F9D41A8F26 /* Base64URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848334DC6B2D30622C7E2A45 /* Base64URL.swift */; };
38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5459D124A555B0E4121361E5 /* PairingProtocol.swift */; };
6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */; };
978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA81C375609633BD8DB42F3 /* DownloadClient.swift */; };
0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */; };
4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */; };
A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD16686BB19417EDC0B611A /* PeerLink.swift */; };
C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C628A05E9C83375781E165EB /* Assets.xcassets */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
928818DCDA72C62B2D8288D5 /* QFT.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QFT.app; sourceTree = BUILT_PRODUCTS_DIR; };
453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = "<group>"; };
0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = "<group>"; };
3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = "<group>"; };
848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = "<group>"; };
5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = "<group>"; };
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = "<group>"; };
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = "<group>"; };
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadClient.swift; sourceTree = "<group>"; };
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerPairing.swift; sourceTree = "<group>"; };
8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = "<group>"; };
C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = "<group>"; };
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = "<group>"; };
453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = "<group>"; };
5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = "<group>"; };
7E4A60F8CA5D515103446ED3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = "<group>"; };
8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = "<group>"; };
928818DCDA72C62B2D8288D5 /* QFT.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QFT.app; sourceTree = BUILT_PRODUCTS_DIR; };
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadClient.swift; sourceTree = "<group>"; };
C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = "<group>"; };
F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -60,20 +60,6 @@
path = App;
sourceTree = "<group>";
};
EC599E8CF455428A5E3179CE /* Core */ = {
isa = PBXGroup;
children = (
848334DC6B2D30622C7E2A45 /* Base64URL.swift */,
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */,
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */,
5459D124A555B0E4121361E5 /* PairingProtocol.swift */,
8DD16686BB19417EDC0B611A /* PeerLink.swift */,
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */,
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */,
);
path = Core;
sourceTree = "<group>";
};
36EDFB66685EBD501D3910CE /* QFT */ = {
isa = PBXGroup;
children = (
@@ -101,12 +87,26 @@
name = Products;
sourceTree = "<group>";
};
EC599E8CF455428A5E3179CE /* Core */ = {
isa = PBXGroup;
children = (
848334DC6B2D30622C7E2A45 /* Base64URL.swift */,
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */,
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */,
5459D124A555B0E4121361E5 /* PairingProtocol.swift */,
8DD16686BB19417EDC0B611A /* PeerLink.swift */,
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */,
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */,
);
path = Core;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
497CBF7ECF21FFA362230876 /* QFT */ = {
isa = PBXNativeTarget;
buildConfigurationList = A886B50DF087AEF7B87CDC65;
buildConfigurationList = A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */;
buildPhases = (
C2511B36F0F0E810A9E46328 /* Sources */,
019BAB185F97B56993A7087D /* Frameworks */,
@@ -136,7 +136,7 @@
};
};
};
buildConfigurationList = 26E84C2B3712F7DFAC8AD93F;
buildConfigurationList = 26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
@@ -188,6 +188,29 @@
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
032222C0BAA33BC7119DFAF1 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 46;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.4.6;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
70DCC1EB255A5F3C8D9ED349 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -203,8 +226,11 @@
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1 $(inherited)";
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -215,25 +241,6 @@
};
name = Debug;
};
DB189EBE9D4E38495C3C7EF5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 0.1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
C3DCEEC1E0EB17A5583B8E94 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -248,9 +255,10 @@
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_VERSION = 5.0;
@@ -258,29 +266,33 @@
};
name = Release;
};
032222C0BAA33BC7119DFAF1 /* Release */ = {
DB189EBE9D4E38495C3C7EF5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 46;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 0.1.0;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.4.6;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
name = Debug;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
26E84C2B3712F7DFAC8AD93F = {
26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */ = {
isa = XCConfigurationList;
buildConfigurations = (
70DCC1EB255A5F3C8D9ED349 /* Debug */,
@@ -289,7 +301,7 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A886B50DF087AEF7B87CDC65 = {
A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */ = {
isa = XCConfigurationList;
buildConfigurations = (
DB189EBE9D4E38495C3C7EF5 /* Debug */,
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
+1 -1
View File
@@ -1,4 +1,4 @@
# QFT iOS 客户端 v0.1.0
# QFT iOS 客户端 v0.4.6
三种传输方式:
+2 -2
View File
@@ -19,7 +19,7 @@ IOS_ROOT = os.path.dirname(HERE)
APP_NAME = "QFT"
BUNDLE_ID = "com.qft.transfer"
DEPLOYMENT_TARGET = "17.0"
MARKETING_VERSION = "0.1.0"
MARKETING_VERSION = "0.4.6"
SOURCES = [
"QFT/App/QFTApp.swift",
@@ -280,7 +280,7 @@ def generate():
"ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon",
"ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor",
"CODE_SIGN_STYLE = Automatic",
"CURRENT_PROJECT_VERSION = 1",
"CURRENT_PROJECT_VERSION = 46",
"ENABLE_PREVIEWS = YES",
"GENERATE_INFOPLIST_FILE = NO",
"INFOPLIST_FILE = QFT/Info.plist",
+1 -1
View File
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qft-windows"
version = "0.4.0-rc6"
version = "0.4.6"
dependencies = [
"anyhow",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "qft-windows"
version = "0.4.0-rc6"
version = "0.4.6"
edition = "2024"
rust-version = "1.95"
+1 -1
View File
@@ -23,7 +23,7 @@ use std::{
// a nominally larger page that is only decoded 10~18 times per second.
const DEFAULT_CHUNK_SIZE: u16 = 320;
const UI_FONT_NAME: &str = "qft-ui";
const APP_VERSION: &str = "0.4.0-rc6";
const APP_VERSION: &str = "0.4.6";
fn main() -> eframe::Result {
let options = eframe::NativeOptions {
+65
View File
@@ -169,6 +169,11 @@ fn handle_client(
sessions: &SessionMap,
completed: &CompletedMap,
) -> Result<()> {
// The listener is non-blocking so the UI can poll for shutdown. On
// Windows an accepted socket may retain that mode, which made a body read
// race the next Wi-Fi Direct packet and fail with WSAEWOULDBLOCK (10035).
// File requests must instead wait under the explicit socket timeouts.
stream.set_nonblocking(false)?;
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
@@ -572,3 +577,63 @@ fn hex(bytes: &[u8]) -> String {
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
io::{Read, Write},
net::TcpListener,
sync::mpsc,
time::{SystemTime, UNIX_EPOCH},
};
#[test]
fn legacy_upload_waits_for_a_delayed_body_on_a_nonblocking_accepted_socket() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let dir = std::env::temp_dir().join(format!(
"qft-receiver-test-{}-{}",
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(),
));
fs::create_dir_all(&dir).unwrap();
let dir_for_server = dir.clone();
let (events, _updates) = mpsc::channel();
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
// This matches the Windows mode inheritance that previously made
// the body read return WSAEWOULDBLOCK between TCP packets.
stream.set_nonblocking(true).unwrap();
handle_client(
&mut stream,
&dir_for_server,
"session",
&events,
&sessions,
&completed,
)
});
let mut client = TcpStream::connect(address).unwrap();
client
.write_all(
b"POST /qft/upload HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nContent-Length: 4\r\nX-QFT-Size: 4\r\n\r\n",
)
.unwrap();
client.flush().unwrap();
thread::sleep(Duration::from_millis(50));
client.write_all(b"qft!").unwrap();
client.flush().unwrap();
let mut response = String::new();
client.read_to_string(&mut response).unwrap();
server.join().unwrap().unwrap();
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
assert_eq!(fs::read(dir.join("qft-upload.bin")).unwrap(), b"qft!");
let _ = fs::remove_dir_all(dir);
}
}