terminal_view.dart 14 KB

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