Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use app-owned OCR selection UI

laurenspriem6d2c15d41237
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 311769eb84..699dfb8925 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
@@ -12,13 +12,7 @@ import "package:mobile_ocr/mobile_ocr.dart"
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";
+ TextRegionDetectionResult;
import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
@@ -26,6 +20,7 @@ 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_detector_widget.dart";
import "package:photos/ui/viewer/file/ocr/text_region_hit_test.dart";
import "package:photos/utils/image_util.dart";
@@ -887,33 +882,12 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
child: TextDetectorWidget(
key: ValueKey("ocr_$_localFilePath"),
imagePath: _localFilePath!,
- autoDetect: true,
- backgroundColor: Colors.transparent,
- showUnselectedBoundaries: false,
- overlayOnly: true,
- showProcessingOverlay: false,
- showScanAnimation: false,
- showEditorHint: false,
- showNoTextMessageOnAutoDetect: 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,
noTextDetected: l10n.ocrNoTextDetected,
retryButtonLabel: l10n.retry,
modelsNetworkRequiredError: l10n.ocrModelsNetworkRequiredError,
@@ -922,7 +896,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
imageDecodeFailedError: l10n.ocrImageDecodeFailedError,
genericDetectError: l10n.ocrGenericDetectError,
),
- onTextCopied: (text) {
+ onTextCopied: () {
HapticFeedback.lightImpact();
},
),
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
index c5b6eb179b..65a40567a0 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
@@ -1,20 +1,16 @@
import 'dart:async';
import 'dart:io';
-import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
-import 'package:mobile_ocr/mobile_ocr_plugin.dart';
-import 'package:mobile_ocr/models/text_block.dart';
-import 'package:mobile_ocr/src/display_image_helper.dart';
-import 'package:mobile_ocr/widgets/text_overlay_widget.dart';
+import 'package:mobile_ocr/mobile_ocr.dart'
+ show DisplayImageHelper, MobileOcr, TextBlock;
+import 'package:photos/ui/viewer/file/ocr/text_overlay_widget.dart';
const Color _entePrimaryColor = Color(0xFF1DB954);
const double _enteSelectionHighlightOpacity = 0.28;
/// Collection of user-facing strings used by [TextDetectorWidget].
class TextDetectorStrings {
- final String processingOverlayMessage;
- final String selectionHint;
final String noTextDetected;
final String retryButtonLabel;
final String modelsNetworkRequiredError;
@@ -24,16 +20,13 @@ class TextDetectorStrings {
final String genericDetectError;
const TextDetectorStrings({
- this.processingOverlayMessage = 'Detecting text...',
- this.selectionHint = 'Swipe or double tap to select just what you need',
- this.noTextDetected = 'No text detected',
- this.retryButtonLabel = 'Retry',
- this.modelsNetworkRequiredError =
- 'Network connection required to download OCR models on first use',
- this.modelsPrepareFailed = 'Could not prepare OCR models',
- this.imageNotFoundError = 'Image file not found',
- this.imageDecodeFailedError = 'Could not read image file',
- this.genericDetectError = 'Could not detect text in image',
+ required this.noTextDetected,
+ required this.retryButtonLabel,
+ required this.modelsNetworkRequiredError,
+ required this.modelsPrepareFailed,
+ required this.imageNotFoundError,
+ required this.imageDecodeFailedError,
+ required this.genericDetectError,
});
}
@@ -72,15 +65,6 @@ class TextDetectorController extends ChangeNotifier {
bool get userAttemptedInteraction =>
_state?._userAttemptedInteraction ?? false;
- /// Programmatically select all recognized text.
- bool selectAllText() {
- final state = _state;
- if (state == null) {
- return false;
- }
- return state._selectAllRecognizedText();
- }
-
bool get hasActiveSelection => _state?._hasActiveSelection ?? false;
bool selectTextAtPosition(Offset globalPosition) {
@@ -104,104 +88,27 @@ class TextDetectorController extends ChangeNotifier {
}
}
-/// A complete text detection widget that displays an image and allows
-/// users to select and copy detected text.
+/// Detects text and renders the Photos OCR selection overlay.
class TextDetectorWidget extends StatefulWidget {
- /// The path to the image file to detect text from
final String imagePath;
-
- /// Callback when text is copied
- final Function(String)? onTextCopied;
-
- /// Callback when text blocks are selected
- final Function(List<TextBlock>)? onTextBlocksSelected;
-
- /// Whether to auto-detect text on load
- final bool autoDetect;
-
- /// Background color
- final Color backgroundColor;
-
- /// Whether to show boundaries for unselected text
- final bool showUnselectedBoundaries;
-
- /// Whether to show the inline selection preview banner.
- final bool enableSelectionPreview;
-
- /// Enable debug utilities like the detected-text dialog.
- final bool debugMode;
-
- /// Strings used for user-facing text in the widget.
+ final VoidCallback? onTextCopied;
final TextDetectorStrings strings;
-
- /// Controller for imperative text selection actions.
- final TextDetectorController? controller;
-
- /// When true, only the text overlay is rendered (no image). Use this when
- /// the image is already displayed by another widget underneath.
- final bool overlayOnly;
-
- /// Whether to show the "Detecting text..." overlay during processing.
- /// Defaults to true for backward compatibility.
- final bool showProcessingOverlay;
-
- /// Whether to show the selection hint after text is detected.
- /// Defaults to true for backward compatibility.
- final bool showEditorHint;
-
- /// Whether automatic detection should show the no-text message.
- final bool showNoTextMessageOnAutoDetect;
-
- /// When set, the widget starts with the interaction animation active and
- /// will auto-select text at this position after detection completes.
- /// Used when the parent captured a long press before the widget was built.
+ final TextDetectorController controller;
final Offset? initialInteractionPosition;
-
- /// Whether to show the built-in scan line animation during processing.
- /// Defaults to true for backward compatibility.
- final bool showScanAnimation;
-
- /// Whether the underlying image viewer is currently zoomed.
final bool isImageZoomed;
-
- /// Optional callback invoked instead of word selection on double tap while
- /// the underlying image is zoomed.
- final VoidCallback? onDoubleTapWhenZoomed;
-
- /// Scale factor applied to the overlay by an ancestor transform.
- /// Passed to [TextOverlayWidget] to counter-scale UI chrome (handles,
- /// copy button) back to a fixed screen size. Defaults to 1.0 (no scaling).
final double uiScale;
-
- /// Translation applied to the overlay by an ancestor transform.
final Offset uiOffset;
- /// Determines how OCR gestures should behave while the image is zoomed.
- final ZoomedInteractionPolicy zoomedInteractionPolicy;
-
const TextDetectorWidget({
super.key,
required this.imagePath,
+ required this.strings,
+ required this.controller,
+ required this.isImageZoomed,
+ required this.uiScale,
+ required this.uiOffset,
this.onTextCopied,
- this.onTextBlocksSelected,
- this.autoDetect = true,
- this.backgroundColor = Colors.transparent,
- this.showUnselectedBoundaries = true,
- this.enableSelectionPreview = false,
- this.debugMode = false,
- this.strings = const TextDetectorStrings(),
- this.controller,
- this.overlayOnly = false,
- this.showProcessingOverlay = true,
- this.showEditorHint = true,
- this.showNoTextMessageOnAutoDetect = true,
this.initialInteractionPosition,
- this.showScanAnimation = true,
- this.isImageZoomed = false,
- this.onDoubleTapWhenZoomed,
- this.uiScale = 1.0,
- this.uiOffset = Offset.zero,
- this.zoomedInteractionPolicy = ZoomedInteractionPolicy.panFirst,
});
@override
@@ -213,14 +120,11 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
final TextOverlayController _textOverlayController = TextOverlayController();
List<TextBlock>? _detectedTextBlocks;
bool _isProcessing = false;
- File? _imageFile;
String? _resolvedImagePath;
Future<void>? _imagePreparation;
bool _modelsReady = false;
Future<void>? _modelPreparation;
String? _errorMessage;
- Timer? _editorHintTimer;
- bool _showEditorHint = false;
bool _isNetworkError = false;
Size? _imageSize;
bool _userAttemptedInteraction = false;
@@ -233,17 +137,12 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
@override
void initState() {
super.initState();
- widget.controller?._attach(this);
- // Pick up initial interaction from parent (e.g. long press before widget existed)
+ widget.controller._attach(this);
+ _isProcessing = true;
if (widget.initialInteractionPosition != null) {
_userAttemptedInteraction = true;
_pendingSelectionPosition = widget.initialInteractionPosition;
- _isProcessing = true;
- } else if (widget.autoDetect) {
- // Set initial processing state if auto-detecting
- _isProcessing = true;
}
- // Schedule file initialization after first frame to ensure immediate rendering
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
unawaited(_initializeFile());
@@ -253,14 +152,12 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
@override
void dispose() {
_cancelActiveDetection();
- _editorHintTimer?.cancel();
- widget.controller?._detach(this);
+ widget.controller._detach(this);
super.dispose();
}
Future<void> _initializeFile() async {
final requestedPath = widget.imagePath;
- _editorHintTimer?.cancel();
final preparation = _prepareDisplayImage(requestedPath);
_imagePreparation = preparation;
@@ -272,9 +169,7 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
Future<void> _prepareDisplayImage(String requestedPath) async {
setState(() {
- _imageFile = null;
_resolvedImagePath = null;
- _showEditorHint = false;
_errorMessage = null;
});
@@ -291,24 +186,15 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
}
setState(() {
- _imageFile = file;
_resolvedImagePath = resolvedPath;
});
-
- if (!widget.overlayOnly) {
- _precacheCurrentImage();
- }
-
- if (widget.autoDetect || widget.initialInteractionPosition != null) {
- unawaited(_detectText());
- }
+ unawaited(_detectText());
} catch (error) {
debugPrint('Failed to prepare image $requestedPath: $error');
if (!mounted || widget.imagePath != requestedPath) {
return;
}
setState(() {
- _imageFile = null;
_resolvedImagePath = null;
_errorMessage = widget.strings.imageDecodeFailedError;
_isProcessing = false;
@@ -316,29 +202,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
}
}
- @override
- void didUpdateWidget(covariant TextDetectorWidget oldWidget) {
- super.didUpdateWidget(oldWidget);
- if (oldWidget.controller != widget.controller) {
- oldWidget.controller?._detach(this);
- widget.controller?._attach(this);
- }
- if (oldWidget.imagePath != widget.imagePath) {
- _cancelActiveDetection();
- setState(() {
- _isProcessing = widget.autoDetect;
- _detectedTextBlocks = null;
- _imageFile = null;
- _errorMessage = null;
- _isNetworkError = false;
- _userAttemptedInteraction = false;
- _pendingSelectionPosition = null;
- });
- _notifyController();
- unawaited(_initializeFile());
- }
- }
-
void _cancelActiveDetection() {
final requestId = _activeDetectionRequestId;
_activeDetectionRequestId = null;
@@ -400,7 +263,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
return;
}
- // Don't set processing true here if already processing
if (!_isProcessing) {
setState(() {
_isProcessing = true;
@@ -439,10 +301,7 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
_pendingSelectionPosition = null;
});
_notifyController();
- _handleEditorHint(_detectedTextBlocks ?? []);
- // If the user long-pressed during processing, queue auto-select.
- // The overlay controller will execute it once block visuals are ready.
if (pendingPos != null && (_detectedTextBlocks?.isNotEmpty ?? false)) {
_textOverlayController.selectTextAtPosition(pendingPos);
}
@@ -451,7 +310,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
debugPrint('Error detecting text: $e');
if (mounted && widget.imagePath == requestedPath) {
setState(() {
- // Show user-friendly message based on error type
final errorStr = e.toString().toLowerCase();
if (errorStr.contains('image') &&
errorStr.contains('not') &&
@@ -493,11 +351,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
@override
Widget build(BuildContext context) {
- final bool showProcessingAnimation =
- _isProcessing &&
- _detectedTextBlocks == null &&
- _userAttemptedInteraction;
-
return GestureDetector(
behavior: HitTestBehavior.translucent,
onLongPressStart: _hasSelectableText ? null : _handleLongPressStart,
@@ -505,18 +358,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
fit: StackFit.expand,
children: [
_buildImageLayer(),
- if (showProcessingAnimation && widget.showScanAnimation)
- const _ScanLineAnimation(),
- if (widget.showProcessingOverlay &&
- _isProcessing &&
- _detectedTextBlocks == null &&
- !_userAttemptedInteraction)
- _buildProcessingOverlay(),
- if (widget.showEditorHint &&
- _showEditorHint &&
- _detectedTextBlocks != null &&
- _detectedTextBlocks!.isNotEmpty)
- _buildEditorHint(),
if (_errorMessage != null)
Positioned(
bottom: 32,
@@ -526,8 +367,7 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
? _buildNetworkErrorBanner(_errorMessage!)
: _buildErrorBanner(_errorMessage!),
),
- if ((widget.showNoTextMessageOnAutoDetect ||
- _userAttemptedInteraction) &&
+ if (_userAttemptedInteraction &&
_detectedTextBlocks != null &&
_detectedTextBlocks!.isEmpty &&
_errorMessage == null)
@@ -542,86 +382,10 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
);
}
- Widget _buildEditorHint() {
- return Positioned(
- bottom: 36,
- left: 0,
- right: 0,
- child: IgnorePointer(
- child: Center(
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
- decoration: BoxDecoration(
- color: Colors.black.withValues(alpha: 0.75),
- borderRadius: BorderRadius.circular(18),
- border: Border.all(
- color: CupertinoColors.activeBlue.withValues(alpha: 0.3),
- width: 0.8,
- ),
- ),
- child: Text(
- widget.strings.selectionHint,
- style: const TextStyle(
- color: Colors.white,
- fontSize: 13,
- fontWeight: FontWeight.w600,
- ),
- ),
- ),
- ),
- ),
- );
- }
-
- void _handleEditorHint(List<TextBlock> blocks) {
- _editorHintTimer?.cancel();
- if (!mounted) {
- return;
- }
-
- if (blocks.isEmpty) {
- if (_showEditorHint) {
- setState(() {
- _showEditorHint = false;
- });
- }
- return;
- }
-
- setState(() {
- _showEditorHint = true;
- });
-
- _editorHintTimer = Timer(const Duration(seconds: 3), () {
- if (!mounted) {
- return;
- }
- setState(() {
- _showEditorHint = false;
- });
- });
- }
-
- void _dismissEditorHint() {
- if (!_showEditorHint) {
- return;
- }
- _editorHintTimer?.cancel();
- if (!mounted) {
- return;
- }
- setState(() {
- _showEditorHint = false;
- });
- }
-
Widget _buildImageLayer() {
- final imageFile = _imageFile;
final textBlocks = _detectedTextBlocks;
- if (imageFile == null || textBlocks == null) {
- return const SizedBox.shrink();
- }
- if (widget.overlayOnly && _imageSize == null) {
+ final imageSize = _imageSize;
+ if (textBlocks == null || imageSize == null) {
return const SizedBox.shrink();
}
@@ -636,67 +400,16 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
selectionHandleColor: _entePrimaryColor,
);
- final overlayWidget = TextOverlayWidget(
- imageFile: widget.overlayOnly ? null : imageFile,
- imageSize: widget.overlayOnly ? _imageSize : null,
- textBlocks: textBlocks,
- onTextBlocksSelected: widget.onTextBlocksSelected,
- onTextCopied: widget.onTextCopied,
- onSelectionStart: _dismissEditorHint,
- showUnselectedBoundaries: widget.showUnselectedBoundaries,
- enableSelectionPreview: widget.enableSelectionPreview,
- debugMode: widget.debugMode,
- controller: _textOverlayController,
- isImageZoomed: widget.isImageZoomed,
- onDoubleTapWhenZoomed: widget.onDoubleTapWhenZoomed,
- uiScale: widget.uiScale,
- uiOffset: widget.uiOffset,
- zoomedInteractionPolicy: widget.zoomedInteractionPolicy,
- );
-
- // In overlay-only mode, don't wrap in a Container with a color β€”
- // even Colors.transparent creates a hit target that blocks the
- // underlying PageView from receiving swipes.
- if (widget.overlayOnly) {
- return TextSelectionTheme(
- data: overlaySelectionTheme,
- child: overlayWidget,
- );
- }
-
- return Container(
- color: widget.backgroundColor,
- child: TextSelectionTheme(
- data: overlaySelectionTheme,
- child: overlayWidget,
- ),
- );
- }
-
- Widget _buildProcessingOverlay() {
- return Positioned(
- top: 100,
- left: 0,
- right: 0,
- child: Center(
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
- decoration: BoxDecoration(
- color: Colors.black.withValues(alpha: 0.7),
- borderRadius: BorderRadius.circular(20),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- const CupertinoActivityIndicator(radius: 10, color: Colors.white),
- const SizedBox(width: 8),
- Text(
- widget.strings.processingOverlayMessage,
- style: const TextStyle(color: Colors.white, fontSize: 14),
- ),
- ],
- ),
- ),
+ return TextSelectionTheme(
+ data: overlaySelectionTheme,
+ child: TextOverlayWidget(
+ imageSize: imageSize,
+ textBlocks: textBlocks,
+ onTextCopied: widget.onTextCopied,
+ controller: _textOverlayController,
+ isImageZoomed: widget.isImageZoomed,
+ uiScale: widget.uiScale,
+ uiOffset: widget.uiOffset,
),
);
}
@@ -810,24 +523,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
);
}
- /// Manually trigger text detection
- Future<void> detectText() {
- return _detectText();
- }
-
- /// Get the currently detected text blocks
- List<TextBlock>? get detectedTextBlocks => _detectedTextBlocks;
-
- /// Check if text detection is currently processing
- bool get isProcessing => _isProcessing;
-
- bool _selectAllRecognizedText() {
- if (!_hasSelectableText) {
- return false;
- }
- return _textOverlayController.selectAllText();
- }
-
bool get _hasActiveSelection => _textOverlayController.hasActiveSelection;
bool _selectTextAtPosition(Offset globalPosition) {
@@ -861,88 +556,6 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
}
void _notifyController() {
- widget.controller?._notifyStateChanged();
- }
-
- void _precacheCurrentImage() {
- final imageFile = _imageFile;
- if (imageFile == null) {
- return;
- }
- precacheImage(FileImage(imageFile), context);
- }
-}
-
-/// A subtle scanning line that sweeps top-to-bottom while OCR is running.
-class _ScanLineAnimation extends StatefulWidget {
- const _ScanLineAnimation();
-
- @override
- State<_ScanLineAnimation> createState() => _ScanLineAnimationState();
-}
-
-class _ScanLineAnimationState extends State<_ScanLineAnimation>
- with SingleTickerProviderStateMixin {
- late final AnimationController _controller;
-
- @override
- void initState() {
- super.initState();
- _controller = AnimationController(
- vsync: this,
- duration: const Duration(milliseconds: 1800),
- )..repeat();
+ widget.controller._notifyStateChanged();
}
-
- @override
- void dispose() {
- _controller.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return IgnorePointer(
- child: AnimatedBuilder(
- animation: _controller,
- builder: (context, _) {
- return CustomPaint(
- painter: _ScanLinePainter(
- progress: _controller.value,
- color: _entePrimaryColor,
- ),
- size: Size.infinite,
- );
- },
- ),
- );
- }
-}
-
-class _ScanLinePainter extends CustomPainter {
- final double progress;
- final Color color;
-
- _ScanLinePainter({required this.progress, required this.color});
-
- @override
- void paint(Canvas canvas, Size size) {
- final double y = size.height * progress;
- final paint = Paint()
- ..shader = LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- colors: [
- color.withValues(alpha: 0.0),
- color.withValues(alpha: 0.4),
- color.withValues(alpha: 0.0),
- ],
- stops: const [0.0, 0.5, 1.0],
- ).createShader(Rect.fromLTWH(0, y - 30, size.width, 60));
- canvas.drawRect(Rect.fromLTWH(0, y - 30, size.width, 60), paint);
- }
-
- @override
- bool shouldRepaint(_ScanLinePainter oldDelegate) =>
- oldDelegate.progress != progress;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
index cc64e6336b..fc5708fd18 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
@@ -1,14 +1,12 @@
-import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
-import 'dart:ui' as ui;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
-import 'package:mobile_ocr/models/text_block.dart';
-import 'package:mobile_ocr/src/text_reading_order.dart';
+import 'package:mobile_ocr/mobile_ocr.dart' show CharacterBox, TextBlock;
+import 'package:photos/ui/viewer/file/ocr/text_reading_order.dart';
// OCR character boxes tend to overhang slightly on the left edge, so keep the
// added selection slack slightly right-biased to visually center the highlight.
@@ -18,8 +16,6 @@ const double _kHighlightVerticalPadding = 1.6;
const double _kHighlightCornerRadius = 4.0;
const double _kHighlightLineToleranceFactor = 0.7;
-enum ZoomedInteractionPolicy { interactive, panFirst }
-
/// Controller that surfaces imperative actions for [TextOverlayWidget].
class TextOverlayController {
_TextOverlayWidgetState? _state;
@@ -34,24 +30,6 @@ class TextOverlayController {
}
}
- /// Attempts to select every recognized text block.
- bool selectAllText() {
- final state = _state;
- if (state == null) {
- return false;
- }
- return state._selectAllText();
- }
-
- /// Whether there is any recognized text to select.
- bool get hasSelectableText {
- final state = _state;
- if (state == null) {
- return false;
- }
- return state._hasSelectableText;
- }
-
bool get hasActiveSelection => _state?._hasActiveSelection ?? false;
/// Queue a position to auto-select when the overlay is ready.
@@ -92,68 +70,26 @@ class TextOverlayController {
}
}
-/// A widget that overlays detected text on top of the source image while
-/// providing an editor-like selection experience.
-///
-/// Can operate in two modes:
-/// - **Image mode** (default): Pass [imageFile] and the widget renders the
-/// image with text overlays on top.
-/// - **Overlay-only mode**: Pass [imageSize] instead of [imageFile] and the
-/// widget renders only the transparent text overlay. Use this when the image
-/// is already rendered by another widget (e.g. PhotoView) and you just need
-/// the text selection layer on top.
+/// Renders selectable OCR text over the image displayed by the Photos viewer.
class TextOverlayWidget extends StatefulWidget {
- final File? imageFile;
+ final Size imageSize;
final List<TextBlock> textBlocks;
- final Function(List<TextBlock>)? onTextBlocksSelected;
- final Function(String)? onTextCopied;
- final VoidCallback? onSelectionStart;
- final bool showUnselectedBoundaries;
- final bool enableSelectionPreview;
- final bool debugMode;
- final TextOverlayController? controller;
+ final VoidCallback? onTextCopied;
+ final TextOverlayController controller;
final bool isImageZoomed;
- final VoidCallback? onDoubleTapWhenZoomed;
-
- /// The original image dimensions in pixels. Required when using
- /// overlay-only mode (no [imageFile]). When [imageFile] is provided
- /// this is ignored β€” dimensions are read from the file.
- final Size? imageSize;
-
- /// Scale factor applied to the overlay by an ancestor transform (e.g.
- /// during photo zoom). Selection handles and the copy button are
- /// counter-scaled by 1/[uiScale] so they appear at a fixed screen size
- /// regardless of zoom level.
final double uiScale;
-
- /// Translation applied to the overlay by an ancestor transform.
- /// Used to clamp selection UI so it stays visible inside the viewport.
final Offset uiOffset;
- /// Determines how OCR gestures should behave while the image is zoomed.
- final ZoomedInteractionPolicy zoomedInteractionPolicy;
-
const TextOverlayWidget({
super.key,
- this.imageFile,
+ required this.imageSize,
required this.textBlocks,
- this.onTextBlocksSelected,
+ required this.controller,
+ required this.isImageZoomed,
+ required this.uiScale,
+ required this.uiOffset,
this.onTextCopied,
- this.onSelectionStart,
- this.showUnselectedBoundaries = true,
- this.enableSelectionPreview = false,
- this.debugMode = false,
- this.controller,
- this.isImageZoomed = false,
- this.onDoubleTapWhenZoomed,
- this.imageSize,
- this.uiScale = 1.0,
- this.uiOffset = Offset.zero,
- this.zoomedInteractionPolicy = ZoomedInteractionPolicy.panFirst,
- }) : assert(
- imageFile != null || imageSize != null,
- 'Either imageFile or imageSize must be provided',
- );
+ });
@override
State<TextOverlayWidget> createState() => _TextOverlayWidgetState();
@@ -189,10 +125,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
);
final GlobalKey _interactiveViewerKey = GlobalKey();
- final TransformationController _transformController =
- TransformationController();
- Size? _imageSize;
Size? _displaySize;
Offset? _displayOffset;
BoxConstraints? _lastConstraints;
@@ -201,16 +134,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
final Map<int, _BlockVisual> _blockVisuals = <int, _BlockVisual>{};
final List<int> _blockOrder = <int>[];
- bool get _hasSelectableText {
- for (final index in _blockOrder) {
- final visual = _blockVisuals[index];
- if (visual != null && visual.characterCount > 0) {
- return true;
- }
- }
- return false;
- }
-
bool get _hasActiveSelection => _activeSelections.isNotEmpty;
bool get _isEntireTextSelected {
var selectableBlockCount = 0;
@@ -230,229 +153,39 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
return selectableBlockCount > 0;
}
- bool get _isPanFirstWhileZoomed =>
- widget.isImageZoomed &&
- widget.zoomedInteractionPolicy == ZoomedInteractionPolicy.panFirst;
+ bool get _isPanFirstWhileZoomed => widget.isImageZoomed;
Map<int, TextSelection> _activeSelections = <int, TextSelection>{};
_SelectionAnchor? _baseAnchor;
_SelectionAnchor? _extentAnchor;
bool _isSelecting = false;
int _activePointerCount = 0;
- bool _isPanEnabled = false;
int? _selectionPointerId;
Offset? _selectionPointerDownScenePoint;
bool _selectionDragArmed = false;
bool _selectionDragInProgress = false;
- String _selectedTextPreview = '';
- Offset? _pendingDoubleTapScenePoint;
_HandleType? _activeHandle;
Offset? _activeHandleTouchOffset;
@override
void initState() {
super.initState();
- widget.controller?._attach(this);
- _loadImageDimensions();
- }
-
- @override
- void didUpdateWidget(covariant TextOverlayWidget oldWidget) {
- super.didUpdateWidget(oldWidget);
- if (oldWidget.controller != widget.controller) {
- oldWidget.controller?._detach(this);
- widget.controller?._attach(this);
- }
-
- final bool imageChanged = _isOverlayOnly
- ? widget.imageSize != oldWidget.imageSize
- : widget.imageFile?.path != oldWidget.imageFile?.path;
- if (imageChanged) {
- _resetForNewImage();
- return;
- }
-
- if (!identical(oldWidget.textBlocks, widget.textBlocks)) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted) return;
- setState(() {
- _computeBlockVisuals();
- });
- });
- }
-
- if (!oldWidget.enableSelectionPreview && widget.enableSelectionPreview) {
- if (_activeSelections.isNotEmpty) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted) return;
- setState(() {
- _updateSelectionPreview();
- });
- });
- }
- } else if (oldWidget.enableSelectionPreview &&
- !widget.enableSelectionPreview) {
- if (_selectedTextPreview.isNotEmpty) {
- setState(() {
- _selectedTextPreview = '';
- });
- }
- }
- }
-
- bool get _isOverlayOnly => widget.imageFile == null;
-
- Future<void> _loadImageDimensions() async {
- if (widget.imageSize != null) {
- if (!mounted) return;
- setState(() {
- _imageSize = widget.imageSize;
- });
- return;
- }
-
- final imageFile = widget.imageFile;
- if (imageFile == null) return;
-
- final bytes = await imageFile.readAsBytes();
- final codec = await ui.instantiateImageCodec(bytes);
- final frame = await codec.getNextFrame();
- final image = frame.image;
-
- if (!mounted) {
- return;
- }
-
- setState(() {
- _imageSize = Size(image.width.toDouble(), image.height.toDouble());
- });
- }
-
- void _resetForNewImage() {
- setState(() {
- _imageSize = null;
- _displaySize = null;
- _displayOffset = null;
- _lastConstraints = null;
- _metricsUpdateScheduled = false;
- _queuedMetrics = null;
- _blockVisuals.clear();
- _blockOrder.clear();
- _activeSelections = <int, TextSelection>{};
- _baseAnchor = null;
- _extentAnchor = null;
- _isSelecting = false;
- _selectedTextPreview = '';
- _pendingDoubleTapScenePoint = null;
- _activeHandle = null;
- _activeHandleTouchOffset = null;
- _activePointerCount = 0;
- _isPanEnabled = false;
- _selectionPointerId = null;
- _selectionPointerDownScenePoint = null;
- _selectionDragArmed = false;
- _selectionDragInProgress = false;
- });
- _loadImageDimensions();
+ widget.controller._attach(this);
}
@override
void dispose() {
- widget.controller?._detach(this);
- _transformController.dispose();
+ widget.controller._detach(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
- return Stack(
- clipBehavior: Clip.none,
- fit: StackFit.expand,
- children: [
- _buildInteractiveImage(),
- if (widget.enableSelectionPreview && _selectedTextPreview.isNotEmpty)
- _buildSelectionPreview(),
- ],
- );
- }
-
- Widget _buildInteractiveImage() {
- if (_isOverlayOnly) {
- return _buildOverlayOnlyImage();
- }
- return LayoutBuilder(
- builder: (context, constraints) {
- _scheduleMetricsRebuild(constraints);
- final Widget? copyButton = _buildCopyHandleButton(constraints);
-
- final Widget interactiveChild = InteractiveViewer(
- key: _interactiveViewerKey,
- transformationController: _transformController,
- minScale: 0.5,
- maxScale: 4.0,
- panEnabled: _isPanEnabled,
- scaleEnabled: true,
- child: Stack(
- clipBehavior: Clip.none,
- children: [
- Center(
- child: Image.file(
- widget.imageFile!,
- fit: BoxFit.contain,
- gaplessPlayback: true,
- frameBuilder:
- (context, child, frame, wasSynchronouslyLoaded) {
- if (frame != null) {
- _scheduleMetricsRebuild(constraints);
- }
- if (wasSynchronouslyLoaded) {
- return child;
- }
- return AnimatedOpacity(
- opacity: frame == null ? 0 : 1,
- duration: const Duration(milliseconds: 200),
- curve: Curves.easeOut,
- child: child,
- );
- },
- ),
- ),
- ..._buildEditableBlockOverlays(),
- ..._buildSelectionHandles(),
- if (copyButton != null) copyButton,
- ],
- ),
- );
-
- return Listener(
- onPointerDown: _handlePointerDown,
- onPointerMove: _handlePointerMove,
- onPointerUp: _handlePointerUp,
- onPointerCancel: _handlePointerCancel,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTapDown: _handleTapDown,
- onDoubleTapDown: _handleDoubleTapDown,
- onDoubleTap: _handleDoubleTap,
- onLongPressStart: (details) {
- if (_activePointerCount > 1) return;
- _onLongPressStart(details);
- },
- child: interactiveChild,
- ),
- );
- },
- );
+ return _buildOverlay();
}
- /// Overlay-only mode: renders text boundaries and handles without any
- /// image, and crucially without intercepting gestures. The entire visual
- /// layer is wrapped in [IgnorePointer] so swipes/taps pass through to
- /// the underlying PageView / PhotoView. A [_TextRegionHitTestBox] sits
- /// on top and only reports hits when the touch lands on a text region,
- /// allowing long-press-to-select without blocking navigation.
- Widget _buildOverlayOnlyImage() {
+ Widget _buildOverlay() {
return LayoutBuilder(
builder: (context, constraints) {
_scheduleMetricsRebuild(constraints);
@@ -521,7 +254,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
visualLayer,
gestureLayer,
..._buildSelectionHandles(),
- if (copyButton != null) copyButton,
+ ?copyButton,
],
);
},
@@ -534,8 +267,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
if (renderBox == null || !renderBox.hasSize) {
return null;
}
- final local = renderBox.globalToLocal(globalPoint);
- return _transformController.toScene(local);
+ return renderBox.globalToLocal(globalPoint);
}
void _setActivePointerCount(int newCount) {
@@ -546,20 +278,13 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_activePointerCount = clamped;
- final bool shouldEnablePan = _activePointerCount > 1;
- if (shouldEnablePan != _isPanEnabled) {
- setState(() {
- _isPanEnabled = shouldEnablePan;
- });
- }
-
if (_activePointerCount > 1) {
_cancelPointerDrivenSelection();
}
}
bool _isPrimaryPointer(PointerDownEvent event) {
- if (event.kind == ui.PointerDeviceKind.mouse) {
+ if (event.kind == PointerDeviceKind.mouse) {
return event.buttons == kPrimaryMouseButton;
}
return true;
@@ -685,7 +410,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
}
final _SelectionAnchor anchor = _anchorForPoint(blockIndex, scenePoint);
- widget.onSelectionStart?.call();
setState(() {
_isSelecting = true;
_baseAnchor = anchor;
@@ -721,18 +445,12 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
return;
}
- setState(() {
- _isSelecting = false;
- if (_activeSelections.isEmpty) {
- _selectedTextPreview = '';
- }
- });
+ setState(() => _isSelecting = false);
if (_activeSelections.isNotEmpty) {
if (!cancelled) {
HapticFeedback.lightImpact();
}
- _notifySelection();
} else {
_baseAnchor = null;
_extentAnchor = null;
@@ -740,10 +458,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
}
void _scheduleMetricsRebuild(BoxConstraints constraints) {
- if (_imageSize == null) {
- return;
- }
-
if (_lastConstraints != null &&
(_lastConstraints!.maxWidth - constraints.maxWidth).abs() < 0.5 &&
(_lastConstraints!.maxHeight - constraints.maxHeight).abs() < 0.5) {
@@ -783,7 +497,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
}
_DisplayMetrics _calculateMetrics(BoxConstraints constraints) {
- final double imageAspect = _imageSize!.width / _imageSize!.height;
+ final double imageAspect = widget.imageSize.width / widget.imageSize.height;
final double containerAspect = constraints.maxWidth / constraints.maxHeight;
double displayWidth;
@@ -812,7 +526,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_displayOffset = metrics.offset;
_computeBlockVisuals();
});
- widget.controller?._consumePendingSelection();
+ widget.controller._consumePendingSelection();
}
double get _effectiveUiScale =>
@@ -985,13 +699,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_isScenePointOnInteractiveSelectionUi(scenePoint);
}
- bool _shouldClearSelectionAtScenePoint(Offset scenePoint) {
- if (_activeSelections.isEmpty) {
- return false;
- }
- return !_isScenePointOnInteractiveSelectionUi(scenePoint);
- }
-
bool _isPositionOnGestureLayer(Offset globalPosition) {
final Offset? scenePoint = _sceneFromGlobal(globalPosition);
if (scenePoint == null) {
@@ -1029,7 +736,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
}
List<Widget> _buildEditableBlockOverlays() {
- if (_displaySize == null || _imageSize == null || _displayOffset == null) {
+ if (_displaySize == null || _displayOffset == null) {
return const [];
}
@@ -1052,7 +759,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
painter: _EditableBlockPainter(
visual: visual,
selection: _activeSelections[index],
- showBoundary: widget.showUnselectedBoundaries,
selectionColor: selectionColor,
),
),
@@ -1150,14 +856,12 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
context,
);
- // Use explicit white color for button text
const TextStyle buttonTextStyle = TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w500,
);
- // Custom toolbar with explicit black background
final Widget toolbar = Container(
decoration: BoxDecoration(
color: Colors.black,
@@ -1395,7 +1099,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
final List<_CharacterVisual> characters = visual.characters;
final int clamped = _clampIndex(index, 0, characters.length - 1);
- Rect candidate = characters[clamped].bounds;
+ final Rect candidate = characters[clamped].bounds;
if (_isRenderableRect(candidate)) {
return candidate;
}
@@ -1444,7 +1148,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
? anchorPoint - fingerScene
: null;
- widget.onSelectionStart?.call();
setState(() {
_activeHandle = type;
_isSelecting = true;
@@ -1511,14 +1214,10 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_isSelecting = false;
_activeHandle = null;
_activeHandleTouchOffset = null;
- if (_activeSelections.isEmpty) {
- _selectedTextPreview = '';
- }
});
if (_activeSelections.isNotEmpty) {
HapticFeedback.lightImpact();
- _notifySelection();
} else {
_baseAnchor = null;
_extentAnchor = null;
@@ -1534,55 +1233,14 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_isSelecting = false;
_activeHandle = null;
_activeHandleTouchOffset = null;
- if (_activeSelections.isEmpty) {
- _selectedTextPreview = '';
- }
});
- if (_activeSelections.isNotEmpty) {
- _notifySelection();
- } else {
+ if (_activeSelections.isEmpty) {
_baseAnchor = null;
_extentAnchor = null;
}
}
- Widget _buildSelectionPreview() {
- final mediaQuery = MediaQuery.of(context);
- return Positioned(
- top: mediaQuery.padding.top + 16,
- left: 16,
- right: 16,
- child: IgnorePointer(
- ignoring: true,
- child: AnimatedOpacity(
- opacity: _selectedTextPreview.isEmpty ? 0 : 1,
- duration: const Duration(milliseconds: 120),
- curve: Curves.easeOut,
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
- decoration: BoxDecoration(
- color: Colors.black.withValues(alpha: 0.7),
- borderRadius: BorderRadius.circular(18),
- ),
- child: Text(
- _selectedTextPreview,
- maxLines: 3,
- overflow: TextOverflow.ellipsis,
- textAlign: TextAlign.center,
- style: const TextStyle(
- color: Colors.white,
- fontSize: 13,
- fontWeight: FontWeight.w500,
- height: 1.3,
- ),
- ),
- ),
- ),
- ),
- );
- }
-
void _onLongPressStart(LongPressStartDetails details) {
final scenePoint = _sceneFromGlobal(details.globalPosition);
if (scenePoint == null) {
@@ -1594,8 +1252,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
return;
}
- widget.onSelectionStart?.call();
-
final bool wordSelected = _performWordSelection(
blockIndex,
scenePoint,
@@ -1621,51 +1277,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
HapticFeedback.mediumImpact();
}
- void _handleTapDown(TapDownDetails details) {
- final scenePoint = _sceneFromGlobal(details.globalPosition);
- if (scenePoint == null) {
- return;
- }
-
- if (_activeSelections.isNotEmpty &&
- _isScenePointOnInteractiveSelectionUi(scenePoint)) {
- return;
- }
-
- if (_shouldClearSelectionAtScenePoint(scenePoint)) {
- _clearSelection();
- }
- }
-
- void _handleDoubleTapDown(TapDownDetails details) {
- _pendingDoubleTapScenePoint = _sceneFromGlobal(details.globalPosition);
- }
-
- void _handleDoubleTap() {
- final Offset? point = _pendingDoubleTapScenePoint;
- _pendingDoubleTapScenePoint = null;
-
- if (widget.isImageZoomed && widget.onDoubleTapWhenZoomed != null) {
- widget.onDoubleTapWhenZoomed!.call();
- return;
- }
-
- if (point == null) {
- return;
- }
-
- final int? blockIndex = _hitTestBlock(point);
- if (blockIndex == null) {
- if (_shouldClearSelectionAtScenePoint(point)) {
- _clearSelection();
- }
- return;
- }
-
- widget.onSelectionStart?.call();
- _performWordSelection(blockIndex, point);
- }
-
bool _performWordSelection(
int blockIndex,
Offset scenePoint, {
@@ -1705,7 +1316,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
if (_activeSelections.isNotEmpty) {
if (finalizeSelection) {
HapticFeedback.selectionClick();
- _notifySelection();
}
return true;
}
@@ -1868,7 +1478,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_clampAnchorsToVisuals();
_normalizeAnchors();
_activeSelections = _computeSelections(_baseAnchor, _extentAnchor);
- _updateSelectionPreview();
}
void _normalizeAnchors() {
@@ -1904,7 +1513,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_blockVisuals.clear();
_blockOrder.clear();
- if (_displaySize == null || _imageSize == null || _displayOffset == null) {
+ if (_displaySize == null || _displayOffset == null) {
return;
}
@@ -1941,7 +1550,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
index: index,
block: block,
scaledPolygon: scaledPoints,
- localPolygon: localPolygon,
bounds: bounds,
characters: characters,
geometry: geometry,
@@ -2149,12 +1757,12 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
}
List<Offset> _getScaledCharacterPoints(CharacterBox character) {
- if (_displaySize == null || _imageSize == null || _displayOffset == null) {
+ if (_displaySize == null || _displayOffset == null) {
return const [];
}
- final double scaleX = _displaySize!.width / _imageSize!.width;
- final double scaleY = _displaySize!.height / _imageSize!.height;
+ final double scaleX = _displaySize!.width / widget.imageSize.width;
+ final double scaleY = _displaySize!.height / widget.imageSize.height;
return character.points
.map(
@@ -2296,7 +1904,7 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
}
Clipboard.setData(ClipboardData(text: text));
- widget.onTextCopied?.call(text);
+ widget.onTextCopied?.call();
HapticFeedback.mediumImpact();
Future.delayed(const Duration(milliseconds: 500), () {
@@ -2344,11 +1952,9 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_isSelecting = false;
_activeHandle = null;
_activeHandleTouchOffset = null;
- _updateSelectionPreview();
});
HapticFeedback.selectionClick();
- _notifySelection();
return true;
}
@@ -2364,7 +1970,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
if (blockIndex == null) {
return false;
}
- widget.onSelectionStart?.call();
final bool selected = _performWordSelection(blockIndex, scenePoint);
return selected;
}
@@ -2376,8 +1981,6 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
_baseAnchor = null;
_extentAnchor = null;
_isSelecting = false;
- _selectedTextPreview = '';
- _pendingDoubleTapScenePoint = null;
_activeHandle = null;
_activeHandleTouchOffset = null;
});
@@ -2428,52 +2031,13 @@ class _TextOverlayWidgetState extends State<TextOverlayWidget> {
return buffer.toString();
}
- String _selectionPreviewText() {
- final raw = _collectSelectionText().trim();
- if (raw.isEmpty) {
- return '';
- }
- const int maxLength = 160;
- if (raw.length <= maxLength) {
- return raw;
- }
- return '${raw.substring(0, maxLength - 1).trimRight()}…';
- }
-
- void _updateSelectionPreview() {
- if (!widget.enableSelectionPreview) {
- if (_selectedTextPreview.isNotEmpty) {
- _selectedTextPreview = '';
- }
- return;
- }
- _selectedTextPreview = _selectionPreviewText();
- }
-
- void _notifySelection() {
- if (widget.onTextBlocksSelected == null) {
- return;
- }
-
- final selectedBlocks = _blockOrder
- .where((index) => _activeSelections.containsKey(index))
- .map((index) => widget.textBlocks[index])
- .toList();
-
- if (selectedBlocks.isEmpty) {
- return;
- }
-
- widget.onTextBlocksSelected!(selectedBlocks);
- }
-
List<Offset> _getScaledPoints(TextBlock block) {
- if (_displaySize == null || _imageSize == null || _displayOffset == null) {
+ if (_displaySize == null || _displayOffset == null) {
return const [];
}
- final double scaleX = _displaySize!.width / _imageSize!.width;
- final double scaleY = _displaySize!.height / _imageSize!.height;
+ final double scaleX = _displaySize!.width / widget.imageSize.width;
+ final double scaleY = _displaySize!.height / widget.imageSize.height;
return block.points
.map(
@@ -2715,7 +2279,6 @@ class _BlockVisual {
required this.index,
required this.block,
required this.scaledPolygon,
- required this.localPolygon,
required this.bounds,
required this.characters,
required this.geometry,
@@ -2724,7 +2287,6 @@ class _BlockVisual {
final int index;
final TextBlock block;
final List<Offset> scaledPolygon;
- final List<Offset> localPolygon;
final Rect bounds;
final List<_CharacterVisual> characters;
final _OrientedGeometry geometry;
@@ -2749,27 +2311,16 @@ class _ToolbarLayout {
class _EditableBlockPainter extends CustomPainter {
const _EditableBlockPainter({
required this.visual,
- required this.showBoundary,
required this.selectionColor,
this.selection,
});
final _BlockVisual visual;
- final bool showBoundary;
final Color selectionColor;
final TextSelection? selection;
@override
void paint(Canvas canvas, Size size) {
- if (showBoundary && visual.localPolygon.length >= 3) {
- final boundaryPaint = Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 0.9
- ..color = Colors.white.withValues(alpha: 0.18);
- final boundaryPath = Path()..addPolygon(visual.localPolygon, true);
- canvas.drawPath(boundaryPath, boundaryPaint);
- }
-
if (selection != null && !selection!.isCollapsed) {
final start = selection!.start.clamp(0, visual.characterCount);
final end = selection!.end.clamp(start, visual.characterCount);
@@ -2829,7 +2380,10 @@ class _EditableBlockPainter extends CustomPainter {
final Path path = Path();
for (final rect in merged) {
path.addRRect(
- RRect.fromRectAndRadius(rect, Radius.circular(_kHighlightCornerRadius)),
+ RRect.fromRectAndRadius(
+ rect,
+ const Radius.circular(_kHighlightCornerRadius),
+ ),
);
}
@@ -2857,7 +2411,7 @@ class _EditableBlockPainter extends CustomPainter {
.map(
(rect) => RRect.fromRectAndRadius(
rect,
- Radius.circular(_kHighlightCornerRadius),
+ const Radius.circular(_kHighlightCornerRadius),
),
)
.toList(growable: false);
@@ -2931,9 +2485,7 @@ class _EditableBlockPainter extends CustomPainter {
@override
bool shouldRepaint(covariant _EditableBlockPainter oldDelegate) {
- return oldDelegate.visual != visual ||
- oldDelegate.selection != selection ||
- oldDelegate.showBoundary != showBoundary;
+ return oldDelegate.visual != visual || oldDelegate.selection != selection;
}
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart
index e044bdd603..5f33be2d53 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_reading_order.dart
@@ -70,12 +70,7 @@ List<int> orderTextBlocksForReading(Iterable<TextReadingOrderBlock> source) {
double bandTop = double.negativeInfinity;
for (final separator in spanning) {
final boundary = separator.bounds.center.dy;
- _appendColumnBand(
- result,
- columns,
- bandTop: bandTop,
- bandBottom: boundary,
- );
+ _appendColumnBand(result, columns, bandTop: bandTop, bandBottom: boundary);
result.add(separator.index);
bandTop = boundary;
}