terminal_view.dart 17 KB

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