From d885259e2b80eb4d487876966487261ef79b14e9 Mon Sep 17 00:00:00 2001 From: zhy Date: Mon, 10 Aug 2026 15:45:04 +0800 Subject: [PATCH] =?UTF-8?q?V0.3.0=E7=89=88=E6=9C=AC=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E4=BC=A0=E8=BE=93=E9=80=9F=E5=BA=A6=E5=92=8C=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 12 + IMPLEMENTATION_STATUS.md | 55 + README.md | 131 + TEST_REPORT.md | 182 + TEST_RESULTS.txt | 29 + VERIFY_WINDOWS_HOST.ps1 | 37 + android/BUILD_FIX_0.1.1.md | 33 + android/BUILD_FIX_0.2.1.md | 20 + android/app/build.gradle.kts | 50 + android/app/proguard-rules.pro | 1 + android/app/src/main/AndroidManifest.xml | 32 + .../main/java/com/qft/optical/Base64Url.kt | 60 + .../main/java/com/qft/optical/GrayFrame.kt | 43 + .../main/java/com/qft/optical/MainActivity.kt | 618 +++ .../java/com/qft/optical/PairingProtocol.kt | 158 + .../src/main/java/com/qft/optical/Protocol.kt | 108 + .../main/java/com/qft/optical/QrAnalyzer.kt | 162 + .../java/com/qft/optical/SessionAssembler.kt | 192 + .../main/java/com/qft/optical/UploadClient.kt | 473 ++ .../java/com/qft/optical/WifiConnector.kt | 310 ++ android/app/src/main/res/values/themes.xml | 9 + .../main/res/xml/network_security_config.xml | 8 + .../test/java/com/qft/optical/ProtocolTest.kt | 75 + android/bootstrap-wrapper.ps1 | 8 + android/bootstrap-wrapper.sh | 17 + android/build.gradle.kts | 4 + android/gradle.properties | 2 + .../gradle/wrapper/gradle-wrapper.properties | 7 + android/gradlew | 4 + android/gradlew.bat | 3 + android/local.properties.example | 3 + android/repair-windows.ps1 | 68 + android/settings.gradle.kts | 18 + docs/PROTOCOL.md | 86 + docs/ROADMAP.md | 58 + scripts/android_compat_selftest.py | 27 + .../local_transfer_integration_selftest.py | 96 + scripts/memory_budget_selftest.py | 17 + scripts/optical_image_decode_selftest.py | 55 + scripts/pairing_selftest.py | 29 + scripts/parallel_upload_selftest.py | 60 + scripts/protocol_selftest.py | 98 + scripts/run_all_selftests.py | 17 + scripts/udp_discovery_selftest.py | 31 + windows/BUILD_0.2.0.md | 34 + windows/BUILD_FIX_0.1.2.md | 21 + windows/BUILD_FIX_0.1.3.md | 56 + windows/BUILD_FIX_0.2.2.md | 20 + windows/Cargo.lock | 4567 +++++++++++++++++ windows/Cargo.toml | 25 + windows/assets/README_FONT.txt | 17 + windows/src/direct_ap.rs | 79 + windows/src/main.rs | 736 +++ windows/src/optical_cache.rs | 128 + windows/src/pairing.rs | 178 + windows/src/protocol.rs | 274 + windows/src/qr.rs | 103 + windows/src/receiver.rs | 540 ++ 58 files changed, 10284 insertions(+) create mode 100644 .gitignore create mode 100644 IMPLEMENTATION_STATUS.md create mode 100644 README.md create mode 100644 TEST_REPORT.md create mode 100644 TEST_RESULTS.txt create mode 100644 VERIFY_WINDOWS_HOST.ps1 create mode 100644 android/BUILD_FIX_0.1.1.md create mode 100644 android/BUILD_FIX_0.2.1.md create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/proguard-rules.pro create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/java/com/qft/optical/Base64Url.kt create mode 100644 android/app/src/main/java/com/qft/optical/GrayFrame.kt create mode 100644 android/app/src/main/java/com/qft/optical/MainActivity.kt create mode 100644 android/app/src/main/java/com/qft/optical/PairingProtocol.kt create mode 100644 android/app/src/main/java/com/qft/optical/Protocol.kt create mode 100644 android/app/src/main/java/com/qft/optical/QrAnalyzer.kt create mode 100644 android/app/src/main/java/com/qft/optical/SessionAssembler.kt create mode 100644 android/app/src/main/java/com/qft/optical/UploadClient.kt create mode 100644 android/app/src/main/java/com/qft/optical/WifiConnector.kt create mode 100644 android/app/src/main/res/values/themes.xml create mode 100644 android/app/src/main/res/xml/network_security_config.xml create mode 100644 android/app/src/test/java/com/qft/optical/ProtocolTest.kt create mode 100644 android/bootstrap-wrapper.ps1 create mode 100644 android/bootstrap-wrapper.sh create mode 100644 android/build.gradle.kts create mode 100644 android/gradle.properties create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100644 android/gradlew create mode 100644 android/gradlew.bat create mode 100644 android/local.properties.example create mode 100644 android/repair-windows.ps1 create mode 100644 android/settings.gradle.kts create mode 100644 docs/PROTOCOL.md create mode 100644 docs/ROADMAP.md create mode 100644 scripts/android_compat_selftest.py create mode 100644 scripts/local_transfer_integration_selftest.py create mode 100644 scripts/memory_budget_selftest.py create mode 100644 scripts/optical_image_decode_selftest.py create mode 100644 scripts/pairing_selftest.py create mode 100644 scripts/parallel_upload_selftest.py create mode 100644 scripts/protocol_selftest.py create mode 100644 scripts/run_all_selftests.py create mode 100644 scripts/udp_discovery_selftest.py create mode 100644 windows/BUILD_0.2.0.md create mode 100644 windows/BUILD_FIX_0.1.2.md create mode 100644 windows/BUILD_FIX_0.1.3.md create mode 100644 windows/BUILD_FIX_0.2.2.md create mode 100644 windows/Cargo.lock create mode 100644 windows/Cargo.toml create mode 100644 windows/assets/README_FONT.txt create mode 100644 windows/src/direct_ap.rs create mode 100644 windows/src/main.rs create mode 100644 windows/src/optical_cache.rs create mode 100644 windows/src/pairing.rs create mode 100644 windows/src/protocol.rs create mode 100644 windows/src/qr.rs create mode 100644 windows/src/receiver.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0ed5ad6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +# Rust +/target +**/target +# Android +.gradle/ +**/build/ +local.properties +.idea/ +*.iml +# OS +.DS_Store +Thumbs.db diff --git a/IMPLEMENTATION_STATUS.md b/IMPLEMENTATION_STATUS.md new file mode 100644 index 0000000..9a8cd20 --- /dev/null +++ b/IMPLEMENTATION_STATUS.md @@ -0,0 +1,55 @@ +# QFT v0.3.0-rc3 implementation status + +## Windows → Android optical + +- [x] QFT1 manifest/data/end wire format +- [x] CRC32 per frame + SHA-256 whole file +- [x] 1 QR / 4 QR per page +- [x] Windows target refresh 1~60 FPS +- [x] 4-code default, 900-byte payload +- [x] Rayon background pre-encoding +- [x] reused egui GPU TextureHandle +- [x] positioned source reads; no whole-file mmap +- [x] bounded pre-render cache; 1.1GiB process design ceiling +- [x] Android 4-region concurrent decoder +- [x] CameraX KEEP_ONLY_LATEST +- [x] no whole-frame rotation/copy in hot path +- [x] runtime scan FPS / decoded QR/s status +- [x] synthetic 4/4 visual QR decode test +- [ ] physical 60Hz/120Hz monitor × multiple Android camera hardware matrix + +## Android → Windows + +- [x] QFTPAIR2 compact pairing QR +- [x] persistent per-PC Direct AP identity + per-session token +- [x] one fast endpoint hint in Direct pairing QR +- [x] Windows Wi-Fi Direct Legacy AP code +- [x] Android 10+ WifiNetworkSpecifier path +- [x] Android 7~9 legacy Wi-Fi path +- [x] wait for actual IPv4/link route before discovery +- [x] UDP QFTDISC2 receiver discovery +- [x] directed broadcast + real gateway discovery +- [x] bounded /24 concurrent subnet fallback +- [x] local cleartext network security config +- [x] private/local IPv4 + session-token validation +- [x] Parallel v2 upload init/chunk/finish +- [x] adaptive 4/8/16 MiB chunk size +- [x] up to 8 Android workers per file +- [x] Windows concurrent positioned writes +- [x] temporary `.qftpart`, final SHA-256 and rename +- [x] legacy single-stream fallback +- [x] loopback UDP + HTTP + 8-worker integration test +- [ ] physical Windows Wi-Fi Direct adapter / driver / firewall matrix + +## Android compatibility + +- [x] minSdk 24 (Android 7.0) +- [x] legacy WRITE_EXTERNAL_STORAGE path <= Android 9 +- [x] MediaStore Downloads >= Android 10 +- [x] ACCESS_FINE_LOCATION compatibility <= Android 12 +- [x] NEARBY_WIFI_DEVICES >= Android 13 +- [x] no `java.util.Base64` dependency in app source +- [x] key Kotlin protocol/pairing/upload/scanner source syntax tests in the build environment +- [ ] APK installation/runtime matrix on Android 7/8/9/10/11/12/13/14/15/16+ physical/emulated devices + +See `TEST_REPORT.md` for exact test evidence and limitations. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3123247 --- /dev/null +++ b/README.md @@ -0,0 +1,131 @@ +# QFT · 超速二维码文件传输 v0.3.0-rc3 + +Windows + Android 双向候选版。两个方向采用不同链路: + +- **Windows → Android:纯光学**。文件数据只经过 Windows 屏幕 → Android 摄像头;不使用 Wi‑Fi、蓝牙、局域网或互联网。 +- **Android → Windows:扫码本地直连**。Windows 选择保存目录并启动 QFT Direct 临时 Wi‑Fi/接收服务;Android 扫码后请求配网、自动发现电脑,然后并行分块上传。文件不经过外网。 + +> rc3 是性能/兼容性候选版。仓库内的协议、二维码、并行上传、UDP 发现、内存预算与 Kotlin 关键源文件测试已通过;真正的 Windows Wi‑Fi Direct 驱动、Windows 防火墙、60Hz 显示器与不同 Android 相机组合仍必须在真实设备上做验收,详见 `TEST_REPORT.md`。 + +## v0.3.0-rc3 针对性优化 + +### 1. Windows → Android:最高 60 FPS 显示目标 + +- Windows UI 支持 `1~60 FPS`,提供 15/30/60 与“极速预设”。 +- 默认 **4 QR/页 + 60 FPS**,每次刷新最多承载 4 个独立 QFT1 数据帧。 +- 单 QR payload 默认 900 B;理论原始文件载荷约 `900 × 4 × 60 = 216,000 B/s`(约 210.9 KiB/s),实际速度取决于显示器刷新率、Android 相机 FPS、曝光/滚动快门和识别率。 +- Android 光学扫描采用 1280×720 分析帧、4 象限并行 ZXing 解码、`KEEP_ONLY_LATEST`、Y 平面直接读取且不再整帧旋转。 +- Windows 预编码使用 Rayon 多核并行;GPU 纹理复用,不再每帧创建新的纹理对象。 +- UI 动态显示目标 FPS、实际页面 FPS、理论载荷和 Android 实际“相机 FPS / 有效 QR/s”。 + +### 2. 文件与内存优化 + +- Windows 光学源文件不做整文件 mmap;使用定位读取,避免大文件被整体映射/触碰进工作集。 +- 预编码缓存硬设计目标:整进程约 **≤ 1100 MiB**。 +- 4 QR / 960px 模式缓存最多 192 页,估算约 **675 MiB**;另为 UI、WGPU/GPU staging、线程栈、二维码临时对象和系统 I/O 留出余量。 +- Android → Windows 每个文件内部最高 **8 路并行**。 +- 分块根据文件大小自适应:小文件 4 MiB、中型 8 MiB、大文件 16 MiB;每个 worker 仅使用约 1 MiB 应用层 I/O buffer。 +- Windows 端预分配 `.qftpart`,多个独立文件句柄按 offset 写入,完成后 SHA-256 校验并原子改名。 + +### 3. Android → Windows:连接速度/稳定性 + +扫码二维码升级到更短的 `QFTPAIR2`: + +- 短字段 JSON + Base64URL。 +- 配对 QR 使用中等级纠错,候选测试为 QR version 10。 +- QFT Direct 二维码携带一个快速 endpoint hint,同时保留真实 Wi‑Fi 网关、UDP 发现与当前子网扫描作为 fallback。 +- Android 配对扫描分辨率降到 640×480,优先 GlobalHistogram 快速路径;失败才周期性使用 HybridBinarizer。 +- Android 连接 Wi‑Fi 后不立即假定网络可用,而是等待真实 IPv4/route。 +- 电脑发现顺序: + 1. QR endpoint hint; + 2. `QFTDISC2` UDP 发现; + 3. Android 真实 Wi‑Fi gateway; + 4. 常见 Windows Direct 地址; + 5. 当前实际子网最多 /24 的并发 fallback 扫描。 +- 所有 HTTP 请求绑定到扫码建立的 `Network`,避免手机 4G/5G/其他 Wi‑Fi 抢路由。 +- Android Manifest 同时启用 local cleartext network security config;QFTPAIR 解析器仍只允许 literal private/local IPv4 + 本次 session token。 + +### 4. Android 7 → 最新 + +- `minSdk = 24`(Android 7.0)。 +- Android 10+:`WifiNetworkSpecifier` local-only 配网。 +- Android 7~9:`WifiManager/WifiConfiguration` 兼容路径。 +- Android 13+:`NEARBY_WIFI_DEVICES`。 +- Android 7~12:位置权限兼容。 +- Android 7~9 光学保存:`WRITE_EXTERNAL_STORAGE` + `Downloads/QFT`。 +- Android 10+ 光学保存:MediaStore Downloads。 + +## Windows → Android 使用 + +1. Windows:进入 `电脑 → Android`。 +2. 选择文件。 +3. 建议先用 `30 FPS / 4 码` 验证,再切 `60 FPS / 4 码`。 +4. Android:`电脑 → 手机 → 开始光学接收`。 +5. 让 2×2 QR 区域尽量完整占据手机取景框。 +6. Android UI 会实时显示相机分析 FPS 和有效 QR/s;若识别偏低,靠近屏幕或把 Windows 降为 30 FPS。 +7. 收齐后自动 SHA-256 校验并保存。 + +## Android → Windows 使用 + +1. Windows:`Android → 电脑`。 +2. 选择接收文件夹。 +3. 默认选择 `QFT Direct`。 +4. 点击“启动接收并生成二维码”。 +5. Windows 保持该页面开启。若 Windows Defender Firewall 首次询问网络访问,请允许 QFT 访问**专用网络**。 +6. Android:`手机 → 电脑 → 扫码连接电脑`。 +7. 首次连接具体 QFT Direct AP 时,Android 系统可能要求确认该本地 Wi‑Fi。 +8. App 自动完成 endpoint/UDP/gateway/subnet 发现,出现“已连接电脑”后选择文件并开始传输。 + +如果电脑没有可用 Wi‑Fi Direct 适配器,可切换 Windows 的“当前局域网”备用模式。 + +## 构建 + +### Windows + +需要 Rust stable MSVC + Visual C++ Build Tools / Windows SDK。 + +```powershell +cd windows +cargo check +cargo build --release +cargo run --release +``` + +### Android + +当前构建栈:compileSdk/targetSdk 35、minSdk 24、JDK 17。 + +```powershell +cd android +.\gradlew.bat :app:testDebugUnitTest :app:assembleDebug +``` + +APK: + +`android/app/build/outputs/apk/debug/app-debug.apk` + +## 字体 + +Windows UI 优先读取: + +`windows/assets/qft-ui.ttf` + +也可设置 `QFT_FONT_PATH` 指向支持中文的 TTF。项目不会分发第三方字体文件。 + +## 验证 + +开发侧测试: + +```bash +python scripts/run_all_selftests.py +python scripts/optical_image_decode_selftest.py +python scripts/local_transfer_integration_selftest.py +``` + +Windows 真机环境可运行根目录: + +```powershell +.\VERIFY_WINDOWS_HOST.ps1 +``` + +详细结果与尚未能在当前生成环境自动验证的硬件项目见 `TEST_REPORT.md`。 diff --git a/TEST_REPORT.md b/TEST_REPORT.md new file mode 100644 index 0000000..534910d --- /dev/null +++ b/TEST_REPORT.md @@ -0,0 +1,182 @@ +# QFT v0.3.0-rc3 test report + +Date: 2026-08-10 + +This report deliberately separates **tests actually executed in the current build environment** from **hardware acceptance that cannot be truthfully simulated here**. + +## Executed and passed + +### Optical protocol recovery + +Command: + +`python scripts/protocol_selftest.py` + +Result: + +- 2,500,123-byte random file +- 900-byte chunks +- 4 QR/page +- target 60 pages/s model +- synthetic 24% whole-page loss + 14% per-lane QR loss +- reconstructed exact original file in 9 rounds +- final SHA-256 identical +- representative frame: QR v25, ~3 rendered pixels/module at native 960px page +- theoretical raw file payload: ~210.9 KiB/s + +**PASS** + +### Synthetic visual QR decode + +Command: + +`python scripts/optical_image_decode_selftest.py` + +Result in this environment: + +- 4/4 high-density QFT optical QR symbols decoded from one 960×960 synthetic page using libzbar/pyzbar +- QFTPAIR2 QR-M decoded after synthetic 7° rotation plus light Gaussian blur + +**PASS** + +This proves generated QR geometry/data is decodable under a synthetic image path; it does **not** prove a particular monitor/camera can decode 60 physical refreshes per second. + +### QFTPAIR2 size / QR density + +Command: + +`python scripts/pairing_selftest.py` + +Result: + +- QFTPAIR2: 207 characters with one Direct-AP endpoint hint +- older QFTPAIR1 comparison: 368 characters +- v2 size: 56.2% of v1 +- medium-error-correction QR: version 10 +- encode/decode round-trip exact + +**PASS** + +### Parallel local-file chunk reconstruction + +Command: + +`python scripts/parallel_upload_selftest.py` + +Result: + +- ~64 MiB random file +- 8 MiB test chunks +- 8 worker threads +- 1 MiB worker I/O buffers +- out-of-order positioned writes +- final SHA-256 identical + +**PASS** + +### End-to-end local protocol integration + +Command: + +`python scripts/local_transfer_integration_selftest.py` + +Result: + +- QFTDISC2 UDP request/response +- session-token authenticated `/qft/ping` +- Parallel-v2 init +- out-of-order chunk POSTs using 8 workers +- finish +- exact reconstructed file and SHA-256 match + +**PASS** + +### Standalone UDP discovery + +Command: + +`python scripts/udp_discovery_selftest.py` + +QFTDISC2 / QFTHERE2 token and port round-trip. + +**PASS** + +### Memory-budget model + +Command: + +`python scripts/memory_budget_selftest.py` + +Result: + +- 4QR 960px pre-render page ≈ 3.5156 MiB as Color32 +- maximum cache page cap 192 → ≈ 675 MiB +- conservative extra transient test allowance remains below the 1100 MiB design ceiling +- whole source file is no longer memory-mapped + +**PASS (design-budget test)** + +This is not an OS-level hard RSS limiter. GPU drivers, allocator fragmentation and platform runtime memory vary; the implementation intentionally leaves several hundred MiB headroom instead of allocating a full 1 GiB cache. + +### Android compatibility/static guards + +Command: + +`python scripts/android_compat_selftest.py` + +Checked: + +- minSdk 24 +- API 29 modern/legacy Wi-Fi split +- Android 7~9 storage path +- Android <=12 location permission +- Android 13+ nearby-WiFi permission +- network security config for local HTTP +- gateway/directed-broadcast/subnet discovery fallbacks +- 8-worker upload +- 640×480 pairing scan + 1280×720 optical analysis +- KEEP_ONLY_LATEST +- no full-frame rotate in scanner hot path +- no `java.util.Base64` dependency in main Android source + +**PASS** + +### Kotlin source checks executed + +Using `kotlinc-jvm 1.9.0` plus small Android/JSON stubs where necessary: + +- `Base64Url.kt + Protocol.kt` runtime parser test: **PASS** +- `PairingProtocol.kt` syntax/type test: **PASS** +- `UploadClient.kt + PairingProtocol.kt` syntax/type test: **PASS** +- `GrayFrame.kt + QrAnalyzer.kt` syntax/type test: **PASS** +- `WifiConnector.kt` syntax/type test across the modern/legacy branches: **PASS** + +These tests caught and fixed an earlier `ExecutorCompletionService.submit` source error before packaging rc3. + +## Not executable in the current Linux build sandbox + +The following are hardware/OS-specific and therefore are **not claimed as passed** here: + +1. Windows `cargo check/build` against the Windows MSVC/WinRT target. +2. Actual `WiFiDirectAdvertisementPublisher` start on a Windows Wi-Fi adapter. +3. Windows Defender Firewall private-network approval behavior. +4. Android Gradle APK build against a local Android SDK in this sandbox. +5. Android 7/8/9/10/11/12/13/14/15/16+ install/runtime matrix. +6. Real monitor → real camera optical performance at 30/60Hz, different brightness, rolling shutter and autofocus conditions. +7. Real Wi-Fi Direct throughput across different NIC/phone vendors. + +For those reasons **v0.3.0-rc3 remains an RC, not a final stable release**. + +## Required physical acceptance before marking stable + +Run `VERIFY_WINDOWS_HOST.ps1`, then at minimum: + +- Windows 10/11 + Android 7/9/10/13/latest available devices. +- Optical files: 10 KiB, 1 MiB, 10 MiB at 30 FPS and 60 FPS. +- Verify Android UI actual camera FPS / QR/s and final SHA-256. +- Android→Windows QFT Direct: first-time pairing, repeat pairing, reconnect after Wi-Fi loss. +- Test with Windows Firewall prompt accepted and with “current LAN” fallback. +- Upload 10 MiB, 500 MiB, and >2 GiB files; verify final SHA-256 and memory usage. +- Observe Windows working set during optical 60 FPS; if host-specific RSS exceeds 1.1 GiB, reduce the pre-encode cache slider (default 384 MiB) and record the device/driver combination. + +Only after this matrix is passed should the RC label be removed. diff --git a/TEST_RESULTS.txt b/TEST_RESULTS.txt new file mode 100644 index 0000000..74e25ea --- /dev/null +++ b/TEST_RESULTS.txt @@ -0,0 +1,29 @@ +QFT v0.3.0-rc3 test execution log +UTC 2026-08-10 06:48:06 + +== protocol_selftest.py == +PASS optical: 2500123 bytes, 2778 chunks, 4 QR/page @ 60 FPS, 24% page loss + 14% lane loss, recovered in 9 rounds; QR v25, 3px/module, frame chars=1243, theoretical payload=210.9 KiB/s +== pairing_selftest.py == +PASS pairing: QFTPAIR2=207 chars vs v1=368 chars (56.2%), QR-M version=10 +== parallel_upload_selftest.py == +PASS parallel upload: 67121209 bytes, 8 MiB chunks, 8 workers, 1 MiB worker I/O, SHA-256 identical +== udp_discovery_selftest.py == +PASS UDP discovery: request/response token+port round-trip from 127.0.0.1 +== local_transfer_integration_selftest.py == +PASS loopback Parallel v2 integration: UDP discovery + HTTP auth + 6 out-of-order chunks / 8 workers; 41955385 bytes SHA-256 identical in 0.22s +== memory_budget_selftest.py == +PASS memory budget: 4QR cache=192 pages/675.0 MiB; 1QR cache=192 pages/423.0 MiB; hard design ceiling=1100 MiB +== android_compat_selftest.py == +PASS Android compatibility/static guards: minSdk24, API29 split, legacy storage/location, Android13 nearby-WiFi, cleartext local config, subnet fallback, fast scanner paths +ALL CORE PYTHON SELFTESTS PASSED +PASS synthetic QR decode: 4/4 optical QR v25 decoded from 960px page in 48.3 ms; QFTPAIR2 QR-M v10 decoded after 7deg rotate+blur in 1.7 ms + +Kotlin runtime: Base64Url + QFT1 +PASS Kotlin Base64Url + QFT1 parser + +Kotlin syntax: PairingProtocol + UploadClient +PASS Kotlin syntax: PairingProtocol.kt + UploadClient.kt +Kotlin syntax: GrayFrame + QrAnalyzer +PASS Kotlin syntax: GrayFrame.kt + QrAnalyzer.kt +Kotlin syntax: WifiConnector +PASS Kotlin syntax: WifiConnector.kt diff --git a/VERIFY_WINDOWS_HOST.ps1 b/VERIFY_WINDOWS_HOST.ps1 new file mode 100644 index 0000000..b65d087 --- /dev/null +++ b/VERIFY_WINDOWS_HOST.ps1 @@ -0,0 +1,37 @@ +$ErrorActionPreference = 'Stop' +$Root = Split-Path -Parent $MyInvocation.MyCommand.Path + +Write-Host "== QFT v0.3.0-rc3 Windows host verification ==" -ForegroundColor Cyan + +if (Get-Command python -ErrorAction SilentlyContinue) { + Write-Host "[1/4] Core protocol/selftests" + & python "$Root\scripts\run_all_selftests.py" +} else { + Write-Warning "python not found; skipping repository Python selftests" +} + +Write-Host "[2/4] Windows Rust compile" +Push-Location "$Root\windows" +try { + & cargo check + if ($LASTEXITCODE -ne 0) { throw "cargo check failed" } + & cargo build --release + if ($LASTEXITCODE -ne 0) { throw "cargo build --release failed" } +} finally { Pop-Location } + +Write-Host "[3/4] Android unit/build" +Push-Location "$Root\android" +try { + if (!(Test-Path '.\gradle\wrapper\gradle-wrapper.jar')) { + Write-Host "Gradle wrapper jar missing; attempting bootstrap..." + & powershell -ExecutionPolicy Bypass -File '.\bootstrap-wrapper.ps1' + } + & .\gradlew.bat :app:testDebugUnitTest :app:assembleDebug --stacktrace + if ($LASTEXITCODE -ne 0) { throw "Android Gradle verification failed" } +} finally { Pop-Location } + +Write-Host "[4/4] Artifact locations" -ForegroundColor Cyan +Write-Host "Windows EXE: $Root\windows\target\release\qft-windows.exe" +Write-Host "Android APK: $Root\android\app\build\outputs\apk\debug\app-debug.apk" +Write-Host "\nHOST BUILD VERIFICATION PASSED" -ForegroundColor Green +Write-Host "Next: perform the physical display/camera and Wi-Fi Direct acceptance matrix in TEST_REPORT.md." diff --git a/android/BUILD_FIX_0.1.1.md b/android/BUILD_FIX_0.1.1.md new file mode 100644 index 0000000..ffed98a --- /dev/null +++ b/android/BUILD_FIX_0.1.1.md @@ -0,0 +1,33 @@ +# Android build fix v0.1.1 + +This revision intentionally uses the Android 15 / API 35 toolchain for the MVP. +The optical receiver does not use Android 16-only APIs, so API 36 is unnecessary for now. + +Pinned stack: + +- compileSdk / targetSdk: 35 +- Android Gradle Plugin: 8.9.1 +- Gradle: 8.11.1 +- JDK: 17 +- Build Tools: 35.0.0 +- Kotlin Gradle Plugin: 2.1.20 +- Activity: 1.10.1 +- CameraX: 1.4.2 +- ZXing core: 3.5.3 + +The manifest now references the local `@style/QftTheme`; the theme inherits the standard Android Material light no-action-bar theme. + +## Windows one-command repair + +From the `android` directory: + +```powershell +Set-ExecutionPolicy -Scope Process Bypass +.\repair-windows.ps1 -Sdk "E:\SYSTEM\APPDATA\Android_SDK" +``` + +If your SDK lives elsewhere, change `-Sdk`. + +After the script succeeds, the APK should be at: + +`app\build\outputs\apk\debug\app-debug.apk` diff --git a/android/BUILD_FIX_0.2.1.md b/android/BUILD_FIX_0.2.1.md new file mode 100644 index 0000000..66ba972 --- /dev/null +++ b/android/BUILD_FIX_0.2.1.md @@ -0,0 +1,20 @@ +# QFT Android v0.2.1 build fix + +Fixes Kotlin compile error in `MainActivity.kt` line ~502. + +Incorrect: +```kotlin +android.view.Space(this) +``` + +Correct: +```kotlin +android.widget.Space(this) +``` + +The accompanying `layoutParams` and type inference errors were cascading errors caused by the unresolved `Space` class. + +Rebuild with: +```powershell +.\gradlew.bat :app:assembleDebug +``` diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..fc3daa7 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,50 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "com.qft.optical" + compileSdk = 35 + buildToolsVersion = "35.0.0" + + defaultConfig { + applicationId = "com.qft.optical" + minSdk = 24 + targetSdk = 35 + versionCode = 8 + versionName = "0.3.0-rc3" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } +} + +dependencies { + implementation("androidx.activity:activity-ktx:1.10.1") + implementation("androidx.camera:camera-core:1.4.2") + implementation("androidx.camera:camera-camera2:1.4.2") + implementation("androidx.camera:camera-lifecycle:1.4.2") + implementation("androidx.camera:camera-view:1.4.2") + implementation("com.google.zxing:core:3.5.3") + + testImplementation("junit:junit:4.13.2") +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..e0eafce --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1 @@ +# MVP: no custom rules yet. diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..01c4d7b --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/qft/optical/Base64Url.kt b/android/app/src/main/java/com/qft/optical/Base64Url.kt new file mode 100644 index 0000000..3fce931 --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/Base64Url.kt @@ -0,0 +1,60 @@ +package com.qft.optical + +/** Small URL-safe Base64 codec with no padding; works unchanged on Android 7+ and JVM unit tests. */ +object Base64Url { + private const val ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" + private val reverse = IntArray(128) { -1 }.also { table -> + ALPHABET.forEachIndexed { index, c -> table[c.code] = index } + } + + fun encode(input: ByteArray): String { + if (input.isEmpty()) return "" + val out = StringBuilder((input.size * 4 + 2) / 3) + var i = 0 + while (i + 2 < input.size) { + val n = ((input[i].toInt() and 0xff) shl 16) or + ((input[i + 1].toInt() and 0xff) shl 8) or + (input[i + 2].toInt() and 0xff) + out.append(ALPHABET[(n ushr 18) and 63]) + out.append(ALPHABET[(n ushr 12) and 63]) + out.append(ALPHABET[(n ushr 6) and 63]) + out.append(ALPHABET[n and 63]) + i += 3 + } + val remaining = input.size - i + if (remaining == 1) { + val n = (input[i].toInt() and 0xff) shl 16 + out.append(ALPHABET[(n ushr 18) and 63]) + out.append(ALPHABET[(n ushr 12) and 63]) + } else if (remaining == 2) { + val n = ((input[i].toInt() and 0xff) shl 16) or ((input[i + 1].toInt() and 0xff) shl 8) + out.append(ALPHABET[(n ushr 18) and 63]) + out.append(ALPHABET[(n ushr 12) and 63]) + out.append(ALPHABET[(n ushr 6) and 63]) + } + return out.toString() + } + + fun decode(text: String): ByteArray? { + if (text.isEmpty()) return ByteArray(0) + if (text.length % 4 == 1) return null + val out = ByteArray((text.length * 6) / 8) + var outIndex = 0 + var accumulator = 0 + var bits = 0 + for (c in text) { + val code = c.code + if (code >= reverse.size) return null + val value = reverse[code] + if (value < 0) return null + accumulator = (accumulator shl 6) or value + bits += 6 + if (bits >= 8) { + bits -= 8 + if (outIndex >= out.size) return null + out[outIndex++] = ((accumulator ushr bits) and 0xff).toByte() + } + } + return if (outIndex == out.size) out else out.copyOf(outIndex) + } +} diff --git a/android/app/src/main/java/com/qft/optical/GrayFrame.kt b/android/app/src/main/java/com/qft/optical/GrayFrame.kt new file mode 100644 index 0000000..936dde1 --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/GrayFrame.kt @@ -0,0 +1,43 @@ +package com.qft.optical + +import androidx.camera.core.ImageProxy + +/** + * Copies only the Y plane. + * + * QFT deliberately keeps the camera buffer in sensor orientation. QR finder + * patterns are rotation independent, and the optical 2x2 layout is still a 2x2 + * layout after a 90° rotation. Avoiding a second full-frame rotate/copy removes + * almost half of the memory traffic in the scanner hot path on portrait phones. + */ +data class GrayFrame(val width: Int, val height: Int, val luma: ByteArray) { + companion object { + fun from(image: ImageProxy): GrayFrame { + val plane = image.planes[0] + val src = plane.buffer.duplicate() + val rowStride = plane.rowStride + val pixelStride = plane.pixelStride + val w = image.width + val h = image.height + val raw = ByteArray(w * h) + + if (pixelStride == 1 && rowStride == w) { + src.position(0) + src.get(raw, 0, raw.size) + } else if (pixelStride == 1) { + for (y in 0 until h) { + src.position(y * rowStride) + src.get(raw, y * w, w) + } + } else { + for (y in 0 until h) { + val rowStart = y * rowStride + for (x in 0 until w) { + raw[y * w + x] = src.get(rowStart + x * pixelStride) + } + } + } + return GrayFrame(w, h, raw) + } + } +} diff --git a/android/app/src/main/java/com/qft/optical/MainActivity.kt b/android/app/src/main/java/com/qft/optical/MainActivity.kt new file mode 100644 index 0000000..844428a --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/MainActivity.kt @@ -0,0 +1,618 @@ +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.net.Network +import android.os.Build +import android.os.Bundle +import android.util.Size +import android.view.Gravity +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.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 currentAnalyzer: QrAnalyzer? = null + private var scannerStatsText: TextView? = null + private var scannerMode = ScannerMode.NONE + private var pendingScannerMode = ScannerMode.NONE + private val pairConsumed = AtomicBoolean(false) + + 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 + private var connectedNetwork: Network? = null + private var connectedBaseUrl: String? = null + private val selectedFiles = mutableListOf() + 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 val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (granted) startScanner(pendingScannerMode) else showHome("需要相机权限才能扫描 QFT 二维码") + } + + private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + 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 -> + selectedFiles.clear() + var unknown = 0 + for (uri in uris) { + val file = UploadClient.describeFile(contentResolver, uri) + if (file != null) selectedFiles += file else unknown++ + } + renderSelectedFiles() + 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) { + stopCamera() + scannerMode = ScannerMode.NONE + pairConsumed.set(false) + wifiConnector.release() + pendingPair = null + connectedNetwork = null + connectedBaseUrl = null + selectedFiles.clear() + + 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 = "光学零网络 · 4码并行 · 60FPS显示", + body = "手机摄像头连续读取电脑动态二维码。Wi-Fi、蓝牙、局域网和互联网都不参与文件数据传输。", + buttonLabel = "开始光学接收", + ) { requestScanner(ScannerMode.OPTICAL) }) + root.addView(space(16)) + root.addView(modeCard( + title = "手机 → 电脑", + badge = "扫码直连 · 快速发现 · 8路并行", + body = "扫描电脑上的接收二维码,自动请求连接 QFT 临时 Wi-Fi,然后把文件直接上传到电脑指定文件夹。", + buttonLabel = "扫码连接电脑", + ) { requestScanner(ScannerMode.PAIR) }) + root.addView(space(22)) + root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED)) + root.addView(text("QFT v0.3.0-rc3 · Android 7+ 到最新", 12f, MUTED)) + setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) }) + } + + private fun requestScanner(mode: ScannerMode) { + 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) + } + } + + 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 preview = Preview.Builder().build().also { it.surfaceProvider = previewView.surfaceProvider } + val profile = if (mode == ScannerMode.PAIR) QrAnalyzer.Profile.PAIR_FAST else QrAnalyzer.Profile.OPTICAL_MULTI + currentAnalyzer?.close() + val analyzer = QrAnalyzer( + profile = profile, + onTexts = { values -> + when (scannerMode) { + ScannerMode.OPTICAL -> values.forEach(assembler::acceptText) + ScannerMode.PAIR -> values.firstOrNull { PairingProtocol.isPairingText(it) }?.let(::acceptPairCode) + ScannerMode.NONE -> Unit + } + }, + onStats = { cameraFps, decodedFps -> + runOnUiThread { + val quality = when (mode) { + ScannerMode.PAIR -> when { + decodedFps >= 1.0 -> "识别稳定" to SUCCESS + cameraFps >= 18.0 -> "正在锁定二维码" to ACCENT + else -> "相机帧率偏低" to WARNING + } + ScannerMode.OPTICAL -> when { + decodedFps >= cameraFps.coerceAtLeast(1.0) * 1.5 -> "光学链路稳定" to SUCCESS + decodedFps >= 5.0 -> "可接收 · 建议保持手机稳定" to ACCENT + else -> "识别偏低 · 靠近屏幕或降低 Windows FPS" to WARNING + } + ScannerMode.NONE -> "空闲" to MUTED + } + scannerStatsText?.text = "%s · 相机 %.1f FPS · 有效 QR %.1f/s".format(quality.first, cameraFps, decodedFps) + scannerStatsText?.setTextColor(quality.second) + } + }, + ) + currentAnalyzer = analyzer + val targetSize = if (mode == ScannerMode.PAIR) Size(640, 480) else Size(1280, 720) + val analysis = ImageAnalysis.Builder() + .setTargetResolution(targetSize) + .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) + .build() + .also { it.setAnalyzer(cameraExecutor, analyzer) } + provider.unbindAll() + val camera = provider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis) + // Screen QR benefits from an immediate center AF/AE metering pass. + try { + val point = previewView.meteringPointFactory.createPoint(0.5f, 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 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)) + + 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发送设备:等待 QFT1 MANIFEST…" + else "目标:等待 QFTPAIR2 配对二维码", + 14f, Color.WHITE + ) + statusText = text( + if (mode == ScannerMode.OPTICAL) "把电脑动态二维码完整放进取景框" + 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)) + scannerStatsText = text("相机分析:等待首帧…", 12f, ACCENT) + panel.addView(scannerStatsText, matchWrap(top = 6)) + 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, "二维码已识别,正在准备本地连接…") + 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) { + showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…") + wifiConnector.connect( + pairing = pair, + onStatus = { message -> runOnUiThread { updateConnectingStatus(message) } }, + onAvailable = { network -> + connectedNetwork = network + transferExecutor.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 (base == null) { + showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。") + } else { + connectedBaseUrl = base + showSendReady(pair, base) + } + } + } + }, + onUnavailable = { message -> runOnUiThread { 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) { + 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 { requestScanner(ScannerMode.PAIR) } }) + 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 路并发 · 4/8/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, MUTED) + addView(sendFilesText, matchWrap(top = 8)) + addView(button("选择文件(可多选)").apply { + setOnClickListener { pickFiles.launch(arrayOf("*/*")) } + }, matchWrap(top = 12)) + }) + root.addView(space(14)) + root.addView(card().apply { + addView(text("传输进度", 17f, Color.WHITE, true)) + sendStatusText = text("选择文件后点击开始传输", 14f, MUTED) + 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) } + } + 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 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?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null + } + + private fun startUploads(pair: PairingPayload, baseUrl: String) { + if (selectedFiles.isEmpty()) 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, + network = connectedNetwork, + baseUrl = baseUrl, + pairing = pair, + deviceName = receiverDeviceLabel, + file = file, + ) { 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 + currentAnalyzer?.close() + currentAnalyzer = null + scannerStatsText = 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 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() + } +} diff --git a/android/app/src/main/java/com/qft/optical/PairingProtocol.kt b/android/app/src/main/java/com/qft/optical/PairingProtocol.kt new file mode 100644 index 0000000..c31781d --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/PairingProtocol.kt @@ -0,0 +1,158 @@ +package com.qft.optical + +import org.json.JSONObject +import java.net.URI + +data class WifiCredentials( + val ssid: String, + val passphrase: String, + val security: String, +) + +data class PairingPayload( + val version: Int, + val session: String, + val pcName: String, + val transport: String, + val port: Int, + val endpoints: List, + val wifi: WifiCredentials?, +) + +object PairingProtocol { + const val PREFIX_V2 = "QFTPAIR2:" + const val PREFIX_V1 = "QFTPAIR1:" + + fun isPairingText(text: String): Boolean = text.startsWith(PREFIX_V2) || text.startsWith(PREFIX_V1) + + fun parse(text: String): PairingPayload? { + if (text.length > 4096) return null + return when { + text.startsWith(PREFIX_V2) -> parseV2(text.substring(PREFIX_V2.length)) + text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length)) + else -> null + } + } + + private fun parseV2(encoded: String): PairingPayload? { + return try { + val jsonBytes = decodeUrlBase64(encoded) ?: return null + if (jsonBytes.size > 2048) return null + val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8)) + if (obj.optInt("v", 0) != 2) return null + + val session = obj.getString("s") + if (!validSession(session)) return null + val port = obj.getInt("p") + if (port !in 1..65535) return null + + val wifiArray = obj.optJSONArray("w") + val wifi = if (wifiArray != null && wifiArray.length() >= 2) { + val ssid = wifiArray.optString(0) + val passphrase = wifiArray.optString(1) + if (!validWifi(ssid, passphrase)) return null + WifiCredentials(ssid, passphrase, "WPA2") + } else null + + val endpoints = mutableListOf() + obj.optJSONArray("e")?.let { arr -> + for (i in 0 until arr.length()) { + val value = arr.optString(i).trim().removeSuffix("/") + if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value + } + } + // QFT Direct v2 can work with no QR-carried endpoint because UDP discovery + // and the actual Wi-Fi gateway are probed after Android obtains an IP. + if (wifi == null && endpoints.isEmpty()) return null + + PairingPayload( + version = 2, + session = session, + pcName = obj.optString("n", "Windows-PC").take(80), + transport = "http-parallel-v2", + port = port, + endpoints = endpoints, + wifi = wifi, + ) + } catch (_: Exception) { + null + } + } + + private fun parseV1(encoded: String): PairingPayload? { + return try { + val jsonBytes = decodeUrlBase64(encoded) ?: return null + if (jsonBytes.size > 3072) return null + val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8)) + if (obj.optInt("v", 0) != 1) return null + + val session = obj.getString("session") + if (!validSession(session)) return null + val transport = obj.optString("transport", "") + if (transport != "http-stream-v1") return null + val port = obj.getInt("port") + if (port !in 1..65535) return null + + val endpoints = mutableListOf() + val endpointsJson = obj.getJSONArray("endpoints") + for (i in 0 until endpointsJson.length()) { + val value = endpointsJson.optString(i).trim().removeSuffix("/") + if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value + } + if (endpoints.isEmpty()) return null + + val wifiObj = obj.optJSONObject("wifi") + val wifi = wifiObj?.let { + val ssid = it.getString("ssid") + val passphrase = it.getString("passphrase") + val security = it.optString("security", "WPA2") + if (!validWifi(ssid, passphrase) || security != "WPA2") return null + WifiCredentials(ssid, passphrase, security) + } + + PairingPayload( + version = 1, + session = session, + pcName = obj.optString("pc_name", "Windows-PC").take(80), + transport = transport, + port = port, + endpoints = endpoints, + wifi = wifi, + ) + } catch (_: Exception) { + null + } + } + + private fun decodeUrlBase64(encoded: String): ByteArray? = Base64Url.decode(encoded) + + private fun validSession(session: String): Boolean = session.matches(Regex("^[A-Za-z0-9_-]{20,64}$")) + + private fun validWifi(ssid: String, passphrase: String): Boolean { + return ssid.isNotBlank() && ssid.toByteArray(Charsets.UTF_8).size <= 32 && passphrase.length in 8..63 + } + + /** + * Pairing QR is treated as untrusted input. QFT only probes literal local + * IPv4 addresses on the exact advertised port; public hosts and DNS names + * are rejected even though the app permits cleartext HTTP for local QFT. + */ + fun isAllowedLocalHttpEndpoint(value: String, expectedPort: Int): Boolean { + val uri = try { URI(value) } catch (_: Exception) { return false } + if (uri.scheme != "http" || uri.userInfo != null || uri.query != null || uri.fragment != null) return false + if (uri.port != expectedPort) return false + val host = uri.host ?: return false + val octets = host.split('.').map { it.toIntOrNull() ?: return false } + if (octets.size != 4 || octets.any { it !in 0..255 }) return false + val a = octets[0] + val b = octets[1] + return when { + a == 10 -> true + a == 127 -> true + a == 169 && b == 254 -> true + a == 172 && b in 16..31 -> true + a == 192 && b == 168 -> true + else -> false + } + } +} diff --git a/android/app/src/main/java/com/qft/optical/Protocol.kt b/android/app/src/main/java/com/qft/optical/Protocol.kt new file mode 100644 index 0000000..8370f92 --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/Protocol.kt @@ -0,0 +1,108 @@ +package com.qft.optical + +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.zip.CRC32 + +enum class FrameKind(val wire: Int) { + MANIFEST(1), DATA(2), END(3); + + companion object { + fun fromWire(v: Int): FrameKind = entries.firstOrNull { it.wire == v } + ?: error("unknown frame kind: $v") + } +} + +data class QftFrame( + val kind: FrameKind, + val sessionId: Long, + val seq: Long, + val totalChunks: Long, + val payload: ByteArray, +) + +data class Manifest( + val sessionId: Long, + val senderDevice: String, + val fileName: String, + val fileSize: Long, + val chunkSize: Int, + val totalChunks: Long, + val sha256: ByteArray, +) + +object QftProtocol { + const val PREFIX = "QFT1:" + private const val VERSION = 1 + + fun parseText(text: String): QftFrame? { + if (!text.startsWith(PREFIX)) return null + val binary = try { + Base64Url.decode(text.substring(PREFIX.length)) ?: return null + } catch (_: IllegalArgumentException) { + return null + } + if (binary.size < 28) return null + + val bodySize = binary.size - 4 + val expectedCrc = ByteBuffer.wrap(binary, bodySize, 4) + .order(ByteOrder.BIG_ENDIAN) + .int.toLong() and 0xffff_ffffL + val crc = CRC32().apply { update(binary, 0, bodySize) }.value + if (crc != expectedCrc) return null + + val bb = ByteBuffer.wrap(binary, 0, bodySize).order(ByteOrder.BIG_ENDIAN) + val magic = ByteArray(4).also(bb::get) + if (!magic.contentEquals(byteArrayOf('Q'.code.toByte(), 'F'.code.toByte(), 'T'.code.toByte(), '1'.code.toByte()))) { + return null + } + val version = bb.get().toInt() and 0xff + if (version != VERSION) return null + val kind = try { FrameKind.fromWire(bb.get().toInt() and 0xff) } catch (_: Exception) { return null } + val sessionId = bb.long + val seq = bb.int.toLong() and 0xffff_ffffL + val totalChunks = bb.int.toLong() and 0xffff_ffffL + val payloadLen = bb.short.toInt() and 0xffff + if (payloadLen != bb.remaining()) return null + val payload = ByteArray(payloadLen).also(bb::get) + return QftFrame(kind, sessionId, seq, totalChunks, payload) + } + + fun parseManifest(frame: QftFrame): Manifest? { + if (frame.kind != FrameKind.MANIFEST || frame.payload.size < 44) return null + val bb = ByteBuffer.wrap(frame.payload).order(ByteOrder.BIG_ENDIAN) + val fileSize = bb.long + val chunkSize = bb.short.toInt() and 0xffff + val sha = ByteArray(32).also(bb::get) + val nameLen = bb.short.toInt() and 0xffff + if (nameLen > bb.remaining()) return null + val nameBytes = ByteArray(nameLen).also(bb::get) + val name = nameBytes.toString(Charsets.UTF_8) + .replace(Regex("[\\/:*?\"<>|]"), "_") + .ifBlank { "qft.bin" } + + val senderDevice = if (bb.remaining() >= 2) { + val deviceLen = bb.short.toInt() and 0xffff + if (deviceLen > bb.remaining()) return null + ByteArray(deviceLen).also(bb::get) + .toString(Charsets.UTF_8) + .replace(Regex("[\u0000-\u001F\u007F]"), "") + .trim() + .ifBlank { "Windows-PC" } + } else { + // Backward compatibility with v0.1/v0.1.2 manifests. + "Windows-PC" + } + + if (chunkSize <= 0) return null + return Manifest( + sessionId = frame.sessionId, + senderDevice = senderDevice, + fileName = name, + fileSize = fileSize, + chunkSize = chunkSize, + totalChunks = frame.totalChunks, + sha256 = sha, + ) + } +} diff --git a/android/app/src/main/java/com/qft/optical/QrAnalyzer.kt b/android/app/src/main/java/com/qft/optical/QrAnalyzer.kt new file mode 100644 index 0000000..53ab4bd --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/QrAnalyzer.kt @@ -0,0 +1,162 @@ +package com.qft.optical + +import androidx.camera.core.ImageAnalysis +import androidx.camera.core.ImageProxy +import com.google.zxing.BarcodeFormat +import com.google.zxing.BinaryBitmap +import com.google.zxing.DecodeHintType +import com.google.zxing.MultiFormatReader +import com.google.zxing.PlanarYUVLuminanceSource +import com.google.zxing.common.GlobalHistogramBinarizer +import com.google.zxing.common.HybridBinarizer +import java.util.concurrent.Callable +import java.util.concurrent.Executors + +class QrAnalyzer( + private val profile: Profile, + private val onTexts: (List) -> Unit, + private val onStats: (cameraFramesPerSecond: Double, decodedPerSecond: Double) -> Unit = { _, _ -> }, +) : ImageAnalysis.Analyzer { + enum class Profile { PAIR_FAST, OPTICAL_MULTI } + + private val readers = Array(5) { newReader() } + private val decodePool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors().coerceIn(2, 4)) + private var frameCounter = 0L + private var decodedCounter = 0L + private var windowStarted = android.os.SystemClock.elapsedRealtime() + + override fun analyze(image: ImageProxy) { + try { + val gray = GrayFrame.from(image) + frameCounter++ + val results = when (profile) { + Profile.PAIR_FAST -> decodePair(gray) + Profile.OPTICAL_MULTI -> decodeOptical(gray) + }.distinct() + if (results.isNotEmpty()) { + decodedCounter += results.size + onTexts(results) + } + reportStatsIfNeeded() + } finally { + image.close() + } + } + + private fun decodePair(gray: GrayFrame): List { + // QFTPAIR2 is intentionally compact. Try a cheap centered GlobalHistogram + // pass first, then the full frame every time so off-axis scans do not wait + // several frames. HybridBinarizer is reserved for every third miss. + val marginX = (gray.width * 0.08).toInt() + val marginY = (gray.height * 0.08).toInt() + decodeRegion( + gray, marginX, marginY, gray.width - marginX * 2, gray.height - marginY * 2, + readers[0], hybridFallback = false, + )?.let { return listOf(it) } + decodeRegion(gray, 0, 0, gray.width, gray.height, readers[0], hybridFallback = false) + ?.let { return listOf(it) } + if (frameCounter % 3L == 0L) { + decodeRegion(gray, 0, 0, gray.width, gray.height, readers[0], hybridFallback = true) + ?.let { return listOf(it) } + } + return emptyList() + } + + private fun decodeOptical(gray: GrayFrame): List { + // v0.3 Windows can present a 2x2 grid. Decode quadrants concurrently. + // 8% overlap tolerates perspective/centering error around the middle. + val overlapX = (gray.width * 0.08).toInt() + val overlapY = (gray.height * 0.08).toInt() + val halfW = gray.width / 2 + val halfH = gray.height / 2 + val regions = arrayOf( + intArrayOf(0, 0, (halfW + overlapX).coerceAtMost(gray.width), (halfH + overlapY).coerceAtMost(gray.height)), + intArrayOf((halfW - overlapX).coerceAtLeast(0), 0, gray.width - (halfW - overlapX).coerceAtLeast(0), (halfH + overlapY).coerceAtMost(gray.height)), + intArrayOf(0, (halfH - overlapY).coerceAtLeast(0), (halfW + overlapX).coerceAtMost(gray.width), gray.height - (halfH - overlapY).coerceAtLeast(0)), + intArrayOf((halfW - overlapX).coerceAtLeast(0), (halfH - overlapY).coerceAtLeast(0), gray.width - (halfW - overlapX).coerceAtLeast(0), gray.height - (halfH - overlapY).coerceAtLeast(0)), + ) + val tasks = regions.mapIndexed { index, r -> + Callable { + decodeRegion(gray, r[0], r[1], r[2], r[3], readers[index], hybridFallback = false) + } + } + val found = try { + decodePool.invokeAll(tasks).mapNotNull { future -> + try { future.get() } catch (_: Exception) { null } + } + } catch (_: Exception) { + emptyList() + } + if (found.isNotEmpty()) return found + + // Backward-compatible single-QR fallback. Limit the expensive hybrid + // pass to every third frame so low-end Android 7 devices stay responsive. + return if (frameCounter % 3L == 0L) { + decodeRegion(gray, 0, 0, gray.width, gray.height, readers[4], hybridFallback = true) + ?.let(::listOf) ?: emptyList() + } else emptyList() + } + + private fun decodeRegion( + gray: GrayFrame, + left: Int, + top: Int, + width: Int, + height: Int, + reader: MultiFormatReader, + hybridFallback: Boolean, + ): String? { + if (width < 80 || height < 80) return null + val source = try { + PlanarYUVLuminanceSource( + gray.luma, gray.width, gray.height, + left.coerceAtLeast(0), top.coerceAtLeast(0), + width.coerceAtMost(gray.width - left.coerceAtLeast(0)), + height.coerceAtMost(gray.height - top.coerceAtLeast(0)), + false, + ) + } catch (_: Exception) { return null } + + try { + return reader.decodeWithState(BinaryBitmap(GlobalHistogramBinarizer(source)))?.text + } catch (_: Exception) { + if (!hybridFallback) return null + } finally { + reader.reset() + } + return try { + reader.decodeWithState(BinaryBitmap(HybridBinarizer(source)))?.text + } catch (_: Exception) { + null + } finally { + reader.reset() + } + } + + private fun reportStatsIfNeeded() { + val now = android.os.SystemClock.elapsedRealtime() + val elapsed = now - windowStarted + if (elapsed < 1000L) return + val seconds = elapsed / 1000.0 + onStats(frameCounter / seconds, decodedCounter / seconds) + frameCounter = 0 + decodedCounter = 0 + windowStarted = now + } + + fun close() { + decodePool.shutdownNow() + } + + companion object { + private fun newReader() = MultiFormatReader().apply { + setHints( + mapOf( + DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE), + DecodeHintType.TRY_HARDER to false, + DecodeHintType.CHARACTER_SET to "UTF-8", + ) + ) + } + } +} diff --git a/android/app/src/main/java/com/qft/optical/SessionAssembler.kt b/android/app/src/main/java/com/qft/optical/SessionAssembler.kt new file mode 100644 index 0000000..df479a8 --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/SessionAssembler.kt @@ -0,0 +1,192 @@ +package com.qft.optical + +import android.content.ContentValues +import android.content.Context +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import java.io.File +import java.io.FileInputStream +import java.io.RandomAccessFile +import java.security.MessageDigest + +sealed interface ReceiveEvent { + data class Started(val manifest: Manifest) : ReceiveEvent + data class Progress(val manifest: Manifest, val received: Int, val total: Int) : ReceiveEvent + data class Completed(val manifest: Manifest, val savedName: String) : ReceiveEvent + data class Error(val message: String) : ReceiveEvent +} + +class SessionAssembler( + private val context: Context, + private val onEvent: (ReceiveEvent) -> Unit, +) { + private var manifest: Manifest? = null + private var received: BooleanArray? = null + private var receivedCount = 0 + private var tempFile: File? = null + private var raf: RandomAccessFile? = null + private var completedSession: Long? = null + + @Synchronized + fun acceptText(text: String) { + val frame = QftProtocol.parseText(text) ?: return + if (completedSession == frame.sessionId) return + + when (frame.kind) { + FrameKind.MANIFEST -> acceptManifest(frame) + FrameKind.DATA -> acceptData(frame) + FrameKind.END -> Unit + } + } + + private fun acceptManifest(frame: QftFrame) { + val incoming = QftProtocol.parseManifest(frame) ?: return + val current = manifest + if (current?.sessionId == incoming.sessionId) return + reset() + + if (incoming.totalChunks > Int.MAX_VALUE) { + onEvent(ReceiveEvent.Error("文件分片数过大")) + return + } + manifest = incoming + received = BooleanArray(incoming.totalChunks.toInt()) + tempFile = File(context.cacheDir, "qft-${incoming.sessionId}.part") + raf = RandomAccessFile(tempFile!!, "rw").apply { setLength(incoming.fileSize) } + onEvent(ReceiveEvent.Started(incoming)) + if (incoming.totalChunks == 0L) finalizeIfComplete() + } + + private fun acceptData(frame: QftFrame) { + val m = manifest ?: return + if (frame.sessionId != m.sessionId) return + if (frame.totalChunks != m.totalChunks) return + if (frame.seq >= m.totalChunks) return + if (frame.payload.size > m.chunkSize) return + + val expectedOffset = frame.seq * m.chunkSize.toLong() + val remaining = m.fileSize - expectedOffset + if (remaining < 0) return + val expectedLen = minOf(m.chunkSize.toLong(), remaining).toInt() + if (frame.payload.size != expectedLen) return + + val flags = received ?: return + val index = frame.seq.toInt() + if (flags[index]) return + + raf?.seek(expectedOffset) + raf?.write(frame.payload) + flags[index] = true + receivedCount++ + onEvent(ReceiveEvent.Progress(m, receivedCount, flags.size)) + finalizeIfComplete() + } + + private fun finalizeIfComplete() { + val m = manifest ?: return + val flags = received ?: return + if (receivedCount != flags.size) return + + raf?.fd?.sync() + raf?.close() + raf = null + val file = tempFile ?: return + val actual = sha256(file) + if (!actual.contentEquals(m.sha256)) { + onEvent(ReceiveEvent.Error("SHA-256 校验失败,等待下一会话重新发送")) + reset() + return + } + + try { + saveToDownloads(file, m.fileName) + completedSession = m.sessionId + onEvent(ReceiveEvent.Completed(m, m.fileName)) + reset(keepCompleted = true) + } catch (e: Exception) { + onEvent(ReceiveEvent.Error("保存失败:${e.message}")) + } + } + + private fun sha256(file: File): ByteArray { + val digest = MessageDigest.getInstance("SHA-256") + FileInputStream(file).use { input -> + val buf = ByteArray(1024 * 1024) + while (true) { + val n = input.read(buf) + if (n <= 0) break + digest.update(buf, 0, n) + } + } + return digest.digest() + } + + private fun saveToDownloads(source: File, name: String) { + if (Build.VERSION.SDK_INT >= 29) { + saveModern(source, name) + } else { + saveLegacy(source, name) + } + } + + @android.annotation.TargetApi(29) + private fun saveModern(source: File, name: String) { + val values = ContentValues().apply { + put(MediaStore.Downloads.DISPLAY_NAME, name) + put(MediaStore.Downloads.MIME_TYPE, "application/octet-stream") + put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/QFT") + put(MediaStore.Downloads.IS_PENDING, 1) + } + val resolver = context.contentResolver + val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) + ?: error("MediaStore insert failed") + try { + resolver.openOutputStream(uri, "w")!!.use { out -> + source.inputStream().use { input -> input.copyTo(out, 1024 * 1024) } + } + values.clear() + values.put(MediaStore.Downloads.IS_PENDING, 0) + resolver.update(uri, values, null, null) + } catch (e: Exception) { + resolver.delete(uri, null, null) + throw e + } + } + + @Suppress("DEPRECATION") + private fun saveLegacy(source: File, name: String) { + val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "QFT") + if (!dir.exists() && !dir.mkdirs()) error("无法创建 Downloads/QFT") + val target = uniqueLegacyFile(dir, name) + source.inputStream().use { input -> + target.outputStream().use { output -> input.copyTo(output, 1024 * 1024) } + } + } + + private fun uniqueLegacyFile(dir: File, original: String): File { + var candidate = File(dir, original) + if (!candidate.exists()) return candidate + val dot = original.lastIndexOf('.') + val stem = if (dot > 0) original.substring(0, dot) else original + val ext = if (dot > 0) original.substring(dot) else "" + var n = 1 + while (candidate.exists()) { + candidate = File(dir, "$stem ($n)$ext") + n++ + } + return candidate + } + + @Synchronized + fun reset(keepCompleted: Boolean = false) { + try { raf?.close() } catch (_: Exception) {} + raf = null + tempFile?.delete() + tempFile = null + manifest = null + received = null + receivedCount = 0 + if (!keepCompleted) completedSession = null + } +} diff --git a/android/app/src/main/java/com/qft/optical/UploadClient.kt b/android/app/src/main/java/com/qft/optical/UploadClient.kt new file mode 100644 index 0000000..d8a632c --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/UploadClient.kt @@ -0,0 +1,473 @@ +package com.qft.optical + +import android.content.ContentResolver +import android.database.Cursor +import android.net.Network +import android.net.Uri +import android.provider.OpenableColumns +import org.json.JSONObject +import java.io.FileInputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.HttpURLConnection +import java.net.InetAddress +import java.net.URL +import java.nio.ByteBuffer +import java.nio.channels.FileChannel +import java.util.concurrent.ExecutorCompletionService +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong + + +data class SelectedFile( + val uri: Uri, + val name: String, + val size: Long, +) + +object UploadClient { + 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 + + fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? { + var name = "qft-upload.bin" + var size = -1L + var cursor: Cursor? = null + try { + cursor = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null) + if (cursor?.moveToFirst() == true) { + val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) + if (nameIndex >= 0) name = cursor.getString(nameIndex) ?: name + if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) size = cursor.getLong(sizeIndex) + } + } finally { + cursor?.close() + } + if (size < 0) { + size = try { resolver.openAssetFileDescriptor(uri, "r")?.use { it.length } ?: -1L } catch (_: Exception) { -1L } + } + if (size < 0) return null + return SelectedFile(uri, name, size) + } + + /** Fast path: ask the PC directly over UDP on the newly connected QFT Wi-Fi. */ + fun discoverUdp( + network: Network?, + pairing: PairingPayload, + hosts: List, + ): String? { + if (hosts.isEmpty()) return null + val socket = DatagramSocket() + return try { + network?.bindSocket(socket) + socket.broadcast = true + socket.soTimeout = 220 + val request = "QFTDISC2:${pairing.session}".toByteArray(Charsets.US_ASCII) + repeat(3) { + for (host in hosts) { + try { socket.send(DatagramPacket(request, request.size, host, DISCOVERY_PORT)) } catch (_: Exception) {} + } + val deadline = android.os.SystemClock.elapsedRealtime() + 320 + while (android.os.SystemClock.elapsedRealtime() < deadline) { + val buf = ByteArray(512) + val packet = DatagramPacket(buf, buf.size) + try { + socket.receive(packet) + } catch (_: Exception) { + break + } + val text = String(packet.data, packet.offset, packet.length, Charsets.US_ASCII) + val prefix = "QFTHERE2:${pairing.session}:" + if (!text.startsWith(prefix)) continue + val port = text.substring(prefix.length).toIntOrNull() ?: continue + if (port != pairing.port) continue + val base = "http://${packet.address.hostAddress}:$port" + if (PairingProtocol.isAllowedLocalHttpEndpoint(base, pairing.port)) return base + } + } + null + } catch (_: Exception) { + null + } finally { + socket.close() + } + } + + fun probeRobust( + network: Network?, + pairing: PairingPayload, + deviceName: String, + preferredEndpoints: List = emptyList(), + discoveredEndpoint: String? = null, + subnetEndpoints: List = emptyList(), + ): String? { + val common = listOf( + "http://192.168.137.1:${pairing.port}", + "http://192.168.49.1:${pairing.port}", + ) + val fast = (listOfNotNull(discoveredEndpoint) + preferredEndpoints + pairing.endpoints + common) + .map { it.trim().removeSuffix("/") } + .filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) } + .distinct() + + // Stage 1: expected gateway/QR addresses. Repeat quickly because a Wi-Fi + // callback can precede ARP/firewall classification by a few hundred ms. + val fastDeadline = android.os.SystemClock.elapsedRealtime() + 2_400 + while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) { + probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 320, readMs = 380) + ?.let { return it } + try { Thread.sleep(90) } catch (_: InterruptedException) { return null } + } + + // Stage 2: actual connected subnet fallback. This specifically fixes the + // case where Windows Wi-Fi Direct is up but uses an unexpected gateway + // address. Up to /24 is scanned concurrently and still session-authenticated. + val scan = subnetEndpoints + .map { it.trim().removeSuffix("/") } + .filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) } + .filterNot { it in fast } + .distinct() + if (scan.isNotEmpty()) { + probeCandidatesParallel(network, pairing, deviceName, scan, workers = 24, connectMs = 240, readMs = 300) + ?.let { return it } + } + + // Final short retry for the expected addresses after the subnet scan. + val deadline = android.os.SystemClock.elapsedRealtime() + 2_000 + while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) { + probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 450, readMs = 500) + ?.let { return it } + try { Thread.sleep(120) } catch (_: InterruptedException) { return null } + } + return null + } + + private fun probeCandidatesParallel( + network: Network?, + pairing: PairingPayload, + deviceName: String, + candidates: List, + workers: Int, + connectMs: Int, + readMs: Int, + ): String? { + if (candidates.isEmpty()) return null + val pool = Executors.newFixedThreadPool(candidates.size.coerceAtMost(workers).coerceAtLeast(1)) + val completion = ExecutorCompletionService(pool) + candidates.forEach { base -> + completion.submit(java.util.concurrent.Callable { + if (probeOne(network, pairing, deviceName, base, connectMs, readMs)) base else null + }) + } + return try { + val overallMs = (connectMs + readMs + 150).toLong() * + ((candidates.size + workers - 1) / workers).coerceAtLeast(1) + val deadline = android.os.SystemClock.elapsedRealtime() + overallMs.coerceAtMost(4_500L) + repeat(candidates.size) { + val remaining = deadline - android.os.SystemClock.elapsedRealtime() + if (remaining <= 0) return null + val future = completion.poll(remaining.coerceAtMost(350L), TimeUnit.MILLISECONDS) ?: return@repeat + val result = future.get() + if (result != null) return result + } + null + } catch (_: Exception) { + null + } finally { + pool.shutdownNow() + } + } + + private fun probeOne( + network: Network?, pairing: PairingPayload, deviceName: String, base: String, + connectMs: Int, readMs: Int, + ): Boolean { + var conn: HttpURLConnection? = null + return try { + conn = open(network, URL("$base/qft/ping")) + conn.requestMethod = "GET" + conn.connectTimeout = connectMs + conn.readTimeout = readMs + conn.useCaches = false + conn.setRequestProperty("X-QFT-Token", pairing.session) + conn.setRequestProperty("X-QFT-Device", b64(deviceName)) + conn.responseCode == 200 + } catch (_: Exception) { + false + } finally { + conn?.disconnect() + } + } + + fun upload( + resolver: ContentResolver, + network: Network?, + baseUrl: String, + pairing: PairingPayload, + deviceName: String, + file: SelectedFile, + onProgress: (sent: Long, total: Long) -> Unit, + ) { + if (pairing.version >= 2 && isSeekable(resolver, file)) { + try { + uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress) + return + } catch (e: Exception) { + // If the provider cannot sustain random access or the v2 endpoint + // is unavailable, preserve compatibility with the v1 stream path. + if (e is SecurityException) throw e + } + } + uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress) + } + + private data class InitReply(val uploadId: String, val chunkSize: Long, val totalChunks: Int) + + private fun uploadParallel( + resolver: ContentResolver, + network: Network?, + baseUrl: String, + pairing: PairingPayload, + deviceName: String, + file: SelectedFile, + onProgress: (sent: Long, total: Long) -> Unit, + ) { + val init = initUpload(network, baseUrl, pairing, deviceName, file) + if (init.totalChunks == 0) { + finishUpload(network, baseUrl, pairing, deviceName, init.uploadId) + onProgress(0, 0) + return + } + + val cpuWorkers = Runtime.getRuntime().availableProcessors().coerceIn(2, MAX_WORKERS) + val workerCount = init.totalChunks.coerceAtMost(cpuWorkers).coerceAtLeast(1) + val pool = Executors.newFixedThreadPool(workerCount) + val next = AtomicInteger(0) + val sent = AtomicLong(0) + val lastReport = AtomicLong(0) + val failures = mutableListOf() + val futures = (0 until workerCount).map { + pool.submit { + resolver.openFileDescriptor(file.uri, "r")?.use { pfd -> + FileInputStream(pfd.fileDescriptor).use { input -> + val channel = input.channel + val buffer = ByteBuffer.allocate(STREAM_BUFFER) + while (!Thread.currentThread().isInterrupted) { + val index = next.getAndIncrement() + if (index >= init.totalChunks) break + val offset = index.toLong() * init.chunkSize + val length = minOf(init.chunkSize, file.size - offset) + sendChunk( + network, baseUrl, pairing, deviceName, + init.uploadId, index, channel, offset, length, buffer, + ) + val totalSent = sent.addAndGet(length) + val now = android.os.SystemClock.elapsedRealtime() + val previous = lastReport.get() + if (now - previous >= 80 && lastReport.compareAndSet(previous, now)) { + onProgress(totalSent.coerceAtMost(file.size), file.size) + } + } + } + } ?: error("无法打开 ${file.name}") + } + } + try { + futures.forEach { future -> + try { future.get() } catch (e: Exception) { failures += (e.cause ?: e) } + } + } finally { + pool.shutdownNow() + } + if (failures.isNotEmpty()) throw failures.first() + finishUpload(network, baseUrl, pairing, deviceName, init.uploadId) + onProgress(file.size, file.size) + } + + + private fun desiredChunkSize(fileSize: Long): Long = when { + fileSize < 32L * 1024L * 1024L -> CHUNK_SMALL + fileSize >= 512L * 1024L * 1024L -> CHUNK_LARGE + else -> CHUNK_DEFAULT + } + + private fun initUpload( + network: Network?, baseUrl: String, pairing: PairingPayload, + deviceName: String, file: SelectedFile, + ): InitReply { + val conn = open(network, URL("$baseUrl/qft/upload/init")) + try { + conn.requestMethod = "POST" + conn.doOutput = true + conn.connectTimeout = 3_000 + conn.readTimeout = 6_000 + conn.setFixedLengthStreamingMode(0) + commonHeaders(conn, pairing, deviceName) + conn.setRequestProperty("X-QFT-Filename", b64(file.name)) + conn.setRequestProperty("X-QFT-Size", file.size.toString()) + conn.setRequestProperty("X-QFT-Chunk-Size", desiredChunkSize(file.size).toString()) + conn.outputStream.close() + val code = conn.responseCode + if (code != 200) error("初始化并行上传失败 HTTP $code") + val body = conn.inputStream.bufferedReader().use { it.readText() } + val obj = JSONObject(body) + return InitReply( + uploadId = obj.getString("upload_id"), + chunkSize = obj.getLong("chunk_size"), + totalChunks = obj.getInt("total_chunks"), + ) + } finally { + conn.disconnect() + } + } + + private fun sendChunk( + network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String, + uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long, + buffer: ByteBuffer, + ) { + val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index")) + try { + conn.requestMethod = "POST" + conn.doOutput = true + conn.connectTimeout = 4_000 + conn.readTimeout = 15_000 + conn.setFixedLengthStreamingMode(length) + conn.setRequestProperty("Content-Type", "application/octet-stream") + commonHeaders(conn, pairing, deviceName) + channel.position(offset) + conn.outputStream.use { output -> + var remaining = length + val array = buffer.array() + while (remaining > 0) { + buffer.clear() + buffer.limit(minOf(array.size.toLong(), remaining).toInt()) + val n = channel.read(buffer) + if (n <= 0) error("读取文件分块提前结束") + output.write(array, 0, n) + remaining -= n.toLong() + } + output.flush() + } + val code = conn.responseCode + if (code != 200) { + val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null } + error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}") + } + try { conn.inputStream.close() } catch (_: Exception) {} + } finally { + conn.disconnect() + } + } + + private fun finishUpload( + network: Network?, baseUrl: String, pairing: PairingPayload, + deviceName: String, uploadId: String, + ) { + val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId")) + try { + conn.requestMethod = "POST" + conn.doOutput = true + conn.connectTimeout = 4_000 + conn.readTimeout = 120_000 + conn.setFixedLengthStreamingMode(0) + commonHeaders(conn, pairing, deviceName) + conn.outputStream.close() + val code = conn.responseCode + if (code != 200) { + val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null } + error("完成上传失败 HTTP $code${message?.let { ": $it" } ?: ""}") + } + conn.inputStream.close() + } finally { + conn.disconnect() + } + } + + private fun uploadLegacy( + resolver: ContentResolver, + network: Network?, + baseUrl: String, + pairing: PairingPayload, + deviceName: String, + file: SelectedFile, + onProgress: (sent: Long, total: Long) -> Unit, + ) { + val conn = open(network, URL("$baseUrl/qft/upload")) + conn.requestMethod = "POST" + conn.doOutput = true + conn.connectTimeout = 8_000 + conn.readTimeout = 30_000 + conn.setFixedLengthStreamingMode(file.size) + conn.setRequestProperty("Content-Type", "application/octet-stream") + commonHeaders(conn, pairing, deviceName) + conn.setRequestProperty("X-QFT-Filename", b64(file.name)) + conn.setRequestProperty("X-QFT-Size", file.size.toString()) + + resolver.openInputStream(file.uri).use { input -> + requireNotNull(input) { "无法打开 ${file.name}" } + conn.outputStream.use { output -> + val buf = ByteArray(STREAM_BUFFER) + var sent = 0L + var lastReport = 0L + while (true) { + val n = input.read(buf) + if (n <= 0) break + output.write(buf, 0, n) + sent += n + val now = android.os.SystemClock.elapsedRealtime() + if (now - lastReport >= 100 || sent == file.size) { + onProgress(sent, file.size) + lastReport = now + } + } + output.flush() + } + } + + val code = conn.responseCode + if (code != 200) { + val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null } + conn.disconnect() + error("电脑返回 HTTP $code${message?.let { ": $it" } ?: ""}") + } + conn.inputStream.close() + conn.disconnect() + } + + private fun isSeekable(resolver: ContentResolver, file: SelectedFile): Boolean { + if (file.size <= 0) return true + return try { + resolver.openFileDescriptor(file.uri, "r")?.use { pfd -> + FileInputStream(pfd.fileDescriptor).use { input -> + val channel = input.channel + val target = minOf(file.size - 1, 4096L).coerceAtLeast(0) + channel.position(target) + channel.position() == target + } + } ?: false + } catch (_: Exception) { + false + } + } + + private fun commonHeaders(conn: HttpURLConnection, pairing: PairingPayload, deviceName: String) { + conn.useCaches = false + conn.setRequestProperty("Connection", "close") + conn.setRequestProperty("X-QFT-Token", pairing.session) + conn.setRequestProperty("X-QFT-Device", b64(deviceName)) + } + + private fun open(network: Network?, url: URL): HttpURLConnection { + return (network?.openConnection(url) ?: url.openConnection()) as HttpURLConnection + } + + private fun b64(value: String): String = Base64Url.encode(value.toByteArray(Charsets.UTF_8)) +} diff --git a/android/app/src/main/java/com/qft/optical/WifiConnector.kt b/android/app/src/main/java/com/qft/optical/WifiConnector.kt new file mode 100644 index 0000000..bc22930 --- /dev/null +++ b/android/app/src/main/java/com/qft/optical/WifiConnector.kt @@ -0,0 +1,310 @@ +package com.qft.optical + +import android.content.Context +import android.net.ConnectivityManager +import android.net.LinkProperties +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.net.wifi.WifiConfiguration +import android.net.wifi.WifiManager +import android.net.wifi.WifiNetworkSpecifier +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import java.net.Inet4Address +import java.net.InetAddress + +class WifiConnector(context: Context) { + private val appContext = context.applicationContext + private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager + private val handler = Handler(Looper.getMainLooper()) + private var callback: ConnectivityManager.NetworkCallback? = null + private var generation = 0 + private var legacyPreviousNetworkId: Int? = null + private var legacyTargetNetworkId: Int? = null + + fun connect( + pairing: PairingPayload, + onStatus: (String) -> Unit, + onAvailable: (Network?) -> Unit, + onUnavailable: (String) -> Unit, + ) { + release(restoreLegacy = false) + generation++ + val run = generation + val wifi = pairing.wifi + if (wifi == null) { + onStatus("正在使用当前局域网发现电脑…") + val wifiNetwork = bestWifiNetwork() + onAvailable(wifiNetwork ?: connectivity.activeNetwork) + return + } + + if (Build.VERSION.SDK_INT >= 29) { + connectModern(run, wifi, onStatus, onAvailable, onUnavailable) + } else { + connectLegacy(run, wifi, onStatus, onAvailable, onUnavailable) + } + } + + private fun connectModern( + run: Int, + wifi: WifiCredentials, + onStatus: (String) -> Unit, + onAvailable: (Network?) -> Unit, + onUnavailable: (String) -> Unit, + ) { + onStatus("正在请求连接 ${wifi.ssid}…") + val specifier = try { + WifiNetworkSpecifier.Builder() + .setSsid(wifi.ssid) + .setWpa2Passphrase(wifi.passphrase) + .build() + } catch (e: Exception) { + onUnavailable("配网参数无效:${e.message}") + return + } + val request = NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .setNetworkSpecifier(specifier) + .build() + + val delivered = booleanArrayOf(false) + val cb = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + if (run != generation) return + onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…") + waitUntilUsable(run, network, onStatus) { + if (!delivered[0] && run == generation) { + delivered[0] = true + onStatus("QFT 本地网络已就绪,正在快速发现电脑…") + onAvailable(network) + } + } + } + + override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) { + if (run != generation || delivered[0]) return + if (hasIpv4(linkProperties)) { + delivered[0] = true + onStatus("QFT 本地网络已就绪,正在快速发现电脑…") + onAvailable(network) + } + } + + override fun onUnavailable() { + if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。") + } + + override fun onLost(network: Network) { + if (run == generation && delivered[0]) onUnavailable("QFT 临时网络已断开") + } + } + callback = cb + try { + connectivity.requestNetwork(request, cb, 15_000) + handler.postDelayed({ + if (run == generation && !delivered[0]) { + onStatus("仍在等待系统完成配网…") + } + }, 8_000) + } catch (e: Exception) { + callback = null + onUnavailable("系统配网请求失败:${e.message}") + } + } + + @Suppress("DEPRECATION") + private fun connectLegacy( + run: Int, + wifi: WifiCredentials, + onStatus: (String) -> Unit, + onAvailable: (Network?) -> Unit, + onUnavailable: (String) -> Unit, + ) { + onStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…") + try { + if (!wifiManager.isWifiEnabled) { + wifiManager.isWifiEnabled = true + } + legacyPreviousNetworkId = wifiManager.connectionInfo?.networkId?.takeIf { it >= 0 } + val quoted = "\"${wifi.ssid}\"" + val existing = try { wifiManager.configuredNetworks?.firstOrNull { it.SSID == quoted } } catch (_: Exception) { null } + val targetId = if (existing != null) { + existing.networkId + } else { + val config = WifiConfiguration().apply { + SSID = quoted + preSharedKey = "\"${wifi.passphrase}\"" + allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK) + } + wifiManager.addNetwork(config) + } + if (targetId < 0) { + onUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。") + return + } + legacyTargetNetworkId = targetId + wifiManager.disconnect() + if (!wifiManager.enableNetwork(targetId, true)) { + onUnavailable("系统拒绝启用 QFT Wi-Fi 网络") + return + } + wifiManager.reconnect() + val started = SystemClock.elapsedRealtime() + fun poll() { + if (run != generation) return + val info = wifiManager.connectionInfo + val matches = info != null && (info.networkId == targetId || normalizeSsid(info.ssid) == wifi.ssid) + if (matches) { + val network = bestWifiNetwork() + if (network != null && hasIpv4(connectivity.getLinkProperties(network))) { + onStatus("QFT Wi-Fi 已连接,正在快速发现电脑…") + onAvailable(network) + return + } + } + if (SystemClock.elapsedRealtime() - started > 15_000) { + onUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。") + } else { + handler.postDelayed({ poll() }, 250) + } + } + handler.postDelayed({ poll() }, 250) + } catch (e: Exception) { + onUnavailable("Android 7~9 配网失败:${e.message}") + } + } + + private fun waitUntilUsable(run: Int, network: Network, onStatus: (String) -> Unit, done: () -> Unit) { + val started = SystemClock.elapsedRealtime() + fun poll() { + if (run != generation) return + if (hasIpv4(connectivity.getLinkProperties(network))) { + done() + return + } + if (SystemClock.elapsedRealtime() - started > 6_000) { + onStatus("网络已连接但路由仍未就绪,继续尝试电脑发现…") + done() + } else { + handler.postDelayed({ poll() }, 120) + } + } + poll() + } + + private fun bestWifiNetwork(): Network? = connectivity.allNetworks.firstOrNull { network -> + val caps = connectivity.getNetworkCapabilities(network) + caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && hasIpv4(connectivity.getLinkProperties(network)) + } + + private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true + + fun gatewayEndpoints(network: Network?, port: Int): List { + if (network == null) return emptyList() + val props = connectivity.getLinkProperties(network) ?: return emptyList() + return props.routes + .asSequence() + .mapNotNull { it.gateway as? Inet4Address } + .map { "http://${it.hostAddress}:$port" } + .distinct() + .toList() + } + + fun discoveryHosts(network: Network?): List { + val out = mutableListOf() + if (network != null) { + val props = connectivity.getLinkProperties(network) + props?.routes + ?.mapNotNull { it.gateway as? Inet4Address } + ?.forEach { if (it !in out) out += it } + // Directed broadcast is more reliable than 255.255.255.255 on some + // Wi-Fi drivers/local-only networks. Derive it from the actual link. + props?.linkAddresses + ?.filter { it.address is Inet4Address } + ?.mapNotNull { directedBroadcast(it.address as Inet4Address, it.prefixLength) } + ?.forEach { if (it !in out) out += it } + } + try { + val broadcast = InetAddress.getByName("255.255.255.255") + if (broadcast !in out) out += broadcast + } catch (_: Exception) {} + return out + } + + /** + * Last-resort receiver discovery. Enumerates at most one /24 around the + * phone's actual QFT Wi-Fi address (<=254 hosts) so a nonstandard Windows + * Direct-AP gateway can still be found without guessing 192.168.137.1. + */ + fun subnetEndpoints(network: Network?, port: Int): List { + if (network == null) return emptyList() + val props = connectivity.getLinkProperties(network) ?: return emptyList() + val out = LinkedHashSet() + for (link in props.linkAddresses) { + val addr = link.address as? Inet4Address ?: continue + val octets = addr.address.map { it.toInt() and 0xFF } + // Never scan more than /24. For a narrower real subnet (/25 etc), + // respect its prefix and enumerate fewer hosts. + val prefix = link.prefixLength.coerceIn(24, 30) + val ip = (octets[0] shl 24) or (octets[1] shl 16) or (octets[2] shl 8) or octets[3] + val mask = if (prefix == 0) 0 else (-1 shl (32 - prefix)) + val networkInt = ip and mask + val broadcastInt = networkInt or mask.inv() + for (candidate in (networkInt + 1) until broadcastInt) { + if (candidate == ip) continue + val host = "%d.%d.%d.%d".format( + (candidate ushr 24) and 0xFF, + (candidate ushr 16) and 0xFF, + (candidate ushr 8) and 0xFF, + candidate and 0xFF, + ) + out += "http://$host:$port" + } + } + return out.toList() + } + + private fun directedBroadcast(address: Inet4Address, prefixLength: Int): InetAddress? { + if (prefixLength !in 1..30) return null + val b = address.address.map { it.toInt() and 0xFF } + val ip = (b[0] shl 24) or (b[1] shl 16) or (b[2] shl 8) or b[3] + val mask = -1 shl (32 - prefixLength) + val broadcast = (ip and mask) or mask.inv() + val bytes = byteArrayOf( + ((broadcast ushr 24) and 0xFF).toByte(), + ((broadcast ushr 16) and 0xFF).toByte(), + ((broadcast ushr 8) and 0xFF).toByte(), + (broadcast and 0xFF).toByte(), + ) + return try { InetAddress.getByAddress(bytes) } catch (_: Exception) { null } + } + + @Suppress("DEPRECATION") + fun release(restoreLegacy: Boolean = true) { + generation++ + callback?.let { + try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {} + } + callback = null + handler.removeCallbacksAndMessages(null) + if (restoreLegacy && Build.VERSION.SDK_INT < 29) { + val previous = legacyPreviousNetworkId + if (previous != null && previous >= 0) { + try { + wifiManager.enableNetwork(previous, true) + wifiManager.reconnect() + } catch (_: Exception) {} + } + } + legacyPreviousNetworkId = null + legacyTargetNetworkId = null + } + + private fun normalizeSsid(value: String?): String = value.orEmpty().removePrefix("\"").removeSuffix("\"") +} diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..a4d09c1 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,9 @@ + + + + diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..3e93fd9 --- /dev/null +++ b/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/android/app/src/test/java/com/qft/optical/ProtocolTest.kt b/android/app/src/test/java/com/qft/optical/ProtocolTest.kt new file mode 100644 index 0000000..eaff9ff --- /dev/null +++ b/android/app/src/test/java/com/qft/optical/ProtocolTest.kt @@ -0,0 +1,75 @@ +package com.qft.optical + +import org.junit.Assert.* +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.Base64 +import java.util.zip.CRC32 + +class ProtocolTest { + @Test + fun parsesDataFrameAndRejectsCorruption() { + val payload = byteArrayOf(1, 2, 3, 4, 5) + val text = encode(kind = 2, session = 7L, seq = 9, total = 11, payload = payload) + val f = QftProtocol.parseText(text)!! + assertEquals(FrameKind.DATA, f.kind) + assertEquals(7L, f.sessionId) + assertEquals(9L, f.seq) + assertArrayEquals(payload, f.payload) + + val corrupted = text.dropLast(1) + if (text.last() == 'A') "B" else "A" + assertNull(QftProtocol.parseText(corrupted)) + } + + @Test + fun parsesCrossLanguageKnownVector() { + val text = "QFT1:UUZUMQECAQIDBAUGBwgAAAADAAAACgAJaGVsbG8tcWZ0XhNTAg" + val f = QftProtocol.parseText(text)!! + assertEquals(FrameKind.DATA, f.kind) + assertEquals(0x0102030405060708L, f.sessionId) + assertEquals(3L, f.seq) + assertEquals(10L, f.totalChunks) + assertEquals("hello-qft", f.payload.toString(Charsets.UTF_8)) + } + + @Test + fun parsesManifestSenderDevice() { + val name = "test.txt".toByteArray() + val device = "DESKTOP-ZHY".toByteArray() + val sha = ByteArray(32) { it.toByte() } + val payload = ByteBuffer.allocate(8 + 2 + 32 + 2 + name.size + 2 + device.size) + .order(ByteOrder.BIG_ENDIAN) + .putLong(1234L) + .putShort(700.toShort()) + .put(sha) + .putShort(name.size.toShort()) + .put(name) + .putShort(device.size.toShort()) + .put(device) + .array() + val text = encode(kind = 1, session = 77L, seq = 0, total = 2, payload = payload) + val frame = QftProtocol.parseText(text)!! + val manifest = QftProtocol.parseManifest(frame)!! + assertEquals("DESKTOP-ZHY", manifest.senderDevice) + assertEquals("test.txt", manifest.fileName) + assertEquals(1234L, manifest.fileSize) + assertEquals(700, manifest.chunkSize) + } + + private fun encode(kind: Int, session: Long, seq: Int, total: Int, payload: ByteArray): String { + val bb = ByteBuffer.allocate(24 + payload.size + 4).order(ByteOrder.BIG_ENDIAN) + bb.put("QFT1".toByteArray()) + bb.put(1) + bb.put(kind.toByte()) + bb.putLong(session) + bb.putInt(seq) + bb.putInt(total) + bb.putShort(payload.size.toShort()) + bb.put(payload) + val bodyLen = bb.position() + val crc = CRC32().apply { update(bb.array(), 0, bodyLen) }.value + bb.putInt(crc.toInt()) + return "QFT1:" + Base64.getUrlEncoder().withoutPadding().encodeToString(bb.array()) + } +} diff --git a/android/bootstrap-wrapper.ps1 b/android/bootstrap-wrapper.ps1 new file mode 100644 index 0000000..91ade39 --- /dev/null +++ b/android/bootstrap-wrapper.ps1 @@ -0,0 +1,8 @@ +$ErrorActionPreference = "Stop" +$jar = Join-Path $PSScriptRoot "gradle\wrapper\gradle-wrapper.jar" +$url = "https://raw.githubusercontent.com/gradle/gradle/v8.11.1/gradle/wrapper/gradle-wrapper.jar" +if (-not (Test-Path $jar)) { + Write-Host "Downloading Gradle wrapper jar..." + Invoke-WebRequest -Uri $url -OutFile $jar +} +Write-Host "Gradle wrapper ready: $jar" diff --git a/android/bootstrap-wrapper.sh b/android/bootstrap-wrapper.sh new file mode 100644 index 0000000..cc83707 --- /dev/null +++ b/android/bootstrap-wrapper.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env sh +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +JAR="$ROOT/gradle/wrapper/gradle-wrapper.jar" +URL="https://raw.githubusercontent.com/gradle/gradle/v8.11.1/gradle/wrapper/gradle-wrapper.jar" +if [ ! -f "$JAR" ]; then + echo "Downloading Gradle wrapper jar..." + if command -v curl >/dev/null 2>&1; then + curl -fL "$URL" -o "$JAR" + elif command -v wget >/dev/null 2>&1; then + wget -O "$JAR" "$URL" + else + echo "Need curl or wget" >&2 + exit 1 + fi +fi +echo "Gradle wrapper ready: $JAR" diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..d1e098a --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.9.1" apply false + id("org.jetbrains.kotlin.android") version "2.1.20" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..c751e06 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e2847c8 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 0000000..34813f7 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,4 @@ +#!/bin/sh +APP_HOME=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar +exec java -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..b8b8394 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,3 @@ +@echo off +set APP_HOME=%~dp0 +java -classpath "%APP_HOME%gradle\wrapper\gradle-wrapper.jar" org.gradle.wrapper.GradleWrapperMain %* diff --git a/android/local.properties.example b/android/local.properties.example new file mode 100644 index 0000000..d5fde09 --- /dev/null +++ b/android/local.properties.example @@ -0,0 +1,3 @@ +# Copy this file to local.properties and point it to your Android SDK. +# Forward slashes avoid escaping problems on Windows. +sdk.dir=E:/SYSTEM/APPDATA/Android_SDK diff --git a/android/repair-windows.ps1 b/android/repair-windows.ps1 new file mode 100644 index 0000000..9b1c541 --- /dev/null +++ b/android/repair-windows.ps1 @@ -0,0 +1,68 @@ +param( + [string]$Sdk = "E:\SYSTEM\APPDATA\Android_SDK" +) + +$ErrorActionPreference = "Stop" +$Project = $PSScriptRoot +$SdkManager = Join-Path $Sdk "cmdline-tools\latest\bin\sdkmanager.bat" + +Write-Host "QFT Android build repair" -ForegroundColor Cyan +Write-Host "Project: $Project" +Write-Host "SDK: $Sdk" + +if (-not (Test-Path $Sdk)) { + throw "Android SDK not found: $Sdk" +} +if (-not (Test-Path $SdkManager)) { + throw "sdkmanager not found: $SdkManager`nInstall Android SDK Command-line Tools (latest) from Android Studio > SDK Manager > SDK Tools." +} + +$javaVersion = (& java -version 2>&1 | Select-Object -First 1) +Write-Host "Java: $javaVersion" +if (-not (Get-Command javac -ErrorAction SilentlyContinue)) { + throw "javac was not found. Configure Android Studio Gradle JDK to JDK 17 (full JDK, not a JRE)." +} + +# Force Gradle and Android Studio project import to use the same SDK. +$SdkForProperties = $Sdk -replace '\\','/' +"sdk.dir=$SdkForProperties" | Set-Content -Encoding ASCII (Join-Path $Project "local.properties") + +Write-Host "Installing/repairing API 35 platform and Build Tools 35.0.0..." -ForegroundColor Yellow +& $SdkManager --install "platforms;android-35" "build-tools;35.0.0" "platform-tools" +if ($LASTEXITCODE -ne 0) { throw "sdkmanager failed with exit code $LASTEXITCODE" } + +$AndroidJar = Join-Path $Sdk "platforms\android-35\android.jar" +if (-not (Test-Path $AndroidJar)) { + throw "android-35/android.jar is still missing after installation: $AndroidJar" +} + +Write-Host "Stopping Gradle daemons..." +Push-Location $Project +try { + if (-not (Test-Path (Join-Path $Project "gradle\wrapper\gradle-wrapper.jar"))) { + & (Join-Path $Project "bootstrap-wrapper.ps1") + } + + & .\gradlew.bat --stop + + Write-Host "Clearing project Gradle state..." + Remove-Item (Join-Path $Project ".gradle") -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item (Join-Path $Project "app\build") -Recurse -Force -ErrorAction SilentlyContinue + + Write-Host "Gradle environment:" -ForegroundColor Cyan + & .\gradlew.bat --version + + Write-Host "Building debug APK..." -ForegroundColor Green + & .\gradlew.bat clean :app:assembleDebug --stacktrace + if ($LASTEXITCODE -ne 0) { throw "Gradle build failed with exit code $LASTEXITCODE" } + + $Apk = Join-Path $Project "app\build\outputs\apk\debug\app-debug.apk" + if (Test-Path $Apk) { + Write-Host "SUCCESS: $Apk" -ForegroundColor Green + } else { + Write-Warning "Build completed but APK was not found at the expected path: $Apk" + } +} +finally { + Pop-Location +} diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..1170365 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "QftOpticalAndroid" +include(":app") diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..108a706 --- /dev/null +++ b/docs/PROTOCOL.md @@ -0,0 +1,86 @@ +# QFT protocol overview · v0.3.0-rc3 + +## QFT1 — Windows → Android optical stream + +Wire text: + +`QFT1:` + +Binary frame fields: + +- magic `QFT1` +- protocol version +- frame kind: MANIFEST / DATA / END +- session id +- sequence index +- total chunks +- payload length +- payload +- CRC32 + +MANIFEST contains file name, file size, chunk size, total chunks, SHA-256 and Windows sender-device name. DATA frames are replayed cyclically; Android de-duplicates chunks and waits for missing chunks in later rounds. No Android→Windows feedback channel is used in optical mode. + +v0.3 defaults: 900-byte DATA payload, 4 QR/page, target up to 60 pages/s. + +## QFTPAIR2 — Android → Windows pairing + +Text: + +`QFTPAIR2:` + +Compact JSON keys: + +- `v`: 2 +- `s`: one-time session token +- `n`: Windows device name +- `p`: receiver TCP port +- `e`: local HTTP endpoint hints; Direct AP normally carries one short hint +- `w`: optional `[ssid, passphrase]` for QFT Direct + +QFTPAIR1 remains parser-compatible for older QR payloads. + +Android treats pairing QR as untrusted. HTTP endpoint hints must be literal private/local IPv4 addresses on the advertised port. Every `/qft/*` request must carry the one-time `X-QFT-Token` session value. + +## Receiver discovery + +UDP request to port 39392: + +`QFTDISC2:` + +Windows response: + +`QFTHERE2::` + +Android combines UDP result with QR hint, the actual connected Wi-Fi gateway, common Windows local addresses and a bounded current-subnet fallback scan. + +## Parallel v2 upload + +### Ping + +`GET /qft/ping` + +Headers include `X-QFT-Token` and encoded Android device name. + +### Init + +`POST /qft/upload/init` + +Headers include file name, file size and desired chunk size. Android requests 4/8/16 MiB depending on file size; Windows clamps accepted chunks to 1~16 MiB. + +Response includes `upload_id`, accepted `chunk_size`, and `total_chunks`. + +### Chunk + +`POST /qft/upload/chunk//` + +Body is exactly that file range. Up to eight Android workers send distinct chunks concurrently. Windows writes each accepted chunk to the preallocated `.qftpart` file at its deterministic offset. + +### Finish + +`POST /qft/upload/finish/` + +Windows rejects finish while chunks are missing. Once complete it computes SHA-256, renames the temporary file to its final unique name, and returns success. + +### Compatibility + +`POST /qft/upload` remains the single-stream fallback for old clients or content providers that cannot sustain seekable parallel reads. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..836075a --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,58 @@ +# Roadmap + +## V0.1 — 单 QR 无网络链路(当前) + +- Windows 选择文件 +- 单 QR 动画 +- Android CameraX 连续识别 +- CRC32 +- SHA-256 +- 重复帧去重 +- 多轮补洞 +- 保存 Downloads/QFT + +目标不是速度,而是证明:**飞行模式下可稳定完整恢复真实文件**。 + +## V0.2 — 扫码稳定性 + +- 自动曝光/对焦锁定 +- 只分析中央 ROI +- 720p/1080p 自适应 +- 帧序号抖动统计 +- 自动 FPS 调节 +- QR 版本/纠错级别动态选择 +- Android 前台常亮、屏幕方向锁定 + +## V0.3 — 多 QR + +- Windows 2x2 -> 3x3 网格 +- Android 一帧多码检测 +- 每个位置独立 lane +- lane interleave,避免同一丢帧损失连续数据 + +## V0.4 — Fountain / RaptorQ + +- source block / symbol +- 无需等待指定 seq +- 达到恢复阈值即可完成 +- 发送端持续产生 repair symbols +- 删除“整文件循环重播”的尾部等待 + +## V0.5 — QFT Visual Code + +- 固定四角定位 +- 自定义二值网格 +- BCH/LDPC 内层纠错 +- SIMD 二值化与采样 +- 60/120 FPS +- 标定显示器刷新率与相机 rolling shutter + +## V0.6 — Android -> Windows + +这个方向因 PC 可能无摄像头,使用 App P2P: + +- 同 LAN +- 临时热点 +- Wi-Fi Direct(可用平台) +- QUIC +- 不经过外网/云端 diff --git a/scripts/android_compat_selftest.py b/scripts/android_compat_selftest.py new file mode 100644 index 0000000..45fc131 --- /dev/null +++ b/scripts/android_compat_selftest.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +from pathlib import Path +import re +ROOT = Path(__file__).resolve().parents[1] +gradle = (ROOT/'android/app/build.gradle.kts').read_text() +manifest = (ROOT/'android/app/src/main/AndroidManifest.xml').read_text() +wifi = (ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text() +upload = (ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text() +main = (ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text() +gray = (ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text() +security = (ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text() + +assert re.search(r'minSdk\s*=\s*24', gradle) +assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest +assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest +assert 'NEARBY_WIFI_DEVICES' in manifest +assert 'networkSecurityConfig="@xml/network_security_config"' in manifest +assert 'cleartextTrafficPermitted="true"' in security +assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi +assert 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi +assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload and 'workers = 24' in upload and 'desiredChunkSize' in upload and 'CHUNK_LARGE' in upload +assert 'Size(640, 480)' in main and 'Size(1280, 720)' in main +assert 'STRATEGY_KEEP_ONLY_LATEST' in main +assert 'rotate90' not in gray and 'image.imageInfo.rotationDegrees' not in gray +all_kotlin = '\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt')) +assert 'java.util.Base64' not in all_kotlin +print('PASS Android compatibility/static guards: minSdk24, API29 split, legacy storage/location, Android13 nearby-WiFi, cleartext local config, subnet fallback, fast scanner paths') diff --git a/scripts/local_transfer_integration_selftest.py b/scripts/local_transfer_integration_selftest.py new file mode 100644 index 0000000..76b4201 --- /dev/null +++ b/scripts/local_transfer_integration_selftest.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Loopback integration test for QFTDISC2 + Parallel v2 init/chunk/finish semantics.""" +import hashlib, http.client, json, os, random, socket, tempfile, threading, time +from concurrent.futures import ThreadPoolExecutor +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +TOKEN = "integration_session_128bit_ABC" +DISCOVERY_MAGIC = f"QFTDISC2:{TOKEN}".encode() +CHUNK = 8 * 1024 * 1024 + +with tempfile.TemporaryDirectory() as td: + root = Path(td) + source = root / "src.bin" + source.write_bytes(os.urandom(40 * 1024 * 1024 + 12345)) + source_sha = hashlib.sha256(source.read_bytes()).hexdigest() + part = root / "recv.qftpart" + part.write_bytes(b"") + part_fp = open(part, "r+b", buffering=0) + part_fp.truncate(source.stat().st_size) + lock = threading.Lock() + received = set() + upload_id = "up_test_01" + total_chunks = (source.stat().st_size + CHUNK - 1) // CHUNK + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): pass + def _auth(self): return self.headers.get("X-QFT-Token") == TOKEN + def _reply(self, code, body=b"{}"): + self.send_response(code); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body) + def do_GET(self): + if not self._auth(): return self._reply(403) + if self.path == "/qft/ping": return self._reply(200, b'{"ok":true,"protocol":2,"parallel":true}') + self._reply(404) + def do_POST(self): + if not self._auth(): return self._reply(403) + if self.path == "/qft/upload/init": + body = json.dumps({"ok":True,"upload_id":upload_id,"chunk_size":CHUNK,"total_chunks":total_chunks}).encode() + return self._reply(200, body) + prefix = f"/qft/upload/chunk/{upload_id}/" + if self.path.startswith(prefix): + idx = int(self.path[len(prefix):]); n = int(self.headers["Content-Length"]); data = self.rfile.read(n) + offset = idx * CHUNK + assert n == min(CHUNK, source.stat().st_size - offset) + with lock: + part_fp.seek(offset); part_fp.write(data); received.add(idx) + return self._reply(200) + if self.path == f"/qft/upload/finish/{upload_id}": + if len(received) != total_chunks: return self._reply(409) + with lock: part_fp.flush(); os.fsync(part_fp.fileno()) + return self._reply(200, json.dumps({"ok":True}).encode()) + self._reply(404) + + httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + port = httpd.server_address[1] + threading.Thread(target=httpd.serve_forever, daemon=True).start() + + udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); udp.bind(("127.0.0.1", 0)); udp_port = udp.getsockname()[1] + stop = threading.Event() + def udp_server(): + while not stop.is_set(): + udp.settimeout(.2) + try: data, peer = udp.recvfrom(512) + except socket.timeout: continue + except OSError: + if stop.is_set(): break + raise + if data == DISCOVERY_MAGIC: udp.sendto(f"QFTHERE2:{TOKEN}:{port}".encode(), peer) + threading.Thread(target=udp_server, daemon=True).start() + + # UDP discovery client. + c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); c.settimeout(1); c.sendto(DISCOVERY_MAGIC, ("127.0.0.1", udp_port)) + resp, _ = c.recvfrom(512); assert resp == f"QFTHERE2:{TOKEN}:{port}".encode(); c.close() + + def request(method, path, body=b"", headers=None): + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5) + h = {"X-QFT-Token": TOKEN}; h.update(headers or {}) + conn.request(method, path, body=body, headers=h); r = conn.getresponse(); payload = r.read(); status = r.status; conn.close(); return status, payload + assert request("GET", "/qft/ping")[0] == 200 + status, body = request("POST", "/qft/upload/init", headers={"Content-Length":"0"}); assert status == 200 + init = json.loads(body); assert init["chunk_size"] == CHUNK and init["total_chunks"] == total_chunks + + indices = list(range(total_chunks)); random.Random(42).shuffle(indices) + def send(idx): + with open(source, "rb") as f: + f.seek(idx * CHUNK); data = f.read(min(CHUNK, source.stat().st_size - idx * CHUNK)) + status, _ = request("POST", f"/qft/upload/chunk/{upload_id}/{idx}", data, {"Content-Length":str(len(data))}) + assert status == 200 + started = time.perf_counter() + with ThreadPoolExecutor(max_workers=8) as ex: list(ex.map(send, indices)) + assert request("POST", f"/qft/upload/finish/{upload_id}", headers={"Content-Length":"0"})[0] == 200 + elapsed = time.perf_counter() - started + part_fp.close(); recv_sha = hashlib.sha256(part.read_bytes()).hexdigest(); assert recv_sha == source_sha + stop.set(); udp.close(); httpd.shutdown(); httpd.server_close() + print(f"PASS loopback Parallel v2 integration: UDP discovery + HTTP auth + {total_chunks} out-of-order chunks / 8 workers; " + f"{source.stat().st_size} bytes SHA-256 identical in {elapsed:.2f}s") diff --git a/scripts/memory_budget_selftest.py b/scripts/memory_budget_selftest.py new file mode 100644 index 0000000..538bae4 --- /dev/null +++ b/scripts/memory_budget_selftest.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +MAX_CACHE_MIB = 768 +MAX_PAGES = 192 +HARD_MIB = 1100 + +def calc(side): + bpp = side * side * 4 + pages = max(4, min(MAX_PAGES, MAX_CACHE_MIB * 1024 * 1024 // bpp)) + managed = pages * bpp / (1024 * 1024) + return pages, managed + +p4, m4 = calc(960) +p1, m1 = calc(760) +# Include a conservative 64 MiB transient batch/decoder allowance in this design-level bound. +assert m4 + 64 < HARD_MIB +assert m1 + 64 < HARD_MIB +print(f"PASS memory budget: 4QR cache={p4} pages/{m4:.1f} MiB; 1QR cache={p1} pages/{m1:.1f} MiB; hard design ceiling={HARD_MIB} MiB") diff --git a/scripts/optical_image_decode_selftest.py b/scripts/optical_image_decode_selftest.py new file mode 100644 index 0000000..142e026 --- /dev/null +++ b/scripts/optical_image_decode_selftest.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Synthetic visual-path smoke test for the 4-QR optical page and QFTPAIR2. +Requires: qrcode, numpy, opencv-python, pyzbar/libzbar. +This is intentionally not a substitute for a real display/camera test. +""" +import base64, json, os, time +import cv2 +import numpy as np +import qrcode +from pyzbar.pyzbar import decode as zdecode, ZBarSymbol +from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M + + +def make_qr(text: str, ec, target: int): + qr = qrcode.QRCode(version=None, error_correction=ec, box_size=1, border=4) + qr.add_data(text); qr.make(fit=True) + mat = np.asarray(qr.get_matrix(), dtype=np.uint8) + scale = max(1, target // mat.shape[0]) + return ((1 - np.kron(mat, np.ones((scale, scale), np.uint8))) * 255).astype(np.uint8), qr.version + +# Four data QR symbols at the same density used by v0.3 (about 1243 chars/frame). +texts = ["QFT1:" + base64.urlsafe_b64encode(os.urandom(928)).decode().rstrip("=") for _ in range(4)] +canvas = np.full((960, 960), 255, np.uint8) +gutter = 15 +cell = (960 - gutter * 3) // 2 +for idx, text in enumerate(texts): + img, version = make_qr(text, ERROR_CORRECT_L, cell) + row, col = divmod(idx, 2) + x = gutter + col * (cell + gutter) + (cell - img.shape[1]) // 2 + y = gutter + row * (cell + gutter) + (cell - img.shape[0]) // 2 + canvas[y:y+img.shape[0], x:x+img.shape[1]] = img +started = time.perf_counter() +found = {r.data.decode() for r in zdecode(canvas, symbols=[ZBarSymbol.QRCODE])} +elapsed = time.perf_counter() - started +assert found == set(texts), (len(found), len(texts)) + +# Pairing QR: downscale + rotate + slight blur to exercise acquisition margin. +v2 = { + "v":2,"s":"qft_test_session_128bit_XY","n":"DESKTOP-QFT","p":39393, + "e":["http://192.168.137.1:39393"], + "w":["QFT-DESKTOP-abc123","3xamplePassw0rd"], +} +raw = json.dumps(v2, separators=(",", ":"), ensure_ascii=False).encode() +pair_text = "QFTPAIR2:" + base64.urlsafe_b64encode(raw).decode().rstrip("=") +pair, pair_ver = make_qr(pair_text, ERROR_CORRECT_M, 520) +pair = cv2.resize(pair, (260, 260), interpolation=cv2.INTER_NEAREST) +rot = cv2.getRotationMatrix2D((130, 130), 7.0, 1.0) +pair = cv2.warpAffine(pair, rot, (300, 300), borderValue=255) +pair = cv2.GaussianBlur(pair, (3, 3), 0.5) +started2 = time.perf_counter() +pair_found = [r.data.decode() for r in zdecode(pair, symbols=[ZBarSymbol.QRCODE])] +elapsed2 = time.perf_counter() - started2 +assert pair_text in pair_found +print(f"PASS synthetic QR decode: 4/4 optical QR v{version} decoded from 960px page in {elapsed*1000:.1f} ms; " + f"QFTPAIR2 QR-M v{pair_ver} decoded after 7deg rotate+blur in {elapsed2*1000:.1f} ms") diff --git a/scripts/pairing_selftest.py b/scripts/pairing_selftest.py new file mode 100644 index 0000000..fe9b0d7 --- /dev/null +++ b/scripts/pairing_selftest.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +import base64, json +import qrcode +from qrcode.constants import ERROR_CORRECT_M + +session = "qft_test_session_128bit_XY" +ssid = "QFT-DESKTOP-abc123" +password = "3xamplePassw0rd" + +v2 = {"v":2,"s":session,"n":"DESKTOP-QFT","p":39393,"e":["http://192.168.137.1:39393"],"w":[ssid,password]} +raw2 = json.dumps(v2, separators=(",", ":"), ensure_ascii=False).encode() +text2 = "QFTPAIR2:" + base64.urlsafe_b64encode(raw2).decode().rstrip("=") +decoded = json.loads(base64.urlsafe_b64decode(text2.split(":",1)[1] + "=" * (-len(text2.split(":",1)[1]) % 4))) +assert decoded == v2 + +v1 = { + "v":1,"session":session,"pc_name":"DESKTOP-QFT","transport":"http-stream-v1","port":39393, + "endpoints":["http://192.168.137.1:39393","http://192.168.49.1:39393"], + "wifi":{"ssid":ssid,"passphrase":password,"security":"WPA2"}, +} +raw1 = json.dumps(v1, separators=(",", ":")).encode() +text1 = "QFTPAIR1:" + base64.urlsafe_b64encode(raw1).decode().rstrip("=") +assert len(text2) < len(text1) * 0.60, (len(text2), len(text1)) + +qr = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_M, box_size=1, border=4) +qr.add_data(text2) +qr.make(fit=True) +assert qr.version <= 10, qr.version +print(f"PASS pairing: QFTPAIR2={len(text2)} chars vs v1={len(text1)} chars ({len(text2)/len(text1):.1%}), QR-M version={qr.version}") diff --git a/scripts/parallel_upload_selftest.py b/scripts/parallel_upload_selftest.py new file mode 100644 index 0000000..e35be71 --- /dev/null +++ b/scripts/parallel_upload_selftest.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +import hashlib, os, tempfile +from concurrent.futures import ThreadPoolExecutor + +SIZE = 64 * 1024 * 1024 + 12345 +CHUNK = 8 * 1024 * 1024 +WORKERS = 8 +IO = 1024 * 1024 + + +def sha(path): + h = hashlib.sha256() + with open(path, "rb", buffering=0) as f: + while True: + b = f.read(4 * 1024 * 1024) + if not b: break + h.update(b) + return h.digest() + + +def main(): + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "source.bin") + dst = os.path.join(d, "received.qftpart") + # deterministic 1 MiB pattern, streamed to avoid holding the file in RAM + pattern = bytes((i * 131 + 17) & 0xFF for i in range(IO)) + remaining = SIZE + with open(src, "wb", buffering=0) as f: + while remaining: + n = min(remaining, len(pattern)) + f.write(pattern[:n]); remaining -= n + with open(dst, "wb") as f: f.truncate(SIZE) + + src_fd = os.open(src, os.O_RDONLY) + dst_fd = os.open(dst, os.O_RDWR) + try: + total = (SIZE + CHUNK - 1) // CHUNK + def worker(index): + offset = index * CHUNK + remaining = min(CHUNK, SIZE - offset) + pos = 0 + while remaining: + n = min(IO, remaining) + block = os.pread(src_fd, n, offset + pos) + assert len(block) == n + wrote = os.pwrite(dst_fd, block, offset + pos) + assert wrote == n + remaining -= n; pos += n + return index + with ThreadPoolExecutor(max_workers=WORKERS) as pool: + completed = sorted(pool.map(worker, reversed(range(total)))) + assert completed == list(range(total)) + finally: + os.close(src_fd); os.close(dst_fd) + + assert sha(src) == sha(dst) + print(f"PASS parallel upload: {SIZE} bytes, {CHUNK//(1024*1024)} MiB chunks, {WORKERS} workers, 1 MiB worker I/O, SHA-256 identical") + + +if __name__ == "__main__": main() diff --git a/scripts/protocol_selftest.py b/scripts/protocol_selftest.py new file mode 100644 index 0000000..1ffc6be --- /dev/null +++ b/scripts/protocol_selftest.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +import base64, binascii, hashlib, math, os, random, struct +import qrcode +from qrcode.constants import ERROR_CORRECT_L + +PREFIX = "QFT1:" +CHUNK = 900 +LANES = 4 +DISPLAY_FPS = 60 + + +def enc(kind, sid, seq, total, payload=b""): + body = b"QFT1" + bytes([1, kind]) + struct.pack(">QIIH", sid, seq, total, len(payload)) + payload + crc = binascii.crc32(body) & 0xFFFFFFFF + return PREFIX + base64.urlsafe_b64encode(body + struct.pack(">I", crc)).decode().rstrip("=") + + +def dec(text): + assert text.startswith(PREFIX) + b64 = text[len(PREFIX):] + raw = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)) + body, crc_raw = raw[:-4], raw[-4:] + assert (binascii.crc32(body) & 0xFFFFFFFF) == struct.unpack(">I", crc_raw)[0] + assert body[:4] == b"QFT1" and body[4] == 1 + kind = body[5] + sid, seq, total, plen = struct.unpack(">QIIH", body[6:24]) + payload = body[24:] + assert len(payload) == plen + return kind, sid, seq, total, payload + + +def test_qr_density(sample): + qr = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_L, box_size=1, border=4) + qr.add_data(sample) + qr.make(fit=True) + modules_with_quiet = qr.modules_count + 8 + canvas = 960 + gutter = max(12, min(24, canvas // 64)) + cell = (canvas - gutter * 3) // 2 + module_px = cell // modules_with_quiet + assert module_px >= 3, (qr.version, qr.modules_count, cell, module_px) + return qr.version, module_px, len(sample) + + +def main(): + random.seed(20260810) + data = os.urandom(2_500_123) + digest = hashlib.sha256(data).digest() + total = math.ceil(len(data) / CHUNK) + sid = 0x1234567890ABCDEF + name = b"sample.bin" + device = b"DESKTOP-QFT" + manifest = ( + struct.pack(">QH", len(data), CHUNK) + + digest + + struct.pack(">H", len(name)) + name + + struct.pack(">H", len(device)) + device + ) + playlist = [enc(1, sid, 0, total, manifest)] + playlist += [enc(2, sid, i, total, data[i*CHUNK:(i+1)*CHUNK]) for i in range(total)] + playlist += [enc(3, sid, 0, total)] + pages = [playlist[i:i+LANES] for i in range(0, len(playlist), LANES)] + + version, module_px, chars = test_qr_density(playlist[min(2, len(playlist)-1)]) + + got = [None] * total + rounds = 0 + manifests = 0 + # Model both whole-camera-frame losses and per-lane decode failures. + while any(x is None for x in got): + rounds += 1 + for page in pages: + if random.random() < 0.24: # display page/camera frame missed + continue + for text in page: + if random.random() < 0.14: # one quadrant not decoded + continue + kind, rsid, seq, rtotal, payload = dec(text) + assert rsid == sid and rtotal == total + if kind == 1: + manifests += 1 + elif kind == 2 and got[seq] is None: + got[seq] = payload + assert rounds < 60 + + rebuilt = b"".join(got)[:len(data)] + assert rebuilt == data + assert hashlib.sha256(rebuilt).digest() == digest + raw_rate = CHUNK * LANES * DISPLAY_FPS + print( + f"PASS optical: {len(data)} bytes, {total} chunks, {LANES} QR/page @ {DISPLAY_FPS} FPS, " + f"24% page loss + 14% lane loss, recovered in {rounds} rounds; " + f"QR v{version}, {module_px}px/module, frame chars={chars}, theoretical payload={raw_rate/1024:.1f} KiB/s" + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/run_all_selftests.py b/scripts/run_all_selftests.py new file mode 100644 index 0000000..a96fbdf --- /dev/null +++ b/scripts/run_all_selftests.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import subprocess, sys +from pathlib import Path +root = Path(__file__).resolve().parent +scripts = [ + 'protocol_selftest.py', + 'pairing_selftest.py', + 'parallel_upload_selftest.py', + 'udp_discovery_selftest.py', + 'local_transfer_integration_selftest.py', + 'memory_budget_selftest.py', + 'android_compat_selftest.py', +] +for name in scripts: + print(f'== {name} ==', flush=True) + subprocess.run([sys.executable, str(root/name)], check=True) +print('ALL CORE PYTHON SELFTESTS PASSED') diff --git a/scripts/udp_discovery_selftest.py b/scripts/udp_discovery_selftest.py new file mode 100644 index 0000000..c828a88 --- /dev/null +++ b/scripts/udp_discovery_selftest.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +import socket, threading, time + +TOKEN = "test_session_1234567890AB" +PORT = 39392 +TCP = 39393 +ready = threading.Event() + + +def server(): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind(("127.0.0.1", PORT)) + s.settimeout(2) + ready.set() + data, peer = s.recvfrom(512) + assert data.decode() == f"QFTDISC2:{TOKEN}" + s.sendto(f"QFTHERE2:{TOKEN}:{TCP}".encode(), peer) + s.close() + + +def main(): + t = threading.Thread(target=server, daemon=True); t.start(); ready.wait(1) + c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); c.settimeout(1) + c.sendto(f"QFTDISC2:{TOKEN}".encode(), ("127.0.0.1", PORT)) + data, peer = c.recvfrom(512); c.close(); t.join(1) + assert data.decode() == f"QFTHERE2:{TOKEN}:{TCP}" + print(f"PASS UDP discovery: request/response token+port round-trip from {peer[0]}") + + +if __name__ == "__main__": main() diff --git a/windows/BUILD_0.2.0.md b/windows/BUILD_0.2.0.md new file mode 100644 index 0000000..9deed8d --- /dev/null +++ b/windows/BUILD_0.2.0.md @@ -0,0 +1,34 @@ +# Windows v0.2.0 build / test + +```powershell +cd E:\tools\qft_win_android_mvp\windows +cargo check +cargo run --release +``` + +新增: + +- `windows = 0.62.2` / `Devices_WiFiDirect` / `Security_Credentials` +- `serde` / `serde_json` +- `if-addrs` + +QFT Direct 真机要求: + +- Windows 10/11 +- Wi-Fi 已开启 +- 适配器/驱动支持 Wi-Fi Direct +- Windows Mobile Hotspot 没有占用 Wi-Fi Direct group-owner 资源 + +首次使用会在 `%LOCALAPPDATA%\QFT\direct-ap.json` 创建随机 QFT Direct SSID/密码。它用于让 Android 记住同一台电脑的网络身份;每次“启动接收”仍会生成不同的 session token。 + +如果 QFT Direct 启动失败: + +1. 关闭 Windows“移动热点”。 +2. 确认 Wi-Fi 开启。 +3. 再试一次。 +4. 仍失败则在 QFT UI 切到 `当前局域网(备用)`。 + +如果 Android 已显示连接 QFT Wi-Fi、但无法找到 Windows: + +- 允许 qft-windows.exe 通过 Windows Defender Firewall 的**专用网络**。 +- Android v0.2.0 会优先探测 QFT Wi-Fi 返回的 gateway,不再依赖固定 Windows IP。 diff --git a/windows/BUILD_FIX_0.1.2.md b/windows/BUILD_FIX_0.1.2.md new file mode 100644 index 0000000..301644e --- /dev/null +++ b/windows/BUILD_FIX_0.1.2.md @@ -0,0 +1,21 @@ +# Windows build fix v0.1.2 + +This patch updates the Windows sender for `eframe = 0.35.0` / `egui = 0.35.0`. + +Changes: + +- `eframe::App::update(ctx, frame)` -> `eframe::App::ui(ui, frame)` +- clone `egui::Context` from `ui.ctx()` for texture/repaint operations +- `egui::TopBottomPanel::top(...)` -> `egui::Panel::top(...)` +- `CentralPanel::show(ctx, ...)` -> `CentralPanel::show(ui, ...)` +- project `rust-version` corrected to `1.95` for egui/eframe 0.35 compatibility + +No QFT protocol, QR framing, file chunking, or Android code was changed. + +Verify on Windows: + +```powershell +cd windows +cargo check +cargo run --release +``` diff --git a/windows/BUILD_FIX_0.1.3.md b/windows/BUILD_FIX_0.1.3.md new file mode 100644 index 0000000..33edb26 --- /dev/null +++ b/windows/BUILD_FIX_0.1.3.md @@ -0,0 +1,56 @@ +# Windows UI / device identity update — v0.1.3 + +## 1. Chinese UI font + +The Windows sender no longer relies on egui's default font for Chinese text. +It loads a TrueType font (`.ttf`) at runtime and installs it as the first +Proportional and Monospace font fallback. + +Lookup order: + +1. `QFT_FONT_PATH` +2. `qft-ui.ttf` next to the executable +3. `assets/qft-ui.ttf` next to the executable +4. `./assets/qft-ui.ttf` from the current working directory +5. common Windows Chinese `.ttf` files + +For development, the most deterministic setup is to put your own Chinese-capable +TTF at: + +```text +windows/assets/qft-ui.ttf +``` + +No font file is bundled by this project. + +## 2. Device display + +The Windows sender now displays: + +```text +本机设备:DESKTOP-XXXX +传输设备:DESKTOP-XXXX → Android 光学接收端 · 正在传输 +``` + +The MANIFEST payload now appends: + +```text +sender_device_len: u16 +sender_device_utf8: bytes +``` + +The Android app displays both endpoints, for example: + +```text +传输设备:DESKTOP-XXXX → Xiaomi 15 +``` + +The field is appended to the end of the old MANIFEST payload, so the new Android +parser remains compatible with v0.1/v0.1.2 manifests. + +## Important limitation + +Windows -> Android is intentionally a one-way optical channel. The Android phone +does not send any ACK or identity back to Windows, so the Windows sender cannot +automatically know the exact receiving phone model. The Android side can show +both the sender PC name and its own local device model. diff --git a/windows/BUILD_FIX_0.2.2.md b/windows/BUILD_FIX_0.2.2.md new file mode 100644 index 0000000..20d12be --- /dev/null +++ b/windows/BUILD_FIX_0.2.2.md @@ -0,0 +1,20 @@ +# QFT Windows v0.2.2 build fix + +This patch fixes the five `cargo check` errors reported against eframe/egui 0.35.0. + +## Fixed + +1. Added semicolons after `ui.small(...)` calls that were used as the final expression of `if/else` blocks. `ui.small()` returns `egui::Response`, while those blocks must evaluate to `()`. +2. Removed the obsolete `Context::style()` and `Context::set_style()` calls. Those APIs are not available in egui 0.35. +3. Preserved the intended spacing by applying it through `Ui::spacing_mut()` inside `eframe::App::ui`. +4. Bumped Windows application/package version to 0.2.2. + +## Verify on Windows + +```powershell +cd E:\tools\qft_win_android_mvp\windows +cargo check +cargo run --release +``` + +The Android/Windows transfer protocol, Wi-Fi Direct pairing flow, receiver service and optical transport are unchanged by this patch. diff --git a/windows/Cargo.lock b/windows/Cargo.lock new file mode 100644 index 0000000..7fee14f --- /dev/null +++ b/windows/Cargo.lock @@ -0,0 +1,4567 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "accesskit" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954" +dependencies = [ + "accesskit", + "accesskit_consumer 0.36.0", + "atspi-common", + "phf", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer 0.38.0", + "hashbrown 0.16.1", + "objc2 0.5.2", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21" +dependencies = [ + "accesskit", + "accesskit_consumer 0.35.0", + "hashbrown 0.16.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313" +dependencies = [ + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.1", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.20", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arboard" +version = "3.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.60.2", + "x11rb", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.4", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.4", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.4", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34ddef2995421ab6a5c779542c81ee77c115206f4ad9d5a8e05f4ff49716a3dd" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.2", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.4", +] + +[[package]] +name = "blocking" +version = "1.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.1", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7" +dependencies = [ + "bitflags 2.13.1", + "polling", + "rustix 1.1.4", + "slab", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.4", + "rustix 1.1.4", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.1", + "block2 0.6.2", + "libc", + "objc2 0.6.4", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "ecolor" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6758be723a3f298bbfda4db75748bc2ba0abafe096b6383c7c32da264764fbc3" +dependencies = [ + "bytemuck", + "emath", +] + +[[package]] +name = "eframe" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc8234e2f681b2afd2b2e8c332fa614de2fddbdcb28d0acf5c420449682ea90" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "egui-wgpu", + "egui-winit", + "egui_glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "pollster", + "profiling", + "raw-window-handle", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "wgpu", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2796c98d50b79631281d516343a6f6e93c0666462ca36e2c93b39f25d7793325" +dependencies = [ + "accesskit", + "ahash", + "bitflags 2.13.1", + "emath", + "epaint", + "itertools", + "log", + "nohash-hasher", + "profiling", + "smallvec", + "unicode-segmentation", +] + +[[package]] +name = "egui-wgpu" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2e6cfac0725563555fa4f91e9f799b9d7c6c5dd831fca6abc8234afc64b7a34" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "epaint", + "log", + "profiling", + "thiserror 2.0.20", + "type-map", + "web-time", + "wgpu", + "winit", +] + +[[package]] +name = "egui-winit" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ea6bf3608db949588b95b8b341ee358d0c3f95cf4dc3f53d8d76717edee87db" +dependencies = [ + "accesskit_winit", + "arboard", + "bytemuck", + "egui", + "log", + "objc2 0.6.4", + "objc2-foundation 0.3.2", + "objc2-ui-kit 0.3.2", + "profiling", + "raw-window-handle", + "smithay-clipboard", + "web-time", + "webbrowser", + "winit", +] + +[[package]] +name = "egui_glow" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52274b9bfb8d8e252cd0f00c9f6214f360d75a0962baa77a2d62ddb002fe99d4" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "memoffset", + "profiling", + "winit", +] + +[[package]] +name = "either" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" + +[[package]] +name = "emath" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd4ec073c9898516584d8c6cfdcee95b530b3d941cd5031ef4050aa36812308b" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "epaint" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e60a8888b51da911df23918fd7301359b1d43a406a0ff3b8863af093dd7fc6c" +dependencies = [ + "ahash", + "bytemuck", + "ecolor", + "emath", + "epaint_default_fonts", + "font-types", + "harfrust", + "log", + "nohash-hasher", + "parking_lot", + "profiling", + "self_cell", + "skrifa", + "smallvec", + "unicode-general-category", + "unicode-segmentation", + "vello_cpu", +] + +[[package]] +name = "epaint_default_fonts" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13ee4e1f553a3584c301f3a56ff1a775f1384781396cea301c8d952e9b93f560" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "fearless_simd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" + +[[package]] +name = "find-msvc-tools" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" + +[[package]] +name = "futures-io" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "futures-task" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" + +[[package]] +name = "futures-util" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.4", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glifo" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "skrifa", + "smallvec", + "vello_common", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.1", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.20", + "windows", +] + +[[package]] +name = "gpu-descriptor" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" +dependencies = [ + "bitflags 2.13.1", + "gpu-descriptor-types", + "hashbrown 0.15.5", +] + +[[package]] +name = "gpu-descriptor-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0431e8e389aa0f1e72bb9d1c2db8957a1a7a3580e8ed97db819c14837aac9b3e" +dependencies = [ + "bitflags 2.13.1", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hexf-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "if-addrs" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "tiff", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.20", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2026a5056764a10b2bf5d56488cba40da507f5493a6a429340e2004d9ed085fa" +dependencies = [ + "bitflags 2.13.1", + "libc", + "plain", + "redox_syscall 0.9.1", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "naga" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2bf919621e7975acb27d881bae2fb993e0d45c8e0446e85e6272971e00dc8df" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.1", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.16.1", + "hexf-parse", + "indexmap", + "libm", + "log", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.20", + "unicode-ident", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.1", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "libc", + "objc2 0.5.2", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.1", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.1", + "dispatch2", + "objc2 0.6.4", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.1", + "dispatch2", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.2", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.1", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.1", + "objc2 0.6.4", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.1", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.1", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.1", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.1", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7d950ca161dc355eaf28f82b11345ed76c6e1f6eb1f4f4479e0323b9e2fbd0e" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.1", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qft-windows" +version = "0.3.0" +dependencies = [ + "anyhow", + "base64", + "crc32fast", + "eframe", + "if-addrs", + "qrcode", + "rand", + "rayon", + "rfd", + "serde", + "serde_json", + "sha2", + "windows", +] + +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81" +dependencies = [ + "bytemuck", + "font-types", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "redox_syscall" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07507be7b4a5f9f26eeb41eeaebb1f5a7ff29dfb29739facc21d35bf8b11c21e" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "pollster", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit 0.19.2", + "tiny-skia", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" + +[[package]] +name = "skrifa" +version = "0.42.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.1", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.1", + "calloop 0.14.4", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.4", + "thiserror 2.0.20", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vello_common" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "hashbrown 0.17.1", + "log", + "peniko", + "smallvec", + "thiserror 2.0.20", +] + +[[package]] +name = "vello_cpu" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "588691169aed86b5c8fb487266afee01323234e6fd0a3f2aaec0eaa8e4007f23" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "vello_common", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "016ccf01d1c58b6f8999612813e17c9b2390f7d70671428869913310f83f54b8" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.4", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.1", + "rustix 1.1.4", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.1", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.4", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.1", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webbrowser" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76e8840e1ba2881d4cbb18d2147627a56af426ff064c0401eb0c8410c6325d07" +dependencies = [ + "arrayvec", + "bitflags 2.13.1", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.16.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f519832254e56965a9940c4af57dcb75f702b6f6fa4a0b172f685395843a4d7" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.1", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.16.1", + "indexmap", + "log", + "naga", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.20", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e39e26c4c0e07589e67d18546cf79ff45383659fc72fca4dd293358a0347f3" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e09be551dc939498bdd5f6b2c66e55ab275dad25825267a08605a80fc9f0af" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1fb1798be2a912497d4c224f72d39bb0cb34af50e8bcc29865bc339c943059" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e592c1bbef6ad047647ae6e666ebd8cee7a32bb4544d9700ec96cbf73230257" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97ace1c17727311c22a46e4e3faf56ea6de81af99dcc839bdfb54857b94d448d" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.1", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "gpu-descriptor", + "hashbrown 0.16.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "ndk-sys", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "thiserror 2.0.20", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95226013f547544b223281cd16a4fb549aa9dcb562adbda0faae4c73ffbbc161" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84bf84cd9ca8ca45e2b223a3868f1adf9bfc0c66aeac212e76ee7e40fdadf8f5" +dependencies = [ + "bitflags 2.13.1", + "bytemuck", + "js-sys", + "log", + "raw-window-handle", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.1", + "block2 0.5.1", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.2", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit 0.19.2", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.4", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.1", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.4", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.3", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "769381976ea05c1f0abde0ca527b02e415bccbdbad148534a2b0c1901c9ab934" +dependencies = [ + "serde", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e28c25bd8bb8da5a1f3e7065d0c156b9ee9a7973adf78b0e35eaefdf3b1b5c" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d496a145685283b67e232bd9e47377f6b60ad9d51e3601b23867f77c42477f96" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.3", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "629d80ece222cad20fe0e8741be493c4ab166acf3b85341bdc2cdbcfd8f3c2d6" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.3", + "winnow", +] diff --git a/windows/Cargo.toml b/windows/Cargo.toml new file mode 100644 index 0000000..dbcec68 --- /dev/null +++ b/windows/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "qft-windows" +version = "0.3.0" +edition = "2024" +rust-version = "1.95" + +[dependencies] +eframe = "0.35.0" +rfd = "0.17.2" +qrcode = { version = "0.14.1", default-features = false } +base64 = "0.22.1" +crc32fast = "1.5.0" +sha2 = "0.10.9" +rand = "0.9.2" +anyhow = "1.0.99" +serde = { version = "1.0.219", features = ["derive"] } +serde_json = "1.0.143" +if-addrs = "0.13.4" +rayon = "1.11.0" + +[target.'cfg(windows)'.dependencies] +windows = { version = "0.62.2", features = [ + "Devices_WiFiDirect", + "Security_Credentials", +] } diff --git a/windows/assets/README_FONT.txt b/windows/assets/README_FONT.txt new file mode 100644 index 0000000..1696fce --- /dev/null +++ b/windows/assets/README_FONT.txt @@ -0,0 +1,17 @@ +QFT Windows UI font + +Place a Chinese-capable TrueType font here and name it: + + qft-ui.ttf + +The application loads TTF at runtime. It does not embed/distribute font files. +Lookup order: +1. QFT_FONT_PATH environment variable +2. qft-ui.ttf beside the executable +3. assets/qft-ui.ttf beside the executable +4. ./assets/qft-ui.ttf from the current working directory +5. common Windows CJK .ttf files (for example C:\Windows\Fonts\simhei.ttf) + +Example PowerShell: + $env:QFT_FONT_PATH = 'D:\fonts\my-cjk-font.ttf' + cargo run --release diff --git a/windows/src/direct_ap.rs b/windows/src/direct_ap.rs new file mode 100644 index 0000000..f29df96 --- /dev/null +++ b/windows/src/direct_ap.rs @@ -0,0 +1,79 @@ +use anyhow::{bail, Context, Result}; + +#[cfg(windows)] +use windows::{ + core::HSTRING, + Devices::WiFiDirect::{ + WiFiDirectAdvertisementPublisher, WiFiDirectAdvertisementPublisherStatus, + }, + Security::Credentials::PasswordCredential, +}; + +pub struct DirectAp { + pub ssid: String, + #[cfg(windows)] + publisher: WiFiDirectAdvertisementPublisher, +} + +impl DirectAp { + pub fn start(ssid: String, passphrase: String) -> Result { + #[cfg(not(windows))] + { + let _ = (ssid, passphrase); + bail!("QFT Direct AP 仅支持 Windows") + } + + #[cfg(windows)] + { + let publisher = WiFiDirectAdvertisementPublisher::new() + .context("创建 Wi-Fi Direct publisher 失败")?; + let ad = publisher.Advertisement() + .context("读取 Wi-Fi Direct advertisement 失败")?; + ad.SetIsAutonomousGroupOwnerEnabled(true) + .context("启用 Autonomous Group Owner 失败")?; + let legacy = ad.LegacySettings() + .context("读取 LegacySettings 失败")?; + legacy.SetIsEnabled(true) + .context("启用 Wi-Fi Direct Legacy AP 失败")?; + legacy.SetSsid(&HSTRING::from(&ssid)) + .context("设置 QFT SSID 失败")?; + let credential = PasswordCredential::new() + .context("创建 Wi-Fi Direct 密码对象失败")?; + credential.SetPassword(&HSTRING::from(&passphrase)) + .context("设置 QFT 热点密码失败")?; + legacy.SetPassphrase(&credential) + .context("应用 QFT 热点密码失败")?; + + publisher.Start().context("启动 QFT Wi-Fi Direct AP 失败")?; + + // Publisher startup is asynchronous. Do not expose the pairing QR until + // Windows reports Started; otherwise Android can scan a network that is + // not yet discoverable. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + let status = publisher.Status().context("读取 AP 状态失败")?; + if status == WiFiDirectAdvertisementPublisherStatus::Started { + break; + } + if status == WiFiDirectAdvertisementPublisherStatus::Aborted { + bail!("Wi-Fi Direct AP 启动被系统中止。请确认 Windows Wi-Fi 已开启,且系统移动热点未占用 Wi-Fi Direct。") + } + if std::time::Instant::now() >= deadline { + bail!("Wi-Fi Direct AP 启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。") + } + std::thread::sleep(std::time::Duration::from_millis(80)); + } + + Ok(Self { ssid, publisher }) + } + } +} + +impl Drop for DirectAp { + fn drop(&mut self) { + #[cfg(windows)] + { + let _ = self.publisher.Stop(); + } + } +} diff --git a/windows/src/main.rs b/windows/src/main.rs new file mode 100644 index 0000000..31e0f13 --- /dev/null +++ b/windows/src/main.rs @@ -0,0 +1,736 @@ +mod direct_ap; +mod optical_cache; +mod pairing; +mod protocol; +mod qr; +mod receiver; + +use eframe::egui::{self, FontData, FontDefinitions, FontFamily, TextureHandle, TextureOptions}; +use optical_cache::OpticalPrefetcher; +use pairing::{PairingPayload, WifiCredentials}; +use protocol::{hex_sha256, TransferSource}; +use receiver::{ReceiverEvent, ReceiverServer}; +use std::{ + path::{Path, PathBuf}, + sync::{mpsc, Arc}, + time::{Duration, Instant}, +}; + +const DEFAULT_CHUNK_SIZE: u16 = 900; +const UI_FONT_NAME: &str = "qft-ui"; +const APP_VERSION: &str = "0.3.0-rc3"; + +fn main() -> eframe::Result { + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("QFT · 超速二维码文件传输") + .with_inner_size([1040.0, 800.0]) + .with_min_inner_size([800.0, 640.0]), + ..Default::default() + }; + eframe::run_native( + "QFT", + options, + Box::new(|cc| Ok(Box::new(QftApp::new(cc)))), + ) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Screen { + Home, + OpticalSend, + PhoneToPc, +} + +struct OpticalState { + source: Option>, + prefetch: Option, + texture: Option, + page_index: u32, + round: u64, + playing: bool, + fps: f32, + lanes: usize, + cache_mib: usize, + last_advance: Instant, + fps_window_started: Instant, + displayed_in_window: u32, + actual_page_fps: f64, + status: String, +} + +struct ReceiveState { + save_dir: Option, + use_direct_ap: bool, + server: Option, + direct_ap: Option, + events: Option>, + pair_texture: Option, + session_token: String, + status: String, + connected_device: String, + current_file: String, + received: u64, + total: u64, + last_saved: String, + last_sha256: String, + transfer_started: Option, + rate_bps: f64, +} + +struct QftApp { + screen: Screen, + font_status: String, + local_device: String, + optical: OpticalState, + receive: ReceiveState, +} + +impl QftApp { + fn new(cc: &eframe::CreationContext<'_>) -> Self { + cc.egui_ctx.set_pixels_per_point(1.0); + install_visuals(&cc.egui_ctx); + let font_status = match install_ttf_font(&cc.egui_ctx) { + Ok(path) => format!("字体:{}", path.display()), + Err(message) => format!("字体加载失败:{message}"), + }; + Self { + screen: Screen::Home, + font_status, + local_device: protocol::local_device_name(), + optical: OpticalState { + source: None, + prefetch: None, + texture: None, + page_index: 0, + round: 0, + playing: false, + fps: 60.0, + lanes: 4, + cache_mib: 384, + last_advance: Instant::now(), + fps_window_started: Instant::now(), + displayed_in_window: 0, + actual_page_fps: 0.0, + status: "选择文件后开始光学发送。默认 4 码/页 · 60 FPS,缓存不足时会自动停在当前页等待。".into(), + }, + receive: ReceiveState { + save_dir: None, + use_direct_ap: true, + server: None, + direct_ap: None, + events: None, + pair_texture: None, + session_token: String::new(), + status: "先选择接收文件夹,然后启动接收。".into(), + connected_device: "等待 Android 扫码".into(), + current_file: "—".into(), + received: 0, + total: 0, + last_saved: "—".into(), + last_sha256: String::new(), + transfer_started: None, + rate_bps: 0.0, + }, + } + } + + fn header(&mut self, ui: &mut egui::Ui) { + ui.horizontal(|ui| { + ui.heading("QFT"); + ui.label(format!("v{APP_VERSION}")); + ui.separator(); + ui.label("扫码配对 · 本地直传 · 光学零网络"); + let space = (ui.available_width() - 150.0).max(0.0); + ui.add_space(space); + if self.screen != Screen::Home && ui.button("← 返回首页").clicked() { + match self.screen { + Screen::PhoneToPc => self.stop_receiver(), + Screen::OpticalSend => { self.optical.playing = false; self.optical.prefetch = None; }, + Screen::Home => {} + } + self.screen = Screen::Home; + } + }); + ui.separator(); + } + + fn home_ui(&mut self, ui: &mut egui::Ui) { + ui.add_space(22.0); + ui.vertical_centered(|ui| { + ui.heading("选择传输方向"); + ui.label("两个方向采用不同链路,让速度、兼容性和“无需外网”同时成立。") + }); + ui.add_space(24.0); + + ui.columns(2, |cols| { + cols[0].group(|ui| { + ui.set_min_height(300.0); + ui.vertical_centered(|ui| { + ui.add_space(22.0); + ui.heading("电脑 → Android"); + ui.label("光学传输"); + ui.add_space(12.0); + ui.label("文件只经过:电脑屏幕 → 手机摄像头"); + ui.label("不使用 Wi-Fi / 蓝牙 / 局域网 / 外网"); + ui.add_space(24.0); + if ui.add_sized([220.0, 46.0], egui::Button::new("选择文件并开始光传")).clicked() { + self.screen = Screen::OpticalSend; + } + }); + }); + cols[1].group(|ui| { + ui.set_min_height(300.0); + ui.vertical_centered(|ui| { + ui.add_space(22.0); + ui.heading("Android → 电脑"); + ui.label("扫码直连"); + ui.add_space(12.0); + ui.label("电脑创建临时 QFT Wi-Fi Direct AP"); + ui.label("Android 扫码配网后高速上传到指定文件夹"); + ui.add_space(24.0); + if ui.add_sized([220.0, 46.0], egui::Button::new("电脑接收手机文件")).clicked() { + self.screen = Screen::PhoneToPc; + } + }); + }); + }); + ui.add_space(18.0); + ui.group(|ui| { + ui.label(format!("本机设备:{}", self.local_device)); + ui.small(&self.font_status); + }); + } + + fn optical_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + if self.optical.playing && self.optical.source.is_some() { + let interval = Duration::from_secs_f32(1.0 / self.optical.fps.max(1.0)); + if self.optical.last_advance.elapsed() >= interval { + self.optical.last_advance = Instant::now(); + self.optical_advance(ctx); + } + // Keep the UI scheduler hot enough for a 60 Hz display without busy-spinning. + ctx.request_repaint_after((interval / 3).max(Duration::from_millis(1))); + } + + ui.horizontal_wrapped(|ui| { + ui.heading("电脑 → Android · 光学极速模式"); + ui.separator(); + ui.label("屏幕 → 摄像头 · 0 网络"); + }); + ui.add_space(8.0); + + ui.group(|ui| { + ui.horizontal_wrapped(|ui| { + if ui.button("选择文件").clicked() { self.optical_pick_file(ctx); } + ui.label("刷新率"); + ui.add(egui::Slider::new(&mut self.optical.fps, 1.0..=60.0).suffix(" FPS").step_by(1.0)); + if ui.small_button("15").clicked() { self.optical.fps = 15.0; } + if ui.small_button("30").clicked() { self.optical.fps = 30.0; } + if ui.small_button("60").clicked() { self.optical.fps = 60.0; } + if ui.small_button("极速预设").clicked() { + self.optical.fps = 60.0; + self.optical.lanes = 4; + self.optical.cache_mib = 384; + self.optical.playing = false; + self.restart_optical_pipeline(); + let _ = self.optical_render_first(ctx); + } + }); + + let old_lanes = self.optical.lanes; + let old_cache = self.optical.cache_mib; + ui.horizontal_wrapped(|ui| { + ui.label("视觉并行"); + ui.radio_value(&mut self.optical.lanes, 1, "1 码/页 · 兼容"); + ui.radio_value(&mut self.optical.lanes, 4, "4 码/页 · 极速"); + ui.separator(); + ui.label("预编码缓存"); + ui.add(egui::Slider::new(&mut self.optical.cache_mib, 64..=optical_cache::MAX_MANAGED_CACHE_MIB) + .suffix(" MiB").step_by(64.0)); + }); + ui.small(format!( + "QFT 只允许预编码缓存使用最多 {} MiB,为进程/GPU/系统缓冲预留空间,目标整进程不超过约 {} MiB。", + optical_cache::MAX_MANAGED_CACHE_MIB, optical_cache::HARD_PROCESS_BUDGET_MIB + )); + if old_lanes != self.optical.lanes || old_cache != self.optical.cache_mib { + self.optical.playing = false; + self.restart_optical_pipeline(); + let _ = self.optical_render_first(ctx); + } + + let enabled = self.optical.source.is_some(); + ui.horizontal_wrapped(|ui| { + if ui.add_enabled(enabled, egui::Button::new(if self.optical.playing { "暂停" } else { "开始播放" })).clicked() { + if !self.optical.playing && self.optical.prefetch.is_none() { + self.restart_optical_pipeline(); + } + self.optical.playing = !self.optical.playing; + self.optical.last_advance = Instant::now(); + self.optical.fps_window_started = Instant::now(); + self.optical.displayed_in_window = 0; + } + if ui.add_enabled(enabled, egui::Button::new("回到第 1 页")).clicked() { + self.optical.playing = false; + self.restart_optical_pipeline(); + let _ = self.optical_render_first(ctx); + } + }); + }); + + ui.add_space(8.0); + if let Some(source) = self.optical.source.as_ref() { + let m = &source.manifest; + let pages = source.total_pages(self.optical.lanes); + let logical_fps = self.optical.fps as f64 * self.optical.lanes as f64; + let payload_rate = logical_fps * m.chunk_size as f64; + ui.columns(3, |cols| { + cols[0].group(|ui| { + ui.small("传输"); + ui.heading(format!("{:.0} FPS", self.optical.fps)); + ui.label(format!("{} 码/页 · {:.0} 逻辑帧/s", self.optical.lanes, logical_fps)); + }); + cols[1].group(|ui| { + ui.small("实测显示"); + ui.heading(format!("{:.1} 页/s", self.optical.actual_page_fps)); + ui.label(format!("理论载荷 ≈ {}/s", human_bytes(payload_rate as u64))); + }); + cols[2].group(|ui| { + ui.small("内存策略"); + ui.heading(format!("{} MiB", self.optical.cache_mib)); + let cap = self.optical.prefetch.as_ref().map(|p| p.capacity_pages).unwrap_or(0); + let page_mib = self.optical.prefetch.as_ref().map(|p| p.estimated_page_mib).unwrap_or(0.0); + ui.label(format!("预编码最多 {cap} 页 · {page_mib:.1} MiB/页 · 定位读取")); + }); + }); + ui.add_space(6.0); + ui.label(format!("传输设备:{} → Android 光学接收端", m.sender_device)); + ui.label(format!("文件:{} · {}", m.file_name, human_bytes(m.file_size))); + ui.small(format!("源路径:{}", source.path().display())); + ui.label(format!("数据块:{} · 当前页:{}/{} · 完整轮次:{}", m.total_chunks, self.optical.page_index + 1, pages, self.optical.round)); + ui.small(format!("SHA-256:{}", hex_sha256(&m.sha256))); + } + ui.label(&self.optical.status); + ui.separator(); + if let Some(texture) = &self.optical.texture { + let avail = ui.available_size(); + let side = avail.x.min(avail.y).min(680.0).max(320.0); + ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); }); + } else { + ui.vertical_centered(|ui| { + ui.add_space(100.0); + ui.heading("请选择一个文件"); + ui.label("极速模式会在后台并行预编码二维码;手机仍可处于飞行模式。") + }); + } + } + + fn receive_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + self.poll_receiver_events(); + ctx.request_repaint_after(Duration::from_millis(100)); + + ui.horizontal_wrapped(|ui| { + ui.heading("Android → 电脑 · 扫码直连"); + ui.separator(); + ui.label("UDP 快速发现 · 4/8/16 MiB 自适应分块 · 最高 8 路并行 · 不经过外网"); + }); + ui.add_space(10.0); + let running = self.receive.server.is_some(); + + ui.group(|ui| { + ui.heading("1 · 保存位置"); + ui.horizontal_wrapped(|ui| { + if ui.add_enabled(!running, egui::Button::new("选择接收文件夹")).clicked() { + if let Some(dir) = rfd::FileDialog::new().pick_folder() { + self.receive.save_dir = Some(dir); + self.receive.status = "保存位置已选择,可以启动接收。".into(); + } + } + ui.label(self.receive.save_dir.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| "尚未选择".into())); + }); + }); + ui.add_space(8.0); + + ui.group(|ui| { + ui.heading("2 · 连接方式"); + ui.add_enabled_ui(!running, |ui| { + ui.radio_value(&mut self.receive.use_direct_ap, true, "QFT Direct(推荐)· Windows 自动创建临时 Wi-Fi Direct AP"); + ui.radio_value(&mut self.receive.use_direct_ap, false, "当前局域网(备用)· 手机和电脑已经在同一 Wi-Fi/LAN"); + }); + if self.receive.use_direct_ap { + ui.small("Android 10+ 使用 WifiNetworkSpecifier;Android 7~9 使用兼容配网。连接后先 UDP 广播发现,再并行探测网关/IP,避免“已连 Wi-Fi 找不到电脑”。"); + if !running && ui.small_button("重置 QFT Direct 网络身份").clicked() { + match pairing::reset_direct_ap_credentials() { + Ok(()) => self.receive.status = "QFT Direct 网络身份已重置;下次启动接收会生成新的 SSID/密码,Android 需要重新批准一次。".into(), + Err(e) => self.receive.status = format!("重置 QFT Direct 网络身份失败:{e:#}"), + } + } + } else { + ui.small("二维码不携带 Wi-Fi 密码;Android 会先 UDP 快速发现电脑,再并行探测二维码内的本地 IP。"); + } + if running { ui.small("接收运行中,停止接收后才能修改保存目录或连接方式。"); } + }); + ui.add_space(8.0); + + ui.group(|ui| { + ui.heading("3 · 启动并扫码"); + ui.horizontal(|ui| { + if ui.add_enabled(!running && self.receive.save_dir.is_some(), egui::Button::new("启动接收并生成二维码")).clicked() { + self.start_receiver(ctx); + } + if ui.add_enabled(running, egui::Button::new("停止接收")).clicked() { + self.stop_receiver(); + } + }); + ui.label(&self.receive.status); + }); + + if self.receive.server.is_some() { + ui.add_space(10.0); + ui.columns(2, |cols| { + cols[0].group(|ui| { + ui.heading("手机扫码 · QFTPAIR2"); + if let Some(texture) = &self.receive.pair_texture { + let side = ui.available_width().min(420.0).max(260.0); + ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); }); + } + if let Some(ap) = &self.receive.direct_ap { + ui.label(format!("临时网络:{}", ap.ssid)); + ui.small("网络身份会在这台电脑上复用以减少重复确认;每次接收仍会生成新的会话 Token。"); + } + if !self.receive.session_token.is_empty() { + let short = &self.receive.session_token[..10.min(self.receive.session_token.len())]; + ui.small(format!("临时会话:{short}… · 停止接收后立即失效")); + } + }); + cols[1].group(|ui| { + ui.heading("接收状态 · Parallel v2"); + ui.label(format!("电脑:{}", self.local_device)); + ui.label(format!("手机:{}", self.receive.connected_device)); + ui.separator(); + ui.label(format!("当前文件:{}", self.receive.current_file)); + let fraction = if self.receive.total == 0 { 0.0 } else { self.receive.received as f32 / self.receive.total as f32 }; + ui.add(egui::ProgressBar::new(fraction.clamp(0.0, 1.0)).show_percentage()); + ui.label(format!("已接收:{} / {}", human_bytes(self.receive.received), human_bytes(self.receive.total))); + if self.receive.rate_bps > 1.0 { + let eta = if self.receive.total > self.receive.received { + (self.receive.total - self.receive.received) as f64 / self.receive.rate_bps + } else { 0.0 }; + ui.label(format!("速度:{}/s · 预计剩余:{}", human_bytes(self.receive.rate_bps as u64), human_duration(eta))); + } + ui.separator(); + ui.label(format!("最近保存:{}", self.receive.last_saved)); + if !self.receive.last_sha256.is_empty() { ui.small(format!("SHA-256:{}", self.receive.last_sha256)); } + }); + }); + } + } + + fn optical_pick_file(&mut self, ctx: &egui::Context) { + let Some(path) = rfd::FileDialog::new().pick_file() else { return }; + match TransferSource::open(&path, DEFAULT_CHUNK_SIZE) { + Ok(source) => { + self.optical.source = Some(Arc::new(source)); + self.optical.playing = false; + self.optical.actual_page_fps = 0.0; + self.restart_optical_pipeline(); + if let Err(e) = self.optical_render_first(ctx) { + self.optical.status = format!("生成二维码失败:{e:#}"); + } else { + self.optical.status = "文件已载入。默认 4 码/页 · 60 FPS;低端手机若有效 QR/s 明显偏低,可降到 30 FPS。".into(); + } + } + Err(e) => self.optical.status = format!("读取文件失败:{e:#}"), + } + } + + fn optical_canvas_side(&self) -> usize { + if self.optical.lanes == 4 { 960 } else { 760 } + } + + fn restart_optical_pipeline(&mut self) { + self.optical.prefetch = None; + self.optical.page_index = 0; + self.optical.round = 0; + let Some(source) = self.optical.source.clone() else { return }; + self.optical.prefetch = Some(OpticalPrefetcher::start( + source, + self.optical.lanes, + self.optical_canvas_side(), + self.optical.cache_mib, + )); + } + + fn optical_render_first(&mut self, ctx: &egui::Context) -> anyhow::Result<()> { + let Some(source) = self.optical.source.as_ref() else { return Ok(()) }; + let texts = source.text_page(0, self.optical.lanes)?; + let image = qr::render_qr_grid(&texts, self.optical_canvas_side())?; + self.set_optical_texture(ctx, image); + self.optical.page_index = 0; + self.optical.round = 0; + Ok(()) + } + + fn set_optical_texture(&mut self, ctx: &egui::Context, image: egui::ColorImage) { + if let Some(texture) = self.optical.texture.as_mut() { + // Reuse one GPU texture instead of allocating/freeing a texture ID + // for every 60 Hz optical page. This materially reduces GPU/driver + // churn and keeps the presentation path deterministic. + texture.set(image, TextureOptions::NEAREST); + } else { + self.optical.texture = Some(ctx.load_texture( + "qft-optical-frame", image, TextureOptions::NEAREST, + )); + } + } + + fn optical_advance(&mut self, ctx: &egui::Context) { + let next = match self.optical.prefetch.as_ref() { + Some(prefetch) => prefetch.try_next(), + None => { + self.restart_optical_pipeline(); + return; + } + }; + match next { + Ok(page) => { + self.set_optical_texture(ctx, page.image); + self.optical.page_index = page.page_index; + self.optical.round = page.round; + self.optical.displayed_in_window = self.optical.displayed_in_window.saturating_add(1); + let elapsed = self.optical.fps_window_started.elapsed(); + if elapsed >= Duration::from_secs(1) { + self.optical.actual_page_fps = self.optical.displayed_in_window as f64 / elapsed.as_secs_f64().max(0.001); + self.optical.displayed_in_window = 0; + self.optical.fps_window_started = Instant::now(); + } + self.optical.status = if self.optical.actual_page_fps + 3.0 < self.optical.fps as f64 && self.optical.actual_page_fps > 1.0 { + "实际页面速率低于目标:可降低 FPS 或把缓存调高;文件数据仍会循环补帧。".into() + } else { + "正在光学发送 · 4 码模式会把一页拆成四个独立 QR 并行解码。".into() + }; + } + Err(std::sync::mpsc::TryRecvError::Empty) => { + self.optical.status = "预编码缓存正在补充,暂缓换页以避免显示空帧。".into(); + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.optical.playing = false; + self.optical.status = "光学预编码线程已停止,请重新选择文件。".into(); + } + } + } + + fn start_receiver(&mut self, ctx: &egui::Context) { + let Some(save_dir) = self.receive.save_dir.clone() else { return }; + self.stop_receiver(); + self.receive.status = "正在初始化接收服务…".into(); + let token = pairing::new_session_token(); + let (tx, rx) = mpsc::channel(); + let server = match ReceiverServer::start(save_dir, token.clone(), tx) { + Ok(v) => v, + Err(e) => { self.receive.status = format!("接收服务启动失败:{e:#}"); return; } + }; + + let mut direct_ap = None; + let wifi = if self.receive.use_direct_ap { + let (ssid, passphrase) = match pairing::load_or_create_direct_ap_credentials(&self.local_device) { + Ok(v) => v, + Err(e) => { + drop(server); + self.receive.status = format!("读取 QFT Direct 配网身份失败:{e:#}"); + return; + } + }; + match direct_ap::DirectAp::start(ssid.clone(), passphrase.clone()) { + Ok(ap) => { + direct_ap = Some(ap); + Some(WifiCredentials { ssid, passphrase, security: "WPA2".into() }) + } + Err(e) => { + drop(server); + self.receive.status = format!("QFT Direct 启动失败:{e:#}\n可切换到“当前局域网”备用模式。 "); + return; + } + } + } else { None }; + + // Give the virtual adapter a moment to appear before enumerating addresses. + if direct_ap.is_some() { std::thread::sleep(Duration::from_millis(250)); } + let payload = PairingPayload { + v: 2, + session: token.clone(), + pc_name: self.local_device.clone(), + transport: "http-parallel-v2".into(), + port: server.port, + endpoints: pairing::local_ipv4_endpoints(server.port), + wifi, + }; + let pair_text = match payload.encode_text() { + Ok(v) => v, + Err(e) => { self.receive.status = format!("配对信息生成失败:{e:#}"); return; } + }; + let image = match qr::render_pair_qr(&pair_text, 520) { + Ok(v) => v, + Err(e) => { self.receive.status = format!("配对二维码生成失败:{e:#}"); return; } + }; + + let receiver_port = server.port; + self.receive.server = Some(server); + self.receive.direct_ap = direct_ap; + self.receive.events = Some(rx); + self.receive.pair_texture = Some(ctx.load_texture("qft-pair-code", image, TextureOptions::NEAREST)); + self.receive.session_token = token; + self.receive.connected_device = "等待 Android 扫码".into(); + self.receive.current_file = "—".into(); + self.receive.received = 0; + self.receive.total = 0; + self.receive.last_saved = "—".into(); + self.receive.last_sha256.clear(); + self.receive.transfer_started = None; + self.receive.rate_bps = 0.0; + self.receive.status = if self.receive.use_direct_ap { + format!("接收已就绪 · TCP {} · UDP 发现 {}。Android 扫码后会自动配网并快速发现电脑。", receiver_port, receiver::DISCOVERY_PORT) + } else { + format!("接收已就绪 · TCP {} · UDP 发现 {}。Android 扫码后会自动发现同一局域网电脑。", receiver_port, receiver::DISCOVERY_PORT) + }; + } + + fn stop_receiver(&mut self) { + self.receive.events = None; + self.receive.server = None; + self.receive.direct_ap = None; + self.receive.pair_texture = None; + self.receive.session_token.clear(); + self.receive.connected_device = "等待 Android 扫码".into(); + self.receive.current_file = "—".into(); + self.receive.received = 0; + self.receive.total = 0; + self.receive.transfer_started = None; + self.receive.rate_bps = 0.0; + self.receive.status = "接收已停止。".into(); + } + + fn poll_receiver_events(&mut self) { + let mut pending = Vec::new(); + if let Some(rx) = &self.receive.events { + while let Ok(event) = rx.try_recv() { pending.push(event); } + } + for event in pending { + match event { + ReceiverEvent::ClientConnected { device } => { + self.receive.connected_device = device; + self.receive.status = "Android 已连接到电脑。可以开始发送文件。".into(); + } + ReceiverEvent::UploadStarted { device, file_name, size } => { + self.receive.connected_device = device; + self.receive.current_file = file_name; + self.receive.received = 0; + self.receive.total = size; + self.receive.transfer_started = Some(Instant::now()); + self.receive.rate_bps = 0.0; + self.receive.status = "正在接收文件…".into(); + } + ReceiverEvent::UploadProgress { device, file_name, received, size } => { + self.receive.connected_device = device; + self.receive.current_file = file_name; + self.receive.received = received; + self.receive.total = size; + if let Some(started) = self.receive.transfer_started { + let secs = started.elapsed().as_secs_f64().max(0.001); + self.receive.rate_bps = received as f64 / secs; + } + } + ReceiverEvent::UploadCompleted { device, file_name, saved_path, sha256 } => { + self.receive.connected_device = device; + self.receive.current_file = file_name; + self.receive.received = self.receive.total; + self.receive.last_saved = saved_path.display().to_string(); + self.receive.last_sha256 = sha256; + if let Some(started) = self.receive.transfer_started { + let secs = started.elapsed().as_secs_f64().max(0.001); + self.receive.rate_bps = self.receive.total as f64 / secs; + } + self.receive.status = "文件接收完成。二维码会继续保持有效,可继续发送其他文件。".into(); + } + ReceiverEvent::Error(message) => self.receive.status = message, + } + } + } +} + +impl eframe::App for QftApp { + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + let ctx = ui.ctx().clone(); + ui.spacing_mut().item_spacing = egui::vec2(10.0, 10.0); + ui.spacing_mut().button_padding = egui::vec2(14.0, 8.0); + egui::CentralPanel::default().show(ui, |ui| { + self.header(ui); + match self.screen { + Screen::Home => self.home_ui(ui), + Screen::OpticalSend => self.optical_ui(ui, &ctx), + Screen::PhoneToPc => self.receive_ui(ui, &ctx), + } + }); + } +} + +fn install_visuals(ctx: &egui::Context) { + // eframe/egui 0.35 no longer exposes Context::style()/set_style(). + // Keep theme initialization here; per-UI spacing is applied in App::ui. + ctx.set_visuals(egui::Visuals::dark()); +} + +fn install_ttf_font(ctx: &egui::Context) -> Result { + let font_path = find_ttf_font().ok_or_else(|| { + "未找到可用 TTF。请把支持中文的字体复制到 windows/assets/qft-ui.ttf,或设置 QFT_FONT_PATH。".to_owned() + })?; + let bytes = std::fs::read(&font_path).map_err(|e| format!("读取 {} 失败:{e}", font_path.display()))?; + let mut fonts = FontDefinitions::default(); + fonts.font_data.insert(UI_FONT_NAME.to_owned(), Arc::new(FontData::from_owned(bytes))); + fonts.families.entry(FontFamily::Proportional).or_default().insert(0, UI_FONT_NAME.to_owned()); + fonts.families.entry(FontFamily::Monospace).or_default().insert(0, UI_FONT_NAME.to_owned()); + ctx.set_fonts(fonts); + Ok(font_path) +} + +fn find_ttf_font() -> Option { + let mut candidates = Vec::::new(); + if let Ok(explicit) = std::env::var("QFT_FONT_PATH") { + if !explicit.trim().is_empty() { candidates.push(PathBuf::from(explicit)); } + } + if let Ok(exe) = std::env::current_exe() { + if let Some(dir) = exe.parent() { + candidates.push(dir.join("qft-ui.ttf")); + candidates.push(dir.join("assets").join("qft-ui.ttf")); + } + } + candidates.push(PathBuf::from("assets").join("qft-ui.ttf")); + if cfg!(target_os = "windows") { + candidates.extend([ + PathBuf::from(r"C:\Windows\Fonts\simhei.ttf"), + PathBuf::from(r"C:\Windows\Fonts\Deng.ttf"), + PathBuf::from(r"C:\Windows\Fonts\msyh.ttf"), + ]); + } + candidates.into_iter().find(|path| is_ttf_file(path.as_path())) +} + +fn is_ttf_file(path: &Path) -> bool { + path.is_file() && path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("ttf")) +} + +fn human_duration(seconds: f64) -> String { + if !seconds.is_finite() || seconds <= 0.5 { return "<1 秒".into(); } + let total = seconds.ceil() as u64; + let minutes = total / 60; + let secs = total % 60; + if minutes > 0 { format!("{minutes} 分 {secs} 秒") } else { format!("{secs} 秒") } +} + +fn human_bytes(v: u64) -> String { + const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; + let mut n = v as f64; + let mut i = 0usize; + while n >= 1024.0 && i < UNITS.len() - 1 { n /= 1024.0; i += 1; } + if i == 0 { format!("{} {}", v, UNITS[i]) } else { format!("{n:.2} {}", UNITS[i]) } +} diff --git a/windows/src/optical_cache.rs b/windows/src/optical_cache.rs new file mode 100644 index 0000000..eb4f9de --- /dev/null +++ b/windows/src/optical_cache.rs @@ -0,0 +1,128 @@ +use crate::{protocol::TransferSource, qr}; +use eframe::egui::ColorImage; +use rayon::prelude::*; +use std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::{self, Receiver, TryRecvError, TrySendError}, + Arc, + }, + thread::{self, JoinHandle}, + time::Duration, +}; + +/// Keep the managed pre-render cache comfortably below the user's 1.1 GiB +/// whole-process ceiling. egui, GPU staging, Rust stacks and OS buffers still +/// need headroom, so QFT never intentionally reserves the entire 1.1 GiB. +pub const HARD_PROCESS_BUDGET_MIB: usize = 1100; +pub const MAX_MANAGED_CACHE_MIB: usize = 768; +const MIN_CACHE_MIB: usize = 64; +const MAX_CACHE_PAGES: usize = 192; +const PREENCODE_BATCH: usize = 8; + +pub struct EncodedPage { + pub page_index: u32, + pub round: u64, + pub image: ColorImage, +} + +pub struct OpticalPrefetcher { + rx: Receiver, + stop: Arc, + thread: Option>, + pub capacity_pages: usize, + pub cache_mib: usize, + pub estimated_page_mib: f64, +} + +impl OpticalPrefetcher { + pub fn start( + source: Arc, + lanes: usize, + canvas_side: usize, + requested_cache_mib: usize, + ) -> Self { + let cache_mib = requested_cache_mib.clamp(MIN_CACHE_MIB, MAX_MANAGED_CACHE_MIB); + // ColorImage uses Color32 pixels: approximately four bytes per pixel. + let bytes_per_page = canvas_side.saturating_mul(canvas_side).saturating_mul(4).max(1); + let budget_bytes = cache_mib.saturating_mul(1024 * 1024); + let capacity_pages = (budget_bytes / bytes_per_page).clamp(4, MAX_CACHE_PAGES); + let estimated_page_mib = bytes_per_page as f64 / (1024.0 * 1024.0); + let (tx, rx) = mpsc::sync_channel::(capacity_pages); + let stop = Arc::new(AtomicBool::new(false)); + let stop_worker = stop.clone(); + + // Render several consecutive pages in one Rayon batch. At 4 QR/page this + // lets all CPU cores work across both pages and QR lanes and is much more + // likely to keep a 60 Hz presentation queue full than a single-page loop. + let thread = thread::spawn(move || { + let total_pages = source.total_pages(lanes).max(1); + let mut next_page = 0u32; + let mut next_round = 0u64; + while !stop_worker.load(Ordering::Relaxed) { + let mut plan = Vec::with_capacity(PREENCODE_BATCH); + for order in 0..PREENCODE_BATCH { + plan.push((order, next_page, next_round)); + next_page += 1; + if next_page >= total_pages { + next_page = 0; + next_round = next_round.saturating_add(1); + } + } + + let mut rendered: Vec<(usize, EncodedPage)> = plan + .into_par_iter() + .filter_map(|(order, page_index, round)| { + if stop_worker.load(Ordering::Relaxed) { return None; } + let texts = source.text_page(page_index, lanes).ok()?; + let image = qr::render_qr_grid(&texts, canvas_side).ok()?; + Some((order, EncodedPage { page_index, round, image })) + }) + .collect(); + rendered.sort_unstable_by_key(|(order, _)| *order); + + if rendered.is_empty() { + thread::sleep(Duration::from_millis(3)); + continue; + } + + // Reorder the parallel batch explicitly before queueing. + for (_, mut item) in rendered { + loop { + match tx.try_send(item) { + Ok(()) => break, + Err(TrySendError::Full(returned)) => { + item = returned; + if stop_worker.load(Ordering::Relaxed) { return; } + thread::sleep(Duration::from_millis(1)); + } + Err(TrySendError::Disconnected(_)) => return, + } + } + } + } + }); + + Self { + rx, + stop, + thread: Some(thread), + capacity_pages, + cache_mib, + estimated_page_mib, + } + } + + pub fn try_next(&self) -> Result { + self.rx.try_recv() + } +} + +impl Drop for OpticalPrefetcher { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(handle) = self.thread.take() { + let _ = handle.join(); + } + } +} diff --git a/windows/src/pairing.rs b/windows/src/pairing.rs new file mode 100644 index 0000000..bf682d6 --- /dev/null +++ b/windows/src/pairing.rs @@ -0,0 +1,178 @@ +use anyhow::{Context, Result}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use rand::RngCore; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::{ + fs, + net::{IpAddr, Ipv4Addr}, + path::PathBuf, +}; + +pub const PAIR_PREFIX: &str = "QFTPAIR2:"; + +#[derive(Clone, Debug)] +pub struct PairingPayload { + pub v: u8, + pub session: String, + pub pc_name: String, + pub transport: String, + pub port: u16, + pub endpoints: Vec, + pub wifi: Option, +} + +#[derive(Clone, Debug)] +pub struct WifiCredentials { + pub ssid: String, + pub passphrase: String, + pub security: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct DirectApIdentity { + version: u8, + ssid: String, + passphrase: String, +} + +impl PairingPayload { + /// v2 intentionally uses short JSON keys. The Direct-AP QR no longer carries + /// a long transport string/security object and only keeps a small endpoint + /// fallback list. This materially lowers QR density and speeds phone scan. + pub fn encode_text(&self) -> Result { + // Direct-AP pairing carries one short endpoint hint for the immediate + // happy path, while Android still treats the connected gateway + UDP + // discovery as authoritative fallbacks. One endpoint keeps QFTPAIR2 + // compact but avoids a full discovery round on common Windows APs. + let endpoints: Vec<&str> = if self.wifi.is_some() { + self.endpoints.iter().take(1).map(String::as_str).collect() + } else { + self.endpoints.iter().take(3).map(String::as_str).collect() + }; + let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase])); + let value = json!({ + "v": 2, + "s": self.session, + "n": self.pc_name, + "p": self.port, + "e": endpoints, + "w": wifi, + }); + let json = serde_json::to_vec(&value).context("serialize pairing payload")?; + Ok(format!("{PAIR_PREFIX}{}", URL_SAFE_NO_PAD.encode(json))) + } +} + +pub fn new_session_token() -> String { + let mut bytes = [0u8; 16]; + rand::rng().fill_bytes(&mut bytes); + URL_SAFE_NO_PAD.encode(bytes) +} + +/// Keep one random AP identity per Windows device so Android can remember the +/// user's approval for that exact local-only network. The AP itself is only +/// active while QFT receive mode is running; the file-transfer session token is +/// regenerated every time receive mode starts. +pub fn load_or_create_direct_ap_credentials(pc_name: &str) -> Result<(String, String)> { + let path = direct_ap_identity_path(); + if let Ok(bytes) = fs::read(&path) { + if let Ok(identity) = serde_json::from_slice::(&bytes) { + if identity.version == 1 + && !identity.ssid.trim().is_empty() + && (8..=63).contains(&identity.passphrase.len()) + { + return Ok((identity.ssid, identity.passphrase)); + } + } + } + + let (ssid, passphrase) = new_direct_ap_credentials(pc_name); + let identity = DirectApIdentity { + version: 1, + ssid: ssid.clone(), + passphrase: passphrase.clone(), + }; + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("创建 QFT 配置目录 {} 失败", parent.display()))?; + } + let tmp = path.with_extension("json.tmp"); + let json = serde_json::to_vec_pretty(&identity)?; + fs::write(&tmp, json) + .with_context(|| format!("保存 QFT Direct 身份 {} 失败", tmp.display()))?; + if path.exists() { + let _ = fs::remove_file(&path); + } + fs::rename(&tmp, &path) + .with_context(|| format!("完成 QFT Direct 身份保存 {} 失败", path.display()))?; + Ok((ssid, passphrase)) +} + +pub fn reset_direct_ap_credentials() -> Result<()> { + let path = direct_ap_identity_path(); + if path.exists() { + fs::remove_file(&path) + .with_context(|| format!("删除 QFT Direct 身份 {} 失败", path.display()))?; + } + Ok(()) +} + +fn direct_ap_identity_path() -> PathBuf { + if let Ok(root) = std::env::var("LOCALAPPDATA") { + if !root.trim().is_empty() { + return PathBuf::from(root).join("QFT").join("direct-ap.json"); + } + } + PathBuf::from(".qft").join("direct-ap.json") +} + +fn new_direct_ap_credentials(pc_name: &str) -> (String, String) { + let suffix = new_session_token(); + let suffix = &suffix[..6.min(suffix.len())]; + let base: String = pc_name + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .take(10) + .collect(); + let base = if base.is_empty() { "PC" } else { &base }; + let ssid = format!("QFT-{base}-{suffix}"); + + let mut random = [0u8; 12]; + rand::rng().fill_bytes(&mut random); + let password = URL_SAFE_NO_PAD.encode(random); + (ssid, password[..16.min(password.len())].to_owned()) +} + +pub fn local_ipv4_endpoints(port: u16) -> Vec { + let mut ips = Vec::::new(); + if let Ok(addrs) = if_addrs::get_if_addrs() { + for iface in addrs { + let IpAddr::V4(ip) = iface.ip() else { continue }; + if ip.is_loopback() || ip.is_unspecified() || ip.is_link_local() { + continue; + } + if !ips.contains(&ip) { + ips.push(ip); + } + } + } + + for fallback in [ + Ipv4Addr::new(192, 168, 137, 1), + Ipv4Addr::new(192, 168, 49, 1), + ] { + if !ips.contains(&fallback) { + ips.push(fallback); + } + } + ips.sort_by_key(|ip| { + if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 } + else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 } + else if ip.is_private() { 2 } + else { 3 } + }); + ips.into_iter() + .map(|ip| format!("http://{ip}:{port}")) + .collect() +} diff --git a/windows/src/protocol.rs b/windows/src/protocol.rs new file mode 100644 index 0000000..f4cccd4 --- /dev/null +++ b/windows/src/protocol.rs @@ -0,0 +1,274 @@ +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use crc32fast::hash as crc32; +use rand::RngCore; +use rayon::prelude::*; +use sha2::{Digest, Sha256}; +use std::{ + fs::File, + io::Read, + path::{Path, PathBuf}, +}; + +pub const PREFIX: &str = "QFT1:"; +pub const VERSION: u8 = 1; + +#[derive(Clone, Copy, Debug)] +#[repr(u8)] +pub enum FrameKind { + Manifest = 1, + Data = 2, + End = 3, +} + +#[derive(Clone, Debug)] +pub struct Manifest { + pub session_id: u64, + pub sender_device: String, + pub file_name: String, + pub file_size: u64, + pub chunk_size: u16, + pub total_chunks: u32, + pub sha256: [u8; 32], +} + +pub struct TransferSource { + path: PathBuf, + file: File, + pub manifest: Manifest, +} + +impl TransferSource { + pub fn open(path: impl AsRef, chunk_size: u16) -> Result { + if chunk_size == 0 { + bail!("chunk_size must be > 0"); + } + let path = path.as_ref().to_path_buf(); + let file = File::open(&path).context("open input file")?; + let file_size = file.metadata()?.len(); + let total_chunks_u64 = if file_size == 0 { + 0 + } else { + (file_size + chunk_size as u64 - 1) / chunk_size as u64 + }; + if total_chunks_u64 > u32::MAX as u64 { + bail!("file requires too many chunks"); + } + + // Keep a single read-only file handle and use positioned reads for each + // optical chunk. This avoids mapping/touching a multi-GB file into the + // process working set, so the bounded QR prefetch cache remains the + // dominant managed memory consumer. + let sha256 = hash_file_streaming(&file)?; + + let mut rng = rand::rng(); + let session_id = rng.next_u64(); + let file_name = path + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("qft.bin") + .to_owned(); + let sender_device = local_device_name(); + + Ok(Self { + path, + file, + manifest: Manifest { + session_id, + sender_device, + file_name, + file_size, + chunk_size, + total_chunks: total_chunks_u64 as u32, + sha256, + }, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn total_playlist_frames(&self) -> u32 { + self.manifest.total_chunks.saturating_add(2) + } + + pub fn total_pages(&self, lanes: usize) -> u32 { + let lanes = lanes.max(1) as u32; + let frames = self.total_playlist_frames(); + (frames + lanes - 1) / lanes + } + + /// Returns 1..=4 QFT text frames for one visual page. QR encodes are generated + /// in parallel by rayon; file bytes are read with positioned reads so workers + /// do not contend on a shared seek cursor and large files are not memory-mapped. + pub fn text_page(&self, page_index: u32, lanes: usize) -> Result> { + let lanes = lanes.clamp(1, 4); + let total = self.total_playlist_frames(); + let start = page_index.saturating_mul(lanes as u32); + if start >= total { + bail!("page index out of range"); + } + let indices: Vec = (0..lanes) + .map(|lane| start + lane as u32) + .filter(|idx| *idx < total) + .collect(); + indices + .into_par_iter() + .map(|idx| self.text_frame(idx)) + .collect() + } + + /// playlist_index: 0=manifest, 1..=N=data, N+1=end + pub fn text_frame(&self, playlist_index: u32) -> Result { + let n = self.manifest.total_chunks; + if playlist_index == 0 { + return Ok(encode_manifest(&self.manifest)); + } + if playlist_index >= 1 && playlist_index <= n { + return self.encode_data(playlist_index - 1); + } + if playlist_index == n + 1 { + return Ok(encode_frame( + FrameKind::End, + self.manifest.session_id, + 0, + n, + &[], + )); + } + bail!("playlist index out of range") + } + + fn encode_data(&self, seq: u32) -> Result { + let offset = seq as u64 * self.manifest.chunk_size as u64; + let remaining = self.manifest.file_size.saturating_sub(offset); + let len = remaining.min(self.manifest.chunk_size as u64) as usize; + let mut payload = vec![0u8; len]; + if len > 0 { + read_exact_at(&self.file, &mut payload, offset)?; + } + Ok(encode_frame( + FrameKind::Data, + self.manifest.session_id, + seq, + self.manifest.total_chunks, + &payload, + )) + } +} + +fn encode_manifest(m: &Manifest) -> String { + let name = m.file_name.as_bytes(); + let name_len = name.len().min(u16::MAX as usize) as u16; + let device = m.sender_device.as_bytes(); + let device_len = device.len().min(u16::MAX as usize) as u16; + let mut payload = Vec::with_capacity( + 8 + 2 + 32 + 2 + name_len as usize + 2 + device_len as usize, + ); + payload.extend_from_slice(&m.file_size.to_be_bytes()); + payload.extend_from_slice(&m.chunk_size.to_be_bytes()); + payload.extend_from_slice(&m.sha256); + payload.extend_from_slice(&name_len.to_be_bytes()); + payload.extend_from_slice(&name[..name_len as usize]); + payload.extend_from_slice(&device_len.to_be_bytes()); + payload.extend_from_slice(&device[..device_len as usize]); + encode_frame( + FrameKind::Manifest, + m.session_id, + 0, + m.total_chunks, + &payload, + ) +} + +pub fn encode_frame( + kind: FrameKind, + session_id: u64, + seq: u32, + total_chunks: u32, + payload: &[u8], +) -> String { + assert!(payload.len() <= u16::MAX as usize); + let mut binary = Vec::with_capacity(28 + payload.len()); + binary.extend_from_slice(b"QFT1"); + binary.push(VERSION); + binary.push(kind as u8); + binary.extend_from_slice(&session_id.to_be_bytes()); + binary.extend_from_slice(&seq.to_be_bytes()); + binary.extend_from_slice(&total_chunks.to_be_bytes()); + binary.extend_from_slice(&(payload.len() as u16).to_be_bytes()); + binary.extend_from_slice(payload); + let crc = crc32(&binary); + binary.extend_from_slice(&crc.to_be_bytes()); + format!("{PREFIX}{}", URL_SAFE_NO_PAD.encode(binary)) +} + +pub fn hex_sha256(bytes: &[u8; 32]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(64); + for &b in bytes { + out.push(HEX[(b >> 4) as usize] as char); + out.push(HEX[(b & 0x0f) as usize] as char); + } + out +} + +pub fn local_device_name() -> String { + let raw = std::env::var("COMPUTERNAME") + .or_else(|_| std::env::var("HOSTNAME")) + .unwrap_or_else(|_| "Windows-PC".to_owned()); + let cleaned: String = raw + .chars() + .filter(|ch| !ch.is_control()) + .take(64) + .collect(); + if cleaned.trim().is_empty() { + "Windows-PC".to_owned() + } else { + cleaned + } +} + +fn hash_file_streaming(file: &File) -> Result<[u8; 32]> { + let mut input = file.try_clone().context("clone input for sha256")?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 4 * 1024 * 1024]; + loop { + let n = input.read(&mut buf).context("read input for sha256")?; + if n == 0 { break; } + hasher.update(&buf[..n]); + } + Ok(hasher.finalize().into()) +} + +fn read_exact_at(file: &File, mut out: &mut [u8], mut offset: u64) -> Result<()> { + while !out.is_empty() { + let n = read_at_once(file, out, offset)?; + if n == 0 { bail!("unexpected EOF at offset {offset}"); } + offset = offset.saturating_add(n as u64); + let (_, rest) = out.split_at_mut(n); + out = rest; + } + Ok(()) +} + +#[cfg(windows)] +fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result { + use std::os::windows::fs::FileExt; + file.seek_read(out, offset) +} + +#[cfg(unix)] +fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result { + use std::os::unix::fs::FileExt; + file.read_at(out, offset) +} + +#[cfg(not(any(windows, unix)))] +fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result { + use std::io::{Seek, SeekFrom}; + let mut cloned = file.try_clone()?; + cloned.seek(SeekFrom::Start(offset))?; + cloned.read(out) +} diff --git a/windows/src/qr.rs b/windows/src/qr.rs new file mode 100644 index 0000000..349f1e5 --- /dev/null +++ b/windows/src/qr.rs @@ -0,0 +1,103 @@ +use anyhow::{Context, Result}; +use eframe::egui::ColorImage; +use qrcode::{types::Color, EcLevel, QrCode}; +use rayon::prelude::*; + +const QUIET_MODULES: usize = 4; + +/// Render exact black/white pixels with an explicit quiet zone. +pub fn render_qr(text: &str, scale: usize) -> Result { + let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L) + .context("QR payload too large")?; + let modules = code.width(); + let scale = scale.max(1); + let side_modules = modules + QUIET_MODULES * 2; + let side_px = side_modules * scale; + let gray = render_code_gray(&code, side_px); + Ok(ColorImage::from_gray([side_px, side_px], &gray)) +} + +/// Render 1..=4 independent QR symbols into one fixed-size optical page. +/// A 2x2 page quadruples the number of logical QFT frames presented per +/// display refresh while keeping every symbol standards-compliant. +pub fn render_qr_grid(texts: &[String], canvas_side: usize) -> Result { + let count = texts.len().clamp(1, 4); + if count == 1 { + return render_qr_fitted(&texts[0], canvas_side.max(320)); + } + + let canvas_side = canvas_side.max(640); + let gutter = (canvas_side / 64).clamp(12, 24); + let cell = (canvas_side - gutter * 3) / 2; + let rendered: Vec<(usize, Vec)> = texts[..count] + .par_iter() + .map(|text| render_qr_gray_fitted(text, cell)) + .collect::>>()?; + + let mut canvas = vec![255u8; canvas_side * canvas_side]; + for (index, (side, gray)) in rendered.into_iter().enumerate() { + let col = index % 2; + let row = index / 2; + let cell_x = gutter + col * (cell + gutter); + let cell_y = gutter + row * (cell + gutter); + let x0 = cell_x + (cell.saturating_sub(side)) / 2; + let y0 = cell_y + (cell.saturating_sub(side)) / 2; + for y in 0..side { + let dst = (y0 + y) * canvas_side + x0; + let src = y * side; + canvas[dst..dst + side].copy_from_slice(&gray[src..src + side]); + } + } + Ok(ColorImage::from_gray([canvas_side, canvas_side], &canvas)) +} + + +/// Pairing QR favors scan reliability over maximum capacity. QFTPAIR2 is kept +/// deliberately short, so medium error correction still yields a low-version +/// symbol that phones acquire faster at imperfect angles. +pub fn render_pair_qr(text: &str, target_side: usize) -> Result { + let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M) + .context("pair QR payload too large")?; + let modules = code.width() + QUIET_MODULES * 2; + let scale = (target_side / modules).max(1); + let side = modules * scale; + Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side))) +} + +pub fn render_qr_fitted(text: &str, target_side: usize) -> Result { + let (side, gray) = render_qr_gray_fitted(text, target_side)?; + Ok(ColorImage::from_gray([side, side], &gray)) +} + +fn render_qr_gray_fitted(text: &str, target_side: usize) -> Result<(usize, Vec)> { + let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L) + .context("QR payload too large")?; + let modules = code.width() + QUIET_MODULES * 2; + let scale = (target_side / modules).max(1); + let side = modules * scale; + Ok((side, render_code_gray(&code, side))) +} + +fn render_code_gray(code: &QrCode, side_px: usize) -> Vec { + let modules = code.width(); + let side_modules = modules + QUIET_MODULES * 2; + let scale = (side_px / side_modules).max(1); + let actual_side = side_modules * scale; + let mut gray = vec![255u8; actual_side * actual_side]; + let colors = code.to_colors(); + + for y in 0..modules { + for x in 0..modules { + if colors[y * modules + x] != Color::Dark { + continue; + } + let x0 = (x + QUIET_MODULES) * scale; + let y0 = (y + QUIET_MODULES) * scale; + for py in y0..y0 + scale { + let row = py * actual_side; + gray[row + x0..row + x0 + scale].fill(0); + } + } + } + gray +} diff --git a/windows/src/receiver.rs b/windows/src/receiver.rs new file mode 100644 index 0000000..9916f0e --- /dev/null +++ b/windows/src/receiver.rs @@ -0,0 +1,540 @@ +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use rand::RngCore; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::{ + collections::HashMap, + fs::{self, File, OpenOptions}, + io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}, + net::{TcpListener, TcpStream, UdpSocket}, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::Sender, + Arc, Mutex, + }, + thread::{self, JoinHandle}, + time::{Duration, Instant}, +}; + +pub const PREFERRED_PORT: u16 = 39393; +pub const DISCOVERY_PORT: u16 = 39392; +pub const PARALLEL_CHUNK_SIZE: u64 = 8 * 1024 * 1024; +const IO_BUFFER: usize = 1024 * 1024; + +#[derive(Clone, Debug)] +pub enum ReceiverEvent { + ClientConnected { device: String }, + UploadStarted { device: String, file_name: String, size: u64 }, + UploadProgress { device: String, file_name: String, received: u64, size: u64 }, + UploadCompleted { device: String, file_name: String, saved_path: PathBuf, sha256: String }, + Error(String), +} + +#[derive(Debug)] +struct UploadSession { + device: String, + file_name: String, + size: u64, + chunk_size: u64, + total_chunks: u32, + part_path: PathBuf, + final_path: PathBuf, + received: Vec, + received_bytes: u64, +} + +type SessionMap = Arc>>>>; + +pub struct ReceiverServer { + pub port: u16, + stop: Arc, + tcp_thread: Option>, + udp_thread: Option>, +} + +impl ReceiverServer { + pub fn start(save_dir: PathBuf, session_token: String, events: Sender) -> Result { + fs::create_dir_all(&save_dir).context("创建接收目录失败")?; + let listener = TcpListener::bind(("0.0.0.0", PREFERRED_PORT)) + .or_else(|_| TcpListener::bind(("0.0.0.0", 0))) + .context("启动本地接收端口失败")?; + let port = listener.local_addr()?.port(); + listener.set_nonblocking(true)?; + + let stop = Arc::new(AtomicBool::new(false)); + let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new())); + + let stop_tcp = stop.clone(); + let sessions_tcp = sessions.clone(); + let token_tcp = session_token.clone(); + let dir_tcp = save_dir.clone(); + let events_tcp = events.clone(); + let tcp_thread = thread::spawn(move || { + while !stop_tcp.load(Ordering::Relaxed) { + match listener.accept() { + Ok((stream, _)) => { + let dir = dir_tcp.clone(); + let token = token_tcp.clone(); + let tx = events_tcp.clone(); + let sessions = sessions_tcp.clone(); + thread::spawn(move || { + if let Err(e) = handle_client(stream, &dir, &token, &tx, &sessions) { + let _ = tx.send(ReceiverEvent::Error(format!("接收失败:{e:#}"))); + } + }); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(12)); + } + Err(e) => { + let _ = events_tcp.send(ReceiverEvent::Error(format!("监听端口失败:{e}"))); + break; + } + } + } + }); + + let stop_udp = stop.clone(); + let token_udp = session_token; + let udp_thread = thread::spawn(move || { + let socket = match UdpSocket::bind(("0.0.0.0", DISCOVERY_PORT)) { + Ok(v) => v, + Err(e) => { + let _ = events.send(ReceiverEvent::Error(format!( + "快速发现端口 {DISCOVERY_PORT} 不可用:{e}。仍可使用网关/IP 探测。" + ))); + return; + } + }; + let _ = socket.set_read_timeout(Some(Duration::from_millis(250))); + let expected = format!("QFTDISC2:{token_udp}"); + let response = format!("QFTHERE2:{token_udp}:{port}"); + let mut buf = [0u8; 512]; + while !stop_udp.load(Ordering::Relaxed) { + match socket.recv_from(&mut buf) { + Ok((n, peer)) => { + if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) { + let _ = socket.send_to(response.as_bytes(), peer); + } + } + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} + Err(_) => break, + } + } + }); + + Ok(Self { + port, + stop, + tcp_thread: Some(tcp_thread), + udp_thread: Some(udp_thread), + }) + } +} + +impl Drop for ReceiverServer { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(handle) = self.tcp_thread.take() { + let _ = handle.join(); + } + if let Some(handle) = self.udp_thread.take() { + let _ = handle.join(); + } + } +} + +fn handle_client( + mut stream: TcpStream, + save_dir: &Path, + token: &str, + events: &Sender, + sessions: &SessionMap, +) -> Result<()> { + stream.set_nodelay(true).ok(); + stream.set_read_timeout(Some(Duration::from_secs(120)))?; + stream.set_write_timeout(Some(Duration::from_secs(120)))?; + let cloned = stream.try_clone()?; + let mut reader = BufReader::with_capacity(64 * 1024, cloned); + + let mut request_line = String::new(); + reader.read_line(&mut request_line)?; + if request_line.len() > 8192 { bail!("请求行过长") } + let mut headers = HashMap::::new(); + loop { + let mut line = String::new(); + let n = reader.read_line(&mut line)?; + if n == 0 { bail!("连接提前关闭") } + if line == "\r\n" || line == "\n" { break } + if line.len() > 16 * 1024 { bail!("请求头过长") } + if let Some((k, v)) = line.split_once(':') { + headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned()); + } + } + + let mut parts = request_line.split_whitespace(); + let method = parts.next().unwrap_or(""); + let path = parts.next().unwrap_or(""); + + let supplied = headers.get("x-qft-token").map(String::as_str).unwrap_or(""); + if supplied != token { + return write_response(&mut stream, 403, "text/plain", b"invalid session"); + } + + let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned()); + let _ = events.send(ReceiverEvent::ClientConnected { device: device.clone() }); + + if method == "GET" && path == "/qft/ping" { + let body = json!({"ok": true, "protocol": 2, "parallel": true}).to_string(); + return write_response(&mut stream, 200, "application/json", body.as_bytes()); + } + + if method == "POST" && path == "/qft/upload/init" { + return init_parallel_upload(&mut stream, save_dir, &headers, &device, events, sessions); + } + + if method == "POST" && path.starts_with("/qft/upload/chunk/") { + return receive_parallel_chunk(&mut stream, &mut reader, path, &headers, events, sessions); + } + + if method == "POST" && path.starts_with("/qft/upload/finish/") { + return finish_parallel_upload(&mut stream, path, events, sessions); + } + + // Compatibility path for old clients and content providers that cannot seek. + if method == "POST" && path == "/qft/upload" { + return receive_legacy_stream(&mut stream, &mut reader, save_dir, &headers, &device, events); + } + + write_response(&mut stream, 404, "text/plain", b"not found") +} + +fn init_parallel_upload( + stream: &mut TcpStream, + save_dir: &Path, + headers: &HashMap, + device: &str, + events: &Sender, + sessions: &SessionMap, +) -> Result<()> { + let file_name = decode_header(headers.get("x-qft-filename")) + .map(sanitize_file_name) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "qft-upload.bin".to_owned()); + let size: u64 = headers.get("x-qft-size") + .context("缺少 X-QFT-Size")? + .parse().context("X-QFT-Size 无效")?; + let chunk_size = headers.get("x-qft-chunk-size") + .and_then(|v| v.parse::().ok()) + .map(|v| v.clamp(1024 * 1024, 16 * 1024 * 1024)) + .unwrap_or(PARALLEL_CHUNK_SIZE); + let total_chunks_u64 = if size == 0 { 0 } else { (size + chunk_size - 1) / chunk_size }; + if total_chunks_u64 > u32::MAX as u64 { bail!("文件分块数过大") } + let total_chunks = total_chunks_u64 as u32; + + let upload_id = random_id(); + let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?; + let final_path = unique_path_reserved(save_dir, &file_name, map.values()); + let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin"); + let part_path = final_path.with_file_name(format!("{final_name}.{upload_id}.qftpart")); + let part = File::create(&part_path) + .with_context(|| format!("创建临时文件 {}", part_path.display()))?; + part.set_len(size)?; + drop(part); + + let session = UploadSession { + device: device.to_owned(), + file_name: file_name.clone(), + size, + chunk_size, + total_chunks, + part_path, + final_path, + received: vec![false; total_chunks as usize], + received_bytes: 0, + }; + map.insert(upload_id.clone(), Arc::new(Mutex::new(session))); + drop(map); + + let _ = events.send(ReceiverEvent::UploadStarted { + device: device.to_owned(), + file_name, + size, + }); + let body = json!({ + "ok": true, + "upload_id": upload_id, + "chunk_size": chunk_size, + "total_chunks": total_chunks, + }).to_string(); + write_response(stream, 200, "application/json", body.as_bytes()) +} + +fn receive_parallel_chunk( + stream: &mut TcpStream, + reader: &mut BufReader, + path: &str, + headers: &HashMap, + events: &Sender, + sessions: &SessionMap, +) -> Result<()> { + let suffix = path.trim_start_matches("/qft/upload/chunk/"); + let (upload_id, index_text) = suffix.split_once('/').context("chunk 路径无效")?; + let index: u32 = index_text.parse().context("chunk index 无效")?; + let content_len: u64 = headers.get("content-length") + .context("缺少 Content-Length")? + .parse().context("Content-Length 无效")?; + + let session_arc = { + let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?; + map.get(upload_id).cloned().context("上传会话不存在或已完成")? + }; + + let (part_path, offset, expected_len, device, file_name, size, already) = { + let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?; + if index >= session.total_chunks { bail!("chunk index 越界") } + let offset = index as u64 * session.chunk_size; + let expected = (session.size - offset).min(session.chunk_size); + ( + session.part_path.clone(), + offset, + expected, + session.device.clone(), + session.file_name.clone(), + session.size, + session.received[index as usize], + ) + }; + if content_len != expected_len { bail!("chunk 长度不匹配:{content_len} != {expected_len}") } + + if already { + drain_exact(reader, content_len)?; + return write_response(stream, 200, "application/json", b"{\"ok\":true,\"duplicate\":true}"); + } + + let mut out = OpenOptions::new().write(true).open(&part_path)?; + out.seek(SeekFrom::Start(offset))?; + copy_exact(reader, &mut out, content_len)?; + out.flush()?; + + let received = { + let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?; + if !session.received[index as usize] { + session.received[index as usize] = true; + session.received_bytes = session.received_bytes.saturating_add(content_len); + } + session.received_bytes + }; + let _ = events.send(ReceiverEvent::UploadProgress { device, file_name, received, size }); + write_response(stream, 200, "application/json", b"{\"ok\":true}") +} + +fn finish_parallel_upload( + stream: &mut TcpStream, + path: &str, + events: &Sender, + sessions: &SessionMap, +) -> Result<()> { + let upload_id = path.trim_start_matches("/qft/upload/finish/"); + let session_arc = { + let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?; + map.get(upload_id).cloned().context("上传会话不存在或已完成")? + }; + + let (device, file_name, size, part_path, final_path) = { + let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?; + if session.received.iter().any(|v| !*v) { + let missing = session.received.iter().filter(|v| !**v).count(); + let body = json!({"ok": false, "missing": missing}).to_string(); + return write_response(stream, 409, "application/json", body.as_bytes()); + } + ( + session.device.clone(), session.file_name.clone(), session.size, + session.part_path.clone(), session.final_path.clone(), + ) + }; + + let sha = hash_file(&part_path)?; + if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") } + fs::rename(&part_path, &final_path).context("完成文件重命名失败")?; + { + let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?; + map.remove(upload_id); + } + let _ = events.send(ReceiverEvent::UploadCompleted { + device, file_name, saved_path: final_path, sha256: sha.clone(), + }); + let body = json!({"ok": true, "sha256": sha, "size": size}).to_string(); + write_response(stream, 200, "application/json", body.as_bytes()) +} + +fn receive_legacy_stream( + stream: &mut TcpStream, + reader: &mut BufReader, + save_dir: &Path, + headers: &HashMap, + device: &str, + events: &Sender, +) -> Result<()> { + let file_name = decode_header(headers.get("x-qft-filename")) + .map(sanitize_file_name) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "qft-upload.bin".to_owned()); + let size: u64 = headers.get("content-length") + .context("缺少 Content-Length")? + .parse().context("Content-Length 无效")?; + let declared_size = headers.get("x-qft-size") + .and_then(|v| v.parse::().ok()) + .unwrap_or(size); + if declared_size != size { bail!("文件大小头与 Content-Length 不一致") } + + let final_path = unique_path(save_dir, &file_name); + let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin"); + let part_path = final_path.with_file_name(format!("{final_name}.qftpart")); + let mut out = File::create(&part_path).with_context(|| format!("创建临时文件 {}", part_path.display()))?; + let _ = events.send(ReceiverEvent::UploadStarted { device: device.to_owned(), file_name: file_name.clone(), size }); + + let mut remaining = size; + let mut received = 0u64; + let mut buf = vec![0u8; IO_BUFFER]; + let mut hasher = Sha256::new(); + let mut last_report = Instant::now(); + while remaining > 0 { + let want = remaining.min(buf.len() as u64) as usize; + let n = reader.read(&mut buf[..want])?; + if n == 0 { bail!("上传中连接提前关闭:{received}/{size}") } + out.write_all(&buf[..n])?; + hasher.update(&buf[..n]); + received += n as u64; + remaining -= n as u64; + if last_report.elapsed() >= Duration::from_millis(100) || remaining == 0 { + let _ = events.send(ReceiverEvent::UploadProgress { + device: device.to_owned(), file_name: file_name.clone(), received, size, + }); + last_report = Instant::now(); + } + } + out.sync_all()?; + drop(out); + fs::rename(&part_path, &final_path).context("完成文件重命名失败")?; + let sha = hex(&hasher.finalize()); + let _ = events.send(ReceiverEvent::UploadCompleted { + device: device.to_owned(), file_name, saved_path: final_path, sha256: sha, + }); + write_response(stream, 200, "application/json", b"{\"ok\":true,\"legacy\":true}") +} + +fn copy_exact(reader: &mut impl Read, writer: &mut impl Write, mut remaining: u64) -> Result<()> { + let mut buf = vec![0u8; IO_BUFFER]; + while remaining > 0 { + let want = remaining.min(buf.len() as u64) as usize; + let n = reader.read(&mut buf[..want])?; + if n == 0 { bail!("chunk 上传中连接提前关闭") } + writer.write_all(&buf[..n])?; + remaining -= n as u64; + } + Ok(()) +} + +fn drain_exact(reader: &mut impl Read, remaining: u64) -> Result<()> { + copy_exact(reader, &mut std::io::sink(), remaining) +} + +fn hash_file(path: &Path) -> Result { + let mut input = File::open(path)?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 4 * 1024 * 1024]; + loop { + let n = input.read(&mut buf)?; + if n == 0 { break } + hasher.update(&buf[..n]); + } + Ok(hex(&hasher.finalize())) +} + +fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> { + let reason = match code { + 200 => "OK", 400 => "Bad Request", 403 => "Forbidden", 404 => "Not Found", + 409 => "Conflict", _ => "Error", + }; + write!(stream, + "HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len())?; + stream.write_all(body)?; + stream.flush()?; + Ok(()) +} + +fn decode_header(value: Option<&String>) -> Option { + let raw = value?; + let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?; + String::from_utf8(bytes).ok() +} + +fn sanitize_file_name(name: String) -> String { + let cleaned: String = name.chars() + .map(|c| if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') { '_' } else { c }) + .collect(); + cleaned.trim().trim_matches('.').chars().take(180).collect() +} + +fn unique_path(dir: &Path, name: &str) -> PathBuf { + let base = Path::new(name); + let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload"); + let ext = base.extension().and_then(|s| s.to_str()); + let mut candidate = dir.join(name); + let mut n = 1; + while candidate.exists() { + let next = match ext { + Some(ext) => format!("{stem} ({n}).{ext}"), + None => format!("{stem} ({n})"), + }; + candidate = dir.join(next); + n += 1; + } + candidate +} + +fn unique_path_reserved<'a>( + dir: &Path, + name: &str, + sessions: impl Iterator>>, +) -> PathBuf { + let reserved: Vec = sessions + .filter_map(|s| s.lock().ok().map(|v| v.final_path.clone())) + .collect(); + let base = Path::new(name); + let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload"); + let ext = base.extension().and_then(|s| s.to_str()); + let mut n = 0u32; + loop { + let next_name = if n == 0 { + name.to_owned() + } else { + match ext { + Some(ext) => format!("{stem} ({n}).{ext}"), + None => format!("{stem} ({n})"), + } + }; + let candidate = dir.join(next_name); + if !candidate.exists() && !reserved.contains(&candidate) { + return candidate; + } + n += 1; + } +} + +fn random_id() -> String { + let mut bytes = [0u8; 12]; + rand::rng().fill_bytes(&mut bytes); + URL_SAFE_NO_PAD.encode(bytes) +} + +fn hex(bytes: &[u8]) -> String { + const H: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); } + out +}