π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile][photos] Improve zoomed OCR selection UX
Amrithesh Kakkoth Ente556281c34a50
diff --git a/mobile/apps/photos/lib/states/detail_page_state.dart b/mobile/apps/photos/lib/states/detail_page_state.dartindex 09fec51922..a93cbe6a10 100644--- a/mobile/apps/photos/lib/states/detail_page_state.dart+++ b/mobile/apps/photos/lib/states/detail_page_state.dart@@ -2,6 +2,29 @@ import "package:flutter/material.dart";import "package:flutter/services.dart";import "package:photos/models/file/file.dart";+/// Continuous zoom transform from the photo viewer.+///+/// [scale] is relative to the initial "contained" scale (1.0 = no zoom).+/// [offset] is the pan translation in logical pixels.+@immutable+class ZoomTransform {+ static const ZoomTransform identity =+ ZoomTransform(scale: 1.0, offset: Offset.zero);++ final double scale;+ final Offset offset;++ const ZoomTransform({required this.scale, required this.offset});++ @override+ bool operator ==(Object other) =>+ identical(this, other) ||+ other is ZoomTransform && other.scale == scale && other.offset == offset;++ @override+ int get hashCode => Object.hash(scale, offset);+}+enum FullScreenRequestReason {userInteraction,playbackStateChange,@@ -36,6 +59,10 @@ class InheritedDetailPageState extends InheritedWidget {/// Whether the photo viewer is currently zoomed in.final ValueNotifier<bool> isZoomedNotifier;+ /// Continuous zoom transform (scale + offset) from the photo viewer.+ /// Updated on every gesture frame so overlays can track the zoom.+ final ValueNotifier<ZoomTransform> zoomTransformNotifier;+// Cannot be const because we accept a ValueNotifier instance at runtime// ignore: prefer_const_constructors_in_immutablesInheritedDetailPageState({@@ -45,6 +72,7 @@ class InheritedDetailPageState extends InheritedWidget {required this.isInSharedCollectionNotifier,required this.showingThumbnailFallbackNotifier,required this.isZoomedNotifier,+ required this.zoomTransformNotifier,});static InheritedDetailPageState of(BuildContext context) =>@@ -96,5 +124,6 @@ class InheritedDetailPageState extends InheritedWidget {oldWidget.isInSharedCollectionNotifier != isInSharedCollectionNotifier ||oldWidget.showingThumbnailFallbackNotifier !=showingThumbnailFallbackNotifier ||- oldWidget.isZoomedNotifier != isZoomedNotifier;+ oldWidget.isZoomedNotifier != isZoomedNotifier ||+ oldWidget.zoomTransformNotifier != zoomTransformNotifier;}diff --git a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dartindex 9d06d36a6a..ee1b5f926d 100644--- a/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/detail_page.dart@@ -91,6 +91,7 @@ class _DetailPageState extends State<DetailPage> {final _isInSharedCollectionNotifier = ValueNotifier(false);final _showingThumbnailFallbackNotifier = ValueNotifier<String?>(null);final _isZoomedNotifier = ValueNotifier(false);+ final _zoomTransformNotifier = ValueNotifier(ZoomTransform.identity);@overridevoid dispose() {@@ -98,6 +99,7 @@ class _DetailPageState extends State<DetailPage> {_isInSharedCollectionNotifier.dispose();_showingThumbnailFallbackNotifier.dispose();_isZoomedNotifier.dispose();+ _zoomTransformNotifier.dispose();super.dispose();}@@ -111,6 +113,7 @@ class _DetailPageState extends State<DetailPage> {isInSharedCollectionNotifier: _isInSharedCollectionNotifier,showingThumbnailFallbackNotifier: _showingThumbnailFallbackNotifier,isZoomedNotifier: _isZoomedNotifier,+ zoomTransformNotifier: _zoomTransformNotifier,child: _Body(widget.config),);}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.dartindex 423d683d1b..a769f21dbd 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@@ -2,10 +2,13 @@ import "dart:async";import "dart:io";import "package:flutter/foundation.dart";+import "package:flutter/gestures.dart";import "package:flutter/material.dart";import "package:flutter/services.dart";import "package:logging/logging.dart";import "package:mobile_ocr/mobile_ocr.dart";+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/file.dart";import "package:photos/models/file/file_type.dart";@@ -16,7 +19,7 @@ import "package:photos/utils/file_util.dart";/// Inline text detection widget that mimics Apple's Live Text behavior:////// 1. Quick `hasText()` check runs silently when the image loads.-/// 2. If text is found and user stays on the image for 1 second, full+/// 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.@@ -39,6 +42,8 @@ class InlineTextDetection extends StatefulWidget {class _InlineTextDetectionState extends State<InlineTextDetection> {static const int _maxCacheSize = 200;+ static const Duration _autoActivateDelay = Duration(seconds: 1);+ static const double _globalGestureSlop = 18.0;static final Map<String, _HasTextResult> _hasTextCache = {};static final ValueNotifier<bool> _defaultZoomNotifier = ValueNotifier(false);final Logger _logger = Logger("InlineTextDetection");@@ -50,10 +55,26 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {int _requestId = 0;bool _overlayActive = false;Offset? _pendingLongPressPosition;+ Timer? _autoActivateTimer;+ bool _zoomGestureSettled = false;+ Timer? _zoomSettleTimer;+ ZoomTransform? _lastSeenTransform;+ int _activePointers = 0;+ bool _isPinching = false;+ bool _isCurrentlyZoomed = false;+ int _globalActivePointers = 0;+ int? _trackedGlobalPointer;+ Offset? _trackedGlobalPointerDownPosition;+ bool _trackedGlobalPointerMoved = false;+ bool _trackedGlobalLongPressTriggered = false;+ Timer? _globalLongPressTimer;@overridevoid initState() {super.initState();+ GestureBinding.instance.pointerRouter.addGlobalRoute(+ _handleGlobalPointerEvent,+ );_evaluateFile();}@@ -68,11 +89,19 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {@overridevoid dispose() {+ _autoActivateTimer?.cancel();+ _zoomSettleTimer?.cancel();+ _globalLongPressTimer?.cancel();+ GestureBinding.instance.pointerRouter.removeGlobalRoute(+ _handleGlobalPointerEvent,+ );_detectorController.dispose();super.dispose();}void _resetState() {+ _autoActivateTimer?.cancel();+ _cancelTrackedGlobalPointer();setState(() {_localFilePath = null;_overlayActive = false;@@ -133,7 +162,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {setState(() {_localFilePath = cached.localPath;});- if (cached.hasText) _activateOverlay();+ if (cached.hasText) _scheduleAutoActivate(requestId);return;}@@ -177,7 +206,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {_localFilePath = result.localPath;});- if (hasText) _activateOverlay();+ if (hasText) _scheduleAutoActivate(requestId);} catch (error, stackTrace) {_logger.severe("Text detection pre-check failed", error, stackTrace);if (!mounted || requestId != _requestId) return;@@ -186,13 +215,25 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {}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();+ });+ }+void _handleLongPress(LongPressStartDetails details) {if (_overlayActive) return; // Already active, let overlay handle it+ _autoActivateTimer?.cancel();setState(() {_pendingLongPressPosition = details.globalPosition;});@@ -205,6 +246,132 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {// Otherwise _evaluateFile will activate when hasText completes}+ bool get _canTrackTapToClearSelection =>+ _overlayActive && _detectorController.hasActiveSelection;++ bool get _canTrackZoomedPanFirstLongPress =>+ _overlayActive &&+ _isCurrentlyZoomed &&+ _zoomGestureSettled &&+ !_isPinching;++ bool _isPrimaryGlobalPointer(PointerDownEvent event) {+ if (event.kind == PointerDeviceKind.mouse) {+ return event.buttons == kPrimaryMouseButton;+ }+ return true;+ }++ void _cancelTrackedGlobalPointer() {+ _globalLongPressTimer?.cancel();+ _globalLongPressTimer = null;+ _trackedGlobalPointer = null;+ _trackedGlobalPointerDownPosition = null;+ _trackedGlobalPointerMoved = false;+ _trackedGlobalLongPressTriggered = false;+ }++ void _handleGlobalPointerDown(PointerDownEvent event) {+ _globalActivePointers++;+ if (!_isPrimaryGlobalPointer(event)) {+ return;+ }+ if (_globalActivePointers != 1) {+ _cancelTrackedGlobalPointer();+ return;+ }++ final bool tapCanClearSelection = _canTrackTapToClearSelection;+ final bool pointOnInteractiveUi =+ _detectorController.isPointOnInteractiveSelectionUi(event.position);+ final bool longPressCanSelect = _canTrackZoomedPanFirstLongPress &&+ !pointOnInteractiveUi &&+ _detectorController.isPointOnSelectableText(event.position);++ if (!tapCanClearSelection && !longPressCanSelect) {+ return;+ }++ if (pointOnInteractiveUi) {+ _cancelTrackedGlobalPointer();+ return;+ }++ _trackedGlobalPointer = event.pointer;+ _trackedGlobalPointerDownPosition = event.position;+ _trackedGlobalPointerMoved = false;+ _trackedGlobalLongPressTriggered = false;++ if (longPressCanSelect) {+ final Offset position = event.position;+ final int pointer = event.pointer;+ _globalLongPressTimer = Timer(kLongPressTimeout, () {+ if (!mounted ||+ _trackedGlobalPointer != pointer ||+ _trackedGlobalPointerMoved ||+ _globalActivePointers != 1 ||+ !_canTrackZoomedPanFirstLongPress) {+ return;+ }+ _trackedGlobalLongPressTriggered =+ _detectorController.selectTextAtPosition(position);+ });+ }+ }++ void _handleGlobalPointerMove(PointerMoveEvent event) {+ if (event.pointer != _trackedGlobalPointer) {+ return;+ }+ final Offset? initialPosition = _trackedGlobalPointerDownPosition;+ if (initialPosition == null) {+ return;+ }+ if ((event.position - initialPosition).distance > _globalGestureSlop) {+ _trackedGlobalPointerMoved = true;+ _globalLongPressTimer?.cancel();+ _globalLongPressTimer = null;+ }+ }++ void _handleGlobalPointerEnd(PointerEvent event) {+ if (event.pointer == _trackedGlobalPointer) {+ final bool shouldClearSelection = !_trackedGlobalLongPressTriggered &&+ !_trackedGlobalPointerMoved &&+ _canTrackTapToClearSelection &&+ !_detectorController.isPointOnInteractiveSelectionUi(event.position);+ if (shouldClearSelection) {+ _detectorController.clearSelection();+ }+ _cancelTrackedGlobalPointer();+ }+ }++ void _handleGlobalPointerEvent(PointerEvent event) {+ if (event is PointerDownEvent) {+ _handleGlobalPointerDown(event);+ return;+ }++ if (event is PointerMoveEvent) {+ _handleGlobalPointerMove(event);+ return;+ }++ if (event is PointerUpEvent) {+ _globalActivePointers =+ _globalActivePointers > 0 ? _globalActivePointers - 1 : 0;+ _handleGlobalPointerEnd(event);+ return;+ }++ if (event is PointerCancelEvent) {+ _globalActivePointers =+ _globalActivePointers > 0 ? _globalActivePointers - 1 : 0;+ _handleGlobalPointerEnd(event);+ }+ }+@overrideWidget build(BuildContext context) {if (!_isEligible || widget.file is TrashFile || widget.isGuestView) {@@ -216,7 +383,11 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {// During the wait period (hasText passed but 1s timer hasn't fired),// show a transparent gesture layer to capture long press.- if (!_overlayActive || _localFilePath == null) {+ // Only show when we know text exists to avoid blocking motion photo gestures.+ if (_localFilePath == null) {+ return const SizedBox.shrink();+ }+ if (!_overlayActive) {return Positioned.fill(child: GestureDetector(behavior: HitTestBehavior.translucent,@@ -226,26 +397,110 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {);}+ final detailState = InheritedDetailPageState.maybeOf(context);+ final zoomTransformNotifier = detailState?.zoomTransformNotifier;+return ValueListenableBuilder<bool>(valueListenable: isZoomedNotifier ?? _defaultZoomNotifier,builder: (context, isZoomed, _) {- final bool shouldHide = isZoomed;-- return Positioned.fill(- child: IgnorePointer(- ignoring: shouldHide,- child: AnimatedOpacity(- opacity: shouldHide ? 0.0 : 1.0,- duration: const Duration(milliseconds: 150),- child: _buildInlineOverlay(context),- ),- ),+ _isCurrentlyZoomed = isZoomed;+ if (!isZoomed) {+ _zoomGestureSettled = false;+ _zoomSettleTimer?.cancel();+ _lastSeenTransform = null;+ }+ return ValueListenableBuilder<ZoomTransform>(+ valueListenable:+ zoomTransformNotifier ?? ValueNotifier(ZoomTransform.identity),+ builder: (context, transform, _) {+ // Only reset the debounce when the transform has genuinely changed.+ // Guarding on value change prevents the setState rebuild from the+ // timer itself from re-entering this block and restarting the timer,+ // which would create an infinite loop where _zoomGestureSettled+ // can never stay true.+ if (isZoomed && transform != _lastSeenTransform) {+ _lastSeenTransform = transform;+ _zoomGestureSettled = false;+ _zoomSettleTimer?.cancel();+ _zoomSettleTimer = Timer(const Duration(milliseconds: 200), () {+ if (mounted) {+ setState(() {+ _zoomGestureSettled = true;+ });+ }+ });+ }++ Widget overlay = _buildInlineOverlay(+ context,+ isZoomed: isZoomed,+ uiScale: transform.scale,+ uiOffset: transform.offset,+ );++ // Always apply the Transform, even when not zoomed.+ // When not zoomed, transform == ZoomTransform.identity (scale=1,+ // offset=zero), so this is a no-op visually. Applying it+ // unconditionally means teardrops and text boundaries immediately+ // track zoom from the very first stream event, with no flash at+ // the unscaled position that occurs when the Transform was only+ // added after isZoomedNotifier fired.+ overlay = Transform(+ alignment: Alignment.center,+ transform: Matrix4.identity()+ ..translate(transform.offset.dx, transform.offset.dy)+ ..scale(transform.scale),+ child: overlay,+ );++ // Ignore pointer events when:+ // - Actively pinching (2+ fingers down) β let PhotoView handle zoom+ // - Zoomed but gesture not yet settled β transform is still changing+ final shouldIgnore =+ _isPinching || (isZoomed && !_zoomGestureSettled);++ return Positioned.fill(+ child: Listener(+ behavior: HitTestBehavior.translucent,+ onPointerDown: (_) {+ _activePointers++;+ if (_activePointers >= 2 && !_isPinching) {+ setState(() {+ _isPinching = true;+ _zoomGestureSettled = false;+ });+ }+ },+ onPointerUp: (_) {+ if (_activePointers > 0) _activePointers--;+ if (_activePointers < 2 && _isPinching) {+ setState(() => _isPinching = false);+ }+ },+ onPointerCancel: (_) {+ if (_activePointers > 0) _activePointers--;+ if (_activePointers < 2 && _isPinching) {+ setState(() => _isPinching = false);+ }+ },+ child: IgnorePointer(+ ignoring: shouldIgnore,+ child: overlay,+ ),+ ),+ );+ },);},);}- Widget _buildInlineOverlay(BuildContext context) {+ Widget _buildInlineOverlay(+ BuildContext context, {+ required bool isZoomed,+ double uiScale = 1.0,+ Offset uiOffset = Offset.zero,+ }) {final l10n = context.l10n;return ListenableBuilder(listenable: _detectorController,@@ -287,6 +542,20 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {showEditorHint: false,initialInteractionPosition: _pendingLongPressPosition,controller: _detectorController,+ isImageZoomed: isZoomed,+ onDoubleTapWhenZoomed: isZoomed+ ? () {+ Bus.instance.fire(+ ResetZoomOfPhotoView(+ uploadedFileID: widget.file.uploadedFileID,+ localID: widget.file.localID,+ ),+ );+ }+ : null,+ uiScale: uiScale,+ uiOffset: uiOffset,+ zoomedInteractionPolicy: ZoomedInteractionPolicy.panFirst,strings: TextDetectorStrings(processingOverlayMessage: l10n.ocrProcessingOverlayMessage,selectionHint: l10n.ocrSelectionHint,diff --git a/mobile/apps/photos/lib/ui/viewer/file/zoomable_image.dart b/mobile/apps/photos/lib/ui/viewer/file/zoomable_image.dartindex 156b6527a1..9fd1a9c6cd 100644--- a/mobile/apps/photos/lib/ui/viewer/file/zoomable_image.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/zoomable_image.dart@@ -66,6 +66,11 @@ class _ZoomableImageState extends State<ZoomableImage> {bool _isZooming = false;PhotoViewController _photoViewController = PhotoViewController();final _scaleStateController = PhotoViewScaleStateController();+ StreamSubscription<dynamic>? _zoomStreamSubscription;++ // Baseline PhotoView scale for the current image/controller when the image+ // is at its contained size. ZoomTransform.scale is reported relative to this.+ double? _initialScale;late final StreamSubscription<FileCaptionUpdatedEvent>_captionUpdatedSubscription;late final StreamSubscription<ResetZoomOfPhotoView> _resetZoomSubscription;@@ -85,13 +90,16 @@ class _ZoomableImageState extends State<ZoomableImage> {widget.shouldDisableScroll!(value != PhotoViewScaleState.initial);}_isZooming = value != PhotoViewScaleState.initial;- InheritedDetailPageState.maybeOf(context)- ?.isZoomedNotifier- .value = _isZooming;- debugPrint("isZooming = $_isZooming, currentState $value");- // _logger.info('is reakky zooming $_isZooming with state $value');+ final state = InheritedDetailPageState.maybeOf(context);+ state?.isZoomedNotifier.value = _isZooming;+ if (!_isZooming) {+ _initialScale = _photoViewController.scale ?? _initialScale;+ state?.zoomTransformNotifier.value = ZoomTransform.identity;+ }};+ _subscribeToZoomStream();+_captionUpdatedSubscription =Bus.instance.on<FileCaptionUpdatedEvent>().listen((event) {if (event.fileGeneratedID == _photo.generatedID) {@@ -112,8 +120,27 @@ class _ZoomableImageState extends State<ZoomableImage> {});}+ void _subscribeToZoomStream() {+ _zoomStreamSubscription =+ _photoViewController.outputStateStream.listen((value) {+ final state = InheritedDetailPageState.maybeOf(context);+ if (value.scale == null) return;+ if (!_isZooming) {+ _initialScale = value.scale;+ state?.zoomTransformNotifier.value = ZoomTransform.identity;+ return;+ }+ _initialScale ??= value.scale;+ state?.zoomTransformNotifier.value = ZoomTransform(+ scale: value.scale! / _initialScale!,+ offset: value.position,+ );+ });+ }+@overridevoid dispose() {+ _zoomStreamSubscription?.cancel();_photoViewController.dispose();_scaleStateController.dispose();_captionUpdatedSubscription.cancel();@@ -462,13 +489,26 @@ class _ZoomableImageState extends State<ZoomableImage> {if (shouldFixPosition) {final prevImageInfo = await getImageInfo(previewImageProvider);finalImageInfo = await getImageInfo(finalImageProvider);- final scale = _photoViewController.scale! /+ final previousScale = _photoViewController.scale!;+ final previousRelativeScale = _initialScale != null && _initialScale! > 0+ ? previousScale / _initialScale!+ : null;+ final scale = previousScale /(finalImageInfo.image.width / prevImageInfo.image.width);final currentPosition = _photoViewController.value.position;+ unawaited(_zoomStreamSubscription?.cancel());_photoViewController = PhotoViewController(initialPosition: currentPosition,initialScale: scale,);+ if (previousRelativeScale != null &&+ previousRelativeScale.isFinite &&+ previousRelativeScale > 0) {+ _initialScale = scale / previousRelativeScale;+ } else {+ _initialScale = null;+ }+ _subscribeToZoomStream();// Fix for auto-zooming when final image is loaded after double tapping//twice._scaleStateController.scaleState = PhotoViewScaleState.zoomedIn;diff --git a/mobile/apps/photos/pubspec.lock b/mobile/apps/photos/pubspec.lockindex 8d93c68600..cebf48843c 100644--- a/mobile/apps/photos/pubspec.lock+++ b/mobile/apps/photos/pubspec.lock@@ -1800,9 +1800,9 @@ packages:dependency: "direct main"description:path: "."- ref: e5edc649e79c822369c87fd8ea8d1db2e5419124- resolved-ref: e5edc649e79c822369c87fd8ea8d1db2e5419124- url: "https://github.com/ente-io/mobile_ocr"+ ref: "197f7d6dc5696f7a6c663c15e255c664fb77ac01"+ resolved-ref: "197f7d6dc5696f7a6c663c15e255c664fb77ac01"+ url: "https://github.com/Amrithesh-Kakkoth/mobile_ocr"source: gitversion: "1.0.0"mockito:diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yamlindex d2890f3a56..b1540737fb 100644--- a/mobile/apps/photos/pubspec.yaml+++ b/mobile/apps/photos/pubspec.yaml@@ -149,8 +149,8 @@ dependencies:ml_linalg: ^13.11.31mobile_ocr:git:- url: https://github.com/ente-io/mobile_ocr- ref: e5edc649e79c822369c87fd8ea8d1db2e5419124+ url: https://github.com/Amrithesh-Kakkoth/mobile_ocr+ ref: 197f7d6dc5696f7a6c663c15e255c664fb77ac01modal_bottom_sheet: ^3.0.0motionphoto:git: "https://github.com/ente-io/motionphoto.git"