This commit is contained in:
LZX committed 2026-09-15 19:17:25 +08:00
1 parent 973d4a6020
commit ce598b2d86
11 files changed
+631 -46

No files matched your search

+4
View File
@@ -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",
+24
View File
@@ -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:
+14
View File
@@ -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';
+12
View File
@@ -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 => '辅助小键盘';
+4
View File
@@ -108,6 +108,10 @@
},
"wordWrap": "自动换行",
"wordWrapSubtitle": "长代码行超出边界时自动折行",
"showLineNumbers": "显示行号",
"showLineNumbersSubtitle": "在代码左侧显示行号与折叠标记",
"pinLineNumbers": "固定行号",
"pinLineNumbersSubtitle": "水平滚动代码时行号固定在左侧",
"virtualKeyboard": "辅助小键盘",
"virtualKeyboardSubtitle": "在代码编辑区底部显示辅助符号与快捷键",
"editVirtualKeyboardConfig": "编辑键盘配置",
+36
View File
@@ -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<void> setShowLineNumbers(bool show) async {
if (_showLineNumbers == show) return;
_showLineNumbers = show;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_keyShowLineNumbers, show);
} catch (_) {}
}
Future<void> 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<void> setEnableVirtualKeyboard(bool enable) =>
setKeyboardEnabled(KeyboardScope.editor, enable);
+50
View File
@@ -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,
+44 -35
View File
@@ -420,11 +420,15 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
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<CodeEditorWidget> {
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<CodeEditorWidget> {
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,
),
],
),
+258 -11
View File
@@ -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(
@@ -497,3 +543,204 @@ class _CodeCursorBlinkController extends ValueNotifier<bool> {
}
}
class _ShiftedViewportOffset extends ViewportOffset {
final ViewportOffset _delegate;
final ValueGetter<double> _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<void> 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<double>? 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<double>? _onWidthMeasured;
double _lastMeasuredWidth = 0.0;
_RenderScrollingGutter({
required ScrollController horizontalScroller,
ValueChanged<double>? 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<double>? 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);
},
);
}
}
@@ -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<CodeEditor> {
cursorWidth: widget.style?.cursorWidth ?? _kDefaultCaretWidth,
showCursorWhenReadOnly: widget.showCursorWhenReadOnly ?? true,
leadingDivider: widget.leadingDivider,
pinLineNumbers: widget.pinLineNumbers,
border: widget.border,
borderRadius: widget.borderRadius,
clipBehavior: widget.clipBehavior,
+180
View File
@@ -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<SettingsProvider>.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<SwitchListTile>(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<SwitchListTile>(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<SwitchListTile>(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);
});
});
}