feat: scan the pairing QR code with the camera

The pairing dialog gained a "扫码" button: a full-screen scanner points the
back camera at the QR that OpenChamber's connect-a-device dialog shows, and a
decoded pairing link connects straight away.

Frames are decoded with zxing2 (pure Dart, no ML Kit or Play services): the
YUV420 Y plane is already luminance, BGRA frames are converted green-weighted,
and each frame is decoded in a background isolate so camera frames never block
the UI. Only an openchamber://connect payload ends the scan; any other QR code
shows a short hint and scanning continues. A torch button, a denied-permission
message with retry, and camera-less devices are handled.

The recorder audio permission the camera plugin declares for video is removed
from the merged manifest: the scanner reads frames only.

0.4.5 (405).
This commit is contained in:
blumia committed 2026-11-22 17:52:47 +08:00
1 parent 902f1e18bb
commit 8f6fd99103
10 files changed
+631 -10

No files matched your search

+13
View File
@@ -5,6 +5,19 @@
--- ---
## 0.4.5 扫码配对(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 扫码入口 | 「配对链接」对话框新增「扫码」:全屏相机 + 取景框 + 手电筒;扫到配对链接直接开始配对,不再要求按第二个按钮 |
| 解码 | 用 `camera` 0.12 + `zxing2` 0.2(纯 Dart,不依赖 ML Kit / Google Play 服务)。Android 取 YUV420 的 Y 平面直接作为亮度;BGRA(iOS/部分相机)按绿加权转亮度。解码放在 `compute` isolate,每帧不阻塞 UI,同一时间只解一帧 |
| 取景 | 后置相机优先、480p 预览、覆盖率/圆角遮罩 + 四角标记;非配对二维码提示「这不是 OpenChamber 配对二维码」并继续扫;无相机/权限被拒给出说明与重试 |
| 权限 | AndroidManifest 增加 CAMERA 权限;camera 硬件声明为非必需,没相机的设备仍可安装 |
| 测试 | `test/qr_scan_test.dart`:用 `qr` 生成配对链接二维码,渲染成 Y 平面(含 rowStride 内边距)后由 `decodeQrLuminance` 解出原文;空白帧、过短/非法尺寸返回 null |
| 版本 | **0.4.5(code 405)** |
---
## 0.4.4 通过 OpenChamber 私有 Relay 连接(分支 `flutter`) ## 0.4.4 通过 OpenChamber 私有 Relay 连接(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+3 -2
View File
@@ -5,9 +5,10 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.4.4 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.4.5 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption), session list with search and live over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a grouped per turn (icon, one-line summary, foldable run) with image previews, a
context usage ring with a detail sheet, model/agent switching (Build/Plan only, context usage ring with a detail sheet, model/agent switching (Build/Plan only,
+8 -1
View File
@@ -1,5 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<!-- The camera plugin declares audio for video; the scanner only reads
frames, so the app must not end up asking for the microphone. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" tools:node="remove"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<application <application
android:label="OpenChamber" android:label="OpenChamber"
android:name="${applicationName}" android:name="${applicationName}"
+98
View File
@@ -0,0 +1,98 @@
// QR decoding for the pairing scanner. The camera hands us a Y plane (YUV420
// on Android) that is already luminance; zxing2's QR reader does the rest. Kept
// free of Flutter so a frame can be decoded in a background isolate and a unit
// test can feed it a generated QR image.
import 'dart:typed_data';
import 'package:zxing2/qrcode.dart';
import 'package:zxing2/zxing2.dart';
/// One grayscale frame: [rowStride] may exceed [width] (camera padding).
class QrFrame {
final Uint8List luminance;
final int width;
final int height;
final int rowStride;
const QrFrame({
required this.luminance,
required this.width,
required this.height,
required this.rowStride,
});
}
/// The payload of the QR code in [frame], or null when there is none.
String? decodeQrFrame(QrFrame frame) => decodeQrLuminance(
frame.luminance,
frame.width,
frame.height,
frame.rowStride,
);
String? decodeQrLuminance(
Uint8List luminance, int width, int height, int rowStride) {
if (width <= 0 || height <= 0 || rowStride < width) return null;
if (luminance.length < rowStride * height) return null;
try {
final source = _PlaneLuminanceSource(luminance, width, height, rowStride);
final bitmap = BinaryBitmap(HybridBinarizer(source));
return QRCodeReader().decode(bitmap).text;
} on ReaderException {
return null;
} catch (_) {
// A torn or malformed frame must not stop the scanner.
return null;
}
}
/// BGRA8888 (iOS and some cameras): green-weighted luminance, as zxing2's
/// RGBLuminanceSource computes it.
Uint8List bgraToLuminance(
Uint8List bytes, int width, int height, int rowStride) {
final out = Uint8List(width * height);
for (var y = 0; y < height; y++) {
final row = y * rowStride;
final target = y * width;
for (var x = 0; x < width; x++) {
final i = row + x * 4;
if (i + 2 >= bytes.length) break;
final b = bytes[i];
final g = bytes[i + 1];
final r = bytes[i + 2];
out[target + x] = (r + 2 * g + b) >> 2;
}
}
return out;
}
class _PlaneLuminanceSource extends LuminanceSource {
final Uint8List data;
final int rowStride;
_PlaneLuminanceSource(this.data, int width, int height, this.rowStride)
: super(width, height);
@override
Int8List getRow(int y, Int8List? row) {
final out = (row != null && row.length >= width) ? row : Int8List(width);
final base = y * rowStride;
for (var x = 0; x < width; x++) {
out[x] = data[base + x].toSigned(8);
}
return out;
}
@override
Int8List getMatrix() {
final out = Int8List(width * height);
for (var y = 0; y < height; y++) {
final base = y * rowStride;
final target = y * width;
for (var x = 0; x < width; x++) {
out[target + x] = data[base + x].toSigned(8);
}
}
return out;
}
}
+301
View File
@@ -0,0 +1,301 @@
// Scans the QR code a pairing link is shown as in OpenChamber's "connect a
// device" dialog. The camera stream's Y plane goes to zxing2 in a background
// isolate; only a decoded `openchamber://connect` link ends the scan.
import 'dart:async';
import 'dart:math' as math;
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/qr_scan.dart';
/// Opens the scanner and returns the pairing link, or null when cancelled.
Future<String?> scanPairingQr(BuildContext context) {
return Navigator.of(context).push<String>(MaterialPageRoute(
fullscreenDialog: true,
builder: (_) => const ScanQrScreen(),
));
}
class ScanQrScreen extends StatefulWidget {
const ScanQrScreen({super.key});
@override
State<ScanQrScreen> createState() => _ScanQrScreenState();
}
class _ScanQrScreenState extends State<ScanQrScreen> {
CameraController? _controller;
String? _error;
String? _hint;
bool _decoding = false;
bool _found = false;
bool _torch = false;
Timer? _hintTimer;
@override
void initState() {
super.initState();
_start();
}
@override
void dispose() {
_hintTimer?.cancel();
_closeCamera();
super.dispose();
}
void _closeCamera() {
final controller = _controller;
_controller = null;
if (controller == null) return;
controller.stopImageStream().catchError((_) {});
controller.dispose();
}
Future<void> _start() async {
setState(() {
_error = null;
_found = false;
});
try {
final cameras = await availableCameras();
if (cameras.isEmpty) {
if (mounted) setState(() => _error = '没有可用的相机');
return;
}
CameraDescription pick = cameras.first;
for (final camera in cameras) {
if (camera.lensDirection == CameraLensDirection.back) {
pick = camera;
break;
}
}
final controller = CameraController(
pick,
ResolutionPreset.medium,
enableAudio: false,
imageFormatGroup: ImageFormatGroup.yuv420,
);
await controller.initialize();
if (!mounted) {
await controller.dispose();
return;
}
setState(() => _controller = controller);
await controller.startImageStream(_onFrame);
} on CameraException catch (error) {
if (!mounted) return;
setState(() {
_error = error.code == 'CameraAccessDenied'
? '需要相机权限才能扫码。请在系统设置里允许 OpenChamber 使用相机。'
: '无法打开相机:${error.description ?? error.code}';
});
} catch (error) {
if (mounted) setState(() => _error = '无法打开相机:$error');
}
}
void _onFrame(CameraImage image) {
if (_decoding || _found || !mounted) return;
final frame = _frameOf(image);
if (frame == null) return;
_decoding = true;
// Decoding off the UI thread: a 480p frame is cheap, but not free, and
// camera frames arrive at 30/s.
compute(decodeQrFrame, frame).then((text) {
_decoding = false;
if (!mounted || text == null || _found) return;
if (text.trim().startsWith('openchamber://connect')) {
_accept(text.trim());
} else {
_showHint('这不是 OpenChamber 配对二维码');
}
}).catchError((_) {
_decoding = false;
});
}
QrFrame? _frameOf(CameraImage image) {
if (image.planes.isEmpty) return null;
final plane = image.planes.first;
final group = image.format.group;
if (group == ImageFormatGroup.bgra8888) {
// The packed BGRA plane is not luminance yet.
final luminance = bgraToLuminance(
plane.bytes, image.width, image.height, plane.bytesPerRow);
return QrFrame(
luminance: luminance,
width: image.width,
height: image.height,
rowStride: image.width,
);
}
return QrFrame(
luminance: plane.bytes,
width: image.width,
height: image.height,
rowStride: plane.bytesPerRow,
);
}
void _showHint(String text) {
_hintTimer?.cancel();
if (mounted) setState(() => _hint = text);
_hintTimer = Timer(const Duration(seconds: 2), () {
if (mounted) setState(() => _hint = null);
});
}
Future<void> _accept(String text) async {
_found = true;
HapticFeedback.mediumImpact();
try {
await _controller?.stopImageStream();
} catch (_) {}
if (mounted) Navigator.of(context).pop(text);
}
Future<void> _toggleTorch() async {
final controller = _controller;
if (controller == null) return;
try {
await controller.setFlashMode(_torch ? FlashMode.off : FlashMode.torch);
if (mounted) setState(() => _torch = !_torch);
} catch (_) {
if (mounted) _showHint('这个相机不支持手电筒');
}
}
@override
Widget build(BuildContext context) {
final controller = _controller;
final ready = controller != null && controller.value.isInitialized;
return Scaffold(
backgroundColor: Colors.black,
body: Stack(
fit: StackFit.expand,
children: [
if (ready)
Center(child: CameraPreview(controller))
else if (_error != null)
Center(
child: Padding(
padding: const EdgeInsets.all(28),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.no_photography_outlined,
size: 36, color: Colors.white70),
const SizedBox(height: 12),
Text(_error!,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70)),
const SizedBox(height: 16),
FilledButton.tonal(
onPressed: _start,
child: const Text('重试'),
),
],
),
),
)
else
const Center(child: CircularProgressIndicator()),
if (ready) const IgnorePointer(child: CustomPaint(painter: _ScanOverlay())),
SafeArea(
child: Column(
children: [
Row(
children: [
IconButton(
tooltip: '关闭',
icon: const Icon(Icons.close),
color: Colors.white,
onPressed: () => Navigator.of(context).pop(),
),
const Spacer(),
IconButton(
tooltip: '手电筒',
icon: Icon(_torch ? Icons.flash_on : Icons.flash_off),
color: Colors.white,
onPressed: _toggleTorch,
),
],
),
const Spacer(),
Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 32),
child: Column(
children: [
Text(
_hint ?? '把配对二维码放进框内',
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white, fontSize: 14),
),
const SizedBox(height: 6),
const Text(
'在 OpenChamber 网页端打开「连接设备」,选择二维码',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white60, fontSize: 12),
),
],
),
),
],
),
),
],
),
);
}
}
/// Dims everything but the scan square and marks its corners.
class _ScanOverlay extends CustomPainter {
const _ScanOverlay();
@override
void paint(Canvas canvas, Size size) {
final side = math.min(size.width, size.height) * 0.68;
final square = Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2),
width: side,
height: side,
);
final radius = Radius.circular(side * 0.05);
final shade = Path()
..fillType = PathFillType.evenOdd
..addRect(Offset.zero & size)
..addRRect(RRect.fromRectAndRadius(square, radius));
canvas.drawPath(shade, Paint()..color = const Color(0x99000000));
final border = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2
..color = Colors.white.withValues(alpha: 0.85);
canvas.drawRRect(RRect.fromRectAndRadius(square, radius), border);
final corner = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 4
..strokeCap = StrokeCap.round
..color = const Color(0xFFC6BFFF);
const arm = 28.0;
for (final (dx, dy, sx, sy) in [
(square.left, square.top, 1.0, 1.0),
(square.right, square.top, -1.0, 1.0),
(square.left, square.bottom, 1.0, -1.0),
(square.right, square.bottom, -1.0, -1.0),
]) {
canvas.drawLine(Offset(dx, dy), Offset(dx + arm * sx, dy), corner);
canvas.drawLine(Offset(dx, dy), Offset(dx, dy + arm * sy), corner);
}
}
@override
bool shouldRepaint(_ScanOverlay oldDelegate) => false;
}
+22 -5
View File
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
import '../state.dart'; import '../state.dart';
import '../storage.dart'; import '../storage.dart';
import 'scan_qr_screen.dart';
/// The first screen: the saved servers, or the connect form. /// The first screen: the saved servers, or the connect form.
class ServersScreen extends StatefulWidget { class ServersScreen extends StatefulWidget {
@@ -420,6 +421,15 @@ class _PairingDialogState extends State<_PairingDialog> {
super.dispose(); super.dispose();
} }
Future<void> _scan() async {
final text = await scanPairingQr(context);
if (!mounted || text == null) return;
setState(() => _text.text = text);
// A scan is an explicit "connect these": do not make the person press
// another button after pointing the camera at the code.
await _connect();
}
Future<void> _paste() async { Future<void> _paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain); final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text?.trim() ?? ''; final text = data?.text?.trim() ?? '';
@@ -459,7 +469,7 @@ class _PairingDialogState extends State<_PairingDialog> {
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Text( Text(
'在 OpenChamber 网页端打开「连接设备」,把生成的链接粘贴到这里。' '在 OpenChamber 网页端打开「连接设备」,粘贴链接或直接扫描二维码。'
'链接里带一次性密钥,以及直连地址或私有 Relay。', '链接里带一次性密钥,以及直连地址或私有 Relay。',
style: TextStyle(fontSize: 12.5, color: theme.hintColor), style: TextStyle(fontSize: 12.5, color: theme.hintColor),
), ),
@@ -482,13 +492,20 @@ class _PairingDialogState extends State<_PairingDialog> {
child: Text(_error!, child: Text(_error!,
style: TextStyle(color: theme.colorScheme.error, fontSize: 12.5)), style: TextStyle(color: theme.colorScheme.error, fontSize: 12.5)),
), ),
Align( Row(
alignment: Alignment.centerLeft, children: [
child: TextButton.icon( TextButton.icon(
onPressed: _busy ? null : _scan,
icon: const Icon(Icons.qr_code_scanner, size: 18),
label: const Text('扫码'),
),
const SizedBox(width: 4),
TextButton.icon(
onPressed: _busy ? null : _paste, onPressed: _busy ? null : _paste,
icon: const Icon(Icons.content_paste, size: 18), icon: const Icon(Icons.content_paste, size: 18),
label: const Text('从剪贴板粘贴'), label: const Text('粘贴'),
), ),
],
), ),
], ],
), ),
+1 -1
View File
@@ -1,2 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes. /// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.4'; const appVersion = '0.4.5';
+88
View File
@@ -41,6 +41,46 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "2.1.2" version: "2.1.2"
camera:
dependency: "direct main"
description:
name: camera
sha256: "4a0863bc142f6fbfdca19161205574fd8a8f00d4753b48d214c4dfbdcc534c51"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.12.2"
camera_android_camerax:
dependency: transitive
description:
name: camera_android_camerax
sha256: daefacb4c2c575426772a83ac312b93e2c49c003224962cddab904426dc04dbc
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.7.6+2"
camera_avfoundation:
dependency: transitive
description:
name: camera_avfoundation
sha256: "971f7b4938ae761797dd667c078af92f1b6a1bb7760774c0cbcf9c9d4a14bdf1"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.11.1"
camera_platform_interface:
dependency: transitive
description:
name: camera_platform_interface
sha256: c22b8403d7925c6cc6a37fc0cf01f645c1400bdfb0e765f81373a3ac080d93e3
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.15.1"
camera_web:
dependency: transitive
description:
name: camera_web
sha256: "54183db5a296cf29478dd150d7685b761f9e8eeb4a11114bcbc2792adea7cb3b"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.3.6"
characters: characters:
dependency: transitive dependency: transitive
description: description:
@@ -49,6 +89,14 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "1.4.1" version: "1.4.1"
charcode:
dependency: transitive
description:
name: charcode
sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.4.0"
cli_util: cli_util:
dependency: transitive dependency: transitive
description: description:
@@ -209,6 +257,14 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "4.2.1" version: "4.2.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.1"
flutter: flutter:
dependency: "direct main" dependency: "direct main"
description: flutter description: flutter
@@ -227,6 +283,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
name: flutter_plugin_android_lifecycle
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.0.35"
flutter_secure_storage: flutter_secure_storage:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -565,6 +629,14 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "2.2.1" version: "2.2.1"
qr:
dependency: "direct dev"
description:
name: qr
sha256: f9461594b257c2ec882159fb8100db28408f6aacdba5b21f109708bce2e482b6
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.0.1"
quiver: quiver:
dependency: transitive dependency: transitive
description: description:
@@ -674,6 +746,14 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "2.1.4" version: "2.1.4"
stream_transform:
dependency: transitive
description:
name: stream_transform
sha256: a00e5f18bffc764f923e7dec1038527f7fe7a1791361a7117f0358193f13d53a
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.2"
string_scanner: string_scanner:
dependency: transitive dependency: transitive
description: description:
@@ -842,6 +922,14 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "0.0.6" version: "0.0.6"
zxing2:
dependency: "direct main"
description:
name: zxing2
sha256: "2677c49a3b9ca9457cb1d294fd4bd5041cac6aab8cdb07b216ba4e98945c684f"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.2.4"
sdks: sdks:
dart: ">=3.14.0 <4.0.0" dart: ">=3.14.0 <4.0.0"
flutter: ">=3.47.0" flutter: ">=3.47.0"
+4 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.4.4+404 version: 0.4.5+405
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
@@ -20,10 +20,13 @@ dependencies:
flutter_slidable: ^5.2.0 flutter_slidable: ^5.2.0
archive: ^3.6.1 archive: ^3.6.1
pointycastle: ^4.0.0 pointycastle: ^4.0.0
camera: ^0.12.2
zxing2: ^0.2.4
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter
flutter_lints: ^6.0.0 flutter_lints: ^6.0.0
qr: ^4.0.1
flutter: flutter:
uses-material-design: true uses-material-design: true
+93
View File
@@ -0,0 +1,93 @@
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/qr_scan.dart';
import 'package:qr/qr.dart';
/// Renders [data] as a black-on-white luminance image, like a camera frame's
/// Y plane, with a quiet zone and the requested scale.
Uint8List _qrImage(String data, {int scale = 6, int quiet = 4, int pad = 0}) {
final code = QrCode(
payload: QrPayload.fromString(data),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final image = QrImage(code);
final size = (image.moduleCount + quiet * 2) * scale;
final stride = size + pad;
final out = Uint8List(stride * size)..fillRange(0, stride * size, 255);
for (var r = 0; r < image.moduleCount; r++) {
for (var c = 0; c < image.moduleCount; c++) {
if (!image.isDark(r, c)) continue;
final y0 = (r + quiet) * scale;
final x0 = (c + quiet) * scale;
for (var dy = 0; dy < scale; dy++) {
final row = (y0 + dy) * stride;
out.fillRange(row + x0, row + x0 + scale, 0);
}
}
}
return out;
}
void main() {
const link =
'openchamber://connect?v=2&p=eyJ2IjoyLCJwYWlyaW5nSWQiOiJwYWlyX2FiYyJ9';
test('decodes a QR rendered as a camera Y plane', () {
const scale = 6;
const quiet = 4;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final image = _qrImage(link, scale: scale, quiet: quiet);
expect(decodeQrLuminance(image, size, size, size), link);
});
test('a frame can be decoded in a background isolate', () async {
const scale = 6;
const quiet = 4;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final image = _qrImage(link, scale: scale, quiet: quiet);
final text = await compute(
decodeQrFrame,
QrFrame(
luminance: image,
width: size,
height: size,
rowStride: size,
),
);
expect(text, link);
});
test('respects a padded row stride', () {
const scale = 6;
const quiet = 4;
const pad = 12;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final image = _qrImage(link, scale: scale, quiet: quiet, pad: pad);
expect(decodeQrLuminance(image, size, size, size + pad), link);
});
test('a frame without a QR code yields null', () {
final blank = Uint8List(320 * 240)..fillRange(0, 320 * 240, 255);
expect(decodeQrLuminance(blank, 320, 240, 320), isNull);
});
test('short buffers and impossible sizes are refused', () {
expect(decodeQrLuminance(Uint8List(10), 100, 100, 100), isNull);
expect(decodeQrLuminance(Uint8List(100), 0, 10, 10), isNull);
expect(decodeQrLuminance(Uint8List(100), 20, 10, 10), isNull);
});
}