terminal_view.dart 17 KB

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