From a59ebed397d7cf1b6bb46525abffcd7042c88978 Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Thu, 17 Sep 2026 18:41:33 +0800 Subject: [PATCH] 2 --- lib/l10n/app_en.arb | 38 ++- lib/l10n/app_localizations.dart | 72 +++++ lib/l10n/app_localizations_en.dart | 44 +++ lib/l10n/app_localizations_zh.dart | 43 +++ lib/l10n/app_zh.arb | 38 ++- lib/providers/settings_provider.dart | 19 +- lib/services/internal_engine_service.dart | 60 ++++ lib/views/settings_view.dart | 122 ++++++-- lib/views/terminal_view.dart | 92 ++++-- lib/widgets/code_autocomplete_view.dart | 62 +++-- lib/widgets/code_editor_widget.dart | 14 +- .../editor/editor_diagnostic_controller.dart | 18 +- lib/widgets/lsp_quick_fix_dialog.dart | 8 +- test/code_autocomplete_adaptive_test.dart | 176 ++++++++++++ ...gs_reorder_and_container_rebuild_test.dart | 261 ++++++++++++++++++ test/terminal_font_size_and_gesture_test.dart | 6 +- 16 files changed, 988 insertions(+), 85 deletions(-) create mode 100644 test/settings_reorder_and_container_rebuild_test.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 87c0780..c8801e7 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -958,5 +958,41 @@ "installingStatus": "Installing…", "uninstallingStatus": "Uninstalling…", "emptyLspLanguagesTitle": "No code intelligence components installed", - "emptyLspLanguagesSubtitle": "Open any source file to trigger installation on demand, or click \"+\" to add manually" + "emptyLspLanguagesSubtitle": "Open any source file to trigger installation on demand, or click \"+\" to add manually", + "lspQuickFixTitle": "Code Issues & Fixes (Line {line})", + "@lspQuickFixTitle": { + "placeholders": { + "line": { + "type": "int" + } + } + }, + "lspNoFixAvailable": "No automated fixes available", + "diagnosticLinePrefix": "Line {line}: {message}", + "@diagnosticLinePrefix": { + "placeholders": { + "line": { + "type": "int" + }, + "message": { + "type": "String" + } + } + }, + "quickFixButton": "Fix", + "containerSection": "Container", + "destroyAndRebuildContainer": "Destroy and Rebuild Container", + "destroyAndRebuildContainerSubtitle": "Clear installed environments in container and re-extract clean container", + "destroyContainerConfirmTitle": "Destroy and Rebuild Container", + "destroyContainerConfirmMessage": "This will permanently delete all installed packages and configurations in the Ubuntu container (project files will not be affected) and re-extract a clean container system. Continue?", + "destroyContainerButton": "Destroy & Rebuild", + "containerRebuiltSuccess": "Container rebuilt successfully", + "containerRebuildFailed": "Failed to rebuild container: {error}", + "@containerRebuildFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index df004aa..39860e8 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2905,6 +2905,78 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加'** String get emptyLspLanguagesSubtitle; + + /// No description provided for @lspQuickFixTitle. + /// + /// In zh, this message translates to: + /// **'代码问题与修复 (第 {line} 行)'** + String lspQuickFixTitle(int line); + + /// No description provided for @lspNoFixAvailable. + /// + /// In zh, this message translates to: + /// **'当前报错未提供自动修复动作'** + String get lspNoFixAvailable; + + /// No description provided for @diagnosticLinePrefix. + /// + /// In zh, this message translates to: + /// **'行 {line}: {message}'** + String diagnosticLinePrefix(int line, String message); + + /// No description provided for @quickFixButton. + /// + /// In zh, this message translates to: + /// **'修复'** + String get quickFixButton; + + /// No description provided for @containerSection. + /// + /// In zh, this message translates to: + /// **'容器'** + String get containerSection; + + /// No description provided for @destroyAndRebuildContainer. + /// + /// In zh, this message translates to: + /// **'销毁并重建容器'** + String get destroyAndRebuildContainer; + + /// No description provided for @destroyAndRebuildContainerSubtitle. + /// + /// In zh, this message translates to: + /// **'清空容器内已安装环境并重新解压纯净容器'** + String get destroyAndRebuildContainerSubtitle; + + /// No description provided for @destroyContainerConfirmTitle. + /// + /// In zh, this message translates to: + /// **'销毁并重建容器'** + String get destroyContainerConfirmTitle; + + /// No description provided for @destroyContainerConfirmMessage. + /// + /// In zh, this message translates to: + /// **'此操作将永久清空当前 Ubuntu 容器内的所有已安装软件包和环境配置(工程文件不受影响),并重新解压纯净容器系统。确定要继续吗?'** + String get destroyContainerConfirmMessage; + + /// No description provided for @destroyContainerButton. + /// + /// In zh, this message translates to: + /// **'销毁并重建'** + String get destroyContainerButton; + + /// No description provided for @containerRebuiltSuccess. + /// + /// In zh, this message translates to: + /// **'容器已成功重建'** + String get containerRebuiltSuccess; + + /// No description provided for @containerRebuildFailed. + /// + /// In zh, this message translates to: + /// **'容器重建失败: {error}'** + String containerRebuildFailed(String error); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0c54158..673c949 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1756,4 +1756,48 @@ class AppLocalizationsEn extends AppLocalizations { @override String get emptyLspLanguagesSubtitle => 'Open any source file to trigger installation on demand, or click \"+\" to add manually'; + + @override + String lspQuickFixTitle(int line) { + return 'Code Issues & Fixes (Line $line)'; + } + + @override + String get lspNoFixAvailable => 'No automated fixes available'; + + @override + String diagnosticLinePrefix(int line, String message) { + return 'Line $line: $message'; + } + + @override + String get quickFixButton => 'Fix'; + + @override + String get containerSection => 'Container'; + + @override + String get destroyAndRebuildContainer => 'Destroy and Rebuild Container'; + + @override + String get destroyAndRebuildContainerSubtitle => + 'Clear installed environments in container and re-extract clean container'; + + @override + String get destroyContainerConfirmTitle => 'Destroy and Rebuild Container'; + + @override + String get destroyContainerConfirmMessage => + 'This will permanently delete all installed packages and configurations in the Ubuntu container (project files will not be affected) and re-extract a clean container system. Continue?'; + + @override + String get destroyContainerButton => 'Destroy & Rebuild'; + + @override + String get containerRebuiltSuccess => 'Container rebuilt successfully'; + + @override + String containerRebuildFailed(String error) { + return 'Failed to rebuild container: $error'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 1fd7699..396df24 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1698,4 +1698,47 @@ class AppLocalizationsZh extends AppLocalizations { @override String get emptyLspLanguagesSubtitle => '在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加'; + + @override + String lspQuickFixTitle(int line) { + return '代码问题与修复 (第 $line 行)'; + } + + @override + String get lspNoFixAvailable => '当前报错未提供自动修复动作'; + + @override + String diagnosticLinePrefix(int line, String message) { + return '行 $line: $message'; + } + + @override + String get quickFixButton => '修复'; + + @override + String get containerSection => '容器'; + + @override + String get destroyAndRebuildContainer => '销毁并重建容器'; + + @override + String get destroyAndRebuildContainerSubtitle => '清空容器内已安装环境并重新解压纯净容器'; + + @override + String get destroyContainerConfirmTitle => '销毁并重建容器'; + + @override + String get destroyContainerConfirmMessage => + '此操作将永久清空当前 Ubuntu 容器内的所有已安装软件包和环境配置(工程文件不受影响),并重新解压纯净容器系统。确定要继续吗?'; + + @override + String get destroyContainerButton => '销毁并重建'; + + @override + String get containerRebuiltSuccess => '容器已成功重建'; + + @override + String containerRebuildFailed(String error) { + return '容器重建失败: $error'; + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index c02afd2..74d354d 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -958,5 +958,41 @@ "installingStatus": "正在安装…", "uninstallingStatus": "正在卸载…", "emptyLspLanguagesTitle": "暂无已安装的代码智能组件", - "emptyLspLanguagesSubtitle": "在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加" + "emptyLspLanguagesSubtitle": "在编辑器中打开代码文件即可按需触发安装,或点击右上角 \"+\" 手动添加", + "lspQuickFixTitle": "代码问题与修复 (第 {line} 行)", + "@lspQuickFixTitle": { + "placeholders": { + "line": { + "type": "int" + } + } + }, + "lspNoFixAvailable": "当前报错未提供自动修复动作", + "diagnosticLinePrefix": "行 {line}: {message}", + "@diagnosticLinePrefix": { + "placeholders": { + "line": { + "type": "int" + }, + "message": { + "type": "String" + } + } + }, + "quickFixButton": "修复", + "containerSection": "容器", + "destroyAndRebuildContainer": "销毁并重建容器", + "destroyAndRebuildContainerSubtitle": "清空容器内已安装环境并重新解压纯净容器", + "destroyContainerConfirmTitle": "销毁并重建容器", + "destroyContainerConfirmMessage": "此操作将永久清空当前 Ubuntu 容器内的所有已安装软件包和环境配置(工程文件不受影响),并重新解压纯净容器系统。确定要继续吗?", + "destroyContainerButton": "销毁并重建", + "containerRebuiltSuccess": "容器已成功重建", + "containerRebuildFailed": "容器重建失败: {error}", + "@containerRebuildFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart index 5e85d71..5173a24 100644 --- a/lib/providers/settings_provider.dart +++ b/lib/providers/settings_provider.dart @@ -39,6 +39,13 @@ class SettingsProvider extends ChangeNotifier { //语言 static const String _keyAppLocale = 'app_locale'; + /// 字号配置常量(编辑区与终端统一) + static const double minFontSize = 8.0; + static const double maxFontSize = 30.0; + static const double defaultFontSize = 14.0; + static const double defaultTerminalFontSize = 13.0; + static const int fontSizeDivisions = 22; // (maxFontSize - minFontSize).toInt() + ThemeMode _appThemeMode = ThemeMode.system; Color _appThemeColor = Colors.blue; String _uiFontId = 'system_default'; @@ -46,8 +53,8 @@ class SettingsProvider extends ChangeNotifier { String _editorFontId = 'jetbrains_mono'; String _terminalFontId = 'jetbrains_mono'; Color _terminalBackgroundColor = const Color(0xFF1E1E1E); - double _terminalFontSize = 13.0; - double _fontSize = 14.0; + double _terminalFontSize = defaultTerminalFontSize; + double _fontSize = defaultFontSize; int _indentSize = 4; bool _wordWrap = false; bool _showLineNumbers = true; @@ -200,7 +207,7 @@ class SettingsProvider extends ChangeNotifier { final savedFontSize = prefs.getDouble(_keyEditorFontSize); - if(savedFontSize != null && savedFontSize >= 10 && savedFontSize <= 32) { + if(savedFontSize != null && savedFontSize >= minFontSize && savedFontSize <= maxFontSize) { _fontSize = savedFontSize; } @@ -282,7 +289,7 @@ class SettingsProvider extends ChangeNotifier { final savedTerminalFontSize = prefs.getDouble(_keyTerminalFontSize); if (savedTerminalFontSize != null) { - _terminalFontSize = savedTerminalFontSize.clamp(8.0, 32.0); + _terminalFontSize = savedTerminalFontSize.clamp(minFontSize, maxFontSize); } //设置项目配置 @@ -341,7 +348,7 @@ class SettingsProvider extends ChangeNotifier { } Future setFontSize(double size) async { - final clamped = size.clamp(10.0, 30.0); + final clamped = size.clamp(minFontSize, maxFontSize); if(_fontSize == clamped) return; _fontSize = clamped; notifyListeners(); @@ -461,7 +468,7 @@ class SettingsProvider extends ChangeNotifier { /// 设置终端字体大小 Future setTerminalFontSize(double size) async { - final clamped = size.clamp(8.0, 32.0); + final clamped = size.clamp(minFontSize, maxFontSize); if (_terminalFontSize == clamped) return; _terminalFontSize = clamped; notifyListeners(); diff --git a/lib/services/internal_engine_service.dart b/lib/services/internal_engine_service.dart index e38ca1d..5ebead8 100644 --- a/lib/services/internal_engine_service.dart +++ b/lib/services/internal_engine_service.dart @@ -2,12 +2,15 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; import '../l10n/app_localizations.dart'; import '../models/distro_manifest.dart'; +import '../providers/terminal_provider.dart'; import '../widgets/distro_extract_dialog.dart'; import 'distro_installer.dart'; import 'distro_manager.dart'; +import 'lsp/lsp_manager.dart'; /// 代码智能与运行时引擎服务(基于统一主系统 Ubuntu 24.04) class InternalEngineService extends ChangeNotifier { @@ -85,6 +88,63 @@ class InternalEngineService extends ChangeNotifier { } } + /// 彻底销毁并重建内置 Ubuntu 容器 + Future rebuildEngine(BuildContext context) async { + _isChecking = true; + notifyListeners(); + + TerminalProvider? terminalProvider; + try { + terminalProvider = Provider.of(context, listen: false); + } catch (_) {} + + try { + // 1. 关闭所有运行中的后台语言服务会话 + await LspManager.instance.disposeAll(); + + // 2. 清理终端中属于 ubuntu 的活跃会话 + terminalProvider?.removeSessionsForDistro(DistroRepository.defaultSystemName); + + // 3. 彻底删除 ubuntu 容器目录 + if (customEngineDir != null) { + if (customEngineDir!.existsSync()) { + customEngineDir!.deleteSync(recursive: true); + } + } else { + await DistroManager().deleteSystem(DistroRepository.defaultSystemName); + } + + if (!context.mounted) { + _isChecking = false; + notifyListeners(); + return false; + } + + final l10n = AppLocalizations.of(context); + + // 4. 唤起解压弹窗重新从内置资源解压 Ubuntu + final success = await DistroExtractDialog.show( + context: context, + systemName: l10n?.internalEngineTitle ?? '代码运行与智能补全引擎 (Ubuntu)', + task: (onProgress, isCancelled) async { + await extractEngine( + onProgress: onProgress, + isCancelled: isCancelled, + ); + }, + ); + + _isChecking = false; + notifyListeners(); + return success; + } catch (e) { + _isChecking = false; + notifyListeners(); + debugPrint('重建 Ubuntu 引擎失败: $e'); + return false; + } + } + /// 解压 Asset 中的 Ubuntu 到主系统目录 Future extractEngine({ InstallProgressCallback? onProgress, diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index a27fd70..6c2cc52 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -5,6 +5,7 @@ import 'package:code_editor/models/virtual_keyboard_config.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../services/internal_engine_service.dart'; import '../widgets/color_palette_dialog.dart'; import 'code_completion_management_view.dart'; import 'virtual_keyboard_config_view.dart'; @@ -50,8 +51,8 @@ class SettingsView extends StatelessWidget { // ============================== _buildSectionHeader(context, l10n.editorSection), _buildEditorThemeTile(context, provider, l10n), - _buildFontSizeTile(context, provider, l10n), _buildEditorFontTile(context, provider), + _buildFontSizeTile(context, provider, l10n), _buildIndentSizeTile(context, provider, l10n), _buildWordWrapTile(context, provider, l10n), _buildShowLineNumbersTile(context, provider, l10n), @@ -67,10 +68,10 @@ class SettingsView extends StatelessWidget { // ============================== _buildSectionHeader(context, l10n.terminal), _buildTerminalBackgroundTile(context, provider, l10n), - _buildTerminalVirtualKeyboardTile(context, provider, l10n), - _buildTerminalVirtualKeyboardConfigTile(context, provider, l10n), _buildTerminalFontTile(context, provider), _buildTerminalFontSizeTile(context, provider, l10n), + _buildTerminalVirtualKeyboardTile(context, provider, l10n), + _buildTerminalVirtualKeyboardConfigTile(context, provider, l10n), const Divider(height: 32, indent: 16, endIndent: 16), @@ -83,7 +84,15 @@ class SettingsView extends StatelessWidget { const Divider(height: 32, indent: 16, endIndent: 16), // ============================== - // 5. 语言分组 (Language) + // 5. 容器分组 (Container) + // ============================== + _buildSectionHeader(context, l10n.containerSection), + _buildRebuildContainerTile(context, l10n), + + const Divider(height: 32, indent: 16, endIndent: 16), + + // ============================== + // 6. 语言分组 (Language) // ============================== _buildSectionHeader(context, l10n.languageSection), _buildLanguageTile(context, provider, l10n), @@ -293,7 +302,7 @@ class SettingsView extends StatelessWidget { icon: const Icon(Icons.remove, size: 18), visualDensity: VisualDensity.compact, tooltip: l10n.decreaseFontSize, - onPressed: provider.terminalFontSize > 8.0 + onPressed: provider.terminalFontSize > SettingsProvider.minFontSize ? () => provider.setTerminalFontSize(provider.terminalFontSize - 1) : null, ), @@ -305,7 +314,7 @@ class SettingsView extends StatelessWidget { icon: const Icon(Icons.add, size: 18), visualDensity: VisualDensity.compact, tooltip: l10n.increaseFontSize, - onPressed: provider.terminalFontSize < 32.0 + onPressed: provider.terminalFontSize < SettingsProvider.maxFontSize ? () => provider.setTerminalFontSize(provider.terminalFontSize + 1) : null, ), @@ -342,10 +351,10 @@ class SettingsView extends StatelessWidget { ), const SizedBox(height: 16), Slider( - value: tempSize.clamp(8.0, 32.0), - min: 8.0, - max: 32.0, - divisions: 24, + value: tempSize.clamp(SettingsProvider.minFontSize, SettingsProvider.maxFontSize), + min: SettingsProvider.minFontSize, + max: SettingsProvider.maxFontSize, + divisions: SettingsProvider.fontSizeDivisions, label: '${tempSize.toInt()}', onChanged: (val) { setDialogState(() { @@ -692,7 +701,7 @@ class SettingsView extends StatelessWidget { icon: const Icon(Icons.remove, size: 18), visualDensity: VisualDensity.compact, tooltip: l10n.decreaseFontSize, - onPressed: provider.fontSize > 10.0 + onPressed: provider.fontSize > SettingsProvider.minFontSize ? () => provider.setFontSize(provider.fontSize - 1) : null, ), @@ -704,7 +713,7 @@ class SettingsView extends StatelessWidget { icon: const Icon(Icons.add, size: 18), visualDensity: VisualDensity.compact, tooltip: l10n.increaseFontSize, - onPressed: provider.fontSize < 30.0 + onPressed: provider.fontSize < SettingsProvider.maxFontSize ? () => provider.setFontSize(provider.fontSize + 1) : null, ), @@ -804,10 +813,10 @@ class SettingsView extends StatelessWidget { ), const SizedBox(height: 16), Slider( - value: tempSize.clamp(10.0, 30.0), - min: 10.0, - max: 30.0, - divisions: 20, + value: tempSize.clamp(SettingsProvider.minFontSize, SettingsProvider.maxFontSize), + min: SettingsProvider.minFontSize, + max: SettingsProvider.maxFontSize, + divisions: SettingsProvider.fontSizeDivisions, label: '${tempSize.toInt()}', onChanged: (val) { setDialogState(() { @@ -1130,4 +1139,85 @@ class SettingsView extends StatelessWidget { }, ); } + + /// 容器:销毁并重建容器条目 + Widget _buildRebuildContainerTile( + BuildContext context, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + final dangerColor = theme.colorScheme.error; + + return ListTile( + leading: Icon(Icons.delete_forever_outlined, color: dangerColor), + title: Text( + l10n.destroyAndRebuildContainer, + style: TextStyle( + color: dangerColor, + fontWeight: FontWeight.w600, + ), + ), + subtitle: Text( + l10n.destroyAndRebuildContainerSubtitle, + style: TextStyle( + color: dangerColor.withValues(alpha: 0.8), + fontSize: 12, + ), + ), + onTap: () { + _showDestroyContainerDialog(context, l10n); + }, + ); + } + + void _showDestroyContainerDialog( + BuildContext context, + AppLocalizations l10n, + ) async { + final confirmed = await showDialog( + context: context, + builder: (dialogContext) { + final dialogTheme = Theme.of(dialogContext); + return AlertDialog( + title: Row( + children: [ + Icon(Icons.warning_amber_rounded, color: dialogTheme.colorScheme.error), + const SizedBox(width: 8), + Expanded(child: Text(l10n.destroyContainerConfirmTitle)), + ], + ), + content: Text(l10n.destroyContainerConfirmMessage), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(l10n.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: dialogTheme.colorScheme.error, + foregroundColor: dialogTheme.colorScheme.onError, + ), + onPressed: () => Navigator.of(dialogContext).pop(true), + child: Text(l10n.destroyContainerButton), + ), + ], + ); + }, + ); + + if (confirmed == true && context.mounted) { + final success = await InternalEngineService.instance.rebuildEngine(context); + if (context.mounted) { + if (success) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(l10n.containerRebuiltSuccess)), + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(l10n.containerRebuildFailed(''))), + ); + } + } + } + } } diff --git a/lib/views/terminal_view.dart b/lib/views/terminal_view.dart index 0f34613..9748ea9 100644 --- a/lib/views/terminal_view.dart +++ b/lib/views/terminal_view.dart @@ -249,7 +249,7 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> { final points = _pointerPositions.values.toList(); final currentDistance = (points[0] - points[1]).distance; final scale = currentDistance / _initialPinchDistance!; - final rawFontSize = (_initialPinchFontSize! * scale).clamp(8.0, 32.0); + final rawFontSize = (_initialPinchFontSize! * scale).clamp(SettingsProvider.minFontSize, SettingsProvider.maxFontSize); final newFontSize = (rawFontSize * 10).round() / 10.0; final fontScale = newFontSize / _initialPinchFontSize!; @@ -367,31 +367,73 @@ class _TerminalSessionBodyState extends State<_TerminalSessionBody> { child: Column( children: [ Expanded( - child: Listener( - behavior: HitTestBehavior.translucent, - onPointerDown: (e) => _handlePointerDown(e, currentBaseFontSize), - onPointerMove: _handlePointerMove, - onPointerUp: _handlePointerUp, - onPointerCancel: _handlePointerCancel, - child: TerminalSelectionOverlay( - terminal: session.terminal, - controller: _terminalController, - terminalViewKey: _terminalViewKey, - scrollController: _terminalScrollController, - focusNode: session.focusNode, - child: xterm.TerminalView( - session.terminal, - key: _terminalViewKey, - controller: _terminalController, - scrollController: _terminalScrollController, - focusNode: session.focusNode, - autofocus: true, - theme: terminalThemeWithBackground(backgroundColor), - textStyle: terminalStyle, - cursorType: xterm.TerminalCursorType.block, - padding: const EdgeInsets.fromLTRB(10.0, 8.0, 10.0, 20.0), + child: Stack( + children: [ + Positioned.fill( + child: Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: (e) => _handlePointerDown(e, currentBaseFontSize), + onPointerMove: _handlePointerMove, + onPointerUp: _handlePointerUp, + onPointerCancel: _handlePointerCancel, + child: TerminalSelectionOverlay( + terminal: session.terminal, + controller: _terminalController, + terminalViewKey: _terminalViewKey, + scrollController: _terminalScrollController, + focusNode: session.focusNode, + child: xterm.TerminalView( + session.terminal, + key: _terminalViewKey, + controller: _terminalController, + scrollController: _terminalScrollController, + focusNode: session.focusNode, + autofocus: true, + theme: terminalThemeWithBackground(backgroundColor), + textStyle: terminalStyle, + cursorType: xterm.TerminalCursorType.block, + padding: const EdgeInsets.fromLTRB(10.0, 8.0, 10.0, 20.0), + ), + ), + ), ), - ), + // 双指缩放实时字号悬浮胶囊提示 + if (_isPinching && _activeZoomFontSize != null) + Positioned( + top: 16, + left: 0, + right: 0, + child: Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6), + decoration: BoxDecoration( + color: backgroundColor.computeLuminance() > 0.5 + ? Colors.black.withValues(alpha: 0.75) + : Colors.white.withValues(alpha: 0.85), + borderRadius: BorderRadius.circular(16), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.2), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: Text( + '${_activeZoomFontSize!.round()} pt', + style: TextStyle( + color: backgroundColor.computeLuminance() > 0.5 + ? Colors.white + : Colors.black87, + fontSize: 13, + fontWeight: FontWeight.w600, + letterSpacing: 0.3, + ), + ), + ), + ), + ), + ], ), ), if (keyboardEnabled && keyboardConfig != null && keyboardConfig.hasKeys) diff --git a/lib/widgets/code_autocomplete_view.dart b/lib/widgets/code_autocomplete_view.dart index 900211a..75e7312 100644 --- a/lib/widgets/code_autocomplete_view.dart +++ b/lib/widgets/code_autocomplete_view.dart @@ -37,6 +37,7 @@ class CodeAutocompleteView extends StatefulWidget implements PreferredSizeWidget class _CodeAutocompleteViewState extends State { final ScrollController _scrollController = ScrollController(); + final ScrollController _horizontalScrollController = ScrollController(); @override void initState() { @@ -57,6 +58,7 @@ class _CodeAutocompleteViewState extends State { void dispose() { widget.notifier.removeListener(_handleValueChanged); _scrollController.dispose(); + _horizontalScrollController.dispose(); super.dispose(); } @@ -74,6 +76,9 @@ class _CodeAutocompleteViewState extends State { _scrollController.jumpTo(math.max(0.0, targetOffset - viewportDimension + CodeAutocompleteView.itemHeight + CodeAutocompleteView.verticalPadding)); } } + if (value.index == 0 && _horizontalScrollController.hasClients) { + _horizontalScrollController.jumpTo(0.0); + } setState(() {}); } @@ -103,17 +108,39 @@ class _CodeAutocompleteViewState extends State { ], ), clipBehavior: Clip.antiAlias, - child: ListView.builder( + child: Scrollbar( controller: _scrollController, - physics: const ClampingScrollPhysics(), - padding: const EdgeInsets.symmetric(vertical: 4.0), - itemCount: prompts.length, - itemExtent: CodeAutocompleteView.itemHeight, - itemBuilder: (context, index) { - final prompt = prompts[index]; - final isSelected = index == value.index; - return _buildPromptItem(context, prompt, isSelected, index, theme, isDark); - }, + notificationPredicate: (notification) => notification.metrics.axis == Axis.vertical, + child: Scrollbar( + controller: _horizontalScrollController, + notificationPredicate: (notification) => notification.metrics.axis == Axis.horizontal, + child: SingleChildScrollView( + controller: _horizontalScrollController, + scrollDirection: Axis.horizontal, + physics: const ClampingScrollPhysics(), + child: ConstrainedBox( + constraints: BoxConstraints( + minWidth: math.max(0.0, widget.width - 2.0), + ), + child: IntrinsicWidth( + child: SingleChildScrollView( + controller: _scrollController, + scrollDirection: Axis.vertical, + physics: const ClampingScrollPhysics(), + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + for (int index = 0; index < prompts.length; index++) + _buildPromptItem(context, prompts[index], index == value.index, index, theme, isDark), + ], + ), + ), + ), + ), + ), + ), ), ); } @@ -144,13 +171,13 @@ class _CodeAutocompleteViewState extends State { color: isSelected ? highlightBg : defaultBg, padding: const EdgeInsets.symmetric(horizontal: 10.0), child: Row( + mainAxisSize: MainAxisSize.min, children: [ _buildKindIcon(kind, theme), const SizedBox(width: 8.0), - Expanded( - child: _buildHighlightedText(prompt.word, matchedIndices, theme, isSelected), - ), - if (typeText.isNotEmpty) + _buildHighlightedText(prompt.word, matchedIndices, theme, isSelected), + if (typeText.isNotEmpty) ...[ + const SizedBox(width: 8.0), Text( typeText, style: TextStyle( @@ -159,8 +186,9 @@ class _CodeAutocompleteViewState extends State { fontFamily: 'monospace', ), maxLines: 1, - overflow: TextOverflow.ellipsis, + softWrap: false, ), + ], ], ), ), @@ -216,7 +244,7 @@ class _CodeAutocompleteViewState extends State { fontFamily: 'monospace', ), maxLines: 1, - overflow: TextOverflow.ellipsis, + softWrap: false, ); } @@ -246,7 +274,7 @@ class _CodeAutocompleteViewState extends State { children: spans, ), maxLines: 1, - overflow: TextOverflow.ellipsis, + softWrap: false, ); } } diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index eb0ceab..b3b47b1 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -239,9 +239,9 @@ class _CodeEditorWidgetState extends State { final currentDistance = (p1 - p2).distance; final rawScale = currentDistance / _initialPinchDistance!; - // 边界弹性阻尼(10.0 ~ 30.0) - final minScale = 10.0 / _initialPinchFontSize!; - final maxScale = 30.0 / _initialPinchFontSize!; + // 边界弹性阻尼(SettingsProvider.minFontSize ~ SettingsProvider.maxFontSize) + final minScale = SettingsProvider.minFontSize / _initialPinchFontSize!; + final maxScale = SettingsProvider.maxFontSize / _initialPinchFontSize!; final clampedScale = rawScale.clamp(minScale * 0.9, maxScale * 1.1); final currentGlobalFocal = (p1 + p2) / 2; @@ -252,7 +252,7 @@ class _CodeEditorWidgetState extends State { _currentLocalFocal = currentLocalFocal; final continuousFontSize = ((_initialPinchFontSize! * clampedScale) * 10).round() / 10.0; - final newFontSize = continuousFontSize.clamp(10.0, 30.0); + final newFontSize = continuousFontSize.clamp(SettingsProvider.minFontSize, SettingsProvider.maxFontSize); AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono; try { @@ -331,7 +331,7 @@ class _CodeEditorWidgetState extends State { if (finalSize != null && initialFontSize != null && initialLocalFocal != null && currentLocalFocal != null) { // 手势释放后定格为整数(如 16.0),持久化到用户设置 - final double targetFontSize = finalSize.clamp(10.0, 30.0).roundToDouble(); + final double targetFontSize = finalSize.clamp(SettingsProvider.minFontSize, SettingsProvider.maxFontSize).roundToDouble(); AppFontItem activeEditorFont = AppFonts.editorJetBrainsMono; try { @@ -871,14 +871,14 @@ class _CodeEditorWidgetState extends State { }, textStyle: TextStyle( color: activeTheme.gutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontSize: (displayFontSize - 1).clamp(SettingsProvider.minFontSize - 1.0, SettingsProvider.maxFontSize), fontFamily: activeEditorFont.fontFamily, fontFamilyFallback: activeEditorFont.fallback, height: 1.4, ), focusedTextStyle: TextStyle( color: activeTheme.focusedGutterTextColor, - fontSize: (displayFontSize - 1).clamp(9.0, 30.0), + fontSize: (displayFontSize - 1).clamp(SettingsProvider.minFontSize - 1.0, SettingsProvider.maxFontSize), fontWeight: FontWeight.bold, fontFamily: activeEditorFont.fontFamily, fontFamilyFallback: activeEditorFont.fallback, diff --git a/lib/widgets/editor/editor_diagnostic_controller.dart b/lib/widgets/editor/editor_diagnostic_controller.dart index dde964c..630d701 100644 --- a/lib/widgets/editor/editor_diagnostic_controller.dart +++ b/lib/widgets/editor/editor_diagnostic_controller.dart @@ -1,6 +1,7 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:re_editor/re_editor.dart'; +import '../../l10n/app_localizations.dart'; import '../../services/lsp/lsp_diagnostics_store.dart'; import '../../services/lsp/lsp_protocol.dart'; import '../lsp_quick_fix_dialog.dart'; @@ -117,6 +118,11 @@ class EditorDiagnosticController { final isErr = diags.any((d) => d.severity == LspDiagnosticSeverity.error); final color = isErr ? Colors.redAccent : Colors.amber; final icon = isErr ? Icons.error_outline : Icons.warning_amber_outlined; + final l10n = AppLocalizations.of(context); + final displayText = l10n != null + ? l10n.diagnosticLinePrefix(lineIndex + 1, first.message) + : 'Line ${lineIndex + 1}: ${first.message}'; + final fixButtonText = l10n?.quickFixButton ?? 'Fix'; return Material( color: Theme.of(context).colorScheme.surfaceContainerHighest, @@ -146,7 +152,7 @@ class EditorDiagnosticController { const SizedBox(width: 8), Expanded( child: Text( - '行 ${lineIndex + 1}: ${first.message}', + displayText, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( @@ -164,12 +170,12 @@ class EditorDiagnosticController { ), child: Row( mainAxisSize: MainAxisSize.min, - children: const [ - Icon(Icons.lightbulb, size: 12, color: Colors.amber), - SizedBox(width: 2), + children: [ + const Icon(Icons.lightbulb, size: 12, color: Colors.amber), + const SizedBox(width: 2), Text( - '修复', - style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Colors.amber), + fixButtonText, + style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Colors.amber), ), ], ), diff --git a/lib/widgets/lsp_quick_fix_dialog.dart b/lib/widgets/lsp_quick_fix_dialog.dart index 2e7af73..c12a7e6 100644 --- a/lib/widgets/lsp_quick_fix_dialog.dart +++ b/lib/widgets/lsp_quick_fix_dialog.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:re_editor/re_editor.dart'; +import '../l10n/app_localizations.dart'; import '../services/lsp/lsp_manager.dart'; import '../services/lsp/lsp_protocol.dart'; import '../services/lsp/lsp_workspace_edit_applier.dart'; @@ -38,6 +39,7 @@ class LspQuickFixDialog { borderRadius: BorderRadius.vertical(top: Radius.circular(16)), ), builder: (ctx) { + final l10n = AppLocalizations.of(ctx) ?? AppLocalizations.of(context)!; return SafeArea( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), @@ -61,7 +63,7 @@ class LspQuickFixDialog { const Icon(Icons.lightbulb, color: Colors.amber, size: 20), const SizedBox(width: 8), Text( - '代码问题与修复 (第 ${lineIndex + 1} 行)', + l10n.lspQuickFixTitle(lineIndex + 1), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), ), ], @@ -114,7 +116,7 @@ class LspQuickFixDialog { ), const SizedBox(width: 8), Text( - '当前报错未提供自动修复动作', + l10n.lspNoFixAvailable, style: TextStyle( fontSize: 13, color: Theme.of(context).colorScheme.onSurfaceVariant, @@ -129,7 +131,7 @@ class LspQuickFixDialog { contentPadding: EdgeInsets.zero, leading: const Icon(Icons.auto_fix_high, color: Colors.blueAccent), title: Text(act.title, style: const TextStyle(fontSize: 14)), - trailing: act.isPreferred ? const Chip(label: Text('推荐', style: TextStyle(fontSize: 11))) : null, + trailing: act.isPreferred ? Chip(label: Text(l10n.recommended, style: const TextStyle(fontSize: 11))) : null, onTap: () { Navigator.pop(ctx); if (act.edit != null) { diff --git a/test/code_autocomplete_adaptive_test.dart b/test/code_autocomplete_adaptive_test.dart index 6e284ee..638f51b 100644 --- a/test/code_autocomplete_adaptive_test.dart +++ b/test/code_autocomplete_adaptive_test.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:code_editor/widgets/code_autocomplete_view.dart'; +import 'package:code_editor/services/code_completion/smart_prompts_builder.dart'; import 'package:re_editor/re_editor.dart'; void main() { @@ -202,5 +203,180 @@ void main() { await tester.pump(const Duration(milliseconds: 600)); controller.dispose(); }); + + testWidgets('CodeAutocompleteView supports bidirectional scrolling without horizontal truncation', (tester) async { + const longWord = 'extremelyLongMethodNameWithManyArgumentsAndParameters(int foo, String bar, double baz, List> nestedOptions)'; + final notifier = ValueNotifier( + CodeAutocompleteEditingValue( + input: '', + prompts: [ + const CodeKeywordPrompt(word: 'short_item'), + const CodeKeywordPrompt(word: longWord), + for (int i = 0; i < 8; i++) CodeKeywordPrompt(word: 'vertical_item_$i'), + ], + index: 0, + ), + ); + + String? selectedWord; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: SizedBox( + width: 270.0, + height: 150.0, + child: CodeAutocompleteView( + notifier: notifier, + onSelected: (result) { + selectedWord = (result as dynamic).word as String?; + }, + ), + ), + ), + ), + ), + ); + + // Verify both horizontal and vertical SingleChildScrollViews are present + final scrollViews = find.byType(SingleChildScrollView); + expect(scrollViews, findsNWidgets(2)); + + // Drag horizontally to test horizontal scrolling + final horizontalFinder = find.byWidgetPredicate( + (w) => w is SingleChildScrollView && w.scrollDirection == Axis.horizontal, + ); + expect(horizontalFinder, findsOneWidget); + + await tester.drag(horizontalFinder, const Offset(-120.0, 0.0)); + await tester.pumpAndSettle(); + + final SingleChildScrollView hView = tester.widget(horizontalFinder); + expect(hView.controller!.offset, greaterThan(0.0)); + + // Drag vertically at visible center to test vertical scrolling + final verticalFinder = find.byWidgetPredicate( + (w) => w is SingleChildScrollView && w.scrollDirection == Axis.vertical, + ); + expect(verticalFinder, findsOneWidget); + + await tester.drag(find.byType(CodeAutocompleteView), const Offset(0.0, -100.0)); + await tester.pumpAndSettle(); + + final SingleChildScrollView vView = tester.widget(verticalFinder); + expect(vView.controller!.offset, greaterThan(0.0)); + + // Tap on a visible item after scrolling + expect(find.text('vertical_item_3'), findsOneWidget); + await tester.tap(find.text('vertical_item_3')); + await tester.pump(); + + expect(selectedWord, equals('vertical_item_3')); + + await tester.pumpWidget(const SizedBox()); + notifier.dispose(); + }); + + testWidgets('CodeAutocompleteView renders SmartPrompt with long type without ellipsis and allows horizontal scrolling', (tester) async { + final notifier = ValueNotifier( + CodeAutocompleteEditingValue( + input: '', + prompts: [ + SmartPrompt( + word: 'veryLongAsyncMethodWithArguments', + type: 'Future>>', + kind: SmartPromptKind.function, + ), + ], + index: 0, + ), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: SizedBox( + width: 270.0, + height: 100.0, + child: CodeAutocompleteView( + notifier: notifier, + onSelected: (_) {}, + ), + ), + ), + ), + ), + ); + + final horizontalFinder = find.byWidgetPredicate( + (w) => w is SingleChildScrollView && w.scrollDirection == Axis.horizontal, + ); + final SingleChildScrollView hView = tester.widget(horizontalFinder); + expect(hView.controller!.offset, equals(0.0)); + + // Scroll to the right + await tester.drag(find.byType(CodeAutocompleteView), const Offset(-200.0, 0.0)); + await tester.pumpAndSettle(); + + expect(hView.controller!.offset, greaterThan(0.0)); + + await tester.pumpWidget(const SizedBox()); + notifier.dispose(); + }); + + testWidgets('CodeAutocompleteView places typeText immediately adjacent to word without pushing to far right', (tester) async { + final notifier = ValueNotifier( + CodeAutocompleteEditingValue( + input: '', + prompts: [ + SmartPrompt( + word: 'foo', + type: 'int', + kind: SmartPromptKind.field, + ), + SmartPrompt( + word: 'extremelyLongMethodNameThatExpandsTheMenuWidthSignificantly(...)', + type: 'void', + kind: SmartPromptKind.function, + ), + ], + index: 0, + ), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: SizedBox( + width: 270.0, + height: 100.0, + child: CodeAutocompleteView( + notifier: notifier, + onSelected: (_) {}, + ), + ), + ), + ), + ), + ); + + final fooFinder = find.text('foo'); + final intFinder = find.text('int'); + expect(fooFinder, findsOneWidget); + expect(intFinder, findsOneWidget); + + final fooTopRight = tester.getTopRight(fooFinder); + final intTopLeft = tester.getTopLeft(intFinder); + + // The gap between 'foo' and 'int' should be exactly 8.0 (adjacent), not pushed hundreds of pixels away + final gap = intTopLeft.dx - fooTopRight.dx; + expect(gap, closeTo(8.0, 1.0)); + + await tester.pumpWidget(const SizedBox()); + notifier.dispose(); + }); }); } diff --git a/test/settings_reorder_and_container_rebuild_test.dart b/test/settings_reorder_and_container_rebuild_test.dart new file mode 100644 index 0000000..2cedb6b --- /dev/null +++ b/test/settings_reorder_and_container_rebuild_test.dart @@ -0,0 +1,261 @@ +import 'dart:io'; +import 'dart:ui'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/editor_tab_item.dart'; +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/providers/terminal_provider.dart'; +import 'package:code_editor/views/settings_view.dart'; +import 'package:code_editor/views/terminal_view.dart'; +import 'package:code_editor/widgets/code_editor_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:re_editor/re_editor.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:xterm/xterm.dart' as xterm; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('Settings Reorder, Font Size 8-30, Container Rebuild & Terminal HUD Tests', () { + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + test('SettingsProvider: fontSize clamped to 8.0 - 30.0 using constants', () async { + final provider = SettingsProvider(); + await provider.init(); + + expect(SettingsProvider.minFontSize, 8.0); + expect(SettingsProvider.maxFontSize, 30.0); + + // Lower clamp + await provider.setFontSize(4.0); + expect(provider.fontSize, SettingsProvider.minFontSize); + + // Upper clamp + await provider.setFontSize(35.0); + expect(provider.fontSize, SettingsProvider.maxFontSize); + + // Valid value + await provider.setFontSize(14.0); + expect(provider.fontSize, 14.0); + }); + + test('SettingsProvider: terminalFontSize clamped to 8.0 - 30.0 using constants', () async { + final provider = SettingsProvider(); + await provider.init(); + + // Lower clamp + await provider.setTerminalFontSize(6.0); + expect(provider.terminalFontSize, SettingsProvider.minFontSize); + + // Upper clamp + await provider.setTerminalFontSize(32.0); + expect(provider.terminalFontSize, SettingsProvider.maxFontSize); + + // Valid value + await provider.setTerminalFontSize(16.0); + expect(provider.terminalFontSize, 16.0); + }); + + test('Localization: all newly added keys exist in both zh and en', () { + final zh = lookupAppLocalizations(const Locale('zh')); + final en = lookupAppLocalizations(const Locale('en')); + + expect(zh.lspQuickFixTitle(457), '代码问题与修复 (第 457 行)'); + expect(en.lspQuickFixTitle(457), 'Code Issues & Fixes (Line 457)'); + + expect(zh.lspNoFixAvailable, '当前报错未提供自动修复动作'); + expect(en.lspNoFixAvailable, 'No automated fixes available'); + + expect(zh.diagnosticLinePrefix(10, 'error'), '行 10: error'); + expect(en.diagnosticLinePrefix(10, 'error'), 'Line 10: error'); + + expect(zh.quickFixButton, '修复'); + expect(en.quickFixButton, 'Fix'); + + expect(zh.containerSection, '容器'); + expect(en.containerSection, 'Container'); + + expect(zh.destroyAndRebuildContainer, '销毁并重建容器'); + expect(en.destroyAndRebuildContainer, 'Destroy and Rebuild Container'); + + expect(zh.destroyContainerConfirmTitle, '销毁并重建容器'); + expect(en.destroyContainerConfirmTitle, 'Destroy and Rebuild Container'); + + expect(zh.destroyContainerButton, '销毁并重建'); + expect(en.destroyContainerButton, 'Destroy & Rebuild'); + + expect(zh.containerRebuiltSuccess, '容器已成功重建'); + expect(en.containerRebuiltSuccess, 'Container rebuilt successfully'); + }); + + testWidgets('SettingsView: renders container section and destroy & rebuild tile in red', (tester) async { + final settings = SettingsProvider(); + await settings.init(); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: settings, + child: const MaterialApp( + locale: Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: SettingsView(), + ), + ), + ); + await tester.pumpAndSettle(); + + // Scroll down to container section + final containerTileFinder = find.widgetWithText(ListTile, '销毁并重建容器'); + await tester.scrollUntilVisible(containerTileFinder, 200); + await tester.pumpAndSettle(); + + expect(containerTileFinder, findsOneWidget); + + // Verify the title text is styled in danger red (colorScheme.error) + final textWidget = tester.widget(find.descendant( + of: containerTileFinder, + matching: find.text('销毁并重建容器'), + )); + expect(textWidget.style?.color, isNotNull); + + // Tap tile and verify AlertDialog opens + await tester.tap(containerTileFinder); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('此操作将永久清空当前 Ubuntu 容器内的所有已安装软件包和环境配置(工程文件不受影响),并重新解压纯净容器系统。确定要继续吗?'), findsOneWidget); + expect(find.text('销毁并重建'), findsOneWidget); + expect(find.text('取消'), findsOneWidget); + + // Tap Cancel + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('TerminalView: shows floating HUD capsule when pinching', (tester) async { + final settings = SettingsProvider(); + await settings.init(); + await settings.setTerminalFontSize(14.0); + + final terminalProvider = TerminalProvider(); + terminalProvider.createSession( + name: 'hud-session', + autoStartProcess: false, + activate: true, + ); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: terminalProvider), + ], + child: const MaterialApp( + locale: Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox( + width: 600, + height: 800, + child: TerminalView(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final center = tester.getCenter(find.byType(xterm.TerminalView)); + + // No HUD initially + expect(find.textContaining('pt'), findsNothing); + + // Pinch zoom in + final touch1 = await tester.startGesture(center - const Offset(30, 0), kind: PointerDeviceKind.touch, pointer: 201); + final touch2 = await tester.startGesture(center + const Offset(30, 0), kind: PointerDeviceKind.touch, pointer: 202); + await tester.pump(); + + await touch1.moveTo(center - const Offset(70, 0)); + await touch2.moveTo(center + const Offset(70, 0)); + await tester.pump(); + + // Floating HUD capsule is now visible with pt font size + expect(find.textContaining('pt'), findsOneWidget); + + // Release touch + await touch1.up(); + await touch2.up(); + await tester.pumpAndSettle(); + + // HUD disappears after pinch completes + expect(find.textContaining('pt'), findsNothing); + }); + + testWidgets('CodeEditorWidget: pinch zoom out scales down to 8.0', (tester) async { + final tempDir = Directory.systemTemp.createTempSync('editor_zoom_min_test'); + final testFile = File('${tempDir.path}/test.dart')..writeAsStringSync('void main() {}'); + + final settingsProvider = SettingsProvider(); + await settingsProvider.init(); + await settingsProvider.setFontSize(14.0); + + final tabProvider = TabProvider(); + await tabProvider.init(); + tabProvider.openTabs.add( + EditorTabItem( + path: testFile.path, + content: 'void main() {}', + originalContent: 'void main() {}', + isLoaded: true, + isModified: false, + ), + ); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: tabProvider), + ], + child: MaterialApp( + home: Scaffold( + body: CodeEditorWidget( + rootPath: tempDir.path, + filePath: testFile.path, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(CodeEditor), findsOneWidget); + expect(settingsProvider.fontSize, 14.0); + + // Pinch zoom out: start far apart (100px) and move close together (20px) + final gesture1 = await tester.createGesture(); + final gesture2 = await tester.createGesture(); + + await gesture1.down(const Offset(200, 250)); + await gesture2.down(const Offset(200, 350)); + await tester.pump(); + + await gesture2.moveTo(const Offset(200, 270)); // distance goes from 100 to 20 -> scale 0.2 + await tester.pump(); + + await gesture1.up(); + await gesture2.up(); + await tester.pumpAndSettle(); + + // Should be clamped to minFontSize (8.0), NOT 10.0 + expect(settingsProvider.fontSize, 8.0); + }); + }); +} diff --git a/test/terminal_font_size_and_gesture_test.dart b/test/terminal_font_size_and_gesture_test.dart index 0827da6..3257a76 100644 --- a/test/terminal_font_size_and_gesture_test.dart +++ b/test/terminal_font_size_and_gesture_test.dart @@ -26,7 +26,7 @@ void main() { expect(provider.terminalFontSize, 16.0); - // Updates and clamps between 8.0 and 32.0 + // Updates and clamps between 8.0 and 30.0 await provider.setTerminalFontSize(20.0); expect(provider.terminalFontSize, 20.0); @@ -34,10 +34,10 @@ void main() { expect(provider.terminalFontSize, 8.0); await provider.setTerminalFontSize(50.0); - expect(provider.terminalFontSize, 32.0); + expect(provider.terminalFontSize, 30.0); final prefs = await SharedPreferences.getInstance(); - expect(prefs.getDouble('terminal_font_size'), 32.0); + expect(prefs.getDouble('terminal_font_size'), 30.0); }); test('L10n: terminalFontSize strings exist in both zh and en', () {