terminal_view.dart 16 KB

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