1
This commit is contained in:
1 parent
8531403c33
commit
b03ece33a2
37 files changed
+6388
-908
No files matched your search
@@ -1,265 +1,111 @@
|
||||
import 'package:code_editor/models/editor_tab_item.dart';
|
||||
import 'package:code_editor/models/editor_theme.dart';
|
||||
import 'package:code_editor/models/file_directory_history.dart';
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:code_editor/services/file_directory_history_service.dart';
|
||||
import 'package:code_editor/services/file_service.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 组合门面 Provider,委托给 SettingsProvider, ProjectProvider, TabProvider,
|
||||
/// 保持向下兼容性与测试透明度。
|
||||
class EditorProvider extends ChangeNotifier {
|
||||
FileDirectoryHistory _history = const FileDirectoryHistory(
|
||||
rootPath: null,
|
||||
lastOpenedFilePath: "未命名",
|
||||
);
|
||||
List<FileItem> _items = [];
|
||||
bool _isLoading = false;
|
||||
FileItem? _cutItem;
|
||||
FileItem? _copiedItem;
|
||||
final SettingsProvider settingsProvider;
|
||||
final ProjectProvider projectProvider;
|
||||
final TabProvider tabProvider;
|
||||
|
||||
FileDirectoryHistory get history => _history;
|
||||
String? get rootPath => _history.rootPath;
|
||||
String? get currentFilePath => _history.lastOpenedFilePath;
|
||||
List<String> get openDirectoryPaths => _history.openDirectoryPaths;
|
||||
List<FileItem> get items => _items;
|
||||
bool get isLoading => _isLoading;
|
||||
FileItem? get cutItem => _cutItem;
|
||||
FileItem? get copiedItem => _copiedItem;
|
||||
bool get canPaste => _cutItem != null || _copiedItem != null;
|
||||
|
||||
bool isFileSelected(String path) {
|
||||
if (currentFilePath == null) return false;
|
||||
return currentFilePath == path || currentFilePath!.trim() == path.trim();
|
||||
EditorProvider({
|
||||
SettingsProvider? settings,
|
||||
ProjectProvider? project,
|
||||
TabProvider? tab,
|
||||
}) : settingsProvider = settings ?? SettingsProvider(),
|
||||
projectProvider = project ?? ProjectProvider(),
|
||||
tabProvider = tab ?? TabProvider() {
|
||||
tabProvider.bindProjectProvider(projectProvider);
|
||||
settingsProvider.addListener(notifyListeners);
|
||||
projectProvider.addListener(notifyListeners);
|
||||
tabProvider.addListener(notifyListeners);
|
||||
}
|
||||
|
||||
bool isItemCut(String path) {
|
||||
if (_cutItem == null) return false;
|
||||
return _cutItem!.path == path || _cutItem!.path.trim() == path.trim();
|
||||
@override
|
||||
void dispose() {
|
||||
settingsProvider.removeListener(notifyListeners);
|
||||
projectProvider.removeListener(notifyListeners);
|
||||
tabProvider.removeListener(notifyListeners);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
await _loadProjectFromHistory();
|
||||
await settingsProvider.init();
|
||||
await projectProvider.init();
|
||||
await tabProvider.init();
|
||||
}
|
||||
|
||||
Future<void> _loadProjectFromHistory() async {
|
||||
_isLoading = true;
|
||||
notifyListeners();
|
||||
// =================== Settings Provider Getters & Methods ===================
|
||||
EditorTheme get editorTheme => settingsProvider.editorTheme;
|
||||
ThemeMode get appThemeMode => settingsProvider.appThemeMode;
|
||||
double get fontSize => settingsProvider.fontSize;
|
||||
bool get wordWrap => settingsProvider.wordWrap;
|
||||
Locale? get locale => settingsProvider.locale;
|
||||
|
||||
try {
|
||||
final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory();
|
||||
if (lastHistory == null) {
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
Future<void> setEditorTheme(EditorTheme theme) => settingsProvider.setEditorTheme(theme);
|
||||
Future<void> setAppThemeMode(ThemeMode mode) => settingsProvider.setAppThemeMode(mode);
|
||||
Future<void> setFontSize(double size) => settingsProvider.setFontSize(size);
|
||||
Future<void> setWordWrap(bool wrap) => settingsProvider.setWordWrap(wrap);
|
||||
Future<void> setLocale(Locale? newLocale) => settingsProvider.setLocale(newLocale);
|
||||
|
||||
final path = lastHistory.rootPath;
|
||||
final cleanPath = (path != null && path.trim().isNotEmpty) ? p.normalize(path.trim()) : null;
|
||||
final validOpenPaths = cleanPath == null
|
||||
? <String>[]
|
||||
: lastHistory.openDirectoryPaths
|
||||
.map((e) => p.normalize(e.trim()))
|
||||
.where((e) => e != cleanPath && p.isWithin(cleanPath, e))
|
||||
.toList();
|
||||
// =================== Project Provider Getters & Methods ===================
|
||||
FileDirectoryHistory get history => projectProvider.history;
|
||||
String? get rootPath => projectProvider.rootPath;
|
||||
List<String> get openDirectoryPaths => projectProvider.openDirectoryPaths;
|
||||
List<FileItem> get items => projectProvider.items;
|
||||
bool get isLoading => projectProvider.isLoading;
|
||||
FileItem? get cutItem => projectProvider.cutItem;
|
||||
FileItem? get copiedItem => projectProvider.copiedItem;
|
||||
bool get canPaste => projectProvider.canPaste;
|
||||
|
||||
List<FileItem> items = cleanPath != null
|
||||
? await FileService.instance.buildTree(
|
||||
cleanPath,
|
||||
openDirectoryPaths: validOpenPaths,
|
||||
)
|
||||
: [];
|
||||
bool isItemCut(String path) => projectProvider.isItemCut(path);
|
||||
Future<void> openDirectory() => projectProvider.openDirectory();
|
||||
Future<void> switchProject(FileDirectoryHistory selectedHistory) => projectProvider.switchProject(selectedHistory);
|
||||
Future<void> toggleDirectory(FileItem item, bool expanded) => projectProvider.toggleDirectory(item, expanded);
|
||||
Future<void> refreshTree() => projectProvider.refreshTree();
|
||||
void cut(FileItem item) => projectProvider.cut(item);
|
||||
void copy(FileItem item) => projectProvider.copy(item);
|
||||
Future<void> paste(FileItem targetDir) => projectProvider.paste(targetDir);
|
||||
Future<void> createFile(String parentDir, String name) => projectProvider.createFile(parentDir, name);
|
||||
Future<void> createDirectory(String parentDir, String name) => projectProvider.createDirectory(parentDir, name);
|
||||
Future<void> rename(FileItem item, String newName) => projectProvider.rename(item, newName);
|
||||
Future<void> delete(FileItem item) => projectProvider.delete(item);
|
||||
|
||||
_items = items;
|
||||
_history = FileDirectoryHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: lastHistory.lastOpenedFilePath,
|
||||
openDirectoryPaths: validOpenPaths,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('加载项目历史失败: $e');
|
||||
} finally {
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
@visibleForTesting
|
||||
void setHistoryForTesting(FileDirectoryHistory history) {
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
projectProvider.setHistoryForTesting(history);
|
||||
}
|
||||
|
||||
Future<void> openDirectory() async {
|
||||
try {
|
||||
final String? selectedPath = await FilePicker.platform.getDirectoryPath();
|
||||
if (selectedPath == null || selectedPath.trim().isEmpty) {
|
||||
return;
|
||||
}
|
||||
// =================== Tab Provider Getters & Methods ===================
|
||||
List<EditorTabItem> get openTabs => tabProvider.openTabs;
|
||||
EditorTabItem? get activeTab => tabProvider.activeTab;
|
||||
String? get currentFilePath => tabProvider.currentFilePath;
|
||||
bool get isModified => tabProvider.isModified;
|
||||
|
||||
final cleanPath = p.normalize(selectedPath.trim());
|
||||
final currentRoot = _history.rootPath != null ? p.normalize(_history.rootPath!) : null;
|
||||
final isSameRoot = currentRoot != null && cleanPath == currentRoot;
|
||||
bool isFileSelected(String path) => tabProvider.isFileSelected(path);
|
||||
Future<void> selectFile(FileItem item) => tabProvider.selectFile(item);
|
||||
Future<void> openFile(String path, {String? content}) => tabProvider.openFile(path, content: content);
|
||||
Future<bool> closeTab(BuildContext context, int index) => tabProvider.closeTab(context, index);
|
||||
Future<void> reorderTabs(int oldIndex, int newIndex) => tabProvider.reorderTabs(oldIndex, newIndex);
|
||||
Future<bool> saveTab(EditorTabItem tab) => tabProvider.saveTab(tab);
|
||||
Future<bool> saveCurrentFile() => tabProvider.saveCurrentFile();
|
||||
Future<bool> saveAllFiles() => tabProvider.saveAllFiles();
|
||||
Future<bool> checkUnsavedChanges(BuildContext context) => tabProvider.checkUnsavedChanges(context);
|
||||
void registerSaveHandler(Future<bool> Function()? handler) => tabProvider.registerSaveHandler(handler);
|
||||
void setModified(bool modified) => tabProvider.setModified(modified);
|
||||
void updateActiveTabContent(String content, {bool? isModified}) =>
|
||||
tabProvider.updateActiveTabContent(content, isModified: isModified);
|
||||
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: isSameRoot ? _history.lastOpenedFilePath : null,
|
||||
openDirectoryPaths: isSameRoot ? _history.openDirectoryPaths : const [],
|
||||
);
|
||||
|
||||
_cutItem = null;
|
||||
_copiedItem = null;
|
||||
|
||||
await _loadProjectFromHistory();
|
||||
} catch (e) {
|
||||
debugPrint('打开文件夹失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> switchProject(FileDirectoryHistory selectedHistory) async {
|
||||
final selectedRoot = selectedHistory.rootPath;
|
||||
if (selectedRoot == null || selectedRoot.trim().isEmpty) return;
|
||||
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: selectedRoot,
|
||||
lastOpenedFilePath: selectedHistory.lastOpenedFilePath,
|
||||
openDirectoryPaths: selectedHistory.openDirectoryPaths,
|
||||
);
|
||||
|
||||
_cutItem = null;
|
||||
_copiedItem = null;
|
||||
|
||||
await _loadProjectFromHistory();
|
||||
}
|
||||
|
||||
Future<void> selectFile(FileItem item) async {
|
||||
if (item.isDirectory) return;
|
||||
final cleanPath = _history.rootPath;
|
||||
if (cleanPath != null) {
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: item.path,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
);
|
||||
_history = FileDirectoryHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: item.path,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> toggleDirectory(FileItem item, bool expanded) async {
|
||||
final cleanPath = _history.rootPath;
|
||||
if (cleanPath == null) return;
|
||||
|
||||
final updatedOpenPaths = List<String>.from(_history.openDirectoryPaths);
|
||||
if (expanded) {
|
||||
if (!updatedOpenPaths.contains(item.path)) {
|
||||
updatedOpenPaths.add(item.path);
|
||||
}
|
||||
if (item.children.isEmpty) {
|
||||
final children = await FileService.instance.buildTree(
|
||||
item.path,
|
||||
depth: item.depth + 1,
|
||||
openDirectoryPaths: updatedOpenPaths,
|
||||
);
|
||||
item.children.clear();
|
||||
item.children.addAll(children);
|
||||
}
|
||||
} else {
|
||||
updatedOpenPaths.remove(item.path);
|
||||
}
|
||||
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: _history.lastOpenedFilePath,
|
||||
openDirectoryPaths: updatedOpenPaths,
|
||||
);
|
||||
_history = FileDirectoryHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: _history.lastOpenedFilePath,
|
||||
openDirectoryPaths: updatedOpenPaths,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> refreshTree() async {
|
||||
final currentRoot = _history.rootPath;
|
||||
if (currentRoot == null || currentRoot.trim().isEmpty) return;
|
||||
|
||||
try {
|
||||
final items = await FileService.instance.buildTree(
|
||||
currentRoot,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
);
|
||||
|
||||
String? currentFile = _history.lastOpenedFilePath;
|
||||
if (currentFile != null) {
|
||||
final exists = await FileService.instance.entityExists(currentFile);
|
||||
if (!exists) {
|
||||
currentFile = null;
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: currentRoot,
|
||||
lastOpenedFilePath: null,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
_items = items;
|
||||
if (currentFile != _history.lastOpenedFilePath) {
|
||||
_history = FileDirectoryHistory(
|
||||
rootPath: currentRoot,
|
||||
lastOpenedFilePath: currentFile,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('刷新目录树失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void cut(FileItem item) {
|
||||
_cutItem = item;
|
||||
_copiedItem = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void copy(FileItem item) {
|
||||
_copiedItem = item;
|
||||
_cutItem = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> paste(FileItem targetDir) async {
|
||||
if (!targetDir.isDirectory) return;
|
||||
|
||||
if (_cutItem != null) {
|
||||
final source = _cutItem!;
|
||||
await FileService.instance.moveEntity(source.path, targetDir.path);
|
||||
_cutItem = null;
|
||||
await refreshTree();
|
||||
} else if (_copiedItem != null) {
|
||||
final source = _copiedItem!;
|
||||
await FileService.instance.copyEntity(source.path, targetDir.path);
|
||||
await refreshTree();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> createFile(String parentDir, String name) async {
|
||||
final targetPath = p.join(parentDir, name.trim());
|
||||
await FileService.instance.createFile(targetPath);
|
||||
await refreshTree();
|
||||
}
|
||||
|
||||
Future<void> createDirectory(String parentDir, String name) async {
|
||||
final targetPath = p.join(parentDir, name.trim());
|
||||
await FileService.instance.createDirectory(targetPath);
|
||||
await refreshTree();
|
||||
}
|
||||
|
||||
Future<void> rename(FileItem item, String newName) async {
|
||||
await FileService.instance.renameEntity(item.path, newName.trim());
|
||||
await refreshTree();
|
||||
}
|
||||
|
||||
Future<void> delete(FileItem item) async {
|
||||
await FileService.instance.deleteEntity(item.path);
|
||||
await refreshTree();
|
||||
@visibleForTesting
|
||||
void setOpenTabsForTesting(List<EditorTabItem> tabs, {String? activePath}) {
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
tabProvider.setOpenTabsForTesting(tabs, activePath: activePath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/models/file_directory_history.dart';
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:code_editor/services/file_directory_history_service.dart';
|
||||
import 'package:code_editor/services/file_service.dart';
|
||||
import 'package:code_editor/services/file_watcher_service.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
class ProjectProvider extends ChangeNotifier {
|
||||
FileDirectoryHistory _history = const FileDirectoryHistory(
|
||||
rootPath: null,
|
||||
lastOpenedFilePath: null,
|
||||
);
|
||||
List<FileItem> _items = [];
|
||||
bool _isLoading = false;
|
||||
FileItem? _cutItem;
|
||||
FileItem? _copiedItem;
|
||||
|
||||
// 跨 Provider 协同回调
|
||||
void Function(String oldPath, String newPath)? onEntityRenamed;
|
||||
void Function(String deletedPath)? onEntityDeleted;
|
||||
void Function(String? rootPath, List<String> openFilePaths, String? lastOpenedFilePath)? onProjectChanged;
|
||||
void Function(String modifiedPath)? onExternalFileModified;
|
||||
void Function(String deletedPath)? onExternalFileDeleted;
|
||||
|
||||
FileDirectoryHistory get history => _history;
|
||||
String? get rootPath => _history.rootPath;
|
||||
List<String> get openDirectoryPaths => _history.openDirectoryPaths;
|
||||
List<FileItem> get items => _items;
|
||||
bool get isLoading => _isLoading;
|
||||
FileItem? get cutItem => _cutItem;
|
||||
FileItem? get copiedItem => _copiedItem;
|
||||
bool get canPaste => _cutItem != null || _copiedItem != null;
|
||||
|
||||
bool isItemCut(String path) {
|
||||
if (_cutItem == null) return false;
|
||||
return _cutItem!.path == path || _cutItem!.path.trim() == path.trim();
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
await _loadProjectFromHistory();
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
void setHistoryForTesting(FileDirectoryHistory history) {
|
||||
_history = history;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
void setItemsForTesting(List<FileItem> items) {
|
||||
_items = items;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _loadProjectFromHistory() async {
|
||||
_isLoading = true;
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory();
|
||||
if (lastHistory == null) {
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
final path = lastHistory.rootPath;
|
||||
final cleanPath = (path != null && path.trim().isNotEmpty) ? p.normalize(path.trim()) : null;
|
||||
final validOpenPaths = cleanPath == null
|
||||
? <String>[]
|
||||
: lastHistory.openDirectoryPaths
|
||||
.map((e) => p.normalize(e.trim()))
|
||||
.where((e) => e != cleanPath && p.isWithin(cleanPath, e))
|
||||
.toList();
|
||||
|
||||
List<FileItem> items = cleanPath != null
|
||||
? await FileService.instance.buildTree(
|
||||
cleanPath,
|
||||
openDirectoryPaths: validOpenPaths,
|
||||
)
|
||||
: [];
|
||||
|
||||
_items = items;
|
||||
_history = FileDirectoryHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: lastHistory.lastOpenedFilePath,
|
||||
openDirectoryPaths: validOpenPaths,
|
||||
openFilePaths: lastHistory.openFilePaths,
|
||||
);
|
||||
|
||||
// 启动外部文件变动监听服务
|
||||
_startWatcher(cleanPath);
|
||||
|
||||
// 通知外部(例如 TabProvider)同步标签页历史
|
||||
onProjectChanged?.call(cleanPath, lastHistory.openFilePaths, lastHistory.lastOpenedFilePath);
|
||||
} catch (e) {
|
||||
debugPrint('加载项目历史失败: $e');
|
||||
} finally {
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> openDirectory() async {
|
||||
try {
|
||||
final String? selectedPath = await FilePicker.platform.getDirectoryPath();
|
||||
if (selectedPath == null || selectedPath.trim().isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
final cleanPath = p.normalize(selectedPath.trim());
|
||||
final currentRoot = _history.rootPath != null ? p.normalize(_history.rootPath!) : null;
|
||||
final isSameRoot = currentRoot != null && cleanPath == currentRoot;
|
||||
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: isSameRoot ? _history.lastOpenedFilePath : null,
|
||||
openDirectoryPaths: isSameRoot ? _history.openDirectoryPaths : const [],
|
||||
openFilePaths: isSameRoot ? _history.openFilePaths : const [],
|
||||
);
|
||||
|
||||
_cutItem = null;
|
||||
_copiedItem = null;
|
||||
|
||||
await _loadProjectFromHistory();
|
||||
} catch (e) {
|
||||
debugPrint('打开文件夹失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> switchProject(FileDirectoryHistory selectedHistory) async {
|
||||
final selectedRoot = selectedHistory.rootPath;
|
||||
if (selectedRoot == null || selectedRoot.trim().isEmpty) return;
|
||||
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: selectedRoot,
|
||||
lastOpenedFilePath: selectedHistory.lastOpenedFilePath,
|
||||
openDirectoryPaths: selectedHistory.openDirectoryPaths,
|
||||
openFilePaths: selectedHistory.openFilePaths,
|
||||
);
|
||||
|
||||
_cutItem = null;
|
||||
_copiedItem = null;
|
||||
|
||||
await _loadProjectFromHistory();
|
||||
}
|
||||
|
||||
Future<void> toggleDirectory(FileItem item, bool expanded) async {
|
||||
final cleanPath = _history.rootPath;
|
||||
if (cleanPath == null) return;
|
||||
|
||||
final updatedOpenPaths = List<String>.from(_history.openDirectoryPaths);
|
||||
if (expanded) {
|
||||
if (!updatedOpenPaths.contains(item.path)) {
|
||||
updatedOpenPaths.add(item.path);
|
||||
}
|
||||
if (item.children.isEmpty) {
|
||||
final children = await FileService.instance.buildTree(
|
||||
item.path,
|
||||
depth: item.depth + 1,
|
||||
openDirectoryPaths: updatedOpenPaths,
|
||||
);
|
||||
item.children.clear();
|
||||
item.children.addAll(children);
|
||||
}
|
||||
} else {
|
||||
updatedOpenPaths.remove(item.path);
|
||||
}
|
||||
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: _history.lastOpenedFilePath,
|
||||
openDirectoryPaths: updatedOpenPaths,
|
||||
openFilePaths: _history.openFilePaths,
|
||||
);
|
||||
_history = FileDirectoryHistory(
|
||||
rootPath: cleanPath,
|
||||
lastOpenedFilePath: _history.lastOpenedFilePath,
|
||||
openDirectoryPaths: updatedOpenPaths,
|
||||
openFilePaths: _history.openFilePaths,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> refreshTree() async {
|
||||
final currentRoot = _history.rootPath;
|
||||
if (currentRoot == null || currentRoot.trim().isEmpty) return;
|
||||
|
||||
try {
|
||||
final items = await FileService.instance.buildTree(
|
||||
currentRoot,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
);
|
||||
|
||||
String? currentFile = _history.lastOpenedFilePath;
|
||||
if (currentFile != null) {
|
||||
final exists = await FileService.instance.entityExists(currentFile);
|
||||
if (!exists) {
|
||||
currentFile = null;
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: currentRoot,
|
||||
lastOpenedFilePath: null,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
openFilePaths: _history.openFilePaths,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
_items = items;
|
||||
if (currentFile != _history.lastOpenedFilePath) {
|
||||
_history = FileDirectoryHistory(
|
||||
rootPath: currentRoot,
|
||||
lastOpenedFilePath: currentFile,
|
||||
openDirectoryPaths: _history.openDirectoryPaths,
|
||||
openFilePaths: _history.openFilePaths,
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('刷新目录树失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void cut(FileItem item) {
|
||||
_cutItem = item;
|
||||
_copiedItem = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void copy(FileItem item) {
|
||||
_copiedItem = item;
|
||||
_cutItem = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> paste(FileItem targetDir) async {
|
||||
if (!targetDir.isDirectory) return;
|
||||
|
||||
if (_cutItem != null) {
|
||||
final source = _cutItem!;
|
||||
await FileService.instance.moveEntity(source.path, targetDir.path);
|
||||
_cutItem = null;
|
||||
await refreshTree();
|
||||
} else if (_copiedItem != null) {
|
||||
final source = _copiedItem!;
|
||||
await FileService.instance.copyEntity(source.path, targetDir.path);
|
||||
await refreshTree();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> createFile(String parentDir, String name) async {
|
||||
final targetPath = p.join(parentDir, name.trim());
|
||||
await FileService.instance.createFile(targetPath);
|
||||
await refreshTree();
|
||||
}
|
||||
|
||||
Future<void> createDirectory(String parentDir, String name) async {
|
||||
final targetPath = p.join(parentDir, name.trim());
|
||||
await FileService.instance.createDirectory(targetPath);
|
||||
await refreshTree();
|
||||
}
|
||||
|
||||
Future<void> rename(FileItem item, String newName) async {
|
||||
final targetPath = p.normalize(p.join(p.dirname(item.path), newName.trim()));
|
||||
await FileService.instance.renameEntity(item.path, newName.trim());
|
||||
final oldNormalized = p.normalize(item.path);
|
||||
|
||||
onEntityRenamed?.call(oldNormalized, targetPath);
|
||||
|
||||
await refreshTree();
|
||||
}
|
||||
|
||||
Future<void> delete(FileItem item) async {
|
||||
await FileService.instance.deleteEntity(item.path);
|
||||
final oldNormalized = p.normalize(item.path);
|
||||
|
||||
onEntityDeleted?.call(oldNormalized);
|
||||
|
||||
await refreshTree();
|
||||
}
|
||||
|
||||
void _startWatcher(String? rootPath) {
|
||||
if (rootPath == null || rootPath.isEmpty) {
|
||||
FileWatcherService.instance.stopWatching();
|
||||
return;
|
||||
}
|
||||
FileWatcherService.instance.startWatching(
|
||||
rootPath,
|
||||
onEvents: _onFileSystemEvents,
|
||||
);
|
||||
}
|
||||
|
||||
void _onFileSystemEvents(List<FileSystemEvent> events) {
|
||||
bool needRefreshTree = false;
|
||||
|
||||
for (final event in events) {
|
||||
final normalizedPath = p.normalize(event.path);
|
||||
|
||||
if (event is FileSystemCreateEvent) {
|
||||
needRefreshTree = true;
|
||||
} else if (event is FileSystemDeleteEvent) {
|
||||
needRefreshTree = true;
|
||||
onExternalFileDeleted?.call(normalizedPath);
|
||||
} else if (event is FileSystemMoveEvent) {
|
||||
needRefreshTree = true;
|
||||
final dest = event.destination;
|
||||
if (dest != null) {
|
||||
onEntityRenamed?.call(normalizedPath, p.normalize(dest));
|
||||
} else {
|
||||
onExternalFileDeleted?.call(normalizedPath);
|
||||
}
|
||||
} else if (event is FileSystemModifyEvent) {
|
||||
if (event.isDirectory) {
|
||||
needRefreshTree = true;
|
||||
} else {
|
||||
onExternalFileModified?.call(normalizedPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (needRefreshTree) {
|
||||
refreshTree();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
FileWatcherService.instance.stopWatching();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'package:code_editor/models/editor_theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class SettingsProvider extends ChangeNotifier {
|
||||
static const String _keyEditorTheme = 'editor_theme_id';
|
||||
static const String _keyAppThemeMode = 'app_theme_mode';
|
||||
static const String _keyEditorFontSize = 'editor_font_size';
|
||||
static const String _keyWordWrap = 'editor_word_wrap';
|
||||
static const String _keyAppLocale = 'app_locale';
|
||||
|
||||
EditorTheme _editorTheme = EditorTheme.atomOneDark;
|
||||
ThemeMode _appThemeMode = ThemeMode.system;
|
||||
double _fontSize = 14.0;
|
||||
bool _wordWrap = true;
|
||||
Locale? _locale;
|
||||
|
||||
EditorTheme get editorTheme => _editorTheme;
|
||||
ThemeMode get appThemeMode => _appThemeMode;
|
||||
double get fontSize => _fontSize;
|
||||
bool get wordWrap => _wordWrap;
|
||||
Locale? get locale => _locale;
|
||||
|
||||
Future<void> init() async {
|
||||
await _loadSettings();
|
||||
}
|
||||
|
||||
Future<void> _loadSettings() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final themeId = prefs.getString(_keyEditorTheme);
|
||||
_editorTheme = EditorTheme.fromId(themeId);
|
||||
|
||||
final themeModeName = prefs.getString(_keyAppThemeMode);
|
||||
if (themeModeName != null) {
|
||||
_appThemeMode = ThemeMode.values.firstWhere(
|
||||
(e) => e.name == themeModeName,
|
||||
orElse: () => ThemeMode.system,
|
||||
);
|
||||
}
|
||||
|
||||
final savedFontSize = prefs.getDouble(_keyEditorFontSize);
|
||||
if (savedFontSize != null && savedFontSize >= 10 && savedFontSize <= 32) {
|
||||
_fontSize = savedFontSize;
|
||||
}
|
||||
|
||||
final savedWordWrap = prefs.getBool(_keyWordWrap);
|
||||
if (savedWordWrap != null) {
|
||||
_wordWrap = savedWordWrap;
|
||||
}
|
||||
|
||||
final savedLocale = prefs.getString(_keyAppLocale);
|
||||
if (savedLocale != null && savedLocale.isNotEmpty) {
|
||||
_locale = Locale(savedLocale);
|
||||
} else {
|
||||
_locale = null; // null 表示跟随系统
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setEditorTheme(EditorTheme theme) async {
|
||||
if (_editorTheme.id == theme.id) return;
|
||||
_editorTheme = theme;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyEditorTheme, theme.id);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setAppThemeMode(ThemeMode mode) async {
|
||||
if (_appThemeMode == mode) return;
|
||||
_appThemeMode = mode;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyAppThemeMode, mode.name);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setFontSize(double size) async {
|
||||
final clamped = size.clamp(10.0, 30.0);
|
||||
if (_fontSize == clamped) return;
|
||||
_fontSize = clamped;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setDouble(_keyEditorFontSize, clamped);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setWordWrap(bool wrap) async {
|
||||
if (_wordWrap == wrap) return;
|
||||
_wordWrap = wrap;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyWordWrap, wrap);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setLocale(Locale? newLocale) async {
|
||||
if (_locale == newLocale) return;
|
||||
_locale = newLocale;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (newLocale == null) {
|
||||
await prefs.remove(_keyAppLocale);
|
||||
} else {
|
||||
await prefs.setString(_keyAppLocale, newLocale.languageCode);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/editor_tab_item.dart';
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/services/file_directory_history_service.dart';
|
||||
import 'package:code_editor/services/file_service.dart';
|
||||
import 'package:code_editor/services/file_watcher_service.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
class TabProvider extends ChangeNotifier {
|
||||
List<EditorTabItem> _openTabs = [];
|
||||
String? _activeFilePath;
|
||||
bool _isModified = false;
|
||||
Future<bool> Function()? _saveHandler;
|
||||
|
||||
ProjectProvider? _projectProvider;
|
||||
|
||||
List<EditorTabItem> get openTabs => _openTabs;
|
||||
EditorTabItem? get activeTab {
|
||||
if (_activeFilePath == null) return null;
|
||||
final index = _openTabs.indexWhere((tab) => p.equals(tab.path, _activeFilePath!));
|
||||
return index != -1 ? _openTabs[index] : null;
|
||||
}
|
||||
|
||||
String? get currentFilePath => _activeFilePath;
|
||||
bool get isModified => activeTab?.isModified ?? _isModified;
|
||||
|
||||
void bindProjectProvider(ProjectProvider projectProvider) {
|
||||
if (_projectProvider == projectProvider) return;
|
||||
_projectProvider = projectProvider;
|
||||
projectProvider.onEntityRenamed = handleEntityRenamed;
|
||||
projectProvider.onEntityDeleted = handleEntityDeleted;
|
||||
projectProvider.onProjectChanged = handleProjectChanged;
|
||||
projectProvider.onExternalFileModified = handleExternalFileModified;
|
||||
projectProvider.onExternalFileDeleted = handleExternalFileDeleted;
|
||||
}
|
||||
|
||||
bool isFileSelected(String path) {
|
||||
if (_activeFilePath == null) return false;
|
||||
return p.equals(_activeFilePath!, path);
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
await _loadTabsFromHistory();
|
||||
}
|
||||
|
||||
Future<void> _loadTabsFromHistory() async {
|
||||
try {
|
||||
final lastHistory = await FileDirectoryHistoryService.instance.getLastHistory();
|
||||
if (lastHistory == null) return;
|
||||
await handleProjectChanged(
|
||||
lastHistory.rootPath,
|
||||
lastHistory.openFilePaths,
|
||||
lastHistory.lastOpenedFilePath,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('加载标签页历史失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> handleProjectChanged(
|
||||
String? rootPath,
|
||||
List<String> openFilePaths,
|
||||
String? lastOpenedFilePath,
|
||||
) async {
|
||||
final List<EditorTabItem> loadedTabs = [];
|
||||
|
||||
for (final filePath in openFilePaths) {
|
||||
final cleanFilePath = p.normalize(filePath.trim());
|
||||
if (await FileService.instance.entityExists(cleanFilePath)) {
|
||||
loadedTabs.add(EditorTabItem(
|
||||
path: cleanFilePath,
|
||||
isModified: false,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (loadedTabs.isEmpty && lastOpenedFilePath != null && lastOpenedFilePath.trim().isNotEmpty) {
|
||||
final cleanLast = p.normalize(lastOpenedFilePath.trim());
|
||||
if (await FileService.instance.entityExists(cleanLast)) {
|
||||
loadedTabs.add(EditorTabItem(
|
||||
path: cleanLast,
|
||||
isModified: false,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
_openTabs = loadedTabs;
|
||||
|
||||
if (lastOpenedFilePath != null && _openTabs.any((t) => p.equals(t.path, lastOpenedFilePath.trim()))) {
|
||||
_activeFilePath = _openTabs.firstWhere((t) => p.equals(t.path, lastOpenedFilePath.trim())).path;
|
||||
} else if (_openTabs.isNotEmpty) {
|
||||
_activeFilePath = _openTabs.first.path;
|
||||
} else {
|
||||
_activeFilePath = null;
|
||||
}
|
||||
|
||||
_isModified = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void handleEntityRenamed(String oldNormalized, String targetPath) {
|
||||
for (int i = 0; i < _openTabs.length; i++) {
|
||||
final tabPath = _openTabs[i].path;
|
||||
if (p.equals(tabPath, oldNormalized)) {
|
||||
_openTabs[i] = EditorTabItem(
|
||||
path: targetPath,
|
||||
content: _openTabs[i].content,
|
||||
originalContent: _openTabs[i].originalContent,
|
||||
isModified: _openTabs[i].isModified,
|
||||
isLoaded: _openTabs[i].isLoaded,
|
||||
verticalScrollOffset: _openTabs[i].verticalScrollOffset,
|
||||
horizontalScrollOffset: _openTabs[i].horizontalScrollOffset,
|
||||
);
|
||||
} else if (p.isWithin(oldNormalized, tabPath)) {
|
||||
final rel = p.relative(tabPath, from: oldNormalized);
|
||||
final newChildPath = p.normalize(p.join(targetPath, rel));
|
||||
_openTabs[i] = EditorTabItem(
|
||||
path: newChildPath,
|
||||
content: _openTabs[i].content,
|
||||
originalContent: _openTabs[i].originalContent,
|
||||
isModified: _openTabs[i].isModified,
|
||||
isLoaded: _openTabs[i].isLoaded,
|
||||
verticalScrollOffset: _openTabs[i].verticalScrollOffset,
|
||||
horizontalScrollOffset: _openTabs[i].horizontalScrollOffset,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (_activeFilePath != null) {
|
||||
if (p.equals(_activeFilePath!, oldNormalized)) {
|
||||
_activeFilePath = targetPath;
|
||||
} else if (p.isWithin(oldNormalized, _activeFilePath!)) {
|
||||
final rel = p.relative(_activeFilePath!, from: oldNormalized);
|
||||
_activeFilePath = p.normalize(p.join(targetPath, rel));
|
||||
}
|
||||
}
|
||||
|
||||
_persistTabsHistory();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void handleEntityDeleted(String oldNormalized) {
|
||||
_openTabs.removeWhere((tab) => p.equals(tab.path, oldNormalized) || p.isWithin(oldNormalized, tab.path));
|
||||
if (_activeFilePath != null && (p.equals(_activeFilePath!, oldNormalized) || p.isWithin(oldNormalized, _activeFilePath!))) {
|
||||
_activeFilePath = _openTabs.isNotEmpty ? _openTabs.first.path : null;
|
||||
_isModified = activeTab?.isModified ?? false;
|
||||
}
|
||||
_persistTabsHistory();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 处理外部文件内容被修改事件
|
||||
Future<void> handleExternalFileModified(String modifiedPath) async {
|
||||
final cleanPath = p.normalize(modifiedPath);
|
||||
final tabIndex = _openTabs.indexWhere((t) => p.equals(t.path, cleanPath));
|
||||
if (tabIndex == -1) return;
|
||||
final tab = _openTabs[tabIndex];
|
||||
|
||||
try {
|
||||
if (!await FileService.instance.entityExists(cleanPath)) return;
|
||||
final raw = await FileService.instance.readFileContent(cleanPath);
|
||||
final diskContent = raw.replaceAll('\r\n', '\n');
|
||||
|
||||
// 内容无实质改变则跳过
|
||||
if (tab.content == diskContent) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!tab.isModified) {
|
||||
// 未修改文件:静默无感热重载
|
||||
tab.content = diskContent;
|
||||
tab.originalContent = diskContent;
|
||||
tab.isLoaded = true;
|
||||
tab.hasExternalConflict = false;
|
||||
notifyListeners();
|
||||
} else {
|
||||
// 已修改文件:发生外部冲突,标记冲突以通知 UI 弹出提示,严禁直接覆盖
|
||||
tab.hasExternalConflict = true;
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('处理外部文件变动失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 解决外部文件冲突
|
||||
Future<void> resolveConflict(EditorTabItem tab, {required bool reloadFromDisk}) async {
|
||||
tab.hasExternalConflict = false;
|
||||
if (reloadFromDisk) {
|
||||
try {
|
||||
final raw = await FileService.instance.readFileContent(tab.path);
|
||||
final diskContent = raw.replaceAll('\r\n', '\n');
|
||||
tab.content = diskContent;
|
||||
tab.originalContent = diskContent;
|
||||
tab.isModified = false;
|
||||
if (_activeFilePath == tab.path) {
|
||||
_isModified = false;
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('重载外部文件失败: $e');
|
||||
}
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 处理外部文件被删除事件
|
||||
void handleExternalFileDeleted(String deletedPath) {
|
||||
final cleanPath = p.normalize(deletedPath);
|
||||
final affectedTabs = _openTabs
|
||||
.where((t) {
|
||||
final tClean = p.normalize(t.path);
|
||||
return tClean == cleanPath || p.isWithin(cleanPath, tClean);
|
||||
})
|
||||
.toList();
|
||||
|
||||
for (final tab in affectedTabs) {
|
||||
if (!tab.isModified) {
|
||||
// 未修改的文件安全自动关闭
|
||||
_openTabs.remove(tab);
|
||||
if (_activeFilePath == tab.path) {
|
||||
_activeFilePath = _openTabs.isNotEmpty ? _openTabs.first.path : null;
|
||||
_isModified = activeTab?.isModified ?? false;
|
||||
}
|
||||
} else {
|
||||
// 已修改的文件保留在标签栏防止丢代码,仅标记磁盘已被删除
|
||||
tab.isDeletedOnDisk = true;
|
||||
}
|
||||
}
|
||||
_persistTabsHistory();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _persistTabsHistory() async {
|
||||
final root = _projectProvider?.rootPath;
|
||||
if (root != null) {
|
||||
final openPaths = _openTabs.map((t) => t.path).toList();
|
||||
await FileDirectoryHistoryService.instance.recordHistory(
|
||||
rootPath: root,
|
||||
lastOpenedFilePath: _activeFilePath,
|
||||
openDirectoryPaths: _projectProvider?.openDirectoryPaths ?? const [],
|
||||
openFilePaths: openPaths,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
void setOpenTabsForTesting(List<EditorTabItem> tabs, {String? activePath}) {
|
||||
_openTabs = List.from(tabs);
|
||||
_activeFilePath = activePath ?? (_openTabs.isNotEmpty ? _openTabs.first.path : null);
|
||||
_isModified = activeTab?.isModified ?? false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
void setModifiedForTesting(bool modified) {
|
||||
_isModified = modified;
|
||||
if (activeTab != null) {
|
||||
activeTab!.isModified = modified;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setModified(bool modified) {
|
||||
if (isModified == modified) return;
|
||||
if (activeTab != null) {
|
||||
activeTab!.isModified = modified;
|
||||
}
|
||||
_isModified = modified;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void updateActiveTabContent(String content, {bool? isModified}) {
|
||||
final tab = activeTab;
|
||||
if (tab != null) {
|
||||
final normalized = content.replaceAll('\r\n', '\n');
|
||||
tab.content = normalized;
|
||||
if (isModified != null) {
|
||||
tab.isModified = isModified;
|
||||
} else {
|
||||
tab.isModified = normalized != tab.originalContent.replaceAll('\r\n', '\n');
|
||||
}
|
||||
_isModified = tab.isModified;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
void registerSaveHandler(Future<bool> Function()? handler) {
|
||||
_saveHandler = handler;
|
||||
}
|
||||
|
||||
Future<void> selectFile(FileItem item) async {
|
||||
if (item.isDirectory) return;
|
||||
await openFile(item.path);
|
||||
}
|
||||
|
||||
Future<void> openFile(String path, {String? content}) async {
|
||||
final cleanPath = p.normalize(path.trim());
|
||||
final existingIndex = _openTabs.indexWhere((tab) => p.equals(tab.path, cleanPath));
|
||||
if (existingIndex != -1) {
|
||||
_activeFilePath = _openTabs[existingIndex].path;
|
||||
_isModified = _openTabs[existingIndex].isModified;
|
||||
} else {
|
||||
String initialContent = content ?? '';
|
||||
bool loaded = false;
|
||||
if (content != null) {
|
||||
initialContent = initialContent.replaceAll('\r\n', '\n');
|
||||
loaded = true;
|
||||
} else {
|
||||
try {
|
||||
if (await FileService.instance.entityExists(cleanPath)) {
|
||||
final raw = await FileService.instance.readFileContent(cleanPath);
|
||||
initialContent = raw.replaceAll('\r\n', '\n');
|
||||
loaded = true;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
final tab = EditorTabItem(
|
||||
path: cleanPath,
|
||||
content: initialContent,
|
||||
originalContent: initialContent,
|
||||
isModified: false,
|
||||
isLoaded: loaded,
|
||||
);
|
||||
_openTabs.add(tab);
|
||||
_activeFilePath = cleanPath;
|
||||
_isModified = false;
|
||||
}
|
||||
|
||||
await _persistTabsHistory();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<bool> closeTab(BuildContext context, int index) async {
|
||||
if (index < 0 || index >= _openTabs.length) return false;
|
||||
final tab = _openTabs[index];
|
||||
|
||||
if (tab.isModified) {
|
||||
final result = await DialogUtils.showSavePromptDialog(
|
||||
context,
|
||||
fileName: tab.name,
|
||||
);
|
||||
switch (result) {
|
||||
case SavePromptResult.save:
|
||||
final saved = await saveTab(tab);
|
||||
if (!saved) return false;
|
||||
break;
|
||||
case SavePromptResult.discard:
|
||||
tab.isModified = false;
|
||||
break;
|
||||
case SavePromptResult.cancel:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
final wasActive = _activeFilePath != null && p.equals(tab.path, _activeFilePath!);
|
||||
_openTabs.removeAt(index);
|
||||
|
||||
if (wasActive) {
|
||||
if (_openTabs.isEmpty) {
|
||||
_activeFilePath = null;
|
||||
_isModified = false;
|
||||
} else {
|
||||
final newIndex = index.clamp(0, _openTabs.length - 1);
|
||||
_activeFilePath = _openTabs[newIndex].path;
|
||||
_isModified = _openTabs[newIndex].isModified;
|
||||
}
|
||||
}
|
||||
|
||||
await _persistTabsHistory();
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> reorderTabs(int oldIndex, int newIndex) async {
|
||||
if (oldIndex < 0 || oldIndex >= _openTabs.length) return;
|
||||
if (newIndex < 0 || newIndex >= _openTabs.length) return;
|
||||
final item = _openTabs.removeAt(oldIndex);
|
||||
_openTabs.insert(newIndex, item);
|
||||
await _persistTabsHistory();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<bool> saveTab(EditorTabItem tab) async {
|
||||
try {
|
||||
FileWatcherService.instance.markRecentlySaved(tab.path);
|
||||
if (_activeFilePath != null && p.equals(tab.path, _activeFilePath!) && _saveHandler != null) {
|
||||
final ok = await _saveHandler!();
|
||||
if (ok) {
|
||||
tab.originalContent = tab.content;
|
||||
tab.isModified = false;
|
||||
_isModified = false;
|
||||
notifyListeners();
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
await FileService.instance.saveFile(tab.path, tab.content);
|
||||
tab.originalContent = tab.content;
|
||||
tab.isModified = false;
|
||||
if (_activeFilePath != null && p.equals(tab.path, _activeFilePath!)) {
|
||||
_isModified = false;
|
||||
}
|
||||
notifyListeners();
|
||||
return true;
|
||||
} catch (e) {
|
||||
debugPrint('保存文件失败: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> saveCurrentFile() async {
|
||||
final tab = activeTab;
|
||||
if (tab != null) {
|
||||
return await saveTab(tab);
|
||||
}
|
||||
if (_saveHandler != null) {
|
||||
return await _saveHandler!();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Future<bool> saveAllFiles() async {
|
||||
if (_openTabs.isEmpty) {
|
||||
return await saveCurrentFile();
|
||||
}
|
||||
bool allSuccess = true;
|
||||
for (final tab in _openTabs) {
|
||||
if (tab.isModified) {
|
||||
FileWatcherService.instance.markRecentlySaved(tab.path);
|
||||
final ok = await saveTab(tab);
|
||||
if (!ok) allSuccess = false;
|
||||
}
|
||||
}
|
||||
notifyListeners();
|
||||
return allSuccess;
|
||||
}
|
||||
|
||||
/// 检查是否有未保存的更改;若有脏文件则弹出确认弹窗
|
||||
Future<bool> checkUnsavedChanges(BuildContext context) async {
|
||||
final dirtyTabs = _openTabs.where((t) => t.isModified).toList();
|
||||
if (dirtyTabs.isEmpty && !_isModified) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final result = await DialogUtils.showSaveAllPromptDialog(context);
|
||||
switch (result) {
|
||||
case SavePromptResult.save:
|
||||
final saved = await saveAllFiles();
|
||||
if (saved && context.mounted) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
DialogUtils.showSuccessToast(context, l10n?.saveAllSuccess ?? '所有文件已保存');
|
||||
}
|
||||
return saved;
|
||||
|
||||
case SavePromptResult.discard:
|
||||
for (final tab in _openTabs) {
|
||||
tab.isModified = false;
|
||||
}
|
||||
_isModified = false;
|
||||
notifyListeners();
|
||||
return true;
|
||||
|
||||
case SavePromptResult.cancel:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user