terminal_view.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import 'dart:math' as math;
  2. import 'dart:ui';
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/gestures.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/rendering.dart';
  7. import 'package:flutter/scheduler.dart';
  8. import 'package:flutter/services.dart';
  9. import 'package:xterm/frontend/cache.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/terminal_painters.dart';
  17. import 'package:xterm/mouse/position.dart';
  18. import 'package:xterm/terminal/terminal_ui_interaction.dart';
  19. import 'package:xterm/theme/terminal_style.dart';
  20. class TerminalView extends StatefulWidget {
  21. TerminalView({
  22. Key? key,
  23. required this.terminal,
  24. this.style = const TerminalStyle(),
  25. this.opacity = 1.0,
  26. FocusNode? focusNode,
  27. this.autofocus = false,
  28. ScrollController? scrollController,
  29. InputBehavior? inputBehavior,
  30. this.padding = 0.0,
  31. }) : focusNode = focusNode ?? FocusNode(),
  32. scrollController = scrollController ?? ScrollController(),
  33. inputBehavior = inputBehavior ?? InputBehaviors.platform,
  34. super(key: key ?? ValueKey(terminal));
  35. final TerminalUiInteraction terminal;
  36. final FocusNode focusNode;
  37. final bool autofocus;
  38. final ScrollController scrollController;
  39. final TerminalStyle style;
  40. final double opacity;
  41. final double padding;
  42. final InputBehavior inputBehavior;
  43. // get the dimensions of a rendered character
  44. CellSize measureCellSize(double fontSize) {
  45. final testString = 'xxxxxxxxxx' * 1000;
  46. final text = Text(
  47. testString,
  48. maxLines: 1,
  49. style: (style.textStyleProvider != null)
  50. ? style.textStyleProvider!(
  51. fontSize: fontSize,
  52. )
  53. : TextStyle(
  54. fontFamily: 'monospace',
  55. fontFamilyFallback: style.fontFamily,
  56. fontSize: 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 blinkOscillator = Oscillator.ms(600);
  79. final textLayoutCache = TextLayoutCache(TextDirection.ltr, 10240);
  80. bool get focused {
  81. return widget.focusNode.hasFocus;
  82. }
  83. late CellSize _cellSize;
  84. Position? _tapPosition;
  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? _pendingTerminalScrollExtent;
  88. void onTerminalChange() {
  89. _pendingTerminalScrollExtent =
  90. _cellSize.cellHeight * widget.terminal.scrollOffsetFromTop;
  91. if (mounted) {
  92. setState(() {});
  93. }
  94. }
  95. // listen to oscillator to update mouse blink etc.
  96. // void onTick() {
  97. // widget.terminal.refresh();
  98. // }
  99. @override
  100. void initState() {
  101. blinkOscillator.start();
  102. // oscillator.addListener(onTick);
  103. // measureCellSize is expensive so we cache the result.
  104. _cellSize = widget.measureCellSize(widget.style.fontSize);
  105. widget.terminal.addListener(onTerminalChange);
  106. super.initState();
  107. }
  108. @override
  109. void didUpdateWidget(TerminalView oldWidget) {
  110. oldWidget.terminal.removeListener(onTerminalChange);
  111. widget.terminal.addListener(onTerminalChange);
  112. if (oldWidget.style != widget.style) {
  113. _cellSize = widget.measureCellSize(widget.style.fontSize);
  114. textLayoutCache.clear();
  115. updateTerminalSize();
  116. }
  117. super.didUpdateWidget(oldWidget);
  118. }
  119. @override
  120. void dispose() {
  121. blinkOscillator.stop();
  122. // oscillator.removeListener(onTick);
  123. widget.terminal.removeListener(onTerminalChange);
  124. super.dispose();
  125. }
  126. @override
  127. Widget build(BuildContext context) {
  128. return InputListener(
  129. listenKeyStroke: widget.inputBehavior.acceptKeyStroke,
  130. onKeyStroke: onKeyStroke,
  131. onTextInput: onInput,
  132. onAction: onAction,
  133. onFocus: onFocus,
  134. focusNode: widget.focusNode,
  135. autofocus: widget.autofocus,
  136. initEditingState: widget.inputBehavior.initEditingState,
  137. child: MouseRegion(
  138. cursor: SystemMouseCursors.text,
  139. child: LayoutBuilder(builder: (context, constraints) {
  140. onWidgetSize(constraints.maxWidth - widget.padding * 2,
  141. constraints.maxHeight - widget.padding * 2);
  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. final position = widget.scrollController.position;
  153. /// use [_EmptyScrollActivity] to suppress unexpected behaviors
  154. /// that come from [applyViewportDimension].
  155. if (position is ScrollActivityDelegate) {
  156. position.beginActivity(
  157. _EmptyScrollActivity(position as ScrollActivityDelegate),
  158. );
  159. }
  160. final viewPortHeight =
  161. constraints.maxHeight - widget.padding * 2;
  162. // set viewport height.
  163. offset.applyViewportDimension(viewPortHeight);
  164. if (widget.terminal.isReady) {
  165. final minScrollExtent = 0.0;
  166. final maxScrollExtent = math.max(
  167. 0.0,
  168. _cellSize.cellHeight *
  169. (widget.terminal.bufferHeight -
  170. widget.terminal.terminalHeight));
  171. // set how much the terminal can scroll
  172. offset.applyContentDimensions(
  173. minScrollExtent, maxScrollExtent);
  174. // synchronize pending terminal scroll extent to ScrollController
  175. if (_pendingTerminalScrollExtent != null) {
  176. position.correctPixels(_pendingTerminalScrollExtent!);
  177. _pendingTerminalScrollExtent = null;
  178. }
  179. }
  180. return buildTerminal(context);
  181. },
  182. ),
  183. );
  184. }),
  185. ),
  186. );
  187. }
  188. Widget buildTerminal(BuildContext context) {
  189. return GestureDetector(
  190. behavior: HitTestBehavior.deferToChild,
  191. dragStartBehavior: DragStartBehavior.down,
  192. onDoubleTapDown: (detail) {
  193. final pos = detail.localPosition;
  194. _tapPosition = getMouseOffset(pos.dx, pos.dy);
  195. },
  196. onTapDown: (detail) {
  197. final pos = detail.localPosition;
  198. _tapPosition = getMouseOffset(pos.dx, pos.dy);
  199. },
  200. onDoubleTap: () {
  201. if (_tapPosition != null) {
  202. widget.terminal.onMouseDoubleTap(_tapPosition!);
  203. widget.terminal.refresh();
  204. }
  205. },
  206. onTap: () {
  207. if (widget.terminal.selection?.isEmpty ?? true) {
  208. InputListener.of(context)!.requestKeyboard();
  209. } else {
  210. widget.terminal.clearSelection();
  211. }
  212. if (_tapPosition != null) {
  213. widget.terminal.onMouseTap(_tapPosition!);
  214. widget.terminal.refresh();
  215. }
  216. },
  217. onPanStart: (detail) {
  218. final pos = detail.localPosition;
  219. final offset = getMouseOffset(pos.dx, pos.dy);
  220. widget.terminal.onPanStart(offset);
  221. widget.terminal.refresh();
  222. },
  223. onPanUpdate: (detail) {
  224. final pos = detail.localPosition;
  225. final offset = getMouseOffset(pos.dx, pos.dy);
  226. widget.terminal.onPanUpdate(offset);
  227. widget.terminal.refresh();
  228. },
  229. child: Container(
  230. constraints: BoxConstraints.expand(),
  231. child: Padding(
  232. padding: EdgeInsets.all(widget.padding),
  233. child: Stack(
  234. children: <Widget>[
  235. CustomPaint(
  236. painter: TerminalPainter(
  237. terminal: widget.terminal,
  238. style: widget.style,
  239. charSize: _cellSize,
  240. textLayoutCache: textLayoutCache,
  241. ),
  242. ),
  243. Positioned(
  244. child: CursorView(
  245. terminal: widget.terminal,
  246. cellSize: _cellSize,
  247. focusNode: widget.focusNode,
  248. blinkOscillator: blinkOscillator,
  249. ),
  250. width: _cellSize.cellWidth,
  251. height: _cellSize.cellHeight,
  252. left: _getCursorOffset().dx,
  253. top: _getCursorOffset().dy,
  254. ),
  255. ],
  256. ),
  257. ),
  258. color: Color(widget.terminal.backgroundColor).withOpacity(
  259. widget.opacity,
  260. ),
  261. ),
  262. );
  263. }
  264. Offset _getCursorOffset() {
  265. final screenCursorY = widget.terminal.cursorY;
  266. final offsetX = _cellSize.cellWidth * widget.terminal.cursorX;
  267. final offsetY = _cellSize.cellHeight * screenCursorY;
  268. return Offset(offsetX, offsetY);
  269. }
  270. /// Get global cell position from mouse position.
  271. Position getMouseOffset(double px, double py) {
  272. final col = ((px - widget.padding) / _cellSize.cellWidth).floor();
  273. final row = ((py - widget.padding) / _cellSize.cellHeight).floor();
  274. final x = col;
  275. final y = widget.terminal.convertViewLineToRawLine(row) -
  276. widget.terminal.scrollOffsetFromBottom;
  277. return Position(x, y);
  278. }
  279. double? _width;
  280. double? _height;
  281. void onWidgetSize(double width, double height) {
  282. if (!widget.terminal.isReady) {
  283. return;
  284. }
  285. _width = width;
  286. _height = height;
  287. updateTerminalSize();
  288. }
  289. int? _lastTerminalWidth;
  290. int? _lastTerminalHeight;
  291. void updateTerminalSize() {
  292. assert(_width != null);
  293. assert(_height != null);
  294. final termWidth = (_width! / _cellSize.cellWidth).floor();
  295. final termHeight = (_height! / _cellSize.cellHeight).floor();
  296. if (_lastTerminalWidth == termWidth && _lastTerminalHeight == termHeight) {
  297. return;
  298. }
  299. _lastTerminalWidth = termWidth;
  300. _lastTerminalHeight = termHeight;
  301. widget.terminal.resize(
  302. termWidth,
  303. termHeight,
  304. (termWidth * _cellSize.cellWidth).floor(),
  305. (termHeight * _cellSize.cellHeight).floor(),
  306. );
  307. }
  308. TextEditingValue? onInput(TextEditingValue value) {
  309. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  310. }
  311. void onKeyStroke(RawKeyEvent event) {
  312. // TODO: find a way to stop scrolling immediately after key stroke.
  313. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  314. widget.terminal.setScrollOffsetFromBottom(0);
  315. }
  316. void onFocus(bool focused) {
  317. SchedulerBinding.instance!.addPostFrameCallback((_) {
  318. widget.terminal.refresh();
  319. });
  320. }
  321. void onAction(TextInputAction action) {
  322. widget.inputBehavior.onAction(action, widget.terminal);
  323. }
  324. // synchronize flutter scroll offset to terminal
  325. void onScroll(double offset) {
  326. final topOffset = (offset / _cellSize.cellHeight).ceil();
  327. final bottomOffset = widget.terminal.invisibleHeight - topOffset;
  328. widget.terminal.setScrollOffsetFromBottom(bottomOffset);
  329. }
  330. }
  331. class CursorView extends StatefulWidget {
  332. final CellSize cellSize;
  333. final TerminalUiInteraction terminal;
  334. final FocusNode? focusNode;
  335. final Oscillator blinkOscillator;
  336. CursorView({
  337. required this.terminal,
  338. required this.cellSize,
  339. required this.focusNode,
  340. required this.blinkOscillator,
  341. });
  342. @override
  343. State<StatefulWidget> createState() => _CursorViewState();
  344. }
  345. class _CursorViewState extends State<CursorView> {
  346. bool get focused {
  347. return widget.focusNode?.hasFocus ?? false;
  348. }
  349. var _isOscillatorCallbackRegistered = false;
  350. @override
  351. void initState() {
  352. _isOscillatorCallbackRegistered = true;
  353. widget.blinkOscillator.addListener(onOscillatorTick);
  354. widget.terminal.addListener(onTerminalChange);
  355. super.initState();
  356. }
  357. @override
  358. Widget build(BuildContext context) {
  359. return CustomPaint(
  360. painter: CursorPainter(
  361. visible: _isCursorVisible(),
  362. focused: focused,
  363. charSize: widget.cellSize,
  364. blinkVisible: widget.blinkOscillator.value,
  365. cursorColor: widget.terminal.cursorColor,
  366. ),
  367. );
  368. }
  369. bool _isCursorVisible() {
  370. final screenCursorY =
  371. widget.terminal.cursorY + widget.terminal.scrollOffsetFromBottom;
  372. if (screenCursorY < 0 || screenCursorY >= widget.terminal.terminalHeight) {
  373. return false;
  374. }
  375. return widget.terminal.showCursor;
  376. }
  377. @override
  378. void dispose() {
  379. widget.terminal.removeListener(onTerminalChange);
  380. widget.blinkOscillator.removeListener(onOscillatorTick);
  381. super.dispose();
  382. }
  383. void onTerminalChange() {
  384. if (!mounted) {
  385. return;
  386. }
  387. setState(() {
  388. if (_isCursorVisible() /*&& widget.terminal.blinkingCursor*/ && focused) {
  389. if (!_isOscillatorCallbackRegistered) {
  390. _isOscillatorCallbackRegistered = true;
  391. widget.blinkOscillator.addListener(onOscillatorTick);
  392. }
  393. } else {
  394. if (_isOscillatorCallbackRegistered) {
  395. _isOscillatorCallbackRegistered = false;
  396. widget.blinkOscillator.removeListener(onOscillatorTick);
  397. }
  398. }
  399. });
  400. }
  401. void onOscillatorTick() {
  402. setState(() {});
  403. }
  404. }
  405. /// A scroll activity that does nothing. Used to suppress unexpected behaviors
  406. /// from [Scrollable] during viewport building process.
  407. class _EmptyScrollActivity extends IdleScrollActivity {
  408. _EmptyScrollActivity(ScrollActivityDelegate delegate) : super(delegate);
  409. @override
  410. void applyNewDimensions() {}
  411. /// set [isScrolling] to ture to prevent flutter from calling the old scroll
  412. /// activity.
  413. @override
  414. final isScrolling = true;
  415. void dispatchScrollStartNotification(
  416. ScrollMetrics metrics, BuildContext? context) {}
  417. void dispatchScrollUpdateNotification(
  418. ScrollMetrics metrics, BuildContext context, double scrollDelta) {}
  419. void dispatchOverscrollNotification(
  420. ScrollMetrics metrics, BuildContext context, double overscroll) {}
  421. void dispatchScrollEndNotification(
  422. ScrollMetrics metrics, BuildContext context) {}
  423. }