terminal_view.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. child: MouseRegion(
  128. cursor: SystemMouseCursors.text,
  129. child: LayoutBuilder(builder: (context, constraints) {
  130. onResize(constraints.maxWidth, constraints.maxHeight);
  131. return Scrollable(
  132. viewportBuilder: (context, offset) {
  133. offset.applyViewportDimension(constraints.maxHeight);
  134. _minScrollExtent = 0.0;
  135. _maxScrollExtent = math.max(
  136. 0.0,
  137. _cellSize.cellHeight * widget.terminal.buffer.height -
  138. constraints.maxHeight);
  139. // final currentScrollExtent = _cellSize.cellHeight *
  140. // widget.terminal.buffer.scrollOffsetFromTop;
  141. // offset.correctBy(currentScrollExtent - offset.pixels - 1);
  142. offset.applyContentDimensions(_minScrollExtent, _maxScrollExtent);
  143. _offset = offset;
  144. _offset.addListener(onScroll);
  145. return buildTerminal(context);
  146. },
  147. );
  148. }),
  149. ),
  150. );
  151. }
  152. Widget buildTerminal(BuildContext context) {
  153. return GestureDetector(
  154. behavior: HitTestBehavior.deferToChild,
  155. dragStartBehavior: DragStartBehavior.down,
  156. onTapDown: (detail) {
  157. if (widget.terminal.selection.isEmpty) {
  158. InputListener.of(context).requestKeyboard();
  159. } else {
  160. widget.terminal.selection.clear();
  161. }
  162. final pos = detail.localPosition;
  163. final offset = getMouseOffset(pos.dx, pos.dy);
  164. widget.terminal.mouseMode.onTap(widget.terminal, offset);
  165. widget.terminal.refresh();
  166. },
  167. onPanStart: (detail) {
  168. final pos = detail.localPosition;
  169. final offset = getMouseOffset(pos.dx, pos.dy);
  170. widget.terminal.mouseMode.onPanStart(widget.terminal, offset);
  171. widget.terminal.refresh();
  172. },
  173. onPanUpdate: (detail) {
  174. final pos = detail.localPosition;
  175. final offset = getMouseOffset(pos.dx, pos.dy);
  176. widget.terminal.mouseMode.onPanUpdate(widget.terminal, offset);
  177. widget.terminal.refresh();
  178. },
  179. child: Container(
  180. constraints: BoxConstraints.expand(),
  181. color: Color(widget.terminal.theme.background.value),
  182. child: CustomPaint(
  183. painter: TerminalPainter(
  184. terminal: widget.terminal,
  185. view: widget,
  186. oscillator: oscillator,
  187. focused: focused,
  188. charSize: _cellSize,
  189. ),
  190. ),
  191. ),
  192. );
  193. }
  194. Position getMouseOffset(double px, double py) {
  195. final col = (px / _cellSize.cellWidth).floor();
  196. final row = (py / _cellSize.cellHeight).floor();
  197. final x = col;
  198. final y = widget.terminal.buffer.convertViewLineToRawLine(row) -
  199. widget.terminal.buffer.scrollOffsetFromBottom;
  200. return Position(x, y);
  201. }
  202. void onResize(double width, double height) {
  203. final termWidth = (width / _cellSize.cellWidth).floor();
  204. final termHeight = (height / _cellSize.cellHeight).floor();
  205. if (_lastTerminalWidth != termWidth || _lastTerminalHeight != termHeight) {
  206. _lastTerminalWidth = termWidth;
  207. _lastTerminalHeight = termHeight;
  208. // print('($termWidth, $termHeight)');
  209. if (widget.onResize != null) {
  210. widget.onResize(termWidth, termHeight);
  211. }
  212. SchedulerBinding.instance.addPostFrameCallback((_) {
  213. widget.terminal.resize(termWidth, termHeight);
  214. });
  215. // Future.delayed(Duration.zero).then((_) {
  216. // widget.terminal.resize(termWidth, termHeight);
  217. // });
  218. }
  219. }
  220. TextEditingValue onInput(TextEditingValue value) {
  221. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  222. }
  223. void onKeyStroke(RawKeyEvent event) {
  224. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  225. _offset.moveTo(_maxScrollExtent);
  226. }
  227. void onFocus(bool focused) {
  228. SchedulerBinding.instance.addPostFrameCallback((_) {
  229. widget.terminal.refresh();
  230. });
  231. }
  232. void onAction(TextInputAction action) {
  233. widget.inputBehavior.onAction(action, widget.terminal);
  234. }
  235. void onScroll() {
  236. final charOffset = (_offset.pixels / _cellSize.cellHeight).ceil();
  237. final offset = widget.terminal.invisibleHeight - charOffset;
  238. widget.terminal.buffer.setScrollOffsetFromBottom(offset);
  239. }
  240. }
  241. class TerminalPainter extends CustomPainter {
  242. TerminalPainter({
  243. this.terminal,
  244. this.view,
  245. this.oscillator,
  246. this.focused,
  247. this.charSize,
  248. });
  249. final Terminal terminal;
  250. final TerminalView view;
  251. final Oscillator oscillator;
  252. final bool focused;
  253. final CellSize charSize;
  254. @override
  255. void paint(Canvas canvas, Size size) {
  256. paintBackground(canvas);
  257. // if (oscillator.value) {
  258. // }
  259. if (terminal.showCursor) {
  260. paintCursor(canvas);
  261. }
  262. paintText(canvas);
  263. // print(textLayoutCacheV2.length);
  264. // or paintTextFast(canvas);
  265. paintSelection(canvas);
  266. }
  267. void paintBackground(Canvas canvas) {
  268. final lines = terminal.getVisibleLines();
  269. for (var i = 0; i < lines.length; i++) {
  270. final line = lines[i];
  271. final offsetY = i * charSize.cellHeight;
  272. final cellCount = math.min(terminal.viewWidth, line.length);
  273. for (var i = 0; i < cellCount; i++) {
  274. final cell = line.getCell(i);
  275. if (cell.attr == null || cell.width == 0) {
  276. continue;
  277. }
  278. final offsetX = i * charSize.cellWidth;
  279. final effectWidth = charSize.cellWidth * cell.width + 1;
  280. final effectHeight = charSize.cellHeight + 1;
  281. final bgColor =
  282. cell.attr.inverse ? cell.attr.fgColor : cell.attr.bgColor;
  283. if (bgColor == null) {
  284. continue;
  285. }
  286. final paint = Paint()..color = Color(bgColor.value);
  287. canvas.drawRect(
  288. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  289. paint,
  290. );
  291. }
  292. }
  293. }
  294. void paintSelection(Canvas canvas) {
  295. for (var y = 0; y < terminal.viewHeight; y++) {
  296. final offsetY = y * charSize.cellHeight;
  297. final absoluteY = terminal.buffer.convertViewLineToRawLine(y) -
  298. terminal.buffer.scrollOffsetFromBottom;
  299. for (var x = 0; x < terminal.viewWidth; x++) {
  300. var cellCount = 0;
  301. while (
  302. terminal.selection.contains(Position(x + cellCount, absoluteY)) &&
  303. x + cellCount < terminal.viewWidth) {
  304. cellCount++;
  305. }
  306. if (cellCount == 0) {
  307. continue;
  308. }
  309. final offsetX = x * charSize.cellWidth;
  310. final effectWidth = cellCount * charSize.cellWidth;
  311. final effectHeight = charSize.cellHeight;
  312. final paint = Paint()..color = Colors.white.withOpacity(0.3);
  313. canvas.drawRect(
  314. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  315. paint,
  316. );
  317. x += cellCount;
  318. }
  319. }
  320. }
  321. void paintText(Canvas canvas) {
  322. final lines = terminal.getVisibleLines();
  323. for (var i = 0; i < lines.length; i++) {
  324. final line = lines[i];
  325. final offsetY = i * charSize.cellHeight;
  326. final cellCount = math.min(terminal.viewWidth, line.length);
  327. for (var i = 0; i < cellCount; i++) {
  328. final cell = line.getCell(i);
  329. if (cell.attr == null || cell.width == 0) {
  330. continue;
  331. }
  332. final offsetX = i * charSize.cellWidth;
  333. paintCell(canvas, cell, offsetX, offsetY);
  334. }
  335. }
  336. }
  337. void paintTextFast(Canvas canvas) {
  338. final lines = terminal.getVisibleLines();
  339. for (var i = 0; i < lines.length; i++) {
  340. final line = lines[i];
  341. final offsetY = i * charSize.cellHeight;
  342. final cellCount = math.min(terminal.viewWidth, line.length);
  343. final builder = StringBuffer();
  344. for (var i = 0; i < cellCount; i++) {
  345. final cell = line.getCell(i);
  346. if (cell.attr == null || cell.width == 0) {
  347. continue;
  348. }
  349. if (cell.codePoint == null) {
  350. builder.write(' ');
  351. } else {
  352. builder.writeCharCode(cell.codePoint);
  353. }
  354. // final offsetX = i * charSize.effectWidth;
  355. // paintCell(canvas, cell, offsetX, offsetY);
  356. }
  357. final style = TextStyle(
  358. // color: color,
  359. // fontWeight: cell.attr.bold ? FontWeight.bold : FontWeight.normal,
  360. // fontStyle: cell.attr.italic ? FontStyle.italic : FontStyle.normal,
  361. fontSize: view.style.fontSize,
  362. letterSpacing: charSize.letterSpacing,
  363. fontFeatures: [FontFeature.tabularFigures()],
  364. // decoration:
  365. // cell.attr.underline ? TextDecoration.underline : TextDecoration.none,
  366. fontFamilyFallback: view.style.fontFamily,
  367. );
  368. final span = TextSpan(
  369. text: builder.toString(),
  370. style: style,
  371. );
  372. final tp = textLayoutCache.getOrPerformLayout(span);
  373. tp.paint(canvas, Offset(0, offsetY));
  374. }
  375. }
  376. void paintCell(Canvas canvas, Cell cell, double offsetX, double offsetY) {
  377. if (cell.codePoint == null || cell.attr.invisible) {
  378. return;
  379. }
  380. final cellColor = cell.attr.inverse
  381. ? cell.attr.bgColor ?? terminal.theme.background
  382. : cell.attr.fgColor ?? terminal.theme.foreground;
  383. var color = Color(cellColor.value);
  384. if (cell.attr.faint) {
  385. color = color.withOpacity(0.5);
  386. }
  387. final style = TextStyle(
  388. color: color,
  389. fontWeight: cell.attr.bold ? FontWeight.bold : FontWeight.normal,
  390. fontStyle: cell.attr.italic ? FontStyle.italic : FontStyle.normal,
  391. fontSize: view.style.fontSize,
  392. decoration: cell.attr.underline
  393. ? TextDecoration.underline
  394. : TextDecoration.none,
  395. fontFamily: 'monospace',
  396. fontFamilyFallback: view.style.fontFamily);
  397. final span = TextSpan(
  398. text: String.fromCharCode(cell.codePoint),
  399. // text: codePointCache.getOrConstruct(cell.codePoint),
  400. style: style,
  401. );
  402. // final tp = textLayoutCache.getOrPerformLayout(span);
  403. final tp = textLayoutCacheV2.getOrPerformLayout(
  404. span, hashValues(cell.codePoint, cell.attr));
  405. tp.paint(canvas, Offset(offsetX, offsetY));
  406. }
  407. void paintCursor(Canvas canvas) {
  408. final screenCursorY = terminal.cursorY + terminal.scrollOffset;
  409. if (screenCursorY < 0 || screenCursorY >= terminal.viewHeight) {
  410. return;
  411. }
  412. final char = terminal.buffer.getCellUnderCursor();
  413. final width =
  414. char != null ? charSize.cellWidth * char.width : charSize.cellWidth;
  415. final offsetX = charSize.cellWidth * terminal.cursorX;
  416. final offsetY = charSize.cellHeight * screenCursorY;
  417. final paint = Paint()
  418. ..color = Color(terminal.theme.cursor.value)
  419. ..strokeWidth = focused ? 0.0 : 1.0
  420. ..style = focused ? PaintingStyle.fill : PaintingStyle.stroke;
  421. canvas.drawRect(
  422. Rect.fromLTWH(offsetX, offsetY, width, charSize.cellHeight), paint);
  423. }
  424. @override
  425. bool shouldRepaint(CustomPainter oldDelegate) {
  426. // print('shouldRepaint');
  427. return terminal.dirty;
  428. }
  429. }