15 Commits
Author SHA1 Message Date
brontomark 9e201bf12e prod 2026-11-22 16:08:17 +01:00
brontomark 5ae45d615e fix linux
Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Successful in 2m44s
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Successful in 1m8s
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Successful in 3m50s
2026-11-22 11:14:15 +01:00
brontomark 0fbcbe5146 v
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Successful in 1m8s
Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Failing after 1m41s
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Failing after 3s
2026-11-22 10:48:19 +01:00
brontomark 58b9a8543f ci 2026-11-22 10:47:38 +01:00
brontomark 08aeaa3f42 rc
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Canceled after 0s
Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Canceled after 0s
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Canceled after 22s
2026-11-21 08:18:01 +01:00
brontomark 57e75068ac v 2026-11-15 14:39:15 +01:00
brontomark 8bfe077108 test ads 2026-11-15 13:25:45 +01:00
brontomark 28009867d8 fix 2026-11-15 12:18:00 +01:00
brontomark 1f2fcb68ea fix 2026-11-15 12:02:40 +01:00
brontomark dfe5dd6eb7 admob e icone 2026-11-15 11:30:43 +01:00
brontomark 119cc4993a fix modalità normale e precisione 2026-11-15 10:04:39 +01:00
brontomark b0f19ec5c7 fix overlay multipli x stesso codice 2026-11-15 09:40:29 +01:00
brontomark 579ddadeff fix code detection 2026-11-15 09:27:26 +01:00
brontomark 466f2f759e v 2026-11-14 09:46:24 +01:00
brontomark bda61b07b8 fix server 2026-11-13 19:32:31 +01:00
61 changed files with 6346 additions and 408 deletions

No files matched your search

+104 -20
View File
@@ -69,14 +69,49 @@ jobs:
} }
} }
- name: Upload Windows Installer Asset - name: Upload Windows Installer Asset su Gitea Release
uses: https://gitea.com/actions/release-action@main uses: https://gitea.com/actions/release-action@main
with: with:
files: "server/dist/installer/BarcodeServerSetup.exe" files: "server/dist/installer/BarcodeServerSetup.exe"
api_key: ${{ secrets.MYRELEASE_TOKEN }} api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Pubblica Windows Installer su apps.catelli.it
env:
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_APPS_DOWNLOADS_DIR: ${{ secrets.VPS_APPS_DOWNLOADS_DIR }}
run: |
if ([string]::IsNullOrWhiteSpace($env:VPS_SSH_KEY)) {
Write-Host "[!] Secret VPS_SSH_KEY non configurato: salto deploy su apps.catelli.it."
exit 0
}
$VpsHost = if ([string]::IsNullOrWhiteSpace($env:VPS_HOST)) { "vps.catelli.it" } else { $env:VPS_HOST }
$VpsUser = if ([string]::IsNullOrWhiteSpace($env:VPS_USER)) { "mark" } else { $env:VPS_USER }
$Port = if ([string]::IsNullOrWhiteSpace($env:VPS_PORT)) { "22" } else { $env:VPS_PORT }
$DestDir = if ([string]::IsNullOrWhiteSpace($env:VPS_APPS_DOWNLOADS_DIR)) { "/home/mark/caddy-docker/apps.catelli.it/downloads" } else { $env:VPS_APPS_DOWNLOADS_DIR.TrimEnd('/') }
$KeyFile = Join-Path $env:TEMP ("vps_deploy_key_" + [guid]::NewGuid().ToString("N"))
try {
$NormalizedKey = $env:VPS_SSH_KEY.Replace("`r`n", "`n").TrimEnd() + "`n"
[System.IO.File]::WriteAllText($KeyFile, $NormalizedKey, (New-Object System.Text.UTF8Encoding($false)))
& icacls $KeyFile /inheritance:r /grant:r "$($env:USERNAME):(R)" | Out-Null
$SshOpts = @("-i", $KeyFile, "-o", "StrictHostKeyChecking=accept-new", "-o", "BatchMode=yes")
& ssh.exe @SshOpts -p $Port "$VpsUser@$VpsHost" "mkdir -p '$DestDir' && chmod 755 '$DestDir'"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& scp.exe @SshOpts -P $Port "server\dist\installer\BarcodeServerSetup.exe" "$VpsUser@$VpsHost`:$DestDir/BarcodeServerSetup.exe.tmp"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& ssh.exe @SshOpts -p $Port "$VpsUser@$VpsHost" "chmod 644 '$DestDir/BarcodeServerSetup.exe.tmp' && mv -f '$DestDir/BarcodeServerSetup.exe.tmp' '$DestDir/BarcodeServerSetup.exe'"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} finally {
if (Test-Path $KeyFile) { Remove-Item -Force $KeyFile }
}
# ----------------------------------------------------------------- # -----------------------------------------------------------------
# JOB 2: LINUX APPIMAGE (.AppImage) # JOB 2: LINUX APPIMAGE (.AppImage via Docker Ubuntu 22.04)
# ----------------------------------------------------------------- # -----------------------------------------------------------------
build-linux: build-linux:
runs-on: linux-runner runs-on: linux-runner
@@ -84,31 +119,53 @@ jobs:
- name: Checkout del codice - name: Checkout del codice
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Compila binario e AppDir PySide6 - name: Prepara immagine Docker (Ubuntu 22.04 / glibc compatibile)
run: |
docker build -t barcode-linux-builder -f docker/linux-appimage.Dockerfile .
- name: Build Server Linux e Genera AppImage nel container
run: | run: |
TagVersion="${GITHUB_REF_NAME#v}" TagVersion="${GITHUB_REF_NAME#v}"
python3 server/build_binary.py --onedir --windowed --appdir --version "$TagVersion" docker run --rm \
-e HOST_UID="$(id -u)" \
-e HOST_GID="$(id -g)" \
-e APP_VERSION="$TagVersion" \
-v "$PWD:/workspace" \
barcode-linux-builder
- name: Scarica appimagetool se non presente - name: Upload Linux AppImage Asset su Gitea Release
run: |
if [ ! -x /tmp/appimagetool-x86_64.AppImage ] || ! head -c 4 /tmp/appimagetool-x86_64.AppImage | grep -q "ELF"; then
rm -f /tmp/appimagetool-x86_64.AppImage
curl -fSL -o /tmp/appimagetool-x86_64.AppImage https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
chmod +x /tmp/appimagetool-x86_64.AppImage
fi
- name: Genera AppImage
run: |
ARCH=x86_64 APPIMAGE_EXTRACT_AND_RUN=1 /tmp/appimagetool-x86_64.AppImage server/dist/BarcodeServer.AppDir BarcodeServer-x86_64.AppImage
chmod +x BarcodeServer-x86_64.AppImage
APPIMAGE_EXTRACT_AND_RUN=1 ./BarcodeServer-x86_64.AppImage --version
- name: Upload Linux AppImage Asset
uses: https://gitea.com/actions/release-action@main uses: https://gitea.com/actions/release-action@main
with: with:
files: "BarcodeServer-x86_64.AppImage" files: "BarcodeServer-x86_64.AppImage"
api_key: ${{ secrets.MYRELEASE_TOKEN }} api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Pubblica Linux AppImage su apps.catelli.it
env:
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_APPS_DOWNLOADS_DIR: ${{ secrets.VPS_APPS_DOWNLOADS_DIR }}
run: |
if [ -z "${VPS_SSH_KEY:-}" ]; then
echo "[!] Secret VPS_SSH_KEY non configurato: salto deploy su apps.catelli.it."
exit 0
fi
HOST="${VPS_HOST:-vps.catelli.it}"
USER="${VPS_USER:-mark}"
PORT="${VPS_PORT:-22}"
DEST_DIR="${VPS_APPS_DOWNLOADS_DIR:-/home/mark/caddy-docker/apps.catelli.it/downloads}"
DEST_DIR="${DEST_DIR%/}"
KEY_FILE="$(mktemp)"
trap 'rm -f "$KEY_FILE"' EXIT
printf '%s\n' "$VPS_SSH_KEY" > "$KEY_FILE"
chmod 600 "$KEY_FILE"
SSH_OPTS=(-i "$KEY_FILE" -o StrictHostKeyChecking=accept-new -o BatchMode=yes)
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "mkdir -p '${DEST_DIR}' && chmod 755 '${DEST_DIR}'"
scp "${SSH_OPTS[@]}" -P "$PORT" "BarcodeServer-x86_64.AppImage" "${USER}@${HOST}:${DEST_DIR}/BarcodeServer-x86_64.AppImage.tmp"
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "chmod 644 '${DEST_DIR}/BarcodeServer-x86_64.AppImage.tmp' && mv -f '${DEST_DIR}/BarcodeServer-x86_64.AppImage.tmp' '${DEST_DIR}/BarcodeServer-x86_64.AppImage'"
# ----------------------------------------------------------------- # -----------------------------------------------------------------
# JOB 3: MACOS (.dmg e .zip per auto-update) # JOB 3: MACOS (.dmg e .zip per auto-update)
# ----------------------------------------------------------------- # -----------------------------------------------------------------
@@ -129,7 +186,7 @@ jobs:
hdiutil create -volname "Barcode Reader Server" -srcfolder "server/dist/BarcodeServer.app" -ov -format UDZO "BarcodeServer-macOS.dmg" hdiutil create -volname "Barcode Reader Server" -srcfolder "server/dist/BarcodeServer.app" -ov -format UDZO "BarcodeServer-macOS.dmg"
ditto -c -k --sequesterRsrc --keepParent "server/dist/BarcodeServer.app" "BarcodeServer-macOS.zip" ditto -c -k --sequesterRsrc --keepParent "server/dist/BarcodeServer.app" "BarcodeServer-macOS.zip"
- name: Upload macOS Assets - name: Upload macOS Assets su Gitea Release
uses: https://gitea.com/actions/release-action@main uses: https://gitea.com/actions/release-action@main
with: with:
files: | files: |
@@ -137,3 +194,30 @@ jobs:
BarcodeServer-macOS.zip BarcodeServer-macOS.zip
api_key: ${{ secrets.MYRELEASE_TOKEN }} api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Pubblica macOS DMG e ZIP su apps.catelli.it
env:
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_APPS_DOWNLOADS_DIR: ${{ secrets.VPS_APPS_DOWNLOADS_DIR }}
run: |
if [ -z "${VPS_SSH_KEY:-}" ]; then
echo "[!] Secret VPS_SSH_KEY non configurato: salto deploy su apps.catelli.it."
exit 0
fi
HOST="${VPS_HOST:-vps.catelli.it}"
USER="${VPS_USER:-mark}"
PORT="${VPS_PORT:-22}"
DEST_DIR="${VPS_APPS_DOWNLOADS_DIR:-/home/mark/caddy-docker/apps.catelli.it/downloads}"
DEST_DIR="${DEST_DIR%/}"
KEY_FILE="$(mktemp)"
trap 'rm -f "$KEY_FILE"' EXIT
printf '%s\n' "$VPS_SSH_KEY" > "$KEY_FILE"
chmod 600 "$KEY_FILE"
SSH_OPTS=(-i "$KEY_FILE" -o StrictHostKeyChecking=accept-new -o BatchMode=yes)
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "mkdir -p '${DEST_DIR}' && chmod 755 '${DEST_DIR}'"
scp "${SSH_OPTS[@]}" -P "$PORT" "BarcodeServer-macOS.dmg" "${USER}@${HOST}:${DEST_DIR}/BarcodeServer-macOS.dmg.tmp"
scp "${SSH_OPTS[@]}" -P "$PORT" "BarcodeServer-macOS.zip" "${USER}@${HOST}:${DEST_DIR}/BarcodeServer-macOS.zip.tmp"
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "chmod 644 '${DEST_DIR}/BarcodeServer-macOS.dmg.tmp' '${DEST_DIR}/BarcodeServer-macOS.zip.tmp' && mv -f '${DEST_DIR}/BarcodeServer-macOS.dmg.tmp' '${DEST_DIR}/BarcodeServer-macOS.dmg' && mv -f '${DEST_DIR}/BarcodeServer-macOS.zip.tmp' '${DEST_DIR}/BarcodeServer-macOS.zip'"
+3 -4
View File
@@ -30,6 +30,7 @@ android {
// For more information, see: https://flutter.dev/to/review-gradle-config. // For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion targetSdk = flutter.targetSdkVersion
multiDexEnabled = true
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
// is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
@@ -56,10 +57,8 @@ android {
} else { } else {
signingConfigs.getByName("debug") signingConfigs.getByName("debug")
} }
proguardFiles( isMinifyEnabled = false
getDefaultProguardFile("proguard-android-optimize.txt"), isShrinkResources = false
"proguard-rules.pro"
)
} }
} }
} }
+19
View File
@@ -17,3 +17,22 @@
-keep class android.net.** { *; } -keep class android.net.** { *; }
-keep class android.net.wifi.** { *; } -keep class android.net.wifi.** { *; }
# Google Mobile Ads (AdMob)
-keep public class com.google.android.gms.ads.** {
public *;
}
-keep public class com.google.ads.** {
public *;
}
-keep class com.google.android.gms.common.** { *; }
-keep class com.google.android.gms.internal.ads.** { *; }
-dontwarn com.google.android.gms.ads.**
-dontwarn com.google.android.gms.internal.ads.**
# WebView (required by AdMob / Google Mobile Ads)
-keepclassmembers class * extends android.webkit.WebView {
public *;
}
-keep class android.webkit.** { *; }
-dontwarn android.webkit.**
@@ -39,6 +39,11 @@
<meta-data <meta-data
android:name="flutterEmbedding" android:name="flutterEmbedding"
android:value="2" /> android:value="2" />
<!-- Google AdMob Application ID -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-8592989118033227~7564566063" />
</application> </application>
<!-- Required to query activities that can process text, see: <!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and https://developer.android.com/training/package-visibility and
Binary file not shown.

Before

Width:  |  Height:  |  Size: 544 B

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 442 B

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 721 B

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 898 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 595 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

+4
View File
@@ -0,0 +1,4 @@
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
output-dir: lib/l10n/generated
+2 -1
View File
@@ -2,7 +2,7 @@ class AppConstants {
AppConstants._(); AppConstants._();
static const String appName = 'Catelli Barcode Reader'; static const String appName = 'Catelli Barcode Reader';
static const String appVersion = '1.0.0'; static const String appVersion = '1.1.0';
static const String organization = 'Catelli Srl'; static const String organization = 'Catelli Srl';
// Network defaults // Network defaults
@@ -24,6 +24,7 @@ class AppConstants {
static const String keyVibrate = 'vibrate_enabled'; static const String keyVibrate = 'vibrate_enabled';
static const String keySound = 'sound_enabled'; static const String keySound = 'sound_enabled';
static const String keyAimMode = 'scan_aim_mode'; static const String keyAimMode = 'scan_aim_mode';
static const String keyLanguageCode = 'app_language_code';
static const String keyHistory = 'scan_history'; static const String keyHistory = 'scan_history';
// Suffix options // Suffix options
+26
View File
@@ -0,0 +1,26 @@
import 'package:flutter/widgets.dart';
import '../../features/scanner/domain/entities/scan_aim_mode.dart';
import '../../l10n/generated/app_localizations.dart';
export '../../l10n/generated/app_localizations.dart';
extension AppLocalizationsX on BuildContext {
/// Returns the active [AppLocalizations], falling back to Italian if a widget
/// is pumped in an isolated test harness without localization delegates.
AppLocalizations get l10n =>
AppLocalizations.of(this) ?? lookupAppLocalizations(const Locale('it'));
}
extension ScanAimModeL10n on ScanAimMode {
String localizedLabel(AppLocalizations l10n) {
switch (this) {
case ScanAimMode.standard:
return l10n.aimModeStandard;
case ScanAimMode.precision:
return l10n.aimModePrecision;
case ScanAimMode.arMulti:
return l10n.aimModeArMulti;
}
}
}
+165
View File
@@ -0,0 +1,165 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
/// Service managing Google AdMob SDK initialization and Rewarded Ads.
class AdService {
AdService();
static const String androidProductionRewardedAdUnitId =
'ca-app-pub-8592989118033227/7181422681';
// Official Google demo ad unit ID for testing rewarded video ads safely
static const String androidTestRewardedAdUnitId =
'ca-app-pub-3940256099942544/5224354917';
// Production Rewarded Ads enabled for release builds (debug builds still use test ads).
static const bool useProductionAds = true;
RewardedAd? _rewardedAd;
bool _isLoading = false;
bool _isInitialized = false;
Completer<RewardedAd?>? _loadCompleter;
static bool get _isFlutterTest =>
!kIsWeb && Platform.environment.containsKey('FLUTTER_TEST');
String get rewardedAdUnitId {
if (useProductionAds && kReleaseMode) {
return androidProductionRewardedAdUnitId;
}
return androidTestRewardedAdUnitId;
}
bool get isInitialized => _isInitialized;
bool get isAdReady => _rewardedAd != null;
bool get isLoading => _isLoading;
Future<void> initialize() async {
if (_isFlutterTest || kIsWeb) return;
try {
await MobileAds.instance.initialize();
_isInitialized = true;
// Preload after the first UI frames have settled
Future.delayed(const Duration(seconds: 1), () {
loadRewardedAd();
});
} catch (e) {
debugPrint('AdService initialize error: $e');
}
}
Future<RewardedAd?> _requestAd(String unitId) {
final completer = Completer<RewardedAd?>();
try {
RewardedAd.load(
adUnitId: unitId,
request: const AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (ad) {
debugPrint('RewardedAd loaded successfully with unit: $unitId');
completer.complete(ad);
},
onAdFailedToLoad: (error) {
debugPrint('RewardedAd failed for $unitId: ${error.message} (code: ${error.code})');
completer.complete(null);
},
),
);
} catch (e) {
debugPrint('RewardedAd request exception for $unitId: $e');
completer.complete(null);
}
return completer.future;
}
Future<bool> loadRewardedAd() async {
if (_isFlutterTest || kIsWeb) return true;
if (_rewardedAd != null) return true;
if (_loadCompleter != null) {
final ad = await _loadCompleter!.future;
return ad != null;
}
_loadCompleter = Completer<RewardedAd?>();
_isLoading = true;
try {
// Request preferred unit (production in release, official test unit in debug).
final ad = await _requestAd(rewardedAdUnitId);
_rewardedAd = ad;
_isLoading = false;
_loadCompleter?.complete(ad);
_loadCompleter = null;
return ad != null;
} catch (e) {
debugPrint('loadRewardedAd top-level error: $e');
_rewardedAd = null;
_isLoading = false;
_loadCompleter?.complete(null);
_loadCompleter = null;
return false;
}
}
Future<bool> showRewardedAd({required VoidCallback onUserEarnedReward}) async {
if (_isFlutterTest) {
onUserEarnedReward();
return true;
}
// If ad is not preloaded yet, wait up to 8s for it to load
if (_rewardedAd == null) {
debugPrint('Ad not preloaded yet, awaiting load on demand...');
final loaded = await loadRewardedAd().timeout(
const Duration(seconds: 8),
onTimeout: () => false,
);
if (!loaded || _rewardedAd == null) {
debugPrint('Ad load failed or timed out');
return false;
}
}
final completer = Completer<bool>();
final ad = _rewardedAd!;
_rewardedAd = null;
ad.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
ad.dispose();
loadRewardedAd();
if (!completer.isCompleted) completer.complete(true);
},
onAdFailedToShowFullScreenContent: (ad, error) {
debugPrint('Ad failed to show: ${error.message}');
ad.dispose();
loadRewardedAd();
if (!completer.isCompleted) completer.complete(false);
},
);
try {
await ad.show(
onUserEarnedReward: (_, reward) {
debugPrint('User earned reward: ${reward.amount} ${reward.type}');
onUserEarnedReward();
},
);
} catch (e) {
debugPrint('Exception showing ad: $e');
if (!completer.isCompleted) completer.complete(false);
}
return completer.future;
}
void dispose() {
_rewardedAd?.dispose();
_rewardedAd = null;
}
}
@@ -0,0 +1,158 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:purchases_flutter/purchases_flutter.dart';
enum PurchaseOutcome {
purchased,
cancelled,
error,
}
/// Service managing RevenueCat In-App Purchases and Subscriptions.
class SubscriptionService {
SubscriptionService();
// RevenueCat Google Play Production API Key
static const String apiKey = 'goog_DwjzlZrJpLkGrgGjZttqXUmPBdM';
// Entitlement ID granting unlimited scanning
static const String entitlementId = 'barcode_reader_pc_unlimited';
// Product / Package identifiers configured in RevenueCat
static const String productLifetime = 'lifetime';
static const String productYearly = 'yearly';
static const String productMonthly = 'monthly';
bool _isConfigured = false;
final _customerInfoController = StreamController<CustomerInfo>.broadcast();
Stream<CustomerInfo> get customerInfoStream => _customerInfoController.stream;
static bool get _isFlutterTest =>
!kIsWeb && Platform.environment.containsKey('FLUTTER_TEST');
bool get isConfigured => _isConfigured;
Future<void> initialize() async {
if (_isFlutterTest || kIsWeb) return;
try {
if (kDebugMode) {
await Purchases.setLogLevel(LogLevel.debug);
} else {
await Purchases.setLogLevel(LogLevel.info);
}
final configuration = PurchasesConfiguration(apiKey);
await Purchases.configure(configuration);
_isConfigured = true;
// Listen for real-time customer info changes (renewals, cancellations, purchases)
Purchases.addCustomerInfoUpdateListener((customerInfo) {
_customerInfoController.add(customerInfo);
});
} catch (e, stack) {
debugPrint('SubscriptionService initialize error: $e\n$stack');
}
}
/// Checks whether the user has the active premium entitlement.
Future<bool> isEntitled() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return false;
try {
final customerInfo = await Purchases.getCustomerInfo();
return isCustomerEntitled(customerInfo);
} catch (e) {
debugPrint('Error checking customer entitlement: $e');
return false;
}
}
/// Helper to verify entitlement from a [CustomerInfo] snapshot.
bool isCustomerEntitled(CustomerInfo? customerInfo) {
if (customerInfo == null) return false;
final entitlement = customerInfo.entitlements.all[entitlementId];
return entitlement != null && entitlement.isActive;
}
/// Fetches available offerings from RevenueCat.
Future<Offerings?> getOfferings() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return null;
try {
return await Purchases.getOfferings();
} catch (e) {
debugPrint('Error fetching offerings: $e');
return null;
}
}
/// Returns the current offering's available packages ordered as:
/// Yearly -> Lifetime -> Monthly -> any other package.
Future<List<Package>> getAvailablePackages() async {
final offerings = await getOfferings();
final packages = List<Package>.from(
offerings?.current?.availablePackages ?? const <Package>[],
);
int rank(Package pkg) {
final id = pkg.identifier.toLowerCase();
if (pkg.packageType == PackageType.annual || id.contains('year') || id.contains('annual')) {
return 0;
}
if (pkg.packageType == PackageType.lifetime || id.contains('life')) {
return 1;
}
if (pkg.packageType == PackageType.monthly || id.contains('month')) {
return 2;
}
return 3;
}
packages.sort((a, b) => rank(a).compareTo(rank(b)));
return packages;
}
/// Purchases a specific RevenueCat [Package].
Future<PurchaseOutcome> purchasePackage(Package package) async {
if (_isFlutterTest || kIsWeb || !_isConfigured) {
return PurchaseOutcome.error;
}
try {
final result = await Purchases.purchase(PurchaseParams.package(package));
_customerInfoController.add(result.customerInfo);
return isCustomerEntitled(result.customerInfo)
? PurchaseOutcome.purchased
: PurchaseOutcome.error;
} on PlatformException catch (e) {
final errorCode = PurchasesErrorHelper.getErrorCode(e);
if (errorCode == PurchasesErrorCode.purchaseCancelledError) {
return PurchaseOutcome.cancelled;
}
debugPrint('Purchase error ($errorCode): $e');
return PurchaseOutcome.error;
} catch (e) {
debugPrint('Unexpected purchase error: $e');
return PurchaseOutcome.error;
}
}
/// Restores existing purchases (e.g. after reinstalling the app or switching devices).
Future<CustomerInfo?> restorePurchases() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return null;
try {
final customerInfo = await Purchases.restorePurchases();
_customerInfoController.add(customerInfo);
return customerInfo;
} catch (e) {
debugPrint('Error restoring purchases: $e');
rethrow;
}
}
void dispose() {
_customerInfoController.close();
}
}
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/server_connection_info.dart'; import '../../domain/entities/server_connection_info.dart';
import '../../domain/repositories/connection_repository.dart'; import '../../domain/repositories/connection_repository.dart';
@@ -46,6 +47,7 @@ class _ConnectScreenState extends State<ConnectScreen> {
} }
void _onManualConnect() { void _onManualConnect() {
final l10n = context.l10n;
final name = _nameController.text.trim(); final name = _nameController.text.trim();
final ip = _ipController.text.trim(); final ip = _ipController.text.trim();
final port = int.tryParse(_portController.text.trim()) ?? 8765; final port = int.tryParse(_portController.text.trim()) ?? 8765;
@@ -53,8 +55,8 @@ class _ConnectScreenState extends State<ConnectScreen> {
if (ip.isEmpty) { if (ip.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( SnackBar(
content: Text('Inserisci un indirizzo IP valido del PC'), content: Text(l10n.enterValidIp),
backgroundColor: AppTheme.error, backgroundColor: AppTheme.error,
), ),
); );
@@ -65,7 +67,7 @@ class _ConnectScreenState extends State<ConnectScreen> {
ip: ip, ip: ip,
port: port, port: port,
pin: pin, pin: pin,
serverName: name.isNotEmpty ? name : 'PC Negozio', serverName: name.isNotEmpty ? name : l10n.defaultStorePcName,
); );
final timeout = context final timeout = context
@@ -80,7 +82,7 @@ class _ConnectScreenState extends State<ConnectScreen> {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Connessione a $ip:$port in corso...'), content: Text(l10n.connectingToHost(ip, port)),
backgroundColor: AppTheme.primary, backgroundColor: AppTheme.primary,
), ),
); );
@@ -89,12 +91,13 @@ class _ConnectScreenState extends State<ConnectScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
final timeout = final timeout =
context.watch<SettingsCubit>().state.settings.inactivityTimeoutMinutes; context.watch<SettingsCubit>().state.settings.inactivityTimeoutMinutes;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Connessione Postazioni PC'), title: Text(l10n.pcConnectionsTitle),
), ),
body: BlocConsumer<ConnectionCubit, ServerConnectionState>( body: BlocConsumer<ConnectionCubit, ServerConnectionState>(
listener: (context, state) { listener: (context, state) {
@@ -125,9 +128,10 @@ class _ConnectScreenState extends State<ConnectScreen> {
borderRadius: BorderRadius.circular(14)), borderRadius: BorderRadius.circular(14)),
), ),
icon: const Icon(Icons.qr_code_scanner_rounded, size: 22), icon: const Icon(Icons.qr_code_scanner_rounded, size: 22),
label: const Text( label: Text(
'Inquadra QR Code sul PC', l10n.scanPcQrCode,
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
), ),
onPressed: () { onPressed: () {
showModalBottomSheet( showModalBottomSheet(
@@ -144,16 +148,16 @@ class _ConnectScreenState extends State<ConnectScreen> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
const Text( Text(
'Postazioni Salvate nel Negozio', l10n.savedStoreWorkstations,
style: TextStyle( style: const TextStyle(
fontSize: 15, fontSize: 15,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary, color: AppTheme.darkTextPrimary,
), ),
), ),
Text( Text(
'${favorites.length} preferiti', l10n.favoritesCount(favorites.length),
style: const TextStyle( style: const TextStyle(
fontSize: 12, color: AppTheme.darkTextSecondary), fontSize: 12, color: AppTheme.darkTextSecondary),
), ),
@@ -217,7 +221,8 @@ class _ConnectScreenState extends State<ConnectScreen> {
timeoutMinutes: timeout); timeoutMinutes: timeout);
Navigator.pop(context); Navigator.pop(context);
}, },
child: Text(isCurrent ? 'Attivo' : 'Connetti'), child:
Text(isCurrent ? l10n.active : l10n.connect),
), ),
], ],
), ),
@@ -232,9 +237,9 @@ class _ConnectScreenState extends State<ConnectScreen> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
const Text( Text(
'PC Rilevati in Wi-Fi', l10n.detectedWifiPcs,
style: TextStyle( style: const TextStyle(
fontSize: 15, fontSize: 15,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary, color: AppTheme.darkTextPrimary,
@@ -251,7 +256,7 @@ class _ConnectScreenState extends State<ConnectScreen> {
strokeWidth: 2, color: AppTheme.primary), strokeWidth: 2, color: AppTheme.primary),
) )
: const Icon(Icons.refresh_rounded, size: 20), : const Icon(Icons.refresh_rounded, size: 20),
tooltip: 'Aggiorna ricerca', tooltip: l10n.refreshDiscoveryTooltip,
onPressed: discoveryState.isScanning onPressed: discoveryState.isScanning
? null ? null
: () => : () =>
@@ -274,18 +279,18 @@ class _ConnectScreenState extends State<ConnectScreen> {
borderRadius: BorderRadius.circular(14), borderRadius: BorderRadius.circular(14),
border: Border.all(color: AppTheme.darkBorder), border: Border.all(color: AppTheme.darkBorder),
), ),
child: const Row( child: Row(
children: [ children: [
SizedBox( const SizedBox(
width: 20, width: 20,
height: 20, height: 20,
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(strokeWidth: 2),
), ),
SizedBox(width: 16), const SizedBox(width: 16),
Expanded( Expanded(
child: Text( child: Text(
'Ricerca server PC in corso sulla rete...', l10n.searchingPcServers,
style: TextStyle( style: const TextStyle(
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
fontSize: 13), fontSize: 13),
), ),
@@ -303,9 +308,9 @@ class _ConnectScreenState extends State<ConnectScreen> {
borderRadius: BorderRadius.circular(14), borderRadius: BorderRadius.circular(14),
border: Border.all(color: AppTheme.darkBorder), border: Border.all(color: AppTheme.darkBorder),
), ),
child: const Text( child: Text(
'Nessun server PC rilevato automaticamente sulla rete.\nAssicurati che il programma sul PC sia avviato e connesso allo stesso Wi-Fi.', l10n.noPcServersFound,
style: TextStyle( style: const TextStyle(
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
fontSize: 13, fontSize: 13,
height: 1.4), height: 1.4),
@@ -340,18 +345,18 @@ class _ConnectScreenState extends State<ConnectScreen> {
fontWeight: FontWeight.bold, fontSize: 15), fontWeight: FontWeight.bold, fontSize: 15),
), ),
subtitle: Text( subtitle: Text(
'${srv.ip}:${srv.port} ${srv.pinRequired ? "• Richiede PIN" : ""}', '${srv.ip}:${srv.port} ${srv.pinRequired ? "• ${l10n.requiresPin}" : ""}',
style: const TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 12,
color: AppTheme.darkTextSecondary), color: AppTheme.darkTextSecondary),
), ),
trailing: isCurrent trailing: isCurrent
? const Chip( ? Chip(
label: Text('Connesso', label: Text(l10n.connected,
style: TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 12,
color: AppTheme.success)), color: AppTheme.success)),
backgroundColor: Color(0xFF064E3B), backgroundColor: const Color(0xFF064E3B),
side: BorderSide.none, side: BorderSide.none,
) )
: FilledButton( : FilledButton(
@@ -371,7 +376,7 @@ class _ConnectScreenState extends State<ConnectScreen> {
); );
Navigator.pop(context); Navigator.pop(context);
}, },
child: const Text('Connetti'), child: Text(l10n.connect),
), ),
), ),
); );
@@ -383,9 +388,9 @@ class _ConnectScreenState extends State<ConnectScreen> {
const SizedBox(height: 28), const SizedBox(height: 28),
// Method 3: Manual Setup // Method 3: Manual Setup
const Text( Text(
'Configurazione Manuale', l10n.manualSetup,
style: TextStyle( style: const TextStyle(
fontSize: 15, fontSize: 15,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary, color: AppTheme.darkTextPrimary,
@@ -395,20 +400,20 @@ class _ConnectScreenState extends State<ConnectScreen> {
TextField( TextField(
controller: _nameController, controller: _nameController,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'Nome Postazione / PC (opzionale)', labelText: l10n.workstationNameLabel,
hintText: 'Es. Cassa 1, Magazzino, Ufficio', hintText: l10n.workstationNameHint,
prefixIcon: Icon(Icons.badge_outlined, size: 20), prefixIcon: const Icon(Icons.badge_outlined, size: 20),
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
TextField( TextField(
controller: _ipController, controller: _ipController,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'Indirizzo IP del PC', labelText: l10n.pcIpLabel,
hintText: 'Es. 192.168.1.100', hintText: l10n.pcIpHint,
prefixIcon: Icon(Icons.lan_outlined, size: 20), prefixIcon: const Icon(Icons.lan_outlined, size: 20),
), ),
keyboardType: TextInputType.url, keyboardType: TextInputType.url,
), ),
@@ -420,10 +425,10 @@ class _ConnectScreenState extends State<ConnectScreen> {
flex: 2, flex: 2,
child: TextField( child: TextField(
controller: _portController, controller: _portController,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'Porta', labelText: l10n.portLabel,
hintText: '8765', hintText: '8765',
prefixIcon: Icon(Icons.tag_rounded, size: 20), prefixIcon: const Icon(Icons.tag_rounded, size: 20),
), ),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
), ),
@@ -433,10 +438,11 @@ class _ConnectScreenState extends State<ConnectScreen> {
flex: 3, flex: 3,
child: TextField( child: TextField(
controller: _pinController, controller: _pinController,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: 'PIN (se impostato)', labelText: l10n.pinOptionalLabel,
hintText: 'Codice PIN', hintText: l10n.pinHint,
prefixIcon: Icon(Icons.lock_outline_rounded, size: 20), prefixIcon:
const Icon(Icons.lock_outline_rounded, size: 20),
), ),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
obscureText: true, obscureText: true,
@@ -451,7 +457,7 @@ class _ConnectScreenState extends State<ConnectScreen> {
padding: const EdgeInsets.symmetric(vertical: 14), padding: const EdgeInsets.symmetric(vertical: 14),
), ),
icon: const Icon(Icons.save_rounded, size: 20), icon: const Icon(Icons.save_rounded, size: 20),
label: const Text('Salva e Connetti Manualmente'), label: Text(l10n.saveAndConnectManually),
onPressed: _onManualConnect, onPressed: _onManualConnect,
), ),
@@ -460,7 +466,7 @@ class _ConnectScreenState extends State<ConnectScreen> {
TextButton.icon( TextButton.icon(
style: TextButton.styleFrom(foregroundColor: AppTheme.error), style: TextButton.styleFrom(foregroundColor: AppTheme.error),
icon: const Icon(Icons.link_off_rounded, size: 20), icon: const Icon(Icons.link_off_rounded, size: 20),
label: const Text('Disconnetti dal PC'), label: Text(l10n.disconnectFromPc),
onPressed: () { onPressed: () {
context.read<ConnectionCubit>().disconnect(); context.read<ConnectionCubit>().disconnect();
}, },
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/repositories/connection_repository.dart'; import '../../domain/repositories/connection_repository.dart';
import '../cubit/connection_cubit.dart'; import '../cubit/connection_cubit.dart';
@@ -11,6 +12,7 @@ class ConnectionStatusChip extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
return BlocBuilder<ConnectionCubit, ServerConnectionState>( return BlocBuilder<ConnectionCubit, ServerConnectionState>(
builder: (context, state) { builder: (context, state) {
Color dotColor; Color dotColor;
@@ -23,15 +25,15 @@ class ConnectionStatusChip extends StatelessWidget {
break; break;
case ConnectionStatus.connecting: case ConnectionStatus.connecting:
dotColor = AppTheme.warning; dotColor = AppTheme.warning;
label = 'Connessione...'; label = l10n.connecting;
break; break;
case ConnectionStatus.error: case ConnectionStatus.error:
dotColor = AppTheme.error; dotColor = AppTheme.error;
label = 'Errore PIN/Rete'; label = l10n.pinOrNetworkError;
break; break;
case ConnectionStatus.disconnected: case ConnectionStatus.disconnected:
dotColor = AppTheme.darkTextSecondary; dotColor = AppTheme.darkTextSecondary;
label = 'Non connesso'; label = l10n.notConnected;
break; break;
} }
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mobile_scanner/mobile_scanner.dart'; import 'package:mobile_scanner/mobile_scanner.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/server_connection_info.dart'; import '../../domain/entities/server_connection_info.dart';
import '../../../settings/presentation/cubit/settings_cubit.dart'; import '../../../settings/presentation/cubit/settings_cubit.dart';
@@ -12,6 +13,7 @@ class QrPairingModal extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
return Container( return Container(
height: MediaQuery.of(context).size.height * 0.75, height: MediaQuery.of(context).size.height * 0.75,
decoration: const BoxDecoration( decoration: const BoxDecoration(
@@ -35,9 +37,9 @@ class QrPairingModal extends StatelessWidget {
children: [ children: [
const Icon(Icons.qr_code_scanner, color: AppTheme.primary), const Icon(Icons.qr_code_scanner, color: AppTheme.primary),
const SizedBox(width: 8), const SizedBox(width: 8),
const Text( Text(
'Inquadra QR Code del Server', l10n.qrModalTitle,
style: TextStyle( style: const TextStyle(
fontSize: 17, fontSize: 17,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary, color: AppTheme.darkTextPrimary,
@@ -51,11 +53,12 @@ class QrPairingModal extends StatelessWidget {
], ],
), ),
), ),
const Padding( Padding(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 4), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
child: Text( child: Text(
'Inquadra il codice QR mostrato nel terminale o nella dashboard web del PC.', l10n.qrModalSubtitle,
style: TextStyle(color: AppTheme.darkTextSecondary, fontSize: 13), style: const TextStyle(
color: AppTheme.darkTextSecondary, fontSize: 13),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
), ),
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/server_connection_info.dart'; import '../../domain/entities/server_connection_info.dart';
import '../../../settings/presentation/cubit/settings_cubit.dart'; import '../../../settings/presentation/cubit/settings_cubit.dart';
@@ -31,7 +32,7 @@ class ServerSelectionSheet extends StatelessWidget {
Navigator.of(context).pop(); Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Connessione a ${server.displayName}...'), content: Text(context.l10n.connectingToName(server.displayName)),
backgroundColor: AppTheme.primary, backgroundColor: AppTheme.primary,
duration: const Duration(seconds: 1), duration: const Duration(seconds: 1),
), ),
@@ -40,17 +41,18 @@ class ServerSelectionSheet extends StatelessWidget {
void _confirmDelete( void _confirmDelete(
BuildContext context, ServerConnectionInfo server) { BuildContext context, ServerConnectionInfo server) {
final l10n = context.l10n;
showDialog( showDialog(
context: context, context: context,
builder: (ctx) => AlertDialog( builder: (ctx) => AlertDialog(
title: const Text('Rimuovere postazione?'), title: Text(l10n.removeWorkstationTitle),
content: Text( content: Text(
'Vuoi eliminare "${server.displayName}" (${server.ip}) dai PC preferiti?', l10n.removeWorkstationMessage(server.displayName, server.ip),
), ),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(ctx), onPressed: () => Navigator.pop(ctx),
child: const Text('Annulla'), child: Text(l10n.cancel),
), ),
FilledButton( FilledButton(
style: FilledButton.styleFrom(backgroundColor: AppTheme.error), style: FilledButton.styleFrom(backgroundColor: AppTheme.error),
@@ -58,7 +60,7 @@ class ServerSelectionSheet extends StatelessWidget {
context.read<ConnectionCubit>().removeFavorite(server.effectiveId); context.read<ConnectionCubit>().removeFavorite(server.effectiveId);
Navigator.pop(ctx); Navigator.pop(ctx);
}, },
child: const Text('Rimuovi'), child: Text(l10n.remove),
), ),
], ],
), ),
@@ -67,6 +69,7 @@ class ServerSelectionSheet extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
return BlocBuilder<SettingsCubit, SettingsState>( return BlocBuilder<SettingsCubit, SettingsState>(
builder: (context, settingsState) { builder: (context, settingsState) {
final settings = settingsState.settings; final settings = settingsState.settings;
@@ -114,22 +117,22 @@ class ServerSelectionSheet extends StatelessWidget {
color: AppTheme.primary, size: 24), color: AppTheme.primary, size: 24),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
const Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Seleziona Postazione PC', l10n.selectPcWorkstation,
style: TextStyle( style: const TextStyle(
fontSize: 17, fontSize: 17,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary, color: AppTheme.darkTextPrimary,
), ),
), ),
SizedBox(height: 2), const SizedBox(height: 2),
Text( Text(
'Scegli il computer del negozio su cui scrivere', l10n.selectPcSubtitle,
style: TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 12,
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
), ),
@@ -159,15 +162,15 @@ class ServerSelectionSheet extends StatelessWidget {
border: Border.all( border: Border.all(
color: AppTheme.warning.withValues(alpha: 0.4)), color: AppTheme.warning.withValues(alpha: 0.4)),
), ),
child: const Row( child: Row(
children: [ children: [
Icon(Icons.timer_outlined, const Icon(Icons.timer_outlined,
color: AppTheme.warning, size: 18), color: AppTheme.warning, size: 18),
SizedBox(width: 10), const SizedBox(width: 10),
Expanded( Expanded(
child: Text( child: Text(
'Disconnesso per inattività. Seleziona la postazione prima di scansionare.', l10n.inactivityAlert,
style: TextStyle( style: const TextStyle(
fontSize: 12, color: AppTheme.warning), fontSize: 12, color: AppTheme.warning),
), ),
), ),
@@ -190,17 +193,17 @@ class ServerSelectionSheet extends StatelessWidget {
color: AppTheme.darkTextSecondary color: AppTheme.darkTextSecondary
.withValues(alpha: 0.4)), .withValues(alpha: 0.4)),
const SizedBox(height: 12), const SizedBox(height: 12),
const Text( Text(
'Nessun PC preferito salvato', l10n.noFavoritePcs,
style: TextStyle( style: const TextStyle(
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 15), fontSize: 15),
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
const Text( Text(
'Aggiungi i computer del negozio per collegarti con 1 tocco ed evitare errori tra colleghi.', l10n.noFavoritePcsHint,
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 12,
color: AppTheme.darkTextSecondary), color: AppTheme.darkTextSecondary),
), ),
@@ -298,9 +301,9 @@ class ServerSelectionSheet extends StatelessWidget {
BorderRadius BorderRadius
.circular(6), .circular(6),
), ),
child: const Text( child: Text(
'ATTIVO', l10n.activeUppercase,
style: TextStyle( style: const TextStyle(
color: color:
AppTheme.success, AppTheme.success,
fontSize: 10, fontSize: 10,
@@ -313,7 +316,7 @@ class ServerSelectionSheet extends StatelessWidget {
), ),
const SizedBox(height: 2), const SizedBox(height: 2),
Text( Text(
'${item.ip}:${item.port} ${item.pin.isNotEmpty ? "• Con PIN" : ""}', '${item.ip}:${item.port} ${item.pin.isNotEmpty ? "• ${l10n.withPin}" : ""}',
style: const TextStyle( style: const TextStyle(
fontFamily: 'monospace', fontFamily: 'monospace',
fontSize: 12, fontSize: 12,
@@ -332,7 +335,7 @@ class ServerSelectionSheet extends StatelessWidget {
Icons.delete_outline_rounded, Icons.delete_outline_rounded,
size: 20), size: 20),
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
tooltip: 'Rimuovi dai preferiti', tooltip: l10n.removeFavoriteTooltip,
onPressed: () => onPressed: () =>
_confirmDelete(context, item), _confirmDelete(context, item),
), ),
@@ -356,8 +359,8 @@ class ServerSelectionSheet extends StatelessWidget {
settings.inactivityTimeoutMinutes, settings.inactivityTimeoutMinutes,
), ),
child: Text(isCurrent child: Text(isCurrent
? 'Riconnetti' ? l10n.reconnect
: 'Connetti'), : l10n.connect),
), ),
], ],
), ),
@@ -381,9 +384,9 @@ class ServerSelectionSheet extends StatelessWidget {
borderRadius: BorderRadius.circular(12)), borderRadius: BorderRadius.circular(12)),
), ),
icon: const Icon(Icons.add_rounded, size: 20), icon: const Icon(Icons.add_rounded, size: 20),
label: const Text( label: Text(
'Aggiungi Nuovo PC (Wi-Fi o QR Code)', l10n.addNewPcButton,
style: TextStyle(fontWeight: FontWeight.bold), style: const TextStyle(fontWeight: FontWeight.bold),
), ),
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
@@ -406,20 +409,20 @@ class ServerSelectionSheet extends StatelessWidget {
const Icon(Icons.flash_auto_rounded, const Icon(Icons.flash_auto_rounded,
size: 20, color: AppTheme.secondary), size: 20, color: AppTheme.secondary),
const SizedBox(width: 10), const SizedBox(width: 10),
const Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Collega automaticamente all\'avvio', l10n.autoConnectOnStartup,
style: TextStyle( style: const TextStyle(
fontSize: 13, fontSize: 13,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
Text( Text(
'Disattivato: richiede la selezione del PC (consigliato in negozio)', l10n.autoConnectSubtitleShort,
style: TextStyle( style: const TextStyle(
fontSize: 11, fontSize: 11,
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
), ),
@@ -0,0 +1,193 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:purchases_flutter/purchases_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../core/services/ad_service.dart';
import '../../../../core/services/subscription_service.dart';
import 'monetization_state.dart';
class MonetizationCubit extends Cubit<MonetizationState> {
late final SharedPreferences _prefs;
late final AdService _adService;
late final SubscriptionService _subscriptionService;
Timer? _countdownTimer;
StreamSubscription? _customerInfoSub;
static const String _keyExpiresAt = 'monetization_unlimited_expires_at';
static const String _keyFreeScans = 'monetization_free_scans_remaining';
MonetizationCubit({
required SharedPreferences prefs,
required AdService adService,
required SubscriptionService subscriptionService,
}) : super(const MonetizationState()) {
_prefs = prefs;
_adService = adService;
_subscriptionService = subscriptionService;
_init();
}
void _init() {
_loadState();
_checkInitialEntitlement();
// Real-time listener for RevenueCat purchases, renewals, restorations
_customerInfoSub = _subscriptionService.customerInfoStream.listen((customerInfo) {
final isEntitled = _subscriptionService.isCustomerEntitled(customerInfo);
if (isEntitled != state.isPremium) {
emit(state.copyWith(isPremium: isEntitled));
}
});
}
Future<void> _checkInitialEntitlement() async {
final isEntitled = await _subscriptionService.isEntitled();
if (isEntitled && !isClosed) {
emit(state.copyWith(isPremium: true));
}
}
void _loadState() {
final rawExpires = _prefs.getInt(_keyExpiresAt);
final freeScans = _prefs.getInt(_keyFreeScans) ?? 15;
DateTime? expiresAt;
int seconds = 0;
if (rawExpires != null) {
final date = DateTime.fromMillisecondsSinceEpoch(rawExpires);
if (date.isAfter(DateTime.now())) {
expiresAt = date;
seconds = date.difference(DateTime.now()).inSeconds;
}
}
emit(MonetizationState(
unlimitedExpiresAt: expiresAt,
freeScansRemaining: freeScans,
remainingSeconds: seconds,
));
if (expiresAt != null && seconds > 0) {
_startCountdownTimer();
}
}
void _startCountdownTimer() {
_countdownTimer?.cancel();
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (isClosed) {
timer.cancel();
return;
}
final expires = state.unlimitedExpiresAt;
if (expires == null) {
timer.cancel();
emit(state.copyWith(clearUnlimited: true));
return;
}
final diffSeconds = expires.difference(DateTime.now()).inSeconds;
if (diffSeconds <= 0) {
timer.cancel();
emit(state.copyWith(clearUnlimited: true));
_prefs.remove(_keyExpiresAt);
} else {
emit(state.copyWith(remainingSeconds: diffSeconds));
}
});
}
/// Verifies if a scan can proceed.
/// If the user is Premium or in an active unlimited session, returns `true` immediately.
/// If using free scans, decrements count and returns `true`.
/// Returns `false` when all scans/sessions are expired.
bool tryConsumeScan() {
if (state.isPremium || state.isUnlimited) {
return true;
}
if (state.freeScansRemaining > 0) {
final nextCount = state.freeScansRemaining - 1;
emit(state.copyWith(freeScansRemaining: nextCount));
_prefs.setInt(_keyFreeScans, nextCount);
return true;
}
return false;
}
/// Grants a block of unlimited scanning (default 15 minutes) via Rewarded Ad.
Future<void> grantRewardedMinutes([int minutes = 15]) async {
final newExpires = DateTime.now().add(Duration(minutes: minutes));
await _prefs.setInt(_keyExpiresAt, newExpires.millisecondsSinceEpoch);
final seconds = newExpires.difference(DateTime.now()).inSeconds;
emit(state.copyWith(
unlimitedExpiresAt: newExpires,
remainingSeconds: seconds,
isAdLoading: false,
));
_startCountdownTimer();
}
/// Triggers the Rewarded Ad display and unlocks 15 minutes upon completion.
Future<bool> watchAdAndUnlock() async {
emit(state.copyWith(isAdLoading: true));
final success = await _adService.showRewardedAd(
onUserEarnedReward: () {
grantRewardedMinutes(15);
},
);
if (!success) {
emit(state.copyWith(isAdLoading: false));
}
return success;
}
/// Fetches available subscription / lifetime packages from RevenueCat.
Future<List<Package>> loadPackages() async {
return _subscriptionService.getAvailablePackages();
}
/// Purchases a selected package via RevenueCat and updates premium state.
Future<PurchaseOutcome> purchasePackage(Package package) async {
final outcome = await _subscriptionService.purchasePackage(package);
if (outcome == PurchaseOutcome.purchased && !isClosed) {
emit(state.copyWith(isPremium: true));
}
return outcome;
}
/// Refreshes the entitlement status from RevenueCat.
Future<void> refreshEntitlement() async {
final isEntitled = await _subscriptionService.isEntitled();
if (!isClosed) {
emit(state.copyWith(isPremium: isEntitled));
}
}
/// Restores previous purchases across device reinstalls.
Future<bool> restorePurchases() async {
try {
final info = await _subscriptionService.restorePurchases();
final isEntitled = _subscriptionService.isCustomerEntitled(info);
emit(state.copyWith(isPremium: isEntitled));
return isEntitled;
} catch (_) {
return false;
}
}
@override
Future<void> close() {
_countdownTimer?.cancel();
_customerInfoSub?.cancel();
return super.close();
}
}
@@ -0,0 +1,65 @@
import 'package:equatable/equatable.dart';
class MonetizationState extends Equatable {
final DateTime? unlimitedExpiresAt;
final int freeScansRemaining;
final bool isAdLoading;
final int remainingSeconds;
final bool isPremium;
const MonetizationState({
this.unlimitedExpiresAt,
this.freeScansRemaining = 15, // 15 initial free scans for new users to test immediately
this.isAdLoading = false,
this.remainingSeconds = 0,
this.isPremium = false,
});
bool get isUnlimited {
if (isPremium) return true;
final expires = unlimitedExpiresAt;
if (expires == null) return false;
return expires.isAfter(DateTime.now()) && remainingSeconds > 0;
}
bool get canScan => isPremium || isUnlimited || freeScansRemaining > 0;
Duration get remainingDuration => Duration(seconds: remainingSeconds);
String get formattedRemainingTime {
if (isPremium) return 'Premium';
final m = remainingSeconds ~/ 60;
final s = remainingSeconds % 60;
return '${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
}
MonetizationState copyWith({
DateTime? unlimitedExpiresAt,
bool clearUnlimited = false,
int? freeScansRemaining,
bool? isAdLoading,
int? remainingSeconds,
bool? isPremium,
}) {
return MonetizationState(
unlimitedExpiresAt: clearUnlimited
? null
: (unlimitedExpiresAt ?? this.unlimitedExpiresAt),
freeScansRemaining: freeScansRemaining ?? this.freeScansRemaining,
isAdLoading: isAdLoading ?? this.isAdLoading,
remainingSeconds: clearUnlimited
? 0
: (remainingSeconds ?? this.remainingSeconds),
isPremium: isPremium ?? this.isPremium,
);
}
@override
List<Object?> get props => [
unlimitedExpiresAt,
freeScansRemaining,
isAdLoading,
remainingSeconds,
isPremium,
];
}
@@ -0,0 +1,647 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:purchases_flutter/purchases_flutter.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/services/subscription_service.dart';
import '../../../../core/theme/app_theme.dart';
import '../cubit/monetization_cubit.dart';
/// Custom native Flutter Paywall powered by RevenueCat Offerings & Packages.
class PaywallSheet extends StatefulWidget {
const PaywallSheet({super.key});
/// Shows the custom paywall modal and returns `true` if Premium was unlocked.
static Future<bool> show(BuildContext context) async {
final result = await showModalBottomSheet<bool>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (_) => BlocProvider.value(
value: context.read<MonetizationCubit>(),
child: const PaywallSheet(),
),
);
return result == true;
}
/// Shows a clean dialog for users who already have an active Premium plan.
static Future<void> showPremiumManageDialog(BuildContext context) {
final l10n = context.l10n;
return showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: Row(
children: [
const Icon(
Icons.workspace_premium_rounded,
color: Color(0xFFFBBF24),
),
const SizedBox(width: 10),
Expanded(child: Text(l10n.premiumManageTitle)),
],
),
content: Text(
l10n.premiumManageBody,
style: const TextStyle(height: 1.45),
),
actions: [
FilledButton(
onPressed: () => Navigator.of(ctx).pop(),
child: Text(l10n.closeButton),
),
],
),
);
}
@override
State<PaywallSheet> createState() => _PaywallSheetState();
}
class _PaywallSheetState extends State<PaywallSheet> {
static const _gold = Color(0xFFFBBF24);
List<Package> _packages = const [];
Package? _selectedPackage;
bool _isLoading = true;
bool _isPurchasing = false;
bool _isRestoring = false;
@override
void initState() {
super.initState();
_loadOfferings();
}
Future<void> _loadOfferings() async {
setState(() => _isLoading = true);
final packages = await context.read<MonetizationCubit>().loadPackages();
if (!mounted) return;
setState(() {
_packages = packages;
_selectedPackage = packages.isNotEmpty ? packages.first : null;
_isLoading = false;
});
}
Future<void> _onPurchasePressed() async {
final pkg = _selectedPackage;
if (pkg == null || _isPurchasing || _isRestoring) return;
setState(() => _isPurchasing = true);
final outcome = await context.read<MonetizationCubit>().purchasePackage(pkg);
if (!mounted) return;
setState(() => _isPurchasing = false);
final l10n = context.l10n;
if (outcome == PurchaseOutcome.purchased) {
Navigator.of(context).pop(true);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('🎉 ${l10n.welcomePremiumSnackbar}'),
backgroundColor: AppTheme.success,
duration: const Duration(milliseconds: 2200),
),
);
} else if (outcome == PurchaseOutcome.error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.paywallPurchaseError),
backgroundColor: AppTheme.error,
),
);
}
}
Future<void> _onRestorePressed() async {
if (_isPurchasing || _isRestoring) return;
setState(() => _isRestoring = true);
final restored = await context.read<MonetizationCubit>().restorePurchases();
if (!mounted) return;
setState(() => _isRestoring = false);
final l10n = context.l10n;
if (restored) {
Navigator.of(context).pop(true);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.restorePurchasesSuccess),
backgroundColor: AppTheme.success,
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.restorePurchasesEmpty),
backgroundColor: AppTheme.darkCard,
),
);
}
}
int? _yearlySavingsPercent() {
Package? monthly;
Package? yearly;
for (final p in _packages) {
final id = p.identifier.toLowerCase();
if (p.packageType == PackageType.monthly || id.contains('month')) {
monthly = p;
} else if (p.packageType == PackageType.annual ||
id.contains('year') ||
id.contains('annual')) {
yearly = p;
}
}
if (monthly == null || yearly == null) return null;
final annualAtMonthlyRate = monthly.storeProduct.price * 12.0;
if (annualAtMonthlyRate <= 0 || yearly.storeProduct.price >= annualAtMonthlyRate) {
return null;
}
final pct = ((1.0 - (yearly.storeProduct.price / annualAtMonthlyRate)) * 100).round();
return pct >= 5 ? pct : null;
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final savingsPct = _yearlySavingsPercent();
return Container(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.90,
),
decoration: const BoxDecoration(
color: AppTheme.darkSurface,
borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
border: Border(
top: BorderSide(color: AppTheme.darkBorder, width: 1.5),
),
),
child: SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Drag handle + close button
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
child: Row(
children: [
const SizedBox(width: 40),
const Spacer(),
Container(
width: 42,
height: 4,
decoration: BoxDecoration(
color: AppTheme.darkTextSecondary.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(2),
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close_rounded),
color: AppTheme.darkTextSecondary,
onPressed: _isPurchasing
? null
: () => Navigator.of(context).pop(false),
),
],
),
),
Flexible(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(22, 4, 22, 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Crown icon
Center(
child: Container(
width: 68,
height: 68,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
_gold.withValues(alpha: 0.25),
AppTheme.primary.withValues(alpha: 0.20),
],
),
shape: BoxShape.circle,
border: Border.all(
color: _gold.withValues(alpha: 0.6),
width: 2,
),
),
child: const Icon(
Icons.workspace_premium_rounded,
color: _gold,
size: 36,
),
),
),
const SizedBox(height: 14),
Text(
l10n.paywallTitle,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w800,
color: Colors.white,
letterSpacing: -0.4,
),
),
const SizedBox(height: 6),
Text(
l10n.paywallSubtitle,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 13.5,
color: AppTheme.darkTextSecondary,
height: 1.35,
),
),
const SizedBox(height: 18),
// Benefits Card
Container(
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 14),
decoration: BoxDecoration(
color: AppTheme.darkCard,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppTheme.darkBorder),
),
child: Column(
children: [
_BenefitRow(
icon: Icons.all_inclusive_rounded,
text: l10n.paywallBenefitUnlimited,
),
const SizedBox(height: 10),
_BenefitRow(
icon: Icons.block_rounded,
text: l10n.paywallBenefitNoAds,
),
const SizedBox(height: 10),
_BenefitRow(
icon: Icons.view_in_ar_rounded,
text: l10n.paywallBenefitAllModes,
),
const SizedBox(height: 10),
_BenefitRow(
icon: Icons.computer_rounded,
text: l10n.paywallBenefitMultiPc,
),
],
),
),
const SizedBox(height: 18),
// Plans section
if (_isLoading)
Padding(
padding: const EdgeInsets.symmetric(vertical: 28),
child: Column(
children: [
const CircularProgressIndicator(color: _gold),
const SizedBox(height: 12),
Text(
l10n.paywallLoadingPlans,
style: const TextStyle(
color: AppTheme.darkTextSecondary,
fontSize: 13,
),
),
],
),
)
else if (_packages.isEmpty)
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: AppTheme.darkCard,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppTheme.darkBorder),
),
child: Column(
children: [
const Icon(
Icons.cloud_off_rounded,
color: AppTheme.darkTextSecondary,
size: 32,
),
const SizedBox(height: 10),
Text(
l10n.paywallUnavailableTitle,
textAlign: TextAlign.center,
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 15,
),
),
const SizedBox(height: 6),
Text(
l10n.paywallUnavailableSubtitle,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 12.5,
color: AppTheme.darkTextSecondary,
),
),
const SizedBox(height: 14),
OutlinedButton.icon(
onPressed: _loadOfferings,
icon: const Icon(Icons.refresh_rounded, size: 18),
label: Text(l10n.paywallRetryButton),
),
],
),
)
else ...[
for (final pkg in _packages) ...[
_PlanCard(
package: pkg,
isSelected: _selectedPackage?.identifier == pkg.identifier,
savingsPercent: savingsPct,
onTap: () => setState(() => _selectedPackage = pkg),
),
const SizedBox(height: 10),
],
const SizedBox(height: 8),
// Primary Purchase CTA
SizedBox(
height: 54,
child: FilledButton(
onPressed: (_selectedPackage == null || _isPurchasing)
? null
: _onPurchasePressed,
style: FilledButton.styleFrom(
backgroundColor: _gold,
foregroundColor: Colors.black87,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
child: _isPurchasing
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: Colors.black87,
),
)
: Text(
_selectedPackage != null
? l10n.paywallContinueWithPrice(
_selectedPackage!.storeProduct.priceString,
)
: l10n.paywallContinueButton,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
),
),
),
),
],
const SizedBox(height: 12),
// Restore Purchases
Center(
child: TextButton(
onPressed:
(_isPurchasing || _isRestoring) ? null : _onRestorePressed,
child: _isRestoring
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(
l10n.restorePurchasesTitle,
style: const TextStyle(
color: AppTheme.secondary,
fontWeight: FontWeight.w600,
),
),
),
),
const SizedBox(height: 4),
Text(
l10n.paywallLegalNote,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 11,
color: AppTheme.darkTextSecondary.withValues(alpha: 0.75),
height: 1.35,
),
),
],
),
),
),
],
),
),
);
}
}
class _BenefitRow extends StatelessWidget {
final IconData icon;
final String text;
const _BenefitRow({required this.icon, required this.text});
@override
Widget build(BuildContext context) {
return Row(
children: [
Icon(icon, color: const Color(0xFFFBBF24), size: 20),
const SizedBox(width: 12),
Expanded(
child: Text(
text,
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w500,
color: AppTheme.darkTextPrimary,
),
),
),
],
);
}
}
class _PlanCard extends StatelessWidget {
final Package package;
final bool isSelected;
final int? savingsPercent;
final VoidCallback onTap;
const _PlanCard({
required this.package,
required this.isSelected,
required this.savingsPercent,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
const gold = Color(0xFFFBBF24);
final id = package.identifier.toLowerCase();
final isYearly = package.packageType == PackageType.annual ||
id.contains('year') ||
id.contains('annual');
final isLifetime =
package.packageType == PackageType.lifetime || id.contains('life');
final isMonthly =
package.packageType == PackageType.monthly || id.contains('month');
final title = isYearly
? l10n.paywallPlanYearly
: isLifetime
? l10n.paywallPlanLifetime
: isMonthly
? l10n.paywallPlanMonthly
: package.storeProduct.title;
final periodLabel = isYearly
? l10n.paywallPerYear
: isLifetime
? l10n.paywallOneTime
: isMonthly
? l10n.paywallPerMonth
: '';
String? badge;
if (isYearly) {
badge = savingsPercent != null
? l10n.paywallSavePercent(savingsPercent!)
: l10n.paywallBestValue;
} else if (isLifetime) {
badge = l10n.paywallOneTimeBadge;
}
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(16),
child: AnimatedContainer(
duration: const Duration(milliseconds: 160),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
decoration: BoxDecoration(
color: isSelected
? gold.withValues(alpha: 0.12)
: AppTheme.darkCard,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: isSelected ? gold : AppTheme.darkBorder,
width: isSelected ? 2 : 1,
),
),
child: Row(
children: [
Container(
width: 22,
height: 22,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: isSelected ? gold : AppTheme.darkTextSecondary,
width: 2,
),
),
child: isSelected
? Center(
child: Container(
width: 11,
height: 11,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: gold,
),
),
)
: null,
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(
title,
style: const TextStyle(
fontSize: 15.5,
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
),
if (badge != null) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7, vertical: 2),
decoration: BoxDecoration(
color: isYearly
? gold
: AppTheme.primary.withValues(alpha: 0.25),
borderRadius: BorderRadius.circular(6),
),
child: Text(
badge,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w800,
color: isYearly ? Colors.black87 : AppTheme.secondary,
letterSpacing: 0.3,
),
),
),
],
],
),
if (periodLabel.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
periodLabel,
style: const TextStyle(
fontSize: 12,
color: AppTheme.darkTextSecondary,
),
),
],
],
),
),
const SizedBox(width: 10),
Text(
package.storeProduct.priceString,
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w800,
color: isSelected ? gold : Colors.white,
),
),
],
),
),
);
}
}
@@ -0,0 +1,209 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart';
import '../cubit/monetization_cubit.dart';
import '../cubit/monetization_state.dart';
import 'paywall_sheet.dart';
/// Bottom sheet dialog prompting user to watch a rewarded video for 15 min unlimited scanning.
class RewardSessionDialog extends StatelessWidget {
const RewardSessionDialog({super.key});
static Future<bool?> show(BuildContext context) {
return showModalBottomSheet<bool>(
context: context,
backgroundColor: Colors.transparent,
isScrollControlled: true,
builder: (_) => BlocProvider.value(
value: context.read<MonetizationCubit>(),
child: const RewardSessionDialog(),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Container(
padding: EdgeInsets.fromLTRB(
24,
20,
24,
MediaQuery.paddingOf(context).bottom + 24,
),
decoration: const BoxDecoration(
color: AppTheme.darkCard,
borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
border: Border(
top: BorderSide(color: AppTheme.darkBorder, width: 1.5),
),
),
child: BlocBuilder<MonetizationCubit, MonetizationState>(
builder: (context, state) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
// Drag handle
Container(
width: 40,
height: 4,
margin: const EdgeInsets.only(bottom: 20),
decoration: BoxDecoration(
color: AppTheme.darkTextSecondary.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(2),
),
),
// Icon badge
Container(
width: 64,
height: 64,
decoration: BoxDecoration(
color: AppTheme.primary.withValues(alpha: 0.15),
shape: BoxShape.circle,
border: Border.all(
color: AppTheme.primary.withValues(alpha: 0.4),
width: 2,
),
),
child: const Icon(
Icons.play_circle_fill_rounded,
color: AppTheme.primary,
size: 34,
),
),
const SizedBox(height: 16),
Text(
l10n.unlimitedScansTitle,
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
letterSpacing: -0.4,
),
),
const SizedBox(height: 8),
Text(
l10n.unlimitedScansDescription,
textAlign: TextAlign.center,
style: TextStyle(
color: AppTheme.darkTextSecondary,
fontSize: 14,
height: 1.4,
),
),
const SizedBox(height: 24),
// Watch video CTA button
SizedBox(
width: double.infinity,
height: 52,
child: FilledButton.icon(
onPressed: state.isAdLoading
? null
: () async {
final cubit = context.read<MonetizationCubit>();
final success = await cubit.watchAdAndUnlock();
if (context.mounted) {
if (success) {
Navigator.of(context).pop(true);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.unlocked15MinSnackbar),
duration: const Duration(milliseconds: 1600),
backgroundColor: AppTheme.success,
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.loadingVideoRetrySnackbar),
duration: const Duration(milliseconds: 1800),
backgroundColor: AppTheme.darkCard,
),
);
}
}
},
style: FilledButton.styleFrom(
backgroundColor: AppTheme.primary,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
icon: state.isAdLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: const Icon(Icons.ondemand_video_rounded, size: 22),
label: Text(
state.isAdLoading
? l10n.loadingVideoButton
: l10n.watchVideoButton,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
),
const SizedBox(height: 12),
// Upgrade to Premium button (Custom Paywall)
SizedBox(
width: double.infinity,
height: 50,
child: OutlinedButton.icon(
onPressed: () async {
final unlocked = await PaywallSheet.show(context);
if (context.mounted && unlocked) {
Navigator.of(context).pop(true);
}
},
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFFFBBF24),
side: const BorderSide(color: Color(0xFFFBBF24), width: 1.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
icon: const Icon(Icons.workspace_premium_rounded, size: 22),
label: Text(
l10n.upgradeToPremiumButton,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
),
const SizedBox(height: 12),
// Cancel button
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text(
l10n.laterButton,
style: const TextStyle(
color: AppTheme.darkTextSecondary,
fontSize: 14,
),
),
),
],
);
},
),
);
}
}
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/scan_record.dart'; import '../../domain/entities/scan_record.dart';
import '../cubit/history_cubit.dart'; import '../cubit/history_cubit.dart';
@@ -24,17 +25,16 @@ class _HistoryScreenState extends State<HistoryScreen> {
} }
void _confirmClear() { void _confirmClear() {
final l10n = context.l10n;
showDialog( showDialog(
context: context, context: context,
builder: (ctx) => AlertDialog( builder: (ctx) => AlertDialog(
title: const Text('Cancellare Cronologia?'), title: Text(l10n.clearHistoryTitle),
content: const Text( content: Text(l10n.clearHistoryMessage),
'Tutti i codici salvati nella cronologia su questo dispositivo verranno rimossi.',
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(ctx), onPressed: () => Navigator.pop(ctx),
child: const Text('Annulla'), child: Text(l10n.cancel),
), ),
FilledButton( FilledButton(
style: FilledButton.styleFrom(backgroundColor: AppTheme.error), style: FilledButton.styleFrom(backgroundColor: AppTheme.error),
@@ -42,7 +42,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
context.read<HistoryCubit>().clearHistory(); context.read<HistoryCubit>().clearHistory();
Navigator.pop(ctx); Navigator.pop(ctx);
}, },
child: const Text('Cancella Tutto'), child: Text(l10n.clearAllButton),
), ),
], ],
), ),
@@ -51,16 +51,17 @@ class _HistoryScreenState extends State<HistoryScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Cronologia Scansioni'), title: Text(l10n.scanHistoryTitle),
actions: [ actions: [
BlocBuilder<HistoryCubit, HistoryState>( BlocBuilder<HistoryCubit, HistoryState>(
builder: (context, state) { builder: (context, state) {
if (state.history.isEmpty) return const SizedBox.shrink(); if (state.history.isEmpty) return const SizedBox.shrink();
return IconButton( return IconButton(
icon: const Icon(Icons.delete_sweep_rounded), icon: const Icon(Icons.delete_sweep_rounded),
tooltip: 'Cancella cronologia', tooltip: l10n.clearHistoryTooltip,
onPressed: _confirmClear, onPressed: _confirmClear,
); );
}, },
@@ -79,7 +80,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
child: TextField( child: TextField(
controller: _searchController, controller: _searchController,
decoration: InputDecoration( decoration: InputDecoration(
hintText: 'Cerca tra i codici...', hintText: l10n.searchCodesHint,
prefixIcon: const Icon(Icons.search_rounded, size: 20), prefixIcon: const Icon(Icons.search_rounded, size: 20),
suffixIcon: state.searchQuery.isNotEmpty suffixIcon: state.searchQuery.isNotEmpty
? IconButton( ? IconButton(
@@ -112,8 +113,8 @@ class _HistoryScreenState extends State<HistoryScreen> {
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
state.searchQuery.isEmpty state.searchQuery.isEmpty
? 'Nessuna scansione in memoria' ? l10n.noScansInHistory
: 'Nessun risultato per "${state.searchQuery}"', : l10n.noResultsForQuery(state.searchQuery),
style: const TextStyle( style: const TextStyle(
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
fontSize: 15, fontSize: 15,
@@ -197,26 +198,26 @@ class _HistoryTile extends StatelessWidget {
children: [ children: [
IconButton( IconButton(
icon: const Icon(Icons.copy_rounded, size: 20), icon: const Icon(Icons.copy_rounded, size: 20),
tooltip: 'Copia codice', tooltip: context.l10n.copyCodeTooltip,
onPressed: () { onPressed: () {
Clipboard.setData(ClipboardData(text: item.code)); Clipboard.setData(ClipboardData(text: item.code));
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( SnackBar(
content: Text('Copiato negli appunti'), content: Text(context.l10n.copiedToClipboardSnackbar),
duration: Duration(seconds: 1), duration: const Duration(seconds: 1),
), ),
); );
}, },
), ),
IconButton( IconButton(
icon: const Icon(Icons.send_rounded, size: 20), icon: const Icon(Icons.send_rounded, size: 20),
tooltip: 'Invia di nuovo al PC', tooltip: context.l10n.resendToPcTooltip,
color: AppTheme.primary, color: AppTheme.primary,
onPressed: () { onPressed: () {
context.read<ScannerCubit>().resendScan(item); context.read<ScannerCubit>().resendScan(item);
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Inviato "${item.code}" al PC'), content: Text(context.l10n.resentCodeSnackbar(item.code)),
duration: const Duration(seconds: 1), duration: const Duration(seconds: 1),
), ),
); );
@@ -4,11 +4,16 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mobile_scanner/mobile_scanner.dart'; import 'package:mobile_scanner/mobile_scanner.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/services/feedback_service.dart'; import '../../../../core/services/feedback_service.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../../connection/presentation/cubit/connection_cubit.dart'; import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/widgets/connection_status_chip.dart'; import '../../../connection/presentation/widgets/connection_status_chip.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart'; import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../monetization/presentation/cubit/monetization_cubit.dart';
import '../../../monetization/presentation/cubit/monetization_state.dart';
import '../../../monetization/presentation/widgets/paywall_sheet.dart';
import '../../../monetization/presentation/widgets/reward_session_dialog.dart';
import '../../../settings/presentation/cubit/settings_cubit.dart'; import '../../../settings/presentation/cubit/settings_cubit.dart';
import '../../../settings/presentation/cubit/settings_state.dart'; import '../../../settings/presentation/cubit/settings_state.dart';
import '../../../settings/presentation/screens/settings_screen.dart'; import '../../../settings/presentation/screens/settings_screen.dart';
@@ -27,6 +32,16 @@ import '../widgets/scanner_controls_bar.dart';
import '../widgets/scanner_overlay.dart'; import '../widgets/scanner_overlay.dart';
import 'history_screen.dart'; import 'history_screen.dart';
class _TrackedBarcodeEntry {
DetectedBarcodeItem item;
DateTime lastSeen;
_TrackedBarcodeEntry({
required this.item,
required this.lastSeen,
});
}
class ScannerScreen extends StatefulWidget { class ScannerScreen extends StatefulWidget {
const ScannerScreen({super.key}); const ScannerScreen({super.key});
@@ -45,6 +60,9 @@ class _ScannerScreenState extends State<ScannerScreen>
bool _autoZoomedForPrecision = false; bool _autoZoomedForPrecision = false;
// Live AR & Precision targeting state // Live AR & Precision targeting state
final Map<String, _TrackedBarcodeEntry> _trackedArItems = {};
final Set<String> _sentLiveKeys = <String>{};
Timer? _arPruneTimer;
List<DetectedBarcodeItem> _liveArItems = const []; List<DetectedBarcodeItem> _liveArItems = const [];
int? _precisionTargetIndex; int? _precisionTargetIndex;
Timer? _arDecayTimer; Timer? _arDecayTimer;
@@ -66,14 +84,16 @@ class _ScannerScreenState extends State<ScannerScreen>
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
_scannerController = MobileScannerController( _scannerController = MobileScannerController(
detectionSpeed: DetectionSpeed.normal, detectionSpeed: DetectionSpeed.unrestricted,
detectionTimeoutMs: 180,
cameraResolution: const Size(1920, 1080),
facing: CameraFacing.back, facing: CameraFacing.back,
torchEnabled: false, torchEnabled: false,
returnImage: true, returnImage: true,
); );
_arPruneTimer = Timer.periodic(const Duration(milliseconds: 200), (_) {
_pruneExpiredArItems();
});
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
_checkStartupConnection(); _checkStartupConnection();
_applyInitialModeZoom(); _applyInitialModeZoom();
@@ -117,6 +137,7 @@ class _ScannerScreenState extends State<ScannerScreen>
void dispose() { void dispose() {
WidgetsBinding.instance.removeObserver(this); WidgetsBinding.instance.removeObserver(this);
_arDecayTimer?.cancel(); _arDecayTimer?.cancel();
_arPruneTimer?.cancel();
_focusRingTimer?.cancel(); _focusRingTimer?.cancel();
_scannerController.dispose(); _scannerController.dispose();
super.dispose(); super.dispose();
@@ -192,6 +213,8 @@ class _ScannerScreenState extends State<ScannerScreen>
if (!mounted) return; if (!mounted) return;
_arDecayTimer?.cancel(); _arDecayTimer?.cancel();
_trackedArItems.clear();
_sentLiveKeys.clear();
setState(() { setState(() {
_liveArItems = const []; _liveArItems = const [];
_precisionTargetIndex = null; _precisionTargetIndex = null;
@@ -227,13 +250,47 @@ class _ScannerScreenState extends State<ScannerScreen>
_precisionTargetIndex = null; _precisionTargetIndex = null;
}); });
} }
final barcodes = capture.barcodes;
if (barcodes.isEmpty) return; final standardReticle = ScannerReticleGeometry.scanRect(
final first = barcodes.first; _viewportSize,
final rawValue = first.rawValue ?? first.displayValue; ScanAimMode.standard,
if (rawValue == null || rawValue.trim().isEmpty) return; );
final formatName = first.format.name.replaceAll('BarcodeFormat.', '');
context.read<ScannerCubit>().processBarcode(rawValue, format: formatName); final items = BarcodeGeometry.mapCaptureToItems(
capture: capture,
widgetSize: _viewportSize,
deviceOrientation: deviceOrientation,
);
if (items.isNotEmpty && standardReticle != null) {
// Check barcodes whose center or bounding box falls inside the reticle
final inside = items.where((item) =>
standardReticle.contains(item.center) ||
standardReticle.overlaps(item.boundingRect)).toList();
if (inside.isEmpty) return;
// Pick the barcode closest to the reticle center
inside.sort((a, b) =>
(a.center - standardReticle.center).distanceSquared.compareTo(
(b.center - standardReticle.center).distanceSquared));
final best = inside.first;
if (!_ensureCanScan()) return;
context.read<ScannerCubit>().processBarcode(
best.code,
format: best.format,
);
} else {
// Fallback if geometric mapping is unavailable
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.', '');
if (!_ensureCanScan()) return;
context.read<ScannerCubit>().processBarcode(rawValue, format: formatName);
}
case ScanAimMode.precision: case ScanAimMode.precision:
final items = BarcodeGeometry.mapCaptureToItems( final items = BarcodeGeometry.mapCaptureToItems(
@@ -248,12 +305,13 @@ class _ScannerScreenState extends State<ScannerScreen>
final target = BarcodeGeometry.selectPrecisionTarget( final target = BarcodeGeometry.selectPrecisionTarget(
items: items, items: items,
crosshairCenter: crosshairCenter, crosshairCenter: crosshairCenter,
hitRadius: 16.0, hitRadius: 24.0,
); );
_updateLiveArItems(items, precisionTargetIndex: target?.index); _updateLiveArItems(items, precisionTargetIndex: target?.index);
if (target != null) { if (target != null) {
if (!_ensureCanScan()) return;
context.read<ScannerCubit>().processBarcode( context.read<ScannerCubit>().processBarcode(
target.code, target.code,
format: target.format, format: target.format,
@@ -266,9 +324,45 @@ class _ScannerScreenState extends State<ScannerScreen>
widgetSize: _viewportSize, widgetSize: _viewportSize,
deviceOrientation: deviceOrientation, deviceOrientation: deviceOrientation,
); );
if (items.isEmpty) return;
_updateLiveArItems(items); final now = DateTime.now();
// 1. Update/Add detected items into sticky cache - key is unique code to prevent duplicate badges
for (final item in items) {
final code = item.code;
if (_trackedArItems.containsKey(code)) {
final entry = _trackedArItems[code]!;
entry.item = item; // Update coordinates for smooth live tracking
entry.lastSeen = now;
} else {
_trackedArItems[code] = _TrackedBarcodeEntry(
item: item,
lastSeen: now,
);
}
}
// 2. Prune items that haven't been seen for > 2200ms
_trackedArItems.removeWhere((key, entry) =>
now.difference(entry.lastSeen) > const Duration(milliseconds: 2200));
final activeItems = _trackedArItems.values.map((e) => e.item).toList();
// Sort predictably and assign 1-based indices
final reindexed = <DetectedBarcodeItem>[];
for (var i = 0; i < activeItems.length; i++) {
final it = activeItems[i];
reindexed.add(it.copyWith(
index: i + 1,
color: kArBarcodePalette[i % kArBarcodePalette.length],
));
}
if (mounted && _frozenSnapshot == null) {
setState(() {
_liveArItems = reindexed;
});
}
final imageBytes = capture.image; final imageBytes = capture.image;
if (imageBytes != null && imageBytes.isNotEmpty) { if (imageBytes != null && imageBytes.isNotEmpty) {
@@ -277,12 +371,12 @@ class _ScannerScreenState extends State<ScannerScreen>
imageSize: capture.size, imageSize: capture.size,
viewportSize: _viewportSize, viewportSize: _viewportSize,
deviceOrientation: deviceOrientation, deviceOrientation: deviceOrientation,
items: items, items: reindexed.isNotEmpty ? reindexed : items,
timestamp: DateTime.now(), timestamp: now,
); );
_latestArSnapshot = snapshot; _latestArSnapshot = snapshot;
if (_pendingFreeze) { if (_pendingFreeze && reindexed.isNotEmpty) {
_pendingFreeze = false; _pendingFreeze = false;
_freezeWithSnapshot(snapshot); _freezeWithSnapshot(snapshot);
} }
@@ -290,6 +384,33 @@ class _ScannerScreenState extends State<ScannerScreen>
} }
} }
void _pruneExpiredArItems() {
if (!mounted || _frozenSnapshot != null) return;
final aimMode = context.read<SettingsCubit>().state.settings.aimMode;
if (aimMode != ScanAimMode.arMulti) return;
if (_trackedArItems.isEmpty && _liveArItems.isEmpty) return;
final now = DateTime.now();
final beforeCount = _trackedArItems.length;
_trackedArItems.removeWhere((key, entry) =>
now.difference(entry.lastSeen) > const Duration(milliseconds: 2200));
if (_trackedArItems.length != beforeCount) {
final activeItems = _trackedArItems.values.map((e) => e.item).toList();
final reindexed = <DetectedBarcodeItem>[];
for (var i = 0; i < activeItems.length; i++) {
final it = activeItems[i];
reindexed.add(it.copyWith(
index: i + 1,
color: kArBarcodePalette[i % kArBarcodePalette.length],
));
}
setState(() {
_liveArItems = reindexed;
});
}
}
void _updateLiveArItems( void _updateLiveArItems(
List<DetectedBarcodeItem> items, { List<DetectedBarcodeItem> items, {
int? precisionTargetIndex, int? precisionTargetIndex,
@@ -311,12 +432,21 @@ class _ScannerScreenState extends State<ScannerScreen>
void _requestFreeze() { void _requestFreeze() {
final snapshot = _latestArSnapshot; final snapshot = _latestArSnapshot;
final now = DateTime.now();
final isFresh = snapshot != null && final isFresh = snapshot != null &&
DateTime.now().difference(snapshot.timestamp) <= now.difference(snapshot.timestamp) <= const Duration(milliseconds: 3000);
const Duration(milliseconds: 1500);
if (isFresh) { if (isFresh && (_liveArItems.isNotEmpty || snapshot.items.isNotEmpty)) {
_freezeWithSnapshot(snapshot); final finalItems = _liveArItems.isNotEmpty ? _liveArItems : snapshot.items;
final readySnapshot = ArCaptureSnapshot(
imageBytes: snapshot.imageBytes,
imageSize: snapshot.imageSize,
viewportSize: snapshot.viewportSize,
deviceOrientation: snapshot.deviceOrientation,
items: finalItems,
timestamp: now,
);
_freezeWithSnapshot(readySnapshot);
return; return;
} }
@@ -351,26 +481,46 @@ class _ScannerScreenState extends State<ScannerScreen>
}); });
} }
bool _ensureCanScan() {
final monetization = context.read<MonetizationCubit>();
if (!monetization.tryConsumeScan()) {
RewardSessionDialog.show(context);
return false;
}
return true;
}
Future<void> _onTapArBarcode(DetectedBarcodeItem item) async { Future<void> _onTapArBarcode(DetectedBarcodeItem item) async {
if (!_ensureCanScan()) return;
final success = await context.read<ScannerCubit>().sendSelectedBarcode( final success = await context.read<ScannerCubit>().sendSelectedBarcode(
item.code, item.code,
format: item.format, format: item.format,
); );
if (!mounted) return; if (!mounted) return;
if (_frozenSnapshot != null && success) { if (success) {
setState(() { setState(() {
_sentFrozenKeys.add(item.selectionKey); if (_frozenSnapshot != null) {
_sentFrozenKeys.add(item.code);
_sentFrozenKeys.add(item.selectionKey);
} else {
_sentLiveKeys.add(item.code);
_sentLiveKeys.add(item.selectionKey);
}
}); });
} else if (_frozenSnapshot == null) { }
if (_frozenSnapshot == null) {
final l10n = context.l10n;
ScaffoldMessenger.of(context) ScaffoldMessenger.of(context)
..hideCurrentSnackBar() ..hideCurrentSnackBar()
..showSnackBar( ..showSnackBar(
SnackBar( SnackBar(
content: Text( content: Text(
success success
? 'Inviato al PC: ${item.code}' ? l10n.sentToPcSnackbar(item.code)
: 'Codice salvato in cronologia (PC non connesso)', : l10n.savedToHistoryOfflineSnackbar,
), ),
duration: const Duration(milliseconds: 1100), duration: const Duration(milliseconds: 1100),
backgroundColor: AppTheme.darkCard, backgroundColor: AppTheme.darkCard,
@@ -379,7 +529,7 @@ class _ScannerScreenState extends State<ScannerScreen>
} }
} }
Future<void> _handleTapToFocus(TapUpDetails details) async { void _handleTapToFocus(TapUpDetails details) {
if (_frozenSnapshot != null || if (_frozenSnapshot != null ||
_viewportSize.isEmpty || _viewportSize.isEmpty ||
!_scannerController.value.isRunning) { !_scannerController.value.isRunning) {
@@ -387,9 +537,6 @@ class _ScannerScreenState extends State<ScannerScreen>
} }
final local = details.localPosition; 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(); _focusRingTimer?.cancel();
setState(() { setState(() {
_focusRingPosition = local; _focusRingPosition = local;
@@ -400,9 +547,7 @@ class _ScannerScreenState extends State<ScannerScreen>
} }
}); });
try { _feedbackService.triggerSelection();
await _scannerController.setFocusPoint(Offset(rx, ry));
} catch (_) {}
} }
void _toggleTorch() { void _toggleTorch() {
@@ -439,10 +584,6 @@ class _ScannerScreenState extends State<ScannerScreen>
return LayoutBuilder( return LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
_viewportSize = constraints.biggest; _viewportSize = constraints.biggest;
final scanWindow = ScannerReticleGeometry.scanRect(
_viewportSize,
aimMode,
);
final topSafe = MediaQuery.paddingOf(context).top + 124.0; final topSafe = MediaQuery.paddingOf(context).top + 124.0;
final bottomReserved = (lastScan != null ? 250.0 : 165.0) + final bottomReserved = (lastScan != null ? 250.0 : 165.0) +
@@ -477,8 +618,6 @@ class _ScannerScreenState extends State<ScannerScreen>
}, },
child: MobileScanner( child: MobileScanner(
controller: _scannerController, controller: _scannerController,
scanWindow: scanWindow,
scanWindowUpdateThreshold: 4.0,
onDetect: _onDetect, onDetect: _onDetect,
), ),
), ),
@@ -500,6 +639,8 @@ class _ScannerScreenState extends State<ScannerScreen>
items: _liveArItems, items: _liveArItems,
safeBounds: arSafeBounds, safeBounds: arSafeBounds,
showBadges: aimMode == ScanAimMode.arMulti, showBadges: aimMode == ScanAimMode.arMulti,
allowBoxTap: true,
sentKeys: _sentLiveKeys,
highlightedIndex: aimMode == ScanAimMode.precision highlightedIndex: aimMode == ScanAimMode.precision
? _precisionTargetIndex ? _precisionTargetIndex
: null, : null,
@@ -525,7 +666,16 @@ class _ScannerScreenState extends State<ScannerScreen>
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const Center(child: ConnectionStatusChip()), Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 6,
children: const [
ConnectionStatusChip(),
_SessionStatusChip(),
],
),
const SizedBox(height: 10), const SizedBox(height: 10),
Row( Row(
mainAxisAlignment: mainAxisAlignment:
@@ -541,14 +691,15 @@ class _ScannerScreenState extends State<ScannerScreen>
color: scannerState.isTorchOn color: scannerState.isTorchOn
? Colors.amber ? Colors.amber
: Colors.white, : Colors.white,
tooltip: 'Torcia', tooltip: context.l10n.torchTooltip,
onPressed: _toggleTorch, onPressed: _toggleTorch,
), ),
const SizedBox(width: 10), const SizedBox(width: 10),
_CircleGlassButton( _CircleGlassButton(
icon: Icons icon: Icons
.flip_camera_ios_rounded, .flip_camera_ios_rounded,
tooltip: 'Inverti Fotocamera', tooltip: context
.l10n.switchCameraTooltip,
onPressed: _switchCamera, onPressed: _switchCamera,
), ),
], ],
@@ -577,7 +728,8 @@ class _ScannerScreenState extends State<ScannerScreen>
offset: const Offset(-2, 2), offset: const Offset(-2, 2),
child: _CircleGlassButton( child: _CircleGlassButton(
icon: Icons.history_rounded, icon: Icons.history_rounded,
tooltip: 'Cronologia', tooltip: context
.l10n.historyTooltip,
onPressed: () { onPressed: () {
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute( MaterialPageRoute(
@@ -593,7 +745,8 @@ class _ScannerScreenState extends State<ScannerScreen>
const SizedBox(width: 10), const SizedBox(width: 10),
_CircleGlassButton( _CircleGlassButton(
icon: Icons.settings_outlined, icon: Icons.settings_outlined,
tooltip: 'Impostazioni', tooltip:
context.l10n.settingsTooltip,
onPressed: () { onPressed: () {
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute( MaterialPageRoute(
@@ -751,3 +904,101 @@ class _CircleGlassButton extends StatelessWidget {
); );
} }
} }
class _SessionStatusChip extends StatelessWidget {
const _SessionStatusChip();
@override
Widget build(BuildContext context) {
return BlocBuilder<MonetizationCubit, MonetizationState>(
builder: (context, state) {
if (state.isPremium) {
const premiumColor = Color(0xFFFBBF24); // Gold amber
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () => PaywallSheet.showPremiumManageDialog(context),
borderRadius: BorderRadius.circular(16),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: premiumColor.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: premiumColor.withValues(alpha: 0.4),
width: 1,
),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.workspace_premium_rounded,
color: premiumColor,
size: 14,
),
SizedBox(width: 5),
Text(
'💎 Premium',
style: TextStyle(
color: premiumColor,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
);
}
final l10n = context.l10n;
final isUnlimited = state.isUnlimited;
final color = isUnlimited
? AppTheme.success
: (state.freeScansRemaining > 0 ? AppTheme.primary : AppTheme.warning);
final label = isUnlimited
? l10n.unlimitedSessionLabel(state.formattedRemainingTime)
: (state.freeScansRemaining > 0
? l10n.freeScansShort(state.freeScansRemaining)
: l10n.unlock15Min);
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () => RewardSessionDialog.show(context),
borderRadius: BorderRadius.circular(16),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: color.withValues(alpha: 0.4), width: 1),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isUnlimited ? Icons.timer_outlined : Icons.ondemand_video_rounded,
color: color,
size: 14,
),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(
color: color,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
);
},
);
}
}
@@ -35,7 +35,8 @@ class ArBarcodeOverlay extends StatelessWidget {
safeBounds: safeBounds, safeBounds: safeBounds,
measureBadge: (item) => _measureBadge( measureBadge: (item) => _measureBadge(
item, item,
isSent: sentKeys.contains(item.selectionKey), isSent: sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey),
), ),
) )
: const <int, Rect>{}; : const <int, Rect>{};
@@ -71,7 +72,8 @@ class ArBarcodeOverlay extends StatelessWidget {
rect: rect, rect: rect,
child: _ArCodeBadge( child: _ArCodeBadge(
item: item, item: item,
isSent: sentKeys.contains(item.selectionKey), isSent: sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey),
onTap: onTapBarcode != null ? () => onTapBarcode!(item) : null, onTap: onTapBarcode != null ? () => onTapBarcode!(item) : null,
), ),
), ),
@@ -197,7 +199,8 @@ class _ArPolygonPainter extends CustomPainter {
final isPrecisionMode = !showBadges; final isPrecisionMode = !showBadges;
final isHighlighted = highlightedIndex == item.index; final isHighlighted = highlightedIndex == item.index;
final isSent = sentKeys.contains(item.selectionKey); final isSent = sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey);
final Color strokeColor; final Color strokeColor;
final double strokeWidth; final double strokeWidth;
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/detected_barcode_item.dart'; import '../../domain/entities/detected_barcode_item.dart';
import 'ar_barcode_overlay.dart'; import 'ar_barcode_overlay.dart';
@@ -143,7 +144,8 @@ class _ArFrozenPickerState extends State<ArFrozenPicker> {
const SizedBox(width: 8), const SizedBox(width: 8),
Flexible( Flexible(
child: Text( child: Text(
'Frame bloccato • ${snapshot.items.length} ${snapshot.items.length == 1 ? 'codice' : 'codici'}', context.l10n.frozenFrameCount(
snapshot.items.length),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: const TextStyle( style: const TextStyle(
@@ -171,7 +173,7 @@ class _ArFrozenPickerState extends State<ArFrozenPicker> {
], ],
_TopPillButton( _TopPillButton(
icon: Icons.close_rounded, icon: Icons.close_rounded,
label: 'Riprendi', label: context.l10n.resumeButton,
accent: true, accent: true,
onTap: widget.onResumeLive, onTap: widget.onResumeLive,
), ),
@@ -215,10 +217,10 @@ class _ArFrozenPickerState extends State<ArFrozenPicker> {
padding: const EdgeInsets.fromLTRB(18, 12, 14, 8), padding: const EdgeInsets.fromLTRB(18, 12, 14, 8),
child: Row( child: Row(
children: [ children: [
const Expanded( Expanded(
child: Text( child: Text(
'Tocca un codice per inviarlo al PC', context.l10n.tapCodeToSend,
style: TextStyle( style: const TextStyle(
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
fontSize: 12.5, fontSize: 12.5,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@@ -231,7 +233,7 @@ class _ArFrozenPickerState extends State<ArFrozenPicker> {
Icons.videocam_rounded, Icons.videocam_rounded,
size: 16, size: 16,
), ),
label: const Text('Nuova scansione'), label: Text(context.l10n.newScanButton),
style: TextButton.styleFrom( style: TextButton.styleFrom(
foregroundColor: AppTheme.secondary, foregroundColor: AppTheme.secondary,
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
@@ -250,7 +252,7 @@ class _ArFrozenPickerState extends State<ArFrozenPicker> {
const SizedBox(height: 8), const SizedBox(height: 8),
itemBuilder: (context, index) { itemBuilder: (context, index) {
final item = snapshot.items[index]; final item = snapshot.items[index];
final isSent = final isSent = widget.sentKeys.contains(item.code) ||
widget.sentKeys.contains(item.selectionKey); widget.sentKeys.contains(item.selectionKey);
return _FrozenCodeRow( return _FrozenCodeRow(
item: item, item: item,
@@ -379,7 +381,9 @@ class _FrozenCodeRow extends StatelessWidget {
), ),
const SizedBox(width: 4), const SizedBox(width: 4),
Text( Text(
isSent ? 'Inviato' : 'Invia', isSent
? context.l10n.sentLabel
: context.l10n.sendLabel,
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 12,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/scan_record.dart'; import '../../domain/entities/scan_record.dart';
import '../cubit/scanner_cubit.dart'; import '../cubit/scanner_cubit.dart';
@@ -12,6 +13,7 @@ class LastScanCard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
final isSuccess = record.sentSuccessfully; final isSuccess = record.sentSuccessfully;
return Container( return Container(
@@ -80,9 +82,10 @@ class LastScanCard extends StatelessWidget {
), ),
if (!isSuccess) ...[ if (!isSuccess) ...[
const Spacer(), const Spacer(),
const Text( Text(
'Non inviato', l10n.notSent,
style: TextStyle(fontSize: 11, color: AppTheme.warning), style: const TextStyle(
fontSize: 11, color: AppTheme.warning),
), ),
], ],
], ],
@@ -105,14 +108,14 @@ class LastScanCard extends StatelessWidget {
const SizedBox(width: 8), const SizedBox(width: 8),
IconButton( IconButton(
icon: const Icon(Icons.copy_rounded, size: 20), icon: const Icon(Icons.copy_rounded, size: 20),
tooltip: 'Copia', tooltip: l10n.copyTooltip,
color: AppTheme.darkTextSecondary, color: AppTheme.darkTextSecondary,
onPressed: () { onPressed: () {
Clipboard.setData(ClipboardData(text: record.code)); Clipboard.setData(ClipboardData(text: record.code));
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( SnackBar(
content: Text('Codice copiato negli appunti'), content: Text(l10n.codeCopiedSnackbar),
duration: Duration(seconds: 1), duration: const Duration(seconds: 1),
backgroundColor: AppTheme.darkCard, backgroundColor: AppTheme.darkCard,
), ),
); );
@@ -120,7 +123,7 @@ class LastScanCard extends StatelessWidget {
), ),
IconButton( IconButton(
icon: const Icon(Icons.send_rounded, size: 20), icon: const Icon(Icons.send_rounded, size: 20),
tooltip: 'Invia di nuovo al PC', tooltip: l10n.resendToPcTooltip,
color: AppTheme.primary, color: AppTheme.primary,
onPressed: () { onPressed: () {
context.read<ScannerCubit>().resendScan(record); context.read<ScannerCubit>().resendScan(record);
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../cubit/scanner_cubit.dart'; import '../cubit/scanner_cubit.dart';
@@ -39,21 +40,24 @@ class _ManualInputDialogState extends State<ManualInputDialog> {
void _submit() { void _submit() {
final code = _textController.text.trim(); final code = _textController.text.trim();
if (code.isNotEmpty) { if (code.isNotEmpty) {
context.read<ScannerCubit>().processBarcode(code, format: 'Manuale'); context
.read<ScannerCubit>()
.processBarcode(code, format: context.l10n.manualFormat);
Navigator.of(context).pop(); Navigator.of(context).pop();
} }
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
return AlertDialog( return AlertDialog(
title: const Row( title: Row(
children: [ children: [
Icon(Icons.keyboard_outlined, color: AppTheme.primary), const Icon(Icons.keyboard_outlined, color: AppTheme.primary),
SizedBox(width: 10), const SizedBox(width: 10),
Text( Text(
'Digitazione Manuale', l10n.manualInputTitle,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
), ),
], ],
), ),
@@ -61,9 +65,10 @@ class _ManualInputDialogState extends State<ManualInputDialog> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const Text( Text(
'Digita o incolla il codice da digitare in tempo reale sul PC:', l10n.manualInputSubtitle,
style: TextStyle(fontSize: 13, color: AppTheme.darkTextSecondary), style: const TextStyle(
fontSize: 13, color: AppTheme.darkTextSecondary),
), ),
const SizedBox(height: 14), const SizedBox(height: 14),
TextField( TextField(
@@ -71,10 +76,10 @@ class _ManualInputDialogState extends State<ManualInputDialog> {
autofocus: true, autofocus: true,
style: const TextStyle(fontFamily: 'monospace', fontSize: 16), style: const TextStyle(fontFamily: 'monospace', fontSize: 16),
decoration: InputDecoration( decoration: InputDecoration(
hintText: 'Es. 8001234567890 o ART-99', hintText: l10n.manualInputHint,
suffixIcon: IconButton( suffixIcon: IconButton(
icon: const Icon(Icons.paste_rounded, size: 20), icon: const Icon(Icons.paste_rounded, size: 20),
tooltip: 'Incolla dagli appunti', tooltip: l10n.pasteFromClipboardTooltip,
onPressed: () async { onPressed: () async {
final data = await Clipboard.getData('text/plain'); final data = await Clipboard.getData('text/plain');
if (data?.text != null) { if (data?.text != null) {
@@ -91,11 +96,11 @@ class _ManualInputDialogState extends State<ManualInputDialog> {
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.of(context).pop(), onPressed: () => Navigator.of(context).pop(),
child: const Text('Annulla'), child: Text(l10n.cancel),
), ),
FilledButton.icon( FilledButton.icon(
icon: const Icon(Icons.send_rounded, size: 18), icon: const Icon(Icons.send_rounded, size: 18),
label: const Text('Invia al PC'), label: Text(l10n.sendToPcButton),
onPressed: _submit, onPressed: _submit,
), ),
], ],
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/scan_aim_mode.dart'; import '../../domain/entities/scan_aim_mode.dart';
@@ -80,12 +81,13 @@ class _FreezeButton extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
final hasCodes = liveBarcodeCount > 0; final hasCodes = liveBarcodeCount > 0;
final label = isPendingFreeze final label = isPendingFreeze
? 'In attesa dei codici… Tocca per annullare' ? l10n.waitingForCodesCancel
: hasCodes : hasCodes
? 'Blocca frame ($liveBarcodeCount ${liveBarcodeCount == 1 ? 'codice' : 'codici'})' ? l10n.freezeFrameCount(liveBarcodeCount)
: 'Blocca e scegli'; : l10n.freezeAndPick;
return SizedBox( return SizedBox(
width: double.infinity, width: double.infinity,
@@ -142,6 +144,7 @@ class _ZoomPresetsBar extends StatelessWidget {
static const _presets = [ static const _presets = [
(label: '1x', scale: 0.0), (label: '1x', scale: 0.0),
(label: '1.5x', scale: 0.125),
(label: '2x', scale: 0.25), (label: '2x', scale: 0.25),
(label: '3x', scale: 0.50), (label: '3x', scale: 0.50),
]; ];
@@ -174,7 +177,7 @@ class _ZoomPresetsBar extends StatelessWidget {
for (final preset in _presets) for (final preset in _presets)
_ZoomChip( _ZoomChip(
label: preset.label, label: preset.label,
selected: !isExtraZoom && (zoomScale - preset.scale).abs() < 0.09, selected: !isExtraZoom && (zoomScale - preset.scale).abs() < 0.06,
onTap: () => onSelect(preset.scale), onTap: () => onSelect(preset.scale),
), ),
if (isExtraZoom) if (isExtraZoom)
@@ -246,14 +249,15 @@ class _ManualActionPill extends StatelessWidget {
width: 1, width: 1,
), ),
), ),
child: const Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(Icons.keyboard_rounded, color: AppTheme.primary, size: 18), const Icon(Icons.keyboard_rounded,
SizedBox(width: 6), color: AppTheme.primary, size: 18),
const SizedBox(width: 6),
Text( Text(
'Manuale', context.l10n.manualButton,
style: TextStyle( style: const TextStyle(
fontSize: 12.5, fontSize: 12.5,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: AppTheme.darkTextPrimary, color: AppTheme.darkTextPrimary,
@@ -292,19 +296,19 @@ class _AimModeSelector extends StatelessWidget {
children: [ children: [
_ModeTab( _ModeTab(
icon: Icons.qr_code_scanner_rounded, icon: Icons.qr_code_scanner_rounded,
label: ScanAimMode.standard.label, label: ScanAimMode.standard.localizedLabel(context.l10n),
selected: selectedMode == ScanAimMode.standard, selected: selectedMode == ScanAimMode.standard,
onTap: () => onChanged(ScanAimMode.standard), onTap: () => onChanged(ScanAimMode.standard),
), ),
_ModeTab( _ModeTab(
icon: Icons.gps_fixed_rounded, icon: Icons.gps_fixed_rounded,
label: ScanAimMode.precision.label, label: ScanAimMode.precision.localizedLabel(context.l10n),
selected: selectedMode == ScanAimMode.precision, selected: selectedMode == ScanAimMode.precision,
onTap: () => onChanged(ScanAimMode.precision), onTap: () => onChanged(ScanAimMode.precision),
), ),
_ModeTab( _ModeTab(
icon: Icons.view_in_ar_rounded, icon: Icons.view_in_ar_rounded,
label: ScanAimMode.arMulti.label, label: ScanAimMode.arMulti.localizedLabel(context.l10n),
selected: selectedMode == ScanAimMode.arMulti, selected: selectedMode == ScanAimMode.arMulti,
onTap: () => onChanged(ScanAimMode.arMulti), onTap: () => onChanged(ScanAimMode.arMulti),
), ),
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../domain/entities/scan_aim_mode.dart'; import '../../domain/entities/scan_aim_mode.dart';
import '../utils/barcode_geometry.dart'; import '../utils/barcode_geometry.dart';
@@ -223,8 +224,8 @@ class _ScannerOverlayState extends State<ScannerOverlay>
) )
: Text( : Text(
isPrecision isPrecision
? 'Centra il mirino sul codice • Tocca per mettere a fuoco' ? context.l10n.precisionHelperText
: 'Inquadra codice a barre o QR • Pizzica per zoomare', : context.l10n.standardHelperText,
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: const TextStyle( style: const TextStyle(
color: Colors.white70, color: Colors.white70,
@@ -455,9 +456,10 @@ class _CooldownStatusPill extends StatelessWidget {
duration: Duration(milliseconds: remainingMs), duration: Duration(milliseconds: remainingMs),
builder: (context, fraction, _) { builder: (context, fraction, _) {
final secsLeft = (fraction * totalMs / 1000.0).clamp(0.0, 99.9); final secsLeft = (fraction * totalMs / 1000.0).clamp(0.0, 99.9);
final secsText = secsLeft.toStringAsFixed(1);
final label = succeeded final label = succeeded
? 'Inviato • Pausa ${secsLeft.toStringAsFixed(1)}s' ? context.l10n.cooldownSent(secsText)
: 'Non inviato • Pausa ${secsLeft.toStringAsFixed(1)}s'; : context.l10n.cooldownNotSent(secsText);
return Container( return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
@@ -22,6 +22,7 @@ class SettingsLocalDataSource {
final aimMode = ScanAimMode.fromStorageKey( final aimMode = ScanAimMode.fromStorageKey(
_prefs.getString(AppConstants.keyAimMode), _prefs.getString(AppConstants.keyAimMode),
); );
final languageCode = _prefs.getString(AppConstants.keyLanguageCode) ?? '';
return AppSettings( return AppSettings(
suffix: suffix, suffix: suffix,
@@ -32,6 +33,7 @@ class SettingsLocalDataSource {
autoConnect: autoConnect, autoConnect: autoConnect,
inactivityTimeoutMinutes: inactivityTimeout, inactivityTimeoutMinutes: inactivityTimeout,
aimMode: aimMode, aimMode: aimMode,
languageCode: languageCode,
); );
} }
@@ -64,4 +66,8 @@ class SettingsLocalDataSource {
Future<void> saveAimMode(ScanAimMode mode) async { Future<void> saveAimMode(ScanAimMode mode) async {
await _prefs.setString(AppConstants.keyAimMode, mode.storageKey); await _prefs.setString(AppConstants.keyAimMode, mode.storageKey);
} }
Future<void> saveLanguageCode(String languageCode) async {
await _prefs.setString(AppConstants.keyLanguageCode, languageCode);
}
} }
@@ -48,4 +48,9 @@ class SettingsRepositoryImpl implements SettingsRepository {
Future<void> saveAimMode(ScanAimMode mode) async { Future<void> saveAimMode(ScanAimMode mode) async {
await _localDataSource.saveAimMode(mode); await _localDataSource.saveAimMode(mode);
} }
@override
Future<void> saveLanguageCode(String languageCode) async {
await _localDataSource.saveLanguageCode(languageCode);
}
} }
@@ -1,3 +1,5 @@
import 'dart:ui';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import '../../../../core/constants/app_constants.dart'; import '../../../../core/constants/app_constants.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart'; import '../../../scanner/domain/entities/scan_aim_mode.dart';
@@ -11,6 +13,7 @@ class AppSettings extends Equatable {
final bool autoConnect; // Default: false (ideal for multi-PC store) final bool autoConnect; // Default: false (ideal for multi-PC store)
final int inactivityTimeoutMinutes; // Default: 5 or 10 min, 0 = disabled final int inactivityTimeoutMinutes; // Default: 5 or 10 min, 0 = disabled
final ScanAimMode aimMode; final ScanAimMode aimMode;
final String languageCode; // '' = system default, 'it', 'en'
const AppSettings({ const AppSettings({
this.suffix = 'enter', this.suffix = 'enter',
@@ -21,8 +24,11 @@ class AppSettings extends Equatable {
this.autoConnect = false, this.autoConnect = false,
this.inactivityTimeoutMinutes = AppConstants.defaultInactivityTimeoutMinutes, this.inactivityTimeoutMinutes = AppConstants.defaultInactivityTimeoutMinutes,
this.aimMode = ScanAimMode.standard, this.aimMode = ScanAimMode.standard,
this.languageCode = '',
}); });
Locale? get locale => languageCode.isEmpty ? null : Locale(languageCode);
AppSettings copyWith({ AppSettings copyWith({
String? suffix, String? suffix,
bool? continuousMode, bool? continuousMode,
@@ -32,6 +38,7 @@ class AppSettings extends Equatable {
bool? autoConnect, bool? autoConnect,
int? inactivityTimeoutMinutes, int? inactivityTimeoutMinutes,
ScanAimMode? aimMode, ScanAimMode? aimMode,
String? languageCode,
}) { }) {
return AppSettings( return AppSettings(
suffix: suffix ?? this.suffix, suffix: suffix ?? this.suffix,
@@ -43,6 +50,7 @@ class AppSettings extends Equatable {
inactivityTimeoutMinutes: inactivityTimeoutMinutes:
inactivityTimeoutMinutes ?? this.inactivityTimeoutMinutes, inactivityTimeoutMinutes ?? this.inactivityTimeoutMinutes,
aimMode: aimMode ?? this.aimMode, aimMode: aimMode ?? this.aimMode,
languageCode: languageCode ?? this.languageCode,
); );
} }
@@ -56,5 +64,6 @@ class AppSettings extends Equatable {
autoConnect, autoConnect,
inactivityTimeoutMinutes, inactivityTimeoutMinutes,
aimMode, aimMode,
languageCode,
]; ];
} }
@@ -10,4 +10,5 @@ abstract class SettingsRepository {
Future<void> saveAutoConnect(bool enabled); Future<void> saveAutoConnect(bool enabled);
Future<void> saveInactivityTimeout(int minutes); Future<void> saveInactivityTimeout(int minutes);
Future<void> saveAimMode(ScanAimMode mode); Future<void> saveAimMode(ScanAimMode mode);
Future<void> saveLanguageCode(String languageCode);
} }
@@ -65,4 +65,10 @@ class SettingsCubit extends Cubit<SettingsState> {
emit(state.copyWith(settings: updated)); emit(state.copyWith(settings: updated));
await _settingsRepository.saveAimMode(mode); await _settingsRepository.saveAimMode(mode);
} }
Future<void> updateLanguageCode(String languageCode) async {
final updated = state.settings.copyWith(languageCode: languageCode);
emit(state.copyWith(settings: updated));
await _settingsRepository.saveLanguageCode(languageCode);
}
} }
@@ -1,11 +1,15 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/constants/app_constants.dart'; import '../../../../core/constants/app_constants.dart';
import '../../../../core/l10n/l10n_extensions.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../../../connection/presentation/cubit/connection_cubit.dart'; import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/cubit/connection_state.dart'; import '../../../connection/presentation/cubit/connection_state.dart';
import '../../../connection/presentation/screens/connect_screen.dart'; import '../../../connection/presentation/screens/connect_screen.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart'; import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../monetization/presentation/cubit/monetization_cubit.dart';
import '../../../monetization/presentation/cubit/monetization_state.dart';
import '../../../monetization/presentation/widgets/paywall_sheet.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart'; import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../cubit/settings_cubit.dart'; import '../cubit/settings_cubit.dart';
import '../cubit/settings_state.dart'; import '../cubit/settings_state.dart';
@@ -15,9 +19,10 @@ class SettingsScreen extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Impostazioni'), title: Text(l10n.settingsTitle),
), ),
body: BlocBuilder<SettingsCubit, SettingsState>( body: BlocBuilder<SettingsCubit, SettingsState>(
builder: (context, settingsState) { builder: (context, settingsState) {
@@ -26,8 +31,101 @@ class SettingsScreen extends StatelessWidget {
return ListView( return ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
children: [ children: [
// Subscription & Premium Section (RevenueCat)
_SectionHeader(title: l10n.sectionPlanSubscription),
BlocBuilder<MonetizationCubit, MonetizationState>(
builder: (context, monState) {
final isPremium = monState.isPremium;
return Card(
child: Column(
children: [
ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: (isPremium
? const Color(0xFFFBBF24)
: AppTheme.primary)
.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
isPremium
? Icons.workspace_premium_rounded
: Icons.lock_open_rounded,
color: isPremium
? const Color(0xFFFBBF24)
: AppTheme.primary,
size: 22,
),
),
title: Text(
isPremium
? l10n.premiumPlanActive
: l10n.freeBaseVersion,
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Text(
isPremium
? l10n.unlimitedAndAdFree
: (monState.isUnlimited
? l10n.activeSessionLabel(
monState.formattedRemainingTime)
: l10n.freeScansRemaining(
monState.freeScansRemaining)),
),
trailing: isPremium
? OutlinedButton(
onPressed: () =>
PaywallSheet.showPremiumManageDialog(
context),
child: Text(l10n.manageButton),
)
: FilledButton(
onPressed: () => PaywallSheet.show(context),
style: FilledButton.styleFrom(
backgroundColor: const Color(0xFFFBBF24),
foregroundColor: Colors.black87,
),
child: Text(l10n.upgradePremiumShort),
),
),
if (!isPremium) ...[
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.restore_rounded),
title: Text(l10n.restorePurchasesTitle),
subtitle: Text(l10n.restorePurchasesSubtitle),
onTap: () async {
final restored = await context
.read<MonetizationCubit>()
.restorePurchases();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
restored
? l10n.restorePurchasesSuccess
: l10n.restorePurchasesEmpty,
),
backgroundColor: restored
? AppTheme.success
: AppTheme.darkCard,
),
);
}
},
),
],
],
),
);
},
),
const SizedBox(height: 14),
// PC Connection Section // PC Connection Section
const _SectionHeader(title: 'CONNESSIONE PC & NEGOZIO'), _SectionHeader(title: l10n.sectionPcConnection),
Card( Card(
child: Column( child: Column(
children: [ children: [
@@ -53,13 +151,14 @@ class SettingsScreen extends StatelessWidget {
size: 22, size: 22,
), ),
), ),
title: const Text('Stato Postazione'), title: Text(l10n.workstationStatusTitle),
subtitle: Text( subtitle: Text(
isConnected isConnected
? 'Connesso a ${connState.info.displayName}' ? l10n.connectedToName(
connState.info.displayName)
: (connState.info.isConfigured : (connState.info.isConfigured
? 'Non connesso (${connState.info.ip})' ? l10n.notConnectedWithIp(connState.info.ip)
: 'Nessun PC configurato'), : l10n.noPcConfigured),
style: const TextStyle(fontSize: 13), style: const TextStyle(fontSize: 13),
), ),
trailing: const Icon(Icons.chevron_right_rounded), trailing: const Icon(Icons.chevron_right_rounded),
@@ -89,11 +188,11 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.storefront_rounded, child: const Icon(Icons.storefront_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Postazioni PC Preferite'), title: Text(l10n.favoriteWorkstationsTitle),
subtitle: Text( subtitle: Text(
count > 0 count > 0
? '$count computer registrati nel negozio' ? l10n.registeredComputersCount(count)
: 'Nessun computer salvato', : l10n.noComputersSaved,
style: const TextStyle(fontSize: 13), style: const TextStyle(fontSize: 13),
), ),
trailing: const Icon(Icons.chevron_right_rounded), trailing: const Icon(Icons.chevron_right_rounded),
@@ -116,13 +215,14 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.flash_auto_rounded, child: const Icon(Icons.flash_auto_rounded,
color: AppTheme.secondary, size: 22), color: AppTheme.secondary, size: 22),
), ),
title: const Text( title: Text(
'Autocollegamento all\'avvio/risveglio', l10n.autoConnectFullTitle,
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w600),
), ),
subtitle: const Text( subtitle: Text(
'Disattivato: chiede sempre a quale PC connettersi (evita di sparare codici sul PC del collega)', l10n.autoConnectFullSubtitle,
style: TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
), ),
value: settings.autoConnect, value: settings.autoConnect,
onChanged: (val) { onChanged: (val) {
@@ -142,14 +242,16 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.timer_outlined, child: const Icon(Icons.timer_outlined,
color: AppTheme.warning, size: 22), color: AppTheme.warning, size: 22),
), ),
title: const Text( title: Text(
'Disconnessione per inattività', l10n.inactivityDisconnectTitle,
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.w600),
), ),
subtitle: Text( subtitle: Text(
settings.inactivityTimeoutMinutes > 0 settings.inactivityTimeoutMinutes > 0
? 'Interrompe la connessione dopo ${settings.inactivityTimeoutMinutes} minuti senza scansioni' ? l10n.inactivityDisconnectActive(
: 'Disattivata (rimane sempre connesso)', settings.inactivityTimeoutMinutes)
: l10n.inactivityDisconnectOff,
style: const TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
), ),
trailing: DropdownButton<int>( trailing: DropdownButton<int>(
@@ -159,11 +261,15 @@ class SettingsScreen extends StatelessWidget {
color: AppTheme.darkTextPrimary, color: AppTheme.darkTextPrimary,
fontWeight: FontWeight.bold), fontWeight: FontWeight.bold),
underline: const SizedBox.shrink(), underline: const SizedBox.shrink(),
items: const [ items: [
DropdownMenuItem(value: 5, child: Text('5 min (Consigliato)')), DropdownMenuItem(
DropdownMenuItem(value: 10, child: Text('10 min')), value: 5, child: Text(l10n.inactivity5Min)),
DropdownMenuItem(value: 15, child: Text('15 min')), DropdownMenuItem(
DropdownMenuItem(value: 0, child: Text('Disattivata')), value: 10, child: Text(l10n.inactivity10Min)),
DropdownMenuItem(
value: 15, child: Text(l10n.inactivity15Min)),
DropdownMenuItem(
value: 0, child: Text(l10n.disabledOption)),
], ],
onChanged: (val) { onChanged: (val) {
if (val != null) { if (val != null) {
@@ -190,10 +296,10 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.send_rounded, child: const Icon(Icons.send_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Invia Test di Digitazione'), title: Text(l10n.sendTypingTestTitle),
subtitle: const Text( subtitle: Text(
'Digita "TEST-CATELLI-123" sul PC attivo', l10n.sendTypingTestSubtitle,
style: TextStyle(fontSize: 13), style: const TextStyle(fontSize: 13),
), ),
onTap: () { onTap: () {
context.read<ConnectionCubit>().sendCode( context.read<ConnectionCubit>().sendCode(
@@ -201,9 +307,9 @@ class SettingsScreen extends StatelessWidget {
suffix: settings.suffix, suffix: settings.suffix,
); );
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( SnackBar(
content: Text('Test di digitazione inviato al PC!'), content: Text(l10n.typingTestSentSnackbar),
duration: Duration(seconds: 1), duration: const Duration(seconds: 1),
backgroundColor: AppTheme.darkCard, backgroundColor: AppTheme.darkCard,
), ),
); );
@@ -216,14 +322,13 @@ class SettingsScreen extends StatelessWidget {
const SizedBox(height: 24), const SizedBox(height: 24),
// Keyboard Emulation Section // Keyboard Emulation Section
const _SectionHeader(title: 'EMULAZIONE TASTIERA PC'), _SectionHeader(title: l10n.sectionKeyboardEmulation),
Card( Card(
child: Column( child: Column(
children: [ children: [
_RadioOption( _RadioOption(
title: 'Tasto Invio (Enter)', title: l10n.suffixEnterTitle,
subtitle: subtitle: l10n.suffixEnterSubtitle,
'Preme Invio dopo ogni codice (consigliato per Excel, ERP, gestionali)',
isSelected: settings.suffix == AppConstants.suffixEnter, isSelected: settings.suffix == AppConstants.suffixEnter,
onTap: () { onTap: () {
context context
@@ -233,8 +338,8 @@ class SettingsScreen extends StatelessWidget {
), ),
const Divider(height: 1), const Divider(height: 1),
_RadioOption( _RadioOption(
title: 'Tasto Tabulatore (Tab)', title: l10n.suffixTabTitle,
subtitle: 'Sposta il cursore al campo/cella successiva', subtitle: l10n.suffixTabSubtitle,
isSelected: settings.suffix == AppConstants.suffixTab, isSelected: settings.suffix == AppConstants.suffixTab,
onTap: () { onTap: () {
context context
@@ -244,8 +349,8 @@ class SettingsScreen extends StatelessWidget {
), ),
const Divider(height: 1), const Divider(height: 1),
_RadioOption( _RadioOption(
title: 'Nessun tasto finale', title: l10n.suffixNoneTitle,
subtitle: 'Scrive solo la stringa pura del codice a barre', subtitle: l10n.suffixNoneSubtitle,
isSelected: settings.suffix == AppConstants.suffixNone, isSelected: settings.suffix == AppConstants.suffixNone,
onTap: () { onTap: () {
context context
@@ -260,7 +365,7 @@ class SettingsScreen extends StatelessWidget {
const SizedBox(height: 24), const SizedBox(height: 24),
// Scan & Feedback Section // Scan & Feedback Section
const _SectionHeader(title: 'SCANSIONE E FEEDBACK'), _SectionHeader(title: l10n.sectionScanFeedback),
Card( Card(
child: Column( child: Column(
children: [ children: [
@@ -274,10 +379,10 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.gps_fixed_rounded, child: const Icon(Icons.gps_fixed_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Modalità di mira'), title: Text(l10n.aimModeTitle),
subtitle: const Text( subtitle: Text(
'Standard, Precisione (mirino + zoom) o AR Multi-Codice', l10n.aimModeSubtitle,
style: TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
), ),
trailing: DropdownButton<ScanAimMode>( trailing: DropdownButton<ScanAimMode>(
value: settings.aimMode, value: settings.aimMode,
@@ -291,7 +396,7 @@ class SettingsScreen extends StatelessWidget {
for (final mode in ScanAimMode.values) for (final mode in ScanAimMode.values)
DropdownMenuItem( DropdownMenuItem(
value: mode, value: mode,
child: Text(mode.label), child: Text(mode.localizedLabel(l10n)),
), ),
], ],
onChanged: (mode) { onChanged: (mode) {
@@ -312,9 +417,11 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.hourglass_bottom_rounded, child: const Icon(Icons.hourglass_bottom_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Pausa dopo scansione'), title: Text(l10n.postScanPauseTitle),
subtitle: Text( subtitle: Text(
'Attesa di ${(settings.scanCooldownMs / 1000).toStringAsFixed(1).replaceAll('.', ',')}s prima della prossima lettura', l10n.postScanPauseSubtitle(
(settings.scanCooldownMs / 1000).toStringAsFixed(1),
),
style: const TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
), ),
trailing: DropdownButton<int>( trailing: DropdownButton<int>(
@@ -325,13 +432,19 @@ class SettingsScreen extends StatelessWidget {
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
underline: const SizedBox.shrink(), underline: const SizedBox.shrink(),
items: const [ items: [
DropdownMenuItem(value: 1000, child: Text('1,0 sec (Rapida)')), DropdownMenuItem(
DropdownMenuItem(value: 2000, child: Text('2,0 sec')), value: 1000, child: Text(l10n.cooldown1s)),
DropdownMenuItem(value: 2500, child: Text('2,5 sec (Consigliata)')), DropdownMenuItem(
DropdownMenuItem(value: 3000, child: Text('3,0 sec')), value: 2000, child: Text(l10n.cooldown2s)),
DropdownMenuItem(value: 4000, child: Text('4,0 sec')), DropdownMenuItem(
DropdownMenuItem(value: 5000, child: Text('5,0 sec')), value: 2500, child: Text(l10n.cooldown25s)),
DropdownMenuItem(
value: 3000, child: Text(l10n.cooldown3s)),
DropdownMenuItem(
value: 4000, child: Text(l10n.cooldown4s)),
DropdownMenuItem(
value: 5000, child: Text(l10n.cooldown5s)),
], ],
onChanged: (val) { onChanged: (val) {
if (val != null) { if (val != null) {
@@ -353,10 +466,10 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.repeat_rounded, child: const Icon(Icons.repeat_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Scansione Continua'), title: Text(l10n.continuousScanTitle),
subtitle: const Text( subtitle: Text(
'Riduce la pausa a 1,0s quando inquadri codici diversi in serie', l10n.continuousScanSubtitle,
style: TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
), ),
value: settings.continuousMode, value: settings.continuousMode,
onChanged: (val) { onChanged: (val) {
@@ -374,10 +487,10 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.vibration_rounded, child: const Icon(Icons.vibration_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Vibrazione alla lettura'), title: Text(l10n.vibrationTitle),
subtitle: const Text( subtitle: Text(
'Feedback aptico alla decodifica del codice', l10n.vibrationSubtitle,
style: TextStyle(fontSize: 13), style: const TextStyle(fontSize: 13),
), ),
value: settings.vibrate, value: settings.vibrate,
onChanged: (val) { onChanged: (val) {
@@ -397,10 +510,10 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.volume_up_rounded, child: const Icon(Icons.volume_up_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Suono di conferma'), title: Text(l10n.soundTitle),
subtitle: const Text( subtitle: Text(
'Segnale acustico alla lettura del barcode', l10n.soundSubtitle,
style: TextStyle(fontSize: 13), style: const TextStyle(fontSize: 13),
), ),
value: settings.sound, value: settings.sound,
onChanged: (val) { onChanged: (val) {
@@ -413,8 +526,55 @@ class SettingsScreen extends StatelessWidget {
const SizedBox(height: 24), const SizedBox(height: 24),
// Language Section
_SectionHeader(title: l10n.sectionLanguage),
Card(
child: 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.language_rounded,
color: AppTheme.primary, size: 22),
),
title: Text(l10n.languageTitle),
trailing: DropdownButton<String>(
value: settings.languageCode,
dropdownColor: AppTheme.darkCard,
style: const TextStyle(
color: AppTheme.darkTextPrimary,
fontWeight: FontWeight.bold,
),
underline: const SizedBox.shrink(),
items: [
DropdownMenuItem(
value: '',
child: Text(l10n.languageSystem),
),
DropdownMenuItem(
value: 'it',
child: Text(l10n.languageItalian),
),
DropdownMenuItem(
value: 'en',
child: Text(l10n.languageEnglish),
),
],
onChanged: (code) {
if (code != null) {
context.read<SettingsCubit>().updateLanguageCode(code);
}
},
),
),
),
const SizedBox(height: 24),
// Info Section // Info Section
const _SectionHeader(title: 'INFORMAZIONI'), _SectionHeader(title: l10n.sectionInfo),
Card( Card(
child: Column( child: Column(
children: [ children: [
@@ -428,7 +588,7 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.business_rounded, child: const Icon(Icons.business_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Organizzazione'), title: Text(l10n.organizationTitle),
subtitle: const Text(AppConstants.organization, subtitle: const Text(AppConstants.organization,
style: TextStyle(fontSize: 13)), style: TextStyle(fontSize: 13)),
), ),
@@ -443,7 +603,7 @@ class SettingsScreen extends StatelessWidget {
child: const Icon(Icons.info_outline_rounded, child: const Icon(Icons.info_outline_rounded,
color: AppTheme.primary, size: 22), color: AppTheme.primary, size: 22),
), ),
title: const Text('Versione App'), title: Text(l10n.appVersionTitle),
subtitle: const Text( subtitle: const Text(
'${AppConstants.appVersion} (Flutter Clean Architecture & Cubit)', '${AppConstants.appVersion} (Flutter Clean Architecture & Cubit)',
style: TextStyle(fontSize: 13), style: TextStyle(fontSize: 13),
+314
View File
@@ -0,0 +1,314 @@
{
"@@locale": "en",
"appTitle": "Catelli Barcode Reader",
"cancel": "Cancel",
"remove": "Remove",
"connect": "Connect",
"reconnect": "Reconnect",
"active": "Active",
"activeUppercase": "ACTIVE",
"connected": "Connected",
"connecting": "Connecting...",
"notConnected": "Not connected",
"pinOrNetworkError": "PIN/Network error",
"defaultStorePcName": "Store PC",
"defaultPcServerName": "PC Server",
"enterValidIp": "Enter a valid PC IP address",
"connectingToHost": "Connecting to {ip}:{port}...",
"@connectingToHost": {
"placeholders": {
"ip": { "type": "String" },
"port": { "type": "int" }
}
},
"connectingToName": "Connecting to {name}...",
"@connectingToName": {
"placeholders": {
"name": { "type": "String" }
}
},
"pcConnectionsTitle": "PC Workstations Connection",
"scanPcQrCode": "Scan QR Code on PC",
"savedStoreWorkstations": "Saved Store Workstations",
"favoritesCount": "{count, plural, =1{1 favorite} other{{count} favorites}}",
"@favoritesCount": {
"placeholders": {
"count": { "type": "int" }
}
},
"detectedWifiPcs": "PCs Detected on Wi-Fi",
"refreshDiscoveryTooltip": "Refresh scan",
"searchingPcServers": "Searching for PC servers on the network...",
"noPcServersFound": "No PC server detected automatically on the network.\nMake sure the PC companion app is running and connected to the same Wi-Fi.",
"requiresPin": "Requires PIN",
"withPin": "With PIN",
"manualSetup": "Manual Configuration",
"workstationNameLabel": "Workstation / PC Name (optional)",
"workstationNameHint": "e.g. Register 1, Warehouse, Office",
"pcIpLabel": "PC IP Address",
"pcIpHint": "e.g. 192.168.1.100",
"portLabel": "Port",
"pinOptionalLabel": "PIN (if set)",
"pinHint": "PIN code",
"saveAndConnectManually": "Save and Connect Manually",
"disconnectFromPc": "Disconnect from PC",
"disconnectedByInactivity": "Disconnected due to inactivity",
"disconnectedManually": "Manually disconnected",
"qrModalTitle": "Scan Server QR Code",
"qrModalSubtitle": "Point the camera at the QR code shown in the PC companion app.",
"removeWorkstationTitle": "Remove workstation?",
"removeWorkstationMessage": "Do you want to remove \"{name}\" ({ip}) from favorite PCs?",
"@removeWorkstationMessage": {
"placeholders": {
"name": { "type": "String" },
"ip": { "type": "String" }
}
},
"selectPcWorkstation": "Select PC Workstation",
"selectPcSubtitle": "Choose the computer where codes will be typed",
"inactivityAlert": "Disconnected due to inactivity. Select a workstation before scanning.",
"noFavoritePcs": "No favorite PC saved",
"noFavoritePcsHint": "Add your store computers to connect with 1 tap and avoid typing on a colleague's PC.",
"removeFavoriteTooltip": "Remove from favorites",
"addNewPcButton": "Add New PC (Wi-Fi or QR Code)",
"autoConnectOnStartup": "Auto-connect on startup",
"autoConnectSubtitleShort": "Disabled: asks to pick a PC (recommended in multi-PC stores)",
"unlimitedScansTitle": "Unlimited Scans",
"unlimitedScansDescription": "Watch a short video to unlock 15 minutes of uninterrupted unlimited PC scanning.",
"unlocked15MinSnackbar": "15 minutes of unlimited scans unlocked!",
"loadingVideoRetrySnackbar": "Loading video... Please try again in a moment.",
"loadingVideoButton": "Loading video...",
"watchVideoButton": "Watch Video (+15 min)",
"welcomePremiumSnackbar": "Welcome to Unlimited Premium!",
"upgradeToPremiumButton": "Upgrade to Unlimited Premium",
"laterButton": "Later",
"sentToPcSnackbar": "Sent to PC: {code}",
"@sentToPcSnackbar": {
"placeholders": {
"code": { "type": "String" }
}
},
"savedToHistoryOfflineSnackbar": "Code saved to history (PC not connected)",
"torchTooltip": "Flashlight",
"switchCameraTooltip": "Switch Camera",
"historyTooltip": "History",
"settingsTooltip": "Settings",
"premiumBadge": "Premium",
"unlimitedSessionLabel": "{time} Unlimited",
"@unlimitedSessionLabel": {
"placeholders": {
"time": { "type": "String" }
}
},
"freeScansShort": "{count} free",
"@freeScansShort": {
"placeholders": {
"count": { "type": "int" }
}
},
"unlock15Min": "Unlock 15 min",
"aimModeStandard": "Standard",
"aimModePrecision": "Precision",
"aimModeArMulti": "AR Multi",
"waitingForCodesCancel": "Waiting for codes… Tap to cancel",
"freezeFrameCount": "{count, plural, =1{Freeze frame (1 code)} other{Freeze frame ({count} codes)}}",
"@freezeFrameCount": {
"placeholders": {
"count": { "type": "int" }
}
},
"freezeAndPick": "Freeze & pick",
"manualButton": "Manual",
"manualFormat": "Manual",
"manualInputTitle": "Manual Entry",
"manualInputSubtitle": "Type or paste the code to send directly to the PC:",
"manualInputHint": "e.g. 8001234567890 or ART-99",
"pasteFromClipboardTooltip": "Paste from clipboard",
"sendToPcButton": "Send to PC",
"precisionHelperText": "Center crosshair on code • Tap to focus",
"standardHelperText": "Frame barcode or QR • Pinch to zoom",
"cooldownSent": "Sent • Pause {seconds}s",
"@cooldownSent": {
"placeholders": {
"seconds": { "type": "String" }
}
},
"cooldownNotSent": "Not sent • Pause {seconds}s",
"@cooldownNotSent": {
"placeholders": {
"seconds": { "type": "String" }
}
},
"notSent": "Not sent",
"copyTooltip": "Copy",
"codeCopiedSnackbar": "Code copied to clipboard",
"resendToPcTooltip": "Send to PC again",
"frozenFrameCount": "{count, plural, =1{Frozen frame • 1 code} other{Frozen frame • {count} codes}}",
"@frozenFrameCount": {
"placeholders": {
"count": { "type": "int" }
}
},
"resumeButton": "Resume",
"tapCodeToSend": "Tap a code to send it to the PC",
"newScanButton": "New scan",
"sentLabel": "Sent",
"sendLabel": "Send",
"clearHistoryTitle": "Clear History?",
"clearHistoryMessage": "All codes saved in history on this device will be removed.",
"clearAllButton": "Clear All",
"scanHistoryTitle": "Scan History",
"clearHistoryTooltip": "Clear history",
"searchCodesHint": "Search codes...",
"noScansInHistory": "No scans in history",
"noResultsForQuery": "No results for \"{query}\"",
"@noResultsForQuery": {
"placeholders": {
"query": { "type": "String" }
}
},
"copyCodeTooltip": "Copy code",
"copiedToClipboardSnackbar": "Copied to clipboard",
"resentCodeSnackbar": "Sent \"{code}\" to PC",
"@resentCodeSnackbar": {
"placeholders": {
"code": { "type": "String" }
}
},
"settingsTitle": "Settings",
"sectionPlanSubscription": "PLAN & SUBSCRIPTION",
"premiumPlanActive": "Premium Plan Active",
"freeBaseVersion": "Free Basic Version",
"unlimitedAndAdFree": "Unlimited scans and zero ads",
"activeSessionLabel": "Active session: {time}",
"@activeSessionLabel": {
"placeholders": {
"time": { "type": "String" }
}
},
"freeScansRemaining": "{count, plural, =1{1 free scan remaining} other{{count} free scans remaining}}",
"@freeScansRemaining": {
"placeholders": {
"count": { "type": "int" }
}
},
"manageButton": "Manage",
"upgradePremiumShort": "Go Premium",
"restorePurchasesTitle": "Restore Purchases",
"restorePurchasesSubtitle": "Already purchased on another device or reinstalled?",
"restorePurchasesSuccess": "Purchases restored successfully!",
"restorePurchasesEmpty": "No active purchases found to restore.",
"sectionPcConnection": "PC & STORE CONNECTION",
"workstationStatusTitle": "Workstation Status",
"connectedToName": "Connected to {name}",
"@connectedToName": {
"placeholders": {
"name": { "type": "String" }
}
},
"notConnectedWithIp": "Not connected ({ip})",
"@notConnectedWithIp": {
"placeholders": {
"ip": { "type": "String" }
}
},
"noPcConfigured": "No PC configured",
"favoriteWorkstationsTitle": "Favorite PC Workstations",
"registeredComputersCount": "{count, plural, =1{1 computer saved} other{{count} computers saved}}",
"@registeredComputersCount": {
"placeholders": {
"count": { "type": "int" }
}
},
"noComputersSaved": "No computers saved",
"autoConnectFullTitle": "Auto-connect on startup/resume",
"autoConnectFullSubtitle": "Disabled: always asks which PC to connect to (prevents typing on a colleague's PC)",
"inactivityDisconnectTitle": "Inactivity disconnect",
"inactivityDisconnectActive": "Disconnects after {minutes} minutes without scans",
"@inactivityDisconnectActive": {
"placeholders": {
"minutes": { "type": "int" }
}
},
"inactivityDisconnectOff": "Disabled (stays connected)",
"inactivity5Min": "5 min (Recommended)",
"inactivity10Min": "10 min",
"inactivity15Min": "15 min",
"disabledOption": "Disabled",
"sendTypingTestTitle": "Send Typing Test",
"sendTypingTestSubtitle": "Types \"TEST-CATELLI-123\" on the active PC",
"typingTestSentSnackbar": "Typing test sent to PC!",
"sectionKeyboardEmulation": "PC KEYBOARD EMULATION",
"suffixEnterTitle": "Enter Key",
"suffixEnterSubtitle": "Presses Enter after each code (recommended for Excel, ERP, POS)",
"suffixTabTitle": "Tab Key",
"suffixTabSubtitle": "Moves cursor to the next field/cell",
"suffixNoneTitle": "No trailing key",
"suffixNoneSubtitle": "Types only the raw barcode string",
"sectionScanFeedback": "SCANNING & FEEDBACK",
"aimModeTitle": "Aiming mode",
"aimModeSubtitle": "Standard, Precision (crosshair + zoom), or AR Multi-Code",
"postScanPauseTitle": "Post-scan pause",
"postScanPauseSubtitle": "Wait {seconds}s before the next reading",
"@postScanPauseSubtitle": {
"placeholders": {
"seconds": { "type": "String" }
}
},
"cooldown1s": "1.0 sec (Fast)",
"cooldown2s": "2.0 sec",
"cooldown25s": "2.5 sec (Recommended)",
"cooldown3s": "3.0 sec",
"cooldown4s": "4.0 sec",
"cooldown5s": "5.0 sec",
"continuousScanTitle": "Continuous Scanning",
"continuousScanSubtitle": "Reduces pause to 1.0s when scanning different codes in a row",
"vibrationTitle": "Vibrate on scan",
"vibrationSubtitle": "Haptic feedback when a code is decoded",
"soundTitle": "Confirmation sound",
"soundSubtitle": "Audio beep when a barcode is read",
"sectionLanguage": "LANGUAGE",
"languageTitle": "App Language",
"languageSystem": "System default",
"languageItalian": "Italiano",
"languageEnglish": "English",
"sectionInfo": "ABOUT",
"organizationTitle": "Organization",
"appVersionTitle": "App Version",
"paywallTitle": "Barcode Reader Premium",
"paywallSubtitle": "Unlock unlimited PC scanning with zero interruptions.",
"paywallBenefitUnlimited": "Unlimited barcode & QR scans forever",
"paywallBenefitNoAds": "Zero ads, no waiting timers",
"paywallBenefitAllModes": "Standard, Precision & AR Multi-Scan modes",
"paywallBenefitMultiPc": "Multi-PC favorites & instant Wi-Fi sync",
"paywallPlanYearly": "Yearly",
"paywallPlanMonthly": "Monthly",
"paywallPlanLifetime": "Lifetime",
"paywallPerYear": "/ year",
"paywallPerMonth": "/ month",
"paywallOneTime": "One-time purchase",
"paywallBestValue": "BEST VALUE",
"paywallSavePercent": "SAVE {percent}%",
"@paywallSavePercent": {
"placeholders": {
"percent": { "type": "int" }
}
},
"paywallOneTimeBadge": "PAY ONCE",
"paywallContinueButton": "Continue",
"paywallContinueWithPrice": "Continue — {price}",
"@paywallContinueWithPrice": {
"placeholders": {
"price": { "type": "String" }
}
},
"paywallLoadingPlans": "Loading available plans...",
"paywallUnavailableTitle": "Plans temporarily unavailable",
"paywallUnavailableSubtitle": "Check your internet connection or Google Play availability and try again.",
"paywallRetryButton": "Retry",
"paywallPurchaseError": "Purchase could not be completed. Please try again.",
"paywallLegalNote": "Subscriptions auto-renew unless cancelled at least 24 hours before the end of the period in Google Play settings.",
"premiumManageTitle": "Premium Active",
"premiumManageBody": "Your Unlimited Premium plan is active on this account.\n\nTo manage or cancel a subscription, open Google Play Store → Payments & subscriptions → Subscriptions.",
"closeButton": "Close"
}
+202
View File
@@ -0,0 +1,202 @@
{
"@@locale": "it",
"appTitle": "Catelli Barcode Reader",
"cancel": "Annulla",
"remove": "Rimuovi",
"connect": "Connetti",
"reconnect": "Riconnetti",
"active": "Attivo",
"activeUppercase": "ATTIVO",
"connected": "Connesso",
"connecting": "Connessione...",
"notConnected": "Non connesso",
"pinOrNetworkError": "Errore PIN/Rete",
"defaultStorePcName": "PC Negozio",
"defaultPcServerName": "PC Server",
"enterValidIp": "Inserisci un indirizzo IP valido del PC",
"connectingToHost": "Connessione a {ip}:{port} in corso...",
"connectingToName": "Connessione a {name}...",
"pcConnectionsTitle": "Connessione Postazioni PC",
"scanPcQrCode": "Inquadra QR Code sul PC",
"savedStoreWorkstations": "Postazioni Salvate nel Negozio",
"favoritesCount": "{count, plural, =1{1 preferito} other{{count} preferiti}}",
"detectedWifiPcs": "PC Rilevati in Wi-Fi",
"refreshDiscoveryTooltip": "Aggiorna ricerca",
"searchingPcServers": "Ricerca server PC in corso sulla rete...",
"noPcServersFound": "Nessun server PC rilevato automaticamente sulla rete.\nAssicurati che il programma sul PC sia avviato e connesso allo stesso Wi-Fi.",
"requiresPin": "Richiede PIN",
"withPin": "Con PIN",
"manualSetup": "Configurazione Manuale",
"workstationNameLabel": "Nome Postazione / PC (opzionale)",
"workstationNameHint": "Es. Cassa 1, Magazzino, Ufficio",
"pcIpLabel": "Indirizzo IP del PC",
"pcIpHint": "Es. 192.168.1.100",
"portLabel": "Porta",
"pinOptionalLabel": "PIN (se impostato)",
"pinHint": "Codice PIN",
"saveAndConnectManually": "Salva e Connetti Manualmente",
"disconnectFromPc": "Disconnetti dal PC",
"disconnectedByInactivity": "Disconnesso per inattività",
"disconnectedManually": "Disconnesso manualmente",
"qrModalTitle": "Inquadra QR Code del Server",
"qrModalSubtitle": "Inquadra il codice QR mostrato nell'app companion sul PC.",
"removeWorkstationTitle": "Rimuovere postazione?",
"removeWorkstationMessage": "Vuoi eliminare \"{name}\" ({ip}) dai PC preferiti?",
"selectPcWorkstation": "Seleziona Postazione PC",
"selectPcSubtitle": "Scegli il computer del negozio su cui scrivere",
"inactivityAlert": "Disconnesso per inattività. Seleziona la postazione prima di scansionare.",
"noFavoritePcs": "Nessun PC preferito salvato",
"noFavoritePcsHint": "Aggiungi i computer del negozio per collegarti con 1 tocco ed evitare errori tra colleghi.",
"removeFavoriteTooltip": "Rimuovi dai preferiti",
"addNewPcButton": "Aggiungi Nuovo PC (Wi-Fi o QR Code)",
"autoConnectOnStartup": "Collega automaticamente all'avvio",
"autoConnectSubtitleShort": "Disattivato: richiede la selezione del PC (consigliato in negozio)",
"unlimitedScansTitle": "Scansioni Illimitate",
"unlimitedScansDescription": "Guarda un breve video per sbloccare 15 minuti di scansioni illimitate al PC senza interruzioni.",
"unlocked15MinSnackbar": "15 minuti di scansioni illimitate sbloccati!",
"loadingVideoRetrySnackbar": "Caricamento video in corso... Riprova tra pochi istanti.",
"loadingVideoButton": "Caricamento video...",
"watchVideoButton": "Guarda Video (+15 min)",
"welcomePremiumSnackbar": "Benvenuto in Premium Illimitato!",
"upgradeToPremiumButton": "Passa a Premium Illimitato",
"laterButton": "Più tardi",
"sentToPcSnackbar": "Inviato al PC: {code}",
"savedToHistoryOfflineSnackbar": "Codice salvato in cronologia (PC non connesso)",
"torchTooltip": "Torcia",
"switchCameraTooltip": "Inverti Fotocamera",
"historyTooltip": "Cronologia",
"settingsTooltip": "Impostazioni",
"premiumBadge": "Premium",
"unlimitedSessionLabel": "{time} Illimitati",
"freeScansShort": "{count} libere",
"unlock15Min": "Sblocca 15 min",
"aimModeStandard": "Standard",
"aimModePrecision": "Precisione",
"aimModeArMulti": "AR Multi",
"waitingForCodesCancel": "In attesa dei codici… Tocca per annullare",
"freezeFrameCount": "{count, plural, =1{Blocca frame (1 codice)} other{Blocca frame ({count} codici)}}",
"freezeAndPick": "Blocca e scegli",
"manualButton": "Manuale",
"manualFormat": "Manuale",
"manualInputTitle": "Digitazione Manuale",
"manualInputSubtitle": "Digita o incolla il codice da digitare in tempo reale sul PC:",
"manualInputHint": "Es. 8001234567890 o ART-99",
"pasteFromClipboardTooltip": "Incolla dagli appunti",
"sendToPcButton": "Invia al PC",
"precisionHelperText": "Centra il mirino sul codice • Tocca per mettere a fuoco",
"standardHelperText": "Inquadra codice a barre o QR • Pizzica per zoomare",
"cooldownSent": "Inviato • Pausa {seconds}s",
"cooldownNotSent": "Non inviato • Pausa {seconds}s",
"notSent": "Non inviato",
"copyTooltip": "Copia",
"codeCopiedSnackbar": "Codice copiato negli appunti",
"resendToPcTooltip": "Invia di nuovo al PC",
"frozenFrameCount": "{count, plural, =1{Frame bloccato • 1 codice} other{Frame bloccato • {count} codici}}",
"resumeButton": "Riprendi",
"tapCodeToSend": "Tocca un codice per inviarlo al PC",
"newScanButton": "Nuova scansione",
"sentLabel": "Inviato",
"sendLabel": "Invia",
"clearHistoryTitle": "Cancellare Cronologia?",
"clearHistoryMessage": "Tutti i codici salvati nella cronologia su questo dispositivo verranno rimossi.",
"clearAllButton": "Cancella Tutto",
"scanHistoryTitle": "Cronologia Scansioni",
"clearHistoryTooltip": "Cancella cronologia",
"searchCodesHint": "Cerca tra i codici...",
"noScansInHistory": "Nessuna scansione in memoria",
"noResultsForQuery": "Nessun risultato per \"{query}\"",
"copyCodeTooltip": "Copia codice",
"copiedToClipboardSnackbar": "Copiato negli appunti",
"resentCodeSnackbar": "Inviato \"{code}\" al PC",
"settingsTitle": "Impostazioni",
"sectionPlanSubscription": "PIANO & ABBONAMENTO",
"premiumPlanActive": "Piano Premium Attivo",
"freeBaseVersion": "Versione Base Gratuita",
"unlimitedAndAdFree": "Scansioni illimitate e zero pubblicità",
"activeSessionLabel": "Sessione attiva: {time}",
"freeScansRemaining": "{count, plural, =1{1 scansione libera rimanente} other{{count} scansioni libere rimanenti}}",
"manageButton": "Gestisci",
"upgradePremiumShort": "Passa a Premium",
"restorePurchasesTitle": "Ripristina Acquisti",
"restorePurchasesSubtitle": "Hai già acquistato su un altro dispositivo o reinstallato?",
"restorePurchasesSuccess": "Acquisti ripristinati con successo!",
"restorePurchasesEmpty": "Nessun acquisto attivo trovato da ripristinare.",
"sectionPcConnection": "CONNESSIONE PC & NEGOZIO",
"workstationStatusTitle": "Stato Postazione",
"connectedToName": "Connesso a {name}",
"notConnectedWithIp": "Non connesso ({ip})",
"noPcConfigured": "Nessun PC configurato",
"favoriteWorkstationsTitle": "Postazioni PC Preferite",
"registeredComputersCount": "{count, plural, =1{1 computer registrato nel negozio} other{{count} computer registrati nel negozio}}",
"noComputersSaved": "Nessun computer salvato",
"autoConnectFullTitle": "Autocollegamento all'avvio/risveglio",
"autoConnectFullSubtitle": "Disattivato: chiede sempre a quale PC connettersi (evita di sparare codici sul PC del collega)",
"inactivityDisconnectTitle": "Disconnessione per inattività",
"inactivityDisconnectActive": "Interrompe la connessione dopo {minutes} minuti senza scansioni",
"inactivityDisconnectOff": "Disattivata (rimane sempre connesso)",
"inactivity5Min": "5 min (Consigliato)",
"inactivity10Min": "10 min",
"inactivity15Min": "15 min",
"disabledOption": "Disattivata",
"sendTypingTestTitle": "Invia Test di Digitazione",
"sendTypingTestSubtitle": "Digita \"TEST-CATELLI-123\" sul PC attivo",
"typingTestSentSnackbar": "Test di digitazione inviato al PC!",
"sectionKeyboardEmulation": "EMULAZIONE TASTIERA PC",
"suffixEnterTitle": "Tasto Invio (Enter)",
"suffixEnterSubtitle": "Preme Invio dopo ogni codice (consigliato per Excel, ERP, gestionali)",
"suffixTabTitle": "Tasto Tabulatore (Tab)",
"suffixTabSubtitle": "Sposta il cursore al campo/cella successiva",
"suffixNoneTitle": "Nessun tasto finale",
"suffixNoneSubtitle": "Scrive solo la stringa pura del codice a barre",
"sectionScanFeedback": "SCANSIONE E FEEDBACK",
"aimModeTitle": "Modalità di mira",
"aimModeSubtitle": "Standard, Precisione (mirino + zoom) o AR Multi-Codice",
"postScanPauseTitle": "Pausa dopo scansione",
"postScanPauseSubtitle": "Attesa di {seconds}s prima della prossima lettura",
"cooldown1s": "1,0 sec (Rapida)",
"cooldown2s": "2,0 sec",
"cooldown25s": "2,5 sec (Consigliata)",
"cooldown3s": "3,0 sec",
"cooldown4s": "4,0 sec",
"cooldown5s": "5,0 sec",
"continuousScanTitle": "Scansione Continua",
"continuousScanSubtitle": "Riduce la pausa a 1,0s quando inquadri codici diversi in serie",
"vibrationTitle": "Vibrazione alla lettura",
"vibrationSubtitle": "Feedback aptico alla decodifica del codice",
"soundTitle": "Suono di conferma",
"soundSubtitle": "Segnale acustico alla lettura del barcode",
"sectionLanguage": "LINGUA",
"languageTitle": "Lingua App",
"languageSystem": "Predefinita di sistema",
"languageItalian": "Italiano",
"languageEnglish": "English",
"sectionInfo": "INFORMAZIONI",
"organizationTitle": "Organizzazione",
"appVersionTitle": "Versione App",
"paywallTitle": "Barcode Reader Premium",
"paywallSubtitle": "Sblocca scansioni illimitate verso il PC senza alcuna interruzione.",
"paywallBenefitUnlimited": "Scansioni barcode e QR illimitate per sempre",
"paywallBenefitNoAds": "Zero pubblicità e nessun timer di attesa",
"paywallBenefitAllModes": "Modalità Standard, Precisione e AR Multi-Codice",
"paywallBenefitMultiPc": "Postazioni multi-PC preferite e sincronizzazione Wi-Fi",
"paywallPlanYearly": "Annuale",
"paywallPlanMonthly": "Mensile",
"paywallPlanLifetime": "A Vita (Lifetime)",
"paywallPerYear": "/ anno",
"paywallPerMonth": "/ mese",
"paywallOneTime": "Acquisto una tantum",
"paywallBestValue": "PIÙ CONVENIENTE",
"paywallSavePercent": "RISPARMIA {percent}%",
"paywallOneTimeBadge": "PAGHI UNA VOLTA",
"paywallContinueButton": "Continua",
"paywallContinueWithPrice": "Continua — {price}",
"paywallLoadingPlans": "Caricamento piani disponibili...",
"paywallUnavailableTitle": "Piani momentaneamente non disponibili",
"paywallUnavailableSubtitle": "Verifica la connessione internet o la disponibilità di Google Play e riprova.",
"paywallRetryButton": "Riprova",
"paywallPurchaseError": "Impossibile completare l'acquisto. Riprova tra poco.",
"paywallLegalNote": "Gli abbonamenti si rinnovano automaticamente salvo disdetta almeno 24 ore prima della scadenza nelle impostazioni di Google Play.",
"premiumManageTitle": "Premium Attivo",
"premiumManageBody": "Il tuo piano Premium Illimitato è attivo su questo account.\n\nPer gestire o disdire un abbonamento, apri Google Play Store → Pagamenti e abbonamenti → Abbonamenti.",
"closeButton": "Chiudi"
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,705 @@
// ignore: unused_import
import 'package:intl/intl.dart' as intl;
import 'app_localizations.dart';
// ignore_for_file: type=lint
/// The translations for English (`en`).
class AppLocalizationsEn extends AppLocalizations {
AppLocalizationsEn([String locale = 'en']) : super(locale);
@override
String get appTitle => 'Catelli Barcode Reader';
@override
String get cancel => 'Cancel';
@override
String get remove => 'Remove';
@override
String get connect => 'Connect';
@override
String get reconnect => 'Reconnect';
@override
String get active => 'Active';
@override
String get activeUppercase => 'ACTIVE';
@override
String get connected => 'Connected';
@override
String get connecting => 'Connecting...';
@override
String get notConnected => 'Not connected';
@override
String get pinOrNetworkError => 'PIN/Network error';
@override
String get defaultStorePcName => 'Store PC';
@override
String get defaultPcServerName => 'PC Server';
@override
String get enterValidIp => 'Enter a valid PC IP address';
@override
String connectingToHost(String ip, int port) {
return 'Connecting to $ip:$port...';
}
@override
String connectingToName(String name) {
return 'Connecting to $name...';
}
@override
String get pcConnectionsTitle => 'PC Workstations Connection';
@override
String get scanPcQrCode => 'Scan QR Code on PC';
@override
String get savedStoreWorkstations => 'Saved Store Workstations';
@override
String favoritesCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count favorites',
one: '1 favorite',
);
return '$_temp0';
}
@override
String get detectedWifiPcs => 'PCs Detected on Wi-Fi';
@override
String get refreshDiscoveryTooltip => 'Refresh scan';
@override
String get searchingPcServers => 'Searching for PC servers on the network...';
@override
String get noPcServersFound =>
'No PC server detected automatically on the network.\nMake sure the PC companion app is running and connected to the same Wi-Fi.';
@override
String get requiresPin => 'Requires PIN';
@override
String get withPin => 'With PIN';
@override
String get manualSetup => 'Manual Configuration';
@override
String get workstationNameLabel => 'Workstation / PC Name (optional)';
@override
String get workstationNameHint => 'e.g. Register 1, Warehouse, Office';
@override
String get pcIpLabel => 'PC IP Address';
@override
String get pcIpHint => 'e.g. 192.168.1.100';
@override
String get portLabel => 'Port';
@override
String get pinOptionalLabel => 'PIN (if set)';
@override
String get pinHint => 'PIN code';
@override
String get saveAndConnectManually => 'Save and Connect Manually';
@override
String get disconnectFromPc => 'Disconnect from PC';
@override
String get disconnectedByInactivity => 'Disconnected due to inactivity';
@override
String get disconnectedManually => 'Manually disconnected';
@override
String get qrModalTitle => 'Scan Server QR Code';
@override
String get qrModalSubtitle =>
'Point the camera at the QR code shown in the PC companion app.';
@override
String get removeWorkstationTitle => 'Remove workstation?';
@override
String removeWorkstationMessage(String name, String ip) {
return 'Do you want to remove \"$name\" ($ip) from favorite PCs?';
}
@override
String get selectPcWorkstation => 'Select PC Workstation';
@override
String get selectPcSubtitle =>
'Choose the computer where codes will be typed';
@override
String get inactivityAlert =>
'Disconnected due to inactivity. Select a workstation before scanning.';
@override
String get noFavoritePcs => 'No favorite PC saved';
@override
String get noFavoritePcsHint =>
'Add your store computers to connect with 1 tap and avoid typing on a colleague\'s PC.';
@override
String get removeFavoriteTooltip => 'Remove from favorites';
@override
String get addNewPcButton => 'Add New PC (Wi-Fi or QR Code)';
@override
String get autoConnectOnStartup => 'Auto-connect on startup';
@override
String get autoConnectSubtitleShort =>
'Disabled: asks to pick a PC (recommended in multi-PC stores)';
@override
String get unlimitedScansTitle => 'Unlimited Scans';
@override
String get unlimitedScansDescription =>
'Watch a short video to unlock 15 minutes of uninterrupted unlimited PC scanning.';
@override
String get unlocked15MinSnackbar => '15 minutes of unlimited scans unlocked!';
@override
String get loadingVideoRetrySnackbar =>
'Loading video... Please try again in a moment.';
@override
String get loadingVideoButton => 'Loading video...';
@override
String get watchVideoButton => 'Watch Video (+15 min)';
@override
String get welcomePremiumSnackbar => 'Welcome to Unlimited Premium!';
@override
String get upgradeToPremiumButton => 'Upgrade to Unlimited Premium';
@override
String get laterButton => 'Later';
@override
String sentToPcSnackbar(String code) {
return 'Sent to PC: $code';
}
@override
String get savedToHistoryOfflineSnackbar =>
'Code saved to history (PC not connected)';
@override
String get torchTooltip => 'Flashlight';
@override
String get switchCameraTooltip => 'Switch Camera';
@override
String get historyTooltip => 'History';
@override
String get settingsTooltip => 'Settings';
@override
String get premiumBadge => 'Premium';
@override
String unlimitedSessionLabel(String time) {
return '$time Unlimited';
}
@override
String freeScansShort(int count) {
return '$count free';
}
@override
String get unlock15Min => 'Unlock 15 min';
@override
String get aimModeStandard => 'Standard';
@override
String get aimModePrecision => 'Precision';
@override
String get aimModeArMulti => 'AR Multi';
@override
String get waitingForCodesCancel => 'Waiting for codes… Tap to cancel';
@override
String freezeFrameCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: 'Freeze frame ($count codes)',
one: 'Freeze frame (1 code)',
);
return '$_temp0';
}
@override
String get freezeAndPick => 'Freeze & pick';
@override
String get manualButton => 'Manual';
@override
String get manualFormat => 'Manual';
@override
String get manualInputTitle => 'Manual Entry';
@override
String get manualInputSubtitle =>
'Type or paste the code to send directly to the PC:';
@override
String get manualInputHint => 'e.g. 8001234567890 or ART-99';
@override
String get pasteFromClipboardTooltip => 'Paste from clipboard';
@override
String get sendToPcButton => 'Send to PC';
@override
String get precisionHelperText => 'Center crosshair on code • Tap to focus';
@override
String get standardHelperText => 'Frame barcode or QR • Pinch to zoom';
@override
String cooldownSent(String seconds) {
return 'Sent • Pause ${seconds}s';
}
@override
String cooldownNotSent(String seconds) {
return 'Not sent • Pause ${seconds}s';
}
@override
String get notSent => 'Not sent';
@override
String get copyTooltip => 'Copy';
@override
String get codeCopiedSnackbar => 'Code copied to clipboard';
@override
String get resendToPcTooltip => 'Send to PC again';
@override
String frozenFrameCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: 'Frozen frame • $count codes',
one: 'Frozen frame • 1 code',
);
return '$_temp0';
}
@override
String get resumeButton => 'Resume';
@override
String get tapCodeToSend => 'Tap a code to send it to the PC';
@override
String get newScanButton => 'New scan';
@override
String get sentLabel => 'Sent';
@override
String get sendLabel => 'Send';
@override
String get clearHistoryTitle => 'Clear History?';
@override
String get clearHistoryMessage =>
'All codes saved in history on this device will be removed.';
@override
String get clearAllButton => 'Clear All';
@override
String get scanHistoryTitle => 'Scan History';
@override
String get clearHistoryTooltip => 'Clear history';
@override
String get searchCodesHint => 'Search codes...';
@override
String get noScansInHistory => 'No scans in history';
@override
String noResultsForQuery(String query) {
return 'No results for \"$query\"';
}
@override
String get copyCodeTooltip => 'Copy code';
@override
String get copiedToClipboardSnackbar => 'Copied to clipboard';
@override
String resentCodeSnackbar(String code) {
return 'Sent \"$code\" to PC';
}
@override
String get settingsTitle => 'Settings';
@override
String get sectionPlanSubscription => 'PLAN & SUBSCRIPTION';
@override
String get premiumPlanActive => 'Premium Plan Active';
@override
String get freeBaseVersion => 'Free Basic Version';
@override
String get unlimitedAndAdFree => 'Unlimited scans and zero ads';
@override
String activeSessionLabel(String time) {
return 'Active session: $time';
}
@override
String freeScansRemaining(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count free scans remaining',
one: '1 free scan remaining',
);
return '$_temp0';
}
@override
String get manageButton => 'Manage';
@override
String get upgradePremiumShort => 'Go Premium';
@override
String get restorePurchasesTitle => 'Restore Purchases';
@override
String get restorePurchasesSubtitle =>
'Already purchased on another device or reinstalled?';
@override
String get restorePurchasesSuccess => 'Purchases restored successfully!';
@override
String get restorePurchasesEmpty => 'No active purchases found to restore.';
@override
String get sectionPcConnection => 'PC & STORE CONNECTION';
@override
String get workstationStatusTitle => 'Workstation Status';
@override
String connectedToName(String name) {
return 'Connected to $name';
}
@override
String notConnectedWithIp(String ip) {
return 'Not connected ($ip)';
}
@override
String get noPcConfigured => 'No PC configured';
@override
String get favoriteWorkstationsTitle => 'Favorite PC Workstations';
@override
String registeredComputersCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count computers saved',
one: '1 computer saved',
);
return '$_temp0';
}
@override
String get noComputersSaved => 'No computers saved';
@override
String get autoConnectFullTitle => 'Auto-connect on startup/resume';
@override
String get autoConnectFullSubtitle =>
'Disabled: always asks which PC to connect to (prevents typing on a colleague\'s PC)';
@override
String get inactivityDisconnectTitle => 'Inactivity disconnect';
@override
String inactivityDisconnectActive(int minutes) {
return 'Disconnects after $minutes minutes without scans';
}
@override
String get inactivityDisconnectOff => 'Disabled (stays connected)';
@override
String get inactivity5Min => '5 min (Recommended)';
@override
String get inactivity10Min => '10 min';
@override
String get inactivity15Min => '15 min';
@override
String get disabledOption => 'Disabled';
@override
String get sendTypingTestTitle => 'Send Typing Test';
@override
String get sendTypingTestSubtitle =>
'Types \"TEST-CATELLI-123\" on the active PC';
@override
String get typingTestSentSnackbar => 'Typing test sent to PC!';
@override
String get sectionKeyboardEmulation => 'PC KEYBOARD EMULATION';
@override
String get suffixEnterTitle => 'Enter Key';
@override
String get suffixEnterSubtitle =>
'Presses Enter after each code (recommended for Excel, ERP, POS)';
@override
String get suffixTabTitle => 'Tab Key';
@override
String get suffixTabSubtitle => 'Moves cursor to the next field/cell';
@override
String get suffixNoneTitle => 'No trailing key';
@override
String get suffixNoneSubtitle => 'Types only the raw barcode string';
@override
String get sectionScanFeedback => 'SCANNING & FEEDBACK';
@override
String get aimModeTitle => 'Aiming mode';
@override
String get aimModeSubtitle =>
'Standard, Precision (crosshair + zoom), or AR Multi-Code';
@override
String get postScanPauseTitle => 'Post-scan pause';
@override
String postScanPauseSubtitle(String seconds) {
return 'Wait ${seconds}s before the next reading';
}
@override
String get cooldown1s => '1.0 sec (Fast)';
@override
String get cooldown2s => '2.0 sec';
@override
String get cooldown25s => '2.5 sec (Recommended)';
@override
String get cooldown3s => '3.0 sec';
@override
String get cooldown4s => '4.0 sec';
@override
String get cooldown5s => '5.0 sec';
@override
String get continuousScanTitle => 'Continuous Scanning';
@override
String get continuousScanSubtitle =>
'Reduces pause to 1.0s when scanning different codes in a row';
@override
String get vibrationTitle => 'Vibrate on scan';
@override
String get vibrationSubtitle => 'Haptic feedback when a code is decoded';
@override
String get soundTitle => 'Confirmation sound';
@override
String get soundSubtitle => 'Audio beep when a barcode is read';
@override
String get sectionLanguage => 'LANGUAGE';
@override
String get languageTitle => 'App Language';
@override
String get languageSystem => 'System default';
@override
String get languageItalian => 'Italiano';
@override
String get languageEnglish => 'English';
@override
String get sectionInfo => 'ABOUT';
@override
String get organizationTitle => 'Organization';
@override
String get appVersionTitle => 'App Version';
@override
String get paywallTitle => 'Barcode Reader Premium';
@override
String get paywallSubtitle =>
'Unlock unlimited PC scanning with zero interruptions.';
@override
String get paywallBenefitUnlimited => 'Unlimited barcode & QR scans forever';
@override
String get paywallBenefitNoAds => 'Zero ads, no waiting timers';
@override
String get paywallBenefitAllModes =>
'Standard, Precision & AR Multi-Scan modes';
@override
String get paywallBenefitMultiPc => 'Multi-PC favorites & instant Wi-Fi sync';
@override
String get paywallPlanYearly => 'Yearly';
@override
String get paywallPlanMonthly => 'Monthly';
@override
String get paywallPlanLifetime => 'Lifetime';
@override
String get paywallPerYear => '/ year';
@override
String get paywallPerMonth => '/ month';
@override
String get paywallOneTime => 'One-time purchase';
@override
String get paywallBestValue => 'BEST VALUE';
@override
String paywallSavePercent(int percent) {
return 'SAVE $percent%';
}
@override
String get paywallOneTimeBadge => 'PAY ONCE';
@override
String get paywallContinueButton => 'Continue';
@override
String paywallContinueWithPrice(String price) {
return 'Continue — $price';
}
@override
String get paywallLoadingPlans => 'Loading available plans...';
@override
String get paywallUnavailableTitle => 'Plans temporarily unavailable';
@override
String get paywallUnavailableSubtitle =>
'Check your internet connection or Google Play availability and try again.';
@override
String get paywallRetryButton => 'Retry';
@override
String get paywallPurchaseError =>
'Purchase could not be completed. Please try again.';
@override
String get paywallLegalNote =>
'Subscriptions auto-renew unless cancelled at least 24 hours before the end of the period in Google Play settings.';
@override
String get premiumManageTitle => 'Premium Active';
@override
String get premiumManageBody =>
'Your Unlimited Premium plan is active on this account.\n\nTo manage or cancel a subscription, open Google Play Store → Payments & subscriptions → Subscriptions.';
@override
String get closeButton => 'Close';
}
@@ -0,0 +1,713 @@
// ignore: unused_import
import 'package:intl/intl.dart' as intl;
import 'app_localizations.dart';
// ignore_for_file: type=lint
/// The translations for Italian (`it`).
class AppLocalizationsIt extends AppLocalizations {
AppLocalizationsIt([String locale = 'it']) : super(locale);
@override
String get appTitle => 'Catelli Barcode Reader';
@override
String get cancel => 'Annulla';
@override
String get remove => 'Rimuovi';
@override
String get connect => 'Connetti';
@override
String get reconnect => 'Riconnetti';
@override
String get active => 'Attivo';
@override
String get activeUppercase => 'ATTIVO';
@override
String get connected => 'Connesso';
@override
String get connecting => 'Connessione...';
@override
String get notConnected => 'Non connesso';
@override
String get pinOrNetworkError => 'Errore PIN/Rete';
@override
String get defaultStorePcName => 'PC Negozio';
@override
String get defaultPcServerName => 'PC Server';
@override
String get enterValidIp => 'Inserisci un indirizzo IP valido del PC';
@override
String connectingToHost(String ip, int port) {
return 'Connessione a $ip:$port in corso...';
}
@override
String connectingToName(String name) {
return 'Connessione a $name...';
}
@override
String get pcConnectionsTitle => 'Connessione Postazioni PC';
@override
String get scanPcQrCode => 'Inquadra QR Code sul PC';
@override
String get savedStoreWorkstations => 'Postazioni Salvate nel Negozio';
@override
String favoritesCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count preferiti',
one: '1 preferito',
);
return '$_temp0';
}
@override
String get detectedWifiPcs => 'PC Rilevati in Wi-Fi';
@override
String get refreshDiscoveryTooltip => 'Aggiorna ricerca';
@override
String get searchingPcServers => 'Ricerca server PC in corso sulla rete...';
@override
String get noPcServersFound =>
'Nessun server PC rilevato automaticamente sulla rete.\nAssicurati che il programma sul PC sia avviato e connesso allo stesso Wi-Fi.';
@override
String get requiresPin => 'Richiede PIN';
@override
String get withPin => 'Con PIN';
@override
String get manualSetup => 'Configurazione Manuale';
@override
String get workstationNameLabel => 'Nome Postazione / PC (opzionale)';
@override
String get workstationNameHint => 'Es. Cassa 1, Magazzino, Ufficio';
@override
String get pcIpLabel => 'Indirizzo IP del PC';
@override
String get pcIpHint => 'Es. 192.168.1.100';
@override
String get portLabel => 'Porta';
@override
String get pinOptionalLabel => 'PIN (se impostato)';
@override
String get pinHint => 'Codice PIN';
@override
String get saveAndConnectManually => 'Salva e Connetti Manualmente';
@override
String get disconnectFromPc => 'Disconnetti dal PC';
@override
String get disconnectedByInactivity => 'Disconnesso per inattività';
@override
String get disconnectedManually => 'Disconnesso manualmente';
@override
String get qrModalTitle => 'Inquadra QR Code del Server';
@override
String get qrModalSubtitle =>
'Inquadra il codice QR mostrato nell\'app companion sul PC.';
@override
String get removeWorkstationTitle => 'Rimuovere postazione?';
@override
String removeWorkstationMessage(String name, String ip) {
return 'Vuoi eliminare \"$name\" ($ip) dai PC preferiti?';
}
@override
String get selectPcWorkstation => 'Seleziona Postazione PC';
@override
String get selectPcSubtitle =>
'Scegli il computer del negozio su cui scrivere';
@override
String get inactivityAlert =>
'Disconnesso per inattività. Seleziona la postazione prima di scansionare.';
@override
String get noFavoritePcs => 'Nessun PC preferito salvato';
@override
String get noFavoritePcsHint =>
'Aggiungi i computer del negozio per collegarti con 1 tocco ed evitare errori tra colleghi.';
@override
String get removeFavoriteTooltip => 'Rimuovi dai preferiti';
@override
String get addNewPcButton => 'Aggiungi Nuovo PC (Wi-Fi o QR Code)';
@override
String get autoConnectOnStartup => 'Collega automaticamente all\'avvio';
@override
String get autoConnectSubtitleShort =>
'Disattivato: richiede la selezione del PC (consigliato in negozio)';
@override
String get unlimitedScansTitle => 'Scansioni Illimitate';
@override
String get unlimitedScansDescription =>
'Guarda un breve video per sbloccare 15 minuti di scansioni illimitate al PC senza interruzioni.';
@override
String get unlocked15MinSnackbar =>
'15 minuti di scansioni illimitate sbloccati!';
@override
String get loadingVideoRetrySnackbar =>
'Caricamento video in corso... Riprova tra pochi istanti.';
@override
String get loadingVideoButton => 'Caricamento video...';
@override
String get watchVideoButton => 'Guarda Video (+15 min)';
@override
String get welcomePremiumSnackbar => 'Benvenuto in Premium Illimitato!';
@override
String get upgradeToPremiumButton => 'Passa a Premium Illimitato';
@override
String get laterButton => 'Più tardi';
@override
String sentToPcSnackbar(String code) {
return 'Inviato al PC: $code';
}
@override
String get savedToHistoryOfflineSnackbar =>
'Codice salvato in cronologia (PC non connesso)';
@override
String get torchTooltip => 'Torcia';
@override
String get switchCameraTooltip => 'Inverti Fotocamera';
@override
String get historyTooltip => 'Cronologia';
@override
String get settingsTooltip => 'Impostazioni';
@override
String get premiumBadge => 'Premium';
@override
String unlimitedSessionLabel(String time) {
return '$time Illimitati';
}
@override
String freeScansShort(int count) {
return '$count libere';
}
@override
String get unlock15Min => 'Sblocca 15 min';
@override
String get aimModeStandard => 'Standard';
@override
String get aimModePrecision => 'Precisione';
@override
String get aimModeArMulti => 'AR Multi';
@override
String get waitingForCodesCancel =>
'In attesa dei codici… Tocca per annullare';
@override
String freezeFrameCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: 'Blocca frame ($count codici)',
one: 'Blocca frame (1 codice)',
);
return '$_temp0';
}
@override
String get freezeAndPick => 'Blocca e scegli';
@override
String get manualButton => 'Manuale';
@override
String get manualFormat => 'Manuale';
@override
String get manualInputTitle => 'Digitazione Manuale';
@override
String get manualInputSubtitle =>
'Digita o incolla il codice da digitare in tempo reale sul PC:';
@override
String get manualInputHint => 'Es. 8001234567890 o ART-99';
@override
String get pasteFromClipboardTooltip => 'Incolla dagli appunti';
@override
String get sendToPcButton => 'Invia al PC';
@override
String get precisionHelperText =>
'Centra il mirino sul codice • Tocca per mettere a fuoco';
@override
String get standardHelperText =>
'Inquadra codice a barre o QR • Pizzica per zoomare';
@override
String cooldownSent(String seconds) {
return 'Inviato • Pausa ${seconds}s';
}
@override
String cooldownNotSent(String seconds) {
return 'Non inviato • Pausa ${seconds}s';
}
@override
String get notSent => 'Non inviato';
@override
String get copyTooltip => 'Copia';
@override
String get codeCopiedSnackbar => 'Codice copiato negli appunti';
@override
String get resendToPcTooltip => 'Invia di nuovo al PC';
@override
String frozenFrameCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: 'Frame bloccato • $count codici',
one: 'Frame bloccato • 1 codice',
);
return '$_temp0';
}
@override
String get resumeButton => 'Riprendi';
@override
String get tapCodeToSend => 'Tocca un codice per inviarlo al PC';
@override
String get newScanButton => 'Nuova scansione';
@override
String get sentLabel => 'Inviato';
@override
String get sendLabel => 'Invia';
@override
String get clearHistoryTitle => 'Cancellare Cronologia?';
@override
String get clearHistoryMessage =>
'Tutti i codici salvati nella cronologia su questo dispositivo verranno rimossi.';
@override
String get clearAllButton => 'Cancella Tutto';
@override
String get scanHistoryTitle => 'Cronologia Scansioni';
@override
String get clearHistoryTooltip => 'Cancella cronologia';
@override
String get searchCodesHint => 'Cerca tra i codici...';
@override
String get noScansInHistory => 'Nessuna scansione in memoria';
@override
String noResultsForQuery(String query) {
return 'Nessun risultato per \"$query\"';
}
@override
String get copyCodeTooltip => 'Copia codice';
@override
String get copiedToClipboardSnackbar => 'Copiato negli appunti';
@override
String resentCodeSnackbar(String code) {
return 'Inviato \"$code\" al PC';
}
@override
String get settingsTitle => 'Impostazioni';
@override
String get sectionPlanSubscription => 'PIANO & ABBONAMENTO';
@override
String get premiumPlanActive => 'Piano Premium Attivo';
@override
String get freeBaseVersion => 'Versione Base Gratuita';
@override
String get unlimitedAndAdFree => 'Scansioni illimitate e zero pubblicità';
@override
String activeSessionLabel(String time) {
return 'Sessione attiva: $time';
}
@override
String freeScansRemaining(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count scansioni libere rimanenti',
one: '1 scansione libera rimanente',
);
return '$_temp0';
}
@override
String get manageButton => 'Gestisci';
@override
String get upgradePremiumShort => 'Passa a Premium';
@override
String get restorePurchasesTitle => 'Ripristina Acquisti';
@override
String get restorePurchasesSubtitle =>
'Hai già acquistato su un altro dispositivo o reinstallato?';
@override
String get restorePurchasesSuccess => 'Acquisti ripristinati con successo!';
@override
String get restorePurchasesEmpty =>
'Nessun acquisto attivo trovato da ripristinare.';
@override
String get sectionPcConnection => 'CONNESSIONE PC & NEGOZIO';
@override
String get workstationStatusTitle => 'Stato Postazione';
@override
String connectedToName(String name) {
return 'Connesso a $name';
}
@override
String notConnectedWithIp(String ip) {
return 'Non connesso ($ip)';
}
@override
String get noPcConfigured => 'Nessun PC configurato';
@override
String get favoriteWorkstationsTitle => 'Postazioni PC Preferite';
@override
String registeredComputersCount(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count computer registrati nel negozio',
one: '1 computer registrato nel negozio',
);
return '$_temp0';
}
@override
String get noComputersSaved => 'Nessun computer salvato';
@override
String get autoConnectFullTitle => 'Autocollegamento all\'avvio/risveglio';
@override
String get autoConnectFullSubtitle =>
'Disattivato: chiede sempre a quale PC connettersi (evita di sparare codici sul PC del collega)';
@override
String get inactivityDisconnectTitle => 'Disconnessione per inattività';
@override
String inactivityDisconnectActive(int minutes) {
return 'Interrompe la connessione dopo $minutes minuti senza scansioni';
}
@override
String get inactivityDisconnectOff => 'Disattivata (rimane sempre connesso)';
@override
String get inactivity5Min => '5 min (Consigliato)';
@override
String get inactivity10Min => '10 min';
@override
String get inactivity15Min => '15 min';
@override
String get disabledOption => 'Disattivata';
@override
String get sendTypingTestTitle => 'Invia Test di Digitazione';
@override
String get sendTypingTestSubtitle =>
'Digita \"TEST-CATELLI-123\" sul PC attivo';
@override
String get typingTestSentSnackbar => 'Test di digitazione inviato al PC!';
@override
String get sectionKeyboardEmulation => 'EMULAZIONE TASTIERA PC';
@override
String get suffixEnterTitle => 'Tasto Invio (Enter)';
@override
String get suffixEnterSubtitle =>
'Preme Invio dopo ogni codice (consigliato per Excel, ERP, gestionali)';
@override
String get suffixTabTitle => 'Tasto Tabulatore (Tab)';
@override
String get suffixTabSubtitle => 'Sposta il cursore al campo/cella successiva';
@override
String get suffixNoneTitle => 'Nessun tasto finale';
@override
String get suffixNoneSubtitle =>
'Scrive solo la stringa pura del codice a barre';
@override
String get sectionScanFeedback => 'SCANSIONE E FEEDBACK';
@override
String get aimModeTitle => 'Modalità di mira';
@override
String get aimModeSubtitle =>
'Standard, Precisione (mirino + zoom) o AR Multi-Codice';
@override
String get postScanPauseTitle => 'Pausa dopo scansione';
@override
String postScanPauseSubtitle(String seconds) {
return 'Attesa di ${seconds}s prima della prossima lettura';
}
@override
String get cooldown1s => '1,0 sec (Rapida)';
@override
String get cooldown2s => '2,0 sec';
@override
String get cooldown25s => '2,5 sec (Consigliata)';
@override
String get cooldown3s => '3,0 sec';
@override
String get cooldown4s => '4,0 sec';
@override
String get cooldown5s => '5,0 sec';
@override
String get continuousScanTitle => 'Scansione Continua';
@override
String get continuousScanSubtitle =>
'Riduce la pausa a 1,0s quando inquadri codici diversi in serie';
@override
String get vibrationTitle => 'Vibrazione alla lettura';
@override
String get vibrationSubtitle => 'Feedback aptico alla decodifica del codice';
@override
String get soundTitle => 'Suono di conferma';
@override
String get soundSubtitle => 'Segnale acustico alla lettura del barcode';
@override
String get sectionLanguage => 'LINGUA';
@override
String get languageTitle => 'Lingua App';
@override
String get languageSystem => 'Predefinita di sistema';
@override
String get languageItalian => 'Italiano';
@override
String get languageEnglish => 'English';
@override
String get sectionInfo => 'INFORMAZIONI';
@override
String get organizationTitle => 'Organizzazione';
@override
String get appVersionTitle => 'Versione App';
@override
String get paywallTitle => 'Barcode Reader Premium';
@override
String get paywallSubtitle =>
'Sblocca scansioni illimitate verso il PC senza alcuna interruzione.';
@override
String get paywallBenefitUnlimited =>
'Scansioni barcode e QR illimitate per sempre';
@override
String get paywallBenefitNoAds => 'Zero pubblicità e nessun timer di attesa';
@override
String get paywallBenefitAllModes =>
'Modalità Standard, Precisione e AR Multi-Codice';
@override
String get paywallBenefitMultiPc =>
'Postazioni multi-PC preferite e sincronizzazione Wi-Fi';
@override
String get paywallPlanYearly => 'Annuale';
@override
String get paywallPlanMonthly => 'Mensile';
@override
String get paywallPlanLifetime => 'A Vita (Lifetime)';
@override
String get paywallPerYear => '/ anno';
@override
String get paywallPerMonth => '/ mese';
@override
String get paywallOneTime => 'Acquisto una tantum';
@override
String get paywallBestValue => 'PIÙ CONVENIENTE';
@override
String paywallSavePercent(int percent) {
return 'RISPARMIA $percent%';
}
@override
String get paywallOneTimeBadge => 'PAGHI UNA VOLTA';
@override
String get paywallContinueButton => 'Continua';
@override
String paywallContinueWithPrice(String price) {
return 'Continua — $price';
}
@override
String get paywallLoadingPlans => 'Caricamento piani disponibili...';
@override
String get paywallUnavailableTitle => 'Piani momentaneamente non disponibili';
@override
String get paywallUnavailableSubtitle =>
'Verifica la connessione internet o la disponibilità di Google Play e riprova.';
@override
String get paywallRetryButton => 'Riprova';
@override
String get paywallPurchaseError =>
'Impossibile completare l\'acquisto. Riprova tra poco.';
@override
String get paywallLegalNote =>
'Gli abbonamenti si rinnovano automaticamente salvo disdetta almeno 24 ore prima della scadenza nelle impostazioni di Google Play.';
@override
String get premiumManageTitle => 'Premium Attivo';
@override
String get premiumManageBody =>
'Il tuo piano Premium Illimitato è attivo su questo account.\n\nPer gestire o disdire un abbonamento, apri Google Play Store → Pagamenti e abbonamenti → Abbonamenti.';
@override
String get closeButton => 'Chiudi';
}
+57 -7
View File
@@ -1,9 +1,13 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'core/l10n/l10n_extensions.dart';
import 'core/services/ad_service.dart';
import 'core/services/feedback_service.dart'; import 'core/services/feedback_service.dart';
import 'core/services/subscription_service.dart';
import 'core/theme/app_theme.dart'; import 'core/theme/app_theme.dart';
import 'features/connection/data/datasources/connection_local_datasource.dart'; import 'features/connection/data/datasources/connection_local_datasource.dart';
import 'features/connection/data/datasources/connection_remote_datasource.dart'; import 'features/connection/data/datasources/connection_remote_datasource.dart';
@@ -12,6 +16,7 @@ import 'features/connection/data/repositories/connection_repository_impl.dart';
import 'features/connection/domain/repositories/connection_repository.dart'; import 'features/connection/domain/repositories/connection_repository.dart';
import 'features/connection/presentation/cubit/connection_cubit.dart'; import 'features/connection/presentation/cubit/connection_cubit.dart';
import 'features/connection/presentation/cubit/discovery_cubit.dart'; import 'features/connection/presentation/cubit/discovery_cubit.dart';
import 'features/monetization/presentation/cubit/monetization_cubit.dart';
import 'features/scanner/data/datasources/scan_history_datasource.dart'; import 'features/scanner/data/datasources/scan_history_datasource.dart';
import 'features/scanner/data/repositories/scan_repository_impl.dart'; import 'features/scanner/data/repositories/scan_repository_impl.dart';
import 'features/scanner/domain/repositories/scan_repository.dart'; import 'features/scanner/domain/repositories/scan_repository.dart';
@@ -22,6 +27,7 @@ import 'features/settings/data/datasources/settings_local_datasource.dart';
import 'features/settings/data/repositories/settings_repository_impl.dart'; import 'features/settings/data/repositories/settings_repository_impl.dart';
import 'features/settings/domain/repositories/settings_repository.dart'; import 'features/settings/domain/repositories/settings_repository.dart';
import 'features/settings/presentation/cubit/settings_cubit.dart'; import 'features/settings/presentation/cubit/settings_cubit.dart';
import 'features/settings/presentation/cubit/settings_state.dart';
void main() async { void main() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
@@ -36,6 +42,19 @@ void main() async {
// Core services // Core services
const feedbackService = FeedbackService(); const feedbackService = FeedbackService();
final adService = AdService();
try {
await adService.initialize();
} catch (e) {
debugPrint('AdService init error: $e');
}
final subscriptionService = SubscriptionService();
try {
await subscriptionService.initialize();
} catch (e) {
debugPrint('SubscriptionService init error: $e');
}
// Repositories // Repositories
final SettingsRepository settingsRepository = SettingsRepositoryImpl( final SettingsRepository settingsRepository = SettingsRepositoryImpl(
@@ -58,6 +77,9 @@ void main() async {
connectionRepository: connectionRepository, connectionRepository: connectionRepository,
scanRepository: scanRepository, scanRepository: scanRepository,
feedbackService: feedbackService, feedbackService: feedbackService,
adService: adService,
subscriptionService: subscriptionService,
prefs: prefs,
), ),
); );
} }
@@ -67,6 +89,9 @@ class BarcodeReaderApp extends StatelessWidget {
final ConnectionRepository connectionRepository; final ConnectionRepository connectionRepository;
final ScanRepository scanRepository; final ScanRepository scanRepository;
final FeedbackService feedbackService; final FeedbackService feedbackService;
final AdService adService;
final SubscriptionService subscriptionService;
final SharedPreferences prefs;
const BarcodeReaderApp({ const BarcodeReaderApp({
super.key, super.key,
@@ -74,12 +99,22 @@ class BarcodeReaderApp extends StatelessWidget {
required this.connectionRepository, required this.connectionRepository,
required this.scanRepository, required this.scanRepository,
required this.feedbackService, required this.feedbackService,
required this.adService,
required this.subscriptionService,
required this.prefs,
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MultiBlocProvider( return MultiBlocProvider(
providers: [ providers: [
BlocProvider<MonetizationCubit>(
create: (_) => MonetizationCubit(
prefs: prefs,
adService: adService,
subscriptionService: subscriptionService,
),
),
BlocProvider<SettingsCubit>( BlocProvider<SettingsCubit>(
create: (_) => SettingsCubit(settingsRepository)..loadSettings(), create: (_) => SettingsCubit(settingsRepository)..loadSettings(),
), ),
@@ -101,13 +136,28 @@ class BarcodeReaderApp extends StatelessWidget {
), ),
), ),
], ],
child: MaterialApp( child: BlocBuilder<SettingsCubit, SettingsState>(
title: 'Catelli Barcode Reader', buildWhen: (prev, curr) =>
debugShowCheckedModeBanner: false, prev.settings.languageCode != curr.settings.languageCode,
themeMode: ThemeMode.dark, // Dark theme provides optimal contrast for scanner viewfinder builder: (context, settingsState) {
theme: AppTheme.lightTheme, return MaterialApp(
darkTheme: AppTheme.darkTheme, onGenerateTitle: (context) => context.l10n.appTitle,
home: const ScannerScreen(), debugShowCheckedModeBanner: false,
locale: settingsState.settings.locale,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
themeMode: ThemeMode
.dark, // Dark theme provides optimal contrast for scanner viewfinder
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
home: const ScannerScreen(),
);
},
), ),
); );
} }
@@ -8,11 +8,15 @@ import Foundation
import audioplayers_darwin import audioplayers_darwin
import device_info_plus import device_info_plus
import mobile_scanner import mobile_scanner
import purchases_flutter
import shared_preferences_foundation import shared_preferences_foundation
import webview_flutter_wkwebview
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin"))
PurchasesFlutterPlugin.register(with: registry.registrar(forPlugin: "PurchasesFlutterPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin"))
} }
+62 -1
View File
@@ -222,6 +222,11 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.0.0" version: "6.0.0"
flutter_localizations:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_test: flutter_test:
dependency: "direct dev" dependency: "direct dev"
description: flutter description: flutter
@@ -232,6 +237,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
google_mobile_ads:
dependency: "direct main"
description:
name: google_mobile_ads
sha256: "439e018d73b47565d1cf21410e893a8f46d5fb95110c41c266a6fb78449d7106"
url: "https://pub.dev"
source: hosted
version: "9.2.0"
hooks: hooks:
dependency: transitive dependency: transitive
description: description:
@@ -256,6 +269,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.1.2" version: "4.1.2"
intl:
dependency: "direct main"
description:
name: intl
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
url: "https://pub.dev"
source: hosted
version: "0.20.3"
jni: jni:
dependency: transitive dependency: transitive
description: description:
@@ -464,6 +485,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.1" version: "2.2.1"
purchases_flutter:
dependency: "direct main"
description:
name: purchases_flutter
sha256: "273a98e9fe3d6a763c9c23ef1fc466b055311d40c3c87b09aef605ec398fd85f"
url: "https://pub.dev"
source: hosted
version: "11.0.3"
record_use: record_use:
dependency: transitive dependency: transitive
description: description:
@@ -661,6 +690,38 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.3" version: "3.0.3"
webview_flutter:
dependency: transitive
description:
name: webview_flutter
sha256: d53e1ccf5516f25017e3c9d44c39034db352d20fa34fe200674270242c2c5111
url: "https://pub.dev"
source: hosted
version: "4.14.1"
webview_flutter_android:
dependency: transitive
description:
name: webview_flutter_android
sha256: "4de8b3d1ff4ebe1bdb42e68a5e4f809194a3cb0117a8f495f590004f00da3964"
url: "https://pub.dev"
source: hosted
version: "4.14.1"
webview_flutter_platform_interface:
dependency: transitive
description:
name: webview_flutter_platform_interface
sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04"
url: "https://pub.dev"
source: hosted
version: "2.15.1"
webview_flutter_wkwebview:
dependency: transitive
description:
name: webview_flutter_wkwebview
sha256: acac45e0a8d7beb1d0805521f44842f406c46eb5a69410f53d935e3c62138afc
url: "https://pub.dev"
source: hosted
version: "3.27.2"
win32: win32:
dependency: transitive dependency: transitive
description: description:
@@ -695,4 +756,4 @@ packages:
version: "3.1.4" version: "3.1.4"
sdks: sdks:
dart: ">=3.13.4 <4.0.0" dart: ">=3.13.4 <4.0.0"
flutter: ">=3.44.0" flutter: ">=3.47.0"
+7 -1
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 1.0.1+2 version: 1.1.0+12
environment: environment:
sdk: ^3.13.4 sdk: ^3.13.4
@@ -30,6 +30,9 @@ environment:
dependencies: dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
flutter_localizations:
sdk: flutter
intl: any
# The following adds the Cupertino Icons font to your application. # The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons. # Use with the CupertinoIcons class for iOS style icons.
@@ -42,6 +45,8 @@ dependencies:
equatable: ^3.0.0 equatable: ^3.0.0
audioplayers: ^6.8.1 audioplayers: ^6.8.1
vibration: ^3.2.1 vibration: ^3.2.1
google_mobile_ads: ^9.2.0
purchases_flutter: ^11.0.3
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
@@ -59,6 +64,7 @@ dev_dependencies:
# The following section is specific to Flutter packages. # The following section is specific to Flutter packages.
flutter: flutter:
generate: true
# The following line ensures that the Material Icons font is # The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in # included with your application, so that you can use the icons in
+1
View File
@@ -307,6 +307,7 @@ void main() {
expect(find.text('Blocca frame (2 codici)'), findsOneWidget); expect(find.text('Blocca frame (2 codici)'), findsOneWidget);
expect(find.text('1x'), findsOneWidget); expect(find.text('1x'), findsOneWidget);
expect(find.text('1.5x'), findsOneWidget);
expect(find.text('2x'), findsOneWidget); expect(find.text('2x'), findsOneWidget);
expect(find.text('3x'), findsOneWidget); expect(find.text('3x'), findsOneWidget);
expect(find.text('Standard'), findsOneWidget); expect(find.text('Standard'), findsOneWidget);
+19
View File
@@ -1,7 +1,11 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:barcode_reader_app/main.dart'; import 'package:barcode_reader_app/main.dart';
import 'package:barcode_reader_app/l10n/generated/app_localizations.dart';
import 'package:barcode_reader_app/core/services/ad_service.dart';
import 'package:barcode_reader_app/core/services/feedback_service.dart'; import 'package:barcode_reader_app/core/services/feedback_service.dart';
import 'package:barcode_reader_app/core/services/subscription_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_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/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/datasources/udp_discovery_datasource.dart';
@@ -24,6 +28,8 @@ void main() {
); );
final scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs)); final scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
const feedbackService = FeedbackService(); const feedbackService = FeedbackService();
final adService = AdService();
final subscriptionService = SubscriptionService();
await tester.pumpWidget( await tester.pumpWidget(
BarcodeReaderApp( BarcodeReaderApp(
@@ -31,9 +37,22 @@ void main() {
connectionRepository: connectionRepo, connectionRepository: connectionRepo,
scanRepository: scanRepo, scanRepository: scanRepo,
feedbackService: feedbackService, feedbackService: feedbackService,
adService: adService,
subscriptionService: subscriptionService,
prefs: prefs,
), ),
); );
expect(find.byType(BarcodeReaderApp), findsOneWidget); expect(find.byType(BarcodeReaderApp), findsOneWidget);
}); });
test('Localization provides both Italian and English strings', () {
final it = lookupAppLocalizations(const Locale('it'));
final en = lookupAppLocalizations(const Locale('en'));
expect(it.settingsTitle, 'Impostazioni');
expect(en.settingsTitle, 'Settings');
expect(it.scanPcQrCode, 'Inquadra QR Code sul PC');
expect(en.scanPcQrCode, 'Scan QR Code on PC');
});
} }
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
SRC_DIR="/tmp/barcode-src"
OUT_APPIMAGE="/workspace/BarcodeServer-x86_64.AppImage"
rm -rf "${SRC_DIR}"
mkdir -p "${SRC_DIR}/server"
tar -C /workspace/server \
--exclude='./venv' \
--exclude='./venv_unix' \
--exclude='./venv_win' \
--exclude='./build' \
--exclude='./dist' \
--exclude='./__pycache__' \
--exclude='./.DS_Store' \
-cf - . | tar -C "${SRC_DIR}/server" -xf -
cd "${SRC_DIR}"
BUILD_ARGS=(server/build_binary.py --onedir --windowed --appdir)
if [ -n "${APP_VERSION:-}" ]; then
BUILD_ARGS+=(--version "${APP_VERSION}")
fi
python "${BUILD_ARGS[@]}"
ARCH=x86_64 appimagetool \
"${SRC_DIR}/server/dist/BarcodeServer.AppDir" \
"${OUT_APPIMAGE}"
chmod +x "${OUT_APPIMAGE}"
APPIMAGE_EXTRACT_AND_RUN=1 "${OUT_APPIMAGE}" --version
if [ -n "${HOST_UID:-}" ] && [ -n "${HOST_GID:-}" ]; then
chown "${HOST_UID}:${HOST_GID}" "${OUT_APPIMAGE}"
fi
+63
View File
@@ -0,0 +1,63 @@
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
binutils \
build-essential \
ca-certificates \
curl \
file \
libdbus-1-3 \
libegl1 \
libfontconfig1 \
libgl1 \
libglib2.0-0 \
libx11-6 \
libxcb-cursor0 \
libxcb-icccm4 \
libxcb-image0 \
libxcb-keysyms1 \
libxcb-randr0 \
libxcb-render-util0 \
libxcb-shape0 \
libxcb-xinerama0 \
libxcb-xkb1 \
libxkbcommon0 \
libxkbcommon-x11-0 \
libxtst6 \
patchelf \
python3 \
python3-dev \
python3-pip \
python3-venv \
tar \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
# Pre-crea il venv Python e installa le dipendenze in cache layer Docker
RUN python3 -m venv /opt/venv
ENV VIRTUAL_ENV="/opt/venv"
ENV PATH="/opt/venv/bin:${PATH}"
COPY server/requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir -r /tmp/requirements.txt pyinstaller \
&& rm -f /tmp/requirements.txt
# Estrae appimagetool per funzionare senza FUSE dentro Docker
RUN curl -fsSL -o /tmp/appimagetool.AppImage \
https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage \
&& chmod +x /tmp/appimagetool.AppImage \
&& cd /opt \
&& /tmp/appimagetool.AppImage --appimage-extract \
&& mv /opt/squashfs-root /opt/appimagetool \
&& ln -s /opt/appimagetool/AppRun /usr/local/bin/appimagetool \
&& rm -f /tmp/appimagetool.AppImage
COPY docker/build-linux-appimage.sh /usr/local/bin/build-linux-appimage.sh
RUN chmod +x /usr/local/bin/build-linux-appimage.sh
WORKDIR /workspace
ENTRYPOINT ["/usr/local/bin/build-linux-appimage.sh"]
+53
View File
@@ -29,10 +29,61 @@ HIDDEN_IMPORTS = [
"qrcode", "qrcode",
"aiohttp", "aiohttp",
"pynput", "pynput",
"pynput._info",
"pynput._util",
"pynput.keyboard",
"pynput.keyboard._base",
"pynput.mouse",
"pynput.mouse._base",
"pyperclip", "pyperclip",
"certifi", "certifi",
] ]
PLATFORM_HIDDEN_IMPORTS = {
"Linux": [
"pynput.keyboard._xorg",
"pynput.mouse._xorg",
"pynput._util.xorg",
"pynput._util.xorg_keysyms",
"pynput._util.uinput",
"pynput.keyboard._uinput",
"pynput.keyboard._dummy",
"pynput.mouse._dummy",
"Xlib",
"Xlib.display",
"Xlib.ext",
"Xlib.ext.xtest",
"Xlib.XK",
"Xlib.X",
"Xlib.protocol",
"Xlib.protocol.display",
"Xlib.protocol.event",
"Xlib.protocol.request",
"Xlib.protocol.rq",
"Xlib.protocol.structs",
"Xlib.keysymdef",
"Xlib.keysymdef.xkb",
"Xlib.keysymdef.latin1",
"Xlib.keysymdef.miscellany",
],
"Windows": [
"pynput.keyboard._win32",
"pynput.mouse._win32",
"pynput._util.win32",
"pynput._util.win32_vks",
"pynput.keyboard._dummy",
"pynput.mouse._dummy",
],
"Darwin": [
"pynput.keyboard._darwin",
"pynput.mouse._darwin",
"pynput._util.darwin",
"pynput._util.darwin_vks",
"pynput.keyboard._dummy",
"pynput.mouse._dummy",
],
}
EXCLUDED_MODULES = [ EXCLUDED_MODULES = [
"tkinter", "tkinter",
"_tkinter", "_tkinter",
@@ -232,6 +283,8 @@ def build(
for hidden_import in HIDDEN_IMPORTS: for hidden_import in HIDDEN_IMPORTS:
cmd.append(f"--hidden-import={hidden_import}") cmd.append(f"--hidden-import={hidden_import}")
for platform_hidden in PLATFORM_HIDDEN_IMPORTS.get(system, []):
cmd.append(f"--hidden-import={platform_hidden}")
for excluded in EXCLUDED_MODULES: for excluded in EXCLUDED_MODULES:
cmd.append(f"--exclude-module={excluded}") cmd.append(f"--exclude-module={excluded}")
+1
View File
@@ -52,6 +52,7 @@ DEFAULT_CONFIG = {
"log_history": True, "log_history": True,
"check_updates": True, # Check for app updates on startup "check_updates": True, # Check for app updates on startup
"update_url": "", # Optional custom release metadata URL "update_url": "", # Optional custom release metadata URL
"language": "auto", # "auto", "it", "en"
} }
+122 -89
View File
@@ -15,6 +15,7 @@ from PySide6.QtWidgets import (
QApplication, QApplication,
QButtonGroup, QButtonGroup,
QCheckBox, QCheckBox,
QComboBox,
QDialog, QDialog,
QFormLayout, QFormLayout,
QFrame, QFrame,
@@ -39,6 +40,7 @@ from PySide6.QtWidgets import (
from autostart import is_autostart_enabled, set_autostart from autostart import is_autostart_enabled, set_autostart
from config import load_config from config import load_config
from i18n import get_language, set_language, tr
from server_core import BarcodeServerCore, generate_qr_image from server_core import BarcodeServerCore, generate_qr_image
from tray import ServerTrayIcon, load_app_icon from tray import ServerTrayIcon, load_app_icon
from updater import ( from updater import (
@@ -90,7 +92,7 @@ QFrame#Card {
border: 1px solid #334155; border: 1px solid #334155;
border-radius: 12px; border-radius: 12px;
} }
QLineEdit, QTextEdit { QLineEdit, QTextEdit, QComboBox {
background-color: #0F172A; background-color: #0F172A;
color: #F8FAFC; color: #F8FAFC;
border: 1px solid #475569; border: 1px solid #475569;
@@ -98,6 +100,11 @@ QLineEdit, QTextEdit {
padding: 7px 10px; padding: 7px 10px;
selection-background-color: #0284C7; selection-background-color: #0284C7;
} }
QComboBox QAbstractItemView {
background-color: #1E293B;
color: #F8FAFC;
selection-background-color: #0284C7;
}
QLineEdit:focus, QTextEdit:focus { QLineEdit:focus, QTextEdit:focus {
border-color: #38BDF8; border-color: #38BDF8;
} }
@@ -234,7 +241,7 @@ class UpdateDialog(QDialog):
self.on_ready_to_exit = on_ready_to_exit self.on_ready_to_exit = on_ready_to_exit
self._download_worker: Optional[_UpdateDownloadWorker] = None self._download_worker: Optional[_UpdateDownloadWorker] = None
self.setWindowTitle(f"Aggiornamento Disponibile — v{release.version}") self.setWindowTitle(tr("update_win_title", version=release.version))
self.setMinimumWidth(480) self.setMinimumWidth(480)
self.setStyleSheet(DARK_STYLESHEET) self.setStyleSheet(DARK_STYLESHEET)
@@ -242,16 +249,18 @@ class UpdateDialog(QDialog):
layout.setContentsMargins(20, 20, 20, 20) layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(12) layout.setSpacing(12)
title_lbl = QLabel(f"Nuova versione disponibile: v{release.version}") title_lbl = QLabel(tr("update_new_version", version=release.version))
title_lbl.setStyleSheet("font-size: 16px; font-weight: 700; color: #38BDF8;") title_lbl.setStyleSheet("font-size: 16px; font-weight: 700; color: #38BDF8;")
layout.addWidget(title_lbl) layout.addWidget(title_lbl)
subtitle_lbl = QLabel(f"Versione installata: v{APP_VERSION} • {release.title}") subtitle_lbl = QLabel(
tr("update_installed_sub", version=APP_VERSION, title=release.title)
)
subtitle_lbl.setStyleSheet("color: #94A3B8;") subtitle_lbl.setStyleSheet("color: #94A3B8;")
subtitle_lbl.setWordWrap(True) subtitle_lbl.setWordWrap(True)
layout.addWidget(subtitle_lbl) layout.addWidget(subtitle_lbl)
notes_text = (release.notes or "").strip() or "Nessuna nota di rilascio specificata." notes_text = (release.notes or "").strip() or tr("update_no_notes")
self.notes_box = QTextEdit() self.notes_box = QTextEdit()
self.notes_box.setReadOnly(True) self.notes_box.setReadOnly(True)
self.notes_box.setMinimumHeight(140) self.notes_box.setMinimumHeight(140)
@@ -263,14 +272,12 @@ class UpdateDialog(QDialog):
self.status_lbl.setWordWrap(True) self.status_lbl.setWordWrap(True)
self.status_lbl.setStyleSheet("color: #94A3B8; font-size: 12px;") self.status_lbl.setStyleSheet("color: #94A3B8; font-size: 12px;")
if self.asset is None: if self.asset is None:
self.status_lbl.setText( self.status_lbl.setText(tr("update_no_asset"))
"Nessun pacchetto specifico trovato per questa piattaforma negli asset della release."
)
elif not self.can_auto: elif not self.can_auto:
self.status_lbl.setText(self.auto_reason) self.status_lbl.setText(self.auto_reason)
else: else:
size_mb = f" ({self.asset.size / (1024 * 1024):.1f} MB)" if self.asset.size > 0 else "" size_mb = f" ({self.asset.size / (1024 * 1024):.1f} MB)" if self.asset.size > 0 else ""
self.status_lbl.setText(f"Pacchetto pronto per l'installazione: {self.asset.name}{size_mb}") self.status_lbl.setText(tr("update_ready_pkg", name=self.asset.name, size=size_mb))
layout.addWidget(self.status_lbl) layout.addWidget(self.status_lbl)
self.progress_bar = QProgressBar() self.progress_bar = QProgressBar()
@@ -278,17 +285,17 @@ class UpdateDialog(QDialog):
layout.addWidget(self.progress_bar) layout.addWidget(self.progress_bar)
btn_row = QHBoxLayout() btn_row = QHBoxLayout()
self.btn_later = QPushButton("Più Tardi") self.btn_later = QPushButton(tr("btn_later"))
self.btn_later.clicked.connect(self.reject) self.btn_later.clicked.connect(self.reject)
btn_row.addWidget(self.btn_later) btn_row.addWidget(self.btn_later)
self.btn_browser = QPushButton("Apri Pagina Release") self.btn_browser = QPushButton(tr("btn_open_release_page"))
self.btn_browser.clicked.connect(self._open_release_page) self.btn_browser.clicked.connect(self._open_release_page)
btn_row.addWidget(self.btn_browser) btn_row.addWidget(self.btn_browser)
btn_row.addStretch(1) btn_row.addStretch(1)
self.btn_install = QPushButton("Aggiorna e Riavvia") self.btn_install = QPushButton(tr("btn_update_restart"))
self.btn_install.setObjectName("PrimaryBtn") self.btn_install.setObjectName("PrimaryBtn")
can_run_auto = self.can_auto and self.asset is not None can_run_auto = self.can_auto and self.asset is not None
self.btn_install.setVisible(can_run_auto) self.btn_install.setVisible(can_run_auto)
@@ -311,7 +318,7 @@ class UpdateDialog(QDialog):
self.btn_browser.setEnabled(False) self.btn_browser.setEnabled(False)
self.progress_bar.setVisible(True) self.progress_bar.setVisible(True)
self.progress_bar.setRange(0, 0) self.progress_bar.setRange(0, 0)
self.status_lbl.setText(f"Scaricamento di {self.asset.name}...") self.status_lbl.setText(tr("update_downloading", name=self.asset.name))
self._download_worker = _UpdateDownloadWorker(self.asset, self) self._download_worker = _UpdateDownloadWorker(self.asset, self)
self._download_worker.progress.connect(self._on_download_progress) self._download_worker.progress.connect(self._on_download_progress)
@@ -325,18 +332,25 @@ class UpdateDialog(QDialog):
self.progress_bar.setRange(0, 100) self.progress_bar.setRange(0, 100)
self.progress_bar.setValue(percent) self.progress_bar.setValue(percent)
self.status_lbl.setText( self.status_lbl.setText(
f"Scaricamento: {downloaded / (1024 * 1024):.1f} / {total / (1024 * 1024):.1f} MB ({percent}%)" tr(
"update_downloading_pct",
done=downloaded / (1024 * 1024),
total=total / (1024 * 1024),
percent=percent,
)
) )
else: else:
self.status_lbl.setText(f"Scaricati {downloaded / (1024 * 1024):.1f} MB...") self.status_lbl.setText(
tr("update_downloading_mb", done=downloaded / (1024 * 1024))
)
def _on_download_completed(self, path_obj: object) -> None: def _on_download_completed(self, path_obj: object) -> None:
downloaded_path = Path(path_obj) downloaded_path = Path(path_obj)
self.status_lbl.setText("Installazione aggiornamento e riavvio in corso...") self.status_lbl.setText(tr("update_installing"))
try: try:
apply_downloaded_update(downloaded_path) apply_downloaded_update(downloaded_path)
except Exception as exc: except Exception as exc:
self._on_download_failed(f"Errore avvio aggiornamento: {exc}") self._on_download_failed(tr("update_apply_error", error=exc))
return return
self.accept() self.accept()
self.on_ready_to_exit() self.on_ready_to_exit()
@@ -346,8 +360,8 @@ class UpdateDialog(QDialog):
self.btn_install.setEnabled(True) self.btn_install.setEnabled(True)
self.btn_later.setEnabled(True) self.btn_later.setEnabled(True)
self.btn_browser.setEnabled(True) self.btn_browser.setEnabled(True)
self.status_lbl.setText(f"Errore: {error_msg}") self.status_lbl.setText(tr("update_error_prefix", error=error_msg))
QMessageBox.critical(self, "Errore Aggiornamento", error_msg) QMessageBox.critical(self, tr("update_error_title"), error_msg)
class ServerAppGUI(QMainWindow): class ServerAppGUI(QMainWindow):
@@ -357,6 +371,7 @@ class ServerAppGUI(QMainWindow):
super().__init__() super().__init__()
self.server = server self.server = server
self.config = load_config() self.config = load_config()
set_language(self.config.get("language", "auto"))
self._quitting = False self._quitting = False
self._update_worker: Optional[_UpdateCheckWorker] = None self._update_worker: Optional[_UpdateCheckWorker] = None
self._pending_update: Optional[UpdateCheckResult] = None self._pending_update: Optional[UpdateCheckResult] = None
@@ -410,16 +425,14 @@ class ServerAppGUI(QMainWindow):
title_box.setSpacing(2) title_box.setSpacing(2)
title_lbl = QLabel("Barcode Reader PC Server") title_lbl = QLabel("Barcode Reader PC Server")
title_lbl.setStyleSheet("font-size: 20px; font-weight: 700; color: #38BDF8;") title_lbl.setStyleSheet("font-size: 20px; font-weight: 700; color: #38BDF8;")
subtitle_lbl = QLabel( subtitle_lbl = QLabel(tr("app_subtitle", version=APP_VERSION))
f"Ricezione codici a barre da Smartphone • Catelli Srl • v{APP_VERSION}"
)
subtitle_lbl.setStyleSheet("color: #94A3B8; font-size: 12px;") subtitle_lbl.setStyleSheet("color: #94A3B8; font-size: 12px;")
title_box.addWidget(title_lbl) title_box.addWidget(title_lbl)
title_box.addWidget(subtitle_lbl) title_box.addWidget(subtitle_lbl)
header_layout.addLayout(title_box) header_layout.addLayout(title_box)
header_layout.addStretch(1) header_layout.addStretch(1)
self.btn_update_banner = QPushButton("Aggiornamento disponibile") self.btn_update_banner = QPushButton(tr("update_available_btn"))
self.btn_update_banner.setObjectName("UpdateBannerBtn") self.btn_update_banner.setObjectName("UpdateBannerBtn")
self.btn_update_banner.setVisible(False) self.btn_update_banner.setVisible(False)
self.btn_update_banner.clicked.connect(self._open_pending_update_dialog) self.btn_update_banner.clicked.connect(self._open_pending_update_dialog)
@@ -441,8 +454,8 @@ class ServerAppGUI(QMainWindow):
self.tabs = QTabWidget() self.tabs = QTabWidget()
self.tab_dashboard = QWidget() self.tab_dashboard = QWidget()
self.tab_settings = QWidget() self.tab_settings = QWidget()
self.tabs.addTab(self.tab_dashboard, "Dashboard & Dispositivi") self.tabs.addTab(self.tab_dashboard, tr("tab_dashboard"))
self.tabs.addTab(self.tab_settings, "Impostazioni") self.tabs.addTab(self.tab_settings, tr("tab_settings"))
root_layout.addWidget(self.tabs, stretch=1) root_layout.addWidget(self.tabs, stretch=1)
self._build_dashboard_tab() self._build_dashboard_tab()
@@ -467,7 +480,7 @@ class ServerAppGUI(QMainWindow):
qr_layout = QVBoxLayout(qr_card) qr_layout = QVBoxLayout(qr_card)
qr_layout.setContentsMargins(18, 16, 18, 16) qr_layout.setContentsMargins(18, 16, 18, 16)
qr_layout.setSpacing(10) qr_layout.setSpacing(10)
qr_title = QLabel("CONNESSIONE RAPIDA (QR)") qr_title = QLabel(tr("card_qr_title"))
qr_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;") qr_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;")
qr_layout.addWidget(qr_title) qr_layout.addWidget(qr_title)
@@ -481,7 +494,7 @@ class ServerAppGUI(QMainWindow):
qr_wrapper_layout.addWidget(self.qr_label, alignment=Qt.AlignmentFlag.AlignCenter) qr_wrapper_layout.addWidget(self.qr_label, alignment=Qt.AlignmentFlag.AlignCenter)
qr_layout.addWidget(qr_wrapper, alignment=Qt.AlignmentFlag.AlignCenter) qr_layout.addWidget(qr_wrapper, alignment=Qt.AlignmentFlag.AlignCenter)
qr_hint = QLabel("Inquadra con l'app Android/iOS") qr_hint = QLabel(tr("qr_hint"))
qr_hint.setStyleSheet("color: #64748B; font-size: 12px;") qr_hint.setStyleSheet("color: #64748B; font-size: 12px;")
qr_hint.setAlignment(Qt.AlignmentFlag.AlignCenter) qr_hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
qr_layout.addWidget(qr_hint) qr_layout.addWidget(qr_hint)
@@ -492,7 +505,7 @@ class ServerAppGUI(QMainWindow):
info_layout = QVBoxLayout(info_card) info_layout = QVBoxLayout(info_card)
info_layout.setContentsMargins(20, 16, 20, 16) info_layout.setContentsMargins(20, 16, 20, 16)
info_layout.setSpacing(12) info_layout.setSpacing(12)
info_title = QLabel("DETTAGLI SERVER") info_title = QLabel(tr("card_server_title"))
info_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;") info_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;")
info_layout.addWidget(info_title) info_layout.addWidget(info_title)
@@ -500,19 +513,19 @@ class ServerAppGUI(QMainWindow):
grid.setHorizontalSpacing(18) grid.setHorizontalSpacing(18)
grid.setVerticalSpacing(10) grid.setVerticalSpacing(10)
self.lbl_ip = self._add_info_row(grid, 0, "Indirizzo IP Locale:", self.server.local_ip, "#38BDF8") self.lbl_ip = self._add_info_row(grid, 0, tr("lbl_local_ip"), self.server.local_ip, "#38BDF8")
self.lbl_port = self._add_info_row(grid, 1, "Porta:", str(self.server.port)) self.lbl_port = self._add_info_row(grid, 1, tr("lbl_port"), str(self.server.port))
self.lbl_name = self._add_info_row(grid, 2, "Nome PC:", self.server.server_name) self.lbl_name = self._add_info_row(grid, 2, tr("lbl_pc_name"), self.server.server_name)
pin_text = self.config.get("pin", "") or "Nessuno (Libero)" pin_text = self.config.get("pin", "") or tr("pin_none")
self.lbl_pin = self._add_info_row(grid, 3, "PIN di Accesso:", pin_text) self.lbl_pin = self._add_info_row(grid, 3, tr("lbl_pin"), pin_text)
info_layout.addLayout(grid) info_layout.addLayout(grid)
info_layout.addStretch(1) info_layout.addStretch(1)
btn_row = QHBoxLayout() btn_row = QHBoxLayout()
btn_copy = QPushButton("Copia IP") btn_copy = QPushButton(tr("btn_copy_ip"))
btn_copy.setCursor(Qt.CursorShape.PointingHandCursor) btn_copy.setCursor(Qt.CursorShape.PointingHandCursor)
btn_copy.clicked.connect(self._copy_ip_to_clipboard) btn_copy.clicked.connect(self._copy_ip_to_clipboard)
btn_web = QPushButton("Apri Dashboard Web") btn_web = QPushButton(tr("btn_open_web"))
btn_web.setObjectName("PrimaryBtn") btn_web.setObjectName("PrimaryBtn")
btn_web.setCursor(Qt.CursorShape.PointingHandCursor) btn_web.setCursor(Qt.CursorShape.PointingHandCursor)
btn_web.clicked.connect(self.open_web_dashboard) btn_web.clicked.connect(self.open_web_dashboard)
@@ -529,9 +542,9 @@ class ServerAppGUI(QMainWindow):
dev_layout = QVBoxLayout(dev_card) dev_layout = QVBoxLayout(dev_card)
dev_layout.setContentsMargins(18, 12, 18, 12) dev_layout.setContentsMargins(18, 12, 18, 12)
dev_layout.setSpacing(4) dev_layout.setSpacing(4)
dev_title = QLabel("DISPOSITIVI CONNESSI") dev_title = QLabel(tr("card_devices_title"))
dev_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;") dev_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;")
self.lbl_devices = QLabel("Nessun dispositivo mobile collegato.") self.lbl_devices = QLabel(tr("no_devices_connected"))
self.lbl_devices.setStyleSheet("color: #64748B;") self.lbl_devices.setStyleSheet("color: #64748B;")
self.lbl_devices.setWordWrap(True) self.lbl_devices.setWordWrap(True)
dev_layout.addWidget(dev_title) dev_layout.addWidget(dev_title)
@@ -545,9 +558,9 @@ class ServerAppGUI(QMainWindow):
hist_layout.setSpacing(10) hist_layout.setSpacing(10)
hist_header = QHBoxLayout() hist_header = QHBoxLayout()
hist_title = QLabel("CRONOLOGIA SCANSIONI LIVE") hist_title = QLabel(tr("card_history_title"))
hist_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;") hist_title.setStyleSheet("font-size: 11px; font-weight: 700; color: #94A3B8;")
btn_clear = QPushButton("Pulisci Log") btn_clear = QPushButton(tr("btn_clear_log"))
btn_clear.setCursor(Qt.CursorShape.PointingHandCursor) btn_clear.setCursor(Qt.CursorShape.PointingHandCursor)
btn_clear.clicked.connect(self._clear_scan_log) btn_clear.clicked.connect(self._clear_scan_log)
hist_header.addWidget(hist_title) hist_header.addWidget(hist_title)
@@ -556,7 +569,9 @@ class ServerAppGUI(QMainWindow):
hist_layout.addLayout(hist_header) hist_layout.addLayout(hist_header)
self.table = QTableWidget(0, 4) self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(["Ora", "Dispositivo", "Codice Letto", "Esito"]) self.table.setHorizontalHeaderLabels(
[tr("col_time"), tr("col_device"), tr("col_code"), tr("col_status")]
)
self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
self.table.setAlternatingRowColors(True) self.table.setAlternatingRowColors(True)
@@ -596,7 +611,7 @@ class ServerAppGUI(QMainWindow):
container.setContentsMargins(24, 22, 24, 22) container.setContentsMargins(24, 22, 24, 22)
container.setSpacing(14) container.setSpacing(14)
sec1 = QLabel("RETE E IDENTIFICAZIONE") sec1 = QLabel(tr("sec_network"))
sec1.setStyleSheet("font-size: 12px; font-weight: 700; color: #38BDF8;") sec1.setStyleSheet("font-size: 12px; font-weight: 700; color: #38BDF8;")
container.addWidget(sec1) container.addWidget(sec1)
@@ -606,32 +621,32 @@ class ServerAppGUI(QMainWindow):
self.inp_name = QLineEdit(self.config.get("server_name", socket.gethostname())) self.inp_name = QLineEdit(self.config.get("server_name", socket.gethostname()))
self.inp_pin = QLineEdit(self.config.get("pin", "")) self.inp_pin = QLineEdit(self.config.get("pin", ""))
self.inp_pin.setPlaceholderText("Lascia vuoto per accesso libero") self.inp_pin.setPlaceholderText(tr("placeholder_pin"))
self.inp_port = QLineEdit(str(self.config.get("port", 8765))) self.inp_port = QLineEdit(str(self.config.get("port", 8765)))
self.inp_port.setMaximumWidth(120) self.inp_port.setMaximumWidth(120)
port_row = QHBoxLayout() port_row = QHBoxLayout()
port_row.addWidget(self.inp_port) port_row.addWidget(self.inp_port)
port_hint = QLabel("(Il cambio porta richiede riavvio)") port_hint = QLabel(tr("port_restart_hint"))
port_hint.setStyleSheet("color: #64748B; font-size: 12px;") port_hint.setStyleSheet("color: #64748B; font-size: 12px;")
port_row.addWidget(port_hint) port_row.addWidget(port_hint)
port_row.addStretch(1) port_row.addStretch(1)
form.addRow("Nome visualizzato nell'app mobile:", self.inp_name) form.addRow(tr("lbl_mobile_name"), self.inp_name)
form.addRow("PIN di accesso (es. 4 cifre):", self.inp_pin) form.addRow(tr("lbl_pin_input"), self.inp_pin)
form.addRow("Porta Server WebSocket:", port_row) form.addRow(tr("lbl_ws_port"), port_row)
container.addLayout(form) container.addLayout(form)
sec2 = QLabel("COMPORTAMENTO TASTIERA") sec2 = QLabel(tr("sec_keyboard"))
sec2.setStyleSheet("font-size: 12px; font-weight: 700; color: #38BDF8; margin-top: 8px;") sec2.setStyleSheet("font-size: 12px; font-weight: 700; color: #38BDF8; margin-top: 8px;")
container.addWidget(sec2) container.addWidget(sec2)
self.grp_suffix = QButtonGroup(self) self.grp_suffix = QButtonGroup(self)
suffix_row = QHBoxLayout() suffix_row = QHBoxLayout()
suffix_row.addWidget(QLabel("Tasto finale dopo ogni scansione:")) suffix_row.addWidget(QLabel(tr("lbl_suffix")))
self.rb_suffix_enter = QRadioButton("Invio (Enter)") self.rb_suffix_enter = QRadioButton(tr("rb_suffix_enter"))
self.rb_suffix_tab = QRadioButton("Tabulatore (Tab)") self.rb_suffix_tab = QRadioButton(tr("rb_suffix_tab"))
self.rb_suffix_none = QRadioButton("Nessun tasto") self.rb_suffix_none = QRadioButton(tr("rb_suffix_none"))
self._suffix_map = { self._suffix_map = {
"enter": self.rb_suffix_enter, "enter": self.rb_suffix_enter,
"tab": self.rb_suffix_tab, "tab": self.rb_suffix_tab,
@@ -646,9 +661,9 @@ class ServerAppGUI(QMainWindow):
self.grp_mode = QButtonGroup(self) self.grp_mode = QButtonGroup(self)
mode_row = QHBoxLayout() mode_row = QHBoxLayout()
mode_row.addWidget(QLabel("Modalità di scrittura:")) mode_row.addWidget(QLabel(tr("lbl_typing_mode")))
self.rb_mode_type = QRadioButton("Digitazione tastiera reale (Consigliato)") self.rb_mode_type = QRadioButton(tr("rb_mode_type"))
self.rb_mode_paste = QRadioButton("Incolla da appunti (Ctrl+V / Cmd+V)") self.rb_mode_paste = QRadioButton(tr("rb_mode_paste"))
self._mode_map = {"type": self.rb_mode_type, "paste": self.rb_mode_paste} self._mode_map = {"type": self.rb_mode_type, "paste": self.rb_mode_paste}
for rb in self._mode_map.values(): for rb in self._mode_map.values():
self.grp_mode.addButton(rb) self.grp_mode.addButton(rb)
@@ -657,46 +672,50 @@ class ServerAppGUI(QMainWindow):
self._mode_map.get(self.config.get("mode", "type"), self.rb_mode_type).setChecked(True) self._mode_map.get(self.config.get("mode", "type"), self.rb_mode_type).setChecked(True)
container.addLayout(mode_row) container.addLayout(mode_row)
sec3 = QLabel("AVVIO AUTOMATICO, TRAY E AGGIORNAMENTI") sec3 = QLabel(tr("sec_system"))
sec3.setStyleSheet("font-size: 12px; font-weight: 700; color: #38BDF8; margin-top: 8px;") sec3.setStyleSheet("font-size: 12px; font-weight: 700; color: #38BDF8; margin-top: 8px;")
container.addWidget(sec3) container.addWidget(sec3)
self.chk_autostart = QCheckBox( self.chk_autostart = QCheckBox(tr("chk_autostart"))
"Avvia automaticamente all'avvio del sistema operativo (Login / Boot)"
)
self.chk_autostart.setChecked(is_autostart_enabled()) self.chk_autostart.setChecked(is_autostart_enabled())
container.addWidget(self.chk_autostart) container.addWidget(self.chk_autostart)
self.chk_tray = QCheckBox( self.chk_tray = QCheckBox(tr("chk_tray"))
"Alla chiusura (X) riduci nella System Tray invece di terminare"
)
self.chk_tray.setChecked(bool(self.config.get("minimize_to_tray", True))) self.chk_tray.setChecked(bool(self.config.get("minimize_to_tray", True)))
container.addWidget(self.chk_tray) container.addWidget(self.chk_tray)
self.chk_updates = QCheckBox( self.chk_updates = QCheckBox(tr("chk_updates"))
"Controlla automaticamente nuovi aggiornamenti all'avvio"
)
self.chk_updates.setChecked(bool(self.config.get("check_updates", True))) self.chk_updates.setChecked(bool(self.config.get("check_updates", True)))
container.addWidget(self.chk_updates) container.addWidget(self.chk_updates)
adv_form = QFormLayout() adv_form = QFormLayout()
adv_form.setHorizontalSpacing(18) adv_form.setHorizontalSpacing(18)
self.cmb_language = QComboBox()
self.cmb_language.addItem(tr("lang_auto"), "auto")
self.cmb_language.addItem(tr("lang_it"), "it")
self.cmb_language.addItem(tr("lang_en"), "en")
current_lang_pref = self.config.get("language", "auto")
lang_idx = self.cmb_language.findData(current_lang_pref)
if lang_idx >= 0:
self.cmb_language.setCurrentIndex(lang_idx)
adv_form.addRow(tr("lbl_language"), self.cmb_language)
self.inp_update_url = QLineEdit(self.config.get("update_url", "")) self.inp_update_url = QLineEdit(self.config.get("update_url", ""))
self.inp_update_url.setPlaceholderText("Vuoto = Gitea Releases (gitea.catelli.it)") self.inp_update_url.setPlaceholderText(tr("placeholder_update_url"))
adv_form.addRow("URL aggiornamento custom (opzionale):", self.inp_update_url) adv_form.addRow(tr("lbl_update_url"), self.inp_update_url)
container.addLayout(adv_form) container.addLayout(adv_form)
update_row = QHBoxLayout() update_row = QHBoxLayout()
self.btn_check_updates = QPushButton("Controlla Aggiornamenti Ora") self.btn_check_updates = QPushButton(tr("btn_check_updates"))
self.btn_check_updates.setCursor(Qt.CursorShape.PointingHandCursor) self.btn_check_updates.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_check_updates.clicked.connect(lambda: self.check_updates_async(manual=True)) self.btn_check_updates.clicked.connect(lambda: self.check_updates_async(manual=True))
self.lbl_update_status = QLabel(f"Versione installata: v{APP_VERSION}") self.lbl_update_status = QLabel(tr("installed_version", version=APP_VERSION))
self.lbl_update_status.setStyleSheet("color: #94A3B8; font-size: 12px;") self.lbl_update_status.setStyleSheet("color: #94A3B8; font-size: 12px;")
update_row.addWidget(self.btn_check_updates) update_row.addWidget(self.btn_check_updates)
update_row.addWidget(self.lbl_update_status, stretch=1) update_row.addWidget(self.lbl_update_status, stretch=1)
container.addLayout(update_row) container.addLayout(update_row)
btn_save = QPushButton("Salva ed Applica Impostazioni") btn_save = QPushButton(tr("btn_save_settings"))
btn_save.setObjectName("PrimaryBtn") btn_save.setObjectName("PrimaryBtn")
btn_save.setCursor(Qt.CursorShape.PointingHandCursor) btn_save.setCursor(Qt.CursorShape.PointingHandCursor)
btn_save.clicked.connect(self._save_settings_action) btn_save.clicked.connect(self._save_settings_action)
@@ -723,7 +742,7 @@ class ServerAppGUI(QMainWindow):
if clipboard is not None: if clipboard is not None:
clipboard.setText(self.server.local_ip) clipboard.setText(self.server.local_ip)
QMessageBox.information( QMessageBox.information(
self, "Copia", f"Indirizzo IP ({self.server.local_ip}) copiato negli appunti!" self, tr("msg_copy_title"), tr("msg_copy_body", ip=self.server.local_ip)
) )
def _clear_scan_log(self) -> None: def _clear_scan_log(self) -> None:
@@ -733,10 +752,10 @@ class ServerAppGUI(QMainWindow):
try: try:
port = int(self.inp_port.text().strip()) port = int(self.inp_port.text().strip())
if not (1 <= port <= 65535): if not (1 <= port <= 65535):
raise ValueError("Porta fuori intervallo") raise ValueError("Port out of range")
except ValueError: except ValueError:
QMessageBox.critical( QMessageBox.critical(
self, "Errore", "La porta deve essere un numero valido (es. 8765)." self, tr("msg_error_title"), tr("msg_port_invalid")
) )
return return
@@ -746,6 +765,8 @@ class ServerAppGUI(QMainWindow):
selected_mode = next( selected_mode = next(
(key for key, btn in self._mode_map.items() if btn.isChecked()), "type" (key for key, btn in self._mode_map.items() if btn.isChecked()), "type"
) )
selected_lang = self.cmb_language.currentData() or "auto"
prev_resolved_lang = get_language()
new_config = { new_config = {
"server_name": self.inp_name.text().strip() or socket.gethostname(), "server_name": self.inp_name.text().strip() or socket.gethostname(),
@@ -756,6 +777,7 @@ class ServerAppGUI(QMainWindow):
"minimize_to_tray": self.chk_tray.isChecked(), "minimize_to_tray": self.chk_tray.isChecked(),
"check_updates": self.chk_updates.isChecked(), "check_updates": self.chk_updates.isChecked(),
"update_url": self.inp_update_url.text().strip(), "update_url": self.inp_update_url.text().strip(),
"language": selected_lang,
} }
autostart_desired = self.chk_autostart.isChecked() autostart_desired = self.chk_autostart.isChecked()
@@ -764,16 +786,21 @@ class ServerAppGUI(QMainWindow):
self.server.update_settings(new_config) self.server.update_settings(new_config)
self.config = load_config() self.config = load_config()
new_resolved_lang = set_language(selected_lang)
self.tray.retranslate()
self.lbl_name.setText(self.server.server_name) self.lbl_name.setText(self.server.server_name)
pin_text = new_config["pin"] if new_config["pin"] else "Nessuno (Libero)" pin_text = new_config["pin"] if new_config["pin"] else tr("pin_none")
self.lbl_pin.setText(pin_text) self.lbl_pin.setText(pin_text)
self.lbl_port.setText(str(port)) self.lbl_port.setText(str(port))
self._refresh_qr_display() self._refresh_qr_display()
QMessageBox.information( msg_key = (
self, "Impostazioni", "Impostazioni salvate ed applicate con successo!" "msg_settings_saved_restart_lang"
if new_resolved_lang != prev_resolved_lang
else "msg_settings_saved"
) )
QMessageBox.information(self, tr("msg_settings_title"), tr(msg_key))
def toggle_listening(self) -> None: def toggle_listening(self) -> None:
new_state = not self.server.is_listening new_state = not self.server.is_listening
@@ -781,19 +808,19 @@ class ServerAppGUI(QMainWindow):
def _update_status_badge(self, is_listening: bool) -> None: def _update_status_badge(self, is_listening: bool) -> None:
if is_listening: if is_listening:
self.status_badge.setText("● IN ASCOLTO") self.status_badge.setText(tr("status_listening_badge"))
self.status_badge.setStyleSheet( self.status_badge.setStyleSheet(
"background-color: #064E3B; color: #10B981; border-radius: 6px;" "background-color: #064E3B; color: #10B981; border-radius: 6px;"
"padding: 6px 12px; font-weight: 700;" "padding: 6px 12px; font-weight: 700;"
) )
self.btn_toggle.setText("Metti in Pausa") self.btn_toggle.setText(tr("btn_pause"))
else: else:
self.status_badge.setText("○ IN PAUSA") self.status_badge.setText(tr("status_paused_badge"))
self.status_badge.setStyleSheet( self.status_badge.setStyleSheet(
"background-color: #451A03; color: #F59E0B; border-radius: 6px;" "background-color: #451A03; color: #F59E0B; border-radius: 6px;"
"padding: 6px 12px; font-weight: 700;" "padding: 6px 12px; font-weight: 700;"
) )
self.btn_toggle.setText("Riprendi Ricezione") self.btn_toggle.setText(tr("btn_resume"))
def _on_status_changed(self, is_listening: bool) -> None: def _on_status_changed(self, is_listening: bool) -> None:
self._update_status_badge(is_listening) self._update_status_badge(is_listening)
@@ -801,7 +828,7 @@ class ServerAppGUI(QMainWindow):
def _on_scan_received(self, code: str, source: str, success: bool) -> None: def _on_scan_received(self, code: str, source: str, success: bool) -> None:
timestamp = datetime.now().strftime("%H:%M:%S") timestamp = datetime.now().strftime("%H:%M:%S")
status_str = "Digitato ✓" if success else "Fallito ✗" status_str = tr("scan_typed") if success else tr("scan_failed")
status_color = QColor("#10B981") if success else QColor("#EF4444") status_color = QColor("#10B981") if success else QColor("#EF4444")
self.table.insertRow(0) self.table.insertRow(0)
@@ -817,10 +844,12 @@ class ServerAppGUI(QMainWindow):
def _on_devices_changed(self, devices: list[str]) -> None: def _on_devices_changed(self, devices: list[str]) -> None:
if not devices: if not devices:
self.lbl_devices.setText("Nessun dispositivo mobile collegato.") self.lbl_devices.setText(tr("no_devices_connected"))
self.lbl_devices.setStyleSheet("color: #64748B;") self.lbl_devices.setStyleSheet("color: #64748B;")
else: else:
self.lbl_devices.setText(f"{len(devices)} collegati: " + ", ".join(devices)) self.lbl_devices.setText(
tr("devices_connected_fmt", count=len(devices), devices=", ".join(devices))
)
self.lbl_devices.setStyleSheet("color: #10B981; font-weight: 600;") self.lbl_devices.setStyleSheet("color: #10B981; font-weight: 600;")
def check_updates_async(self, manual: bool = False) -> None: def check_updates_async(self, manual: bool = False) -> None:
@@ -830,7 +859,7 @@ class ServerAppGUI(QMainWindow):
if manual: if manual:
self.btn_check_updates.setEnabled(False) self.btn_check_updates.setEnabled(False)
self.lbl_update_status.setText("Ricerca aggiornamenti in corso...") self.lbl_update_status.setText(tr("checking_updates"))
update_url = self.inp_update_url.text().strip() if manual else self.config.get("update_url", "") update_url = self.inp_update_url.text().strip() if manual else self.config.get("update_url", "")
self._update_worker = _UpdateCheckWorker(APP_VERSION, update_url, manual, self) self._update_worker = _UpdateCheckWorker(APP_VERSION, update_url, manual, self)
@@ -839,27 +868,31 @@ class ServerAppGUI(QMainWindow):
def _on_update_check_finished(self, result: UpdateCheckResult, manual: bool) -> None: def _on_update_check_finished(self, result: UpdateCheckResult, manual: bool) -> None:
self.btn_check_updates.setEnabled(True) self.btn_check_updates.setEnabled(True)
self.lbl_update_status.setText(result.message or f"Versione installata: v{APP_VERSION}") self.lbl_update_status.setText(
result.message or tr("installed_version", version=APP_VERSION)
)
if result.status == "update_available" and result.release is not None: if result.status == "update_available" and result.release is not None:
self._pending_update = result self._pending_update = result
self.btn_update_banner.setText(f"Aggiorna a v{result.release.version}") self.btn_update_banner.setText(
tr("update_to_version_btn", version=result.release.version)
)
self.btn_update_banner.setVisible(True) self.btn_update_banner.setVisible(True)
if manual or self.isVisible(): if manual or self.isVisible():
self._show_update_dialog(result) self._show_update_dialog(result)
elif self._tray_available: elif self._tray_available:
self.tray.show_message( self.tray.show_message(
f"Aggiornamento disponibile (v{result.release.version})", tr("tray_update_title", version=result.release.version),
"Apri la finestra di Barcode Reader Server per installarlo automaticamente.", tr("tray_update_body"),
) )
return return
if manual: if manual:
if result.status == "up_to_date": if result.status == "up_to_date":
QMessageBox.information(self, "Aggiornamenti", result.message) QMessageBox.information(self, tr("updates_dialog_title"), result.message)
else: else:
QMessageBox.warning(self, "Controllo Aggiornamenti", result.message) QMessageBox.warning(self, tr("updates_check_title"), result.message)
def _open_pending_update_dialog(self) -> None: def _open_pending_update_dialog(self) -> None:
if self._pending_update and self._pending_update.release: if self._pending_update and self._pending_update.release:
+253
View File
@@ -0,0 +1,253 @@
"""Internationalization (i18n) helper for Barcode Reader PC Server (IT / EN)."""
from __future__ import annotations
import locale
import os
_CURRENT_LANG = "en"
TRANSLATIONS: dict[str, dict[str, str]] = {
"en": {
"app_subtitle": "Receive barcodes from Smartphone • Catelli Srl • v{version}",
"update_available_btn": "Update available",
"update_to_version_btn": "Update to v{version}",
"tab_dashboard": "Dashboard & Devices",
"tab_settings": "Settings",
"card_qr_title": "QUICK CONNECT (QR)",
"qr_hint": "Scan with the Android/iOS app",
"card_server_title": "SERVER DETAILS",
"lbl_local_ip": "Local IP Address:",
"lbl_port": "Port:",
"lbl_pc_name": "PC Name:",
"lbl_pin": "Access PIN:",
"pin_none": "None (Open)",
"btn_copy_ip": "Copy IP",
"btn_open_web": "Open Web Dashboard",
"card_devices_title": "CONNECTED DEVICES",
"no_devices_connected": "No mobile device connected.",
"devices_connected_fmt": "{count} connected: {devices}",
"card_history_title": "LIVE SCAN HISTORY",
"btn_clear_log": "Clear Log",
"col_time": "Time",
"col_device": "Device",
"col_code": "Scanned Code",
"col_status": "Status",
"scan_typed": "Typed ✓",
"scan_failed": "Failed ✗",
"status_listening_badge": "● LISTENING",
"status_paused_badge": "○ PAUSED",
"status_listening_short": "LISTENING",
"status_paused_short": "PAUSED",
"btn_pause": "Pause",
"btn_resume": "Resume Listening",
"sec_network": "NETWORK & IDENTIFICATION",
"lbl_mobile_name": "Name shown in mobile app:",
"lbl_pin_input": "Access PIN (e.g. 4 digits):",
"placeholder_pin": "Leave empty for open access",
"lbl_ws_port": "WebSocket Server Port:",
"port_restart_hint": "(Changing port requires restart)",
"sec_keyboard": "KEYBOARD BEHAVIOR",
"lbl_suffix": "Trailing key after each scan:",
"rb_suffix_enter": "Enter",
"rb_suffix_tab": "Tab",
"rb_suffix_none": "No key",
"lbl_typing_mode": "Input mode:",
"rb_mode_type": "Real keyboard typing (Recommended)",
"rb_mode_paste": "Paste from clipboard (Ctrl+V / Cmd+V)",
"sec_system": "AUTOSTART, TRAY, LANGUAGE & UPDATES",
"chk_autostart": "Start automatically at OS login (Autostart)",
"chk_tray": "Minimize to System Tray on close (X) instead of quitting",
"chk_updates": "Check for updates automatically on startup",
"lbl_language": "Interface language:",
"lang_auto": "System default (Auto)",
"lang_it": "Italiano",
"lang_en": "English",
"lbl_update_url": "Custom update URL (optional):",
"placeholder_update_url": "Empty = Gitea Releases (gitea.catelli.it)",
"btn_check_updates": "Check for Updates Now",
"installed_version": "Installed version: v{version}",
"btn_save_settings": "Save & Apply Settings",
"msg_copy_title": "Copied",
"msg_copy_body": "IP address ({ip}) copied to clipboard!",
"msg_error_title": "Error",
"msg_port_invalid": "Port must be a valid number (e.g. 8765).",
"msg_settings_title": "Settings",
"msg_settings_saved": "Settings saved and applied successfully!",
"msg_settings_saved_restart_lang": "Settings saved! Restart the app to apply the new language everywhere.",
"checking_updates": "Checking for updates...",
"tray_show_window": "Show Window",
"tray_pause": "Pause",
"tray_resume": "Resume Listening",
"tray_open_web": "Open Web Dashboard",
"tray_check_updates": "Check for Updates...",
"tray_quit": "Quit",
"tray_update_title": "Update available (v{version})",
"tray_update_body": "Open Barcode Reader Server to install it automatically.",
"updates_dialog_title": "Updates",
"updates_check_title": "Update Check",
"update_win_title": "Update Available — v{version}",
"update_new_version": "New version available: v{version}",
"update_installed_sub": "Installed version: v{version} • {title}",
"update_no_notes": "No release notes provided.",
"update_no_asset": "No platform-specific package found in this release.",
"update_ready_pkg": "Package ready to install: {name}{size}",
"btn_later": "Later",
"btn_open_release_page": "Open Release Page",
"btn_update_restart": "Update & Restart",
"update_downloading": "Downloading {name}...",
"update_downloading_pct": "Downloading: {done:.1f} / {total:.1f} MB ({percent}%)",
"update_downloading_mb": "Downloaded {done:.1f} MB...",
"update_installing": "Installing update and restarting...",
"update_apply_error": "Failed to launch update: {error}",
"update_error_prefix": "Error: {error}",
"update_error_title": "Update Error",
},
"it": {
"app_subtitle": "Ricezione codici a barre da Smartphone • Catelli Srl • v{version}",
"update_available_btn": "Aggiornamento disponibile",
"update_to_version_btn": "Aggiorna a v{version}",
"tab_dashboard": "Dashboard & Dispositivi",
"tab_settings": "Impostazioni",
"card_qr_title": "CONNESSIONE RAPIDA (QR)",
"qr_hint": "Inquadra con l'app Android/iOS",
"card_server_title": "DETTAGLI SERVER",
"lbl_local_ip": "Indirizzo IP Locale:",
"lbl_port": "Porta:",
"lbl_pc_name": "Nome PC:",
"lbl_pin": "PIN di Accesso:",
"pin_none": "Nessuno (Libero)",
"btn_copy_ip": "Copia IP",
"btn_open_web": "Apri Dashboard Web",
"card_devices_title": "DISPOSITIVI CONNESSI",
"no_devices_connected": "Nessun dispositivo mobile collegato.",
"devices_connected_fmt": "{count} collegati: {devices}",
"card_history_title": "CRONOLOGIA SCANSIONI LIVE",
"btn_clear_log": "Pulisci Log",
"col_time": "Ora",
"col_device": "Dispositivo",
"col_code": "Codice Letto",
"col_status": "Esito",
"scan_typed": "Digitato ✓",
"scan_failed": "Fallito ✗",
"status_listening_badge": "● IN ASCOLTO",
"status_paused_badge": "○ IN PAUSA",
"status_listening_short": "IN ASCOLTO",
"status_paused_short": "IN PAUSA",
"btn_pause": "Metti in Pausa",
"btn_resume": "Riprendi Ricezione",
"sec_network": "RETE E IDENTIFICAZIONE",
"lbl_mobile_name": "Nome visualizzato nell'app mobile:",
"lbl_pin_input": "PIN di accesso (es. 4 cifre):",
"placeholder_pin": "Lascia vuoto per accesso libero",
"lbl_ws_port": "Porta Server WebSocket:",
"port_restart_hint": "(Il cambio porta richiede riavvio)",
"sec_keyboard": "COMPORTAMENTO TASTIERA",
"lbl_suffix": "Tasto finale dopo ogni scansione:",
"rb_suffix_enter": "Invio (Enter)",
"rb_suffix_tab": "Tabulatore (Tab)",
"rb_suffix_none": "Nessun tasto",
"lbl_typing_mode": "Modalità di scrittura:",
"rb_mode_type": "Digitazione tastiera reale (Consigliato)",
"rb_mode_paste": "Incolla da appunti (Ctrl+V / Cmd+V)",
"sec_system": "AVVIO AUTOMATICO, TRAY, LINGUA E AGGIORNAMENTI",
"chk_autostart": "Avvia automaticamente all'avvio del sistema operativo (Login / Boot)",
"chk_tray": "Alla chiusura (X) riduci nella System Tray invece di terminare",
"chk_updates": "Controlla automaticamente nuovi aggiornamenti all'avvio",
"lbl_language": "Lingua interfaccia:",
"lang_auto": "Predefinita di sistema (Auto)",
"lang_it": "Italiano",
"lang_en": "English",
"lbl_update_url": "URL aggiornamento custom (opzionale):",
"placeholder_update_url": "Vuoto = Gitea Releases (gitea.catelli.it)",
"btn_check_updates": "Controlla Aggiornamenti Ora",
"installed_version": "Versione installata: v{version}",
"btn_save_settings": "Salva ed Applica Impostazioni",
"msg_copy_title": "Copia",
"msg_copy_body": "Indirizzo IP ({ip}) copiato negli appunti!",
"msg_error_title": "Errore",
"msg_port_invalid": "La porta deve essere un numero valido (es. 8765).",
"msg_settings_title": "Impostazioni",
"msg_settings_saved": "Impostazioni salvate ed applicate con successo!",
"msg_settings_saved_restart_lang": "Impostazioni salvate! Riavvia l'app per applicare completamente la nuova lingua.",
"checking_updates": "Ricerca aggiornamenti in corso...",
"tray_show_window": "Mostra Finestra",
"tray_pause": "Metti in Pausa",
"tray_resume": "Riprendi Ascolto",
"tray_open_web": "Apri Dashboard Web",
"tray_check_updates": "Controlla Aggiornamenti...",
"tray_quit": "Esci",
"tray_update_title": "Aggiornamento disponibile (v{version})",
"tray_update_body": "Apri la finestra di Barcode Reader Server per installarlo automaticamente.",
"updates_dialog_title": "Aggiornamenti",
"updates_check_title": "Controllo Aggiornamenti",
"update_win_title": "Aggiornamento Disponibile — v{version}",
"update_new_version": "Nuova versione disponibile: v{version}",
"update_installed_sub": "Versione installata: v{version} • {title}",
"update_no_notes": "Nessuna nota di rilascio specificata.",
"update_no_asset": "Nessun pacchetto specifico trovato per questa piattaforma negli asset della release.",
"update_ready_pkg": "Pacchetto pronto per l'installazione: {name}{size}",
"btn_later": "Più Tardi",
"btn_open_release_page": "Apri Pagina Release",
"btn_update_restart": "Aggiorna e Riavvia",
"update_downloading": "Scaricamento di {name}...",
"update_downloading_pct": "Scaricamento: {done:.1f} / {total:.1f} MB ({percent}%)",
"update_downloading_mb": "Scaricati {done:.1f} MB...",
"update_installing": "Installazione aggiornamento e riavvio in corso...",
"update_apply_error": "Errore avvio aggiornamento: {error}",
"update_error_prefix": "Errore: {error}",
"update_error_title": "Errore Aggiornamento",
},
}
def detect_system_language() -> str:
"""Detect OS locale and return 'it' for Italian, 'en' otherwise."""
try:
from PySide6.QtCore import QLocale
qt_lang = QLocale.system().name().lower()
if qt_lang.startswith("it"):
return "it"
if qt_lang:
return "en"
except Exception:
pass
for candidate in (
os.environ.get("LC_ALL"),
os.environ.get("LC_MESSAGES"),
os.environ.get("LANG"),
):
if candidate:
return "it" if candidate.lower().startswith("it") else "en"
try:
loc, _ = locale.getlocale()
if loc and loc.lower().startswith("it"):
return "it"
except Exception:
pass
return "en"
def set_language(lang_code: str | None) -> str:
"""Set active language ('auto', 'it', 'en') and return the resolved language code."""
global _CURRENT_LANG
normalized = (lang_code or "auto").strip().lower()
if normalized in ("it", "en"):
_CURRENT_LANG = normalized
else:
_CURRENT_LANG = detect_system_language()
return _CURRENT_LANG
def get_language() -> str:
return _CURRENT_LANG
def tr(key: str, **kwargs) -> str:
table = TRANSLATIONS.get(_CURRENT_LANG, TRANSLATIONS["en"])
template = table.get(key, TRANSLATIONS["en"].get(key, key))
return template.format(**kwargs) if kwargs else template
+26 -1
View File
@@ -331,13 +331,35 @@ class KeyboardSimulator:
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, self._sync_type, full_text, active_suffix, active_mode) return await loop.run_in_executor(None, self._sync_type, full_text, active_suffix, active_mode)
def _ensure_controller(self) -> bool:
if self.controller is not None:
return True
global _controller, Controller, Key, KeyCode
try:
from pynput.keyboard import Controller as _C, Key as _K, KeyCode as _KC
Controller = _C
Key = _K
KeyCode = _KC
self.controller = Controller()
_controller = self.controller
self._linux_xtest, self._win32_helper = _init_platform_helpers(self.controller)
print("[+] Controller tastiera pynput inizializzato con successo.")
return True
except Exception as e:
print(f"Errore inizializzazione controller tastiera: {e}")
return False
def _tap_special(self, x11_name: str, pynput_key) -> None: def _tap_special(self, x11_name: str, pynput_key) -> None:
if not self._ensure_controller():
return
if self._linux_xtest is not None: if self._linux_xtest is not None:
if self._linux_xtest.tap_named(x11_name): if self._linux_xtest.tap_named(x11_name):
return return
self.controller.tap(pynput_key) self.controller.tap(pynput_key)
def _type_single_char(self, char: str) -> None: def _type_single_char(self, char: str) -> None:
if not self._ensure_controller():
return
if self._linux_xtest is not None: if self._linux_xtest is not None:
if self._linux_xtest.type_char(char): if self._linux_xtest.type_char(char):
return return
@@ -380,6 +402,9 @@ class KeyboardSimulator:
time.sleep(0.04) time.sleep(0.04)
return True return True
if not self._ensure_controller():
return False
modifier = Key.cmd if self.is_mac else Key.ctrl modifier = Key.cmd if self.is_mac else Key.ctrl
paste_key = KeyCode.from_vk(0x56) if (self.is_windows and KeyCode is not None) else "v" paste_key = KeyCode.from_vk(0x56) if (self.is_windows and KeyCode is not None) else "v"
with self.controller.pressed(modifier): with self.controller.pressed(modifier):
@@ -388,7 +413,7 @@ class KeyboardSimulator:
return True return True
def _sync_type(self, full_text: str, suffix: str, mode: str) -> bool: def _sync_type(self, full_text: str, suffix: str, mode: str) -> bool:
if not self.controller: if not self._ensure_controller():
print("Errore: controller tastiera non disponibile!") print("Errore: controller tastiera non disponibile!")
return False return False
+8 -1
View File
@@ -203,7 +203,14 @@ class QtGuiAndTrayTests(unittest.TestCase):
self.assertEqual(gui.table.rowCount(), 1) self.assertEqual(gui.table.rowCount(), 1)
self.assertIn("Pixel 8", gui.lbl_devices.text()) self.assertIn("Pixel 8", gui.lbl_devices.text())
self.assertFalse(dummy.is_listening) self.assertFalse(dummy.is_listening)
self.assertIn("IN PAUSA", gui.status_badge.text()) import i18n
self.assertIn(i18n.tr("status_paused_short"), gui.status_badge.text())
# Verifica traduzioni IT/EN
i18n.set_language("it")
self.assertEqual(i18n.tr("tab_settings"), "Impostazioni")
i18n.set_language("en")
self.assertEqual(i18n.tr("tab_settings"), "Settings")
# Smoke test UpdateDialog # Smoke test UpdateDialog
rel = updater.ReleaseInfo( rel = updater.ReleaseInfo(
+19 -6
View File
@@ -8,6 +8,7 @@ from PySide6.QtCore import QObject, Qt
from PySide6.QtGui import QAction, QColor, QFont, QIcon, QPainter, QPainterPath, QPen, QPixmap from PySide6.QtGui import QAction, QColor, QFont, QIcon, QPainter, QPainterPath, QPen, QPixmap
from PySide6.QtWidgets import QMenu, QSystemTrayIcon from PySide6.QtWidgets import QMenu, QSystemTrayIcon
from i18n import tr
from version import APP_NAME, APP_VERSION, get_resource_path from version import APP_NAME, APP_VERSION, get_resource_path
@@ -124,7 +125,7 @@ class ServerTrayIcon(QObject):
self._action_status.setEnabled(False) self._action_status.setEnabled(False)
self._menu.addAction(self._action_status) self._menu.addAction(self._action_status)
self._action_show = QAction("Mostra Finestra", self._menu) self._action_show = QAction(tr("tray_show_window"), self._menu)
show_font = QFont(self._action_show.font()) show_font = QFont(self._action_show.font())
show_font.setBold(True) show_font.setBold(True)
self._action_show.setFont(show_font) self._action_show.setFont(show_font)
@@ -137,17 +138,17 @@ class ServerTrayIcon(QObject):
self._action_toggle.triggered.connect(self.on_toggle_listening) self._action_toggle.triggered.connect(self.on_toggle_listening)
self._menu.addAction(self._action_toggle) self._menu.addAction(self._action_toggle)
self._action_web = QAction("Apri Dashboard Web", self._menu) self._action_web = QAction(tr("tray_open_web"), self._menu)
self._action_web.triggered.connect(self.on_open_web) self._action_web.triggered.connect(self.on_open_web)
self._menu.addAction(self._action_web) self._menu.addAction(self._action_web)
self._action_updates = QAction("Controlla Aggiornamenti...", self._menu) self._action_updates = QAction(tr("tray_check_updates"), self._menu)
self._action_updates.triggered.connect(self.on_check_updates) self._action_updates.triggered.connect(self.on_check_updates)
self._menu.addAction(self._action_updates) self._menu.addAction(self._action_updates)
self._menu.addSeparator() self._menu.addSeparator()
self._action_quit = QAction("Esci", self._menu) self._action_quit = QAction(tr("tray_quit"), self._menu)
self._action_quit.triggered.connect(self.on_quit) self._action_quit.triggered.connect(self.on_quit)
self._menu.addAction(self._action_quit) self._menu.addAction(self._action_quit)
@@ -169,14 +170,26 @@ class ServerTrayIcon(QObject):
icon.addPixmap(create_status_pixmap(is_listening, 64)) icon.addPixmap(create_status_pixmap(is_listening, 64))
self._tray.setIcon(icon) self._tray.setIcon(icon)
status_text = "IN ASCOLTO" if is_listening else "IN PAUSA" status_text = tr("status_listening_short") if is_listening else tr("status_paused_short")
self._tray.setToolTip(f"{APP_NAME} v{APP_VERSION} — {status_text}") self._tray.setToolTip(f"{APP_NAME} v{APP_VERSION} — {status_text}")
if self._action_status is not None: if self._action_status is not None:
marker = "●" if is_listening else "○" marker = "●" if is_listening else "○"
self._action_status.setText(f"{marker} {status_text} (v{APP_VERSION})") self._action_status.setText(f"{marker} {status_text} (v{APP_VERSION})")
if self._action_toggle is not None: if self._action_toggle is not None:
self._action_toggle.setText("Metti in Pausa" if is_listening else "Riprendi Ascolto") self._action_toggle.setText(tr("tray_pause") if is_listening else tr("tray_resume"))
def retranslate(self) -> None:
"""Aggiorna le etichette del menu tray dopo un cambio lingua."""
if self._action_show is not None:
self._action_show.setText(tr("tray_show_window"))
if self._action_web is not None:
self._action_web.setText(tr("tray_open_web"))
if self._action_updates is not None:
self._action_updates.setText(tr("tray_check_updates"))
if self._action_quit is not None:
self._action_quit.setText(tr("tray_quit"))
self.update_status(self.is_listening)
def show_message(self, title: str, message: str, duration_ms: int = 5000) -> None: def show_message(self, title: str, message: str, duration_ms: int = 5000) -> None:
"""Mostra una notifica desktop nativa tramite la System Tray.""" """Mostra una notifica desktop nativa tramite la System Tray."""
+1 -1
View File
@@ -7,7 +7,7 @@ APP_NAME = "Barcode Reader Server"
APP_BINARY_NAME = "BarcodeServer" APP_BINARY_NAME = "BarcodeServer"
APP_ID = "com.catellisrl.barcodereader" APP_ID = "com.catellisrl.barcodereader"
APP_PUBLISHER = "Catelli Srl" APP_PUBLISHER = "Catelli Srl"
APP_VERSION = "1.0.1" APP_VERSION = "1.0.6"
GITEA_BASE_URL = "https://gitea.catelli.it" GITEA_BASE_URL = "https://gitea.catelli.it"
GITEA_REPO = "brontomark/barcode_reader_pc" GITEA_REPO = "brontomark/barcode_reader_pc"