terminal_view.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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: (details) {
  188. print('details : $details');
  189. },
  190. onTapDown: (detail) {
  191. if (widget.terminal.selection?.isEmpty ?? true) {
  192. InputListener.of(context)!.requestKeyboard();
  193. } else {
  194. widget.terminal.clearSelection();
  195. }
  196. final pos = detail.localPosition;
  197. final offset = getMouseOffset(pos.dx, pos.dy);
  198. widget.terminal.onMouseTap(offset);
  199. widget.terminal.refresh();
  200. },
  201. onPanStart: (detail) {
  202. final pos = detail.localPosition;
  203. final offset = getMouseOffset(pos.dx, pos.dy);
  204. widget.terminal.onPanStart(offset);
  205. widget.terminal.refresh();
  206. },
  207. onPanUpdate: (detail) {
  208. final pos = detail.localPosition;
  209. final offset = getMouseOffset(pos.dx, pos.dy);
  210. widget.terminal.onPanUpdate(offset);
  211. widget.terminal.refresh();
  212. },
  213. child: Container(
  214. constraints: BoxConstraints.expand(),
  215. child: CustomPaint(
  216. painter: TerminalPainter(
  217. terminal: widget.terminal,
  218. view: widget,
  219. oscillator: oscillator,
  220. focused: focused,
  221. charSize: _cellSize,
  222. textLayoutCache: textLayoutCache,
  223. ),
  224. ),
  225. color: Color(widget.terminal.backgroundColor).withOpacity(
  226. widget.opacity,
  227. ),
  228. ),
  229. );
  230. }
  231. /// Get global cell position from mouse position.
  232. Position getMouseOffset(double px, double py) {
  233. final col = (px / _cellSize.cellWidth).floor();
  234. final row = (py / _cellSize.cellHeight).floor();
  235. final x = col;
  236. final y = widget.terminal.convertViewLineToRawLine(row) -
  237. widget.terminal.scrollOffsetFromBottom;
  238. return Position(x, y);
  239. }
  240. double? _width;
  241. double? _height;
  242. void onWidgetSize(double width, double height) {
  243. if (!widget.terminal.isReady) {
  244. return;
  245. }
  246. _width = width;
  247. _height = height;
  248. updateTerminalSize();
  249. }
  250. int? _lastTerminalWidth;
  251. int? _lastTerminalHeight;
  252. void updateTerminalSize() {
  253. assert(_width != null);
  254. assert(_height != null);
  255. final termWidth = (_width! / _cellSize.cellWidth).floor();
  256. final termHeight = (_height! / _cellSize.cellHeight).floor();
  257. if (_lastTerminalWidth == termWidth && _lastTerminalHeight == termHeight) {
  258. return;
  259. }
  260. _lastTerminalWidth = termWidth;
  261. _lastTerminalHeight = termHeight;
  262. widget.terminal.resize(
  263. termWidth,
  264. termHeight,
  265. (termWidth * _cellSize.cellWidth).floor(),
  266. (termHeight * _cellSize.cellHeight).floor(),
  267. );
  268. }
  269. TextEditingValue? onInput(TextEditingValue value) {
  270. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  271. }
  272. void onKeyStroke(RawKeyEvent event) {
  273. // TODO: find a way to stop scrolling immediately after key stroke.
  274. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  275. widget.terminal.setScrollOffsetFromBottom(0);
  276. }
  277. void onFocus(bool focused) {
  278. SchedulerBinding.instance!.addPostFrameCallback((_) {
  279. widget.terminal.refresh();
  280. });
  281. }
  282. void onAction(TextInputAction action) {
  283. widget.inputBehavior.onAction(action, widget.terminal);
  284. }
  285. // synchronize flutter scroll offset to terminal
  286. void onScroll(double offset) {
  287. final topOffset = (offset / _cellSize.cellHeight).ceil();
  288. final bottomOffset = widget.terminal.invisibleHeight - topOffset;
  289. widget.terminal.setScrollOffsetFromBottom(bottomOffset);
  290. }
  291. }
  292. class TerminalPainter extends CustomPainter {
  293. TerminalPainter({
  294. required this.terminal,
  295. required this.view,
  296. required this.oscillator,
  297. required this.focused,
  298. required this.charSize,
  299. required this.textLayoutCache,
  300. });
  301. final TerminalUiInteraction terminal;
  302. final TerminalView view;
  303. final Oscillator oscillator;
  304. final bool focused;
  305. final CellSize charSize;
  306. final TextLayoutCache textLayoutCache;
  307. @override
  308. void paint(Canvas canvas, Size size) {
  309. if (!terminal.isReady) {
  310. return;
  311. }
  312. _paintBackground(canvas);
  313. // if (oscillator.value) {
  314. // }
  315. if (terminal.showCursor) {
  316. _paintCursor(canvas);
  317. }
  318. _paintText(canvas);
  319. _paintSelection(canvas);
  320. }
  321. void _paintBackground(Canvas canvas) {
  322. final lines = terminal.getVisibleLines();
  323. for (var row = 0; row < lines.length; row++) {
  324. final line = lines[row];
  325. final offsetY = row * charSize.cellHeight;
  326. // final cellCount = math.min(terminal.viewWidth, line.length);
  327. final cellCount = terminal.terminalWidth;
  328. for (var col = 0; col < cellCount; col++) {
  329. final cellWidth = line.cellGetWidth(col);
  330. if (cellWidth == 0) {
  331. continue;
  332. }
  333. final cellFgColor = line.cellGetFgColor(col);
  334. final cellBgColor = line.cellGetBgColor(col);
  335. final effectBgColor = line.cellHasFlag(col, CellFlags.inverse)
  336. ? cellFgColor
  337. : cellBgColor;
  338. if (effectBgColor == 0x00) {
  339. continue;
  340. }
  341. // when a program reports black as background then it "really" means transparent
  342. if (effectBgColor == 0xFF000000) {
  343. continue;
  344. }
  345. // final cellFlags = line.cellGetFlags(i);
  346. // final cell = line.getCell(i);
  347. // final attr = cell.attr;
  348. final offsetX = col * charSize.cellWidth;
  349. final effectWidth = charSize.cellWidth * cellWidth + 1;
  350. final effectHeight = charSize.cellHeight + 1;
  351. // background color is already painted with opacity by the Container of
  352. // TerminalPainter so wo don't need to fallback to
  353. // terminal.theme.background here.
  354. final paint = Paint()..color = Color(effectBgColor);
  355. canvas.drawRect(
  356. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  357. paint,
  358. );
  359. }
  360. }
  361. }
  362. void _paintSelection(Canvas canvas) {
  363. final selection = terminal.selection;
  364. if (selection == null) {
  365. return;
  366. }
  367. final paint = Paint()..color = Colors.white.withOpacity(0.3);
  368. for (var y = 0; y < terminal.terminalHeight; y++) {
  369. final offsetY = y * charSize.cellHeight;
  370. final absoluteY = terminal.convertViewLineToRawLine(y) -
  371. terminal.scrollOffsetFromBottom;
  372. for (var x = 0; x < terminal.terminalWidth; x++) {
  373. var cellCount = 0;
  374. while (selection.contains(Position(x + cellCount, absoluteY)) &&
  375. x + cellCount < terminal.terminalWidth) {
  376. cellCount++;
  377. }
  378. if (cellCount == 0) {
  379. continue;
  380. }
  381. final offsetX = x * charSize.cellWidth;
  382. final effectWidth = cellCount * charSize.cellWidth;
  383. final effectHeight = charSize.cellHeight;
  384. canvas.drawRect(
  385. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  386. paint,
  387. );
  388. x += cellCount;
  389. }
  390. }
  391. }
  392. void _paintText(Canvas canvas) {
  393. final lines = terminal.getVisibleLines();
  394. for (var row = 0; row < lines.length; row++) {
  395. final line = lines[row];
  396. final offsetY = row * charSize.cellHeight;
  397. // final cellCount = math.min(terminal.viewWidth, line.length);
  398. final cellCount = terminal.terminalWidth;
  399. for (var col = 0; col < cellCount; col++) {
  400. final width = line.cellGetWidth(col);
  401. if (width == 0) {
  402. continue;
  403. }
  404. final offsetX = col * charSize.cellWidth;
  405. _paintCell(canvas, line, col, offsetX, offsetY);
  406. }
  407. }
  408. }
  409. void _paintCell(
  410. Canvas canvas,
  411. BufferLine line,
  412. int cell,
  413. double offsetX,
  414. double offsetY,
  415. ) {
  416. final codePoint = line.cellGetContent(cell);
  417. final fgColor = line.cellGetFgColor(cell);
  418. final bgColor = line.cellGetBgColor(cell);
  419. final flags = line.cellGetFlags(cell);
  420. if (codePoint == 0 || flags.hasFlag(CellFlags.invisible)) {
  421. return;
  422. }
  423. // final cellHash = line.cellGetHash(cell);
  424. final fontSize = view.style.fontSize;
  425. final cellHash = hashValues(codePoint, fgColor, bgColor, flags);
  426. var character = textLayoutCache.getLayoutFromCache(cellHash);
  427. if (character != null) {
  428. canvas.drawParagraph(character, Offset(offsetX, offsetY));
  429. return;
  430. }
  431. final cellColor = flags.hasFlag(CellFlags.inverse) ? bgColor : fgColor;
  432. var color = Color(cellColor);
  433. if (flags & CellFlags.faint != 0) {
  434. color = color.withOpacity(0.5);
  435. }
  436. final style = (view.style.textStyleProvider != null)
  437. ? view.style.textStyleProvider!(
  438. color: color,
  439. fontSize: fontSize,
  440. fontWeight: flags.hasFlag(CellFlags.bold)
  441. ? FontWeight.bold
  442. : FontWeight.normal,
  443. fontStyle: flags.hasFlag(CellFlags.italic)
  444. ? FontStyle.italic
  445. : FontStyle.normal,
  446. decoration: flags.hasFlag(CellFlags.underline)
  447. ? TextDecoration.underline
  448. : TextDecoration.none,
  449. )
  450. : TextStyle(
  451. color: color,
  452. fontSize: fontSize,
  453. fontWeight: flags.hasFlag(CellFlags.bold)
  454. ? FontWeight.bold
  455. : FontWeight.normal,
  456. fontStyle: flags.hasFlag(CellFlags.italic)
  457. ? FontStyle.italic
  458. : FontStyle.normal,
  459. decoration: flags.hasFlag(CellFlags.underline)
  460. ? TextDecoration.underline
  461. : TextDecoration.none,
  462. fontFamily: 'monospace',
  463. fontFamilyFallback: view.style.fontFamily,
  464. );
  465. // final tp = textLayoutCache.getOrPerformLayout(span);
  466. character = textLayoutCache.performAndCacheLayout(
  467. String.fromCharCode(codePoint), style, cellHash);
  468. canvas.drawParagraph(character, Offset(offsetX, offsetY));
  469. }
  470. void _paintCursor(Canvas canvas) {
  471. final screenCursorY = terminal.cursorY + terminal.scrollOffsetFromBottom;
  472. if (screenCursorY < 0 || screenCursorY >= terminal.terminalHeight) {
  473. return;
  474. }
  475. final width = charSize.cellWidth *
  476. (terminal.currentLine?.cellGetWidth(terminal.cursorX).clamp(1, 2) ?? 1);
  477. final offsetX = charSize.cellWidth * terminal.cursorX;
  478. final offsetY = charSize.cellHeight * screenCursorY;
  479. final paint = Paint()
  480. ..color = Color(terminal.cursorColor)
  481. ..strokeWidth = focused ? 0.0 : 1.0
  482. ..style = focused ? PaintingStyle.fill : PaintingStyle.stroke;
  483. canvas.drawRect(
  484. Rect.fromLTWH(offsetX, offsetY, width, charSize.cellHeight), paint);
  485. }
  486. @override
  487. bool shouldRepaint(CustomPainter oldDelegate) {
  488. /// paint only when the terminal has changed since last paint.
  489. return terminal.dirty;
  490. }
  491. }
  492. /// A scroll activity that does nothing. Used to suppress unexpected behaviors
  493. /// from [Scrollable] during viewport building process.
  494. class _EmptyScrollActivity extends IdleScrollActivity {
  495. _EmptyScrollActivity(ScrollActivityDelegate delegate) : super(delegate);
  496. @override
  497. void applyNewDimensions() {}
  498. /// set [isScrolling] to ture to prevent flutter from calling the old scroll
  499. /// activity.
  500. @override
  501. final isScrolling = true;
  502. void dispatchScrollStartNotification(
  503. ScrollMetrics metrics, BuildContext? context) {}
  504. void dispatchScrollUpdateNotification(
  505. ScrollMetrics metrics, BuildContext context, double scrollDelta) {}
  506. void dispatchOverscrollNotification(
  507. ScrollMetrics metrics, BuildContext context, double overscroll) {}
  508. void dispatchScrollEndNotification(
  509. ScrollMetrics metrics, BuildContext context) {}
  510. }