terminal_view.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. 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() {
  45. final testString = 'xxxxxxxxxx' * 1000;
  46. final text = Text(
  47. testString,
  48. style: (style.textStyleProvider != null)
  49. ? style.textStyleProvider!(
  50. fontSize: style.fontSize,
  51. )
  52. : TextStyle(
  53. fontFamily: 'monospace',
  54. fontFamilyFallback: style.fontFamily,
  55. fontSize: style.fontSize,
  56. ),
  57. );
  58. final size = textSize(text);
  59. final charWidth = (size.width / testString.length);
  60. final charHeight = size.height;
  61. final cellWidth = charWidth * style.fontWidthScaleFactor;
  62. final cellHeight = size.height * style.fontHeightScaleFactor;
  63. return CellSize(
  64. charWidth: charWidth,
  65. charHeight: charHeight,
  66. cellWidth: cellWidth,
  67. cellHeight: cellHeight,
  68. letterSpacing: cellWidth - charWidth,
  69. lineSpacing: cellHeight - charHeight,
  70. );
  71. }
  72. @override
  73. _TerminalViewState createState() => _TerminalViewState();
  74. }
  75. class _TerminalViewState extends State<TerminalView> {
  76. /// blinking cursor and blinking character
  77. final oscillator = Oscillator.ms(600);
  78. bool get focused {
  79. return widget.focusNode.hasFocus;
  80. }
  81. late CellSize _cellSize;
  82. /// Scroll position from the terminal. Not null if terminal scroll extent has
  83. /// been updated and needs to be syncronized to flutter side.
  84. double? _terminalScrollExtent;
  85. void onTerminalChange() {
  86. _terminalScrollExtent =
  87. _cellSize.cellHeight * widget.terminal.scrollOffsetFromTop;
  88. if (mounted) {
  89. setState(() {});
  90. }
  91. }
  92. // listen to oscillator to update mouse blink etc.
  93. // void onTick() {
  94. // widget.terminal.refresh();
  95. // }
  96. @override
  97. void initState() {
  98. // oscillator.start();
  99. // oscillator.addListener(onTick);
  100. // measureCellSize is expensive so we cache the result.
  101. _cellSize = widget.measureCellSize();
  102. widget.terminal.addListener(onTerminalChange);
  103. super.initState();
  104. }
  105. @override
  106. void didUpdateWidget(TerminalView oldWidget) {
  107. oldWidget.terminal.removeListener(onTerminalChange);
  108. widget.terminal.addListener(onTerminalChange);
  109. super.didUpdateWidget(oldWidget);
  110. }
  111. @override
  112. void dispose() {
  113. // oscillator.stop();
  114. // oscillator.removeListener(onTick);
  115. widget.terminal.removeListener(onTerminalChange);
  116. super.dispose();
  117. }
  118. @override
  119. Widget build(BuildContext context) {
  120. return InputListener(
  121. listenKeyStroke: widget.inputBehavior.acceptKeyStroke,
  122. onKeyStroke: onKeyStroke,
  123. onTextInput: onInput,
  124. onAction: onAction,
  125. onFocus: onFocus,
  126. focusNode: widget.focusNode,
  127. autofocus: widget.autofocus,
  128. initEditingState: widget.inputBehavior.initEditingState,
  129. child: MouseRegion(
  130. cursor: SystemMouseCursors.text,
  131. child: LayoutBuilder(builder: (context, constraints) {
  132. onSize(constraints.maxWidth, constraints.maxHeight);
  133. // use flutter's Scrollable to manage scrolling to better integrate
  134. // with widgets such as Scrollbar.
  135. return NotificationListener<ScrollNotification>(
  136. onNotification: (notification) {
  137. onScroll(notification.metrics.pixels);
  138. return false;
  139. },
  140. child: Scrollable(
  141. controller: widget.scrollController,
  142. viewportBuilder: (context, offset) {
  143. final position = widget.scrollController.position;
  144. /// use [_EmptyScrollActivity] to suppress unexpected behaviors
  145. /// that come from [applyViewportDimension].
  146. if (position is ScrollActivityDelegate) {
  147. position.beginActivity(
  148. _EmptyScrollActivity(position as ScrollActivityDelegate),
  149. );
  150. }
  151. // set viewport height.
  152. offset.applyViewportDimension(constraints.maxHeight);
  153. if (widget.terminal.isReady) {
  154. final minScrollExtent = 0.0;
  155. final maxScrollExtent = math.max(
  156. 0.0,
  157. _cellSize.cellHeight * widget.terminal.bufferHeight -
  158. constraints.maxHeight);
  159. // set how much the terminal can scroll
  160. offset.applyContentDimensions(
  161. minScrollExtent, maxScrollExtent);
  162. // syncronize pending terminal scroll extent to ScrollController
  163. if (_terminalScrollExtent != null) {
  164. position.correctPixels(_terminalScrollExtent!);
  165. _terminalScrollExtent = null;
  166. }
  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. if (!widget.terminal.isReady) {
  235. return;
  236. }
  237. final termWidth = (width / _cellSize.cellWidth).floor();
  238. final termHeight = (height / _cellSize.cellHeight).floor();
  239. if (_lastTerminalWidth == termWidth && _lastTerminalHeight == termHeight) {
  240. return;
  241. }
  242. _lastTerminalWidth = termWidth;
  243. _lastTerminalHeight = termHeight;
  244. widget.terminal.resize(termWidth, termHeight);
  245. }
  246. TextEditingValue? onInput(TextEditingValue value) {
  247. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  248. }
  249. void onKeyStroke(RawKeyEvent event) {
  250. // TODO: find a way to stop scrolling immediately after key stroke.
  251. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  252. widget.terminal.setScrollOffsetFromBottom(0);
  253. }
  254. void onFocus(bool focused) {
  255. SchedulerBinding.instance!.addPostFrameCallback((_) {
  256. widget.terminal.refresh();
  257. });
  258. }
  259. void onAction(TextInputAction action) {
  260. widget.inputBehavior.onAction(action, widget.terminal);
  261. }
  262. // synchronize flutter scroll offset to terminal
  263. void onScroll(double offset) {
  264. final topOffset = (offset / _cellSize.cellHeight).ceil();
  265. final bottomOffset = widget.terminal.invisibleHeight - topOffset;
  266. widget.terminal.setScrollOffsetFromBottom(bottomOffset);
  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. if (!terminal.isReady) {
  285. return;
  286. }
  287. _paintBackground(canvas);
  288. // if (oscillator.value) {
  289. // }
  290. if (terminal.showCursor) {
  291. _paintCursor(canvas);
  292. }
  293. _paintText(canvas);
  294. _paintSelection(canvas);
  295. }
  296. void _paintBackground(Canvas canvas) {
  297. final lines = terminal.getVisibleLines();
  298. for (var row = 0; row < lines.length; row++) {
  299. final line = lines[row];
  300. final offsetY = row * charSize.cellHeight;
  301. // final cellCount = math.min(terminal.viewWidth, line.length);
  302. final cellCount = terminal.terminalWidth;
  303. for (var col = 0; col < cellCount; col++) {
  304. final cellWidth = line.cellGetWidth(col);
  305. if (cellWidth == 0) {
  306. continue;
  307. }
  308. final cellFgColor = line.cellGetFgColor(col);
  309. final cellBgColor = line.cellGetBgColor(col);
  310. final effectBgColor = line.cellHasFlag(col, CellFlags.inverse)
  311. ? cellFgColor
  312. : cellBgColor;
  313. if (effectBgColor == 0x00) {
  314. continue;
  315. }
  316. // final cellFlags = line.cellGetFlags(i);
  317. // final cell = line.getCell(i);
  318. // final attr = cell.attr;
  319. final offsetX = col * charSize.cellWidth;
  320. final effectWidth = charSize.cellWidth * cellWidth + 1;
  321. final effectHeight = charSize.cellHeight + 1;
  322. // background color is already painted with opacity by the Container of
  323. // TerminalPainter so wo don't need to fallback to
  324. // terminal.theme.background here.
  325. final paint = Paint()..color = Color(effectBgColor);
  326. canvas.drawRect(
  327. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  328. paint,
  329. );
  330. }
  331. }
  332. }
  333. void _paintSelection(Canvas canvas) {
  334. final selection = terminal.selection;
  335. if (selection == null) {
  336. return;
  337. }
  338. final paint = Paint()..color = Colors.white.withOpacity(0.3);
  339. for (var y = 0; y < terminal.terminalHeight; y++) {
  340. final offsetY = y * charSize.cellHeight;
  341. final absoluteY = terminal.convertViewLineToRawLine(y) -
  342. terminal.scrollOffsetFromBottom;
  343. for (var x = 0; x < terminal.terminalWidth; x++) {
  344. var cellCount = 0;
  345. while (selection.contains(Position(x + cellCount, absoluteY)) &&
  346. x + cellCount < terminal.terminalWidth) {
  347. cellCount++;
  348. }
  349. if (cellCount == 0) {
  350. continue;
  351. }
  352. final offsetX = x * charSize.cellWidth;
  353. final effectWidth = cellCount * charSize.cellWidth;
  354. final effectHeight = charSize.cellHeight;
  355. canvas.drawRect(
  356. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  357. paint,
  358. );
  359. x += cellCount;
  360. }
  361. }
  362. }
  363. void _paintText(Canvas canvas) {
  364. final lines = terminal.getVisibleLines();
  365. for (var row = 0; row < lines.length; row++) {
  366. final line = lines[row];
  367. final offsetY = row * charSize.cellHeight;
  368. // final cellCount = math.min(terminal.viewWidth, line.length);
  369. final cellCount = terminal.terminalWidth;
  370. for (var col = 0; col < cellCount; col++) {
  371. final width = line.cellGetWidth(col);
  372. if (width == 0) {
  373. continue;
  374. }
  375. final offsetX = col * charSize.cellWidth;
  376. _paintCell(canvas, line, col, offsetX, offsetY);
  377. }
  378. }
  379. }
  380. void _paintCell(
  381. Canvas canvas,
  382. BufferLine line,
  383. int cell,
  384. double offsetX,
  385. double offsetY,
  386. ) {
  387. final codePoint = line.cellGetContent(cell);
  388. final fgColor = line.cellGetFgColor(cell);
  389. final bgColor = line.cellGetBgColor(cell);
  390. final flags = line.cellGetFlags(cell);
  391. if (codePoint == 0 || flags.hasFlag(CellFlags.invisible)) {
  392. return;
  393. }
  394. // final cellHash = line.cellGetHash(cell);
  395. final cellHash = hashValues(codePoint, fgColor, bgColor, flags);
  396. var tp = textLayoutCache.getLayoutFromCache(cellHash);
  397. if (tp != null) {
  398. tp.paint(canvas, Offset(offsetX, offsetY));
  399. return;
  400. }
  401. final cellColor = flags.hasFlag(CellFlags.inverse) ? bgColor : fgColor;
  402. var color = Color(cellColor);
  403. if (flags & CellFlags.faint != 0) {
  404. color = color.withOpacity(0.5);
  405. }
  406. final style = (view.style.textStyleProvider != null)
  407. ? view.style.textStyleProvider!(
  408. color: color,
  409. fontSize: view.style.fontSize,
  410. fontWeight: flags.hasFlag(CellFlags.bold)
  411. ? FontWeight.bold
  412. : FontWeight.normal,
  413. fontStyle: flags.hasFlag(CellFlags.italic)
  414. ? FontStyle.italic
  415. : FontStyle.normal,
  416. decoration: flags.hasFlag(CellFlags.underline)
  417. ? TextDecoration.underline
  418. : TextDecoration.none,
  419. )
  420. : TextStyle(
  421. color: color,
  422. fontSize: view.style.fontSize,
  423. fontWeight: flags.hasFlag(CellFlags.bold)
  424. ? FontWeight.bold
  425. : FontWeight.normal,
  426. fontStyle: flags.hasFlag(CellFlags.italic)
  427. ? FontStyle.italic
  428. : FontStyle.normal,
  429. decoration: flags.hasFlag(CellFlags.underline)
  430. ? TextDecoration.underline
  431. : TextDecoration.none,
  432. fontFamily: 'monospace',
  433. fontFamilyFallback: view.style.fontFamily,
  434. );
  435. final span = TextSpan(
  436. text: String.fromCharCode(codePoint),
  437. // text: codePointCache.getOrConstruct(cell.codePoint),
  438. style: style,
  439. );
  440. // final tp = textLayoutCache.getOrPerformLayout(span);
  441. tp = textLayoutCache.performAndCacheLayout(span, cellHash);
  442. tp.paint(canvas, Offset(offsetX, offsetY));
  443. }
  444. void _paintCursor(Canvas canvas) {
  445. final screenCursorY = terminal.cursorY + terminal.scrollOffsetFromBottom;
  446. if (screenCursorY < 0 || screenCursorY >= terminal.terminalHeight) {
  447. return;
  448. }
  449. final width = charSize.cellWidth *
  450. (terminal.currentLine?.cellGetWidth(terminal.cursorX).clamp(1, 2) ?? 1);
  451. final offsetX = charSize.cellWidth * terminal.cursorX;
  452. final offsetY = charSize.cellHeight * screenCursorY;
  453. final paint = Paint()
  454. ..color = Color(terminal.cursorColor)
  455. ..strokeWidth = focused ? 0.0 : 1.0
  456. ..style = focused ? PaintingStyle.fill : PaintingStyle.stroke;
  457. canvas.drawRect(
  458. Rect.fromLTWH(offsetX, offsetY, width, charSize.cellHeight), paint);
  459. }
  460. @override
  461. bool shouldRepaint(CustomPainter oldDelegate) {
  462. /// paint only when the terminal has changed since last paint.
  463. return terminal.dirty;
  464. }
  465. }
  466. /// A scroll activity that does nothing. Used to suppress unexpected behaviors
  467. /// from [Scrollable] during viewport building process.
  468. class _EmptyScrollActivity extends IdleScrollActivity {
  469. _EmptyScrollActivity(ScrollActivityDelegate delegate) : super(delegate);
  470. @override
  471. void applyNewDimensions() {}
  472. /// set [isScrolling] to ture to prevent flutter from calling the old scroll
  473. /// activity.
  474. @override
  475. final isScrolling = true;
  476. void dispatchScrollStartNotification(
  477. ScrollMetrics metrics, BuildContext? context) {}
  478. void dispatchScrollUpdateNotification(
  479. ScrollMetrics metrics, BuildContext context, double scrollDelta) {}
  480. void dispatchOverscrollNotification(
  481. ScrollMetrics metrics, BuildContext context, double overscroll) {}
  482. void dispatchScrollEndNotification(
  483. ScrollMetrics metrics, BuildContext context) {}
  484. }