Skip to content

armgit / ente

Public Imported from GitHub
0

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

Route OCR from long presses and live text regions

Neeraj Gupta68ccd94d93da
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 0f77e15997..e93c3b8fea 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart
@@ -148,6 +148,7 @@ class _BodyState extends State<_Body> {
List<EnteFile>? _files;
late PageController _pageController;
final _selectedIndexNotifier = ValueNotifier(0);
+ final _inlineTextDetectionController = InlineTextDetectionController();
bool _isFirstOpened = true;
bool isGuestView = false;
bool swipeLocked = false;
@@ -267,6 +268,24 @@ class _BodyState extends State<_Body> {
child: Stack(
children: [
_buildPageView(),
+ // Keep viewer controls above OCR so their real hit boxes, rather
+ // than approximated screen insets, decide which gestures they own.
+ ValueListenableBuilder(
+ valueListenable: _selectedIndexNotifier,
+ builder: (BuildContext context, int selectedIndex, _) {
+ if (widget.config.mode == DetailPageMode.minimalistic) {
+ return const SizedBox.shrink();
+ }
+ if (flagService.ocrOverlayEnabled) {
+ return InlineTextDetection(
+ file: _files![selectedIndex],
+ controller: _inlineTextDetectionController,
+ isGuestView: isGuestView,
+ );
+ }
+ return const SizedBox.shrink();
+ },
+ ),
ValueListenableBuilder(
builder: (BuildContext context, int selectedIndex, _) {
return widget.config.mode == DetailPageMode.minimalistic
@@ -283,24 +302,6 @@ class _BodyState extends State<_Body> {
},
valueListenable: _selectedIndexNotifier,
),
- ValueListenableBuilder(
- valueListenable: _selectedIndexNotifier,
- builder: (BuildContext context, int selectedIndex, _) {
- if (widget.config.mode == DetailPageMode.minimalistic) {
- return const SizedBox.shrink();
- }
- if (flagService.ocrOverlayEnabled) {
- return InlineTextDetection(
- file: _files![selectedIndex],
- enableFullScreenNotifier: InheritedDetailPageState.of(
- context,
- ).enableFullScreenNotifier,
- isGuestView: isGuestView,
- );
- }
- return const SizedBox.shrink();
- },
- ),
if (_qrHelper != null)
ValueListenableBuilder(
valueListenable: _selectedIndexNotifier,
@@ -423,6 +424,13 @@ class _BodyState extends State<_Body> {
qrDetectionsNotifier: _qrHelper?.qrDetectionsNotifier,
);
return GestureDetector(
+ onLongPressStart:
+ flagService.ocrOverlayEnabled &&
+ widget.config.mode != DetailPageMode.minimalistic &&
+ !file.isLiveOrMotionPhoto
+ ? (details) => _inlineTextDetectionController
+ .startTextSelectionAt(details.globalPosition)
+ : null,
onTap: () {
file.fileType != FileType.video
? InheritedDetailPageState.of(context).toggleFullScreenByUser()
diff --git a/mobile/apps/photos/lib/ui/viewer/file/inline_text_detection.dart b/mobile/apps/photos/lib/ui/viewer/file/inline_text_detection.dart
index 7f39948268..24f5a53296 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/inline_text_detection.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/inline_text_detection.dart
@@ -1,7 +1,6 @@
import "dart:async";
import "dart:io";
-import "package:flutter/foundation.dart";
import "package:flutter/gestures.dart";
import "package:flutter/material.dart";
import "package:flutter/rendering.dart";
@@ -11,37 +10,55 @@ import "package:mobile_ocr/mobile_ocr.dart"
show
DisplayImageHelper,
MobileOcr,
+ OcrModelComponent,
TextDetectorController,
TextDetectorStrings,
TextDetectorWidget,
+ TextRegionDetectionResult,
ZoomedInteractionPolicy;
import "package:photos/core/event_bus.dart";
import "package:photos/events/reset_zoom_of_photo_view_event.dart";
import "package:photos/l10n/l10n.dart";
+import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
import "package:photos/models/file/trash_file.dart";
import "package:photos/module/download/file.dart";
import "package:photos/states/detail_page_state.dart";
import "package:photos/ui/viewer/file/ocr/ocr_dot_wave_overlay.dart";
+import "package:photos/ui/viewer/file/ocr/text_region_hit_test.dart";
import "package:photos/utils/image_util.dart";
-/// Inline text detection widget that mimics Apple's Live Text behavior:
+/// Routes still-photo gestures from the viewer to its OCR overlay.
+class InlineTextDetectionController {
+ _InlineTextDetectionState? _state;
+
+ void _attach(_InlineTextDetectionState state) => _state = state;
+
+ void _detach(_InlineTextDetectionState state) {
+ if (identical(_state, state)) {
+ _state = null;
+ }
+ }
+
+ void startTextSelectionAt(Offset globalPosition) {
+ _state?._handleLongPressAt(globalPosition);
+ }
+}
+
+/// Inline on-demand text selection for the photo viewer.
///
-/// 1. Quick `hasText()` check runs silently when the image loads.
-/// 2. If text is found and the user stays on the image for 1 second, full
-/// detection runs automatically and text boundaries appear as a
-/// transparent overlay.
-/// 3. Long press on detected text lets users select and copy.
-/// 4. Taps and swipes pass through to the underlying image viewer.
+/// Still images use long press as the signal to start recognition. Live and
+/// motion photos precompute detector-only regions so a long press on text
+/// starts selection, while a long press elsewhere continues to play video.
class InlineTextDetection extends StatefulWidget {
final EnteFile file;
- final ValueListenable<bool> enableFullScreenNotifier;
+ final InlineTextDetectionController controller;
final bool isGuestView;
const InlineTextDetection({
required this.file,
- required this.enableFullScreenNotifier,
+ required this.controller,
required this.isGuestView,
super.key,
});
@@ -52,22 +69,23 @@ class InlineTextDetection extends StatefulWidget {
class _InlineTextDetectionState extends State<InlineTextDetection> {
static const int _maxCacheSize = 200;
- static const Duration _hasTextTimeout = Duration(seconds: 15);
- static const Duration _autoActivateDelay = Duration(seconds: 1);
+ static const Duration _regionDetectionTimeout = Duration(seconds: 15);
static const double _globalGestureSlop = 18.0;
static const double _photoGestureEdgeSlop = 8.0;
- static const double _visibleBottomControlsHeight = 120.0;
- static final Map<String, _HasTextResult> _hasTextCache = {};
+ static const double _textRegionHitSlop = 8.0;
+ static final Map<String, _RegionCacheEntry> _regionCache = {};
final Logger _logger = Logger("InlineTextDetection");
final MobileOcr _mobileOcr = MobileOcr();
final TextDetectorController _detectorController = TextDetectorController();
bool _isEligible = false;
String? _localFilePath;
- int _requestId = 0;
+ int _evaluationGeneration = 0;
+ String? _activeRegionRequestId;
+ TextRegionDetectionResult? _detectedRegions;
bool _overlayActive = false;
+ bool _isPreparingOnDemand = false;
Offset? _pendingLongPressPosition;
- Timer? _autoActivateTimer;
bool _zoomGestureSettled = false;
Timer? _zoomSettleTimer;
ZoomTransform? _lastSeenTransform;
@@ -87,6 +105,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
@override
void initState() {
super.initState();
+ widget.controller._attach(this);
GestureBinding.instance.pointerRouter.addGlobalRoute(
_handleGlobalPointerEvent,
);
@@ -96,7 +115,12 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
@override
void didUpdateWidget(covariant InlineTextDetection oldWidget) {
super.didUpdateWidget(oldWidget);
- if (_didFileChange(oldWidget.file, widget.file)) {
+ if (!identical(oldWidget.controller, widget.controller)) {
+ oldWidget.controller._detach(this);
+ widget.controller._attach(this);
+ }
+ if (_didFileChange(oldWidget.file, widget.file) ||
+ oldWidget.isGuestView != widget.isGuestView) {
_resetState();
_evaluateFile();
}
@@ -104,23 +128,27 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
@override
void dispose() {
- _autoActivateTimer?.cancel();
+ _cancelActiveRegionRequest();
_zoomSettleTimer?.cancel();
_globalLongPressTimer?.cancel();
GestureBinding.instance.pointerRouter.removeGlobalRoute(
_handleGlobalPointerEvent,
);
+ widget.controller._detach(this);
_detectorController.dispose();
super.dispose();
}
void _resetState() {
- _autoActivateTimer?.cancel();
+ _evaluationGeneration++;
+ _cancelActiveRegionRequest();
_cancelTrackedGlobalPointer();
_imageSizeRequestId++;
setState(() {
_localFilePath = null;
+ _detectedRegions = null;
_overlayActive = false;
+ _isPreparingOnDemand = false;
_pendingLongPressPosition = null;
_resolvedImageSizePath = null;
_resolvedImageSize = null;
@@ -128,6 +156,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
}
bool _didFileChange(EnteFile oldFile, EnteFile newFile) {
+ if ((oldFile is TrashFile) != (newFile is TrashFile)) return true;
if (oldFile.generatedID != newFile.generatedID) return true;
if (oldFile.uploadedFileID != newFile.uploadedFileID) return true;
if (oldFile.localID != newFile.localID) return true;
@@ -140,38 +169,32 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
return "generated_${file.generatedID}";
}
- static void _cacheResult(String key, _HasTextResult result) {
- if (_hasTextCache.length >= _maxCacheSize) {
- _hasTextCache.remove(_hasTextCache.keys.first);
+ static void _cacheRegionResult(String key, _RegionCacheEntry result) {
+ if (_regionCache.length >= _maxCacheSize) {
+ _regionCache.remove(_regionCache.keys.first);
}
- _hasTextCache[key] = result;
+ _regionCache[key] = result;
}
bool _isFileEligible(EnteFile file) {
+ if (widget.isGuestView || file is TrashFile) return false;
return file.fileType == FileType.image ||
file.fileType == FileType.livePhoto;
}
- Future<bool?> _checkHasText(File localFile) async {
- _logger.info("running hasText check");
- try {
- final bool hasText = await _mobileOcr
- .hasText(imagePath: localFile.path)
- .timeout(_hasTextTimeout);
- _logger.info("hasText result: $hasText");
- return hasText;
- } on TimeoutException {
- _logger.info("hasText timed out");
- return null;
- } catch (error, stackTrace) {
- _logger.warning("hasText failed", error, stackTrace);
- return null;
+ bool get _requiresRegionRouting => widget.file.isLiveOrMotionPhoto;
+
+ void _cancelActiveRegionRequest() {
+ final requestId = _activeRegionRequestId;
+ _activeRegionRequestId = null;
+ if (requestId != null) {
+ unawaited(_mobileOcr.cancelRequest(requestId).catchError((_) {}));
}
}
Future<void> _evaluateFile() async {
final bool isEligible = _isFileEligible(widget.file);
- final int requestId = ++_requestId;
+ final int generation = ++_evaluationGeneration;
_logger.info(
"evaluateFile: eligible=$isEligible, type=${widget.file.fileType}",
);
@@ -180,6 +203,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
setState(() {
_isEligible = false;
_localFilePath = null;
+ _detectedRegions = null;
});
return;
}
@@ -187,98 +211,96 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
setState(() {
_isEligible = true;
_localFilePath = null;
+ _detectedRegions = null;
});
+ if (!_requiresRegionRouting) {
+ return;
+ }
- // Check cache first
final String cacheKey = _cacheKey(widget.file);
- final _HasTextResult? cached = _hasTextCache[cacheKey];
- if (cached != null) {
- if (!mounted || requestId != _requestId) return;
+ final _RegionCacheEntry? cached = _regionCache[cacheKey];
+ if (cached != null && File(cached.localPath).existsSync()) {
+ if (!mounted || generation != _evaluationGeneration) return;
setState(() {
_localFilePath = cached.localPath;
- if (!cached.hasText) {
- _pendingLongPressPosition = null;
- }
+ _detectedRegions = cached.result;
});
- if (cached.hasText) {
- final localPath = cached.localPath;
- if (localPath != null) {
- unawaited(_resolveDisplayImageSize(localPath));
- }
- _scheduleAutoActivate(requestId);
- }
return;
}
+ if (cached != null) {
+ _regionCache.remove(cacheKey);
+ }
- // Resolve local file
try {
final File? localFile = await getFile(widget.file);
- if (!mounted || requestId != _requestId) return;
+ if (!mounted || generation != _evaluationGeneration) return;
if (localFile == null || !localFile.existsSync()) {
- _cacheResult(cacheKey, const _HasTextResult(hasText: false));
- setState(() {
- _pendingLongPressPosition = null;
- });
return;
}
- final bool? hasText = await _checkHasText(localFile);
- if (!mounted || requestId != _requestId) return;
- if (hasText == null) {
- setState(() {
- _pendingLongPressPosition = null;
- });
- return;
- }
-
- final result = _HasTextResult(
- hasText: hasText,
- localPath: hasText ? localFile.path : null,
- );
- _cacheResult(cacheKey, result);
-
setState(() {
- _localFilePath = result.localPath;
- if (!hasText) {
- _pendingLongPressPosition = null;
- }
+ _localFilePath = localFile.path;
});
+ final detectorStatus = await _mobileOcr.prepareModels(
+ components: {OcrModelComponent.detector},
+ );
+ if (!mounted || generation != _evaluationGeneration) return;
+ if (!detectorStatus.isReady) {
+ throw StateError("OCR detector is not ready");
+ }
- if (hasText) {
- unawaited(_resolveDisplayImageSize(localFile.path));
- if (_pendingLongPressPosition != null) {
- _activateOverlay();
- } else {
- _scheduleAutoActivate(requestId);
+ final regionRequestId = "photos-$cacheKey-$generation";
+ _activeRegionRequestId = regionRequestId;
+ late final TextRegionDetectionResult result;
+ try {
+ result = await _mobileOcr
+ .detectTextRegions(
+ imagePath: localFile.path,
+ requestId: regionRequestId,
+ )
+ .timeout(_regionDetectionTimeout);
+ } on TimeoutException {
+ await _mobileOcr.cancelRequest(regionRequestId);
+ rethrow;
+ } finally {
+ if (_activeRegionRequestId == regionRequestId) {
+ _activeRegionRequestId = null;
}
}
- } catch (error, stackTrace) {
- _logger.severe("Text detection pre-check failed", error, stackTrace);
- if (!mounted || requestId != _requestId) return;
+ if (!mounted || generation != _evaluationGeneration) return;
+
+ _cacheRegionResult(
+ cacheKey,
+ _RegionCacheEntry(localPath: localFile.path, result: result),
+ );
setState(() {
- _pendingLongPressPosition = null;
+ _detectedRegions = result;
});
+ _logger.info("Detected ${result.regions.length} live-photo text regions");
+ } catch (error, stackTrace) {
+ if (!mounted || generation != _evaluationGeneration) return;
+ _logger.warning(
+ "Live-photo text region detection failed",
+ error,
+ stackTrace,
+ );
}
}
void _activateOverlay() {
- _autoActivateTimer?.cancel();
if (_overlayActive) return;
setState(() {
_overlayActive = true;
});
}
- void _scheduleAutoActivate(int requestId) {
- _autoActivateTimer?.cancel();
- _autoActivateTimer = Timer(_autoActivateDelay, () {
- if (!mounted || requestId != _requestId) return;
- if (_localFilePath == null || _overlayActive) return;
- _activateOverlay();
- });
- }
-
Size? get _displayImageSize {
+ final regionImageSize = _detectedRegions?.imageSize;
+ if (regionImageSize != null &&
+ regionImageSize.width > 0 &&
+ regionImageSize.height > 0) {
+ return regionImageSize;
+ }
if (widget.file.hasDimensions &&
widget.file.width > 0 &&
widget.file.height > 0) {
@@ -327,18 +349,45 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
}
void _handleLongPressAt(Offset globalPosition) {
+ if (!_isEligible) return;
if (_overlayActive) return; // Already active, let overlay handle it
if (!_isGlobalPointEligibleForOcrGesture(globalPosition)) return;
- _autoActivateTimer?.cancel();
+ if (_isPreparingOnDemand) return;
setState(() {
_pendingLongPressPosition = globalPosition;
});
- // If hasText already completed and file path is ready, activate now
if (_localFilePath != null) {
_activateOverlay();
- return;
+ } else {
+ unawaited(_prepareStillImageOnDemand());
+ }
+ }
+
+ Future<void> _prepareStillImageOnDemand() async {
+ final generation = _evaluationGeneration;
+ setState(() {
+ _isPreparingOnDemand = true;
+ });
+ try {
+ final localFile = await getFile(widget.file);
+ if (!mounted || generation != _evaluationGeneration) return;
+ if (localFile == null || !localFile.existsSync()) {
+ throw StateError("Could not resolve image for OCR");
+ }
+ setState(() {
+ _localFilePath = localFile.path;
+ _isPreparingOnDemand = false;
+ });
+ unawaited(_resolveDisplayImageSize(localFile.path));
+ _activateOverlay();
+ } catch (error, stackTrace) {
+ if (!mounted || generation != _evaluationGeneration) return;
+ _logger.warning("Could not prepare image for OCR", error, stackTrace);
+ setState(() {
+ _isPreparingOnDemand = false;
+ _pendingLongPressPosition = null;
+ });
}
- unawaited(_evaluateFile());
}
void _handleLongPress(LongPressStartDetails details) {
@@ -354,14 +403,6 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
_zoomGestureSettled &&
!_isPinching;
- bool get _canRetryHasTextFromLongPress =>
- _isEligible &&
- !_overlayActive &&
- _localFilePath == null &&
- _pendingLongPressPosition == null &&
- widget.file is! TrashFile &&
- !widget.isGuestView;
-
bool _isPrimaryGlobalPointer(PointerDownEvent event) {
if (event.kind == PointerDeviceKind.mouse) {
return event.buttons == kPrimaryMouseButton;
@@ -394,17 +435,13 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
final bool pointEligibleForOcr = _isGlobalPointEligibleForOcrGesture(
event.position,
);
- final bool longPressCanRetry =
- pointEligibleForOcr &&
- widget.enableFullScreenNotifier.value &&
- _canRetryHasTextFromLongPress;
final bool longPressCanSelect =
pointEligibleForOcr &&
_canTrackZoomedPanFirstLongPress &&
!pointOnInteractiveUi &&
_detectorController.isPointOnSelectableText(event.position);
- if (!tapCanClearSelection && !longPressCanSelect && !longPressCanRetry) {
+ if (!tapCanClearSelection && !longPressCanSelect) {
return;
}
@@ -418,7 +455,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
_trackedGlobalPointerMoved = false;
_trackedGlobalLongPressTriggered = false;
- if (longPressCanSelect || longPressCanRetry) {
+ if (longPressCanSelect) {
final Offset position = event.position;
final int pointer = event.pointer;
_globalLongPressTimer = Timer(kLongPressTimeout, () {
@@ -429,13 +466,8 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
(longPressCanSelect && !_canTrackZoomedPanFirstLongPress)) {
return;
}
- if (longPressCanSelect) {
- _trackedGlobalLongPressTriggered = _detectorController
- .selectTextAtPosition(position);
- } else if (_canRetryHasTextFromLongPress) {
- _trackedGlobalLongPressTriggered = true;
- _handleLongPressAt(position);
- }
+ _trackedGlobalLongPressTriggered = _detectorController
+ .selectTextAtPosition(position);
});
}
}
@@ -508,39 +540,25 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
return allowViewportFallback ? Offset.zero & viewportSize : Rect.zero;
}
- final double imageAspect = imageSize.width / imageSize.height;
- final double viewportAspect = viewportSize.width / viewportSize.height;
- late final double displayWidth;
- late final double displayHeight;
- if (imageAspect > viewportAspect) {
- displayWidth = viewportSize.width;
- displayHeight = displayWidth / imageAspect;
- } else {
- displayHeight = viewportSize.height;
- displayWidth = displayHeight * imageAspect;
- }
-
- return Rect.fromLTWH(
- (viewportSize.width - displayWidth) / 2,
- (viewportSize.height - displayHeight) / 2,
- displayWidth,
- displayHeight,
- );
+ return containedImageRect(viewportSize, imageSize);
}
- bool _isLocalPointInVisibleControls(Offset localPosition, Size viewportSize) {
- if (widget.enableFullScreenNotifier.value) {
+ bool _isLocalPointInDetectedTextRegion(
+ Offset localPosition,
+ Size viewportSize,
+ ) {
+ final detection = _detectedRegions;
+ if (detection == null || detection.regions.isEmpty) {
return false;
}
-
- final EdgeInsets padding =
- MediaQuery.maybeOf(context)?.padding ?? EdgeInsets.zero;
- final double topControlsHeight = padding.top + kToolbarHeight;
- final double bottomControlsHeight =
- padding.bottom + _visibleBottomControlsHeight;
-
- return localPosition.dy < topControlsHeight ||
- localPosition.dy > viewportSize.height - bottomControlsHeight;
+ final imageSize = detection.imageSize;
+ return isViewportPointInTextRegions(
+ point: localPosition,
+ viewportSize: viewportSize,
+ imageSize: imageSize,
+ regions: detection.regions,
+ hitSlop: _textRegionHitSlop,
+ );
}
bool _isLocalPointEligibleForOcrGesture(
@@ -550,9 +568,6 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
if (viewportSize.width <= 0 || viewportSize.height <= 0) {
return false;
}
- if (_isLocalPointInVisibleControls(localPosition, viewportSize)) {
- return false;
- }
return _displayedPhotoRect(
viewportSize,
).inflate(_photoGestureEdgeSlop).contains(localPosition);
@@ -577,13 +592,21 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
return _isLocalPointEligibleForOcrGesture(globalPosition, viewportSize);
}
- Widget _buildOcrGestureRegion(Widget child) {
+ Widget _buildOcrGestureRegion(Widget child, {bool textRegionsOnly = false}) {
return LayoutBuilder(
builder: (context, constraints) {
final Size viewportSize = constraints.biggest;
return _OcrGestureHitTestBox(
- hitTest: (localPosition) =>
- _isLocalPointEligibleForOcrGesture(localPosition, viewportSize),
+ hitTest: (localPosition) {
+ if (!_isLocalPointEligibleForOcrGesture(
+ localPosition,
+ viewportSize,
+ )) {
+ return false;
+ }
+ return !textRegionsOnly ||
+ _isLocalPointInDetectedTextRegion(localPosition, viewportSize);
+ },
child: child,
);
},
@@ -598,6 +621,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
onLongPressStart: _handleLongPress,
child: const SizedBox.expand(),
),
+ textRegionsOnly: _requiresRegionRouting,
),
);
}
@@ -659,19 +683,30 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
@override
Widget build(BuildContext context) {
- if (!_isEligible || widget.file is TrashFile || widget.isGuestView) {
+ if (!_isEligible) {
return const SizedBox.shrink();
}
final detailState = InheritedDetailPageState.of(context);
final isZoomedNotifier = detailState.isZoomedNotifier;
- if (_localFilePath == null) {
- return const SizedBox.shrink();
- }
if (!_overlayActive) {
+ if (!_requiresRegionRouting) {
+ return _isPreparingOnDemand
+ ? _buildImageBoundedProcessingOverlay()
+ : const SizedBox.shrink();
+ }
+ if (_localFilePath == null) {
+ return const SizedBox.shrink();
+ }
+ if (_detectedRegions?.regions.isEmpty ?? true) {
+ return const SizedBox.shrink();
+ }
return _buildInactiveGestureLayer();
}
+ if (_localFilePath == null) {
+ return const SizedBox.shrink();
+ }
final zoomTransformNotifier = detailState.zoomTransformNotifier;
@@ -821,11 +856,11 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
}
}
-class _HasTextResult {
- final bool hasText;
- final String? localPath;
+class _RegionCacheEntry {
+ final String localPath;
+ final TextRegionDetectionResult result;
- const _HasTextResult({required this.hasText, this.localPath});
+ const _RegionCacheEntry({required this.localPath, required this.result});
}
class _OcrGestureHitTestBox extends SingleChildRenderObjectWidget {
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_region_hit_test.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_region_hit_test.dart
new file mode 100644
index 0000000000..3c375a10e7
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_region_hit_test.dart
@@ -0,0 +1,94 @@
+import "package:flutter/widgets.dart";
+import "package:mobile_ocr/models/text_region.dart";
+
+Rect containedImageRect(Size viewportSize, Size imageSize) {
+ if (viewportSize.width <= 0 ||
+ viewportSize.height <= 0 ||
+ imageSize.width <= 0 ||
+ imageSize.height <= 0) {
+ return Rect.zero;
+ }
+
+ final imageAspect = imageSize.width / imageSize.height;
+ final viewportAspect = viewportSize.width / viewportSize.height;
+ final double displayWidth;
+ final double displayHeight;
+ if (imageAspect > viewportAspect) {
+ displayWidth = viewportSize.width;
+ displayHeight = displayWidth / imageAspect;
+ } else {
+ displayHeight = viewportSize.height;
+ displayWidth = displayHeight * imageAspect;
+ }
+ return Rect.fromLTWH(
+ (viewportSize.width - displayWidth) / 2,
+ (viewportSize.height - displayHeight) / 2,
+ displayWidth,
+ displayHeight,
+ );
+}
+
+bool isViewportPointInTextRegions({
+ required Offset point,
+ required Size viewportSize,
+ required Size imageSize,
+ required List<TextRegion> regions,
+ double hitSlop = 0,
+}) {
+ if (regions.isEmpty) return false;
+ final photoRect = containedImageRect(viewportSize, imageSize);
+ if (photoRect.isEmpty || !photoRect.inflate(hitSlop).contains(point)) {
+ return false;
+ }
+
+ for (final region in regions) {
+ final viewportPoints = region.points
+ .map(
+ (regionPoint) => Offset(
+ photoRect.left + regionPoint.dx / imageSize.width * photoRect.width,
+ photoRect.top +
+ regionPoint.dy / imageSize.height * photoRect.height,
+ ),
+ )
+ .toList(growable: false);
+ if (_isPointInPaddedPolygon(point, viewportPoints, hitSlop)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool _isPointInPaddedPolygon(
+ Offset point,
+ List<Offset> polygon,
+ double padding,
+) {
+ if (polygon.length < 3) return false;
+
+ final path = Path()..moveTo(polygon.first.dx, polygon.first.dy);
+ for (final vertex in polygon.skip(1)) {
+ path.lineTo(vertex.dx, vertex.dy);
+ }
+ path.close();
+ if (path.contains(point)) return true;
+ if (padding <= 0) return false;
+
+ for (var index = 0; index < polygon.length; index++) {
+ final start = polygon[index];
+ final end = polygon[(index + 1) % polygon.length];
+ if (_distanceToSegment(point, start, end) <= padding) return true;
+ }
+ return false;
+}
+
+double _distanceToSegment(Offset point, Offset start, Offset end) {
+ final segment = end - start;
+ final lengthSquared = segment.distanceSquared;
+ if (lengthSquared == 0) return (point - start).distance;
+
+ final relative = point - start;
+ final projection =
+ ((relative.dx * segment.dx + relative.dy * segment.dy) / lengthSquared)
+ .clamp(0.0, 1.0);
+ return (point - (start + segment * projection)).distance;
+}
diff --git a/mobile/apps/photos/test/ui/viewer/file/inline_text_detection_test.dart b/mobile/apps/photos/test/ui/viewer/file/inline_text_detection_test.dart
new file mode 100644
index 0000000000..c9d8678c47
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/file/inline_text_detection_test.dart
@@ -0,0 +1,83 @@
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file/file_type.dart";
+import "package:photos/states/detail_page_state.dart";
+import "package:photos/ui/viewer/file/inline_text_detection.dart";
+
+void main() {
+ testWidgets("inactive OCR leaves still-photo taps available", (tester) async {
+ var tapped = false;
+
+ await tester.pumpWidget(
+ _testViewer(
+ photo: GestureDetector(
+ key: const Key("photo"),
+ behavior: HitTestBehavior.opaque,
+ onTap: () => tapped = true,
+ child: const SizedBox.expand(),
+ ),
+ ),
+ );
+ await tester.pump();
+
+ await tester.tap(find.byKey(const Key("photo")));
+
+ expect(tapped, isTrue);
+ });
+
+ testWidgets("inactive OCR leaves still-photo paging available", (
+ tester,
+ ) async {
+ final pageController = PageController();
+ addTearDown(pageController.dispose);
+
+ await tester.pumpWidget(
+ _testViewer(
+ photo: PageView(
+ controller: pageController,
+ children: const [
+ ColoredBox(color: Colors.black),
+ SizedBox.expand(),
+ ],
+ ),
+ ),
+ );
+ await tester.pump();
+
+ await tester.drag(find.byType(PageView), const Offset(-600, 0));
+ await tester.pumpAndSettle();
+
+ expect(pageController.page, 1);
+ });
+}
+
+Widget _testViewer({required Widget photo}) {
+ final file = EnteFile()
+ ..generatedID = 1
+ ..fileType = FileType.image;
+
+ return MaterialApp(
+ home: InheritedDetailPageState(
+ enableFullScreenNotifier: ValueNotifier(false),
+ isInSharedCollectionNotifier: ValueNotifier(false),
+ showingThumbnailFallbackNotifier: ValueNotifier(null),
+ isZoomedNotifier: ValueNotifier(false),
+ zoomTransformNotifier: ValueNotifier(ZoomTransform.identity),
+ child: Scaffold(
+ body: Stack(
+ children: [
+ Positioned.fill(child: photo),
+ Positioned.fill(
+ child: InlineTextDetection(
+ file: file,
+ controller: InlineTextDetectionController(),
+ isGuestView: false,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
diff --git a/mobile/apps/photos/test/ui/viewer/file/ocr/text_region_hit_test_test.dart b/mobile/apps/photos/test/ui/viewer/file/ocr/text_region_hit_test_test.dart
new file mode 100644
index 0000000000..373b99e3f3
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/file/ocr/text_region_hit_test_test.dart
@@ -0,0 +1,90 @@
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:mobile_ocr/models/text_region.dart";
+import "package:photos/ui/viewer/file/ocr/text_region_hit_test.dart";
+
+void main() {
+ const imageSize = Size(400, 200);
+ const viewportSize = Size(200, 200);
+ const region = TextRegion(
+ confidence: 0.9,
+ points: [
+ Offset(100, 50),
+ Offset(300, 50),
+ Offset(300, 100),
+ Offset(100, 100),
+ ],
+ );
+
+ test("maps letterboxed viewport points into image coordinates", () {
+ expect(
+ containedImageRect(viewportSize, imageSize),
+ const Rect.fromLTWH(0, 50, 200, 100),
+ );
+ expect(
+ isViewportPointInTextRegions(
+ point: const Offset(100, 87.5),
+ viewportSize: viewportSize,
+ imageSize: imageSize,
+ regions: const [region],
+ ),
+ isTrue,
+ );
+ });
+
+ test("rejects points outside text and outside the displayed image", () {
+ expect(
+ isViewportPointInTextRegions(
+ point: const Offset(20, 90),
+ viewportSize: viewportSize,
+ imageSize: imageSize,
+ regions: const [region],
+ ),
+ isFalse,
+ );
+ expect(
+ isViewportPointInTextRegions(
+ point: const Offset(100, 20),
+ viewportSize: viewportSize,
+ imageSize: imageSize,
+ regions: const [region],
+ ),
+ isFalse,
+ );
+ });
+
+ test("applies hit slop in viewport pixels", () {
+ expect(
+ isViewportPointInTextRegions(
+ point: const Offset(45, 87.5),
+ viewportSize: viewportSize,
+ imageSize: imageSize,
+ regions: const [region],
+ hitSlop: 8,
+ ),
+ isTrue,
+ );
+ });
+
+ test("does not claim corners outside a rotated text region", () {
+ const rotatedRegion = TextRegion(
+ confidence: 0.9,
+ points: [
+ Offset(200, 20),
+ Offset(380, 100),
+ Offset(200, 180),
+ Offset(20, 100),
+ ],
+ );
+
+ expect(
+ isViewportPointInTextRegions(
+ point: const Offset(15, 60),
+ viewportSize: viewportSize,
+ imageSize: imageSize,
+ regions: const [rotatedRegion],
+ ),
+ isFalse,
+ );
+ });
+}