terminal_view.dart 18 KB

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