suggestion.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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({Key? key}) : super(key: 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!.cursorRect);
  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! RawKeyDownEvent) {
  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. class SuggestionViewController extends ChangeNotifier {
  259. final scrollController = ScrollController();
  260. List<FigToken> get suggestions => _suggestions;
  261. List<FigToken> _suggestions = [];
  262. var _selected = 0;
  263. set selected(int index) {
  264. _selected = max(0, min(index, suggestions.length - 1));
  265. notifyListeners();
  266. }
  267. double get itemExtent => _itemExtent;
  268. double _itemExtent = 20;
  269. set itemExtent(double value) {
  270. if (value == _itemExtent) return;
  271. _itemExtent = value;
  272. notifyListeners();
  273. }
  274. FigToken? get currentSuggestion {
  275. if (_suggestions.isEmpty) return null;
  276. return _suggestions[_selected];
  277. }
  278. void update(List<FigToken> suggestions) {
  279. _suggestions = suggestions;
  280. _selected = 0;
  281. notifyListeners();
  282. }
  283. void selectNext() {
  284. _selected = (_selected + 1) % _suggestions.length;
  285. ensureVisible(_selected);
  286. notifyListeners();
  287. }
  288. void selectPrevious() {
  289. _selected = (_selected - 1) % _suggestions.length;
  290. ensureVisible(_selected);
  291. notifyListeners();
  292. }
  293. void ensureVisible(int index) {
  294. if (!scrollController.hasClients) {
  295. return;
  296. }
  297. final position = scrollController.position;
  298. final targetOffset = itemExtent * index;
  299. final viewportBottomOffset = position.pixels + position.viewportDimension;
  300. if (targetOffset < position.pixels) {
  301. position.jumpTo(targetOffset);
  302. } else if (targetOffset + itemExtent > viewportBottomOffset) {
  303. position.jumpTo(
  304. max(0, targetOffset + itemExtent - position.viewportDimension),
  305. );
  306. }
  307. }
  308. }
  309. class SuggestionView extends StatelessWidget {
  310. const SuggestionView(
  311. this.controller, {
  312. super.key,
  313. this.onSuggestionSelected,
  314. });
  315. final SuggestionViewController controller;
  316. final void Function(FigToken)? onSuggestionSelected;
  317. @override
  318. Widget build(BuildContext context) {
  319. return ListenableBuilder(
  320. listenable: controller,
  321. builder: (context, child) {
  322. return _build(context);
  323. },
  324. );
  325. }
  326. Widget _build(BuildContext context) {
  327. return ClipRRect(
  328. borderRadius: BorderRadius.circular(4),
  329. child: Container(
  330. constraints: BoxConstraints(
  331. maxWidth: 300,
  332. maxHeight: 200,
  333. ),
  334. decoration: BoxDecoration(
  335. color: Colors.grey[800],
  336. ),
  337. child: Column(
  338. crossAxisAlignment: CrossAxisAlignment.start,
  339. children: [
  340. Expanded(
  341. child: ListView.builder(
  342. controller: controller.scrollController,
  343. itemExtent: controller.itemExtent,
  344. itemCount: controller._suggestions.length,
  345. itemBuilder: (context, index) {
  346. final suggestion = controller._suggestions[index];
  347. return GestureDetector(
  348. onTapDown: (_) => controller.selected = index,
  349. onDoubleTapDown: (_) =>
  350. onSuggestionSelected?.call(suggestion),
  351. child: ClipRect(
  352. child: SuggestionTile(
  353. selected: index == controller._selected,
  354. suggestion: suggestion,
  355. ),
  356. ),
  357. );
  358. },
  359. ),
  360. ),
  361. if (controller.currentSuggestion != null) ...[
  362. Divider(
  363. height: 1,
  364. thickness: 1,
  365. color: Colors.grey[700],
  366. ),
  367. SuggestionDescriptionView(controller.currentSuggestion!),
  368. ],
  369. ],
  370. ),
  371. ),
  372. );
  373. }
  374. }
  375. class SuggestionDescriptionView extends StatefulWidget {
  376. const SuggestionDescriptionView(
  377. this.suggestion, {
  378. super.key,
  379. });
  380. final FigToken suggestion;
  381. @override
  382. State<SuggestionDescriptionView> createState() =>
  383. _SuggestionDescriptionViewState();
  384. }
  385. class _SuggestionDescriptionViewState extends State<SuggestionDescriptionView> {
  386. var isHovering = false;
  387. @override
  388. Widget build(BuildContext context) {
  389. return MouseRegion(
  390. onEnter: (event) {
  391. setState(() {
  392. isHovering = true;
  393. });
  394. },
  395. onExit: (event) {
  396. setState(() {
  397. isHovering = false;
  398. });
  399. },
  400. child: Container(
  401. padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
  402. child: Text(
  403. widget.suggestion.description ?? '',
  404. maxLines: isHovering ? null : 1,
  405. overflow: isHovering ? null : TextOverflow.ellipsis,
  406. style: TextStyle(color: Colors.grey[400], fontSize: 12),
  407. ),
  408. ),
  409. );
  410. }
  411. }
  412. /// An item in the suggestion list.
  413. class SuggestionTile extends StatelessWidget {
  414. const SuggestionTile({
  415. super.key,
  416. required this.selected,
  417. required this.suggestion,
  418. });
  419. final bool selected;
  420. final FigToken suggestion;
  421. static final primaryStyle = TerminalStyle().toTextStyle().copyWith(
  422. leadingDistribution: TextLeadingDistribution.even,
  423. );
  424. static final argumentStyle = TerminalStyle().toTextStyle().copyWith(
  425. leadingDistribution: TextLeadingDistribution.even,
  426. color: Colors.grey[500],
  427. fontSize: 12,
  428. );
  429. @override
  430. Widget build(BuildContext context) {
  431. final (icon, iconColor) = _getIcon(suggestion);
  432. final canSelect = suggestion is! FigArgument;
  433. return Container(
  434. color: selected ? Colors.blue[800] : Colors.transparent,
  435. child: Row(
  436. crossAxisAlignment: CrossAxisAlignment.center,
  437. children: [
  438. SizedBox(width: 4),
  439. Icon(icon, size: 14, color: iconColor),
  440. SizedBox(width: 4),
  441. Expanded(
  442. child: RichText(
  443. overflow: TextOverflow.ellipsis,
  444. maxLines: 1,
  445. text: TextSpan(
  446. text: _getContent(suggestion) ?? '',
  447. children: [...buildArgs()],
  448. style: canSelect
  449. ? primaryStyle
  450. : primaryStyle.copyWith(fontStyle: FontStyle.italic),
  451. ),
  452. ),
  453. ),
  454. if (selected && canSelect) ...[
  455. Icon(Icons.keyboard_tab_rounded, size: 16, color: Colors.grey[400]),
  456. SizedBox(width: 4),
  457. ],
  458. ],
  459. ),
  460. );
  461. }
  462. Iterable<InlineSpan> buildArgs() sync* {
  463. final args = switch (suggestion) {
  464. FigCommand(:var args) => args,
  465. FigOption(:var args) => args,
  466. _ => <FigArgument>[],
  467. };
  468. const indent = ' ';
  469. for (final arg in args) {
  470. yield TextSpan(
  471. text: arg.isOptional ? '$indent[${arg.name}]' : '$indent<${arg.name}>',
  472. style: argumentStyle,
  473. );
  474. }
  475. }
  476. static (IconData, Color) _getIcon(FigToken suggestion) {
  477. return switch (suggestion) {
  478. FigCommand() => (Icons.subdirectory_arrow_right, Colors.blue),
  479. FigOption() => (Icons.settings, Colors.green),
  480. FigArgument() => (Icons.text_fields, Colors.yellow),
  481. };
  482. }
  483. static String? _getContent(FigToken suggestion) {
  484. return switch (suggestion) {
  485. FigCommand(:final names) => names.join(', '),
  486. FigOption(names: final name) => name.join(', '),
  487. FigArgument(:final name) => name,
  488. };
  489. }
  490. }
  491. String get shell {
  492. if (Platform.isMacOS || Platform.isLinux) {
  493. return Platform.environment['SHELL'] ?? 'bash';
  494. }
  495. if (Platform.isWindows) {
  496. return 'cmd.exe';
  497. }
  498. return 'sh';
  499. }
  500. extension on String {
  501. String trimRightNewline() {
  502. return endsWith('\n') ? substring(0, length - 1) : this;
  503. }
  504. }