diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 3a04e56..a8f1d2a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -108,6 +108,10 @@ }, "wordWrap": "Word Wrap", "wordWrapSubtitle": "Wrap long lines to fit the editor width", + "showLineNumbers": "Show Line Numbers", + "showLineNumbersSubtitle": "Display line numbers and code folding markers on the left", + "pinLineNumbers": "Pin Line Numbers", + "pinLineNumbersSubtitle": "Keep line numbers pinned to the left during horizontal scroll", "virtualKeyboard": "Accessory Keyboard", "virtualKeyboardSubtitle": "Show accessory symbols and shortcuts below the code editor", "editVirtualKeyboardConfig": "Edit Keyboard Config", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 6fd3d37..ba3d5b7 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -656,6 +656,30 @@ abstract class AppLocalizations { /// **'长代码行超出边界时自动折行'** String get wordWrapSubtitle; + /// No description provided for @showLineNumbers. + /// + /// In zh, this message translates to: + /// **'显示行号'** + String get showLineNumbers; + + /// No description provided for @showLineNumbersSubtitle. + /// + /// In zh, this message translates to: + /// **'在代码左侧显示行号与折叠标记'** + String get showLineNumbersSubtitle; + + /// No description provided for @pinLineNumbers. + /// + /// In zh, this message translates to: + /// **'固定行号'** + String get pinLineNumbers; + + /// No description provided for @pinLineNumbersSubtitle. + /// + /// In zh, this message translates to: + /// **'水平滚动代码时行号固定在左侧'** + String get pinLineNumbersSubtitle; + /// No description provided for @virtualKeyboard. /// /// In zh, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0977a7e..fd64554 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -323,6 +323,20 @@ class AppLocalizationsEn extends AppLocalizations { @override String get wordWrapSubtitle => 'Wrap long lines to fit the editor width'; + @override + String get showLineNumbers => 'Show Line Numbers'; + + @override + String get showLineNumbersSubtitle => + 'Display line numbers and code folding markers on the left'; + + @override + String get pinLineNumbers => 'Pin Line Numbers'; + + @override + String get pinLineNumbersSubtitle => + 'Keep line numbers pinned to the left during horizontal scroll'; + @override String get virtualKeyboard => 'Accessory Keyboard'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 10f7b6c..dc1239d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -319,6 +319,18 @@ class AppLocalizationsZh extends AppLocalizations { @override String get wordWrapSubtitle => '长代码行超出边界时自动折行'; + @override + String get showLineNumbers => '显示行号'; + + @override + String get showLineNumbersSubtitle => '在代码左侧显示行号与折叠标记'; + + @override + String get pinLineNumbers => '固定行号'; + + @override + String get pinLineNumbersSubtitle => '水平滚动代码时行号固定在左侧'; + @override String get virtualKeyboard => '辅助小键盘'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 1aca5b1..3054a48 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -108,6 +108,10 @@ }, "wordWrap": "自动换行", "wordWrapSubtitle": "长代码行超出边界时自动折行", + "showLineNumbers": "显示行号", + "showLineNumbersSubtitle": "在代码左侧显示行号与折叠标记", + "pinLineNumbers": "固定行号", + "pinLineNumbersSubtitle": "水平滚动代码时行号固定在左侧", "virtualKeyboard": "辅助小键盘", "virtualKeyboardSubtitle": "在代码编辑区底部显示辅助符号与快捷键", "editVirtualKeyboardConfig": "编辑键盘配置", diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart index 62cef5c..1a524a6 100644 --- a/lib/providers/settings_provider.dart +++ b/lib/providers/settings_provider.dart @@ -18,6 +18,8 @@ class SettingsProvider extends ChangeNotifier { static const String _keyEditorFontSize = 'editor_font_size'; //代码字体大小 static const String _keyEditorIndentSize = 'editor_indent_size'; //缩进大小 static const String _keyWordWrap = 'editor_word_wrap'; //自动换行 + static const String _keyShowLineNumbers = 'editor_show_line_numbers'; //显示行号 + static const String _keyPinLineNumbers = 'editor_pin_line_numbers'; //固定行号 static const String _keyEnableVirtualKeyboard = 'enable_virtual_keyboard'; //小键盘启用 static const String _keyVirtualKeyboardConfig = 'virtual_keyboard_config'; //小键盘配置JSON static const String _keyEditorFont = 'editor_font_family'; //代码字体 @@ -47,6 +49,8 @@ class SettingsProvider extends ChangeNotifier { double _fontSize = 14.0; int _indentSize = 4; bool _wordWrap = false; + bool _showLineNumbers = true; + bool _pinLineNumbers = true; bool _enableVirtualKeyboard = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS; String _virtualKeyboardConfigJson = VirtualKeyboardConfig.defaultJsonPretty(); VirtualKeyboardConfig _virtualKeyboardConfig = VirtualKeyboardConfig.defaultConfiguration(); @@ -77,6 +81,8 @@ class SettingsProvider extends ChangeNotifier { double get fontSize => _fontSize; int get indentSize => _indentSize; bool get wordWrap => _wordWrap; + bool get showLineNumbers => _showLineNumbers; + bool get pinLineNumbers => _pinLineNumbers; bool get enableVirtualKeyboard => _enableVirtualKeyboard; String get virtualKeyboardConfigJson => _virtualKeyboardConfigJson; VirtualKeyboardConfig get virtualKeyboardConfig => _virtualKeyboardConfig; @@ -205,6 +211,16 @@ class SettingsProvider extends ChangeNotifier { _wordWrap = savedWordWrap; } + final savedShowLineNumbers = prefs.getBool(_keyShowLineNumbers); + if (savedShowLineNumbers != null) { + _showLineNumbers = savedShowLineNumbers; + } + + final savedPinLineNumbers = prefs.getBool(_keyPinLineNumbers); + if (savedPinLineNumbers != null) { + _pinLineNumbers = savedPinLineNumbers; + } + final savedEnableVirtualKeyboard = prefs.getBool(_keyEnableVirtualKeyboard); if (savedEnableVirtualKeyboard != null) { _enableVirtualKeyboard = savedEnableVirtualKeyboard; @@ -348,6 +364,26 @@ class SettingsProvider extends ChangeNotifier { }catch (_) {} } + Future setShowLineNumbers(bool show) async { + if (_showLineNumbers == show) return; + _showLineNumbers = show; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_keyShowLineNumbers, show); + } catch (_) {} + } + + Future setPinLineNumbers(bool pin) async { + if (_pinLineNumbers == pin) return; + _pinLineNumbers = pin; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_keyPinLineNumbers, pin); + } catch (_) {} + } + /// 编辑区小键盘开关(等价于 `setKeyboardEnabled(KeyboardScope.editor, ...)`) Future setEnableVirtualKeyboard(bool enable) => setKeyboardEnabled(KeyboardScope.editor, enable); diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index 219835e..79efde7 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -54,6 +54,8 @@ class SettingsView extends StatelessWidget { _buildEditorFontTile(context, provider), _buildIndentSizeTile(context, provider, l10n), _buildWordWrapTile(context, provider, l10n), + _buildShowLineNumbersTile(context, provider, l10n), + _buildPinLineNumbersTile(context, provider, l10n), _buildVirtualKeyboardTile(context, provider, l10n), _buildVirtualKeyboardConfigTile(context, provider, l10n), @@ -754,6 +756,54 @@ class SettingsView extends StatelessWidget { ); } + /// 编辑区:显示行号条目 + Widget _buildShowLineNumbersTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + + return SwitchListTile( + secondary: Icon(Icons.format_list_numbered, color: theme.colorScheme.primary), + title: Text(l10n.showLineNumbers), + subtitle: Text(l10n.showLineNumbersSubtitle), + value: provider.showLineNumbers, + onChanged: (val) => provider.setShowLineNumbers(val), + ); + } + + /// 编辑区:固定行号条目(当显示行号开启时才可调整) + Widget _buildPinLineNumbersTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + final isEnabled = provider.showLineNumbers; + + return SwitchListTile( + secondary: Icon( + Icons.push_pin_outlined, + color: isEnabled ? theme.colorScheme.primary : theme.disabledColor, + ), + title: Text( + l10n.pinLineNumbers, + style: TextStyle( + color: isEnabled ? null : theme.disabledColor, + ), + ), + subtitle: Text( + l10n.pinLineNumbersSubtitle, + style: TextStyle( + color: isEnabled ? null : theme.disabledColor, + ), + ), + value: provider.pinLineNumbers, + onChanged: isEnabled ? (val) => provider.setPinLineNumbers(val) : null, + ); + } + /// 编辑区:虚拟小键盘开关条目 Widget _buildVirtualKeyboardTile( BuildContext context, diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index 49a16ea..ff1e17c 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -420,11 +420,15 @@ class _CodeEditorWidgetState extends State { bool enableVirtualKeyboard = false; VirtualKeyboardConfig? keyboardConfig; AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono; + bool showLineNumbers = true; + bool pinLineNumbers = true; try { final settings = _getSettingsProvider(context, listen: true); activeTheme = settings.editorTheme; activeFontSize = settings.fontSize; activeWordWrap = settings.wordWrap; + showLineNumbers = settings.showLineNumbers; + pinLineNumbers = settings.pinLineNumbers; enableVirtualKeyboard = settings.enableVirtualKeyboard; keyboardConfig = settings.virtualKeyboardConfig; activeEditorFont = settings.editorFont; @@ -458,13 +462,16 @@ class _CodeEditorWidgetState extends State { focusNode: _focusNode, scrollController: _scrollController, wordWrap: activeWordWrap, + pinLineNumbers: pinLineNumbers, toolbarController: _toolbarController, margin: const EdgeInsets.only(left: 2.0, top: 4.0, right: 8, bottom: 8.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), - ), + leadingDivider: showLineNumbers + ? Container( + width: 1.0, + color: activeTheme.gutterTextColor.withValues(alpha: 0.25), + ) + : null, style: CodeEditorStyle( fontSize: displayFontSize, textColor: activeTheme.textColor, @@ -479,37 +486,39 @@ class _CodeEditorWidgetState extends State { theme: activeTheme.highlightTheme, ), ), - indicatorBuilder: (context, editingController, chunkController, notifier) { - return Row( - children: [ - DefaultCodeLineNumber( - controller: editingController, - notifier: notifier, - textStyle: TextStyle( - color: activeTheme.gutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - ), - focusedTextStyle: TextStyle( - color: activeTheme.focusedGutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), - fontWeight: FontWeight.bold, - fontFamily: activeEditorFont.fontFamily, - fontFamilyFallback: activeEditorFont.fallback, - ), - ), - DefaultCodeChunkIndicator( - width: 20, - controller: chunkController, - notifier: notifier, - painter: DefaultCodeChunkIndicatorPainter( - color: activeTheme.gutterTextColor, - ), - ), - ], - ); - }, + indicatorBuilder: showLineNumbers + ? (context, editingController, chunkController, notifier) { + return Row( + children: [ + DefaultCodeLineNumber( + controller: editingController, + notifier: notifier, + textStyle: TextStyle( + color: activeTheme.gutterTextColor, + fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + ), + focusedTextStyle: TextStyle( + color: activeTheme.focusedGutterTextColor, + fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontWeight: FontWeight.bold, + fontFamily: activeEditorFont.fontFamily, + fontFamilyFallback: activeEditorFont.fallback, + ), + ), + DefaultCodeChunkIndicator( + width: 20, + controller: chunkController, + notifier: notifier, + painter: DefaultCodeChunkIndicatorPainter( + color: activeTheme.gutterTextColor, + ), + ), + ], + ); + } + : null, ), ], ), diff --git a/packages/re_editor/lib/src/_code_editable.dart b/packages/re_editor/lib/src/_code_editable.dart index 606417d..4209179 100644 --- a/packages/re_editor/lib/src/_code_editable.dart +++ b/packages/re_editor/lib/src/_code_editable.dart @@ -27,6 +27,7 @@ class _CodeEditable extends StatefulWidget { final EdgeInsetsGeometry padding; final EdgeInsetsGeometry margin; final Widget? leadingDivider; + final bool pinLineNumbers; final Border? border; final BorderRadius? borderRadius; final Clip clipBehavior; @@ -68,6 +69,7 @@ class _CodeEditable extends StatefulWidget { required this.padding, required this.margin, required this.leadingDivider, + this.pinLineNumbers = true, this.border, this.borderRadius, this.clipBehavior = Clip.none, @@ -104,6 +106,8 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli late _CodeHighlighter _highlighter; late CodeIndicatorValueNotifier _codeIndicatorValueNotifier; + _ShiftedViewportOffset? _shiftedHorizontalViewport; + double _gutterWidth = 0.0; @override bool get wantKeepAlive => widget.focusNode.hasFocus; @@ -183,6 +187,7 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli _floatingCursorAnimationController.dispose(); widget.focusNode.removeListener(_onFocusChanged); widget.findController.removeListener(_onCodeFindChanged); + _shiftedHorizontalViewport?.dispose(); super.dispose(); } @@ -193,6 +198,41 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli axisDirection: AxisDirection.down, controller: widget.scrollController.verticalScroller, viewportBuilder: (context, ViewportOffset vertical) { + final Widget? indicator = widget.indicatorBuilder?.call( + context, + widget.controller, + widget.chunkController, + _codeIndicatorValueNotifier + ); + final Widget? gutterWidget; + if (indicator != null || widget.leadingDivider != null) { + gutterWidget = Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (indicator != null) indicator, + if (widget.leadingDivider != null) widget.leadingDivider!, + ], + ); + } else { + gutterWidget = null; + } + + final Widget? effectiveGutter; + if (gutterWidget == null) { + effectiveGutter = null; + } else if (widget.pinLineNumbers || widget.wordWrap) { + effectiveGutter = gutterWidget; + } else { + effectiveGutter = _ScrollingGutter( + horizontalScroller: widget.scrollController.horizontalScroller, + onWidthMeasured: (width) { + _gutterWidth = width; + }, + child: gutterWidget, + ); + } + Widget codeField; if (widget.wordWrap) { codeField = _buildCodeField(vertical, null); @@ -201,7 +241,21 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli axisDirection: AxisDirection.right, controller: widget.scrollController.horizontalScroller, viewportBuilder: (context, ViewportOffset horizontal) { - return _buildCodeField(vertical, horizontal); + final ViewportOffset effectiveHorizontal; + if (widget.pinLineNumbers || gutterWidget == null) { + effectiveHorizontal = horizontal; + } else { + if (_shiftedHorizontalViewport == null || + _shiftedHorizontalViewport!._delegate != horizontal) { + _shiftedHorizontalViewport?.dispose(); + _shiftedHorizontalViewport = _ShiftedViewportOffset( + horizontal, + () => _gutterWidth, + ); + } + effectiveHorizontal = _shiftedHorizontalViewport!; + } + return _buildCodeField(vertical, effectiveHorizontal); }, scrollbarBuilder: widget.scrollbarBuilder ); @@ -228,12 +282,6 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli ); } } - final Widget? indicator = widget.indicatorBuilder?.call( - context, - widget.controller, - widget.chunkController, - _codeIndicatorValueNotifier - ); return Container( decoration: BoxDecoration( border: widget.border, @@ -245,10 +293,8 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - if (indicator != null) - indicator, - if (widget.leadingDivider != null) - widget.leadingDivider!, + if (effectiveGutter != null) + effectiveGutter, Expanded( child: RepaintBoundary( child: CompositedTransformTarget( @@ -496,4 +542,205 @@ class _CodeCursorBlinkController extends ValueNotifier { super.dispose(); } +} + +class _ShiftedViewportOffset extends ViewportOffset { + + final ViewportOffset _delegate; + final ValueGetter _gutterWidthGetter; + + _ShiftedViewportOffset(this._delegate, this._gutterWidthGetter) { + _delegate.addListener(notifyListeners); + } + + double get _gutterWidth => _gutterWidthGetter(); + + @override + bool get hasPixels => _delegate.hasPixels; + + @override + double get pixels => + _delegate.hasPixels ? max(0.0, _delegate.pixels - _gutterWidth) : 0.0; + + @override + bool applyViewportDimension(double viewportDimension) { + return _delegate.applyViewportDimension(viewportDimension); + } + + @override + bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) { + return _delegate.applyContentDimensions( + minScrollExtent, + maxScrollExtent + _gutterWidth, + ); + } + + @override + void correctBy(double correction) { + _delegate.correctBy(correction); + } + + @override + void jumpTo(double pixels) { + _delegate.jumpTo(pixels + _gutterWidth); + } + + @override + Future animateTo( + double to, { + required Duration duration, + required Curve curve, + }) { + return _delegate.animateTo( + to + _gutterWidth, + duration: duration, + curve: curve, + ); + } + + @override + ScrollDirection get userScrollDirection => _delegate.userScrollDirection; + + @override + bool get allowImplicitScrolling => _delegate.allowImplicitScrolling; + + @override + void dispose() { + _delegate.removeListener(notifyListeners); + super.dispose(); + } + +} + +class _ScrollingGutter extends SingleChildRenderObjectWidget { + + final ScrollController horizontalScroller; + final ValueChanged? onWidthMeasured; + + const _ScrollingGutter({ + required this.horizontalScroller, + this.onWidthMeasured, + required super.child, + }); + + @override + RenderObject createRenderObject(BuildContext context) { + return _RenderScrollingGutter( + horizontalScroller: horizontalScroller, + onWidthMeasured: onWidthMeasured, + ); + } + + @override + void updateRenderObject( + BuildContext context, covariant _RenderScrollingGutter renderObject) { + renderObject + ..horizontalScroller = horizontalScroller + ..onWidthMeasured = onWidthMeasured; + } + +} + +class _RenderScrollingGutter extends RenderShiftedBox { + + ScrollController _horizontalScroller; + ValueChanged? _onWidthMeasured; + double _lastMeasuredWidth = 0.0; + + _RenderScrollingGutter({ + required ScrollController horizontalScroller, + ValueChanged? onWidthMeasured, + RenderBox? child, + }) : _horizontalScroller = horizontalScroller, + _onWidthMeasured = onWidthMeasured, + super(child); + + ScrollController get horizontalScroller => _horizontalScroller; + set horizontalScroller(ScrollController value) { + if (_horizontalScroller == value) return; + if (attached) { + _horizontalScroller.removeListener(_handleScroll); + } + _horizontalScroller = value; + if (attached) { + _horizontalScroller.addListener(_handleScroll); + } + markNeedsLayout(); + } + + set onWidthMeasured(ValueChanged? value) { + _onWidthMeasured = value; + } + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _horizontalScroller.addListener(_handleScroll); + } + + @override + void detach() { + _horizontalScroller.removeListener(_handleScroll); + super.detach(); + } + + void _handleScroll() { + markNeedsLayout(); + } + + @override + void performLayout() { + if (child == null) { + size = Size(0.0, constraints.maxHeight); + return; + } + + child!.layout(constraints.loosen(), parentUsesSize: true); + final double naturalWidth = child!.size.width; + if (naturalWidth != _lastMeasuredWidth) { + _lastMeasuredWidth = naturalWidth; + _onWidthMeasured?.call(naturalWidth); + } + + final double scrollOffset = + _horizontalScroller.hasClients ? _horizontalScroller.offset : 0.0; + final double visibleWidth = max(0.0, naturalWidth - scrollOffset); + + size = Size(visibleWidth, constraints.maxHeight); + + final BoxParentData childParentData = child!.parentData! as BoxParentData; + childParentData.offset = Offset(-scrollOffset, 0.0); + } + + @override + void paint(PaintingContext context, Offset offset) { + if (child == null || size.width <= 0) { + return; + } + context.pushClipRect( + needsCompositing, + offset, + Rect.fromLTWH(0, 0, size.width, size.height), + (PaintingContext context, Offset offset) { + final BoxParentData childParentData = child!.parentData! as BoxParentData; + context.paintChild(child!, offset + childParentData.offset); + }, + ); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + if (child == null || size.width <= 0) { + return false; + } + final BoxParentData childParentData = child!.parentData! as BoxParentData; + return result.addWithPaintOffset( + offset: childParentData.offset, + position: position, + hitTest: (BoxHitTestResult result, Offset transformed) { + return child!.hitTest(result, position: transformed); + }, + ); + } + } \ No newline at end of file diff --git a/packages/re_editor/lib/src/code_editor.dart b/packages/re_editor/lib/src/code_editor.dart index f23d031..f2739b8 100644 --- a/packages/re_editor/lib/src/code_editor.dart +++ b/packages/re_editor/lib/src/code_editor.dart @@ -199,6 +199,7 @@ class CodeEditor extends StatefulWidget { this.shortcutsActivatorsBuilder, this.shortcutOverrideActions, this.leadingDivider, + this.pinLineNumbers = true, this.border, this.borderRadius, this.clipBehavior = Clip.none, @@ -269,6 +270,9 @@ class CodeEditor extends StatefulWidget { /// A leadingDivider widget between indicator and editor field. final Widget? leadingDivider; + /// Whether line numbers and indicator are pinned to the left during horizontal scroll. + final bool pinLineNumbers; + /// The border of the editor. final Border? border; @@ -523,6 +527,7 @@ class _CodeEditorState extends State { cursorWidth: widget.style?.cursorWidth ?? _kDefaultCaretWidth, showCursorWhenReadOnly: widget.showCursorWhenReadOnly ?? true, leadingDivider: widget.leadingDivider, + pinLineNumbers: widget.pinLineNumbers, border: widget.border, borderRadius: widget.borderRadius, clipBehavior: widget.clipBehavior, diff --git a/test/widget_test.dart b/test/widget_test.dart index 7eebbe0..3a34f9b 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -3214,6 +3214,186 @@ void main() { expect(find.text('JetBrains Mono (Recommended)'), findsWidgets); }); }); + + group('Editor Line Numbers Settings', () { + test('SettingsProvider line numbers defaults, setters, and persistence', () async { + SharedPreferences.setMockInitialValues({}); + final provider = SettingsProvider(); + await provider.init(); + + // Defaults + expect(provider.showLineNumbers, isTrue); + expect(provider.pinLineNumbers, isTrue); + + // Setters + bool notified = false; + provider.addListener(() => notified = true); + + await provider.setShowLineNumbers(false); + expect(provider.showLineNumbers, isFalse); + expect(notified, isTrue); + + notified = false; + await provider.setPinLineNumbers(false); + expect(provider.pinLineNumbers, isFalse); + expect(notified, isTrue); + + // Verify loaded from SharedPreferences + final provider2 = SettingsProvider(); + await provider2.init(); + expect(provider2.showLineNumbers, isFalse); + expect(provider2.pinLineNumbers, isFalse); + }); + + test('Localization strings exist in both zh and en without hardcoding', () { + final zh = AppLocalizationsZh(); + final en = AppLocalizationsEn(); + + expect(zh.showLineNumbers, '显示行号'); + expect(zh.showLineNumbersSubtitle, '在代码左侧显示行号与折叠标记'); + expect(zh.pinLineNumbers, '固定行号'); + expect(zh.pinLineNumbersSubtitle, '水平滚动代码时行号固定在左侧'); + + expect(en.showLineNumbers, 'Show Line Numbers'); + expect(en.showLineNumbersSubtitle, 'Display line numbers and code folding markers on the left'); + expect(en.pinLineNumbers, 'Pin Line Numbers'); + expect(en.pinLineNumbersSubtitle, 'Keep line numbers pinned to the left during horizontal scroll'); + }); + + testWidgets('SettingsView displays line numbers tiles and disables pin when show is false', (tester) async { + tester.view.physicalSize = const Size(800, 1400); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + SharedPreferences.setMockInitialValues({}); + final provider = SettingsProvider(); + await provider.init(); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: provider, + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: Locale('zh'), + home: SettingsView(), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('显示行号'), findsOneWidget); + expect(find.text('在代码左侧显示行号与折叠标记'), findsOneWidget); + expect(find.text('固定行号'), findsOneWidget); + expect(find.text('水平滚动代码时行号固定在左侧'), findsOneWidget); + + // Both switches should initially be enabled and true + final switchesBefore = tester.widgetList(find.byType(SwitchListTile)); + final showSwitchBefore = switchesBefore.firstWhere((s) => (s.title as Text).data == '显示行号'); + final pinSwitchBefore = switchesBefore.firstWhere((s) => (s.title as Text).data == '固定行号'); + expect(showSwitchBefore.value, isTrue); + expect(showSwitchBefore.onChanged, isNotNull); + expect(pinSwitchBefore.value, isTrue); + expect(pinSwitchBefore.onChanged, isNotNull); + + // Turn off showLineNumbers + await tester.tap(find.text('显示行号')); + await tester.pumpAndSettle(); + + expect(provider.showLineNumbers, isFalse); + + // Now pinLineNumbers should be disabled (onChanged == null) + final switchesAfter = tester.widgetList(find.byType(SwitchListTile)); + final pinSwitchAfter = switchesAfter.firstWhere((s) => (s.title as Text).data == '固定行号'); + expect(pinSwitchAfter.onChanged, isNull); + + // Tapping disabled pinLineNumbers does nothing + await tester.tap(find.text('固定行号')); + await tester.pumpAndSettle(); + expect(provider.pinLineNumbers, isTrue); // unchanged + + // Re-enabling showLineNumbers re-enables pinLineNumbers + await tester.tap(find.text('显示行号')); + await tester.pumpAndSettle(); + expect(provider.showLineNumbers, isTrue); + + final switchesReenabled = tester.widgetList(find.byType(SwitchListTile)); + final pinSwitchReenabled = switchesReenabled.firstWhere((s) => (s.title as Text).data == '固定行号'); + expect(pinSwitchReenabled.onChanged, isNotNull); + }); + + testWidgets('CodeEditor renders without line numbers when indicatorBuilder is null', (tester) async { + final controller = CodeLineEditingController.fromText('const x = 1;\nconst y = 2;'); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 500, + height: 400, + child: CodeEditor( + controller: controller, + wordWrap: false, + pinLineNumbers: true, + indicatorBuilder: null, + leadingDivider: null, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(CodeEditor), findsOneWidget); + expect(find.byType(DefaultCodeLineNumber), findsNothing); + }); + + testWidgets('CodeEditor with pinLineNumbers: false scrolls line numbers horizontally', (tester) async { + final longText = 'const aLongVariableNameThatIsVeryLong = 1234567890 + 987654321;'; + final controller = CodeLineEditingController.fromText('$longText\nline2'); + final scrollController = CodeScrollController(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 300, + height: 400, + child: CodeEditor( + controller: controller, + scrollController: scrollController, + wordWrap: false, + pinLineNumbers: false, + leadingDivider: const SizedBox(width: 1.0), + indicatorBuilder: (context, c, ch, n) { + return DefaultCodeLineNumber( + controller: c, + notifier: n, + ); + }, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(CodeEditor), findsOneWidget); + expect(find.byType(DefaultCodeLineNumber), findsOneWidget); + + // Initially at offset 0 + expect(scrollController.horizontalScroller.offset, 0.0); + + // Scroll horizontally + scrollController.horizontalScroller.jumpTo(50.0); + await tester.pumpAndSettle(); + + expect(scrollController.horizontalScroller.offset, 50.0); + }); + }); }