terminal_view.dart 19 KB

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