a960ad91d8
# Conflicts: # README.md # android/app/src/main/java/com/qft/optical/DownloadClient.kt # android/app/src/main/java/com/qft/optical/UploadClient.kt # docs/PROTOCOL.md # windows/src/sender.rs
1164 lines
55 KiB
Kotlin
1164 lines
55 KiB
Kotlin
package com.qft.optical
|
||
|
||
import android.Manifest
|
||
import android.content.pm.PackageManager
|
||
import android.content.res.ColorStateList
|
||
import android.graphics.Color
|
||
import android.graphics.drawable.GradientDrawable
|
||
import android.hardware.camera2.CameraCharacteristics
|
||
import android.hardware.camera2.CameraManager
|
||
import android.hardware.camera2.CaptureRequest
|
||
import android.net.Network
|
||
import android.os.Build
|
||
import android.os.Bundle
|
||
import android.util.Log
|
||
import android.util.Range
|
||
import android.util.Size
|
||
import android.view.Gravity
|
||
import android.view.MotionEvent
|
||
import android.view.ScaleGestureDetector
|
||
import android.view.ViewGroup
|
||
import android.widget.Button
|
||
import android.widget.FrameLayout
|
||
import android.widget.LinearLayout
|
||
import android.widget.ProgressBar
|
||
import android.widget.ScrollView
|
||
import android.widget.TextView
|
||
import androidx.activity.ComponentActivity
|
||
import androidx.activity.result.contract.ActivityResultContracts
|
||
import androidx.annotation.OptIn
|
||
import androidx.camera.camera2.interop.Camera2Interop
|
||
import androidx.camera.camera2.interop.ExperimentalCamera2Interop
|
||
import androidx.camera.core.Camera
|
||
import androidx.camera.core.CameraSelector
|
||
import androidx.camera.core.FocusMeteringAction
|
||
import androidx.camera.core.ImageAnalysis
|
||
import androidx.camera.core.Preview
|
||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||
import androidx.camera.view.PreviewView
|
||
import java.util.concurrent.Executors
|
||
import java.util.concurrent.TimeUnit
|
||
import java.util.concurrent.atomic.AtomicBoolean
|
||
|
||
class MainActivity : ComponentActivity() {
|
||
private enum class ScannerMode { NONE, OPTICAL, PAIR }
|
||
|
||
private val receiverDeviceLabel: String by lazy { localDeviceLabel() }
|
||
private val cameraExecutor = Executors.newSingleThreadExecutor()
|
||
private val transferExecutor = Executors.newSingleThreadExecutor()
|
||
private val wifiConnector by lazy { WifiConnector(this) }
|
||
private lateinit var assembler: SessionAssembler
|
||
|
||
private var cameraProvider: ProcessCameraProvider? = null
|
||
private var activeCamera: Camera? = null
|
||
private var lastLockFocusAt = 0L
|
||
private var lastLockFocusX = -1f
|
||
private var lastLockFocusY = -1f
|
||
private var currentAnalyzer: QrAnalyzer? = null
|
||
private var qrLockOverlay: QrLockOverlay? = null
|
||
private var scannerStatsText: TextView? = null
|
||
private var scannerLockText: TextView? = null
|
||
private var scannerZoomText: TextView? = null
|
||
private var scannerMode = ScannerMode.NONE
|
||
private var pendingScannerMode = ScannerMode.NONE
|
||
private val pairConsumed = AtomicBoolean(false)
|
||
|
||
private data class CameraFpsPlan(
|
||
val normalCandidates: List<Range<Int>>,
|
||
val highestNormalFps: Int,
|
||
val highestConstrainedHighSpeedFps: Int?,
|
||
)
|
||
|
||
private lateinit var previewView: PreviewView
|
||
private lateinit var titleText: TextView
|
||
private lateinit var deviceText: TextView
|
||
private lateinit var statusText: TextView
|
||
private lateinit var progress: ProgressBar
|
||
|
||
private var pendingPair: PairingPayload? = null
|
||
@Volatile private var connectedNetwork: Network? = null
|
||
private var connectedBaseUrl: String? = null
|
||
private val selectedFiles = mutableListOf<SelectedFile>()
|
||
private var managingFilesForPair: PairingPayload? = null
|
||
private var managingFilesForBaseUrl: String? = null
|
||
private var sendStatusText: TextView? = null
|
||
private var sendFilesText: TextView? = null
|
||
private var sendProgress: ProgressBar? = null
|
||
private var sendButton: Button? = null
|
||
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 ->
|
||
if (granted) startScanner(pendingScannerMode) else showHome("需要相机权限才能扫描 QFT 二维码")
|
||
}
|
||
|
||
private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||
val pair = pendingPair
|
||
if (granted && pair?.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||
connectPair(pair)
|
||
return@registerForActivityResult
|
||
}
|
||
if (granted) requestScanner(pendingScannerMode) else showHome("Android 7~9 需要存储权限才能把光学接收文件保存到 Downloads/QFT")
|
||
}
|
||
|
||
private val requestWifiPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
|
||
val denied = result.filterValues { !it }.keys
|
||
val pair = pendingPair
|
||
if (denied.isEmpty() && pair != null) {
|
||
connectPair(pair)
|
||
} else {
|
||
showPairError(pair, "需要附近 Wi-Fi/位置权限才能完成扫码配网")
|
||
}
|
||
}
|
||
|
||
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||
var unknown = 0
|
||
for (uri in uris) {
|
||
val file = UploadClient.describeFile(contentResolver, uri)
|
||
if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
|
||
}
|
||
renderSelectedFiles()
|
||
val pair = managingFilesForPair
|
||
val baseUrl = managingFilesForBaseUrl
|
||
if (pair != null && baseUrl != null) {
|
||
showFileSelection(pair, baseUrl)
|
||
return@registerForActivityResult
|
||
}
|
||
if (unknown > 0) {
|
||
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
|
||
} else if (selectedFiles.isNotEmpty()) {
|
||
sendStatusText?.text = "已选择 ${selectedFiles.size} 个文件,点击“开始传输”"
|
||
}
|
||
}
|
||
|
||
override fun onCreate(savedInstanceState: Bundle?) {
|
||
super.onCreate(savedInstanceState)
|
||
window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||
window.statusBarColor = BG
|
||
window.navigationBarColor = BG
|
||
assembler = SessionAssembler(this) { event -> runOnUiThread { renderOpticalEvent(event) } }
|
||
showHome()
|
||
}
|
||
|
||
private fun showHome(message: String? = null) {
|
||
transferAbortReason = "已返回首页,传输已停止"
|
||
pairConnectionAttempt++
|
||
stopCamera()
|
||
scannerMode = ScannerMode.NONE
|
||
pairConsumed.set(false)
|
||
wifiConnector.release()
|
||
pendingPair = null
|
||
connectedNetwork = null
|
||
connectedBaseUrl = null
|
||
downloadRunning = false
|
||
downloadStatusText = null
|
||
selectedFiles.clear()
|
||
managingFilesForPair = null
|
||
managingFilesForBaseUrl = null
|
||
|
||
val root = pageColumn()
|
||
root.addView(text("QFT", 30f, Color.WHITE, true))
|
||
root.addView(text("超速二维码文件传输", 16f, MUTED))
|
||
root.addView(space(26))
|
||
message?.let {
|
||
val banner = text(it, 14f, WARNING)
|
||
banner.setPadding(dp(14), dp(12), dp(14), dp(12))
|
||
banner.background = rounded(0xFF2B2112.toInt(), 14)
|
||
root.addView(banner, matchWrap(top = 0, bottom = 18))
|
||
}
|
||
|
||
root.addView(modeCard(
|
||
title = "电脑 → 手机",
|
||
badge = "光学零网络 · 单码锁定 · QFT2低密度字母数字QR · 最高60FPS显示",
|
||
body = "手机先搜索并锁定一个大二维码,之后只分析锁定区域。QFT2 使用 Base45 让 QR 保持字母数字模式并降低模块密度;Wi-Fi、蓝牙、局域网和互联网都不参与文件数据传输。",
|
||
buttonLabel = "开始光学接收",
|
||
) { requestScanner(ScannerMode.OPTICAL) })
|
||
root.addView(space(16))
|
||
root.addView(modeCard(
|
||
title = "扫码直传",
|
||
badge = "手机上传 / 电脑下发 · 自动配网 · 快速发现",
|
||
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.7 · Android 7+ 到最新", 12f, MUTED))
|
||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||
}
|
||
|
||
private fun requestScanner(mode: ScannerMode) {
|
||
if (mode == ScannerMode.PAIR) {
|
||
pairConnectionAttempt++
|
||
wifiConnector.release()
|
||
}
|
||
pendingScannerMode = mode
|
||
if (mode == ScannerMode.OPTICAL && Build.VERSION.SDK_INT <= 28 &&
|
||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|
||
) {
|
||
requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||
return
|
||
}
|
||
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
|
||
startScanner(mode)
|
||
} else {
|
||
requestCamera.launch(Manifest.permission.CAMERA)
|
||
}
|
||
}
|
||
|
||
@OptIn(markerClass = [ExperimentalCamera2Interop::class])
|
||
private fun startScanner(mode: ScannerMode) {
|
||
scannerMode = mode
|
||
pairConsumed.set(false)
|
||
setContentView(buildCameraUi(mode))
|
||
val future = ProcessCameraProvider.getInstance(this)
|
||
future.addListener({
|
||
val provider = future.get()
|
||
cameraProvider = provider
|
||
val fpsPlan = chooseCameraFpsPlan()
|
||
val requestedFps = fpsPlan.normalCandidates.first()
|
||
Log.i(
|
||
TAG,
|
||
"normalRanges=${fpsPlan.normalCandidates.joinToString()} " +
|
||
"highestNormal=${fpsPlan.highestNormalFps} " +
|
||
"constrainedHighSpeed=${fpsPlan.highestConstrainedHighSpeedFps} " +
|
||
"requested=$requestedFps",
|
||
)
|
||
|
||
// CameraX exposes no public target-frame-rate setter for
|
||
// ImageAnalysis. Apply the highest normal Camera2 range to both
|
||
// bound use cases through the Camera2 interop layer.
|
||
val previewBuilder = Preview.Builder()
|
||
Camera2Interop.Extender(previewBuilder).setCaptureRequestOption(
|
||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||
requestedFps,
|
||
)
|
||
val preview = previewBuilder.build().also { it.surfaceProvider = previewView.surfaceProvider }
|
||
|
||
val profile = if (mode == ScannerMode.PAIR) QrAnalyzer.Profile.PAIR_FAST else QrAnalyzer.Profile.OPTICAL_LOCKED
|
||
currentAnalyzer?.close()
|
||
val analyzer = QrAnalyzer(
|
||
profile = profile,
|
||
onCode = { code ->
|
||
when (scannerMode) {
|
||
ScannerMode.OPTICAL -> assembler.acceptText(code.text)
|
||
ScannerMode.PAIR -> if (PairingProtocol.isPairingText(code.text)) acceptPairCode(code.text)
|
||
ScannerMode.NONE -> Unit
|
||
}
|
||
},
|
||
onStats = { cameraFps, decodedFps, distinctFps, attemptedFps, decodeMs ->
|
||
runOnUiThread {
|
||
val quality = when (mode) {
|
||
ScannerMode.PAIR -> when {
|
||
decodedFps >= 1.0 -> "识别稳定" to SUCCESS
|
||
cameraFps >= 18.0 -> "正在锁定二维码" to ACCENT
|
||
else -> "相机帧率偏低" to WARNING
|
||
}
|
||
ScannerMode.OPTICAL -> when {
|
||
distinctFps >= 18.0 -> "新帧吞吐良好" to SUCCESS
|
||
distinctFps >= 8.0 -> "可接收 · 继续保持二维码稳定" to ACCENT
|
||
decodedFps >= 8.0 -> "重复帧较多 · 尝试 Windows 30/45 FPS" to WARNING
|
||
else -> "识别偏低 · 放大 Windows 二维码或降到 30 FPS" to WARNING
|
||
}
|
||
ScannerMode.NONE -> "空闲" to MUTED
|
||
}
|
||
scannerStatsText?.text = if (mode == ScannerMode.OPTICAL) {
|
||
"%s · 相机 %.1f FPS · 解码 %.1f/s · 新帧 %.1f/s · 尝试 %.1f/s · %.1fms/次".format(
|
||
quality.first, cameraFps, decodedFps, distinctFps, attemptedFps, decodeMs
|
||
)
|
||
} else {
|
||
"%s · 相机 %.1f FPS · 解码 %.1f/s · 尝试 %.1f/s · %.1fms/次".format(
|
||
quality.first, cameraFps, decodedFps, attemptedFps, decodeMs
|
||
)
|
||
}
|
||
scannerStatsText?.setTextColor(quality.second)
|
||
}
|
||
},
|
||
onLock = { lock ->
|
||
runOnUiThread {
|
||
qrLockOverlay?.update(lock)
|
||
if (mode == ScannerMode.OPTICAL) {
|
||
if (lock.locked && lock.misses == 0 && lock.stability >= 0.67f) maybeRefocusLockedQr()
|
||
scannerLockText?.text = if (lock.locked) {
|
||
val lockHint = when {
|
||
lock.misses > 0 -> "保持锁定 · miss ${lock.misses}"
|
||
lock.stability < 0.67f -> "正在稳定取景框"
|
||
else -> "稳定锁定"
|
||
}
|
||
"$lockHint · 仅分析 ${(lock.searchAreaFraction * 100f).toInt().coerceIn(1, 100)}% 画面"
|
||
} else {
|
||
"区域锁定:搜索中 · 让单个大二维码占取景框 50% 以上"
|
||
}
|
||
scannerLockText?.setTextColor(
|
||
if (!lock.locked) ACCENT else if (lock.misses > 0) WARNING else if (lock.stability >= 0.67f) SUCCESS else ACCENT
|
||
)
|
||
}
|
||
}
|
||
},
|
||
)
|
||
currentAnalyzer = analyzer
|
||
|
||
// v0.4 single large QR is intentionally analyzed at 640x480. With the
|
||
// QR occupying most of the view this still leaves several camera
|
||
// pixels/module, while substantially reducing Y-copy + ZXing work.
|
||
val targetSize = Size(640, 480)
|
||
val analysisBuilder = ImageAnalysis.Builder()
|
||
.setTargetResolution(targetSize)
|
||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||
.setImageQueueDepth(1)
|
||
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||
requestedFps,
|
||
)
|
||
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
||
CaptureRequest.CONTROL_AF_MODE,
|
||
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE,
|
||
)
|
||
val analysis = analysisBuilder.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||
|
||
provider.unbindAll()
|
||
val camera = try {
|
||
provider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis).also {
|
||
scannerStatsText?.text = "相机请求 ${requestedFps.lower}~${requestedFps.upper} FPS · 等待首帧…"
|
||
}
|
||
} catch (_: Exception) {
|
||
// Some old/OEM devices advertise a Camera2 FPS range that is not
|
||
// accepted together with the selected CameraX stream combination.
|
||
// Retry without the explicit AE range rather than failing scanner
|
||
// startup; KEEP_ONLY_LATEST + ROI still provides the fast path.
|
||
provider.unbindAll()
|
||
val fallbackPreview = Preview.Builder().build().also {
|
||
it.surfaceProvider = previewView.surfaceProvider
|
||
}
|
||
val fallbackAnalysis = ImageAnalysis.Builder()
|
||
.setTargetResolution(targetSize)
|
||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||
.setImageQueueDepth(1)
|
||
.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||
scannerStatsText?.text = "设备拒绝显式高帧率请求 · 已回退相机自动 FPS · 等待首帧…"
|
||
provider.bindToLifecycle(
|
||
this,
|
||
CameraSelector.DEFAULT_BACK_CAMERA,
|
||
fallbackPreview,
|
||
fallbackAnalysis,
|
||
)
|
||
}
|
||
activeCamera = camera
|
||
updateScannerZoom(camera.cameraInfo.zoomState.value?.zoomRatio ?: 1f)
|
||
|
||
previewView.post {
|
||
if (previewView.width <= 0 || previewView.height <= 0) return@post
|
||
try {
|
||
val point = previewView.meteringPointFactory.createPoint(
|
||
previewView.width * 0.5f,
|
||
previewView.height * 0.5f,
|
||
)
|
||
val action = FocusMeteringAction.Builder(
|
||
point,
|
||
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
|
||
).setAutoCancelDuration(5, TimeUnit.SECONDS).build()
|
||
camera.cameraControl.startFocusAndMetering(action)
|
||
} catch (_: Exception) {}
|
||
}
|
||
}, mainExecutor)
|
||
}
|
||
|
||
private fun maybeRefocusLockedQr() {
|
||
val camera = activeCamera ?: return
|
||
val center = qrLockOverlay?.lockedCenterInView() ?: return
|
||
if (previewView.width <= 0 || previewView.height <= 0) return
|
||
|
||
// Do not force an AF/AE cycle every few seconds while the phone is
|
||
// stationary: focus pumping can temporarily destroy QR contrast.
|
||
// Re-meter only on the first lock or after the locked region moved
|
||
// materially in the preview.
|
||
val threshold = minOf(previewView.width, previewView.height) * 0.10f
|
||
val dx = center.x - lastLockFocusX
|
||
val dy = center.y - lastLockFocusY
|
||
val moved = lastLockFocusX < 0f || dx * dx + dy * dy >= threshold * threshold
|
||
if (!moved) return
|
||
|
||
val now = android.os.SystemClock.elapsedRealtime()
|
||
if (now - lastLockFocusAt < 1200L) return
|
||
lastLockFocusAt = now
|
||
lastLockFocusX = center.x
|
||
lastLockFocusY = center.y
|
||
try {
|
||
val point = previewView.meteringPointFactory.createPoint(center.x, center.y)
|
||
val action = FocusMeteringAction.Builder(
|
||
point,
|
||
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
|
||
).setAutoCancelDuration(2, TimeUnit.SECONDS).build()
|
||
camera.cameraControl.startFocusAndMetering(action)
|
||
} catch (_: Exception) {}
|
||
}
|
||
|
||
private fun adjustScannerZoom(scale: Float) {
|
||
val camera = activeCamera ?: return
|
||
val zoom = camera.cameraInfo.zoomState.value ?: return
|
||
val next = (zoom.zoomRatio * scale).coerceIn(zoom.minZoomRatio, zoom.maxZoomRatio)
|
||
try {
|
||
camera.cameraControl.setZoomRatio(next)
|
||
updateScannerZoom(next)
|
||
} catch (_: Exception) {}
|
||
}
|
||
|
||
private fun updateScannerZoom(ratio: Float) {
|
||
scannerZoomText?.text = "缩放 %.1fx · 双指缩放,点按二维码处重新聚焦".format(ratio)
|
||
}
|
||
|
||
private fun focusScannerAt(x: Float, y: Float) {
|
||
val camera = activeCamera ?: return
|
||
if (previewView.width <= 0 || previewView.height <= 0) return
|
||
try {
|
||
val point = previewView.meteringPointFactory.createPoint(x, y)
|
||
val action = FocusMeteringAction.Builder(
|
||
point,
|
||
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
|
||
).setAutoCancelDuration(3, TimeUnit.SECONDS).build()
|
||
camera.cameraControl.startFocusAndMetering(action)
|
||
scannerLockText?.text = "已在点按位置重新聚焦"
|
||
scannerLockText?.setTextColor(ACCENT)
|
||
} catch (_: Exception) {}
|
||
}
|
||
|
||
private fun installScannerGestures(target: android.view.View) {
|
||
var downX = 0f
|
||
var downY = 0f
|
||
var scaled = false
|
||
val detector = ScaleGestureDetector(this, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
|
||
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
|
||
scaled = true
|
||
return true
|
||
}
|
||
|
||
override fun onScale(detector: ScaleGestureDetector): Boolean {
|
||
adjustScannerZoom(detector.scaleFactor)
|
||
return true
|
||
}
|
||
})
|
||
target.setOnTouchListener { _, event ->
|
||
detector.onTouchEvent(event)
|
||
when (event.actionMasked) {
|
||
MotionEvent.ACTION_DOWN -> {
|
||
downX = event.x
|
||
downY = event.y
|
||
scaled = false
|
||
}
|
||
MotionEvent.ACTION_UP -> {
|
||
val dx = event.x - downX
|
||
val dy = event.y - downY
|
||
val tapSlop = dp(12).toFloat()
|
||
if (!scaled && dx * dx + dy * dy <= tapSlop * tapSlop) {
|
||
focusScannerAt(event.x, event.y)
|
||
}
|
||
}
|
||
MotionEvent.ACTION_CANCEL -> scaled = false
|
||
}
|
||
true
|
||
}
|
||
}
|
||
|
||
private fun chooseCameraFpsPlan(): CameraFpsPlan {
|
||
return try {
|
||
val manager = getSystemService(android.content.Context.CAMERA_SERVICE) as CameraManager
|
||
val characteristics = manager.cameraIdList
|
||
.asSequence()
|
||
.map { manager.getCameraCharacteristics(it) }
|
||
.firstOrNull { it.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK }
|
||
val normalRanges = characteristics
|
||
?.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
|
||
?.filter { it.lower > 0 && it.upper >= it.lower }
|
||
?.sortedWith(compareByDescending<Range<Int>> { it.upper }.thenByDescending { it.lower })
|
||
.orEmpty()
|
||
val highSpeed = characteristics
|
||
?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
|
||
?.highSpeedVideoFpsRanges
|
||
?.maxOfOrNull { it.upper }
|
||
CameraFpsPlan(
|
||
normalCandidates = normalRanges.ifEmpty { listOf(Range(30, 30)) },
|
||
highestNormalFps = normalRanges.maxOfOrNull { it.upper } ?: 30,
|
||
highestConstrainedHighSpeedFps = highSpeed,
|
||
)
|
||
} catch (_: Exception) {
|
||
CameraFpsPlan(
|
||
normalCandidates = listOf(Range(30, 30)),
|
||
highestNormalFps = 30,
|
||
highestConstrainedHighSpeedFps = null,
|
||
)
|
||
}
|
||
}
|
||
|
||
private fun buildCameraUi(mode: ScannerMode): FrameLayout {
|
||
val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||
previewView = PreviewView(this).apply {
|
||
implementationMode = PreviewView.ImplementationMode.PERFORMANCE
|
||
scaleType = PreviewView.ScaleType.FILL_CENTER
|
||
}
|
||
root.addView(previewView, FrameLayout.LayoutParams(-1, -1))
|
||
qrLockOverlay = QrLockOverlay(this)
|
||
root.addView(qrLockOverlay, FrameLayout.LayoutParams(-1, -1))
|
||
// The overlay is above PreviewView, so it owns both gestures: one-finger
|
||
// tap selects AF/AE, and a two-finger gesture adjusts CameraX zoom.
|
||
installScannerGestures(qrLockOverlay!!)
|
||
|
||
val top = LinearLayout(this).apply {
|
||
orientation = LinearLayout.HORIZONTAL
|
||
gravity = Gravity.CENTER_VERTICAL
|
||
setPadding(dp(14), dp(12), dp(14), dp(12))
|
||
setBackgroundColor(0xB80C0E12.toInt())
|
||
}
|
||
val back = button("‹ 返回").apply { setOnClickListener { showHome() } }
|
||
top.addView(back)
|
||
titleText = text(if (mode == ScannerMode.OPTICAL) "电脑 → 手机" else "扫码连接电脑", 19f, Color.WHITE, true)
|
||
top.addView(titleText, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(10) })
|
||
root.addView(top, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
|
||
|
||
val panel = LinearLayout(this).apply {
|
||
orientation = LinearLayout.VERTICAL
|
||
setPadding(dp(16), dp(14), dp(16), dp(16))
|
||
background = rounded(0xE80C0E12.toInt(), 18)
|
||
}
|
||
deviceText = text(
|
||
if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT2 MANIFEST…"
|
||
else "目标:等待 QFTPAIR2 配对二维码",
|
||
14f, Color.WHITE
|
||
)
|
||
statusText = text(
|
||
if (mode == ScannerMode.OPTICAL) "让电脑的单个大二维码占取景框 50% 以上,识别后会自动锁定区域"
|
||
else "扫描 Windows“手机传电脑”页面上的二维码",
|
||
14f, MUTED
|
||
)
|
||
progress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
|
||
panel.addView(deviceText)
|
||
panel.addView(statusText, matchWrap(top = 7))
|
||
scannerLockText = text(
|
||
if (mode == ScannerMode.OPTICAL) "区域锁定:搜索中" else "配对识别:快速模式",
|
||
12f, ACCENT
|
||
)
|
||
panel.addView(scannerLockText, matchWrap(top = 6))
|
||
val zoomRow = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
|
||
val zoomOut = button("−").apply { setOnClickListener { adjustScannerZoom(0.80f) } }
|
||
val zoomIn = button("+").apply { setOnClickListener { adjustScannerZoom(1.25f) } }
|
||
scannerZoomText = text("缩放 1.0x · 双指缩放,点按二维码处重新聚焦", 12f, MUTED)
|
||
zoomRow.addView(zoomOut, LinearLayout.LayoutParams(dp(48), dp(42)))
|
||
zoomRow.addView(scannerZoomText, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(8); marginEnd = dp(8) })
|
||
zoomRow.addView(zoomIn, LinearLayout.LayoutParams(dp(48), dp(42)))
|
||
panel.addView(zoomRow, matchWrap(top = 6))
|
||
scannerStatsText = text("相机分析:等待首帧…", 12f, ACCENT)
|
||
panel.addView(scannerStatsText, matchWrap(top = 4))
|
||
panel.addView(progress, LinearLayout.LayoutParams(-1, dp(8)).apply { topMargin = dp(12) })
|
||
root.addView(panel, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply {
|
||
leftMargin = dp(12); rightMargin = dp(12); bottomMargin = dp(12)
|
||
})
|
||
return root
|
||
}
|
||
|
||
private fun acceptPairCode(text: String) {
|
||
if (!PairingProtocol.isPairingText(text)) return
|
||
if (!pairConsumed.compareAndSet(false, true)) return
|
||
val pair = PairingProtocol.parse(text)
|
||
if (pair == null) {
|
||
pairConsumed.set(false)
|
||
runOnUiThread { statusText.text = "配对二维码格式无效,请重新对准" }
|
||
return
|
||
}
|
||
pendingPair = pair
|
||
runOnUiThread {
|
||
stopCamera()
|
||
showConnecting(pair, "二维码已识别,正在准备本地连接…")
|
||
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && Build.VERSION.SDK_INT <= 28 &&
|
||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|
||
) {
|
||
requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||
} else {
|
||
ensureWifiPermissionThenConnect(pair)
|
||
}
|
||
}
|
||
}
|
||
|
||
private fun ensureWifiPermissionThenConnect(pair: PairingPayload) {
|
||
if (pair.wifi == null) {
|
||
connectPair(pair)
|
||
return
|
||
}
|
||
val required = when {
|
||
Build.VERSION.SDK_INT >= 33 -> arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES)
|
||
else -> arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
|
||
}
|
||
val missing = required.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||
if (missing.isEmpty()) connectPair(pair) else requestWifiPermissions.launch(missing.toTypedArray())
|
||
}
|
||
|
||
private fun connectPair(pair: PairingPayload) {
|
||
val attempt = ++pairConnectionAttempt
|
||
transferAbortReason = null
|
||
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
|
||
wifiConnector.connect(
|
||
pairing = pair,
|
||
onStatus = { message -> runOnUiThread {
|
||
if (attempt == pairConnectionAttempt) updateConnectingStatus(message)
|
||
} },
|
||
onAvailable = available@{ network ->
|
||
if (attempt != pairConnectionAttempt) return@available
|
||
connectedNetwork = network
|
||
// A retained WifiNetworkSpecifier request may deliver a fresh
|
||
// Network after a brief radio fluctuation. Do not restart the
|
||
// page or transfer; chunk retries will use this new handle.
|
||
if (connectedBaseUrl != null) return@available
|
||
transferExecutor.execute {
|
||
if (attempt != pairConnectionAttempt) return@execute
|
||
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
|
||
val discovered = UploadClient.discoverUdp(
|
||
network = network,
|
||
pairing = pair,
|
||
hosts = wifiConnector.discoveryHosts(network),
|
||
)
|
||
runOnUiThread {
|
||
updateConnectingStatus(
|
||
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
|
||
else "UDP 未响应 · 正在并行探测网关与本地 IP…"
|
||
)
|
||
}
|
||
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
|
||
val subnet = wifiConnector.subnetEndpoints(network, pair.port)
|
||
if (discovered == null) {
|
||
runOnUiThread {
|
||
updateConnectingStatus("正在并行探测网关;必要时自动扫描当前 QFT 子网…")
|
||
}
|
||
}
|
||
val base = UploadClient.probeRobust(
|
||
network = network,
|
||
pairing = pair,
|
||
deviceName = receiverDeviceLabel,
|
||
preferredEndpoints = gateways,
|
||
discoveredEndpoint = discovered,
|
||
subnetEndpoints = subnet,
|
||
)
|
||
runOnUiThread {
|
||
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||
if (base == null) {
|
||
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
|
||
} else {
|
||
connectedBaseUrl = base
|
||
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||
startDownloadFromPc(pair, base)
|
||
} else {
|
||
showSendReady(pair, base)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
onUnavailable = { message -> runOnUiThread {
|
||
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||
// onLost is recovered inside WifiConnector. onUnavailable is
|
||
// terminal (system/user rejected the retained request), so it
|
||
// is the only network callback that aborts an active transfer.
|
||
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) {
|
||
transferAbortReason = message
|
||
downloadStatusText?.apply {
|
||
text = "QFT 本地网络已断开,正在结束当前下载请求…"
|
||
setTextColor(WARNING)
|
||
}
|
||
} else {
|
||
showPairError(pair, message)
|
||
}
|
||
} },
|
||
)
|
||
}
|
||
|
||
private fun showConnecting(pair: PairingPayload, message: String) {
|
||
val root = pageColumn()
|
||
root.addView(text("正在连接电脑", 28f, Color.WHITE, true))
|
||
root.addView(text(pair.pcName, 18f, ACCENT))
|
||
root.addView(space(22))
|
||
root.addView(card().apply {
|
||
addView(text("配对信息", 15f, MUTED))
|
||
addView(text("电脑:${pair.pcName}", 16f, Color.WHITE), matchWrap(top = 8))
|
||
addView(text("网络:${pair.wifi?.ssid ?: "当前局域网"}", 14f, Color.WHITE), matchWrap(top = 5))
|
||
addView(text("会话:${pair.session.take(10)}…", 12f, MUTED), matchWrap(top = 5))
|
||
})
|
||
root.addView(space(18))
|
||
val spinner = ProgressBar(this)
|
||
root.addView(spinner, LinearLayout.LayoutParams(dp(48), dp(48)).apply { gravity = Gravity.CENTER_HORIZONTAL })
|
||
connectingStatusText = text(message, 14f, MUTED).apply { gravity = Gravity.CENTER }
|
||
root.addView(connectingStatusText, matchWrap(top = 12))
|
||
root.addView(space(20))
|
||
root.addView(button("取消").apply { setOnClickListener { showHome() } })
|
||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||
}
|
||
|
||
private fun updateConnectingStatus(message: String) {
|
||
connectingStatusText?.text = message
|
||
}
|
||
|
||
private fun showPairError(pair: PairingPayload?, message: String) {
|
||
// Do not unregister here: Android may still be displaying its
|
||
// Wi-Fi-selection sheet, and unregistering at that moment produces
|
||
// "the app cancelled the device selection request". A retry reuses
|
||
// this retained request; returning home is what explicitly releases it.
|
||
pairConnectionAttempt++
|
||
connectedNetwork = null
|
||
connectedBaseUrl = null
|
||
val root = pageColumn()
|
||
root.addView(text("连接未完成", 28f, Color.WHITE, true))
|
||
root.addView(text(message, 15f, WARNING), matchWrap(top = 12))
|
||
root.addView(space(24))
|
||
if (pair != null) {
|
||
root.addView(button("重试连接").apply { setOnClickListener { ensureWifiPermissionThenConnect(pair) } })
|
||
root.addView(space(10))
|
||
}
|
||
root.addView(button("返回首页重新扫码").apply { setOnClickListener { showHome() } })
|
||
root.addView(space(10))
|
||
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
|
||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||
}
|
||
|
||
private fun showSendReady(pair: PairingPayload, baseUrl: String) {
|
||
val root = pageColumn()
|
||
root.addView(text("已连接电脑", 28f, Color.WHITE, true))
|
||
root.addView(text("${receiverDeviceLabel} → ${pair.pcName}", 16f, ACCENT))
|
||
root.addView(space(18))
|
||
root.addView(card().apply {
|
||
addView(text("连接状态", 14f, MUTED))
|
||
addView(text("● 本地直连已就绪", 17f, SUCCESS, true), matchWrap(top = 8))
|
||
addView(text(if (pair.version >= 2) "Parallel v2 · 目标 8 路并发 · 64 KiB–16 MiB 自适应分块" else "兼容单流模式", 13f, ACCENT), matchWrap(top = 5))
|
||
addView(text("目标:$baseUrl", 12f, MUTED), matchWrap(top = 6))
|
||
pair.wifi?.let { addView(text("QFT 临时网络:${it.ssid}", 12f, MUTED), matchWrap(top = 4)) }
|
||
})
|
||
root.addView(space(14))
|
||
root.addView(card().apply {
|
||
addView(text("选择文件", 17f, Color.WHITE, true))
|
||
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
|
||
addView(sendFilesText, matchWrap(top = 8))
|
||
addView(button("选择文件(可多选)").apply {
|
||
setOnClickListener { showFileSelection(pair, baseUrl) }
|
||
}, matchWrap(top = 12))
|
||
})
|
||
root.addView(space(14))
|
||
root.addView(card().apply {
|
||
addView(text("传输进度", 17f, Color.WHITE, true))
|
||
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 = connectedBaseUrl != null
|
||
setOnClickListener {
|
||
if (selectedFiles.isEmpty()) showFileSelection(pair, baseUrl)
|
||
else startUploads(pair, baseUrl)
|
||
}
|
||
}
|
||
addView(sendButton, matchWrap(top = 14))
|
||
})
|
||
root.addView(space(14))
|
||
root.addView(button("断开并返回首页").apply { setOnClickListener { showHome() } })
|
||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||
renderSelectedFiles()
|
||
}
|
||
|
||
private fun startDownloadFromPc(pair: PairingPayload, baseUrl: String) {
|
||
val fileName = pair.fileName ?: "qft-download.bin"
|
||
val total = pair.fileSize ?: 0L
|
||
val root = pageColumn()
|
||
root.addView(text("正在接收文件", 28f, Color.WHITE, true))
|
||
root.addView(text("${pair.pcName} → $receiverDeviceLabel", 16f, ACCENT))
|
||
root.addView(space(18))
|
||
root.addView(card().apply {
|
||
addView(text("扫码配置已完成", 17f, SUCCESS, true))
|
||
addView(text(
|
||
if (total >= 32L * 1024L * 1024L)
|
||
"连接将保持到返回首页;正在通过本地网络进行最高 8 路并行直传。"
|
||
else
|
||
"连接将保持到返回首页;正在通过本地网络直接传输。",
|
||
14f, MUTED,
|
||
), matchWrap(top = 8))
|
||
addView(text(fileName, 15f, Color.WHITE), matchWrap(top = 12))
|
||
addView(text(humanBytes(total), 13f, MUTED), matchWrap(top = 4))
|
||
})
|
||
root.addView(space(14))
|
||
val status = text("正在建立文件下载…", 14f, MUTED)
|
||
downloadStatusText = status
|
||
val bar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000 }
|
||
root.addView(status)
|
||
root.addView(bar, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
|
||
root.addView(space(18))
|
||
root.addView(button("取消并返回首页").apply { setOnClickListener { showHome() } })
|
||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||
|
||
downloadRunning = true
|
||
transferAbortReason = null
|
||
transferExecutor.execute {
|
||
// 「传输 / 校验 / 保存」三个阶段各自的速率含义不同,
|
||
// 每进入一个新阶段就重新计时,否则显示出来的速率毫无意义。
|
||
var phaseLabel = "正在接收"
|
||
var phaseStartedAt = android.os.SystemClock.elapsedRealtime()
|
||
try {
|
||
val saved = DownloadClient.download(
|
||
context = this@MainActivity,
|
||
resolver = contentResolver,
|
||
networkProvider = { connectedNetwork },
|
||
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() - phaseStartedAt).coerceAtLeast(1L)
|
||
val rate = received * 1000.0 / elapsed
|
||
bar.progress = fraction
|
||
status.text = "$phaseLabel ${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
|
||
}
|
||
}
|
||
runOnUiThread {
|
||
bar.progress = 1000
|
||
status.setTextColor(SUCCESS)
|
||
status.text = "接收完成:已保存到 Downloads/QFT/${saved.name}"
|
||
}
|
||
} catch (e: Exception) {
|
||
runOnUiThread {
|
||
downloadRunning = false
|
||
// 落盘失败时文件其实已经完整收到了,别再说「接收失败」误导用户
|
||
val prefix = if (e is DownloadClient.SaveFailure) "保存失败" else "从电脑接收失败"
|
||
showPairError(pair, "$prefix:${e.message}")
|
||
}
|
||
} finally {
|
||
downloadRunning = false
|
||
}
|
||
}
|
||
}
|
||
|
||
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") }
|
||
if (selectedFiles.size > 8) append("…另外 ${selectedFiles.size - 8} 个文件\n")
|
||
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
|
||
}.trim()
|
||
}
|
||
sendButton?.text = if (selectedFiles.isEmpty()) "选择传输文件" else "开始传输"
|
||
sendButton?.isEnabled = connectedBaseUrl != null
|
||
}
|
||
|
||
private fun startUploads(pair: PairingPayload, baseUrl: String) {
|
||
if (selectedFiles.isEmpty()) {
|
||
sendStatusText?.setTextColor(WARNING)
|
||
sendStatusText?.text = "请先选择需要传输的文件"
|
||
showFileSelection(pair, baseUrl)
|
||
return
|
||
}
|
||
val files = selectedFiles.toList()
|
||
sendButton?.isEnabled = false
|
||
transferExecutor.execute {
|
||
try {
|
||
files.forEachIndexed { index, file ->
|
||
val startedAt = android.os.SystemClock.elapsedRealtime()
|
||
runOnUiThread {
|
||
sendProgress?.progress = 0
|
||
sendStatusText?.text = "${index + 1}/${files.size} · 正在发送 ${file.name}"
|
||
}
|
||
UploadClient.upload(
|
||
resolver = contentResolver,
|
||
networkProvider = { connectedNetwork },
|
||
baseUrl = baseUrl,
|
||
pairing = pair,
|
||
deviceName = receiverDeviceLabel,
|
||
file = file,
|
||
abortReason = { transferAbortReason },
|
||
) { sent, total ->
|
||
runOnUiThread {
|
||
val p = if (total == 0L) 1000 else ((sent.toDouble() / total) * 1000).toInt().coerceIn(0, 1000)
|
||
val elapsedMs = (android.os.SystemClock.elapsedRealtime() - startedAt).coerceAtLeast(1L)
|
||
val bytesPerSecond = sent * 1000.0 / elapsedMs
|
||
val etaSeconds = if (bytesPerSecond > 1.0 && total > sent) (total - sent) / bytesPerSecond else 0.0
|
||
sendProgress?.progress = p
|
||
sendStatusText?.text = buildString {
|
||
append("${index + 1}/${files.size} · ${file.name}\n")
|
||
append("${humanBytes(sent)} / ${humanBytes(total)} · ${humanBytes(bytesPerSecond.toLong())}/s")
|
||
if (etaSeconds > 0.5) append(" · 剩余 ${humanDuration(etaSeconds)}")
|
||
}
|
||
}
|
||
}
|
||
}
|
||
runOnUiThread {
|
||
sendProgress?.progress = 1000
|
||
sendStatusText?.text = "全部完成 · 已发送 ${files.size} 个文件"
|
||
sendButton?.isEnabled = true
|
||
}
|
||
} catch (e: Exception) {
|
||
runOnUiThread {
|
||
sendStatusText?.text = "传输失败:${e.message}"
|
||
sendButton?.isEnabled = true
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
private fun renderOpticalEvent(event: ReceiveEvent) {
|
||
if (scannerMode != ScannerMode.OPTICAL) return
|
||
when (event) {
|
||
is ReceiveEvent.Started -> {
|
||
titleText.text = event.manifest.fileName
|
||
deviceText.text = "传输设备:${event.manifest.senderDevice} → $receiverDeviceLabel"
|
||
statusText.text = "已锁定会话,等待数据块…"
|
||
progress.progress = 0
|
||
}
|
||
is ReceiveEvent.Progress -> {
|
||
val total = event.total.coerceAtLeast(1)
|
||
val p = event.received.toDouble() / total.toDouble()
|
||
progress.progress = (p * 1000).toInt().coerceIn(0, 1000)
|
||
statusText.text = "已收到 ${event.received}/${event.total} · ${(p * 100).toInt()}% · 漏帧会在下一轮补齐"
|
||
}
|
||
is ReceiveEvent.Completed -> {
|
||
progress.progress = 1000
|
||
deviceText.text = "传输完成:${event.manifest.senderDevice} → $receiverDeviceLabel"
|
||
statusText.text = "完成:已保存到 Downloads/QFT/${event.savedName}"
|
||
}
|
||
is ReceiveEvent.Error -> statusText.text = event.message
|
||
}
|
||
}
|
||
|
||
private fun stopCamera() {
|
||
try { cameraProvider?.unbindAll() } catch (_: Exception) {}
|
||
cameraProvider = null
|
||
activeCamera = null
|
||
lastLockFocusAt = 0L
|
||
lastLockFocusX = -1f
|
||
lastLockFocusY = -1f
|
||
currentAnalyzer?.close()
|
||
currentAnalyzer = null
|
||
qrLockOverlay?.clear()
|
||
qrLockOverlay = null
|
||
scannerStatsText = null
|
||
scannerLockText = null
|
||
scannerZoomText = null
|
||
scannerMode = ScannerMode.NONE
|
||
}
|
||
|
||
private fun localDeviceLabel(): String {
|
||
val manufacturer = Build.MANUFACTURER.orEmpty().trim()
|
||
val model = Build.MODEL.orEmpty().trim()
|
||
return when {
|
||
model.isBlank() -> "Android"
|
||
manufacturer.isBlank() -> model
|
||
model.startsWith(manufacturer, ignoreCase = true) -> model
|
||
else -> "$manufacturer $model"
|
||
}
|
||
}
|
||
|
||
private fun pageColumn(): LinearLayout = LinearLayout(this).apply {
|
||
orientation = LinearLayout.VERTICAL
|
||
setPadding(dp(20), dp(28), dp(20), dp(28))
|
||
setBackgroundColor(BG)
|
||
}
|
||
|
||
private fun modeCard(title: String, badge: String, body: String, buttonLabel: String, onClick: () -> Unit): LinearLayout = card().apply {
|
||
addView(text(title, 23f, Color.WHITE, true))
|
||
addView(text(badge, 13f, ACCENT, true), matchWrap(top = 5))
|
||
addView(text(body, 14f, MUTED), matchWrap(top = 12))
|
||
addView(button(buttonLabel).apply { setOnClickListener { onClick() } }, matchWrap(top = 18))
|
||
}
|
||
|
||
private fun card(): LinearLayout = LinearLayout(this).apply {
|
||
orientation = LinearLayout.VERTICAL
|
||
setPadding(dp(18), dp(18), dp(18), dp(18))
|
||
background = rounded(CARD, 18)
|
||
}
|
||
|
||
private fun text(value: String, size: Float, color: Int, bold: Boolean = false): TextView = TextView(this).apply {
|
||
text = value
|
||
textSize = size
|
||
setTextColor(color)
|
||
if (bold) setTypeface(typeface, android.graphics.Typeface.BOLD)
|
||
setLineSpacing(0f, 1.12f)
|
||
}
|
||
|
||
private fun button(label: String): Button = Button(this).apply {
|
||
text = label
|
||
isAllCaps = false
|
||
setTextColor(Color.WHITE)
|
||
backgroundTintList = ColorStateList.valueOf(0xFF2667FF.toInt())
|
||
minHeight = dp(48)
|
||
}
|
||
|
||
private fun rounded(color: Int, radiusDp: Int): GradientDrawable = GradientDrawable().apply {
|
||
shape = GradientDrawable.RECTANGLE
|
||
setColor(color)
|
||
cornerRadius = dp(radiusDp).toFloat()
|
||
}
|
||
|
||
private fun space(heightDp: Int) = android.widget.Space(this).apply {
|
||
layoutParams = LinearLayout.LayoutParams(1, dp(heightDp))
|
||
}
|
||
|
||
private fun matchWrap(top: Int = 0, bottom: Int = 0) = LinearLayout.LayoutParams(-1, -2).apply {
|
||
topMargin = dp(top); bottomMargin = dp(bottom)
|
||
}
|
||
|
||
private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()
|
||
|
||
private fun humanDuration(seconds: Double): String {
|
||
if (!seconds.isFinite() || seconds <= 0.5) return "<1 秒"
|
||
val total = kotlin.math.ceil(seconds).toLong()
|
||
val minutes = total / 60
|
||
val secs = total % 60
|
||
return if (minutes > 0) "${minutes}分${secs}秒" else "${secs}秒"
|
||
}
|
||
|
||
private fun humanBytes(v: Long): String {
|
||
val units = arrayOf("B", "KB", "MB", "GB", "TB")
|
||
var n = v.toDouble()
|
||
var i = 0
|
||
while (n >= 1024.0 && i < units.lastIndex) { n /= 1024.0; i++ }
|
||
return if (i == 0) "$v ${units[i]}" else "%.2f %s".format(n, units[i])
|
||
}
|
||
|
||
override fun onDestroy() {
|
||
assembler.reset()
|
||
wifiConnector.release()
|
||
stopCamera()
|
||
cameraExecutor.shutdownNow()
|
||
transferExecutor.shutdownNow()
|
||
super.onDestroy()
|
||
}
|
||
|
||
companion object {
|
||
private const val TAG = "QftCamera"
|
||
private const val BG = 0xFF0B0E13.toInt()
|
||
private const val CARD = 0xFF151A22.toInt()
|
||
private const val MUTED = 0xFF9AA4B2.toInt()
|
||
private const val ACCENT = 0xFF6EA8FF.toInt()
|
||
private const val SUCCESS = 0xFF69D38B.toInt()
|
||
private const val WARNING = 0xFFFFC56D.toInt()
|
||
}
|
||
}
|