Files
ZV-Manager/lib/features/terminal/terminal_page.dart
T
Ventiの酒 e32125aa8e api修改和更新检查器修改
modrinth_api.dart:拦截器改为只替换 options.baseUrl,path 保持相对 /v2/search、query 留在 queryParameters,避免"整串写回 path"导致的 host 缺失 + query 重复拼接。mirror_service.dart:新增 apiBase getter,返回当前镜像的 API base(official→api.modrinth.com、mcim→modrinth-api.mcimirror.top、custom→自定义 base)

Signed-off-by: driftinblock <3480428251@qq.com>
2026-11-04 17:43:57 +08:00

283 lines
8.7 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/wallpaper_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';
import '../../core/l10n/strings.dart';
import '../../core/widgets/empty_state_page.dart';
import '../../core/widgets/z_widgets.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 EmptyStatePage(
title: '终端',
icon: Icons.terminal_outlined,
message: '没有配置 SSH 的服务器。\n\n请在「服务器」页编辑服务器,开启 SSH 后即可使用终端。',
);
}
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final active = _sessions[_activeId];
return Scaffold(
backgroundColor: hasWallpaper ? Colors.transparent : null,
appBar: ZAppBar(
title: T('终端'),
actions: [
PopupMenuButton<ServerConfig>(
icon: const Icon(Icons.add),
tooltip: S.t('新会话'),
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,
padding: const EdgeInsets.symmetric(horizontal: 8),
children: _sessions.values.map((s) {
final selected = s.server.id == _activeId;
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4, vertical: 6),
child: _SessionTab(
label: s.server.name,
selected: selected,
onTap: () =>
setState(() => _activeId = s.server.id),
),
);
}).toList(),
),
),
),
),
body: active == null
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.terminal_rounded,
size: 36,
color: Theme.of(context).colorScheme.onSurfaceVariant),
const SizedBox(height: 12),
T('选择一台服务器开始会话'),
],
),
)
: Column(
children: [
Expanded(
child: TerminalView(
active.terminal,
autofocus: true,
),
),
_buildQuickBar(),
],
),
);
}
/// 快捷键栏:Tab / Ctrl+C / Ctrl+D / 上下历史 / 常用命令。
///
/// 移动端软键盘没有这些键,因此用控制字符直接模拟:
/// Ctrl+C = 0x03,Ctrl+D = 0x04,↑ = ESC[A,↓ = ESC[B。
Widget _buildQuickBar() {
return Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHigh.withOpacity(0.5),
border: Border(
top: BorderSide(color: Theme.of(context).colorScheme.outlineVariant),
),
),
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'),
],
),
),
),
);
}
/// 生成一个快捷按键按钮。
/// [data] 是实际写入终端的字节(含控制字符或带换行的整条命令)。
Widget _key(String label, String data) {
final scheme = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 3),
child: Center(
child: GestureDetector(
onTap: () => _sendKey(data),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(20),
),
child: Text(
label,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 12,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
),
),
),
);
}
}
/// 终端会话切换标签:选中的用品牌色填充,未选中为透明描边。
class _SessionTab extends StatelessWidget {
final String label;
final bool selected;
final VoidCallback onTap;
const _SessionTab({
required this.label,
required this.selected,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 180),
padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 6),
decoration: BoxDecoration(
color: selected ? kZAccent : Colors.transparent,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: selected ? kZAccent : scheme.outlineVariant,
),
),
child: Center(
child: Text(
label,
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: selected ? Colors.white : scheme.onSurfaceVariant,
),
),
),
),
);
}
}
/// 一个终端会话 = 一台服务器 + 终端缓冲 + SSH 服务。
///
/// 多服务器时每个会话独立保活(切页签不重连),
/// 缓冲上限 5000 行,足以回看滚动输出又不会吃太多内存。
class _Session {
final ServerConfig server;
final Terminal terminal = Terminal(maxLines: 5000);
final SshShellService service = SshShellService();
_Session(this.server) {
terminal.onOutput = (data) => service.write(data);
}
}