v2.0.0: 模组插件管理、下载引擎(镜像+队列)、SSH终端、UI改版与依赖仓库

This commit is contained in:
ZV Dev committed 2026-10-22 23:28:14 +08:00
1 parent b8f163aa3a
commit 33d137e33c
29 files changed
+3061 -30

No files matched your search

+20 -3
View File
@@ -166,7 +166,7 @@ class _ConsolePageState extends State<ConsolePage> {
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
color: theme.colorScheme.surfaceContainerHighest.withOpacity(0.3),
child: ListView.builder(
controller: _scrollController,
itemCount: _outputLines.length,
@@ -181,7 +181,8 @@ class _ConsolePageState extends State<ConsolePage> {
? theme.colorScheme.error
: line.isCommand
? theme.colorScheme.primary
: theme.colorScheme.onSurface,
// 按日志级别前缀着色:WARN 黄 / ERROR 红 / INFO 绿
: _logLevelColor(line.text) ?? theme.colorScheme.onSurface,
),
);
},
@@ -242,6 +243,22 @@ class _LogLine {
_LogLine({required this.text, this.isCommand = false, this.isError = false});
}
/// 按日志前缀识别级别并返回对应颜色(INFO 绿 / WARN 黄 / ERROR 红)。
Color? _logLevelColor(String text) {
final upper = text.toUpperCase();
// 兼容 [WARN]、[WARN/...]、WARN : 等常见格式
if (upper.contains('ERROR') || upper.contains('FATAL') || upper.contains('SEVERE')) {
return Colors.red;
}
if (upper.contains(RegExp(r'\bWARN(ING)?\b'))) {
return Colors.orange;
}
if (upper.contains(RegExp(r'\bINFO\b'))) {
return Colors.green;
}
return null;
}
/// 快速命令预设栏:横向滚动的预设按钮 + 管理入口。
class _PresetBar extends StatelessWidget {
final List<QuickCommandPreset> presets;
@@ -273,7 +290,7 @@ class _PresetBar extends StatelessWidget {
label: Text(preset.label),
labelStyle: TextStyle(fontSize: 13, color: theme.colorScheme.onSecondaryContainer),
visualDensity: VisualDensity.compact,
backgroundColor: theme.colorScheme.secondaryContainer.withValues(alpha: 0.5),
backgroundColor: theme.colorScheme.secondaryContainer.withOpacity(0.5),
onPressed: () => onSend(preset.command),
);
},
+215
View File
@@ -0,0 +1,215 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/rcon_provider.dart';
import '../../providers/server_provider.dart';
import '../download/download_page.dart';
import '../mod_manager/mod_list_page.dart';
import '../terminal/terminal_page.dart';
import 'server_picker_bar.dart';
/// 服务器 Dashboard:卡片式布局展示选中服务器的
/// 在线状态 / 延迟 / 在线人数 / TPS / 磁盘(后续 Shell 采集)+ 快捷入口(M4)。
class DashboardPage extends StatefulWidget {
const DashboardPage({super.key});
@override
State<DashboardPage> createState() => _DashboardPageState();
}
class _DashboardPageState extends State<DashboardPage> {
Map<String, ServerStatus> _status = {};
@override
void initState() {
super.initState();
_refreshAll();
}
Future<void> _refreshAll() async {
final rcon = context.read<RconProvider>();
final servers = context.read<ServerProvider>().servers;
final map = <String, ServerStatus>{};
for (final s in servers) {
map[s.id] = await rcon.checkStatus(s);
}
if (!mounted) return;
setState(() => _status = map);
}
@override
Widget build(BuildContext context) {
final servers = context.watch<ServerProvider>().servers;
final holder = context.watch<SelectedServerHolder>();
final selected = holder.server ?? (servers.isNotEmpty ? servers.first : null);
final status = selected != null ? _status[selected.id] : null;
return Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: const Text('ZV Manager'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: '刷新状态',
onPressed: _refreshAll,
),
],
),
body: servers.isEmpty
? const Center(child: Text('还没有服务器,去「服务器」页添加吧'))
: ListView(
padding: const EdgeInsets.all(12),
children: [
// 服务器选择器
Card(
child: ListTile(
leading: const Icon(Icons.dns),
title: Text(selected?.name ?? '未选择'),
subtitle: Text('${selected?.host ?? '-'}:${selected?.port ?? '-'}'),
trailing: DropdownButton<ServerConfig>(
underline: const SizedBox.shrink(),
hint: const Text('切换'),
items: servers
.map((s) => DropdownMenuItem(value: s, child: Text(s.name)))
.toList(),
onChanged: (s) {
holder.select(s);
setState(() {});
},
),
),
),
const SizedBox(height: 8),
// 状态卡片
GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
childAspectRatio: 1.8,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
children: [
_statusCard(
icon: status?.online == true ? Icons.circle : Icons.circle_outlined,
color: status?.online == true ? Colors.green : Colors.red,
label: status?.online == true ? '在线' : '离线',
sub: status == null ? '—' : '${status.latencyMs}ms',
),
_statusCard(
icon: Icons.person,
color: Colors.blue,
label: '在线人数',
sub: '${status?.playerCount ?? 0}',
),
_statusCard(
icon: Icons.speed,
color: Colors.orange,
label: 'TPS',
sub: status?.tps?.toStringAsFixed(1) ?? '—',
),
_statusCard(
icon: Icons.storage,
color: Colors.purple,
label: '磁盘',
sub: '需 SSH 终端',
),
],
),
const SizedBox(height: 8),
// 服务器卡片列表(点击选中)
Text('服务器', style: Theme.of(context).textTheme.titleMedium),
...servers.map((s) {
final st = _status[s.id];
final isSel = selected?.id == s.id;
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
child: ListTile(
selected: isSel,
leading: Icon(
st?.online == true ? Icons.circle : Icons.circle_outlined,
color: st?.online == true ? Colors.green : Colors.red,
),
title: Text(s.name),
subtitle: Text(
st?.online == true
? '在线 · ${st!.latencyMs}ms · ${st.playerCount} 人'
'${st.tps != null ? " · TPS ${st.tps!.toStringAsFixed(1)}" : ""}'
: '离线',
),
trailing: isSel ? const Icon(Icons.check) : null,
onTap: () {
holder.select(s);
setState(() {});
},
),
);
}),
const SizedBox(height: 8),
// 快捷入口
Card(
child: Column(
children: [
ListTile(
leading: const Icon(Icons.download_outlined),
title: const Text('下载中心'),
subtitle: const Text('Modrinth 搜索 · 镜像加速'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const DownloadPage()),
),
),
ListTile(
leading: const Icon(Icons.terminal),
title: const Text('远程终端'),
subtitle: const Text('SSH Shell'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const TerminalPage()),
),
),
ListTile(
leading: const Icon(Icons.extension_outlined),
title: const Text('模组管理'),
subtitle: const Text('上传 / 删除 / 查看依赖'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const ModListPage()),
),
),
],
),
),
],
),
);
}
Widget _statusCard({
required IconData icon,
required Color color,
required String label,
required String sub,
}) {
return Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(icon, color: color, size: 18),
const SizedBox(width: 6),
Text(label, style: Theme.of(context).textTheme.bodyMedium),
]),
const SizedBox(height: 6),
Text(sub, style: Theme.of(context).textTheme.headlineSmall),
],
),
),
);
}
}
@@ -0,0 +1,15 @@
import 'package:flutter/foundation.dart';
import '../../../providers/server_provider.dart';
/// 跨页签共享的「当前选中服务器」。
/// Dashboard / 模组 / 终端 / 下载上传目标等页签共用此状态。
class SelectedServerHolder extends ChangeNotifier {
ServerConfig? _server;
ServerConfig? get server => _server;
void select(ServerConfig? s) {
_server = s;
notifyListeners();
}
}
+396
View File
@@ -0,0 +1,396 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/services/modrinth_api.dart';
import '../../providers/download_provider.dart';
import '../../core/services/download_manager.dart';
/// 下载中心:Modrinth 搜索 + 镜像线路选择 + 下载任务队列(M2)。
class DownloadPage extends StatefulWidget {
const DownloadPage({super.key});
@override
State<DownloadPage> createState() => _DownloadPageState();
}
class _DownloadPageState extends State<DownloadPage> {
final _searchCtrl = TextEditingController();
List<ModrinthSearchResult>? _results;
bool _searching = false;
String _projectType = 'mod';
String? _mcVersion;
String? _loader;
static const _mcVersions = ['1.21.4', '1.21.1', '1.20.6', '1.20.4', '1.20.1', '1.19.4', '1.18.2', '1.16.5'];
static const _loaders = ['fabric', 'forge', 'quilt', 'neoforge', 'paper', 'bukkit', 'spigot'];
@override
void initState() {
super.initState();
context.read<DownloadProvider>().init();
}
Future<void> _search() async {
final query = _searchCtrl.text.trim();
if (query.isEmpty) return;
setState(() {
_searching = true;
_results = null;
});
try {
final dp = context.read<DownloadProvider>();
final results = await dp.search(
query,
projectType: _projectType,
mcVersion: _mcVersion,
loader: _loader,
);
if (!mounted) return;
setState(() {
_results = results;
_searching = false;
});
} catch (e) {
if (!mounted) return;
setState(() => _searching = false);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('搜索失败:$e')));
}
}
@override
Widget build(BuildContext context) {
final dp = context.read<DownloadProvider>();
return DefaultTabController(
length: 2,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: const Text('下载中心'),
actions: [
IconButton(
icon: const Icon(Icons.speed),
tooltip: '镜像线路:${dp.mirror.currentName}',
onPressed: _showMirrorDialog,
),
],
bottom: const TabBar(tabs: [Tab(text: '搜索下载'), Tab(text: '任务队列')]),
),
body: TabBarView(children: [_buildSearchTab(), _buildQueueTab(dp)]),
),
);
}
Widget _buildSearchTab() {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Expanded(
child: TextField(
controller: _searchCtrl,
decoration: const InputDecoration(
hintText: '搜索 Modrinth 模组/插件,如 sodium',
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
isDense: true,
),
onSubmitted: (_) => _search(),
),
),
const SizedBox(width: 8),
FilledButton(onPressed: _searching ? null : _search, child: const Text('搜索')),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
_dropdown<String>(
value: _projectType,
items: const {'mod': '模组', 'plugin': '插件'},
onChanged: (v) => setState(() => _projectType = v!),
),
const SizedBox(width: 8),
_dropdown<String>(
value: _mcVersion,
hint: 'MC 版本',
items: {for (final v in _mcVersions) v: v},
onChanged: (v) => setState(() => _mcVersion = v),
),
const SizedBox(width: 8),
_dropdown<String>(
value: _loader,
hint: '加载器',
items: {for (final v in _loaders) v: v},
onChanged: (v) => setState(() => _loader = v),
),
],
),
),
Expanded(
child: _searching
? const Center(child: CircularProgressIndicator())
: _results == null
? const Center(child: Text('输入关键词开始搜索'))
: _results!.isEmpty
? const Center(child: Text('没有结果'))
: ListView.builder(
itemCount: _results!.length,
itemBuilder: (context, i) {
final r = _results![i];
return ListTile(
leading: const Icon(Icons.extension),
title: Text(r.title),
subtitle: Text(r.description, maxLines: 2, overflow: TextOverflow.ellipsis),
trailing: Text('${r.downloads}',
style: Theme.of(context).textTheme.bodySmall),
onTap: () => _showVersionSheet(r),
);
},
),
),
],
);
}
Widget _dropdown<T>({
required T? value,
required Map<String, String> items,
String? hint,
required ValueChanged<T?> onChanged,
}) {
return Expanded(
child: DropdownButtonFormField<T>(
value: value,
isDense: true,
decoration: InputDecoration(hintText: hint, border: const OutlineInputBorder(), isDense: true),
items: items.entries
.map((e) => DropdownMenuItem<T>(value: e.key as T, child: Text(e.value, overflow: TextOverflow.ellipsis)))
.toList(),
onChanged: onChanged,
),
);
}
/// 版本选择底部弹层。
Future<void> _showVersionSheet(ModrinthSearchResult r) async {
final dp = context.read<DownloadProvider>();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('正在获取版本列表...'), duration: Duration(seconds: 1)),
);
try {
final versions = await dp.versions(r.projectId);
if (!mounted) return;
showModalBottomSheet(
context: context,
builder: (_) => SafeArea(
child: ListView(
shrinkWrap: true,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text('选择 ${r.title} 的版本', style: Theme.of(context).textTheme.titleMedium),
),
...versions.take(15).map((v) => ListTile(
title: Text(v.versionNumber),
subtitle: Text('${v.loaders.join('/')} · ${v.gameVersions.take(3).join(', ')}'),
trailing: const Icon(Icons.download),
onTap: () => _downloadVersion(v),
)),
],
),
),
);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('获取版本失败:$e')));
}
}
}
Future<void> _downloadVersion(ModrinthVersion v) async {
Navigator.pop(context);
final dp = context.read<DownloadProvider>();
// 取主 jar 文件
final files = v.files;
if (files.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('该版本没有可用文件')));
return;
}
final primary = files.firstWhere((f) => f['primary'] == true, orElse: () => files.first);
final url = primary['url'] as String;
final fileName = primary['filename'] as String;
await dp.download(url: url, fileName: fileName, projectType: _projectType);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已加入下载队列:$fileName')));
}
}
Widget _buildQueueTab(DownloadProvider dp) {
return AnimatedBuilder(
animation: dp.manager,
builder: (context, _) {
final tasks = dp.manager.tasks;
if (tasks.isEmpty) return const Center(child: Text('暂无下载任务'));
return ListView.builder(
itemCount: tasks.length,
itemBuilder: (context, i) {
final t = tasks[i];
return Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(child: Text(t.fileName, overflow: TextOverflow.ellipsis)),
_statusChip(t.status),
],
),
const SizedBox(height: 8),
LinearProgressIndicator(value: t.progress),
const SizedBox(height: 6),
Row(
children: [
Text(
'${_fmt(t.receivedBytes)} / ${_fmt(t.totalBytes)}'
'${t.status == DownloadStatus.running ? " · ${_fmt(t.speed)}/s" : ""}',
style: Theme.of(context).textTheme.bodySmall,
),
const Spacer(),
if (t.status == DownloadStatus.running)
IconButton(
icon: const Icon(Icons.pause),
tooltip: '暂停',
onPressed: () => dp.manager.pause(t.id),
),
if (t.status == DownloadStatus.paused)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: '继续',
onPressed: () => dp.manager.resume(t.id),
),
if (t.status == DownloadStatus.failed)
IconButton(
icon: const Icon(Icons.replay),
tooltip: '重试',
onPressed: () => dp.manager.retry(t.id),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: '取消',
onPressed: () => dp.manager.cancel(t.id),
),
],
),
if (t.error != null)
Text(t.error!, style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12)),
],
),
),
);
},
);
},
);
}
Widget _statusChip(DownloadStatus s) {
final (label, color) = switch (s) {
DownloadStatus.queued => ('排队中', Colors.grey),
DownloadStatus.running => ('下载中', Colors.blue),
DownloadStatus.paused => ('已暂停', Colors.orange),
DownloadStatus.completed => ('已完成', Colors.green),
DownloadStatus.failed => ('失败', Colors.red),
DownloadStatus.canceled => ('已取消', Colors.grey),
};
return Chip(label: Text(label, style: const TextStyle(fontSize: 12)), backgroundColor: color.withOpacity(0.15), visualDensity: VisualDensity.compact);
}
String _fmt(num bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
}
Future<void> _showMirrorDialog() async {
final dp = context.read<DownloadProvider>();
final mirror = dp.mirror;
await showDialog(
context: context,
builder: (_) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog(
title: const Text('镜像线路'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
RadioListTile<String>(
title: const Text('Modrinth 官方'),
value: 'official',
groupValue: mirror.currentId,
onChanged: (v) async {
await mirror.select(v!);
setDialogState(() {});
},
),
RadioListTile<String>(
title: const Text('MCIM 国内镜像'),
value: 'mcim',
groupValue: mirror.currentId,
onChanged: (v) async {
await mirror.select(v!);
setDialogState(() {});
},
),
RadioListTile<String>(
title: const Text('自定义镜像'),
value: 'custom',
groupValue: mirror.currentId,
onChanged: (v) async {
final ctrl = TextEditingController(text: mirror.customUrl);
final url = await showDialog<String>(
context: context,
builder: (_) => AlertDialog(
title: const Text('自定义镜像地址'),
content: TextField(controller: ctrl, decoration: const InputDecoration(hintText: 'https://your-mirror.example.com')),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(onPressed: () => Navigator.pop(context, ctrl.text.trim()), child: const Text('确定')),
],
),
);
if (url != null && url.isNotEmpty) {
await mirror.select('custom', customUrl: url);
}
setDialogState(() {});
},
),
const SizedBox(height: 8),
OutlinedButton.icon(
icon: const Icon(Icons.bolt),
label: const Text('一键测速并选择最快线路'),
onPressed: () async {
await mirror.autoSelect();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已选择最快线路:${mirror.currentName}(${mirror.lastSpeedMs}ms)')),
);
}
setDialogState(() {});
},
),
],
),
actions: [
FilledButton(onPressed: () => Navigator.pop(context), child: const Text('完成')),
],
),
),
);
if (mounted) setState(() {});
}
}
@@ -0,0 +1,228 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/services/dependency_index_service.dart';
import '../../providers/download_provider.dart';
import '../../providers/server_provider.dart';
/// 依赖仓库页:服务器本地仓库增量同步 + 依赖树查询 + 缺失依赖一键补齐 + 重复检测。
class DependencyTreePage extends StatefulWidget {
final ServerConfig server;
const DependencyTreePage({super.key, required this.server});
@override
State<DependencyTreePage> createState() => _DependencyTreePageState();
}
class _DependencyTreePageState extends State<DependencyTreePage> {
List<IndexedMod>? _mods;
bool _syncing = false;
String? _syncInfo;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final mods = await DependencyIndexService.listForServer(widget.server.id);
if (!mounted) return;
setState(() => _mods = mods);
}
Future<void> _sync() async {
setState(() {
_syncing = true;
_syncInfo = null;
});
try {
final result = await DependencyIndexService.syncServer(widget.server);
if (!mounted) return;
setState(() {
_syncInfo = result.toString();
_syncing = false;
});
await _load();
} catch (e) {
if (!mounted) return;
setState(() {
_syncing = false;
_syncInfo = '同步失败:$e';
});
}
}
Future<void> _showTree(IndexedMod mod) async {
final tree = await DependencyIndexService.queryTree(widget.server.id, mod.modId);
if (!mounted) return;
showModalBottomSheet(
context: context,
builder: (_) => SafeArea(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(16),
children: [
Text('${tree.mod.name ?? tree.mod.fileName} ${tree.mod.version ?? ''}',
style: Theme.of(context).textTheme.titleMedium),
const Divider(),
const Text('该模组依赖:'),
...tree.dependsOn.map((m) => ListTile(
dense: true,
leading: const Icon(Icons.link, size: 18),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
)),
if (tree.dependsOn.isEmpty) const Text('无', style: TextStyle(color: Colors.grey)),
const SizedBox(height: 8),
const Text('被以下模组依赖:'),
...tree.dependents.map((m) => ListTile(
dense: true,
leading: const Icon(Icons.link, size: 18),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
)),
if (tree.dependents.isEmpty) const Text('无', style: TextStyle(color: Colors.grey)),
if (tree.missing.isNotEmpty) ...[
const SizedBox(height: 8),
const Text('缺失依赖(可一键补齐):',
style: TextStyle(color: Colors.red, fontWeight: FontWeight.w600)),
...tree.missing.map((d) => ListTile(
dense: true,
leading: const Icon(Icons.warning_amber_rounded, color: Colors.red, size: 20),
title: Text(d),
trailing: TextButton(
onPressed: () => _fetchMissing(d),
child: const Text('从 Modrinth 补齐'),
),
)),
],
],
),
),
);
}
Future<void> _fetchMissing(String name) async {
final dp = context.read<DownloadProvider>();
try {
final results = await dp.search(name, projectType: 'mod', limit: 1);
if (results.isEmpty) throw '未找到 $name';
final project = results.first;
final versions = await dp.versions(project.projectId);
if (versions.isEmpty) throw '该项目没有可用版本';
final v = versions.first;
if (v.files.isEmpty) throw '没有可用文件';
final primary = v.files.firstWhere((f) => f['primary'] == true, orElse: () => v.files.first);
await dp.download(url: primary['url'], fileName: primary['filename'], projectType: 'mod');
if (mounted) {
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已下载 $name(${v.versionNumber})')));
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('补齐失败:$e')));
}
}
}
Future<void> _checkDuplicates() async {
final dups = await DependencyIndexService.findDuplicates(widget.server.id);
if (!mounted) return;
showModalBottomSheet(
context: context,
builder: (_) => SafeArea(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(16),
children: [
Text('版本冲突 / 重复 jar', style: Theme.of(context).textTheme.titleMedium),
const Divider(),
if (dups.isEmpty) const Text('未发现重复'),
...dups.map((g) => ExpansionTile(
title: Text(g.modId,
style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.w600)),
subtitle: Text('${g.items.length} 个版本共存'),
children: g.items
.map((m) => ListTile(
dense: true,
title: Text(m.fileName),
subtitle: Text('版本 ${m.version ?? '未知'} · ${m.remotePath}'),
))
.toList(),
)),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('依赖仓库'),
actions: [
IconButton(
icon: const Icon(Icons.rule),
tooltip: '重复检测',
onPressed: _checkDuplicates,
),
],
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Expanded(
child: Text(_syncInfo ?? '点击「同步」增量扫描服务器 mods/plugins 并建立依赖索引'),
),
FilledButton.icon(
icon: _syncing
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.sync),
label: const Text('同步'),
onPressed: _syncing ? null : _sync,
),
],
),
),
Expanded(
child: _mods == null
? const Center(child: CircularProgressIndicator())
: _mods!.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('索引为空,先点击「同步」'),
if (!widget.server.hasSsh)
const Padding(
padding: EdgeInsets.all(8),
child: Text('(该服务器未配置 SSH,无法同步)',
style: TextStyle(color: Colors.red)),
),
],
),
)
: ListView.builder(
itemCount: _mods!.length,
itemBuilder: (context, i) {
final m = _mods![i];
return ListTile(
leading: const Icon(Icons.inventory_2_outlined),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
subtitle: Text(
'${m.fileName} · 依赖 ${m.depends.length} · 软依赖 ${m.softDepends.length}',
),
trailing: const Icon(Icons.account_tree_outlined),
onTap: () => _showTree(m),
);
},
),
),
],
),
);
}
}
@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import '../mod_manager/mod_provider.dart';
/// 模组详情页:展示 jar 元数据(名称 / 版本 / 作者 / 依赖 / 描述)。
class ModDetailPage extends StatelessWidget {
final RemoteJarFile file;
final ModProvider provider;
const ModDetailPage({super.key, required this.file, required this.provider});
@override
Widget build(BuildContext context) {
final meta = file.meta;
return Scaffold(
appBar: AppBar(title: Text(file.fileName)),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
ListTile(
leading: const Icon(Icons.extension),
title: Text(meta.name ?? '未知名称',
style: Theme.of(context).textTheme.titleLarge),
subtitle: Text('版本 ${meta.version ?? '未知'}'),
),
const Divider(),
_kv('文件名', file.fileName),
_kv('大小', _fmtSize(file.size)),
_kv('修改时间', '${file.mtime.toLocal()}'),
_kv('作者', meta.authors ?? '未知'),
_kv('元数据来源', meta.source),
if (meta.description != null) _kv('描述', meta.description!),
const Divider(),
Text('硬依赖', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
if (meta.depends.isEmpty)
const Text('无')
else
Wrap(
spacing: 6,
children: meta.depends
.map((d) => Chip(label: Text(d)))
.toList(),
),
const SizedBox(height: 12),
Text('软依赖', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
if (meta.softDepends.isEmpty)
const Text('无')
else
Wrap(spacing: 6, children: meta.softDepends.map((d) => Chip(label: Text(d))).toList()),
],
),
);
}
Widget _kv(String k, String v) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(width: 96, child: Text(k, style: const TextStyle(fontWeight: FontWeight.w600))),
Expanded(child: Text(v)),
],
),
);
String _fmtSize(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
}
}
+254
View File
@@ -0,0 +1,254 @@
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../dashboard/server_picker_bar.dart';
import 'mod_provider.dart';
import 'mod_detail_page.dart';
import 'dependency_tree_page.dart';
/// 模组/插件管理页:列出服务器 mods / plugins 目录中的 jar 文件,
/// 支持上传 / 删除 / 重命名 / 查看详情(M1)。
class ModListPage extends StatefulWidget {
const ModListPage({super.key});
@override
State<ModListPage> createState() => _ModListPageState();
}
class _ModListPageState extends State<ModListPage>
with AutomaticKeepAliveClientMixin {
ModProvider? _provider;
@override
bool get wantKeepAlive => true;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final server = context.read<SelectedServerHolder>().server;
if (server != null && (_provider == null || _provider!.server?.id != server.id)) {
_disposeProvider();
final p = ModProvider();
_provider = p;
p.open(server);
}
}
@override
void dispose() {
_disposeProvider();
super.dispose();
}
void _disposeProvider() {
_provider?.disconnect();
_provider?.dispose();
_provider = null;
}
@override
Widget build(BuildContext context) {
super.build(context);
final server = context.watch<SelectedServerHolder>().server;
if (server == null) {
return const Center(child: Text('请先在「服务器」页选择一台服务器'));
}
if (!server.hasSsh) {
return _NoSshHint(serverName: server.name);
}
final p = _provider;
if (p == null) return const SizedBox.shrink();
return ChangeNotifierProvider<ModProvider>.value(
value: p,
child: Consumer<ModProvider>(builder: (context, mod, _) {
return Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: const Text('模组管理'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: mod.loading ? null : mod.refresh,
tooltip: '刷新',
),
IconButton(
icon: const Icon(Icons.account_tree_outlined),
tooltip: '依赖仓库',
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => DependencyTreePage(server: server),
),
),
),
],
),
body: Column(
children: [
// mods / plugins 切换 + 排序
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
children: [
SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'mods', label: Text('mods')),
ButtonSegment(value: 'plugins', label: Text('plugins')),
],
selected: {mod.currentDir},
onSelectionChanged: (s) =>
mod.open(server, dir: s.first),
),
const Spacer(),
PopupMenuButton<ModSortMode>(
icon: const Icon(Icons.sort),
onSelected: (m) => mod.setSortMode(m),
itemBuilder: (_) => const [
PopupMenuItem(value: ModSortMode.name, child: Text('按名称')),
PopupMenuItem(value: ModSortMode.size, child: Text('按大小')),
PopupMenuItem(value: ModSortMode.mtime, child: Text('按修改时间')),
],
),
],
),
),
if (mod.loading) const LinearProgressIndicator(),
if (mod.error != null)
Padding(
padding: const EdgeInsets.all(12),
child: Text('加载失败:${mod.error}',
style: TextStyle(color: Theme.of(context).colorScheme.error)),
),
Expanded(
child: mod.files.isEmpty && !mod.loading
? const Center(child: Text('目录下没有 .jar 文件'))
: ListView.builder(
itemCount: mod.files.length,
itemBuilder: (context, i) {
final f = mod.files[i];
return ListTile(
leading: const Icon(Icons.extension_outlined),
title: Text(f.fileName),
subtitle: Text(
'${f.meta.name ?? '未知'} ${f.meta.version ?? ''}'
' · ${_fmtSize(f.size)}',
),
trailing: PopupMenuButton<String>(
onSelected: (a) => _onAction(context, mod, f, a),
itemBuilder: (_) => const [
PopupMenuItem(value: 'detail', child: Text('详情')),
PopupMenuItem(value: 'rename', child: Text('重命名')),
PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ModDetailPage(file: f, provider: mod),
),
),
);
},
),
),
],
),
floatingActionButton: FloatingActionButton.extended(
icon: const Icon(Icons.upload_file),
label: const Text('上传 jar'),
onPressed: mod.loading ? null : () => _upload(context, mod),
),
);
}),
);
}
Future<void> _upload(BuildContext context, ModProvider mod) async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jar'],
);
if (result == null || result.files.single.path == null) return;
try {
await mod.uploadJar(result.files.single.path!);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('上传失败:$e')));
}
}
}
Future<void> _onAction(
BuildContext context, ModProvider mod, RemoteJarFile f, String action) async {
switch (action) {
case 'delete':
final ok = await showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
title: const Text('确认删除'),
content: Text('确定要删除 ${f.fileName} 吗?此操作不可恢复。'),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('删除')),
],
),
);
if (ok == true) await mod.deleteJar(f.fileName);
break;
case 'rename':
final ctrl = TextEditingController(text: f.fileName);
final newName = await showDialog<String>(
context: context,
builder: (_) => AlertDialog(
title: const Text('重命名'),
content: TextField(controller: ctrl, autofocus: true),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(context, ctrl.text.trim()),
child: const Text('确定')),
],
),
);
if (newName != null && newName.isNotEmpty && newName != f.fileName) {
await mod.renameJar(f.fileName, newName);
}
break;
}
}
String _fmtSize(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
}
}
class _NoSshHint extends StatelessWidget {
final String serverName;
const _NoSshHint({required this.serverName});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.no_encryption_outlined, size: 56),
const SizedBox(height: 12),
Text('$serverName 未配置 SSH'),
const SizedBox(height: 8),
const Text(
'模组管理需要 SSH 连接。请在「服务器」页编辑该服务器,\n开启 SSH 并填写用户名和密码。',
textAlign: TextAlign.center,
),
],
),
),
);
}
}
+176
View File
@@ -0,0 +1,176 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import '../../core/services/jar_metadata.dart';
import '../../core/services/sftp_service.dart';
import '../../providers/server_provider.dart';
enum ModSortMode { name, size, mtime }
/// 模组/插件管理状态:通过 SFTP 列出 mods/plugins 目录的 jar 文件,
/// 本地缓存元数据解析结果。
class ModProvider extends ChangeNotifier {
ServerConfig? server;
String currentDir = 'mods'; // mods | plugins
final Map<String, RemoteJarFile> _files = {};
bool loading = false;
String? error;
ModSortMode sortMode = ModSortMode.name;
void setSortMode(ModSortMode mode) {
sortMode = mode;
notifyListeners();
}
final SftpService _sftp = SftpService();
List<RemoteJarFile> get files {
final list = _files.values.toList();
list.sort((a, b) => switch (sortMode) {
ModSortMode.name => a.fileName.toLowerCase().compareTo(b.fileName.toLowerCase()),
ModSortMode.size => b.size.compareTo(a.size),
ModSortMode.mtime => b.mtime.compareTo(a.mtime),
});
return list;
}
Future<void> open(ServerConfig s, {String dir = 'mods'}) async {
server = s;
currentDir = dir;
await refresh();
}
String get _remoteBase {
final user = server!.sshUser;
final home = user == 'root' ? '/root' : '/home/$user';
return '$home/$currentDir';
}
Future<void> refresh() async {
final s = server;
if (s == null || !s.hasSsh) return;
loading = true;
error = null;
notifyListeners();
try {
await _sftp.connect(s);
final items = await _sftp.listDir(_remoteBase);
_files.clear();
for (final item in items) {
if (item.attr.isDirectory || !item.filename.endsWith('.jar')) continue;
_files[item.filename] = RemoteJarFile(
fileName: item.filename,
remotePath: '$_remoteBase/${item.filename}',
size: item.attr.size ?? 0,
mtime: DateTime.fromMillisecondsSinceEpoch((item.attr.modifyTime ?? 0) * 1000),
);
}
// 后台解析元数据(复用本地缓存)
final cacheDir = await _cacheDir();
for (final f in _files.values) {
final meta = await _metadataFor(f, cacheDir);
f.meta = meta;
}
loading = false;
notifyListeners();
} catch (e) {
error = e.toString();
loading = false;
notifyListeners();
}
}
/// 首次进入时下载 jar 解析元数据并缓存到本地,之后按 (name,size,mtime) 复用。
Future<JarMetadata> _metadataFor(RemoteJarFile f, Directory cacheDir) async {
final cacheFile = File('${cacheDir.path}/${f.cacheKey}.meta.json');
if (await cacheFile.exists()) {
try {
return JarMetaCache.fromJsonString(await cacheFile.readAsString());
} catch (_) {}
}
try {
final tmp = File('${cacheDir.path}/${f.cacheKey}.jar');
await _sftp.download(f.remotePath, tmp.path);
final meta = JarMetadata.parse(tmp.path);
await tmp.delete();
await cacheFile.writeAsString(meta.toJsonString());
return meta;
} catch (_) {
return JarMetadata.empty;
}
}
Future<Directory> _cacheDir() async {
final base = await getApplicationDocumentsDirectory();
final dir = Directory('${base.path}/jar_meta_cache');
if (!await dir.exists()) await dir.create(recursive: true);
return dir;
}
/// 上传本地 jar。
Future<void> uploadJar(String localPath) async {
final name = localPath.split(Platform.pathSeparator).last;
await _sftp.upload(localPath, '$_remoteBase/$name');
await refresh();
}
/// 删除远程 jar。
Future<void> deleteJar(String fileName) async {
await _sftp.delete('$_remoteBase/$fileName');
_files.remove(fileName);
notifyListeners();
}
/// 重命名远程 jar。
Future<void> renameJar(String oldName, String newName) async {
await _sftp.rename('$_remoteBase/$oldName', newName);
await refresh();
}
Future<void> disconnect() => _sftp.disconnect();
}
/// 远程 jar 文件描述。
class RemoteJarFile {
final String fileName;
final String remotePath;
final int size;
final DateTime mtime;
JarMetadata meta = JarMetadata.empty;
RemoteJarFile({
required this.fileName,
required this.remotePath,
required this.size,
required this.mtime,
});
String get cacheKey =>
'${fileName.hashCode}_${size}_${mtime.millisecondsSinceEpoch ~/ 1000}';
}
extension JarMetaCache on JarMetadata {
String toJsonString() => jsonEncode({
'name': name,
'version': version,
'authors': authors,
'description': description,
'depends': depends,
'softDepends': softDepends,
'source': source,
});
static JarMetadata fromJsonString(String s) {
final m = jsonDecode(s) as Map<String, dynamic>;
return JarMetadata(
name: m['name'],
version: m['version'],
authors: m['authors'],
description: m['description'],
depends: List<String>.from(m['depends'] ?? const []),
softDepends: List<String>.from(m['softDepends'] ?? const []),
source: m['source'] ?? 'cache',
);
}
}
+10 -10
View File
@@ -87,7 +87,7 @@ class ServerCard extends StatelessWidget {
// 卡片底色跟随主题表面色,浮一层极淡的品牌色,避免纯白/纯黑显得生硬。
final Color base = Color.alphaBlend(
scheme.primary.withValues(alpha: online ? 0.06 : 0.02),
scheme.primary.withOpacity(online ? 0.06 : 0.02),
scheme.surface,
);
@@ -102,13 +102,13 @@ class ServerCard extends StatelessWidget {
color: base,
border: Border.all(
color: online
? scheme.primary.withValues(alpha: 0.38)
: scheme.outlineVariant.withValues(alpha: 0.55),
? scheme.primary.withOpacity(0.38)
: scheme.outlineVariant.withOpacity(0.55),
width: online ? 1.4 : 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: online ? 0.08 : 0.04),
color: Colors.black.withOpacity(online ? 0.08 : 0.04),
blurRadius: online ? 18 : 10,
offset: const Offset(0, 6),
),
@@ -158,9 +158,9 @@ class ServerCard extends StatelessWidget {
Container(
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3),
decoration: BoxDecoration(
color: _statusColor.withValues(alpha: 0.13),
color: _statusColor.withOpacity(0.13),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: _statusColor.withValues(alpha: 0.28)),
border: Border.all(color: _statusColor.withOpacity(0.28)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
@@ -177,7 +177,7 @@ class ServerCard extends StatelessWidget {
Text(
'${latencyMs}ms',
style: theme.textTheme.labelSmall?.copyWith(
color: _statusColor.withValues(alpha: 0.75),
color: _statusColor.withOpacity(0.75),
fontFeatures: const [FontFeature.tabularFigures()],
),
),
@@ -393,7 +393,7 @@ class _StatusDotState extends State<_StatusDot>
color: widget.color,
boxShadow: [
BoxShadow(
color: widget.color.withValues(alpha: glow),
color: widget.color.withOpacity(glow),
blurRadius: 10,
spreadRadius: 3,
),
@@ -422,8 +422,8 @@ class _Pill extends StatelessWidget {
@override
Widget build(BuildContext context) {
final bg = emphasized
? color.withValues(alpha: 0.14)
: color.withValues(alpha: 0.08);
? color.withOpacity(0.14)
: color.withOpacity(0.08);
final content = Container(
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
@@ -17,6 +17,12 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
late TextEditingController _portCtrl;
late TextEditingController _passCtrl;
bool _obscurePassword = true;
// SSH 可选配置(模组管理 / 终端需要)
bool _sshEnabled = false;
bool _obscureSshPassword = true;
late TextEditingController _sshPortCtrl;
late TextEditingController _sshUserCtrl;
late TextEditingController _sshPasswordCtrl;
bool get isEditing => widget.existingServer != null;
@@ -28,6 +34,10 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
_hostCtrl = TextEditingController(text: s?.host ?? '');
_portCtrl = TextEditingController(text: s?.port.toString() ?? '25575');
_passCtrl = TextEditingController(text: s?.password ?? '');
_sshEnabled = s?.sshEnabled ?? false;
_sshPortCtrl = TextEditingController(text: s?.sshPort.toString() ?? '22');
_sshUserCtrl = TextEditingController(text: s?.sshUser ?? '');
_sshPasswordCtrl = TextEditingController(text: s?.sshPassword ?? '');
}
@override
@@ -36,6 +46,9 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
_hostCtrl.dispose();
_portCtrl.dispose();
_passCtrl.dispose();
_sshPortCtrl.dispose();
_sshUserCtrl.dispose();
_sshPasswordCtrl.dispose();
super.dispose();
}
@@ -60,6 +73,10 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
host: _hostCtrl.text.trim(),
port: int.parse(_portCtrl.text.trim()),
password: _passCtrl.text,
sshEnabled: _sshEnabled,
sshPort: int.tryParse(_sshPortCtrl.text.trim()) ?? 22,
sshUser: _sshUserCtrl.text.trim(),
sshPassword: _sshPasswordCtrl.text,
);
Navigator.pop(context, server);
@@ -111,6 +128,51 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _submit(),
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('SSH 连接(可选)'),
subtitle: const Text('用于模组插件管理与远程终端'),
value: _sshEnabled,
onChanged: (v) => setState(() => _sshEnabled = v),
),
if (_sshEnabled) ...[
TextFormField(
controller: _sshPortCtrl,
decoration: const InputDecoration(labelText: 'SSH 端口', hintText: '默认 22'),
keyboardType: TextInputType.number,
validator: (v) {
if (!_sshEnabled) return null;
return _validatePort(v);
},
textInputAction: TextInputAction.next,
),
const SizedBox(height: 12),
TextFormField(
controller: _sshUserCtrl,
decoration: const InputDecoration(labelText: 'SSH 用户名', hintText: '例如 root'),
validator: (v) => _sshEnabled ? _validateRequired(v, 'SSH 用户名') : null,
textInputAction: TextInputAction.next,
),
const SizedBox(height: 12),
TextFormField(
controller: _sshPasswordCtrl,
obscureText: _obscureSshPassword,
decoration: InputDecoration(
labelText: 'SSH 密码',
suffixIcon: IconButton(
icon: Icon(_obscureSshPassword
? Icons.visibility_off_outlined
: Icons.visibility_outlined),
onPressed: () =>
setState(() => _obscureSshPassword = !_obscureSshPassword),
),
),
validator: (v) => _sshEnabled ? _validateRequired(v, 'SSH 密码') : null,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _submit(),
),
],
],
),
),
@@ -265,9 +265,9 @@ class _EmptyState extends StatelessWidget {
height: 84,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: scheme.primary.withValues(alpha: 0.08),
color: scheme.primary.withOpacity(0.08),
border: Border.all(
color: scheme.primary.withValues(alpha: 0.18),
color: scheme.primary.withOpacity(0.18),
),
),
child: Icon(Icons.dns_outlined, size: 36, color: scheme.primary),
+2 -2
View File
@@ -132,10 +132,10 @@ class _SettingsPageState extends State<SettingsPage> {
}
Future<void> _pickVideo() async {
final result = await FilePicker.pickFile(type: FileType.video);
final result = await FilePicker.platform.pickFiles(type: FileType.video);
if (result == null) return;
final filePath = result.path;
final filePath = result.files.single.path;
if (filePath == null) return;
final path = await _saveFileToAssets(filePath, 'video');
+114
View File
@@ -0,0 +1,114 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/utils/rcon_client.dart';
import '../../providers/rcon_provider.dart';
import '../console/console_page.dart';
import '../dashboard/dashboard_page.dart';
import '../mod_manager/mod_list_page.dart';
import '../player_management/player_list_page.dart';
import '../settings/settings_page.dart';
import '../terminal/terminal_page.dart';
import '../dashboard/server_picker_bar.dart';
/// 主导航壳:底部导航「服务器 · 控制台 · 玩家 · 模组 · 终端 · 我的」(M4)。
class MainShell extends StatefulWidget {
const MainShell({super.key});
@override
State<MainShell> createState() => _MainShellState();
}
class _MainShellState extends State<MainShell> {
int _index = 0;
@override
Widget build(BuildContext context) {
final pages = [
const DashboardPage(),
const _ConsoleTab(),
const _PlayerTab(),
const ModListPage(),
const TerminalPage(),
const SettingsPage(),
];
return Scaffold(
body: IndexedStack(index: _index, children: pages),
bottomNavigationBar: NavigationBar(
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
destinations: const [
NavigationDestination(icon: Icon(Icons.dns_outlined), selectedIcon: Icon(Icons.dns), label: '服务器'),
NavigationDestination(icon: Icon(Icons.terminal_outlined), selectedIcon: Icon(Icons.terminal), label: '控制台'),
NavigationDestination(icon: Icon(Icons.group_outlined), selectedIcon: Icon(Icons.group), label: '玩家'),
NavigationDestination(icon: Icon(Icons.extension_outlined), selectedIcon: Icon(Icons.extension), label: '模组'),
NavigationDestination(icon: Icon(Icons.terminal), selectedIcon: Icon(Icons.terminal), label: '终端'),
NavigationDestination(icon: Icon(Icons.settings_outlined), selectedIcon: Icon(Icons.settings), label: '我的'),
],
),
);
}
}
/// 控制台页签:选中服务器后通过 RconProvider 拿连接。
class _ConsoleTab extends StatelessWidget {
const _ConsoleTab();
@override
Widget build(BuildContext context) {
final holder = context.watch<SelectedServerHolder>();
final rcon = context.read<RconProvider>();
final server = holder.server;
if (server == null) {
return const _NeedServerHint();
}
return FutureBuilder<RconClient>(
future: rcon.getClient(server),
builder: (context, snap) {
if (snap.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snap.hasError) {
return Center(child: Text('RCON 连接失败:${snap.error}'));
}
return ConsolePage(rconClient: snap.data!);
},
);
}
}
/// 玩家页签。
class _PlayerTab extends StatelessWidget {
const _PlayerTab();
@override
Widget build(BuildContext context) {
final holder = context.watch<SelectedServerHolder>();
final rcon = context.read<RconProvider>();
final server = holder.server;
if (server == null) {
return const _NeedServerHint();
}
return FutureBuilder<RconClient>(
future: rcon.getClient(server),
builder: (context, snap) {
if (snap.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snap.hasError) {
return Center(child: Text('RCON 连接失败:${snap.error}'));
}
return PlayerListPage(rconClient: snap.data!);
},
);
}
}
class _NeedServerHint extends StatelessWidget {
const _NeedServerHint();
@override
Widget build(BuildContext context) {
return const Center(child: Text('请先在「服务器」页选择一台服务器'));
}
}
+194
View File
@@ -0,0 +1,194 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xterm/core.dart';
import 'package:xterm/ui.dart' show TerminalView;
import '../../core/services/ssh_shell_service.dart';
import '../../providers/server_provider.dart';
/// SSH 终端页:xterm 终端 + 快捷键栏 + 多服务器会话标签(M3)。
class TerminalPage extends StatefulWidget {
const TerminalPage({super.key});
@override
State<TerminalPage> createState() => _TerminalPageState();
}
class _TerminalPageState extends State<TerminalPage>
with AutomaticKeepAliveClientMixin {
final Map<String, _Session> _sessions = {};
String? _activeId;
List<ServerConfig> _sshServers = const [];
@override
bool get wantKeepAlive => true;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final servers = context.watch<ServerProvider>().servers.where((s) => s.hasSsh).toList();
_sshServers = servers;
if (servers.isNotEmpty && (_activeId == null || !_sessions.containsKey(_activeId))) {
_openSession(servers.first);
}
}
@override
void dispose() {
for (final s in _sessions.values) {
s.service.disconnect();
s.terminal.onOutput = null;
}
_sessions.clear();
super.dispose();
}
Future<void> _openSession(ServerConfig server) async {
if (_sessions.containsKey(server.id)) {
setState(() => _activeId = server.id);
return;
}
final session = _Session(server);
_sessions[server.id] = session;
setState(() => _activeId = server.id);
_connect(session);
}
Future<void> _connect(_Session session) async {
try {
await session.service.connect(
session.server,
onOutput: (data) => session.terminal.write(data),
onDisconnected: () {
session.terminal.write('\r\n\x1b[31m[连接已断开]\x1b[0m\r\n');
},
);
} catch (e) {
session.terminal.write('\r\n\x1b[31m连接失败:$e\x1b[0m\r\n');
}
}
void _sendKey(String data) {
final s = _sessions[_activeId];
if (s == null) return;
s.service.write(data);
}
@override
Widget build(BuildContext context) {
super.build(context);
if (_sshServers.isEmpty) {
return const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Text('没有配置 SSH 的服务器。\n\n请在「服务器」页编辑服务器,开启 SSH 后即可使用终端。',
textAlign: TextAlign.center),
),
);
}
final active = _sessions[_activeId];
return Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: const Text('终端'),
actions: [
PopupMenuButton<ServerConfig>(
icon: const Icon(Icons.add),
tooltip: '新会话',
onSelected: _openSession,
itemBuilder: (_) => _sshServers
.map((s) => PopupMenuItem(value: s, child: Text(s.name)))
.toList(),
),
],
bottom: _sessions.isEmpty
? null
: PreferredSize(
preferredSize: const Size.fromHeight(44),
child: SizedBox(
height: 44,
child: ListView(
scrollDirection: Axis.horizontal,
children: _sessions.values.map((s) {
final selected = s.server.id == _activeId;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6),
child: ChoiceChip(
label: Text(s.server.name),
selected: selected,
onSelected: (_) => setState(() => _activeId = s.server.id),
),
);
}).toList(),
),
),
),
),
body: active == null
? const Center(child: Text('选择一台服务器开始会话'))
: Column(
children: [
Expanded(
child: TerminalView(
active.terminal,
autofocus: true,
),
),
_buildQuickBar(),
],
),
);
}
/// 快捷键栏:Tab / Ctrl+C / Ctrl+D / 上下历史 / 常用命令。
Widget _buildQuickBar() {
return Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest.withOpacity(0.5),
),
child: SafeArea(
child: SizedBox(
height: 44,
child: ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
children: [
_key('Tab', '\t'),
_key('Ctrl+C', '\x03'),
_key('Ctrl+D', '\x04'),
_key('↑', '\x1b[A'),
_key('↓', '\x1b[B'),
_key('htop', 'htop\n'),
_key('df -h', 'df -h\n'),
_key('screen -r', 'screen -r\n'),
_key('clear', 'clear\n'),
_key('Esc', '\x1b'),
],
),
),
),
);
}
Widget _key(String label, String data) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: ActionChip(
label: Text(label),
onPressed: () => _sendKey(data),
),
);
}
}
/// 一个终端会话 = 一台服务器 + 终端缓冲 + SSH 服务。
class _Session {
final ServerConfig server;
final Terminal terminal = Terminal(maxLines: 5000);
final SshShellService service = SshShellService();
_Session(this.server) {
terminal.onOutput = (data) => service.write(data);
}
}