terminal_view.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import 'dart:math' as math;
  2. import 'dart:ui';
  3. import 'package:flutter/gestures.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter/rendering.dart';
  6. import 'package:flutter/scheduler.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:xterm/buffer/cell_flags.dart';
  9. import 'package:xterm/buffer/line/line.dart';
  10. import 'package:xterm/frontend/cache.dart';
  11. import 'package:xterm/frontend/char_size.dart';
  12. import 'package:xterm/frontend/helpers.dart';
  13. import 'package:xterm/frontend/input_behavior.dart';
  14. import 'package:xterm/frontend/input_behaviors.dart';
  15. import 'package:xterm/frontend/input_listener.dart';
  16. import 'package:xterm/frontend/oscillator.dart';
  17. import 'package:xterm/mouse/position.dart';
  18. import 'package:xterm/terminal/terminal_ui_interaction.dart';
  19. import 'package:xterm/theme/terminal_style.dart';
  20. import 'package:xterm/util/bit_flags.dart';
  21. import 'package:xterm/util/hash_values.dart';
  22. class TerminalView extends StatefulWidget {
  23. TerminalView({
  24. Key? key,
  25. required this.terminal,
  26. this.style = const TerminalStyle(),
  27. this.opacity = 1.0,
  28. FocusNode? focusNode,
  29. this.autofocus = false,
  30. ScrollController? scrollController,
  31. InputBehavior? inputBehavior,
  32. }) : focusNode = focusNode ?? FocusNode(),
  33. scrollController = scrollController ?? ScrollController(),
  34. inputBehavior = inputBehavior ?? InputBehaviors.platform,
  35. super(key: key ?? ValueKey(terminal));
  36. final TerminalUiInteraction terminal;
  37. final FocusNode focusNode;
  38. final bool autofocus;
  39. final ScrollController scrollController;
  40. final TerminalStyle style;
  41. final double opacity;
  42. final InputBehavior inputBehavior;
  43. // get the dimensions of a rendered character
  44. CellSize measureCellSize(double fontSize) {
  45. final testString = 'xxxxxxxxxx' * 1000;
  46. final text = Text(
  47. testString,
  48. maxLines: 1,
  49. style: (style.textStyleProvider != null)
  50. ? style.textStyleProvider!(
  51. fontSize: fontSize,
  52. )
  53. : TextStyle(
  54. fontFamily: 'monospace',
  55. fontFamilyFallback: style.fontFamily,
  56. fontSize: fontSize,
  57. ),
  58. );
  59. final size = textSize(text);
  60. final charWidth = (size.width / testString.length);
  61. final charHeight = size.height;
  62. final cellWidth = charWidth * style.fontWidthScaleFactor;
  63. final cellHeight = size.height * style.fontHeightScaleFactor;
  64. return CellSize(
  65. charWidth: charWidth,
  66. charHeight: charHeight,
  67. cellWidth: cellWidth,
  68. cellHeight: cellHeight,
  69. letterSpacing: cellWidth - charWidth,
  70. lineSpacing: cellHeight - charHeight,
  71. );
  72. }
  73. @override
  74. _TerminalViewState createState() => _TerminalViewState();
  75. }
  76. class _TerminalViewState extends State<TerminalView> {
  77. /// blinking cursor and blinking character
  78. final oscillator = Oscillator.ms(600);
  79. final textLayoutCache = TextLayoutCache(TextDirection.ltr, 10240);
  80. bool get focused {
  81. return widget.focusNode.hasFocus;
  82. }
  83. late CellSize _cellSize;
  84. /// Scroll position from the terminal. Not null if terminal scroll extent has
  85. /// been updated and needs to be syncronized to flutter side.
  86. double? _terminalScrollExtent;
  87. void onTerminalChange() {
  88. _terminalScrollExtent =
  89. _cellSize.cellHeight * widget.terminal.scrollOffsetFromTop;
  90. if (mounted) {
  91. setState(() {});
  92. }
  93. }
  94. // listen to oscillator to update mouse blink etc.
  95. // void onTick() {
  96. // widget.terminal.refresh();
  97. // }
  98. @override
  99. void initState() {
  100. // oscillator.start();
  101. // oscillator.addListener(onTick);
  102. // measureCellSize is expensive so we cache the result.
  103. _cellSize = widget.measureCellSize(widget.style.fontSize);
  104. widget.terminal.addListener(onTerminalChange);
  105. super.initState();
  106. }
  107. @override
  108. void didUpdateWidget(TerminalView oldWidget) {
  109. oldWidget.terminal.removeListener(onTerminalChange);
  110. widget.terminal.addListener(onTerminalChange);
  111. if (oldWidget.style != widget.style) {
  112. _cellSize = widget.measureCellSize(widget.style.fontSize);
  113. textLayoutCache.clear();
  114. updateTerminalSize();
  115. }
  116. super.didUpdateWidget(oldWidget);
  117. }
  118. @override
  119. void dispose() {
  120. // oscillator.stop();
  121. // oscillator.removeListener(onTick);
  122. widget.terminal.removeListener(onTerminalChange);
  123. super.dispose();
  124. }
  125. @override
  126. Widget build(BuildContext context) {
  127. return InputListener(
  128. listenKeyStroke: widget.inputBehavior.acceptKeyStroke,
  129. onKeyStroke: onKeyStroke,
  130. onTextInput: onInput,
  131. onAction: onAction,
  132. onFocus: onFocus,
  133. focusNode: widget.focusNode,
  134. autofocus: widget.autofocus,
  135. initEditingState: widget.inputBehavior.initEditingState,
  136. child: MouseRegion(
  137. cursor: SystemMouseCursors.text,
  138. child: LayoutBuilder(builder: (context, constraints) {
  139. onWidgetSize(constraints.maxWidth, constraints.maxHeight);
  140. // use flutter's Scrollable to manage scrolling to better integrate
  141. // with widgets such as Scrollbar.
  142. return NotificationListener<ScrollNotification>(
  143. onNotification: (notification) {
  144. onScroll(notification.metrics.pixels);
  145. return false;
  146. },
  147. child: Scrollable(
  148. controller: widget.scrollController,
  149. viewportBuilder: (context, offset) {
  150. final position = widget.scrollController.position;
  151. /// use [_EmptyScrollActivity] to suppress unexpected behaviors
  152. /// that come from [applyViewportDimension].
  153. if (position is ScrollActivityDelegate) {
  154. position.beginActivity(
  155. _EmptyScrollActivity(position as ScrollActivityDelegate),
  156. );
  157. }
  158. // set viewport height.
  159. offset.applyViewportDimension(constraints.maxHeight);
  160. if (widget.terminal.isReady) {
  161. final minScrollExtent = 0.0;
  162. final maxScrollExtent = math.max(
  163. 0.0,
  164. _cellSize.cellHeight * widget.terminal.bufferHeight -
  165. constraints.maxHeight);
  166. // set how much the terminal can scroll
  167. offset.applyContentDimensions(
  168. minScrollExtent, maxScrollExtent);
  169. // syncronize pending terminal scroll extent to ScrollController
  170. if (_terminalScrollExtent != null) {
  171. position.correctPixels(_terminalScrollExtent!);
  172. _terminalScrollExtent = null;
  173. }
  174. }
  175. return buildTerminal(context);
  176. },
  177. ),
  178. );
  179. }),
  180. ),
  181. );
  182. }
  183. Widget buildTerminal(BuildContext context) {
  184. return GestureDetector(
  185. behavior: HitTestBehavior.deferToChild,
  186. dragStartBehavior: DragStartBehavior.down,
  187. onDoubleTapDown: (detail) {
  188. final pos = detail.localPosition;
  189. final offset = getMouseOffset(pos.dx, pos.dy);
  190. widget.terminal.onMouseDoubleTap(offset);
  191. widget.terminal.refresh();
  192. },
  193. // this is needed to activate double tap
  194. onDoubleTap: () {},
  195. onTapDown: (detail) {
  196. if (widget.terminal.selection?.isEmpty ?? true) {
  197. InputListener.of(context)!.requestKeyboard();
  198. } else {
  199. widget.terminal.clearSelection();
  200. }
  201. final pos = detail.localPosition;
  202. final offset = getMouseOffset(pos.dx, pos.dy);
  203. widget.terminal.onMouseTap(offset);
  204. widget.terminal.refresh();
  205. },
  206. onPanStart: (detail) {
  207. final pos = detail.localPosition;
  208. final offset = getMouseOffset(pos.dx, pos.dy);
  209. widget.terminal.onPanStart(offset);
  210. widget.terminal.refresh();
  211. },
  212. onPanUpdate: (detail) {
  213. final pos = detail.localPosition;
  214. final offset = getMouseOffset(pos.dx, pos.dy);
  215. widget.terminal.onPanUpdate(offset);
  216. widget.terminal.refresh();
  217. },
  218. child: Container(
  219. constraints: BoxConstraints.expand(),
  220. child: CustomPaint(
  221. painter: TerminalPainter(
  222. terminal: widget.terminal,
  223. view: widget,
  224. oscillator: oscillator,
  225. focused: focused,
  226. charSize: _cellSize,
  227. textLayoutCache: textLayoutCache,
  228. ),
  229. ),
  230. color: Color(widget.terminal.backgroundColor).withOpacity(
  231. widget.opacity,
  232. ),
  233. ),
  234. );
  235. }
  236. /// Get global cell position from mouse position.
  237. Position getMouseOffset(double px, double py) {
  238. final col = (px / _cellSize.cellWidth).floor();
  239. final row = (py / _cellSize.cellHeight).floor();
  240. final x = col;
  241. final y = widget.terminal.convertViewLineToRawLine(row) -
  242. widget.terminal.scrollOffsetFromBottom;
  243. return Position(x, y);
  244. }
  245. double? _width;
  246. double? _height;
  247. void onWidgetSize(double width, double height) {
  248. if (!widget.terminal.isReady) {
  249. return;
  250. }
  251. _width = width;
  252. _height = height;
  253. updateTerminalSize();
  254. }
  255. int? _lastTerminalWidth;
  256. int? _lastTerminalHeight;
  257. void updateTerminalSize() {
  258. assert(_width != null);
  259. assert(_height != null);
  260. final termWidth = (_width! / _cellSize.cellWidth).floor();
  261. final termHeight = (_height! / _cellSize.cellHeight).floor();
  262. if (_lastTerminalWidth == termWidth && _lastTerminalHeight == termHeight) {
  263. return;
  264. }
  265. _lastTerminalWidth = termWidth;
  266. _lastTerminalHeight = termHeight;
  267. widget.terminal.resize(
  268. termWidth,
  269. termHeight,
  270. (termWidth * _cellSize.cellWidth).floor(),
  271. (termHeight * _cellSize.cellHeight).floor(),
  272. );
  273. }
  274. TextEditingValue? onInput(TextEditingValue value) {
  275. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  276. }
  277. void onKeyStroke(RawKeyEvent event) {
  278. // TODO: find a way to stop scrolling immediately after key stroke.
  279. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  280. widget.terminal.setScrollOffsetFromBottom(0);
  281. }
  282. void onFocus(bool focused) {
  283. SchedulerBinding.instance!.addPostFrameCallback((_) {
  284. widget.terminal.refresh();
  285. });
  286. }
  287. void onAction(TextInputAction action) {
  288. widget.inputBehavior.onAction(action, widget.terminal);
  289. }
  290. // synchronize flutter scroll offset to terminal
  291. void onScroll(double offset) {
  292. final topOffset = (offset / _cellSize.cellHeight).ceil();
  293. final bottomOffset = widget.terminal.invisibleHeight - topOffset;
  294. widget.terminal.setScrollOffsetFromBottom(bottomOffset);
  295. }
  296. }
  297. class TerminalPainter extends CustomPainter {
  298. TerminalPainter({
  299. required this.terminal,
  300. required this.view,
  301. required this.oscillator,
  302. required this.focused,
  303. required this.charSize,
  304. required this.textLayoutCache,
  305. });
  306. final TerminalUiInteraction terminal;
  307. final TerminalView view;
  308. final Oscillator oscillator;
  309. final bool focused;
  310. final CellSize charSize;
  311. final TextLayoutCache textLayoutCache;
  312. @override
  313. void paint(Canvas canvas, Size size) {
  314. if (!terminal.isReady) {
  315. return;
  316. }
  317. _paintBackground(canvas);
  318. // if (oscillator.value) {
  319. // }
  320. if (terminal.showCursor) {
  321. _paintCursor(canvas);
  322. }
  323. _paintText(canvas);
  324. _paintSelection(canvas);
  325. }
  326. void _paintBackground(Canvas canvas) {
  327. final lines = terminal.getVisibleLines();
  328. for (var row = 0; row < lines.length; row++) {
  329. final line = lines[row];
  330. final offsetY = row * charSize.cellHeight;
  331. // final cellCount = math.min(terminal.viewWidth, line.length);
  332. final cellCount = terminal.terminalWidth;
  333. for (var col = 0; col < cellCount; col++) {
  334. final cellWidth = line.cellGetWidth(col);
  335. if (cellWidth == 0) {
  336. continue;
  337. }
  338. final cellFgColor = line.cellGetFgColor(col);
  339. final cellBgColor = line.cellGetBgColor(col);
  340. final effectBgColor = line.cellHasFlag(col, CellFlags.inverse)
  341. ? cellFgColor
  342. : cellBgColor;
  343. if (effectBgColor == 0x00) {
  344. continue;
  345. }
  346. // when a program reports black as background then it "really" means transparent
  347. if (effectBgColor == 0xFF000000) {
  348. continue;
  349. }
  350. // final cellFlags = line.cellGetFlags(i);
  351. // final cell = line.getCell(i);
  352. // final attr = cell.attr;
  353. final offsetX = col * charSize.cellWidth;
  354. final effectWidth = charSize.cellWidth * cellWidth + 1;
  355. final effectHeight = charSize.cellHeight + 1;
  356. // background color is already painted with opacity by the Container of
  357. // TerminalPainter so wo don't need to fallback to
  358. // terminal.theme.background here.
  359. final paint = Paint()..color = Color(effectBgColor);
  360. canvas.drawRect(
  361. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  362. paint,
  363. );
  364. }
  365. }
  366. }
  367. void _paintSelection(Canvas canvas) {
  368. final selection = terminal.selection;
  369. if (selection == null) {
  370. return;
  371. }
  372. final paint = Paint()..color = Colors.white.withOpacity(0.3);
  373. for (var y = 0; y < terminal.terminalHeight; y++) {
  374. final offsetY = y * charSize.cellHeight;
  375. final absoluteY = terminal.convertViewLineToRawLine(y) -
  376. terminal.scrollOffsetFromBottom;
  377. for (var x = 0; x < terminal.terminalWidth; x++) {
  378. var cellCount = 0;
  379. while (selection.contains(Position(x + cellCount, absoluteY)) &&
  380. x + cellCount < terminal.terminalWidth) {
  381. cellCount++;
  382. }
  383. if (cellCount == 0) {
  384. continue;
  385. }
  386. final offsetX = x * charSize.cellWidth;
  387. final effectWidth = cellCount * charSize.cellWidth;
  388. final effectHeight = charSize.cellHeight;
  389. canvas.drawRect(
  390. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  391. paint,
  392. );
  393. x += cellCount;
  394. }
  395. }
  396. }
  397. void _paintText(Canvas canvas) {
  398. final lines = terminal.getVisibleLines();
  399. for (var row = 0; row < lines.length; row++) {
  400. final line = lines[row];
  401. final offsetY = row * charSize.cellHeight;
  402. // final cellCount = math.min(terminal.viewWidth, line.length);
  403. final cellCount = terminal.terminalWidth;
  404. for (var col = 0; col < cellCount; col++) {
  405. final width = line.cellGetWidth(col);
  406. if (width == 0) {
  407. continue;
  408. }
  409. final offsetX = col * charSize.cellWidth;
  410. _paintCell(canvas, line, col, offsetX, offsetY);
  411. }
  412. }
  413. }
  414. void _paintCell(
  415. Canvas canvas,
  416. BufferLine line,
  417. int cell,
  418. double offsetX,
  419. double offsetY,
  420. ) {
  421. final codePoint = line.cellGetContent(cell);
  422. final fgColor = line.cellGetFgColor(cell);
  423. final bgColor = line.cellGetBgColor(cell);
  424. final flags = line.cellGetFlags(cell);
  425. if (codePoint == 0 || flags.hasFlag(CellFlags.invisible)) {
  426. return;
  427. }
  428. // final cellHash = line.cellGetHash(cell);
  429. final fontSize = view.style.fontSize;
  430. final cellHash = hashValues(codePoint, fgColor, bgColor, flags);
  431. var character = textLayoutCache.getLayoutFromCache(cellHash);
  432. if (character != null) {
  433. canvas.drawParagraph(character, Offset(offsetX, offsetY));
  434. return;
  435. }
  436. final cellColor = flags.hasFlag(CellFlags.inverse) ? bgColor : fgColor;
  437. var color = Color(cellColor);
  438. if (flags & CellFlags.faint != 0) {
  439. color = color.withOpacity(0.5);
  440. }
  441. final style = (view.style.textStyleProvider != null)
  442. ? view.style.textStyleProvider!(
  443. color: color,
  444. fontSize: fontSize,
  445. fontWeight: flags.hasFlag(CellFlags.bold)
  446. ? FontWeight.bold
  447. : FontWeight.normal,
  448. fontStyle: flags.hasFlag(CellFlags.italic)
  449. ? FontStyle.italic
  450. : FontStyle.normal,
  451. decoration: flags.hasFlag(CellFlags.underline)
  452. ? TextDecoration.underline
  453. : TextDecoration.none,
  454. )
  455. : TextStyle(
  456. color: color,
  457. fontSize: fontSize,
  458. fontWeight: flags.hasFlag(CellFlags.bold)
  459. ? FontWeight.bold
  460. : FontWeight.normal,
  461. fontStyle: flags.hasFlag(CellFlags.italic)
  462. ? FontStyle.italic
  463. : FontStyle.normal,
  464. decoration: flags.hasFlag(CellFlags.underline)
  465. ? TextDecoration.underline
  466. : TextDecoration.none,
  467. fontFamily: 'monospace',
  468. fontFamilyFallback: view.style.fontFamily,
  469. );
  470. // final tp = textLayoutCache.getOrPerformLayout(span);
  471. character = textLayoutCache.performAndCacheLayout(
  472. String.fromCharCode(codePoint), style, cellHash);
  473. canvas.drawParagraph(character, Offset(offsetX, offsetY));
  474. }
  475. void _paintCursor(Canvas canvas) {
  476. final screenCursorY = terminal.cursorY + terminal.scrollOffsetFromBottom;
  477. if (screenCursorY < 0 || screenCursorY >= terminal.terminalHeight) {
  478. return;
  479. }
  480. final width = charSize.cellWidth *
  481. (terminal.currentLine?.cellGetWidth(terminal.cursorX).clamp(1, 2) ?? 1);
  482. final offsetX = charSize.cellWidth * terminal.cursorX;
  483. final offsetY = charSize.cellHeight * screenCursorY;
  484. final paint = Paint()
  485. ..color = Color(terminal.cursorColor)
  486. ..strokeWidth = focused ? 0.0 : 1.0
  487. ..style = focused ? PaintingStyle.fill : PaintingStyle.stroke;
  488. canvas.drawRect(
  489. Rect.fromLTWH(offsetX, offsetY, width, charSize.cellHeight), paint);
  490. }
  491. @override
  492. bool shouldRepaint(CustomPainter oldDelegate) {
  493. /// paint only when the terminal has changed since last paint.
  494. return terminal.dirty;
  495. }
  496. }
  497. /// A scroll activity that does nothing. Used to suppress unexpected behaviors
  498. /// from [Scrollable] during viewport building process.
  499. class _EmptyScrollActivity extends IdleScrollActivity {
  500. _EmptyScrollActivity(ScrollActivityDelegate delegate) : super(delegate);
  501. @override
  502. void applyNewDimensions() {}
  503. /// set [isScrolling] to ture to prevent flutter from calling the old scroll
  504. /// activity.
  505. @override
  506. final isScrolling = true;
  507. void dispatchScrollStartNotification(
  508. ScrollMetrics metrics, BuildContext? context) {}
  509. void dispatchScrollUpdateNotification(
  510. ScrollMetrics metrics, BuildContext context, double scrollDelta) {}
  511. void dispatchOverscrollNotification(
  512. ScrollMetrics metrics, BuildContext context, double overscroll) {}
  513. void dispatchScrollEndNotification(
  514. ScrollMetrics metrics, BuildContext context) {}
  515. }