migliorata scansione barcode

This commit is contained in:
brontomark committed 2026-11-11 10:25:12 +01:00
1 parent 77caf8241e
commit 7bf0ae9725
18 files changed
+2795 -152

No files matched your search

@@ -22,6 +22,7 @@ class AppConstants {
static const String keyContinuous = 'continuous_mode';
static const String keyVibrate = 'vibrate_enabled';
static const String keySound = 'sound_enabled';
static const String keyAimMode = 'scan_aim_mode';
static const String keyHistory = 'scan_history';
// Suffix options
@@ -0,0 +1,59 @@
import 'package:flutter/services.dart';
/// Represents a detected barcode mapped into widget coordinates for AR overlays.
class DetectedBarcodeItem {
final int index;
final String code;
final String format;
final List<Offset> corners;
final Rect boundingRect;
final Offset center;
final Color color;
const DetectedBarcodeItem({
required this.index,
required this.code,
required this.format,
required this.corners,
required this.boundingRect,
required this.center,
required this.color,
});
String get selectionKey =>
'$code@${center.dx.round()}_${center.dy.round()}';
DetectedBarcodeItem copyWith({
int? index,
Color? color,
}) {
return DetectedBarcodeItem(
index: index ?? this.index,
code: code,
format: format,
corners: corners,
boundingRect: boundingRect,
center: center,
color: color ?? this.color,
);
}
}
/// Snapshot of a captured camera frame with all mapped barcodes for Freeze & Pick.
class ArCaptureSnapshot {
final Uint8List imageBytes;
final Size imageSize;
final Size viewportSize;
final DeviceOrientation deviceOrientation;
final List<DetectedBarcodeItem> items;
final DateTime timestamp;
const ArCaptureSnapshot({
required this.imageBytes,
required this.imageSize,
required this.viewportSize,
required this.deviceOrientation,
required this.items,
required this.timestamp,
});
}
@@ -0,0 +1,26 @@
enum ScanAimMode {
standard,
precision,
arMulti;
String get label {
switch (this) {
case ScanAimMode.standard:
return 'Standard';
case ScanAimMode.precision:
return 'Precisione';
case ScanAimMode.arMulti:
return 'AR Multi';
}
}
String get storageKey => name;
static ScanAimMode fromStorageKey(String? value) {
return ScanAimMode.values.firstWhere(
(mode) => mode.name == value,
orElse: () => ScanAimMode.standard,
);
}
}
@@ -27,7 +27,16 @@ class ScannerCubit extends Cubit<ScannerState> {
emit(state.copyWith(isFrontCamera: !state.isFrontCamera));
}
Future<void> processBarcode(String rawValue, {String format = 'Barcode'}) async {
void setZoomScale(double scale) {
final clamped = scale.clamp(0.0, 1.0);
if ((clamped - state.zoomScale).abs() < 0.001) return;
emit(state.copyWith(zoomScale: clamped));
}
Future<void> processBarcode(
String rawValue, {
String format = 'Barcode',
}) async {
final cleanCode = rawValue.trim();
if (cleanCode.isEmpty) return;
@@ -36,19 +45,59 @@ class ScannerCubit extends Cubit<ScannerState> {
final durationSinceLast = now.difference(state.lastScannedTime);
final continuous = settingsCubit.state.settings.continuousMode;
// Minimum debounce interval
// Minimum debounce interval for live camera stream
final minInterval = isSameCode
? (continuous ? const Duration(milliseconds: 1000) : const Duration(milliseconds: 1800))
? (continuous
? const Duration(milliseconds: 1000)
: const Duration(milliseconds: 1800))
: const Duration(milliseconds: 600);
if (durationSinceLast < minInterval || state.isProcessing) {
return;
}
await _sendAndRecord(cleanCode, format: format, timestamp: now);
}
/// Sends a barcode explicitly chosen by the user (e.g. from AR badge or frozen picker),
/// bypassing the live-camera debounce so rapid multi-code picking feels instant.
Future<bool> sendSelectedBarcode(
String rawValue, {
String format = 'Barcode',
}) async {
final cleanCode = rawValue.trim();
if (cleanCode.isEmpty || state.isProcessing) return false;
final record = await _sendAndRecord(
cleanCode,
format: format,
timestamp: DateTime.now(),
);
return record.sentSuccessfully;
}
Future<void> resendScan(ScanRecord record) async {
if (state.isProcessing) return;
await _sendAndRecord(
record.code,
format: record.format,
timestamp: DateTime.now(),
idOverride: record.id,
updateDebounceTracker: false,
);
}
Future<ScanRecord> _sendAndRecord(
String cleanCode, {
required String format,
required DateTime timestamp,
String? idOverride,
bool updateDebounceTracker = true,
}) async {
emit(state.copyWith(
isProcessing: true,
lastScannedValue: cleanCode,
lastScannedTime: now,
lastScannedValue: updateDebounceTracker ? cleanCode : state.lastScannedValue,
lastScannedTime: updateDebounceTracker ? timestamp : state.lastScannedTime,
));
final settings = settingsCubit.state.settings;
@@ -67,10 +116,10 @@ class ScannerCubit extends Cubit<ScannerState> {
}
final record = ScanRecord(
id: DateTime.now().millisecondsSinceEpoch.toString(),
id: idOverride ?? DateTime.now().millisecondsSinceEpoch.toString(),
code: cleanCode,
format: format,
timestamp: now,
timestamp: timestamp,
sentSuccessfully: success,
);
@@ -80,30 +129,7 @@ class ScannerCubit extends Cubit<ScannerState> {
isProcessing: false,
lastScan: record,
));
}
Future<void> resendScan(ScanRecord record) async {
final settings = settingsCubit.state.settings;
await feedbackService.triggerScanFeedback(
sound: settings.sound,
vibrate: settings.vibrate,
);
final success = await connectionCubit.sendCode(
code: record.code,
suffix: settings.suffix,
);
if (success) {
await feedbackService.triggerSuccess();
}
final updated = record.copyWith(
timestamp: DateTime.now(),
sentSuccessfully: success,
);
await historyCubit.addScan(updated);
emit(state.copyWith(lastScan: updated));
return record;
}
}
@@ -8,6 +8,7 @@ class ScannerState extends Equatable {
final bool isProcessing;
final String? lastScannedValue;
final DateTime lastScannedTime;
final double zoomScale;
ScannerState({
this.lastScan,
@@ -16,7 +17,9 @@ class ScannerState extends Equatable {
this.isProcessing = false,
this.lastScannedValue,
DateTime? lastScannedTime,
}) : lastScannedTime = lastScannedTime ?? DateTime.fromMillisecondsSinceEpoch(0);
this.zoomScale = 0.0,
}) : lastScannedTime =
lastScannedTime ?? DateTime.fromMillisecondsSinceEpoch(0);
ScannerState copyWith({
ScanRecord? lastScan,
@@ -25,6 +28,7 @@ class ScannerState extends Equatable {
bool? isProcessing,
String? lastScannedValue,
DateTime? lastScannedTime,
double? zoomScale,
}) {
return ScannerState(
lastScan: lastScan ?? this.lastScan,
@@ -33,6 +37,7 @@ class ScannerState extends Equatable {
isProcessing: isProcessing ?? this.isProcessing,
lastScannedValue: lastScannedValue ?? this.lastScannedValue,
lastScannedTime: lastScannedTime ?? this.lastScannedTime,
zoomScale: zoomScale ?? this.zoomScale,
);
}
@@ -44,6 +49,6 @@ class ScannerState extends Equatable {
isProcessing,
lastScannedValue,
lastScannedTime,
zoomScale,
];
}
@@ -1,18 +1,29 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../../../../core/services/feedback_service.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/widgets/connection_status_chip.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../settings/presentation/cubit/settings_cubit.dart';
import '../../../settings/presentation/cubit/settings_state.dart';
import '../../../settings/presentation/screens/settings_screen.dart';
import '../../domain/entities/detected_barcode_item.dart';
import '../../domain/entities/scan_aim_mode.dart';
import '../cubit/history_cubit.dart';
import '../cubit/history_state.dart';
import '../cubit/scanner_cubit.dart';
import '../cubit/scanner_state.dart';
import '../utils/barcode_geometry.dart';
import '../widgets/ar_barcode_overlay.dart';
import '../widgets/ar_frozen_picker.dart';
import '../widgets/last_scan_card.dart';
import '../widgets/manual_input_dialog.dart';
import '../widgets/scanner_controls_bar.dart';
import '../widgets/scanner_overlay.dart';
import 'history_screen.dart';
@@ -23,26 +34,61 @@ class ScannerScreen extends StatefulWidget {
State<ScannerScreen> createState() => _ScannerScreenState();
}
class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserver {
class _ScannerScreenState extends State<ScannerScreen>
with WidgetsBindingObserver {
late MobileScannerController _scannerController;
DateTime? _pausedTime;
bool _isSelectionSheetOpen = false;
Size _viewportSize = Size.zero;
double _zoomAtScaleStart = 0.0;
bool _autoZoomedForPrecision = false;
// Live AR & Precision targeting state
List<DetectedBarcodeItem> _liveArItems = const [];
int? _precisionTargetIndex;
Timer? _arDecayTimer;
// Freeze & Pick AR state
ArCaptureSnapshot? _latestArSnapshot;
ArCaptureSnapshot? _frozenSnapshot;
bool _pendingFreeze = false;
final Set<String> _sentFrozenKeys = <String>{};
// Tap-to-focus indicator state
Offset? _focusRingPosition;
Timer? _focusRingTimer;
static const _feedbackService = FeedbackService();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_scannerController = MobileScannerController(
detectionSpeed: DetectionSpeed.normal,
detectionTimeoutMs: 180,
cameraResolution: const Size(1920, 1080),
facing: CameraFacing.back,
torchEnabled: false,
returnImage: true,
);
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkStartupConnection();
_applyInitialModeZoom();
});
}
void _applyInitialModeZoom() {
if (!mounted) return;
final aimMode = context.read<SettingsCubit>().state.settings.aimMode;
if (aimMode == ScanAimMode.precision) {
_autoZoomedForPrecision = true;
_applyZoomScale(0.25, manual: false);
}
}
Future<void> _checkStartupConnection() async {
final settingsCubit = context.read<SettingsCubit>();
final connectionCubit = context.read<ConnectionCubit>();
@@ -70,6 +116,8 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_arDecayTimer?.cancel();
_focusRingTimer?.cancel();
_scannerController.dispose();
super.dispose();
}
@@ -77,11 +125,18 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (!_scannerController.value.isInitialized) return;
if (state == AppLifecycleState.inactive || state == AppLifecycleState.paused) {
if (state == AppLifecycleState.inactive ||
state == AppLifecycleState.paused) {
_scannerController.stop();
_pausedTime = DateTime.now();
} else if (state == AppLifecycleState.resumed) {
_scannerController.start();
_scannerController.start().then((_) {
if (!mounted) return;
final savedZoom = context.read<ScannerCubit>().state.zoomScale;
if (savedZoom > 0.01) {
_applyZoomScale(savedZoom, manual: false);
}
});
_onAppResumed();
}
}
@@ -114,16 +169,240 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
}
}
Future<void> _applyZoomScale(double scale, {required bool manual}) async {
final clamped = scale.clamp(0.0, 1.0);
if (manual) {
_autoZoomedForPrecision = false;
}
context.read<ScannerCubit>().setZoomScale(clamped);
if (!_scannerController.value.isRunning) return;
try {
await _scannerController.setZoomScale(clamped);
} catch (_) {}
}
Future<void> _onAimModeChanged(ScanAimMode nextMode) async {
final settingsCubit = context.read<SettingsCubit>();
final prevMode = settingsCubit.state.settings.aimMode;
if (prevMode == nextMode) return;
await _feedbackService.triggerSelection();
await settingsCubit.updateAimMode(nextMode);
if (!mounted) return;
_arDecayTimer?.cancel();
setState(() {
_liveArItems = const [];
_precisionTargetIndex = null;
_latestArSnapshot = null;
_frozenSnapshot = null;
_pendingFreeze = false;
_sentFrozenKeys.clear();
});
final currentZoom = context.read<ScannerCubit>().state.zoomScale;
if (nextMode == ScanAimMode.precision && currentZoom < 0.05) {
_autoZoomedForPrecision = true;
await _applyZoomScale(0.25, manual: false);
} else if (prevMode == ScanAimMode.precision &&
nextMode != ScanAimMode.precision &&
_autoZoomedForPrecision) {
_autoZoomedForPrecision = false;
await _applyZoomScale(0.0, manual: false);
}
}
void _onDetect(BarcodeCapture capture) {
if (!mounted || _frozenSnapshot != null || _viewportSize.isEmpty) return;
final aimMode = context.read<SettingsCubit>().state.settings.aimMode;
final deviceOrientation = _scannerController.value.deviceOrientation;
switch (aimMode) {
case ScanAimMode.standard:
if (_liveArItems.isNotEmpty || _precisionTargetIndex != null) {
setState(() {
_liveArItems = const [];
_precisionTargetIndex = null;
});
}
final barcodes = capture.barcodes;
if (barcodes.isEmpty) return;
final first = barcodes.first;
final rawValue = first.rawValue ?? first.displayValue;
if (rawValue == null || rawValue.trim().isEmpty) return;
final formatName = first.format.name.replaceAll('BarcodeFormat.', '');
context.read<ScannerCubit>().processBarcode(rawValue, format: formatName);
case ScanAimMode.precision:
final items = BarcodeGeometry.mapCaptureToItems(
capture: capture,
widgetSize: _viewportSize,
deviceOrientation: deviceOrientation,
);
if (items.isEmpty) return;
final crosshairCenter =
ScannerReticleGeometry.precisionCrosshairCenter(_viewportSize);
final target = BarcodeGeometry.selectPrecisionTarget(
items: items,
crosshairCenter: crosshairCenter,
hitRadius: 16.0,
);
_updateLiveArItems(items, precisionTargetIndex: target?.index);
if (target != null) {
context.read<ScannerCubit>().processBarcode(
target.code,
format: target.format,
);
}
case ScanAimMode.arMulti:
final items = BarcodeGeometry.mapCaptureToItems(
capture: capture,
widgetSize: _viewportSize,
deviceOrientation: deviceOrientation,
);
if (items.isEmpty) return;
_updateLiveArItems(items);
final imageBytes = capture.image;
if (imageBytes != null && imageBytes.isNotEmpty) {
final snapshot = ArCaptureSnapshot(
imageBytes: imageBytes,
imageSize: capture.size,
viewportSize: _viewportSize,
deviceOrientation: deviceOrientation,
items: items,
timestamp: DateTime.now(),
);
_latestArSnapshot = snapshot;
if (_pendingFreeze) {
_pendingFreeze = false;
_freezeWithSnapshot(snapshot);
}
}
}
}
void _updateLiveArItems(
List<DetectedBarcodeItem> items, {
int? precisionTargetIndex,
}) {
_arDecayTimer?.cancel();
setState(() {
_liveArItems = items;
_precisionTargetIndex = precisionTargetIndex;
});
_arDecayTimer = Timer(const Duration(milliseconds: 450), () {
if (!mounted || _frozenSnapshot != null) return;
setState(() {
_liveArItems = const [];
_precisionTargetIndex = null;
});
});
}
void _requestFreeze() {
final snapshot = _latestArSnapshot;
final isFresh = snapshot != null &&
DateTime.now().difference(snapshot.timestamp) <=
const Duration(milliseconds: 1500);
if (isFresh) {
_freezeWithSnapshot(snapshot);
return;
}
_feedbackService.triggerSelection();
setState(() {
_pendingFreeze = true;
});
}
void _cancelPendingFreeze() {
setState(() {
_pendingFreeze = false;
});
}
void _freezeWithSnapshot(ArCaptureSnapshot snapshot) {
_arDecayTimer?.cancel();
_feedbackService.triggerSelection();
setState(() {
_frozenSnapshot = snapshot;
_pendingFreeze = false;
_sentFrozenKeys.clear();
});
}
void _resumeLiveFromFreeze() {
_feedbackService.triggerSelection();
setState(() {
_frozenSnapshot = null;
_pendingFreeze = false;
_sentFrozenKeys.clear();
});
}
Future<void> _onTapArBarcode(DetectedBarcodeItem item) async {
final success = await context.read<ScannerCubit>().sendSelectedBarcode(
item.code,
format: item.format,
);
if (!mounted) return;
if (_frozenSnapshot != null && success) {
setState(() {
_sentFrozenKeys.add(item.selectionKey);
});
} else if (_frozenSnapshot == null) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(
success
? 'Inviato al PC: ${item.code}'
: 'Codice salvato in cronologia (PC non connesso)',
),
duration: const Duration(milliseconds: 1100),
backgroundColor: AppTheme.darkCard,
),
);
}
}
Future<void> _handleTapToFocus(TapUpDetails details) async {
if (_frozenSnapshot != null ||
_viewportSize.isEmpty ||
!_scannerController.value.isRunning) {
return;
}
final local = details.localPosition;
final rx = (local.dx / _viewportSize.width).clamp(0.0, 1.0);
final ry = (local.dy / _viewportSize.height).clamp(0.0, 1.0);
_focusRingTimer?.cancel();
setState(() {
_focusRingPosition = local;
});
_focusRingTimer = Timer(const Duration(milliseconds: 700), () {
if (mounted) {
setState(() => _focusRingPosition = null);
}
});
try {
await _scannerController.setFocusPoint(Offset(rx, ry));
} catch (_) {}
}
void _toggleTorch() {
@@ -134,45 +413,121 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
void _switchCamera() {
_scannerController.switchCamera();
context.read<ScannerCubit>().toggleCamera();
context.read<ScannerCubit>().setZoomScale(0.0);
_autoZoomedForPrecision = false;
}
@override
Widget build(BuildContext context) {
return Scaffold(
return PopScope(
canPop: _frozenSnapshot == null,
onPopInvokedWithResult: (didPop, _) {
if (!didPop && _frozenSnapshot != null) {
_resumeLiveFromFreeze();
}
},
child: Scaffold(
backgroundColor: Colors.black,
body: BlocBuilder<ScannerCubit, ScannerState>(
body: BlocBuilder<SettingsCubit, SettingsState>(
builder: (context, settingsState) {
final aimMode = settingsState.settings.aimMode;
return BlocBuilder<ScannerCubit, ScannerState>(
builder: (context, scannerState) {
final lastScan = scannerState.lastScan;
return LayoutBuilder(
builder: (context, constraints) {
_viewportSize = constraints.biggest;
final scanWindow = ScannerReticleGeometry.scanRect(
_viewportSize,
aimMode,
);
final topSafe = MediaQuery.paddingOf(context).top + 124.0;
final bottomReserved = (lastScan != null ? 250.0 : 165.0) +
(aimMode == ScanAimMode.arMulti ? 56.0 : 0.0) +
MediaQuery.paddingOf(context).bottom;
final safeBottom = (_viewportSize.height - bottomReserved)
.clamp(topSafe + 80.0, _viewportSize.height);
final arSafeBounds = Rect.fromLTRB(
12,
topSafe,
(_viewportSize.width - 12)
.clamp(24.0, _viewportSize.width),
safeBottom,
);
return Stack(
fit: StackFit.expand,
children: [
// 1. Camera Viewfinder
MobileScanner(
// 1. Camera Viewfinder + Tap-to-Focus + Pinch-to-Zoom
GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: _handleTapToFocus,
onScaleStart: (_) {
_zoomAtScaleStart = scannerState.zoomScale;
},
onScaleUpdate: (details) {
if (details.pointerCount < 2) return;
final nextZoom =
(_zoomAtScaleStart + (details.scale - 1.0) * 0.45)
.clamp(0.0, 1.0);
_applyZoomScale(nextZoom, manual: true);
},
child: MobileScanner(
controller: _scannerController,
scanWindow: scanWindow,
scanWindowUpdateThreshold: 4.0,
onDetect: _onDetect,
),
),
// 2. High-Tech Laser Reticle Overlay
const ScannerOverlay(),
// 2. Reticle Overlay (Standard / Precisione)
ScannerOverlay(
aimMode: aimMode,
hasPrecisionTarget: _precisionTargetIndex != null,
),
// 3. Top Floating Glass Control Bar (disposto su due righe per evitare overflow)
// 3. Live AR Overlay (outlines in Precisione, badges in AR Multi)
if (_frozenSnapshot == null &&
aimMode != ScanAimMode.standard &&
_liveArItems.isNotEmpty)
ArBarcodeOverlay(
items: _liveArItems,
safeBounds: arSafeBounds,
showBadges: aimMode == ScanAimMode.arMulti,
highlightedIndex: aimMode == ScanAimMode.precision
? _precisionTargetIndex
: null,
onTapBarcode: aimMode == ScanAimMode.arMulti
? _onTapArBarcode
: null,
),
// 4. Tap-to-Focus visual ring feedback
if (_focusRingPosition case final Offset focusPos)
IgnorePointer(
child: _FocusRingIndicator(position: focusPos),
),
// 5. Top Floating Glass Control Bar
if (_frozenSnapshot == null)
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Riga 1: Stato connessione / Nome host al centro
const Center(
child: ConnectionStatusChip(),
),
const Center(child: ConnectionStatusChip()),
const SizedBox(height: 10),
// Riga 2: Pulsanti di controllo rapidi
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
// Gruppo Sinistra: Torcia e Inverti Fotocamera
Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -180,31 +535,39 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
icon: scannerState.isTorchOn
? Icons.flash_on_rounded
: Icons.flash_off_rounded,
color: scannerState.isTorchOn ? Colors.amber : Colors.white,
color: scannerState.isTorchOn
? Colors.amber
: Colors.white,
tooltip: 'Torcia',
onPressed: _toggleTorch,
),
const SizedBox(width: 10),
_CircleGlassButton(
icon: Icons.flip_camera_ios_rounded,
icon: Icons
.flip_camera_ios_rounded,
tooltip: 'Inverti Fotocamera',
onPressed: _switchCamera,
),
],
),
// Gruppo Destra: Cronologia e Impostazioni
Row(
mainAxisSize: MainAxisSize.min,
children: [
BlocBuilder<HistoryCubit, HistoryState>(
BlocBuilder<HistoryCubit,
HistoryState>(
builder: (context, historyState) {
final count = historyState.history.length;
final count =
historyState.history.length;
return Badge(
isLabelVisible: count > 0,
label: Text(
count > 99 ? '99+' : count.toString(),
style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold),
count > 99
? '99+'
: count.toString(),
style: const TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
backgroundColor: AppTheme.primary,
textColor: Colors.white,
@@ -214,7 +577,10 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
tooltip: 'Cronologia',
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const HistoryScreen()),
MaterialPageRoute(
builder: (_) =>
const HistoryScreen(),
),
);
},
),
@@ -227,7 +593,10 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
tooltip: 'Impostazioni',
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
MaterialPageRoute(
builder: (_) =>
const SettingsScreen(),
),
);
},
),
@@ -240,39 +609,101 @@ class _ScannerScreenState extends State<ScannerScreen> with WidgetsBindingObserv
),
),
// 4. Floating Action Button for Manual Entry
Positioned(
bottom: lastScan != null ? 120 : 32,
right: 20,
child: FloatingActionButton.extended(
heroTag: 'scanner_manual_input',
backgroundColor: AppTheme.darkCard,
foregroundColor: AppTheme.primary,
elevation: 6,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: AppTheme.darkBorder, width: 1),
),
icon: const Icon(Icons.keyboard_rounded),
label: const Text(
'Manuale',
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: () => ManualInputDialog.show(context),
),
),
// 5. Bottom Last Scan Card
if (lastScan != null)
// 6. Bottom Controls Dock (Zoom, Freeze, Mode Switcher, Last Scan)
if (_frozenSnapshot == null)
Positioned(
left: 0,
right: 0,
bottom: 24,
child: LastScanCard(record: lastScan),
bottom: 0,
child: SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ScannerControlsBar(
aimMode: aimMode,
zoomScale: scannerState.zoomScale,
liveBarcodeCount: _liveArItems.length,
isPendingFreeze: _pendingFreeze,
onAimModeChanged: _onAimModeChanged,
onZoomPresetSelected: (scale) {
_feedbackService.triggerSelection();
_applyZoomScale(scale, manual: true);
},
onFreezePressed: _requestFreeze,
onCancelPendingFreeze:
_cancelPendingFreeze,
onManualInputPressed: () =>
ManualInputDialog.show(context),
),
if (lastScan != null) ...[
const SizedBox(height: 10),
LastScanCard(record: lastScan),
],
],
),
),
),
),
// 7. Frozen AR Multi-Code Picker Overlay
if (_frozenSnapshot case final ArCaptureSnapshot frozen)
Positioned.fill(
child: ArFrozenPicker(
snapshot: frozen,
sentKeys: _sentFrozenKeys,
onSelectBarcode: _onTapArBarcode,
onResumeLive: _resumeLiveFromFreeze,
),
),
],
);
},
);
},
);
},
),
),
);
}
}
class _FocusRingIndicator extends StatelessWidget {
final Offset position;
const _FocusRingIndicator({required this.position});
@override
Widget build(BuildContext context) {
const size = 56.0;
return Positioned(
left: position.dx - size / 2,
top: position.dy - size / 2,
width: size,
height: size,
child: TweenAnimationBuilder<double>(
key: ValueKey(position),
tween: Tween(begin: 1.25, end: 1.0),
duration: const Duration(milliseconds: 220),
curve: Curves.easeOutCubic,
builder: (context, scale, child) {
return Transform.scale(scale: scale, child: child);
},
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.amberAccent, width: 2),
boxShadow: [
BoxShadow(
color: Colors.amberAccent.withValues(alpha: 0.35),
blurRadius: 8,
),
],
),
),
),
);
}
@@ -297,7 +728,10 @@ class _CircleGlassButton extends StatelessWidget {
decoration: BoxDecoration(
color: AppTheme.darkCard.withValues(alpha: 0.8),
shape: BoxShape.circle,
border: Border.all(color: AppTheme.darkBorder.withValues(alpha: 0.6), width: 1),
border: Border.all(
color: AppTheme.darkBorder.withValues(alpha: 0.6),
width: 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.25),
@@ -314,4 +748,3 @@ class _CircleGlassButton extends StatelessWidget {
);
}
}
@@ -0,0 +1,379 @@
import 'dart:math' as math;
import 'package:flutter/material.dart' show BoxFit, Color;
import 'package:flutter/services.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../../domain/entities/detected_barcode_item.dart';
import '../../domain/entities/scan_aim_mode.dart';
/// High-contrast color palette for distinguishing adjacent AR barcode overlays.
const List<Color> kArBarcodePalette = [
Color(0xFF38BDF8), // Sky cyan
Color(0xFF10B981), // Emerald
Color(0xFFF59E0B), // Amber
Color(0xFFA855F7), // Violet
Color(0xFFF43F5E), // Rose
Color(0xFF84CC16), // Lime
];
/// Single source of truth for reticle dimensions shared between [MobileScanner.scanWindow]
/// and the visual [ScannerOverlay].
class ScannerReticleGeometry {
ScannerReticleGeometry._();
static Rect? scanRect(Size layoutSize, ScanAimMode mode) {
if (layoutSize.isEmpty) return null;
switch (mode) {
case ScanAimMode.standard:
final width = layoutSize.width * 0.84;
final height = layoutSize.height * 0.34;
final left = (layoutSize.width - width) / 2;
final top = (layoutSize.height - height) * 0.40;
return Rect.fromLTWH(left, top, width, height);
case ScanAimMode.precision:
// Wide horizontally so long Code-128 barcodes at 2x/3x zoom still have all
// 4 corners inside Android's scanWindow check; dart-side crosshair filtering
// handles strict single-target isolation.
final width = layoutSize.width * 0.90;
final height = (layoutSize.height * 0.22).clamp(130.0, 210.0);
final centerY = layoutSize.height * 0.434;
return Rect.fromCenter(
center: Offset(layoutSize.width / 2, centerY),
width: width,
height: height,
);
case ScanAimMode.arMulti:
return null;
}
}
static Offset precisionCrosshairCenter(Size layoutSize) {
final rect = scanRect(layoutSize, ScanAimMode.precision);
return rect?.center ?? Offset(layoutSize.width / 2, layoutSize.height * 0.434);
}
}
/// Geometry helpers for mapping camera barcode coordinates to widget space,
/// precision crosshair hit-testing, and non-overlapping AR badge placement.
class BarcodeGeometry {
BarcodeGeometry._();
static List<Offset> mapCornersToWidget({
required List<Offset> corners,
required Size cameraImageSize,
required Size widgetSize,
BoxFit boxFit = BoxFit.cover,
DeviceOrientation deviceOrientation = DeviceOrientation.portraitUp,
}) {
if (corners.isEmpty || cameraImageSize.isEmpty || widgetSize.isEmpty) {
return const [];
}
final isLandscape = deviceOrientation == DeviceOrientation.landscapeLeft ||
deviceOrientation == DeviceOrientation.landscapeRight;
final adjustedCameraSize =
isLandscape ? cameraImageSize.flipped : cameraImageSize;
final ratios = ScanWindowUtils.calculateBoxFitRatio(
boxFit: boxFit,
cameraPreviewSize: adjustedCameraSize,
size: widgetSize,
);
final horizontalPadding =
(adjustedCameraSize.width * ratios.widthRatio - widgetSize.width) / 2;
final verticalPadding =
(adjustedCameraSize.height * ratios.heightRatio - widgetSize.height) /
2;
return [
for (final offset in corners)
Offset(
offset.dx * ratios.widthRatio - horizontalPadding,
offset.dy * ratios.heightRatio - verticalPadding,
),
];
}
/// Maps raw [Barcode] entries from [BarcodeCapture] into sorted, deduplicated
/// [DetectedBarcodeItem] instances in widget coordinates.
static List<DetectedBarcodeItem> mapCaptureToItems({
required BarcodeCapture capture,
required Size widgetSize,
required DeviceOrientation deviceOrientation,
BoxFit boxFit = BoxFit.cover,
}) {
if (capture.barcodes.isEmpty ||
capture.size.isEmpty ||
widgetSize.isEmpty) {
return const [];
}
final rawItems = <DetectedBarcodeItem>[];
for (final barcode in capture.barcodes) {
final rawValue = (barcode.rawValue ?? barcode.displayValue)?.trim();
if (rawValue == null || rawValue.isEmpty) continue;
final mappedCorners = mapCornersToWidget(
corners: barcode.corners,
cameraImageSize: capture.size,
widgetSize: widgetSize,
boxFit: boxFit,
deviceOrientation: deviceOrientation,
);
if (mappedCorners.length < 3) continue;
final bounds = polygonBounds(mappedCorners);
final center = polygonCentroid(mappedCorners);
// Deduplicate identical codes reported at virtually the same location in one frame.
final duplicate = rawItems.any(
(existing) =>
existing.code == rawValue &&
(existing.center - center).distance < 16.0,
);
if (duplicate) continue;
final format = barcode.format.name.replaceAll('BarcodeFormat.', '');
rawItems.add(
DetectedBarcodeItem(
index: rawItems.length + 1,
code: rawValue,
format: format,
corners: mappedCorners,
boundingRect: bounds,
center: center,
color: kArBarcodePalette[rawItems.length % kArBarcodePalette.length],
),
);
}
return sortTopToBottomLeftToRight(rawItems);
}
/// Sorts barcodes in natural label reading order (top-to-bottom, then left-to-right)
/// and assigns sequential 1-based indices and distinct palette colors.
static List<DetectedBarcodeItem> sortTopToBottomLeftToRight(
List<DetectedBarcodeItem> items, {
double rowTolerance = 22.0,
}) {
if (items.isEmpty) return const [];
final sorted = List<DetectedBarcodeItem>.from(items)
..sort((a, b) {
final dy = a.center.dy - b.center.dy;
if (dy.abs() > rowTolerance) {
return dy.compareTo(0);
}
return a.center.dx.compareTo(b.center.dx);
});
return [
for (var i = 0; i < sorted.length; i++)
sorted[i].copyWith(
index: i + 1,
color: kArBarcodePalette[i % kArBarcodePalette.length],
),
];
}
static Rect polygonBounds(List<Offset> corners) {
var minX = double.infinity;
var minY = double.infinity;
var maxX = double.negativeInfinity;
var maxY = double.negativeInfinity;
for (final p in corners) {
if (p.dx < minX) minX = p.dx;
if (p.dy < minY) minY = p.dy;
if (p.dx > maxX) maxX = p.dx;
if (p.dy > maxY) maxY = p.dy;
}
return Rect.fromLTRB(minX, minY, maxX, maxY);
}
static Offset polygonCentroid(List<Offset> corners) {
var sumX = 0.0;
var sumY = 0.0;
for (final p in corners) {
sumX += p.dx;
sumY += p.dy;
}
return Offset(sumX / corners.length, sumY / corners.length);
}
/// Ray-casting algorithm to determine whether [point] lies inside [polygon].
static bool isPointInPolygon(Offset point, List<Offset> polygon) {
if (polygon.length < 3) return false;
var inside = false;
var j = polygon.length - 1;
for (var i = 0; i < polygon.length; i++) {
final pi = polygon[i];
final pj = polygon[j];
final intersects = ((pi.dy > point.dy) != (pj.dy > point.dy)) &&
(point.dx <
(pj.dx - pi.dx) * (point.dy - pi.dy) / (pj.dy - pi.dy) + pi.dx);
if (intersects) inside = !inside;
j = i;
}
return inside;
}
/// Returns `0.0` if [point] is inside [polygon], otherwise the minimum Euclidean
/// distance to any polygon edge.
static double distancePointToPolygon(Offset point, List<Offset> polygon) {
if (polygon.isEmpty) return double.infinity;
if (polygon.length >= 3 && isPointInPolygon(point, polygon)) {
return 0.0;
}
var minDistance = double.infinity;
for (var i = 0; i < polygon.length; i++) {
final a = polygon[i];
final b = polygon[(i + 1) % polygon.length];
final d = _distancePointToSegment(point, a, b);
if (d < minDistance) minDistance = d;
}
return minDistance;
}
static double _distancePointToSegment(Offset p, Offset a, Offset b) {
final dx = b.dx - a.dx;
final dy = b.dy - a.dy;
final lenSq = dx * dx + dy * dy;
if (lenSq == 0) return (p - a).distance;
final t = (((p.dx - a.dx) * dx + (p.dy - a.dy) * dy) / lenSq).clamp(0.0, 1.0);
final projection = Offset(a.dx + t * dx, a.dy + t * dy);
return (p - projection).distance;
}
/// Picks the single barcode intersecting or closest to [crosshairCenter] within
/// [hitRadius], ignoring adjacent neighboring barcodes.
static DetectedBarcodeItem? selectPrecisionTarget({
required List<DetectedBarcodeItem> items,
required Offset crosshairCenter,
double hitRadius = 16.0,
}) {
DetectedBarcodeItem? bestItem;
var bestDistance = double.infinity;
var bestCentroidDistance = double.infinity;
for (final item in items) {
final distance = distancePointToPolygon(crosshairCenter, item.corners);
if (distance > hitRadius) continue;
final centroidDistance = (item.center - crosshairCenter).distance;
if (distance < bestDistance - 0.5 ||
((distance - bestDistance).abs() <= 0.5 &&
centroidDistance < bestCentroidDistance)) {
bestDistance = distance;
bestCentroidDistance = centroidDistance;
bestItem = item;
}
}
return bestItem;
}
/// Places floating AR badges near their corresponding barcodes while avoiding
/// collisions between closely stacked labels and clamping inside [safeBounds].
static Map<int, Rect> layoutArBadges({
required List<DetectedBarcodeItem> items,
required Rect safeBounds,
required Size Function(DetectedBarcodeItem item) measureBadge,
double verticalGap = 6.0,
double collisionPadding = 4.0,
}) {
final placed = <int, Rect>{};
final occupied = <Rect>[];
for (final item in items) {
final badgeSize = measureBadge(item);
final clampedLeft = (item.center.dx - badgeSize.width / 2)
.clamp(
safeBounds.left,
math.max(safeBounds.left, safeBounds.right - badgeSize.width),
)
.toDouble();
// Prefer just above the barcode, fallback below if above exceeds safeBounds.
var top = item.boundingRect.top - badgeSize.height - verticalGap;
if (top < safeBounds.top) {
top = item.boundingRect.bottom + verticalGap;
}
var candidate = Rect.fromLTWH(
clampedLeft,
top
.clamp(
safeBounds.top,
math.max(safeBounds.top, safeBounds.bottom - badgeSize.height),
)
.toDouble(),
badgeSize.width,
badgeSize.height,
);
// Try placing below barcode if above collides with another badge.
if (_collidesAny(candidate, occupied, collisionPadding)) {
final belowTop = item.boundingRect.bottom + verticalGap;
if (belowTop + badgeSize.height <= safeBounds.bottom) {
final belowCandidate = Rect.fromLTWH(
clampedLeft,
belowTop,
badgeSize.width,
badgeSize.height,
);
if (!_collidesAny(belowCandidate, occupied, collisionPadding)) {
candidate = belowCandidate;
}
}
}
// If still colliding (very dense stack), nudge downwards then upwards inside safeBounds.
var guard = 0;
while (_collidesAny(candidate, occupied, collisionPadding) && guard < 12) {
final nextTop = candidate.top + badgeSize.height + collisionPadding;
if (nextTop + badgeSize.height <= safeBounds.bottom) {
candidate = candidate.shift(
Offset(0, badgeSize.height + collisionPadding),
);
} else {
break;
}
guard++;
}
guard = 0;
while (_collidesAny(candidate, occupied, collisionPadding) && guard < 12) {
final prevTop = candidate.top - badgeSize.height - collisionPadding;
if (prevTop >= safeBounds.top) {
candidate = candidate.shift(
Offset(0, -(badgeSize.height + collisionPadding)),
);
} else {
break;
}
guard++;
}
placed[item.index] = candidate;
occupied.add(candidate);
}
return placed;
}
static bool _collidesAny(Rect rect, List<Rect> others, double padding) {
final inflated = rect.inflate(padding);
return others.any(inflated.overlaps);
}
}
@@ -0,0 +1,268 @@
import 'package:flutter/material.dart';
import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/detected_barcode_item.dart';
import '../utils/barcode_geometry.dart';
/// Renders AR bounding polygons and non-overlapping clickable code badges over
/// either the live camera feed or a frozen snapshot.
class ArBarcodeOverlay extends StatelessWidget {
final List<DetectedBarcodeItem> items;
final Rect safeBounds;
final bool showBadges;
final bool allowBoxTap;
final int? highlightedIndex;
final Set<String> sentKeys;
final ValueChanged<DetectedBarcodeItem>? onTapBarcode;
const ArBarcodeOverlay({
super.key,
required this.items,
required this.safeBounds,
this.showBadges = true,
this.allowBoxTap = false,
this.highlightedIndex,
this.sentKeys = const {},
this.onTapBarcode,
});
@override
Widget build(BuildContext context) {
if (items.isEmpty) return const SizedBox.shrink();
final badgeRects = showBadges
? BarcodeGeometry.layoutArBadges(
items: items,
safeBounds: safeBounds,
measureBadge: (item) => _measureBadge(
item,
isSent: sentKeys.contains(item.selectionKey),
),
)
: const <int, Rect>{};
return Stack(
fit: StackFit.expand,
children: [
IgnorePointer(
child: CustomPaint(
painter: _ArPolygonPainter(
items: items,
badgeRects: badgeRects,
highlightedIndex: highlightedIndex,
sentKeys: sentKeys,
showBadges: showBadges,
),
),
),
if (allowBoxTap && onTapBarcode != null)
for (final item in items)
Positioned.fromRect(
rect: item.boundingRect.inflate(8),
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => onTapBarcode!(item),
child: const SizedBox.expand(),
),
),
if (showBadges)
for (final item in items)
if (badgeRects[item.index] case final Rect rect)
Positioned.fromRect(
rect: rect,
child: _ArCodeBadge(
item: item,
isSent: sentKeys.contains(item.selectionKey),
onTap: onTapBarcode != null ? () => onTapBarcode!(item) : null,
),
),
],
);
}
static String _previewText(String code) {
if (code.length <= 13) return code;
return '${code.substring(0, 12)}…';
}
static Size _measureBadge(DetectedBarcodeItem item, {required bool isSent}) {
final label = _previewText(item.code);
final width =
(46.0 + (label.length * 7.4) + (isSent ? 18.0 : 0.0)).clamp(84.0, 182.0);
return Size(width, 30.0);
}
}
class _ArCodeBadge extends StatelessWidget {
final DetectedBarcodeItem item;
final bool isSent;
final VoidCallback? onTap;
const _ArCodeBadge({
required this.item,
required this.isSent,
this.onTap,
});
@override
Widget build(BuildContext context) {
final badgeColor = isSent ? AppTheme.success : item.color;
final preview = ArBarcodeOverlay._previewText(item.code);
return Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
decoration: BoxDecoration(
color: AppTheme.darkBackground.withValues(alpha: 0.90),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: badgeColor, width: 1.6),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.45),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 20,
height: 20,
alignment: Alignment.center,
decoration: BoxDecoration(
color: badgeColor,
shape: BoxShape.circle,
),
child: isSent
? const Icon(
Icons.check_rounded,
color: Colors.white,
size: 13,
)
: Text(
'${item.index}',
style: const TextStyle(
color: Colors.black,
fontSize: 11,
fontWeight: FontWeight.w800,
),
),
),
const SizedBox(width: 6),
Expanded(
child: Text(
preview,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 11.5,
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
),
],
),
),
),
);
}
}
class _ArPolygonPainter extends CustomPainter {
final List<DetectedBarcodeItem> items;
final Map<int, Rect> badgeRects;
final int? highlightedIndex;
final Set<String> sentKeys;
final bool showBadges;
_ArPolygonPainter({
required this.items,
required this.badgeRects,
required this.highlightedIndex,
required this.sentKeys,
required this.showBadges,
});
@override
void paint(Canvas canvas, Size size) {
for (final item in items) {
if (item.corners.length < 3) continue;
final isPrecisionMode = !showBadges;
final isHighlighted = highlightedIndex == item.index;
final isSent = sentKeys.contains(item.selectionKey);
final Color strokeColor;
final double strokeWidth;
final double fillAlpha;
if (isPrecisionMode) {
strokeColor = isHighlighted
? AppTheme.success
: Colors.white.withValues(alpha: 0.45);
strokeWidth = isHighlighted ? 3.0 : 1.5;
fillAlpha = isHighlighted ? 0.18 : 0.05;
} else {
strokeColor = isSent ? AppTheme.success : item.color;
strokeWidth = 2.4;
fillAlpha = isSent ? 0.22 : 0.14;
}
final path = Path()..addPolygon(item.corners, true);
final fillPaint = Paint()
..color = strokeColor.withValues(alpha: fillAlpha)
..style = PaintingStyle.fill;
canvas.drawPath(path, fillPaint);
final borderPaint = Paint()
..color = strokeColor
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth
..strokeJoin = StrokeJoin.round;
canvas.drawPath(path, borderPaint);
// Draw subtle leader line from nudged badge to barcode box so stacked tiny
// barcodes remain unmistakably paired with their badge.
if (showBadges) {
final badgeRect = badgeRects[item.index];
if (badgeRect != null) {
final anchorOnBadge = badgeRect.center.dy < item.center.dy
? badgeRect.bottomCenter
: badgeRect.topCenter;
final anchorOnBox = badgeRect.center.dy < item.center.dy
? Offset(item.center.dx, item.boundingRect.top)
: Offset(item.center.dx, item.boundingRect.bottom);
if ((anchorOnBadge - anchorOnBox).distance > 6.0) {
final linePaint = Paint()
..color = strokeColor.withValues(alpha: 0.85)
..strokeWidth = 1.4;
canvas.drawLine(anchorOnBadge, anchorOnBox, linePaint);
canvas.drawCircle(
anchorOnBox,
3.0,
Paint()..color = strokeColor,
);
}
}
}
}
}
@override
bool shouldRepaint(covariant _ArPolygonPainter oldDelegate) {
return oldDelegate.items != items ||
oldDelegate.highlightedIndex != highlightedIndex ||
oldDelegate.sentKeys != sentKeys ||
oldDelegate.showBadges != showBadges;
}
}
@@ -0,0 +1,451 @@
import 'package:flutter/material.dart';
import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/detected_barcode_item.dart';
import 'ar_barcode_overlay.dart';
/// Displays a frozen high-resolution camera frame with pinch-to-zoom AR overlays
/// alongside an ordered bottom picker list for unmistakable multi-code selection.
class ArFrozenPicker extends StatefulWidget {
final ArCaptureSnapshot snapshot;
final Set<String> sentKeys;
final ValueChanged<DetectedBarcodeItem> onSelectBarcode;
final VoidCallback onResumeLive;
const ArFrozenPicker({
super.key,
required this.snapshot,
required this.sentKeys,
required this.onSelectBarcode,
required this.onResumeLive,
});
@override
State<ArFrozenPicker> createState() => _ArFrozenPickerState();
}
class _ArFrozenPickerState extends State<ArFrozenPicker> {
final TransformationController _transformController =
TransformationController();
bool _isZoomed = false;
@override
void initState() {
super.initState();
_transformController.addListener(_onTransformChanged);
}
@override
void dispose() {
_transformController.removeListener(_onTransformChanged);
_transformController.dispose();
super.dispose();
}
void _onTransformChanged() {
final scale = _transformController.value.getMaxScaleOnAxis();
final zoomed = scale > 1.05;
if (zoomed != _isZoomed && mounted) {
setState(() => _isZoomed = zoomed);
}
}
void _resetZoom() {
_transformController.value = Matrix4.identity();
}
@override
Widget build(BuildContext context) {
final snapshot = widget.snapshot;
return LayoutBuilder(
builder: (context, constraints) {
final viewport = snapshot.viewportSize.isEmpty
? constraints.biggest
: snapshot.viewportSize;
final safeTop = MediaQuery.paddingOf(context).top + 64;
final safeBottom = viewport.height * 0.58;
final safeBounds = Rect.fromLTRB(
12,
safeTop,
(viewport.width - 12).clamp(24.0, viewport.width),
safeBottom.clamp(safeTop + 60, viewport.height - 20),
);
return Container(
color: Colors.black,
child: Stack(
fit: StackFit.expand,
children: [
// 1. Pinch-zoomable frozen frame + synchronized AR overlays
InteractiveViewer(
transformationController: _transformController,
minScale: 1.0,
maxScale: 4.5,
boundaryMargin: const EdgeInsets.all(40),
child: SizedBox(
width: viewport.width,
height: viewport.height,
child: Stack(
fit: StackFit.expand,
children: [
Image.memory(
snapshot.imageBytes,
fit: BoxFit.cover,
gaplessPlayback: true,
),
Container(
color: Colors.black.withValues(alpha: 0.14),
),
ArBarcodeOverlay(
items: snapshot.items,
safeBounds: safeBounds,
showBadges: true,
allowBoxTap: true,
sentKeys: widget.sentKeys,
onTapBarcode: widget.onSelectBarcode,
),
],
),
),
),
// 2. Top status banner
SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 10, 16, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 8,
),
decoration: BoxDecoration(
color:
AppTheme.darkSurface.withValues(alpha: 0.90),
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: AppTheme.primary.withValues(alpha: 0.5),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.pause_circle_filled_rounded,
color: AppTheme.primary,
size: 18,
),
const SizedBox(width: 8),
Flexible(
child: Text(
'Frame bloccato • ${snapshot.items.length} ${snapshot.items.length == 1 ? 'codice' : 'codici'}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppTheme.darkTextPrimary,
fontSize: 12.5,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
const SizedBox(width: 8),
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (_isZoomed) ...[
_TopPillButton(
icon: Icons.zoom_out_map_rounded,
label: '1x',
onTap: _resetZoom,
),
const SizedBox(width: 8),
],
_TopPillButton(
icon: Icons.close_rounded,
label: 'Riprendi',
accent: true,
onTap: widget.onResumeLive,
),
],
),
],
),
),
),
),
// 3. Bottom numbered picker panel
Align(
alignment: Alignment.bottomCenter,
child: Container(
constraints: BoxConstraints(
maxHeight: constraints.maxHeight * 0.38,
),
decoration: BoxDecoration(
color: AppTheme.darkSurface.withValues(alpha: 0.96),
borderRadius: const BorderRadius.vertical(
top: Radius.circular(24),
),
border: const Border(
top: BorderSide(color: AppTheme.darkBorder, width: 1),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.55),
blurRadius: 20,
offset: const Offset(0, -4),
),
],
),
child: SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(18, 12, 14, 8),
child: Row(
children: [
const Expanded(
child: Text(
'Tocca un codice per inviarlo al PC',
style: TextStyle(
color: AppTheme.darkTextSecondary,
fontSize: 12.5,
fontWeight: FontWeight.w600,
),
),
),
TextButton.icon(
onPressed: widget.onResumeLive,
icon: const Icon(
Icons.videocam_rounded,
size: 16,
),
label: const Text('Nuova scansione'),
style: TextButton.styleFrom(
foregroundColor: AppTheme.secondary,
visualDensity: VisualDensity.compact,
),
),
],
),
),
const Divider(height: 1),
Flexible(
child: ListView.separated(
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(14, 10, 14, 12),
itemCount: snapshot.items.length,
separatorBuilder: (_, _) =>
const SizedBox(height: 8),
itemBuilder: (context, index) {
final item = snapshot.items[index];
final isSent =
widget.sentKeys.contains(item.selectionKey);
return _FrozenCodeRow(
item: item,
isSent: isSent,
onTap: () => widget.onSelectBarcode(item),
);
},
),
),
],
),
),
),
),
],
),
);
},
);
}
}
class _FrozenCodeRow extends StatelessWidget {
final DetectedBarcodeItem item;
final bool isSent;
final VoidCallback onTap;
const _FrozenCodeRow({
required this.item,
required this.isSent,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final badgeColor = isSent ? AppTheme.success : item.color;
return Material(
color: AppTheme.darkCard,
borderRadius: BorderRadius.circular(14),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(14),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: isSent
? AppTheme.success.withValues(alpha: 0.55)
: AppTheme.darkBorder,
width: 1.2,
),
),
child: Row(
children: [
Container(
width: 28,
height: 28,
alignment: Alignment.center,
decoration: BoxDecoration(
color: badgeColor,
shape: BoxShape.circle,
),
child: isSent
? const Icon(
Icons.check_rounded,
color: Colors.white,
size: 16,
)
: Text(
'${item.index}',
style: const TextStyle(
color: Colors.black,
fontSize: 13,
fontWeight: FontWeight.w800,
),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
item.format.toUpperCase(),
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: badgeColor,
letterSpacing: 0.5,
),
),
const SizedBox(height: 2),
Text(
item.code,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 14,
fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary,
),
),
],
),
),
const SizedBox(width: 10),
Container(
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: (isSent ? AppTheme.success : AppTheme.primary)
.withValues(alpha: 0.16),
borderRadius: BorderRadius.circular(10),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isSent ? Icons.refresh_rounded : Icons.send_rounded,
size: 15,
color: isSent ? AppTheme.success : AppTheme.primary,
),
const SizedBox(width: 4),
Text(
isSent ? 'Inviato' : 'Invia',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: isSent ? AppTheme.success : AppTheme.primary,
),
),
],
),
),
],
),
),
),
);
}
}
class _TopPillButton extends StatelessWidget {
final IconData icon;
final String label;
final VoidCallback onTap;
final bool accent;
const _TopPillButton({
required this.icon,
required this.label,
required this.onTap,
this.accent = false,
});
@override
Widget build(BuildContext context) {
return Material(
color: accent
? AppTheme.primary
: AppTheme.darkSurface.withValues(alpha: 0.90),
borderRadius: BorderRadius.circular(24),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(24),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
border: accent
? null
: Border.all(color: AppTheme.darkBorder, width: 1),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: Colors.white, size: 16),
const SizedBox(width: 5),
Text(
label,
style: const TextStyle(
color: Colors.white,
fontSize: 12.5,
fontWeight: FontWeight.w700,
),
),
],
),
),
),
);
}
}
@@ -0,0 +1,382 @@
import 'package:flutter/material.dart';
import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/scan_aim_mode.dart';
class ScannerControlsBar extends StatelessWidget {
final ScanAimMode aimMode;
final double zoomScale;
final int liveBarcodeCount;
final bool isPendingFreeze;
final ValueChanged<ScanAimMode> onAimModeChanged;
final ValueChanged<double> onZoomPresetSelected;
final VoidCallback onFreezePressed;
final VoidCallback onCancelPendingFreeze;
final VoidCallback onManualInputPressed;
const ScannerControlsBar({
super.key,
required this.aimMode,
required this.zoomScale,
required this.liveBarcodeCount,
required this.isPendingFreeze,
required this.onAimModeChanged,
required this.onZoomPresetSelected,
required this.onFreezePressed,
required this.onCancelPendingFreeze,
required this.onManualInputPressed,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (aimMode == ScanAimMode.arMulti) ...[
_FreezeButton(
liveBarcodeCount: liveBarcodeCount,
isPendingFreeze: isPendingFreeze,
onPressed:
isPendingFreeze ? onCancelPendingFreeze : onFreezePressed,
),
const SizedBox(height: 10),
],
// Zoom quick presets + Manual entry button
Row(
children: [
_ZoomPresetsBar(
zoomScale: zoomScale,
onSelect: onZoomPresetSelected,
),
const Spacer(),
_ManualActionPill(onPressed: onManualInputPressed),
],
),
const SizedBox(height: 10),
// 3-Mode Aim Selector
_AimModeSelector(
selectedMode: aimMode,
onChanged: onAimModeChanged,
),
],
),
);
}
}
class _FreezeButton extends StatelessWidget {
final int liveBarcodeCount;
final bool isPendingFreeze;
final VoidCallback onPressed;
const _FreezeButton({
required this.liveBarcodeCount,
required this.isPendingFreeze,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
final hasCodes = liveBarcodeCount > 0;
final label = isPendingFreeze
? 'In attesa dei codici… Tocca per annullare'
: hasCodes
? 'Blocca frame ($liveBarcodeCount ${liveBarcodeCount == 1 ? 'codice' : 'codici'})'
: 'Blocca e scegli';
return SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: onPressed,
style: FilledButton.styleFrom(
backgroundColor: isPendingFreeze
? AppTheme.warning
: (hasCodes ? AppTheme.primary : AppTheme.darkCard),
foregroundColor: isPendingFreeze ? Colors.black : Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(
color: isPendingFreeze
? AppTheme.warning
: (hasCodes ? AppTheme.secondary : AppTheme.darkBorder),
width: 1.2,
),
),
),
icon: isPendingFreeze
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.black,
),
)
: Icon(
hasCodes
? Icons.pause_circle_outline_rounded
: Icons.camera_alt_rounded,
size: 20,
),
label: Text(
label,
style: const TextStyle(fontSize: 13.5, fontWeight: FontWeight.w700),
),
),
);
}
}
class _ZoomPresetsBar extends StatelessWidget {
final double zoomScale;
final ValueChanged<double> onSelect;
const _ZoomPresetsBar({
required this.zoomScale,
required this.onSelect,
});
static const _presets = [
(label: '1x', scale: 0.0),
(label: '2x', scale: 0.25),
(label: '3x', scale: 0.50),
];
@override
Widget build(BuildContext context) {
final isExtraZoom = zoomScale > 0.58;
return Container(
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
color: AppTheme.darkCard.withValues(alpha: 0.88),
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: AppTheme.darkBorder.withValues(alpha: 0.8),
width: 1,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Padding(
padding: EdgeInsets.only(left: 8, right: 4),
child: Icon(
Icons.zoom_in_rounded,
size: 16,
color: AppTheme.darkTextSecondary,
),
),
for (final preset in _presets)
_ZoomChip(
label: preset.label,
selected: !isExtraZoom && (zoomScale - preset.scale).abs() < 0.09,
onTap: () => onSelect(preset.scale),
),
if (isExtraZoom)
_ZoomChip(
label: '${(1 + zoomScale * 4).toStringAsFixed(1)}x',
selected: true,
onTap: () => onSelect(0.0),
),
],
),
);
}
}
class _ZoomChip extends StatelessWidget {
final String label;
final bool selected;
final VoidCallback onTap;
const _ZoomChip({
required this.label,
required this.selected,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 140),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: selected ? AppTheme.primary : Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: selected ? Colors.white : AppTheme.darkTextSecondary,
),
),
),
);
}
}
class _ManualActionPill extends StatelessWidget {
final VoidCallback onPressed;
const _ManualActionPill({required this.onPressed});
@override
Widget build(BuildContext context) {
return Material(
color: AppTheme.darkCard.withValues(alpha: 0.90),
borderRadius: BorderRadius.circular(22),
child: InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(22),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 9),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
border: Border.all(
color: AppTheme.darkBorder.withValues(alpha: 0.9),
width: 1,
),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.keyboard_rounded, color: AppTheme.primary, size: 18),
SizedBox(width: 6),
Text(
'Manuale',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary,
),
),
],
),
),
),
);
}
}
class _AimModeSelector extends StatelessWidget {
final ScanAimMode selectedMode;
final ValueChanged<ScanAimMode> onChanged;
const _AimModeSelector({
required this.selectedMode,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: AppTheme.darkSurface.withValues(alpha: 0.92),
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: AppTheme.darkBorder.withValues(alpha: 0.85),
width: 1,
),
),
child: Row(
children: [
_ModeTab(
icon: Icons.qr_code_scanner_rounded,
label: ScanAimMode.standard.label,
selected: selectedMode == ScanAimMode.standard,
onTap: () => onChanged(ScanAimMode.standard),
),
_ModeTab(
icon: Icons.gps_fixed_rounded,
label: ScanAimMode.precision.label,
selected: selectedMode == ScanAimMode.precision,
onTap: () => onChanged(ScanAimMode.precision),
),
_ModeTab(
icon: Icons.view_in_ar_rounded,
label: ScanAimMode.arMulti.label,
selected: selectedMode == ScanAimMode.arMulti,
onTap: () => onChanged(ScanAimMode.arMulti),
),
],
),
);
}
}
class _ModeTab extends StatelessWidget {
final IconData icon;
final String label;
final bool selected;
final VoidCallback onTap;
const _ModeTab({
required this.icon,
required this.label,
required this.selected,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return Expanded(
child: GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.opaque,
child: AnimatedContainer(
duration: const Duration(milliseconds: 160),
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 6),
decoration: BoxDecoration(
color: selected
? AppTheme.primary.withValues(alpha: 0.22)
: Colors.transparent,
borderRadius: BorderRadius.circular(14),
border: selected
? Border.all(
color: AppTheme.primary.withValues(alpha: 0.7),
width: 1,
)
: null,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
size: 16,
color:
selected ? AppTheme.secondary : AppTheme.darkTextSecondary,
),
const SizedBox(width: 5),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
color: selected
? AppTheme.darkTextPrimary
: AppTheme.darkTextSecondary,
),
),
),
],
),
),
),
);
}
}
@@ -1,8 +1,17 @@
import 'package:flutter/material.dart';
import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/scan_aim_mode.dart';
import '../utils/barcode_geometry.dart';
class ScannerOverlay extends StatefulWidget {
const ScannerOverlay({super.key});
final ScanAimMode aimMode;
final bool hasPrecisionTarget;
const ScannerOverlay({
super.key,
this.aimMode = ScanAimMode.standard,
this.hasPrecisionTarget = false,
});
@override
State<ScannerOverlay> createState() => _ScannerOverlayState();
@@ -35,19 +44,30 @@ class _ScannerOverlayState extends State<ScannerOverlay>
@override
Widget build(BuildContext context) {
return LayoutBuilder(
return IgnorePointer(
child: LayoutBuilder(
builder: (context, constraints) {
final boxWidth = constraints.maxWidth * 0.84;
final boxHeight = constraints.maxHeight * 0.38;
final left = (constraints.maxWidth - boxWidth) / 2;
final top = (constraints.maxHeight - boxHeight) / 2.3;
final layoutSize = constraints.biggest;
final scanRect =
ScannerReticleGeometry.scanRect(layoutSize, widget.aimMode);
if (widget.aimMode == ScanAimMode.arMulti || scanRect == null) {
return const SizedBox.expand();
}
final isPrecision = widget.aimMode == ScanAimMode.precision;
final accentColor = isPrecision && widget.hasPrecisionTarget
? AppTheme.success
: AppTheme.primary;
final maskAlpha = isPrecision ? 0.72 : 0.62;
final radius = isPrecision ? 14.0 : 18.0;
return Stack(
children: [
// Dark semi-transparent cutout mask
// Dark semi-transparent cutout mask matching exact scanWindow
ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.black.withValues(alpha: 0.65),
Colors.black.withValues(alpha: maskAlpha),
BlendMode.srcOut,
),
child: Stack(
@@ -58,14 +78,14 @@ class _ScannerOverlayState extends State<ScannerOverlay>
),
child: Container(
margin: EdgeInsets.fromLTRB(
left,
top,
left,
constraints.maxHeight - top - boxHeight,
scanRect.left,
scanRect.top,
layoutSize.width - scanRect.right,
layoutSize.height - scanRect.bottom,
),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(18),
borderRadius: BorderRadius.circular(radius),
),
),
),
@@ -73,35 +93,44 @@ class _ScannerOverlayState extends State<ScannerOverlay>
),
),
// Corner Reticles & Outer Border
Positioned(
left: left,
top: top,
width: boxWidth,
height: boxHeight,
// Outer border
Positioned.fromRect(
rect: scanRect,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
borderRadius: BorderRadius.circular(radius),
border: Border.all(
color: AppTheme.primary.withValues(alpha: 0.35),
color: accentColor.withValues(alpha: 0.4),
width: 1.5,
),
),
),
),
// Corner Accents (High-Tech look)
_CornerAccents(left: left, top: top, width: boxWidth, height: boxHeight),
// Corner Accents
_CornerAccents(
rect: scanRect,
color: accentColor,
radius: radius,
),
// Animated Laser Beam
if (isPrecision)
_PrecisionCrosshair(
scanRect: scanRect,
accentColor: accentColor,
locked: widget.hasPrecisionTarget,
)
else
// Animated Laser Beam in Standard mode
AnimatedBuilder(
animation: _anim,
builder: (context, child) {
final beamTop = top + 14 + (_anim.value * (boxHeight - 28));
final beamTop =
scanRect.top + 14 + (_anim.value * (scanRect.height - 28));
return Positioned(
left: left + 14,
left: scanRect.left + 14,
top: beamTop,
width: boxWidth - 28,
width: scanRect.width - 28,
height: 2.5,
child: Container(
decoration: BoxDecoration(
@@ -128,19 +157,21 @@ class _ScannerOverlayState extends State<ScannerOverlay>
},
),
// Subtle helper text
// Helper text below reticle
Positioned(
left: 0,
right: 0,
top: top + boxHeight + 20,
child: const Text(
'Inquadra codice a barre o QR code',
left: 20,
right: 20,
top: scanRect.bottom + 14,
child: Text(
isPrecision
? 'Centra il mirino sul codice • Tocca per mettere a fuoco'
: 'Inquadra codice a barre o QR • Pizzica per zoomare',
textAlign: TextAlign.center,
style: TextStyle(
style: const TextStyle(
color: Colors.white70,
fontSize: 13,
fontSize: 12,
fontWeight: FontWeight.w500,
letterSpacing: 0.3,
letterSpacing: 0.2,
shadows: [
Shadow(color: Colors.black, blurRadius: 6),
],
@@ -150,41 +181,132 @@ class _ScannerOverlayState extends State<ScannerOverlay>
],
);
},
),
);
}
}
class _PrecisionCrosshair extends StatelessWidget {
final Rect scanRect;
final Color accentColor;
final bool locked;
const _PrecisionCrosshair({
required this.scanRect,
required this.accentColor,
required this.locked,
});
@override
Widget build(BuildContext context) {
final center = scanRect.center;
final ringSize = locked ? 34.0 : 30.0;
return Stack(
children: [
// Subtle horizontal laser guide across the precision slit
Positioned(
left: scanRect.left + 14,
top: center.dy - 0.75,
width: scanRect.width - 28,
height: 1.5,
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.transparent,
accentColor.withValues(alpha: 0.45),
accentColor.withValues(alpha: 0.85),
accentColor.withValues(alpha: 0.45),
Colors.transparent,
],
),
),
),
),
// Subtle vertical crosshair tick
Positioned(
left: center.dx - 0.75,
top: center.dy - 26,
width: 1.5,
height: 52,
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
accentColor.withValues(alpha: 0.7),
Colors.transparent,
],
),
),
),
),
// Target lock ring & center dot
Positioned(
left: center.dx - ringSize / 2,
top: center.dy - ringSize / 2,
width: ringSize,
height: ringSize,
child: AnimatedContainer(
duration: const Duration(milliseconds: 120),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: locked ? AppTheme.success : Colors.redAccent,
width: locked ? 2.5 : 2.0,
),
boxShadow: [
BoxShadow(
color: (locked ? AppTheme.success : Colors.redAccent)
.withValues(alpha: 0.55),
blurRadius: 10,
spreadRadius: 1,
),
],
),
child: Center(
child: Container(
width: 6,
height: 6,
decoration: BoxDecoration(
color: locked ? AppTheme.success : Colors.redAccent,
shape: BoxShape.circle,
),
),
),
),
),
],
);
}
}
class _CornerAccents extends StatelessWidget {
final double left;
final double top;
final double width;
final double height;
final Rect rect;
final Color color;
final double radius;
const _CornerAccents({
required this.left,
required this.top,
required this.width,
required this.height,
required this.rect,
required this.color,
required this.radius,
});
@override
Widget build(BuildContext context) {
const cornerSize = 24.0;
const strokeWidth = 3.5;
const cornerRadius = 18.0;
const color = AppTheme.primary;
return Positioned(
left: left,
top: top,
width: width,
height: height,
return Positioned.fromRect(
rect: rect,
child: CustomPaint(
painter: _CornersPainter(
color: color,
cornerSize: cornerSize,
strokeWidth: strokeWidth,
radius: cornerRadius,
cornerSize: 22.0,
strokeWidth: 3.5,
radius: radius,
),
),
);
@@ -240,12 +362,13 @@ class _CornersPainter extends CustomPainter {
final pathBR = Path()
..moveTo(size.width - cornerSize, size.height)
..lineTo(size.width - radius, size.height)
..quadraticBezierTo(size.width, size.height, size.width, size.height - radius)
..quadraticBezierTo(
size.width, size.height, size.width, size.height - radius)
..lineTo(size.width, size.height - cornerSize);
canvas.drawPath(pathBR, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
bool shouldRepaint(covariant _CornersPainter oldDelegate) =>
oldDelegate.color != color || oldDelegate.radius != radius;
}
@@ -1,5 +1,6 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../core/constants/app_constants.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../../domain/entities/app_settings.dart';
class SettingsLocalDataSource {
@@ -16,6 +17,9 @@ class SettingsLocalDataSource {
final autoConnect = _prefs.getBool(AppConstants.keyAutoConnect) ?? false;
final inactivityTimeout = _prefs.getInt(AppConstants.keyInactivityTimeout) ??
AppConstants.defaultInactivityTimeoutMinutes;
final aimMode = ScanAimMode.fromStorageKey(
_prefs.getString(AppConstants.keyAimMode),
);
return AppSettings(
suffix: suffix,
@@ -24,6 +28,7 @@ class SettingsLocalDataSource {
sound: sound,
autoConnect: autoConnect,
inactivityTimeoutMinutes: inactivityTimeout,
aimMode: aimMode,
);
}
@@ -48,4 +53,8 @@ class SettingsLocalDataSource {
Future<void> saveInactivityTimeout(int minutes) async {
await _prefs.setInt(AppConstants.keyInactivityTimeout, minutes);
}
Future<void> saveAimMode(ScanAimMode mode) async {
await _prefs.setString(AppConstants.keyAimMode, mode.storageKey);
}
}
@@ -1,3 +1,4 @@
import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../../domain/entities/app_settings.dart';
import '../../domain/repositories/settings_repository.dart';
import '../datasources/settings_local_datasource.dart';
@@ -37,4 +38,9 @@ class SettingsRepositoryImpl implements SettingsRepository {
Future<void> saveInactivityTimeout(int minutes) async {
await _localDataSource.saveInactivityTimeout(minutes);
}
@override
Future<void> saveAimMode(ScanAimMode mode) async {
await _localDataSource.saveAimMode(mode);
}
}
@@ -1,5 +1,6 @@
import 'package:equatable/equatable.dart';
import '../../../../core/constants/app_constants.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart';
class AppSettings extends Equatable {
final String suffix; // 'enter', 'tab', 'none'
@@ -8,6 +9,7 @@ class AppSettings extends Equatable {
final bool sound;
final bool autoConnect; // Default: false (ideal for multi-PC store)
final int inactivityTimeoutMinutes; // Default: 5 or 10 min, 0 = disabled
final ScanAimMode aimMode;
const AppSettings({
this.suffix = 'enter',
@@ -16,6 +18,7 @@ class AppSettings extends Equatable {
this.sound = true,
this.autoConnect = false,
this.inactivityTimeoutMinutes = AppConstants.defaultInactivityTimeoutMinutes,
this.aimMode = ScanAimMode.standard,
});
AppSettings copyWith({
@@ -25,6 +28,7 @@ class AppSettings extends Equatable {
bool? sound,
bool? autoConnect,
int? inactivityTimeoutMinutes,
ScanAimMode? aimMode,
}) {
return AppSettings(
suffix: suffix ?? this.suffix,
@@ -34,6 +38,7 @@ class AppSettings extends Equatable {
autoConnect: autoConnect ?? this.autoConnect,
inactivityTimeoutMinutes:
inactivityTimeoutMinutes ?? this.inactivityTimeoutMinutes,
aimMode: aimMode ?? this.aimMode,
);
}
@@ -45,5 +50,6 @@ class AppSettings extends Equatable {
sound,
autoConnect,
inactivityTimeoutMinutes,
aimMode,
];
}
@@ -1,3 +1,4 @@
import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../entities/app_settings.dart';
abstract class SettingsRepository {
@@ -7,4 +8,5 @@ abstract class SettingsRepository {
Future<void> saveFeedbackToggles({required bool vibrate, required bool sound});
Future<void> saveAutoConnect(bool enabled);
Future<void> saveInactivityTimeout(int minutes);
Future<void> saveAimMode(ScanAimMode mode);
}
@@ -1,4 +1,5 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../../domain/repositories/settings_repository.dart';
import 'settings_state.dart';
@@ -52,4 +53,10 @@ class SettingsCubit extends Cubit<SettingsState> {
emit(state.copyWith(settings: updated));
await _settingsRepository.saveInactivityTimeout(minutes);
}
Future<void> updateAimMode(ScanAimMode mode) async {
final updated = state.settings.copyWith(aimMode: mode);
emit(state.copyWith(settings: updated));
await _settingsRepository.saveAimMode(mode);
}
}
@@ -6,6 +6,7 @@ import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/cubit/connection_state.dart';
import '../../../connection/presentation/screens/connect_screen.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../cubit/settings_cubit.dart';
import '../cubit/settings_state.dart';
@@ -263,6 +264,44 @@ class SettingsScreen extends StatelessWidget {
Card(
child: Column(
children: [
ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: AppTheme.primary.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.gps_fixed_rounded,
color: AppTheme.primary, size: 22),
),
title: const Text('Modalità di mira'),
subtitle: const Text(
'Standard, Precisione (mirino + zoom) o AR Multi-Codice',
style: TextStyle(fontSize: 12),
),
trailing: DropdownButton<ScanAimMode>(
value: settings.aimMode,
dropdownColor: AppTheme.darkCard,
style: const TextStyle(
color: AppTheme.darkTextPrimary,
fontWeight: FontWeight.bold,
),
underline: const SizedBox.shrink(),
items: [
for (final mode in ScanAimMode.values)
DropdownMenuItem(
value: mode,
child: Text(mode.label),
),
],
onChanged: (mode) {
if (mode != null) {
context.read<SettingsCubit>().updateAimMode(mode);
}
},
),
),
const Divider(height: 1),
SwitchListTile(
secondary: Container(
padding: const EdgeInsets.all(8),
+421
View File
@@ -0,0 +1,421 @@
import 'package:barcode_reader_app/core/services/feedback_service.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_local_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/udp_discovery_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/repositories/connection_repository_impl.dart';
import 'package:barcode_reader_app/features/connection/presentation/cubit/connection_cubit.dart';
import 'package:barcode_reader_app/features/scanner/data/datasources/scan_history_datasource.dart';
import 'package:barcode_reader_app/features/scanner/data/repositories/scan_repository_impl.dart';
import 'package:barcode_reader_app/features/scanner/domain/entities/detected_barcode_item.dart';
import 'package:barcode_reader_app/features/scanner/domain/entities/scan_aim_mode.dart';
import 'package:barcode_reader_app/features/scanner/presentation/cubit/history_cubit.dart';
import 'package:barcode_reader_app/features/scanner/presentation/cubit/scanner_cubit.dart';
import 'package:barcode_reader_app/features/scanner/presentation/utils/barcode_geometry.dart';
import 'package:barcode_reader_app/features/scanner/presentation/widgets/ar_barcode_overlay.dart';
import 'package:barcode_reader_app/features/scanner/presentation/widgets/ar_frozen_picker.dart';
import 'package:barcode_reader_app/features/scanner/presentation/widgets/scanner_controls_bar.dart';
import 'package:barcode_reader_app/features/settings/data/datasources/settings_local_datasource.dart';
import 'package:barcode_reader_app/features/settings/data/repositories/settings_repository_impl.dart';
import 'package:barcode_reader_app/features/settings/presentation/cubit/settings_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:shared_preferences/shared_preferences.dart';
// Minimal valid 1x1 PNG for Image.memory widget tests.
final Uint8List _kTinyPng = Uint8List.fromList([
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00,
0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00,
0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49,
0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
]);
DetectedBarcodeItem _makeItem({
required int index,
required String code,
required Rect rect,
String format = 'code128',
Color color = const Color(0xFF38BDF8),
}) {
return DetectedBarcodeItem(
index: index,
code: code,
format: format,
corners: [rect.topLeft, rect.topRight, rect.bottomRight, rect.bottomLeft],
boundingRect: rect,
center: rect.center,
color: color,
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('ScannerReticleGeometry & BarcodeGeometry', () {
test('scanRect returns distinct rects for standard/precision and null for arMulti', () {
const viewport = Size(400, 800);
final standardRect =
ScannerReticleGeometry.scanRect(viewport, ScanAimMode.standard);
final precisionRect =
ScannerReticleGeometry.scanRect(viewport, ScanAimMode.precision);
final arRect =
ScannerReticleGeometry.scanRect(viewport, ScanAimMode.arMulti);
expect(standardRect, isNotNull);
expect(precisionRect, isNotNull);
expect(arRect, isNull);
expect(precisionRect!.height, lessThan(standardRect!.height));
expect(precisionRect.center.dy, closeTo(standardRect.center.dy, 1.0));
});
test('mapCornersToWidget accurately applies BoxFit.cover centering', () {
// 1080x1920 camera image rendered into a 400x860 BoxFit.cover widget:
// center (540, 960) must map precisely to (200, 430).
final mapped = BarcodeGeometry.mapCornersToWidget(
corners: const [Offset(540, 960)],
cameraImageSize: const Size(1080, 1920),
widgetSize: const Size(400, 860),
deviceOrientation: DeviceOrientation.portraitUp,
);
expect(mapped.length, 1);
expect(mapped.first.dx, closeTo(200.0, 0.01));
expect(mapped.first.dy, closeTo(430.0, 0.01));
});
test('mapCaptureToItems sorts top-to-bottom, left-to-right and deduplicates', () {
final capture = BarcodeCapture(
size: const Size(400, 800),
barcodes: [
const Barcode(
rawValue: 'BOTTOM-CODE',
format: BarcodeFormat.code128,
corners: [
Offset(50, 500),
Offset(250, 500),
Offset(250, 540),
Offset(50, 540),
],
),
const Barcode(
rawValue: 'TOP-RIGHT',
format: BarcodeFormat.qrCode,
corners: [
Offset(240, 120),
Offset(320, 120),
Offset(320, 180),
Offset(240, 180),
],
),
const Barcode(
rawValue: 'TOP-LEFT',
format: BarcodeFormat.ean13,
corners: [
Offset(40, 125),
Offset(160, 125),
Offset(160, 175),
Offset(40, 175),
],
),
// Near-identical duplicate of TOP-LEFT
const Barcode(
rawValue: 'TOP-LEFT',
format: BarcodeFormat.ean13,
corners: [
Offset(44, 127),
Offset(162, 127),
Offset(162, 177),
Offset(44, 177),
],
),
],
);
final items = BarcodeGeometry.mapCaptureToItems(
capture: capture,
widgetSize: const Size(400, 800),
deviceOrientation: DeviceOrientation.portraitUp,
);
expect(items.map((e) => e.code).toList(), [
'TOP-LEFT',
'TOP-RIGHT',
'BOTTOM-CODE',
]);
expect(items.map((e) => e.index).toList(), [1, 2, 3]);
});
test('selectPrecisionTarget isolates only the barcode at crosshair', () {
final upper = _makeItem(
index: 1,
code: 'UPPER-111',
rect: const Rect.fromLTWH(80, 290, 240, 26),
);
final targeted = _makeItem(
index: 2,
code: 'CENTER-222',
rect: const Rect.fromLTWH(80, 336, 240, 26),
);
final lower = _makeItem(
index: 3,
code: 'LOWER-333',
rect: const Rect.fromLTWH(80, 382, 240, 26),
);
const crosshairCenter = Offset(200, 349);
final selected = BarcodeGeometry.selectPrecisionTarget(
items: [upper, targeted, lower],
crosshairCenter: crosshairCenter,
hitRadius: 16.0,
);
expect(selected?.code, 'CENTER-222');
// Moving crosshair into gap well outside hitRadius selects nothing.
final noneSelected = BarcodeGeometry.selectPrecisionTarget(
items: [upper, lower],
crosshairCenter: const Offset(200, 349),
hitRadius: 16.0,
);
expect(noneSelected, isNull);
});
test('layoutArBadges prevents overlapping badges on tightly stacked barcodes', () {
final items = [
_makeItem(
index: 1,
code: 'CODE-ONE-1234',
rect: const Rect.fromLTWH(100, 220, 200, 20),
),
_makeItem(
index: 2,
code: 'CODE-TWO-5678',
rect: const Rect.fromLTWH(100, 246, 200, 20),
),
_makeItem(
index: 3,
code: 'CODE-THREE-90',
rect: const Rect.fromLTWH(100, 272, 200, 20),
),
];
const safeBounds = Rect.fromLTWH(12, 120, 376, 460);
final layout = BarcodeGeometry.layoutArBadges(
items: items,
safeBounds: safeBounds,
measureBadge: (_) => const Size(150, 30),
);
expect(layout.length, 3);
final r1 = layout[1]!;
final r2 = layout[2]!;
final r3 = layout[3]!;
expect(r1.overlaps(r2), isFalse);
expect(r2.overlaps(r3), isFalse);
expect(r1.overlaps(r3), isFalse);
for (final r in [r1, r2, r3]) {
expect(safeBounds.contains(r.topLeft), isTrue);
expect(safeBounds.contains(r.bottomRight), isTrue);
}
});
});
group('AimMode Settings & ScannerCubit multi-pick', () {
late SharedPreferences prefs;
late SettingsRepositoryImpl settingsRepo;
late ConnectionRepositoryImpl connectionRepo;
late ScanRepositoryImpl scanRepo;
setUp(() async {
SharedPreferences.setMockInitialValues({});
prefs = await SharedPreferences.getInstance();
settingsRepo = SettingsRepositoryImpl(SettingsLocalDataSource(prefs));
connectionRepo = ConnectionRepositoryImpl(
localDataSource: ConnectionLocalDataSource(prefs),
remoteDataSource: ConnectionRemoteDataSource(),
discoveryDataSource: const UdpDiscoveryDataSource(),
);
scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
});
tearDown(() {
connectionRepo.dispose();
});
test('SettingsCubit persists ScanAimMode', () async {
final cubit = SettingsCubit(settingsRepo);
await cubit.loadSettings();
expect(cubit.state.settings.aimMode, ScanAimMode.standard);
await cubit.updateAimMode(ScanAimMode.arMulti);
expect(cubit.state.settings.aimMode, ScanAimMode.arMulti);
final reloaded = await settingsRepo.loadSettings();
expect(reloaded.aimMode, ScanAimMode.arMulti);
});
test('ScannerCubit.sendSelectedBarcode bypasses debounce for rapid AR taps', () async {
final settingsCubit = SettingsCubit(settingsRepo);
final connectionCubit = ConnectionCubit(connectionRepo);
final historyCubit = HistoryCubit(scanRepo);
final scannerCubit = ScannerCubit(
connectionCubit: connectionCubit,
settingsCubit: settingsCubit,
historyCubit: historyCubit,
feedbackService: const FeedbackService(),
);
await scannerCubit.sendSelectedBarcode('ART-001', format: 'code128');
await scannerCubit.sendSelectedBarcode('SN-999', format: 'qrCode');
await scannerCubit.sendSelectedBarcode('SN-999', format: 'qrCode');
expect(historyCubit.state.history.length, 3);
expect(scannerCubit.state.lastScan?.code, 'SN-999');
scannerCubit.setZoomScale(1.4);
expect(scannerCubit.state.zoomScale, 1.0);
});
});
group('Scanner UI Widgets', () {
testWidgets('ScannerControlsBar renders presets, modes and freeze CTA', (tester) async {
ScanAimMode? switchedMode;
double? selectedZoom;
var freezeTapped = false;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ScannerControlsBar(
aimMode: ScanAimMode.arMulti,
zoomScale: 0.25,
liveBarcodeCount: 2,
isPendingFreeze: false,
onAimModeChanged: (m) => switchedMode = m,
onZoomPresetSelected: (z) => selectedZoom = z,
onFreezePressed: () => freezeTapped = true,
onCancelPendingFreeze: () {},
onManualInputPressed: () {},
),
),
),
);
expect(find.text('Blocca frame (2 codici)'), findsOneWidget);
expect(find.text('1x'), findsOneWidget);
expect(find.text('2x'), findsOneWidget);
expect(find.text('3x'), findsOneWidget);
expect(find.text('Standard'), findsOneWidget);
expect(find.text('Precisione'), findsOneWidget);
expect(find.text('AR Multi'), findsOneWidget);
await tester.tap(find.text('Blocca frame (2 codici)'));
expect(freezeTapped, isTrue);
await tester.tap(find.text('3x'));
expect(selectedZoom, 0.50);
await tester.tap(find.text('Precisione'));
expect(switchedMode, ScanAimMode.precision);
});
testWidgets('ArBarcodeOverlay triggers onTapBarcode when tapping a badge', (tester) async {
DetectedBarcodeItem? tappedItem;
final items = [
_makeItem(
index: 1,
code: '8001234567890',
rect: const Rect.fromLTWH(80, 200, 180, 30),
),
_makeItem(
index: 2,
code: 'SN-ABC-42',
rect: const Rect.fromLTWH(80, 270, 180, 30),
),
];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 400,
height: 700,
child: ArBarcodeOverlay(
items: items,
safeBounds: const Rect.fromLTWH(10, 60, 380, 560),
showBadges: true,
onTapBarcode: (item) => tappedItem = item,
),
),
),
),
);
expect(find.text('8001234567890'), findsOneWidget);
expect(find.text('SN-ABC-42'), findsOneWidget);
await tester.tap(find.text('SN-ABC-42'));
expect(tappedItem?.code, 'SN-ABC-42');
});
testWidgets('ArFrozenPicker displays numbered list, sent badge, and resume callback', (tester) async {
DetectedBarcodeItem? selected;
var resumed = false;
final items = [
_makeItem(
index: 1,
code: 'ART-100',
rect: const Rect.fromLTWH(80, 180, 180, 28),
),
_makeItem(
index: 2,
code: 'SN-200',
rect: const Rect.fromLTWH(80, 240, 180, 28),
),
];
final snapshot = ArCaptureSnapshot(
imageBytes: _kTinyPng,
imageSize: const Size(400, 800),
viewportSize: const Size(400, 800),
deviceOrientation: DeviceOrientation.portraitUp,
items: items,
timestamp: DateTime.now(),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 400,
height: 800,
child: ArFrozenPicker(
snapshot: snapshot,
sentKeys: {items.first.selectionKey},
onSelectBarcode: (item) => selected = item,
onResumeLive: () => resumed = true,
),
),
),
),
);
expect(find.text('Frame bloccato • 2 codici'), findsOneWidget);
expect(find.text('ART-100'), findsNWidgets(2)); // AR badge + list row
expect(find.text('SN-200'), findsNWidgets(2));
expect(find.text('Inviato'), findsOneWidget);
expect(find.text('Invia'), findsOneWidget);
await tester.tap(find.text('Invia'));
expect(selected?.code, 'SN-200');
await tester.tap(find.text('Riprendi'));
expect(resumed, isTrue);
});
});
}