terminal_view.dart 16 KB

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