diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 663075a..5bfd497 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1012,5 +1012,94 @@ "chrootFailedFallbackToProot": "Chroot mount or permission failed, automatically fell back to PRoot", "drawerTabExplorer": "Explorer", "drawerTabSearch": "Search", - "drawerTabGit": "Source Control" + "drawerTabGit": "Source Control", + "searchHint": "Search", + "replaceHint": "Replace", + "matchCase": "Match Case", + "matchWholeWord": "Match Whole Word", + "useRegularExpression": "Use Regular Expression", + "invalidRegularExpression": "Invalid regular expression", + "projectDirectoryNotFound": "Project directory does not exist", + "searchMoreOptions": "More Options", + "searchModeText": "Text Search", + "searchModeFileName": "File Name Search", + "replaceAllInFile": "Replace All in This File", + "replaceAllInProject": "Replace All", + "replaceSingleMatch": "Replace", + "searchResultStats": "{matchCount} results in {fileCount} files", + "@searchResultStats": { + "placeholders": { + "fileCount": { + "type": "int" + }, + "matchCount": { + "type": "int" + } + } + }, + "noSearchResults": "No results found", + "searchError": "Search failed: {error}", + "@searchError": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "replaceSuccess": "Replaced {count} occurrences", + "@replaceSuccess": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "expandAll": "Expand All", + "collapseAll": "Collapse All", + "searchLoadMoreFiles": "Load more files ({count} remaining)", + "@searchLoadMoreFiles": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "searchLoadMoreMatches": "Load more matches ({count} remaining)", + "@searchLoadMoreMatches": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "confirmReplaceAllTitle": "Confirm Replace All", + "confirmReplaceAllMessage": "Are you sure you want to replace all {matchCount} occurrences in {fileCount} files with \"{replaceText}\"? This will modify files on disk.", + "@confirmReplaceAllMessage": { + "placeholders": { + "matchCount": { + "type": "int" + }, + "fileCount": { + "type": "int" + }, + "replaceText": { + "type": "String" + } + } + }, + "confirmReplaceFileTitle": "Replace in File", + "confirmReplaceFileMessage": "Are you sure you want to replace all {matchCount} occurrences in \"{fileName}\" with \"{replaceText}\"?", + "@confirmReplaceFileMessage": { + "placeholders": { + "fileName": { + "type": "String" + }, + "matchCount": { + "type": "int" + }, + "replaceText": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 839b03a..da2f167 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3043,6 +3043,164 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'源代码管理'** String get drawerTabGit; + + /// No description provided for @searchHint. + /// + /// In zh, this message translates to: + /// **'搜索'** + String get searchHint; + + /// No description provided for @replaceHint. + /// + /// In zh, this message translates to: + /// **'替换'** + String get replaceHint; + + /// No description provided for @matchCase. + /// + /// In zh, this message translates to: + /// **'区分大小写'** + String get matchCase; + + /// No description provided for @matchWholeWord. + /// + /// In zh, this message translates to: + /// **'全字匹配'** + String get matchWholeWord; + + /// No description provided for @useRegularExpression. + /// + /// In zh, this message translates to: + /// **'使用正则表达式'** + String get useRegularExpression; + + /// No description provided for @invalidRegularExpression. + /// + /// In zh, this message translates to: + /// **'无效的正则表达式'** + String get invalidRegularExpression; + + /// No description provided for @projectDirectoryNotFound. + /// + /// In zh, this message translates to: + /// **'项目目录不存在'** + String get projectDirectoryNotFound; + + /// No description provided for @searchMoreOptions. + /// + /// In zh, this message translates to: + /// **'更多选项'** + String get searchMoreOptions; + + /// No description provided for @searchModeText. + /// + /// In zh, this message translates to: + /// **'内容搜索'** + String get searchModeText; + + /// No description provided for @searchModeFileName. + /// + /// In zh, this message translates to: + /// **'文件名搜索'** + String get searchModeFileName; + + /// No description provided for @replaceAllInFile. + /// + /// In zh, this message translates to: + /// **'替换此文件中的所有匹配项'** + String get replaceAllInFile; + + /// No description provided for @replaceAllInProject. + /// + /// In zh, this message translates to: + /// **'全部替换'** + String get replaceAllInProject; + + /// No description provided for @replaceSingleMatch. + /// + /// In zh, this message translates to: + /// **'替换'** + String get replaceSingleMatch; + + /// No description provided for @searchResultStats. + /// + /// In zh, this message translates to: + /// **'在 {fileCount} 个文件中找到 {matchCount} 处匹配'** + String searchResultStats(int fileCount, int matchCount); + + /// No description provided for @noSearchResults. + /// + /// In zh, this message translates to: + /// **'未找到匹配项'** + String get noSearchResults; + + /// No description provided for @searchError. + /// + /// In zh, this message translates to: + /// **'搜索失败: {error}'** + String searchError(String error); + + /// No description provided for @replaceSuccess. + /// + /// In zh, this message translates to: + /// **'已替换 {count} 处匹配'** + String replaceSuccess(int count); + + /// No description provided for @expandAll. + /// + /// In zh, this message translates to: + /// **'全部展开'** + String get expandAll; + + /// No description provided for @collapseAll. + /// + /// In zh, this message translates to: + /// **'全部折叠'** + String get collapseAll; + + /// No description provided for @searchLoadMoreFiles. + /// + /// In zh, this message translates to: + /// **'加载更多文件 (还有 {count} 个)'** + String searchLoadMoreFiles(int count); + + /// No description provided for @searchLoadMoreMatches. + /// + /// In zh, this message translates to: + /// **'加载更多匹配项 (还有 {count} 项)'** + String searchLoadMoreMatches(int count); + + /// No description provided for @confirmReplaceAllTitle. + /// + /// In zh, this message translates to: + /// **'全部替换确认'** + String get confirmReplaceAllTitle; + + /// No description provided for @confirmReplaceAllMessage. + /// + /// In zh, this message translates to: + /// **'确定要在整个项目(共 {fileCount} 个文件)中将全部 {matchCount} 处匹配替换为 \"{replaceText}\" 吗?此操作将直接修改磁盘文件。'** + String confirmReplaceAllMessage( + int matchCount, + int fileCount, + String replaceText, + ); + + /// No description provided for @confirmReplaceFileTitle. + /// + /// In zh, this message translates to: + /// **'替换文件匹配项确认'** + String get confirmReplaceFileTitle; + + /// No description provided for @confirmReplaceFileMessage. + /// + /// In zh, this message translates to: + /// **'确定要在 \"{fileName}\" 中将全部 {matchCount} 处匹配替换为 \"{replaceText}\" 吗?'** + String confirmReplaceFileMessage( + String fileName, + int matchCount, + String replaceText, + ); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index d470d78..7dfac17 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1836,4 +1836,101 @@ class AppLocalizationsEn extends AppLocalizations { @override String get drawerTabGit => 'Source Control'; + + @override + String get searchHint => 'Search'; + + @override + String get replaceHint => 'Replace'; + + @override + String get matchCase => 'Match Case'; + + @override + String get matchWholeWord => 'Match Whole Word'; + + @override + String get useRegularExpression => 'Use Regular Expression'; + + @override + String get invalidRegularExpression => 'Invalid regular expression'; + + @override + String get projectDirectoryNotFound => 'Project directory does not exist'; + + @override + String get searchMoreOptions => 'More Options'; + + @override + String get searchModeText => 'Text Search'; + + @override + String get searchModeFileName => 'File Name Search'; + + @override + String get replaceAllInFile => 'Replace All in This File'; + + @override + String get replaceAllInProject => 'Replace All'; + + @override + String get replaceSingleMatch => 'Replace'; + + @override + String searchResultStats(int fileCount, int matchCount) { + return '$matchCount results in $fileCount files'; + } + + @override + String get noSearchResults => 'No results found'; + + @override + String searchError(String error) { + return 'Search failed: $error'; + } + + @override + String replaceSuccess(int count) { + return 'Replaced $count occurrences'; + } + + @override + String get expandAll => 'Expand All'; + + @override + String get collapseAll => 'Collapse All'; + + @override + String searchLoadMoreFiles(int count) { + return 'Load more files ($count remaining)'; + } + + @override + String searchLoadMoreMatches(int count) { + return 'Load more matches ($count remaining)'; + } + + @override + String get confirmReplaceAllTitle => 'Confirm Replace All'; + + @override + String confirmReplaceAllMessage( + int matchCount, + int fileCount, + String replaceText, + ) { + return 'Are you sure you want to replace all $matchCount occurrences in $fileCount files with \"$replaceText\"? This will modify files on disk.'; + } + + @override + String get confirmReplaceFileTitle => 'Replace in File'; + + @override + String confirmReplaceFileMessage( + String fileName, + int matchCount, + String replaceText, + ) { + return 'Are you sure you want to replace all $matchCount occurrences in \"$fileName\" with \"$replaceText\"?'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index bd4d758..026ff45 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1776,4 +1776,101 @@ class AppLocalizationsZh extends AppLocalizations { @override String get drawerTabGit => '源代码管理'; + + @override + String get searchHint => '搜索'; + + @override + String get replaceHint => '替换'; + + @override + String get matchCase => '区分大小写'; + + @override + String get matchWholeWord => '全字匹配'; + + @override + String get useRegularExpression => '使用正则表达式'; + + @override + String get invalidRegularExpression => '无效的正则表达式'; + + @override + String get projectDirectoryNotFound => '项目目录不存在'; + + @override + String get searchMoreOptions => '更多选项'; + + @override + String get searchModeText => '内容搜索'; + + @override + String get searchModeFileName => '文件名搜索'; + + @override + String get replaceAllInFile => '替换此文件中的所有匹配项'; + + @override + String get replaceAllInProject => '全部替换'; + + @override + String get replaceSingleMatch => '替换'; + + @override + String searchResultStats(int fileCount, int matchCount) { + return '在 $fileCount 个文件中找到 $matchCount 处匹配'; + } + + @override + String get noSearchResults => '未找到匹配项'; + + @override + String searchError(String error) { + return '搜索失败: $error'; + } + + @override + String replaceSuccess(int count) { + return '已替换 $count 处匹配'; + } + + @override + String get expandAll => '全部展开'; + + @override + String get collapseAll => '全部折叠'; + + @override + String searchLoadMoreFiles(int count) { + return '加载更多文件 (还有 $count 个)'; + } + + @override + String searchLoadMoreMatches(int count) { + return '加载更多匹配项 (还有 $count 项)'; + } + + @override + String get confirmReplaceAllTitle => '全部替换确认'; + + @override + String confirmReplaceAllMessage( + int matchCount, + int fileCount, + String replaceText, + ) { + return '确定要在整个项目(共 $fileCount 个文件)中将全部 $matchCount 处匹配替换为 \"$replaceText\" 吗?此操作将直接修改磁盘文件。'; + } + + @override + String get confirmReplaceFileTitle => '替换文件匹配项确认'; + + @override + String confirmReplaceFileMessage( + String fileName, + int matchCount, + String replaceText, + ) { + return '确定要在 \"$fileName\" 中将全部 $matchCount 处匹配替换为 \"$replaceText\" 吗?'; + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 7bf5bb2..287f816 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1012,5 +1012,94 @@ "chrootFailedFallbackToProot": "Chroot 挂载或权限失败,已自动降级为 PRoot 运行模式", "drawerTabExplorer": "文件", "drawerTabSearch": "搜索", - "drawerTabGit": "源代码管理" + "drawerTabGit": "源代码管理", + "searchHint": "搜索", + "replaceHint": "替换", + "matchCase": "区分大小写", + "matchWholeWord": "全字匹配", + "useRegularExpression": "使用正则表达式", + "invalidRegularExpression": "无效的正则表达式", + "projectDirectoryNotFound": "项目目录不存在", + "searchMoreOptions": "更多选项", + "searchModeText": "内容搜索", + "searchModeFileName": "文件名搜索", + "replaceAllInFile": "替换此文件中的所有匹配项", + "replaceAllInProject": "全部替换", + "replaceSingleMatch": "替换", + "searchResultStats": "在 {fileCount} 个文件中找到 {matchCount} 处匹配", + "@searchResultStats": { + "placeholders": { + "fileCount": { + "type": "int" + }, + "matchCount": { + "type": "int" + } + } + }, + "noSearchResults": "未找到匹配项", + "searchError": "搜索失败: {error}", + "@searchError": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "replaceSuccess": "已替换 {count} 处匹配", + "@replaceSuccess": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "expandAll": "全部展开", + "collapseAll": "全部折叠", + "searchLoadMoreFiles": "加载更多文件 (还有 {count} 个)", + "@searchLoadMoreFiles": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "searchLoadMoreMatches": "加载更多匹配项 (还有 {count} 项)", + "@searchLoadMoreMatches": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "confirmReplaceAllTitle": "全部替换确认", + "confirmReplaceAllMessage": "确定要在整个项目(共 {fileCount} 个文件)中将全部 {matchCount} 处匹配替换为 \"{replaceText}\" 吗?此操作将直接修改磁盘文件。", + "@confirmReplaceAllMessage": { + "placeholders": { + "matchCount": { + "type": "int" + }, + "fileCount": { + "type": "int" + }, + "replaceText": { + "type": "String" + } + } + }, + "confirmReplaceFileTitle": "替换文件匹配项确认", + "confirmReplaceFileMessage": "确定要在 \"{fileName}\" 中将全部 {matchCount} 处匹配替换为 \"{replaceText}\" 吗?", + "@confirmReplaceFileMessage": { + "placeholders": { + "fileName": { + "type": "String" + }, + "matchCount": { + "type": "int" + }, + "replaceText": { + "type": "String" + } + } + } } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index f6fe5ee..69907d5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -2,9 +2,10 @@ import 'package:code_editor/l10n/app_localizations.dart'; import 'package:code_editor/providers/distro_provider.dart'; import 'package:code_editor/providers/notice_center.dart'; import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/providers/search_provider.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; -import 'package:code_editor/providers/run_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; import 'package:code_editor/services/background_task/background_task_scheduler.dart'; import 'package:code_editor/views/main_view.dart'; @@ -45,6 +46,11 @@ class MyApp extends StatelessWidget { update: (_, project, tab) => (tab ?? (TabProvider()..init()))..bindProjectProvider(project), ), + ChangeNotifierProxyProvider( + create: (_) => SearchProvider(), + update: (_, project, search) => + (search ?? SearchProvider())..bindRootPath(project.rootPath), + ), ChangeNotifierProvider(create: (_) => TerminalProvider()), ChangeNotifierProvider( create: (_) { diff --git a/lib/models/search_model.dart b/lib/models/search_model.dart new file mode 100644 index 0000000..84a0a05 --- /dev/null +++ b/lib/models/search_model.dart @@ -0,0 +1,213 @@ +import 'package:flutter/foundation.dart'; + +enum SearchMode { + text, + fileName, +} + +@immutable +class SearchOptions { + final String query; + final String replaceText; + final bool caseSensitive; + final bool wholeWord; + final bool isRegex; + final SearchMode mode; + final bool isReplaceExpanded; + + const SearchOptions({ + this.query = '', + this.replaceText = '', + this.caseSensitive = false, + this.wholeWord = false, + this.isRegex = false, + this.mode = SearchMode.text, + this.isReplaceExpanded = false, + }); + + SearchOptions copyWith({ + String? query, + String? replaceText, + bool? caseSensitive, + bool? wholeWord, + bool? isRegex, + SearchMode? mode, + bool? isReplaceExpanded, + }) { + return SearchOptions( + query: query ?? this.query, + replaceText: replaceText ?? this.replaceText, + caseSensitive: caseSensitive ?? this.caseSensitive, + wholeWord: wholeWord ?? this.wholeWord, + isRegex: isRegex ?? this.isRegex, + mode: mode ?? this.mode, + isReplaceExpanded: isReplaceExpanded ?? this.isReplaceExpanded, + ); + } + + /// 构建用于匹配的正则表达式,非法正则时返回 null + RegExp? buildRegExp() { + if (query.isEmpty) return null; + try { + String pattern = isRegex ? query : RegExp.escape(query); + if (wholeWord) { + pattern = '\\b$pattern\\b'; + } + return RegExp(pattern, caseSensitive: caseSensitive, multiLine: false); + } catch (_) { + return null; + } + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is SearchOptions && + other.query == query && + other.replaceText == replaceText && + other.caseSensitive == caseSensitive && + other.wholeWord == wholeWord && + other.isRegex == isRegex && + other.mode == mode && + other.isReplaceExpanded == isReplaceExpanded; + } + + @override + int get hashCode => Object.hash( + query, + replaceText, + caseSensitive, + wholeWord, + isRegex, + mode, + isReplaceExpanded, + ); +} + +class LineMatch { + final int lineNumber; // 1-indexed + final String lineContent; + final int matchStart; // 0-indexed within lineContent + final int matchEnd; + + LineMatch({ + required this.lineNumber, + required this.lineContent, + required this.matchStart, + required this.matchEnd, + }); + + String get matchedText { + if (matchStart < 0 || matchEnd > lineContent.length || matchStart > matchEnd) { + return ''; + } + return lineContent.substring(matchStart, matchEnd); + } + + LineMatch copyWith({ + int? lineNumber, + String? lineContent, + int? matchStart, + int? matchEnd, + }) { + return LineMatch( + lineNumber: lineNumber ?? this.lineNumber, + lineContent: lineContent ?? this.lineContent, + matchStart: matchStart ?? this.matchStart, + matchEnd: matchEnd ?? this.matchEnd, + ); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is LineMatch && + other.lineNumber == lineNumber && + other.lineContent == lineContent && + other.matchStart == matchStart && + other.matchEnd == matchEnd; + } + + @override + int get hashCode => Object.hash(lineNumber, lineContent, matchStart, matchEnd); +} + +class FileSearchResult { + final String filePath; + final String relativePath; + final String fileName; + final List matches; + final bool isDirectory; + bool isExpanded; + + FileSearchResult({ + required this.filePath, + required this.relativePath, + required this.fileName, + required this.matches, + this.isDirectory = false, + this.isExpanded = true, + }); + + int get matchCount => matches.length; + + FileSearchResult copyWith({ + String? filePath, + String? relativePath, + String? fileName, + List? matches, + bool? isDirectory, + bool? isExpanded, + }) { + return FileSearchResult( + filePath: filePath ?? this.filePath, + relativePath: relativePath ?? this.relativePath, + fileName: fileName ?? this.fileName, + matches: matches ?? this.matches, + isDirectory: isDirectory ?? this.isDirectory, + isExpanded: isExpanded ?? this.isExpanded, + ); + } +} + +enum SearchErrorCode { + invalidRegex, + projectDirNotFound, +} + +class SearchResult { + final String query; + final List fileResults; + final int totalMatches; + final int durationMs; + final bool isFileNameSearch; + final String? errorMessage; + final SearchErrorCode? errorCode; + + const SearchResult({ + required this.query, + required this.fileResults, + required this.totalMatches, + this.durationMs = 0, + this.isFileNameSearch = false, + this.errorMessage, + this.errorCode, + }); + + const SearchResult.empty() + : query = '', + fileResults = const [], + totalMatches = 0, + durationMs = 0, + isFileNameSearch = false, + errorMessage = null, + errorCode = null; + + const SearchResult.error(String message, {this.errorCode}) + : query = '', + fileResults = const [], + totalMatches = 0, + durationMs = 0, + isFileNameSearch = false, + errorMessage = message; +} diff --git a/lib/providers/search_provider.dart b/lib/providers/search_provider.dart new file mode 100644 index 0000000..feb68c5 --- /dev/null +++ b/lib/providers/search_provider.dart @@ -0,0 +1,351 @@ +import 'dart:async'; +import 'dart:io'; +import 'package:code_editor/models/search_model.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/file_service.dart'; +import 'package:code_editor/services/project_search_service.dart'; +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +class SearchProvider extends ChangeNotifier { + SearchOptions _options = const SearchOptions(); + SearchResult _result = const SearchResult.empty(); + bool _isLoading = false; + Timer? _debounceTimer; + int _searchVersion = 0; + String? _rootPath; + + SearchOptions get options => _options; + SearchResult get result => _result; + bool get isLoading => _isLoading; + String get query => _options.query; + String get replaceText => _options.replaceText; + bool get isReplaceExpanded => _options.isReplaceExpanded; + SearchMode get mode => _options.mode; + bool get caseSensitive => _options.caseSensitive; + bool get wholeWord => _options.wholeWord; + bool get isRegex => _options.isRegex; + + double scrollOffset = 0.0; + int _displayedFilesLimit = 20; + final Map _displayedMatchesLimits = {}; + final Map _fileExpandedStates = {}; + + int get displayedFilesLimit => _displayedFilesLimit; + + void loadMoreFiles(int step) { + _displayedFilesLimit += step; + notifyListeners(); + } + + int getFileMatchesLimit(String filePath, int defaultSize) { + return _displayedMatchesLimits[filePath] ?? defaultSize; + } + + void loadMoreMatches(String filePath, int step, int defaultSize) { + final cur = _displayedMatchesLimits[filePath] ?? defaultSize; + _displayedMatchesLimits[filePath] = cur + step; + notifyListeners(); + } + + void resetPagination() { + scrollOffset = 0.0; + _displayedFilesLimit = 20; + _displayedMatchesLimits.clear(); + } + + @visibleForTesting + void setResultForTesting(SearchResult result) { + for (final f in result.fileResults) { + if (_fileExpandedStates.containsKey(f.filePath)) { + f.isExpanded = _fileExpandedStates[f.filePath]!; + } + } + _result = result; + _isLoading = false; + notifyListeners(); + } + + void bindRootPath(String? rootPath) { + if (_rootPath != rootPath) { + _rootPath = rootPath; + if (_options.query.isNotEmpty && _rootPath != null && _rootPath!.isNotEmpty) { + triggerSearch(); + } + } + } + + void setQuery(String newQuery) { + if (_options.query == newQuery) return; + _options = _options.copyWith(query: newQuery); + scrollOffset = 0.0; + _displayedFilesLimit = 20; + _displayedMatchesLimits.clear(); + _fileExpandedStates.clear(); + notifyListeners(); + _scheduleDebouncedSearch(); + } + + void setReplaceText(String newReplaceText) { + if (_options.replaceText == newReplaceText) return; + _options = _options.copyWith(replaceText: newReplaceText); + notifyListeners(); + } + + void toggleReplaceExpanded() { + _options = _options.copyWith(isReplaceExpanded: !_options.isReplaceExpanded); + notifyListeners(); + } + + void setMode(SearchMode newMode) { + if (_options.mode == newMode) return; + _options = _options.copyWith(mode: newMode); + scrollOffset = 0.0; + _displayedFilesLimit = 20; + _displayedMatchesLimits.clear(); + _fileExpandedStates.clear(); + notifyListeners(); + triggerSearch(); + } + + void toggleCaseSensitive() { + _options = _options.copyWith(caseSensitive: !_options.caseSensitive); + scrollOffset = 0.0; + _displayedFilesLimit = 20; + _displayedMatchesLimits.clear(); + notifyListeners(); + triggerSearch(); + } + + void toggleWholeWord() { + _options = _options.copyWith(wholeWord: !_options.wholeWord); + scrollOffset = 0.0; + _displayedFilesLimit = 20; + _displayedMatchesLimits.clear(); + notifyListeners(); + triggerSearch(); + } + + void toggleRegex() { + _options = _options.copyWith(isRegex: !_options.isRegex); + scrollOffset = 0.0; + _displayedFilesLimit = 20; + _displayedMatchesLimits.clear(); + notifyListeners(); + triggerSearch(); + } + + void toggleFileExpanded(FileSearchResult file) { + file.isExpanded = !file.isExpanded; + _fileExpandedStates[file.filePath] = file.isExpanded; + notifyListeners(); + } + + void collapseAll() { + for (final f in _result.fileResults) { + f.isExpanded = false; + _fileExpandedStates[f.filePath] = false; + } + notifyListeners(); + } + + void expandAll() { + for (final f in _result.fileResults) { + f.isExpanded = true; + _fileExpandedStates[f.filePath] = true; + } + notifyListeners(); + } + + void _scheduleDebouncedSearch() { + _debounceTimer?.cancel(); + if (_options.query.trim().isEmpty) { + _result = const SearchResult.empty(); + _isLoading = false; + resetPagination(); + notifyListeners(); + return; + } + _debounceTimer = Timer(const Duration(milliseconds: 300), () { + triggerSearch(); + }); + } + + Future triggerSearch({bool keepPagination = false}) async { + _debounceTimer?.cancel(); + final currentQuery = _options.query.trim(); + if (currentQuery.isEmpty || _rootPath == null || _rootPath!.isEmpty) { + _result = const SearchResult.empty(); + _isLoading = false; + resetPagination(); + notifyListeners(); + return; + } + + final thisVersion = ++_searchVersion; + _isLoading = true; + if (!keepPagination) { + resetPagination(); + } + notifyListeners(); + + try { + final searchResult = await ProjectSearchService.instance.search( + rootPath: _rootPath!, + options: _options, + ); + + // 仅保留最新检索请求的结果,规避时序竞态 + if (thisVersion == _searchVersion) { + // 恢复之前对同路径文件的展开/折叠状态偏好 + for (final f in searchResult.fileResults) { + if (_fileExpandedStates.containsKey(f.filePath)) { + f.isExpanded = _fileExpandedStates[f.filePath]!; + } + } + _result = searchResult; + _isLoading = false; + notifyListeners(); + } + } catch (e) { + if (thisVersion == _searchVersion) { + _result = SearchResult.error(e.toString()); + _isLoading = false; + notifyListeners(); + } + } + } + + /// 替换单行单处匹配项 + Future replaceSingleMatch({ + required FileSearchResult file, + required LineMatch match, + required TabProvider tabProvider, + }) async { + final cleanPath = p.normalize(file.filePath); + final openTab = tabProvider.openTabs.where((t) => p.equals(t.path, cleanPath)).firstOrNull; + + try { + String originalContent; + if (openTab != null && openTab.isLoaded) { + originalContent = openTab.content; + } else { + originalContent = await FileService.instance.readFileContent(cleanPath); + } + + final updatedContent = ProjectSearchService.instance.replaceSingleMatchInContent( + fileContent: originalContent, + match: match, + replacement: _options.replaceText, + ); + + if (openTab != null && openTab.isLoaded) { + // 若在标签页中已打开,直接同步内存并置脏,避免与磁盘抢占覆盖 + openTab.content = updatedContent.replaceAll('\r\n', '\n'); + openTab.isModified = true; + tabProvider.notifyListeners(); + } else { + // 未打开的文件直接安全覆写磁盘 + final ioFile = File(cleanPath); + await ioFile.writeAsString(updatedContent); + } + + // 局部移除已替换的行匹配 + file.matches.remove(match); + if (file.matches.isEmpty) { + _result.fileResults.remove(file); + } + _updateTotalMatchesCount(); + notifyListeners(); + return true; + } catch (e) { + debugPrint('替换单项失败: $e'); + return false; + } + } + + /// 替换单文件中的所有匹配项 + Future replaceFileMatches({ + required FileSearchResult file, + required TabProvider tabProvider, + }) async { + final regExp = _options.buildRegExp(); + if (regExp == null) return 0; + + final cleanPath = p.normalize(file.filePath); + final openTab = tabProvider.openTabs.where((t) => p.equals(t.path, cleanPath)).firstOrNull; + + try { + String originalContent; + if (openTab != null && openTab.isLoaded) { + originalContent = openTab.content; + } else { + originalContent = await FileService.instance.readFileContent(cleanPath); + } + + final replacedCount = file.matches.length; + final updatedContent = ProjectSearchService.instance.replaceAllInContent( + fileContent: originalContent, + regExp: regExp, + replacement: _options.replaceText, + ); + + if (openTab != null && openTab.isLoaded) { + openTab.content = updatedContent.replaceAll('\r\n', '\n'); + openTab.isModified = true; + tabProvider.notifyListeners(); + } else { + final ioFile = File(cleanPath); + await ioFile.writeAsString(updatedContent); + } + + _result.fileResults.remove(file); + _updateTotalMatchesCount(); + notifyListeners(); + return replacedCount; + } catch (e) { + debugPrint('替换文件全部项失败: $e'); + return 0; + } + } + + /// 替换工程内所有文件中的所有匹配项 + Future replaceAllMatches({ + required TabProvider tabProvider, + }) async { + final files = List.from(_result.fileResults); + int totalReplaced = 0; + + for (final file in files) { + final count = await replaceFileMatches( + file: file, + tabProvider: tabProvider, + ); + totalReplaced += count; + } + + return totalReplaced; + } + + void _updateTotalMatchesCount() { + int count = 0; + for (final f in _result.fileResults) { + count += f.matches.length; + } + _result = SearchResult( + query: _result.query, + fileResults: _result.fileResults, + totalMatches: count, + durationMs: _result.durationMs, + isFileNameSearch: _result.isFileNameSearch, + errorMessage: _result.errorMessage, + errorCode: _result.errorCode, + ); + } + + @override + void dispose() { + _debounceTimer?.cancel(); + super.dispose(); + } +} diff --git a/lib/providers/tab_provider.dart b/lib/providers/tab_provider.dart index 8ffcaeb..23a9a43 100644 --- a/lib/providers/tab_provider.dart +++ b/lib/providers/tab_provider.dart @@ -9,21 +9,57 @@ import 'package:code_editor/utils/dialog_utils.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; +class EditorNavigationTarget { + final String filePath; + final int line; // 0-based + final int? column; // 0-based + final int? length; + final int timestamp; + + EditorNavigationTarget({ + required this.filePath, + required this.line, + this.column, + this.length, + }) : timestamp = DateTime.now().microsecondsSinceEpoch; +} + class TabProvider extends ChangeNotifier { List _openTabs = []; String? _activeFilePath; bool _isModified = false; Future Function()? _saveHandler; + EditorNavigationTarget? _navigationTarget; ProjectProvider? _projectProvider; List get openTabs => _openTabs; + EditorNavigationTarget? get navigationTarget => _navigationTarget; EditorTabItem? get activeTab { if (_activeFilePath == null) return null; final index = _openTabs.indexWhere((tab) => p.equals(tab.path, _activeFilePath!)); return index != -1 ? _openTabs[index] : null; } + void navigateTo({ + required String filePath, + required int line, + int? column, + int? length, + }) { + _navigationTarget = EditorNavigationTarget( + filePath: p.normalize(filePath), + line: line, + column: column, + length: length, + ); + notifyListeners(); + } + + void clearNavigationTarget() { + _navigationTarget = null; + } + String? get currentFilePath => _activeFilePath; bool get isModified => activeTab?.isModified ?? _isModified; bool get hasUnsavedChanges => _isModified || _openTabs.any((t) => t.isModified); diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart index ae99714..23ba0a4 100644 --- a/lib/services/distro_manager.dart +++ b/lib/services/distro_manager.dart @@ -161,12 +161,9 @@ class DistroManager { break; case ContainerRuntimeMode.chroot: - bool hasRoot = false; - if (RootService.instance.isDeviceRootCapable()) { - hasRoot = await RootService.instance.isRootAvailablePassive(); - if (!hasRoot) { - hasRoot = await RootService.instance.promptRequestRootExplicit(); - } + bool hasRoot = await RootService.instance.isRootAvailablePassive(); + if (!hasRoot) { + hasRoot = await RootService.instance.promptRequestRootExplicit(); } if (hasRoot && rootDir.existsSync()) { final chrootReady = await ChrootMountManager.instance.prepareChrootEnvironment( diff --git a/lib/services/project_search_service.dart b/lib/services/project_search_service.dart new file mode 100644 index 0000000..6c01a6f --- /dev/null +++ b/lib/services/project_search_service.dart @@ -0,0 +1,257 @@ +import 'dart:io'; +import 'dart:isolate'; +import 'package:code_editor/models/search_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; + +class ProjectSearchService { + static final ProjectSearchService instance = ProjectSearchService._(); + ProjectSearchService._(); + + static const Set ignoredDirectories = { + '.git', + '.dart_tool', + '.idea', + '.vscode', + 'build', + 'node_modules', + '.gradle', + '.svn', + '.hg', + 'dist', + 'target', + 'out', + '__pycache__', + '.vs', + '.settings', + }; + + static const Set binaryExtensions = { + '.png', '.jpg', '.jpeg', '.gif', '.ico', '.webp', '.bmp', + '.mp3', '.mp4', '.wav', '.avi', '.mov', '.flac', + '.zip', '.tar', '.gz', '.7z', '.rar', '.bz2', + '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', + '.exe', '.dll', '.so', '.dylib', '.class', '.jar', '.apk', '.aab', '.bin', + '.pyc', '.o', '.a', '.obj', + '.ttf', '.otf', '.woff', '.woff2', '.eot', + }; + + static const int maxFileSizeBytes = 2 * 1024 * 1024; // 2MB + + /// 在后台 Isolate 中执行工程全文或文件名异步检索 + Future search({ + required String rootPath, + required SearchOptions options, + int maxResults = 2000, + }) async { + final query = options.query.trim(); + if (query.isEmpty) { + return const SearchResult.empty(); + } + + final regExp = options.buildRegExp(); + if (regExp == null) { + return const SearchResult.error('无效的正则表达式', errorCode: SearchErrorCode.invalidRegex); + } + + final dir = Directory(rootPath); + if (!await dir.exists()) { + return const SearchResult.error('项目目录不存在', errorCode: SearchErrorCode.projectDirNotFound); + } + + // 采用 Isolate.run 彻底隔离耗时文件读取与正则计算,UI 线程 0 阻塞 + try { + return await Isolate.run(() => _executeSearchInIsolate( + rootPath: rootPath, + options: options, + maxResults: maxResults, + )); + } catch (e) { + debugPrint('ProjectSearchService 搜索异常: $e'); + return SearchResult.error(e.toString()); + } + } + + static SearchResult _executeSearchInIsolate({ + required String rootPath, + required SearchOptions options, + required int maxResults, + }) { + final sw = Stopwatch()..start(); + final regExp = options.buildRegExp(); + if (regExp == null) { + return const SearchResult.error('无效的正则表达式', errorCode: SearchErrorCode.invalidRegex); + } + + final rootDir = Directory(rootPath); + if (!rootDir.existsSync()) { + return const SearchResult.error('项目目录不存在', errorCode: SearchErrorCode.projectDirNotFound); + } + + final List fileResults = []; + int totalMatchCount = 0; + + void processDirectory(Directory dir) { + final List entities; + try { + entities = dir.listSync(followLinks: false); + } catch (_) { + return; + } + + for (final entity in entities) { + if (totalMatchCount >= maxResults) return; + + final basename = p.basename(entity.path); + + if (entity is Directory) { + if (ignoredDirectories.contains(basename) || basename.startsWith('.')) { + continue; + } + if (options.mode == SearchMode.fileName) { + final match = regExp.firstMatch(basename); + if (match != null) { + final relPath = p.relative(entity.path, from: rootPath).replaceAll('\\', '/'); + fileResults.add(FileSearchResult( + filePath: entity.path, + relativePath: relPath, + fileName: basename, + isDirectory: true, + matches: [ + LineMatch( + lineNumber: 1, + lineContent: basename, + matchStart: match.start, + matchEnd: match.end, + ), + ], + )); + totalMatchCount++; + } + } + processDirectory(entity); + } else if (entity is File) { + final ext = p.extension(basename).toLowerCase(); + if (binaryExtensions.contains(ext)) { + continue; + } + + final relPath = p.relative(entity.path, from: rootPath).replaceAll('\\', '/'); + + if (options.mode == SearchMode.fileName) { + // 文件名称匹配(仅对文件名/文件夹名本身匹配,不含上层相对路径) + final match = regExp.firstMatch(basename); + if (match != null) { + fileResults.add(FileSearchResult( + filePath: entity.path, + relativePath: relPath, + fileName: basename, + isDirectory: false, + matches: [ + LineMatch( + lineNumber: 1, + lineContent: basename, + matchStart: match.start, + matchEnd: match.end, + ), + ], + )); + totalMatchCount++; + } + } else { + // 文本内容匹配 + try { + final stat = entity.statSync(); + if (stat.size > maxFileSizeBytes) { + continue; + } + + final content = entity.readAsStringSync(); + final lines = content.split('\n'); + final List lineMatches = []; + + for (var i = 0; i < lines.length; i++) { + final line = lines[i].replaceAll('\r', ''); + final matches = regExp.allMatches(line); + + for (final m in matches) { + lineMatches.add(LineMatch( + lineNumber: i + 1, + lineContent: line, + matchStart: m.start, + matchEnd: m.end, + )); + totalMatchCount++; + if (totalMatchCount >= maxResults) break; + } + if (totalMatchCount >= maxResults) break; + } + + if (lineMatches.isNotEmpty) { + fileResults.add(FileSearchResult( + filePath: entity.path, + relativePath: relPath, + fileName: basename, + matches: lineMatches, + )); + } + } catch (_) { + // 忽略编码不可读等非文本异常文件 + } + } + } + } + } + + processDirectory(rootDir); + sw.stop(); + + return SearchResult( + query: options.query, + fileResults: fileResults, + totalMatches: totalMatchCount, + durationMs: sw.elapsedMilliseconds, + isFileNameSearch: options.mode == SearchMode.fileName, + ); + } + + /// 替换单行匹配项并返回更新后的整篇文本内容 + String replaceSingleMatchInContent({ + required String fileContent, + required LineMatch match, + required String replacement, + }) { + final hasCrLf = fileContent.contains('\r\n'); + final normalized = fileContent.replaceAll('\r\n', '\n'); + final lines = normalized.split('\n'); + + final lineIndex = match.lineNumber - 1; + if (lineIndex < 0 || lineIndex >= lines.length) { + return fileContent; + } + + final targetLine = lines[lineIndex]; + if (match.matchStart >= 0 && + match.matchEnd <= targetLine.length && + match.matchStart <= match.matchEnd) { + final updatedLine = targetLine.replaceRange( + match.matchStart, + match.matchEnd, + replacement, + ); + lines[lineIndex] = updatedLine; + } + + final result = lines.join('\n'); + return hasCrLf ? result.replaceAll('\n', '\r\n') : result; + } + + /// 替换文本中所有匹配项并返回更新后的内容 + String replaceAllInContent({ + required String fileContent, + required RegExp regExp, + required String replacement, + }) { + return fileContent.replaceAll(regExp, replacement); + } +} diff --git a/lib/services/root_service.dart b/lib/services/root_service.dart index 49cc181..f137aa5 100644 --- a/lib/services/root_service.dart +++ b/lib/services/root_service.dart @@ -16,7 +16,7 @@ class RootService { @visibleForTesting bool? mockRootGranted; - /// 常见 Linux/Android su 二进制搜索路径 + /// 常见 Linux/Android su 二进制搜索路径(包含现代 KernelSU / APatch / Magisk 扩展路径) static const List _commonSuPaths = [ '/system/bin/su', '/system/xbin/su', @@ -26,17 +26,38 @@ class RootService { '/system/sd/xbin/su', '/data/local/xbin/su', '/data/local/bin/su', + '/data/adb/ksu/bin/su', + '/data/adb/ap/bin/su', + '/data/adb/magisk/su', + '/data/adb/magisk/busybox', + '/apex/com.android.runtime/bin/su', + '/system_ext/bin/su', + '/product/bin/su', + '/odm/bin/su', + '/vendor/bin/su', + '/system/bin/.ext/.su', + '/system/usr/we-need-root/su', + '/system/xbin/ku.sud', ]; - /// 静态检测当前设备是否具备 Root 能力(文件系统存在 su 二进制) + /// 常见现代 Root 框架特征目录 (KernelSU / APatch / Magisk) + static const List _commonRootIndicatorDirs = [ + '/data/adb/ksu', + '/data/adb/ap', + '/data/adb/magisk', + '/data/adb/modules', + ]; + + /// 静态检测当前设备是否具备 Root 能力(文件系统存在 su 二进制或现代 Root 管理器特征) /// - /// 该方法纯粹检查静态文件路径,绝不调用任何命令,因此绝对不会触发 Magisk / KernelSU / APatch 授权弹窗。 + /// 该方法纯粹检查静态文件路径与环境变量,绝不调用外部进程命令,因此不会触发授权弹窗。 bool isDeviceRootCapable() { if (mockRootCapable != null) { return mockRootCapable!; } if (!kIsWeb && Platform.isAndroid) { + // 1. 遍历已知 su 二进制路径 for (final path in _commonSuPaths) { try { if (File(path).existsSync()) { @@ -44,6 +65,29 @@ class RootService { } } catch (_) {} } + + // 2. 遍历 PATH 环境变量中的所有目录进行动态检索 + final pathEnv = Platform.environment['PATH']; + if (pathEnv != null && pathEnv.isNotEmpty) { + final dirs = pathEnv.split(':'); + for (final dir in dirs) { + if (dir.isEmpty) continue; + try { + if (File('$dir/su').existsSync()) { + return true; + } + } catch (_) {} + } + } + + // 3. 探测现代 Root 框架特征目录 (KernelSU / APatch / Magisk) + for (final dir in _commonRootIndicatorDirs) { + try { + if (Directory(dir).existsSync()) { + return true; + } + } catch (_) {} + } } return false; @@ -74,16 +118,12 @@ class RootService { /// 被动检测当前是否已获得真实 Root 权限 (uid=0) /// - /// 仅在用户主动触发 Chroot 操作、或 Auto 模式下准备启动容器时被动调用。 + /// 直接执行最小命令探针 `su -c 'id -u'`,不受静态文件可见性(Root 隐藏/SELinux 隔离)限制。 Future isRootAvailablePassive({Duration timeout = const Duration(seconds: 4)}) async { if (mockRootGranted != null) { return mockRootGranted!; } - if (!isDeviceRootCapable()) { - return false; - } - try { final result = await Process.run( 'su', diff --git a/lib/utils/file_icon_utils.dart b/lib/utils/file_icon_utils.dart new file mode 100644 index 0000000..586f7ce --- /dev/null +++ b/lib/utils/file_icon_utils.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +class FileIconUtils { + FileIconUtils._(); + + /// 根据路径/名称、扩展名以及是否为文件夹获取匹配的图标 + static IconData getIcon({ + required String name, + bool isDirectory = false, + bool isOpen = false, + }) { + if (isDirectory) { + return isOpen ? Icons.folder_open_outlined : Icons.folder_outlined; + } + + final lowerName = name.toLowerCase(); + if (lowerName == '.gitignore' || + lowerName == '.gitattributes' || + lowerName == '.gitmodules') { + return Icons.commit_outlined; + } + + final ext = p.extension(name).toLowerCase(); + return switch (ext) { + '.dart' => Icons.flutter_dash, + '.html' || '.htm' => Icons.html, + '.css' || '.scss' || '.sass' || '.less' => Icons.css, + '.js' || '.mjs' || '.cjs' => Icons.javascript, + '.ts' || '.tsx' || '.jsx' || '.vue' || '.svelte' => Icons.code, + '.json' => Icons.data_object, + '.yaml' || + '.yml' || + '.toml' || + '.ini' || + '.env' || + '.conf' || + '.config' || + '.properties' => + Icons.settings_suggest_outlined, + '.xml' => Icons.code, + '.md' || '.markdown' => Icons.article_outlined, + '.pdf' => Icons.picture_as_pdf_outlined, + '.py' || + '.pyw' || + '.java' || + '.kt' || + '.kts' || + '.c' || + '.cpp' || + '.cc' || + '.h' || + '.hpp' || + '.cs' || + '.go' || + '.rs' || + '.swift' || + '.rb' || + '.php' => + Icons.code, + '.sh' || '.bash' || '.zsh' || '.bat' || '.cmd' || '.ps1' => + Icons.terminal, + '.sql' || '.db' || '.sqlite' => Icons.storage_outlined, + '.png' || + '.jpg' || + '.jpeg' || + '.gif' || + '.webp' || + '.svg' || + '.ico' || + '.bmp' => + Icons.image_outlined, + '.mp3' || '.wav' || '.ogg' || '.flac' || '.aac' => + Icons.audio_file_outlined, + '.mp4' || '.avi' || '.mov' || '.mkv' || '.flv' || '.webm' => + Icons.video_file_outlined, + '.zip' || '.rar' || '.7z' || '.tar' || '.gz' => + Icons.folder_zip_outlined, + '.lock' => Icons.lock_outline, + _ => Icons.description_outlined, + }; + } +} diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index d1e351a..d40637d 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -7,7 +7,6 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../services/distro_manager.dart'; import '../services/internal_engine_service.dart'; -import '../services/root_service.dart'; import '../widgets/color_palette_dialog.dart'; import 'code_completion_management_view.dart'; import 'virtual_keyboard_config_view.dart'; @@ -1175,7 +1174,6 @@ class SettingsView extends StatelessWidget { ) async { final currentMode = provider.containerRuntimeMode; final theme = Theme.of(context); - final isRootGranted = await RootService.instance.isRootAvailablePassive(); if (!context.mounted) return; @@ -1184,19 +1182,16 @@ class SettingsView extends StatelessWidget { mode: ContainerRuntimeMode.auto, title: l10n.containerRuntimeModeAuto, icon: Icons.auto_mode_rounded, - enabled: true, ), ( mode: ContainerRuntimeMode.proot, title: l10n.containerRuntimeModeProot, icon: Icons.shield_outlined, - enabled: true, ), ( mode: ContainerRuntimeMode.chroot, title: l10n.containerRuntimeModeChroot, icon: Icons.bolt_rounded, - enabled: isRootGranted, ), ]; @@ -1220,40 +1215,33 @@ class SettingsView extends StatelessWidget { const Divider(height: 1), for (final opt in options) ...[ ListTile( - enabled: opt.enabled, leading: Icon( opt.icon, - color: opt.enabled - ? (opt.mode == currentMode ? theme.colorScheme.primary : null) - : theme.disabledColor, + color: opt.mode == currentMode ? theme.colorScheme.primary : null, ), title: Text( opt.title, style: TextStyle( fontWeight: opt.mode == currentMode ? FontWeight.bold : FontWeight.normal, - color: opt.enabled - ? (opt.mode == currentMode ? theme.colorScheme.primary : null) - : theme.disabledColor, + color: opt.mode == currentMode ? theme.colorScheme.primary : null, ), ), trailing: opt.mode == currentMode - ? Icon(Icons.check, color: opt.enabled ? theme.colorScheme.primary : theme.disabledColor) - : (!opt.enabled ? Icon(Icons.lock_outline, size: 18, color: theme.disabledColor) : null), - onTap: opt.enabled - ? () async { - Navigator.of(sheetContext).pop(); - if (provider.containerRuntimeMode != opt.mode) { - await provider.setContainerRuntimeMode(opt.mode); - } - if (context.mounted) { - await DistroManager().detectAndApplyRuntime( - context: context, - settings: provider, - showToast: true, - ); - } - } + ? Icon(Icons.check, color: theme.colorScheme.primary) : null, + onTap: () async { + Navigator.of(sheetContext).pop(); + if (provider.containerRuntimeMode != opt.mode) { + await provider.setContainerRuntimeMode(opt.mode); + } + if (context.mounted) { + await DistroManager().detectAndApplyRuntime( + context: context, + settings: provider, + showToast: true, + ); + } + }, ), ], const SizedBox(height: 12), diff --git a/lib/widgets/code_editor_drawer.dart b/lib/widgets/code_editor_drawer.dart index 09b2003..49ca61d 100644 --- a/lib/widgets/code_editor_drawer.dart +++ b/lib/widgets/code_editor_drawer.dart @@ -9,6 +9,7 @@ import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/views/project_management_view.dart'; import 'package:code_editor/widgets/project_history_widget.dart'; import 'package:code_editor/widgets/file_tree_widget.dart'; +import 'package:code_editor/widgets/search/search_panel_widget.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; @@ -20,6 +21,9 @@ enum _OpenProjectSource { } class CodeEditorDrawer extends StatefulWidget { + /// 内存中常驻记录抽屉当前选中的 Tab 索引 (0: 文件, 1: 搜索, 2: Git) + static int lastSelectedTabIndex = 0; + const CodeEditorDrawer({super.key}); @override @@ -27,7 +31,7 @@ class CodeEditorDrawer extends StatefulWidget { } class _CodeEditorDrawerState extends State { - int _selectedIndex = 0; + int _selectedIndex = CodeEditorDrawer.lastSelectedTabIndex; static ProjectProvider _getProjectProvider( BuildContext context, { @@ -151,6 +155,7 @@ class _CodeEditorDrawerState extends State { if (_selectedIndex != index) { setState(() { _selectedIndex = index; + CodeEditorDrawer.lastSelectedTabIndex = index; }); } }, @@ -442,44 +447,7 @@ class _CodeEditorDrawerState extends State { ); } - Widget _buildSearchPlaceholder( - BuildContext context, - AppLocalizations l10n, - ThemeData theme, - ) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Container( - decoration: BoxDecoration( - color: theme.colorScheme.primaryContainer, - ), - child: SafeArea( - bottom: false, - left: false, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0), - child: Row( - children: [ - Expanded( - child: Text( - l10n.drawerTabSearch, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.bold, - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, - ), - ), - ], - ), - ), - ), - ), - const Expanded(child: SizedBox.shrink()), - ], - ); - } + Widget _buildGitPlaceholder( BuildContext context, @@ -538,7 +506,7 @@ class _CodeEditorDrawerState extends State { index: _selectedIndex, children: [ _buildExplorerPage(context, l10n, theme, rootPath, hasProject), - _buildSearchPlaceholder(context, l10n, theme), + const SearchPanelWidget(), _buildGitPlaceholder(context, l10n, theme), ], ), diff --git a/lib/widgets/code_editor_widget.dart b/lib/widgets/code_editor_widget.dart index b3b47b1..a35f422 100644 --- a/lib/widgets/code_editor_widget.dart +++ b/lib/widgets/code_editor_widget.dart @@ -4,6 +4,8 @@ import 'package:code_editor/models/app_font.dart'; import 'package:code_editor/models/editor_tab_item.dart'; import 'package:code_editor/models/editor_theme.dart'; import 'package:code_editor/models/virtual_keyboard_config.dart'; +import 'package:code_editor/models/search_model.dart'; +import 'package:code_editor/providers/search_provider.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/services/file_service.dart'; @@ -82,6 +84,7 @@ class _CodeEditorWidgetState extends State { CodeLineEditingController? _controller; CodeScrollController? _scrollController; + CodeFindController? _findController; final FocusNode _focusNode = FocusNode(); late final CodeEditorToolbarController _toolbarController; final EditorDiagnosticController _diagnosticController = const EditorDiagnosticController(); @@ -462,6 +465,87 @@ class _CodeEditorWidgetState extends State { }); } + void _handleNavigationTarget(TabProvider tabProvider) { + final target = tabProvider.navigationTarget; + if (target != null && + _controller != null && + p.equals(target.filePath, _currentLoadedPath ?? '')) { + final int totalLines = _controller!.lineCount; + final int maxLine = max(0, totalLines - 1); + final int line = target.line.clamp(0, maxLine); + final lineText = _controller!.codeLines[line].text; + final int col = (target.column ?? 0).clamp(0, lineText.length); + final int len = (target.length ?? 0).clamp(0, lineText.length - col); + + _controller!.selection = CodeLineSelection( + baseIndex: line, + baseOffset: col, + extentIndex: line, + extentOffset: col + len, + ); + _controller!.makePositionCenterIfInvisible(CodeLinePosition(index: line, offset: col)); + tabProvider.clearNavigationTarget(); + } + } + + void _syncSearchHighlight(SearchProvider? searchProvider) { + if (searchProvider == null || _findController == null) return; + // 仅在文本内容搜索模式(SearchMode.text)下才同步编辑区高亮; + // 文件名搜索模式(SearchMode.fileName)下严禁在代码编辑区高亮匹配词。 + final isTextSearch = searchProvider.options.mode == SearchMode.text; + final query = isTextSearch ? searchProvider.query : ''; + final curVal = _findController!.value; + final curOpt = curVal?.option; + + if (curOpt == null || + curOpt.pattern != query || + curOpt.caseSensitive != searchProvider.caseSensitive || + curOpt.regex != searchProvider.isRegex) { + if (query.isEmpty) { + if (curVal != null && curOpt?.pattern.isNotEmpty == true) { + // 注意:不能直接调用 _findController!.close(), + // 因为 re_editor 内部在 value == null 时会强制执行 widget.focusNode.requestFocus(), + // 导致侧边抽屉中的搜索输入框在内容清空时瞬间失去焦点。 + // 此处同时临时锁定 _focusNode.canRequestFocus 并赋空匹配正则,彻底杜绝编辑器抢夺焦点。 + final wasCanRequest = _focusNode.canRequestFocus; + _focusNode.canRequestFocus = false; + try { + _findController!.value = const CodeFindValue( + option: CodeFindOption( + pattern: r'(?!)', + caseSensitive: false, + regex: true, + ), + replaceMode: false, + searching: false, + ); + } finally { + _focusNode.canRequestFocus = wasCanRequest; + } + } + } else { + final wasCanRequest = _focusNode.canRequestFocus; + _focusNode.canRequestFocus = false; + try { + _findController!.value = CodeFindValue( + option: CodeFindOption( + pattern: query, + caseSensitive: searchProvider.caseSensitive, + regex: searchProvider.isRegex, + ), + replaceMode: false, + searching: true, + ); + if (_findController!.findInputController.text != query) { + _findController!.findInputController.text = query; + } + } finally { + _focusNode.canRequestFocus = wasCanRequest; + } + } + } + } + void _onDiagnosticsChanged() { if (!mounted || _controller == null) return; _controller?.forceRepaint(); @@ -522,6 +606,8 @@ class _CodeEditorWidgetState extends State { _scrollController?.verticalScroller.dispose(); _scrollController?.horizontalScroller.dispose(); _scrollController?.dispose(); + _findController?.dispose(); + _findController = null; _controller?.removeListener(_onTextChanged); _controller?.dispose(); _focusNode.dispose(); @@ -702,8 +788,18 @@ class _CodeEditorWidgetState extends State { try { final tabProvider = _getTabProvider(context, listen: true); _syncExternalContentIfChanged(tabProvider); + if (tabProvider.navigationTarget != null) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _handleNavigationTarget(tabProvider); + } + }); + } } catch (_) {} + final searchProvider = context.watch(); + _syncSearchHighlight(searchProvider); + final l10n = AppLocalizations.of(context); final hasNoProject = widget.rootPath == null || widget.rootPath!.trim().isEmpty; final hasNoFile = widget.filePath == null || widget.filePath!.trim().isEmpty; @@ -822,6 +918,7 @@ class _CodeEditorWidgetState extends State { child: CodeEditor( key: ValueKey(_currentLoadedPath), controller: controller, + findController: _findController, focusNode: _focusNode, scrollController: _scrollController, wordWrap: activeWordWrap, @@ -843,6 +940,7 @@ class _CodeEditorWidgetState extends State { cursorColor: activeTheme.cursorColor, cursorLineColor: activeTheme.cursorLineColor, selectionColor: activeTheme.selectionColor, + highlightColor: const Color(0xFFFFEB3B).withValues(alpha: 0.45), fontFamily: activeEditorFont.fontFamily, fontFamilyFallback: activeEditorFont.fallback, codeTheme: CodeHighlightTheme( @@ -1031,6 +1129,8 @@ class _CodeEditorWidgetState extends State { ); _controller = newController; + _findController?.dispose(); + _findController = CodeFindController(newController); _currentLoadedPath = fullFilePath; _currentIndentSize = activeIndentSize; _errorMessage = null; @@ -1057,6 +1157,11 @@ class _CodeEditorWidgetState extends State { if (mounted) { setState(() {}); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _handleNavigationTarget(provider); + } + }); } return; } @@ -1090,6 +1195,8 @@ class _CodeEditorWidgetState extends State { ); _controller = newController; + _findController?.dispose(); + _findController = CodeFindController(newController); _currentLoadedPath = fullFilePath; _currentIndentSize = activeIndentSize; _errorMessage = null; @@ -1120,6 +1227,11 @@ class _CodeEditorWidgetState extends State { provider.setModified(tab?.isModified ?? false); provider.registerSaveHandler(() => _saveFile()); } catch (_) {} + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _handleNavigationTarget(provider); + } + }); } } catch (e) { if (!mounted || requestVersion != _currentLoadVersion) return; diff --git a/lib/widgets/file_item_widget.dart b/lib/widgets/file_item_widget.dart index 0087a6a..a868bf1 100644 --- a/lib/widgets/file_item_widget.dart +++ b/lib/widgets/file_item_widget.dart @@ -4,6 +4,7 @@ import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/services/permission_service.dart'; import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:code_editor/utils/file_icon_utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; @@ -136,36 +137,11 @@ class _FileItemWidgetState extends State { } IconData _getFileIcon(FileItem item) { - final lowerName = item.name.toLowerCase(); - if (lowerName == '.gitignore' || lowerName == '.gitattributes' || lowerName == '.gitmodules') { - return Icons.commit_outlined; - } - - return switch (item.extension) { - '.dart' => Icons.flutter_dash, - '.html' || '.htm' => Icons.html, - '.css' || '.scss' || '.sass' || '.less' => Icons.css, - '.js' || '.mjs' || '.cjs' => Icons.javascript, - '.ts' || '.tsx' || '.jsx' || '.vue' || '.svelte' => Icons.code, - '.json' => Icons.data_object, - '.yaml' || '.yml' || '.toml' || '.ini' || '.env' || '.conf' || '.config' || '.properties' => - Icons.settings_suggest_outlined, - '.xml' => Icons.code, - '.md' || '.markdown' => Icons.article_outlined, - '.pdf' => Icons.picture_as_pdf_outlined, - '.py' || '.pyw' || '.java' || '.kt' || '.kts' || '.c' || '.cpp' || '.cc' || - '.h' || '.hpp' || '.cs' || '.go' || '.rs' || '.swift' || '.rb' || '.php' => - Icons.code, - '.sh' || '.bash' || '.zsh' || '.bat' || '.cmd' || '.ps1' => Icons.terminal, - '.sql' || '.db' || '.sqlite' => Icons.storage_outlined, - '.png' || '.jpg' || '.jpeg' || '.gif' || '.webp' || '.svg' || '.ico' || '.bmp' => - Icons.image_outlined, - '.mp3' || '.wav' || '.ogg' || '.flac' || '.aac' => Icons.audio_file_outlined, - '.mp4' || '.avi' || '.mov' || '.mkv' || '.flv' || '.webm' => Icons.video_file_outlined, - '.zip' || '.rar' || '.7z' || '.tar' || '.gz' => Icons.folder_zip_outlined, - '.lock' => Icons.lock_outline, - _ => Icons.description_outlined, - }; + return FileIconUtils.getIcon( + name: item.name, + isDirectory: item.isDirectory, + isOpen: item.isOpen, + ); } void _showContextMenu(FileItem item, Offset tapPosition) async { diff --git a/lib/widgets/search/search_panel_widget.dart b/lib/widgets/search/search_panel_widget.dart new file mode 100644 index 0000000..b2e3c4d --- /dev/null +++ b/lib/widgets/search/search_panel_widget.dart @@ -0,0 +1,1209 @@ +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/file_item.dart'; +import 'package:code_editor/models/search_model.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/search_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/utils/dialog_utils.dart'; +import 'package:code_editor/utils/file_icon_utils.dart'; +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; + +class SearchPanelWidget extends StatefulWidget { + /// 一次性加载并展示的文件数量上限 + static const int defaultFilesPageSize = 20; + + /// 每个文件内部一次性加载并展示的查询匹配行数量上限 + static const int defaultFileMatchesPageSize = 20; + + const SearchPanelWidget({super.key}); + + @override + State createState() => _SearchPanelWidgetState(); +} + +class _SearchPanelWidgetState extends State { + late final TextEditingController _searchController; + late final TextEditingController _replaceController; + late final ScrollController _scrollController; + final FocusNode _searchFocusNode = FocusNode(); + final FocusNode _replaceFocusNode = FocusNode(); + SearchProvider? _fallbackProvider; + + SearchProvider _getEffectiveProvider(BuildContext context, {bool listen = false}) { + final fromContext = listen ? context.watch() : context.read(); + return fromContext ?? (_fallbackProvider ??= SearchProvider()); + } + + @override + void initState() { + super.initState(); + final searchProvider = _getEffectiveProvider(context, listen: false); + _searchController = TextEditingController(text: searchProvider.query); + _replaceController = TextEditingController(text: searchProvider.replaceText); + _scrollController = ScrollController( + initialScrollOffset: searchProvider.scrollOffset, + ); + _scrollController.addListener(_onScroll); + } + + void _onScroll() { + if (_scrollController.hasClients) { + final searchProvider = _getEffectiveProvider(context, listen: false); + searchProvider.scrollOffset = _scrollController.offset; + } + } + + @override + void dispose() { + if (_scrollController.hasClients) { + final searchProvider = _getEffectiveProvider(context, listen: false); + searchProvider.scrollOffset = _scrollController.offset; + } + _scrollController.removeListener(_onScroll); + _scrollController.dispose(); + _searchController.dispose(); + _replaceController.dispose(); + _searchFocusNode.dispose(); + _replaceFocusNode.dispose(); + _fallbackProvider?.dispose(); + super.dispose(); + } + + final MenuController _menuController = MenuController(); + + /// 搜索框右侧更多选项弹出菜单(区分大小写、全字匹配、正则表达式) + Widget _buildSearchOptionsMenu( + SearchProvider searchProvider, + SearchOptions options, + ThemeData theme, + AppLocalizations l10n, + ) { + final hasActiveFilter = options.caseSensitive || options.wholeWord || options.isRegex; + final colorScheme = theme.colorScheme; + + return MenuAnchor( + controller: _menuController, + alignmentOffset: const Offset(0, 4), + style: MenuStyle( + elevation: const WidgetStatePropertyAll(4), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(vertical: 4), + ), + ), + menuChildren: [ + StatefulBuilder( + builder: (context, setMenuState) { + final curOptions = searchProvider.options; + return SizedBox( + width: 220, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // 区分大小写 + InkWell( + onTap: () { + searchProvider.toggleCaseSensitive(); + setMenuState(() {}); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4), + child: Row( + children: [ + SizedBox( + width: 24, + child: Text( + 'Aa', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + color: curOptions.caseSensitive + ? colorScheme.primary + : colorScheme.onSurface, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + l10n.matchCase, + style: const TextStyle(fontSize: 13), + ), + ), + Switch( + value: curOptions.caseSensitive, + onChanged: (val) { + searchProvider.toggleCaseSensitive(); + setMenuState(() {}); + }, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + ), + ), + + // 全字匹配 + InkWell( + onTap: () { + searchProvider.toggleWholeWord(); + setMenuState(() {}); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4), + child: Row( + children: [ + SizedBox( + width: 24, + child: Text( + 'ab', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + decoration: TextDecoration.underline, + decorationThickness: 2, + color: curOptions.wholeWord + ? colorScheme.primary + : colorScheme.onSurface, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + l10n.matchWholeWord, + style: const TextStyle(fontSize: 13), + ), + ), + Switch( + value: curOptions.wholeWord, + onChanged: (val) { + searchProvider.toggleWholeWord(); + setMenuState(() {}); + }, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + ), + ), + + // 正则表达式 + InkWell( + onTap: () { + searchProvider.toggleRegex(); + setMenuState(() {}); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4), + child: Row( + children: [ + SizedBox( + width: 24, + child: Text( + '.*', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + color: curOptions.isRegex + ? colorScheme.primary + : colorScheme.onSurface, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + l10n.useRegularExpression, + style: const TextStyle(fontSize: 13), + ), + ), + Switch( + value: curOptions.isRegex, + onChanged: (val) { + searchProvider.toggleRegex(); + setMenuState(() {}); + }, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + ), + ), + ], + ), + ); + }, + ), + ], + builder: (context, controller, child) { + return Tooltip( + message: l10n.searchMoreOptions, + child: InkWell( + borderRadius: BorderRadius.circular(4), + onTap: () { + if (controller.isOpen) { + controller.close(); + } else { + controller.open(); + } + }, + child: Padding( + padding: const EdgeInsets.all(2.0), + child: Icon( + Icons.more_vert, + size: 18, + color: hasActiveFilter + ? colorScheme.primary + : colorScheme.onSurfaceVariant, + ), + ), + ), + ); + }, + ); + } + + Widget _buildHighlightedSnippet(LineMatch match, ThemeData theme) { + // 替换换行与制表符,保证单行代码片段整洁 + final cleanLine = match.lineContent.replaceAll('\t', ' ').replaceAll(RegExp(r'[\r\n]'), ' '); + final start = match.matchStart.clamp(0, cleanLine.length); + final end = match.matchEnd.clamp(0, cleanLine.length); + + // 匹配处定位显示策略: + // 若匹配前文本较长,从匹配处往前保留极少量(约4个字符)并加省略号,使显示区域直接聚焦于匹配高亮处 + const int prefixContextLen = 4; + const int suffixContextLen = 40; + + String before; + if (start > prefixContextLen) { + final sub = cleanLine.substring(start - prefixContextLen, start); + before = '…$sub'; + } else { + before = cleanLine.substring(0, start); + } + + final matched = (start <= end) ? cleanLine.substring(start, end) : ''; + + String after; + if (cleanLine.length - end > suffixContextLen) { + final sub = cleanLine.substring(end, end + suffixContextLen); + after = '$sub…'; + } else { + after = (end <= cleanLine.length) ? cleanLine.substring(end) : ''; + } + + return RichText( + maxLines: 1, + overflow: TextOverflow.clip, + text: TextSpan( + style: TextStyle( + fontFamily: 'JetBrains Mono', + fontSize: 12, + color: theme.colorScheme.onSurface, + ), + children: [ + TextSpan(text: before), + TextSpan( + text: matched, + style: const TextStyle( + backgroundColor: Color(0xFFFFEB3B), + color: Colors.black87, + fontWeight: FontWeight.bold, + ), + ), + TextSpan(text: after), + ], + ), + ); + } + + /// 在文件名搜索模式下,定位到匹配处开始显示并高亮 + Widget _buildFileNameHighlightedTitle( + String fileName, + LineMatch? match, + ThemeData theme, + ) { + if (match == null || match.matchStart < 0 || match.matchEnd > fileName.length || match.matchStart >= match.matchEnd) { + return Text( + fileName, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ); + } + + final start = match.matchStart.clamp(0, fileName.length); + final end = match.matchEnd.clamp(0, fileName.length); + + // 名称过长时,直接从匹配处(前留最多 4 个字符)开始显示 + const int prefixContextLen = 4; + const int suffixContextLen = 40; + + String before; + if (start > prefixContextLen) { + final sub = fileName.substring(start - prefixContextLen, start); + before = '…$sub'; + } else { + before = fileName.substring(0, start); + } + + final matched = fileName.substring(start, end); + + String after; + if (fileName.length - end > suffixContextLen) { + final sub = fileName.substring(end, end + suffixContextLen); + after = '$sub…'; + } else { + after = fileName.substring(end); + } + + return RichText( + maxLines: 1, + overflow: TextOverflow.clip, + text: TextSpan( + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + color: theme.colorScheme.onSurface, + ), + children: [ + TextSpan(text: before), + TextSpan( + text: matched, + style: const TextStyle( + backgroundColor: Color(0xFFFFEB3B), + color: Colors.black87, + fontWeight: FontWeight.bold, + ), + ), + TextSpan(text: after), + ], + ), + ); + } + + String _getSearchErrorMessage(SearchResult result, AppLocalizations l10n) { + if (result.errorCode == SearchErrorCode.invalidRegex || + result.errorMessage == '无效的正则表达式') { + return l10n.searchError(l10n.invalidRegularExpression); + } + if (result.errorCode == SearchErrorCode.projectDirNotFound || + result.errorMessage == '项目目录不存在') { + return l10n.searchError(l10n.projectDirectoryNotFound); + } + return l10n.searchError(result.errorMessage ?? ''); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + final searchProvider = _getEffectiveProvider(context, listen: true); + final tabProvider = context.read(); + final options = searchProvider.options; + final result = searchProvider.result; + + // 如果 Provider 中的滚动偏移已被重置为 0(如发起新查询),将列表同步回顶部 + if (searchProvider.scrollOffset == 0.0 && _scrollController.hasClients && _scrollController.offset > 0) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_scrollController.hasClients && _scrollController.offset > 0) { + _scrollController.jumpTo(0.0); + } + }); + } + + // 内存数据实时双向同步校验 + if (_searchController.text != options.query) { + _searchController.value = _searchController.value.copyWith( + text: options.query, + selection: TextSelection.collapsed(offset: options.query.length), + ); + } + if (_replaceController.text != options.replaceText) { + _replaceController.value = _replaceController.value.copyWith( + text: options.replaceText, + selection: TextSelection.collapsed(offset: options.replaceText.length), + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 顶部标题栏 + Container( + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer, + ), + child: SafeArea( + bottom: false, + left: false, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 10.0), + child: Row( + children: [ + Expanded( + child: Text( + l10n.drawerTabSearch, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + if (options.mode == SearchMode.text && result.fileResults.isNotEmpty) ...[ + IconButton( + visualDensity: VisualDensity.compact, + iconSize: 18, + tooltip: l10n.expandAll, + icon: const Icon(Icons.unfold_more), + onPressed: () => searchProvider.expandAll(), + ), + IconButton( + visualDensity: VisualDensity.compact, + iconSize: 18, + tooltip: l10n.collapseAll, + icon: const Icon(Icons.unfold_less), + onPressed: () => searchProvider.collapseAll(), + ), + ], + ], + ), + ), + ), + ), + + // 搜索与替换输入操作区 + Padding( + padding: const EdgeInsets.fromLTRB(6.0, 8.0, 6.0, 4.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 搜索输入行 + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // 展开/折叠替换输入栏按钮 + InkWell( + borderRadius: BorderRadius.circular(4), + onTap: () => searchProvider.toggleReplaceExpanded(), + child: Padding( + padding: const EdgeInsets.all(2.0), + child: Icon( + options.isReplaceExpanded + ? Icons.keyboard_arrow_down + : Icons.keyboard_arrow_right, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + const SizedBox(width: 2), + + // 搜索输入框与内嵌模式切换按钮 + Expanded( + child: Container( + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), + width: 1, + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: TextField( + controller: _searchController, + focusNode: _searchFocusNode, + keyboardType: TextInputType.multiline, + minLines: 1, + maxLines: 4, + style: const TextStyle(fontSize: 12.5), + decoration: InputDecoration( + hintText: l10n.searchHint, + hintStyle: TextStyle( + fontSize: 12.5, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 6, + ), + border: InputBorder.none, + ), + onChanged: (val) => searchProvider.setQuery(val), + ), + ), + if (options.query.isNotEmpty) + InkWell( + borderRadius: BorderRadius.circular(4), + onTap: () { + _searchController.clear(); + searchProvider.setQuery(''); + _searchFocusNode.requestFocus(); + }, + child: Padding( + padding: const EdgeInsets.all(3.0), + child: Icon( + Icons.clear, + size: 15, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + + // 搜索模式切换(内容搜索 vs 文件名搜索)- 纯切换按钮,点击只改变图标,不改变背景选中颜色 + Tooltip( + message: options.mode == SearchMode.fileName + ? l10n.searchModeFileName + : l10n.searchModeText, + child: InkWell( + borderRadius: BorderRadius.circular(4), + onTap: () { + searchProvider.setMode( + options.mode == SearchMode.text + ? SearchMode.fileName + : SearchMode.text, + ); + }, + child: Padding( + padding: const EdgeInsets.all(3.0), + child: Icon( + options.mode == SearchMode.fileName + ? Icons.insert_drive_file_outlined + : Icons.text_fields, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ), + const SizedBox(width: 2), + ], + ), + ), + ), + const SizedBox(width: 2), + + // 更多选项菜单按钮(区分大小写、全字匹配、正则表达式) + _buildSearchOptionsMenu(searchProvider, options, theme, l10n), + ], + ), + + // 可折叠展开的替换输入行 + if (options.isReplaceExpanded) ...[ + const SizedBox(height: 4), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const SizedBox(width: 22), // 对齐上方展开箭头与间距 (18 + 4) + Expanded( + child: Container( + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), + width: 1, + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: TextField( + controller: _replaceController, + focusNode: _replaceFocusNode, + keyboardType: TextInputType.multiline, + minLines: 1, + maxLines: 4, + style: const TextStyle(fontSize: 12.5), + decoration: InputDecoration( + hintText: l10n.replaceHint, + hintStyle: TextStyle( + fontSize: 12.5, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 6, + ), + border: InputBorder.none, + ), + onChanged: (val) => searchProvider.setReplaceText(val), + ), + ), + if (options.replaceText.isNotEmpty) + InkWell( + borderRadius: BorderRadius.circular(4), + onTap: () { + _replaceController.clear(); + searchProvider.setReplaceText(''); + _replaceFocusNode.requestFocus(); + }, + child: Padding( + padding: const EdgeInsets.all(3.0), + child: Icon( + Icons.clear, + size: 15, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + const SizedBox(width: 2), + ], + ), + ), + ), + const SizedBox(width: 2), + + // 全局一键替换全部按钮(与右侧更多按钮上下对齐) + Tooltip( + message: l10n.replaceAllInProject, + child: InkWell( + borderRadius: BorderRadius.circular(4), + onTap: (result.totalMatches > 0 && tabProvider != null) + ? () async { + final confirmed = await DialogUtils.showConfirmDialog( + context, + title: l10n.confirmReplaceAllTitle, + message: l10n.confirmReplaceAllMessage( + result.totalMatches, + result.fileResults.length, + options.replaceText, + ), + confirmText: l10n.replaceSingleMatch, + ); + if (!confirmed || !context.mounted) return; + + final count = await searchProvider.replaceAllMatches( + tabProvider: tabProvider, + ); + if (context.mounted && count > 0) { + DialogUtils.showSuccessToast( + context, + l10n.replaceSuccess(count), + ); + } + } + : null, + child: Padding( + padding: const EdgeInsets.all(2.0), + child: Icon( + Icons.find_replace, + size: 18, + color: result.totalMatches > 0 + ? theme.colorScheme.primary + : theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.35), + ), + ), + ), + ), + ], + ), + ], + ], + ), + ), + + // 加载进度指示器 + if (searchProvider.isLoading) + const LinearProgressIndicator(minHeight: 2), + + // 状态摘要信息 + if (!searchProvider.isLoading && options.query.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 4.0), + child: Row( + children: [ + Expanded( + child: Text( + result.errorMessage != null + ? _getSearchErrorMessage(result, l10n) + : (result.totalMatches > 0 + ? l10n.searchResultStats(result.fileResults.length, result.totalMatches) + : l10n.noSearchResults), + style: theme.textTheme.bodySmall?.copyWith( + color: result.errorMessage != null + ? theme.colorScheme.error + : theme.colorScheme.onSurfaceVariant, + fontSize: 11.5, + ), + ), + ), + if (result.durationMs > 0) + Text( + '${result.durationMs}ms', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + fontSize: 10.5, + ), + ), + ], + ), + ), + + const Divider(height: 1), + + // 搜索结果树形列表(按需分页懒加载,彻底消除顶部空白与大列表渲染卡顿) + Expanded( + child: result.fileResults.isEmpty + ? (options.query.isEmpty + ? const SizedBox.shrink() + : Center( + child: Text( + l10n.noSearchResults, + style: TextStyle( + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + fontSize: 13, + ), + ), + )) + : Builder( + builder: (context) { + final allFiles = result.fileResults; + final visibleFilesCount = allFiles.length < searchProvider.displayedFilesLimit + ? allFiles.length + : searchProvider.displayedFilesLimit; + final visibleFiles = allFiles.take(visibleFilesCount).toList(); + final hasMoreFiles = allFiles.length > visibleFilesCount; + final remainingFilesCount = allFiles.length - visibleFilesCount; + + return MediaQuery.removePadding( + context: context, + removeTop: true, + child: ListView.builder( + key: const PageStorageKey('project_search_results_list'), + controller: _scrollController, + padding: EdgeInsets.zero, + itemCount: visibleFiles.length + (hasMoreFiles ? 1 : 0), + itemBuilder: (context, fileIndex) { + if (fileIndex == visibleFiles.length) { + return _buildLoadMoreFilesTile( + theme, + l10n, + remainingFilesCount, + searchProvider, + ); + } + + final fileResult = visibleFiles[fileIndex]; + final isExpanded = fileResult.isExpanded; + final dirName = p.dirname(fileResult.relativePath); + final hasDir = dirName != '.' && dirName.isNotEmpty; + + final currentMatchesLimit = searchProvider.getFileMatchesLimit( + fileResult.filePath, + SearchPanelWidget.defaultFileMatchesPageSize, + ); + final allMatches = fileResult.matches; + final visibleMatchesCount = allMatches.length < currentMatchesLimit + ? allMatches.length + : currentMatchesLimit; + final visibleMatches = allMatches.take(visibleMatchesCount).toList(); + final hasMoreMatches = allMatches.length > visibleMatchesCount; + final remainingMatchesCount = allMatches.length - visibleMatchesCount; + + final isFileNameMode = options.mode == SearchMode.fileName; + + if (isFileNameMode) { + // 文件名/文件夹名匹配模式:普通扁平 item,不折叠,高亮直接绘制在主标题文件名上 + final match = fileResult.matches.isNotEmpty ? fileResult.matches.first : null; + final iconData = FileIconUtils.getIcon( + name: fileResult.fileName, + isDirectory: fileResult.isDirectory, + ); + + return InkWell( + onTap: () async { + if (fileResult.isDirectory) { + // 点击文件夹搜索项:展开并跳转到目录 + final projectProvider = context.read(); + if (projectProvider != null) { + final cleanRoot = projectProvider.rootPath; + if (cleanRoot != null) { + final updatedOpenPaths = List.from(projectProvider.openDirectoryPaths); + if (!updatedOpenPaths.contains(fileResult.filePath)) { + updatedOpenPaths.add(fileResult.filePath); + } + await projectProvider.toggleDirectory( + FileItem( + path: fileResult.filePath, + name: fileResult.fileName, + relativePath: fileResult.relativePath, + isDirectory: true, + ), + true, + ); + } + } + } else { + // 点击文件搜索项:打开并进入编辑该文件 + if (tabProvider != null) { + await tabProvider.openFile(fileResult.filePath); + } + } + if (context.mounted) { + Navigator.of(context).maybePop(); + } + }, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 10.0, + vertical: 6.0, + ), + child: Row( + children: [ + Icon( + iconData, + size: 18, + color: fileResult.isDirectory + ? theme.colorScheme.primary + : theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + // 主标题:文件名带关键词高亮 + _buildFileNameHighlightedTitle( + fileResult.fileName, + match, + theme, + ), + if (hasDir) + Padding( + padding: const EdgeInsets.only(top: 2.0), + child: Text( + dirName, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + // 文本内容匹配模式:可折叠树形结构展示 + final iconData = FileIconUtils.getIcon( + name: fileResult.fileName, + isDirectory: fileResult.isDirectory, + ); + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 文件分组条目 + InkWell( + onTap: () => searchProvider.toggleFileExpanded(fileResult), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 10.0, + vertical: 6.0, + ), + child: Row( + children: [ + Icon( + isExpanded + ? Icons.keyboard_arrow_down + : Icons.keyboard_arrow_right, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 4), + Icon( + iconData, + size: 16, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 8), + // 主标题文件名,副标题相对路径(一上一下) + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + fileResult.fileName, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + if (hasDir) + Padding( + padding: const EdgeInsets.only(top: 2.0), + child: Text( + dirName, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ), + const SizedBox(width: 6), + + // 匹配次数 Badge + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '${fileResult.matchCount}', + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + + // 文件级全部替换按钮:仅在展开替换输入框时展示 + if (options.mode == SearchMode.text && options.isReplaceExpanded) + IconButton( + visualDensity: VisualDensity.compact, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(4), + ), + constraints: const BoxConstraints( + minWidth: 24, + minHeight: 24, + ), + iconSize: 16, + icon: const Icon(Icons.find_replace), + tooltip: l10n.replaceAllInFile, + onPressed: tabProvider == null + ? null + : () async { + final confirmed = await DialogUtils.showConfirmDialog( + context, + title: l10n.confirmReplaceFileTitle, + message: l10n.confirmReplaceFileMessage( + fileResult.fileName, + fileResult.matchCount, + options.replaceText, + ), + confirmText: l10n.replaceSingleMatch, + ); + if (!confirmed || !context.mounted) return; + + final count = await searchProvider.replaceFileMatches( + file: fileResult, + tabProvider: tabProvider, + ); + if (context.mounted && count > 0) { + DialogUtils.showSuccessToast( + context, + l10n.replaceSuccess(count), + ); + } + }, + ), + ], + ), + ), + ), + + // 展开展示具体匹配行(按需分页加载) + if (isExpanded) ...[ + ...visibleMatches.map((match) { + return InkWell( + onTap: () async { + if (tabProvider != null) { + // 1. 打开文件并切换 tab + await tabProvider.openFile(fileResult.filePath); + // 2. 发送行定位与选区高亮事件 + tabProvider.navigateTo( + filePath: fileResult.filePath, + line: match.lineNumber - 1, + column: match.matchStart, + length: match.matchEnd - match.matchStart, + ); + } + // 3. 移动端抽屉收起(保留宽屏适配) + if (context.mounted) { + Navigator.of(context).maybePop(); + } + }, + child: Padding( + padding: const EdgeInsets.fromLTRB(36.0, 4.0, 10.0, 4.0), + child: Row( + children: [ + // 行号 + ConstrainedBox( + constraints: const BoxConstraints(minWidth: 28), + child: Text( + '${match.lineNumber}:', + style: TextStyle( + fontFamily: 'JetBrains Mono', + fontSize: 11.5, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + ), + ), + const SizedBox(width: 4), + + // 代码文本摘要(黄色高亮匹配部分) + Expanded( + child: _buildHighlightedSnippet(match, theme), + ), + + // 行单项替换按钮:仅在展开替换输入框时展示 + if (options.mode == SearchMode.text && options.isReplaceExpanded) + IconButton( + visualDensity: VisualDensity.compact, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.all(3), + ), + constraints: const BoxConstraints( + minWidth: 22, + minHeight: 22, + ), + iconSize: 15, + icon: const Icon(Icons.redo), + tooltip: l10n.replaceSingleMatch, + onPressed: tabProvider == null + ? null + : () async { + final success = await searchProvider.replaceSingleMatch( + file: fileResult, + match: match, + tabProvider: tabProvider, + ); + if (context.mounted && success) { + DialogUtils.showSuccessToast( + context, + l10n.replaceSuccess(1), + ); + } + }, + ), + ], + ), + ), + ); + }), + + // 文件内更多匹配项加载按钮 + if (hasMoreMatches) + InkWell( + onTap: () { + searchProvider.loadMoreMatches( + fileResult.filePath, + SearchPanelWidget.defaultFileMatchesPageSize, + SearchPanelWidget.defaultFileMatchesPageSize, + ); + }, + child: Padding( + padding: const EdgeInsets.fromLTRB(36.0, 6.0, 10.0, 8.0), + child: Row( + children: [ + Icon( + Icons.more_horiz, + size: 16, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + l10n.searchLoadMoreMatches(remainingMatchesCount), + style: TextStyle( + fontSize: 11.5, + color: theme.colorScheme.primary, + fontWeight: FontWeight.w500, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ), + ), + ], + ], + ); + }, + ), + ); + }, + ), + ), + ], + ); + } + + /// 加载更多文件条目 + Widget _buildLoadMoreFilesTile( + ThemeData theme, + AppLocalizations l10n, + int remainingFilesCount, + SearchProvider searchProvider, + ) { + return InkWell( + onTap: () { + searchProvider.loadMoreFiles(SearchPanelWidget.defaultFilesPageSize); + }, + child: Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16), + alignment: Alignment.center, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.expand_more, size: 16, color: theme.colorScheme.primary), + const SizedBox(width: 6), + Flexible( + child: Text( + l10n.searchLoadMoreFiles(remainingFilesCount), + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.primary, + fontWeight: FontWeight.w600, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ), + ), + ); + } +} diff --git a/test/container_runtime_chroot_test.dart b/test/container_runtime_chroot_test.dart index 2e433ab..91a2a1c 100644 --- a/test/container_runtime_chroot_test.dart +++ b/test/container_runtime_chroot_test.dart @@ -328,7 +328,7 @@ void main() { }); group('SettingsView Container Runtime UI Tests', () { - testWidgets('SettingsView disables Chroot when root is not granted', (tester) async { + testWidgets('SettingsView always enables Chroot option and falls back to PRoot if root denied', (tester) async { final settings = SettingsProvider(); await settings.init(); RootService.instance.mockRootGranted = false; @@ -359,16 +359,17 @@ void main() { expect(find.text('PRoot'), findsOneWidget); expect(find.text('Chroot'), findsOneWidget); - // Chroot should be disabled (has lock outline icon) + // Chroot should be enabled (open to all users) final chrootTile = tester.widget( find.ancestor(of: find.text('Chroot'), matching: find.byType(ListTile)), ); - expect(chrootTile.enabled, isFalse); + expect(chrootTile.enabled, isTrue); - // Tapping disabled Chroot does not change mode + // Tapping Chroot sets setting to chroot, explicitly attempts detection, and falls back to PRoot await tester.tap(find.text('Chroot')); await tester.pumpAndSettle(); - expect(settings.containerRuntimeMode, equals(ContainerRuntimeMode.auto)); + expect(settings.containerRuntimeMode, equals(ContainerRuntimeMode.chroot)); + expect(find.text('当前容器运行环境:PRoot'), findsOneWidget); }); testWidgets('SettingsView allows Chroot selection when root is granted and shows toast', (tester) async { diff --git a/test/project_search_test.dart b/test/project_search_test.dart new file mode 100644 index 0000000..0386238 --- /dev/null +++ b/test/project_search_test.dart @@ -0,0 +1,662 @@ +import 'dart:io'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/project_history.dart'; +import 'package:code_editor/models/search_model.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/run_provider.dart'; +import 'package:code_editor/providers/search_provider.dart'; +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/internal_project_service.dart'; +import 'package:code_editor/services/project_search_service.dart'; +import 'package:code_editor/widgets/code_editor_drawer.dart'; +import 'package:code_editor/widgets/code_editor_widget.dart'; +import 'package:code_editor/widgets/search/search_panel_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempBaseDir; + late Directory testProjectDir; + late ProjectProvider projectProvider; + late TabProvider tabProvider; + late SettingsProvider settingsProvider; + late RunProvider runProvider; + late SearchProvider searchProvider; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + tempBaseDir = Directory.systemTemp.createTempSync('project_search_test_'); + testProjectDir = Directory(p.join(tempBaseDir.path, 'my_project'))..createSync(); + + InternalProjectService.instance.customProjectsDir = + Directory(p.join(tempBaseDir.path, 'files', 'projects')); + + projectProvider = ProjectProvider(); + tabProvider = TabProvider()..bindProjectProvider(projectProvider); + settingsProvider = SettingsProvider(); + runProvider = RunProvider(); + searchProvider = SearchProvider()..bindRootPath(testProjectDir.path); + + await projectProvider.switchProject( + ProjectHistory( + rootPath: testProjectDir.path, + lastOpenedFilePath: null, + ), + ); + }); + + tearDown(() { + InternalProjectService.instance.customProjectsDir = null; + if (tempBaseDir.existsSync()) { + tempBaseDir.deleteSync(recursive: true); + } + }); + + group('ProjectSearchService & SearchOptions Unit Tests', () { + test('SearchOptions builds correct RegExp for case sensitive, whole word, regex', () { + // Default: case-insensitive literal + final opt1 = const SearchOptions(query: 'foo'); + expect(opt1.buildRegExp()!.hasMatch('FOO'), isTrue); + expect(opt1.buildRegExp()!.hasMatch('foobar'), isTrue); + + // Case sensitive + final opt2 = const SearchOptions(query: 'foo', caseSensitive: true); + expect(opt2.buildRegExp()!.hasMatch('FOO'), isFalse); + expect(opt2.buildRegExp()!.hasMatch('foo'), isTrue); + + // Whole word + final opt3 = const SearchOptions(query: 'foo', wholeWord: true); + expect(opt3.buildRegExp()!.hasMatch('foobar'), isFalse); + expect(opt3.buildRegExp()!.hasMatch('bar foo baz'), isTrue); + + // Regex + final opt4 = const SearchOptions(query: r'f\w+o', isRegex: true); + expect(opt4.buildRegExp()!.hasMatch('froo'), isTrue); + expect(opt4.buildRegExp()!.hasMatch('f123o'), isTrue); + expect(opt4.buildRegExp()!.hasMatch('fx'), isFalse); + }); + + test('search finds matches in project files and skips ignored dirs and binaries', () async { + // Create file 1 + final file1 = File(p.join(testProjectDir.path, 'lib', 'main.dart'))..createSync(recursive: true); + file1.writeAsStringSync('void main() {\n final name = "hello";\n print(name);\n}\n'); + + // Create file 2 (use greet to avoid duplicate "Hello" match) + final file2 = File(p.join(testProjectDir.path, 'lib', 'utils.dart'))..createSync(recursive: true); + file2.writeAsStringSync('String greet() => "hello world";\n'); + + // Create file in .git (should be ignored) + final gitFile = File(p.join(testProjectDir.path, '.git', 'HEAD'))..createSync(recursive: true); + gitFile.writeAsStringSync('hello in git'); + + // Create binary file (should be ignored) + final binFile = File(p.join(testProjectDir.path, 'test.png'))..createSync(); + binFile.writeAsStringSync('hello in png'); + + final result = await ProjectSearchService.instance.search( + rootPath: testProjectDir.path, + options: const SearchOptions(query: 'hello'), + ); + + expect(result.fileResults.length, equals(2)); + expect(result.totalMatches, equals(2)); + + final mainMatch = result.fileResults.firstWhere((f) => f.fileName == 'main.dart'); + expect(mainMatch.matches.length, equals(1)); + expect(mainMatch.matches.first.lineNumber, equals(2)); + expect(mainMatch.matches.first.matchedText, equals('hello')); + }); + + test('fileName search mode correctly matches file and directory names', () async { + File(p.join(testProjectDir.path, 'app_config.json'))..createSync()..writeAsStringSync('{}'); + Directory(p.join(testProjectDir.path, 'config_dir')).createSync(); + File(p.join(testProjectDir.path, 'main.dart'))..createSync()..writeAsStringSync('code'); + + final result = await ProjectSearchService.instance.search( + rootPath: testProjectDir.path, + options: const SearchOptions(query: 'config', mode: SearchMode.fileName), + ); + + expect(result.fileResults.length, equals(2)); + final fileMatch = result.fileResults.firstWhere((f) => f.fileName == 'app_config.json'); + final dirMatch = result.fileResults.firstWhere((f) => f.fileName == 'config_dir'); + + expect(fileMatch.isDirectory, isFalse); + expect(dirMatch.isDirectory, isTrue); + }); + + test('replaceSingleMatchInContent replaces target line match cleanly', () { + const original = 'line 1\nhello world\nline 3'; + final match = LineMatch(lineNumber: 2, lineContent: 'hello world', matchStart: 0, matchEnd: 5); + final replaced = ProjectSearchService.instance.replaceSingleMatchInContent( + fileContent: original, + match: match, + replacement: 'hi', + ); + expect(replaced, equals('line 1\nhi world\nline 3')); + }); + }); + + group('SearchProvider Integration Tests', () { + test('replaceSingleMatch updates open tab content in memory and marks tab modified', () async { + final file = File(p.join(testProjectDir.path, 'demo.txt'))..createSync()..writeAsStringSync('apple banana apple'); + await tabProvider.openFile(file.path); + + await searchProvider.triggerSearch(); + searchProvider.setQuery('apple'); + searchProvider.setReplaceText('orange'); + await searchProvider.triggerSearch(); + + expect(searchProvider.result.totalMatches, equals(2)); + final fileRes = searchProvider.result.fileResults.first; + final match1 = fileRes.matches.first; + + final success = await searchProvider.replaceSingleMatch( + file: fileRes, + match: match1, + tabProvider: tabProvider, + ); + + expect(success, isTrue); + expect(tabProvider.activeTab?.isModified, isTrue); + expect(tabProvider.activeTab?.content, equals('orange banana apple')); + expect(searchProvider.result.totalMatches, equals(1)); + }); + + test('replaceFileMatches replaces all occurrences in file', () async { + final file = File(p.join(testProjectDir.path, 'batch.txt'))..createSync()..writeAsStringSync('cat dog cat dog cat'); + await tabProvider.openFile(file.path); + + searchProvider.setQuery('cat'); + searchProvider.setReplaceText('fox'); + await searchProvider.triggerSearch(); + + final fileRes = searchProvider.result.fileResults.first; + final count = await searchProvider.replaceFileMatches( + file: fileRes, + tabProvider: tabProvider, + ); + + expect(count, equals(3)); + expect(tabProvider.activeTab?.content, equals('fox dog fox dog fox')); + expect(searchProvider.result.totalMatches, equals(0)); + }); + }); + + Widget buildTestApp({Locale locale = const Locale('zh')}) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: runProvider), + ChangeNotifierProvider.value(value: searchProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: locale, + home: const Scaffold( + drawer: CodeEditorDrawer(), + body: Center(child: Text('Editor View')), + ), + ), + ); + } + + group('Search Panel Widget & Drawer UI Tests', () { + testWidgets('Switching to search tab displays SearchPanelWidget with inputs and toggles', (tester) async { + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Switch to search tab + await tester.tap(find.byTooltip('搜索')); + await tester.pumpAndSettle(); + + expect(find.byType(SearchPanelWidget), findsOneWidget); + // 模式切换按钮存在且初始为文本模式 + expect(find.byTooltip('内容搜索'), findsOneWidget); + + // 验证更多选项菜单按钮 + expect(find.byTooltip('更多选项'), findsOneWidget); + // 点击打开更多选项弹出菜单 + await tester.tap(find.byTooltip('更多选项')); + await tester.pumpAndSettle(); + + // 菜单内包含 3 个选项开关 + expect(find.text('区分大小写'), findsOneWidget); + expect(find.text('全字匹配'), findsOneWidget); + expect(find.text('使用正则表达式'), findsOneWidget); + + // 点击“区分大小写”项 + await tester.tap(find.text('区分大小写')); + await tester.pumpAndSettle(); + expect(searchProvider.caseSensitive, isTrue); + + // Expand replace row + expect(find.text('替换'), findsNothing); + await tester.tap(find.byIcon(Icons.keyboard_arrow_right).first); + await tester.pumpAndSettle(); + + expect(find.text('替换'), findsOneWidget); + expect(find.byTooltip('全部替换'), findsOneWidget); + }); + + testWidgets('Search input retains state in memory when switching tabs', (tester) async { + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Switch to search tab + await tester.tap(find.byTooltip('搜索')); + await tester.pumpAndSettle(); + + // Type in search box + await tester.enterText(find.byType(TextField).first, 'testQuery'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 350)); + await tester.pump(); + + // Switch back to Explorer tab + await tester.tap(find.byTooltip('文件')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + // Switch back to Search tab + await tester.tap(find.byTooltip('搜索')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + // Memory state preserved! + expect(searchProvider.query, equals('testQuery')); + expect(find.text('testQuery'), findsOneWidget); + }); + + testWidgets('Search input retains focus when text is deleted to empty or cleared', (tester) async { + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + await tester.tap(find.byTooltip('搜索')); + await tester.pumpAndSettle(); + + final searchField = find.byType(TextField).first; + await tester.tap(searchField); + await tester.pumpAndSettle(); + + final FocusNode focusNode = tester.widget(searchField).focusNode!; + expect(focusNode.hasFocus, isTrue); + + // Enter text + await tester.enterText(searchField, 'abc'); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, isTrue); + + // Delete all text (becomes empty) + await tester.enterText(searchField, ''); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, isTrue, reason: 'Focus should not be lost when all text is deleted'); + + // Re-enter text and tap clear button + await tester.enterText(searchField, 'def'); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.clear), findsOneWidget); + + await tester.tap(find.byIcon(Icons.clear)); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, isTrue, reason: 'Focus should not be lost when clear icon is tapped'); + expect(searchProvider.query, isEmpty); + }); + + testWidgets('Invalid regex displays localized error message in Chinese and English', (tester) async { + // 1. Chinese locale + await tester.pumpWidget(buildTestApp(locale: const Locale('zh'))); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + await tester.tap(find.byTooltip('搜索')); + await tester.pumpAndSettle(); + + // Enable regex + searchProvider.toggleRegex(); + searchProvider.setQuery('['); // Invalid regex: unclosed bracket + await tester.pump(); + await tester.pump(const Duration(milliseconds: 350)); + await tester.pumpAndSettle(); + + // Should display localized Chinese error + expect(find.text('搜索失败: 无效的正则表达式'), findsOneWidget); + + // 2. English locale + await tester.pumpWidget(buildTestApp(locale: const Locale('en'))); + await tester.pumpAndSettle(); + + // Trigger search again to update result with current locale + await searchProvider.triggerSearch(); + await tester.pumpAndSettle(); + + // Should display localized English error + expect(find.text('Search failed: Invalid regular expression'), findsOneWidget); + }); + + testWidgets('SearchPanelWidget page size constants and lazy loading for files and matches', (tester) async { + tester.view.physicalSize = const Size(800, 1200); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + expect(SearchPanelWidget.defaultFilesPageSize, equals(20)); + expect(SearchPanelWidget.defaultFileMatchesPageSize, equals(20)); + + // Construct a mock SearchResult with 25 files, file 0 is expanded with 25 matches, others collapsed + final List mockFiles = List.generate(25, (fIndex) { + return FileSearchResult( + filePath: '/path/file_$fIndex.dart', + relativePath: 'sub/file_$fIndex.dart', + fileName: 'file_$fIndex.dart', + isExpanded: fIndex == 0, + matches: List.generate(25, (mIndex) { + return LineMatch( + lineNumber: mIndex + 1, + lineContent: 'Line $mIndex matching target text', + matchStart: 16, + matchEnd: 22, + ); + }), + ); + }); + + final customResult = SearchResult( + query: 'target', + fileResults: mockFiles, + totalMatches: 25 * 25, + durationMs: 12, + ); + + searchProvider.setResultForTesting(customResult); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: runProvider), + ChangeNotifierProvider.value(value: searchProvider), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: Locale('zh'), + home: Scaffold( + body: SizedBox( + width: 320, + height: 800, + child: SearchPanelWidget(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Verify matches lazy loading in the first file: + // First file has 25 matches. Since defaultFileMatchesPageSize is 20, 20 are shown. + // And a "Load more matches" button showing "加载更多匹配项 (还有 5 项)" + final loadMoreMatchesFinder = find.text('加载更多匹配项 (还有 5 项)'); + await tester.scrollUntilVisible( + loadMoreMatchesFinder, + 200.0, + scrollable: find.byType(Scrollable).last, + ); + expect(loadMoreMatchesFinder, findsOneWidget); + + // Tap "Load more matches" + await tester.tap(loadMoreMatchesFinder); + await tester.pumpAndSettle(); + // All 25 matches now loaded, button for matches is gone! + expect(find.text('加载更多匹配项 (还有 5 项)'), findsNothing); + + // Verify files lazy loading: + // Since defaultFilesPageSize is 20, only 20 files are initially displayed. + // There should be a "Load more files" button showing "加载更多文件 (还有 5 个)" + final loadMoreFilesFinder = find.text('加载更多文件 (还有 5 个)'); + await tester.scrollUntilVisible( + loadMoreFilesFinder, + 300.0, + scrollable: find.byType(Scrollable).last, + ); + expect(loadMoreFilesFinder, findsOneWidget); + + // Tap "Load more files" + await tester.tap(loadMoreFilesFinder); + await tester.pumpAndSettle(); + // All 25 files now loaded, button for files is gone! + expect(find.text('加载更多文件 (还有 5 个)'), findsNothing); + + // Test with long file name to ensure no horizontal layout overflow + final longFileName = 'aime25_openai__gpt-oss-120b-high_default_temp_0.75_aime25_100_eval_response.json'; + final fileWithLongName = FileSearchResult( + filePath: '/path/$longFileName', + relativePath: 'very/deep/nested/path/to/project/$longFileName', + fileName: longFileName, + matches: [ + LineMatch( + lineNumber: 10, + lineContent: 'const a = "target";', + matchStart: 11, + matchEnd: 17, + ), + ], + ); + + searchProvider.setResultForTesting(SearchResult( + query: 'target', + fileResults: [fileWithLongName], + totalMatches: 1, + )); + await tester.pumpAndSettle(); + + // If there was any overflow, tester.takeException() would catch it or pumpAndSettle fails + expect(tester.takeException(), isNull); + }); + + testWidgets('Replace buttons only appear when replace row is expanded, and show confirmation dialog', (tester) async { + tester.view.physicalSize = const Size(800, 1200); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + final testFile = FileSearchResult( + filePath: '/path/test.dart', + relativePath: 'test.dart', + fileName: 'test.dart', + matches: [ + LineMatch( + lineNumber: 1, + lineContent: 'hello world target', + matchStart: 12, + matchEnd: 18, + ), + ], + ); + + searchProvider.setResultForTesting(SearchResult( + query: 'target', + fileResults: [testFile], + totalMatches: 1, + )); + + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Switch to search tab + await tester.tap(find.byTooltip('搜索')); + await tester.pumpAndSettle(); + + // Initially replace row is collapsed: replace buttons in file & match line should NOT be visible! + expect(find.byTooltip('替换此文件中的所有匹配项'), findsNothing); + expect(find.byTooltip('替换'), findsNothing); + + // Expand replace row + await tester.tap(find.byIcon(Icons.keyboard_arrow_right).first); + await tester.pumpAndSettle(); + + // Now replace buttons ARE visible! + expect(find.byTooltip('替换此文件中的所有匹配项'), findsOneWidget); + expect(find.byTooltip('替换'), findsOneWidget); + + // Tapping replace all in file shows confirmation dialog + await tester.tap(find.byTooltip('替换此文件中的所有匹配项')); + await tester.pumpAndSettle(); + + expect(find.text('替换文件匹配项确认'), findsOneWidget); + expect(find.text('取消'), findsOneWidget); + + // Cancel dialog + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(find.text('替换文件匹配项确认'), findsNothing); + }); + + testWidgets('Drawer tab selection is persisted in memory across drawer closing and reopening', (tester) async { + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Switch to search tab (index 1) + await tester.tap(find.byTooltip('搜索')); + await tester.pumpAndSettle(); + expect(CodeEditorDrawer.lastSelectedTabIndex, equals(1)); + + // Close drawer + scaffoldState.closeDrawer(); + await tester.pumpAndSettle(); + + // Reopen drawer: should automatically restore search tab (index 1) + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + expect(find.byType(SearchPanelWidget), findsOneWidget); + }); + + testWidgets('Editor does not highlight search query in fileName mode', (tester) async { + searchProvider.setMode(SearchMode.fileName); + searchProvider.setQuery('main'); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: runProvider), + ChangeNotifierProvider.value(value: searchProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: CodeEditorWidget( + filePath: 'lib/main.dart', + rootPath: testProjectDir.path, + ), + ), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + // In CodeEditorWidget, _syncSearchHighlight with mode == fileName should clear/not set findController + // Switching to text mode enables highlighting, and switching back clears it + searchProvider.setMode(SearchMode.text); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + searchProvider.setMode(SearchMode.fileName); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + }); + + testWidgets('Search result state (expansion, limits, scroll offset) persists across drawer close/reopen', (tester) async { + final List mockFiles = List.generate(25, (fIndex) { + return FileSearchResult( + filePath: '/path/file_$fIndex.dart', + relativePath: 'sub/file_$fIndex.dart', + fileName: 'file_$fIndex.dart', + isExpanded: fIndex == 0, + matches: [ + LineMatch( + lineNumber: 1, + lineContent: 'matching line in file $fIndex', + matchStart: 9, + matchEnd: 13, + ), + ], + ); + }); + + final result = SearchResult( + query: 'test', + fileResults: mockFiles, + totalMatches: 25, + ); + searchProvider.setResultForTesting(result); + + await tester.pumpWidget(buildTestApp()); + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // Switch to search tab + await tester.tap(find.byTooltip('搜索')); + await tester.pumpAndSettle(); + + // 1. Toggle file 1 expansion + expect(mockFiles[1].isExpanded, isFalse); + searchProvider.toggleFileExpanded(mockFiles[1]); + await tester.pumpAndSettle(); + expect(mockFiles[1].isExpanded, isTrue); + + // 2. Load more files + searchProvider.loadMoreFiles(10); + expect(searchProvider.displayedFilesLimit, equals(30)); + + // 3. Set scroll offset + searchProvider.scrollOffset = 150.0; + + // Close drawer + scaffoldState.closeDrawer(); + await tester.pumpAndSettle(); + + // Reopen drawer + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // State is preserved! + expect(searchProvider.displayedFilesLimit, equals(30)); + expect(mockFiles[1].isExpanded, isTrue); + expect(searchProvider.scrollOffset, equals(150.0)); + }); + }); +}