1
This commit is contained in:
1 parent
8531403c33
commit
b03ece33a2
37 files changed
+6388
-908
No files matched your search
@@ -4,18 +4,20 @@ import 'package:path/path.dart' as p;
|
||||
|
||||
class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
final String? filePath;
|
||||
final VoidCallback? onUndo;
|
||||
final VoidCallback? onRedo;
|
||||
final String? rootPath;
|
||||
final bool isModified;
|
||||
final VoidCallback? onSave;
|
||||
final VoidCallback? onSaveAll;
|
||||
final VoidCallback? onRun;
|
||||
final VoidCallback? onSettings;
|
||||
|
||||
const CodeEditorAppBar({
|
||||
super.key,
|
||||
required this.filePath,
|
||||
this.onUndo,
|
||||
this.onRedo,
|
||||
this.rootPath,
|
||||
this.isModified = false,
|
||||
this.onSave,
|
||||
this.onSaveAll,
|
||||
this.onRun,
|
||||
this.onSettings,
|
||||
});
|
||||
@@ -29,29 +31,59 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final path = filePath;
|
||||
|
||||
final String titleText;
|
||||
final String? subtitleText;
|
||||
if (path != null && path.isNotEmpty) {
|
||||
final base = p.basename(path);
|
||||
titleText = isModified ? '* $base' : base;
|
||||
|
||||
if (rootPath != null && rootPath!.trim().isNotEmpty) {
|
||||
final cleanRoot = p.normalize(rootPath!.trim());
|
||||
final cleanFile = p.normalize(path.trim());
|
||||
final dirPath = p.dirname(cleanFile);
|
||||
|
||||
if (dirPath == cleanRoot || !p.isWithin(cleanRoot, cleanFile)) {
|
||||
subtitleText = '/';
|
||||
} else {
|
||||
final rel = p.relative(dirPath, from: cleanRoot);
|
||||
final formattedRel = rel.replaceAll(r'\', '/');
|
||||
subtitleText = formattedRel.startsWith('/') ? formattedRel : '/$formattedRel';
|
||||
}
|
||||
} else {
|
||||
subtitleText = '/';
|
||||
}
|
||||
} else {
|
||||
titleText = '';
|
||||
subtitleText = null;
|
||||
}
|
||||
|
||||
return AppBar(
|
||||
backgroundColor: theme.colorScheme.primaryContainer,
|
||||
foregroundColor: theme.colorScheme.onPrimaryContainer,
|
||||
title: Text(path != null && path.isNotEmpty ? p.basename(path) : ''),
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
titleText,
|
||||
style: const TextStyle(
|
||||
fontSize: 16.0,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (subtitleText != null)
|
||||
Text(
|
||||
subtitleText,
|
||||
style: TextStyle(
|
||||
fontSize: 11.0,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.undo),
|
||||
tooltip: l10n.undo,
|
||||
onPressed: onUndo ?? () {},
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.redo),
|
||||
tooltip: l10n.redo,
|
||||
onPressed: onRedo ?? () {},
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.save_outlined),
|
||||
tooltip: l10n.save,
|
||||
onPressed: onSave ?? () {},
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.play_arrow),
|
||||
@@ -60,9 +92,43 @@ class CodeEditorAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
),
|
||||
IconButton(
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.settings),
|
||||
tooltip: l10n.settings,
|
||||
onPressed: onSettings ?? () {},
|
||||
icon: const Icon(Icons.save_outlined),
|
||||
tooltip: l10n.save,
|
||||
onPressed: onSave ?? () {},
|
||||
),
|
||||
PopupMenuButton<String>(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
tooltip: l10n.more,
|
||||
position: PopupMenuPosition.under,
|
||||
onSelected: (value) {
|
||||
if (value == 'save_all') {
|
||||
onSaveAll?.call();
|
||||
} else if (value == 'settings') {
|
||||
onSettings?.call();
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem<String>(
|
||||
value: 'save_all',
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.save_as_outlined, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text(l10n.saveAll),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem<String>(
|
||||
value: 'settings',
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.settings, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text(l10n.settings),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/providers/editor_provider.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:code_editor/widgets/file_directory_history_widget.dart';
|
||||
import 'package:code_editor/widgets/file_tree_widget.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -8,11 +10,30 @@ import 'package:provider/provider.dart';
|
||||
class CodeEditorDrawer extends StatelessWidget {
|
||||
const CodeEditorDrawer({super.key});
|
||||
|
||||
static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) {
|
||||
try {
|
||||
return listen ? context.watch<ProjectProvider>() : context.read<ProjectProvider>();
|
||||
} catch (_) {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.projectProvider;
|
||||
}
|
||||
}
|
||||
|
||||
static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) {
|
||||
try {
|
||||
return listen ? context.watch<TabProvider>() : context.read<TabProvider>();
|
||||
} catch (_) {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.tabProvider;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final rootPath = context.select<EditorProvider, String?>((p) => p.rootPath);
|
||||
final projectProvider = _getProjectProvider(context, listen: true);
|
||||
final rootPath = projectProvider.rootPath;
|
||||
|
||||
return Drawer(
|
||||
child: SafeArea(
|
||||
@@ -38,13 +59,17 @@ class CodeEditorDrawer extends StatelessWidget {
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh),
|
||||
tooltip: '刷新目录',
|
||||
onPressed: () => context.read<EditorProvider>().refreshTree(),
|
||||
tooltip: l10n.refreshDirectory,
|
||||
onPressed: () => _getProjectProvider(context).refreshTree(),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.folder_open),
|
||||
tooltip: l10n.openFileDirectory,
|
||||
onPressed: () => context.read<EditorProvider>().openDirectory(),
|
||||
onPressed: () async {
|
||||
final canProceed = await _getTabProvider(context).checkUnsavedChanges(context);
|
||||
if (!canProceed || !context.mounted) return;
|
||||
_getProjectProvider(context).openDirectory();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
@@ -52,8 +77,10 @@ class CodeEditorDrawer extends StatelessWidget {
|
||||
onPressed: () {
|
||||
FileDirectoryHistoryWidget.show(
|
||||
context,
|
||||
onSelectHistory: (selectedHistory) {
|
||||
context.read<EditorProvider>().switchProject(selectedHistory);
|
||||
onSelectHistory: (selectedHistory) async {
|
||||
final canProceed = await _getTabProvider(context).checkUnsavedChanges(context);
|
||||
if (!canProceed || !context.mounted) return;
|
||||
_getProjectProvider(context).switchProject(selectedHistory);
|
||||
},
|
||||
);
|
||||
},
|
||||
@@ -63,7 +90,7 @@ class CodeEditorDrawer extends StatelessWidget {
|
||||
Text(
|
||||
rootPath ?? '',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onPrimaryContainer.withValues(alpha: 0.8),
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
maxLines: 1,
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
/// 桌面端与移动端代码编辑器的浮动/右键菜单项组件
|
||||
class _EditorContextMenuItem extends PopupMenuItem<void> implements PreferredSizeWidget {
|
||||
_EditorContextMenuItem({
|
||||
required String text,
|
||||
required IconData icon,
|
||||
required VoidCallback onTap,
|
||||
super.enabled = true,
|
||||
}) : super(
|
||||
onTap: onTap,
|
||||
height: 36,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 16),
|
||||
const SizedBox(width: 8),
|
||||
Text(text, style: const TextStyle(fontSize: 13)),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Size get preferredSize => const Size(140, 36);
|
||||
}
|
||||
|
||||
/// 自定义代码编辑器选区与右键菜单控制器
|
||||
class CodeEditorToolbarController implements SelectionToolbarController {
|
||||
const CodeEditorToolbarController();
|
||||
|
||||
@override
|
||||
void hide(BuildContext context) {
|
||||
// 菜单由 showMenu / 遮罩自动关闭,不需要额外动作
|
||||
}
|
||||
|
||||
@override
|
||||
void show({
|
||||
required BuildContext context,
|
||||
required CodeLineEditingController controller,
|
||||
required TextSelectionToolbarAnchors anchors,
|
||||
Rect? renderRect,
|
||||
required LayerLink layerLink,
|
||||
required ValueNotifier<bool> visibility,
|
||||
}) async {
|
||||
final hasSelection = controller.selection.baseOffset != -1 &&
|
||||
controller.selection.extentOffset != -1 &&
|
||||
!controller.selection.isCollapsed;
|
||||
|
||||
// 检查剪贴板是否有内容以决定是否启用粘贴
|
||||
final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
|
||||
final hasClipboard = clipboardData != null && (clipboardData.text?.isNotEmpty ?? false);
|
||||
|
||||
if (!context.mounted) return;
|
||||
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final mediaQuery = MediaQuery.of(context);
|
||||
final anchor = anchors.primaryAnchor.dx > 0 && anchors.primaryAnchor.dy > 0
|
||||
? anchors.primaryAnchor
|
||||
: (anchors.secondaryAnchor ?? Offset.zero);
|
||||
|
||||
await showMenu<void>(
|
||||
context: context,
|
||||
elevation: 6,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
side: BorderSide(
|
||||
color: Theme.of(context).colorScheme.outlineVariant,
|
||||
width: 0.8,
|
||||
),
|
||||
),
|
||||
position: RelativeRect.fromRect(
|
||||
anchor & const Size(140, 40),
|
||||
Offset.zero & mediaQuery.size,
|
||||
),
|
||||
items: [
|
||||
_EditorContextMenuItem(
|
||||
text: l10n?.cut ?? '剪切',
|
||||
icon: Icons.content_cut,
|
||||
enabled: hasSelection,
|
||||
onTap: () {
|
||||
controller.cut();
|
||||
},
|
||||
),
|
||||
_EditorContextMenuItem(
|
||||
text: l10n?.copy ?? '复制',
|
||||
icon: Icons.copy,
|
||||
enabled: hasSelection,
|
||||
onTap: () {
|
||||
controller.copy();
|
||||
},
|
||||
),
|
||||
_EditorContextMenuItem(
|
||||
text: l10n?.paste ?? '粘贴',
|
||||
icon: Icons.paste,
|
||||
enabled: hasClipboard,
|
||||
onTap: () {
|
||||
controller.paste();
|
||||
},
|
||||
),
|
||||
const PopupMenuDivider(height: 1),
|
||||
_EditorContextMenuItem(
|
||||
text: l10n?.selectAll ?? '全选',
|
||||
icon: Icons.select_all,
|
||||
enabled: !controller.isEmpty,
|
||||
onTap: () {
|
||||
controller.selectAll();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:code_editor/models/editor_tab_item.dart';
|
||||
import 'package:code_editor/providers/editor_provider.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
class CodeEditorTabBar extends StatelessWidget {
|
||||
const CodeEditorTabBar({super.key});
|
||||
|
||||
static TabProvider _getTabProvider(BuildContext context, {bool listen = true}) {
|
||||
try {
|
||||
return listen ? context.watch<TabProvider>() : context.read<TabProvider>();
|
||||
} catch (_) {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.tabProvider;
|
||||
}
|
||||
}
|
||||
|
||||
static ProjectProvider? _getProjectProvider(BuildContext context, {bool listen = true}) {
|
||||
try {
|
||||
return listen ? context.watch<ProjectProvider>() : context.read<ProjectProvider>();
|
||||
} catch (_) {
|
||||
try {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.projectProvider;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double _calculateTabNaturalWidth(
|
||||
BuildContext context, {
|
||||
required String displayName,
|
||||
required bool isModified,
|
||||
}) {
|
||||
final textScaler = MediaQuery.maybeTextScalerOf(context) ?? TextScaler.noScaling;
|
||||
final theme = Theme.of(context);
|
||||
final textPainter = TextPainter(
|
||||
text: TextSpan(
|
||||
text: displayName,
|
||||
style: TextStyle(
|
||||
fontSize: 12.0,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontFamilyFallback: theme.textTheme.bodyMedium?.fontFamilyFallback,
|
||||
),
|
||||
),
|
||||
textScaler: textScaler,
|
||||
maxLines: 1,
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
|
||||
// 实际所需完整宽度(向上取整避免浮点精度缺失):
|
||||
// 文本宽度 + 脏标记 (12.0) + 内外间距与关闭按钮 (33.0) + 安全呼吸缓冲空间 (16.0)
|
||||
final textWidth = textPainter.width.ceilToDouble();
|
||||
final dirtyWidth = isModified ? 12.0 : 0.0;
|
||||
const fixedElementsWidth = 33.0; // 容器内边距(8) + 关闭按钮(24) + 边框(1)
|
||||
const safetyBuffer = 16.0; // 安全呼吸空间,杜绝亚像素及字体微偏差导致的省略号
|
||||
|
||||
return textWidth + dirtyWidth + fixedElementsWidth + safetyBuffer;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tabProvider = _getTabProvider(context);
|
||||
final projectProvider = _getProjectProvider(context);
|
||||
final tabs = tabProvider.openTabs;
|
||||
if (tabs.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final theme = Theme.of(context);
|
||||
final activePath = tabProvider.currentFilePath;
|
||||
final rootPath = projectProvider?.rootPath;
|
||||
|
||||
return Container(
|
||||
height: 36.0,
|
||||
width: double.infinity,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.2),
|
||||
border: Border(
|
||||
bottom: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
width: 0.8,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final totalWidth = constraints.maxWidth;
|
||||
final tabCount = tabs.length;
|
||||
final equalShare = math.max(28.0, totalWidth / tabCount);
|
||||
|
||||
return Theme(
|
||||
data: theme.copyWith(
|
||||
canvasColor: Colors.transparent,
|
||||
shadowColor: Colors.transparent,
|
||||
),
|
||||
child: ReorderableListView.builder(
|
||||
scrollDirection: Axis.horizontal,
|
||||
buildDefaultDragHandles: false,
|
||||
itemCount: tabs.length,
|
||||
onReorderItem: (oldIndex, newIndex) {
|
||||
tabProvider.reorderTabs(oldIndex, newIndex);
|
||||
},
|
||||
itemBuilder: (context, index) {
|
||||
final tab = tabs[index];
|
||||
final isSelected = activePath != null && tab.path == activePath;
|
||||
final displayName = tab.getDisplayName(tabs, rootPath);
|
||||
final naturalWidth = _calculateTabNaturalWidth(
|
||||
context,
|
||||
displayName: displayName,
|
||||
isModified: tab.isModified,
|
||||
);
|
||||
// 单个 tab 最大宽度为内容宽度(名称宽度+默认间距+按钮宽度),不足时等比例压缩划分
|
||||
final itemWidth = math.min(naturalWidth, equalShare);
|
||||
|
||||
return _buildTabItem(
|
||||
context,
|
||||
tabProvider: tabProvider,
|
||||
tab: tab,
|
||||
index: index,
|
||||
isSelected: isSelected,
|
||||
displayName: displayName,
|
||||
width: itemWidth,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTabItem(
|
||||
BuildContext context, {
|
||||
required TabProvider tabProvider,
|
||||
required EditorTabItem tab,
|
||||
required int index,
|
||||
required bool isSelected,
|
||||
required String displayName,
|
||||
required double width,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return ReorderableDelayedDragStartListener(
|
||||
key: ValueKey(tab.path),
|
||||
index: index,
|
||||
child: Container(
|
||||
width: width,
|
||||
height: 36.0,
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected
|
||||
? theme.colorScheme.surface
|
||||
: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.35),
|
||||
border: Border(
|
||||
right: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5),
|
||||
width: 1.0,
|
||||
),
|
||||
bottom: isSelected
|
||||
? BorderSide(
|
||||
color: theme.colorScheme.primary,
|
||||
width: 2.0,
|
||||
)
|
||||
: BorderSide.none,
|
||||
),
|
||||
),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
onTap: () {
|
||||
tabProvider.openFile(tab.path);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (tab.isModified)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 2.0),
|
||||
child: Text(
|
||||
'*',
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.error,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 13.0,
|
||||
),
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: Text(
|
||||
displayName,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12.0,
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
|
||||
color: isSelected
|
||||
? theme.colorScheme.onSurface
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
InkResponse(
|
||||
radius: 12,
|
||||
borderRadius: BorderRadius.circular(4.0),
|
||||
hoverColor: theme.colorScheme.onSurface.withValues(alpha: 0.12),
|
||||
highlightColor: theme.colorScheme.onSurface.withValues(alpha: 0.18),
|
||||
onTap: () {
|
||||
tabProvider.closeTab(context, index);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(3.0),
|
||||
child: Icon(
|
||||
Icons.close,
|
||||
size: 14.0,
|
||||
color: isSelected
|
||||
? theme.colorScheme.onSurface
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,19 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/editor_tab_item.dart';
|
||||
import 'package:code_editor/models/editor_theme.dart';
|
||||
import 'package:code_editor/providers/editor_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';
|
||||
import 'package:code_editor/services/file_watcher_service.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:code_editor/utils/syntax_highlight_helper.dart';
|
||||
import 'package:code_editor/widgets/code_editor_menu.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_code_editor/flutter_code_editor.dart';
|
||||
import 'package:flutter_highlight/themes/atom-one-dark.dart';
|
||||
import 'package:highlight/languages/dart.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
class CodeEditorWidget extends StatefulWidget {
|
||||
final String? rootPath;
|
||||
@@ -14,7 +22,7 @@ class CodeEditorWidget extends StatefulWidget {
|
||||
const CodeEditorWidget({
|
||||
super.key,
|
||||
required this.rootPath,
|
||||
required this.filePath
|
||||
required this.filePath,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -22,10 +30,102 @@ class CodeEditorWidget extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
final CodeController _controller = CodeController();
|
||||
static SettingsProvider _getSettingsProvider(BuildContext context, {bool listen = false}) {
|
||||
try {
|
||||
return listen ? context.watch<SettingsProvider>() : context.read<SettingsProvider>();
|
||||
} catch (_) {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.settingsProvider;
|
||||
}
|
||||
}
|
||||
|
||||
static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) {
|
||||
try {
|
||||
return listen ? context.watch<TabProvider>() : context.read<TabProvider>();
|
||||
} catch (_) {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.tabProvider;
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineEditingController? _controller;
|
||||
CodeScrollController? _scrollController;
|
||||
bool _isLoading = false;
|
||||
int _currentLoadVersion = 0;
|
||||
String? _errorMessage;
|
||||
String? _currentLoadedPath;
|
||||
bool _isShowingConflictDialog = false;
|
||||
|
||||
EditorTabItem? _getCurrentTab() {
|
||||
final filePath = widget.filePath;
|
||||
if (filePath == null || filePath.isEmpty) return null;
|
||||
try {
|
||||
final provider = _getTabProvider(context);
|
||||
final rootPath = widget.rootPath;
|
||||
final fullFilePath = (rootPath == null || rootPath.isEmpty || p.isAbsolute(filePath))
|
||||
? filePath
|
||||
: p.join(rootPath, filePath);
|
||||
final cleanPath = p.normalize(fullFilePath);
|
||||
return provider.openTabs.where((t) => p.equals(t.path, cleanPath)).firstOrNull;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _saveCurrentTabScrollState(EditorTabItem? tab) {
|
||||
if (tab == null || _scrollController == null) return;
|
||||
if (_scrollController!.verticalScroller.hasClients) {
|
||||
tab.verticalScrollOffset = _scrollController!.verticalScroller.offset;
|
||||
}
|
||||
if (_scrollController!.horizontalScroller.hasClients) {
|
||||
tab.horizontalScrollOffset = _scrollController!.horizontalScroller.offset;
|
||||
}
|
||||
}
|
||||
|
||||
void _restoreTabScrollState(EditorTabItem tab) {
|
||||
final oldScroll = _scrollController;
|
||||
|
||||
final vScroller = ScrollController(initialScrollOffset: tab.verticalScrollOffset);
|
||||
final hScroller = ScrollController(initialScrollOffset: tab.horizontalScrollOffset);
|
||||
|
||||
vScroller.addListener(() {
|
||||
if (vScroller.hasClients) {
|
||||
tab.verticalScrollOffset = vScroller.offset;
|
||||
}
|
||||
});
|
||||
hScroller.addListener(() {
|
||||
if (hScroller.hasClients) {
|
||||
tab.horizontalScrollOffset = hScroller.offset;
|
||||
}
|
||||
});
|
||||
|
||||
_scrollController = CodeScrollController(
|
||||
verticalScroller: vScroller,
|
||||
horizontalScroller: hScroller,
|
||||
);
|
||||
|
||||
oldScroll?.verticalScroller.dispose();
|
||||
oldScroll?.horizontalScroller.dispose();
|
||||
oldScroll?.dispose();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || _scrollController == null) return;
|
||||
if (vScroller.hasClients) {
|
||||
final maxV = vScroller.position.maxScrollExtent;
|
||||
final targetV = tab.verticalScrollOffset.clamp(0.0, maxV);
|
||||
if ((vScroller.offset - targetV).abs() > 0.5) {
|
||||
vScroller.jumpTo(targetV);
|
||||
}
|
||||
}
|
||||
if (hScroller.hasClients) {
|
||||
final maxH = hScroller.position.maxScrollExtent;
|
||||
final targetH = tab.horizontalScrollOffset.clamp(0.0, maxH);
|
||||
if ((hScroller.offset - targetH).abs() > 0.5) {
|
||||
hScroller.jumpTo(targetH);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -37,25 +137,173 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
void didUpdateWidget(covariant CodeEditorWidget oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.filePath != widget.filePath || oldWidget.rootPath != widget.rootPath) {
|
||||
if (_controller != null && oldWidget.filePath != null) {
|
||||
try {
|
||||
final provider = _getTabProvider(context);
|
||||
final oldPath = p.normalize(oldWidget.filePath!);
|
||||
final oldTab = provider.openTabs.where((t) => p.equals(t.path, oldPath)).firstOrNull;
|
||||
if (oldTab != null && oldTab.isLoaded) {
|
||||
final current = _controller!.text.replaceAll('\r\n', '\n');
|
||||
final normalizedOriginal = oldTab.originalContent.replaceAll('\r\n', '\n');
|
||||
oldTab.content = current;
|
||||
oldTab.isModified = current != normalizedOriginal;
|
||||
_saveCurrentTabScrollState(oldTab);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
_loadFileContent();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
try {
|
||||
_getTabProvider(context).registerSaveHandler(null);
|
||||
} catch (_) {}
|
||||
final currentTab = _getCurrentTab();
|
||||
_saveCurrentTabScrollState(currentTab);
|
||||
_scrollController?.verticalScroller.dispose();
|
||||
_scrollController?.horizontalScroller.dispose();
|
||||
_scrollController?.dispose();
|
||||
_controller?.removeListener(_onTextChanged);
|
||||
_controller?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onTextChanged() {
|
||||
if (!mounted || _controller == null) return;
|
||||
final currentTab = _getCurrentTab();
|
||||
if (currentTab == null || !currentTab.isLoaded) return;
|
||||
// 确保当前活跃 tab 与当前加载的控制器路径严格一致,杜绝切换过程中误写其他 tab
|
||||
if (!p.equals(currentTab.path, _currentLoadedPath ?? '')) return;
|
||||
|
||||
final current = _controller!.text.replaceAll('\r\n', '\n');
|
||||
final normalizedOriginal = currentTab.originalContent.replaceAll('\r\n', '\n');
|
||||
final isModified = current != normalizedOriginal;
|
||||
|
||||
// 若文本内容与脏状态均未变化(例如光标移动、选区变动、代理绑定),直接跳过
|
||||
if (currentTab.content == current && currentTab.isModified == isModified) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentTab.content = current;
|
||||
currentTab.isModified = isModified;
|
||||
|
||||
void notifyProvider() {
|
||||
if (!mounted) return;
|
||||
try {
|
||||
final provider = _getTabProvider(context);
|
||||
provider.updateActiveTabContent(current, isModified: isModified);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (WidgetsBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => notifyProvider());
|
||||
} else {
|
||||
notifyProvider();
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _saveFile({bool showToast = false}) async {
|
||||
final currentPath = widget.filePath;
|
||||
if (currentPath == null || currentPath.isEmpty || _controller == null) {
|
||||
return false;
|
||||
}
|
||||
final rootPath = widget.rootPath;
|
||||
final String fullFilePath = (rootPath == null || rootPath.isEmpty || p.isAbsolute(currentPath))
|
||||
? currentPath
|
||||
: p.join(rootPath, currentPath);
|
||||
|
||||
try {
|
||||
FileWatcherService.instance.markRecentlySaved(fullFilePath);
|
||||
final content = _controller!.text.replaceAll('\r\n', '\n');
|
||||
await FileService.instance.saveFile(fullFilePath, content);
|
||||
if (mounted) {
|
||||
try {
|
||||
final provider = _getTabProvider(context);
|
||||
final tab = provider.activeTab;
|
||||
if (tab != null) {
|
||||
tab.content = content;
|
||||
tab.originalContent = content;
|
||||
tab.isModified = false;
|
||||
}
|
||||
provider.setModified(false);
|
||||
} catch (_) {}
|
||||
if (showToast) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
DialogUtils.showSuccessToast(context, l10n?.saveSuccess ?? '保存成功');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
DialogUtils.showErrorToast(
|
||||
context,
|
||||
l10n?.saveFailed(e.toString()) ?? '保存失败: $e',
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _syncExternalContentIfChanged(TabProvider provider) {
|
||||
final activeTab = provider.activeTab;
|
||||
if (activeTab == null || _controller == null || _currentLoadedPath == null) return;
|
||||
if (!activeTab.isLoaded) return;
|
||||
// 仅在当前编辑器已经加载了当前激活 tab 的内容时,才响应外部变动。杜绝标签切换过程中的状态混淆!
|
||||
if (!p.equals(activeTab.path, _currentLoadedPath!)) return;
|
||||
|
||||
// 1. 外部修改冲突处理(本地已修改,外部也发生修改)
|
||||
if (activeTab.hasExternalConflict && !_isShowingConflictDialog) {
|
||||
_isShowingConflictDialog = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||
if (!mounted) return;
|
||||
final result = await DialogUtils.showFileConflictDialog(
|
||||
context,
|
||||
fileName: activeTab.name,
|
||||
);
|
||||
if (!mounted) return;
|
||||
_isShowingConflictDialog = false;
|
||||
final reload = result == FileConflictResult.reloadFromDisk;
|
||||
await provider.resolveConflict(activeTab, reloadFromDisk: reload);
|
||||
if (reload && mounted && p.equals(activeTab.path, _currentLoadedPath!)) {
|
||||
_controller?.removeListener(_onTextChanged);
|
||||
_controller?.text = activeTab.content;
|
||||
_controller?.addListener(_onTextChanged);
|
||||
setState(() {});
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 未修改文件外部静默热更新
|
||||
if (!activeTab.isModified && activeTab.content != _controller!.text) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || _controller == null || !p.equals(activeTab.path, _currentLoadedPath!)) return;
|
||||
_controller?.removeListener(_onTextChanged);
|
||||
_controller?.text = activeTab.content;
|
||||
_controller?.addListener(_onTextChanged);
|
||||
setState(() {});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
try {
|
||||
final tabProvider = _getTabProvider(context, listen: true);
|
||||
_syncExternalContentIfChanged(tabProvider);
|
||||
} catch (_) {}
|
||||
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final hasNoProject = widget.rootPath == null || widget.rootPath!.trim().isEmpty;
|
||||
final hasNoFile = widget.filePath == null || widget.filePath!.trim().isEmpty;
|
||||
|
||||
if (hasNoProject && hasNoFile) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"当前未打开文件目录",
|
||||
l10n?.noOpenDirectory ?? "当前未打开文件目录",
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
@@ -83,7 +331,7 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
if (hasNoFile) {
|
||||
return Center(
|
||||
child: Text(
|
||||
"当前未打开文件",
|
||||
l10n?.noOpenFile ?? "当前未打开文件",
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
@@ -91,24 +339,74 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
);
|
||||
}
|
||||
|
||||
// atomOneDark 默认背景色为 0xFF282C34
|
||||
const editorBgColor = Color(0xFF282C34);
|
||||
final controller = _controller;
|
||||
if (controller == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
// 获取独立的代码编辑器主题与字号(若处于无 Provider 测试环境则安全降级)
|
||||
EditorTheme activeTheme = EditorTheme.atomOneDark;
|
||||
double activeFontSize = 14.0;
|
||||
bool activeWordWrap = true;
|
||||
try {
|
||||
final settings = _getSettingsProvider(context, listen: true);
|
||||
activeTheme = settings.editorTheme;
|
||||
activeFontSize = settings.fontSize;
|
||||
activeWordWrap = settings.wordWrap;
|
||||
} catch (_) {}
|
||||
|
||||
return Container(
|
||||
color: editorBgColor,
|
||||
color: activeTheme.backgroundColor,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
child: CodeTheme(
|
||||
data: CodeThemeData(styles: atomOneDarkTheme),
|
||||
child: SingleChildScrollView(
|
||||
child: CodeField(
|
||||
controller: _controller,
|
||||
gutterStyle: const GutterStyle(
|
||||
showLineNumbers: true,
|
||||
showFoldingHandles: true,
|
||||
),
|
||||
child: CodeEditor(
|
||||
key: ValueKey(_currentLoadedPath),
|
||||
controller: controller,
|
||||
scrollController: _scrollController,
|
||||
wordWrap: activeWordWrap,
|
||||
toolbarController: const CodeEditorToolbarController(),
|
||||
style: CodeEditorStyle(
|
||||
fontSize: activeFontSize,
|
||||
textColor: activeTheme.textColor,
|
||||
backgroundColor: activeTheme.backgroundColor,
|
||||
cursorColor: activeTheme.cursorColor,
|
||||
cursorLineColor: activeTheme.cursorLineColor,
|
||||
selectionColor: activeTheme.selectionColor,
|
||||
fontFamily: 'Consolas, Monaco, "Courier New", monospace',
|
||||
codeTheme: CodeHighlightTheme(
|
||||
languages: SyntaxHighlightHelper.getLanguagesForFile(_currentLoadedPath ?? widget.filePath),
|
||||
theme: activeTheme.highlightTheme,
|
||||
),
|
||||
),
|
||||
indicatorBuilder: (context, editingController, chunkController, notifier) {
|
||||
return Row(
|
||||
children: [
|
||||
DefaultCodeLineNumber(
|
||||
controller: editingController,
|
||||
notifier: notifier,
|
||||
textStyle: TextStyle(
|
||||
color: activeTheme.gutterTextColor,
|
||||
fontSize: (activeFontSize - 1).clamp(9.0, 30.0),
|
||||
fontFamily: 'Consolas, Monaco, "Courier New", monospace',
|
||||
),
|
||||
focusedTextStyle: TextStyle(
|
||||
color: activeTheme.focusedGutterTextColor,
|
||||
fontSize: (activeFontSize - 1).clamp(9.0, 30.0),
|
||||
fontWeight: FontWeight.bold,
|
||||
fontFamily: 'Consolas, Monaco, "Courier New", monospace',
|
||||
),
|
||||
),
|
||||
DefaultCodeChunkIndicator(
|
||||
width: 20,
|
||||
controller: chunkController,
|
||||
notifier: notifier,
|
||||
painter: DefaultCodeChunkIndicatorPainter(
|
||||
color: activeTheme.gutterTextColor,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -120,8 +418,19 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
final hasNoFile = filePath == null || filePath.trim().isEmpty;
|
||||
|
||||
if (hasNoFile) {
|
||||
_controller.text = '';
|
||||
_currentLoadedPath = null;
|
||||
_controller?.removeListener(_onTextChanged);
|
||||
_controller?.dispose();
|
||||
_controller = null;
|
||||
if (mounted) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
try {
|
||||
final provider = _getTabProvider(context);
|
||||
provider.setModified(false);
|
||||
provider.registerSaveHandler(null);
|
||||
} catch (_) {}
|
||||
});
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = null;
|
||||
@@ -134,36 +443,104 @@ class _CodeEditorWidgetState extends State<CodeEditorWidget> {
|
||||
? filePath
|
||||
: p.join(rootPath, filePath);
|
||||
|
||||
if (_currentLoadedPath != null && p.equals(_currentLoadedPath!, fullFilePath) && _controller != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final provider = _getTabProvider(context);
|
||||
final cleanPath = p.normalize(fullFilePath);
|
||||
final tab = provider.openTabs.where((t) => p.equals(t.path, cleanPath)).firstOrNull;
|
||||
|
||||
// 内存复用极速通道:若标签页已经在内存中,直接同步切换控制器,0毫秒响应,彻底免去 isLoading 转圈与销毁重建
|
||||
if (tab != null && tab.isLoaded) {
|
||||
final oldController = _controller;
|
||||
oldController?.removeListener(_onTextChanged);
|
||||
|
||||
final normalizedContent = tab.content.replaceAll('\r\n', '\n');
|
||||
final normalizedOriginal = tab.originalContent.replaceAll('\r\n', '\n');
|
||||
tab.content = normalizedContent;
|
||||
tab.originalContent = normalizedOriginal;
|
||||
|
||||
final newController = CodeLineEditingController.fromText(normalizedContent);
|
||||
|
||||
_controller = newController;
|
||||
_currentLoadedPath = fullFilePath;
|
||||
_errorMessage = null;
|
||||
_isLoading = false;
|
||||
|
||||
// 必须在 _controller 和 tab 状态准备就绪后再挂载文本监听,避免初始化阶段被误判为脏
|
||||
newController.addListener(_onTextChanged);
|
||||
|
||||
oldController?.dispose();
|
||||
|
||||
_restoreTabScrollState(tab);
|
||||
|
||||
try {
|
||||
provider.setModified(tab.isModified);
|
||||
provider.registerSaveHandler(() => _saveFile());
|
||||
} catch (_) {}
|
||||
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 首次冷加载文件(未在内存中):
|
||||
final int requestVersion = ++_currentLoadVersion;
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
// 仅在当前未展示任何代码时才显示 loading,已有代码切换时保持编辑器容器,避免白屏闪烁
|
||||
if (_controller == null) {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
final content = await FileService.instance.readFileContent(fullFilePath);
|
||||
if(!mounted || requestVersion != _currentLoadVersion) {
|
||||
final rawDiskContent = await FileService.instance.readFileContent(fullFilePath);
|
||||
final diskContent = rawDiskContent.replaceAll('\r\n', '\n');
|
||||
|
||||
if (!mounted || requestVersion != _currentLoadVersion) {
|
||||
return;
|
||||
}
|
||||
_controller.language = _resolveLanguage(fullFilePath);
|
||||
_controller.text = content;
|
||||
|
||||
}catch(e) {
|
||||
if(!mounted || requestVersion != _currentLoadVersion) return;
|
||||
setState(() {
|
||||
_errorMessage = '$e';
|
||||
});
|
||||
}finally {
|
||||
if(mounted && requestVersion == _currentLoadVersion) {
|
||||
final oldController = _controller;
|
||||
oldController?.removeListener(_onTextChanged);
|
||||
|
||||
final newController = CodeLineEditingController.fromText(diskContent);
|
||||
|
||||
_controller = newController;
|
||||
_currentLoadedPath = fullFilePath;
|
||||
_errorMessage = null;
|
||||
|
||||
if (tab != null) {
|
||||
tab.content = diskContent;
|
||||
tab.originalContent = diskContent;
|
||||
tab.isLoaded = true;
|
||||
tab.isModified = false;
|
||||
}
|
||||
|
||||
newController.addListener(_onTextChanged);
|
||||
oldController?.dispose();
|
||||
|
||||
if (tab != null) {
|
||||
_restoreTabScrollState(tab);
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
try {
|
||||
provider.setModified(tab?.isModified ?? false);
|
||||
provider.registerSaveHandler(() => _saveFile());
|
||||
} catch (_) {}
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted || requestVersion != _currentLoadVersion) return;
|
||||
_errorMessage = '$e';
|
||||
} finally {
|
||||
if (mounted && requestVersion == _currentLoadVersion) {
|
||||
setState(() => _isLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dynamic _resolveLanguage(String path) {
|
||||
if(path.endsWith('.dart')) return dart;
|
||||
if(path.endsWith('.json')) return json;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/file_directory_history.dart';
|
||||
import 'package:code_editor/services/file_directory_history_service.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
@@ -56,14 +58,27 @@ class _FileDirectoryHistoryWidgetState
|
||||
Future<void> _deleteHistory(FileDirectoryHistory item) async {
|
||||
final root = item.rootPath;
|
||||
if (root != null && root.isNotEmpty) {
|
||||
await FileDirectoryHistoryService.instance.removeHistory(root);
|
||||
await _loadHistory();
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
|
||||
context,
|
||||
title: l10n.deleteHistoryTitle,
|
||||
message: l10n.deleteHistoryMessage,
|
||||
confirmText: l10n.remove,
|
||||
);
|
||||
if (confirmed && mounted) {
|
||||
await FileDirectoryHistoryService.instance.removeHistory(root);
|
||||
await _loadHistory();
|
||||
if (mounted) {
|
||||
DialogUtils.showSuccessToast(context, l10n.historyRemoved);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
|
||||
return Dialog(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
@@ -92,19 +107,19 @@ class _FileDirectoryHistoryWidgetState
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'历史文件目录',
|
||||
l10n.historyFileDirectories,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
Icons.close,
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
tooltip: '关闭',
|
||||
tooltip: l10n.close,
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
@@ -126,7 +141,7 @@ class _FileDirectoryHistoryWidgetState
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Text(
|
||||
'暂无历史记录',
|
||||
l10n.noHistory,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
fontSize: 14,
|
||||
@@ -149,8 +164,8 @@ class _FileDirectoryHistoryWidgetState
|
||||
final fileName = (lastFile != null &&
|
||||
lastFile.trim().isNotEmpty)
|
||||
? p.basename(lastFile)
|
||||
: '未打开文件';
|
||||
final rootDir = item.rootPath ?? '未知目录';
|
||||
: l10n.noOpenFile;
|
||||
final rootDir = item.rootPath ?? l10n.unknownDirectory;
|
||||
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
@@ -210,7 +225,7 @@ class _FileDirectoryHistoryWidgetState
|
||||
size: 20,
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
tooltip: '删除此记录',
|
||||
tooltip: l10n.deleteThisHistory,
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () => _deleteHistory(item),
|
||||
),
|
||||
|
||||
+160
-343
@@ -1,5 +1,9 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:code_editor/providers/editor_provider.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -17,6 +21,24 @@ class FileItemWidget extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) {
|
||||
try {
|
||||
return listen ? context.watch<ProjectProvider>() : context.read<ProjectProvider>();
|
||||
} catch (_) {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.projectProvider;
|
||||
}
|
||||
}
|
||||
|
||||
static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) {
|
||||
try {
|
||||
return listen ? context.watch<TabProvider>() : context.read<TabProvider>();
|
||||
} catch (_) {
|
||||
final editor = listen ? context.watch<EditorProvider>() : context.read<EditorProvider>();
|
||||
return editor.tabProvider;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _buildFileItem(context, widget.fileItem);
|
||||
@@ -24,14 +46,15 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
|
||||
Widget _buildFileItem(BuildContext context, FileItem item) {
|
||||
final theme = Theme.of(context);
|
||||
final provider = context.watch<EditorProvider>();
|
||||
final projectProvider = _getProjectProvider(context, listen: true);
|
||||
final tabProvider = _getTabProvider(context, listen: true);
|
||||
final indent = EdgeInsets.only(left: item.depth * 16.0 + 8.0, right: 8.0);
|
||||
|
||||
// 判断该文件是否处于被剪切状态
|
||||
final isCut = provider.isItemCut(item.path);
|
||||
final isCut = projectProvider.isItemCut(item.path);
|
||||
|
||||
// 判断该文件是否为当前正在编辑/修改的文件
|
||||
final isSelected = !item.isDirectory && provider.isFileSelected(item.path);
|
||||
final isSelected = !item.isDirectory && tabProvider.isFileSelected(item.path);
|
||||
|
||||
// 文字样式:剪切时变灰,选中时高亮,其余正常
|
||||
final itemTextStyle = theme.textTheme.bodyMedium?.copyWith(
|
||||
@@ -72,7 +95,7 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
setState(() {
|
||||
item.isOpen = expanded;
|
||||
});
|
||||
context.read<EditorProvider>().toggleDirectory(item, expanded);
|
||||
_getProjectProvider(context).toggleDirectory(item, expanded);
|
||||
},
|
||||
children: item.children
|
||||
.map((child) => FileItemWidget(fileItem: child))
|
||||
@@ -86,33 +109,36 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
},
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 1.0),
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected
|
||||
? theme.colorScheme.primaryContainer.withValues(alpha: 0.5)
|
||||
: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
child: ListTile(
|
||||
contentPadding: indent,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: ListTile(
|
||||
contentPadding: indent,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
selected: isSelected,
|
||||
selectedTileColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.5),
|
||||
leading: Icon(
|
||||
_getFileIcon(item),
|
||||
size: 20,
|
||||
color: iconColor,
|
||||
),
|
||||
title: Text(
|
||||
item.name,
|
||||
style: itemTextStyle,
|
||||
),
|
||||
dense: true,
|
||||
onTap: () {
|
||||
final scaffold = Scaffold.maybeOf(context);
|
||||
if (scaffold != null && scaffold.isDrawerOpen) {
|
||||
scaffold.closeDrawer();
|
||||
}
|
||||
if (tabProvider.isFileSelected(item.path)) {
|
||||
return;
|
||||
}
|
||||
_getTabProvider(context).selectFile(item);
|
||||
},
|
||||
),
|
||||
selected: isSelected,
|
||||
selectedTileColor: Colors.transparent,
|
||||
leading: Icon(
|
||||
_getFileIcon(item),
|
||||
size: 20,
|
||||
color: iconColor,
|
||||
),
|
||||
title: Text(
|
||||
item.name,
|
||||
style: itemTextStyle,
|
||||
),
|
||||
dense: true,
|
||||
onTap: () {
|
||||
Navigator.of(context).maybePop(); // 关闭 Drawer
|
||||
context.read<EditorProvider>().selectFile(item);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -125,107 +151,31 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
return Icons.commit_outlined;
|
||||
}
|
||||
|
||||
switch (item.extension) {
|
||||
case '.dart':
|
||||
return Icons.flutter_dash;
|
||||
case '.html':
|
||||
case '.htm':
|
||||
return Icons.html;
|
||||
case '.css':
|
||||
case '.scss':
|
||||
case '.sass':
|
||||
case '.less':
|
||||
return Icons.css;
|
||||
case '.js':
|
||||
case '.mjs':
|
||||
case '.cjs':
|
||||
return Icons.javascript;
|
||||
case '.ts':
|
||||
case '.tsx':
|
||||
case '.jsx':
|
||||
case '.vue':
|
||||
case '.svelte':
|
||||
return Icons.code;
|
||||
case '.json':
|
||||
return Icons.data_object;
|
||||
case '.yaml':
|
||||
case '.yml':
|
||||
case '.toml':
|
||||
case '.ini':
|
||||
case '.env':
|
||||
case '.conf':
|
||||
case '.config':
|
||||
case '.properties':
|
||||
return Icons.settings_suggest_outlined;
|
||||
case '.xml':
|
||||
return Icons.code;
|
||||
case '.md':
|
||||
case '.markdown':
|
||||
return Icons.article_outlined;
|
||||
case '.pdf':
|
||||
return Icons.picture_as_pdf_outlined;
|
||||
case '.py':
|
||||
case '.pyw':
|
||||
case '.java':
|
||||
case '.kt':
|
||||
case '.kts':
|
||||
case '.c':
|
||||
case '.cpp':
|
||||
case '.cc':
|
||||
case '.h':
|
||||
case '.hpp':
|
||||
case '.cs':
|
||||
case '.go':
|
||||
case '.rs':
|
||||
case '.swift':
|
||||
case '.rb':
|
||||
case '.php':
|
||||
return Icons.code;
|
||||
case '.sh':
|
||||
case '.bash':
|
||||
case '.zsh':
|
||||
case '.bat':
|
||||
case '.cmd':
|
||||
case '.ps1':
|
||||
return Icons.terminal;
|
||||
case '.sql':
|
||||
case '.db':
|
||||
case '.sqlite':
|
||||
return Icons.storage_outlined;
|
||||
case '.png':
|
||||
case '.jpg':
|
||||
case '.jpeg':
|
||||
case '.gif':
|
||||
case '.webp':
|
||||
case '.svg':
|
||||
case '.ico':
|
||||
case '.bmp':
|
||||
return Icons.image_outlined;
|
||||
case '.mp3':
|
||||
case '.wav':
|
||||
case '.ogg':
|
||||
case '.flac':
|
||||
case '.aac':
|
||||
return Icons.audio_file_outlined;
|
||||
case '.mp4':
|
||||
case '.avi':
|
||||
case '.mov':
|
||||
case '.mkv':
|
||||
case '.flv':
|
||||
case '.webm':
|
||||
return Icons.video_file_outlined;
|
||||
case '.zip':
|
||||
case '.rar':
|
||||
case '.7z':
|
||||
case '.tar':
|
||||
case '.gz':
|
||||
return Icons.folder_zip_outlined;
|
||||
case '.lock':
|
||||
return Icons.lock_outline;
|
||||
case '.txt':
|
||||
default:
|
||||
return Icons.description_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,
|
||||
};
|
||||
}
|
||||
|
||||
void _showContextMenu(FileItem item, Offset tapPosition) async {
|
||||
@@ -236,17 +186,28 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
);
|
||||
|
||||
final theme = Theme.of(context);
|
||||
final l10n = AppLocalizations.of(context);
|
||||
final onSurfaceColor = theme.colorScheme.onSurface;
|
||||
final canPaste = context.read<EditorProvider>().canPaste;
|
||||
final canPaste = _getProjectProvider(context).canPaste;
|
||||
final menuItems = <PopupMenuEntry<String>>[];
|
||||
|
||||
final strNewFile = l10n?.newFile ?? '新建文件';
|
||||
final strNewFolder = l10n?.newFolder ?? '新建文件夹';
|
||||
final strCut = l10n?.cut ?? '剪切';
|
||||
final strCopy = l10n?.copy ?? '复制';
|
||||
final strPaste = l10n?.paste ?? '粘贴';
|
||||
final strCopyPath = l10n?.copyPath ?? '复制路径';
|
||||
final strCopyRelativePath = l10n?.copyRelativePath ?? '复制相对路径';
|
||||
final strRename = l10n?.rename ?? '重命名';
|
||||
final strDelete = l10n?.delete ?? '删除';
|
||||
|
||||
if (item.isDirectory) {
|
||||
menuItems.addAll([
|
||||
_buildMenuItem('new_file', Icons.note_add_outlined, '新建文件', onSurfaceColor),
|
||||
_buildMenuItem('new_folder', Icons.create_new_folder_outlined, '新建文件夹', onSurfaceColor),
|
||||
_buildMenuItem('new_file', Icons.note_add_outlined, strNewFile, onSurfaceColor),
|
||||
_buildMenuItem('new_folder', Icons.create_new_folder_outlined, strNewFolder, onSurfaceColor),
|
||||
const PopupMenuDivider(),
|
||||
_buildMenuItem('cut', Icons.content_cut, '剪切', onSurfaceColor),
|
||||
_buildMenuItem('copy', Icons.copy, '复制', onSurfaceColor),
|
||||
_buildMenuItem('cut', Icons.content_cut, strCut, onSurfaceColor),
|
||||
_buildMenuItem('copy', Icons.copy, strCopy, onSurfaceColor),
|
||||
PopupMenuItem<String>(
|
||||
value: 'paste',
|
||||
enabled: canPaste,
|
||||
@@ -261,7 +222,7 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'粘贴',
|
||||
strPaste,
|
||||
style: TextStyle(
|
||||
color: canPaste
|
||||
? onSurfaceColor
|
||||
@@ -272,31 +233,31 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
),
|
||||
),
|
||||
const PopupMenuDivider(),
|
||||
_buildMenuItem('copy_path', Icons.link, '复制路径', onSurfaceColor),
|
||||
_buildMenuItem('copy_relative_path', Icons.short_text, '复制相对路径', onSurfaceColor),
|
||||
_buildMenuItem('copy_path', Icons.link, strCopyPath, onSurfaceColor),
|
||||
_buildMenuItem('copy_relative_path', Icons.short_text, strCopyRelativePath, onSurfaceColor),
|
||||
const PopupMenuDivider(),
|
||||
_buildMenuItem('rename', Icons.edit_outlined, '重命名', onSurfaceColor),
|
||||
_buildMenuItem('rename', Icons.edit_outlined, strRename, onSurfaceColor),
|
||||
_buildMenuItem(
|
||||
'delete',
|
||||
Icons.delete_outline,
|
||||
'删除',
|
||||
strDelete,
|
||||
theme.colorScheme.error,
|
||||
isDestructive: true,
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
menuItems.addAll([
|
||||
_buildMenuItem('cut', Icons.content_cut, '剪切', onSurfaceColor),
|
||||
_buildMenuItem('copy', Icons.copy, '复制', onSurfaceColor),
|
||||
_buildMenuItem('cut', Icons.content_cut, strCut, onSurfaceColor),
|
||||
_buildMenuItem('copy', Icons.copy, strCopy, onSurfaceColor),
|
||||
const PopupMenuDivider(),
|
||||
_buildMenuItem('copy_path', Icons.link, '复制路径', onSurfaceColor),
|
||||
_buildMenuItem('copy_relative_path', Icons.short_text, '复制相对路径', onSurfaceColor),
|
||||
_buildMenuItem('copy_path', Icons.link, strCopyPath, onSurfaceColor),
|
||||
_buildMenuItem('copy_relative_path', Icons.short_text, strCopyRelativePath, onSurfaceColor),
|
||||
const PopupMenuDivider(),
|
||||
_buildMenuItem('rename', Icons.edit_outlined, '重命名', onSurfaceColor),
|
||||
_buildMenuItem('rename', Icons.edit_outlined, strRename, onSurfaceColor),
|
||||
_buildMenuItem(
|
||||
'delete',
|
||||
Icons.delete_outline,
|
||||
'删除',
|
||||
strDelete,
|
||||
theme.colorScheme.error,
|
||||
isDestructive: true,
|
||||
),
|
||||
@@ -350,247 +311,103 @@ class _FileItemWidgetState extends State<FileItemWidget> {
|
||||
}
|
||||
|
||||
void _handleMenuAction(FileItem item, String action) async {
|
||||
final provider = context.read<EditorProvider>();
|
||||
final provider = _getProjectProvider(context);
|
||||
final l10n = AppLocalizations.of(context);
|
||||
|
||||
switch (action) {
|
||||
case 'new_file':
|
||||
await _showCreateInputDialog(
|
||||
title: '新建文件',
|
||||
hintText: '文件名 (例如: main.dart)',
|
||||
onConfirm: (name) async {
|
||||
await provider.createFile(item.path, name);
|
||||
},
|
||||
final name = await DialogUtils.showInputDialog(
|
||||
context,
|
||||
title: l10n?.newFile ?? '新建文件',
|
||||
hintText: l10n?.fileNameHint ?? '文件名 (例如: main.dart)',
|
||||
);
|
||||
if (name != null && name.trim().isNotEmpty) {
|
||||
try {
|
||||
await provider.createFile(item.path, name.trim());
|
||||
} catch (e) {
|
||||
if (mounted) DialogUtils.showErrorToast(context, l10n?.createFileFailed(e.toString()) ?? '创建文件失败: $e');
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'new_folder':
|
||||
await _showCreateInputDialog(
|
||||
title: '新建文件夹',
|
||||
hintText: '文件夹名',
|
||||
onConfirm: (name) async {
|
||||
await provider.createDirectory(item.path, name);
|
||||
},
|
||||
final name = await DialogUtils.showInputDialog(
|
||||
context,
|
||||
title: l10n?.newFolder ?? '新建文件夹',
|
||||
hintText: l10n?.folderNameHint ?? '文件夹名',
|
||||
);
|
||||
if (name != null && name.trim().isNotEmpty) {
|
||||
try {
|
||||
await provider.createDirectory(item.path, name.trim());
|
||||
} catch (e) {
|
||||
if (mounted) DialogUtils.showErrorToast(context, l10n?.createFolderFailed(e.toString()) ?? '创建文件夹失败: $e');
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'cut':
|
||||
provider.cut(item);
|
||||
if (mounted) _showToast(context, '已剪切: ${item.name}');
|
||||
if (mounted) DialogUtils.showInfoToast(context, l10n?.cutItem(item.name) ?? '已剪切: ${item.name}');
|
||||
break;
|
||||
|
||||
case 'copy':
|
||||
provider.copy(item);
|
||||
if (mounted) _showToast(context, '已复制: ${item.name}');
|
||||
if (mounted) DialogUtils.showInfoToast(context, l10n?.copiedItem(item.name) ?? '已复制: ${item.name}');
|
||||
break;
|
||||
|
||||
case 'paste':
|
||||
try {
|
||||
await provider.paste(item);
|
||||
if (mounted) _showToast(context, '操作成功');
|
||||
if (mounted) DialogUtils.showSuccessToast(context, l10n?.operationSuccess ?? '操作成功');
|
||||
} catch (e) {
|
||||
if (mounted) _showToast(context, '操作失败: $e', isError: true);
|
||||
if (mounted) DialogUtils.showErrorToast(context, l10n?.operationFailed(e.toString()) ?? '操作失败: $e');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'copy_path':
|
||||
await Clipboard.setData(ClipboardData(text: item.fullPath));
|
||||
if (mounted) {
|
||||
_showToast(context, '已复制完整路径到剪贴板');
|
||||
DialogUtils.showSuccessToast(context, l10n?.copiedPathToClipboard ?? '已复制完整路径到剪贴板');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'copy_relative_path':
|
||||
await Clipboard.setData(ClipboardData(text: item.getRelativePath(provider.rootPath)));
|
||||
if (mounted) {
|
||||
_showToast(context, '已复制相对路径到剪贴板');
|
||||
DialogUtils.showSuccessToast(context, l10n?.copiedRelativePathToClipboard ?? '已复制相对路径到剪贴板');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'rename':
|
||||
await _showCreateInputDialog(
|
||||
title: '重命名',
|
||||
hintText: '新名称',
|
||||
final newName = await DialogUtils.showInputDialog(
|
||||
context,
|
||||
title: l10n?.rename ?? '重命名',
|
||||
hintText: l10n?.newName ?? '新名称',
|
||||
initialValue: item.name,
|
||||
onConfirm: (newName) async {
|
||||
if (newName.trim() == item.name) return;
|
||||
await provider.rename(item, newName.trim());
|
||||
},
|
||||
);
|
||||
if (newName != null && newName.trim().isNotEmpty && newName.trim() != item.name) {
|
||||
try {
|
||||
await provider.rename(item, newName.trim());
|
||||
} catch (e) {
|
||||
if (mounted) DialogUtils.showErrorToast(context, l10n?.renameFailed(e.toString()) ?? '重命名失败: $e');
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'delete':
|
||||
final confirmed = await _showConfirmDialog(
|
||||
title: '确认删除',
|
||||
content: '确定要删除 "${item.name}" 吗?此操作不可恢复。',
|
||||
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
|
||||
context,
|
||||
title: l10n?.confirmDelete ?? '确认删除',
|
||||
message: l10n?.confirmDeleteMessage(item.name) ?? '确定要删除 "${item.name}" 吗?此操作不可恢复。',
|
||||
);
|
||||
if (confirmed == true && mounted) {
|
||||
await provider.delete(item);
|
||||
if (confirmed && mounted) {
|
||||
try {
|
||||
await provider.delete(item);
|
||||
} catch (e) {
|
||||
if (mounted) DialogUtils.showErrorToast(context, l10n?.deleteFailed(e.toString()) ?? '删除失败: $e');
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _showToast(BuildContext context, String message, {bool isError = false}) {
|
||||
final overlay = Overlay.of(context, rootOverlay: true);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
late OverlayEntry entry;
|
||||
entry = OverlayEntry(
|
||||
builder: (ctx) => Positioned(
|
||||
bottom: 48,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Center(
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: isError
|
||||
? theme.colorScheme.errorContainer
|
||||
: theme.colorScheme.inverseSurface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isError
|
||||
? theme.colorScheme.error
|
||||
: theme.colorScheme.outlineVariant,
|
||||
width: 1,
|
||||
),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black26,
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Text(
|
||||
message,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: isError
|
||||
? theme.colorScheme.onErrorContainer
|
||||
: theme.colorScheme.onInverseSurface,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
overlay.insert(entry);
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
if (entry.mounted) {
|
||||
entry.remove();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _showCreateInputDialog({
|
||||
required String title,
|
||||
required String hintText,
|
||||
String? initialValue,
|
||||
required Future<void> Function(String value) onConfirm,
|
||||
}) async {
|
||||
final controller = TextEditingController(text: initialValue);
|
||||
final formKey = GlobalKey<FormState>();
|
||||
|
||||
final theme = Theme.of(context);
|
||||
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16.0),
|
||||
side: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
width: 1.0,
|
||||
),
|
||||
),
|
||||
title: Text(title),
|
||||
content: Form(
|
||||
key: formKey,
|
||||
child: TextFormField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(
|
||||
hintText: hintText,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (val) {
|
||||
if (val == null || val.trim().isEmpty) {
|
||||
return '名称不能为空';
|
||||
}
|
||||
if (val.contains(RegExp(r'[\\/:*?"<>|]'))) {
|
||||
return '名称不能包含非法字符 (\\/:*?"<>|)';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
final inputVal = controller.text;
|
||||
Navigator.of(dialogContext).pop();
|
||||
try {
|
||||
await onConfirm(inputVal);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
_showToast(context, '操作失败: $e', isError: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
child: const Text('确定'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool?> _showConfirmDialog({
|
||||
required String title,
|
||||
required String content,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
return showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16.0),
|
||||
side: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
width: 1.0,
|
||||
),
|
||||
),
|
||||
title: Text(title),
|
||||
content: Text(content),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.error,
|
||||
foregroundColor: theme.colorScheme.onError,
|
||||
),
|
||||
onPressed: () => Navigator.of(dialogContext).pop(true),
|
||||
child: const Text('删除'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:code_editor/models/file_item.dart';
|
||||
import 'package:code_editor/providers/editor_provider.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/widgets/file_item_widget.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -7,11 +7,20 @@ import 'package:provider/provider.dart';
|
||||
class FileTreeWidget extends StatelessWidget {
|
||||
const FileTreeWidget({super.key});
|
||||
|
||||
static ProjectProvider _getProjectProvider(BuildContext context) {
|
||||
try {
|
||||
return context.watch<ProjectProvider>();
|
||||
} catch (_) {
|
||||
return context.watch<EditorProvider>().projectProvider;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final rootPath = context.select<EditorProvider, String?>((p) => p.rootPath);
|
||||
final items = context.select<EditorProvider, List<FileItem>>((p) => p.items);
|
||||
final projectProvider = _getProjectProvider(context);
|
||||
final rootPath = projectProvider.rootPath;
|
||||
final items = projectProvider.items;
|
||||
|
||||
// 1. 如果用户还没有打开/选择任何根目录
|
||||
if (rootPath == null || rootPath.trim().isEmpty) {
|
||||
|
||||
Reference in new issue
Block a user