feat: the terminal, project knowledge, and downloads that can be cancelled

- lib/api/terminal.dart: the PTY protocol (create/resize/restart/close, and
  the /api/terminal/ws binary control frames) with a reconnecting socket
  that replays the server snapshot at the size it was drawn for.
- lib/terminal_state.dart: an xterm model plus that socket, kept per
  workspace on AppState, so closing the panel or switching tabs keeps the
  shell; the app reattaches when it returns from the background.
- lib/screens/terminal_panel.dart: TerminalView, a status bar (keyboard,
  restart, clear, close) and a Termux-style key bar whose CTRL/ALT/SHIFT
  modifiers also apply to what the phone keyboard types.
- lib/screens/knowledge_panel.dart: notes, todos and plans from
  /api/project-context, searchable, with a full page for a plan's Markdown
  and its raw editor.
- Downloads stream with a progress dialog (bytes, total, percent) and a
  cancel that aborts the request; the save dialog only opens on success.
  The request asks for `accept-encoding: identity` so Content-Length exists.
- MarkdownView renders task lists as ✅/⬜ instead of material_ui's
  Checkbox, which wants a material_ui Material ancestor the app lacks.
- Dialogs own their TextEditingControllers, so closing one no longer
  trips a framework assertion in debug builds.
- 0.3.11 (311).
This commit is contained in:
blumia committed 2026-11-21 02:49:07 +08:00
1 parent 60d02083d3
commit 5f95e2da97
14 files changed
+2347 -57

No files matched your search

+132 -36
View File
@@ -9,8 +9,11 @@ import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../api/transport.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
import 'knowledge_panel.dart';
import 'terminal_panel.dart';
Future<void> showFilesPanel(
BuildContext context, AppState app, Session session) {
@@ -289,16 +292,28 @@ class _FilesPanelState extends State<FilesPanel> {
final client = _client;
final path = _previewPath;
if (client == null || path == null) return;
// A file already in memory needs no progress; the rest stream with one.
var bytes = _previewBytes;
if (bytes == null) {
bytes = await showDialog<Uint8List>(
context: context,
barrierDismissible: false,
builder: (_) => _DownloadDialog(
name: _previewName,
start: (onProgress, cancel) => client.downloadFile(path,
directory: _root, onProgress: onProgress, cancel: cancel),
),
);
}
if (bytes == null || !mounted) return;
try {
final bytes = _previewBytes ??
Uint8List.fromList(await client.rawFile(path, directory: _root));
final uri = await FilePicker.saveFile(
fileName: _previewName,
bytes: bytes,
);
if (uri != null) _toast('已保存');
} catch (e) {
_toast('下载失败:$e');
_toast('保存失败:$e');
}
}
@@ -516,46 +531,15 @@ class _FilesPanelState extends State<FilesPanel> {
}
switch (_tab) {
case 1:
return _placeholder(theme, Icons.menu_book_outlined, '项目知识',
'笔记、待办与计划会在这里。');
return KnowledgePanel(app: widget.app, directory: _root);
case 2:
return _placeholder(
theme, Icons.terminal, '终端', '在服务器上运行的终端会在这里。');
return TerminalPanel(app: widget.app, directory: _root);
default:
if (_previewPath != null) return _previewBody(theme);
return _browser(theme);
}
}
Widget _placeholder(
ThemeData theme, IconData icon, String title, String note) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 40, color: theme.hintColor),
const SizedBox(height: 12),
Text(title,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 6),
Text(note,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
const SizedBox(height: 10),
Chip(
label: const Text('即将支持'),
visualDensity: VisualDensity.compact,
side: BorderSide(color: theme.dividerColor),
),
],
),
),
);
}
Widget _browser(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -935,3 +919,115 @@ class _FilesPanelState extends State<FilesPanel> {
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
}
/// Streams one download and shows its progress; 取消 aborts the request and
/// the dialog closes with no bytes, so nothing is saved.
class _DownloadDialog extends StatefulWidget {
final String name;
final Future<Uint8List> Function(
void Function(int received, int? total) onProgress,
CancelToken cancel) start;
const _DownloadDialog({required this.name, required this.start});
@override
State<_DownloadDialog> createState() => _DownloadDialogState();
}
class _DownloadDialogState extends State<_DownloadDialog> {
final CancelToken _cancel = CancelToken();
int _received = 0;
int? _total;
bool _cancelling = false;
String? _error;
int _lastPaint = 0;
@override
void initState() {
super.initState();
_run();
}
Future<void> _run() async {
try {
final bytes = await widget.start((received, total) {
if (!mounted) return;
// Chunks arrive every few dozen KB; repaint a few times a second at
// most, and always on the last one.
final now = DateTime.now().millisecondsSinceEpoch;
if (total != null && received < total && now - _lastPaint < 80) return;
_lastPaint = now;
setState(() {
_received = received;
_total = total;
});
}, _cancel);
if (mounted) Navigator.of(context).pop(bytes);
} on DownloadCancelled {
if (mounted) Navigator.of(context).pop();
} catch (error) {
if (!mounted) return;
setState(() => _error = error is ApiError ? error.message : '$error');
}
}
String _size(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';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final total = _total;
final fraction = total != null && total > 0
? (_received / total).clamp(0.0, 1.0)
: null;
return AlertDialog(
title: const Text('正在下载'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13)),
const SizedBox(height: 12),
if (_error == null) ...[
LinearProgressIndicator(value: fraction),
const SizedBox(height: 8),
Text(
total != null
? '${_size(_received)} / ${_size(total)}'
'(${(fraction! * 100).toStringAsFixed(0)}%)'
: '已下载 ${_size(_received)}',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
] else
Text(_error!,
style:
TextStyle(fontSize: 12.5, color: theme.colorScheme.error)),
],
),
actions: [
if (_error == null)
TextButton(
onPressed: _cancelling
? null
: () {
setState(() => _cancelling = true);
_cancel.cancel();
},
child: Text(_cancelling ? '正在取消…' : '取消'),
)
else
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('关闭'),
),
],
);
}
}
+842
View File
@@ -0,0 +1,842 @@
// The project knowledge tab: notes, todos and plans stored by the server in
// the project context (`/api/project-context`), with search across all three.
import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
class KnowledgePanel extends StatefulWidget {
final AppState app;
final String directory;
const KnowledgePanel({super.key, required this.app, required this.directory});
@override
State<KnowledgePanel> createState() => _KnowledgePanelState();
}
class _KnowledgePanelState extends State<KnowledgePanel> {
ProjectContext? _context;
bool _loading = true;
String? _error;
int _section = 0;
String _query = '';
final TextEditingController _search = TextEditingController();
String get _projectId => Client.projectIdFor(widget.directory);
Client? get _client => widget.app.client;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_search.dispose();
super.dispose();
}
Future<void> _load() async {
final client = _client;
if (client == null || _projectId.isEmpty) {
setState(() {
_loading = false;
_error = '这个会话没有关联目录';
});
return;
}
setState(() {
_loading = true;
_error = null;
});
try {
final context = await client.projectContext(_projectId,
directory: widget.directory);
if (!mounted) return;
setState(() {
_context = context;
_loading = false;
});
} catch (error) {
if (!mounted) return;
setState(() {
_loading = false;
_error = '$error';
});
}
}
/// Applies a mutation's fresh context without a second round trip.
void _apply(ProjectContext context) {
if (!mounted) return;
setState(() => _context = context);
}
void _fail(Object error) {
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$error')));
}
bool _matches(Iterable<String> fields) {
final query = _query.trim().toLowerCase();
if (query.isEmpty) return true;
return fields.any((field) => field.toLowerCase().contains(query));
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 4, 0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _search,
onChanged: (value) => setState(() => _query = value),
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
hintText: '搜索笔记、待办与计划',
prefixIcon: const Icon(Icons.search, size: 18),
suffixIcon: _query.isEmpty
? null
: IconButton(
icon: const Icon(Icons.close, size: 16),
onPressed: () {
_search.clear();
setState(() => _query = '');
},
),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
),
IconButton(
tooltip: '刷新',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.refresh, size: 20),
onPressed: _load,
),
],
),
),
_sections(theme),
Expanded(child: _body(theme)),
],
);
}
Widget _sections(ThemeData theme) {
final context_ = _context;
final counts = [
context_?.notes.length ?? 0,
context_?.todos.length ?? 0,
context_?.plans.length ?? 0,
];
const names = ['笔记', '待办', '计划'];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 6),
child: SegmentedButton<int>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < names.length; i++)
ButtonSegment(value: i, label: Text('${names[i]} ${counts[i]}')),
],
selected: {_section},
onSelectionChanged: (value) => setState(() => _section = value.first),
),
);
}
Widget _body(ThemeData theme) {
if (_loading) return const Center(child: CircularProgressIndicator());
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_error!,
textAlign: TextAlign.center,
style: TextStyle(color: theme.colorScheme.error, fontSize: 13)),
const SizedBox(height: 8),
FilledButton(onPressed: _load, child: const Text('重试')),
],
),
),
);
}
switch (_section) {
case 1:
return _todos(theme);
case 2:
return _plans(theme);
default:
return _notes(theme);
}
}
// --------------------------------------------------------------- notes
Widget _notes(ThemeData theme) {
final notes = (_context?.notes ?? [])
.where((note) => _matches([note.body]))
.toList()
..sort((a, b) {
if (a.pinned != b.pinned) return a.pinned ? -1 : 1;
return b.updatedAt.compareTo(a.updatedAt);
});
return Column(
children: [
_sectionHeader(theme, '${notes.length} 条笔记', '新建笔记', _addNote),
Expanded(
child: notes.isEmpty
? _empty(theme, Icons.sticky_note_2_outlined,
_query.isEmpty ? '还没有笔记' : '没有匹配的笔记')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
itemCount: notes.length,
itemBuilder: (context, index) {
final note = notes[index];
return _noteCard(theme, note);
},
),
),
],
);
}
Widget _noteCard(ThemeData theme, ProjectNote note) {
final scheme = theme.colorScheme;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => _editNote(note),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 4, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
note.body.trim(),
maxLines: 5,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13.5, height: 1.35),
),
const SizedBox(height: 4),
Row(
children: [
if (note.pinned)
Padding(
padding: const EdgeInsets.only(right: 4),
child: Icon(Icons.push_pin,
size: 12, color: scheme.primary),
),
Text(
_stamp(note.updatedAt),
style:
TextStyle(fontSize: 11, color: theme.hintColor),
),
],
),
],
),
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) async {
final client = _client;
if (client == null) return;
try {
switch (value) {
case 'edit':
await _editNote(note);
break;
case 'pin':
_apply(await client.updateNote(
_projectId, note.id,
pinned: !note.pinned, directory: widget.directory));
break;
case 'delete':
_apply(await client.deleteNote(_projectId, note.id,
directory: widget.directory));
break;
}
} catch (error) {
_fail(error);
}
},
itemBuilder: (_) => [
const PopupMenuItem(value: 'edit', child: Text('编辑')),
PopupMenuItem(
value: 'pin', child: Text(note.pinned ? '取消置顶' : '置顶')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
],
),
),
),
);
}
// --------------------------------------------------------------- todos
Widget _todos(ThemeData theme) {
final todos = (_context?.todos ?? [])
.where((todo) => _matches([todo.text]))
.toList();
final done = todos.where((todo) => todo.completed).length;
return Column(
children: [
_sectionHeader(theme, '$done/${todos.length} 已完成', '新建待办', _addTodo),
Expanded(
child: todos.isEmpty
? _empty(theme, Icons.checklist,
_query.isEmpty ? '还没有待办' : '没有匹配的待办')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 12),
itemCount: todos.length,
itemBuilder: (context, index) {
final todo = todos[index];
return CheckboxListTile(
dense: true,
value: todo.completed,
onChanged: (value) => _toggleTodo(todo, value ?? false),
controlAffinity: ListTileControlAffinity.leading,
title: Text(
todo.text,
style: TextStyle(
fontSize: 13.5,
decoration: todo.completed
? TextDecoration.lineThrough
: null,
color: todo.completed ? theme.hintColor : null,
),
),
secondary: PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) async {
final client = _client;
if (client == null) return;
try {
if (value == 'delete') {
_apply(await client.deleteTodo(
_projectId, todo.id,
directory: widget.directory));
}
} catch (error) {
_fail(error);
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
);
},
),
),
],
);
}
Future<void> _toggleTodo(ProjectTodo todo, bool completed) async {
final client = _client;
if (client == null) return;
try {
_apply(await client.updateTodo(_projectId, todo.id,
completed: completed, directory: widget.directory));
} catch (error) {
_fail(error);
}
}
// --------------------------------------------------------------- plans
Widget _plans(ThemeData theme) {
final plans = (_context?.plans ?? [])
.where((plan) => _matches([plan.title, plan.file]))
.toList()
..sort((a, b) {
if (a.pinned != b.pinned) return a.pinned ? -1 : 1;
return b.createdAt.compareTo(a.createdAt);
});
return Column(
children: [
_sectionHeader(theme, '${plans.length} 份计划', '新建计划', _newPlan),
Expanded(
child: plans.isEmpty
? _empty(theme, Icons.description_outlined,
_query.isEmpty ? '还没有计划' : '没有匹配的计划')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 12),
itemCount: plans.length,
itemBuilder: (context, index) =>
_planTile(theme, plans[index]),
),
),
],
);
}
Widget _planTile(ThemeData theme, ProjectPlanLink plan) {
final scheme = theme.colorScheme;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
dense: true,
title: Row(
children: [
if (plan.pinned)
Padding(
padding: const EdgeInsets.only(right: 4),
child: Icon(Icons.push_pin, size: 13, color: scheme.primary),
),
Expanded(
child: Text(plan.title.isEmpty ? plan.file : plan.title,
maxLines: 2, overflow: TextOverflow.ellipsis),
),
],
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (plan.hasProgress) ...[
const SizedBox(height: 4),
Row(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: plan.progressDone / plan.progressTotal,
minHeight: 4,
backgroundColor: scheme.surfaceContainerHighest,
),
),
),
const SizedBox(width: 6),
Text('${plan.progressDone}/${plan.progressTotal}',
style:
TextStyle(fontSize: 11, color: theme.hintColor)),
],
),
],
const SizedBox(height: 2),
Text(
plan.source == 'shared' ? '团队共享' : '个人',
style: TextStyle(fontSize: 11, color: theme.hintColor),
),
],
),
trailing: PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) async {
final client = _client;
if (client == null) return;
try {
switch (value) {
case 'pin':
_apply(await client.setPlanPinned(
_projectId, plan.id, !plan.pinned,
directory: widget.directory));
break;
case 'delete':
_apply(await client.deletePlan(_projectId, plan.id,
directory: widget.directory));
break;
}
} catch (error) {
_fail(error);
}
},
itemBuilder: (_) => [
PopupMenuItem(
value: 'pin', child: Text(plan.pinned ? '取消置顶' : '置顶')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
onTap: () => _viewPlan(plan),
),
);
}
// -------------------------------------------------------------- dialogs
Widget _sectionHeader(
ThemeData theme, String summary, String action, VoidCallback onTap) {
return Padding(
padding: const EdgeInsets.fromLTRB(14, 0, 8, 2),
child: Row(
children: [
Expanded(
child: Text(summary,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
TextButton.icon(
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 32),
),
onPressed: onTap,
icon: const Icon(Icons.add, size: 16),
label: Text(action, style: const TextStyle(fontSize: 12.5)),
),
],
),
);
}
Widget _empty(ThemeData theme, IconData icon, String text) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 36, color: theme.hintColor),
const SizedBox(height: 8),
Text(text, style: TextStyle(fontSize: 13, color: theme.hintColor)),
],
),
);
}
Future<void> _addNote() => _editNote(null);
Future<void> _editNote(ProjectNote? note) async {
final text = await showDialog<String>(
context: context,
builder: (_) => _TextPromptDialog(
title: note == null ? '新建笔记' : '编辑笔记',
hint: '记点什么,供之后的会话参考',
initial: note?.body ?? '',
maxLength: 3000,
maxLines: 10,
minLines: 4,
action: '保存',
),
);
if (text == null || text.isEmpty) return;
final client = _client;
if (client == null) return;
try {
if (note == null) {
_apply(await client.createNote(_projectId, text,
directory: widget.directory));
} else {
_apply(await client.updateNote(_projectId, note.id,
body: text, directory: widget.directory));
}
} catch (error) {
_fail(error);
}
}
Future<void> _addTodo() async {
final text = await showDialog<String>(
context: context,
builder: (_) => const _TextPromptDialog(
title: '新建待办',
hint: '要做什么',
maxLength: 1000,
maxLines: 1,
minLines: 1,
action: '保存',
),
);
if (text == null || text.isEmpty) return;
final client = _client;
if (client == null) return;
try {
_apply(await client.createTodo(_projectId, text,
directory: widget.directory));
} catch (error) {
_fail(error);
}
}
Future<void> _newPlan() async {
final result = await showDialog<(String, String)>(
context: context,
builder: (_) => const _NewPlanDialog(),
);
if (result == null || result.$2.trim().isEmpty) return;
final client = _client;
if (client == null) return;
try {
_apply(await client.createPlan(_projectId,
title: result.$1, body: result.$2, directory: widget.directory));
} catch (error) {
_fail(error);
}
}
Future<void> _viewPlan(ProjectPlanLink plan) async {
final client = _client;
if (client == null) return;
ProjectPlanContent content;
try {
content = await client.planContent(_projectId, plan.id,
directory: widget.directory);
} catch (error) {
_fail(error);
return;
}
if (!mounted) return;
// A full page, not a dialog: a plan is long, and a page keeps the editor
// and the scroll view in their own hit-testable surface.
await Navigator.of(context).push(MaterialPageRoute<void>(
builder: (context) => _PlanPage(
title: content.title.isEmpty ? plan.file : content.title,
raw: content.raw,
onSave: (raw) async {
_apply(await client.savePlan(_projectId, plan.id, raw,
directory: widget.directory));
},
),
));
}
String _stamp(int millis) {
if (millis <= 0) return '';
final time = DateTime.fromMillisecondsSinceEpoch(millis);
String two(int value) => value.toString().padLeft(2, '0');
return '${time.year}-${two(time.month)}-${two(time.day)} '
'${two(time.hour)}:${two(time.minute)}';
}
}
/// One plan, rendered; 编辑 swaps in the raw Markdown, 保存 writes it back.
class _PlanPage extends StatefulWidget {
final String title;
final String raw;
final Future<void> Function(String raw) onSave;
const _PlanPage({
required this.title,
required this.raw,
required this.onSave,
});
@override
State<_PlanPage> createState() => _PlanPageState();
}
class _PlanPageState extends State<_PlanPage> {
late final TextEditingController _controller =
TextEditingController(text: widget.raw);
bool _editing = false;
bool _saving = false;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _save() async {
setState(() => _saving = true);
try {
await widget.onSave(_controller.text);
if (mounted) setState(() => _editing = false);
} catch (error) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$error')));
}
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title, maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [
if (_editing)
TextButton(
onPressed: _saving ? null : () => setState(() => _editing = false),
child: const Text('取消'),
),
TextButton(
onPressed: _saving
? null
: (_editing ? _save : () => setState(() => _editing = true)),
child: Text(_saving ? '保存中…' : (_editing ? '保存' : '编辑')),
),
],
),
body: _editing
? Padding(
padding: const EdgeInsets.all(12),
child: TextField(
controller: _controller,
expands: true,
maxLines: null,
minLines: null,
textAlignVertical: TextAlignVertical.top,
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding: EdgeInsets.all(10),
),
),
)
: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: MarkdownView(_controller.text, fontSize: 14.5),
),
);
}
}
/// A one-field prompt that owns its controller (a controller created outside
/// a dialog is disposed while the dialog is still animating out, which trips a
/// framework assertion in debug builds).
class _TextPromptDialog extends StatefulWidget {
final String title;
final String hint;
final String initial;
final int maxLength;
final int maxLines;
final int minLines;
final String action;
const _TextPromptDialog({
required this.title,
required this.hint,
required this.maxLength,
required this.maxLines,
required this.minLines,
required this.action,
this.initial = '',
});
@override
State<_TextPromptDialog> createState() => _TextPromptDialogState();
}
class _TextPromptDialogState extends State<_TextPromptDialog> {
late final TextEditingController _controller =
TextEditingController(text: widget.initial);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(widget.title),
content: SizedBox(
width: double.maxFinite,
child: TextField(
controller: _controller,
autofocus: true,
maxLength: widget.maxLength,
maxLines: widget.maxLines,
minLines: widget.minLines,
decoration: InputDecoration(
hintText: widget.hint,
border: const OutlineInputBorder(),
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(context, _controller.text.trim()),
child: Text(widget.action)),
],
);
}
}
/// Title plus Markdown body, as one dialog.
class _NewPlanDialog extends StatefulWidget {
const _NewPlanDialog();
@override
State<_NewPlanDialog> createState() => _NewPlanDialogState();
}
class _NewPlanDialogState extends State<_NewPlanDialog> {
final TextEditingController _title = TextEditingController();
final TextEditingController _body = TextEditingController();
@override
void dispose() {
_title.dispose();
_body.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('新建计划'),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _title,
autofocus: true,
maxLength: 160,
decoration: const InputDecoration(
labelText: '标题',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: _body,
maxLines: 10,
minLines: 6,
decoration: const InputDecoration(
alignLabelWithHint: true,
labelText: '计划正文(Markdown)',
border: OutlineInputBorder(),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(
context, (_title.text.trim(), _body.text)),
child: const Text('创建')),
],
);
}
}
+279
View File
@@ -0,0 +1,279 @@
// The terminal tab: xterm renders the PTY, a status bar offers restart and
// close, and the key bar below sends what a phone keyboard cannot (Esc, Tab,
// Ctrl, arrows, punctuation), the way Termux does.
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
import '../api/terminal.dart';
import '../state.dart';
import '../terminal_state.dart';
/// A light palette, so the terminal does not turn into a black hole in the
/// light theme. (xterm ships only dark ones.)
const _lightTheme = TerminalTheme(
cursor: Color(0xFF3A3A3A),
selection: Color(0x553A6EA5),
foreground: Color(0xFF1F1F1F),
background: Color(0xFFFFFFFF),
black: Color(0xFF000000),
red: Color(0xFFCD3131),
green: Color(0xFF0D7A44),
yellow: Color(0xFF7A6200),
blue: Color(0xFF1B5FA6),
magenta: Color(0xFFA626A4),
cyan: Color(0xFF0E7490),
white: Color(0xFFBDBDBD),
brightBlack: Color(0xFF666666),
brightRed: Color(0xFFD73A49),
brightGreen: Color(0xFF1A8A4E),
brightYellow: Color(0xFF8A6D00),
brightBlue: Color(0xFF2E6FBF),
brightMagenta: Color(0xFFB23BB0),
brightCyan: Color(0xFF12859B),
brightWhite: Color(0xFFEEEEEE),
searchHitBackground: Color(0xFFFFF176),
searchHitBackgroundCurrent: Color(0xFFAED581),
searchHitForeground: Color(0xFF000000),
);
class TerminalPanel extends StatefulWidget {
final AppState app;
final String directory;
const TerminalPanel({super.key, required this.app, this.directory = ''});
@override
State<TerminalPanel> createState() => _TerminalPanelState();
}
class _TerminalPanelState extends State<TerminalPanel> {
TerminalSessionState? _terminal;
final FocusNode _focus = FocusNode();
@override
void initState() {
super.initState();
_terminal = widget.app.terminalFor(widget.directory);
_terminal!.ensureOpen();
}
@override
void dispose() {
_focus.dispose();
super.dispose();
}
TerminalSessionState get _t => _terminal!;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return ListenableBuilder(
listenable: _t,
builder: (context, _) {
return Column(
children: [
_statusBar(theme),
Expanded(
child: ColoredBox(
color: theme.brightness == Brightness.dark
? const Color(0xFF1E1E1E)
: Colors.white,
child: TerminalView(
_t.model,
focusNode: _focus,
theme: theme.brightness == Brightness.dark
? TerminalThemes.defaultTheme
: _lightTheme,
textStyle: const TerminalStyle(
fontSize: 13,
height: 1.25,
fontFamily: 'monospace',
),
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
keyboardType: TextInputType.text,
deleteDetection: true,
backgroundOpacity: 1,
),
),
),
_keyBar(theme),
],
);
},
);
}
Widget _statusBar(ThemeData theme) {
final scheme = theme.colorScheme;
final (label, color) = switch (_t.link) {
TerminalLinkState.idle => ('未启动', theme.hintColor),
TerminalLinkState.creating => ('正在创建…', theme.hintColor),
TerminalLinkState.connecting => ('正在连接…', theme.hintColor),
TerminalLinkState.reconnecting => ('连接中断,正在重连…', scheme.error),
TerminalLinkState.open => ('运行中', scheme.primary),
TerminalLinkState.exited => (_t.detail ?? '已退出', theme.hintColor),
TerminalLinkState.error => (_t.detail ?? '连接失败', scheme.error),
};
return Container(
padding: const EdgeInsets.fromLTRB(12, 2, 4, 2),
child: Row(
children: [
Icon(Icons.circle, size: 8, color: color),
const SizedBox(width: 6),
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: color),
),
),
IconButton(
tooltip: '键盘',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.keyboard_outlined, size: 18),
onPressed: () => _focus.requestFocus(),
),
IconButton(
tooltip: '重新启动',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.restart_alt, size: 18),
onPressed: _t.link == TerminalLinkState.exited ||
_t.link == TerminalLinkState.error
? _restart
: _t.isRunning
? _restart
: null,
),
PopupMenuButton<String>(
tooltip: '更多',
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) {
switch (value) {
case 'clear':
_t.model.write('\x1b[2J\x1b[H');
break;
case 'close':
_closeSession();
break;
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'clear', child: Text('清屏')),
PopupMenuItem(value: 'close', child: Text('关闭终端')),
],
),
],
),
);
}
Future<void> _restart() async {
if (_t.link == TerminalLinkState.exited ||
_t.link == TerminalLinkState.error) {
// A dead session cannot restart in place; a fresh one replaces it.
await _t.closeSession();
await _t.ensureOpen();
return;
}
await _t.restart();
}
Future<void> _closeSession() async {
await _t.closeSession();
if (mounted) await _t.ensureOpen();
}
// ------------------------------------------------------------- key bar
static const _symbols = [
'/', '-', '|', '~', '*', r'$', '#', '_', '=', '+', ':', ';',
'"', "'", '(', ')', '[', ']', '{', '}', '<', '>', '?', '!',
'&', r'\', '^', '%', '@',
];
Widget _keyBar(ThemeData theme) {
return Container(
height: 46,
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
border: Border(top: BorderSide(color: theme.dividerColor, width: 0.5)),
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Row(
children: [
_key('CTRL', active: _t.ctrl, onTap: _t.toggleCtrl),
_key('ALT', active: _t.alt, onTap: _t.toggleAlt),
_key('SHIFT', active: _t.shift, onTap: _t.toggleShift),
_divider(theme),
_key('ESC', onTap: () => _sendKey(TerminalKey.escape)),
_key('TAB', onTap: () => _sendKey(TerminalKey.tab)),
_divider(theme),
_key('←', onTap: () => _sendKey(TerminalKey.arrowLeft)),
_key('↑', onTap: () => _sendKey(TerminalKey.arrowUp)),
_key('↓', onTap: () => _sendKey(TerminalKey.arrowDown)),
_key('→', onTap: () => _sendKey(TerminalKey.arrowRight)),
_divider(theme),
_key('HOME', onTap: () => _sendKey(TerminalKey.home)),
_key('END', onTap: () => _sendKey(TerminalKey.end)),
_key('PGUP', onTap: () => _sendKey(TerminalKey.pageUp)),
_key('PGDN', onTap: () => _sendKey(TerminalKey.pageDown)),
_key('DEL', onTap: () => _sendKey(TerminalKey.delete)),
_divider(theme),
for (final symbol in _symbols)
_key(symbol, onTap: () => _sendText(symbol)),
],
),
),
);
}
Widget _divider(ThemeData theme) => Container(
width: 1,
height: 20,
margin: const EdgeInsets.symmetric(horizontal: 4),
color: theme.dividerColor,
);
Widget _key(String label,
{bool active = false, required VoidCallback onTap}) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 2, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 10),
alignment: Alignment.center,
constraints: const BoxConstraints(minWidth: 34),
decoration: BoxDecoration(
color: active
? scheme.primary.withValues(alpha: 0.22)
: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(7),
border: Border.all(
color: active ? scheme.primary : Colors.transparent, width: 1),
),
child: Text(
label,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 12,
fontWeight: active ? FontWeight.w700 : FontWeight.w500,
color: active ? scheme.primary : scheme.onSurface,
),
),
),
);
}
// The terminal state applies the pending modifiers (and clears them) as the
// text leaves for the PTY, so both the bar and the phone keyboard take them.
void _sendKey(TerminalKey key) =>
_t.model.keyInput(key, ctrl: _t.ctrl, alt: _t.alt, shift: _t.shift);
void _sendText(String text) => _t.model.textInput(text);
}