This commit is contained in:
LZX committed 2026-09-15 18:16:12 +08:00
1 parent 63e1fe3861
commit 973d4a6020
9 files changed
+332 -118

No files matched your search

+27 -31
View File
@@ -55,9 +55,11 @@ class _MobileToolbarLayoutDelegate extends SingleChildLayoutDelegate {
@override @override
Offset getPositionForChild(Size size, Size childSize) { Offset getPositionForChild(Size size, Size childSize) {
// 1. 计算受保护的可视安全编辑区 safeEditorRect // 1. 计算受保护的可视安全编辑区与屏幕顶界
// 顶部:排除 AppBar, TabBar (renderRect.top) 以及系统状态栏 // 屏幕顶界:手机系统状态栏安全区(由于菜单置于 rootOverlay 顶层悬浮层,高于 TabBar 和 AppBar,因此向上可借用其空间,避免向下翻转遮挡光标)
final double safeTop = max(renderRect?.top ?? 0.0, mediaQuery.padding.top) + 6.0; final double screenTop = mediaQuery.padding.top + 6.0;
// 编辑区顶界:排除 AppBar / TabBar (renderRect.top),用于编辑区居中或贴顶显示
final double editorTop = max(renderRect?.top ?? 0.0, mediaQuery.padding.top) + 6.0;
// 底部:排除软键盘 (viewInsets.bottom)、虚拟小键盘 (renderRect.bottom) 以及底部安全区 // 底部:排除软键盘 (viewInsets.bottom)、虚拟小键盘 (renderRect.bottom) 以及底部安全区
final double screenBottomWithoutKeyboard = mediaQuery.size.height - mediaQuery.viewInsets.bottom - mediaQuery.padding.bottom; final double screenBottomWithoutKeyboard = mediaQuery.size.height - mediaQuery.viewInsets.bottom - mediaQuery.padding.bottom;
final double safeBottom = min(renderRect?.bottom ?? screenBottomWithoutKeyboard, screenBottomWithoutKeyboard) - 6.0; final double safeBottom = min(renderRect?.bottom ?? screenBottomWithoutKeyboard, screenBottomWithoutKeyboard) - 6.0;
@@ -66,57 +68,61 @@ class _MobileToolbarLayoutDelegate extends SingleChildLayoutDelegate {
final double safeRight = min(renderRect?.right ?? mediaQuery.size.width, mediaQuery.size.width - mediaQuery.padding.right) - 8.0; final double safeRight = min(renderRect?.right ?? mediaQuery.size.width, mediaQuery.size.width - mediaQuery.padding.right) - 8.0;
final double availableWidth = max(0.0, safeRight - safeLeft); final double availableWidth = max(0.0, safeRight - safeLeft);
final double availableHeight = max(0.0, safeBottom - safeTop); final double editorAvailableHeight = max(0.0, safeBottom - editorTop);
// 2. 根据 anchors 中的 EditorToolbarPlacement 或传统 anchors 计算位置 // 2. 根据 anchors 中的 EditorToolbarPlacement 或传统 anchors 计算位置
EditorToolbarPlacement placement = EditorToolbarPlacement.aboveStart; EditorToolbarPlacement placement = EditorToolbarPlacement.aboveStart;
Offset targetOffset = anchors.primaryAnchor; Offset targetOffset = anchors.primaryAnchor;
double lineHeight = 24.0;
if (anchors is EditorSelectionToolbarAnchors) { if (anchors is EditorSelectionToolbarAnchors) {
final customAnchors = anchors as EditorSelectionToolbarAnchors; final customAnchors = anchors as EditorSelectionToolbarAnchors;
placement = customAnchors.placement; placement = customAnchors.placement;
targetOffset = customAnchors.targetOffset; targetOffset = customAnchors.targetOffset;
lineHeight = customAnchors.lineHeight;
} }
// 光标手柄(水滴形手柄)下挂高度约 26px,加上间距共 32px 避让距离
const double handleClearance = 32.0;
double x; double x;
double y; double y;
switch (placement) { switch (placement) {
case EditorToolbarPlacement.center: case EditorToolbarPlacement.center:
// 框选文本完全占据当前屏幕:在中间显示 // 框选文本完全占据当前屏幕:在编辑区中间显示
x = safeLeft + (availableWidth - childSize.width) / 2.0; x = safeLeft + (availableWidth - childSize.width) / 2.0;
y = safeTop + (availableHeight - childSize.height) / 2.0; y = editorTop + (editorAvailableHeight - childSize.height) / 2.0;
break; break;
case EditorToolbarPlacement.top: case EditorToolbarPlacement.top:
// 选区整体在视口上方:在视口顶部贴边显示 // 选区整体在视口上方:在视口顶部贴边显示
x = safeLeft + (availableWidth - childSize.width) / 2.0; x = safeLeft + (availableWidth - childSize.width) / 2.0;
y = safeTop + 4.0; y = editorTop + 4.0;
break; break;
case EditorToolbarPlacement.bottom: case EditorToolbarPlacement.bottom:
// 选区整体在视口下方:在视口底部贴边显示(紧贴软键盘/小键盘上方) // 选区整体在视口下方:在视口底部贴边显示(紧贴软键盘/小键盘上方)
x = safeLeft + (availableWidth - childSize.width) / 2.0; x = safeLeft + (availableWidth - childSize.width) / 2.0;
y = max(safeTop, safeBottom - childSize.height - 4.0); y = max(screenTop, safeBottom - childSize.height - 4.0);
break; break;
case EditorToolbarPlacement.aboveStart: case EditorToolbarPlacement.aboveStart:
// 在左端点上方弹出,若上方空间不足则翻转至下方 // 在左端点上方弹出,菜单位于 rootOverlay,允许借用 TabBar/AppBar 空间,只要不超出状态栏即可保留在上方
x = targetOffset.dx - childSize.width / 2.0; x = targetOffset.dx - childSize.width / 2.0;
final double yAbove = targetOffset.dy - childSize.height - 8.0; final double yAbove = targetOffset.dy - childSize.height - 8.0;
if (yAbove >= safeTop) { if (yAbove >= screenTop) {
y = yAbove; y = yAbove;
} else { } else {
// 上方空间不足,翻转到左端点下方(行高约为 24) // 状态栏顶部空间不足时翻转到下方,并根据动态行高与手柄下挂高度充分避让
y = targetOffset.dy + 24.0 + 8.0; y = targetOffset.dy + lineHeight + handleClearance;
} }
break; break;
case EditorToolbarPlacement.belowEnd: case EditorToolbarPlacement.belowEnd:
// 在右端点下方弹出,若下方空间不足则翻转至上方 // 在右端点下方弹出,根据当前实际字号行高与手柄下挂高度充分避让
x = targetOffset.dx - childSize.width / 2.0; x = targetOffset.dx - childSize.width / 2.0;
// 右端点手柄下挂高度约 28px,避免遮挡光标水滴手柄 final double yBelow = targetOffset.dy + lineHeight + handleClearance;
final double yBelow = targetOffset.dy + 24.0 + 26.0;
if (yBelow + childSize.height <= safeBottom) { if (yBelow + childSize.height <= safeBottom) {
y = yBelow; y = yBelow;
} else { } else {
@@ -130,9 +136,9 @@ class _MobileToolbarLayoutDelegate extends SingleChildLayoutDelegate {
final double clampedX = (availableWidth >= childSize.width) final double clampedX = (availableWidth >= childSize.width)
? x.clamp(safeLeft, safeRight - childSize.width) ? x.clamp(safeLeft, safeRight - childSize.width)
: safeLeft; : safeLeft;
final double clampedY = (availableHeight >= childSize.height) final double clampedY = (safeBottom - screenTop >= childSize.height)
? y.clamp(safeTop, safeBottom - childSize.height) ? y.clamp(screenTop, safeBottom - childSize.height)
: safeTop; : screenTop;
return Offset(clampedX, clampedY); return Offset(clampedX, clampedY);
} }
@@ -218,7 +224,6 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
if (hasSelection) ...[ if (hasSelection) ...[
_buildItem( _buildItem(
context, context,
icon: Icons.content_cut,
label: cutLabel, label: cutLabel,
onTap: () { onTap: () {
widget.controller.cut(); widget.controller.cut();
@@ -229,7 +234,6 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
_buildDivider(context), _buildDivider(context),
_buildItem( _buildItem(
context, context,
icon: Icons.copy,
label: copyLabel, label: copyLabel,
onTap: () { onTap: () {
widget.controller.copy(); widget.controller.copy();
@@ -242,7 +246,6 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
if (hasSelection) _buildDivider(context), if (hasSelection) _buildDivider(context),
_buildItem( _buildItem(
context, context,
icon: Icons.paste,
label: pasteLabel, label: pasteLabel,
onTap: () { onTap: () {
widget.controller.paste(); widget.controller.paste();
@@ -255,7 +258,6 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
_buildDivider(context), _buildDivider(context),
_buildItem( _buildItem(
context, context,
icon: Icons.select_all,
label: selectAllLabel, label: selectAllLabel,
onTap: () { onTap: () {
widget.controller.selectAll(); widget.controller.selectAll();
@@ -281,7 +283,6 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
Widget _buildItem( Widget _buildItem(
BuildContext context, { BuildContext context, {
required IconData icon,
required String label, required String label,
required VoidCallback onTap, required VoidCallback onTap,
}) { }) {
@@ -289,13 +290,9 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
return InkWell( return InkWell(
onTap: onTap, onTap: onTap,
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 9.0),
child: Row( child: Center(
mainAxisSize: MainAxisSize.min, child: Text(
children: [
Icon(icon, size: 16, color: colorScheme.onSurface),
const SizedBox(width: 4),
Text(
label, label,
style: TextStyle( style: TextStyle(
fontSize: 13, fontSize: 13,
@@ -303,7 +300,6 @@ class _MobileSelectionToolbarWidgetState extends State<_MobileSelectionToolbarWi
color: colorScheme.onSurface, color: colorScheme.onSurface,
), ),
), ),
],
), ),
), ),
); );
+5 -36
View File
@@ -460,7 +460,11 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
wordWrap: activeWordWrap, wordWrap: activeWordWrap,
toolbarController: _toolbarController, toolbarController: _toolbarController,
margin: const EdgeInsets.only(left: 2.0, top: 4.0, right: 8, bottom: 8.0), margin: const EdgeInsets.only(left: 2.0, top: 4.0, right: 8, bottom: 8.0),
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), padding: const EdgeInsets.fromLTRB(6.0, 0.0, 0.0, 0.0),
leadingDivider: Container(
width: 1.0,
color: activeTheme.gutterTextColor.withValues(alpha: 0.25),
),
style: CodeEditorStyle( style: CodeEditorStyle(
fontSize: displayFontSize, fontSize: displayFontSize,
textColor: activeTheme.textColor, textColor: activeTheme.textColor,
@@ -507,41 +511,6 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
); );
}, },
), ),
if (_isPinching && _activeZoomFontSize != null)
Center(
child: IgnorePointer(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.75),
borderRadius: BorderRadius.circular(24),
boxShadow: const [
BoxShadow(
color: Colors.black26,
blurRadius: 8,
offset: Offset(0, 2),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.format_size, color: Colors.white, size: 18),
const SizedBox(width: 8),
Text(
'${_activeZoomFontSize!.round()} pt',
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.bold,
decoration: TextDecoration.none,
),
),
],
),
),
),
),
], ],
), ),
), ),
@@ -243,7 +243,7 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli
clipBehavior: widget.clipBehavior, clipBehavior: widget.clipBehavior,
margin: widget.margin, margin: widget.margin,
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (indicator != null) if (indicator != null)
indicator, indicator,
@@ -1240,6 +1240,64 @@ class _CodeFieldRender extends RenderBox implements MouseTrackerAnnotation {
return Rect.fromLTRB(minX, minY, maxX, maxY); return Rect.fromLTRB(minX, minY, maxX, maxY);
} }
/// Checks whether a given [position] (in global coordinates) physically intersects
/// the visible selection bounding rectangles.
/// Clicking beyond the end of text into trailing blank space returns false.
bool isPositionInSelection({
required Offset position,
required CodeLineSelection selection,
}) {
if (selection.isCollapsed) {
return false;
}
final Offset localPosition = globalToLocal(position);
if (!isValidPointer(localPosition)) {
return false;
}
final Offset offset = localPosition + paintOffset;
final CodeLinePosition start = selection.start;
final CodeLinePosition end = selection.end;
for (final CodeLineRenderParagraph paragraph in _displayParagraphs) {
if (paragraph.index < start.index || paragraph.index > end.index) {
continue;
}
if (!paragraph.inVerticalRange(offset)) {
continue;
}
final int startIndex = (paragraph.index == start.index) ? start.offset : 0;
final int endIndex = (paragraph.index == end.index) ? end.offset : paragraph.length;
final List<Rect> rects;
if (startIndex == endIndex) {
final Offset? off = paragraph.getOffset(TextPosition(offset: startIndex));
if (off != null) {
rects = [Rect.fromLTWH(off.dx, off.dy, 0, paragraph.preferredLineHeight)];
} else {
rects = const [];
}
} else {
rects = paragraph.getRangeRects(TextRange(start: startIndex, end: endIndex));
}
if (rects.isEmpty) {
continue;
}
final Offset pointInParagraph = offset - paragraph.offset;
for (final Rect rect in rects) {
if (rect.isEmpty) {
continue;
}
final Rect visualRect = (rect == rects.last && paragraph.index < end.index)
? Rect.fromPoints(rect.topLeft, rect.bottomRight + const Offset(5.0, 0.0))
: rect;
if (visualRect.inflate(2.0).contains(pointInParagraph)) {
return true;
}
}
}
return false;
}
void _updateDisplayRenderParagraphs() { void _updateDisplayRenderParagraphs() {
final double effectiveWidth; final double effectiveWidth;
if (_horizontalViewport == null) { if (_horizontalViewport == null) {
+62 -44
View File
@@ -35,7 +35,7 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
bool _longPressOnSelection = false; bool _longPressOnSelection = false;
CodeLineSelection? _anchorSelection; CodeLineSelection? _anchorSelection;
_CodeFieldRender get render => widget.editorKey.currentContext?.findRenderObject() as _CodeFieldRender; _CodeFieldRender? get render => widget.editorKey.currentContext?.findRenderObject() as _CodeFieldRender?;
bool _tapping = false; bool _tapping = false;
@@ -72,26 +72,26 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
_dragPosition = null; _dragPosition = null;
_longPressOnSelection = false; _longPressOnSelection = false;
_dragging = false; _dragging = false;
render.stopAutoScroll(); render?.stopAutoScroll();
widget.selectionOverlayController.showHandle(context); widget.selectionOverlayController.showHandle(context);
}, },
onLongPressCancel: () { onLongPressCancel: () {
_dragPosition = null; _dragPosition = null;
_longPressOnSelection = false; _longPressOnSelection = false;
_dragging = false; _dragging = false;
render.stopAutoScroll(); render?.stopAutoScroll();
widget.selectionOverlayController.hideToolbar(); widget.selectionOverlayController.hideToolbar();
widget.selectionOverlayController.hideHandle(); widget.selectionOverlayController.hideHandle();
}, },
onLongPressUp: () { onLongPressUp: () {
_dragPosition = null; _dragPosition = null;
render.stopAutoScroll(); render?.stopAutoScroll();
}, },
onTapUp: (details) { onTapUp: (details) {
_onMobileTapUp(details.globalPosition); _onMobileTapUp(details.globalPosition);
}, },
onTapDown: (details) { onTapDown: (details) {
if (!render.hasFocus) { if (render?.hasFocus != true) {
_onMobileTapDown(details.globalPosition); _onMobileTapDown(details.globalPosition);
} }
}, },
@@ -113,12 +113,12 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
onVerticalDragEnd: (_) { onVerticalDragEnd: (_) {
_dragPosition = null; _dragPosition = null;
_dragging = false; _dragging = false;
render.stopAutoScroll(); render?.stopAutoScroll();
}, },
onVerticalDragCancel: () { onVerticalDragCancel: () {
_dragPosition = null; _dragPosition = null;
_dragging = false; _dragging = false;
render.stopAutoScroll(); render?.stopAutoScroll();
}, },
onHorizontalDragStart: (details) { onHorizontalDragStart: (details) {
if (!_tapping) { if (!_tapping) {
@@ -131,12 +131,12 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
onHorizontalDragEnd: (_) { onHorizontalDragEnd: (_) {
_dragPosition = null; _dragPosition = null;
_dragging = false; _dragging = false;
render.stopAutoScroll(); render?.stopAutoScroll();
}, },
onHorizontalDragCancel: () { onHorizontalDragCancel: () {
_dragPosition = null; _dragPosition = null;
_dragging = false; _dragging = false;
render.stopAutoScroll(); render?.stopAutoScroll();
}, },
behavior: widget.behavior, behavior: widget.behavior,
onSecondaryTapDown: (detail) { onSecondaryTapDown: (detail) {
@@ -147,7 +147,7 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
}, },
child: Listener( child: Listener(
onPointerDown: (event) { onPointerDown: (event) {
_tapping = render.isValidPointer2(event.position); _tapping = render?.isValidPointer2(event.position) ?? false;
// A trick, delay the focus request here to avoid loss. // A trick, delay the focus request here to avoid loss.
Future(widget.inputController.ensureInput); Future(widget.inputController.ensureInput);
_onDesktopTapDown(event.position); _onDesktopTapDown(event.position);
@@ -210,7 +210,7 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
} }
void _onMobileLongPressedStart(Offset position) { void _onMobileLongPressedStart(Offset position) {
final CodeLineRange? range = render.selectWord( final CodeLineRange? range = render?.selectWord(
position: position, position: position,
); );
if (range == null) { if (range == null) {
@@ -260,7 +260,7 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
} }
void _onDoubleTap(Offset position) { void _onDoubleTap(Offset position) {
final CodeLineRange? range = render.selectWord( final CodeLineRange? range = render?.selectWord(
position: position, position: position,
); );
if (range == null) { if (range == null) {
@@ -315,7 +315,8 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
void _onSecondaryTapDown(BuildContext context, TapDownDetails details) { void _onSecondaryTapDown(BuildContext context, TapDownDetails details) {
_handleByNextEvent = false; _handleByNextEvent = false;
if (!render.size.contains(render.globalToLocal(details.globalPosition))) { final _CodeFieldRender? r = render;
if (r == null || !r.size.contains(r.globalToLocal(details.globalPosition))) {
return; return;
} }
widget.controller.clearComposing(); widget.controller.clearComposing();
@@ -323,12 +324,16 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
} }
void _extendSelection(Offset offset, _SelectionChangedCause cause) { void _extendSelection(Offset offset, _SelectionChangedCause cause) {
final _CodeFieldRender? r = render;
if (r == null) {
return;
}
if (cause == _SelectionChangedCause.tapDown || cause == _SelectionChangedCause.tapUp) { if (cause == _SelectionChangedCause.tapDown || cause == _SelectionChangedCause.tapUp) {
if (expandChunkIfNeeded(render.chunkIndicatorHitIndex(offset))) { if (expandChunkIfNeeded(r.chunkIndicatorHitIndex(offset))) {
return; return;
} }
} }
final CodeLineSelection? selection = render.extendPositionTo( final CodeLineSelection? selection = r.extendPositionTo(
oldSelection: widget.controller.selection, oldSelection: widget.controller.selection,
position: offset, position: offset,
anchor: _isMobile ? null : _anchorSelection, anchor: _isMobile ? null : _anchorSelection,
@@ -348,12 +353,16 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
} }
void _selectPosition(Offset offset, _SelectionChangedCause cause) { void _selectPosition(Offset offset, _SelectionChangedCause cause) {
final _CodeFieldRender? r = render;
if (r == null) {
return;
}
if (cause == _SelectionChangedCause.tapDown || cause == _SelectionChangedCause.tapUp) { if (cause == _SelectionChangedCause.tapDown || cause == _SelectionChangedCause.tapUp) {
if (expandChunkIfNeeded(render.chunkIndicatorHitIndex(offset))) { if (expandChunkIfNeeded(r.chunkIndicatorHitIndex(offset))) {
return; return;
} }
} }
final CodeLineSelection? selection = render.setPositionAt( final CodeLineSelection? selection = r.setPositionAt(
position: offset, position: offset,
); );
if (selection == null) { if (selection == null) {
@@ -364,7 +373,7 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
} }
if (cause == _SelectionChangedCause.tapDown) { if (cause == _SelectionChangedCause.tapDown) {
if (!widget.controller.selection.isCollapsed && widget.controller.selection.contains(selection)) { if (!widget.controller.selection.isCollapsed && _isPositionOnSelection(offset)) {
_handleByNextEvent = true; _handleByNextEvent = true;
return; return;
} }
@@ -377,16 +386,14 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
} }
bool _isPositionOnSelection(Offset position) { bool _isPositionOnSelection(Offset position) {
final CodeLineSelection? selection = render.setPositionAt( final _CodeFieldRender? r = render;
if (r == null) {
return false;
}
return r.isPositionInSelection(
position: position, position: position,
selection: widget.controller.selection,
); );
if (selection == null) {
return false;
}
if (widget.controller.selection == selection) {
return false;
}
return widget.controller.selection.contains(selection);
} }
void _autoScrollWhenDragging() { void _autoScrollWhenDragging() {
@@ -399,12 +406,13 @@ class _CodeSelectionGestureDetectorState extends State<_CodeSelectionGestureDete
void _runAutoScrollLoop() { void _runAutoScrollLoop() {
Future.delayed(const Duration(milliseconds: 16), () { Future.delayed(const Duration(milliseconds: 16), () {
if (!_dragging || _dragPosition == null) { final _CodeFieldRender? r = render;
if (!_dragging || _dragPosition == null || r == null) {
_isAutoScrolling = false; _isAutoScrolling = false;
render.stopAutoScroll(); render?.stopAutoScroll();
return; return;
} }
render.autoScrollWhenDragging(_dragPosition!); r.autoScrollWhenDragging(_dragPosition!);
_extendSelection(_dragPosition!, _SelectionChangedCause.drag); _extendSelection(_dragPosition!, _SelectionChangedCause.drag);
_runAutoScrollLoop(); _runAutoScrollLoop();
}); });
@@ -585,21 +593,25 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController {
@override @override
void showToolbar(BuildContext context, Offset globalPosition, [TextSelectionHandleType? targetHandle]) { void showToolbar(BuildContext context, Offset globalPosition, [TextSelectionHandleType? targetHandle]) {
final _CodeFieldRender? render = ensureRender;
if (render == null || !render.hasSize) {
return;
}
globalPosition = _clampPosition(globalPosition); globalPosition = _clampPosition(globalPosition);
final Rect editingRegion = Rect.fromPoints( final Rect editingRegion = Rect.fromPoints(
ensureRender.localToGlobal(Offset.zero), render.localToGlobal(Offset.zero),
ensureRender.localToGlobal(ensureRender.size.bottomRight(Offset.zero)), render.localToGlobal(render.size.bottomRight(Offset.zero)),
); );
final CodeLineSelection selection = controller.selection; final CodeLineSelection selection = controller.selection;
final TextSelectionToolbarAnchors anchors; final TextSelectionToolbarAnchors anchors;
if (selection.isCollapsed) { if (selection.isCollapsed) {
anchors = TextSelectionToolbarAnchors( anchors = TextSelectionToolbarAnchors(
primaryAnchor: ensureRender.calculateTextPositionScreenOffset(selection.start, false) ?? globalPosition, primaryAnchor: render.calculateTextPositionScreenOffset(selection.start, false) ?? globalPosition,
); );
} else { } else {
final Offset? startScreenOffset = ensureRender.calculateTextPositionScreenOffset(selection.start, false); final Offset? startScreenOffset = render.calculateTextPositionScreenOffset(selection.start, false);
final Offset? endScreenOffset = ensureRender.calculateTextPositionScreenOffset(selection.end, false); final Offset? endScreenOffset = render.calculateTextPositionScreenOffset(selection.end, false);
final double lineHeight = ensureRender.lineHeight; final double lineHeight = render.lineHeight;
// 判断左端点是否完全在屏幕编辑区内(留有微小容差) // 判断左端点是否完全在屏幕编辑区内(留有微小容差)
final bool isStartOnScreen = startScreenOffset != null && final bool isStartOnScreen = startScreenOffset != null &&
@@ -642,11 +654,11 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController {
targetOffset = endScreenOffset!; targetOffset = endScreenOffset!;
} else { } else {
// 都不在屏幕内 // 都不在屏幕内
final int firstVisibleLine = ensureRender.displayParagraphs.isNotEmpty final int firstVisibleLine = render.displayParagraphs.isNotEmpty
? ensureRender.displayParagraphs.first.index ? render.displayParagraphs.first.index
: 0; : 0;
final int lastVisibleLine = ensureRender.displayParagraphs.isNotEmpty final int lastVisibleLine = render.displayParagraphs.isNotEmpty
? ensureRender.displayParagraphs.last.index ? render.displayParagraphs.last.index
: 0; : 0;
if (selection.startIndex <= firstVisibleLine && selection.endIndex >= lastVisibleLine) { if (selection.startIndex <= firstVisibleLine && selection.endIndex >= lastVisibleLine) {
@@ -675,6 +687,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController {
placement: placement, placement: placement,
targetOffset: targetOffset, targetOffset: targetOffset,
visibleEditorRect: editingRegion, visibleEditorRect: editingRegion,
lineHeight: lineHeight,
); );
} }
onShowToolbar(context, anchors, editingRegion); onShowToolbar(context, anchors, editingRegion);
@@ -682,8 +695,9 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController {
void init() { void init() {
_inited = true; _inited = true;
ensureRender.selectionStartInViewport.addListener(_updateTextSelectionOverlayVisibilities); final _CodeFieldRender? render = ensureRender;
ensureRender.selectionEndInViewport.addListener(_updateTextSelectionOverlayVisibilities); render?.selectionStartInViewport.addListener(_updateTextSelectionOverlayVisibilities);
render?.selectionEndInViewport.addListener(_updateTextSelectionOverlayVisibilities);
} }
@override @override
@@ -715,7 +729,11 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController {
return render != null && render.attached; return render != null && render.attached;
} }
_CodeFieldRender get ensureRender => editorKey.currentContext?.findRenderObject() as _CodeFieldRender; _CodeFieldRender get ensureRender {
final _CodeFieldRender? render = editorKey.currentContext?.findRenderObject() as _CodeFieldRender?;
assert(render != null, 'ensureRender called when render object is not available');
return render!;
}
void _updateTextSelectionHandle() { void _updateTextSelectionHandle() {
if (!_handlesVisible) { if (!_handlesVisible) {
@@ -768,7 +786,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController {
type: type, type: type,
handleLayerLink: startHandleLayerLink, handleLayerLink: startHandleLayerLink,
onSelectionHandleTapped: () { onSelectionHandleTapped: () {
final Offset? position = ensureRender.calculateTextPositionScreenOffset(controller.selection.start, false); final Offset? position = ensureRender?.calculateTextPositionScreenOffset(controller.selection.start, false);
showToolbar(_context, position ?? Offset.zero, TextSelectionHandleType.left); showToolbar(_context, position ?? Offset.zero, TextSelectionHandleType.left);
}, },
onSelectionHandleDragStart: _handleStartHandleDragStart, onSelectionHandleDragStart: _handleStartHandleDragStart,
@@ -797,7 +815,7 @@ class _MobileSelectionOverlayController implements _SelectionOverlayController {
type: type, type: type,
handleLayerLink: endHandleLayerLink, handleLayerLink: endHandleLayerLink,
onSelectionHandleTapped: () { onSelectionHandleTapped: () {
final Offset? position = ensureRender.calculateTextPositionScreenOffset(controller.selection.end, false); final Offset? position = ensureRender?.calculateTextPositionScreenOffset(controller.selection.end, false);
showToolbar(_context, position ?? Offset.zero, TextSelectionHandleType.right); showToolbar(_context, position ?? Offset.zero, TextSelectionHandleType.right);
}, },
onSelectionHandleDragStart: _handleEndHandleDragStart, onSelectionHandleDragStart: _handleEndHandleDragStart,
@@ -22,6 +22,8 @@ class EditorSelectionToolbarAnchors extends TextSelectionToolbarAnchors {
final Offset targetOffset; final Offset targetOffset;
/// 当前编辑器的有效可视区域边界(绝对屏幕坐标) /// 当前编辑器的有效可视区域边界(绝对屏幕坐标)
final Rect visibleEditorRect; final Rect visibleEditorRect;
/// 当前编辑区字号对应的实际行高
final double lineHeight;
const EditorSelectionToolbarAnchors({ const EditorSelectionToolbarAnchors({
required super.primaryAnchor, required super.primaryAnchor,
@@ -29,6 +31,7 @@ class EditorSelectionToolbarAnchors extends TextSelectionToolbarAnchors {
required this.placement, required this.placement,
required this.targetOffset, required this.targetOffset,
required this.visibleEditorRect, required this.visibleEditorRect,
this.lineHeight = 24.0,
}); });
} }
+174 -4
View File
@@ -229,7 +229,7 @@ void main() {
final abovePos = tester.getTopLeft(find.byType(Material).last); final abovePos = tester.getTopLeft(find.byType(Material).last);
expect(abovePos.dy, lessThan(300)); expect(abovePos.dy, lessThan(300));
// 2. aboveStart: 空间狭小(靠近顶部)时翻转到下方 // 2. aboveStart: 靠前行可借用 AppBar 空间留在上方,避免向下翻转遮挡光标
controller.show( controller.show(
context: buildCtx, context: buildCtx,
controller: codeController, controller: codeController,
@@ -244,10 +244,29 @@ void main() {
visibility: visibility, visibility: visibility,
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
final flippedBelowPos = tester.getTopLeft(find.byType(Material).last); final borrowAppBarPos = tester.getTopLeft(find.byType(Material).last);
expect(flippedBelowPos.dy, greaterThan(60)); expect(borrowAppBarPos.dy, lessThan(60));
// 3. belowEnd: 空间充裕时显示在目标下方 // 2.1 aboveStart: 触及手机状态栏安全区极限时向下翻转,并避开行高与手柄
controller.show(
context: buildCtx,
controller: codeController,
anchors: const EditorSelectionToolbarAnchors(
primaryAnchor: Offset(200, 20),
placement: EditorToolbarPlacement.aboveStart,
targetOffset: Offset(200, 20),
visibleEditorRect: Rect.fromLTWH(0, 0, 400, 500),
lineHeight: 24.0,
),
renderRect: const Rect.fromLTWH(0, 0, 400, 500),
layerLink: layerLink,
visibility: visibility,
);
await tester.pumpAndSettle();
final flippedBelowPos = tester.getTopLeft(find.byType(Material).last);
expect(flippedBelowPos.dy, greaterThan(20 + 24.0 + 30.0));
// 3. belowEnd: 空间充裕时显示在目标下方(避让动态行高 + 手柄)
controller.show( controller.show(
context: buildCtx, context: buildCtx,
controller: codeController, controller: codeController,
@@ -387,5 +406,156 @@ void main() {
// 选区在点击外部后被取消 // 选区在点击外部后被取消
expect(codeController.selection.isCollapsed, isTrue); expect(codeController.selection.isCollapsed, isTrue);
}); });
testWidgets('点击选中文本所在行的末尾空白区域,严格判定为非选区并取消框选', (tester) async {
final codeController = CodeLineEditingController.fromText('Hello Flutter Code Editor\nSecond line text');
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: SizedBox(
width: 500,
height: 400,
child: CodeEditor(
controller: codeController,
),
),
),
),
);
await tester.pumpAndSettle();
// 选中第 0 行的 "Hello"
codeController.selection = const CodeLineSelection(
baseIndex: 0,
baseOffset: 0,
extentIndex: 0,
extentOffset: 5,
);
await tester.pumpAndSettle();
expect(codeController.selection.isCollapsed, isFalse);
// 点击第 0 行后面的空白区域 (例如横坐标 400 远超文本宽度)
final editorFinder = find.byType(CodeEditor);
final editorTopLeft = tester.getTopLeft(editorFinder);
await tester.tapAt(editorTopLeft + const Offset(400, 10));
await tester.pumpAndSettle();
// 严格判定:点击末尾空白区域时,框选必须被取消
expect(codeController.selection.isCollapsed, isTrue);
});
testWidgets('移动端选区菜单移除图标仅保留文字', (tester) async {
final controller = CodeEditorToolbarController();
final codeController = CodeLineEditingController.fromText('Hello World');
codeController.selection = const CodeLineSelection(
baseIndex: 0,
baseOffset: 0,
extentIndex: 0,
extentOffset: 5,
);
late BuildContext buildCtx;
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: Builder(
builder: (context) {
buildCtx = context;
return const SizedBox(width: 400, height: 600);
},
),
),
),
);
await tester.pumpAndSettle();
final layerLink = LayerLink();
final visibility = ValueNotifier<bool>(true);
controller.show(
context: buildCtx,
controller: codeController,
anchors: const TextSelectionToolbarAnchors(
primaryAnchor: Offset(100, 100),
),
renderRect: const Rect.fromLTWH(0, 0, 400, 600),
layerLink: layerLink,
visibility: visibility,
);
await tester.pumpAndSettle();
// 验证菜单弹出的 Material 容器内不包含任何 Icon,只保留文字
final toolbarMaterial = find.byType(Material).last;
expect(find.descendant(of: toolbarMaterial, matching: find.byType(Icon)), findsNothing);
expect(find.descendant(of: toolbarMaterial, matching: find.byType(Text)), findsWidgets);
controller.hide(buildCtx);
await tester.pumpAndSettle();
});
testWidgets('大字号下 belowEnd 与翻转到下方时,根据动态行高与手柄下挂距离充分下移', (tester) async {
final controller = CodeEditorToolbarController();
final codeController = CodeLineEditingController.fromText('Large Font Test');
codeController.selection = const CodeLineSelection(
baseIndex: 0,
baseOffset: 0,
extentIndex: 0,
extentOffset: 5,
);
late BuildContext buildCtx;
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: Builder(
builder: (context) {
buildCtx = context;
return const SizedBox(width: 400, height: 700);
},
),
),
),
);
await tester.pumpAndSettle();
final layerLink = LayerLink();
final visibility = ValueNotifier<bool>(true);
// 模拟大字号:lineHeight 达到 48.0
const double largeLineHeight = 48.0;
const double targetY = 150.0;
controller.show(
context: buildCtx,
controller: codeController,
anchors: const EditorSelectionToolbarAnchors(
primaryAnchor: Offset(200, targetY),
placement: EditorToolbarPlacement.belowEnd,
targetOffset: Offset(200, targetY),
visibleEditorRect: Rect.fromLTWH(0, 0, 400, 700),
lineHeight: largeLineHeight,
),
renderRect: const Rect.fromLTWH(0, 0, 400, 700),
layerLink: layerLink,
visibility: visibility,
);
await tester.pumpAndSettle();
final menuPos = tester.getTopLeft(find.byType(Material).last);
// y 应该正好是 targetY + largeLineHeight + 32.0 = 150 + 48 + 32 = 230.0
expect(menuPos.dy, equals(targetY + largeLineHeight + 32.0));
controller.hide(buildCtx);
await tester.pumpAndSettle();
});
}); });
} }
+2 -2
View File
@@ -2750,8 +2750,8 @@ void main() {
await gesture2.moveTo(const Offset(200, 400)); await gesture2.moveTo(const Offset(200, 400));
await tester.pump(); await tester.pump();
// Verify pinch HUD is visible // Verify pinch HUD is NOT shown (per user requirement: no font size prompt on screen)
expect(find.text('28 pt'), findsOneWidget); expect(find.text('28 pt'), findsNothing);
// Release pointers // Release pointers
await gesture1.up(); await gesture1.up();