terminal_view.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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/cell.dart';
  9. import 'package:xterm/frontend/char_size.dart';
  10. import 'package:xterm/frontend/helpers.dart';
  11. import 'package:xterm/frontend/input_behavior.dart';
  12. import 'package:xterm/frontend/input_behaviors.dart';
  13. import 'package:xterm/frontend/input_listener.dart';
  14. import 'package:xterm/frontend/oscillator.dart';
  15. import 'package:xterm/frontend/cache.dart';
  16. import 'package:xterm/mouse/position.dart';
  17. import 'package:xterm/terminal/terminal.dart';
  18. import 'package:xterm/theme/terminal_style.dart';
  19. import 'package:xterm/utli/hash_values.dart';
  20. typedef ResizeHandler = void Function(int width, int height);
  21. class TerminalView extends StatefulWidget {
  22. TerminalView({
  23. Key? key,
  24. required this.terminal,
  25. this.onResize,
  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 Terminal terminal;
  37. final ResizeHandler? onResize;
  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. CellSize measureCellSize() {
  45. final testString = 'xxxxxxxxxx' * 1000;
  46. final text = Text(
  47. testString,
  48. style: (style.textStyleProvider != null)
  49. ? style.textStyleProvider!(
  50. fontSize: style.fontSize,
  51. )
  52. : TextStyle(
  53. fontFamily: 'monospace',
  54. fontFamilyFallback: style.fontFamily,
  55. fontSize: style.fontSize,
  56. ),
  57. );
  58. final size = textSize(text);
  59. final charWidth = (size.width / testString.length);
  60. final charHeight = size.height;
  61. final cellWidth = charWidth * style.fontWidthScaleFactor;
  62. final cellHeight = size.height * style.fontHeightScaleFactor;
  63. return CellSize(
  64. charWidth: charWidth,
  65. charHeight: charHeight,
  66. cellWidth: cellWidth,
  67. cellHeight: cellHeight,
  68. letterSpacing: cellWidth - charWidth,
  69. lineSpacing: cellHeight - charHeight,
  70. );
  71. }
  72. @override
  73. _TerminalViewState createState() => _TerminalViewState();
  74. }
  75. class _TerminalViewState extends State<TerminalView> {
  76. final oscillator = Oscillator.ms(600);
  77. bool get focused {
  78. return widget.focusNode.hasFocus;
  79. }
  80. int? _lastTerminalWidth;
  81. int? _lastTerminalHeight;
  82. late CellSize _cellSize;
  83. late ViewportOffset _offset;
  84. var _minScrollExtent = 0.0;
  85. var _maxScrollExtent = 0.0;
  86. void onTerminalChange() {
  87. // if (_offset != null) {
  88. // final currentScrollExtent =
  89. // _cellSize.cellHeight * widget.terminal.buffer.scrollOffsetFromTop;
  90. // if (_offset.pixels != currentScrollExtent) {
  91. // _offset.correctBy(currentScrollExtent - _offset.pixels - 1);
  92. // }
  93. // }
  94. if (mounted) {
  95. setState(() {});
  96. }
  97. }
  98. void onTick() {
  99. widget.terminal.refresh();
  100. }
  101. @override
  102. void initState() {
  103. // oscillator.start();
  104. // oscillator.addListener(onTick);
  105. _cellSize = widget.measureCellSize();
  106. widget.terminal.addListener(onTerminalChange);
  107. super.initState();
  108. }
  109. @override
  110. void didUpdateWidget(TerminalView oldWidget) {
  111. widget.terminal.addListener(onTerminalChange);
  112. super.didUpdateWidget(oldWidget);
  113. }
  114. @override
  115. void dispose() {
  116. // oscillator.stop();
  117. // oscillator.removeListener(onTick);
  118. widget.terminal.removeListener(onTerminalChange);
  119. super.dispose();
  120. }
  121. @override
  122. Widget build(BuildContext context) {
  123. return InputListener(
  124. listenKeyStroke: widget.inputBehavior.acceptKeyStroke,
  125. onKeyStroke: onKeyStroke,
  126. onTextInput: onInput,
  127. onAction: onAction,
  128. onFocus: onFocus,
  129. focusNode: widget.focusNode,
  130. autofocus: widget.autofocus,
  131. initEditingState: widget.inputBehavior.initEditingState,
  132. child: MouseRegion(
  133. cursor: SystemMouseCursors.text,
  134. child: LayoutBuilder(builder: (context, constraints) {
  135. onResize(constraints.maxWidth, constraints.maxHeight);
  136. return Scrollable(
  137. viewportBuilder: (context, offset) {
  138. offset.applyViewportDimension(constraints.maxHeight);
  139. _minScrollExtent = 0.0;
  140. _maxScrollExtent = math.max(
  141. 0.0,
  142. _cellSize.cellHeight * widget.terminal.buffer.height -
  143. constraints.maxHeight);
  144. // final currentScrollExtent = _cellSize.cellHeight *
  145. // widget.terminal.buffer.scrollOffsetFromTop;
  146. // offset.correctBy(currentScrollExtent - offset.pixels - 1);
  147. offset.applyContentDimensions(_minScrollExtent, _maxScrollExtent);
  148. _offset = offset;
  149. _offset.addListener(onScroll);
  150. return buildTerminal(context);
  151. },
  152. );
  153. }),
  154. ),
  155. );
  156. }
  157. Widget buildTerminal(BuildContext context) {
  158. return GestureDetector(
  159. behavior: HitTestBehavior.deferToChild,
  160. dragStartBehavior: DragStartBehavior.down,
  161. onTapDown: (detail) {
  162. if (widget.terminal.selection.isEmpty) {
  163. InputListener.of(context)!.requestKeyboard();
  164. } else {
  165. widget.terminal.selection.clear();
  166. }
  167. final pos = detail.localPosition;
  168. final offset = getMouseOffset(pos.dx, pos.dy);
  169. widget.terminal.mouseMode.onTap(widget.terminal, offset);
  170. widget.terminal.refresh();
  171. },
  172. onPanStart: (detail) {
  173. final pos = detail.localPosition;
  174. final offset = getMouseOffset(pos.dx, pos.dy);
  175. widget.terminal.mouseMode.onPanStart(widget.terminal, offset);
  176. widget.terminal.refresh();
  177. },
  178. onPanUpdate: (detail) {
  179. final pos = detail.localPosition;
  180. final offset = getMouseOffset(pos.dx, pos.dy);
  181. widget.terminal.mouseMode.onPanUpdate(widget.terminal, offset);
  182. widget.terminal.refresh();
  183. },
  184. child: Container(
  185. constraints: BoxConstraints.expand(),
  186. color: Color(widget.terminal.theme.background.value)
  187. .withOpacity(widget.opacity),
  188. child: CustomPaint(
  189. painter: TerminalPainter(
  190. terminal: widget.terminal,
  191. view: widget,
  192. oscillator: oscillator,
  193. focused: focused,
  194. charSize: _cellSize,
  195. ),
  196. ),
  197. ),
  198. );
  199. }
  200. Position getMouseOffset(double px, double py) {
  201. final col = (px / _cellSize.cellWidth).floor();
  202. final row = (py / _cellSize.cellHeight).floor();
  203. final x = col;
  204. final y = widget.terminal.buffer.convertViewLineToRawLine(row) -
  205. widget.terminal.buffer.scrollOffsetFromBottom;
  206. return Position(x, y);
  207. }
  208. void onResize(double width, double height) {
  209. final termWidth = (width / _cellSize.cellWidth).floor();
  210. final termHeight = (height / _cellSize.cellHeight).floor();
  211. if (_lastTerminalWidth != termWidth || _lastTerminalHeight != termHeight) {
  212. _lastTerminalWidth = termWidth;
  213. _lastTerminalHeight = termHeight;
  214. // print('($termWidth, $termHeight)');
  215. widget.onResize?.call(termWidth, termHeight);
  216. SchedulerBinding.instance!.addPostFrameCallback((_) {
  217. widget.terminal.resize(termWidth, termHeight);
  218. });
  219. // Future.delayed(Duration.zero).then((_) {
  220. // widget.terminal.resize(termWidth, termHeight);
  221. // });
  222. }
  223. }
  224. TextEditingValue? onInput(TextEditingValue value) {
  225. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  226. }
  227. void onKeyStroke(RawKeyEvent event) {
  228. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  229. _offset.moveTo(_maxScrollExtent);
  230. }
  231. void onFocus(bool focused) {
  232. SchedulerBinding.instance!.addPostFrameCallback((_) {
  233. widget.terminal.refresh();
  234. });
  235. }
  236. void onAction(TextInputAction action) {
  237. widget.inputBehavior.onAction(action, widget.terminal);
  238. }
  239. void onScroll() {
  240. final charOffset = (_offset.pixels / _cellSize.cellHeight).ceil();
  241. final offset = widget.terminal.invisibleHeight - charOffset;
  242. widget.terminal.buffer.setScrollOffsetFromBottom(offset);
  243. }
  244. }
  245. class TerminalPainter extends CustomPainter {
  246. TerminalPainter({
  247. required this.terminal,
  248. required this.view,
  249. required this.oscillator,
  250. required this.focused,
  251. required this.charSize,
  252. });
  253. final Terminal terminal;
  254. final TerminalView view;
  255. final Oscillator oscillator;
  256. final bool focused;
  257. final CellSize charSize;
  258. @override
  259. void paint(Canvas canvas, Size size) {
  260. paintBackground(canvas);
  261. // if (oscillator.value) {
  262. // }
  263. if (terminal.showCursor) {
  264. paintCursor(canvas);
  265. }
  266. paintText(canvas);
  267. paintSelection(canvas);
  268. }
  269. void paintBackground(Canvas canvas) {
  270. final lines = terminal.getVisibleLines();
  271. for (var i = 0; i < lines.length; i++) {
  272. final line = lines[i];
  273. final offsetY = i * charSize.cellHeight;
  274. final cellCount = math.min(terminal.viewWidth, line.length);
  275. for (var i = 0; i < cellCount; i++) {
  276. final cell = line.getCell(i);
  277. final attr = cell.attr;
  278. if (attr == null || cell.width == 0) {
  279. continue;
  280. }
  281. final offsetX = i * charSize.cellWidth;
  282. final effectWidth = charSize.cellWidth * cell.width + 1;
  283. final effectHeight = charSize.cellHeight + 1;
  284. final bgColor = attr.inverse ? attr.fgColor : attr.bgColor;
  285. if (bgColor == null) {
  286. continue;
  287. }
  288. final paint = Paint()..color = Color(bgColor.value);
  289. canvas.drawRect(
  290. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  291. paint,
  292. );
  293. }
  294. }
  295. }
  296. void paintSelection(Canvas canvas) {
  297. for (var y = 0; y < terminal.viewHeight; y++) {
  298. final offsetY = y * charSize.cellHeight;
  299. final absoluteY = terminal.buffer.convertViewLineToRawLine(y) -
  300. terminal.buffer.scrollOffsetFromBottom;
  301. for (var x = 0; x < terminal.viewWidth; x++) {
  302. var cellCount = 0;
  303. while (
  304. terminal.selection.contains(Position(x + cellCount, absoluteY)) &&
  305. x + cellCount < terminal.viewWidth) {
  306. cellCount++;
  307. }
  308. if (cellCount == 0) {
  309. continue;
  310. }
  311. final offsetX = x * charSize.cellWidth;
  312. final effectWidth = cellCount * charSize.cellWidth;
  313. final effectHeight = charSize.cellHeight;
  314. final paint = Paint()..color = Colors.white.withOpacity(0.3);
  315. canvas.drawRect(
  316. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  317. paint,
  318. );
  319. x += cellCount;
  320. }
  321. }
  322. }
  323. void paintText(Canvas canvas) {
  324. final lines = terminal.getVisibleLines();
  325. for (var i = 0; i < lines.length; i++) {
  326. final line = lines[i];
  327. final offsetY = i * charSize.cellHeight;
  328. final cellCount = math.min(terminal.viewWidth, line.length);
  329. for (var i = 0; i < cellCount; i++) {
  330. final cell = line.getCell(i);
  331. if (cell.attr == null || cell.width == 0) {
  332. continue;
  333. }
  334. final offsetX = i * charSize.cellWidth;
  335. paintCell(canvas, cell, offsetX, offsetY);
  336. }
  337. }
  338. }
  339. void paintCell(Canvas canvas, Cell cell, double offsetX, double offsetY) {
  340. final attr = cell.attr!;
  341. if (cell.codePoint == null || attr.invisible) {
  342. return;
  343. }
  344. final cellColor = attr.inverse
  345. ? attr.bgColor ?? terminal.theme.background
  346. : attr.fgColor ?? terminal.theme.foreground;
  347. var color = Color(cellColor.value);
  348. if (attr.faint) {
  349. color = color.withOpacity(0.5);
  350. }
  351. final style = (view.style.textStyleProvider != null)
  352. ? view.style.textStyleProvider!(
  353. color: color,
  354. fontWeight: attr.bold ? FontWeight.bold : FontWeight.normal,
  355. fontStyle: attr.italic ? FontStyle.italic : FontStyle.normal,
  356. fontSize: view.style.fontSize,
  357. decoration:
  358. attr.underline ? TextDecoration.underline : TextDecoration.none,
  359. )
  360. : TextStyle(
  361. color: color,
  362. fontWeight: attr.bold ? FontWeight.bold : FontWeight.normal,
  363. fontStyle: attr.italic ? FontStyle.italic : FontStyle.normal,
  364. fontSize: view.style.fontSize,
  365. decoration:
  366. attr.underline ? TextDecoration.underline : TextDecoration.none,
  367. fontFamily: 'monospace',
  368. fontFamilyFallback: view.style.fontFamily);
  369. final span = TextSpan(
  370. text: String.fromCharCode(cell.codePoint!),
  371. // text: codePointCache.getOrConstruct(cell.codePoint),
  372. style: style,
  373. );
  374. // final tp = textLayoutCache.getOrPerformLayout(span);
  375. final tp = textLayoutCacheV2.getOrPerformLayout(
  376. span, hashValues(cell.codePoint, attr));
  377. tp.paint(canvas, Offset(offsetX, offsetY));
  378. }
  379. void paintCursor(Canvas canvas) {
  380. final screenCursorY = terminal.cursorY + terminal.scrollOffset;
  381. if (screenCursorY < 0 || screenCursorY >= terminal.viewHeight) {
  382. return;
  383. }
  384. final char = terminal.buffer.getCellUnderCursor();
  385. final width =
  386. char != null ? charSize.cellWidth * char.width : charSize.cellWidth;
  387. final offsetX = charSize.cellWidth * terminal.cursorX;
  388. final offsetY = charSize.cellHeight * screenCursorY;
  389. final paint = Paint()
  390. ..color = Color(terminal.theme.cursor.value)
  391. ..strokeWidth = focused ? 0.0 : 1.0
  392. ..style = focused ? PaintingStyle.fill : PaintingStyle.stroke;
  393. canvas.drawRect(
  394. Rect.fromLTWH(offsetX, offsetY, width, charSize.cellHeight), paint);
  395. }
  396. @override
  397. bool shouldRepaint(CustomPainter oldDelegate) {
  398. // print('shouldRepaint');
  399. return terminal.dirty;
  400. }
  401. }