14 Commits
Author SHA1 Message Date
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
34 changed files with 1602 additions and 70 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
with:
files: "server/dist/installer/BarcodeServerSetup.exe"
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:
runs-on: linux-runner
@@ -84,31 +119,53 @@ jobs:
- name: Checkout del codice
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: |
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
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
- name: Upload Linux AppImage Asset su Gitea Release
uses: https://gitea.com/actions/release-action@main
with:
files: "BarcodeServer-x86_64.AppImage"
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)
# -----------------------------------------------------------------
@@ -129,7 +186,7 @@ jobs:
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"
- name: Upload macOS Assets
- name: Upload macOS Assets su Gitea Release
uses: https://gitea.com/actions/release-action@main
with:
files: |
@@ -137,3 +194,30 @@ jobs:
BarcodeServer-macOS.zip
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'"
+7 -4
View File
@@ -30,6 +30,7 @@ android {
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
multiDexEnabled = true
// 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)
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
@@ -56,10 +57,8 @@ android {
} else {
signingConfigs.getByName("debug")
}
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
isMinifyEnabled = false
isShrinkResources = false
}
}
}
@@ -70,6 +69,10 @@ kotlin {
}
}
tasks.matching { it.name.contains("AarMetadata") }.configureEach {
enabled = false
}
flutter {
source = "../.."
}
+19
View File
@@ -17,3 +17,22 @@
-keep class android.net.** { *; }
-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
android:name="flutterEmbedding"
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>
<!-- Required to query activities that can process text, see:
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

+174
View File
@@ -0,0 +1,174 @@
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';
// Set to true only when publishing the final public release to production.
// Kept false during development and closed testing to guarantee 100% fill rate
// and prevent accidental invalid traffic strikes on the AdMob account.
static const bool useProductionAds = false;
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 {
// 1. Try preferred unit (production in release, test in debug)
var ad = await _requestAd(rewardedAdUnitId);
// 2. If production has No Fill (brand new unit taking up to 24h to activate),
// fallback to Google Test Unit so testers and reviewers are never blocked!
if (ad == null && rewardedAdUnitId != androidTestRewardedAdUnitId) {
debugPrint('Production ad unit has no inventory yet. Falling back to test unit...');
ad = await _requestAd(androidTestRewardedAdUnitId);
}
_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,151 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:purchases_flutter/purchases_flutter.dart';
import 'package:purchases_ui_flutter/purchases_ui_flutter.dart';
/// Service managing RevenueCat In-App Purchases, Subscriptions, Paywalls and Customer Center.
class SubscriptionService {
SubscriptionService();
// RevenueCat Google / Android API Key
static const String apiKey = 'test_WfBStIXoLdiBaGJjDFgiLQSPjnl';
// Entitlement ID granting unlimited scanning
static const String entitlementId = 'barcode_reader_pc_unlimited';
// Product IDs 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 and subscription packages 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;
}
}
/// 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;
}
}
/// Presents the official RevenueCat Paywall UI.
Future<PaywallResult> presentPaywall({Offering? offering}) async {
if (_isFlutterTest || kIsWeb || !_isConfigured) {
return PaywallResult.notPresented;
}
try {
final result = await RevenueCatUI.presentPaywall(offering: offering);
if (result == PaywallResult.purchased || result == PaywallResult.restored) {
final info = await Purchases.getCustomerInfo();
_customerInfoController.add(info);
}
return result;
} catch (e) {
debugPrint('Error presenting Paywall: $e');
return PaywallResult.error;
}
}
/// Presents the Paywall only if the user does NOT have the active entitlement.
Future<PaywallResult> presentPaywallIfNeeded() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) {
return PaywallResult.notPresented;
}
try {
final result = await RevenueCatUI.presentPaywallIfNeeded(entitlementId);
if (result == PaywallResult.purchased || result == PaywallResult.restored) {
final info = await Purchases.getCustomerInfo();
_customerInfoController.add(info);
}
return result;
} catch (e) {
debugPrint('Error presenting Paywall if needed: $e');
return PaywallResult.error;
}
}
/// Presents the official RevenueCat Customer Center to manage or cancel subscriptions.
Future<void> presentCustomerCenter() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return;
try {
await RevenueCatUI.presentCustomerCenter();
final info = await Purchases.getCustomerInfo();
_customerInfoController.add(info);
} catch (e) {
debugPrint('Error presenting Customer Center: $e');
}
}
void dispose() {
_customerInfoController.close();
}
}
@@ -0,0 +1,187 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:purchases_ui_flutter/purchases_ui_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;
}
/// Presents the official RevenueCat Paywall UI.
Future<PaywallResult> presentPaywall() async {
final result = await _subscriptionService.presentPaywall();
if (result == PaywallResult.purchased || result == PaywallResult.restored) {
emit(state.copyWith(isPremium: true));
}
return result;
}
/// Presents the RevenueCat Customer Center to view/manage subscription.
Future<void> presentCustomerCenter() async {
await _subscriptionService.presentCustomerCenter();
final isEntitled = await _subscriptionService.isEntitled();
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,219 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:purchases_ui_flutter/purchases_ui_flutter.dart';
import '../../../../core/theme/app_theme.dart';
import '../cubit/monetization_cubit.dart';
import '../cubit/monetization_state.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) {
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),
const Text(
'Scansioni Illimitate',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
letterSpacing: -0.4,
),
),
const SizedBox(height: 8),
Text(
'Guarda un breve video per sbloccare 15 minuti di scansioni illimitate al PC senza interruzioni.',
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(
const SnackBar(
content: Text(
'15 minuti di scansioni illimitate sbloccati!',
),
duration: Duration(milliseconds: 1600),
backgroundColor: AppTheme.success,
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Caricamento video in corso... Riprova tra pochi istanti.',
),
duration: 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 ? 'Caricamento video...' : 'Guarda Video (+15 min)',
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
),
const SizedBox(height: 12),
// Upgrade to Premium button (RevenueCat Paywall)
SizedBox(
width: double.infinity,
height: 50,
child: OutlinedButton.icon(
onPressed: () async {
final cubit = context.read<MonetizationCubit>();
final result = await cubit.presentPaywall();
if (context.mounted &&
(result == PaywallResult.purchased ||
result == PaywallResult.restored)) {
Navigator.of(context).pop(true);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('🎉 Benvenuto in Premium Illimitato!'),
backgroundColor: AppTheme.success,
duration: Duration(milliseconds: 2000),
),
);
}
},
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: const Text(
'Passa a Premium Illimitato',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
),
const SizedBox(height: 12),
// Cancel button
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text(
'Più tardi',
style: TextStyle(
color: AppTheme.darkTextSecondary,
fontSize: 14,
),
),
),
],
);
},
),
);
}
}
@@ -9,6 +9,9 @@ import '../../../../core/theme/app_theme.dart';
import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/widgets/connection_status_chip.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../monetization/presentation/cubit/monetization_cubit.dart';
import '../../../monetization/presentation/cubit/monetization_state.dart';
import '../../../monetization/presentation/widgets/reward_session_dialog.dart';
import '../../../settings/presentation/cubit/settings_cubit.dart';
import '../../../settings/presentation/cubit/settings_state.dart';
import '../../../settings/presentation/screens/settings_screen.dart';
@@ -27,6 +30,16 @@ import '../widgets/scanner_controls_bar.dart';
import '../widgets/scanner_overlay.dart';
import 'history_screen.dart';
class _TrackedBarcodeEntry {
DetectedBarcodeItem item;
DateTime lastSeen;
_TrackedBarcodeEntry({
required this.item,
required this.lastSeen,
});
}
class ScannerScreen extends StatefulWidget {
const ScannerScreen({super.key});
@@ -45,6 +58,9 @@ class _ScannerScreenState extends State<ScannerScreen>
bool _autoZoomedForPrecision = false;
// Live AR & Precision targeting state
final Map<String, _TrackedBarcodeEntry> _trackedArItems = {};
final Set<String> _sentLiveKeys = <String>{};
Timer? _arPruneTimer;
List<DetectedBarcodeItem> _liveArItems = const [];
int? _precisionTargetIndex;
Timer? _arDecayTimer;
@@ -66,14 +82,16 @@ class _ScannerScreenState extends State<ScannerScreen>
super.initState();
WidgetsBinding.instance.addObserver(this);
_scannerController = MobileScannerController(
detectionSpeed: DetectionSpeed.normal,
detectionTimeoutMs: 180,
cameraResolution: const Size(1920, 1080),
detectionSpeed: DetectionSpeed.unrestricted,
facing: CameraFacing.back,
torchEnabled: false,
returnImage: true,
);
_arPruneTimer = Timer.periodic(const Duration(milliseconds: 200), (_) {
_pruneExpiredArItems();
});
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkStartupConnection();
_applyInitialModeZoom();
@@ -117,6 +135,7 @@ class _ScannerScreenState extends State<ScannerScreen>
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_arDecayTimer?.cancel();
_arPruneTimer?.cancel();
_focusRingTimer?.cancel();
_scannerController.dispose();
super.dispose();
@@ -192,6 +211,8 @@ class _ScannerScreenState extends State<ScannerScreen>
if (!mounted) return;
_arDecayTimer?.cancel();
_trackedArItems.clear();
_sentLiveKeys.clear();
setState(() {
_liveArItems = const [];
_precisionTargetIndex = null;
@@ -227,13 +248,47 @@ class _ScannerScreenState extends State<ScannerScreen>
_precisionTargetIndex = null;
});
}
final barcodes = capture.barcodes;
if (barcodes.isEmpty) return;
final first = barcodes.first;
final rawValue = first.rawValue ?? first.displayValue;
if (rawValue == null || rawValue.trim().isEmpty) return;
final formatName = first.format.name.replaceAll('BarcodeFormat.', '');
context.read<ScannerCubit>().processBarcode(rawValue, format: formatName);
final standardReticle = ScannerReticleGeometry.scanRect(
_viewportSize,
ScanAimMode.standard,
);
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:
final items = BarcodeGeometry.mapCaptureToItems(
@@ -248,12 +303,13 @@ class _ScannerScreenState extends State<ScannerScreen>
final target = BarcodeGeometry.selectPrecisionTarget(
items: items,
crosshairCenter: crosshairCenter,
hitRadius: 16.0,
hitRadius: 24.0,
);
_updateLiveArItems(items, precisionTargetIndex: target?.index);
if (target != null) {
if (!_ensureCanScan()) return;
context.read<ScannerCubit>().processBarcode(
target.code,
format: target.format,
@@ -266,9 +322,45 @@ class _ScannerScreenState extends State<ScannerScreen>
widgetSize: _viewportSize,
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;
if (imageBytes != null && imageBytes.isNotEmpty) {
@@ -277,12 +369,12 @@ class _ScannerScreenState extends State<ScannerScreen>
imageSize: capture.size,
viewportSize: _viewportSize,
deviceOrientation: deviceOrientation,
items: items,
timestamp: DateTime.now(),
items: reindexed.isNotEmpty ? reindexed : items,
timestamp: now,
);
_latestArSnapshot = snapshot;
if (_pendingFreeze) {
if (_pendingFreeze && reindexed.isNotEmpty) {
_pendingFreeze = false;
_freezeWithSnapshot(snapshot);
}
@@ -290,6 +382,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(
List<DetectedBarcodeItem> items, {
int? precisionTargetIndex,
@@ -311,12 +430,21 @@ class _ScannerScreenState extends State<ScannerScreen>
void _requestFreeze() {
final snapshot = _latestArSnapshot;
final now = DateTime.now();
final isFresh = snapshot != null &&
DateTime.now().difference(snapshot.timestamp) <=
const Duration(milliseconds: 1500);
now.difference(snapshot.timestamp) <= const Duration(milliseconds: 3000);
if (isFresh) {
_freezeWithSnapshot(snapshot);
if (isFresh && (_liveArItems.isNotEmpty || snapshot.items.isNotEmpty)) {
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;
}
@@ -351,18 +479,37 @@ 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 {
if (!_ensureCanScan()) return;
final success = await context.read<ScannerCubit>().sendSelectedBarcode(
item.code,
format: item.format,
);
if (!mounted) return;
if (_frozenSnapshot != null && success) {
if (success) {
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) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
@@ -379,7 +526,7 @@ class _ScannerScreenState extends State<ScannerScreen>
}
}
Future<void> _handleTapToFocus(TapUpDetails details) async {
void _handleTapToFocus(TapUpDetails details) {
if (_frozenSnapshot != null ||
_viewportSize.isEmpty ||
!_scannerController.value.isRunning) {
@@ -387,9 +534,6 @@ class _ScannerScreenState extends State<ScannerScreen>
}
final local = details.localPosition;
final rx = (local.dx / _viewportSize.width).clamp(0.0, 1.0);
final ry = (local.dy / _viewportSize.height).clamp(0.0, 1.0);
_focusRingTimer?.cancel();
setState(() {
_focusRingPosition = local;
@@ -400,9 +544,7 @@ class _ScannerScreenState extends State<ScannerScreen>
}
});
try {
await _scannerController.setFocusPoint(Offset(rx, ry));
} catch (_) {}
_feedbackService.triggerSelection();
}
void _toggleTorch() {
@@ -439,10 +581,6 @@ class _ScannerScreenState extends State<ScannerScreen>
return LayoutBuilder(
builder: (context, constraints) {
_viewportSize = constraints.biggest;
final scanWindow = ScannerReticleGeometry.scanRect(
_viewportSize,
aimMode,
);
final topSafe = MediaQuery.paddingOf(context).top + 124.0;
final bottomReserved = (lastScan != null ? 250.0 : 165.0) +
@@ -477,8 +615,6 @@ class _ScannerScreenState extends State<ScannerScreen>
},
child: MobileScanner(
controller: _scannerController,
scanWindow: scanWindow,
scanWindowUpdateThreshold: 4.0,
onDetect: _onDetect,
),
),
@@ -500,6 +636,8 @@ class _ScannerScreenState extends State<ScannerScreen>
items: _liveArItems,
safeBounds: arSafeBounds,
showBadges: aimMode == ScanAimMode.arMulti,
allowBoxTap: true,
sentKeys: _sentLiveKeys,
highlightedIndex: aimMode == ScanAimMode.precision
? _precisionTargetIndex
: null,
@@ -525,7 +663,16 @@ class _ScannerScreenState extends State<ScannerScreen>
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Center(child: ConnectionStatusChip()),
Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 6,
children: const [
ConnectionStatusChip(),
_SessionStatusChip(),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment:
@@ -751,3 +898,100 @@ 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: () => context.read<MonetizationCubit>().presentCustomerCenter(),
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 isUnlimited = state.isUnlimited;
final color = isUnlimited
? AppTheme.success
: (state.freeScansRemaining > 0 ? AppTheme.primary : AppTheme.warning);
final label = isUnlimited
? '${state.formattedRemainingTime} Illimitati'
: (state.freeScansRemaining > 0
? '${state.freeScansRemaining} libere'
: 'Sblocca 15 min');
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,
measureBadge: (item) => _measureBadge(
item,
isSent: sentKeys.contains(item.selectionKey),
isSent: sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey),
),
)
: const <int, Rect>{};
@@ -71,7 +72,8 @@ class ArBarcodeOverlay extends StatelessWidget {
rect: rect,
child: _ArCodeBadge(
item: item,
isSent: sentKeys.contains(item.selectionKey),
isSent: sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey),
onTap: onTapBarcode != null ? () => onTapBarcode!(item) : null,
),
),
@@ -197,7 +199,8 @@ class _ArPolygonPainter extends CustomPainter {
final isPrecisionMode = !showBadges;
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 double strokeWidth;
@@ -250,7 +250,7 @@ class _ArFrozenPickerState extends State<ArFrozenPicker> {
const SizedBox(height: 8),
itemBuilder: (context, index) {
final item = snapshot.items[index];
final isSent =
final isSent = widget.sentKeys.contains(item.code) ||
widget.sentKeys.contains(item.selectionKey);
return _FrozenCodeRow(
item: item,
@@ -142,6 +142,7 @@ class _ZoomPresetsBar extends StatelessWidget {
static const _presets = [
(label: '1x', scale: 0.0),
(label: '1.5x', scale: 0.125),
(label: '2x', scale: 0.25),
(label: '3x', scale: 0.50),
];
@@ -174,7 +175,7 @@ class _ZoomPresetsBar extends StatelessWidget {
for (final preset in _presets)
_ZoomChip(
label: preset.label,
selected: !isExtraZoom && (zoomScale - preset.scale).abs() < 0.09,
selected: !isExtraZoom && (zoomScale - preset.scale).abs() < 0.06,
onTap: () => onSelect(preset.scale),
),
if (isExtraZoom)
@@ -6,6 +6,8 @@ import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/cubit/connection_state.dart';
import '../../../connection/presentation/screens/connect_screen.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../monetization/presentation/cubit/monetization_cubit.dart';
import '../../../monetization/presentation/cubit/monetization_state.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../cubit/settings_cubit.dart';
import '../cubit/settings_state.dart';
@@ -26,6 +28,99 @@ class SettingsScreen extends StatelessWidget {
return ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
children: [
// Subscription & Premium Section (RevenueCat)
const _SectionHeader(title: 'PIANO & ABBONAMENTO'),
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 ? 'Piano Premium Attivo' : 'Versione Base Gratuita',
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Text(
isPremium
? 'Scansioni illimitate e zero pubblicità'
: (monState.isUnlimited
? 'Sessione attiva: ${monState.formattedRemainingTime}'
: '${monState.freeScansRemaining} scansioni libere rimanenti'),
),
trailing: isPremium
? OutlinedButton(
onPressed: () => context
.read<MonetizationCubit>()
.presentCustomerCenter(),
child: const Text('Gestisci'),
)
: FilledButton(
onPressed: () => context
.read<MonetizationCubit>()
.presentPaywall(),
style: FilledButton.styleFrom(
backgroundColor: const Color(0xFFFBBF24),
foregroundColor: Colors.black87,
),
child: const Text('Passa a Premium'),
),
),
if (!isPremium) ...[
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.restore_rounded),
title: const Text('Ripristina Acquisti'),
subtitle: const Text(
'Hai già acquistato su un altro dispositivo o reinstallato?',
),
onTap: () async {
final restored = await context
.read<MonetizationCubit>()
.restorePurchases();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
restored
? 'Acquisti ripristinati con successo!'
: 'Nessun acquisto attivo trovato da ripristinare.',
),
backgroundColor: restored
? AppTheme.success
: AppTheme.darkCard,
),
);
}
},
),
],
],
),
);
},
),
const SizedBox(height: 14),
// PC Connection Section
const _SectionHeader(title: 'CONNESSIONE PC & NEGOZIO'),
Card(
+32
View File
@@ -3,7 +3,9 @@ import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'core/services/ad_service.dart';
import 'core/services/feedback_service.dart';
import 'core/services/subscription_service.dart';
import 'core/theme/app_theme.dart';
import 'features/connection/data/datasources/connection_local_datasource.dart';
import 'features/connection/data/datasources/connection_remote_datasource.dart';
@@ -12,6 +14,7 @@ import 'features/connection/data/repositories/connection_repository_impl.dart';
import 'features/connection/domain/repositories/connection_repository.dart';
import 'features/connection/presentation/cubit/connection_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/repositories/scan_repository_impl.dart';
import 'features/scanner/domain/repositories/scan_repository.dart';
@@ -36,6 +39,19 @@ void main() async {
// Core services
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
final SettingsRepository settingsRepository = SettingsRepositoryImpl(
@@ -58,6 +74,9 @@ void main() async {
connectionRepository: connectionRepository,
scanRepository: scanRepository,
feedbackService: feedbackService,
adService: adService,
subscriptionService: subscriptionService,
prefs: prefs,
),
);
}
@@ -67,6 +86,9 @@ class BarcodeReaderApp extends StatelessWidget {
final ConnectionRepository connectionRepository;
final ScanRepository scanRepository;
final FeedbackService feedbackService;
final AdService adService;
final SubscriptionService subscriptionService;
final SharedPreferences prefs;
const BarcodeReaderApp({
super.key,
@@ -74,12 +96,22 @@ class BarcodeReaderApp extends StatelessWidget {
required this.connectionRepository,
required this.scanRepository,
required this.feedbackService,
required this.adService,
required this.subscriptionService,
required this.prefs,
});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<MonetizationCubit>(
create: (_) => MonetizationCubit(
prefs: prefs,
adService: adService,
subscriptionService: subscriptionService,
),
),
BlocProvider<SettingsCubit>(
create: (_) => SettingsCubit(settingsRepository)..loadSettings(),
),
@@ -8,11 +8,15 @@ import Foundation
import audioplayers_darwin
import device_info_plus
import mobile_scanner
import purchases_flutter
import shared_preferences_foundation
import webview_flutter_wkwebview
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin"))
PurchasesFlutterPlugin.register(with: registry.registrar(forPlugin: "PurchasesFlutterPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin"))
}
+57 -1
View File
@@ -232,6 +232,14 @@ packages:
description: flutter
source: sdk
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:
dependency: transitive
description:
@@ -464,6 +472,22 @@ packages:
url: "https://pub.dev"
source: hosted
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"
purchases_ui_flutter:
dependency: "direct main"
description:
name: purchases_ui_flutter
sha256: "9931ffb9729b61b667f41da213de299cff9993ecaf95f18e455aef78b02b17a8"
url: "https://pub.dev"
source: hosted
version: "11.0.3"
record_use:
dependency: transitive
description:
@@ -661,6 +685,38 @@ packages:
url: "https://pub.dev"
source: hosted
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:
dependency: transitive
description:
@@ -695,4 +751,4 @@ packages:
version: "3.1.4"
sdks:
dart: ">=3.13.4 <4.0.0"
flutter: ">=3.44.0"
flutter: ">=3.47.0"
+4 -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
# 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.
version: 1.0.1+2
version: 1.0.10+11
environment:
sdk: ^3.13.4
@@ -42,6 +42,9 @@ dependencies:
equatable: ^3.0.0
audioplayers: ^6.8.1
vibration: ^3.2.1
google_mobile_ads: ^9.2.0
purchases_flutter: ^11.0.3
purchases_ui_flutter: ^11.0.3
dev_dependencies:
flutter_test:
+1
View File
@@ -307,6 +307,7 @@ void main() {
expect(find.text('Blocca frame (2 codici)'), findsOneWidget);
expect(find.text('1x'), findsOneWidget);
expect(find.text('1.5x'), findsOneWidget);
expect(find.text('2x'), findsOneWidget);
expect(find.text('3x'), findsOneWidget);
expect(find.text('Standard'), findsOneWidget);
+7
View File
@@ -1,7 +1,9 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:barcode_reader_app/main.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/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_remote_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/udp_discovery_datasource.dart';
@@ -24,6 +26,8 @@ void main() {
);
final scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
const feedbackService = FeedbackService();
final adService = AdService();
final subscriptionService = SubscriptionService();
await tester.pumpWidget(
BarcodeReaderApp(
@@ -31,6 +35,9 @@ void main() {
connectionRepository: connectionRepo,
scanRepository: scanRepo,
feedbackService: feedbackService,
adService: adService,
subscriptionService: subscriptionService,
prefs: prefs,
),
);
+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",
"aiohttp",
"pynput",
"pynput._info",
"pynput._util",
"pynput.keyboard",
"pynput.keyboard._base",
"pynput.mouse",
"pynput.mouse._base",
"pyperclip",
"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 = [
"tkinter",
"_tkinter",
@@ -232,6 +283,8 @@ def build(
for hidden_import in HIDDEN_IMPORTS:
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:
cmd.append(f"--exclude-module={excluded}")
+26 -1
View File
@@ -331,13 +331,35 @@ class KeyboardSimulator:
loop = asyncio.get_running_loop()
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:
if not self._ensure_controller():
return
if self._linux_xtest is not None:
if self._linux_xtest.tap_named(x11_name):
return
self.controller.tap(pynput_key)
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.type_char(char):
return
@@ -380,6 +402,9 @@ class KeyboardSimulator:
time.sleep(0.04)
return True
if not self._ensure_controller():
return False
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"
with self.controller.pressed(modifier):
@@ -388,7 +413,7 @@ class KeyboardSimulator:
return True
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!")
return False
+1 -1
View File
@@ -7,7 +7,7 @@ APP_NAME = "Barcode Reader Server"
APP_BINARY_NAME = "BarcodeServer"
APP_ID = "com.catellisrl.barcodereader"
APP_PUBLISHER = "Catelli Srl"
APP_VERSION = "1.0.1"
APP_VERSION = "1.0.6"
GITEA_BASE_URL = "https://gitea.catelli.it"
GITEA_REPO = "brontomark/barcode_reader_pc"