selectable_text.dart 25.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle;

7 8 9
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
10
import 'package:flutter/rendering.dart';
11

12
import 'desktop_text_selection.dart';
13 14
import 'feedback.dart';
import 'text_selection.dart';
15
import 'text_selection_theme.dart';
16 17 18 19 20 21 22 23 24 25 26
import 'theme.dart';

/// An eyeballed value that moves the cursor slightly left of where it is
/// rendered for text on Android so its positioning more accurately matches the
/// native iOS text cursor positioning.
///
/// This value is in device pixels, not logical pixels as is typically used
/// throughout the codebase.
const int iOSHorizontalOffset = -2;

class _TextSpanEditingController extends TextEditingController {
27
  _TextSpanEditingController({required TextSpan textSpan}):
28 29
    assert(textSpan != null),
    _textSpan = textSpan,
30
    super(text: textSpan.toPlainText(includeSemanticsLabels: false));
31 32 33 34

  final TextSpan _textSpan;

  @override
35
  TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) {
36
    // This does not care about composing.
37 38 39 40 41 42 43
    return TextSpan(
      style: style,
      children: <TextSpan>[_textSpan],
    );
  }

  @override
44
  set text(String? newText) {
45 46
    // This should never be reached.
    throw UnimplementedError();
47 48 49 50 51
  }
}

class _SelectableTextSelectionGestureDetectorBuilder extends TextSelectionGestureDetectorBuilder {
  _SelectableTextSelectionGestureDetectorBuilder({
52
    required _SelectableTextState state,
53
  }) : _state = state,
54
       super(delegate: state);
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

  final _SelectableTextState _state;

  @override
  void onForcePressStart(ForcePressDetails details) {
    super.onForcePressStart(details);
    if (delegate.selectionEnabled && shouldShowSelectionToolbar) {
      editableText.showToolbar();
    }
  }

  @override
  void onForcePressEnd(ForcePressDetails details) {
    // Not required.
  }

  @override
  void onSingleLongTapMoveUpdate(LongPressMoveUpdateDetails details) {
    if (delegate.selectionEnabled) {
74 75 76 77 78
      renderEditable.selectWordsInRange(
        from: details.globalPosition - details.offsetFromOrigin,
        to: details.globalPosition,
        cause: SelectionChangedCause.longPress,
      );
79 80 81 82 83 84 85
    }
  }

  @override
  void onSingleTapUp(TapUpDetails details) {
    editableText.hideToolbar();
    if (delegate.selectionEnabled) {
86
      switch (Theme.of(_state.context).platform) {
87
        case TargetPlatform.iOS:
88
        case TargetPlatform.macOS:
89 90 91 92
          renderEditable.selectWordEdge(cause: SelectionChangedCause.tap);
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
93 94
        case TargetPlatform.linux:
        case TargetPlatform.windows:
95 96 97 98
          renderEditable.selectPosition(cause: SelectionChangedCause.tap);
          break;
      }
    }
99
    _state.widget.onTap?.call();
100 101 102 103 104
  }

  @override
  void onSingleLongTapStart(LongPressStartDetails details) {
    if (delegate.selectionEnabled) {
105 106
      renderEditable.selectWord(cause: SelectionChangedCause.longPress);
      Feedback.forLongPress(_state.context);
107 108 109 110 111 112 113 114 115 116
    }
  }
}

/// A run of selectable text with a single style.
///
/// The [SelectableText] widget displays a string of text with a single style.
/// The string might break across multiple lines or might all be displayed on
/// the same line depending on the layout constraints.
///
117 118
/// {@youtube 560 315 https://www.youtube.com/watch?v=ZSU3ZXOs6hc}
///
119 120 121 122 123 124 125
/// The [style] argument is optional. When omitted, the text will use the style
/// from the closest enclosing [DefaultTextStyle]. If the given style's
/// [TextStyle.inherit] property is true (the default), the given style will
/// be merged with the closest enclosing [DefaultTextStyle]. This merging
/// behavior is useful, for example, to make the text bold while using the
/// default font family and size.
///
126 127
/// {@macro flutter.material.textfield.wantKeepAlive}
///
128
/// {@tool snippet}
129 130
///
/// ```dart
131
/// const SelectableText(
132 133 134 135 136 137 138 139 140 141 142 143
///   'Hello! How are you?',
///   textAlign: TextAlign.center,
///   style: TextStyle(fontWeight: FontWeight.bold),
/// )
/// ```
/// {@end-tool}
///
/// Using the [SelectableText.rich] constructor, the [SelectableText] widget can
/// display a paragraph with differently styled [TextSpan]s. The sample
/// that follows displays "Hello beautiful world" with different styles
/// for each word.
///
144
/// {@tool snippet}
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
///
/// ```dart
/// const SelectableText.rich(
///   TextSpan(
///     text: 'Hello', // default text style
///     children: <TextSpan>[
///       TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic)),
///       TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold)),
///     ],
///   ),
/// )
/// ```
/// {@end-tool}
///
/// ## Interactivity
///
/// To make [SelectableText] react to touch events, use callback [onTap] to achieve
/// the desired behavior.
///
/// See also:
///
///  * [Text], which is the non selectable version of this widget.
///  * [TextField], which is the editable version of this widget.
class SelectableText extends StatefulWidget {
  /// Creates a selectable text widget.
  ///
  /// If the [style] argument is null, the text will use the style from the
  /// closest enclosing [DefaultTextStyle].
  ///
174

175 176 177
  /// The [showCursor], [autofocus], [dragStartBehavior], [selectionHeightStyle],
  /// [selectionWidthStyle] and [data] parameters must not be null. If specified,
  /// the [maxLines] argument must be greater than zero.
178
  const SelectableText(
179
    String this.data, {
180
    Key? key,
181 182 183 184 185
    this.focusNode,
    this.style,
    this.strutStyle,
    this.textAlign,
    this.textDirection,
186
    this.textScaleFactor,
187 188
    this.showCursor = false,
    this.autofocus = false,
189
    ToolbarOptions? toolbarOptions,
190
    this.minLines,
191 192
    this.maxLines,
    this.cursorWidth = 2.0,
193
    this.cursorHeight,
194 195
    this.cursorRadius,
    this.cursorColor,
196 197
    this.selectionHeightStyle = ui.BoxHeightStyle.tight,
    this.selectionWidthStyle = ui.BoxWidthStyle.tight,
198 199
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection = true,
200
    this.selectionControls,
201 202
    this.onTap,
    this.scrollPhysics,
203
    this.semanticsLabel,
204
    this.textHeightBehavior,
205
    this.textWidthBasis,
206
    this.onSelectionChanged,
207 208 209
  }) :  assert(showCursor != null),
        assert(autofocus != null),
        assert(dragStartBehavior != null),
210 211
        assert(selectionHeightStyle != null),
        assert(selectionWidthStyle != null),
212
        assert(maxLines == null || maxLines > 0),
213 214 215
        assert(minLines == null || minLines > 0),
        assert(
          (maxLines == null) || (minLines == null) || (maxLines >= minLines),
216
          "minLines can't be greater than maxLines",
217
        ),
218 219 220 221 222
        assert(
          data != null,
          'A non-null String must be provided to a SelectableText widget.',
        ),
        textSpan = null,
223 224 225 226 227
        toolbarOptions = toolbarOptions ??
          const ToolbarOptions(
            selectAll: true,
            copy: true,
          ),
228 229 230 231 232
        super(key: key);

  /// Creates a selectable text widget with a [TextSpan].
  ///
  /// The [textSpan] parameter must not be null and only contain [TextSpan] in
233
  /// [textSpan].children. Other type of [InlineSpan] is not allowed.
234 235
  ///
  /// The [autofocus] and [dragStartBehavior] arguments must not be null.
236
  const SelectableText.rich(
237
    TextSpan this.textSpan, {
238
    Key? key,
239 240 241 242 243
    this.focusNode,
    this.style,
    this.strutStyle,
    this.textAlign,
    this.textDirection,
244
    this.textScaleFactor,
245 246
    this.showCursor = false,
    this.autofocus = false,
247
    ToolbarOptions? toolbarOptions,
248
    this.minLines,
249 250
    this.maxLines,
    this.cursorWidth = 2.0,
251
    this.cursorHeight,
252 253
    this.cursorRadius,
    this.cursorColor,
254 255
    this.selectionHeightStyle = ui.BoxHeightStyle.tight,
    this.selectionWidthStyle = ui.BoxWidthStyle.tight,
256 257
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection = true,
258
    this.selectionControls,
259 260
    this.onTap,
    this.scrollPhysics,
261
    this.semanticsLabel,
262
    this.textHeightBehavior,
263
    this.textWidthBasis,
264
    this.onSelectionChanged,
265 266 267 268
  }) :  assert(showCursor != null),
    assert(autofocus != null),
    assert(dragStartBehavior != null),
    assert(maxLines == null || maxLines > 0),
269 270 271
    assert(minLines == null || minLines > 0),
    assert(
      (maxLines == null) || (minLines == null) || (maxLines >= minLines),
272
      "minLines can't be greater than maxLines",
273
    ),
274 275 276 277 278
    assert(
      textSpan != null,
      'A non-null TextSpan must be provided to a SelectableText.rich widget.',
    ),
    data = null,
279 280 281 282 283
    toolbarOptions = toolbarOptions ??
      const ToolbarOptions(
        selectAll: true,
        copy: true,
      ),
284 285 286 287 288
    super(key: key);

  /// The text to display.
  ///
  /// This will be null if a [textSpan] is provided instead.
289
  final String? data;
290 291 292 293

  /// The text to display as a [TextSpan].
  ///
  /// This will be null if [data] is provided instead.
294
  final TextSpan? textSpan;
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318

  /// Defines the focus for this widget.
  ///
  /// Text is only selectable when widget is focused.
  ///
  /// The [focusNode] is a long-lived object that's typically managed by a
  /// [StatefulWidget] parent. See [FocusNode] for more information.
  ///
  /// To give the focus to this widget, provide a [focusNode] and then
  /// use the current [FocusScope] to request the focus:
  ///
  /// ```dart
  /// FocusScope.of(context).requestFocus(myFocusNode);
  /// ```
  ///
  /// This happens automatically when the widget is tapped.
  ///
  /// To be notified when the widget gains or loses the focus, add a listener
  /// to the [focusNode]:
  ///
  /// ```dart
  /// focusNode.addListener(() { print(myFocusNode.hasFocus); });
  /// ```
  ///
319 320 321
  /// If null, this widget will create its own [FocusNode] with
  /// [FocusNode.skipTraversal] parameter set to `true`, which causes the widget
  /// to be skipped over during focus traversal.
322
  final FocusNode? focusNode;
323 324 325 326

  /// The style to use for the text.
  ///
  /// If null, defaults [DefaultTextStyle] of context.
327
  final TextStyle? style;
328 329

  /// {@macro flutter.widgets.editableText.strutStyle}
330
  final StrutStyle? strutStyle;
331 332

  /// {@macro flutter.widgets.editableText.textAlign}
333
  final TextAlign? textAlign;
334 335

  /// {@macro flutter.widgets.editableText.textDirection}
336
  final TextDirection? textDirection;
337

338
  /// {@macro flutter.widgets.editableText.textScaleFactor}
339
  final double? textScaleFactor;
340

341 342 343
  /// {@macro flutter.widgets.editableText.autofocus}
  final bool autofocus;

344
  /// {@macro flutter.widgets.editableText.minLines}
345
  final int? minLines;
346

347
  /// {@macro flutter.widgets.editableText.maxLines}
348
  final int? maxLines;
349 350 351 352 353 354 355

  /// {@macro flutter.widgets.editableText.showCursor}
  final bool showCursor;

  /// {@macro flutter.widgets.editableText.cursorWidth}
  final double cursorWidth;

356
  /// {@macro flutter.widgets.editableText.cursorHeight}
357
  final double? cursorHeight;
358

359
  /// {@macro flutter.widgets.editableText.cursorRadius}
360
  final Radius? cursorRadius;
361 362 363 364

  /// The color to use when painting the cursor.
  ///
  /// Defaults to the theme's `cursorColor` when null.
365
  final Color? cursorColor;
366

367 368 369 370 371 372 373 374 375 376
  /// Controls how tall the selection highlight boxes are computed to be.
  ///
  /// See [ui.BoxHeightStyle] for details on available styles.
  final ui.BoxHeightStyle selectionHeightStyle;

  /// Controls how wide the selection highlight boxes are computed to be.
  ///
  /// See [ui.BoxWidthStyle] for details on available styles.
  final ui.BoxWidthStyle selectionWidthStyle;

377 378 379
  /// {@macro flutter.widgets.editableText.enableInteractiveSelection}
  final bool enableInteractiveSelection;

380 381 382
  /// {@macro flutter.widgets.editableText.selectionControls}
  final TextSelectionControls? selectionControls;

383 384 385
  /// {@macro flutter.widgets.scrollable.dragStartBehavior}
  final DragStartBehavior dragStartBehavior;

386 387 388 389 390 391 392
  /// Configuration of toolbar options.
  ///
  /// Paste and cut will be disabled regardless.
  ///
  /// If not set, select all and copy will be enabled by default.
  final ToolbarOptions toolbarOptions;

393 394
  /// {@macro flutter.widgets.editableText.selectionEnabled}
  bool get selectionEnabled => enableInteractiveSelection;
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

  /// Called when the user taps on this selectable text.
  ///
  /// The selectable text builds a [GestureDetector] to handle input events like tap,
  /// to trigger focus requests, to move the caret, adjust the selection, etc.
  /// Handling some of those events by wrapping the selectable text with a competing
  /// GestureDetector is problematic.
  ///
  /// To unconditionally handle taps, without interfering with the selectable text's
  /// internal gesture detector, provide this callback.
  ///
  /// To be notified when the text field gains or loses the focus, provide a
  /// [focusNode] and add a listener to that.
  ///
  /// To listen to arbitrary pointer events without competing with the
  /// selectable text's internal gesture detector, use a [Listener].
411
  final GestureTapCallback? onTap;
412

Dan Field's avatar
Dan Field committed
413
  /// {@macro flutter.widgets.editableText.scrollPhysics}
414
  final ScrollPhysics? scrollPhysics;
415

416 417 418
  /// {@macro flutter.widgets.Text.semanticsLabel}
  final String? semanticsLabel;

419
  /// {@macro dart.ui.textHeightBehavior}
420
  final TextHeightBehavior? textHeightBehavior;
421

422
  /// {@macro flutter.painting.textPainter.textWidthBasis}
423
  final TextWidthBasis? textWidthBasis;
424

425
  /// {@macro flutter.widgets.editableText.onSelectionChanged}
426
  final SelectionChangedCallback? onSelectionChanged;
427

428
  @override
429
  State<SelectableText> createState() => _SelectableTextState();
430 431 432 433 434

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<String>('data', data, defaultValue: null));
435
    properties.add(DiagnosticsProperty<String>('semanticsLabel', semanticsLabel, defaultValue: null));
436 437 438 439
    properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
    properties.add(DiagnosticsProperty<TextStyle>('style', style, defaultValue: null));
    properties.add(DiagnosticsProperty<bool>('autofocus', autofocus, defaultValue: false));
    properties.add(DiagnosticsProperty<bool>('showCursor', showCursor, defaultValue: false));
440
    properties.add(IntProperty('minLines', minLines, defaultValue: null));
441 442 443
    properties.add(IntProperty('maxLines', maxLines, defaultValue: null));
    properties.add(EnumProperty<TextAlign>('textAlign', textAlign, defaultValue: null));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
444
    properties.add(DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: null));
445
    properties.add(DoubleProperty('cursorWidth', cursorWidth, defaultValue: 2.0));
446
    properties.add(DoubleProperty('cursorHeight', cursorHeight, defaultValue: null));
447 448 449
    properties.add(DiagnosticsProperty<Radius>('cursorRadius', cursorRadius, defaultValue: null));
    properties.add(DiagnosticsProperty<Color>('cursorColor', cursorColor, defaultValue: null));
    properties.add(FlagProperty('selectionEnabled', value: selectionEnabled, defaultValue: true, ifFalse: 'selection disabled'));
450
    properties.add(DiagnosticsProperty<TextSelectionControls>('selectionControls', selectionControls, defaultValue: null));
451
    properties.add(DiagnosticsProperty<ScrollPhysics>('scrollPhysics', scrollPhysics, defaultValue: null));
452
    properties.add(DiagnosticsProperty<TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
453 454 455
  }
}

456
class _SelectableTextState extends State<SelectableText> implements TextSelectionGestureDetectorBuilderDelegate {
457
  EditableTextState? get _editableText => editableTextKey.currentState;
458

459
  late _TextSpanEditingController _controller;
460

461
  FocusNode? _focusNode;
462 463
  FocusNode get _effectiveFocusNode =>
      widget.focusNode ?? (_focusNode ??= FocusNode(skipTraversal: true));
464 465 466

  bool _showSelectionHandles = false;

467
  late _SelectableTextSelectionGestureDetectorBuilder _selectionGestureDetectorBuilder;
468 469 470

  // API for TextSelectionGestureDetectorBuilderDelegate.
  @override
471
  late bool forcePressEnabled;
472 473 474 475 476 477 478 479 480 481 482 483 484

  @override
  final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();

  @override
  bool get selectionEnabled => widget.selectionEnabled;
  // End of API for TextSelectionGestureDetectorBuilderDelegate.

  @override
  void initState() {
    super.initState();
    _selectionGestureDetectorBuilder = _SelectableTextSelectionGestureDetectorBuilder(state: this);
    _controller = _TextSpanEditingController(
485
        textSpan: widget.textSpan ?? TextSpan(text: widget.data),
486
    );
487
    _controller.addListener(_onControllerChanged);
488 489 490 491 492 493
  }

  @override
  void didUpdateWidget(SelectableText oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.data != oldWidget.data || widget.textSpan != oldWidget.textSpan) {
494
      _controller.removeListener(_onControllerChanged);
495
      _controller = _TextSpanEditingController(
496
          textSpan: widget.textSpan ?? TextSpan(text: widget.data),
497
      );
498
      _controller.addListener(_onControllerChanged);
499 500
    }
    if (_effectiveFocusNode.hasFocus && _controller.selection.isCollapsed) {
501
      _showSelectionHandles = false;
502 503
    } else {
      _showSelectionHandles = true;
504 505 506 507 508 509
    }
  }

  @override
  void dispose() {
    _focusNode?.dispose();
510
    _controller.removeListener(_onControllerChanged);
511 512 513
    super.dispose();
  }

514 515 516 517 518 519 520 521 522 523 524
  void _onControllerChanged() {
    final bool showSelectionHandles = !_effectiveFocusNode.hasFocus
      || !_controller.selection.isCollapsed;
    if (showSelectionHandles == _showSelectionHandles) {
      return;
    }
    setState(() {
      _showSelectionHandles = showSelectionHandles;
    });
  }

525 526
  TextSelection? _lastSeenTextSelection;

527
  void _handleSelectionChanged(TextSelection selection, SelectionChangedCause? cause) {
528 529 530 531 532 533
    final bool willShowSelectionHandles = _shouldShowSelectionHandles(cause);
    if (willShowSelectionHandles != _showSelectionHandles) {
      setState(() {
        _showSelectionHandles = willShowSelectionHandles;
      });
    }
534 535 536
    // TODO(chunhtai): The selection may be the same. We should remove this
    // check once this is fixed https://github.com/flutter/flutter/issues/76349.
    if (widget.onSelectionChanged != null && _lastSeenTextSelection != selection) {
537
      widget.onSelectionChanged!(selection, cause);
538
    }
539
    _lastSeenTextSelection = selection;
540

541
    switch (Theme.of(context).platform) {
542
      case TargetPlatform.iOS:
543
      case TargetPlatform.macOS:
544 545 546 547 548 549
        if (cause == SelectionChangedCause.longPress) {
          _editableText?.bringIntoView(selection.base);
        }
        return;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
550 551
      case TargetPlatform.linux:
      case TargetPlatform.windows:
552 553 554 555 556 557 558
      // Do nothing.
    }
  }

  /// Toggle the toolbar when a selection handle is tapped.
  void _handleSelectionHandleTapped() {
    if (_controller.selection.isCollapsed) {
559
      _editableText!.toggleToolbar();
560 561 562
    }
  }

563
  bool _shouldShowSelectionHandles(SelectionChangedCause? cause) {
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    // When the text field is activated by something that doesn't trigger the
    // selection overlay, we shouldn't show the handles either.
    if (!_selectionGestureDetectorBuilder.shouldShowSelectionToolbar)
      return false;

    if (_controller.selection.isCollapsed)
      return false;

    if (cause == SelectionChangedCause.keyboard)
      return false;

    if (cause == SelectionChangedCause.longPress)
      return true;

    if (_controller.text.isNotEmpty)
      return true;

    return false;
  }

  @override
  Widget build(BuildContext context) {
586 587 588 589 590
    // TODO(garyq): Assert to block WidgetSpans from being used here are removed,
    // but we still do not yet have nice handling of things like carets, clipboard,
    // and other features. We should add proper support. Currently, caret handling
    // is blocked on SkParagraph switch and https://github.com/flutter/engine/pull/27010
    // should be landed in SkParagraph after the switch is complete.
591 592 593
    assert(debugCheckHasMediaQuery(context));
    assert(debugCheckHasDirectionality(context));
    assert(
594 595
      !(widget.style != null && widget.style!.inherit == false &&
          (widget.style!.fontSize == null || widget.style!.textBaseline == null)),
596 597 598
      'inherit false style must supply fontSize and textBaseline',
    );

599
    final ThemeData theme = Theme.of(context);
600
    final TextSelectionThemeData selectionTheme = TextSelectionTheme.of(context);
601 602
    final FocusNode focusNode = _effectiveFocusNode;

603
    TextSelectionControls? textSelectionControls =  widget.selectionControls;
604 605
    final bool paintCursorAboveText;
    final bool cursorOpacityAnimates;
606 607
    Offset? cursorOffset;
    Color? cursorColor = widget.cursorColor;
608
    final Color selectionColor;
609
    Radius? cursorRadius = widget.cursorRadius;
610

611
    switch (theme.platform) {
612
      case TargetPlatform.iOS:
613
        final CupertinoThemeData cupertinoTheme = CupertinoTheme.of(context);
614
        forcePressEnabled = true;
615
        textSelectionControls ??= cupertinoTextSelectionControls;
616 617
        paintCursorAboveText = true;
        cursorOpacityAnimates = true;
618 619
        cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;
        selectionColor = selectionTheme.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40);
620
        cursorRadius ??= const Radius.circular(2.0);
621 622 623 624 625 626 627 628 629 630 631 632
        cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.of(context).devicePixelRatio, 0);
        break;

      case TargetPlatform.macOS:
        final CupertinoThemeData cupertinoTheme = CupertinoTheme.of(context);
        forcePressEnabled = false;
        textSelectionControls ??= cupertinoDesktopTextSelectionControls;
        paintCursorAboveText = true;
        cursorOpacityAnimates = true;
        cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;
        selectionColor = selectionTheme.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40);
        cursorRadius ??= const Radius.circular(2.0);
633
        cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.of(context).devicePixelRatio, 0);
634 635 636 637
        break;

      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
638 639 640 641 642 643 644 645
        forcePressEnabled = false;
        textSelectionControls ??= materialTextSelectionControls;
        paintCursorAboveText = false;
        cursorOpacityAnimates = false;
        cursorColor ??= selectionTheme.cursorColor ?? theme.colorScheme.primary;
        selectionColor = selectionTheme.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40);
        break;

646 647
      case TargetPlatform.linux:
      case TargetPlatform.windows:
648
        forcePressEnabled = false;
649
        textSelectionControls ??= desktopTextSelectionControls;
650 651
        paintCursorAboveText = false;
        cursorOpacityAnimates = false;
652 653
        cursorColor ??= selectionTheme.cursorColor ?? theme.colorScheme.primary;
        selectionColor = selectionTheme.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40);
654 655 656 657
        break;
    }

    final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context);
658 659
    TextStyle? effectiveTextStyle = widget.style;
    if (effectiveTextStyle == null || effectiveTextStyle.inherit)
660 661 662 663 664 665 666 667 668
      effectiveTextStyle = defaultTextStyle.style.merge(widget.style);
    if (MediaQuery.boldTextOverride(context))
      effectiveTextStyle = effectiveTextStyle.merge(const TextStyle(fontWeight: FontWeight.bold));
    final Widget child = RepaintBoundary(
      child: EditableText(
        key: editableTextKey,
        style: effectiveTextStyle,
        readOnly: true,
        textWidthBasis: widget.textWidthBasis ?? defaultTextStyle.textWidthBasis,
669
        textHeightBehavior: widget.textHeightBehavior ?? defaultTextStyle.textHeightBehavior,
670 671 672 673
        showSelectionHandles: _showSelectionHandles,
        showCursor: widget.showCursor,
        controller: _controller,
        focusNode: focusNode,
674
        strutStyle: widget.strutStyle ?? const StrutStyle(),
675 676
        textAlign: widget.textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start,
        textDirection: widget.textDirection,
677
        textScaleFactor: widget.textScaleFactor,
678 679
        autofocus: widget.autofocus,
        forceLine: false,
680
        toolbarOptions: widget.toolbarOptions,
681
        minLines: widget.minLines,
682
        maxLines: widget.maxLines ?? defaultTextStyle.maxLines,
683
        selectionColor: selectionColor,
684 685 686 687 688
        selectionControls: widget.selectionEnabled ? textSelectionControls : null,
        onSelectionChanged: _handleSelectionChanged,
        onSelectionHandleTapped: _handleSelectionHandleTapped,
        rendererIgnoresPointer: true,
        cursorWidth: widget.cursorWidth,
689
        cursorHeight: widget.cursorHeight,
690 691
        cursorRadius: cursorRadius,
        cursorColor: cursorColor,
692 693
        selectionHeightStyle: widget.selectionHeightStyle,
        selectionWidthStyle: widget.selectionWidthStyle,
694 695 696 697 698 699 700
        cursorOpacityAnimates: cursorOpacityAnimates,
        cursorOffset: cursorOffset,
        paintCursorAboveText: paintCursorAboveText,
        backgroundCursorColor: CupertinoColors.inactiveGray,
        enableInteractiveSelection: widget.enableInteractiveSelection,
        dragStartBehavior: widget.dragStartBehavior,
        scrollPhysics: widget.scrollPhysics,
701
        autofillHints: null,
702 703 704 705
      ),
    );

    return Semantics(
706
      label: widget.semanticsLabel,
707
      excludeSemantics: widget.semanticsLabel != null,
708 709 710 711 712 713 714 715 716 717
      onLongPress: () {
        _effectiveFocusNode.requestFocus();
      },
      child: _selectionGestureDetectorBuilder.buildGestureDetector(
        behavior: HitTestBehavior.translucent,
        child: child,
      ),
    );
  }
}