terminal_view.dart 13 KB

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