diff --git a/.gitignore b/.gitignore
index 0ed5ad6..8dff8e0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,10 @@ local.properties
# OS
.DS_Store
Thumbs.db
+# 标定工具产物(wedge_gen.py 默认输出目录)
+/out
+# Xcode
+ios/**/xcuserdata/
+ios/**/*.xcworkspace/xcuserdata/
+ios/build/
+DerivedData/
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
index 27dbe36..44310cd 100644
--- a/android/app/build.gradle.kts
+++ b/android/app/build.gradle.kts
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
- versionCode = 16
- versionName = "0.4.0-rc8"
+ versionCode = 17
+ versionName = "0.4.0-rc9"
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")
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 01c4d7b..b88be45 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -19,6 +19,15 @@
android:label="QFT"
android:supportsRtl="true"
android:theme="@style/QftTheme">
+
+
+
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,21 +233,30 @@ 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(
@@ -176,6 +264,7 @@ object DownloadClient {
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("保存下载文件时大小发生变化")
diff --git a/android/app/src/main/java/com/qft/optical/MainActivity.kt b/android/app/src/main/java/com/qft/optical/MainActivity.kt
index 510e4f5..fea790a 100644
--- a/android/app/src/main/java/com/qft/optical/MainActivity.kt
+++ b/android/app/src/main/java/com/qft/optical/MainActivity.kt
@@ -79,6 +79,8 @@ class MainActivity : ComponentActivity() {
private var connectedNetwork: Network? = null
private var connectedBaseUrl: String? = null
private val selectedFiles = mutableListOf()
+ 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,6 +184,13 @@ 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))
@@ -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 {
diff --git a/android/app/src/main/java/com/qft/optical/ReceivedFileCabinet.kt b/android/app/src/main/java/com/qft/optical/ReceivedFileCabinet.kt
new file mode 100644
index 0000000..656c08a
--- /dev/null
+++ b/android/app/src/main/java/com/qft/optical/ReceivedFileCabinet.kt
@@ -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 =
+ 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 {
+ val projection = arrayOf(
+ MediaStore.Downloads._ID,
+ MediaStore.Downloads.DISPLAY_NAME,
+ MediaStore.Downloads.SIZE,
+ MediaStore.Downloads.MIME_TYPE,
+ MediaStore.Downloads.DATE_MODIFIED,
+ )
+ val out = mutableListOf()
+ 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 {
+ 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"
+ }
+}
diff --git a/android/app/src/main/java/com/qft/optical/UploadClient.kt b/android/app/src/main/java/com/qft/optical/UploadClient.kt
index 5f59201..910a043 100644
--- a/android/app/src/main/java/com/qft/optical/UploadClient.kt
+++ b/android/app/src/main/java/com/qft/optical/UploadClient.kt
@@ -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(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()
}
diff --git a/android/app/src/main/java/com/qft/optical/WifiConnector.kt b/android/app/src/main/java/com/qft/optical/WifiConnector.kt
index 4849bb7..935cc0a 100644
--- a/android/app/src/main/java/com/qft/optical/WifiConnector.kt
+++ b/android/app/src/main/java/com/qft/optical/WifiConnector.kt
@@ -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
diff --git a/android/app/src/main/res/xml/qft_file_paths.xml b/android/app/src/main/res/xml/qft_file_paths.xml
new file mode 100644
index 0000000..6ca1580
--- /dev/null
+++ b/android/app/src/main/res/xml/qft_file_paths.xml
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/docs/OPTICAL_V5_PLAN.md b/docs/OPTICAL_V5_PLAN.md
new file mode 100644
index 0000000..11d5466
--- /dev/null
+++ b/docs/OPTICAL_V5_PLAN.md
@@ -0,0 +1,433 @@
+# QFT5 光学链路方案(黑白 · 位阵列 · 陀螺仪稳定)
+
+目标:
+- **A**:相机 24 FPS 下,1 MB < 5 s(≥ 209.7 KB/s)
+- **B**:相机 50~60 FPS 下,10 MB < 10 s(≥ 1048.6 KB/s)
+- 相机帧率自动取系统最高值并锁死、稳定
+- 手持抖动不导致丢锁重捕获
+
+全程纯黑白(二值),不使用彩色或灰阶调制。
+
+---
+
+## 0. 选型结论:必须放弃 QR
+
+| 方案 | B/画布 | @24fps | @60fps | 目标A | 目标B |
+|---|---|---|---|---|---|
+| QR 2×1 v40 @720p | 5 729 | 130 KB/s | 325 KB/s | 7.9 s ❌ | 32 s ❌ |
+| QR 3×1 v40 @1080p | 8 593 | 193 KB/s | 463 KB/s | 5.3 s ❌ | 22.1 s ❌ |
+| 位阵列 3.5 px/模块 @1080p | 15 571 | 350 KB/s | 839 KB/s | 2.9 s ✅ | 12.2 s ❌ |
+| **位阵列 3.0 px/模块 @1080p** | **21 209** | 477 KB/s | **1143 KB/s** | **2.5 s ✅** | **9.0 s ✅** |
+
+原因:QR 单符号上限 v40 = 177 模块。在 1080p 取景下相机能分辨约 330 模块/边,
+单个 QR 只能用掉约 40% 的像素预算;横向排 3 个又受 16:9 宽度限制。
+QR-L 本身还要付 finder/timing/format/RS 约 14% 的结构开销。
+
+位阵列取消这三项限制:无版本上限、无 finder 图案、纠错交给喷泉码。
+代价是不能再用 ZXing,需要自研采样解码器(见 §3.6,实际比 RS 解码更简单)。
+
+**硬件前提(不满足则目标 B 无法达成,需在 App 内检测并提示):**
+- 手机后摄支持 **1920×1080 ImageAnalysis @ 60 FPS**(用 `getOutputMinFrameDuration` 实测,非 flagship 常见只有 1080p30)
+- 显示器 **≥ 60 Hz**,画布区可用宽度 **≥ 1824 逻辑像素**(3 显示 px/模块 × 608 模块)
+- 取景需填满约 95% 画面 → 目标 B 建议使用支架
+
+---
+
+## 1. 需求一:相机帧率的获取、锁定与稳定
+
+### 1.1 现有实现的三个缺陷
+
+`MainActivity.chooseCameraFpsPlan()`(约 452 行):
+
+1. **只读 `CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES`,没有按目标分辨率校验。**
+ 该表是相机级能力,与具体输出尺寸无关。1080p 常见只支持 30 FPS,而 720p 支持 60。
+ 现在的代码会对 1080p 请求一个它根本达不到的 `[60,60]`,结果要么被拒(走 fallback
+ 丢失全部控制),要么被静默降频。
+ → 必须用 `StreamConfigurationMap.getOutputMinFrameDuration(ImageFormat.YUV_420_888, size)`
+ 算出**该尺寸的真实上限** `1e9 / minFrameDuration`,再与 AE 表求交集。
+
+2. **没有优先选固定区间。** 排序是 `upper` 降序,所以 `[15,60]` 会排在 `[30,30]` 前面被选中。
+ 可变区间授权 AE 在光线不足时把帧率降到 `lower`——这正是"不稳定"的根源。
+ → 必须优先 `lower == upper` 的固定区间。
+
+3. **没有验证实际达成帧率。** 请求 ≠ 实际。
+
+### 1.2 三级锁定策略
+
+```
+L1 固定 AE 区间 CONTROL_AE_TARGET_FPS_RANGE = [max, max]
+ ↓ 实测不达标
+L2 全手动曝光(推荐) CONTROL_AE_MODE = OFF
+ SENSOR_FRAME_DURATION = 1e9 / fps
+ SENSOR_EXPOSURE_TIME = 2~4 ms
+ SENSOR_SENSITIVITY = ISO 200~400(按实测亮度标定一次)
+ ↓ 设备拒绝该组合
+L3 回退设备默认 + 降级目标(告知用户目标 B 不可达)
+```
+
+**L2 是真正的"锁死"**,也是本方案的推荐路径:屏幕是自发光强光源,2~4 ms 曝光完全够用;
+AE 关闭后帧间隔由 `SENSOR_FRAME_DURATION` 精确决定,不再受测光波动影响。
+更重要的是——**短曝光同时是防抖的第一杠杆**(见 §2.1)。
+
+标定流程:启动时用 AE 自动跑 10 帧,读回 `CaptureResult` 的
+`SENSOR_EXPOSURE_TIME` × `SENSOR_SENSITIVITY` 乘积作为曝光量基准,
+再按"曝光缩到 3 ms、ISO 等比放大并夹到设备 `SENSOR_INFO_SENSITIVITY_RANGE` 上限"求解,
+之后切 `AE_MODE_OFF` 固定住。
+
+### 1.3 必须关闭 / 必须开启
+
+| 项 | 设置 | 理由 |
+|---|---|---|
+| `CONTROL_VIDEO_STABILIZATION_MODE` | **OFF** | EIS 会逐帧裁切+几何形变,直接破坏单应矩阵跟踪 |
+| `CONTROL_AE_ANTIBANDING_MODE` | **OFF** | 50 Hz 抗闪烁会把曝光量化到 10 ms 整数倍,与 2~4 ms 短曝光直接冲突,并把帧率钉死 |
+| `NOISE_REDUCTION_MODE` | **OFF / FAST** | 强降噪会抹平单像素级模块边界 |
+| `EDGE_MODE` | **OFF / FAST** | 锐化会产生振铃,制造伪模块边缘 |
+| `LENS_OPTICAL_STABILIZATION_MODE` | **ON** | OIS 是光学补偿,不改成像几何,纯收益 |
+| `CONTROL_AF_MODE` | 锁定后 **OFF** + 固定 `LENS_FOCUS_DISTANCE` | 连续 AF 每次搜索都产生几帧模糊 |
+
+现有代码用 `AF_MODE_CONTINUOUS_PICTURE`(MainActivity 约 306 行)并在稳定锁定时
+还周期性重新触发对焦(约 272 行)——对着固定距离的屏幕,这是纯负收益,必须改掉。
+
+### 1.4 闭环验证("稳定下来"的判据)
+
+用 `CaptureResult.SENSOR_TIMESTAMP` 做差分,滑动窗口 60 帧:
+
+```
+p50(Δt) → 实际帧率
+p95(Δt) / p50(Δt) > 1.30 → 判定"不稳定",降一档重试
+丢帧率 = count(Δt > 1.5 × p50) / N
+```
+
+三档实测都不稳定时,把目标降到"尽力而为"模式并在 UI 明示。
+实测帧率必须回传给 Windows 端(通过配对二维码之外的一次性握手,或让用户手动选档),
+**Windows 显示帧率 = 手机实测相机帧率**(见 §3.3,无需更精细的同步)。
+
+---
+
+## 2. 需求二:防抖 / 锁定不丢失
+
+现有实现是"轴对齐矩形 + `smoothToward` 平滑 + 连续 miss 逐级扩大 + 10 次 miss 全幅重搜"
+(`QrAnalyzer.decodeOptical` / `LockRect`)。三个结构性问题:
+
+- 轴对齐矩形无法表达旋转与透视,手一歪矩形就被迫变大,分析面积和解码成本同时上升;
+- ROI 只在**解码成功后**才更新,一旦 miss 就完全没有状态推进(无航位推算);
+- 恢复策略是"扩大并祈祷"。
+
+### 2.1 第一杠杆:短曝光(量化)
+
+1080p、65° FOV → 等效焦距 **f ≈ 1507 px/rad**。运动模糊长度 = ω × t_exposure × f。
+
+| 手持角速度 | 曝光 33 ms(自动) | 8 ms | 4 ms | 2 ms |
+|---|---|---|---|---|
+| 3 °/s(平稳) | 2.60 px = 0.87 模块 ❌ | 0.63 px ✅ | 0.32 px ✅ | 0.16 px ✅ |
+| 10 °/s(典型手持) | **8.68 px = 2.89 模块 ❌** | 2.10 px ❌ | 1.05 px ⚠️ | 0.53 px ✅ |
+| 20 °/s(明显晃动) | 17.36 px ❌ | 4.21 px ❌ | 2.10 px ❌ | 1.05 px ⚠️ |
+
+**在 3 px/模块下,自动曝光的 33 ms 会抹掉近 3 个模块——必然解不出。**
+这解释了当前"识别率不高"的相当一部分。锁到 2~4 ms 后模糊降到 1 px 以内。
+判据:`blur = ω · t_exp · f < 0.7 模块`。
+
+### 2.2 第二杠杆:陀螺仪前馈(真正的"防抖")
+
+60 FPS 下 10 °/s 的帧间像素位移 = **4.4 px**,看似很小,但连续 10 帧漂移 44 px,
+远超 `smoothToward` 的跟随带宽——这就是丢锁的直接机理。陀螺仪可以**提前**算出这个位移。
+
+```
+SensorManager.registerListener(TYPE_GYROSCOPE_UNCALIBRATED, SENSOR_DELAY_FASTEST) // ~200 Hz
+环形缓冲 (timestampNanos, ωx, ωy, ωz)
+
+对每个相机帧 t:
+ 1. 校验 SENSOR_INFO_TIMESTAMP_SOURCE == REALTIME,
+ 使 ImageProxy.imageInfo.timestamp 与陀螺时间戳同域(elapsedRealtimeNanos)
+ 2. 积分 [t-1, t] 区间的角速度 → Δθ = (Δθx, Δθy, Δθz)
+ 3. 小角近似的图像位移:
+ dx ≈ -f · Δθy dy ≈ f · Δθx roll ≈ Δθz
+ (需按 sensorOrientation / 显示旋转做一次坐标系映射)
+ 4. 用 dx, dy, roll 预推上一帧的 4 个角标位置
+ 5. 只在预测点 ±12 px 的窗口内做角标模板匹配
+```
+
+效果:搜索窗从"全幅" 降到 4 个 25×25 px 的小窗,即使剧烈晃动也能保持跟踪。
+陀螺仪对**旋转**敏感,而手持抖动在 30 cm 距离上 90% 以上的像素位移来自旋转而非平移,
+所以纯陀螺前馈就足够,不需要 IMU 融合。
+
+### 2.3 第三杠杆:模糊门控
+
+在解码前用陀螺仪算曝光窗口内的模糊长度。若 `blur > 0.7 模块`,
+**直接跳过该帧的采样解码**,只更新位姿预测。省下的 CPU 留给清晰帧。
+这比"试着解、失败、扩大 ROI"的现有策略便宜一个数量级。
+
+### 2.4 跟踪 4 角单应,不跟踪矩形
+
+画布四角放**同心方环**基准标(比 QR finder 更抗透视,且可做亚像素质心定位),
+四边中点再各放一个辅助标 → 8 个点解 8-DOF 单应矩阵 H。
+
+- H 直接给出"画布坐标 → 图像坐标"的完整映射,倾斜/旋转/透视全部被吸收;
+- 采样时用 H 逆映射,**不需要把图像旋正**,省掉一次全帧变换;
+- 8 点冗余 → 遮挡 1~2 个标仍可解(最小二乘 + RANSAC 剔除)。
+
+### 2.5 永不完全丢锁:三级恢复
+
+```
+L1 窄窗跟踪 预测点 ±12 px 每帧,成本 ~4 × 625 px
+ ↓ 连续 3 帧失败
+L2 陀螺预测窗 预测点 ±40 px + 放宽阈值 成本 ~4 × 6400 px
+ ↓ 持续 0.5 s 失败
+L3 全幅重捕获 降采样 1/4 的粗搜 + 精定位
+```
+
+关键是**永远保留最后一次有效的 H**,L3 也以它为先验起点。
+现有的"10 次 miss 后 `lockRegion = null` 全量重来"必须删掉。
+
+### 2.6 诚实提醒
+
+目标 B(3.0 px/模块 @1080p60)在手持下几乎不可能长时间守住。
+App 应持续统计陀螺 RMS,超阈值时明确提示"请靠稳桌沿或使用支架",
+并在支架模式下自动切到更激进的参数档。目标 A(3.5 px/模块 @24fps)手持可行。
+
+---
+
+## 3. 需求三:QFT5 位阵列格式
+
+### 3.1 画布布局
+
+```
+┌─◎──────────────────────────────────────◎─┐ ◎ = 同心方环基准标(4 角 + 4 边中点)
+│ ▓▓░░▓░▓▓░ 帧序号条纹(上) ░▓░▓▓░░▓▓ │ 帧计数 8 bit,撕裂检测用
+├──────────────────────────────────────────┤
+│ 条带 0 ← 独立喷泉包(头 + 数据 + CRC)│
+│ 条带 1 │
+◎ 条带 … ◎ 共 12 条(@1080p 每条约 28 模块高)
+│ 条带 11 │
+├──────────────────────────────────────────┤
+│ ▓▓░░▓░▓▓░ 帧序号条纹(下) ░▓░▓▓░░▓▓ │
+└─◎──────────────────────────────────────◎─┘
+```
+
+@1080p / 3.0 px/模块 → **608 × 342 模块 = 207 936 模块/画布**
+减去基准标、条纹、参考网格(约 4%)与喷泉冗余(15%)→ **净 21 209 B/画布**。
+
+### 3.2 抗撕裂的水平条带设计(本方案的关键)
+
+卷帘快门自上而下扫描,读出耗时 T_r ≈ 16~20 ms。期间显示器换页会在某一行产生撕裂:
+上半部分是显示帧 k,下半部分是 k+1。
+
+**如果画布是一个整体(如单个大 QR),撕裂帧 100% 报废。**
+
+改成 12 条独立水平条带后,每条带自带头部(条带序号 + 喷泉种子 + CRC),于是:
+
+- 撕裂线只穿过 **1 条**条带 → 只损失 1/12;
+- 撕裂线上方的 11 条属于帧 k,下方的属于帧 k+1,**两边都是有效的新数据**;
+- 效率 = (B − T_r·f_display) / B。@60 FPS、T_r=16 ms、B=12 → **92%**。
+
+**推论:显示帧率直接设成相机帧率即可,不需要任何显示/相机同步机制。**
+这消除了整个方案里最难工程化的一环。
+
+(条带数 B 的选择:B 越大抗撕裂越好,但每条带的头部开销占比上升。
+B=12 时头部开销约 0.9%,是合理平衡点。)
+
+### 3.3 帧序号条纹(tear guard)
+
+上下各一条 8 格黑白条纹,编码同一个 8-bit 帧计数。解码时先读这 16 个采样点:
+
+- 上下一致 → 整帧属于同一显示帧,全部 12 条带可信;
+- 不一致 → 存在撕裂,用二分法在条带边界上定位撕裂行,只丢弃跨越它的那一条。
+
+成本:16 次采样。收益:把"撕裂帧全废"变成"损失 1/12"。
+
+### 3.4 参考模块网格(局部阈值)
+
+屏幕亮度不均、镜头暗角、moiré 会让全局阈值失效。
+每 **16×16 模块**嵌入一对已知的黑/白参考模块(开销 0.78%),解码时:
+
+```
+读取所有参考对 → 得到稀疏的 (black_level, white_level) 采样点
+→ 双线性插值出全画布的阈值面 threshold(x,y) = (black + white) / 2
+→ 每个数据模块与其所在位置的插值阈值比较
+```
+
+这同时天然抵抗屏幕 PWM 调光造成的整体亮度波动。
+
+### 3.5 喷泉码(条带级)
+
+每条带 = 一个独立喷泉包:
+
+```
+条带头(12 B):magic(2) | sessionId(4) | blockId(2) | seed(4)
+条带数据:~1 750 B
+CRC32(4 B)
+```
+
+- 文件按 **块(block)** 切分,每块 64 个源分片;
+- 编码包 = 块内随机子集的 XOR,参与集合由 `seed` 经约定 PRNG 还原;
+- 前 64 个包用系统码(原始分片本身),信道好时零解码开销;
+- 接收端每块维护 64×64 的 GF(2) 矩阵,高斯消元求解;
+- 冗余 15%(即平均收到 1.15×N 个包即可解出)。
+
+Windows 端可直接用 `raptorq` crate;Android 端建议自研分组 XOR + 高斯消元,
+两端算法必须逐位对齐(提供跨语言测试向量)。
+
+### 3.6 采样解码器(替代 ZXing)
+
+比 RS 解码更简单,纯整数运算:
+
+```
+1. tear guard 检查(16 次采样) → 决定丢弃哪条带
+2. 模糊门控(陀螺仪) → 可能直接跳过整帧
+3. 从跟踪状态取单应矩阵 H
+4. 读参考网格 → 插值阈值面
+5. 对每个模块:用 H 逆映射取中心点采样,与阈值比较 → 1 bit
+ (只取中心单点,不做邻域平均——3 px/模块下中心点信噪比已足够,速度快 3 倍)
+6. 逐条带校验 CRC32 → 通过的送入喷泉解码器
+```
+
+复杂度 O(模块数),@1080p 每帧 208 K 次采样。可用 NEON 向量化,
+或直接在 `ImageProxy` 的 Y 平面上按行做(内存访问连续)。
+实测预算:60 FPS 下约 12.5 M 采样/s,中端 SoC 单核即可,不需要 GPU。
+
+**并行结构**:`analyze()` 回调只做"按 H 计算 ROI 并 memcpy Y 平面"然后立即
+`image.close()` 返回;采样解码与喷泉解码交给 2~3 个 worker 线程。
+注意现有 `GrayFrameBuffer` 是单实例、非线程安全的,必须改成 per-worker 实例。
+
+---
+
+## 4. Windows 发送端
+
+### 4.1 显示管线(必须先修)
+
+现状:`qr.rs` 生成 1024×1024 的 `ColorImage`(RGBA)= **4 MiB/帧**,
+每帧 `texture.set()` 上传 GPU;`optical_cache.rs` 按 4 MiB/页 计算容量,
+最多占用 **768 MiB** 内存。60 FPS 下这是 240 MB/s 的分配与上传。
+
+改法:上传 **模块级纹理**(608×342 = 208 KB 灰度),用 `TextureOptions::NEAREST`
+让 GPU 放大。绘制矩形边长取模块数的整数倍(608 × 3 = 1824 px),避免不均匀缩放。
+
+- 纹理上传:4 MiB → 208 KB(**减少 95%**,且不随显示尺寸增长)
+- 预编码缓存:768 MiB → < 20 MiB
+- 60 FPS 变得毫无压力
+
+### 4.2 换页时序
+
+现有 `last_advance.elapsed() >= interval` 轮询会产生抖动。
+改为**按 vsync 计数换页**:60 Hz 屏每 1 个 vsync 换一页 = 精确 60 FPS;
+每 2 个 vsync 换一页 = 精确 30 FPS。保证每帧显示时长完全一致。
+
+### 4.3 显示器体检
+
+启动光学模式时检测:刷新率、画布区可用逻辑像素宽度、DPI 缩放。
+不满足"≥60 Hz 且 ≥1824 px"时,明确提示目标 B 不可达并给出当前档位的预计耗时。
+
+### 4.4 编码吞吐
+
+60 FPS × 21 KB = 1.27 MB/s 的 XOR + 位阵列打包。Rayon 并行下可忽略。
+
+---
+
+## 5. 分阶段落地
+
+| 阶段 | 内容 | 可验证指标 | 风险 |
+|---|---|---|---|
+| **P1** | Windows 模块级纹理 + vsync 换页 | 稳定 60.0 页/s,内存 < 50 MiB | 低 |
+| **P2** | 相机帧率三级锁定 + 闭环验证 + 关 EIS/抗闪烁 + 锁 AF | p95/p50 < 1.30,实测帧率 = 标称 | 低 |
+| **P3** | 手动曝光 2~4 ms + 陀螺仪前馈 + 模糊门控 | 10 °/s 晃动下不丢锁,模糊 < 1 px | 中 |
+| **P4** | QFT5 画布格式 + 单应跟踪 + 采样解码器 | 单帧 208 K 模块解码 < 12 ms | **高** |
+| **P5** | 条带喷泉码(两端对齐 + 跨语言测试向量) | 收包 1.15×N 即可还原 | 中 |
+| **P6** | 1080p60 + tear guard + 参数调优 | 目标 A / B 达标 | 中 |
+
+P1、P2 可以立刻做且零协议风险;P4 是主要工程量(估计是全部工作量的一半)。
+
+**建议在 P4 之前先做一个离线验证台**:Windows 端把画布导出成 PNG 序列,
+Android 端加一个"从相册读图解码"的调试入口,先在无相机噪声的条件下
+把采样解码器和喷泉码调通,再接实时相机。这能省掉大量难以复现的现场调试。
+
+---
+
+## 5.1 P0 · 分辨率楔形标定(已实现)
+
+上表所有数字都建立在一个未经实测的假设上:**px/模块 的真实下限**。
+合成实验显示这个值仅因对焦质量不同就能在 3.1~5.7 之间摆动,
+所以它必须先测出来,不能靠推算。工具已在 `scripts/` 下:
+
+```bash
+# 1. 生成标定图(尺寸填显示器的设备像素)
+python scripts/wedge_gen.py --width 1920 --height 1080 --out out/wedge
+
+# 2. 用浏览器打开 out/wedge.html,按 F11 全屏
+# 页面左上角必须显示「缩放 1.000 ✅」,否则测量无效
+
+# 3. 手机拍照:大致正立,四个黑色角标全部入画并尽量填满画面
+# 建议在 2~4 个不同距离各拍一张
+
+# 4. 分析
+python scripts/wedge_analyze.py --spec out/wedge.json --photo IMG_0001.jpg
+```
+
+输出每条带的 **实测 px/模块 → 对比度 → 误码率**,并给出 BER=1e-3 的临界点,
+以及按该临界点换算的画布净载荷与各帧率下的预计传输耗时。
+
+`--analysis-width` 默认 1920,即把 12MP 原片降采样到 1080p,模拟真实的
+ImageAnalysis 流;改成 1280 可直接对比 720p 分析流的能力差距。
+
+自检(合成相机模型,无需硬件):`python scripts/wedge_selftest.py`。
+
+### 标定结果如何反馈到本方案
+
+| 实测临界 px/模块 | 结论 |
+|---|---|
+| ≤ 2.6 | 目标 B 有余量,可考虑 §5.2 的六边形点阵进一步加码 |
+| 2.6 ~ 3.2 | 按本方案原样实施,目标 B 余量约 10% |
+| 3.2 ~ 4.0 | 目标 B 不可达;目标 A 仍可达。需下调指标或提高分析分辨率 |
+| > 4.0 | 光学链路能力远低于预期,应优先排查对焦/曝光(§1.2、§2.1) |
+
+### 一个必须修正的设计细节
+
+标定工具的误码率输出暴露了 §3.5 的一个缺口:**条带只有 CRC,没有内码**。
+1750 B 的条带有约 14 000 bit,只要 1 bit 错就整条报废。
+若要求带错率 < 13%(喷泉码 15% 冗余能承受的上限),
+原始 BER 必须低于 **1e-5**——这对光学信道是很苛刻的。
+
+因此条带内部必须加**内码**,形成"内码纠错 + 外层喷泉码纠删"的级联结构
+(与 QR 内部用 RS 是同一思路)。粗估所需冗余 ≈ 48 × BER:
+
+| 实测原始 BER | 内码冗余 |
+|---|---|
+| 1e-5 | 可省略 |
+| 1e-4 | ~0.5% |
+| 1e-3 | ~4.8% |
+| 1e-2 | ~48%(此工作点不可用) |
+
+`wedge_analyze.py` 已按此公式输出所需内码冗余,并计入净载荷估算。
+
+---
+
+## 6. 达标核算与回退
+
+### 达标条件(目标 B)
+```
+1080p ImageAnalysis @ 60 FPS × 21 209 B/画布 × 92% 撕裂效率
+= 1 143 KB/s → 10 MB / 9.0 s ✅(余量 10%)
+```
+余量只有 10%,任一环节退化都会掉出指标。必须全部满足:
+手机支持 1080p60 分析、显示器 ≥60 Hz、3.0 px/模块下解码成功率 > 95%、使用支架。
+
+### 达标条件(目标 A)
+```
+1080p @ 24 FPS × 15 571 B/画布(3.5 px/模块) × 96%
+= 350 KB/s → 1 MB / 2.9 s ✅(余量 42%)
+```
+余量充足,手持可行。**建议把 3.5 px/模块设为默认档。**
+
+### 回退阶梯
+App 应根据实测能力自动选档,并在 UI 明示当前档位与预计耗时:
+
+| 档位 | 分析分辨率 | px/模块 | 相机 FPS | 吞吐 | 适用 |
+|---|---|---|---|---|---|
+| 极速(支架) | 1080p | 3.0 | 60 | 1143 KB/s | 目标 B |
+| 标准(手持) | 1080p | 3.5 | 24~30 | 350~438 KB/s | 目标 A |
+| 保守 | 720p | 3.5 | 30 | 167 KB/s | 老设备 |
+| 兼容 | 720p | 4.0 | 30 | 128 KB/s | 最低保障 |
+
+### 何时不该用光学
+仓库已有 `QFTSEND2` 扫码直传(`windows/src/sender.rs`:HTTP + Range 续传 + UDP 发现),
+10 MB 在局域网下是亚秒级。光学链路应明确定位为**物理隔离场景专用**,
+并在选择大文件时主动提示直传方案与两者的预计耗时对比。
diff --git a/ios/CoreTests/Helpers.swift b/ios/CoreTests/Helpers.swift
new file mode 100644
index 0000000..0c7de41
--- /dev/null
+++ b/ios/CoreTests/Helpers.swift
@@ -0,0 +1,24 @@
+import Foundation
+import CryptoKit
+
+func sha256Hex(_ data: Data) -> String {
+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+}
+
+/// 从管道里读一行,带超时。用来等 MockPCServer 打印 `READY `。
+func readReadyLine(from handle: FileHandle, timeout: TimeInterval) -> String? {
+ let deadline = Date().addingTimeInterval(timeout)
+ var buffer = Data()
+ while Date() < deadline {
+ let available = handle.availableData
+ if available.isEmpty {
+ Thread.sleep(forTimeInterval: 0.02)
+ continue
+ }
+ buffer.append(available)
+ if let index = buffer.firstIndex(of: 0x0a) {
+ return String(data: buffer[buffer.startIndex.. --serve <文件> --save-dir <目录> --port 0
+启动后在 stdout 打印一行 `READY `,供测试脚本读取。
+"""
+
+import argparse
+import base64
+import hashlib
+import json
+import os
+import socket
+import sys
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+STATE = {}
+
+
+def b64url_decode(text):
+ padding = "=" * (-len(text) % 4)
+ return base64.urlsafe_b64decode(text + padding)
+
+
+def b64url_encode(data):
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
+
+
+class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *_args):
+ pass
+
+ # -------------------------------------------------- 工具
+
+ def _json(self, code, payload):
+ body = json.dumps(payload).encode("utf-8")
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Connection", "close")
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _authorized(self):
+ if self.headers.get("X-QFT-Token") != STATE["token"]:
+ self.send_response(403)
+ self.send_header("Content-Length", "0")
+ self.send_header("Connection", "close")
+ self.end_headers()
+ return False
+ # 设备名必须是 base64url,解不出来说明客户端编码错了
+ device = self.headers.get("X-QFT-Device")
+ if device is not None:
+ b64url_decode(device).decode("utf-8")
+ return True
+
+ # -------------------------------------------------- GET
+
+ def do_GET(self):
+ if not self._authorized():
+ return
+ if self.path == "/qft/ping":
+ return self._json(200, {"ok": True, "protocol": 2, "parallel": True})
+ if self.path == "/qft/download":
+ return self._download()
+ return self._json(404, {"ok": False})
+
+ def _download(self):
+ path = STATE["serve"]
+ size = os.path.getsize(path)
+ offset = 0
+ header = self.headers.get("Range")
+ if header:
+ assert header.startswith("bytes="), "只支持 bytes= 形式的 Range"
+ assert header.endswith("-"), "sender.rs 只支持单段开区间 Range"
+ offset = int(header[len("bytes="):-1])
+ assert 0 <= offset < size, "Range 越界"
+ remaining = size - offset
+
+ self.send_response(206 if offset else 200)
+ self.send_header("Content-Type", "application/octet-stream")
+ self.send_header("Content-Length", str(remaining))
+ self.send_header("Accept-Ranges", "bytes")
+ if offset:
+ self.send_header("Content-Range", "bytes %d-%d/%d" % (offset, size - 1, size))
+ self.send_header("X-QFT-Filename", b64url_encode(os.path.basename(path).encode("utf-8")))
+ self.send_header("Connection", "close")
+ self.end_headers()
+ with open(path, "rb") as fh:
+ fh.seek(offset)
+ while True:
+ block = fh.read(256 * 1024)
+ if not block:
+ break
+ self.wfile.write(block)
+
+ # -------------------------------------------------- POST
+
+ def do_POST(self):
+ if not self._authorized():
+ return
+ if self.path == "/qft/upload/init":
+ return self._upload_init()
+ if self.path.startswith("/qft/upload/chunk/"):
+ return self._upload_chunk()
+ if self.path.startswith("/qft/upload/finish/"):
+ return self._upload_finish()
+ return self._json(404, {"ok": False})
+
+ def _upload_init(self):
+ name = b64url_decode(self.headers["X-QFT-Filename"]).decode("utf-8")
+ size = int(self.headers["X-QFT-Size"])
+ chunk_size = int(self.headers.get("X-QFT-Chunk-Size", 8 * 1024 * 1024))
+ chunk_size = max(1024 * 1024, min(16 * 1024 * 1024, chunk_size))
+ total = 0 if size == 0 else (size + chunk_size - 1) // chunk_size
+
+ upload_id = base64.urlsafe_b64encode(os.urandom(9)).decode("ascii").rstrip("=")
+ part = os.path.join(STATE["save_dir"], "%s.%s.qftpart" % (name, upload_id))
+ with open(part, "wb") as fh:
+ fh.truncate(size)
+ STATE["uploads"][upload_id] = {
+ "name": name, "size": size, "chunk_size": chunk_size,
+ "total": total, "part": part, "received": [False] * total,
+ "lock": threading.Lock(),
+ }
+ return self._json(200, {"ok": True, "upload_id": upload_id,
+ "chunk_size": chunk_size, "total_chunks": total})
+
+ def _upload_chunk(self):
+ suffix = self.path[len("/qft/upload/chunk/"):]
+ upload_id, _, index_text = suffix.partition("/")
+ index = int(index_text)
+ session = STATE["uploads"].get(upload_id)
+ if session is None:
+ return self._json(500, {"ok": False, "error": "unknown upload"})
+
+ length = int(self.headers["Content-Length"])
+ offset = index * session["chunk_size"]
+ expected = min(session["chunk_size"], session["size"] - offset)
+ assert length == expected, "chunk 长度不匹配:%d != %d" % (length, expected)
+
+ body = b""
+ while len(body) < length:
+ block = self.rfile.read(length - len(body))
+ if not block:
+ break
+ body += block
+ assert len(body) == length, "chunk 体不完整"
+
+ with session["lock"]:
+ if session["received"][index]:
+ return self._json(200, {"ok": True, "duplicate": True})
+ with open(session["part"], "r+b") as fh:
+ fh.seek(offset)
+ fh.write(body)
+ session["received"][index] = True
+ return self._json(200, {"ok": True})
+
+ def _upload_finish(self):
+ upload_id = self.path[len("/qft/upload/finish/"):]
+ session = STATE["uploads"].get(upload_id)
+ if session is None:
+ return self._json(500, {"ok": False, "error": "unknown upload"})
+ missing = session["received"].count(False)
+ if missing:
+ return self._json(409, {"ok": False, "missing": missing})
+
+ digest = hashlib.sha256()
+ with open(session["part"], "rb") as fh:
+ while True:
+ block = fh.read(1024 * 1024)
+ if not block:
+ break
+ digest.update(block)
+ final = os.path.join(STATE["save_dir"], session["name"])
+ os.replace(session["part"], final)
+ del STATE["uploads"][upload_id]
+ return self._json(200, {"ok": True, "sha256": digest.hexdigest(), "size": session["size"]})
+
+
+def udp_responder(token, http_port, stop):
+ """QFTDISC2: → QFTHERE2::,对应 sender.rs 的发现线程。"""
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ sock.bind(("0.0.0.0", 39392))
+ except OSError:
+ return
+ sock.settimeout(0.25)
+ expected = ("QFTDISC2:%s" % token).encode("ascii")
+ reply = ("QFTHERE2:%s:%d" % (token, http_port)).encode("ascii")
+ while not stop.is_set():
+ try:
+ data, peer = sock.recvfrom(512)
+ except socket.timeout:
+ continue
+ except OSError:
+ break
+ if data == expected:
+ sock.sendto(reply, peer)
+ sock.close()
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--token", required=True)
+ parser.add_argument("--serve", required=True, help="供 /qft/download 下发的文件")
+ parser.add_argument("--save-dir", required=True, help="接收上传的目录")
+ parser.add_argument("--port", type=int, default=0)
+ parser.add_argument("--udp", action="store_true", help="同时启动 UDP 发现应答")
+ args = parser.parse_args()
+
+ STATE.update(token=args.token, serve=args.serve, save_dir=args.save_dir, uploads={})
+ os.makedirs(args.save_dir, exist_ok=True)
+
+ server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
+ port = server.server_address[1]
+
+ stop = threading.Event()
+ if args.udp:
+ threading.Thread(target=udp_responder, args=(args.token, port, stop), daemon=True).start()
+
+ print("READY %d" % port, flush=True)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ stop.set()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ios/CoreTests/main.swift b/ios/CoreTests/main.swift
new file mode 100644
index 0000000..d8ec3e1
--- /dev/null
+++ b/ios/CoreTests/main.swift
@@ -0,0 +1,377 @@
+import Foundation
+
+// QFT iOS 核心层测试。刻意不依赖 XCTest:这样在只有 Command Line Tools、
+// 没有 Xcode 的机器上也能 `swiftc` 直接编译运行,CI 与本地一致。
+//
+// 集成测试跑在 MockPCServer.py 上,该 mock 严格复刻 receiver.rs / sender.rs
+// 的线上语义,因此这里通过 == 线格式与 Windows 端兼容。
+
+var failures = 0
+var checks = 0
+
+func check(_ condition: Bool, _ message: String) {
+ checks += 1
+ if condition {
+ print(" ok \(message)")
+ } else {
+ failures += 1
+ print(" FAIL \(message)")
+ }
+}
+
+func checkEqual(_ actual: T, _ expected: T, _ message: String) {
+ check(actual == expected, "\(message)(实得 \(actual))")
+}
+
+func section(_ title: String) { print("\n== \(title) ==") }
+
+// ---------------------------------------------------------------- Base64URL
+
+section("Base64URL")
+checkEqual(Base64URL.encode("QFT"), "UUZU", "编码无填充")
+checkEqual(Base64URL.decodeString("UUZU"), "QFT", "解码往返")
+check(Base64URL.decode("a+b/c") == nil, "拒绝标准 Base64 字母表")
+check(Base64URL.decode("A") == nil, "拒绝不可能的长度")
+checkEqual(Base64URL.encode(Data([0xfb, 0xff])), "-_8", "- 与 _ 替换正确")
+checkEqual(Base64URL.decode("-_8"), Data([0xfb, 0xff]), "- 与 _ 解码正确")
+for _ in 0..<200 {
+ let raw = Data((0.. String {
+ let data = try! JSONSerialization.data(withJSONObject: object)
+ return prefix + Base64URL.encode(data)
+}
+
+let session = "abcdefghijklmnopqrstuvwxyz012345"
+let uploadText = makePairingText(prefix: "QFTPAIR2:", [
+ "v": 2, "s": session, "n": "DESKTOP-QFT", "p": 39393,
+ "e": ["http://192.168.1.20:39393"],
+])
+let upload = PairingProtocol.parse(uploadText)
+check(upload != nil, "解析 QFTPAIR2")
+checkEqual(upload?.direction, .uploadToPC, "方向为上传")
+checkEqual(upload?.session, session, "会话令牌")
+checkEqual(upload?.port, 39393, "端口")
+checkEqual(upload?.pcName, "DESKTOP-QFT", "电脑名")
+checkEqual(upload?.endpoints.count, 1, "端点数量")
+
+let downloadText = makePairingText(prefix: "QFTSEND2:", [
+ "v": 2, "s": session, "n": "DESKTOP-QFT", "p": 39393,
+ "e": ["http://10.0.0.5:39393"], "d": "d",
+ "f": "报告.pdf", "z": 1_234_567, "h": String(repeating: "ab", count: 32),
+])
+let download = PairingProtocol.parse(downloadText)
+check(download != nil, "解析 QFTSEND2")
+checkEqual(download?.direction, .downloadToPhone, "方向为下载")
+checkEqual(download?.fileName, "报告.pdf", "文件名支持中文")
+checkEqual(download?.fileSize, 1_234_567, "文件大小")
+
+check(PairingProtocol.parse("QFTPAIR2:" + Base64URL.encode(
+ try! JSONSerialization.data(withJSONObject: [
+ "v": 2, "s": session, "p": 39393, "e": ["http://192.168.1.20:39393"], "d": "d",
+ ]))) == nil, "前缀与方向不符时拒绝")
+
+check(PairingProtocol.parse(makePairingText(prefix: "QFTSEND2:", [
+ "v": 2, "s": session, "p": 39393, "e": ["http://10.0.0.5:39393"], "d": "d",
+ "f": "x.bin", "z": 1, "h": "not-a-hash",
+])) == nil, "SHA-256 格式错误时拒绝")
+
+check(PairingProtocol.parse(makePairingText(prefix: "QFTPAIR2:", [
+ "v": 1, "s": session, "p": 39393, "e": ["http://192.168.1.20:39393"],
+])) == nil, "版本号不是 2 时拒绝")
+
+check(PairingProtocol.parse(makePairingText(prefix: "QFTPAIR2:", [
+ "v": 2, "s": "short", "p": 39393, "e": ["http://192.168.1.20:39393"],
+])) == nil, "会话令牌过短时拒绝")
+
+// ---------------------------------------------------------------- 端点白名单
+
+section("端点白名单(二维码是不可信输入)")
+let allowed = [
+ "http://192.168.1.1:39393", "http://10.1.2.3:39393",
+ "http://172.16.0.1:39393", "http://172.31.255.254:39393",
+ "http://127.0.0.1:39393", "http://169.254.1.2:39393",
+]
+for endpoint in allowed {
+ check(PairingProtocol.isAllowedLocalHTTPEndpoint(endpoint, expectedPort: 39393), "接受 \(endpoint)")
+}
+let rejected = [
+ "https://192.168.1.1:39393", // 只允许 http
+ "http://evil.com:39393", // 域名
+ "http://8.8.8.8:39393", // 公网
+ "http://172.32.0.1:39393", // 172 段边界外
+ "http://192.168.1.1:1234", // 端口不符
+ "http://user@192.168.1.1:39393", // 带凭据
+ "http://192.168.1.1:39393/path", // 带路径
+ "http://192.168.1.1:39393?a=b", // 带 query
+ "http://192.168.01.1:39393", // 非规范八位组
+ "http://192.168.1:39393", // 段数不足
+ "http://[::1]:39393", // IPv6
+]
+for endpoint in rejected {
+ check(!PairingProtocol.isAllowedLocalHTTPEndpoint(endpoint, expectedPort: 39393), "拒绝 \(endpoint)")
+}
+
+// ---------------------------------------------------------------- 本地网络
+
+section("本机网络推导")
+checkEqual(LocalNetwork.ipv4("192.168.1.20"), 0xC0A80114, "IPv4 转整数")
+checkEqual(LocalNetwork.format(0xC0A80114), "192.168.1.20", "整数转 IPv4")
+check(LocalNetwork.ipv4("192.168.1.256") == nil, "拒绝越界八位组")
+
+// ---------------------------------------------------------------- 集成测试
+
+section("集成:与 MockPCServer 的完整传输")
+
+let root = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1]
+ : NSTemporaryDirectory()).appendingPathComponent("qft-ios-test", isDirectory: true)
+try? FileManager.default.removeItem(at: root)
+try! FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+
+let mockScript = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().appendingPathComponent("MockPCServer.py")
+
+// 3 MiB + 一点零头,确保最后一块是不完整块
+let payloadSize = 3 * 1024 * 1024 + 4321
+var payload = Data(count: payloadSize)
+payload.withUnsafeMutableBytes { buffer in
+ guard let base = buffer.bindMemory(to: UInt8.self).baseAddress else { return }
+ var state: UInt64 = 0x2026_0810
+ for index in 0..> 33) & 0xff)
+ }
+}
+let sourceURL = root.appendingPathComponent("payload.bin")
+try! payload.write(to: sourceURL)
+let payloadHash = sha256Hex(payload)
+
+let saveDir = root.appendingPathComponent("received", isDirectory: true)
+let downloadDir = root.appendingPathComponent("downloads", isDirectory: true)
+try! FileManager.default.createDirectory(at: downloadDir, withIntermediateDirectories: true)
+let token = "testsession0123456789abcdefghijk"
+
+let process = Process()
+process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
+process.arguments = ["python3", mockScript.path, "--token", token,
+ "--serve", sourceURL.path, "--save-dir", saveDir.path, "--port", "0"]
+let pipe = Pipe()
+process.standardOutput = pipe
+try! process.run()
+
+var port = 0
+let readyLine = readReadyLine(from: pipe.fileHandleForReading, timeout: 10)
+if let readyLine, readyLine.hasPrefix("READY ") {
+ port = Int(readyLine.dropFirst("READY ".count).trimmingCharacters(in: .whitespaces)) ?? 0
+}
+check(port > 0, "mock 电脑端已启动(端口 \(port))")
+
+if port > 0 {
+ let base = "http://127.0.0.1:\(port)"
+ let host = QFTHost(baseURL: base)
+
+ let sendPairing = PairingPayload(
+ version: 2, session: token, pcName: "MOCK-PC", port: port,
+ endpoints: [base], wifi: nil, direction: .downloadToPhone,
+ fileName: "payload.bin", fileSize: UInt64(payloadSize), sha256: payloadHash)
+
+ let semaphore = DispatchSemaphore(value: 0)
+ Task {
+ defer { semaphore.signal() }
+
+ // --- 发现 ---
+ let discovery = HostDiscovery(pairing: sendPairing, deviceName: "iPhone 测试机")
+ let located = try? await discovery.locate()
+ check(located?.baseURL == base, "通过二维码端点定位到电脑")
+
+ // --- 下载 ---
+ var lastFraction = 0.0
+ let downloader = DownloadClient(host: host, pairing: sendPairing,
+ deviceName: "iPhone 测试机",
+ destinationDirectory: downloadDir)
+ do {
+ let saved = try await downloader.run { lastFraction = $0.fraction }
+ let received = try Data(contentsOf: saved)
+ checkEqual(received.count, payloadSize, "下载字节数一致")
+ checkEqual(sha256Hex(received), payloadHash, "下载内容 SHA-256 一致")
+ check(lastFraction > 0.99, "进度回调抵达 100%")
+ checkEqual(saved.lastPathComponent, "payload.bin", "落盘文件名正确")
+ check(!FileManager.default.fileExists(atPath: saved.path + ".qftpart"), "临时文件已清理")
+ } catch {
+ check(false, "下载失败:\(error.localizedDescription)")
+ }
+
+ // --- 下载续传 ---
+ do {
+ let partURL = downloadDir.appendingPathComponent("payload.bin.qftpart")
+ try? FileManager.default.removeItem(at: partURL)
+ try payload.prefix(1_000_000).write(to: partURL)
+ let resumed = try await DownloadClient(host: host, pairing: sendPairing,
+ deviceName: "iPhone",
+ destinationDirectory: downloadDir).run { _ in }
+ let data = try Data(contentsOf: resumed)
+ checkEqual(sha256Hex(data), payloadHash, "从 1,000,000 字节处续传后内容仍正确")
+ try? FileManager.default.removeItem(at: resumed)
+ } catch {
+ check(false, "续传失败:\(error.localizedDescription)")
+ }
+
+ // --- 上传 ---
+ let uploadPairing = PairingPayload(
+ version: 2, session: token, pcName: "MOCK-PC", port: port,
+ endpoints: [base], wifi: nil, direction: .uploadToPC,
+ fileName: nil, fileSize: nil, sha256: nil)
+ do {
+ var seen = 0.0
+ let uploader = UploadClient(host: host, pairing: uploadPairing, deviceName: "iPhone 测试机")
+ let sha = try await uploader.run(fileURL: sourceURL) { seen = $0.fraction }
+ checkEqual(sha, payloadHash, "上传后电脑侧 SHA-256 与本地一致")
+ check(seen > 0.99, "上传进度回调抵达 100%")
+ let landed = saveDir.appendingPathComponent("payload.bin")
+ let data = try Data(contentsOf: landed)
+ checkEqual(data.count, payloadSize, "电脑侧落盘大小一致")
+ checkEqual(sha256Hex(data), payloadHash, "电脑侧落盘内容一致")
+ } catch {
+ check(false, "上传失败:\(error.localizedDescription)")
+ }
+
+ // --- 错误令牌必须被拒 ---
+ let badPairing = PairingPayload(
+ version: 2, session: "wrongsession0123456789abcdefghij", pcName: "MOCK-PC",
+ port: port, endpoints: [base], wifi: nil, direction: .uploadToPC,
+ fileName: nil, fileSize: nil, sha256: nil)
+ do {
+ _ = try await UploadClient(host: host, pairing: badPairing,
+ deviceName: "iPhone").run(fileURL: sourceURL) { _ in }
+ check(false, "错误令牌本应失败")
+ } catch {
+ check(true, "错误令牌被拒绝:\(error.localizedDescription)")
+ }
+ }
+ semaphore.wait()
+}
+
+process.terminate()
+
+// ---------------------------------------------------------------- P2P 配对码
+
+section("隔空投送式配对码")
+
+let peerSample = PeerPairing(
+ version: 1, key: Data((0..<32).map { UInt8($0) }), instance: "qft-abcdefghijkl",
+ senderName: "我的 iPhone", fileName: "视频.mov", fileSize: 987_654_321,
+ sha256: String(repeating: "cd", count: 32))
+let peerRoundTrip = PeerPairing.parse(peerSample.encode())
+checkEqual(peerRoundTrip, peerSample, "QFTP2P1 编解码往返一致")
+check(PeerPairing.isPeerText(peerSample.encode()), "前缀识别")
+check(PairingProtocol.parse(peerSample.encode()) == nil, "P2P 码不会被误判为 QFTPAIR2")
+
+func mutatedPeer(_ change: (inout [String: Any]) -> Void) -> String? {
+ var object: [String: Any] = [
+ "v": 1, "k": Base64URL.encode(Data(repeating: 7, count: 32)),
+ "i": "qft-abcdefghijkl", "n": "iPhone", "f": "a.bin",
+ "z": 10, "h": String(repeating: "ab", count: 32),
+ ]
+ change(&object)
+ let data = try! JSONSerialization.data(withJSONObject: object)
+ return PeerPairing.prefix + Base64URL.encode(data)
+}
+check(PeerPairing.parse(mutatedPeer { $0["k"] = Base64URL.encode(Data(repeating: 7, count: 16)) }!) == nil,
+ "密钥不足 32 字节时拒绝")
+check(PeerPairing.parse(mutatedPeer { $0["i"] = "bad instance!" }!) == nil, "非法实例名时拒绝")
+check(PeerPairing.parse(mutatedPeer { $0["f"] = "../../etc/passwd" }!) == nil, "文件名含路径分隔符时拒绝")
+check(PeerPairing.parse(mutatedPeer { $0["h"] = "zz" }!) == nil, "摘要格式错误时拒绝")
+check(PeerPairing.newKey().count == 32, "新密钥为 32 字节")
+check(PeerPairing.isValidInstance(PeerPairing.newInstance()), "新实例名合法")
+check(PeerPairing.newKey() != PeerPairing.newKey(), "密钥每次不同")
+
+// ---------------------------------------------------------------- P2P 传输
+
+section("隔空投送式点对点传输(TLS-PSK 真实握手)")
+
+let peerDir = root.appendingPathComponent("peer", isDirectory: true)
+try! FileManager.default.createDirectory(at: peerDir, withIntermediateDirectories: true)
+
+let peerSemaphore = DispatchSemaphore(value: 0)
+Task {
+ defer { peerSemaphore.signal() }
+ let sender = PeerSender(fileURL: sourceURL, deviceName: "发送端 iPhone")
+ do {
+ let pairing = try sender.start()
+ checkEqual(pairing.fileSize, UInt64(payloadSize), "配对码里的文件大小")
+ checkEqual(pairing.sha256, payloadHash, "配对码里的 SHA-256 由发送端实算")
+
+ let port = try await sender.listeningPort()
+ check(port > 0, "监听器就绪(端口 \(port))")
+
+ // 二维码在真机上是扫出来的,这里模拟:编码 → 解码 → 用解出来的配对码连接
+ guard let scanned = PeerPairing.parse(pairing.encode()) else {
+ check(false, "配对码无法解析"); return
+ }
+
+ var receiver = PeerReceiver(pairing: scanned, destinationDirectory: peerDir)
+ receiver.directPort = port // 测试跳过 Bonjour,直连回环
+
+ async let sendSide: Void = sender.waitAndSend { _ in }
+ var peerFraction = 0.0
+ let saved = try await receiver.run { peerFraction = $0.fraction }
+ try await sendSide
+
+ let data = try Data(contentsOf: saved)
+ checkEqual(data.count, payloadSize, "P2P 收到字节数一致")
+ checkEqual(sha256Hex(data), payloadHash, "P2P 收到内容 SHA-256 一致")
+ check(peerFraction > 0.99, "P2P 进度回调抵达 100%")
+ check(!FileManager.default.fileExists(atPath: saved.path + ".qftpart"), "P2P 临时文件已清理")
+ } catch {
+ check(false, "P2P 传输失败:\(error.localizedDescription)")
+ }
+ sender.stop()
+}
+if peerSemaphore.wait(timeout: .now() + 60) == .timedOut {
+ check(false, "P2P 传输超时")
+}
+
+// 错误密钥必须握手失败
+let wrongKeySemaphore = DispatchSemaphore(value: 0)
+Task {
+ defer { wrongKeySemaphore.signal() }
+ let sender = PeerSender(fileURL: sourceURL, deviceName: "发送端")
+ do {
+ let pairing = try sender.start()
+ let port = try await sender.listeningPort()
+ let tampered = PeerPairing(version: 1, key: PeerPairing.newKey(),
+ instance: pairing.instance, senderName: pairing.senderName,
+ fileName: pairing.fileName, fileSize: pairing.fileSize,
+ sha256: pairing.sha256)
+ var receiver = PeerReceiver(pairing: tampered, destinationDirectory: peerDir)
+ receiver.directPort = port
+ _ = try await receiver.run { _ in }
+ check(false, "错误密钥本应握手失败")
+ } catch {
+ check(true, "错误密钥被 TLS-PSK 拒绝")
+ }
+ sender.stop()
+}
+if wrongKeySemaphore.wait(timeout: .now() + 30) == .timedOut {
+ check(false, "错误密钥用例超时(握手未在预期时间内失败)")
+}
+
+// 测试全程只写 root 下的临时目录,不碰 Documents
+try? FileManager.default.removeItem(at: root)
+
+print("\n检查 \(checks) 项,失败 \(failures) 项")
+if failures > 0 {
+ print("IOS CORE TESTS FAILED")
+ exit(1)
+}
+print("IOS CORE TESTS PASSED")
diff --git a/ios/CoreTests/run.sh b/ios/CoreTests/run.sh
new file mode 100755
index 0000000..407e842
--- /dev/null
+++ b/ios/CoreTests/run.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+# 在只有 Command Line Tools 的机器上编译并运行 iOS 核心层测试。
+#
+# 核心层刻意不 import UIKit/AVFoundation,因此可以直接以 macOS 为目标编译,
+# 在没有 Xcode / 没有模拟器的环境里也能验证协议、发现与传输逻辑。
+set -euo pipefail
+
+cd "$(dirname "$0")/.."
+OUT="$(mktemp -d)"
+trap 'rm -rf "$OUT"' EXIT
+
+echo "== 编译 =="
+swiftc -swift-version 5 -O \
+ QFT/Core/*.swift CoreTests/*.swift \
+ -o "$OUT/qft-core-tests"
+
+echo "== 运行 =="
+"$OUT/qft-core-tests" "$OUT"
diff --git a/ios/QFT.xcodeproj/project.pbxproj b/ios/QFT.xcodeproj/project.pbxproj
new file mode 100644
index 0000000..174384c
--- /dev/null
+++ b/ios/QFT.xcodeproj/project.pbxproj
@@ -0,0 +1,316 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 56;
+ 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 */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXFileReference section */
+ 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerPairing.swift; sourceTree = ""; };
+ 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = ""; };
+ 3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = ""; };
+ 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = ""; };
+ 453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = ""; };
+ 5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = ""; };
+ 7E4A60F8CA5D515103446ED3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
+ 848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = ""; };
+ 8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = ""; };
+ 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 = ""; };
+ C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
+ EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = ""; };
+ F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = ""; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ 019BAB185F97B56993A7087D /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+ 32AAB6DFB51CD1888CC4883B /* App */ = {
+ isa = PBXGroup;
+ children = (
+ 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */,
+ 453B172D654B3AEDE4E36D1E /* QFTApp.swift */,
+ F3B15455554D7647B44D5038 /* ScannerView.swift */,
+ 3017489412A6FCAE8995B32E /* TransferModel.swift */,
+ );
+ path = App;
+ sourceTree = "";
+ };
+ 36EDFB66685EBD501D3910CE /* QFT */ = {
+ isa = PBXGroup;
+ children = (
+ 32AAB6DFB51CD1888CC4883B /* App */,
+ C628A05E9C83375781E165EB /* Assets.xcassets */,
+ EC599E8CF455428A5E3179CE /* Core */,
+ 7E4A60F8CA5D515103446ED3 /* Info.plist */,
+ );
+ path = QFT;
+ sourceTree = "";
+ };
+ 47C128B82C29A60341C3928E = {
+ isa = PBXGroup;
+ children = (
+ 36EDFB66685EBD501D3910CE /* QFT */,
+ 83E44493474BECB586AAD962 /* Products */,
+ );
+ sourceTree = "";
+ };
+ 83E44493474BECB586AAD962 /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ 928818DCDA72C62B2D8288D5 /* QFT.app */,
+ );
+ name = Products;
+ sourceTree = "";
+ };
+ 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 = "";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 497CBF7ECF21FFA362230876 /* QFT */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */;
+ buildPhases = (
+ C2511B36F0F0E810A9E46328 /* Sources */,
+ 019BAB185F97B56993A7087D /* Frameworks */,
+ C2112B99FC6905E49DE55430 /* Resources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = QFT;
+ productName = QFT;
+ productReference = 928818DCDA72C62B2D8288D5 /* QFT.app */;
+ productType = "com.apple.product-type.application";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ 98F54143AB4E86B28C3AFEE0 /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ BuildIndependentTargetsInParallel = 1;
+ LastSwiftUpdateCheck = 1600;
+ LastUpgradeCheck = 1600;
+ TargetAttributes = {
+ 497CBF7ECF21FFA362230876 = {
+ CreatedOnToolsVersion = 16.0;
+ };
+ };
+ };
+ buildConfigurationList = 26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */;
+ compatibilityVersion = "Xcode 14.0";
+ developmentRegion = en;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ en,
+ Base,
+ "zh-Hans",
+ );
+ mainGroup = 47C128B82C29A60341C3928E;
+ productRefGroup = 83E44493474BECB586AAD962 /* Products */;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ 497CBF7ECF21FFA362230876 /* QFT */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+ C2112B99FC6905E49DE55430 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+ C2511B36F0F0E810A9E46328 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 554512A1FC8A6F66E2784787 /* QFTApp.swift in Sources */,
+ 78FD5CF5E04D7E2483B90BAA /* HomeView.swift in Sources */,
+ BDCF0D82F0BD0328770A8ABD /* ScannerView.swift in Sources */,
+ E26487D1146FDF6DD5F92D80 /* TransferModel.swift in Sources */,
+ EE5510DAC5BBB7F9D41A8F26 /* Base64URL.swift in Sources */,
+ 38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */,
+ 6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */,
+ 978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */,
+ 0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */,
+ 4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */,
+ A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* 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 = 1;
+ 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.1.0;
+ 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 = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = dwarf;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ ENABLE_TESTABILITY = YES;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_OPTIMIZATION_LEVEL = 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;
+ SDKROOT = iphoneos;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 5.0;
+ };
+ name = Debug;
+ };
+ C3DCEEC1E0EB17A5583B8E94 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_NO_COMMON_BLOCKS = YES;
+ 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;
+ VALIDATE_PRODUCT = YES;
+ };
+ name = 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;
+ 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.1.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_EMIT_LOC_STRINGS = NO;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Debug;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ 26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 70DCC1EB255A5F3C8D9ED349 /* Debug */,
+ C3DCEEC1E0EB17A5583B8E94 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ DB189EBE9D4E38495C3C7EF5 /* Debug */,
+ 032222C0BAA33BC7119DFAF1 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+ };
+ rootObject = 98F54143AB4E86B28C3AFEE0 /* Project object */;
+}
diff --git a/ios/QFT.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/QFT.xcodeproj/project.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 0000000..919434a
--- /dev/null
+++ b/ios/QFT.xcodeproj/project.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/ios/QFT/App/HomeView.swift b/ios/QFT/App/HomeView.swift
new file mode 100644
index 0000000..7f8aba4
--- /dev/null
+++ b/ios/QFT/App/HomeView.swift
@@ -0,0 +1,197 @@
+import SwiftUI
+import UniformTypeIdentifiers
+
+struct HomeView: View {
+
+ /// 同一个 view 上挂多个 .fileImporter 会互相覆盖,只能有一个,
+ /// 所以用这个枚举区分「选完文件之后要干什么」。
+ private enum PickPurpose: Equatable {
+ case peerSend
+ case uploadToPC(PairingPayload)
+ }
+
+ @StateObject private var model = TransferModel()
+ @State private var pickPurpose: PickPurpose?
+
+ var body: some View {
+ NavigationStack {
+ content
+ .navigationTitle("QFT 快传")
+ .navigationBarTitleDisplayMode(.inline)
+ }
+ .fullScreenCover(isPresented: isScanning) {
+ ScannerView(onFound: { model.handleScanned($0) }, onCancel: { model.cancel() })
+ .ignoresSafeArea()
+ }
+ .fileImporter(isPresented: isPicking,
+ allowedContentTypes: [UTType.item], allowsMultipleSelection: false) { result in
+ let purpose = pickPurpose
+ pickPurpose = nil
+ guard case .success(let urls) = result, let url = urls.first else {
+ model.reset()
+ return
+ }
+ switch purpose {
+ case .peerSend: model.startPeerSend(fileURL: url)
+ case .uploadToPC(let pairing): model.startUpload(pairing, fileURL: url)
+ case nil: break
+ }
+ }
+ .onAppear { model.refreshReceivedFiles() }
+ .onChange(of: model.stage) { _, stage in
+ // 扫到 QFTPAIR2 之后才知道要选文件,所以选择器由 stage 驱动
+ if case .pickFileForUpload(let pairing) = stage {
+ pickPurpose = .uploadToPC(pairing)
+ }
+ }
+ }
+
+ private var isScanning: Binding {
+ Binding(get: { model.stage == .scanning }, set: { if !$0 { model.cancel() } })
+ }
+
+ private var isPicking: Binding {
+ Binding(get: { pickPurpose != nil }, set: { if !$0 { pickPurpose = nil } })
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ switch model.stage {
+ case .idle, .scanning, .pickFileForUpload:
+ landing
+ case .connecting(let message):
+ StatusCard(icon: "antenna.radiowaves.left.and.right", title: message) {
+ ProgressView()
+ Button("取消", role: .cancel) { model.cancel() }
+ }
+ case .running(let message):
+ StatusCard(icon: "arrow.left.arrow.right", title: message) {
+ if let progress = model.progress {
+ ProgressView(value: progress.fraction)
+ Text("\(progress.readableSize) · \(progress.readableRate)")
+ .font(.footnote.monospacedDigit())
+ .foregroundStyle(.secondary)
+ } else {
+ ProgressView()
+ }
+ Button("取消", role: .cancel) { model.cancel() }
+ }
+ case .showingPeerCode(let pairing):
+ peerCode(pairing)
+ case .finished(let message, let url):
+ StatusCard(icon: "checkmark.circle.fill", title: message) {
+ if let url {
+ Text(url.lastPathComponent).font(.footnote).foregroundStyle(.secondary)
+ ShareLink(item: url) { Label("分享", systemImage: "square.and.arrow.up") }
+ }
+ Button("完成") { model.reset() }.buttonStyle(.borderedProminent)
+ }
+ case .failed(let message):
+ StatusCard(icon: "exclamationmark.triangle.fill", title: "传输失败") {
+ Text(message).font(.footnote).multilineTextAlignment(.center)
+ .foregroundStyle(.secondary)
+ Button("返回") { model.reset() }.buttonStyle(.borderedProminent)
+ }
+ }
+ }
+
+ private var landing: some View {
+ List {
+ Section {
+ ActionRow(icon: "qrcode.viewfinder", title: "扫码",
+ detail: "扫电脑上的二维码收发文件,或扫另一台 iPhone 的码接收") {
+ model.beginScan()
+ }
+ ActionRow(icon: "iphone.gen3.radiowaves.left.and.right", title: "发给附近的 iPhone",
+ detail: "选文件后显示二维码,对方扫一下即可,无需连同一个 Wi-Fi") {
+ pickPurpose = .peerSend
+ }
+ } footer: {
+ Text("与电脑互传需要手机和电脑连在同一个 Wi-Fi。iPhone 之间使用点对点直连,不经过路由器。")
+ }
+
+ if !model.receivedFiles.isEmpty {
+ Section("已接收") {
+ ForEach(model.receivedFiles, id: \.self) { url in
+ ShareLink(item: url) {
+ Label(url.lastPathComponent, systemImage: "doc")
+ .lineLimit(1)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private func peerCode(_ pairing: PeerPairing) -> some View {
+ VStack(spacing: 20) {
+ Text("让对方用 QFT 扫这个码")
+ .font(.headline)
+ if let image = QRRenderer.image(from: pairing.encode()) {
+ Image(uiImage: image)
+ .interpolation(.none)
+ .resizable()
+ .scaledToFit()
+ .frame(maxWidth: 300)
+ .padding()
+ .background(.white)
+ .clipShape(RoundedRectangle(cornerRadius: 16))
+ }
+ VStack(spacing: 4) {
+ Text(pairing.fileName).font(.subheadline).lineLimit(1)
+ Text(TransferProgress.readable(pairing.fileSize))
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ if let progress = model.progress {
+ ProgressView(value: progress.fraction)
+ .padding(.horizontal, 40)
+ Text("\(progress.readableSize) · \(progress.readableRate)")
+ .font(.footnote.monospacedDigit()).foregroundStyle(.secondary)
+ } else {
+ Label("等待对方扫码…", systemImage: "hourglass")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ Button("取消", role: .cancel) { model.cancel() }
+ }
+ .padding()
+ }
+}
+
+private struct ActionRow: View {
+ let icon: String
+ let title: String
+ let detail: String
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 14) {
+ Image(systemName: icon)
+ .font(.title2)
+ .frame(width: 34)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(title).font(.body.weight(.medium))
+ Text(detail).font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ .padding(.vertical, 4)
+ }
+ .buttonStyle(.plain)
+ }
+}
+
+private struct StatusCard: View {
+ let icon: String
+ let title: String
+ @ViewBuilder let content: Content
+
+ var body: some View {
+ VStack(spacing: 18) {
+ Image(systemName: icon).font(.system(size: 44))
+ Text(title).font(.headline).multilineTextAlignment(.center)
+ content
+ }
+ .padding(32)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+}
diff --git a/ios/QFT/App/QFTApp.swift b/ios/QFT/App/QFTApp.swift
new file mode 100644
index 0000000..b4d405d
--- /dev/null
+++ b/ios/QFT/App/QFTApp.swift
@@ -0,0 +1,10 @@
+import SwiftUI
+
+@main
+struct QFTApp: App {
+ var body: some Scene {
+ WindowGroup {
+ HomeView()
+ }
+ }
+}
diff --git a/ios/QFT/App/ScannerView.swift b/ios/QFT/App/ScannerView.swift
new file mode 100644
index 0000000..cd56856
--- /dev/null
+++ b/ios/QFT/App/ScannerView.swift
@@ -0,0 +1,137 @@
+import SwiftUI
+import AVFoundation
+
+/// 二维码扫描。用 AVCaptureMetadataOutput 而不是 Vision:
+/// 硬件解码路径延迟更低,而且这里只需要识别静态配对码,
+/// 不需要 QFT2 光学链路那套 ROI 锁定与高频解码。
+struct ScannerView: UIViewControllerRepresentable {
+
+ /// 只在识别到我们认识的前缀时回调,且只回调一次。
+ let onFound: (String) -> Void
+ let onCancel: () -> Void
+
+ func makeCoordinator() -> Coordinator { Coordinator(onFound: onFound) }
+
+ func makeUIViewController(context: Context) -> ScannerController {
+ let controller = ScannerController()
+ controller.coordinator = context.coordinator
+ controller.onCancel = onCancel
+ return controller
+ }
+
+ func updateUIViewController(_ controller: ScannerController, context: Context) {}
+
+ final class Coordinator: NSObject, AVCaptureMetadataOutputObjectsDelegate {
+ private let onFound: (String) -> Void
+ private var consumed = false
+
+ init(onFound: @escaping (String) -> Void) { self.onFound = onFound }
+
+ func metadataOutput(_ output: AVCaptureMetadataOutput,
+ didOutput objects: [AVMetadataObject],
+ from connection: AVCaptureConnection) {
+ guard !consumed else { return }
+ for object in objects {
+ guard let readable = object as? AVMetadataMachineReadableCodeObject,
+ readable.type == .qr, let text = readable.stringValue else { continue }
+ guard PairingProtocol.isPairingText(text) || PeerPairing.isPeerText(text) else { continue }
+ consumed = true
+ UINotificationFeedbackGenerator().notificationOccurred(.success)
+ DispatchQueue.main.async { self.onFound(text) }
+ return
+ }
+ }
+ }
+}
+
+final class ScannerController: UIViewController {
+
+ var coordinator: ScannerView.Coordinator?
+ var onCancel: (() -> Void)?
+
+ private let session = AVCaptureSession()
+ private var preview: AVCaptureVideoPreviewLayer?
+ private let hintLabel = UILabel()
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ view.backgroundColor = .black
+ configureSession()
+ configureOverlay()
+ }
+
+ private func configureSession() {
+ guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),
+ let input = try? AVCaptureDeviceInput(device: device),
+ session.canAddInput(input) else {
+ showFailure("无法打开相机")
+ return
+ }
+ session.addInput(input)
+
+ let output = AVCaptureMetadataOutput()
+ guard session.canAddOutput(output) else {
+ showFailure("无法启动二维码识别")
+ return
+ }
+ session.addOutput(output)
+ output.setMetadataObjectsDelegate(coordinator, queue: .main)
+ output.metadataObjectTypes = [.qr]
+
+ let layer = AVCaptureVideoPreviewLayer(session: session)
+ layer.videoGravity = .resizeAspectFill
+ layer.frame = view.bounds
+ view.layer.insertSublayer(layer, at: 0)
+ preview = layer
+ }
+
+ private func configureOverlay() {
+ hintLabel.text = "对准电脑或另一台 iPhone 上的二维码"
+ hintLabel.textColor = .white
+ hintLabel.font = .systemFont(ofSize: 15, weight: .medium)
+ hintLabel.textAlignment = .center
+ hintLabel.numberOfLines = 0
+ hintLabel.translatesAutoresizingMaskIntoConstraints = false
+ view.addSubview(hintLabel)
+
+ let cancel = UIButton(type: .system)
+ cancel.setTitle("取消", for: .normal)
+ cancel.setTitleColor(.white, for: .normal)
+ cancel.titleLabel?.font = .systemFont(ofSize: 17, weight: .semibold)
+ cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
+ cancel.translatesAutoresizingMaskIntoConstraints = false
+ view.addSubview(cancel)
+
+ NSLayoutConstraint.activate([
+ hintLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32),
+ hintLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32),
+ hintLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -96),
+ cancel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
+ cancel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -32),
+ ])
+ }
+
+ @objc private func cancelTapped() { onCancel?() }
+
+ private func showFailure(_ message: String) {
+ hintLabel.text = message
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ super.viewWillAppear(animated)
+ guard !session.isRunning else { return }
+ // startRunning 会阻塞,必须离开主线程
+ DispatchQueue.global(qos: .userInitiated).async { [session] in session.startRunning() }
+ }
+
+ override func viewWillDisappear(_ animated: Bool) {
+ super.viewWillDisappear(animated)
+ guard session.isRunning else { return }
+ DispatchQueue.global(qos: .userInitiated).async { [session] in session.stopRunning() }
+ }
+
+ override func viewDidLayoutSubviews() {
+ super.viewDidLayoutSubviews()
+ preview?.frame = view.bounds
+ }
+}
diff --git a/ios/QFT/App/TransferModel.swift b/ios/QFT/App/TransferModel.swift
new file mode 100644
index 0000000..02ddb61
--- /dev/null
+++ b/ios/QFT/App/TransferModel.swift
@@ -0,0 +1,242 @@
+import SwiftUI
+import CoreImage.CIFilterBuiltins
+
+@MainActor
+final class TransferModel: ObservableObject {
+
+ enum Stage: Equatable {
+ case idle
+ case scanning
+ /// 扫到 QFTPAIR2:需要用户挑一个文件传给电脑
+ case pickFileForUpload(PairingPayload)
+ case connecting(String)
+ case running(String)
+ case showingPeerCode(PeerPairing)
+ case finished(String, URL?)
+ case failed(String)
+ }
+
+ @Published private(set) var stage: Stage = .idle
+ @Published private(set) var progress: TransferProgress?
+ @Published private(set) var receivedFiles: [URL] = []
+
+ private var task: Task?
+ private var sender: PeerSender?
+ private var scopedURL: URL?
+
+ private let deviceName = DeviceInfo.name
+
+ // MARK: - 入口
+
+ func beginScan() { stage = .scanning }
+
+ func cancel() {
+ task?.cancel()
+ task = nil
+ sender?.stop()
+ sender = nil
+ releaseScope()
+ progress = nil
+ stage = .idle
+ }
+
+ func reset() {
+ progress = nil
+ stage = .idle
+ refreshReceivedFiles()
+ }
+
+ /// 扫到码之后的统一分发
+ func handleScanned(_ text: String) {
+ if let peer = PeerPairing.parse(text) {
+ startPeerReceive(peer)
+ return
+ }
+ guard let pairing = PairingProtocol.parse(text) else {
+ stage = .failed("这不是 QFT 的二维码,或二维码里的地址不是局域网地址。")
+ return
+ }
+ switch pairing.direction {
+ case .downloadToPhone: startDownload(pairing)
+ case .uploadToPC: stage = .pickFileForUpload(pairing)
+ }
+ }
+
+ // MARK: - 电脑 → 手机
+
+ private func startDownload(_ pairing: PairingPayload) {
+ stage = .connecting("正在找 \(pairing.pcName)…")
+ task = Task {
+ do {
+ let host = try await HostDiscovery(pairing: pairing, deviceName: deviceName).locate()
+ guard !Task.isCancelled else { return }
+ stage = .running("正在从 \(pairing.pcName) 接收 \(pairing.fileName ?? "文件")")
+ let client = DownloadClient(host: host, pairing: pairing, deviceName: deviceName)
+ let saved = try await client.run { [weak self] value in
+ Task { @MainActor in self?.progress = value }
+ }
+ finish("已保存到「文件」App 的 QFT 文件夹", saved)
+ } catch {
+ fail(error)
+ }
+ }
+ }
+
+ // MARK: - 手机 → 电脑
+
+ func startUpload(_ pairing: PairingPayload, fileURL: URL) {
+ guard claimScope(fileURL) else {
+ stage = .failed("没有权限读取这个文件,请换一个位置再试。")
+ return
+ }
+ stage = .connecting("正在找 \(pairing.pcName)…")
+ task = Task {
+ defer { releaseScope() }
+ do {
+ let host = try await HostDiscovery(pairing: pairing, deviceName: deviceName).locate()
+ guard !Task.isCancelled else { return }
+ stage = .running("正在发送 \(fileURL.lastPathComponent) 到 \(pairing.pcName)")
+ let client = UploadClient(host: host, pairing: pairing, deviceName: deviceName)
+ _ = try await client.run(fileURL: fileURL) { [weak self] value in
+ Task { @MainActor in self?.progress = value }
+ }
+ finish("已发送到 \(pairing.pcName)", nil)
+ } catch {
+ fail(error)
+ }
+ }
+ }
+
+ // MARK: - iPhone ↔ iPhone(隔空投送式)
+
+ func startPeerSend(fileURL: URL) {
+ guard claimScope(fileURL) else {
+ stage = .failed("没有权限读取这个文件,请换一个位置再试。")
+ return
+ }
+ stage = .connecting("正在准备…")
+ task = Task {
+ defer { releaseScope() }
+ do {
+ let sender = PeerSender(fileURL: fileURL, deviceName: deviceName)
+ // start() 里要完整读一遍文件算摘要,别卡住主线程
+ let pairing = try await Task.detached { try sender.start() }.value
+ guard !Task.isCancelled else { sender.stop(); return }
+ self.sender = sender
+ stage = .showingPeerCode(pairing)
+ try await sender.waitAndSend { [weak self] value in
+ Task { @MainActor in self?.progress = value }
+ }
+ finish("已发送给对方", nil)
+ } catch {
+ fail(error)
+ }
+ sender?.stop()
+ sender = nil
+ }
+ }
+
+ private func startPeerReceive(_ pairing: PeerPairing) {
+ stage = .connecting("正在连接 \(pairing.senderName)…")
+ task = Task {
+ do {
+ let directory = try DownloadClient.defaultDestinationDirectory()
+ let receiver = PeerReceiver(pairing: pairing, destinationDirectory: directory)
+ stage = .running("正在接收 \(pairing.fileName)")
+ let saved = try await receiver.run { [weak self] value in
+ Task { @MainActor in self?.progress = value }
+ }
+ finish("已保存到「文件」App 的 QFT 文件夹", saved)
+ } catch {
+ fail(error)
+ }
+ }
+ }
+
+ // MARK: - 收尾
+
+ private func finish(_ message: String, _ url: URL?) {
+ progress = nil
+ stage = .finished(message, url)
+ refreshReceivedFiles()
+ }
+
+ private func fail(_ error: Error) {
+ guard !(error is CancellationError) else { return }
+ progress = nil
+ stage = .failed(error.localizedDescription)
+ }
+
+ func refreshReceivedFiles() {
+ guard let directory = try? DownloadClient.defaultDestinationDirectory(),
+ let entries = try? FileManager.default.contentsOfDirectory(
+ at: directory, includingPropertiesForKeys: [.contentModificationDateKey]) else {
+ receivedFiles = []
+ return
+ }
+ receivedFiles = entries
+ .filter { $0.pathExtension != "qftpart" }
+ .sorted { lhs, rhs in
+ let l = (try? lhs.resourceValues(forKeys: [.contentModificationDateKey]))?
+ .contentModificationDate ?? .distantPast
+ let r = (try? rhs.resourceValues(forKeys: [.contentModificationDateKey]))?
+ .contentModificationDate ?? .distantPast
+ return l > r
+ }
+ }
+
+ // MARK: - 安全作用域
+
+ /// 文件选择器给的 URL 属于其他进程的沙盒,读之前必须声明作用域,
+ /// 而且整个传输期间都要持有。
+ private func claimScope(_ url: URL) -> Bool {
+ releaseScope()
+ guard url.startAccessingSecurityScopedResource() else { return false }
+ scopedURL = url
+ return true
+ }
+
+ private func releaseScope() {
+ scopedURL?.stopAccessingSecurityScopedResource()
+ scopedURL = nil
+ }
+}
+
+// MARK: - 二维码渲染
+
+enum QRRenderer {
+ /// 配对码只有几百字节,用 M 级纠错换取更好的首次识别率。
+ static func image(from text: String) -> UIImage? {
+ let filter = CIFilter.qrCodeGenerator()
+ filter.message = Data(text.utf8)
+ filter.correctionLevel = "M"
+ guard let output = filter.outputImage else { return nil }
+ // 放大用最近邻,避免插值把模块边缘糊掉
+ let scaled = output.transformed(by: CGAffineTransform(scaleX: 12, y: 12))
+ let context = CIContext()
+ guard let cgImage = context.createCGImage(scaled, from: scaled.extent) else { return nil }
+ return UIImage(cgImage: cgImage)
+ }
+}
+
+extension TransferProgress {
+ var readableRate: String {
+ let units = ["B/s", "KB/s", "MB/s", "GB/s"]
+ var value = bytesPerSecond
+ var index = 0
+ while value >= 1024, index < units.count - 1 { value /= 1024; index += 1 }
+ return String(format: "%.1f %@", value, units[index])
+ }
+
+ var readableSize: String {
+ Self.readable(completed) + " / " + Self.readable(total)
+ }
+
+ static func readable(_ bytes: UInt64) -> String {
+ let units = ["B", "KB", "MB", "GB"]
+ var value = Double(bytes)
+ var index = 0
+ while value >= 1024, index < units.count - 1 { value /= 1024; index += 1 }
+ return String(format: index == 0 ? "%.0f %@" : "%.1f %@", value, units[index])
+ }
+}
diff --git a/ios/QFT/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/QFT/Assets.xcassets/AccentColor.colorset/Contents.json
new file mode 100644
index 0000000..3be300b
--- /dev/null
+++ b/ios/QFT/Assets.xcassets/AccentColor.colorset/Contents.json
@@ -0,0 +1,4 @@
+{
+ "colors" : [ { "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/ios/QFT/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/QFT/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 0000000..07942c2
--- /dev/null
+++ b/ios/QFT/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,6 @@
+{
+ "images" : [
+ { "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" }
+ ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/ios/QFT/Assets.xcassets/Contents.json b/ios/QFT/Assets.xcassets/Contents.json
new file mode 100644
index 0000000..d8b757a
--- /dev/null
+++ b/ios/QFT/Assets.xcassets/Contents.json
@@ -0,0 +1,3 @@
+{
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/ios/QFT/Core/Base64URL.swift b/ios/QFT/Core/Base64URL.swift
new file mode 100644
index 0000000..480b526
--- /dev/null
+++ b/ios/QFT/Core/Base64URL.swift
@@ -0,0 +1,46 @@
+import Foundation
+
+/// RFC 4648 §5 的 URL-safe Base64,无填充。
+/// Windows 端用 `URL_SAFE_NO_PAD` 编码设备名、文件名与配对载荷,
+/// Android 端对应 `Base64Url`,三端必须逐字节一致。
+enum Base64URL {
+
+ static func encode(_ data: Data) -> String {
+ var text = data.base64EncodedString()
+ text = text.replacingOccurrences(of: "+", with: "-")
+ text = text.replacingOccurrences(of: "/", with: "_")
+ while text.hasSuffix("=") { text.removeLast() }
+ return text
+ }
+
+ static func encode(_ text: String) -> String {
+ encode(Data(text.utf8))
+ }
+
+ static func decode(_ text: String) -> Data? {
+ // 只接受合法字母表,避免把任意输入喂给 Data(base64Encoded:)
+ // 后得到一个「解出来了但不是原意」的结果。
+ guard !text.isEmpty else { return Data() }
+ for scalar in text.unicodeScalars {
+ switch scalar {
+ case "A"..."Z", "a"..."z", "0"..."9", "-", "_":
+ continue
+ default:
+ return nil
+ }
+ }
+ var padded = text.replacingOccurrences(of: "-", with: "+")
+ padded = padded.replacingOccurrences(of: "_", with: "/")
+ let remainder = padded.count % 4
+ if remainder == 1 { return nil } // 不可能出现的长度
+ if remainder != 0 {
+ padded.append(String(repeating: "=", count: 4 - remainder))
+ }
+ return Data(base64Encoded: padded)
+ }
+
+ static func decodeString(_ text: String) -> String? {
+ guard let data = decode(text) else { return nil }
+ return String(data: data, encoding: .utf8)
+ }
+}
diff --git a/ios/QFT/Core/DownloadClient.swift b/ios/QFT/Core/DownloadClient.swift
new file mode 100644
index 0000000..2a25e9b
--- /dev/null
+++ b/ios/QFT/Core/DownloadClient.swift
@@ -0,0 +1,210 @@
+import Foundation
+import CryptoKit
+
+struct TransferProgress {
+ let completed: UInt64
+ let total: UInt64
+ let bytesPerSecond: Double
+
+ var fraction: Double {
+ total == 0 ? 1 : min(1, Double(completed) / Double(total))
+ }
+}
+
+/// 电脑 → 手机下载(QFTSEND2)。
+///
+/// 边收边写盘、边算 SHA-256,中断后用 `Range: bytes=N-` 续传。
+/// Windows 端 `sender.rs` 只支持单段 Range,这里也只发单段。
+final class DownloadClient: NSObject {
+
+ private let host: QFTHost
+ private let pairing: PairingPayload
+ private let deviceName: String
+ /// 落盘目录。默认 Documents/QFT(会出现在「文件」App 里);
+ /// 测试注入临时目录,避免碰到用户真实的文档目录。
+ private let destinationDirectory: URL?
+
+ private var fileHandle: FileHandle?
+ private var hasher = SHA256()
+ private var written: UInt64 = 0
+ private var expectedTotal: UInt64 = 0
+ private var startedAt = Date()
+ private var lastReport = Date.distantPast
+ private var onProgress: ((TransferProgress) -> Void)?
+ private var continuation: CheckedContinuation?
+ private var session: URLSession?
+
+ init(host: QFTHost, pairing: PairingPayload, deviceName: String,
+ destinationDirectory: URL? = nil) {
+ self.host = host
+ self.pairing = pairing
+ self.deviceName = deviceName
+ self.destinationDirectory = destinationDirectory
+ super.init()
+ }
+
+ /// 下载到目标目录,返回最终文件 URL。
+ func run(onProgress: @escaping (TransferProgress) -> Void) async throws -> URL {
+ let name = pairing.fileName ?? "qft-download.bin"
+ let directory = try destinationDirectory ?? Self.defaultDestinationDirectory()
+ let partURL = directory.appendingPathComponent(name + ".qftpart")
+
+ // 续传:已经落盘多少就从多少开始要
+ var resumeFrom: UInt64 = 0
+ if let attributes = try? FileManager.default.attributesOfItem(atPath: partURL.path),
+ let size = attributes[.size] as? NSNumber {
+ resumeFrom = UInt64(truncating: size)
+ }
+ if resumeFrom > 0, let declared = pairing.fileSize, resumeFrom >= declared {
+ // 断点比声明的文件还大,说明这个 .qftpart 不是本次会话的,丢弃重来
+ try? FileManager.default.removeItem(at: partURL)
+ resumeFrom = 0
+ }
+ if resumeFrom > 0 {
+ // 续传时无法复用之前的哈希中间态,重新扫一遍已落盘的部分
+ hasher = SHA256()
+ let handle = try FileHandle(forReadingFrom: partURL)
+ defer { try? handle.close() }
+ while let block = try handle.read(upToCount: 4 * 1024 * 1024), !block.isEmpty {
+ hasher.update(data: block)
+ }
+ } else {
+ FileManager.default.createFile(atPath: partURL.path, contents: nil)
+ }
+
+ self.written = resumeFrom
+ self.expectedTotal = pairing.fileSize ?? 0
+ self.onProgress = onProgress
+ self.startedAt = Date()
+ self.fileHandle = try FileHandle(forWritingTo: partURL)
+ try fileHandle?.seekToEnd()
+
+ guard let url = URL(string: host.baseURL + "/qft/download") else {
+ throw QFTError.malformedResponse("下载地址无效")
+ }
+ var request = URLRequest(url: url)
+ request.httpMethod = "GET"
+ request.timeoutInterval = 30
+ request.setValue(pairing.session, forHTTPHeaderField: "X-QFT-Token")
+ request.setValue(Base64URL.encode(deviceName), forHTTPHeaderField: "X-QFT-Device")
+ if resumeFrom > 0 {
+ request.setValue("bytes=\(resumeFrom)-", forHTTPHeaderField: "Range")
+ }
+
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = 30
+ configuration.timeoutIntervalForResource = 3600
+ let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
+ self.session = urlSession
+ defer {
+ try? fileHandle?.close()
+ fileHandle = nil
+ urlSession.invalidateAndCancel()
+ session = nil
+ }
+
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in
+ self.continuation = continuation
+ urlSession.dataTask(with: request).resume()
+ }
+
+ if let declared = pairing.fileSize, written != declared {
+ throw QFTError.integrity("收到 \(written) 字节,电脑声明 \(declared) 字节")
+ }
+ if let expected = pairing.sha256 {
+ let actual = hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ guard actual == expected else {
+ try? FileManager.default.removeItem(at: partURL)
+ throw QFTError.integrity("SHA-256 不匹配,文件已丢弃")
+ }
+ }
+
+ let finalURL = Self.uniqueURL(in: directory, name: name)
+ try FileManager.default.moveItem(at: partURL, to: finalURL)
+ return finalURL
+ }
+
+ // MARK: - 落盘目录
+
+ static func defaultDestinationDirectory() throws -> URL {
+ let documents = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
+ appropriateFor: nil, create: true)
+ let directory = documents.appendingPathComponent("QFT", isDirectory: true)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ return directory
+ }
+
+ static func uniqueURL(in directory: URL, name: String) -> URL {
+ var candidate = directory.appendingPathComponent(name)
+ guard FileManager.default.fileExists(atPath: candidate.path) else { return candidate }
+ let stem = (name as NSString).deletingPathExtension
+ let ext = (name as NSString).pathExtension
+ var index = 1
+ while FileManager.default.fileExists(atPath: candidate.path) {
+ let suffix = ext.isEmpty ? "\(stem) (\(index))" : "\(stem) (\(index)).\(ext)"
+ candidate = directory.appendingPathComponent(suffix)
+ index += 1
+ }
+ return candidate
+ }
+}
+
+extension DownloadClient: URLSessionDataDelegate {
+
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
+ didReceive response: URLResponse,
+ completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
+ guard let http = response as? HTTPURLResponse else {
+ finish(with: QFTError.malformedResponse("非 HTTP 响应"))
+ completionHandler(.cancel)
+ return
+ }
+ guard http.statusCode == 200 || http.statusCode == 206 else {
+ finish(with: QFTError.httpStatus(http.statusCode, http.statusCode == 403 ? "会话已失效,请让电脑重新生成二维码" : ""))
+ completionHandler(.cancel)
+ return
+ }
+ if expectedTotal == 0 {
+ let length = http.expectedContentLength
+ if length > 0 { expectedTotal = written + UInt64(length) }
+ }
+ completionHandler(.allow)
+ }
+
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+ do {
+ try fileHandle?.write(contentsOf: data)
+ } catch {
+ finish(with: error)
+ dataTask.cancel()
+ return
+ }
+ hasher.update(data: data)
+ written &+= UInt64(data.count)
+ report()
+ }
+
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+ if let error, (error as NSError).code != NSURLErrorCancelled {
+ finish(with: error)
+ } else {
+ report(force: true)
+ finish(with: nil)
+ }
+ }
+
+ private func report(force: Bool = false) {
+ let now = Date()
+ guard force || now.timeIntervalSince(lastReport) > 0.1 else { return }
+ lastReport = now
+ let elapsed = max(0.001, now.timeIntervalSince(startedAt))
+ onProgress?(TransferProgress(completed: written, total: expectedTotal,
+ bytesPerSecond: Double(written) / elapsed))
+ }
+
+ private func finish(with error: Error?) {
+ guard let continuation else { return }
+ self.continuation = nil
+ if let error { continuation.resume(throwing: error) } else { continuation.resume() }
+ }
+}
diff --git a/ios/QFT/Core/HostDiscovery.swift b/ios/QFT/Core/HostDiscovery.swift
new file mode 100644
index 0000000..be908d8
--- /dev/null
+++ b/ios/QFT/Core/HostDiscovery.swift
@@ -0,0 +1,271 @@
+import Foundation
+
+#if canImport(UIKit)
+import UIKit
+#endif
+
+enum DeviceInfo {
+ static var name: String {
+ #if canImport(UIKit)
+ let raw = UIDevice.current.name
+ #else
+ let raw = Host.current().localizedName ?? "iPhone"
+ #endif
+ let cleaned = raw.filter { !$0.isNewline }
+ return cleaned.isEmpty ? "iPhone" : String(cleaned.prefix(64))
+ }
+}
+
+struct QFTHost: Equatable {
+ let baseURL: String // 形如 http://192.168.1.20:39393
+}
+
+enum QFTError: LocalizedError {
+ case hostNotFound
+ case httpStatus(Int, String)
+ case malformedResponse(String)
+ case integrity(String)
+ case cancelled
+
+ var errorDescription: String? {
+ switch self {
+ case .hostNotFound:
+ return "找不到电脑。请确认手机和电脑连在同一个 Wi-Fi,并且电脑上的 QFT 正在等待连接。"
+ case .httpStatus(let code, let detail):
+ return "电脑返回 HTTP \(code)\(detail.isEmpty ? "" : ":\(detail)")"
+ case .malformedResponse(let detail):
+ return "电脑返回的数据无法解析:\(detail)"
+ case .integrity(let detail):
+ return "校验失败:\(detail)"
+ case .cancelled:
+ return "已取消"
+ }
+ }
+}
+
+/// 在局域网里定位 Windows 端。
+///
+/// 顺序:二维码自带的 endpoint → UDP QFTDISC2 广播 → 当前子网有界扫描。
+/// 与 Android 端同一套策略,但去掉了 Direct-AP 相关的分支:iOS 连不上指定 AP。
+struct HostDiscovery {
+
+ let pairing: PairingPayload
+ let deviceName: String
+
+ static let discoveryPort: UInt16 = 39392
+
+ func locate() async throws -> QFTHost {
+ if let host = await probe(pairing.endpoints, timeout: 1.2) {
+ return host
+ }
+ if let hinted = await udpDiscover(timeout: 1.5),
+ let host = await probe([hinted], timeout: 1.5) {
+ return host
+ }
+ let candidates = LocalNetwork.subnetCandidates(port: pairing.port, limit: 254)
+ if !candidates.isEmpty, let host = await probe(candidates, timeout: 0.7) {
+ return host
+ }
+ throw QFTError.hostNotFound
+ }
+
+ /// 并发 ping 全部候选,返回第一个应答的。
+ func probe(_ endpoints: [String], timeout: TimeInterval) async -> QFTHost? {
+ guard !endpoints.isEmpty else { return nil }
+ return await withTaskGroup(of: QFTHost?.self) { group in
+ for endpoint in endpoints {
+ group.addTask { await Self.ping(endpoint, session: pairing.session,
+ deviceName: deviceName, timeout: timeout) }
+ }
+ for await result in group {
+ if let result {
+ group.cancelAll()
+ return result
+ }
+ }
+ return nil
+ }
+ }
+
+ static func ping(_ baseURL: String, session: String,
+ deviceName: String, timeout: TimeInterval) async -> QFTHost? {
+ guard let url = URL(string: baseURL + "/qft/ping") else { return nil }
+ var request = URLRequest(url: url)
+ request.httpMethod = "GET"
+ request.timeoutInterval = timeout
+ request.setValue(session, forHTTPHeaderField: "X-QFT-Token")
+ request.setValue(Base64URL.encode(deviceName), forHTTPHeaderField: "X-QFT-Device")
+
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = timeout
+ configuration.waitsForConnectivity = false
+ let urlSession = URLSession(configuration: configuration)
+ defer { urlSession.finishTasksAndInvalidate() }
+
+ guard let (data, response) = try? await urlSession.data(for: request),
+ let http = response as? HTTPURLResponse, http.statusCode == 200,
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ (object["ok"] as? Bool) == true else { return nil }
+ return QFTHost(baseURL: baseURL)
+ }
+
+ /// 向广播地址发 `QFTDISC2:`,等待 `QFTHERE2::`。
+ /// 返回可用的 base URL;iOS 首次调用会触发「本地网络」权限弹窗。
+ func udpDiscover(timeout: TimeInterval) async -> String? {
+ let expected = "QFTHERE2:\(pairing.session):"
+ let request = Data("QFTDISC2:\(pairing.session)".utf8)
+
+ return await withCheckedContinuation { continuation in
+ DispatchQueue.global(qos: .userInitiated).async {
+ let result = Self.udpRoundTrip(request: request,
+ expectedPrefix: expected,
+ timeout: timeout)
+ continuation.resume(returning: result)
+ }
+ }
+ }
+
+ private static func udpRoundTrip(request: Data, expectedPrefix: String,
+ timeout: TimeInterval) -> String? {
+ let fd = socket(AF_INET, SOCK_DGRAM, 0)
+ guard fd >= 0 else { return nil }
+ defer { close(fd) }
+
+ var enable: Int32 = 1
+ setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &enable, socklen_t(MemoryLayout.size))
+ var tv = timeval(tv_sec: Int(timeout), tv_usec: Int32((timeout - floor(timeout)) * 1_000_000))
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout.size))
+
+ var targets = ["255.255.255.255"]
+ if let broadcast = LocalNetwork.subnetBroadcastAddress() { targets.insert(broadcast, at: 0) }
+
+ for target in targets {
+ var address = sockaddr_in()
+ address.sin_family = sa_family_t(AF_INET)
+ address.sin_port = discoveryPort.bigEndian
+ address.sin_addr.s_addr = inet_addr(target)
+ let sent = request.withUnsafeBytes { buffer -> Int in
+ withUnsafePointer(to: &address) { pointer in
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPointer in
+ sendto(fd, buffer.baseAddress, buffer.count, 0,
+ sockPointer, socklen_t(MemoryLayout.size))
+ }
+ }
+ }
+ if sent < 0 { continue }
+ }
+
+ let deadline = Date().addingTimeInterval(timeout)
+ var buffer = [UInt8](repeating: 0, count: 512)
+ while Date() < deadline {
+ var from = sockaddr_in()
+ var fromLength = socklen_t(MemoryLayout.size)
+ let received = withUnsafeMutablePointer(to: &from) { pointer -> Int in
+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPointer in
+ recvfrom(fd, &buffer, buffer.count, 0, sockPointer, &fromLength)
+ }
+ }
+ if received <= 0 { break }
+ guard let text = String(bytes: buffer[0.. [Interface] {
+ var head: UnsafeMutablePointer?
+ guard getifaddrs(&head) == 0, let first = head else { return [] }
+ defer { freeifaddrs(head) }
+
+ var result: [Interface] = []
+ var cursor: UnsafeMutablePointer? = first
+ while let entry = cursor {
+ defer { cursor = entry.pointee.ifa_next }
+ guard let rawAddress = entry.pointee.ifa_addr,
+ rawAddress.pointee.sa_family == UInt8(AF_INET) else { continue }
+ let flags = Int32(entry.pointee.ifa_flags)
+ guard flags & IFF_UP != 0, flags & IFF_LOOPBACK == 0 else { continue }
+
+ guard let address = describe(rawAddress),
+ let maskPointer = entry.pointee.ifa_netmask,
+ let netmask = describe(maskPointer) else { continue }
+ guard PairingProtocol.isPrivateIPv4(address) else { continue }
+ result.append(Interface(name: String(cString: entry.pointee.ifa_name),
+ address: address, netmask: netmask))
+ }
+ // en0 是 iPhone 的 Wi-Fi 接口,优先于蜂窝/热点接口
+ return result.sorted { lhs, _ in lhs.name == "en0" }
+ }
+
+ private static func describe(_ address: UnsafeMutablePointer) -> String? {
+ var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
+ let length = socklen_t(MemoryLayout.size)
+ guard getnameinfo(address, length, &host, socklen_t(host.count),
+ nil, 0, NI_NUMERICHOST) == 0 else { return nil }
+ return String(cString: host)
+ }
+
+ static func subnetBroadcastAddress() -> String? {
+ guard let iface = activeInterfaces().first,
+ let ip = ipv4(iface.address), let mask = ipv4(iface.netmask) else { return nil }
+ return format(ip | ~mask)
+ }
+
+ /// 当前子网内的候选地址。仅在 /24 或更小的子网上启用,
+ /// 避免在大网段里做无意义的上千次探测。
+ static func subnetCandidates(port: Int, limit: Int) -> [String] {
+ guard let iface = activeInterfaces().first,
+ let ip = ipv4(iface.address), let mask = ipv4(iface.netmask) else { return [] }
+ let hostBits = (~mask).nonzeroBitCount
+ guard hostBits > 0, hostBits <= 8 else { return [] }
+
+ let network = ip & mask
+ let broadcast = ip | ~mask
+ var result: [String] = []
+ var candidate = network &+ 1
+ while candidate < broadcast && result.count < limit {
+ if candidate != ip { result.append("http://\(format(candidate)):\(port)") }
+ candidate &+= 1
+ }
+ // 网关通常是 .1,多半就是那台开热点/路由的机器,放最前面
+ if let gatewayIndex = result.firstIndex(of: "http://\(format(network &+ 1)):\(port)") {
+ result.swapAt(0, gatewayIndex)
+ }
+ return result
+ }
+
+ static func ipv4(_ text: String) -> UInt32? {
+ let parts = text.split(separator: ".", omittingEmptySubsequences: false)
+ guard parts.count == 4 else { return nil }
+ var value: UInt32 = 0
+ for part in parts {
+ guard let octet = UInt32(part), octet <= 255 else { return nil }
+ value = (value << 8) | octet
+ }
+ return value
+ }
+
+ static func format(_ value: UInt32) -> String {
+ "\((value >> 24) & 0xff).\((value >> 16) & 0xff).\((value >> 8) & 0xff).\(value & 0xff)"
+ }
+}
diff --git a/ios/QFT/Core/PairingProtocol.swift b/ios/QFT/Core/PairingProtocol.swift
new file mode 100644
index 0000000..56d36ea
--- /dev/null
+++ b/ios/QFT/Core/PairingProtocol.swift
@@ -0,0 +1,188 @@
+import Foundation
+
+enum TransferDirection: String {
+ case uploadToPC = "u" // QFTPAIR2:手机把文件传给电脑
+ case downloadToPhone = "d" // QFTSEND2:电脑已选好文件,手机扫码后下载
+}
+
+struct WifiCredentials: Equatable {
+ let ssid: String
+ let passphrase: String
+}
+
+struct PairingPayload: Equatable {
+ let version: Int
+ let session: String
+ let pcName: String
+ let port: Int
+ let endpoints: [String]
+ let wifi: WifiCredentials?
+ let direction: TransferDirection
+ let fileName: String?
+ let fileSize: UInt64?
+ let sha256: String?
+}
+
+/// QFTPAIR2 / QFTSEND2 配对二维码解析。
+///
+/// 二维码是**不可信输入**:它决定了 App 接下来去连哪个地址。因此这里只接受
+/// 字面量私有 IPv4 + 二维码自称的端口,任何域名、公网地址、带 query/fragment
+/// 的 URL 一律拒绝——与 Windows/Android 两端的校验保持一致。
+enum PairingProtocol {
+
+ static let prefixUpload = "QFTPAIR2:"
+ static let prefixDownload = "QFTSEND2:"
+
+ static func isPairingText(_ text: String) -> Bool {
+ text.hasPrefix(prefixUpload) || text.hasPrefix(prefixDownload)
+ }
+
+ static func parse(_ text: String) -> PairingPayload? {
+ guard text.count <= 4096 else { return nil }
+ if text.hasPrefix(prefixUpload) {
+ return parseV2(String(text.dropFirst(prefixUpload.count)), expected: .uploadToPC)
+ }
+ if text.hasPrefix(prefixDownload) {
+ return parseV2(String(text.dropFirst(prefixDownload.count)), expected: .downloadToPhone)
+ }
+ return nil
+ }
+
+ private static func parseV2(_ encoded: String, expected: TransferDirection) -> PairingPayload? {
+ guard let data = Base64URL.decode(encoded), data.count <= 2048 else { return nil }
+ guard let root = try? JSONSerialization.jsonObject(with: data),
+ let object = root as? [String: Any] else { return nil }
+ guard (object["v"] as? Int) == 2 else { return nil }
+
+ // 缺省为 "u",与 Windows 端「上传 QR 不写 d 字段」的编码方式对应
+ let rawDirection = (object["d"] as? String) ?? "u"
+ guard let direction = TransferDirection(rawValue: rawDirection),
+ direction == expected else { return nil }
+
+ guard let session = object["s"] as? String, isValidSession(session) else { return nil }
+ guard let port = object["p"] as? Int, (1...65535).contains(port) else { return nil }
+
+ var wifi: WifiCredentials?
+ if let array = object["w"] as? [Any], array.count >= 2,
+ let ssid = array[0] as? String, let passphrase = array[1] as? String {
+ guard isValidWifi(ssid: ssid, passphrase: passphrase) else { return nil }
+ wifi = WifiCredentials(ssid: ssid, passphrase: passphrase)
+ }
+
+ var endpoints: [String] = []
+ if let array = object["e"] as? [Any] {
+ for item in array {
+ guard let raw = item as? String else { continue }
+ var value = raw.trimmingCharacters(in: .whitespaces)
+ while value.hasSuffix("/") { value.removeLast() }
+ if isAllowedLocalHTTPEndpoint(value, expectedPort: port), !endpoints.contains(value) {
+ endpoints.append(value)
+ }
+ }
+ }
+ // iOS 无法用代码加入指定 Wi-Fi(NEHotspotConfiguration 需要付费账号的
+ // entitlement),所以 Direct-AP 二维码在本端必须自带可用 endpoint。
+ if endpoints.isEmpty { return nil }
+
+ var fileName: String?
+ var fileSize: UInt64?
+ var sha256: String?
+ if direction == .downloadToPhone {
+ guard let name = (object["f"] as? String)?.trimmingCharacters(in: .whitespaces),
+ isValidFileName(name) else { return nil }
+ guard let size = object["z"] as? NSNumber, size.int64Value >= 0 else { return nil }
+ guard let hash = (object["h"] as? String)?.lowercased(), isValidSHA256(hash) else { return nil }
+ fileName = name
+ fileSize = UInt64(size.int64Value)
+ sha256 = hash
+ }
+
+ let pcName = String(((object["n"] as? String) ?? "Windows-PC").prefix(80))
+ return PairingPayload(
+ version: 2,
+ session: session,
+ pcName: pcName,
+ port: port,
+ endpoints: endpoints,
+ wifi: wifi,
+ direction: direction,
+ fileName: fileName,
+ fileSize: fileSize,
+ sha256: sha256
+ )
+ }
+
+ // MARK: - 校验
+
+ static func isValidSession(_ value: String) -> Bool {
+ guard (20...64).contains(value.count) else { return false }
+ for scalar in value.unicodeScalars {
+ switch scalar {
+ case "A"..."Z", "a"..."z", "0"..."9", "-", "_": continue
+ default: return false
+ }
+ }
+ return true
+ }
+
+ static func isValidWifi(ssid: String, passphrase: String) -> Bool {
+ !ssid.trimmingCharacters(in: .whitespaces).isEmpty
+ && Data(ssid.utf8).count <= 32
+ && (8...63).contains(passphrase.count)
+ }
+
+ static func isValidFileName(_ value: String) -> Bool {
+ guard !value.isEmpty, value.count <= 180 else { return false }
+ let forbidden: Set = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|"]
+ for scalar in value.unicodeScalars {
+ if scalar.value <= 31 || scalar.value == 127 { return false }
+ if forbidden.contains(scalar) { return false }
+ }
+ return true
+ }
+
+ static func isValidSHA256(_ value: String) -> Bool {
+ guard value.count == 64 else { return false }
+ for scalar in value.unicodeScalars {
+ switch scalar {
+ case "0"..."9", "a"..."f": continue
+ default: return false
+ }
+ }
+ return true
+ }
+
+ /// 只允许 `http://<私有 IPv4 字面量>:<期望端口>`。
+ /// 故意不使用 URL/URLComponents 的宽松解析:它会接受域名、IPv6、
+ /// 带凭据的 URL 等本协议不该出现的形态。
+ static func isAllowedLocalHTTPEndpoint(_ value: String, expectedPort: Int) -> Bool {
+ guard value.hasPrefix("http://") else { return false }
+ let rest = String(value.dropFirst("http://".count))
+ guard !rest.contains("@"), !rest.contains("?"), !rest.contains("#"),
+ !rest.contains("/") else { return false }
+ let parts = rest.split(separator: ":", omittingEmptySubsequences: false)
+ guard parts.count == 2, let port = Int(parts[1]), port == expectedPort else { return false }
+ return isPrivateIPv4(String(parts[0]))
+ }
+
+ static func isPrivateIPv4(_ host: String) -> Bool {
+ let octets = host.split(separator: ".", omittingEmptySubsequences: false)
+ guard octets.count == 4 else { return false }
+ var values: [Int] = []
+ for octet in octets {
+ // 拒绝 "01"、"+1"、空段这类非规范写法
+ guard !octet.isEmpty, octet.count <= 3, octet.allSatisfy({ $0.isASCII && $0.isNumber }),
+ let value = Int(octet), (0...255).contains(value),
+ octet.count == 1 || !octet.hasPrefix("0") else { return false }
+ values.append(value)
+ }
+ switch (values[0], values[1]) {
+ case (10, _): return true
+ case (127, _): return true
+ case (169, 254): return true
+ case (172, 16...31): return true
+ case (192, 168): return true
+ default: return false
+ }
+ }
+}
diff --git a/ios/QFT/Core/PeerLink.swift b/ios/QFT/Core/PeerLink.swift
new file mode 100644
index 0000000..39735bd
--- /dev/null
+++ b/ios/QFT/Core/PeerLink.swift
@@ -0,0 +1,469 @@
+import Foundation
+import Network
+import CryptoKit
+
+/// 点对点链路:Bonjour 发现 + TLS-PSK 加密 + 长度前缀分帧。
+///
+/// `includePeerToPeer = true` 让 Network.framework 在没有路由器时
+/// 自动使用 BLE 发现 + AWDL 点对点 Wi-Fi,也就是 AirDrop 用的同一条链路。
+/// 两台设备在同一个 Wi-Fi 下时它会优先走基础网络,速度同样很快。
+///
+/// AWDL 是苹果私有链路,Windows 无法参与——PC 方向仍走 HTTP 局域网路径。
+enum PeerLink {
+
+ static let frameHeaderSize = 5 // 1 字节类型 + 4 字节 BE 长度
+ static let chunkSize = 256 * 1024
+ static let maxFrameSize = 4 * 1024 * 1024
+
+ enum FrameType: UInt8 {
+ case manifest = 1
+ case data = 2
+ case eof = 3
+ case result = 4
+ }
+
+ enum PeerError: LocalizedError {
+ case handshake(String)
+ case protocolViolation(String)
+ case rejected(String)
+ case timeout
+
+ var errorDescription: String? {
+ switch self {
+ case .handshake(let detail): return "建立加密连接失败:\(detail)"
+ case .protocolViolation(let detail): return "对方发来的数据不符合协议:\(detail)"
+ case .rejected(let detail): return "对方拒绝了传输:\(detail)"
+ case .timeout: return "等待对方超时"
+ }
+ }
+ }
+
+ /// TLS-PSK 参数。密钥来自二维码,因此不需要任何证书体系,
+ /// 且扫码这个动作本身就完成了双向认证——中间人拿不到密钥就握不了手。
+ static func parameters(key: Data, identity: String) -> NWParameters {
+ let tls = NWProtocolTLS.Options()
+ let keyData = key.withUnsafeBytes { DispatchData(bytes: $0) }
+ let identityData = Data(identity.utf8).withUnsafeBytes { DispatchData(bytes: $0) }
+
+ sec_protocol_options_add_pre_shared_key(
+ tls.securityProtocolOptions,
+ keyData as __DispatchData,
+ identityData as __DispatchData)
+ if let suite = tls_ciphersuite_t(rawValue: UInt16(TLS_PSK_WITH_AES_128_GCM_SHA256)) {
+ sec_protocol_options_append_tls_ciphersuite(tls.securityProtocolOptions, suite)
+ }
+
+ let tcp = NWProtocolTCP.Options()
+ tcp.noDelay = true
+ // 传输是一次性的,对端消失时不要长时间挂着
+ tcp.connectionTimeout = 10
+ tcp.enableKeepalive = true
+ tcp.keepaliveIdle = 5
+
+ let parameters = NWParameters(tls: tls, tcp: tcp)
+ parameters.includePeerToPeer = true
+ return parameters
+ }
+
+ // MARK: - 分帧收发
+
+ static func send(_ connection: NWConnection, type: FrameType, payload: Data) async throws {
+ var header = Data([type.rawValue])
+ var length = UInt32(payload.count).bigEndian
+ withUnsafeBytes(of: &length) { header.append(contentsOf: $0) }
+
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in
+ connection.send(content: header + payload,
+ completion: .contentProcessed { error in
+ if let error { continuation.resume(throwing: error) } else { continuation.resume() }
+ })
+ }
+ }
+
+ static func receiveFrame(_ connection: NWConnection) async throws -> (FrameType, Data) {
+ let header = try await receiveExactly(connection, count: frameHeaderSize)
+ guard let type = FrameType(rawValue: header[header.startIndex]) else {
+ throw PeerError.protocolViolation("未知帧类型 \(header[header.startIndex])")
+ }
+ let length = header[(header.startIndex + 1)...].withUnsafeBytes {
+ UInt32(bigEndian: $0.loadUnaligned(as: UInt32.self))
+ }
+ guard length <= UInt32(maxFrameSize) else {
+ throw PeerError.protocolViolation("帧长度 \(length) 超出上限")
+ }
+ if length == 0 { return (type, Data()) }
+ return (type, try await receiveExactly(connection, count: Int(length)))
+ }
+
+ static func receiveExactly(_ connection: NWConnection, count: Int) async throws -> Data {
+ var buffer = Data()
+ buffer.reserveCapacity(count)
+ while buffer.count < count {
+ let remaining = count - buffer.count
+ let block = try await withCheckedThrowingContinuation {
+ (continuation: CheckedContinuation) in
+ connection.receive(minimumIncompleteLength: 1, maximumLength: remaining) {
+ content, _, isComplete, error in
+ if let error { continuation.resume(throwing: error); return }
+ if let content, !content.isEmpty { continuation.resume(returning: content); return }
+ if isComplete {
+ continuation.resume(throwing: PeerError.protocolViolation("连接提前关闭"))
+ } else {
+ continuation.resume(returning: Data())
+ }
+ }
+ }
+ buffer.append(block)
+ }
+ return buffer
+ }
+
+ static func waitReady(_ connection: NWConnection, queue: DispatchQueue,
+ timeout: TimeInterval = 15) async throws {
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in
+ let resumed = Locked(false)
+ func finish(_ error: Error?) {
+ guard resumed.exchange(true) == false else { return }
+ if let error { continuation.resume(throwing: error) } else { continuation.resume() }
+ }
+
+ connection.stateUpdateHandler = { state in
+ switch state {
+ case .ready:
+ finish(nil)
+ case .failed(let error):
+ finish(error)
+ case .waiting(let error):
+ // NWConnection 默认会在 .waiting 里无限重试。对一次性传输来说:
+ // TLS 类错误(密钥不匹配、对端拒绝)不可能自愈,立刻失败;
+ // 而链路层的暂时不可达在 AWDL/Bonjour 起来之前是正常现象,继续等。
+ if case .tls = error {
+ finish(PeerError.handshake("预共享密钥不匹配,或对方已结束这次会话"))
+ }
+ case .cancelled:
+ finish(PeerError.handshake("连接被取消"))
+ default:
+ break
+ }
+ }
+ queue.asyncAfter(deadline: .now() + timeout) { finish(PeerError.timeout) }
+ connection.start(queue: queue)
+ }
+ }
+}
+
+/// 极简互斥包装。continuation 只能 resume 一次,而 stateUpdateHandler
+/// 可能在多个状态里触发,需要一个原子的「是否已 resume」。
+final class Locked {
+ private var value: Value
+ private let lock = NSLock()
+
+ init(_ value: Value) { self.value = value }
+
+ func exchange(_ newValue: Value) -> Value {
+ lock.lock(); defer { lock.unlock() }
+ let old = value
+ value = newValue
+ return old
+ }
+
+ var current: Value {
+ lock.lock(); defer { lock.unlock() }
+ return value
+ }
+}
+
+// MARK: - 发送端
+
+/// 展示二维码的一方。持有文件,等待对方扫码后连入。
+final class PeerSender {
+
+ /// 监听器的状态与排队中的连接。stateUpdateHandler / newConnectionHandler
+ /// 在任意线程触发,而等待方是 async,所以两边都要经过这把锁。
+ private final class Box {
+ let lock = NSLock()
+ var readyPort: UInt16?
+ var failure: Error?
+ var pending: [NWConnection] = []
+ var portWaiter: CheckedContinuation?
+ var connectionWaiter: CheckedContinuation?
+
+ /// 同步方法:async 上下文里不允许直接调用 NSLock.lock()
+ func drainPending() -> [NWConnection] {
+ lock.lock(); defer { lock.unlock() }
+ let extras = pending
+ pending = []
+ return extras
+ }
+ }
+
+ private let fileURL: URL
+ private let deviceName: String
+ private let queue = DispatchQueue(label: "qft.peer.sender")
+ private let box = Box()
+ private var listener: NWListener?
+ private var pairing: PeerPairing?
+
+ init(fileURL: URL, deviceName: String) {
+ self.fileURL = fileURL
+ self.deviceName = deviceName
+ }
+
+ /// 等待监听就绪并返回实际端口。P2P 场景下对端靠 Bonjour 实例名找过来,
+ /// 端口只在测试直连时才需要。
+ func listeningPort() async throws -> UInt16 {
+ try await withCheckedThrowingContinuation { continuation in
+ box.lock.lock()
+ if let port = box.readyPort {
+ box.lock.unlock(); continuation.resume(returning: port)
+ } else if let failure = box.failure {
+ box.lock.unlock(); continuation.resume(throwing: failure)
+ } else {
+ box.portWaiter = continuation
+ box.lock.unlock()
+ }
+ }
+ }
+
+ /// 计算文件摘要、启动监听并广播 Bonjour 服务,返回要显示成二维码的配对码。
+ func start() throws -> PeerPairing {
+ let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
+ let size = UInt64(truncating: (attributes[.size] as? NSNumber) ?? 0)
+
+ var hasher = SHA256()
+ let handle = try FileHandle(forReadingFrom: fileURL)
+ while let block = try handle.read(upToCount: 4 * 1024 * 1024), !block.isEmpty {
+ hasher.update(data: block)
+ }
+ try handle.close()
+ let digest = hasher.finalize().map { String(format: "%02x", $0) }.joined()
+
+ let pairing = PeerPairing(
+ version: 1,
+ key: PeerPairing.newKey(),
+ instance: PeerPairing.newInstance(),
+ senderName: deviceName,
+ fileName: fileURL.lastPathComponent,
+ fileSize: size,
+ sha256: digest)
+
+ let parameters = PeerLink.parameters(key: pairing.key, identity: pairing.instance)
+ let listener = try NWListener(using: parameters)
+ listener.service = NWListener.Service(name: pairing.instance,
+ type: PeerPairing.serviceType)
+
+ listener.stateUpdateHandler = { [box] state in
+ switch state {
+ case .ready:
+ box.lock.lock()
+ box.readyPort = listener.port?.rawValue
+ let waiter = box.portWaiter
+ box.portWaiter = nil
+ box.lock.unlock()
+ if let port = listener.port?.rawValue { waiter?.resume(returning: port) }
+ case .failed(let error):
+ box.lock.lock()
+ box.failure = error
+ let portWaiter = box.portWaiter
+ let connectionWaiter = box.connectionWaiter
+ box.portWaiter = nil
+ box.connectionWaiter = nil
+ box.lock.unlock()
+ portWaiter?.resume(throwing: error)
+ connectionWaiter?.resume(throwing: error)
+ default:
+ break
+ }
+ }
+ listener.newConnectionHandler = { [box] connection in
+ box.lock.lock()
+ if let waiter = box.connectionWaiter {
+ box.connectionWaiter = nil
+ box.lock.unlock()
+ waiter.resume(returning: connection)
+ } else {
+ box.pending.append(connection)
+ box.lock.unlock()
+ }
+ }
+ listener.start(queue: queue)
+
+ self.listener = listener
+ self.pairing = pairing
+ return pairing
+ }
+
+ /// 等待一个连接并把文件推过去。
+ func waitAndSend(onProgress: @escaping (TransferProgress) -> Void) async throws {
+ guard let listener, let pairing else {
+ throw PeerLink.PeerError.handshake("尚未调用 start()")
+ }
+
+ let connection = try await withCheckedThrowingContinuation {
+ (continuation: CheckedContinuation) in
+ box.lock.lock()
+ if !box.pending.isEmpty {
+ let first = box.pending.removeFirst()
+ box.lock.unlock()
+ continuation.resume(returning: first)
+ } else if let failure = box.failure {
+ box.lock.unlock()
+ continuation.resume(throwing: failure)
+ } else {
+ box.connectionWaiter = continuation
+ box.lock.unlock()
+ }
+ }
+ // 一次会话只服务一个对端,其余排队的连接直接断开
+ box.drainPending().forEach { $0.cancel() }
+
+ defer { connection.cancel(); listener.cancel() }
+
+ try await PeerLink.waitReady(connection, queue: queue)
+
+ let manifest: [String: Any] = [
+ "name": pairing.fileName,
+ "size": NSNumber(value: pairing.fileSize),
+ "sha256": pairing.sha256,
+ "sender": pairing.senderName,
+ ]
+ try await PeerLink.send(connection, type: .manifest,
+ payload: try JSONSerialization.data(withJSONObject: manifest))
+
+ let handle = try FileHandle(forReadingFrom: fileURL)
+ defer { try? handle.close() }
+ var sent: UInt64 = 0
+ let startedAt = Date()
+ var lastReport = Date.distantPast
+
+ while let block = try handle.read(upToCount: PeerLink.chunkSize), !block.isEmpty {
+ try Task.checkCancellation()
+ try await PeerLink.send(connection, type: .data, payload: block)
+ sent &+= UInt64(block.count)
+ let now = Date()
+ if now.timeIntervalSince(lastReport) > 0.1 || sent >= pairing.fileSize {
+ lastReport = now
+ onProgress(TransferProgress(
+ completed: sent, total: pairing.fileSize,
+ bytesPerSecond: Double(sent) / max(0.001, now.timeIntervalSince(startedAt))))
+ }
+ }
+ try await PeerLink.send(connection, type: .eof, payload: Data())
+
+ let (type, payload) = try await PeerLink.receiveFrame(connection)
+ guard type == .result,
+ let object = try? JSONSerialization.jsonObject(with: payload) as? [String: Any] else {
+ throw PeerLink.PeerError.protocolViolation("收尾帧无效")
+ }
+ if (object["ok"] as? Bool) != true {
+ throw PeerLink.PeerError.rejected((object["error"] as? String) ?? "对方未说明原因")
+ }
+ }
+
+ func stop() {
+ listener?.cancel()
+ listener = nil
+ }
+}
+
+// MARK: - 接收端
+
+/// 扫码的一方。按实例名找到对端并接收文件。
+struct PeerReceiver {
+
+ let pairing: PeerPairing
+ let destinationDirectory: URL
+ /// 测试用:跳过 Bonjour,直接连指定端口。
+ var directPort: UInt16?
+
+ func run(onProgress: @escaping (TransferProgress) -> Void) async throws -> URL {
+ let queue = DispatchQueue(label: "qft.peer.receiver")
+ let parameters = PeerLink.parameters(key: pairing.key, identity: pairing.instance)
+
+ let endpoint: NWEndpoint
+ if let directPort {
+ endpoint = .hostPort(host: .ipv4(.loopback), port: .init(rawValue: directPort)!)
+ } else {
+ endpoint = .service(name: pairing.instance, type: PeerPairing.serviceType,
+ domain: "local", interface: nil)
+ }
+
+ let connection = NWConnection(to: endpoint, using: parameters)
+ defer { connection.cancel() }
+ try await PeerLink.waitReady(connection, queue: queue)
+
+ // --- 清单 ---
+ let (manifestType, manifestPayload) = try await PeerLink.receiveFrame(connection)
+ guard manifestType == .manifest,
+ let manifest = try? JSONSerialization.jsonObject(with: manifestPayload) as? [String: Any],
+ let declaredSize = (manifest["size"] as? NSNumber)?.uint64Value,
+ let declaredHash = manifest["sha256"] as? String else {
+ throw PeerLink.PeerError.protocolViolation("清单帧无效")
+ }
+ // 清单必须与二维码一致,否则说明连到的不是扫码时看到的那个文件
+ guard declaredSize == pairing.fileSize, declaredHash == pairing.sha256 else {
+ try? await PeerLink.send(connection, type: .result, payload: Data(
+ #"{"ok":false,"error":"manifest mismatch"}"#.utf8))
+ throw PeerLink.PeerError.protocolViolation("对方声明的文件与二维码不符")
+ }
+
+ try FileManager.default.createDirectory(at: destinationDirectory,
+ withIntermediateDirectories: true)
+ let partURL = destinationDirectory.appendingPathComponent(pairing.fileName + ".qftpart")
+ try? FileManager.default.removeItem(at: partURL)
+ FileManager.default.createFile(atPath: partURL.path, contents: nil)
+ let handle = try FileHandle(forWritingTo: partURL)
+
+ var hasher = SHA256()
+ var received: UInt64 = 0
+ let startedAt = Date()
+ var lastReport = Date.distantPast
+
+ // --- 数据 ---
+ do {
+ loop: while true {
+ try Task.checkCancellation()
+ let (type, payload) = try await PeerLink.receiveFrame(connection)
+ switch type {
+ case .data:
+ guard received &+ UInt64(payload.count) <= pairing.fileSize else {
+ throw PeerLink.PeerError.protocolViolation("收到的数据超出声明大小")
+ }
+ try handle.write(contentsOf: payload)
+ hasher.update(data: payload)
+ received &+= UInt64(payload.count)
+ let now = Date()
+ if now.timeIntervalSince(lastReport) > 0.1 || received >= pairing.fileSize {
+ lastReport = now
+ onProgress(TransferProgress(
+ completed: received, total: pairing.fileSize,
+ bytesPerSecond: Double(received) / max(0.001, now.timeIntervalSince(startedAt))))
+ }
+ case .eof:
+ break loop
+ default:
+ throw PeerLink.PeerError.protocolViolation("数据阶段收到 \(type)")
+ }
+ }
+ try handle.close()
+ } catch {
+ try? handle.close()
+ try? FileManager.default.removeItem(at: partURL)
+ throw error
+ }
+
+ // --- 校验 ---
+ let actual = hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ guard received == pairing.fileSize, actual == pairing.sha256 else {
+ try? FileManager.default.removeItem(at: partURL)
+ try? await PeerLink.send(connection, type: .result, payload: Data(
+ #"{"ok":false,"error":"integrity"}"#.utf8))
+ throw QFTError.integrity("收到 \(received)/\(pairing.fileSize) 字节,SHA-256 \(actual == pairing.sha256 ? "一致" : "不一致")")
+ }
+
+ let finalURL = DownloadClient.uniqueURL(in: destinationDirectory, name: pairing.fileName)
+ try FileManager.default.moveItem(at: partURL, to: finalURL)
+ try await PeerLink.send(connection, type: .result, payload: Data(#"{"ok":true}"#.utf8))
+ return finalURL
+ }
+}
diff --git a/ios/QFT/Core/PeerPairing.swift b/ios/QFT/Core/PeerPairing.swift
new file mode 100644
index 0000000..19e7feb
--- /dev/null
+++ b/ios/QFT/Core/PeerPairing.swift
@@ -0,0 +1,94 @@
+import Foundation
+import Security
+
+/// 隔空投送式点对点配对码。
+///
+/// 与 QFTPAIR2/QFTSEND2 的关键区别:那两个是「连到某个 IP」,
+/// 这个是「连到某个 Bonjour 服务实例,并用二维码里的预共享密钥做 TLS 认证」。
+/// 二维码在这里充当带外信道——和 AirDrop 用 BLE 交换身份是同一个作用,
+/// 只是我们把身份交换搬到了用户可见的扫码动作上,不需要任何配对弹窗。
+struct PeerPairing: Equatable {
+ static let prefix = "QFTP2P1:"
+
+ let version: Int
+ /// 32 字节预共享密钥。既是 TLS-PSK,也是服务实例的唯一凭据。
+ let key: Data
+ /// Bonjour 服务实例名,由发送端随机生成
+ let instance: String
+ let senderName: String
+ let fileName: String
+ let fileSize: UInt64
+ let sha256: String
+
+ static let serviceType = "_qft-p2p._tcp"
+
+ func encode() -> String {
+ let object: [String: Any] = [
+ "v": version,
+ "k": Base64URL.encode(key),
+ "i": instance,
+ "n": senderName,
+ "f": fileName,
+ "z": NSNumber(value: fileSize),
+ "h": sha256,
+ ]
+ let data = (try? JSONSerialization.data(withJSONObject: object)) ?? Data()
+ return Self.prefix + Base64URL.encode(data)
+ }
+
+ static func isPeerText(_ text: String) -> Bool { text.hasPrefix(prefix) }
+
+ static func parse(_ text: String) -> PeerPairing? {
+ guard text.hasPrefix(prefix), text.count <= 4096 else { return nil }
+ guard let data = Base64URL.decode(String(text.dropFirst(prefix.count))),
+ data.count <= 2048,
+ let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {
+ return nil
+ }
+ guard (object["v"] as? Int) == 1 else { return nil }
+ guard let keyText = object["k"] as? String,
+ let key = Base64URL.decode(keyText), key.count == 32 else { return nil }
+ guard let instance = object["i"] as? String, isValidInstance(instance) else { return nil }
+ guard let fileName = (object["f"] as? String)?.trimmingCharacters(in: .whitespaces),
+ PairingProtocol.isValidFileName(fileName) else { return nil }
+ guard let size = object["z"] as? NSNumber, size.int64Value >= 0 else { return nil }
+ guard let hash = (object["h"] as? String)?.lowercased(),
+ PairingProtocol.isValidSHA256(hash) else { return nil }
+
+ return PeerPairing(
+ version: 1,
+ key: key,
+ instance: instance,
+ senderName: String(((object["n"] as? String) ?? "iPhone").prefix(80)),
+ fileName: fileName,
+ fileSize: UInt64(size.int64Value),
+ sha256: hash
+ )
+ }
+
+ /// Bonjour 实例名:只允许我们自己生成的字符集,避免把任意字符串
+ /// 交给 mDNS 解析。
+ static func isValidInstance(_ value: String) -> Bool {
+ guard (8...48).contains(value.count) else { return false }
+ for scalar in value.unicodeScalars {
+ switch scalar {
+ case "A"..."Z", "a"..."z", "0"..."9", "-": continue
+ default: return false
+ }
+ }
+ return true
+ }
+
+ static func newKey() -> Data {
+ var bytes = [UInt8](repeating: 0, count: 32)
+ _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
+ return Data(bytes)
+ }
+
+ static func newInstance() -> String {
+ let alphabet = Array("abcdefghijklmnopqrstuvwxyz0123456789")
+ var bytes = [UInt8](repeating: 0, count: 16)
+ _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
+ return "qft-" + String(bytes.map { alphabet[Int($0) % alphabet.count] })
+ }
+}
diff --git a/ios/QFT/Core/UploadClient.swift b/ios/QFT/Core/UploadClient.swift
new file mode 100644
index 0000000..fab2b8e
--- /dev/null
+++ b/ios/QFT/Core/UploadClient.swift
@@ -0,0 +1,189 @@
+import Foundation
+
+/// 手机 → 电脑并行上传(QFTPAIR2)。
+///
+/// 与 Android 端同一套 v2 流程:init → 并行 chunk → finish。
+/// Windows 端 `receiver.rs` 会预分配 `.qftpart`、按 offset 定位写入、
+/// 校验 SHA-256 后 rename,因此 chunk 之间没有顺序要求,重复 chunk 也是幂等的。
+///
+/// 与 Android 的唯一差异是**块大小固定 4 MiB**:Android 会按文件大小选 4/8/16 MiB,
+/// 但 iOS 上 `workers × chunkSize` 就是内存峰值,16 MiB × 6 会在旧机型上触发
+/// jetsam。4 MiB × 6 = 24 MiB 峰值,在局域网速度下每块的往返开销可以忽略。
+struct UploadClient {
+
+ let host: QFTHost
+ let pairing: PairingPayload
+ let deviceName: String
+
+ static let chunkSize: UInt64 = 4 * 1024 * 1024
+ static let maxWorkers = 6
+
+ struct Session {
+ let uploadID: String
+ let chunkSize: UInt64
+ let totalChunks: Int
+ }
+
+ func run(fileURL: URL, onProgress: @escaping (TransferProgress) -> Void) async throws -> String {
+ let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
+ let size = UInt64(truncating: (attributes[.size] as? NSNumber) ?? 0)
+ let name = fileURL.lastPathComponent
+
+ let session = try await initUpload(name: name, size: size)
+ if session.totalChunks == 0 {
+ return try await finishUpload(session)
+ }
+
+ let counter = ByteCounter(total: size, onProgress: onProgress)
+ let queue = IndexQueue(count: session.totalChunks)
+
+ try await withThrowingTaskGroup(of: Void.self) { group in
+ let workers = min(session.totalChunks, Self.maxWorkers)
+ for _ in 0.. Session {
+ var request = try makeRequest(path: "/qft/upload/init")
+ request.setValue(Base64URL.encode(name), forHTTPHeaderField: "X-QFT-Filename")
+ request.setValue(String(size), forHTTPHeaderField: "X-QFT-Size")
+ request.setValue(String(Self.chunkSize), forHTTPHeaderField: "X-QFT-Chunk-Size")
+ request.setValue("0", forHTTPHeaderField: "Content-Length")
+
+ let object = try await sendJSON(request, body: Data())
+ guard let uploadID = object["upload_id"] as? String, !uploadID.isEmpty,
+ let chunkSize = (object["chunk_size"] as? NSNumber)?.uint64Value, chunkSize > 0,
+ let totalChunks = (object["total_chunks"] as? NSNumber)?.intValue, totalChunks >= 0 else {
+ throw QFTError.malformedResponse("init 响应缺少字段")
+ }
+ return Session(uploadID: uploadID, chunkSize: chunkSize, totalChunks: totalChunks)
+ }
+
+ private func uploadChunk(_ session: Session, index: Int, body: Data) async throws {
+ var request = try makeRequest(path: "/qft/upload/chunk/\(session.uploadID)/\(index)")
+ request.setValue(String(body.count), forHTTPHeaderField: "Content-Length")
+
+ // 重复的 chunk 在接收端是幂等的,因此重试是安全的。
+ // Wi-Fi 漫游或 Windows 防火墙首次放行都可能吃掉第一次请求。
+ var lastError: Error = QFTError.malformedResponse("未知错误")
+ for attempt in 0..<3 {
+ do {
+ _ = try await sendJSON(request, body: body)
+ return
+ } catch {
+ lastError = error
+ if case QFTError.httpStatus(let code, _) = error, code == 403 || code == 404 { throw error }
+ try? await Task.sleep(nanoseconds: UInt64(120_000_000 << attempt))
+ }
+ }
+ throw lastError
+ }
+
+ private func finishUpload(_ session: Session) async throws -> String {
+ var request = try makeRequest(path: "/qft/upload/finish/\(session.uploadID)")
+ request.setValue("0", forHTTPHeaderField: "Content-Length")
+ let object = try await sendJSON(request, body: Data())
+ guard let sha = object["sha256"] as? String else {
+ throw QFTError.malformedResponse("finish 响应缺少 sha256")
+ }
+ return sha
+ }
+
+ // MARK: - HTTP
+
+ private func makeRequest(path: String) throws -> URLRequest {
+ guard let url = URL(string: host.baseURL + path) else {
+ throw QFTError.malformedResponse("上传地址无效:\(path)")
+ }
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.timeoutInterval = 60
+ request.setValue(pairing.session, forHTTPHeaderField: "X-QFT-Token")
+ request.setValue(Base64URL.encode(deviceName), forHTTPHeaderField: "X-QFT-Device")
+ request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
+ return request
+ }
+
+ private func sendJSON(_ request: URLRequest, body: Data) async throws -> [String: Any] {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = request.timeoutInterval
+ let urlSession = URLSession(configuration: configuration)
+ defer { urlSession.finishTasksAndInvalidate() }
+
+ let (data, response) = try await urlSession.upload(for: request, from: body)
+ guard let http = response as? HTTPURLResponse else {
+ throw QFTError.malformedResponse("非 HTTP 响应")
+ }
+ guard http.statusCode == 200 else {
+ let detail = String(data: data.prefix(200), encoding: .utf8) ?? ""
+ throw QFTError.httpStatus(http.statusCode, detail)
+ }
+ guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ throw QFTError.malformedResponse("响应不是 JSON")
+ }
+ if let ok = object["ok"] as? Bool, ok == false {
+ throw QFTError.malformedResponse("电脑拒绝了请求:\(object)")
+ }
+ return object
+ }
+}
+
+/// 分发块序号。
+actor IndexQueue {
+ private var current = 0
+ private let count: Int
+
+ init(count: Int) { self.count = count }
+
+ func next() -> Int? {
+ guard current < count else { return nil }
+ defer { current += 1 }
+ return current
+ }
+}
+
+/// 汇总各 worker 的已传字节并限频回调。
+actor ByteCounter {
+ private var completed: UInt64 = 0
+ private let total: UInt64
+ private let startedAt = Date()
+ private var lastReport = Date.distantPast
+ private let onProgress: (TransferProgress) -> Void
+
+ init(total: UInt64, onProgress: @escaping (TransferProgress) -> Void) {
+ self.total = total
+ self.onProgress = onProgress
+ }
+
+ func add(_ bytes: UInt64) {
+ completed &+= bytes
+ let now = Date()
+ guard now.timeIntervalSince(lastReport) > 0.1 || completed >= total else { return }
+ lastReport = now
+ let elapsed = max(0.001, now.timeIntervalSince(startedAt))
+ onProgress(TransferProgress(completed: completed, total: total,
+ bytesPerSecond: Double(completed) / elapsed))
+ }
+}
diff --git a/ios/QFT/Info.plist b/ios/QFT/Info.plist
new file mode 100644
index 0000000..35e4bd3
--- /dev/null
+++ b/ios/QFT/Info.plist
@@ -0,0 +1,68 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ zh_CN
+ CFBundleDisplayName
+ QFT 快传
+ CFBundleExecutable
+ $(EXECUTABLE_NAME)
+ CFBundleIdentifier
+ $(PRODUCT_BUNDLE_IDENTIFIER)
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ $(PRODUCT_NAME)
+ CFBundlePackageType
+ APPL
+ CFBundleShortVersionString
+ $(MARKETING_VERSION)
+ CFBundleVersion
+ $(CURRENT_PROJECT_VERSION)
+
+
+ NSCameraUsageDescription
+ QFT 需要使用相机扫描电脑或另一台 iPhone 上的配对二维码。相机画面不会离开本机。
+
+
+ NSLocalNetworkUsageDescription
+ QFT 需要在本地网络里找到你的电脑,才能直接传输文件。所有数据只在本地网络内传输,不经过互联网。
+
+
+ NSBonjourServices
+
+ _qft-p2p._tcp
+
+
+
+ NSAppTransportSecurity
+
+ NSAllowsLocalNetworking
+
+
+
+
+ UIFileSharingEnabled
+
+ LSSupportsOpeningDocumentsInPlace
+
+
+ UILaunchScreen
+
+ UIColorName
+
+
+ UISupportedInterfaceOrientations
+
+ UIInterfaceOrientationPortrait
+
+ UISupportedInterfaceOrientations~ipad
+
+ UIInterfaceOrientationPortrait
+ UIInterfaceOrientationPortraitUpsideDown
+ UIInterfaceOrientationLandscapeLeft
+ UIInterfaceOrientationLandscapeRight
+
+
+
diff --git a/ios/README.md b/ios/README.md
new file mode 100644
index 0000000..25a389e
--- /dev/null
+++ b/ios/README.md
@@ -0,0 +1,118 @@
+# QFT iOS 客户端 v0.1.0
+
+三种传输方式:
+
+| 方向 | 链路 | 说明 |
+|---|---|---|
+| 电脑 → iPhone | 局域网 HTTP | 扫 Windows 端的 `QFTSEND2` 码,自动下载,支持断点续传 |
+| iPhone → 电脑 | 局域网 HTTP | 扫 `QFTPAIR2` 码,选文件后并行分块上传 |
+| **iPhone ↔ iPhone** | **点对点直连** | 发送方显示二维码,接收方扫码,**不需要连同一个 Wi-Fi** |
+
+## 打开工程
+
+```bash
+open ios/QFT.xcodeproj
+```
+
+工程已提交到仓库,不需要 XcodeGen 之类的额外工具。首次构建前在
+Target → Signing & Capabilities 里选一下你自己的开发者账号(免费账号即可,
+生成的描述文件 7 天有效)。
+
+增删源文件后重新生成工程:
+
+```bash
+python3 ios/tools/generate_xcodeproj.py
+```
+
+- 最低系统:iOS 17.0
+- Bundle ID:`com.qft.transfer`(按需改 `generate_xcodeproj.py` 里的常量)
+
+## 隔空投送式点对点传输
+
+`PeerLink` 用 `Network.framework` 并打开 `includePeerToPeer`。底层就是
+AirDrop 用的那条链路——BLE 发现 + AWDL 点对点 Wi-Fi,两台设备不需要路由器,
+也不需要连同一个 Wi-Fi。两端在同一个 Wi-Fi 下时它会自动优先走基础网络。
+
+握手用 **TLS-PSK**:预共享密钥(32 字节)由发送端随机生成并写进二维码,
+扫码这个动作本身就完成了带外密钥交换与双向认证。没扫到码的第三方
+连上来也过不了 TLS 握手,因此不需要任何证书体系,也不需要配对弹窗。
+
+```
+发送方 接收方
+选文件 → 算 SHA-256
+启动 NWListener(Bonjour: _qft-p2p._tcp)
+生成 32 字节 PSK
+显示 QFTP2P1 二维码 ──────扫码────→ 解析出 PSK + 服务实例名
+ NWBrowser 找到实例
+ ←──────── TLS-PSK 握手 ────────→
+MANIFEST(JSON) ─────────────────────→ 校验与二维码是否一致
+DATA × N ─────────────────────→ 落盘 + 增量 SHA-256
+EOF ─────────────────────→
+ ←──────── RESULT(JSON) ──────── 校验通过才 rename
+```
+
+**AWDL 是苹果私有链路,Windows 无法参与**,所以与电脑互传仍走局域网 HTTP。
+如果现场没有路由器,可行的替代是让 iPhone 开个人热点、电脑连上来。
+
+## 已知的 iOS 平台限制
+
+1. **无法用代码连接指定 Wi-Fi。** Android 端用 `WifiNetworkSpecifier` 自动加入
+ Windows 的 QFT Direct AP,iOS 对应的 `NEHotspotConfiguration` 需要
+ HotspotConfiguration entitlement,免费开发者账号拿不到。因此 iOS 端
+ **不实现 Direct AP 流程**,`PairingProtocol` 在二维码不带可用 endpoint 时
+ 会直接拒绝,而不是给用户一个连不上的假成功。
+2. **首次访问局域网会弹权限窗。** 已在 `Info.plist` 声明
+ `NSLocalNetworkUsageDescription` 与 `NSBonjourServices`。
+ 若用户误点了拒绝,需要去 设置 → 隐私与安全性 → 本地网络 里重新打开。
+3. **没有「下载」文件夹。** 收到的文件存在 App 的 Documents/QFT 下,
+ 通过 `UIFileSharingEnabled` + `LSSupportsOpeningDocumentsInPlace`
+ 暴露到「文件」App,也可以在 App 内直接分享出去。
+4. **上传块固定 4 MiB。** Android 端按文件大小选 4/8/16 MiB,但 iOS 上
+ `worker 数 × 块大小` 就是内存峰值,16 MiB × 6 会在旧机型触发 jetsam。
+ 4 MiB × 6 = 24 MiB 峰值,局域网速度下每块的往返开销可以忽略。
+
+## 测试
+
+核心层(协议、发现、上传、下载、P2P 链路)不依赖 UIKit,
+可以直接以 macOS 为目标编译运行,**不需要 Xcode,也不需要模拟器**:
+
+```bash
+./ios/CoreTests/run.sh
+```
+
+也已接入主自检套件(`python scripts/run_all_selftests.py`)。
+
+测试内容:
+
+- `Base64URL` 与三端一致性(含 200 组随机字节往返)
+- `QFTPAIR2` / `QFTSEND2` / `QFTP2P1` 解析,含各类畸形输入
+- **端点白名单**:二维码是不可信输入,只接受字面量私有 IPv4 + 声明端口。
+ 已覆盖域名、公网地址、`172.32` 边界、非规范八位组、IPv6、带凭据/路径/query 等 11 种拒绝用例
+- **与 `MockPCServer.py` 的完整传输**:该 mock 严格复刻 `receiver.rs` / `sender.rs`
+ 的线上语义(路径、header 名、JSON 字段、Range 行为、chunk 长度校验),
+ 因此这组测试就是 Swift 端与 Rust 端的**线格式契约测试**——任何一边改了协议都会红
+- **真实 TLS-PSK 握手**下的 P2P 端到端传输,含错误密钥必须被拒
+
+## 目录
+
+```
+ios/
+ QFT.xcodeproj/ 生成的工程(已提交)
+ QFT/
+ Info.plist 权限声明、Bonjour 服务、ATS 本地网络例外
+ App/ SwiftUI 界面 + 相机扫码(需要 Xcode 才能构建)
+ Core/ 纯 Foundation,可在 macOS 上编译测试
+ Base64URL.swift
+ PairingProtocol.swift QFTPAIR2 / QFTSEND2 + 端点白名单
+ HostDiscovery.swift endpoint 探测 → UDP 广播 → 子网扫描
+ DownloadClient.swift 流式落盘 + 增量 SHA-256 + Range 续传
+ UploadClient.swift init/chunk/finish 并行上传
+ PeerPairing.swift QFTP2P1 配对码
+ PeerLink.swift TLS-PSK + 分帧的点对点链路
+ CoreTests/
+ run.sh 编译并运行(swiftc,无需 Xcode)
+ main.swift 测试用例
+ MockPCServer.py 复刻 Windows 端线上语义的假电脑
+ tools/
+ generate_xcodeproj.py 工程生成器
+```
diff --git a/ios/tools/generate_xcodeproj.py b/ios/tools/generate_xcodeproj.py
new file mode 100644
index 0000000..fcf2d60
--- /dev/null
+++ b/ios/tools/generate_xcodeproj.py
@@ -0,0 +1,371 @@
+#!/usr/bin/env python3
+"""生成 ios/QFT.xcodeproj,不依赖 XcodeGen 等外部工具。
+
+生成结果已提交到仓库,正常情况下双击 QFT.xcodeproj 即可。
+只有在**增删源文件**之后才需要重跑:
+
+ python3 ios/tools/generate_xcodeproj.py
+
+对象 ID 由文件路径哈希得到,因此同样的文件集合总是产出同样的工程,
+diff 干净,不会每次生成都全量变动。
+"""
+
+import hashlib
+import os
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+IOS_ROOT = os.path.dirname(HERE)
+
+APP_NAME = "QFT"
+BUNDLE_ID = "com.qft.transfer"
+DEPLOYMENT_TARGET = "17.0"
+MARKETING_VERSION = "0.1.0"
+
+SOURCES = [
+ "QFT/App/QFTApp.swift",
+ "QFT/App/HomeView.swift",
+ "QFT/App/ScannerView.swift",
+ "QFT/App/TransferModel.swift",
+ "QFT/Core/Base64URL.swift",
+ "QFT/Core/PairingProtocol.swift",
+ "QFT/Core/HostDiscovery.swift",
+ "QFT/Core/DownloadClient.swift",
+ "QFT/Core/UploadClient.swift",
+ "QFT/Core/PeerPairing.swift",
+ "QFT/Core/PeerLink.swift",
+]
+RESOURCES = ["QFT/Assets.xcassets"]
+OTHER_FILES = ["QFT/Info.plist"]
+
+
+def oid(*parts):
+ """由稳定字符串派生 24 位十六进制对象 ID。"""
+ digest = hashlib.sha1("::".join(parts).encode("utf-8")).hexdigest()
+ return digest[:24].upper()
+
+
+def file_type(path):
+ if path.endswith(".swift"):
+ return "sourcecode.swift"
+ if path.endswith(".xcassets"):
+ return "folder.assetcatalog"
+ if path.endswith(".plist"):
+ return "text.plist.xml"
+ return "text"
+
+
+def build_tree(paths):
+ """把扁平路径列表折成 {目录: {...}} 的嵌套结构。"""
+ tree = {}
+ for path in paths:
+ node = tree
+ segments = path.split("/")
+ for segment in segments[:-1]:
+ node = node.setdefault(segment, {})
+ node[segments[-1]] = None
+ return tree
+
+
+def emit_groups(tree, prefix, lines):
+ """深度优先输出 PBXGroup,返回本层 group 的 ID。"""
+ children = []
+ for name in sorted(tree.keys()):
+ path = "%s/%s" % (prefix, name) if prefix else name
+ if tree[name] is None:
+ children.append((oid("file", path), name))
+ else:
+ children.append((emit_groups(tree[name], path, lines), name))
+
+ group_id = oid("group", prefix or "")
+ lines.append("\t\t%s /* %s */ = {" % (group_id, prefix.split("/")[-1] if prefix else APP_NAME))
+ lines.append("\t\t\tisa = PBXGroup;")
+ lines.append("\t\t\tchildren = (")
+ for child_id, child_name in children:
+ lines.append("\t\t\t\t%s /* %s */," % (child_id, child_name))
+ lines.append("\t\t\t);")
+ if prefix:
+ lines.append("\t\t\tpath = %s;" % prefix.split("/")[-1])
+ lines.append("\t\t\tsourceTree = \"\";")
+ lines.append("\t\t};")
+ return group_id
+
+
+def generate():
+ all_files = SOURCES + RESOURCES + OTHER_FILES
+
+ project_id = oid("project")
+ target_id = oid("target", APP_NAME)
+ product_id = oid("product", APP_NAME)
+ products_group_id = oid("group", "")
+ sources_phase_id = oid("phase", "sources")
+ resources_phase_id = oid("phase", "resources")
+ frameworks_phase_id = oid("phase", "frameworks")
+ project_config_list = oid("configlist", "project")
+ target_config_list = oid("configlist", "target")
+
+ lines = []
+ add = lines.append
+
+ add("// !$*UTF8*$!")
+ add("{")
+ add("\tarchiveVersion = 1;")
+ add("\tclasses = {")
+ add("\t};")
+ add("\tobjectVersion = 56;")
+ add("\tobjects = {")
+
+ # ---------------- PBXBuildFile
+ add("")
+ add("/* Begin PBXBuildFile section */")
+ for path in SOURCES + RESOURCES:
+ name = path.split("/")[-1]
+ add("\t\t%s /* %s in %s */ = {isa = PBXBuildFile; fileRef = %s /* %s */; };"
+ % (oid("buildfile", path), name,
+ "Resources" if path in RESOURCES else "Sources",
+ oid("file", path), name))
+ add("/* End PBXBuildFile section */")
+
+ # ---------------- PBXFileReference
+ add("")
+ add("/* Begin PBXFileReference section */")
+ add("\t\t%s /* %s.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; "
+ "includeInIndex = 0; path = %s.app; sourceTree = BUILT_PRODUCTS_DIR; };"
+ % (product_id, APP_NAME, APP_NAME))
+ for path in all_files:
+ name = path.split("/")[-1]
+ add("\t\t%s /* %s */ = {isa = PBXFileReference; lastKnownFileType = %s; path = %s; "
+ "sourceTree = \"\"; };" % (oid("file", path), name, file_type(path), name))
+ add("/* End PBXFileReference section */")
+
+ # ---------------- PBXFrameworksBuildPhase
+ add("")
+ add("/* Begin PBXFrameworksBuildPhase section */")
+ add("\t\t%s /* Frameworks */ = {" % frameworks_phase_id)
+ add("\t\t\tisa = PBXFrameworksBuildPhase;")
+ add("\t\t\tbuildActionMask = 2147483647;")
+ add("\t\t\tfiles = (")
+ add("\t\t\t);")
+ add("\t\t\trunOnlyForDeploymentPostprocessing = 0;")
+ add("\t\t};")
+ add("/* End PBXFrameworksBuildPhase section */")
+
+ # ---------------- PBXGroup
+ add("")
+ add("/* Begin PBXGroup section */")
+ group_lines = []
+ app_group_id = emit_groups(build_tree(all_files)[APP_NAME], APP_NAME, group_lines)
+ lines.extend(group_lines)
+
+ root_group_id = oid("group", "")
+ add("\t\t%s = {" % root_group_id)
+ add("\t\t\tisa = PBXGroup;")
+ add("\t\t\tchildren = (")
+ add("\t\t\t\t%s /* %s */," % (app_group_id, APP_NAME))
+ add("\t\t\t\t%s /* Products */," % products_group_id)
+ add("\t\t\t);")
+ add("\t\t\tsourceTree = \"\";")
+ add("\t\t};")
+
+ add("\t\t%s /* Products */ = {" % products_group_id)
+ add("\t\t\tisa = PBXGroup;")
+ add("\t\t\tchildren = (")
+ add("\t\t\t\t%s /* %s.app */," % (product_id, APP_NAME))
+ add("\t\t\t);")
+ add("\t\t\tname = Products;")
+ add("\t\t\tsourceTree = \"\";")
+ add("\t\t};")
+ add("/* End PBXGroup section */")
+
+ # ---------------- PBXNativeTarget
+ add("")
+ add("/* Begin PBXNativeTarget section */")
+ add("\t\t%s /* %s */ = {" % (target_id, APP_NAME))
+ add("\t\t\tisa = PBXNativeTarget;")
+ add("\t\t\tbuildConfigurationList = %s;" % target_config_list)
+ add("\t\t\tbuildPhases = (")
+ add("\t\t\t\t%s /* Sources */," % sources_phase_id)
+ add("\t\t\t\t%s /* Frameworks */," % frameworks_phase_id)
+ add("\t\t\t\t%s /* Resources */," % resources_phase_id)
+ add("\t\t\t);")
+ add("\t\t\tbuildRules = (")
+ add("\t\t\t);")
+ add("\t\t\tdependencies = (")
+ add("\t\t\t);")
+ add("\t\t\tname = %s;" % APP_NAME)
+ add("\t\t\tproductName = %s;" % APP_NAME)
+ add("\t\t\tproductReference = %s /* %s.app */;" % (product_id, APP_NAME))
+ add("\t\t\tproductType = \"com.apple.product-type.application\";")
+ add("\t\t};")
+ add("/* End PBXNativeTarget section */")
+
+ # ---------------- PBXProject
+ add("")
+ add("/* Begin PBXProject section */")
+ add("\t\t%s /* Project object */ = {" % project_id)
+ add("\t\t\tisa = PBXProject;")
+ add("\t\t\tattributes = {")
+ add("\t\t\t\tBuildIndependentTargetsInParallel = 1;")
+ add("\t\t\t\tLastSwiftUpdateCheck = 1600;")
+ add("\t\t\t\tLastUpgradeCheck = 1600;")
+ add("\t\t\t\tTargetAttributes = {")
+ add("\t\t\t\t\t%s = {" % target_id)
+ add("\t\t\t\t\t\tCreatedOnToolsVersion = 16.0;")
+ add("\t\t\t\t\t};")
+ add("\t\t\t\t};")
+ add("\t\t\t};")
+ add("\t\t\tbuildConfigurationList = %s;" % project_config_list)
+ add("\t\t\tcompatibilityVersion = \"Xcode 14.0\";")
+ add("\t\t\tdevelopmentRegion = en;")
+ add("\t\t\thasScannedForEncodings = 0;")
+ add("\t\t\tknownRegions = (")
+ add("\t\t\t\ten,")
+ add("\t\t\t\tBase,")
+ add("\t\t\t\t\"zh-Hans\",")
+ add("\t\t\t);")
+ add("\t\t\tmainGroup = %s;" % root_group_id)
+ add("\t\t\tproductRefGroup = %s /* Products */;" % products_group_id)
+ add("\t\t\tprojectDirPath = \"\";")
+ add("\t\t\tprojectRoot = \"\";")
+ add("\t\t\ttargets = (")
+ add("\t\t\t\t%s /* %s */," % (target_id, APP_NAME))
+ add("\t\t\t);")
+ add("\t\t};")
+ add("/* End PBXProject section */")
+
+ # ---------------- PBXResourcesBuildPhase
+ add("")
+ add("/* Begin PBXResourcesBuildPhase section */")
+ add("\t\t%s /* Resources */ = {" % resources_phase_id)
+ add("\t\t\tisa = PBXResourcesBuildPhase;")
+ add("\t\t\tbuildActionMask = 2147483647;")
+ add("\t\t\tfiles = (")
+ for path in RESOURCES:
+ add("\t\t\t\t%s /* %s in Resources */," % (oid("buildfile", path), path.split("/")[-1]))
+ add("\t\t\t);")
+ add("\t\t\trunOnlyForDeploymentPostprocessing = 0;")
+ add("\t\t};")
+ add("/* End PBXResourcesBuildPhase section */")
+
+ # ---------------- PBXSourcesBuildPhase
+ add("")
+ add("/* Begin PBXSourcesBuildPhase section */")
+ add("\t\t%s /* Sources */ = {" % sources_phase_id)
+ add("\t\t\tisa = PBXSourcesBuildPhase;")
+ add("\t\t\tbuildActionMask = 2147483647;")
+ add("\t\t\tfiles = (")
+ for path in SOURCES:
+ add("\t\t\t\t%s /* %s in Sources */," % (oid("buildfile", path), path.split("/")[-1]))
+ add("\t\t\t);")
+ add("\t\t\trunOnlyForDeploymentPostprocessing = 0;")
+ add("\t\t};")
+ add("/* End PBXSourcesBuildPhase section */")
+
+ # ---------------- XCBuildConfiguration
+ shared_project = [
+ "ALWAYS_SEARCH_USER_PATHS = NO",
+ "CLANG_ANALYZER_NONNULL = YES",
+ "CLANG_ENABLE_MODULES = YES",
+ "CLANG_ENABLE_OBJC_ARC = YES",
+ "CLANG_WARN_DOCUMENTATION_COMMENTS = YES",
+ "CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE",
+ "COPY_PHASE_STRIP = NO",
+ "ENABLE_STRICT_OBJC_MSGSEND = YES",
+ "GCC_NO_COMMON_BLOCKS = YES",
+ "IPHONEOS_DEPLOYMENT_TARGET = %s" % DEPLOYMENT_TARGET,
+ "MTL_FAST_MATH = YES",
+ "SDKROOT = iphoneos",
+ "SWIFT_VERSION = 5.0",
+ ]
+ shared_target = [
+ "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 = %s" % MARKETING_VERSION,
+ "PRODUCT_BUNDLE_IDENTIFIER = %s" % BUNDLE_ID,
+ "PRODUCT_NAME = \"$(TARGET_NAME)\"",
+ "SWIFT_EMIT_LOC_STRINGS = NO",
+ "TARGETED_DEVICE_FAMILY = \"1,2\"",
+ ]
+ variants = {
+ "Debug": {
+ "project": ["DEBUG_INFORMATION_FORMAT = dwarf",
+ "ENABLE_TESTABILITY = YES",
+ "GCC_OPTIMIZATION_LEVEL = 0",
+ "GCC_PREPROCESSOR_DEFINITIONS = \"DEBUG=1 $(inherited)\"",
+ "MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE",
+ "ONLY_ACTIVE_ARCH = YES",
+ "SWIFT_ACTIVE_COMPILATION_CONDITIONS = \"DEBUG $(inherited)\"",
+ "SWIFT_OPTIMIZATION_LEVEL = \"-Onone\""],
+ "target": [],
+ },
+ "Release": {
+ "project": ["DEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\"",
+ "ENABLE_NS_ASSERTIONS = NO",
+ "MTL_ENABLE_DEBUG_INFO = NO",
+ "SWIFT_COMPILATION_MODE = wholemodule",
+ "VALIDATE_PRODUCT = YES"],
+ "target": [],
+ },
+ }
+
+ add("")
+ add("/* Begin XCBuildConfiguration section */")
+ for name, extra in variants.items():
+ for scope, base in (("project", shared_project), ("target", shared_target)):
+ config_id = oid("config", scope, name)
+ add("\t\t%s /* %s */ = {" % (config_id, name))
+ add("\t\t\tisa = XCBuildConfiguration;")
+ add("\t\t\tbuildSettings = {")
+ for setting in sorted(base + extra[scope]):
+ add("\t\t\t\t%s;" % setting)
+ add("\t\t\t};")
+ add("\t\t\tname = %s;" % name)
+ add("\t\t};")
+ add("/* End XCBuildConfiguration section */")
+
+ # ---------------- XCConfigurationList
+ add("")
+ add("/* Begin XCConfigurationList section */")
+ for scope, list_id in (("project", project_config_list), ("target", target_config_list)):
+ add("\t\t%s = {" % list_id)
+ add("\t\t\tisa = XCConfigurationList;")
+ add("\t\t\tbuildConfigurations = (")
+ for name in variants:
+ add("\t\t\t\t%s /* %s */," % (oid("config", scope, name), name))
+ add("\t\t\t);")
+ add("\t\t\tdefaultConfigurationIsVisible = 0;")
+ add("\t\t\tdefaultConfigurationName = Release;")
+ add("\t\t};")
+ add("/* End XCConfigurationList section */")
+
+ add("\t};")
+ add("\trootObject = %s /* Project object */;" % project_id)
+ add("}")
+ return "\n".join(lines) + "\n"
+
+
+def main():
+ project_dir = os.path.join(IOS_ROOT, "%s.xcodeproj" % APP_NAME)
+ os.makedirs(project_dir, exist_ok=True)
+ target = os.path.join(project_dir, "project.pbxproj")
+ with open(target, "w", encoding="utf-8") as fh:
+ fh.write(generate())
+ print("已生成 %s" % target)
+
+ missing = [p for p in SOURCES + RESOURCES + OTHER_FILES
+ if not os.path.exists(os.path.join(IOS_ROOT, p))]
+ if missing:
+ print("警告:以下文件在工程里被引用但不存在:")
+ for path in missing:
+ print(" " + path)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/ios_core_selftest.py b/scripts/ios_core_selftest.py
new file mode 100644
index 0000000..24f2dde
--- /dev/null
+++ b/scripts/ios_core_selftest.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python3
+"""把 iOS 核心层测试接进主自检套件。
+
+iOS 核心层(协议解析、局域网发现、上传/下载、P2P 链路)刻意不 import
+UIKit/AVFoundation,因此可以直接以 macOS 为目标编译运行,
+不需要 Xcode,也不需要模拟器。
+
+非 macOS 主机或没有 swiftc 时跳过,不让整套自检失败。
+"""
+
+import platform
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+RUNNER = ROOT / "ios" / "CoreTests" / "run.sh"
+
+
+def main() -> int:
+ if platform.system() != "Darwin":
+ print("SKIP:iOS 核心层测试需要 macOS")
+ return 0
+ if shutil.which("swiftc") is None:
+ print("SKIP:未找到 swiftc(安装 Xcode 或 Command Line Tools 后可运行)")
+ return 0
+ if not RUNNER.exists():
+ print("SKIP:%s 不存在" % RUNNER)
+ return 0
+
+ result = subprocess.run(["bash", str(RUNNER)], cwd=str(ROOT))
+ if result.returncode != 0:
+ print("iOS 核心层测试失败")
+ return result.returncode
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/run_all_selftests.py b/scripts/run_all_selftests.py
index 2d6e220..a9de7c5 100644
--- a/scripts/run_all_selftests.py
+++ b/scripts/run_all_selftests.py
@@ -13,6 +13,8 @@ scripts = [
'android_compat_selftest.py',
'single_channel_guard_selftest.py',
'kotlin_host_smoke.py',
+ 'wedge_selftest.py',
+ 'ios_core_selftest.py',
]
for name in scripts:
print(f'== {name} ==', flush=True)
diff --git a/scripts/wedge_analyze.py b/scripts/wedge_analyze.py
new file mode 100644
index 0000000..fee4e8d
--- /dev/null
+++ b/scripts/wedge_analyze.py
@@ -0,0 +1,446 @@
+#!/usr/bin/env python3
+"""分析楔形标定图的照片,输出「每模块相机像素数 → 误码率」曲线。
+
+ python scripts/wedge_analyze.py --spec out/wedge.json --photo IMG_0001.jpg
+
+流程与真实解码器完全一致,所以测出来的就是真实可用的下限:
+ 检测四角基准标 → 解单应矩阵 → 按模块中心单点采样
+ → 局部均值阈值面 → 判决 → 与期望比特比对
+
+--analysis-width 用来模拟手机 ImageAnalysis 流的分辨率(默认 1920,即 1080p)。
+照片本身通常是 12MP,直接分析会高估能力;先降采样到分析流分辨率才有意义。
+"""
+
+import argparse
+import os
+import sys
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from wedge_common import WedgeSpec, band_bits, module_centers_active # noqa: E402
+
+
+# ---------------------------------------------------------------- 图像载入
+
+def load_gray(path, analysis_width):
+ from PIL import Image, ImageOps
+
+ image = Image.open(path)
+ image = ImageOps.exif_transpose(image)
+ image = image.convert("L")
+ original = image.size
+ if analysis_width and image.width > analysis_width:
+ height = max(1, int(round(image.height * analysis_width / image.width)))
+ # BOX(面积平均)最接近相机 ISP 的降采样行为
+ image = image.resize((analysis_width, height), Image.BOX)
+ return np.asarray(image, dtype=np.float32), original
+
+
+# ---------------------------------------------------------------- 连通域
+
+def otsu(gray):
+ hist, _ = np.histogram(gray, bins=256, range=(0, 256))
+ total = hist.sum()
+ if total == 0:
+ return 128.0
+ levels = np.arange(256, dtype=np.float64)
+ w0 = np.cumsum(hist).astype(np.float64)
+ w1 = total - w0
+ s0 = np.cumsum(hist * levels)
+ total_sum = s0[-1]
+ valid = (w0 > 0) & (w1 > 0)
+ if not valid.any():
+ return 128.0
+ m0 = np.where(w0 > 0, s0 / np.maximum(w0, 1), 0.0)
+ m1 = np.where(w1 > 0, (total_sum - s0) / np.maximum(w1, 1), 0.0)
+ between = w0 * w1 * (m0 - m1) ** 2
+ between[~valid] = -1.0
+ return float(np.argmax(between))
+
+
+def label_components(mask):
+ """行程 + 并查集的连通域标记(4 连通)。返回 (labels, count)。"""
+ height, width = mask.shape
+ parent = [0]
+
+ def find(a):
+ while parent[a] != a:
+ parent[a] = parent[parent[a]]
+ a = parent[a]
+ return a
+
+ def union(a, b):
+ ra, rb = find(a), find(b)
+ if ra != rb:
+ parent[max(ra, rb)] = min(ra, rb)
+
+ labels = np.zeros((height, width), dtype=np.int32)
+ prev_runs = []
+ for y in range(height):
+ row = mask[y]
+ if not row.any():
+ prev_runs = []
+ continue
+ diff = np.diff(np.concatenate(([0], row.view(np.int8), [0])))
+ starts = np.flatnonzero(diff == 1)
+ ends = np.flatnonzero(diff == -1)
+ runs = []
+ for x0, x1 in zip(starts, ends):
+ parent.append(len(parent))
+ current = len(parent) - 1
+ for px0, px1, plabel in prev_runs:
+ if px0 < x1 and x0 < px1:
+ union(current, plabel)
+ labels[y, x0:x1] = current
+ runs.append((x0, x1, current))
+ prev_runs = runs
+
+ flat = labels.reshape(-1)
+ nonzero = flat > 0
+ if nonzero.any():
+ roots = np.array([find(i) for i in range(len(parent))], dtype=np.int32)
+ flat[nonzero] = roots[flat[nonzero]]
+ unique, remapped = np.unique(flat[nonzero], return_inverse=True)
+ flat[nonzero] = remapped + 1
+ count = len(unique)
+ else:
+ count = 0
+ return labels, count
+
+
+def find_markers(gray, debug=None):
+ """返回四个基准标中心(照片像素),顺序 TL, TR, BR, BL。"""
+ height, width = gray.shape
+ scale = max(1.0, width / 1200.0)
+ if scale > 1.0:
+ from PIL import Image
+ small = np.asarray(
+ Image.fromarray(gray.astype(np.uint8)).resize(
+ (int(width / scale), int(height / scale)), Image.BOX),
+ dtype=np.float32)
+ else:
+ small = gray
+
+ threshold = otsu(small)
+ mask = small < threshold
+ labels, count = label_components(mask)
+ if count == 0:
+ raise RuntimeError("照片里找不到任何暗色区域")
+
+ area_image = small.shape[0] * small.shape[1]
+ candidates = []
+ for index in range(1, count + 1):
+ ys, xs = np.nonzero(labels == index)
+ area = len(xs)
+ if area < 24 or area > area_image * 0.02:
+ continue
+ x0, x1 = xs.min(), xs.max() + 1
+ y0, y1 = ys.min(), ys.max() + 1
+ bw, bh = x1 - x0, y1 - y0
+ aspect = bw / float(bh)
+ if not 0.55 < aspect < 1.8:
+ continue
+ if area / float(bw * bh) < 0.72: # 实心方块
+ continue
+ # 外围一圈必须是白的(黑方块落在白底上),排除画面外的暗区与数据模块
+ pad = int(max(bw, bh) * 0.6) + 2
+ ry0, ry1 = max(0, y0 - pad), min(small.shape[0], y1 + pad)
+ rx0, rx1 = max(0, x0 - pad), min(small.shape[1], x1 + pad)
+ ring = small[ry0:ry1, rx0:rx1].copy()
+ inner = ring[y0 - ry0:y1 - ry0, x0 - rx0:x1 - rx0]
+ ring_sum = ring.sum() - inner.sum()
+ ring_n = ring.size - inner.size
+ if ring_n <= 0 or ring_sum / ring_n < threshold * 1.15:
+ continue
+ candidates.append((area, (xs.mean() + 0.5) * scale, (ys.mean() + 0.5) * scale,
+ bw * scale, bh * scale))
+
+ if len(candidates) < 4:
+ raise RuntimeError("只找到 %d 个候选基准标(需要 4 个)。"
+ "请让四个黑色角标全部进入画面,并保持画面明亮、对焦清晰。"
+ % len(candidates))
+
+ candidates.sort(key=lambda c: -c[0])
+ pool = candidates[:24]
+ pts = np.array([[c[1], c[2]] for c in pool])
+ sizes = np.array([max(c[3], c[4]) for c in pool])
+
+ def pick(score):
+ return int(np.argmax(score))
+
+ tl = pick(-(pts[:, 0] + pts[:, 1]))
+ br = pick(pts[:, 0] + pts[:, 1])
+ tr = pick(pts[:, 0] - pts[:, 1])
+ bl = pick(pts[:, 1] - pts[:, 0])
+ chosen = [tl, tr, br, bl]
+ if len(set(chosen)) != 4:
+ raise RuntimeError("角标定位歧义,请正对屏幕重拍,避免过大的倾斜")
+
+ refined = []
+ for index in chosen:
+ cx, cy, size = pts[index, 0], pts[index, 1], sizes[index]
+ refined.append(refine_centroid(gray, cx, cy, size))
+ if debug is not None:
+ debug["markers_raw"] = pts[chosen].tolist()
+ return refined
+
+
+def refine_centroid(gray, cx, cy, size):
+ """在全分辨率图上做灰度加权质心,取得亚像素中心。"""
+ half = max(4.0, size * 0.9)
+ x0 = int(max(0, np.floor(cx - half)))
+ x1 = int(min(gray.shape[1], np.ceil(cx + half)))
+ y0 = int(max(0, np.floor(cy - half)))
+ y1 = int(min(gray.shape[0], np.ceil(cy + half)))
+ patch = gray[y0:y1, x0:x1]
+ if patch.size == 0:
+ return (float(cx), float(cy))
+ level = otsu(patch)
+ weight = np.clip(level - patch, 0, None)
+ total = weight.sum()
+ if total <= 0:
+ return (float(cx), float(cy))
+ ys, xs = np.mgrid[y0:y1, x0:x1]
+ return (float((weight * xs).sum() / total) + 0.5,
+ float((weight * ys).sum() / total) + 0.5)
+
+
+# ---------------------------------------------------------------- 几何
+
+def homography(src, dst):
+ """求解 src(4×2) → dst(4×2) 的 3×3 单应矩阵(h8 = 1)。"""
+ a = np.zeros((8, 8), dtype=np.float64)
+ b = np.zeros(8, dtype=np.float64)
+ for i in range(4):
+ x, y = src[i]
+ u, v = dst[i]
+ a[2 * i] = [x, y, 1, 0, 0, 0, -x * u, -y * u]
+ b[2 * i] = u
+ a[2 * i + 1] = [0, 0, 0, x, y, 1, -x * v, -y * v]
+ b[2 * i + 1] = v
+ h = np.linalg.solve(a, b)
+ return np.append(h, 1.0).reshape(3, 3)
+
+
+def project(h, points):
+ """单应变换。逐分量展开而非 matmul:大点集下更省内存,
+ 也避开 BLAS 在大矩阵乘法上偶发的伪浮点警告。"""
+ pts = np.asarray(points, dtype=np.float64)
+ x = pts[..., 0]
+ y = pts[..., 1]
+ u = h[0, 0] * x + h[0, 1] * y + h[0, 2]
+ v = h[1, 0] * x + h[1, 1] * y + h[1, 2]
+ w = h[2, 0] * x + h[2, 1] * y + h[2, 2]
+ # w 趋近 0 表示该点被映射到无穷远(逆映射时落在画面之外),
+ # 夹住分母避免 inf/nan 污染后续采样。
+ w = np.where(np.abs(w) < 1e-12, 1e-12, w)
+ return np.stack([u / w, v / w], axis=-1)
+
+
+def local_scale(h, x, y):
+ """单应矩阵在 (x, y) 处的各向同性放大率:照片像素 / 显示像素。"""
+ u = h[0, 0] * x + h[0, 1] * y + h[0, 2]
+ v = h[1, 0] * x + h[1, 1] * y + h[1, 2]
+ w = h[2, 0] * x + h[2, 1] * y + h[2, 2]
+ dudx = (h[0, 0] * w - u * h[2, 0]) / w ** 2
+ dudy = (h[0, 1] * w - u * h[2, 1]) / w ** 2
+ dvdx = (h[1, 0] * w - v * h[2, 0]) / w ** 2
+ dvdy = (h[1, 1] * w - v * h[2, 1]) / w ** 2
+ return float(np.sqrt(abs(dudx * dvdy - dudy * dvdx)))
+
+
+def bilinear(gray, points):
+ height, width = gray.shape
+ x = np.clip(points[..., 0], 0, width - 1.001)
+ y = np.clip(points[..., 1], 0, height - 1.001)
+ x0 = np.floor(x).astype(np.int32)
+ y0 = np.floor(y).astype(np.int32)
+ fx = x - x0
+ fy = y - y0
+ v00 = gray[y0, x0]
+ v01 = gray[y0, x0 + 1]
+ v10 = gray[y0 + 1, x0]
+ v11 = gray[y0 + 1, x0 + 1]
+ return (v00 * (1 - fx) * (1 - fy) + v01 * fx * (1 - fy) +
+ v10 * (1 - fx) * fy + v11 * fx * fy)
+
+
+def box_mean(values, ky, kx):
+ """边界收缩的滑动平均,用作局部阈值面。"""
+ rows, cols = values.shape
+ ky = max(1, min(ky if ky % 2 == 1 else ky - 1, rows if rows % 2 == 1 else rows - 1))
+ kx = max(1, min(kx if kx % 2 == 1 else kx - 1, cols if cols % 2 == 1 else cols - 1))
+ ry, rx = ky // 2, kx // 2
+
+ padded = np.pad(values, ((ry, ry), (rx, rx)), mode="edge")
+ integral = np.zeros((padded.shape[0] + 1, padded.shape[1] + 1), dtype=np.float64)
+ integral[1:, 1:] = padded.cumsum(axis=0).cumsum(axis=1)
+ total = (integral[ky:ky + rows, kx:kx + cols]
+ - integral[0:rows, kx:kx + cols]
+ - integral[ky:ky + rows, 0:cols]
+ + integral[0:rows, 0:cols])
+ return total / float(ky * kx)
+
+
+# ---------------------------------------------------------------- 分析
+
+def analyze_band(gray, spec, band, h, threshold_window):
+ centers = module_centers_active(band, spec)
+ photo = project(h, centers)
+ samples = bilinear(gray, photo)
+
+ expected = band_bits(band) # 1 = 黑
+ threshold = box_mean(samples, threshold_window, threshold_window)
+ decoded = (samples < threshold).astype(np.uint8) # 比阈值暗 → 判为黑(1)
+
+ errors = int(np.count_nonzero(decoded != expected))
+ total = expected.size
+ ber = errors / float(total)
+
+ white = samples[expected == 0]
+ black = samples[expected == 1]
+ if white.size and black.size:
+ mw, mb = float(white.mean()), float(black.mean())
+ contrast = (mw - mb) / (mw + mb) if (mw + mb) > 0 else 0.0
+ else:
+ mw = mb = contrast = 0.0
+
+ cx = band.x + band.width_px / 2.0
+ cy = band.y + band.height_px / 2.0
+ px_per_module = local_scale(h, cx, cy) * band.pitch_px
+
+ return {
+ "index": band.index,
+ "pitch_px": band.pitch_px,
+ "px_per_module": px_per_module,
+ "modules": total,
+ "errors": errors,
+ "ber": ber,
+ "contrast": contrast,
+ "white": mw,
+ "black": mb,
+ }
+
+
+def inner_fec_overhead(ber):
+ """把给定原始误码率压到可忽略的带错率,所需的内码冗余(粗估)。
+
+ 条带级 CRC 下,1750 B 的条带只要有 1 bit 错就整条报废,
+ 因此必须用内码(RS/LDPC)先把原始 BER 吃掉,外层喷泉码只负责丢包。
+ GF(256) 的 RS:字节错率 ≈ 8·BER,留 3 倍余量 → 冗余 ≈ 48·BER。
+ """
+ if ber <= 0:
+ return 0.0
+ return min(1.0, 48.0 * ber)
+
+
+def verdict(ber):
+ if ber == 0:
+ return "✅ 无误码"
+ if ber < 1e-3:
+ return "✅ 可用"
+ if ber < 1e-2:
+ return "⚠️ 勉强"
+ return "❌ 不可用"
+
+
+def crossing(rows, limit):
+ """在 BER-px/模块 曲线上插值出 BER 恰好等于 limit 的位置。"""
+ ordered = sorted(rows, key=lambda r: r["px_per_module"])
+ for a, b in zip(ordered, ordered[1:]):
+ if a["ber"] > limit >= b["ber"]:
+ ya, yb = np.log10(max(a["ber"], 1e-9)), np.log10(max(b["ber"], 1e-9))
+ if abs(yb - ya) < 1e-12:
+ return b["px_per_module"]
+ t = (np.log10(limit) - ya) / (yb - ya)
+ return a["px_per_module"] + t * (b["px_per_module"] - a["px_per_module"])
+ return None
+
+
+def write_debug_image(path, gray, spec, h, markers):
+ from PIL import Image, ImageDraw
+
+ image = Image.fromarray(gray.astype(np.uint8)).convert("RGB")
+ draw = ImageDraw.Draw(image)
+ for x, y in markers:
+ draw.ellipse([x - 9, y - 9, x + 9, y + 9], outline=(255, 40, 40), width=3)
+ corners = project(h, spec.active_corners())
+ draw.polygon([tuple(p) for p in corners], outline=(40, 220, 255))
+ for band in spec.bands:
+ rect = [(band.x, band.y),
+ (band.x + band.width_px, band.y),
+ (band.x + band.width_px, band.y + band.height_px),
+ (band.x, band.y + band.height_px)]
+ pts = project(h, rect)
+ draw.polygon([tuple(p) for p in pts], outline=(80, 255, 120))
+ image.save(path)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="分析楔形标定图照片")
+ parser.add_argument("--spec", required=True, help="wedge_gen.py 产出的 .json")
+ parser.add_argument("--photo", required=True, help="手机拍摄的照片")
+ parser.add_argument("--analysis-width", type=int, default=1920,
+ help="模拟 ImageAnalysis 流宽度,0 表示不降采样")
+ parser.add_argument("--threshold-window", type=int, default=17,
+ help="局部阈值面的窗口边长(模块数)")
+ parser.add_argument("--debug-image", type=str, default=None,
+ help="写出一张叠加了定位结果的诊断图")
+ args = parser.parse_args()
+
+ spec = WedgeSpec.load(args.spec)
+ gray, original = load_gray(args.photo, args.analysis_width)
+
+ debug = {}
+ markers = find_markers(gray, debug)
+ h = homography(spec.active_corners(), markers)
+
+ rows = [analyze_band(gray, spec, band, h, args.threshold_window) for band in spec.bands]
+
+ if args.debug_image:
+ write_debug_image(args.debug_image, gray, spec, h, markers)
+
+ width_px = float(np.hypot(markers[1][0] - markers[0][0], markers[1][1] - markers[0][1]))
+ print("照片:%s" % os.path.basename(args.photo))
+ print("原始尺寸 %d×%d → 分析尺寸 %d×%d" % (original[0], original[1], gray.shape[1], gray.shape[0]))
+ print("标定图 active 宽 %d 显示像素 → 照片中 %.1f 像素(放大率 %.3f)"
+ % (spec.active_w, width_px, width_px / spec.active_w))
+ print()
+ print("%-6s %-9s %-11s %-9s %-10s %-11s %s"
+ % ("条带", "显示pitch", "px/模块", "对比度", "模块数", "误码率", "判定"))
+ for row in rows:
+ print("%-6d %-9d %-11.2f %-9.3f %-10d %-11s %s"
+ % (row["index"], row["pitch_px"], row["px_per_module"], row["contrast"],
+ row["modules"],
+ "0" if row["ber"] == 0 else "%.2e" % row["ber"],
+ verdict(row["ber"])))
+
+ print()
+ limit = crossing(rows, 1e-3)
+ if limit is not None:
+ print("BER=1e-3 的临界点:约 %.2f px/模块" % limit)
+ usable = [r for r in rows if r["ber"] < 1e-3]
+ if usable:
+ best = min(usable, key=lambda r: r["px_per_module"])
+ print("本次实测可用下限:%.2f px/模块(BER %s,内码冗余需 %.1f%%)"
+ % (best["px_per_module"],
+ "0" if best["ber"] == 0 else "%.1e" % best["ber"],
+ inner_fec_overhead(best["ber"]) * 100))
+ area = gray.shape[0] * gray.shape[1] * 0.95
+ modules = area / best["px_per_module"] ** 2
+ payload = modules * (1 - 0.04) * (1 - 0.15 - inner_fec_overhead(best["ber"])) / 8
+ print("→ 按此下限,%d×%d 分析流每画布净载荷约 %.0f B"
+ % (gray.shape[1], gray.shape[0], max(payload, 0)))
+ for fps in (24, 30, 60):
+ rate = payload * fps * 0.92
+ if rate > 0:
+ print(" @%d FPS:%.0f KB/s 1MB %.2fs 10MB %.2fs"
+ % (fps, rate / 1024, 1048576 / rate, 10485760 / rate))
+ else:
+ print("所有条带都超过 1e-3,请靠近屏幕重拍,或改用更大的 --pitches")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/wedge_common.py b/scripts/wedge_common.py
new file mode 100644
index 0000000..781d67a
--- /dev/null
+++ b/scripts/wedge_common.py
@@ -0,0 +1,229 @@
+#!/usr/bin/env python3
+"""QFT 分辨率楔形标定图 —— 共享规格、PRNG 与渲染。
+
+用途:在屏幕上显示一张同时包含多种模块尺寸(pitch)的伪随机二值图案,
+手机拍一张照片,由 wedge_analyze.py 反解出「每模块相机像素数 → 误码率」曲线,
+从而实测出本套硬件真正的 px/模块 下限。这个下限直接决定 QFT5 位阵列的容量。
+
+坐标系
+------
+canvas 坐标:整张标定图的像素坐标,原点左上。
+active 坐标:以左上角基准标**中心**为原点的坐标系;四个基准标中心构成 active 矩形。
+ 分析端解出的单应矩阵就是 active → 照片像素 的映射,因此所有条带几何
+ 都用 active 坐标描述,与画布边距无关。
+
+约定
+----
+- 模块 bit == 1 → 黑 (0),bit == 0 → 白 (255)。
+- PRNG 为 SplitMix64,Rust / Kotlin 移植时必须逐位一致(见 splitmix64)。
+- 模块 (r, c) 的比特序号 k = r * cols + c;取第 k//64 个 64 位输出的第 k%64 位(LSB 起)。
+"""
+
+from dataclasses import dataclass, asdict
+from typing import List, Optional
+import json
+
+MASK64 = (1 << 64) - 1
+GOLDEN = 0x9E3779B97F4A7C15
+
+SPEC_VERSION = 1
+DEFAULT_PITCHES = [10, 8, 6, 5, 4, 3, 2]
+DEFAULT_SEED = 20260810
+
+# 画布留白与基准标尺寸(canvas 像素)
+MARGIN_PX = 40
+MARKER_PX = 56
+INSET_PX = 64 # 数据区相对 active 矩形的内缩,保证基准标周围留白
+GUTTER_PX = 8 # 条带间隔
+
+
+def splitmix64(state: int):
+ """SplitMix64 生成器。返回 (下一状态, 64 位输出)。"""
+ state = (state + GOLDEN) & MASK64
+ z = state
+ z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK64
+ z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK64
+ return state, z ^ (z >> 31)
+
+
+def band_seed(seed: int, index: int) -> int:
+ return (seed ^ ((GOLDEN * (index + 1)) & MASK64)) & MASK64
+
+
+@dataclass
+class BandSpec:
+ index: int
+ pitch_px: int
+ cols: int
+ rows: int
+ x: int # active 坐标
+ y: int
+ seed: int
+
+ @property
+ def width_px(self) -> int:
+ return self.cols * self.pitch_px
+
+ @property
+ def height_px(self) -> int:
+ return self.rows * self.pitch_px
+
+ @property
+ def modules(self) -> int:
+ return self.cols * self.rows
+
+
+@dataclass
+class WedgeSpec:
+ version: int
+ canvas_w: int
+ canvas_h: int
+ margin_px: int
+ marker_px: int
+ inset_px: int
+ gutter_px: int
+ seed: int
+ active_w: int # active 矩形尺寸(= 基准标中心间距)
+ active_h: int
+ bands: List[BandSpec]
+
+ def to_json(self, indent: Optional[int] = 2) -> str:
+ payload = asdict(self)
+ return json.dumps(payload, indent=indent, ensure_ascii=False)
+
+ @staticmethod
+ def from_dict(payload: dict) -> "WedgeSpec":
+ bands = [BandSpec(**b) for b in payload["bands"]]
+ rest = {k: v for k, v in payload.items() if k != "bands"}
+ return WedgeSpec(bands=bands, **rest)
+
+ @staticmethod
+ def load(path) -> "WedgeSpec":
+ with open(path, "r", encoding="utf-8") as fh:
+ return WedgeSpec.from_dict(json.load(fh))
+
+ def marker_centers_canvas(self):
+ """四个基准标中心在 canvas 坐标下的位置,顺序 TL, TR, BR, BL。"""
+ half = self.marker_px / 2.0
+ x0 = self.margin_px + half
+ y0 = self.margin_px + half
+ x1 = self.canvas_w - self.margin_px - half
+ y1 = self.canvas_h - self.margin_px - half
+ return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
+
+ def active_corners(self):
+ """active 坐标下的四角,顺序与 marker_centers_canvas 一致。"""
+ return [(0.0, 0.0), (float(self.active_w), 0.0),
+ (float(self.active_w), float(self.active_h)), (0.0, float(self.active_h))]
+
+
+def build_spec(canvas_w: int = 1920,
+ canvas_h: int = 1080,
+ pitches: Optional[List[int]] = None,
+ seed: int = DEFAULT_SEED,
+ margin_px: int = MARGIN_PX,
+ marker_px: int = MARKER_PX,
+ inset_px: int = INSET_PX,
+ gutter_px: int = GUTTER_PX) -> WedgeSpec:
+ pitches = list(pitches or DEFAULT_PITCHES)
+ if not pitches:
+ raise ValueError("至少需要一个 pitch")
+ if any(p < 1 for p in pitches):
+ raise ValueError("pitch 必须 >= 1 显示像素")
+
+ active_w = canvas_w - 2 * margin_px - marker_px
+ active_h = canvas_h - 2 * margin_px - marker_px
+ data_w = active_w - 2 * inset_px
+ data_h = active_h - 2 * inset_px
+ if data_w < 64 or data_h < 64:
+ raise ValueError("画布太小,数据区不足")
+
+ n = len(pitches)
+ band_h = (data_h - (n - 1) * gutter_px) // n
+ if band_h < max(pitches):
+ raise ValueError("画布高度不足以容纳全部条带")
+
+ bands: List[BandSpec] = []
+ for i, pitch in enumerate(pitches):
+ cols = data_w // pitch
+ rows = band_h // pitch
+ if cols < 8 or rows < 2:
+ raise ValueError("pitch %d 下条带尺寸过小" % pitch)
+ bands.append(BandSpec(
+ index=i,
+ pitch_px=pitch,
+ cols=cols,
+ rows=rows,
+ x=inset_px,
+ y=inset_px + i * (band_h + gutter_px),
+ seed=band_seed(seed, i),
+ ))
+
+ return WedgeSpec(
+ version=SPEC_VERSION,
+ canvas_w=canvas_w,
+ canvas_h=canvas_h,
+ margin_px=margin_px,
+ marker_px=marker_px,
+ inset_px=inset_px,
+ gutter_px=gutter_px,
+ seed=seed,
+ active_w=active_w,
+ active_h=active_h,
+ bands=bands,
+ )
+
+
+def band_bits(band: BandSpec):
+ """返回形状 (rows, cols) 的 uint8 数组,1 = 黑模块。"""
+ import numpy as np
+
+ total = band.modules
+ words = (total + 63) // 64
+ state = band.seed
+ out = np.empty(words, dtype=np.uint64)
+ for i in range(words):
+ state, value = splitmix64(state)
+ out[i] = value
+ bits = np.unpackbits(out.view(np.uint8).reshape(words, 8), axis=1, bitorder="little")
+ # view(uint8) 在小端机器上给出 LSB->MSB 的字节序,配合 bitorder="little"
+ # 即得到 k 递增方向的比特流。
+ bits = bits.reshape(-1)[:total]
+ return bits.reshape(band.rows, band.cols)
+
+
+def render(spec: WedgeSpec):
+ """渲染整张标定图,返回 (H, W) 的 uint8 灰度数组。"""
+ import numpy as np
+
+ canvas = np.full((spec.canvas_h, spec.canvas_w), 255, dtype=np.uint8)
+
+ # active 原点在 canvas 中的位置 = 左上基准标中心
+ ox = spec.margin_px + spec.marker_px / 2.0
+ oy = spec.margin_px + spec.marker_px / 2.0
+
+ # 四个实心黑方块基准标,中心落在 active 四角
+ half = spec.marker_px // 2
+ for cx, cy in spec.marker_centers_canvas():
+ x0, y0 = int(round(cx)) - half, int(round(cy)) - half
+ canvas[y0:y0 + spec.marker_px, x0:x0 + spec.marker_px] = 0
+
+ for band in spec.bands:
+ bits = band_bits(band)
+ block = np.repeat(np.repeat(bits, band.pitch_px, axis=0), band.pitch_px, axis=1)
+ px = int(round(ox + band.x))
+ py = int(round(oy + band.y))
+ canvas[py:py + block.shape[0], px:px + block.shape[1]] = np.where(block == 1, 0, 255)
+
+ return canvas
+
+
+def module_centers_active(band: BandSpec, spec: WedgeSpec):
+ """返回该条带全部模块中心的 active 坐标,形状 (rows, cols, 2)。"""
+ import numpy as np
+
+ del spec # 条带 x/y 已是 active 坐标,无需画布信息
+ cx = band.x + (np.arange(band.cols) + 0.5) * band.pitch_px
+ cy = band.y + (np.arange(band.rows) + 0.5) * band.pitch_px
+ gx, gy = np.meshgrid(cx, cy)
+ return np.stack([gx, gy], axis=-1)
diff --git a/scripts/wedge_gen.py b/scripts/wedge_gen.py
new file mode 100644
index 0000000..c639546
--- /dev/null
+++ b/scripts/wedge_gen.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python3
+"""生成 QFT 分辨率楔形标定图。
+
+ python scripts/wedge_gen.py --width 1920 --height 1080 --out out/wedge
+
+产出三个文件:
+ .png 标定图本体(必须 1:1 显示,任何缩放都会让测量失效)
+ .json 规格,wedge_analyze.py 用它反解几何与期望比特
+ .html 全屏 1:1 查看器,自带缩放校验
+
+显示方法(二选一):
+ A. 用浏览器打开 .html,按 F11 全屏。页面会显示「缩放 1.000 ✅」才算有效。
+ B. 任何能保证 100% 原始像素显示的看图工具,且系统 DPI 缩放为 100%。
+
+拍摄方法:
+ - 手机大致正立(旋转 < 45°),让四个黑色角标都在画面内且尽量填满画面;
+ - 关闭闪光灯,对焦到屏幕上;
+ - 建议在 2~4 个不同距离各拍一张,这样能把 px/模块 曲线的采样点连起来。
+"""
+
+import argparse
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from wedge_common import build_spec, render, DEFAULT_PITCHES, DEFAULT_SEED # noqa: E402
+
+VIEWER_HTML = """
+
+QFT 标定图 1:1 查看器
+
+
+测量中…(按 H 隐藏此框,F11 全屏)
+
+"""
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="生成 QFT 分辨率楔形标定图")
+ parser.add_argument("--width", type=int, default=1920, help="画布宽(显示设备像素)")
+ parser.add_argument("--height", type=int, default=1080, help="画布高(显示设备像素)")
+ parser.add_argument("--pitches", type=str, default=",".join(str(p) for p in DEFAULT_PITCHES),
+ help="各条带的模块尺寸,单位显示像素,逗号分隔(必须为整数)")
+ parser.add_argument("--seed", type=int, default=DEFAULT_SEED)
+ parser.add_argument("--out", type=str, default="out/wedge", help="输出前缀,不带扩展名")
+ args = parser.parse_args()
+
+ try:
+ pitches = [int(p) for p in args.pitches.split(",") if p.strip()]
+ except ValueError:
+ print("--pitches 必须是逗号分隔的整数", file=sys.stderr)
+ return 2
+
+ try:
+ spec = build_spec(args.width, args.height, pitches, args.seed)
+ except ValueError as exc:
+ print("规格无效:%s" % exc, file=sys.stderr)
+ return 2
+
+ from PIL import Image
+
+ canvas = render(spec)
+ out_dir = os.path.dirname(os.path.abspath(args.out))
+ if out_dir:
+ os.makedirs(out_dir, exist_ok=True)
+
+ png_path = args.out + ".png"
+ json_path = args.out + ".json"
+ html_path = args.out + ".html"
+
+ Image.fromarray(canvas).save(png_path, optimize=True)
+ with open(json_path, "w", encoding="utf-8") as fh:
+ fh.write(spec.to_json())
+ with open(html_path, "w", encoding="utf-8") as fh:
+ fh.write(VIEWER_HTML.replace("__PNG__", os.path.basename(png_path)))
+
+ print("已生成:")
+ print(" %s %d×%d" % (png_path, spec.canvas_w, spec.canvas_h))
+ print(" %s" % json_path)
+ print(" %s ← 用浏览器打开并按 F11 全屏" % html_path)
+ print()
+ print("条带(模块尺寸以显示像素计):")
+ total = 0
+ for band in spec.bands:
+ total += band.modules
+ print(" #%d pitch=%2d px %4d×%-3d = %6d 模块"
+ % (band.index, band.pitch_px, band.cols, band.rows, band.modules))
+ print(" 合计 %d 模块" % total)
+ print()
+ print("拍摄后运行:python scripts/wedge_analyze.py --spec %s --photo <照片>" % json_path)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/wedge_selftest.py b/scripts/wedge_selftest.py
new file mode 100644
index 0000000..9fbf4bf
--- /dev/null
+++ b/scripts/wedge_selftest.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""楔形标定工具自检:用合成相机模型端到端验证,无需真实硬件。
+
+合成链路刻意模拟真实拍摄里会出问题的每一环:
+ 透视倾斜 → 镜头模糊 → 传感器面积平均降采样 → 亮度梯度 + 暗角 → 噪声 → JPEG
+
+通过判据:
+ 1. 四个基准标能在暗背景 + 亮度不均的场景里被找到;
+ 2. 单应矩阵反解出的放大率与合成时用的真值一致(误差 < 1%);
+ 3. 大 pitch 条带零误码,小 pitch 条带明显劣化(曲线单调);
+ 4. BER=1e-3 的临界点落在合理区间。
+"""
+
+import os
+import subprocess
+import sys
+import tempfile
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from wedge_common import build_spec, render # noqa: E402
+import wedge_analyze as wa # noqa: E402
+
+
+def warp_into_scene(canvas, scene_size, corners_dst):
+ """把画布按给定四角透视贴进场景(逆映射 + 双线性)。"""
+ scene_w, scene_h = scene_size
+ src = [(0, 0), (canvas.shape[1], 0), (canvas.shape[1], canvas.shape[0]), (0, canvas.shape[0])]
+ inverse = wa.homography(corners_dst, src)
+
+ ys, xs = np.mgrid[0:scene_h, 0:scene_w]
+ pts = np.stack([xs.ravel(), ys.ravel()], axis=-1).astype(np.float64)
+ mapped = wa.project(inverse, pts)
+ mx, my = mapped[:, 0], mapped[:, 1]
+
+ inside = (mx >= 0) & (mx < canvas.shape[1] - 1) & (my >= 0) & (my < canvas.shape[0] - 1)
+ scene = np.full(scene_h * scene_w, 26.0, dtype=np.float32) # 暗背景 = 房间/边框
+ if inside.any():
+ sample = wa.bilinear(canvas.astype(np.float32), mapped[inside])
+ scene[inside] = sample
+ return scene.reshape(scene_h, scene_w)
+
+
+def synth_photo(canvas, tilt=0.018, blur=1.1, scene_scale=1.5,
+ analysis_width=1920, noise=1.6, seed=7):
+ rng = np.random.default_rng(seed)
+ scene_w = int(canvas.shape[1] * scene_scale)
+ scene_h = int(canvas.shape[0] * scene_scale)
+
+ # 画布占场景约 92%,并带一点透视倾斜
+ mx = scene_w * 0.04
+ my = scene_h * 0.04
+ dx = scene_w * tilt
+ dy = scene_h * tilt
+ corners = [
+ (mx + dx, my + dy * 0.6),
+ (scene_w - mx, my),
+ (scene_w - mx - dx * 0.4, scene_h - my),
+ (mx, scene_h - my - dy * 0.5),
+ ]
+ scene = warp_into_scene(canvas, (scene_w, scene_h), corners)
+
+ # 屏幕亮度梯度 + 镜头暗角
+ ys, xs = np.mgrid[0:scene_h, 0:scene_w]
+ gradient = 1.0 - 0.16 * (xs / scene_w) - 0.10 * (ys / scene_h)
+ cx, cy = scene_w / 2.0, scene_h / 2.0
+ radius = np.sqrt(((xs - cx) / cx) ** 2 + ((ys - cy) / cy) ** 2)
+ vignette = 1.0 - 0.18 * np.clip(radius, 0, 1.4) ** 2
+ scene = scene * gradient * vignette
+
+ from PIL import Image, ImageFilter
+
+ image = Image.fromarray(np.clip(scene, 0, 255).astype(np.uint8))
+ image = image.filter(ImageFilter.GaussianBlur(radius=blur)) # 镜头 PSF + 轻微失焦
+ height = int(round(scene_h * analysis_width / scene_w))
+ image = image.resize((analysis_width, height), Image.BOX) # 传感器面积平均
+
+ array = np.asarray(image, dtype=np.float32)
+ array = array + rng.normal(0.0, noise, array.shape)
+ photo = Image.fromarray(np.clip(array, 0, 255).astype(np.uint8))
+
+ # 合成时画布 active 宽在场景中的真值放大率
+ active_dst = np.hypot(corners[1][0] - corners[0][0], corners[1][1] - corners[0][1])
+ truth_scale = active_dst / canvas.shape[1] * (analysis_width / float(scene_w))
+ return photo, truth_scale
+
+
+def check(condition, message):
+ if not condition:
+ raise AssertionError(message)
+ print(" ok %s" % message)
+
+
+def main() -> int:
+ print("== 生成标定图 ==")
+ spec = build_spec(1920, 1080)
+ canvas = render(spec)
+ check(canvas.shape == (1080, 1920), "画布尺寸 1920×1080")
+ check(set(np.unique(canvas).tolist()) == {0, 255}, "画布为纯二值")
+
+ print("== 合成相机拍摄 ==")
+ photo, truth_scale = synth_photo(canvas)
+ with tempfile.TemporaryDirectory() as tmp:
+ spec_path = os.path.join(tmp, "wedge.json")
+ photo_path = os.path.join(tmp, "photo.jpg")
+ with open(spec_path, "w", encoding="utf-8") as fh:
+ fh.write(spec.to_json())
+ photo.save(photo_path, quality=92)
+
+ print("== 定位与解码 ==")
+ gray, _ = wa.load_gray(photo_path, 0)
+ markers = wa.find_markers(gray)
+ check(len(markers) == 4, "找到 4 个基准标")
+
+ h = wa.homography(spec.active_corners(), markers)
+ measured = wa.local_scale(h, spec.active_w / 2.0, spec.active_h / 2.0)
+ expected = truth_scale
+ error = abs(measured - expected) / expected
+ print(" 放大率 真值 %.4f / 实测 %.4f / 偏差 %.2f%%" % (expected, measured, error * 100))
+ check(error < 0.01, "单应矩阵放大率与真值一致(<1%%)")
+
+ rows = [wa.analyze_band(gray, spec, band, h, 17) for band in spec.bands]
+ print()
+ print(" %-9s %-11s %-9s %-11s" % ("显示pitch", "px/模块", "对比度", "误码率"))
+ for row in rows:
+ print(" %-9d %-11.2f %-9.3f %-11s"
+ % (row["pitch_px"], row["px_per_module"], row["contrast"],
+ "0" if row["ber"] == 0 else "%.2e" % row["ber"]))
+ print()
+
+ coarse = [r for r in rows if r["px_per_module"] >= 4.0]
+ fine = [r for r in rows if r["px_per_module"] <= 2.2]
+ check(bool(coarse) and all(r["ber"] == 0 for r in coarse),
+ "px/模块 >= 4.0 的条带零误码")
+ check(bool(fine) and max(r["ber"] for r in fine) > 1e-3,
+ "px/模块 <= 2.2 的条带出现明显误码")
+
+ ordered = sorted(rows, key=lambda r: r["px_per_module"])
+ check(ordered[0]["ber"] >= ordered[-1]["ber"], "误码率随 px/模块 增大而下降")
+ check(all(r["contrast"] > 0.05 for r in rows), "各条带对比度为正")
+
+ limit = wa.crossing(rows, 1e-3)
+ check(limit is not None and 1.5 < limit < 5.0,
+ "BER=1e-3 临界点落在 1.5~5.0 区间(实测 %.2f)" % (limit or 0))
+
+ print()
+ print("== CLI 冒烟 ==")
+ result = subprocess.run(
+ [sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "wedge_analyze.py"),
+ "--spec", spec_path, "--photo", photo_path, "--analysis-width", "0"],
+ capture_output=True, text=True)
+ check(result.returncode == 0, "wedge_analyze.py 正常退出")
+ check("px/模块" in result.stdout, "输出包含结果表格")
+
+ print()
+ print("WEDGE SELFTEST PASSED")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/windows/src/receiver.rs b/windows/src/receiver.rs
index 7475917..faab643 100644
--- a/windows/src/receiver.rs
+++ b/windows/src/receiver.rs
@@ -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);
+ }
+}