terminal_view.dart 18 KB

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