terminal_view.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. 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. /// 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. void _changeFontSizeCorrection(double correction) {
  96. _fontSizeCorrection += correction;
  97. _resetCellSize();
  98. onSize(_width!, _height!);
  99. }
  100. void _resetCellSize() {
  101. final newCellSize =
  102. widget.measureCellSize(widget.style.fontSize + _fontSizeCorrection);
  103. setState(() {
  104. _cellSize = newCellSize;
  105. });
  106. }
  107. // listen to oscillator to update mouse blink etc.
  108. // void onTick() {
  109. // widget.terminal.refresh();
  110. // }
  111. @override
  112. void initState() {
  113. // oscillator.start();
  114. // oscillator.addListener(onTick);
  115. // measureCellSize is expensive so we cache the result.
  116. _cellSize =
  117. widget.measureCellSize(widget.style.fontSize + _fontSizeCorrection);
  118. widget.terminal.addListener(onTerminalChange);
  119. super.initState();
  120. }
  121. @override
  122. void didUpdateWidget(TerminalView oldWidget) {
  123. oldWidget.terminal.removeListener(onTerminalChange);
  124. widget.terminal.addListener(onTerminalChange);
  125. super.didUpdateWidget(oldWidget);
  126. }
  127. @override
  128. void dispose() {
  129. // oscillator.stop();
  130. // oscillator.removeListener(onTick);
  131. widget.terminal.removeListener(onTerminalChange);
  132. super.dispose();
  133. }
  134. @override
  135. Widget build(BuildContext context) {
  136. return InputListener(
  137. listenKeyStroke: widget.inputBehavior.acceptKeyStroke,
  138. onKeyStroke: onKeyStroke,
  139. onTextInput: onInput,
  140. onAction: onAction,
  141. onFocus: onFocus,
  142. focusNode: widget.focusNode,
  143. autofocus: widget.autofocus,
  144. initEditingState: widget.inputBehavior.initEditingState,
  145. child: MouseRegion(
  146. cursor: SystemMouseCursors.text,
  147. child: LayoutBuilder(builder: (context, constraints) {
  148. onSize(constraints.maxWidth, constraints.maxHeight);
  149. // use flutter's Scrollable to manage scrolling to better integrate
  150. // with widgets such as Scrollbar.
  151. return NotificationListener<ScrollNotification>(
  152. onNotification: (notification) {
  153. onScroll(notification.metrics.pixels);
  154. return false;
  155. },
  156. child: Scrollable(
  157. controller: widget.scrollController,
  158. viewportBuilder: (context, offset) {
  159. final position = widget.scrollController.position;
  160. /// use [_EmptyScrollActivity] to suppress unexpected behaviors
  161. /// that come from [applyViewportDimension].
  162. if (position is ScrollActivityDelegate) {
  163. position.beginActivity(
  164. _EmptyScrollActivity(position as ScrollActivityDelegate),
  165. );
  166. }
  167. // set viewport height.
  168. offset.applyViewportDimension(constraints.maxHeight);
  169. if (widget.terminal.isReady) {
  170. final minScrollExtent = 0.0;
  171. final maxScrollExtent = math.max(
  172. 0.0,
  173. _cellSize.cellHeight * widget.terminal.bufferHeight -
  174. constraints.maxHeight);
  175. // set how much the terminal can scroll
  176. offset.applyContentDimensions(
  177. minScrollExtent, maxScrollExtent);
  178. // syncronize pending terminal scroll extent to ScrollController
  179. if (_terminalScrollExtent != null) {
  180. position.correctPixels(_terminalScrollExtent!);
  181. _terminalScrollExtent = null;
  182. }
  183. }
  184. return buildTerminal(context);
  185. },
  186. ),
  187. );
  188. }),
  189. ),
  190. );
  191. }
  192. Widget buildTerminal(BuildContext context) {
  193. return GestureDetector(
  194. behavior: HitTestBehavior.deferToChild,
  195. dragStartBehavior: DragStartBehavior.down,
  196. onDoubleTapDown: (details) {
  197. print('details : $details');
  198. },
  199. onTapDown: (detail) {
  200. if (widget.terminal.selection?.isEmpty ?? true) {
  201. InputListener.of(context)!.requestKeyboard();
  202. } else {
  203. widget.terminal.clearSelection();
  204. }
  205. final pos = detail.localPosition;
  206. final offset = getMouseOffset(pos.dx, pos.dy);
  207. widget.terminal.onMouseTap(offset);
  208. widget.terminal.refresh();
  209. },
  210. onPanStart: (detail) {
  211. final pos = detail.localPosition;
  212. final offset = getMouseOffset(pos.dx, pos.dy);
  213. widget.terminal.onPanStart(offset);
  214. widget.terminal.refresh();
  215. },
  216. onPanUpdate: (detail) {
  217. final pos = detail.localPosition;
  218. final offset = getMouseOffset(pos.dx, pos.dy);
  219. widget.terminal.onPanUpdate(offset);
  220. widget.terminal.refresh();
  221. },
  222. child: Container(
  223. constraints: BoxConstraints.expand(),
  224. child: CustomPaint(
  225. painter: TerminalPainter(
  226. terminal: widget.terminal,
  227. view: widget,
  228. oscillator: oscillator,
  229. focused: focused,
  230. charSize: _cellSize,
  231. fontSizeCorrection: _fontSizeCorrection,
  232. ),
  233. ),
  234. color:
  235. Color(widget.terminal.backgroundColor).withOpacity(widget.opacity),
  236. ),
  237. );
  238. }
  239. /// Get global cell position from mouse position.
  240. Position getMouseOffset(double px, double py) {
  241. final col = (px / _cellSize.cellWidth).floor();
  242. final row = (py / _cellSize.cellHeight).floor();
  243. final x = col;
  244. final y = widget.terminal.convertViewLineToRawLine(row) -
  245. widget.terminal.scrollOffsetFromBottom;
  246. return Position(x, y);
  247. }
  248. double? _width;
  249. double? _height;
  250. int? _lastTerminalWidth;
  251. int? _lastTerminalHeight;
  252. void onSize(double width, double height) {
  253. if (!widget.terminal.isReady) {
  254. return;
  255. }
  256. _width = width;
  257. _height = height;
  258. final termWidth = (width / _cellSize.cellWidth).floor();
  259. final termHeight = (height / _cellSize.cellHeight).floor();
  260. if (_lastTerminalWidth == termWidth && _lastTerminalHeight == termHeight) {
  261. return;
  262. }
  263. _lastTerminalWidth = termWidth;
  264. _lastTerminalHeight = termHeight;
  265. widget.terminal.resize(termWidth, termHeight);
  266. }
  267. TextEditingValue? onInput(TextEditingValue value) {
  268. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  269. }
  270. void onKeyStroke(RawKeyEvent event) {
  271. if (Platform.isMacOS) {
  272. // for Mac we have META + x triggering special functions
  273. if (event.isMetaPressed) {
  274. // detect Zoom
  275. if (event.character == '+') {
  276. _changeFontSizeCorrection(1);
  277. }
  278. if (event.character == '-') {
  279. _changeFontSizeCorrection(-1);
  280. }
  281. }
  282. } else {
  283. // for Windows and Linux we have CTRL + SHIFT + x triggering special functions
  284. if (event.isControlPressed && event.isShiftPressed) {
  285. if (event.character == '+') {
  286. _changeFontSizeCorrection(1);
  287. }
  288. if (event.character == '-') {
  289. _changeFontSizeCorrection(-1);
  290. }
  291. }
  292. }
  293. // TODO: find a way to stop scrolling immediately after key stroke.
  294. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  295. widget.terminal.setScrollOffsetFromBottom(0);
  296. }
  297. void onFocus(bool focused) {
  298. SchedulerBinding.instance!.addPostFrameCallback((_) {
  299. widget.terminal.refresh();
  300. });
  301. }
  302. void onAction(TextInputAction action) {
  303. widget.inputBehavior.onAction(action, widget.terminal);
  304. }
  305. // synchronize flutter scroll offset to terminal
  306. void onScroll(double offset) {
  307. final topOffset = (offset / _cellSize.cellHeight).ceil();
  308. final bottomOffset = widget.terminal.invisibleHeight - topOffset;
  309. widget.terminal.setScrollOffsetFromBottom(bottomOffset);
  310. }
  311. }
  312. class TerminalPainter extends CustomPainter {
  313. TerminalPainter({
  314. required this.terminal,
  315. required this.view,
  316. required this.oscillator,
  317. required this.focused,
  318. required this.charSize,
  319. required this.fontSizeCorrection,
  320. });
  321. final TerminalUiInteraction terminal;
  322. final TerminalView view;
  323. final Oscillator oscillator;
  324. final bool focused;
  325. final CellSize charSize;
  326. final double fontSizeCorrection;
  327. @override
  328. void paint(Canvas canvas, Size size) {
  329. if (!terminal.isReady) {
  330. return;
  331. }
  332. _paintBackground(canvas);
  333. // if (oscillator.value) {
  334. // }
  335. if (terminal.showCursor) {
  336. _paintCursor(canvas);
  337. }
  338. _paintText(canvas);
  339. _paintSelection(canvas);
  340. }
  341. void _paintBackground(Canvas canvas) {
  342. final lines = terminal.getVisibleLines();
  343. for (var row = 0; row < lines.length; row++) {
  344. final line = lines[row];
  345. final offsetY = row * charSize.cellHeight;
  346. // final cellCount = math.min(terminal.viewWidth, line.length);
  347. final cellCount = terminal.terminalWidth;
  348. for (var col = 0; col < cellCount; col++) {
  349. final cellWidth = line.cellGetWidth(col);
  350. if (cellWidth == 0) {
  351. continue;
  352. }
  353. final cellFgColor = line.cellGetFgColor(col);
  354. final cellBgColor = line.cellGetBgColor(col);
  355. final effectBgColor = line.cellHasFlag(col, CellFlags.inverse)
  356. ? cellFgColor
  357. : cellBgColor;
  358. if (effectBgColor == 0x00) {
  359. continue;
  360. }
  361. // when a program reports black as background then it "really" means transparent
  362. if (effectBgColor == 0xFF000000) {
  363. continue;
  364. }
  365. // final cellFlags = line.cellGetFlags(i);
  366. // final cell = line.getCell(i);
  367. // final attr = cell.attr;
  368. final offsetX = col * charSize.cellWidth;
  369. final effectWidth = charSize.cellWidth * cellWidth + 1;
  370. final effectHeight = charSize.cellHeight + 1;
  371. // background color is already painted with opacity by the Container of
  372. // TerminalPainter so wo don't need to fallback to
  373. // terminal.theme.background here.
  374. final paint = Paint()..color = Color(effectBgColor);
  375. canvas.drawRect(
  376. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  377. paint,
  378. );
  379. }
  380. }
  381. }
  382. void _paintSelection(Canvas canvas) {
  383. final selection = terminal.selection;
  384. if (selection == null) {
  385. return;
  386. }
  387. final paint = Paint()..color = Colors.white.withOpacity(0.3);
  388. for (var y = 0; y < terminal.terminalHeight; y++) {
  389. final offsetY = y * charSize.cellHeight;
  390. final absoluteY = terminal.convertViewLineToRawLine(y) -
  391. terminal.scrollOffsetFromBottom;
  392. for (var x = 0; x < terminal.terminalWidth; x++) {
  393. var cellCount = 0;
  394. while (selection.contains(Position(x + cellCount, absoluteY)) &&
  395. x + cellCount < terminal.terminalWidth) {
  396. cellCount++;
  397. }
  398. if (cellCount == 0) {
  399. continue;
  400. }
  401. final offsetX = x * charSize.cellWidth;
  402. final effectWidth = cellCount * charSize.cellWidth;
  403. final effectHeight = charSize.cellHeight;
  404. canvas.drawRect(
  405. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  406. paint,
  407. );
  408. x += cellCount;
  409. }
  410. }
  411. }
  412. void _paintText(Canvas canvas) {
  413. final lines = terminal.getVisibleLines();
  414. for (var row = 0; row < lines.length; row++) {
  415. final line = lines[row];
  416. final offsetY = row * charSize.cellHeight;
  417. // final cellCount = math.min(terminal.viewWidth, line.length);
  418. final cellCount = terminal.terminalWidth;
  419. for (var col = 0; col < cellCount; col++) {
  420. final width = line.cellGetWidth(col);
  421. if (width == 0) {
  422. continue;
  423. }
  424. final offsetX = col * charSize.cellWidth;
  425. _paintCell(canvas, line, col, offsetX, offsetY);
  426. }
  427. }
  428. }
  429. void _paintCell(
  430. Canvas canvas,
  431. BufferLine line,
  432. int cell,
  433. double offsetX,
  434. double offsetY,
  435. ) {
  436. final codePoint = line.cellGetContent(cell);
  437. final fgColor = line.cellGetFgColor(cell);
  438. final bgColor = line.cellGetBgColor(cell);
  439. final flags = line.cellGetFlags(cell);
  440. if (codePoint == 0 || flags.hasFlag(CellFlags.invisible)) {
  441. return;
  442. }
  443. // final cellHash = line.cellGetHash(cell);
  444. final fontSize = view.style.fontSize + fontSizeCorrection;
  445. if (textLayoutCacheFontSize != fontSize) {
  446. textLayoutCache.clear();
  447. textLayoutCacheFontSize = fontSize;
  448. }
  449. final cellHash = hashValues(codePoint, fgColor, bgColor, flags);
  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. }