terminal_view.dart 15 KB

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