Barcode Scanning Updates (#915)

* Handle "hidden characters" for barcode scanning

e.g. digikey datamatrix

* add release note

* Prevent multi-barcode scans in quick succession

* Auto-submit barcode after timeout duration

* Add barcode scan log widget

* display most recent scan result
This commit is contained in:
Oliver authored and GitHub committed 2026-11-11 22:20:22 +11:00
1 parent 60b8e90ebe
commit a504263923
12 files changed
+1465 -28

No files matched your search

+9
View File
@@ -1,3 +1,12 @@
### x.x.x - November 2026
---
- Handle control characters for "keyboard wedge" barcode scanners
- Ignore additional barcodes read in the same shot by "keyboard wedge" barcode scanners
- Support "keyboard wedge" barcode scanners which do not send an Enter key after each scan
- Adds barcode scan log, showing recent scans and server responses
- Barcode scanner displays the most recently scanned code
## 1.0.0 - November 2026
---
+9
View File
@@ -479,6 +479,15 @@ class UniqueBarcodeHandler extends BarcodeHandler {
Future<void> onBarcodeUnknown(Map<String, dynamic> data) async {
await onBarcodeMatched(data);
}
// An "unknown" barcode is the expected result here - success is
// receiving the barcode hash and data back from the server
@override
bool isScanSuccessful(APIResponse response, Map<String, dynamic> data) {
return response.isValid() &&
(data.containsKey("hash") || data.containsKey("barcode_hash")) &&
((data["barcode_data"] ?? "") as String).isNotEmpty;
}
}
SpeedDialChild customBarcodeAction(
+8 -1
View File
@@ -84,6 +84,9 @@ class _CameraBarcodeControllerState extends InvenTreeBarcodeControllerState {
}
}
@override
bool get isScanPaused => scanning_paused;
@override
Future<void> pauseScan() async {
if (mounted) {
@@ -394,7 +397,11 @@ class _CameraBarcodeControllerState extends InvenTreeBarcodeControllerState {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(L10().scanBarcode)),
appBar: AppBar(
title: Text(L10().scanBarcode),
actions: [buildScanLogAction()],
),
bottomNavigationBar: buildLastScanBar(),
floatingActionButton: buildActions(context),
body: GestureDetector(
onTap: () async {
+52
View File
@@ -1,7 +1,10 @@
import "package:flutter/material.dart";
import "package:flutter_tabler_icons/flutter_tabler_icons.dart";
import "package:inventree/l10.dart";
import "package:inventree/preferences.dart";
import "package:inventree/barcode/handler.dart";
import "package:inventree/widget/barcode_scan_log.dart";
import "package:inventree/widget/progress.dart";
/*
@@ -93,6 +96,55 @@ class InvenTreeBarcodeControllerState
// Implement this function in subclass
}
// Hook function: return true if scanning is currently paused
bool get isScanPaused => false;
/*
* Open a page over the scanner, pausing scanning while it is displayed.
* Scanning is only resumed if it was running beforehand.
*/
Future<void> _openOverScanner(Widget page) async {
final bool wasPaused = isScanPaused;
if (!wasPaused) {
await pauseScan();
}
if (!mounted) return;
await Navigator.of(context).push(MaterialPageRoute(builder: (_) => page));
if (!wasPaused && mounted && !processingBarcode) {
await resumeScan();
}
}
// Open the barcode scan log
Future<void> showScanLog() => _openOverScanner(const BarcodeScanLogWidget());
// When this scanner was opened
final DateTime openedAt = DateTime.now();
// Bar at the bottom of the scanner which shows the most recent scan
// (starts empty - only scans made since this scanner opened are shown)
Widget buildLastScanBar() {
return BarcodeLastScanBar(
since: openedAt,
onTap: (entry) =>
_openOverScanner(BarcodeScanLogDetailWidget(entry: entry)),
);
}
// App bar action which opens the barcode scan log
Widget buildScanLogAction() {
return IconButton(
key: const Key("barcodeScanLog"),
icon: const Icon(TablerIcons.history),
tooltip: L10().barcodeScanLog,
onPressed: showScanLog,
);
}
/*
* Implementing classes are in control of building out the widget
*/
+49
View File
@@ -1,10 +1,12 @@
import "package:flutter/material.dart";
import "package:flutter_tabler_icons/flutter_tabler_icons.dart";
import "package:one_context/one_context.dart";
import "package:inventree/api.dart";
import "package:inventree/helpers.dart";
import "package:inventree/l10.dart";
import "package:inventree/barcode/scan_log.dart";
import "package:inventree/barcode/tones.dart";
import "package:inventree/inventree/sentry.dart";
@@ -25,6 +27,44 @@ class BarcodeHandler {
// Note: Will be overridden by child classes
String getOverlayText(BuildContext context) => "Barcode Overlay";
// Description of this scan for the barcode scan log
String get scanLogContext {
final BuildContext? context = hasContext() ? OneContext().context : null;
return context != null ? getOverlayText(context) : "";
}
/*
* Return true if the server response represents a successful scan,
* for the barcode scan log.
* Override where the handler treats responses differently.
*/
bool isScanSuccessful(APIResponse response, Map<String, dynamic> data) {
return response.isValid() &&
response.statusCode < 400 &&
response.isMap() &&
!data.containsKey("error");
}
void _logScan(
String barcode,
String url, {
required bool success,
APIResponse? response,
}) {
BarcodeScanLog().add(
BarcodeScanLogEntry(
timestamp: DateTime.now(),
context: scanLogContext,
barcode: barcode,
success: success,
url: url,
statusCode: response?.statusCode,
response: response?.data,
),
);
}
// Called when the server "matches" a barcode
Future<void> onBarcodeMatched(Map<String, dynamic> data) async {
// Override this function
@@ -90,6 +130,7 @@ class BarcodeHandler {
}
if (response == null) {
_logScan(barcode, url, success: false);
barcodeFailureTone();
showSnackIcon(L10().barcodeError, success: false);
return;
@@ -99,6 +140,14 @@ class BarcodeHandler {
Map<String, dynamic> data = response.asMap();
// Log before dispatch, as handlers may navigate away
_logScan(
barcode,
url,
success: isScanSuccessful(response, data),
response: response,
);
// No usable response (connection failure, timeout, certificate error,
// or a 5xx server error). The API layer has already shown an error
// to the user, and reported any unexpected server errors to sentry.
+8 -1
View File
@@ -96,6 +96,9 @@ class _IntentBarcodeControllerState extends InvenTreeBarcodeControllerState {
super.dispose();
}
@override
bool get isScanPaused => !canScan;
@override
Future<void> pauseScan() async {
if (!mounted) return;
@@ -119,7 +122,11 @@ class _IntentBarcodeControllerState extends InvenTreeBarcodeControllerState {
}
return Scaffold(
appBar: AppBar(title: Text(L10().scanBarcode)),
appBar: AppBar(
title: Text(L10().scanBarcode),
actions: [buildScanLogAction()],
),
bottomNavigationBar: buildLastScanBar(),
backgroundColor: Colors.black.withValues(alpha: 0.9),
body: Center(
child: Column(
+120
View File
@@ -0,0 +1,120 @@
import "dart:convert";
import "package:flutter/foundation.dart";
/*
* A single barcode scan, as recorded in the barcode scan log
*/
class BarcodeScanLogEntry {
BarcodeScanLogEntry({
required this.timestamp,
required this.context,
required this.barcode,
required this.success,
required this.url,
this.statusCode,
this.response,
});
final DateTime timestamp;
// Description of what the scan was for (e.g. "Scan stock location")
final String context;
// Barcode data, exactly as scanned
final String barcode;
// True if the server accepted the barcode
final bool success;
// API endpoint the barcode was sent to
final String url;
// HTTP status code, or null if no response was received
final int? statusCode;
// Decoded response body, or null if no response was received
final dynamic response;
bool get hasResponse => statusCode != null && statusCode! >= 0;
// Server response formatted for display
String get responseText {
if (response == null) {
return "";
}
try {
return const JsonEncoder.withIndent(" ").convert(response);
} catch (_) {
return response.toString();
}
}
// Barcode with control characters (e.g. the RS / GS separators in
// DataMatrix codes) shown as visible Unicode "control pictures"
String get displayBarcode => visibleControlCharacters(barcode);
}
/*
* Replace ASCII control characters with their Unicode "control picture"
* (e.g. 0x1E RS -> U+241E), so they can be seen when displayed
*/
String visibleControlCharacters(String text) {
final StringBuffer buffer = StringBuffer();
for (final int c in text.runes) {
if (c < 0x20) {
buffer.writeCharCode(0x2400 + c);
} else if (c == 0x7F) {
buffer.writeCharCode(0x2421);
} else {
buffer.writeCharCode(c);
}
}
return buffer.toString();
}
/*
* In-memory log of barcode scans.
*
* Lives only as long as the app is running (nothing is persisted),
* and keeps at most [maxEntries] scans, discarding the oldest.
*/
class BarcodeScanLog extends ChangeNotifier {
factory BarcodeScanLog() => _instance;
BarcodeScanLog._internal();
static final BarcodeScanLog _instance = BarcodeScanLog._internal();
static const int maxEntries = 100;
final List<BarcodeScanLogEntry> _entries = [];
// Scans, most recent first
List<BarcodeScanLogEntry> get entries => List.unmodifiable(_entries.reversed);
// Most recent scan, or null if the log is empty
BarcodeScanLogEntry? get latest => _entries.isEmpty ? null : _entries.last;
int get length => _entries.length;
bool get isEmpty => _entries.isEmpty;
void add(BarcodeScanLogEntry entry) {
_entries.add(entry);
if (_entries.length > maxEntries) {
_entries.removeRange(0, _entries.length - maxEntries);
}
notifyListeners();
}
void clear() {
_entries.clear();
notifyListeners();
}
}
+252 -26
View File
@@ -1,3 +1,5 @@
import "dart:async";
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_tabler_icons/flutter_tabler_icons.dart";
@@ -8,6 +10,181 @@ import "package:inventree/barcode/handler.dart";
import "package:inventree/l10.dart";
import "package:inventree/helpers.dart";
import "package:inventree/preferences.dart";
/*
* Control characters produced by Ctrl+<key>, keyed by logical key.
*
* Keyboard-wedge scanners have no HID keycode for ASCII control characters,
* so they type them as Ctrl combinations (e.g. GS = Ctrl+], RS = Ctrl+^).
* On Android, KeyEvent.getUnicodeChar() returns 0 for any Ctrl combination,
* so Flutter reports KeyEvent.character == null and the character is lost
* unless we rebuild it here.
*/
final Map<LogicalKeyboardKey, String> _ctrlCharacters = {
// Ctrl+@ / Ctrl+2 -> NUL is deliberately omitted (a NUL would truncate data)
LogicalKeyboardKey.keyA: "\x01",
LogicalKeyboardKey.keyB: "\x02",
LogicalKeyboardKey.keyC: "\x03",
LogicalKeyboardKey.keyD: "\x04", // EOT
LogicalKeyboardKey.keyE: "\x05",
LogicalKeyboardKey.keyF: "\x06",
LogicalKeyboardKey.keyG: "\x07",
LogicalKeyboardKey.keyH: "\x08",
LogicalKeyboardKey.keyI: "\x09",
LogicalKeyboardKey.keyJ: "\x0A",
LogicalKeyboardKey.keyK: "\x0B",
LogicalKeyboardKey.keyL: "\x0C",
LogicalKeyboardKey.keyM: "\x0D",
LogicalKeyboardKey.keyN: "\x0E",
LogicalKeyboardKey.keyO: "\x0F",
LogicalKeyboardKey.keyP: "\x10",
LogicalKeyboardKey.keyQ: "\x11",
LogicalKeyboardKey.keyR: "\x12",
LogicalKeyboardKey.keyS: "\x13",
LogicalKeyboardKey.keyT: "\x14",
LogicalKeyboardKey.keyU: "\x15",
LogicalKeyboardKey.keyV: "\x16",
LogicalKeyboardKey.keyW: "\x17",
LogicalKeyboardKey.keyX: "\x18",
LogicalKeyboardKey.keyY: "\x19",
LogicalKeyboardKey.keyZ: "\x1A",
LogicalKeyboardKey.bracketLeft: "\x1B", // ESC
LogicalKeyboardKey.backslash: "\x1C", // FS
LogicalKeyboardKey.bracketRight: "\x1D", // GS
LogicalKeyboardKey.caret: "\x1E", // RS
LogicalKeyboardKey.digit6: "\x1E", // RS (Ctrl+Shift+6 on US layout)
LogicalKeyboardKey.underscore: "\x1F", // US
LogicalKeyboardKey.minus: "\x1F", // US (Ctrl+Shift+- on US layout)
};
/*
* Resolve the character a wedge scanner meant to send for a key-down event.
*
* Returns null when the event produces no character (e.g. a bare modifier).
*/
String? wedgeCharacterForEvent(KeyEvent event, {required bool ctrlPressed}) {
if (ctrlPressed) {
final String? ctrlChar = _ctrlCharacters[event.logicalKey];
if (ctrlChar != null) {
return ctrlChar;
}
}
final String? character = event.character;
if (character == null || character.isEmpty) {
return null;
}
return character;
}
/*
* Assembles keyboard-wedge characters into complete barcodes.
*
* A wedge scanner can read several barcodes in one shot (e.g. an InvenTree
* label next to a DigiKey label) and types them all, separated by newlines.
* Only the first barcode is wanted (#625), so after a barcode is completed
* all further input is discarded until the keyboard has been quiet for
* [blankingPeriod]. The window is extended by every discarded key, so a long
* trailing barcode cannot be resumed part-way through and submitted as a
* fragment.
*
* Input received while the scanner is paused (processing a barcode) is
* treated the same way.
*/
class WedgeScanBuffer {
WedgeScanBuffer({
this.blankingPeriod = const Duration(milliseconds: 500),
this.characterTimeout = const Duration(milliseconds: 250),
this.minimumFlushLength = 4,
});
// Quiet time required after a completed scan before accepting new input
Duration blankingPeriod;
// Maximum gap between characters of a single barcode.
// Also the time after the last character at which a scan with no
// terminating newline is submitted (see [flush])
final Duration characterTimeout;
// Shortest unterminated input which [flush] will submit, so that stray
// key presses on a hardware keyboard do not trigger barcode lookups
final int minimumFlushLength;
bool get hasPendingCharacters => _characters.isNotEmpty;
final List<String> _characters = [];
DateTime? _lastKeyTime;
DateTime? _blankUntil;
bool isBlanking(DateTime now) =>
_blankUntil != null && now.isBefore(_blankUntil!);
/*
* Add a single character received at [now].
* Returns the completed barcode when a newline terminates one, else null.
* Set [accepting] to false while the scanner is paused.
*/
String? addCharacter(
String character,
DateTime now, {
bool accepting = true,
}) {
if (!accepting || isBlanking(now)) {
_blankUntil = now.add(blankingPeriod);
_characters.clear();
_lastKeyTime = now;
return null;
}
// Throw away stale characters from an earlier, incomplete scan
if (_lastKeyTime == null ||
now.difference(_lastKeyTime!) > characterTimeout) {
_characters.clear();
}
_lastKeyTime = now;
if (character != "\n") {
_characters.add(character);
return null;
}
final String data = _characters.join();
_characters.clear();
if (data.isEmpty) {
return null;
}
_blankUntil = now.add(blankingPeriod);
return data;
}
/*
* Complete a scan which was not terminated by a newline.
*
* Call once [characterTimeout] has passed since the last character.
* Returns the buffered barcode, or null if there is none (or it is shorter
* than [minimumFlushLength], in which case it is discarded).
* A returned barcode starts the blanking period, as for a newline.
*/
String? flush(DateTime now) {
final String data = _characters.join();
_characters.clear();
if (data.length < minimumFlushLength) {
return null;
}
_blankUntil = now.add(blankingPeriod);
return data;
}
}
/*
* Barcode controller which acts as a keyboard wedge,
@@ -30,9 +207,56 @@ class _WedgeBarcodeControllerState extends InvenTreeBarcodeControllerState {
final FocusNode _focusNode = FocusNode();
List<String> _scannedCharacters = [];
final WedgeScanBuffer _buffer = WedgeScanBuffer();
DateTime? _lastScanTime;
// Submits a scan which is not terminated by a newline
Timer? _flushTimer;
@override
void initState() {
super.initState();
_loadScanDelay();
}
@override
void dispose() {
_flushTimer?.cancel();
_focusNode.dispose();
super.dispose();
}
void _submitBarcode(String barcode) {
// Debug output required for unit testing
debug("scanned: ${barcode}");
handleBarcodeData(barcode);
}
void _flushPendingScan() {
_flushTimer = null;
final String? barcode = _buffer.flush(DateTime.now());
if (barcode != null && scanning) {
_submitBarcode(barcode);
}
}
// Blank further input for the user's scan delay (never shorter than the
// inter-character timeout, so trailing barcodes are always discarded)
Future<void> _loadScanDelay() async {
final int delay =
await InvenTreeSettingsManager().getValue(INV_BARCODE_SCAN_DELAY, 500)
as int;
final Duration period = Duration(milliseconds: delay);
_buffer.blankingPeriod = period > _buffer.characterTimeout
? period
: _buffer.characterTimeout;
}
@override
bool get isScanPaused => !canScan;
@override
Future<void> pauseScan() async {
@@ -54,47 +278,49 @@ class _WedgeBarcodeControllerState extends InvenTreeBarcodeControllerState {
// Callback for a single key press / scan
void handleKeyEvent(KeyEvent event) {
if (!scanning) {
return;
}
// Look only for key-down events
if (event is! KeyDownEvent) {
return;
}
// Ignore events without a character code
if (event.character == null) {
// (control characters are rebuilt from Ctrl+<key> combinations)
final String? character = wedgeCharacterForEvent(
event,
ctrlPressed: HardwareKeyboard.instance.isControlPressed,
);
if (character == null) {
return;
}
DateTime now = DateTime.now();
// Input is still tracked while paused, so that the blanking window
// covers barcodes which are typed while the previous one is processed
final String? barcode = _buffer.addCharacter(
character,
DateTime.now(),
accepting: scanning,
);
// Throw away old characters
if (_lastScanTime == null ||
_lastScanTime!.isBefore(now.subtract(Duration(milliseconds: 250)))) {
_scannedCharacters.clear();
}
// Restart the timeout for scanners which send no terminating newline
_flushTimer?.cancel();
_flushTimer = _buffer.hasPendingCharacters
? Timer(_buffer.characterTimeout, _flushPendingScan)
: null;
_lastScanTime = now;
if (event.character == "\n") {
if (_scannedCharacters.isNotEmpty) {
// Debug output required for unit testing
debug("scanned: ${_scannedCharacters.join()}");
handleBarcodeData(_scannedCharacters.join());
}
_scannedCharacters.clear();
} else {
_scannedCharacters.add(event.character!);
if (barcode != null) {
_submitBarcode(barcode);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(L10().scanBarcode)),
appBar: AppBar(
title: Text(L10().scanBarcode),
actions: [buildScanLogAction()],
),
bottomNavigationBar: buildLastScanBar(),
backgroundColor: Colors.black.withValues(alpha: 0.9),
body: Center(
child: Column(
+33
View File
@@ -256,6 +256,39 @@
"barcodeScanLocation": "Scan stock location",
"@barcodeScanLocation": {},
"barcodeScanLog": "Barcode Scan Log",
"@barcodeScanLog": {},
"barcodeScanLast": "Last Scan",
"@barcodeScanLast": {},
"barcodeScanLogClear": "Clear scan log",
"@barcodeScanLogClear": {},
"barcodeScanLogClearDetail": "Remove all entries from the barcode scan log?",
"@barcodeScanLogClearDetail": {},
"barcodeScanLogEmpty": "No barcodes scanned",
"@barcodeScanLogEmpty": {},
"barcodeScanContext": "Context",
"@barcodeScanContext": {},
"barcodeScanData": "Barcode Data",
"@barcodeScanData": {},
"barcodeScanFailed": "Failed",
"@barcodeScanFailed": {},
"barcodeScanSuccess": "Success",
"@barcodeScanSuccess": {},
"barcodeScanNoResponse": "No response received from server",
"@barcodeScanNoResponse": {},
"barcodeScanResponse": "Server Response",
"@barcodeScanResponse": {},
"barcodeScanSingle": "Single Scan Mode",
"@barcodeScanSingle": {},
+275
View File
@@ -0,0 +1,275 @@
import "package:flutter/material.dart";
import "package:flutter_tabler_icons/flutter_tabler_icons.dart";
import "package:intl/intl.dart";
import "package:inventree/app_colors.dart";
import "package:inventree/barcode/scan_log.dart";
import "package:inventree/l10.dart";
const TextStyle _monospace = TextStyle(fontFamily: "monospace", fontSize: 12);
String _formatTimestamp(DateTime timestamp) =>
DateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
Widget _statusIcon(BarcodeScanLogEntry entry) => entry.success
? Icon(TablerIcons.circle_check, color: COLOR_SUCCESS)
: Icon(TablerIcons.circle_x, color: COLOR_DANGER);
/*
* Displays the barcode scan log (most recent scan first)
*/
class BarcodeScanLogWidget extends StatelessWidget {
const BarcodeScanLogWidget({super.key});
// Ask the user to confirm before clearing the scan log
Future<void> _confirmClear(BuildContext context, BarcodeScanLog log) async {
final bool? confirmed = await showDialog<bool>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: ListTile(
leading: Icon(TablerIcons.trash, color: COLOR_DANGER),
title: Text(
L10().barcodeScanLogClear,
style: TextStyle(color: COLOR_DANGER),
),
),
content: Text(L10().barcodeScanLogClearDetail),
actions: [
TextButton(
key: const Key("barcodeScanLogClearCancel"),
child: Text(L10().cancel),
onPressed: () => Navigator.pop(context, false),
),
TextButton(
key: const Key("barcodeScanLogClearConfirm"),
child: Text(L10().delete),
onPressed: () => Navigator.pop(context, true),
),
],
),
);
if (confirmed ?? false) {
log.clear();
}
}
@override
Widget build(BuildContext context) {
final BarcodeScanLog log = BarcodeScanLog();
return ListenableBuilder(
listenable: log,
builder: (context, _) {
final List<BarcodeScanLogEntry> entries = log.entries;
return Scaffold(
appBar: AppBar(
title: Text(L10().barcodeScanLog),
actions: [
if (entries.isNotEmpty)
IconButton(
key: const Key("barcodeScanLogClear"),
icon: const Icon(TablerIcons.trash),
tooltip: L10().barcodeScanLogClear,
onPressed: () => _confirmClear(context, log),
),
],
),
body: entries.isEmpty
? Center(child: Text(L10().barcodeScanLogEmpty))
: ListView.separated(
itemCount: entries.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final BarcodeScanLogEntry entry = entries[index];
return ListTile(
leading: _statusIcon(entry),
title: Text(
entry.displayBarcode,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: _monospace,
),
subtitle: Text(
[
if (entry.context.isNotEmpty) entry.context,
_formatTimestamp(entry.timestamp),
].join("\n"),
),
trailing: const Icon(TablerIcons.chevron_right),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) =>
BarcodeScanLogDetailWidget(entry: entry),
),
);
},
);
},
),
);
},
);
}
}
/*
* Bar displayed at the bottom of the barcode scanner views,
* showing the most recent scan. Hidden when nothing has been scanned.
*
* Uses fixed light-on-dark colours, as the scanner views are dark.
*/
class BarcodeLastScanBar extends StatelessWidget {
const BarcodeLastScanBar({this.since, this.onTap, super.key});
// Only show scans made at or after this time (e.g. when the scanner opened)
final DateTime? since;
// Called with the displayed entry when the bar is tapped
final void Function(BarcodeScanLogEntry entry)? onTap;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: BarcodeScanLog(),
builder: (context, _) {
final BarcodeScanLogEntry? entry = BarcodeScanLog().latest;
if (entry == null ||
(since != null && entry.timestamp.isBefore(since!))) {
return const SizedBox.shrink();
}
final Color statusColor = entry.success
? COLOR_SUCCESS
: Colors.redAccent;
final String detail = [
L10().barcodeScanLast,
if (entry.context.isNotEmpty) entry.context,
DateFormat("HH:mm:ss").format(entry.timestamp),
].join(" • ");
return Material(
key: const Key("barcodeLastScan"),
color: Colors.black,
child: InkWell(
onTap: onTap == null ? null : () => onTap!(entry),
child: SafeArea(
top: false,
child: Container(
decoration: BoxDecoration(
border: Border(top: BorderSide(color: statusColor, width: 3)),
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
child: Row(
children: [
Icon(
entry.success
? TablerIcons.circle_check
: TablerIcons.circle_x,
color: statusColor,
size: 36,
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
entry.displayBarcode,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontFamily: "monospace",
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
detail,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
),
),
],
),
),
if (onTap != null)
const Icon(
TablerIcons.chevron_right,
color: Colors.white70,
),
],
),
),
),
),
);
},
);
}
}
/*
* Full detail for a single barcode scan, including the server response
*/
class BarcodeScanLogDetailWidget extends StatelessWidget {
const BarcodeScanLogDetailWidget({required this.entry, super.key});
final BarcodeScanLogEntry entry;
@override
Widget build(BuildContext context) {
final String status = entry.success
? L10().barcodeScanSuccess
: L10().barcodeScanFailed;
return Scaffold(
appBar: AppBar(title: Text(L10().barcodeScanLog)),
body: ListView(
children: [
ListTile(
leading: _statusIcon(entry),
title: Text(status),
subtitle: Text(
[
if (entry.hasResponse)
"${L10().statusCode}: ${entry.statusCode}",
entry.url,
_formatTimestamp(entry.timestamp),
].join("\n"),
),
),
if (entry.context.isNotEmpty)
ListTile(
title: Text(L10().barcodeScanContext),
subtitle: Text(entry.context),
),
ListTile(
title: Text(L10().barcodeScanData),
subtitle: SelectableText(entry.displayBarcode, style: _monospace),
),
ListTile(
title: Text(L10().barcodeScanResponse),
subtitle: entry.response == null
? Text(L10().barcodeScanNoResponse)
: SelectableText(entry.responseText, style: _monospace),
),
],
),
);
}
}
+353
View File
@@ -0,0 +1,353 @@
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_test/flutter_test.dart";
import "package:flutter_tabler_icons/flutter_tabler_icons.dart";
import "package:inventree/api.dart";
import "package:inventree/barcode/barcode.dart";
import "package:inventree/barcode/handler.dart";
import "package:inventree/barcode/scan_log.dart";
import "package:inventree/barcode/wedge_controller.dart";
import "package:inventree/helpers.dart";
import "package:inventree/widget/barcode_scan_log.dart";
import "setup.dart";
import "widget/harness.dart";
// Handler with a fixed log context (there is no app context in tests)
class _TestHandler extends BarcodeHandler {
@override
String get scanLogContext => "Test context";
}
BarcodeScanLogEntry _entry(
String barcode, {
bool success = true,
int? statusCode = 200,
dynamic response = const {"success": "Match found"},
DateTime? timestamp,
}) {
return BarcodeScanLogEntry(
timestamp: timestamp ?? DateTime.now(),
context: "Scan stock location",
barcode: barcode,
success: success,
url: "barcode/",
statusCode: statusCode,
response: response,
);
}
void main() {
setupTestEnv();
mockSharedPreferences();
setUp(() {
BarcodeScanLog().clear();
});
group("Scan log store", () {
test("Entries are newest first", () {
BarcodeScanLog().add(_entry("first"));
BarcodeScanLog().add(_entry("second"));
expect(BarcodeScanLog().entries.map((e) => e.barcode), [
"second",
"first",
]);
});
test("Oldest entries are discarded beyond the limit", () {
for (int i = 0; i < BarcodeScanLog.maxEntries + 5; i++) {
BarcodeScanLog().add(_entry("code$i"));
}
expect(BarcodeScanLog().length, BarcodeScanLog.maxEntries);
expect(BarcodeScanLog().entries.first.barcode, "code104");
expect(BarcodeScanLog().entries.last.barcode, "code5");
});
test("Clear empties the log and notifies listeners", () {
int notified = 0;
void listener() => notified++;
BarcodeScanLog().addListener(listener);
BarcodeScanLog().add(_entry("abc"));
BarcodeScanLog().clear();
BarcodeScanLog().removeListener(listener);
expect(BarcodeScanLog().isEmpty, isTrue);
expect(notified, 2);
});
test("Entries cannot be modified from outside", () {
BarcodeScanLog().add(_entry("abc"));
expect(() => BarcodeScanLog().entries.clear(), throwsUnsupportedError);
});
});
group("Scan log entry", () {
test("Control characters are shown as visible symbols", () {
expect(visibleControlCharacters("[)>\x1E06\x1DP1\x04"), "[)>␞06␝P1␄");
expect(visibleControlCharacters("plain"), "plain");
});
test("Response is pretty-printed JSON", () {
final entry = _entry(
"abc",
response: {
"part": {"pk": 1},
},
);
expect(entry.responseText, contains('"pk": 1'));
expect(entry.responseText, contains("\n"));
});
test("Missing response is reported as such", () {
final entry = _entry("abc", statusCode: null, response: null);
expect(entry.hasResponse, isFalse);
expect(entry.responseText, isEmpty);
});
});
group("Scan success rules", () {
final handler = BarcodeHandler();
bool check(BarcodeHandler h, int code, Map<String, dynamic> data) =>
h.isScanSuccessful(APIResponse(statusCode: code, data: data), data);
test("Default handler", () {
expect(check(handler, 200, {"success": "Match", "part": {}}), isTrue);
expect(check(handler, 200, {"action_required": "x"}), isTrue);
expect(check(handler, 400, {"error": "No match found"}), isFalse);
expect(check(handler, 200, {"error": "Something"}), isFalse);
expect(check(handler, -1, {}), isFalse);
});
test("Unique (assign) handler treats an unknown barcode as success", () {
final unique = UniqueBarcodeHandler((_) {});
expect(
check(unique, 400, {
"error": "No match found",
"barcode_hash": "abc123",
"barcode_data": "NEWCODE",
}),
isTrue,
);
expect(check(unique, 200, {"success": "Match"}), isFalse);
});
});
group("Scans are recorded", () {
test("A failed request is logged with context and barcode", () async {
await _TestHandler().processBarcode(" LOGME123 ");
expect(BarcodeScanLog().length, 1);
final entry = BarcodeScanLog().entries.first;
expect(entry.barcode, "LOGME123");
expect(entry.context, "Test context");
expect(entry.url, "barcode/");
expect(entry.success, isFalse);
});
test("An empty barcode is not logged", () async {
await _TestHandler().processBarcode(" ");
expect(BarcodeScanLog().isEmpty, isTrue);
});
});
group("Scan log widgets", () {
testWidgets("Empty log", (tester) async {
await pumpScreen(tester, const BarcodeScanLogWidget());
expect(find.text("No barcodes scanned"), findsOneWidget);
expect(find.byKey(const Key("barcodeScanLogClear")), findsNothing);
});
testWidgets("List, detail and clear", (tester) async {
BarcodeScanLog().add(
_entry(
"LOC\x1D001",
response: {
"stocklocation": {"pk": 42},
},
),
);
BarcodeScanLog().add(
_entry(
"BAD",
success: false,
statusCode: 400,
response: {"error": "No match found"},
),
);
await pumpScreen(tester, const BarcodeScanLogWidget());
// Newest first, control characters visible
expect(find.text("BAD"), findsOneWidget);
expect(find.text("LOC␝001"), findsOneWidget);
// Server response is only shown in the detail view
expect(find.textContaining('"pk": 42'), findsNothing);
await tester.tap(find.text("LOC␝001"));
await tester.pumpAndSettle();
expect(find.text("Success"), findsOneWidget);
expect(find.text("Scan stock location"), findsOneWidget);
expect(find.textContaining('"pk": 42'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
// A new scan appears in the open list
BarcodeScanLog().add(_entry("LIVE"));
await tester.pump();
expect(find.text("LIVE"), findsOneWidget);
// Clearing asks for confirmation - cancel keeps the log
await tester.tap(find.byKey(const Key("barcodeScanLogClear")));
await tester.pumpAndSettle();
expect(
find.text("Remove all entries from the barcode scan log?"),
findsOneWidget,
);
await tester.tap(find.byKey(const Key("barcodeScanLogClearCancel")));
await tester.pumpAndSettle();
expect(BarcodeScanLog().length, 3);
expect(find.text("LIVE"), findsOneWidget);
// Confirming clears it
await tester.tap(find.byKey(const Key("barcodeScanLogClear")));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key("barcodeScanLogClearConfirm")));
await tester.pumpAndSettle();
expect(BarcodeScanLog().isEmpty, isTrue);
expect(find.text("No barcodes scanned"), findsOneWidget);
});
testWidgets("Last scan bar starts empty each time the scanner opens", (
tester,
) async {
// Scanned during an earlier visit to the scanner
BarcodeScanLog().add(
_entry(
"PREVIOUS",
timestamp: DateTime.now().subtract(const Duration(minutes: 1)),
),
);
await pumpScreen(tester, WedgeBarcodeController(BarcodeScanHandler()));
expect(find.byKey(const Key("barcodeLastScan")), findsNothing);
expect(find.text("PREVIOUS"), findsNothing);
// ...but is still in the scan log
expect(BarcodeScanLog().latest?.barcode, "PREVIOUS");
// A scan made on this visit is shown
BarcodeScanLog().add(_entry("THISVISIT"));
await tester.pump();
expect(find.byKey(const Key("barcodeLastScan")), findsOneWidget);
expect(find.text("THISVISIT"), findsOneWidget);
// Let the scanner's pending timers complete
await tester.pump(const Duration(seconds: 1));
});
testWidgets("Scanner shows the most recent scan at the bottom", (
tester,
) async {
await pumpScreen(tester, WedgeBarcodeController(BarcodeScanHandler()));
// Nothing scanned yet
expect(find.byKey(const Key("barcodeLastScan")), findsNothing);
BarcodeScanLog().add(_entry("OLDER\x1E1"));
BarcodeScanLog().add(_entry("NEWEST\x1E2", success: false));
await tester.pump();
final bar = find.byKey(const Key("barcodeLastScan"));
expect(bar, findsOneWidget);
// Only the latest scan is shown, with its context and status
expect(
find.descendant(of: bar, matching: find.text("NEWEST␞2")),
findsOneWidget,
);
expect(find.text("OLDER␞1"), findsNothing);
expect(
find.descendant(
of: bar,
matching: find.textContaining("Scan stock location"),
),
findsOneWidget,
);
expect(
find.descendant(of: bar, matching: find.byIcon(TablerIcons.circle_x)),
findsOneWidget,
);
// Updates live as new scans arrive
BarcodeScanLog().add(_entry("LATEST"));
await tester.pump();
expect(find.text("NEWEST␞2"), findsNothing);
expect(
find.descendant(
of: bar,
matching: find.byIcon(TablerIcons.circle_check),
),
findsOneWidget,
);
// Tapping opens the detail view for that scan
await tester.tap(bar);
await tester.pump(const Duration(seconds: 1));
expect(find.byType(BarcodeScanLogDetailWidget), findsOneWidget);
expect(find.textContaining('"success": "Match found"'), findsOneWidget);
await tester.pageBack();
await tester.pump(const Duration(seconds: 1));
});
testWidgets("Opened from the scanner, which keeps working after", (
tester,
) async {
await pumpScreen(tester, WedgeBarcodeController(BarcodeScanHandler()));
await tester.tap(find.byKey(const Key("barcodeScanLog")));
// The scanner spinner never settles
await tester.pump(const Duration(seconds: 1));
expect(find.byType(BarcodeScanLogWidget), findsOneWidget);
await tester.pageBack();
// The scanner spinner never settles
await tester.pump(const Duration(seconds: 1));
// Wedge input is still received after returning
for (final key in [
LogicalKeyboardKey.keyL,
LogicalKeyboardKey.keyO,
LogicalKeyboardKey.keyG,
]) {
await simulateKeyDownEvent(key);
await simulateKeyUpEvent(key);
}
await simulateKeyDownEvent(LogicalKeyboardKey.enter, character: "\n");
await simulateKeyUpEvent(LogicalKeyboardKey.enter);
expect(debugContains("scanned: log", raiseAssert: false), isTrue);
// Let the controller's resume timer complete
await tester.pump(const Duration(seconds: 1));
});
});
}
+297
View File
@@ -5,6 +5,49 @@ import "package:inventree/barcode/barcode.dart";
import "package:inventree/barcode/wedge_controller.dart";
import "package:inventree/helpers.dart";
// ASCII separators used by ISO/IEC 15434 (e.g. DigiKey / Mouser DataMatrix)
const String RS = "\x1E";
const String GS = "\x1D";
const String EOT = "\x04";
/*
* Build a key-down event exactly as Flutter delivers it on Android
* for a Ctrl+<key> combination: getUnicodeChar() returns 0, so character is null
*/
KeyDownEvent androidCtrlKeyDown(LogicalKeyboardKey key) {
return KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyA,
logicalKey: key,
character: null,
timeStamp: Duration.zero,
);
}
Future<void> typeCtrl(LogicalKeyboardKey key, {bool shift = false}) async {
await simulateKeyDownEvent(LogicalKeyboardKey.controlLeft);
if (shift) await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft);
await simulateKeyDownEvent(key);
await simulateKeyUpEvent(key);
if (shift) await simulateKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await simulateKeyUpEvent(LogicalKeyboardKey.controlLeft);
}
Future<void> typeText(String text) async {
for (final String c in text.split("")) {
// Shifted symbols are sent on their physical (unshifted) key
const Map<String, LogicalKeyboardKey> symbols = {
"\n": LogicalKeyboardKey.enter,
"[": LogicalKeyboardKey.bracketLeft,
")": LogicalKeyboardKey.digit0,
">": LogicalKeyboardKey.period,
};
final LogicalKeyboardKey key =
symbols[c] ?? LogicalKeyboardKey.findKeyByKeyId(c.codeUnitAt(0))!;
await simulateKeyDownEvent(key, character: c);
await simulateKeyUpEvent(key);
}
}
void main() {
testWidgets("Wedge Scanner Test", (tester) async {
await tester.pumpWidget(
@@ -26,4 +69,258 @@ void main() {
debugContains("showServerError");
expect(debugContains("No match for barcode", raiseAssert: false), isFalse);
});
group("Wedge control characters (#542)", () {
test("Ctrl combos with null character map to separators", () {
// This is the Android case which previously dropped the character
expect(
wedgeCharacterForEvent(
androidCtrlKeyDown(LogicalKeyboardKey.bracketRight),
ctrlPressed: true,
),
GS,
);
expect(
wedgeCharacterForEvent(
androidCtrlKeyDown(LogicalKeyboardKey.digit6),
ctrlPressed: true,
),
RS,
);
expect(
wedgeCharacterForEvent(
androidCtrlKeyDown(LogicalKeyboardKey.caret),
ctrlPressed: true,
),
RS,
);
expect(
wedgeCharacterForEvent(
androidCtrlKeyDown(LogicalKeyboardKey.keyD),
ctrlPressed: true,
),
EOT,
);
});
test("Platform-supplied control characters are preserved", () {
// Desktop / iOS may already report the control character itself
for (final String c in [RS, GS, EOT]) {
final event = KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyA,
logicalKey: LogicalKeyboardKey.keyA,
character: c,
timeStamp: Duration.zero,
);
expect(wedgeCharacterForEvent(event, ctrlPressed: false), c);
}
});
test("Normal characters and bare modifiers are unchanged", () {
final event = KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyA,
logicalKey: LogicalKeyboardKey.keyA,
character: "a",
timeStamp: Duration.zero,
);
expect(wedgeCharacterForEvent(event, ctrlPressed: false), "a");
// Without Ctrl, a null character is still ignored
expect(
wedgeCharacterForEvent(
androidCtrlKeyDown(LogicalKeyboardKey.bracketRight),
ctrlPressed: false,
),
isNull,
);
// The Ctrl key itself produces nothing
expect(
wedgeCharacterForEvent(
androidCtrlKeyDown(LogicalKeyboardKey.controlLeft),
ctrlPressed: true,
),
isNull,
);
});
testWidgets("ISO 15434 DataMatrix scan keeps RS / GS / EOT", (
tester,
) async {
await tester.pumpWidget(
MaterialApp(home: WedgeBarcodeController(BarcodeScanHandler())),
);
// [)>{RS}06{GS}pABC{RS}{EOT} (structure of a DigiKey label)
await typeText("[)>");
await typeCtrl(LogicalKeyboardKey.digit6, shift: true); // RS
await typeText("06");
await typeCtrl(LogicalKeyboardKey.bracketRight); // GS
await typeText("pabc");
await typeCtrl(LogicalKeyboardKey.digit6, shift: true); // RS
await typeCtrl(LogicalKeyboardKey.keyD); // EOT
await simulateKeyDownEvent(LogicalKeyboardKey.enter, character: "\n");
expect(
debugContains(
"scanned: [)>${RS}06${GS}pabc$RS$EOT",
raiseAssert: false,
),
isTrue,
);
});
});
group("Wedge multi-barcode blanking (#625)", () {
final DateTime t0 = DateTime(2026);
DateTime at(int ms) => t0.add(Duration(milliseconds: ms));
// Feed a string one character every [gapMs], starting at [startMs].
// Returns every completed barcode.
List<String> feed(
WedgeScanBuffer buffer,
String text, {
int startMs = 0,
int gapMs = 10,
bool accepting = true,
}) {
final List<String> results = [];
int ms = startMs;
for (final String c in text.split("")) {
final String? result = buffer.addCharacter(
c,
at(ms),
accepting: accepting,
);
if (result != null) results.add(result);
ms += gapMs;
}
return results;
}
test("Only the first barcode in a multi-barcode burst is returned", () {
final buffer = WedgeScanBuffer();
expect(feed(buffer, "first\nsecond\nthird\n"), ["first"]);
});
test("Long trailing barcodes are never resumed part-way", () {
// The trailing burst (300 chars @ 10ms = 3s) far outlasts the
// blanking period, but keeps extending it, so no fragment leaks out
final buffer = WedgeScanBuffer();
final String trailing = "${"x" * 150}\n${"y" * 150}\n";
expect(feed(buffer, "first\n$trailing"), ["first"]);
});
test("A new scan after the quiet period is accepted", () {
final buffer = WedgeScanBuffer();
expect(feed(buffer, "first\nsecond\n"), ["first"]);
// Last key at 120ms; blanking ends at 620ms
expect(feed(buffer, "early\n", startMs: 400), isEmpty);
expect(feed(buffer, "next\n", startMs: 1200), ["next"]);
});
test("Input while paused is discarded and blanks its continuation", () {
final buffer = WedgeScanBuffer();
// Scanner paused part-way through a barcode, then resumed
expect(feed(buffer, "abcdef", accepting: false), isEmpty);
expect(feed(buffer, "ghij\n", startMs: 60), isEmpty);
expect(feed(buffer, "fresh\n", startMs: 1000), ["fresh"]);
});
test("Characters within a barcode still time out", () {
final buffer = WedgeScanBuffer();
expect(feed(buffer, "stale"), isEmpty);
expect(feed(buffer, "new\n", startMs: 1000), ["new"]);
});
test("Empty lines do not start blanking", () {
final buffer = WedgeScanBuffer();
expect(feed(buffer, "\n\nabc\n"), ["abc"]);
});
testWidgets("Controller submits only the first of several barcodes", (
tester,
) async {
await tester.pumpWidget(
MaterialApp(home: WedgeBarcodeController(BarcodeScanHandler())),
);
await typeText("multia\n");
await typeText("multib\n");
expect(debugContains("scanned: multia", raiseAssert: false), isTrue);
expect(debugContains("multib", raiseAssert: false), isFalse);
// Let the controller's resume timer complete
await tester.pump(const Duration(seconds: 1));
});
group("Scans without a terminating newline", () {
test("Flush returns the buffered barcode", () {
final buffer = WedgeScanBuffer();
expect(feed(buffer, "noenter"), isEmpty);
expect(buffer.hasPendingCharacters, isTrue);
expect(buffer.flush(at(400)), "noenter");
expect(buffer.hasPendingCharacters, isFalse);
// Nothing left to flush
expect(buffer.flush(at(500)), isNull);
});
test("Flushed barcode starts the blanking period", () {
final buffer = WedgeScanBuffer();
feed(buffer, "first");
expect(buffer.flush(at(300)), "first");
// Trailing input is discarded, and keeps the window open
expect(feed(buffer, "second\n", startMs: 400), isEmpty);
expect(buffer.flush(at(600)), isNull);
expect(feed(buffer, "third\n", startMs: 1500), ["third"]);
});
test("Short input is discarded rather than submitted", () {
final buffer = WedgeScanBuffer();
feed(buffer, "abc");
expect(buffer.flush(at(300)), isNull);
expect(buffer.hasPendingCharacters, isFalse);
// ...and does not start the blanking period
expect(feed(buffer, "next\n", startMs: 310), ["next"]);
});
testWidgets("Controller submits after the character timeout", (
tester,
) async {
await tester.pumpWidget(
MaterialApp(home: WedgeBarcodeController(BarcodeScanHandler())),
);
await typeText("timeoutscan");
expect(debugContains("timeoutscan", raiseAssert: false), isFalse);
await tester.pump(const Duration(milliseconds: 300));
expect(
debugContains("scanned: timeoutscan", raiseAssert: false),
isTrue,
);
// Let the controller's resume timer complete
await tester.pump(const Duration(seconds: 1));
});
testWidgets("Controller ignores a short stray key press", (tester) async {
await tester.pumpWidget(
MaterialApp(home: WedgeBarcodeController(BarcodeScanHandler())),
);
await typeText("qz");
await tester.pump(const Duration(milliseconds: 300));
expect(debugContains("scanned: qz", raiseAssert: false), isFalse);
});
});
});
}