From fd83f6fc75206f62e31b7599d777cfde310a9d30 Mon Sep 17 00:00:00 2001 From: Mark M2 Macbook Date: Wed, 11 Nov 2026 21:45:38 +0100 Subject: [PATCH] feat: add audio and vibration feedback alongside configurable scan cooldowns --- app/assets/sounds/beep_error.wav | Bin 0 -> 21210 bytes app/assets/sounds/beep_success.wav | Bin 0 -> 10186 bytes app/lib/core/constants/app_constants.dart | 4 + app/lib/core/services/feedback_service.dart | 145 +++++++++++- .../presentation/cubit/scanner_cubit.dart | 84 +++++-- .../presentation/cubit/scanner_state.dart | 16 ++ .../presentation/screens/scanner_screen.dart | 3 + .../presentation/widgets/scanner_overlay.dart | 193 +++++++++++++-- .../settings_local_datasource.dart | 7 + .../settings_repository_impl.dart | 5 + .../domain/entities/app_settings.dart | 5 + .../repositories/settings_repository.dart | 1 + .../presentation/cubit/settings_cubit.dart | 6 + .../presentation/screens/settings_screen.dart | 45 +++- .../flutter/generated_plugin_registrant.cc | 4 + app/linux/flutter/generated_plugins.cmake | 1 + .../Flutter/GeneratedPluginRegistrant.swift | 4 + app/pubspec.lock | 224 ++++++++++++++++++ app/pubspec.yaml | 5 + app/test/scan_feedback_and_cooldown_test.dart | 222 +++++++++++++++++ .../flutter/generated_plugin_registrant.cc | 3 + app/windows/flutter/generated_plugins.cmake | 1 + 22 files changed, 921 insertions(+), 57 deletions(-) create mode 100644 app/assets/sounds/beep_error.wav create mode 100644 app/assets/sounds/beep_success.wav create mode 100644 app/test/scan_feedback_and_cooldown_test.dart diff --git a/app/assets/sounds/beep_error.wav b/app/assets/sounds/beep_error.wav new file mode 100644 index 0000000000000000000000000000000000000000..6459ca8050c4723bedd544b96c489f34cf26dac9 GIT binary patch literal 21210 zcmeI)Rd8Bs*y!uy(b1VJ$HN_vMN z=N4fQEMktNtlGWm1N<2T!6O!kH#)JN^SCx#EdCn4 z3m-{1O(-E)5N8t45`PifiA0hcDV)S1O(1beQ6x{2F=>F9N4!hiL<}Qp2x){vgh;{& z{w+QQ?})F$UBXS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79i_?VbXv?Ep!E)pgX5JDP$KRyEF(>GYFI2;yNh`kBsDg>r>wU`fJ zuvTN(7*`Ay(}ffxU*QuUFChEjQy&*0Q;>K#!S_a-;WW<#Ap%CzqNC^tI*9h6J*Wg4 S$p3vw;Ojng2$iE6^nU;itbV`% literal 0 HcmV?d00001 diff --git a/app/assets/sounds/beep_success.wav b/app/assets/sounds/beep_success.wav new file mode 100644 index 0000000000000000000000000000000000000000..b6f2d3bf4beddeee622bbdf7948f76a4facc3846 GIT binary patch literal 10186 zcmeI2_g|Cu7RSHOlO2)}AYlYz!k$4v_E1n(M6HSzuh&`kt^>!lYO8hNUQ}xZN2{%< z*B!zVki8XTNZ5n~NJ2se*?F%2#r-9(^XvKX^E&5q-k-CKo09U;7l6#f?~}LeKFFp5 z0HAM`^c;ZmD_D%iB);D)?!JpjxA`@smvfc}E2q1Vtphz30d{@{0H)B;%)raB|v zfanMG7Y%l%l@=#Rg4&AZ;Bf>g9>!n63ecXYUWBTGB1f?B3PUQDLX^NnV6V%S=TPW(0tUnLTM=%F;fDqqe&&l8k9Y`iqoYJBdP7JOvx-ZYqd zZr-9uk^f#d8dZu;Fks}@hDjYowKXM`JXOKXip=&52^af4yFOeo|1LK^^}(Fv&_BJ- zIz6}f3`o-(C-(O>x4Kl87AEr^6`ig%3NC9NP`~pJjdM@E!Oc$M#Mp9=}fbiZuSe8?$K@$P)M)3Rw4fP0K>A=?tk+?{DQiA%#9eD^cbDJiHNU5M=b;8a_C z_2J?@ya9eoC zG@{$@N7rCm7xYfO+vMdTOM7*VYspRCMt=TB(2*%yhY#`ak9?8znp>4p8y_EX$Mc$F zD-nPY&5z^TdMjI^KgJb)$IB@0s%!0gsC{Y=0>6*XP2J5MogW(w2OXFpw9CPYjctl+ zLcgw;^fSkZhV;q1IvPqTh+54l zXP3~V1OQy8*Gf(dIJOto=9UpkpH+Ys($F4V54GMWA#zWGA#pM;efB2bXji@M0A`ix zr1GJ-N-)@3Q_U}{DdW`kc4SO+L3o$jK}a+vVPK9W@(d^6o#FVvh7I@XrYB7!>D`>> zysA&-=PS=PhxA`lJtK11P9fW4kIjK&3qxCc=ecdM`y2Pra$Iv#a(pnb!?AH`mH1

b|7r%|OL{k~}CUHeGFV-TQ&i5@7))T(KLZNn;q-C879*X#H zRAJc5plcp3&OcD{F~68+XhtPXL$|wXTT<(X>k3;sdeBk;WDZka9ka3`#NnBEbQ`8cke6Zsc&`^KS4(~#S=t-cb+_YM_r}5f(rDvD;sNItk1KvZ`!Do~WEVQy z+rh*aD8BiswnnjG+&J`JpzXqS=l6ady{PnpeznbW9re8J+v9V?gYH&NyGQoLErxQ9 z7c`$I^TmUM`GR#{se;g>!E$z|Eww#FL}T%AvSqb_GQD}K zUaA>u64AtQ6Tym9-7aV`G2iZnW3Kb06O)dzJ4mA9ndodlFfY*iY8n(g>GScUW2NJ7 zWK=cPbOXJbw8maY|LB-TXWKhbgai}jBs?E6e*26%sy?B>%9Y!Z5zolGW!FeAyD|ko1i_Pfa(5!gBm7N`oEj5MN`EDy_h-Rx+q@Qi>28+=Q+$jDE zA%I}Ut-{_$OW?hb3uw0NG>;iq8e}?&_O6zrd!xsgdM!=RZuACh7VaSqj}v3gpjoJH zh!0*NPb}xm875Dom*I*&N59-qW2`U(FcXH*F_;R>eT)H(L91aogo9$iPYBO4WJZ}I zOu5E&#y^a!Oc%{~ triggerScanFeedback({required bool sound, required bool vibrate}) async { + static AudioPlayer? _successPlayer; + static AudioPlayer? _errorPlayer; + static bool _audioConfigured = false; + static bool? _hasVibrator; + + static bool get _isFlutterTest => + !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); + + static Future _ensureAudioConfigured() async { + if (_audioConfigured || _isFlutterTest) return; + _audioConfigured = true; try { - if (vibrate) { - await HapticFeedback.mediumImpact(); + await AudioPlayer.global.setAudioContext( + AudioContext( + iOS: AudioContextIOS( + category: AVAudioSessionCategory.playback, + options: {AVAudioSessionOptions.mixWithOthers}, + ), + android: AudioContextAndroid( + isSpeakerphoneOn: false, + stayAwake: false, + contentType: AndroidContentType.sonification, + usageType: AndroidUsageType.assistanceSonification, + audioFocus: AndroidAudioFocus.none, + ), + ), + ); + } catch (_) {} + } + + static Future _getPlayer({required bool isError}) async { + if (_isFlutterTest) return null; + try { + await _ensureAudioConfigured(); + if (isError) { + _errorPlayer ??= AudioPlayer() + ..setReleaseMode(ReleaseMode.stop) + ..setPlayerMode(PlayerMode.lowLatency); + return _errorPlayer; + } else { + _successPlayer ??= AudioPlayer() + ..setReleaseMode(ReleaseMode.stop) + ..setPlayerMode(PlayerMode.lowLatency); + return _successPlayer; } - if (sound) { - await SystemSound.play(SystemSoundType.click); + } catch (_) { + return null; + } + } + + Future _playBeep({required bool isError}) async { + if (_isFlutterTest) return; + try { + final player = await _getPlayer(isError: isError); + if (player != null) { + await player.stop(); + await player.play( + AssetSource( + isError ? 'sounds/beep_error.wav' : 'sounds/beep_success.wav', + ), + volume: 1.0, + ); + return; + } + } catch (_) { + // Fallback to system sound if asset player is unavailable + try { + await SystemSound.play( + isError ? SystemSoundType.alert : SystemSoundType.click, + ); + } catch (_) {} + } + } + + Future _vibrate({required bool isError}) async { + if (_isFlutterTest) return; + try { + _hasVibrator ??= await Vibration.hasVibrator(); + if (_hasVibrator == true) { + if (isError) { + await Vibration.vibrate(pattern: [0, 75, 65, 120]); + } else { + await Vibration.vibrate(duration: 110, amplitude: 220); + } + return; } } catch (_) {} + + // Fallback to Flutter HapticFeedback + try { + if (isError) { + await HapticFeedback.vibrate(); + } else { + await HapticFeedback.heavyImpact(); + } + } catch (_) {} + } + + /// Feedback confermato quando il codice è stato inviato con successo al PC. + Future triggerSentSuccess({ + required bool sound, + required bool vibrate, + }) async { + final futures = >[]; + if (vibrate) futures.add(_vibrate(isError: false)); + if (sound) futures.add(_playBeep(isError: false)); + if (futures.isNotEmpty) { + await Future.wait(futures); + } + } + + /// Feedback distinto quando l'invio al PC non è riuscito (es. PC disconnesso). + Future triggerSentError({ + required bool sound, + required bool vibrate, + }) async { + final futures = >[]; + if (vibrate) futures.add(_vibrate(isError: true)); + if (sound) futures.add(_playBeep(isError: true)); + if (futures.isNotEmpty) { + await Future.wait(futures); + } + } + + Future triggerScanFeedback({ + required bool sound, + required bool vibrate, + }) async { + await triggerSentSuccess(sound: sound, vibrate: vibrate); } Future triggerSuccess() async { - try { - await HapticFeedback.heavyImpact(); - } catch (_) {} + await _vibrate(isError: false); } Future triggerError() async { - try { - await HapticFeedback.vibrate(); - } catch (_) {} + await _vibrate(isError: true); } Future triggerSelection() async { @@ -32,4 +154,3 @@ class FeedbackService { } catch (_) {} } } - diff --git a/app/lib/features/scanner/presentation/cubit/scanner_cubit.dart b/app/lib/features/scanner/presentation/cubit/scanner_cubit.dart index f25c999..0bd798a 100644 --- a/app/lib/features/scanner/presentation/cubit/scanner_cubit.dart +++ b/app/lib/features/scanner/presentation/cubit/scanner_cubit.dart @@ -1,3 +1,6 @@ +import 'dart:async'; +import 'dart:math' as math; + import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../../core/services/feedback_service.dart'; import '../../../connection/presentation/cubit/connection_cubit.dart'; @@ -12,6 +15,8 @@ class ScannerCubit extends Cubit { final HistoryCubit historyCubit; final FeedbackService feedbackService; + Timer? _cooldownTimer; + ScannerCubit({ required this.connectionCubit, required this.settingsCubit, @@ -33,34 +38,48 @@ class ScannerCubit extends Cubit { emit(state.copyWith(zoomScale: clamped)); } + void clearCooldown() { + _cooldownTimer?.cancel(); + _cooldownTimer = null; + if (!isClosed && (state.cooldownUntil != null || state.cooldownTotalMs != 0)) { + emit(state.copyWith(clearCooldown: true)); + } + } + Future processBarcode( String rawValue, { String format = 'Barcode', }) async { final cleanCode = rawValue.trim(); if (cleanCode.isEmpty) return; + if (state.isProcessing || state.isInCooldown) return; final now = DateTime.now(); final isSameCode = cleanCode == state.lastScannedValue; final durationSinceLast = now.difference(state.lastScannedTime); - final continuous = settingsCubit.state.settings.continuousMode; + final settings = settingsCubit.state.settings; - // Minimum debounce interval for live camera stream - final minInterval = isSameCode - ? (continuous - ? const Duration(milliseconds: 1000) - : const Duration(milliseconds: 1800)) - : const Duration(milliseconds: 600); + // Post-scan cooldown pause: gives the operator time (default 2.5s) to + // move the camera away before the next automatic read. + final configuredCooldownMs = settings.scanCooldownMs; + final effectiveCooldownMs = (settings.continuousMode && !isSameCode) + ? math.min(configuredCooldownMs, 1000) + : configuredCooldownMs; - if (durationSinceLast < minInterval || state.isProcessing) { + if (durationSinceLast < Duration(milliseconds: effectiveCooldownMs)) { return; } - await _sendAndRecord(cleanCode, format: format, timestamp: now); + await _sendAndRecord( + cleanCode, + format: format, + timestamp: now, + cooldownMs: effectiveCooldownMs, + ); } /// 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. + /// bypassing the live-camera cooldown so rapid multi-code picking feels instant. Future sendSelectedBarcode( String rawValue, { String format = 'Barcode', @@ -93,6 +112,7 @@ class ScannerCubit extends Cubit { required DateTime timestamp, String? idOverride, bool updateDebounceTracker = true, + int cooldownMs = 0, }) async { emit(state.copyWith( isProcessing: true, @@ -101,18 +121,23 @@ class ScannerCubit extends Cubit { )); final settings = settingsCubit.state.settings; - await feedbackService.triggerScanFeedback( - sound: settings.sound, - vibrate: settings.vibrate, - ); final success = await connectionCubit.sendCode( code: cleanCode, suffix: settings.suffix, ); + // Distinct audio + vibration confirmation right when the code is sent if (success) { - await feedbackService.triggerSuccess(); + await feedbackService.triggerSentSuccess( + sound: settings.sound, + vibrate: settings.vibrate, + ); + } else { + await feedbackService.triggerSentError( + sound: settings.sound, + vibrate: settings.vibrate, + ); } final record = ScanRecord( @@ -125,11 +150,32 @@ class ScannerCubit extends Cubit { await historyCubit.addScan(record); - emit(state.copyWith( - isProcessing: false, - lastScan: record, - )); + DateTime? cooldownUntil; + var activeCooldownTotalMs = 0; + + if (cooldownMs > 0) { + _cooldownTimer?.cancel(); + cooldownUntil = DateTime.now().add(Duration(milliseconds: cooldownMs)); + activeCooldownTotalMs = cooldownMs; + _cooldownTimer = Timer(Duration(milliseconds: cooldownMs), clearCooldown); + } + + if (!isClosed) { + emit(state.copyWith( + isProcessing: false, + lastScan: record, + cooldownUntil: cooldownUntil, + cooldownTotalMs: activeCooldownTotalMs, + )); + } return record; } + + @override + Future close() { + _cooldownTimer?.cancel(); + _cooldownTimer = null; + return super.close(); + } } diff --git a/app/lib/features/scanner/presentation/cubit/scanner_state.dart b/app/lib/features/scanner/presentation/cubit/scanner_state.dart index 532609c..f483310 100644 --- a/app/lib/features/scanner/presentation/cubit/scanner_state.dart +++ b/app/lib/features/scanner/presentation/cubit/scanner_state.dart @@ -9,6 +9,8 @@ class ScannerState extends Equatable { final String? lastScannedValue; final DateTime lastScannedTime; final double zoomScale; + final DateTime? cooldownUntil; + final int cooldownTotalMs; ScannerState({ this.lastScan, @@ -18,9 +20,14 @@ class ScannerState extends Equatable { this.lastScannedValue, DateTime? lastScannedTime, this.zoomScale = 0.0, + this.cooldownUntil, + this.cooldownTotalMs = 0, }) : lastScannedTime = lastScannedTime ?? DateTime.fromMillisecondsSinceEpoch(0); + bool get isInCooldown => + cooldownUntil != null && DateTime.now().isBefore(cooldownUntil!); + ScannerState copyWith({ ScanRecord? lastScan, bool? isTorchOn, @@ -29,6 +36,9 @@ class ScannerState extends Equatable { String? lastScannedValue, DateTime? lastScannedTime, double? zoomScale, + DateTime? cooldownUntil, + int? cooldownTotalMs, + bool clearCooldown = false, }) { return ScannerState( lastScan: lastScan ?? this.lastScan, @@ -38,6 +48,10 @@ class ScannerState extends Equatable { lastScannedValue: lastScannedValue ?? this.lastScannedValue, lastScannedTime: lastScannedTime ?? this.lastScannedTime, zoomScale: zoomScale ?? this.zoomScale, + cooldownUntil: + clearCooldown ? null : (cooldownUntil ?? this.cooldownUntil), + cooldownTotalMs: + clearCooldown ? 0 : (cooldownTotalMs ?? this.cooldownTotalMs), ); } @@ -50,5 +64,7 @@ class ScannerState extends Equatable { lastScannedValue, lastScannedTime, zoomScale, + cooldownUntil, + cooldownTotalMs, ]; } diff --git a/app/lib/features/scanner/presentation/screens/scanner_screen.dart b/app/lib/features/scanner/presentation/screens/scanner_screen.dart index f1d7042..55f0c7c 100644 --- a/app/lib/features/scanner/presentation/screens/scanner_screen.dart +++ b/app/lib/features/scanner/presentation/screens/scanner_screen.dart @@ -487,6 +487,9 @@ class _ScannerScreenState extends State ScannerOverlay( aimMode: aimMode, hasPrecisionTarget: _precisionTargetIndex != null, + cooldownUntil: scannerState.cooldownUntil, + cooldownTotalMs: scannerState.cooldownTotalMs, + lastScanSucceeded: lastScan?.sentSuccessfully ?? true, ), // 3. Live AR Overlay (outlines in Precisione, badges in AR Multi) diff --git a/app/lib/features/scanner/presentation/widgets/scanner_overlay.dart b/app/lib/features/scanner/presentation/widgets/scanner_overlay.dart index 4cad38e..a50536f 100644 --- a/app/lib/features/scanner/presentation/widgets/scanner_overlay.dart +++ b/app/lib/features/scanner/presentation/widgets/scanner_overlay.dart @@ -6,11 +6,17 @@ import '../utils/barcode_geometry.dart'; class ScannerOverlay extends StatefulWidget { final ScanAimMode aimMode; final bool hasPrecisionTarget; + final DateTime? cooldownUntil; + final int cooldownTotalMs; + final bool lastScanSucceeded; const ScannerOverlay({ super.key, this.aimMode = ScanAimMode.standard, this.hasPrecisionTarget = false, + this.cooldownUntil, + this.cooldownTotalMs = 0, + this.lastScanSucceeded = true, }); @override @@ -55,10 +61,20 @@ class _ScannerOverlayState extends State return const SizedBox.expand(); } + final cooldownUntil = widget.cooldownUntil; + final remainingMs = cooldownUntil != null + ? cooldownUntil.difference(DateTime.now()).inMilliseconds + : 0; + final isCoolingDown = remainingMs > 0; + final cooldownColor = + widget.lastScanSucceeded ? AppTheme.success : AppTheme.warning; + final isPrecision = widget.aimMode == ScanAimMode.precision; - final accentColor = isPrecision && widget.hasPrecisionTarget - ? AppTheme.success - : AppTheme.primary; + final accentColor = isCoolingDown + ? cooldownColor + : (isPrecision && widget.hasPrecisionTarget + ? AppTheme.success + : AppTheme.primary); final maskAlpha = isPrecision ? 0.72 : 0.62; final radius = isPrecision ? 14.0 : 18.0; @@ -93,15 +109,19 @@ class _ScannerOverlayState extends State ), ), - // Outer border + // Outer border (+ subtle confirmation tint during cooldown) Positioned.fromRect( rect: scanRect, - child: Container( + child: AnimatedContainer( + duration: const Duration(milliseconds: 160), decoration: BoxDecoration( + color: isCoolingDown + ? cooldownColor.withValues(alpha: 0.14) + : Colors.transparent, borderRadius: BorderRadius.circular(radius), border: Border.all( - color: accentColor.withValues(alpha: 0.4), - width: 1.5, + color: accentColor.withValues(alpha: isCoolingDown ? 0.85 : 0.4), + width: isCoolingDown ? 2.0 : 1.5, ), ), ), @@ -114,7 +134,34 @@ class _ScannerOverlayState extends State radius: radius, ), - if (isPrecision) + if (isCoolingDown) + Positioned.fromRect( + rect: scanRect, + child: Center( + child: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: cooldownColor.withValues(alpha: 0.9), + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: cooldownColor.withValues(alpha: 0.5), + blurRadius: 14, + spreadRadius: 2, + ), + ], + ), + child: Icon( + widget.lastScanSucceeded + ? Icons.check_rounded + : Icons.priority_high_rounded, + color: Colors.white, + size: 28, + ), + ), + ), + ) + else if (isPrecision) _PrecisionCrosshair( scanRect: scanRect, accentColor: accentColor, @@ -157,26 +204,38 @@ class _ScannerOverlayState extends State }, ), - // Helper text below reticle + // Cooldown pill or helper text below reticle Positioned( 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: const TextStyle( - color: Colors.white70, - fontSize: 12, - fontWeight: FontWeight.w500, - letterSpacing: 0.2, - shadows: [ - Shadow(color: Colors.black, blurRadius: 6), - ], - ), - ), + child: isCoolingDown + ? Center( + child: _CooldownStatusPill( + key: ValueKey(cooldownUntil), + remainingMs: remainingMs, + totalMs: widget.cooldownTotalMs > 0 + ? widget.cooldownTotalMs + : remainingMs, + succeeded: widget.lastScanSucceeded, + color: cooldownColor, + ), + ) + : 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: const TextStyle( + color: Colors.white70, + fontSize: 12, + fontWeight: FontWeight.w500, + letterSpacing: 0.2, + shadows: [ + Shadow(color: Colors.black, blurRadius: 6), + ], + ), + ), ), ], ); @@ -372,3 +431,89 @@ class _CornersPainter extends CustomPainter { bool shouldRepaint(covariant _CornersPainter oldDelegate) => oldDelegate.color != color || oldDelegate.radius != radius; } + +class _CooldownStatusPill extends StatelessWidget { + final int remainingMs; + final int totalMs; + final bool succeeded; + final Color color; + + const _CooldownStatusPill({ + super.key, + required this.remainingMs, + required this.totalMs, + required this.succeeded, + required this.color, + }); + + @override + Widget build(BuildContext context) { + final startFraction = (remainingMs / totalMs).clamp(0.0, 1.0); + + return TweenAnimationBuilder( + tween: Tween(begin: startFraction, end: 0.0), + duration: Duration(milliseconds: remainingMs), + builder: (context, fraction, _) { + final secsLeft = (fraction * totalMs / 1000.0).clamp(0.0, 99.9); + final label = succeeded + ? 'Inviato • Pausa ${secsLeft.toStringAsFixed(1)}s' + : 'Non inviato • Pausa ${secsLeft.toStringAsFixed(1)}s'; + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: AppTheme.darkBackground.withValues(alpha: 0.88), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: color.withValues(alpha: 0.65), width: 1.2), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.4), + blurRadius: 10, + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + succeeded + ? Icons.check_circle_rounded + : Icons.warning_amber_rounded, + size: 15, + color: color, + ), + const SizedBox(width: 6), + Text( + label, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 0.2, + ), + ), + ], + ), + const SizedBox(height: 6), + SizedBox( + width: 150, + child: ClipRRect( + borderRadius: BorderRadius.circular(2), + child: LinearProgressIndicator( + value: fraction, + minHeight: 3, + backgroundColor: color.withValues(alpha: 0.2), + valueColor: AlwaysStoppedAnimation(color), + ), + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/app/lib/features/settings/data/datasources/settings_local_datasource.dart b/app/lib/features/settings/data/datasources/settings_local_datasource.dart index ab0091a..e7a6f1e 100644 --- a/app/lib/features/settings/data/datasources/settings_local_datasource.dart +++ b/app/lib/features/settings/data/datasources/settings_local_datasource.dart @@ -12,6 +12,8 @@ class SettingsLocalDataSource { final suffix = _prefs.getString(AppConstants.keySuffix) ?? AppConstants.suffixEnter; final continuous = _prefs.getBool(AppConstants.keyContinuous) ?? false; + final scanCooldownMs = _prefs.getInt(AppConstants.keyScanCooldownMs) ?? + AppConstants.defaultScanCooldownMs; final vibrate = _prefs.getBool(AppConstants.keyVibrate) ?? true; final sound = _prefs.getBool(AppConstants.keySound) ?? true; final autoConnect = _prefs.getBool(AppConstants.keyAutoConnect) ?? false; @@ -24,6 +26,7 @@ class SettingsLocalDataSource { return AppSettings( suffix: suffix, continuousMode: continuous, + scanCooldownMs: scanCooldownMs, vibrate: vibrate, sound: sound, autoConnect: autoConnect, @@ -40,6 +43,10 @@ class SettingsLocalDataSource { await _prefs.setBool(AppConstants.keyContinuous, enabled); } + Future saveScanCooldownMs(int cooldownMs) async { + await _prefs.setInt(AppConstants.keyScanCooldownMs, cooldownMs); + } + Future saveFeedbackToggles( {required bool vibrate, required bool sound}) async { await _prefs.setBool(AppConstants.keyVibrate, vibrate); diff --git a/app/lib/features/settings/data/repositories/settings_repository_impl.dart b/app/lib/features/settings/data/repositories/settings_repository_impl.dart index 59ce8d3..09e9546 100644 --- a/app/lib/features/settings/data/repositories/settings_repository_impl.dart +++ b/app/lib/features/settings/data/repositories/settings_repository_impl.dart @@ -23,6 +23,11 @@ class SettingsRepositoryImpl implements SettingsRepository { await _localDataSource.saveContinuousMode(enabled); } + @override + Future saveScanCooldownMs(int cooldownMs) async { + await _localDataSource.saveScanCooldownMs(cooldownMs); + } + @override Future saveFeedbackToggles( {required bool vibrate, required bool sound}) async { diff --git a/app/lib/features/settings/domain/entities/app_settings.dart b/app/lib/features/settings/domain/entities/app_settings.dart index a139435..8bd8489 100644 --- a/app/lib/features/settings/domain/entities/app_settings.dart +++ b/app/lib/features/settings/domain/entities/app_settings.dart @@ -5,6 +5,7 @@ import '../../../scanner/domain/entities/scan_aim_mode.dart'; class AppSettings extends Equatable { final String suffix; // 'enter', 'tab', 'none' final bool continuousMode; + final int scanCooldownMs; // Default: 2500ms (2.5s pause between scans) final bool vibrate; final bool sound; final bool autoConnect; // Default: false (ideal for multi-PC store) @@ -14,6 +15,7 @@ class AppSettings extends Equatable { const AppSettings({ this.suffix = 'enter', this.continuousMode = false, + this.scanCooldownMs = AppConstants.defaultScanCooldownMs, this.vibrate = true, this.sound = true, this.autoConnect = false, @@ -24,6 +26,7 @@ class AppSettings extends Equatable { AppSettings copyWith({ String? suffix, bool? continuousMode, + int? scanCooldownMs, bool? vibrate, bool? sound, bool? autoConnect, @@ -33,6 +36,7 @@ class AppSettings extends Equatable { return AppSettings( suffix: suffix ?? this.suffix, continuousMode: continuousMode ?? this.continuousMode, + scanCooldownMs: scanCooldownMs ?? this.scanCooldownMs, vibrate: vibrate ?? this.vibrate, sound: sound ?? this.sound, autoConnect: autoConnect ?? this.autoConnect, @@ -46,6 +50,7 @@ class AppSettings extends Equatable { List get props => [ suffix, continuousMode, + scanCooldownMs, vibrate, sound, autoConnect, diff --git a/app/lib/features/settings/domain/repositories/settings_repository.dart b/app/lib/features/settings/domain/repositories/settings_repository.dart index 78e6ff3..d4463ab 100644 --- a/app/lib/features/settings/domain/repositories/settings_repository.dart +++ b/app/lib/features/settings/domain/repositories/settings_repository.dart @@ -5,6 +5,7 @@ abstract class SettingsRepository { Future loadSettings(); Future saveSuffix(String suffix); Future saveContinuousMode(bool enabled); + Future saveScanCooldownMs(int cooldownMs); Future saveFeedbackToggles({required bool vibrate, required bool sound}); Future saveAutoConnect(bool enabled); Future saveInactivityTimeout(int minutes); diff --git a/app/lib/features/settings/presentation/cubit/settings_cubit.dart b/app/lib/features/settings/presentation/cubit/settings_cubit.dart index 90cb645..39a5f97 100644 --- a/app/lib/features/settings/presentation/cubit/settings_cubit.dart +++ b/app/lib/features/settings/presentation/cubit/settings_cubit.dart @@ -30,6 +30,12 @@ class SettingsCubit extends Cubit { await _settingsRepository.saveContinuousMode(enabled); } + Future updateScanCooldownMs(int cooldownMs) async { + final updated = state.settings.copyWith(scanCooldownMs: cooldownMs); + emit(state.copyWith(settings: updated)); + await _settingsRepository.saveScanCooldownMs(cooldownMs); + } + Future updateFeedback({bool? vibrate, bool? sound}) async { final updated = state.settings.copyWith( vibrate: vibrate ?? state.settings.vibrate, diff --git a/app/lib/features/settings/presentation/screens/settings_screen.dart b/app/lib/features/settings/presentation/screens/settings_screen.dart index 767396c..af8c2d1 100644 --- a/app/lib/features/settings/presentation/screens/settings_screen.dart +++ b/app/lib/features/settings/presentation/screens/settings_screen.dart @@ -302,6 +302,47 @@ class SettingsScreen extends StatelessWidget { ), ), const Divider(height: 1), + 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.hourglass_bottom_rounded, + color: AppTheme.primary, size: 22), + ), + title: const Text('Pausa dopo scansione'), + subtitle: Text( + 'Attesa di ${(settings.scanCooldownMs / 1000).toStringAsFixed(1).replaceAll('.', ',')}s prima della prossima lettura', + style: const TextStyle(fontSize: 12), + ), + trailing: DropdownButton( + value: settings.scanCooldownMs, + dropdownColor: AppTheme.darkCard, + style: const TextStyle( + color: AppTheme.darkTextPrimary, + fontWeight: FontWeight.bold, + ), + underline: const SizedBox.shrink(), + items: const [ + DropdownMenuItem(value: 1000, child: Text('1,0 sec (Rapida)')), + DropdownMenuItem(value: 2000, child: Text('2,0 sec')), + DropdownMenuItem(value: 2500, child: Text('2,5 sec (Consigliata)')), + DropdownMenuItem(value: 3000, child: Text('3,0 sec')), + DropdownMenuItem(value: 4000, child: Text('4,0 sec')), + DropdownMenuItem(value: 5000, child: Text('5,0 sec')), + ], + onChanged: (val) { + if (val != null) { + context + .read() + .updateScanCooldownMs(val); + } + }, + ), + ), + const Divider(height: 1), SwitchListTile( secondary: Container( padding: const EdgeInsets.all(8), @@ -314,8 +355,8 @@ class SettingsScreen extends StatelessWidget { ), title: const Text('Scansione Continua'), subtitle: const Text( - 'Continua a leggere codici in sequenza senza pause', - style: TextStyle(fontSize: 13), + 'Riduce la pausa a 1,0s quando inquadri codici diversi in serie', + style: TextStyle(fontSize: 12), ), value: settings.continuousMode, onChanged: (val) { diff --git a/app/linux/flutter/generated_plugin_registrant.cc b/app/linux/flutter/generated_plugin_registrant.cc index e71a16d..1830e5c 100644 --- a/app/linux/flutter/generated_plugin_registrant.cc +++ b/app/linux/flutter/generated_plugin_registrant.cc @@ -6,6 +6,10 @@ #include "generated_plugin_registrant.h" +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); + audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); } diff --git a/app/linux/flutter/generated_plugins.cmake b/app/linux/flutter/generated_plugins.cmake index be1ee3e..f4bf1dc 100644 --- a/app/linux/flutter/generated_plugins.cmake +++ b/app/linux/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/app/macos/Flutter/GeneratedPluginRegistrant.swift b/app/macos/Flutter/GeneratedPluginRegistrant.swift index f15c78b..9c4e8ad 100644 --- a/app/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/app/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,10 +5,14 @@ import FlutterMacOS import Foundation +import audioplayers_darwin +import device_info_plus import mobile_scanner import shared_preferences_foundation func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) + DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) } diff --git a/app/pubspec.lock b/app/pubspec.lock index 7c1d640..17c3030 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -17,6 +17,62 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + audioplayers: + dependency: "direct main" + description: + name: audioplayers + sha256: "2ba4bb2944baacbdd5372ff8254a8e7feb8c10d7739545e392f5605a8f618745" + url: "https://pub.dev" + source: hosted + version: "6.8.1" + audioplayers_android: + dependency: transitive + description: + name: audioplayers_android + sha256: f5ff5b15620fbab8cb0849e9636c48e2b96c3f0f71723bbbe2ad3c761b205f05 + url: "https://pub.dev" + source: hosted + version: "5.3.0" + audioplayers_darwin: + dependency: transitive + description: + name: audioplayers_darwin + sha256: "1ca553add991384ecf421b9569da850f3ab2472ffb83f6970b0416365abc51be" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + audioplayers_linux: + dependency: transitive + description: + name: audioplayers_linux + sha256: "15178b726b7cdee5364d0463c8d445630c4e0fb7d26612b73c767e7d25de9417" + url: "https://pub.dev" + source: hosted + version: "4.3.0" + audioplayers_platform_interface: + dependency: transitive + description: + name: audioplayers_platform_interface + sha256: "765f6f0e6dca55cb471c9483fc77700564b3484d19198aca4ebb5147c6c85acb" + url: "https://pub.dev" + source: hosted + version: "7.2.0" + audioplayers_web: + dependency: transitive + description: + name: audioplayers_web + sha256: ae1e0103c865a03e273f6d13d97b93f5595eac09915729cd5e37ef96e2857319 + url: "https://pub.dev" + source: hosted + version: "5.3.0" + audioplayers_windows: + dependency: transitive + description: + name: audioplayers_windows + sha256: a70ae82bba2dfcb6eb03dd4815d737a2d46d33ea5a96a03f535cfcaac490e413 + url: "https://pub.dev" + source: hosted + version: "4.4.1" bloc: dependency: transitive description: @@ -49,6 +105,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.3" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.dev" + source: hosted + version: "1.2.1" collection: dependency: transitive description: @@ -73,6 +137,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.9" + device_info_plus: + dependency: transitive + description: + name: device_info_plus + sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa + url: "https://pub.dev" + source: hosted + version: "13.3.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" + url: "https://pub.dev" + source: hosted + version: "8.1.0" equatable: dependency: "direct main" description: @@ -97,6 +177,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" file: dependency: transitive description: @@ -105,6 +193,14 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" flutter: dependency: "direct main" description: flutter @@ -136,6 +232,14 @@ packages: description: flutter source: sdk version: "0.0.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.dev" + source: hosted + version: "2.0.2" http: dependency: "direct main" description: @@ -160,6 +264,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.2" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" + url: "https://pub.dev" + source: hosted + version: "1.0.4+1" jni_util: dependency: transitive description: @@ -200,6 +312,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" matcher: dependency: transitive description: @@ -240,6 +360,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e + url: "https://pub.dev" + source: hosted + version: "9.5.0" package_config: dependency: transitive description: @@ -256,6 +384,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" path_provider_linux: dependency: transitive description: @@ -304,6 +456,22 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.5+1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" shared_preferences: dependency: "direct main" description: @@ -397,6 +565,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: a77637ebe1460f3b48cac89a790d2eb634f0a8593cab0d3f340c6db174ba9b94 + url: "https://pub.dev" + source: hosted + version: "3.6.1+1" term_glyph: dependency: transitive description: @@ -421,6 +597,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" vector_math: dependency: transitive description: @@ -429,6 +613,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.4.0" + vibration: + dependency: "direct main" + description: + name: vibration + sha256: "3424f7856b971a2ce94d22be3a3abfb5b9b5984562fdedd621f4e67574be7254" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + vibration_platform_interface: + dependency: transitive + description: + name: vibration_platform_interface + sha256: "258c273268f8aa40c88d29741137c536874a738779b92ddb8aa32ed093721ec5" + url: "https://pub.dev" + source: hosted + version: "0.1.2" vm_service: dependency: transitive description: @@ -461,6 +661,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.3" + win32: + dependency: transitive + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.dev" + source: hosted + version: "6.4.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" + url: "https://pub.dev" + source: hosted + version: "3.0.3" xdg_directories: dependency: transitive description: @@ -469,6 +685,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" sdks: dart: ">=3.13.4 <4.0.0" flutter: ">=3.44.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 2a4d2ec..78a4808 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -40,6 +40,8 @@ dependencies: shared_preferences: ^2.5.6 flutter_bloc: ^9.1.1 equatable: ^3.0.0 + audioplayers: ^6.8.1 + vibration: ^3.2.1 dev_dependencies: flutter_test: @@ -63,6 +65,9 @@ flutter: # the material Icons class. uses-material-design: true + assets: + - assets/sounds/ + # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg diff --git a/app/test/scan_feedback_and_cooldown_test.dart b/app/test/scan_feedback_and_cooldown_test.dart new file mode 100644 index 0000000..b6b9c17 --- /dev/null +++ b/app/test/scan_feedback_and_cooldown_test.dart @@ -0,0 +1,222 @@ +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/domain/entities/discovered_server.dart'; +import 'package:barcode_reader_app/features/connection/domain/entities/server_connection_info.dart'; +import 'package:barcode_reader_app/features/connection/domain/repositories/connection_repository.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/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/widgets/scanner_overlay.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_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _SpyFeedbackService extends FeedbackService { + int successCalls = 0; + int errorCalls = 0; + bool? lastSound; + bool? lastVibrate; + + @override + Future triggerSentSuccess({ + required bool sound, + required bool vibrate, + }) async { + successCalls++; + lastSound = sound; + lastVibrate = vibrate; + } + + @override + Future triggerSentError({ + required bool sound, + required bool vibrate, + }) async { + errorCalls++; + lastSound = sound; + lastVibrate = vibrate; + } +} + +class _FakeConnectionRepository implements ConnectionRepository { + bool nextSendResult = true; + + @override + ConnectionStatus get currentStatus => ConnectionStatus.connected; + + @override + Stream get messageStream => const Stream.empty(); + + @override + Stream get statusStream => const Stream.empty(); + + @override + Future connect(ServerConnectionInfo info) async {} + + @override + Future disconnect() async {} + + @override + Future> discoverServers({ + Duration timeout = const Duration(seconds: 3), + }) async => + const []; + + @override + Future> loadFavoriteServers() async => const []; + + @override + Future loadSavedConnection() async => + const ServerConnectionInfo(); + + @override + Future removeFavoriteServer(String id) async {} + + @override + Future saveConnection(ServerConnectionInfo info) async {} + + @override + Future saveFavoriteServer(ServerConnectionInfo server) async {} + + @override + Future sendCode({ + required String code, + required String suffix, + required String pin, + String? ip, + int? port, + }) async => + nextSendResult; + + @override + void dispose() {} +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('Scan Feedback & Cooldown Pause', () { + late SharedPreferences prefs; + late SettingsRepositoryImpl settingsRepo; + late ScanRepositoryImpl scanRepo; + late _FakeConnectionRepository fakeConnectionRepo; + late ConnectionRepositoryImpl realConnectionRepo; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + prefs = await SharedPreferences.getInstance(); + settingsRepo = SettingsRepositoryImpl(SettingsLocalDataSource(prefs)); + scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs)); + fakeConnectionRepo = _FakeConnectionRepository(); + realConnectionRepo = ConnectionRepositoryImpl( + localDataSource: ConnectionLocalDataSource(prefs), + remoteDataSource: ConnectionRemoteDataSource(), + discoveryDataSource: const UdpDiscoveryDataSource(), + ); + }); + + tearDown(() { + realConnectionRepo.dispose(); + }); + + test('SettingsCubit defaults scanCooldownMs to 2500ms and persists updates', + () async { + final cubit = SettingsCubit(settingsRepo); + await cubit.loadSettings(); + + expect(cubit.state.settings.scanCooldownMs, 2500); + + await cubit.updateScanCooldownMs(3000); + expect(cubit.state.settings.scanCooldownMs, 3000); + + final reloaded = await settingsRepo.loadSettings(); + expect(reloaded.scanCooldownMs, 3000); + }); + + test( + 'ScannerCubit triggers success/error feedback on send and enforces post-scan cooldown', + () async { + final settingsCubit = SettingsCubit(settingsRepo); + await settingsCubit.loadSettings(); + await settingsCubit.updateScanCooldownMs(3000); + + final connectionCubit = ConnectionCubit(fakeConnectionRepo); + final historyCubit = HistoryCubit(scanRepo); + final spyFeedback = _SpyFeedbackService(); + + final scannerCubit = ScannerCubit( + connectionCubit: connectionCubit, + settingsCubit: settingsCubit, + historyCubit: historyCubit, + feedbackService: spyFeedback, + ); + + addTearDown(scannerCubit.close); + addTearDown(connectionCubit.close); + + // 1. Successful send triggers success sound & vibration and starts 3s cooldown + fakeConnectionRepo.nextSendResult = true; + await scannerCubit.processBarcode('8001234567890', format: 'ean13'); + + expect(spyFeedback.successCalls, 1); + expect(spyFeedback.errorCalls, 0); + expect(spyFeedback.lastSound, true); + expect(spyFeedback.lastVibrate, true); + expect(scannerCubit.state.isInCooldown, true); + expect(scannerCubit.state.cooldownTotalMs, 3000); + expect(historyCubit.state.history.length, 1); + + // 2. Immediate second barcode (even a DIFFERENT code) is blocked by 3s cooldown + await scannerCubit.processBarcode('9998887776665', format: 'code128'); + expect(historyCubit.state.history.length, 1); + expect(spyFeedback.successCalls, 1); + + // 3. After cooldown clears, next scan is accepted; if send fails, error feedback triggers + scannerCubit.clearCooldown(); + // Reset lastScannedTime by simulating elapsed time via resend/new scan check: + // Note: durationSinceLast still checks lastScannedTime when testing synchronously, + // so verify sendSelectedBarcode triggers error feedback when send fails. + fakeConnectionRepo.nextSendResult = false; + final sent = await scannerCubit.sendSelectedBarcode('FAIL-001'); + expect(sent, false); + expect(spyFeedback.errorCalls, 1); + expect(historyCubit.state.history.length, 2); + }); + + testWidgets('ScannerOverlay displays green confirmation and cooldown pill', + (tester) async { + final cooldownUntil = DateTime.now().add(const Duration(milliseconds: 2500)); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 400, + height: 800, + child: ScannerOverlay( + aimMode: ScanAimMode.standard, + cooldownUntil: cooldownUntil, + cooldownTotalMs: 2500, + lastScanSucceeded: true, + ), + ), + ), + ), + ); + + expect(find.byIcon(Icons.check_rounded), findsOneWidget); + expect(find.textContaining('Inviato • Pausa'), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + }); + }); +} + diff --git a/app/windows/flutter/generated_plugin_registrant.cc b/app/windows/flutter/generated_plugin_registrant.cc index 8b6d468..09e8e2c 100644 --- a/app/windows/flutter/generated_plugin_registrant.cc +++ b/app/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,9 @@ #include "generated_plugin_registrant.h" +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + AudioplayersWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); } diff --git a/app/windows/flutter/generated_plugins.cmake b/app/windows/flutter/generated_plugins.cmake index 3ad69c6..53f4ef8 100644 --- a/app/windows/flutter/generated_plugins.cmake +++ b/app/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST