terminal_view.dart 19 KB

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