π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix QR detection: background thread, gesture conflict, remove cache
Amrithesh Kakkoth Ente6ada61514358
diff --git a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swiftindex 7a94d2fbe5..f7c656fffd 100644--- a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift+++ b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift@@ -2,6 +2,8 @@ import Flutterimport UIKitpublic class EnteQrPlugin: NSObject, FlutterPlugin {+ private static let detectionQueue = DispatchQueue(label: "io.ente.qr.detection", qos: .userInitiated)+public static func register(with registrar: FlutterPluginRegistrar) {let channel = FlutterMethodChannel(name: "ente_qr", binaryMessenger: registrar.messenger())let instance = EnteQrPlugin()@@ -40,135 +42,159 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {}private func scanQrCode(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)-- if let qrFeature = features.first as? CIQRCodeFeature,- let messageString = qrFeature.messageString {- result([- "success": true,- "content": messageString- ])- } else {- result([- "success": false,- "error": "No QR code found in image"- ])- }- }-- 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- }+ EnteQrPlugin.detectionQueue.async {+ guard let image = UIImage(contentsOfFile: imagePath) else {+ DispatchQueue.main.async {+ 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- }+ guard let cgImage = image.cgImage else {+ DispatchQueue.main.async {+ result([+ "success": false,+ "error": "Unable to get CGImage from UIImage"+ ])+ }+ return+ }- let detector = CIDetector(ofType: CIDetectorTypeQRCode,- context: nil,- options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])+ let detector = CIDetector(ofType: CIDetectorTypeQRCode,+ context: nil,+ options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])++ guard let qrDetector = detector else {+ DispatchQueue.main.async {+ result([+ "success": false,+ "error": "Unable to create QR code detector"+ ])+ }+ return+ }- 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)++ if let qrFeature = features.first as? CIQRCodeFeature,+ let messageString = qrFeature.messageString {+ DispatchQueue.main.async {+ result([+ "success": true,+ "content": messageString+ ])+ }+ } else {+ DispatchQueue.main.async {+ result([+ "success": false,+ "error": "No QR code found in image"+ ])+ }+ }}+ }- let ciImage = CIImage(cgImage: cgImage)- let features = qrDetector.features(in: ciImage)-- let imageWidth = CGFloat(cgImage.width)- let imageHeight = CGFloat(cgImage.height)+ private func scanAllQrCodes(from imagePath: String, result: @escaping FlutterResult) {+ EnteQrPlugin.detectionQueue.async {+ guard let image = UIImage(contentsOfFile: imagePath) else {+ DispatchQueue.main.async {+ result([+ "success": false,+ "error": "Unable to load image from path: \(imagePath)"+ ])+ }+ return+ }- var detections: [[String: Any]] = []+ guard let cgImage = image.cgImage else {+ DispatchQueue.main.async {+ result([+ "success": false,+ "error": "Unable to get CGImage from UIImage"+ ])+ }+ return+ }- for feature in features {- guard let qrFeature = feature as? CIQRCodeFeature,- let messageString = qrFeature.messageString else {- continue+ let detector = CIDetector(ofType: CIDetectorTypeQRCode,+ context: nil,+ options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])++ guard let qrDetector = detector else {+ DispatchQueue.main.async {+ result([+ "success": false,+ "error": "Unable to create QR code detector"+ ])+ }+ return}- // 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)-- // Add padding around finder patterns (matching Android's 15%)- let padX = (maxX - minX) * 0.15- let padY = (maxYci - minYci) * 0.15- let paddedMinX = max(minX - padX, 0)- let paddedMaxX = min(maxX + padX, imageWidth)- let paddedMinYci = max(minYci - padY, 0)- let paddedMaxYci = min(maxYci + padY, imageHeight)-- // Flip y: top-left origin- let normX = paddedMinX / imageWidth- let normY = 1.0 - (paddedMaxYci / imageHeight)- let normW = (paddedMaxX - paddedMinX) / imageWidth- let normH = (paddedMaxYci - paddedMinYci) / imageHeight-- detections.append([- "content": messageString,- "x": Double(normX),- "y": Double(normY),- "width": Double(normW),- "height": Double(normH),- ])- }+ 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)++ // Add padding around finder patterns (matching Android's 15%)+ let padX = (maxX - minX) * 0.15+ let padY = (maxYci - minYci) * 0.15+ let paddedMinX = max(minX - padX, 0)+ let paddedMaxX = min(maxX + padX, imageWidth)+ let paddedMinYci = max(minYci - padY, 0)+ let paddedMaxYci = min(maxYci + padY, imageHeight)++ // Flip y: top-left origin+ let normX = paddedMinX / imageWidth+ let normY = 1.0 - (paddedMaxYci / imageHeight)+ let normW = (paddedMaxX - paddedMinX) / imageWidth+ let normH = (paddedMaxYci - paddedMinYci) / 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- ])+ if detections.isEmpty {+ DispatchQueue.main.async {+ result([+ "success": false,+ "error": "No QR code found in image"+ ])+ }+ } else {+ DispatchQueue.main.async {+ result([+ "success": true,+ "detections": detections+ ])+ }+ }}}}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.dartindex c8b6232184..e3fc39e112 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@@ -9,8 +9,7 @@ import "package:photos/models/file/file_type.dart";import "package:photos/utils/file_util.dart";class QrCodeDetectionHelper {- static final Map<String, _DetectionResult> _cache = {};- static const _debounceDuration = Duration(milliseconds: 500);+ static const _debounceDuration = Duration(milliseconds: 1500);final Logger _logger = Logger("QrCodeDetectionHelper");final EnteQr _enteQr = EnteQr();@@ -33,26 +32,15 @@ class QrCodeDetectionHelper {return;}- // Return cached results immediately without debounce- final String cacheKey = _cacheKey(file);- final _DetectionResult? cachedResult = _cache[cacheKey];- if (cachedResult != null) {- if (_disposed || requestId != _requestId) return;- qrDetectionsNotifier.value = cachedResult.detections;- return;- }-qrDetectionsNotifier.value = const [];- // Debounce uncached scans so swiping doesn't trigger work_debounceTimer = Timer(_debounceDuration, () {- _scanFile(file, cacheKey, requestId);+ _scanFile(file, requestId);});}Future<void> _scanFile(EnteFile file,- String cacheKey,int requestId,) async {if (_disposed || requestId != _requestId) return;@@ -61,7 +49,6 @@ class QrCodeDetectionHelper {final File? localFile = await getFile(file);if (_disposed || requestId != _requestId) return;if (localFile == null || !localFile.existsSync()) {- _cache[cacheKey] = const _DetectionResult(detections: []);qrDetectionsNotifier.value = const [];return;}@@ -78,13 +65,10 @@ class QrCodeDetectionHelper {if (_disposed || requestId != _requestId) return;- final detectionResult = _DetectionResult(detections: detections);- _cache[cacheKey] = detectionResult;- qrDetectionsNotifier.value = detectionResult.detections;+ qrDetectionsNotifier.value = detections;} catch (error, stackTrace) {_logger.severe("QR code detection failed", error, stackTrace);if (_disposed || requestId != _requestId) return;- _cache[cacheKey] = const _DetectionResult(detections: []);qrDetectionsNotifier.value = const [];}}@@ -94,25 +78,9 @@ class QrCodeDetectionHelper {file.fileType == FileType.livePhoto;}- String _cacheKey(EnteFile file) {- if (file.uploadedFileID != null) {- return "qr_uploaded_${file.uploadedFileID}";- }- if (file.localID != null) {- return "qr_local_${file.localID}";- }- return "qr_generated_${file.generatedID}";- }-void dispose() {_disposed = true;_debounceTimer?.cancel();qrDetectionsNotifier.dispose();}}--class _DetectionResult {- final List<QrDetection> detections;-- 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.dartindex ef64f2a275..f6962d934e 100644--- 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@@ -140,20 +140,19 @@ class _QrTapRegionState extends State<_QrTapRegion> {const double minTapTarget = 48.0;final screenW = rawW < minTapTarget ? minTapTarget : rawW;final screenH = rawH < minTapTarget ? minTapTarget : rawH;- final screenX = widget.offsetX +- widget.detection.x * widget.displayWidth -- (screenW - rawW) / 2;- final screenY = widget.offsetY +- widget.detection.y * widget.displayHeight -- (screenH - rawH) / 2;+ final centerX = widget.offsetX ++ (widget.detection.x + widget.detection.width / 2) * widget.displayWidth;+ final centerY = widget.offsetY ++ (widget.detection.y + widget.detection.height / 2) *+ widget.displayHeight;return Positioned(- left: screenX,- top: screenY,+ left: centerX - screenW / 2,+ top: centerY - screenH / 2,width: screenW,height: screenH,child: Listener(- behavior: HitTestBehavior.translucent,+ behavior: HitTestBehavior.opaque,onPointerDown: (event) {_downPosition = event.position;_timer?.cancel();