Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add multi-QR code detection with per-QR long-press actions

Amrithesh Kakkoth Enteaa7e2a2f3519
diff --git a/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt b/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt
index 1ea1da596e..0b1cd484bf 100644
--- a/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt
+++ b/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt
@@ -11,6 +11,7 @@ import com.google.zxing.NotFoundException
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.Result as ZXingResult
import com.google.zxing.common.HybridBinarizer
+import com.google.zxing.multi.GenericMultipleBarcodeReader
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
@@ -46,7 +47,7 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
))
return
}
-
+
try {
val qrResult = scanQrCode(imagePath)
result.success(qrResult)
@@ -57,6 +58,26 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
))
}
}
+ "scanAllQrFromImage" -> {
+ val imagePath = call.argument<String>("imagePath")
+ if (imagePath == null) {
+ result.success(mapOf(
+ "success" to false,
+ "error" to "Image path is required"
+ ))
+ return
+ }
+
+ try {
+ val qrResult = scanAllQrCodes(imagePath)
+ result.success(qrResult)
+ } catch (e: Exception) {
+ result.success(mapOf(
+ "success" to false,
+ "error" to "Error scanning QR codes: ${e.message}"
+ ))
+ }
+ }
else -> {
result.notImplemented()
}
@@ -132,6 +153,118 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
+ private fun scanAllQrCodes(imagePath: String): Map<String, Any> {
+ try {
+ val file = File(imagePath)
+ if (!file.exists()) {
+ return mapOf(
+ "success" to false,
+ "error" to "Image file not found: $imagePath"
+ )
+ }
+
+ var bitmap = BitmapFactory.decodeFile(imagePath)
+ if (bitmap == null) {
+ return mapOf(
+ "success" to false,
+ "error" to "Unable to decode image file"
+ )
+ }
+
+ for (i in 0..2) {
+ if (i != 0) {
+ val newWidth = bitmap.width / (i * 2)
+ val newHeight = bitmap.height / (i * 2)
+ if (newWidth > 0 && newHeight > 0) {
+ bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
+ }
+ }
+
+ try {
+ val width = bitmap.width
+ val height = bitmap.height
+ val pixels = IntArray(width * height)
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
+
+ val source = RGBLuminanceSource(width, height, pixels)
+ val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
+
+ val reader = MultiFormatReader()
+ val hints = HashMap<DecodeHintType, Any>()
+ hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)
+ hints[DecodeHintType.TRY_HARDER] = true
+ hints[DecodeHintType.ALSO_INVERTED] = true
+ reader.setHints(hints)
+
+ val multiReader = GenericMultipleBarcodeReader(reader)
+ val results: Array<ZXingResult> = multiReader.decodeMultiple(binaryBitmap, hints)
+
+ val detections = mutableListOf<Map<String, Any>>()
+ val scaleX = if (i == 0) 1.0 else (i * 2).toDouble()
+ val scaleY = if (i == 0) 1.0 else (i * 2).toDouble()
+ val origBitmap = BitmapFactory.decodeFile(imagePath)
+ val origWidth = origBitmap.width.toDouble()
+ val origHeight = origBitmap.height.toDouble()
+
+ for (qrResult in results) {
+ val points = qrResult.resultPoints
+ if (points == null || points.isEmpty()) continue
+
+ var minX = Float.MAX_VALUE
+ var minY = Float.MAX_VALUE
+ var maxX = Float.MIN_VALUE
+ var maxY = Float.MIN_VALUE
+
+ for (point in points) {
+ if (point == null) continue
+ val px = point.x * scaleX.toFloat()
+ val py = point.y * scaleY.toFloat()
+ if (px < minX) minX = px
+ if (py < minY) minY = py
+ if (px > maxX) maxX = px
+ if (py > maxY) maxY = py
+ }
+
+ // Add padding around finder patterns (they mark corners, not edges)
+ val padX = (maxX - minX) * 0.15f
+ val padY = (maxY - minY) * 0.15f
+ minX = (minX - padX).coerceAtLeast(0f)
+ minY = (minY - padY).coerceAtLeast(0f)
+ maxX = (maxX + padX).coerceAtMost(origWidth.toFloat())
+ maxY = (maxY + padY).coerceAtMost(origHeight.toFloat())
+
+ detections.add(mapOf(
+ "content" to qrResult.text,
+ "x" to (minX / origWidth),
+ "y" to (minY / origHeight),
+ "width" to ((maxX - minX) / origWidth),
+ "height" to ((maxY - minY) / origHeight),
+ ))
+ }
+
+ if (detections.isNotEmpty()) {
+ return mapOf(
+ "success" to true,
+ "detections" to detections
+ )
+ }
+ } catch (e: NotFoundException) {
+ continue
+ }
+ }
+
+ return mapOf(
+ "success" to false,
+ "error" to "No QR code found in image"
+ )
+ } catch (e: Exception) {
+ return mapOf(
+ "success" to false,
+ "error" to "Error scanning QR codes: ${e.message}"
+ )
+ }
+ }
+
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
diff --git a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift
index 6a03563511..629daa67d4 100644
--- a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift
+++ b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift
@@ -22,8 +22,19 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {
])
return
}
-
+
scanQrCode(from: imagePath, result: result)
+ case "scanAllQrFromImage":
+ guard let args = call.arguments as? [String: Any],
+ let imagePath = args["imagePath"] as? String else {
+ result([
+ "success": false,
+ "error": "Image path is required"
+ ])
+ return
+ }
+
+ scanAllQrCodes(from: imagePath, result: result)
default:
result(FlutterMethodNotImplemented)
}
@@ -74,4 +85,83 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {
])
}
}
+
+ private func scanAllQrCodes(from imagePath: String, result: @escaping FlutterResult) {
+ guard let image = UIImage(contentsOfFile: imagePath) else {
+ result([
+ "success": false,
+ "error": "Unable to load image from path: \(imagePath)"
+ ])
+ return
+ }
+
+ guard let cgImage = image.cgImage else {
+ result([
+ "success": false,
+ "error": "Unable to get CGImage from UIImage"
+ ])
+ return
+ }
+
+ let detector = CIDetector(ofType: CIDetectorTypeQRCode,
+ context: nil,
+ options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
+
+ guard let qrDetector = detector else {
+ result([
+ "success": false,
+ "error": "Unable to create QR code detector"
+ ])
+ return
+ }
+
+ let ciImage = CIImage(cgImage: cgImage)
+ let features = qrDetector.features(in: ciImage)
+
+ let imageWidth = CGFloat(cgImage.width)
+ let imageHeight = CGFloat(cgImage.height)
+
+ var detections: [[String: Any]] = []
+
+ for feature in features {
+ guard let qrFeature = feature as? CIQRCodeFeature,
+ let messageString = qrFeature.messageString else {
+ continue
+ }
+
+ // Core Image has origin at bottom-left with y-up.
+ // Convert to normalized [0,1] coords with origin top-left, y-down.
+ let minX = min(qrFeature.topLeft.x, qrFeature.bottomLeft.x)
+ let maxX = max(qrFeature.topRight.x, qrFeature.bottomRight.x)
+ // In CI coords, topLeft.y > bottomLeft.y (y goes up)
+ let minYci = min(qrFeature.bottomLeft.y, qrFeature.bottomRight.y)
+ let maxYci = max(qrFeature.topLeft.y, qrFeature.topRight.y)
+
+ // Flip y: top-left origin
+ let normX = minX / imageWidth
+ let normY = 1.0 - (maxYci / imageHeight)
+ let normW = (maxX - minX) / imageWidth
+ let normH = (maxYci - minYci) / imageHeight
+
+ detections.append([
+ "content": messageString,
+ "x": Double(normX),
+ "y": Double(normY),
+ "width": Double(normW),
+ "height": Double(normH),
+ ])
+ }
+
+ if detections.isEmpty {
+ result([
+ "success": false,
+ "error": "No QR code found in image"
+ ])
+ } else {
+ result([
+ "success": true,
+ "detections": detections
+ ])
+ }
+ }
}
diff --git a/mobile/apps/auth/plugins/qr/lib/ente_qr.dart b/mobile/apps/auth/plugins/qr/lib/ente_qr.dart
index 0488d6aeec..ee7f3f2e10 100644
--- a/mobile/apps/auth/plugins/qr/lib/ente_qr.dart
+++ b/mobile/apps/auth/plugins/qr/lib/ente_qr.dart
@@ -1,6 +1,7 @@
import 'package:ente_qr/ente_qr_platform_interface.dart';
-export 'ente_qr_platform_interface.dart' show QrScanResult;
+export 'ente_qr_platform_interface.dart'
+ show QrDetection, QrScanResult, QrScanResults;
class EnteQr {
Future<String?> getPlatformVersion() {
@@ -13,18 +14,15 @@ class EnteQr {
///
/// Returns a [QrScanResult] containing either the QR code content on success
/// or an error message on failure.
- ///
- /// Example:
- /// ```dart
- /// final qr = EnteQr();
- /// final result = await qr.scanQrFromImage('/path/to/image.jpg');
- /// if (result.success) {
- /// print('QR Code content: ${result.content}');
- /// } else {
- /// print('Error: ${result.error}');
- /// }
- /// ```
Future<QrScanResult> scanQrFromImage(String imagePath) {
return EnteQrPlatform.instance.scanQrFromImage(imagePath);
}
+
+ /// Scans all QR codes from an image file at the given path.
+ ///
+ /// Returns a [QrScanResults] containing a list of [QrDetection] with
+ /// content and normalized bounding boxes for each detected QR code.
+ Future<QrScanResults> scanAllQrFromImage(String imagePath) {
+ return EnteQrPlatform.instance.scanAllQrFromImage(imagePath);
+ }
}
diff --git a/mobile/apps/auth/plugins/qr/lib/ente_qr_method_channel.dart b/mobile/apps/auth/plugins/qr/lib/ente_qr_method_channel.dart
index 825466405a..5fe06b5099 100644
--- a/mobile/apps/auth/plugins/qr/lib/ente_qr_method_channel.dart
+++ b/mobile/apps/auth/plugins/qr/lib/ente_qr_method_channel.dart
@@ -49,4 +49,42 @@ class MethodChannelEnteQr extends EnteQrPlatform {
return QrScanResult.error('Unexpected error: $e');
}
}
+
+ @override
+ Future<QrScanResults> scanAllQrFromImage(String imagePath) async {
+ try {
+ final dynamic result = await methodChannel.invokeMethod(
+ 'scanAllQrFromImage',
+ {'imagePath': imagePath},
+ );
+
+ if (result == null) {
+ return QrScanResults.error('Failed to scan QR codes');
+ }
+
+ final Map<String, dynamic> resultMap =
+ Map<String, dynamic>.from(result as Map);
+
+ final bool success = resultMap['success'] as bool? ?? false;
+ if (success) {
+ final List<dynamic>? rawDetections =
+ resultMap['detections'] as List<dynamic>?;
+ if (rawDetections != null && rawDetections.isNotEmpty) {
+ final detections = rawDetections.map((d) {
+ return QrDetection.fromMap(Map<String, dynamic>.from(d as Map));
+ }).toList();
+ return QrScanResults.fromDetections(detections);
+ } else {
+ return QrScanResults.error('No QR codes found in image');
+ }
+ } else {
+ final String? error = resultMap['error'] as String?;
+ return QrScanResults.error(error ?? 'Unknown error occurred');
+ }
+ } on PlatformException catch (e) {
+ return QrScanResults.error('Platform error: ${e.message}');
+ } catch (e) {
+ return QrScanResults.error('Unexpected error: $e');
+ }
+ }
}
diff --git a/mobile/apps/auth/plugins/qr/lib/ente_qr_platform_interface.dart b/mobile/apps/auth/plugins/qr/lib/ente_qr_platform_interface.dart
index 4b870368e7..08bbd45518 100644
--- a/mobile/apps/auth/plugins/qr/lib/ente_qr_platform_interface.dart
+++ b/mobile/apps/auth/plugins/qr/lib/ente_qr_platform_interface.dart
@@ -28,6 +28,70 @@ class QrScanResult {
}
}
+/// A single detected QR code with its content and normalized bounding box.
+class QrDetection {
+ /// The decoded QR code content.
+ final String content;
+
+ /// Normalized x coordinate of the bounding box (0.0 to 1.0).
+ final double x;
+
+ /// Normalized y coordinate of the bounding box (0.0 to 1.0).
+ final double y;
+
+ /// Normalized width of the bounding box (0.0 to 1.0).
+ final double width;
+
+ /// Normalized height of the bounding box (0.0 to 1.0).
+ final double height;
+
+ const QrDetection({
+ required this.content,
+ required this.x,
+ required this.y,
+ required this.width,
+ required this.height,
+ });
+
+ factory QrDetection.fromMap(Map<String, dynamic> map) {
+ return QrDetection(
+ content: map['content'] as String,
+ x: (map['x'] as num).toDouble(),
+ y: (map['y'] as num).toDouble(),
+ width: (map['width'] as num).toDouble(),
+ height: (map['height'] as num).toDouble(),
+ );
+ }
+}
+
+/// The result of scanning for multiple QR codes.
+class QrScanResults {
+ final List<QrDetection> detections;
+ final String? error;
+ final bool success;
+
+ const QrScanResults({
+ required this.detections,
+ this.error,
+ required this.success,
+ });
+
+ factory QrScanResults.fromDetections(List<QrDetection> detections) {
+ return QrScanResults(
+ detections: detections,
+ success: true,
+ );
+ }
+
+ factory QrScanResults.error(String error) {
+ return QrScanResults(
+ detections: const [],
+ error: error,
+ success: false,
+ );
+ }
+}
+
abstract class EnteQrPlatform extends PlatformInterface {
/// Constructs a EnteQrPlatform.
EnteQrPlatform() : super(token: _token);
@@ -58,4 +122,10 @@ abstract class EnteQrPlatform extends PlatformInterface {
Future<QrScanResult> scanQrFromImage(String imagePath) {
throw UnimplementedError('scanQrFromImage() has not been implemented.');
}
+
+ /// Scans all QR codes from an image file at the given path.
+ /// Returns a list of detections with content and bounding boxes.
+ Future<QrScanResults> scanAllQrFromImage(String imagePath) {
+ throw UnimplementedError('scanAllQrFromImage() has not been implemented.');
+ }
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
index f2c80e5217..51a63fe0bf 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
@@ -28,8 +28,8 @@ import "package:photos/ui/viewer/file/file_app_bar.dart";
import "package:photos/ui/viewer/file/file_bottom_bar.dart";
import 'package:photos/ui/viewer/file/file_widget.dart';
import "package:photos/ui/viewer/file/panorama_viewer_screen.dart";
-import "package:photos/ui/viewer/file/qr_code_content_sheet.dart";
import "package:photos/ui/viewer/file/qr_code_detection_helper.dart";
+import "package:photos/ui/viewer/file/qr_code_highlight_overlay.dart";
import "package:photos/ui/viewer/file/text_detection_overlay_button.dart";
import 'package:photos/ui/viewer/gallery/gallery.dart';
import 'package:photos/utils/dialog_util.dart';
@@ -133,7 +133,6 @@ class _BodyState extends State<_Body> {
bool swipeLocked = false;
late final StreamSubscription<GuestViewEvent> _guestViewEventSubscription;
QrCodeDetectionHelper? _qrHelper;
- Timer? _longPressTimer;
@override
void initState() {
@@ -167,7 +166,6 @@ class _BodyState extends State<_Body> {
_guestViewEventSubscription.cancel();
_pageController.dispose();
_selectedIndexNotifier.dispose();
- _longPressTimer?.cancel();
_qrHelper?.dispose();
super.dispose();
@@ -266,6 +264,29 @@ class _BodyState extends State<_Body> {
);
},
),
+ if (_qrHelper != null)
+ ValueListenableBuilder(
+ valueListenable: _selectedIndexNotifier,
+ builder: (BuildContext context, int selectedIndex, _) {
+ if (widget.config.mode == DetailPageMode.minimalistic ||
+ isGuestView ||
+ _files![selectedIndex] is TrashFile) {
+ return const SizedBox.shrink();
+ }
+ return ValueListenableBuilder(
+ valueListenable: _qrHelper!.qrDetectionsNotifier,
+ builder: (context, detections, _) {
+ return QrCodeHighlightOverlay(
+ detections: detections,
+ file: _files![selectedIndex],
+ enableFullScreenNotifier:
+ InheritedDetailPageState.of(context)
+ .enableFullScreenNotifier,
+ );
+ },
+ );
+ },
+ ),
ValueListenableBuilder(
valueListenable: _selectedIndexNotifier,
builder: (BuildContext context, int selectedIndex, _) {
@@ -362,30 +383,13 @@ class _BodyState extends State<_Body> {
},
backgroundDecoration: const BoxDecoration(color: Colors.black),
);
- return Listener(
- onPointerDown: (_) {
- _longPressTimer?.cancel();
- _longPressTimer = Timer(
- const Duration(milliseconds: 500),
- () => _onLongPress(context, file),
- );
+ return GestureDetector(
+ onTap: () {
+ file.fileType != FileType.video
+ ? InheritedDetailPageState.of(context).toggleFullScreenByUser()
+ : null;
},
- onPointerUp: (_) => _longPressTimer?.cancel(),
- onPointerCancel: (_) => _longPressTimer?.cancel(),
- onPointerMove: (event) {
- if (event.delta.distance > 5) {
- _longPressTimer?.cancel();
- }
- },
- child: GestureDetector(
- onTap: () {
- file.fileType != FileType.video
- ? InheritedDetailPageState.of(context)
- .toggleFullScreenByUser()
- : null;
- },
- child: fileContent,
- ),
+ child: fileContent,
);
},
onPageChanged: (index) {
@@ -530,20 +534,6 @@ class _BodyState extends State<_Body> {
);
}
- Future<void> _onLongPress(BuildContext context, EnteFile file) async {
- if (file.fileType != FileType.image) return;
- if (widget.config.mode == DetailPageMode.minimalistic) return;
- if (isGuestView) return;
- if (file is TrashFile) return;
-
- final content = _qrHelper?.qrContentNotifier.value;
- if (content == null || content.isEmpty) return;
-
- await HapticFeedback.lightImpact();
- if (!mounted) return;
- await showQrCodeContentSheet(context, content: content);
- }
-
Future<void> _updateSharedCollectionState(EnteFile file) async {
final fileID = file.uploadedFileID;
final notifier =
diff --git a/mobile/apps/photos/lib/ui/viewer/file/qr_code_content_sheet.dart b/mobile/apps/photos/lib/ui/viewer/file/qr_code_content_sheet.dart
index d8185ca03c..91c4a0de62 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/qr_code_content_sheet.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/qr_code_content_sheet.dart
@@ -1,3 +1,4 @@
+import "package:ente_qr/ente_qr.dart";
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:photos/generated/l10n.dart";
@@ -9,19 +10,84 @@ import "package:url_launcher/url_launcher.dart";
Future<void> showQrCodeContentSheet(
BuildContext context, {
- required String content,
+ required List<QrDetection> detections,
+ int initialIndex = 0,
}) {
return showBaseBottomSheet(
context,
title: AppLocalizations.of(context).qrCode,
- child: _QrCodeContentBody(content: content),
+ child: detections.length == 1
+ ? _SingleQrContent(content: detections.first.content)
+ : _MultiQrContent(
+ detections: detections,
+ initialIndex: initialIndex,
+ ),
);
}
-class _QrCodeContentBody extends StatelessWidget {
+class _SingleQrContent extends StatelessWidget {
+ final String content;
+
+ const _SingleQrContent({required this.content});
+
+ @override
+ Widget build(BuildContext context) {
+ return _QrContentEntry(content: content);
+ }
+}
+
+class _MultiQrContent extends StatelessWidget {
+ final List<QrDetection> detections;
+ final int initialIndex;
+
+ const _MultiQrContent({
+ required this.detections,
+ required this.initialIndex,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (int i = 0; i < detections.length; i++) ...[
+ if (i > 0) Divider(color: colorScheme.strokeFaint, height: 24),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Container(
+ width: 24,
+ height: 24,
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: colorScheme.primary700,
+ shape: BoxShape.circle,
+ ),
+ child: Text(
+ "${i + 1}",
+ style: textTheme.mini.copyWith(color: Colors.white),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: _QrContentEntry(content: detections[i].content),
+ ),
+ ],
+ ),
+ ],
+ ],
+ );
+ }
+}
+
+class _QrContentEntry extends StatelessWidget {
final String content;
- const _QrCodeContentBody({required this.content});
+ const _QrContentEntry({required this.content});
@override
Widget build(BuildContext context) {
diff --git a/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dart b/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dart
index 6d1816f7e7..34adb65873 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dart
@@ -12,7 +12,8 @@ class QrCodeDetectionHelper {
final Logger _logger = Logger("QrCodeDetectionHelper");
final EnteQr _enteQr = EnteQr();
- final ValueNotifier<String?> qrContentNotifier = ValueNotifier<String?>(null);
+ final ValueNotifier<List<QrDetection>> qrDetectionsNotifier =
+ ValueNotifier<List<QrDetection>>(const []);
int _requestId = 0;
bool _disposed = false;
@@ -22,7 +23,7 @@ class QrCodeDetectionHelper {
final int requestId = ++_requestId;
if (!isEligible) {
- qrContentNotifier.value = null;
+ qrDetectionsNotifier.value = const [];
return;
}
@@ -30,46 +31,41 @@ class QrCodeDetectionHelper {
final _DetectionResult? cachedResult = _cache[cacheKey];
if (cachedResult != null) {
if (_disposed || requestId != _requestId) return;
- qrContentNotifier.value = cachedResult.content;
+ qrDetectionsNotifier.value = cachedResult.detections;
return;
}
- qrContentNotifier.value = null;
+ qrDetectionsNotifier.value = const [];
try {
final File? localFile = await getFile(file);
if (_disposed || requestId != _requestId) return;
if (localFile == null || !localFile.existsSync()) {
- _cache[cacheKey] = const _DetectionResult(hasQr: false);
- qrContentNotifier.value = null;
+ _cache[cacheKey] = const _DetectionResult(detections: []);
+ qrDetectionsNotifier.value = const [];
return;
}
- bool hasQr = false;
- String? qrContent;
+ List<QrDetection> detections = const [];
try {
- final result = await _enteQr.scanQrFromImage(localFile.path);
- if (result.success && result.content != null) {
- hasQr = true;
- qrContent = result.content;
+ final result = await _enteQr.scanAllQrFromImage(localFile.path);
+ if (result.success && result.detections.isNotEmpty) {
+ detections = result.detections;
}
} catch (error, stackTrace) {
- _logger.severe("Failed to scan QR code", error, stackTrace);
+ _logger.severe("Failed to scan QR codes", error, stackTrace);
}
if (_disposed || requestId != _requestId) return;
- final detectionResult = _DetectionResult(
- hasQr: hasQr,
- content: hasQr ? qrContent : null,
- );
+ final detectionResult = _DetectionResult(detections: detections);
_cache[cacheKey] = detectionResult;
- qrContentNotifier.value = detectionResult.content;
+ qrDetectionsNotifier.value = detectionResult.detections;
} catch (error, stackTrace) {
_logger.severe("QR code detection failed", error, stackTrace);
if (_disposed || requestId != _requestId) return;
- _cache[cacheKey] = const _DetectionResult(hasQr: false);
- qrContentNotifier.value = null;
+ _cache[cacheKey] = const _DetectionResult(detections: []);
+ qrDetectionsNotifier.value = const [];
}
}
@@ -90,13 +86,12 @@ class QrCodeDetectionHelper {
void dispose() {
_disposed = true;
- qrContentNotifier.dispose();
+ qrDetectionsNotifier.dispose();
}
}
class _DetectionResult {
- final bool hasQr;
- final String? content;
+ final List<QrDetection> detections;
- const _DetectionResult({required this.hasQr, this.content});
+ const _DetectionResult({required this.detections});
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/qr_code_highlight_overlay.dart b/mobile/apps/photos/lib/ui/viewer/file/qr_code_highlight_overlay.dart
new file mode 100644
index 0000000000..6387c50650
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/file/qr_code_highlight_overlay.dart
@@ -0,0 +1,123 @@
+import "package:ente_qr/ente_qr.dart";
+import "package:flutter/foundation.dart";
+import "package:flutter/material.dart";
+import "package:flutter/services.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/ui/viewer/file/qr_code_content_sheet.dart";
+import "package:url_launcher/url_launcher.dart";
+
+class QrCodeHighlightOverlay extends StatelessWidget {
+ final List<QrDetection> detections;
+ final EnteFile file;
+ final ValueListenable<bool> enableFullScreenNotifier;
+
+ const QrCodeHighlightOverlay({
+ required this.detections,
+ required this.file,
+ required this.enableFullScreenNotifier,
+ super.key,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ if (detections.isEmpty || !file.hasDimensions) {
+ return const SizedBox.shrink();
+ }
+
+ return ValueListenableBuilder<bool>(
+ valueListenable: enableFullScreenNotifier,
+ builder: (context, isFullScreen, _) {
+ if (isFullScreen) {
+ return const SizedBox.shrink();
+ }
+
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final screenWidth = constraints.maxWidth;
+ final screenHeight = constraints.maxHeight;
+ final imageAspect = file.width / file.height;
+ final screenAspect = screenWidth / screenHeight;
+
+ double displayWidth;
+ double displayHeight;
+ if (imageAspect > screenAspect) {
+ displayWidth = screenWidth;
+ displayHeight = screenWidth / imageAspect;
+ } else {
+ displayHeight = screenHeight;
+ displayWidth = screenHeight * imageAspect;
+ }
+
+ final offsetX = (screenWidth - displayWidth) / 2;
+ final offsetY = (screenHeight - displayHeight) / 2;
+
+ return Stack(
+ children: [
+ for (final detection in detections)
+ _QrTapRegion(
+ detection: detection,
+ allDetections: detections,
+ offsetX: offsetX,
+ offsetY: offsetY,
+ displayWidth: displayWidth,
+ displayHeight: displayHeight,
+ ),
+ ],
+ );
+ },
+ );
+ },
+ );
+ }
+}
+
+class _QrTapRegion extends StatelessWidget {
+ final QrDetection detection;
+ final List<QrDetection> allDetections;
+ final double offsetX;
+ final double offsetY;
+ final double displayWidth;
+ final double displayHeight;
+
+ const _QrTapRegion({
+ required this.detection,
+ required this.allDetections,
+ required this.offsetX,
+ required this.offsetY,
+ required this.displayWidth,
+ required this.displayHeight,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final screenX = offsetX + detection.x * displayWidth;
+ final screenY = offsetY + detection.y * displayHeight;
+ final screenW = detection.width * displayWidth;
+ final screenH = detection.height * displayHeight;
+
+ return Positioned(
+ left: screenX,
+ top: screenY,
+ width: screenW,
+ height: screenH,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onLongPress: () {
+ HapticFeedback.lightImpact();
+ final uri = Uri.tryParse(detection.content);
+ final isUrl =
+ uri != null && (uri.scheme == "http" || uri.scheme == "https");
+ if (isUrl) {
+ launchUrl(uri);
+ } else {
+ showQrCodeContentSheet(
+ context,
+ detections: [detection],
+ );
+ }
+ },
+ child: const SizedBox.expand(),
+ ),
+ );
+ }
+}