terminal_view.dart 15 KB

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