This commit is contained in:
LZX committed 2026-09-17 22:31:44 +08:00
1 parent 27cdb00af2
commit f78f4aeb4a
20 files changed
+3549 -120

No files matched your search

+90 -1
View File
@@ -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"
}
}
}
}
+158
View File
@@ -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
+97
View File
@@ -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\"?';
}
}
+97
View File
@@ -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\" 吗?';
}
}
+90 -1
View File
@@ -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"
}
}
}
}
+7 -1
View File
@@ -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<ProjectProvider, SearchProvider>(
create: (_) => SearchProvider(),
update: (_, project, search) =>
(search ?? SearchProvider())..bindRootPath(project.rootPath),
),
ChangeNotifierProvider(create: (_) => TerminalProvider()),
ChangeNotifierProvider(
create: (_) {
+213
View File
@@ -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<LineMatch> 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<LineMatch>? 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<FileSearchResult> 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;
}
+351
View File
@@ -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<String, int> _displayedMatchesLimits = {};
final Map<String, bool> _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<void> 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<bool> 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<int> 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<int> replaceAllMatches({
required TabProvider tabProvider,
}) async {
final files = List<FileSearchResult>.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();
}
}
+36
View File
@@ -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<EditorTabItem> _openTabs = [];
String? _activeFilePath;
bool _isModified = false;
Future<bool> Function()? _saveHandler;
EditorNavigationTarget? _navigationTarget;
ProjectProvider? _projectProvider;
List<EditorTabItem> 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);
+3 -6
View File
@@ -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(
+257
View File
@@ -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<String> ignoredDirectories = {
'.git',
'.dart_tool',
'.idea',
'.vscode',
'build',
'node_modules',
'.gradle',
'.svn',
'.hg',
'dist',
'target',
'out',
'__pycache__',
'.vs',
'.settings',
};
static const Set<String> 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<SearchResult> 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<FileSearchResult> fileResults = [];
int totalMatchCount = 0;
void processDirectory(Directory dir) {
final List<FileSystemEntity> 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<LineMatch> 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);
}
}
+48 -8
View File
@@ -16,7 +16,7 @@ class RootService {
@visibleForTesting
bool? mockRootGranted;
/// 常见 Linux/Android su 二进制搜索路径
/// 常见 Linux/Android su 二进制搜索路径(包含现代 KernelSU / APatch / Magisk 扩展路径)
static const List<String> _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<String> _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<bool> isRootAvailablePassive({Duration timeout = const Duration(seconds: 4)}) async {
if (mockRootGranted != null) {
return mockRootGranted!;
}
if (!isDeviceRootCapable()) {
return false;
}
try {
final result = await Process.run(
'su',
+83
View File
@@ -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,
};
}
}
+16 -28
View File
@@ -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),
+8 -40
View File
@@ -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<CodeEditorDrawer> {
int _selectedIndex = 0;
int _selectedIndex = CodeEditorDrawer.lastSelectedTabIndex;
static ProjectProvider _getProjectProvider(
BuildContext context, {
@@ -151,6 +155,7 @@ class _CodeEditorDrawerState extends State<CodeEditorDrawer> {
if (_selectedIndex != index) {
setState(() {
_selectedIndex = index;
CodeEditorDrawer.lastSelectedTabIndex = index;
});
}
},
@@ -442,44 +447,7 @@ class _CodeEditorDrawerState extends State<CodeEditorDrawer> {
);
}
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<CodeEditorDrawer> {
index: _selectedIndex,
children: [
_buildExplorerPage(context, l10n, theme, rootPath, hasProject),
_buildSearchPlaceholder(context, l10n, theme),
const SearchPanelWidget(),
_buildGitPlaceholder(context, l10n, theme),
],
),
+112
View File
@@ -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<CodeEditorWidget> {
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<CodeEditorWidget> {
});
}
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<CodeEditorWidget> {
_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<CodeEditorWidget> {
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<SearchProvider?>();
_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<CodeEditorWidget> {
child: CodeEditor(
key: ValueKey(_currentLoadedPath),
controller: controller,
findController: _findController,
focusNode: _focusNode,
scrollController: _scrollController,
wordWrap: activeWordWrap,
@@ -843,6 +940,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
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<CodeEditorWidget> {
);
_controller = newController;
_findController?.dispose();
_findController = CodeFindController(newController);
_currentLoadedPath = fullFilePath;
_currentIndentSize = activeIndentSize;
_errorMessage = null;
@@ -1057,6 +1157,11 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
if (mounted) {
setState(() {});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_handleNavigationTarget(provider);
}
});
}
return;
}
@@ -1090,6 +1195,8 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
);
_controller = newController;
_findController?.dispose();
_findController = CodeFindController(newController);
_currentLoadedPath = fullFilePath;
_currentIndentSize = activeIndentSize;
_errorMessage = null;
@@ -1120,6 +1227,11 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
provider.setModified(tab?.isModified ?? false);
provider.registerSaveHandler(() => _saveFile());
} catch (_) {}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
_handleNavigationTarget(provider);
}
});
}
} catch (e) {
if (!mounted || requestVersion != _currentLoadVersion) return;
+6 -30
View File
@@ -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<FileItemWidget> {
}
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 {
File diff suppressed because it is too large. Load diff