suggestion.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'dart:math';
  4. import 'package:example/src/platform_menu.dart';
  5. import 'package:example/src/suggestion_engine.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:flutter_pty/flutter_pty.dart';
  9. import 'package:xterm/xterm.dart';
  10. import 'package:xterm/suggestion.dart';
  11. final engine = SuggestionEngine();
  12. Future<Map<String, dynamic>> loadSuggestion() async {
  13. final data = await rootBundle.load('assets/specs_v1.json.gz');
  14. return await Stream.value(data.buffer.asUint8List())
  15. .cast<List<int>>()
  16. .transform(gzip.decoder)
  17. .transform(utf8.decoder)
  18. .transform(json.decoder)
  19. .first as Map<String, dynamic>;
  20. }
  21. void main() async {
  22. WidgetsFlutterBinding.ensureInitialized();
  23. engine.load(await loadSuggestion());
  24. runApp(MyApp());
  25. }
  26. class MyApp extends StatelessWidget {
  27. @override
  28. Widget build(BuildContext context) {
  29. return MaterialApp(
  30. title: 'xterm.dart demo',
  31. debugShowCheckedModeBanner: false,
  32. home: AppPlatformMenu(child: Home()),
  33. );
  34. }
  35. }
  36. class Home extends StatefulWidget {
  37. Home({super.key});
  38. @override
  39. // ignore: library_private_types_in_public_api
  40. _HomeState createState() => _HomeState();
  41. }
  42. class _HomeState extends State<Home> {
  43. late final terminal = Terminal(
  44. maxLines: 10000,
  45. onPrivateOSC: _handlePrivateOSC,
  46. );
  47. final terminalController = TerminalController();
  48. final terminalKey = GlobalKey<TerminalViewState>();
  49. final suggestionOverlay = SuggestionPortalController();
  50. late final Pty pty;
  51. @override
  52. void initState() {
  53. super.initState();
  54. terminal.addListener(_handleTerminalChanged);
  55. WidgetsBinding.instance.endOfFrame.then(
  56. (_) {
  57. if (mounted) _startPty();
  58. },
  59. );
  60. }
  61. @override
  62. void dispose() {
  63. super.dispose();
  64. terminal.removeListener(_handleTerminalChanged);
  65. }
  66. void _startPty() {
  67. pty = Pty.start(
  68. shell,
  69. columns: terminal.viewWidth,
  70. rows: terminal.viewHeight,
  71. );
  72. pty.output
  73. .cast<List<int>>()
  74. .transform(Utf8Decoder())
  75. .listen(terminal.write);
  76. pty.exitCode.then((code) {
  77. terminal.write('the process exited with exit code $code');
  78. });
  79. terminal.onOutput = (data) {
  80. pty.write(const Utf8Encoder().convert(data));
  81. };
  82. terminal.onResize = (w, h, pw, ph) {
  83. pty.resize(h, w);
  84. };
  85. }
  86. /// Where the current shell prompt starts
  87. CellAnchor? _promptStart;
  88. /// Where the current user input starts
  89. CellAnchor? _commandStart;
  90. /// Where the current user input ends and the command starts to execute
  91. CellAnchor? _commandEnd;
  92. /// Where the command finishes
  93. CellAnchor? _commandFinished;
  94. void _handlePrivateOSC(String code, List<String> args) {
  95. switch (code) {
  96. case '133':
  97. _handleFinalTermOSC(args);
  98. }
  99. }
  100. void _handleFinalTermOSC(List<String> args) {
  101. switch (args) {
  102. case ['A']:
  103. _promptStart?.dispose();
  104. _promptStart = terminal.buffer.createAnchorFromCursor();
  105. _commandStart?.dispose();
  106. _commandStart = null;
  107. _commandEnd?.dispose();
  108. _commandEnd = null;
  109. _commandFinished?.dispose();
  110. _commandFinished = null;
  111. case ['B']:
  112. _commandStart?.dispose();
  113. _commandStart = terminal.buffer.createAnchorFromCursor();
  114. break;
  115. case ['C', ..._]:
  116. _commandEnd?.dispose();
  117. _commandEnd = terminal.buffer.createAnchorFromCursor();
  118. _handleCommandEnd();
  119. break;
  120. case ['D', String exitCode]:
  121. _commandFinished?.dispose();
  122. _commandFinished = terminal.buffer.createAnchorFromCursor();
  123. _handleCommandFinished(int.tryParse(exitCode));
  124. break;
  125. }
  126. }
  127. void _handleCommandEnd() {
  128. if (_commandStart == null || _commandEnd == null) return;
  129. final command = terminal.buffer
  130. .getText(BufferRangeLine(_commandStart!.offset, _commandEnd!.offset))
  131. .trim();
  132. print('command: $command');
  133. }
  134. void _handleCommandFinished(int? exitCode) {
  135. if (_commandEnd == null || _commandFinished == null) return;
  136. final result = terminal.buffer
  137. .getText(BufferRangeLine(_commandEnd!.offset, _commandFinished!.offset))
  138. .trim();
  139. print('result: $result');
  140. print('exitCode: $exitCode');
  141. }
  142. final suggestionView = SuggestionViewController();
  143. String? get commandBuffer {
  144. final commandStart = _commandStart;
  145. if (commandStart == null || _commandEnd != null) {
  146. return null;
  147. }
  148. var commandRange = BufferRangeLine(
  149. commandStart.offset,
  150. CellOffset(
  151. terminal.buffer.cursorX,
  152. terminal.buffer.absoluteCursorY,
  153. ),
  154. );
  155. return terminal.buffer.getText(commandRange).trimRightNewline();
  156. }
  157. void _handleTerminalChanged() {
  158. final command = commandBuffer;
  159. if (command == null || command.isEmpty) {
  160. suggestionOverlay.hide();
  161. return;
  162. }
  163. final suggestions = engine.getSuggestions(command).toList();
  164. suggestionView.update(suggestions);
  165. print('suggestions: $suggestions');
  166. if (suggestions.isNotEmpty) {
  167. suggestionOverlay.update(terminalKey.currentState!.globalCursorRect);
  168. } else {
  169. suggestionOverlay.hide();
  170. }
  171. }
  172. void _handleSuggestionSelected(FigToken suggestion) {
  173. final command = commandBuffer;
  174. if (command == null) {
  175. return;
  176. }
  177. final incompleteCommand =
  178. command.endsWith(' ') ? null : command.split(' ').last;
  179. switch (suggestion) {
  180. case FigCommand(:var names):
  181. if (incompleteCommand == null) {
  182. _emitSuggestion(names.first);
  183. } else {
  184. for (final name in names) {
  185. if (name.startsWith(incompleteCommand)) {
  186. _emitSuggestion(name.substring(incompleteCommand.length));
  187. break;
  188. }
  189. }
  190. }
  191. case FigOption(:var names):
  192. if (incompleteCommand == null) {
  193. _emitSuggestion(names.first);
  194. } else {
  195. for (final name in names) {
  196. if (name.startsWith(incompleteCommand)) {
  197. _emitSuggestion(name.substring(incompleteCommand.length));
  198. break;
  199. }
  200. }
  201. }
  202. break;
  203. default:
  204. }
  205. }
  206. void _emitSuggestion(String text) {
  207. pty.write(const Utf8Encoder().convert(text));
  208. }
  209. @override
  210. Widget build(BuildContext context) {
  211. return Scaffold(
  212. backgroundColor: Colors.transparent,
  213. body: SuggestionPortal(
  214. controller: suggestionOverlay,
  215. overlayBuilder: (context) {
  216. return SuggestionView(
  217. suggestionView,
  218. onSuggestionSelected: _handleSuggestionSelected,
  219. );
  220. },
  221. child: TerminalView(
  222. terminal,
  223. key: terminalKey,
  224. controller: terminalController,
  225. autofocus: true,
  226. backgroundOpacity: 0.7,
  227. onKey: (node, event) {
  228. if (event is! KeyDownEvent) {
  229. return KeyEventResult.ignored;
  230. }
  231. if (suggestionOverlay.isShowing) {
  232. switch (event.logicalKey) {
  233. case LogicalKeyboardKey.escape:
  234. suggestionOverlay.hide();
  235. return KeyEventResult.handled;
  236. case LogicalKeyboardKey.tab:
  237. final suggestion = suggestionView.currentSuggestion;
  238. if (suggestion != null) {
  239. _handleSuggestionSelected(suggestion);
  240. return KeyEventResult.handled;
  241. }
  242. case LogicalKeyboardKey.arrowUp:
  243. suggestionView.selectPrevious();
  244. return KeyEventResult.handled;
  245. case LogicalKeyboardKey.arrowDown:
  246. suggestionView.selectNext();
  247. return KeyEventResult.handled;
  248. default:
  249. }
  250. }
  251. return KeyEventResult.ignored;
  252. },
  253. ),
  254. ),
  255. );
  256. }
  257. }
  258. /// The state of the suggestion overlay.
  259. class SuggestionViewController extends ChangeNotifier {
  260. final scrollController = ScrollController();
  261. List<FigToken> get suggestions => _suggestions;
  262. List<FigToken> _suggestions = [];
  263. var _selected = 0;
  264. set selected(int index) {
  265. _selected = max(0, min(index, suggestions.length - 1));
  266. notifyListeners();
  267. }
  268. double get itemExtent => _itemExtent;
  269. double _itemExtent = 20;
  270. set itemExtent(double value) {
  271. if (value == _itemExtent) return;
  272. _itemExtent = value;
  273. notifyListeners();
  274. }
  275. FigToken? get currentSuggestion {
  276. if (_suggestions.isEmpty) return null;
  277. return _suggestions[_selected];
  278. }
  279. void update(List<FigToken> suggestions) {
  280. _suggestions = suggestions;
  281. _selected = 0;
  282. notifyListeners();
  283. }
  284. void selectNext() {
  285. _selected = (_selected + 1) % _suggestions.length;
  286. ensureVisible(_selected);
  287. notifyListeners();
  288. }
  289. void selectPrevious() {
  290. _selected = (_selected - 1) % _suggestions.length;
  291. ensureVisible(_selected);
  292. notifyListeners();
  293. }
  294. void ensureVisible(int index) {
  295. if (!scrollController.hasClients) {
  296. return;
  297. }
  298. final position = scrollController.position;
  299. final targetOffset = itemExtent * index;
  300. final viewportBottomOffset = position.pixels + position.viewportDimension;
  301. if (targetOffset < position.pixels) {
  302. position.jumpTo(targetOffset);
  303. } else if (targetOffset + itemExtent > viewportBottomOffset) {
  304. position.jumpTo(
  305. max(0, targetOffset + itemExtent - position.viewportDimension),
  306. );
  307. }
  308. }
  309. }
  310. /// The suggestion popup shown above the terminal when user is typing a command.
  311. class SuggestionView extends StatelessWidget {
  312. const SuggestionView(
  313. this.controller, {
  314. super.key,
  315. this.onSuggestionSelected,
  316. });
  317. final SuggestionViewController controller;
  318. final void Function(FigToken)? onSuggestionSelected;
  319. @override
  320. Widget build(BuildContext context) {
  321. return ListenableBuilder(
  322. listenable: controller,
  323. builder: (context, child) {
  324. return _build(context);
  325. },
  326. );
  327. }
  328. Widget _build(BuildContext context) {
  329. return ClipRRect(
  330. borderRadius: BorderRadius.circular(4),
  331. child: Container(
  332. constraints: BoxConstraints(
  333. maxWidth: 300,
  334. maxHeight: 200,
  335. ),
  336. decoration: BoxDecoration(
  337. color: Colors.grey[800],
  338. ),
  339. child: Column(
  340. crossAxisAlignment: CrossAxisAlignment.start,
  341. children: [
  342. Expanded(
  343. child: ListView.builder(
  344. controller: controller.scrollController,
  345. itemExtent: controller.itemExtent,
  346. itemCount: controller._suggestions.length,
  347. itemBuilder: (context, index) {
  348. final suggestion = controller._suggestions[index];
  349. return GestureDetector(
  350. onTapDown: (_) => controller.selected = index,
  351. onDoubleTapDown: (_) =>
  352. onSuggestionSelected?.call(suggestion),
  353. child: ClipRect(
  354. child: SuggestionTile(
  355. selected: index == controller._selected,
  356. suggestion: suggestion,
  357. ),
  358. ),
  359. );
  360. },
  361. ),
  362. ),
  363. if (controller.currentSuggestion != null) ...[
  364. Divider(
  365. height: 1,
  366. thickness: 1,
  367. color: Colors.grey[700],
  368. ),
  369. SuggestionDescriptionView(controller.currentSuggestion!),
  370. ],
  371. ],
  372. ),
  373. ),
  374. );
  375. }
  376. }
  377. /// The area at the bottom of [SuggestionView] that shows the description of
  378. /// the currently selected suggestion.
  379. class SuggestionDescriptionView extends StatefulWidget {
  380. const SuggestionDescriptionView(
  381. this.suggestion, {
  382. super.key,
  383. });
  384. final FigToken suggestion;
  385. @override
  386. State<SuggestionDescriptionView> createState() =>
  387. _SuggestionDescriptionViewState();
  388. }
  389. class _SuggestionDescriptionViewState extends State<SuggestionDescriptionView> {
  390. var isHovering = false;
  391. @override
  392. Widget build(BuildContext context) {
  393. return MouseRegion(
  394. onEnter: (event) {
  395. setState(() {
  396. isHovering = true;
  397. });
  398. },
  399. onExit: (event) {
  400. setState(() {
  401. isHovering = false;
  402. });
  403. },
  404. child: Container(
  405. padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
  406. child: Text(
  407. widget.suggestion.description ?? '',
  408. maxLines: isHovering ? null : 1,
  409. overflow: isHovering ? null : TextOverflow.ellipsis,
  410. style: TextStyle(color: Colors.grey[400], fontSize: 12),
  411. ),
  412. ),
  413. );
  414. }
  415. }
  416. /// An item in [SuggestionView].
  417. class SuggestionTile extends StatelessWidget {
  418. const SuggestionTile({
  419. super.key,
  420. required this.selected,
  421. required this.suggestion,
  422. });
  423. final bool selected;
  424. final FigToken suggestion;
  425. static final primaryStyle = TerminalStyle().toTextStyle().copyWith(
  426. leadingDistribution: TextLeadingDistribution.even,
  427. );
  428. static final argumentStyle = TerminalStyle().toTextStyle().copyWith(
  429. leadingDistribution: TextLeadingDistribution.even,
  430. color: Colors.grey[500],
  431. fontSize: 12,
  432. );
  433. @override
  434. Widget build(BuildContext context) {
  435. final (icon, iconColor) = _getIcon(suggestion);
  436. final canSelect = suggestion is! FigArgument;
  437. return Container(
  438. color: selected ? Colors.blue[800] : Colors.transparent,
  439. child: Row(
  440. crossAxisAlignment: CrossAxisAlignment.center,
  441. children: [
  442. SizedBox(width: 4),
  443. Icon(icon, size: 14, color: iconColor),
  444. SizedBox(width: 4),
  445. Expanded(
  446. child: RichText(
  447. overflow: TextOverflow.ellipsis,
  448. maxLines: 1,
  449. text: TextSpan(
  450. text: _getContent(suggestion) ?? '',
  451. children: [...buildArgs()],
  452. style: canSelect
  453. ? primaryStyle
  454. : primaryStyle.copyWith(fontStyle: FontStyle.italic),
  455. ),
  456. ),
  457. ),
  458. if (selected && canSelect) ...[
  459. Icon(Icons.keyboard_tab_rounded, size: 16, color: Colors.grey[400]),
  460. SizedBox(width: 4),
  461. ],
  462. ],
  463. ),
  464. );
  465. }
  466. Iterable<InlineSpan> buildArgs() sync* {
  467. final args = switch (suggestion) {
  468. FigCommand(:var args) => args,
  469. FigOption(:var args) => args,
  470. _ => <FigArgument>[],
  471. };
  472. const indent = ' ';
  473. for (final arg in args) {
  474. yield TextSpan(
  475. text: arg.isOptional ? '$indent[${arg.name}]' : '$indent<${arg.name}>',
  476. style: argumentStyle,
  477. );
  478. }
  479. }
  480. static (IconData, Color) _getIcon(FigToken suggestion) {
  481. return switch (suggestion) {
  482. FigCommand() => (Icons.subdirectory_arrow_right, Colors.blue),
  483. FigOption() => (Icons.settings, Colors.green),
  484. FigArgument() => (Icons.text_fields, Colors.yellow),
  485. };
  486. }
  487. static String? _getContent(FigToken suggestion) {
  488. return switch (suggestion) {
  489. FigCommand(:final names) => names.join(', '),
  490. FigOption(names: final name) => name.join(', '),
  491. FigArgument(:final name) => name,
  492. };
  493. }
  494. }
  495. String get shell {
  496. if (Platform.isMacOS || Platform.isLinux) {
  497. return Platform.environment['SHELL'] ?? 'bash';
  498. }
  499. if (Platform.isWindows) {
  500. return 'cmd.exe';
  501. }
  502. return 'sh';
  503. }
  504. extension on String {
  505. String trimRightNewline() {
  506. return endsWith('\n') ? substring(0, length - 1) : this;
  507. }
  508. }