Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] Switch QR detection to ZXing-CPP native and fix overlay hit testing

Amrithesh Kakkoth Entee20fa0ff8981
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 7386f80649..5ab121d401 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
@@ -2,6 +2,8 @@ package io.ente.auth.ente_qr
import android.graphics.Bitmap
import android.graphics.BitmapFactory
+import android.graphics.Canvas
+import android.graphics.Color
import android.graphics.Matrix
import androidx.exifinterface.media.ExifInterface
import androidx.annotation.NonNull
@@ -29,6 +31,10 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
private lateinit var channel : MethodChannel
private val executor = Executors.newSingleThreadExecutor()
+ companion object {
+ private const val SCAN_MAX_DIM = 1200
+ }
+
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "ente_qr")
channel.setMethodCallHandler(this)
@@ -87,12 +93,32 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
- /**
- * Load a bitmap and apply EXIF orientation so the image is upright
- * before QR detection.
- */
- private fun loadBitmapWithOrientation(imagePath: String): Bitmap? {
- val bitmap = BitmapFactory.decodeFile(imagePath) ?: return null
+ // ── Image loading & pre-processing ────────────────────────────────
+
+ private fun loadAtMaxDimension(imagePath: String, maxDim: Int): Bitmap? {
+ val opts = BitmapFactory.Options()
+ opts.inJustDecodeBounds = true
+ BitmapFactory.decodeFile(imagePath, opts)
+ val w = opts.outWidth
+ val h = opts.outHeight
+ if (w <= 0 || h <= 0) return null
+
+ var inSampleSize = 1
+ if (w > maxDim || h > maxDim) {
+ val halfW = w / 2
+ val halfH = h / 2
+ while (halfW / inSampleSize >= maxDim ||
+ halfH / inSampleSize >= maxDim) {
+ inSampleSize *= 2
+ }
+ }
+
+ val decodeOpts = BitmapFactory.Options()
+ decodeOpts.inSampleSize = inSampleSize
+ return BitmapFactory.decodeFile(imagePath, decodeOpts)
+ }
+
+ private fun applyExifOrientation(bitmap: Bitmap, imagePath: String): Bitmap {
return try {
val exif = ExifInterface(imagePath)
val orientation = exif.getAttributeInt(
@@ -115,68 +141,89 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
- private fun createDecodeHints(): HashMap<DecodeHintType, Any> {
+ private fun fixTransparency(bitmap: Bitmap): Bitmap {
+ if (!bitmap.hasAlpha()) return bitmap
+ val opaque = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(opaque)
+ canvas.drawColor(Color.WHITE)
+ canvas.drawBitmap(bitmap, 0f, 0f, null)
+ bitmap.recycle()
+ return opaque
+ }
+
+ private fun prepareBitmap(imagePath: String, maxDim: Int): Bitmap? {
+ val raw = loadAtMaxDimension(imagePath, maxDim) ?: return null
+ val oriented = applyExifOrientation(raw, imagePath)
+ return fixTransparency(oriented)
+ }
+
+ // ── ZXing helpers ─────────────────────────────────────────────────
+
+ private fun fastHints(): HashMap<DecodeHintType, Any> {
val hints = HashMap<DecodeHintType, Any>()
hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)
- hints[DecodeHintType.TRY_HARDER] = true
hints[DecodeHintType.ALSO_INVERTED] = true
return hints
}
+ private fun thoroughHints(): HashMap<DecodeHintType, Any> {
+ val hints = fastHints()
+ hints[DecodeHintType.TRY_HARDER] = true
+ return hints
+ }
+
private fun getPixels(bitmap: Bitmap): IntArray {
- val width = bitmap.width
- val height = bitmap.height
- val pixels = IntArray(width * height)
- bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
+ val pixels = IntArray(bitmap.width * bitmap.height)
+ bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
return pixels
}
- // ── ZXing decode strategies ───────────────────────────────────────
- //
- // 1. HybridBinarizer at original resolution (fast, handles most cases)
- // 2. GlobalHistogramBinarizer at original resolution (uneven lighting)
- // 3. HybridBinarizer at half resolution (moirΓ©, noise)
+ // ── ZXing decode ──────────────────────────────────────────────────
private fun zxingDecode(pixels: IntArray, width: Int, height: Int, hints: HashMap<DecodeHintType, Any>): ZXingResult? {
- val source = RGBLuminanceSource(width, height, pixels)
val reader = MultiFormatReader()
reader.setHints(hints)
- // Strategy 1: HybridBinarizer
try {
+ val source = RGBLuminanceSource(width, height, pixels)
return reader.decode(BinaryBitmap(HybridBinarizer(source)))
} catch (_: NotFoundException) {}
- // Strategy 2: GlobalHistogramBinarizer
try {
- val source2 = RGBLuminanceSource(width, height, pixels)
- return reader.decode(BinaryBitmap(GlobalHistogramBinarizer(source2)))
+ val source = RGBLuminanceSource(width, height, pixels)
+ return reader.decode(BinaryBitmap(GlobalHistogramBinarizer(source)))
} catch (_: NotFoundException) {}
return null
}
private fun zxingDecodeMultiple(pixels: IntArray, width: Int, height: Int, hints: HashMap<DecodeHintType, Any>): Array<ZXingResult>? {
- val source = RGBLuminanceSource(width, height, pixels)
val reader = MultiFormatReader()
reader.setHints(hints)
val multiReader = GenericMultipleBarcodeReader(reader)
- // Strategy 1: HybridBinarizer
try {
+ val source = RGBLuminanceSource(width, height, pixels)
return multiReader.decodeMultiple(BinaryBitmap(HybridBinarizer(source)), hints)
} catch (_: NotFoundException) {}
- // Strategy 2: GlobalHistogramBinarizer
try {
- val source2 = RGBLuminanceSource(width, height, pixels)
- return multiReader.decodeMultiple(BinaryBitmap(GlobalHistogramBinarizer(source2)), hints)
+ val source = RGBLuminanceSource(width, height, pixels)
+ return multiReader.decodeMultiple(BinaryBitmap(GlobalHistogramBinarizer(source)), hints)
} catch (_: NotFoundException) {}
return null
}
// ── Main scan methods ─────────────────────────────────────────────
+ //
+ // Two-phase strategy:
+ // Phase 1 (fast): No TRY_HARDER, single resolution, dual binarizer
+ // β†’ resolves most photos in <200ms
+ // Phase 2 (thorough): Only if phase 1 found something β€” re-scan
+ // with TRY_HARDER to catch additional QR codes
+ //
+ // Images without QR codes (the common case) only pay the phase 1 cost.
private fun scanQrCode(imagePath: String): Map<String, Any> {
try {
@@ -185,33 +232,24 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
return mapOf("success" to false, "error" to "Image file not found: $imagePath")
}
- val bitmap = loadBitmapWithOrientation(imagePath)
+ val bitmap = prepareBitmap(imagePath, SCAN_MAX_DIM)
?: return mapOf("success" to false, "error" to "Unable to decode image file")
try {
- val hints = createDecodeHints()
-
- // Try at original resolution
val pixels = getPixels(bitmap)
- val result = zxingDecode(pixels, bitmap.width, bitmap.height, hints)
- if (result != null) {
- return mapOf("success" to true, "content" to result.text)
+ val w = bitmap.width
+ val h = bitmap.height
+
+ // Phase 1: fast scan (no TRY_HARDER)
+ val fastResult = zxingDecode(pixels, w, h, fastHints())
+ if (fastResult != null) {
+ return mapOf("success" to true, "content" to fastResult.text)
}
- // Fallback: half resolution (helps with moirΓ©/noise)
- val halfW = bitmap.width / 2
- val halfH = bitmap.height / 2
- if (halfW > 0 && halfH > 0) {
- val halfBitmap = Bitmap.createScaledBitmap(bitmap, halfW, halfH, true)
- try {
- val halfPixels = getPixels(halfBitmap)
- val halfResult = zxingDecode(halfPixels, halfW, halfH, hints)
- if (halfResult != null) {
- return mapOf("success" to true, "content" to halfResult.text)
- }
- } finally {
- halfBitmap.recycle()
- }
+ // Phase 2: thorough scan (TRY_HARDER) only as fallback
+ val thoroughResult = zxingDecode(pixels, w, h, thoroughHints())
+ if (thoroughResult != null) {
+ return mapOf("success" to true, "content" to thoroughResult.text)
}
return mapOf("success" to false, "error" to "No QR code found in image")
@@ -229,40 +267,31 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
return mapOf("success" to false, "error" to "Image file not found: $imagePath")
}
- val bitmap = loadBitmapWithOrientation(imagePath)
+ val bitmap = prepareBitmap(imagePath, SCAN_MAX_DIM)
?: return mapOf("success" to false, "error" to "Unable to decode image file")
try {
- val imgWidth = bitmap.width.toDouble()
- val imgHeight = bitmap.height.toDouble()
- val hints = createDecodeHints()
-
- // Try at original resolution
val pixels = getPixels(bitmap)
- val results = zxingDecodeMultiple(pixels, bitmap.width, bitmap.height, hints)
- if (results != null && results.isNotEmpty()) {
- val detections = buildDetections(results, imgWidth, imgHeight, 1.0)
+ val w = bitmap.width
+ val h = bitmap.height
+ val imgW = w.toDouble()
+ val imgH = h.toDouble()
+
+ // Phase 1: fast scan (no TRY_HARDER)
+ val fastResults = zxingDecodeMultiple(pixels, w, h, fastHints())
+ if (fastResults != null && fastResults.isNotEmpty()) {
+ val detections = buildDetections(fastResults, imgW, imgH)
if (detections.isNotEmpty()) {
return mapOf("success" to true, "detections" to detections)
}
}
- // Fallback: half resolution
- val halfW = bitmap.width / 2
- val halfH = bitmap.height / 2
- if (halfW > 0 && halfH > 0) {
- val halfBitmap = Bitmap.createScaledBitmap(bitmap, halfW, halfH, true)
- try {
- val halfPixels = getPixels(halfBitmap)
- val halfResults = zxingDecodeMultiple(halfPixels, halfW, halfH, hints)
- if (halfResults != null && halfResults.isNotEmpty()) {
- val detections = buildDetections(halfResults, imgWidth, imgHeight, 2.0)
- if (detections.isNotEmpty()) {
- return mapOf("success" to true, "detections" to detections)
- }
- }
- } finally {
- halfBitmap.recycle()
+ // Phase 2: thorough scan (TRY_HARDER) only as fallback
+ val thoroughResults = zxingDecodeMultiple(pixels, w, h, thoroughHints())
+ if (thoroughResults != null && thoroughResults.isNotEmpty()) {
+ val detections = buildDetections(thoroughResults, imgW, imgH)
+ if (detections.isNotEmpty()) {
+ return mapOf("success" to true, "detections" to detections)
}
}
@@ -278,7 +307,6 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
results: Array<ZXingResult>,
imgWidth: Double,
imgHeight: Double,
- scale: Double,
): List<Map<String, Any>> {
val detections = mutableListOf<Map<String, Any>>()
@@ -293,12 +321,10 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
for (point in points) {
if (point == null) continue
- val px = (point.x * scale).toFloat()
- val py = (point.y * scale).toFloat()
- if (px < minX) minX = px
- if (py < minY) minY = py
- if (px > maxX) maxX = px
- if (py > maxY) maxY = py
+ if (point.x < minX) minX = point.x
+ if (point.y < minY) minY = point.y
+ if (point.x > maxX) maxX = point.x
+ if (point.y > maxY) maxY = point.y
}
// Add padding around finder patterns
diff --git a/mobile/apps/photos/android/app/build.gradle b/mobile/apps/photos/android/app/build.gradle
index 6e7336dd31..9e724d5db8 100644
--- a/mobile/apps/photos/android/app/build.gradle
+++ b/mobile/apps/photos/android/app/build.gradle
@@ -107,6 +107,10 @@ android {
}
}
+ packagingOptions {
+ pickFirst 'lib/*/libc++_shared.so'
+ }
+
buildTypes {
release {
signingConfig signingConfigs.release
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 9709696aa5..a107be2ee2 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
@@ -382,6 +382,7 @@ class _BodyState extends State<_Body> {
});
},
backgroundDecoration: const BoxDecoration(color: Colors.black),
+ qrDetectionsNotifier: _qrHelper?.qrDetectionsNotifier,
);
return GestureDetector(
onTap: () {
diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/file_widget.dart
index 9c311fd4f5..3e4602780b 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/file_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/file_widget.dart
@@ -1,3 +1,4 @@
+import "package:ente_qr/ente_qr.dart";
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:photos/models/file/file.dart';
@@ -15,6 +16,7 @@ class FileWidget extends StatelessWidget {
final bool? autoPlay;
final bool? isFromMemories;
final Function({required int memoryDuration})? onFinalFileLoad;
+ final ValueNotifier<List<QrDetection>>? qrDetectionsNotifier;
const FileWidget(
this.file, {
@@ -25,6 +27,7 @@ class FileWidget extends StatelessWidget {
this.backgroundDecoration,
this.isFromMemories = false,
this.onFinalFileLoad,
+ this.qrDetectionsNotifier,
super.key,
});
@@ -45,6 +48,7 @@ class FileWidget extends StatelessWidget {
isFromMemories: isFromMemories ?? false,
key: key ?? ValueKey(fileKey),
onFinalFileLoad: onFinalFileLoad,
+ qrDetectionsNotifier: qrDetectionsNotifier,
);
} else if (file.fileType == FileType.video) {
// use old video widget on iOS simulator as the new one crashes while
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 f78b0a5950..1a95ab1d01 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
@@ -1,4 +1,5 @@
import "dart:async";
+import "dart:collection";
import "dart:io";
import "package:ente_qr/ente_qr.dart";
@@ -10,6 +11,7 @@ import "package:photos/utils/file_util.dart";
class QrCodeDetectionHelper {
static const _debounceDuration = Duration(milliseconds: 500);
+ static const _maxCacheSize = 20;
final Logger _logger = Logger("QrCodeDetectionHelper");
final EnteQr _enteQr = EnteQr();
@@ -17,6 +19,10 @@ class QrCodeDetectionHelper {
final ValueNotifier<List<QrDetection>> qrDetectionsNotifier =
ValueNotifier<List<QrDetection>>(const []);
+ /// LRU cache keyed by file tag (unique identifier).
+ final LinkedHashMap<String, List<QrDetection>> _cache =
+ LinkedHashMap<String, List<QrDetection>>();
+
int _requestId = 0;
bool _disposed = false;
Timer? _debounceTimer;
@@ -32,6 +38,14 @@ class QrCodeDetectionHelper {
return;
}
+ // Return cached result immediately if available
+ final cached = _cache[file.tag];
+ if (cached != null) {
+ _logger.info("QR cache hit: found=${cached.length}");
+ qrDetectionsNotifier.value = cached;
+ return;
+ }
+
qrDetectionsNotifier.value = const [];
_debounceTimer = Timer(_debounceDuration, () {
@@ -46,12 +60,14 @@ class QrCodeDetectionHelper {
if (_disposed || requestId != _requestId) return;
try {
+ final stopwatch = Stopwatch()..start();
final File? localFile = await getFile(file);
if (_disposed || requestId != _requestId) return;
if (localFile == null || !localFile.existsSync()) {
qrDetectionsNotifier.value = const [];
return;
}
+ final getFileMs = stopwatch.elapsedMilliseconds;
List<QrDetection> detections = const [];
try {
@@ -63,6 +79,17 @@ class QrCodeDetectionHelper {
_logger.severe("Failed to scan QR codes", error, stackTrace);
}
+ final totalMs = stopwatch.elapsedMilliseconds;
+ _logger.info(
+ "QR scan: getFile=${getFileMs}ms, "
+ "detect=${totalMs - getFileMs}ms, "
+ "total=${totalMs}ms, "
+ "found=${detections.length}",
+ );
+
+ // Cache the result
+ _cacheResult(file.tag, detections);
+
if (_disposed || requestId != _requestId) return;
qrDetectionsNotifier.value = detections;
@@ -73,6 +100,16 @@ class QrCodeDetectionHelper {
}
}
+ void _cacheResult(String fileId, List<QrDetection> detections) {
+ // Move to end (most recently used)
+ _cache.remove(fileId);
+ _cache[fileId] = detections;
+ // Evict oldest entry if over limit
+ if (_cache.length > _maxCacheSize) {
+ _cache.remove(_cache.keys.first);
+ }
+ }
+
bool _isFileEligible(EnteFile file) {
return file.fileType == FileType.image ||
file.fileType == FileType.livePhoto;
@@ -81,6 +118,7 @@ class QrCodeDetectionHelper {
void dispose() {
_disposed = true;
_debounceTimer?.cancel();
+ _cache.clear();
qrDetectionsNotifier.dispose();
}
}
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
index c2dea530aa..901d3e7fb2 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
@@ -4,7 +4,6 @@ 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;
@@ -51,17 +50,19 @@ class QrCodeHighlightOverlay extends StatelessWidget {
final offsetX = (screenWidth - displayWidth) / 2;
final offsetY = (screenHeight - displayHeight) / 2;
- return Stack(
- children: [
- for (final detection in detections)
- _QrTapRegion(
- detection: detection,
- offsetX: offsetX,
- offsetY: offsetY,
- displayWidth: displayWidth,
- displayHeight: displayHeight,
- ),
- ],
+ return SizedBox.expand(
+ child: Stack(
+ children: [
+ for (final detection in detections)
+ _QrTapRegion(
+ detection: detection,
+ offsetX: offsetX,
+ offsetY: offsetY,
+ displayWidth: displayWidth,
+ displayHeight: displayHeight,
+ ),
+ ],
+ ),
);
},
);
@@ -92,32 +93,11 @@ class _QrTapRegion extends StatefulWidget {
class _QrTapRegionState extends State<_QrTapRegion> {
Future<void> _onLongPress() async {
await HapticFeedback.lightImpact();
- final uri = Uri.tryParse(widget.detection.content);
- final isUpi = uri != null && uri.scheme == "upi";
- if (isUpi) {
- try {
- final launched =
- await launchUrl(uri, mode: LaunchMode.externalApplication);
- if (!launched && mounted) {
- await showQrCodeContentSheet(
- context,
- detections: [widget.detection],
- );
- }
- } catch (_) {
- if (mounted) {
- await showQrCodeContentSheet(
- context,
- detections: [widget.detection],
- );
- }
- }
- } else {
- await showQrCodeContentSheet(
- context,
- detections: [widget.detection],
- );
- }
+ if (!mounted) return;
+ await showQrCodeContentSheet(
+ context,
+ detections: [widget.detection],
+ );
}
@override
@@ -140,7 +120,6 @@ class _QrTapRegionState extends State<_QrTapRegion> {
height: screenH,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
- onTap: () {},
onLongPress: _onLongPress,
child: const SizedBox.expand(),
),
diff --git a/mobile/apps/photos/lib/ui/viewer/file/zoomable_live_image_new.dart b/mobile/apps/photos/lib/ui/viewer/file/zoomable_live_image_new.dart
index a17907d566..c7c4abeb0d 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/zoomable_live_image_new.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/zoomable_live_image_new.dart
@@ -1,6 +1,7 @@
import "dart:async";
import "dart:io";
+import "package:ente_qr/ente_qr.dart";
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import "package:media_kit/media_kit.dart";
@@ -25,6 +26,7 @@ class ZoomableLiveImageNew extends StatefulWidget {
final Decoration? backgroundDecoration;
final bool isFromMemories;
final Function({required int memoryDuration})? onFinalFileLoad;
+ final ValueNotifier<List<QrDetection>>? qrDetectionsNotifier;
const ZoomableLiveImageNew(
this.enteFile, {
@@ -34,6 +36,7 @@ class ZoomableLiveImageNew extends StatefulWidget {
this.backgroundDecoration,
this.isFromMemories = false,
this.onFinalFileLoad,
+ this.qrDetectionsNotifier,
});
@override
@@ -70,7 +73,55 @@ class _ZoomableLiveImageNewState extends State<ZoomableLiveImageNew>
});
}
- void _onLongPressEvent(bool isPressed) {
+ /// Check if a local position (relative to this widget) falls within any
+ /// detected QR code bounding box.
+ bool _isPositionInQrRegion(Offset localPosition) {
+ final detections = widget.qrDetectionsNotifier?.value;
+ if (detections == null || detections.isEmpty) return false;
+ final file = widget.enteFile;
+ if (!file.hasDimensions) return false;
+
+ final size = context.size;
+ if (size == null) return false;
+
+ final imageAspect = file.width / file.height;
+ final widgetAspect = size.width / size.height;
+
+ double displayW, displayH;
+ if (imageAspect > widgetAspect) {
+ displayW = size.width;
+ displayH = size.width / imageAspect;
+ } else {
+ displayH = size.height;
+ displayW = size.height * imageAspect;
+ }
+
+ final offsetX = (size.width - displayW) / 2;
+ final offsetY = (size.height - displayH) / 2;
+
+ // Normalize the tap position to image coordinates (0-1)
+ final normX = (localPosition.dx - offsetX) / displayW;
+ final normY = (localPosition.dy - offsetY) / displayH;
+
+ for (final d in detections) {
+ if (normX >= d.x &&
+ normX <= d.x + d.width &&
+ normY >= d.y &&
+ normY <= d.y + d.height) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void _onLongPressEvent(bool isPressed, [Offset? localPosition]) {
+ // If pressing within a QR code region, let the QR overlay handle it
+ if (isPressed &&
+ localPosition != null &&
+ _isPositionInQrRegion(localPosition)) {
+ return;
+ }
+
if (isPressed) {
if (_videoController == null) {
unawaited(_loadLiveVideo());
@@ -122,7 +173,8 @@ class _ZoomableLiveImageNewState extends State<ZoomableLiveImageNew>
if (!widget.isFromMemories) {
return GestureDetector(
- onLongPressStart: (_) => _onLongPressEvent(true),
+ onLongPressStart: (details) =>
+ _onLongPressEvent(true, details.localPosition),
onLongPressEnd: (_) => _onLongPressEvent(false),
child: content,
);
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index 06560f07d1..859a7a4779 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -329,6 +329,16 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {
faceEmbedding: (args["faceEmbeddingModelPath"] as String?) ?? "",
clipImage: (args["clipImageModelPath"] as String?) ?? "",
clipText: (args["clipTextModelPath"] as String?) ?? "",
+ petFaceDetection: (args["petFaceDetectionModelPath"] as String?) ?? "",
+ petFaceEmbeddingDog:
+ (args["petFaceEmbeddingDogModelPath"] as String?) ?? "",
+ petFaceEmbeddingCat:
+ (args["petFaceEmbeddingCatModelPath"] as String?) ?? "",
+ petBodyDetection: (args["petBodyDetectionModelPath"] as String?) ?? "",
+ petBodyEmbeddingDog:
+ (args["petBodyEmbeddingDogModelPath"] as String?) ?? "",
+ petBodyEmbeddingCat:
+ (args["petBodyEmbeddingCatModelPath"] as String?) ?? "",
);
final providerPolicy = rust_ml.RustExecutionProviderPolicy(
preferCoreml: args["preferCoreml"] as bool? ?? true,
@@ -390,6 +400,12 @@ String _runtimeConfigCacheKey(
modelPaths.faceEmbedding,
modelPaths.clipImage,
modelPaths.clipText,
+ modelPaths.petFaceDetection,
+ modelPaths.petFaceEmbeddingDog,
+ modelPaths.petFaceEmbeddingCat,
+ modelPaths.petBodyDetection,
+ modelPaths.petBodyEmbeddingDog,
+ modelPaths.petBodyEmbeddingCat,
providerPolicy.preferCoreml,
providerPolicy.preferNnapi,
providerPolicy.preferXnnpack,
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 34dcbd470c..173a18665f 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -702,6 +702,12 @@ Future<MLResult> analyzeImageRust(Map args) async {
faceEmbedding: faceEmbeddingModelPath ?? "",
clipImage: clipImageModelPath ?? "",
clipText: "",
+ petFaceDetection: petFaceDetectionModelPath ?? "",
+ petFaceEmbeddingDog: petFaceEmbeddingDogModelPath ?? "",
+ petFaceEmbeddingCat: petFaceEmbeddingCatModelPath ?? "",
+ petBodyDetection: petBodyDetectionModelPath ?? "",
+ petBodyEmbeddingDog: petBodyEmbeddingDogModelPath ?? "",
+ petBodyEmbeddingCat: petBodyEmbeddingCatModelPath ?? "",
);
final providerPolicy = rust_ml.RustExecutionProviderPolicy(
preferCoreml: preferCoreml,
@@ -719,6 +725,7 @@ Future<MLResult> analyzeImageRust(Map args) async {
imagePath: analyzePath,
runFaces: runFaces,
runClip: runClip,
+ runPets: runPets,
modelPaths: modelPaths,
providerPolicy: providerPolicy,
),
@@ -873,7 +880,46 @@ Future<MLResult> analyzeImageRust(Map args) async {
);
}
- // TODO: pet detection (petFaces/petBodies) pending Rust implementation
+ if (runPets) {
+ if (rustResult.petFaces != null) {
+ result.petFaces = rustResult.petFaces!.map((face) {
+ final detection = FaceDetectionRelative(
+ score: face.detection.score,
+ box: face.detection.boxXyxy.toList(growable: false),
+ allKeypoints: face.detection.keypoints
+ .map((point) => point.toList(growable: false))
+ .toList(growable: false),
+ );
+ final alignment = AlignmentResult(
+ // Pet alignment is done in Rust; no Dart-side affine matrix needed.
+ affineMatrix: const [],
+ center: face.alignment.center.toList(growable: false),
+ size: face.alignment.cropSize,
+ rotation: face.alignment.angle,
+ );
+ return PetFaceResult(
+ fileId: enteFileID,
+ petFaceId: face.petFaceId,
+ detection: detection,
+ alignment: alignment,
+ species: face.species,
+ embedding: Embedding.from(face.faceEmbedding),
+ );
+ }).toList(growable: false);
+ }
+
+ if (rustResult.petBodies != null) {
+ result.petBodies = rustResult.petBodies!.map((body) {
+ return PetBodyResult(
+ boxXyxy: body.boxXyxy.toList(growable: false),
+ score: body.score,
+ cocoClass: body.cocoClass,
+ petBodyId: body.petBodyId,
+ embedding: Embedding.from(body.bodyEmbedding),
+ );
+ }).toList(growable: false);
+ }
+ }
return result;
} catch (e, s) {
diff --git a/mobile/apps/photos/plugins/ente_qr/CHANGELOG.md b/mobile/apps/photos/plugins/ente_qr/CHANGELOG.md
new file mode 100644
index 0000000000..b5e7771fe5
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/CHANGELOG.md
@@ -0,0 +1,8 @@
+## 0.0.1
+
+* Initial release of ente_qr plugin
+* Support for scanning QR codes from image files
+* Android implementation using ZXing library
+* iOS implementation using Core Image framework
+* Comprehensive error handling
+* Example app demonstrating usage with file picker
diff --git a/mobile/apps/photos/plugins/ente_qr/README.md b/mobile/apps/photos/plugins/ente_qr/README.md
new file mode 100644
index 0000000000..741fdc38bb
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/README.md
@@ -0,0 +1,170 @@
+# ente_qr
+
+A Flutter plugin for scanning QR codes from image files. This plugin provides a simple interface to scan QR codes from images on both Android and iOS platforms.
+
+## Features
+
+- Scan QR codes from image files
+- Support for Android (using ZXing library)
+- Support for iOS (using AVFoundation/Core Image)
+- Returns structured results with error handling
+- Works with images from file picker or camera
+
+## Platform Support
+
+| Platform | Support |
+|----------|---------|
+| Android | βœ… |
+| iOS | βœ… |
+| Web | ❌ |
+| macOS | ❌ |
+| Windows | ❌ |
+| Linux | ❌ |
+
+## Installation
+
+Add this to your package's `pubspec.yaml` file:
+
+```yaml
+dependencies:
+ ente_qr:
+ path: path/to/ente_qr
+```
+
+## Usage
+
+### Basic Usage
+
+```dart
+import 'package:ente_qr/ente_qr.dart';
+
+final qr = EnteQr();
+
+// Scan QR code from an image file
+final result = await qr.scanQrFromImage('/path/to/image.jpg');
+
+if (result.success) {
+ print('QR Code content: ${result.content}');
+} else {
+ print('Error: ${result.error}');
+}
+```
+
+### Complete Example with File Picker
+
+```dart
+import 'package:flutter/material.dart';
+import 'package:ente_qr/ente_qr.dart';
+import 'package:file_picker/file_picker.dart';
+
+class QrScannerPage extends StatefulWidget {
+ @override
+ _QrScannerPageState createState() => _QrScannerPageState();
+}
+
+class _QrScannerPageState extends State<QrScannerPage> {
+ final _enteQr = EnteQr();
+ String _result = 'No QR code scanned';
+
+ Future<void> _scanQrFromImage() async {
+ // Pick an image file
+ FilePickerResult? fileResult = await FilePicker.platform.pickFiles(
+ type: FileType.image,
+ allowMultiple: false,
+ );
+
+ if (fileResult != null && fileResult.files.single.path != null) {
+ final imagePath = fileResult.files.single.path!;
+
+ // Scan QR code from the selected image
+ final qrResult = await _enteQr.scanQrFromImage(imagePath);
+
+ setState(() {
+ if (qrResult.success) {
+ _result = 'QR Code: ${qrResult.content}';
+ } else {
+ _result = 'Error: ${qrResult.error}';
+ }
+ });
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(title: Text('QR Scanner')),
+ body: Column(
+ children: [
+ ElevatedButton(
+ onPressed: _scanQrFromImage,
+ child: Text('Pick Image and Scan QR'),
+ ),
+ Text(_result),
+ ],
+ ),
+ );
+ }
+}
+```
+
+## API Reference
+
+### EnteQr
+
+The main class for QR code scanning operations.
+
+#### Methods
+
+##### `scanQrFromImage(String imagePath)`
+
+Scans a QR code from an image file.
+
+**Parameters:**
+- `imagePath` (String): The file path to the image containing the QR code
+
+**Returns:**
+- `Future<QrScanResult>`: A result object containing either the QR code content or an error
+
+### QrScanResult
+
+The result object returned by QR scanning operations.
+
+**Properties:**
+- `content` (String?): The QR code content if successful, null otherwise
+- `error` (String?): Error message if scanning failed, null otherwise
+- `success` (bool): Whether the scanning operation was successful
+
+**Factory Constructors:**
+- `QrScanResult.success(String content)`: Creates a successful result
+- `QrScanResult.error(String error)`: Creates an error result
+
+## Implementation Details
+
+### Android
+
+The Android implementation uses the ZXing library (com.google.zxing) for QR code detection:
+- `com.journeyapps:zxing-android-embedded:4.3.0`
+- `com.google.zxing:core:3.5.1`
+
+### iOS
+
+The iOS implementation uses Core Image framework's built-in QR code detection capabilities via `CIDetector`.
+
+## Error Handling
+
+The plugin provides comprehensive error handling for common scenarios:
+- File not found
+- Invalid image format
+- No QR code found in image
+- Platform-specific errors
+- Unexpected errors
+
+All errors are returned as part of the `QrScanResult` object with descriptive error messages.
+
+## Contributing
+
+Contributions are welcome! Please feel free to submit a Pull Request.
+
+## License
+
+This project is licensed under the same license as the Ente project.
diff --git a/mobile/apps/photos/plugins/ente_qr/analysis_options.yaml b/mobile/apps/photos/plugins/ente_qr/analysis_options.yaml
new file mode 100644
index 0000000000..f04c6cf0f3
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/analysis_options.yaml
@@ -0,0 +1 @@
+include: ../../analysis_options.yaml
diff --git a/mobile/apps/photos/plugins/ente_qr/android/build.gradle b/mobile/apps/photos/plugins/ente_qr/android/build.gradle
new file mode 100644
index 0000000000..4ee0a77c87
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/android/build.gradle
@@ -0,0 +1,67 @@
+group 'io.ente.photos.ente_qr'
+version '1.0-SNAPSHOT'
+
+buildscript {
+ ext.kotlin_version = '1.7.10'
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath 'com.android.tools.build:gradle:7.3.0'
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+ }
+}
+
+rootProject.allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ maven { url 'https://jitpack.io' }
+ }
+}
+
+apply plugin: 'com.android.library'
+apply plugin: 'kotlin-android'
+
+android {
+ namespace 'io.ente.photos.ente_qr'
+ compileSdk 36
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+
+ kotlinOptions {
+ jvmTarget = '1.8'
+ }
+
+ sourceSets {
+ main.java.srcDirs += 'src/main/kotlin'
+ test.java.srcDirs += 'src/test/kotlin'
+ }
+
+ defaultConfig {
+ minSdkVersion 16
+ }
+
+ dependencies {
+ implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
+ implementation 'com.github.markusfisch:zxing-cpp:v3.0.2.1'
+ implementation 'androidx.exifinterface:exifinterface:1.3.7'
+ }
+
+ testOptions {
+ unitTests.all {
+ useJUnitPlatform()
+
+ testLogging {
+ events "passed", "skipped", "failed", "standardOut", "standardError"
+ outputs.upToDateWhen {false}
+ showStandardStreams = true
+ }
+ }
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_qr/android/settings.gradle b/mobile/apps/photos/plugins/ente_qr/android/settings.gradle
new file mode 100644
index 0000000000..89b0daf645
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/android/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'ente_qr'
diff --git a/mobile/apps/photos/plugins/ente_qr/android/src/main/AndroidManifest.xml b/mobile/apps/photos/plugins/ente_qr/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..a2f47b6057
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/android/src/main/AndroidManifest.xml
@@ -0,0 +1,2 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+</manifest>
diff --git a/mobile/apps/photos/plugins/ente_qr/android/src/main/kotlin/io/ente/photos/ente_qr/EnteQrPlugin.kt b/mobile/apps/photos/plugins/ente_qr/android/src/main/kotlin/io/ente/photos/ente_qr/EnteQrPlugin.kt
new file mode 100644
index 0000000000..2fd4b79bf3
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/android/src/main/kotlin/io/ente/photos/ente_qr/EnteQrPlugin.kt
@@ -0,0 +1,278 @@
+package io.ente.photos.ente_qr
+
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Matrix
+import androidx.exifinterface.media.ExifInterface
+import androidx.annotation.NonNull
+import de.markusfisch.android.zxingcpp.ZxingCpp
+import de.markusfisch.android.zxingcpp.ZxingCpp.Binarizer
+import de.markusfisch.android.zxingcpp.ZxingCpp.ReaderOptions
+import io.flutter.embedding.engine.plugins.FlutterPlugin
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import io.flutter.plugin.common.MethodChannel.Result
+import java.io.File
+import java.util.concurrent.Executors
+
+/** EnteQrPlugin */
+class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
+ private lateinit var channel : MethodChannel
+ private val executor = Executors.newSingleThreadExecutor()
+
+ override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
+ channel = MethodChannel(flutterPluginBinding.binaryMessenger, "ente_qr")
+ channel.setMethodCallHandler(this)
+ }
+
+ override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
+ when (call.method) {
+ "getPlatformVersion" -> {
+ result.success("Android ${android.os.Build.VERSION.RELEASE}")
+ }
+ "scanQrFromImage" -> {
+ val imagePath = call.argument<String>("imagePath")
+ if (imagePath == null) {
+ result.success(mapOf(
+ "success" to false,
+ "error" to "Image path is required"
+ ))
+ return
+ }
+
+ executor.execute {
+ val qrResult = try {
+ scanQrCode(imagePath)
+ } catch (e: Exception) {
+ mapOf("success" to false, "error" to "Error scanning QR code: ${e.message}")
+ }
+ android.os.Handler(android.os.Looper.getMainLooper()).post {
+ result.success(qrResult)
+ }
+ }
+ }
+ "scanAllQrFromImage" -> {
+ val imagePath = call.argument<String>("imagePath")
+ if (imagePath == null) {
+ result.success(mapOf(
+ "success" to false,
+ "error" to "Image path is required"
+ ))
+ return
+ }
+
+ executor.execute {
+ val qrResult = try {
+ scanAllQrCodes(imagePath)
+ } catch (e: Exception) {
+ mapOf("success" to false, "error" to "Error scanning QR codes: ${e.message}")
+ }
+ android.os.Handler(android.os.Looper.getMainLooper()).post {
+ result.success(qrResult)
+ }
+ }
+ }
+ else -> {
+ result.notImplemented()
+ }
+ }
+ }
+
+ /**
+ * Load a bitmap with efficient downsampling and EXIF orientation correction.
+ * Uses two-pass decoding: first get dimensions, then load at target size.
+ */
+ private fun loadBitmap(imagePath: String, maxDimension: Int = 1024): Bitmap? {
+ // Pass 1: get dimensions without loading pixels
+ val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeFile(imagePath, opts)
+ val rawW = opts.outWidth
+ val rawH = opts.outHeight
+ if (rawW <= 0 || rawH <= 0) return null
+
+ // Pass 2: load with downsampling
+ var sampleSize = 1
+ while (rawW / (sampleSize * 2) >= maxDimension ||
+ rawH / (sampleSize * 2) >= maxDimension) {
+ sampleSize *= 2
+ }
+ val decodeOpts = BitmapFactory.Options().apply { inSampleSize = sampleSize }
+ val bitmap = BitmapFactory.decodeFile(imagePath, decodeOpts) ?: return null
+
+ // Apply EXIF orientation
+ return try {
+ val exif = ExifInterface(imagePath)
+ val orientation = exif.getAttributeInt(
+ ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL
+ )
+ val matrix = Matrix()
+ when (orientation) {
+ ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
+ ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
+ ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.preScale(-1f, 1f)
+ ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.preScale(1f, -1f)
+ else -> return bitmap
+ }
+ val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
+ if (rotated !== bitmap) bitmap.recycle()
+ rotated
+ } catch (_: Exception) {
+ bitmap
+ }
+ }
+
+ private fun createReaderOptions(): ReaderOptions {
+ return ReaderOptions().apply {
+ formats = setOf(ZxingCpp.BarcodeFormat.QRCode)
+ tryHarder = true
+ tryRotate = true
+ tryInvert = true
+ tryDownscale = true
+ binarizer = Binarizer.LOCAL_AVERAGE
+ }
+ }
+
+ // ── Main scan methods ─────────────────────────────────────────────
+
+ private fun scanQrCode(imagePath: String): Map<String, Any> {
+ val file = File(imagePath)
+ if (!file.exists()) {
+ return mapOf("success" to false, "error" to "Image file not found: $imagePath")
+ }
+
+ val bitmap = loadBitmap(imagePath)
+ ?: return mapOf("success" to false, "error" to "Unable to decode image file")
+
+ try {
+ val options = createReaderOptions()
+ val results = ZxingCpp.readBitmap(
+ bitmap, 0, 0, bitmap.width, bitmap.height, 0, options
+ )
+
+ if (results != null && results.isNotEmpty()) {
+ val text = results[0].text
+ if (text != null && text.isNotEmpty()) {
+ return mapOf("success" to true, "content" to text)
+ }
+ }
+
+ // Fallback: try GlobalHistogram binarizer
+ options.binarizer = Binarizer.GLOBAL_HISTOGRAM
+ val fallbackResults = ZxingCpp.readBitmap(
+ bitmap, 0, 0, bitmap.width, bitmap.height, 0, options
+ )
+ if (fallbackResults != null && fallbackResults.isNotEmpty()) {
+ val text = fallbackResults[0].text
+ if (text != null && text.isNotEmpty()) {
+ return mapOf("success" to true, "content" to text)
+ }
+ }
+
+ return mapOf("success" to false, "error" to "No QR code found in image")
+ } finally {
+ bitmap.recycle()
+ }
+ }
+
+ private fun scanAllQrCodes(imagePath: String): Map<String, Any> {
+ val file = File(imagePath)
+ if (!file.exists()) {
+ return mapOf("success" to false, "error" to "Image file not found: $imagePath")
+ }
+
+ val bitmap = loadBitmap(imagePath)
+ ?: return mapOf("success" to false, "error" to "Unable to decode image file")
+
+ try {
+ val imgWidth = bitmap.width.toDouble()
+ val imgHeight = bitmap.height.toDouble()
+ val options = createReaderOptions()
+
+ val results = ZxingCpp.readBitmap(
+ bitmap, 0, 0, bitmap.width, bitmap.height, 0, options
+ )
+
+ if (results != null && results.isNotEmpty()) {
+ val detections = buildDetections(results, imgWidth, imgHeight)
+ if (detections.isNotEmpty()) {
+ return mapOf("success" to true, "detections" to detections)
+ }
+ }
+
+ // Fallback: try GlobalHistogram binarizer
+ options.binarizer = Binarizer.GLOBAL_HISTOGRAM
+ val fallbackResults = ZxingCpp.readBitmap(
+ bitmap, 0, 0, bitmap.width, bitmap.height, 0, options
+ )
+ if (fallbackResults != null && fallbackResults.isNotEmpty()) {
+ val detections = buildDetections(fallbackResults, imgWidth, imgHeight)
+ if (detections.isNotEmpty()) {
+ return mapOf("success" to true, "detections" to detections)
+ }
+ }
+
+ return mapOf("success" to false, "error" to "No QR code found in image")
+ } finally {
+ bitmap.recycle()
+ }
+ }
+
+ private fun buildDetections(
+ results: List<ZxingCpp.Result>,
+ imgWidth: Double,
+ imgHeight: Double,
+ ): List<Map<String, Any>> {
+ val detections = mutableListOf<Map<String, Any>>()
+
+ for (qrResult in results) {
+ val text = qrResult.text ?: continue
+ if (text.isEmpty()) continue
+
+ val position = qrResult.position ?: continue
+ val points = listOf(
+ position.topLeft,
+ position.topRight,
+ position.bottomRight,
+ position.bottomLeft,
+ )
+
+ var minX = Float.MAX_VALUE
+ var minY = Float.MAX_VALUE
+ var maxX = -Float.MAX_VALUE
+ var maxY = -Float.MAX_VALUE
+
+ for (point in points) {
+ val px = point.x.toFloat()
+ val py = point.y.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
+ 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(imgWidth.toFloat())
+ maxY = (maxY + padY).coerceAtMost(imgHeight.toFloat())
+
+ detections.add(mapOf(
+ "content" to text,
+ "x" to (minX / imgWidth),
+ "y" to (minY / imgHeight),
+ "width" to ((maxX - minX) / imgWidth),
+ "height" to ((maxY - minY) / imgHeight),
+ ))
+ }
+
+ return detections
+ }
+
+ override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
+ channel.setMethodCallHandler(null)
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_qr/ios/Classes/EnteQrPlugin.swift b/mobile/apps/photos/plugins/ente_qr/ios/Classes/EnteQrPlugin.swift
new file mode 100644
index 0000000000..b198b25719
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/ios/Classes/EnteQrPlugin.swift
@@ -0,0 +1,142 @@
+import Flutter
+import UIKit
+import Vision
+
+public 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()
+ registrar.addMethodCallDelegate(instance, channel: channel)
+ }
+
+ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ switch call.method {
+ case "getPlatformVersion":
+ result("iOS " + UIDevice.current.systemVersion)
+ case "scanQrFromImage":
+ guard let args = call.arguments as? [String: Any],
+ let imagePath = args["imagePath"] as? String else {
+ result([
+ "success": false,
+ "error": "Image path is required"
+ ])
+ 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)
+ }
+ }
+
+ private func detectBarcodes(in cgImage: CGImage) -> [VNBarcodeObservation] {
+ let request = VNDetectBarcodesRequest()
+ request.symbologies = [.qr]
+
+ let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
+ do {
+ try handler.perform([request])
+ } catch {
+ return []
+ }
+
+ return request.results ?? []
+ }
+
+ private func scanQrCode(from imagePath: String, result: @escaping FlutterResult) {
+ EnteQrPlugin.detectionQueue.async {
+ guard let image = UIImage(contentsOfFile: imagePath),
+ let cgImage = image.cgImage else {
+ DispatchQueue.main.async {
+ result([
+ "success": false,
+ "error": "Unable to load image from path: \(imagePath)"
+ ])
+ }
+ return
+ }
+
+ let observations = self.detectBarcodes(in: cgImage)
+
+ if let obs = observations.first,
+ let payload = obs.payloadStringValue {
+ DispatchQueue.main.async {
+ result([
+ "success": true,
+ "content": payload
+ ])
+ }
+ } else {
+ DispatchQueue.main.async {
+ result([
+ "success": false,
+ "error": "No QR code found in image"
+ ])
+ }
+ }
+ }
+ }
+
+ private func scanAllQrCodes(from imagePath: String, result: @escaping FlutterResult) {
+ EnteQrPlugin.detectionQueue.async {
+ guard let image = UIImage(contentsOfFile: imagePath),
+ let cgImage = image.cgImage else {
+ DispatchQueue.main.async {
+ result([
+ "success": false,
+ "error": "Unable to load image from path: \(imagePath)"
+ ])
+ }
+ return
+ }
+
+ let observations = self.detectBarcodes(in: cgImage)
+
+ var detections: [[String: Any]] = []
+
+ for obs in observations {
+ guard let payload = obs.payloadStringValue else { continue }
+
+ // Vision's boundingBox is normalized [0,1] with origin at bottom-left.
+ // Convert to top-left origin (y-down) for Flutter.
+ let box = obs.boundingBox
+ detections.append([
+ "content": payload,
+ "x": Double(box.origin.x),
+ "y": Double(1.0 - box.origin.y - box.height),
+ "width": Double(box.width),
+ "height": Double(box.height),
+ ])
+ }
+
+ 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/plugins/ente_qr/ios/ente_qr.podspec b/mobile/apps/photos/plugins/ente_qr/ios/ente_qr.podspec
new file mode 100644
index 0000000000..11df118b30
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/ios/ente_qr.podspec
@@ -0,0 +1,23 @@
+#
+# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
+# Run `pod lib lint ente_qr.podspec` to validate before publishing.
+#
+Pod::Spec.new do |s|
+ s.name = 'ente_qr'
+ s.version = '0.0.1'
+ s.summary = 'A QR code reader plugin for Ente.'
+ s.description = <<-DESC
+A QR code reader plugin for Ente.
+ DESC
+ s.homepage = 'https://ente.com'
+ s.license = { :file => '../LICENSE' }
+ s.author = { 'Ente' => '[email protected]' }
+ s.source = { :path => '.' }
+ s.source_files = 'Classes/**/*'
+ s.dependency 'Flutter'
+ s.platform = :ios, '12.0'
+
+ # Flutter.framework does not contain a i386 slice.
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
+ s.swift_version = '5.0'
+end
diff --git a/mobile/apps/photos/plugins/ente_qr/lib/ente_qr.dart b/mobile/apps/photos/plugins/ente_qr/lib/ente_qr.dart
new file mode 100644
index 0000000000..ee7f3f2e10
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/lib/ente_qr.dart
@@ -0,0 +1,28 @@
+import 'package:ente_qr/ente_qr_platform_interface.dart';
+
+export 'ente_qr_platform_interface.dart'
+ show QrDetection, QrScanResult, QrScanResults;
+
+class EnteQr {
+ Future<String?> getPlatformVersion() {
+ return EnteQrPlatform.instance.getPlatformVersion();
+ }
+
+ /// Scans a QR code from an image file at the given path.
+ ///
+ /// [imagePath] - The file path to the image containing the QR code
+ ///
+ /// Returns a [QrScanResult] containing either the QR code content on success
+ /// or an error message on failure.
+ 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/photos/plugins/ente_qr/lib/ente_qr_method_channel.dart b/mobile/apps/photos/plugins/ente_qr/lib/ente_qr_method_channel.dart
new file mode 100644
index 0000000000..5fe06b5099
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/lib/ente_qr_method_channel.dart
@@ -0,0 +1,90 @@
+import 'package:ente_qr/ente_qr_platform_interface.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+/// An implementation of [EnteQrPlatform] that uses method channels.
+class MethodChannelEnteQr extends EnteQrPlatform {
+ /// The method channel used to interact with the native platform.
+ @visibleForTesting
+ final methodChannel = const MethodChannel('ente_qr');
+
+ @override
+ Future<String?> getPlatformVersion() async {
+ final version =
+ await methodChannel.invokeMethod<String>('getPlatformVersion');
+ return version;
+ }
+
+ @override
+ Future<QrScanResult> scanQrFromImage(String imagePath) async {
+ try {
+ final dynamic result = await methodChannel.invokeMethod(
+ 'scanQrFromImage',
+ {'imagePath': imagePath},
+ );
+
+ if (result == null) {
+ return QrScanResult.error('Failed to scan QR code');
+ }
+
+ // Convert to Map<String, dynamic> safely
+ final Map<String, dynamic> resultMap =
+ Map<String, dynamic>.from(result as Map);
+
+ final bool success = resultMap['success'] as bool? ?? false;
+ if (success) {
+ final String? content = resultMap['content'] as String?;
+ if (content != null && content.isNotEmpty) {
+ return QrScanResult.success(content);
+ } else {
+ return QrScanResult.error('No QR code found in image');
+ }
+ } else {
+ final String? error = resultMap['error'] as String?;
+ return QrScanResult.error(error ?? 'Unknown error occurred');
+ }
+ } on PlatformException catch (e) {
+ return QrScanResult.error('Platform error: ${e.message}');
+ } catch (e) {
+ 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/photos/plugins/ente_qr/lib/ente_qr_platform_interface.dart b/mobile/apps/photos/plugins/ente_qr/lib/ente_qr_platform_interface.dart
new file mode 100644
index 0000000000..08bbd45518
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/lib/ente_qr_platform_interface.dart
@@ -0,0 +1,131 @@
+import 'package:ente_qr/ente_qr_method_channel.dart';
+import 'package:plugin_platform_interface/plugin_platform_interface.dart';
+
+/// The result of QR code scanning
+class QrScanResult {
+ final String? content;
+ final String? error;
+ final bool success;
+
+ const QrScanResult({
+ this.content,
+ this.error,
+ required this.success,
+ });
+
+ factory QrScanResult.success(String content) {
+ return QrScanResult(
+ content: content,
+ success: true,
+ );
+ }
+
+ factory QrScanResult.error(String error) {
+ return QrScanResult(
+ error: error,
+ success: false,
+ );
+ }
+}
+
+/// 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);
+
+ static final Object _token = Object();
+
+ static EnteQrPlatform _instance = MethodChannelEnteQr();
+
+ /// The default instance of [EnteQrPlatform] to use.
+ ///
+ /// Defaults to [MethodChannelEnteQr].
+ static EnteQrPlatform get instance => _instance;
+
+ /// Platform-specific implementations should set this with their own
+ /// platform-specific class that extends [EnteQrPlatform] when
+ /// they register themselves.
+ static set instance(EnteQrPlatform instance) {
+ PlatformInterface.verifyToken(instance, _token);
+ _instance = instance;
+ }
+
+ Future<String?> getPlatformVersion() {
+ throw UnimplementedError('platformVersion() has not been implemented.');
+ }
+
+ /// Scans a QR code from an image file at the given path.
+ /// Returns the QR code content as a string if successful, null otherwise.
+ 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/plugins/ente_qr/pubspec.yaml b/mobile/apps/photos/plugins/ente_qr/pubspec.yaml
new file mode 100644
index 0000000000..f04100d1d6
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/pubspec.yaml
@@ -0,0 +1,29 @@
+name: ente_qr
+description: "A QR code reader plugin for Ente."
+version: 0.0.1
+homepage: https://ente.com
+
+environment:
+ sdk: '>=3.4.3 <4.0.0'
+ flutter: '>=3.3.0'
+
+dependencies:
+ flutter:
+ sdk: flutter
+ plugin_platform_interface: ^2.0.2
+
+dev_dependencies:
+ flutter_lints: ^3.0.0
+ flutter_test:
+ sdk: flutter
+
+# The following section is specific to Flutter packages.
+flutter:
+ # This section identifies this Flutter project as a plugin project.
+ plugin:
+ platforms:
+ android:
+ package: io.ente.photos.ente_qr
+ pluginClass: EnteQrPlugin
+ ios:
+ pluginClass: EnteQrPlugin
diff --git a/mobile/apps/photos/plugins/ente_qr/test/ente_qr_test.dart b/mobile/apps/photos/plugins/ente_qr/test/ente_qr_test.dart
new file mode 100644
index 0000000000..2d9bf5f019
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_qr/test/ente_qr_test.dart
@@ -0,0 +1,36 @@
+import 'package:ente_qr/ente_qr.dart';
+import 'package:ente_qr/ente_qr_method_channel.dart';
+import 'package:ente_qr/ente_qr_platform_interface.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:plugin_platform_interface/plugin_platform_interface.dart';
+
+class MockEnteQrPlatform
+ with MockPlatformInterfaceMixin
+ implements EnteQrPlatform {
+ @override
+ Future<String?> getPlatformVersion() => Future.value('42');
+
+ @override
+ Future<QrScanResult> scanQrFromImage(String imagePath) =>
+ Future.value(QrScanResult.error('Mock implementation'));
+
+ @override
+ Future<QrScanResults> scanAllQrFromImage(String imagePath) =>
+ Future.value(QrScanResults.error('Mock implementation'));
+}
+
+void main() {
+ final EnteQrPlatform initialPlatform = EnteQrPlatform.instance;
+
+ test('$MethodChannelEnteQr is the default instance', () {
+ expect(initialPlatform, isInstanceOf<MethodChannelEnteQr>());
+ });
+
+ test('getPlatformVersion', () async {
+ final EnteQr enteQrPlugin = EnteQr();
+ final MockEnteQrPlatform fakePlatform = MockEnteQrPlatform();
+ EnteQrPlatform.instance = fakePlatform;
+
+ expect(await enteQrPlugin.getPlatformVersion(), '42');
+ });
+}
diff --git a/mobile/apps/photos/pubspec.lock b/mobile/apps/photos/pubspec.lock
index 6f031ce9c3..322d3d7658 100644
--- a/mobile/apps/photos/pubspec.lock
+++ b/mobile/apps/photos/pubspec.lock
@@ -639,7 +639,7 @@ packages:
ente_qr:
dependency: "direct main"
description:
- path: "../auth/plugins/qr"
+ path: "plugins/ente_qr"
relative: true
source: path
version: "0.0.1"
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index 93714a01e1..d1ae57cb9c 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -67,7 +67,7 @@ dependencies:
ente_pure_utils:
path: ../../packages/ente_pure_utils
ente_qr:
- path: ../auth/plugins/qr
+ path: plugins/ente_qr
ente_qr_ui:
path: ../../packages/qr
ente_rust: