terminal_view.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. // print(textLayoutCacheV2.length);
  265. // or paintTextFast(canvas);
  266. paintSelection(canvas);
  267. }
  268. void paintBackground(Canvas canvas) {
  269. final lines = terminal.getVisibleLines();
  270. for (var i = 0; i < lines.length; i++) {
  271. final line = lines[i];
  272. final offsetY = i * charSize.cellHeight;
  273. final cellCount = math.min(terminal.viewWidth, line.length);
  274. for (var i = 0; i < cellCount; i++) {
  275. final cell = line.getCell(i);
  276. if (cell.attr == null || cell.width == 0) {
  277. continue;
  278. }
  279. final offsetX = i * charSize.cellWidth;
  280. final effectWidth = charSize.cellWidth * cell.width + 1;
  281. final effectHeight = charSize.cellHeight + 1;
  282. final bgColor =
  283. cell.attr.inverse ? cell.attr.fgColor : cell.attr.bgColor;
  284. if (bgColor == null) {
  285. continue;
  286. }
  287. final paint = Paint()..color = Color(bgColor.value);
  288. canvas.drawRect(
  289. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  290. paint,
  291. );
  292. }
  293. }
  294. }
  295. void paintSelection(Canvas canvas) {
  296. for (var y = 0; y < terminal.viewHeight; y++) {
  297. final offsetY = y * charSize.cellHeight;
  298. final absoluteY = terminal.buffer.convertViewLineToRawLine(y) -
  299. terminal.buffer.scrollOffsetFromBottom;
  300. for (var x = 0; x < terminal.viewWidth; x++) {
  301. var cellCount = 0;
  302. while (
  303. terminal.selection.contains(Position(x + cellCount, absoluteY)) &&
  304. x + cellCount < terminal.viewWidth) {
  305. cellCount++;
  306. }
  307. if (cellCount == 0) {
  308. continue;
  309. }
  310. final offsetX = x * charSize.cellWidth;
  311. final effectWidth = cellCount * charSize.cellWidth;
  312. final effectHeight = charSize.cellHeight;
  313. final paint = Paint()..color = Colors.white.withOpacity(0.3);
  314. canvas.drawRect(
  315. Rect.fromLTWH(offsetX, offsetY, effectWidth, effectHeight),
  316. paint,
  317. );
  318. x += cellCount;
  319. }
  320. }
  321. }
  322. void paintText(Canvas canvas) {
  323. final lines = terminal.getVisibleLines();
  324. for (var i = 0; i < lines.length; i++) {
  325. final line = lines[i];
  326. final offsetY = i * charSize.cellHeight;
  327. final cellCount = math.min(terminal.viewWidth, line.length);
  328. for (var i = 0; i < cellCount; i++) {
  329. final cell = line.getCell(i);
  330. if (cell.attr == null || cell.width == 0) {
  331. continue;
  332. }
  333. final offsetX = i * charSize.cellWidth;
  334. paintCell(canvas, cell, offsetX, offsetY);
  335. }
  336. }
  337. }
  338. void paintTextFast(Canvas canvas) {
  339. final lines = terminal.getVisibleLines();
  340. for (var i = 0; i < lines.length; i++) {
  341. final line = lines[i];
  342. final offsetY = i * charSize.cellHeight;
  343. final cellCount = math.min(terminal.viewWidth, line.length);
  344. final builder = StringBuffer();
  345. for (var i = 0; i < cellCount; i++) {
  346. final cell = line.getCell(i);
  347. if (cell.attr == null || cell.width == 0) {
  348. continue;
  349. }
  350. if (cell.codePoint == null) {
  351. builder.write(' ');
  352. } else {
  353. builder.writeCharCode(cell.codePoint);
  354. }
  355. // final offsetX = i * charSize.effectWidth;
  356. // paintCell(canvas, cell, offsetX, offsetY);
  357. }
  358. final style = TextStyle(
  359. // color: color,
  360. // fontWeight: cell.attr.bold ? FontWeight.bold : FontWeight.normal,
  361. // fontStyle: cell.attr.italic ? FontStyle.italic : FontStyle.normal,
  362. fontSize: view.style.fontSize,
  363. letterSpacing: charSize.letterSpacing,
  364. fontFeatures: [FontFeature.tabularFigures()],
  365. // decoration:
  366. // cell.attr.underline ? TextDecoration.underline : TextDecoration.none,
  367. fontFamilyFallback: view.style.fontFamily,
  368. );
  369. final span = TextSpan(
  370. text: builder.toString(),
  371. style: style,
  372. );
  373. final tp = textLayoutCache.getOrPerformLayout(span);
  374. tp.paint(canvas, Offset(0, offsetY));
  375. }
  376. }
  377. void paintCell(Canvas canvas, Cell cell, double offsetX, double offsetY) {
  378. if (cell.codePoint == null || cell.attr.invisible) {
  379. return;
  380. }
  381. final cellColor = cell.attr.inverse
  382. ? cell.attr.bgColor ?? terminal.theme.background
  383. : cell.attr.fgColor ?? terminal.theme.foreground;
  384. var color = Color(cellColor.value);
  385. if (cell.attr.faint) {
  386. color = color.withOpacity(0.5);
  387. }
  388. final style = TextStyle(
  389. color: color,
  390. fontWeight: cell.attr.bold ? FontWeight.bold : FontWeight.normal,
  391. fontStyle: cell.attr.italic ? FontStyle.italic : FontStyle.normal,
  392. fontSize: view.style.fontSize,
  393. decoration: cell.attr.underline
  394. ? TextDecoration.underline
  395. : TextDecoration.none,
  396. fontFamily: 'monospace',
  397. fontFamilyFallback: view.style.fontFamily);
  398. final span = TextSpan(
  399. text: String.fromCharCode(cell.codePoint),
  400. // text: codePointCache.getOrConstruct(cell.codePoint),
  401. style: style,
  402. );
  403. // final tp = textLayoutCache.getOrPerformLayout(span);
  404. final tp = textLayoutCacheV2.getOrPerformLayout(
  405. span, hashValues(cell.codePoint, cell.attr));
  406. tp.paint(canvas, Offset(offsetX, offsetY));
  407. }
  408. void paintCursor(Canvas canvas) {
  409. final screenCursorY = terminal.cursorY + terminal.scrollOffset;
  410. if (screenCursorY < 0 || screenCursorY >= terminal.viewHeight) {
  411. return;
  412. }
  413. final char = terminal.buffer.getCellUnderCursor();
  414. final width =
  415. char != null ? charSize.cellWidth * char.width : charSize.cellWidth;
  416. final offsetX = charSize.cellWidth * terminal.cursorX;
  417. final offsetY = charSize.cellHeight * screenCursorY;
  418. final paint = Paint()
  419. ..color = Color(terminal.theme.cursor.value)
  420. ..strokeWidth = focused ? 0.0 : 1.0
  421. ..style = focused ? PaintingStyle.fill : PaintingStyle.stroke;
  422. canvas.drawRect(
  423. Rect.fromLTWH(offsetX, offsetY, width, charSize.cellHeight), paint);
  424. }
  425. @override
  426. bool shouldRepaint(CustomPainter oldDelegate) {
  427. // print('shouldRepaint');
  428. return terminal.dirty;
  429. }
  430. }