terminal_view.dart 19 KB

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