terminal_view.dart 15 KB

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