terminal_view.dart 18 KB

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