terminal_view.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. GlobalKey _keyCursor = GlobalKey();
  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. onWidgetSize(constraints.maxWidth - widget.padding * 2,
  142. constraints.maxHeight - widget.padding * 2);
  143. if (_keyCursor.currentContext != null) {
  144. /// this gets set so that the accent selection menu on MacOS pops up
  145. /// at the right spot
  146. final RenderBox cursorRenderObj =
  147. _keyCursor.currentContext!.findRenderObject() as RenderBox;
  148. final offset = cursorRenderObj.localToGlobal(Offset.zero);
  149. InputListener.of(context)!.setCaretRect(
  150. Rect.fromLTWH(
  151. offset.dx,
  152. offset.dy,
  153. _cellSize.cellWidth,
  154. _cellSize.cellHeight,
  155. ),
  156. );
  157. }
  158. // use flutter's Scrollable to manage scrolling to better integrate
  159. // with widgets such as Scrollbar.
  160. return NotificationListener<ScrollNotification>(
  161. onNotification: (notification) {
  162. onScroll(notification.metrics.pixels);
  163. return false;
  164. },
  165. child: Scrollable(
  166. controller: widget.scrollController,
  167. viewportBuilder: (context, offset) {
  168. final position = widget.scrollController.position;
  169. /// use [_EmptyScrollActivity] to suppress unexpected behaviors
  170. /// that come from [applyViewportDimension].
  171. if (InputBehaviors.platform == InputBehaviors.desktop &&
  172. position is ScrollActivityDelegate) {
  173. position.beginActivity(
  174. _EmptyScrollActivity(position as ScrollActivityDelegate),
  175. );
  176. }
  177. final viewPortHeight =
  178. constraints.maxHeight - widget.padding * 2;
  179. // set viewport height.
  180. offset.applyViewportDimension(viewPortHeight);
  181. if (widget.terminal.isReady) {
  182. final minScrollExtent = 0.0;
  183. final maxScrollExtent = math.max(
  184. 0.0,
  185. _cellSize.cellHeight *
  186. (widget.terminal.bufferHeight -
  187. widget.terminal.terminalHeight));
  188. // set how much the terminal can scroll
  189. offset.applyContentDimensions(
  190. minScrollExtent, maxScrollExtent);
  191. // synchronize pending terminal scroll extent to ScrollController
  192. if (_pendingTerminalScrollExtent != null) {
  193. position.correctPixels(_pendingTerminalScrollExtent!);
  194. _pendingTerminalScrollExtent = null;
  195. }
  196. }
  197. return buildTerminal(context);
  198. },
  199. ),
  200. );
  201. }),
  202. ),
  203. );
  204. }
  205. Widget buildTerminal(BuildContext context) {
  206. return GestureDetector(
  207. behavior: HitTestBehavior.deferToChild,
  208. dragStartBehavior: DragStartBehavior.down,
  209. onDoubleTapDown: (detail) {
  210. final pos = detail.localPosition;
  211. _tapPosition = getMouseOffset(pos.dx, pos.dy);
  212. },
  213. onTapDown: (detail) {
  214. final pos = detail.localPosition;
  215. _tapPosition = getMouseOffset(pos.dx, pos.dy);
  216. },
  217. onDoubleTap: () {
  218. if (_tapPosition != null) {
  219. widget.terminal.onMouseDoubleTap(_tapPosition!);
  220. widget.terminal.refresh();
  221. }
  222. },
  223. onTap: () {
  224. if (widget.terminal.selection?.isEmpty ?? true) {
  225. InputListener.of(context)!.requestKeyboard();
  226. } else {
  227. widget.terminal.clearSelection();
  228. }
  229. if (_tapPosition != null) {
  230. widget.terminal.onMouseTap(_tapPosition!);
  231. widget.terminal.refresh();
  232. }
  233. },
  234. onPanStart: (detail) {
  235. final pos = detail.localPosition;
  236. final offset = getMouseOffset(pos.dx, pos.dy);
  237. widget.terminal.onPanStart(offset);
  238. widget.terminal.refresh();
  239. },
  240. onPanUpdate: (detail) {
  241. final pos = detail.localPosition;
  242. final offset = getMouseOffset(pos.dx, pos.dy);
  243. widget.terminal.onPanUpdate(offset);
  244. widget.terminal.refresh();
  245. },
  246. child: Container(
  247. constraints: BoxConstraints.expand(),
  248. child: Padding(
  249. padding: EdgeInsets.all(widget.padding),
  250. child: Stack(
  251. children: <Widget>[
  252. CustomPaint(
  253. painter: TerminalPainter(
  254. terminal: widget.terminal,
  255. style: widget.style,
  256. charSize: _cellSize,
  257. textLayoutCache: textLayoutCache,
  258. ),
  259. ),
  260. Positioned(
  261. key: _keyCursor,
  262. child: CursorView(
  263. terminal: widget.terminal,
  264. cellSize: _cellSize,
  265. focusNode: widget.focusNode,
  266. blinkOscillator: blinkOscillator,
  267. style: widget.style,
  268. textLayoutCache: textLayoutCache,
  269. ),
  270. width: _cellSize.cellWidth,
  271. height: _cellSize.cellHeight,
  272. left: _getCursorOffset().dx,
  273. top: _getCursorOffset().dy,
  274. ),
  275. ],
  276. ),
  277. ),
  278. color: Color(widget.terminal.backgroundColor).withOpacity(
  279. widget.opacity,
  280. ),
  281. ),
  282. );
  283. }
  284. Offset _getCursorOffset() {
  285. final screenCursorY = widget.terminal.cursorY;
  286. final offsetX = _cellSize.cellWidth * widget.terminal.cursorX;
  287. final offsetY = _cellSize.cellHeight * screenCursorY;
  288. return Offset(offsetX, offsetY);
  289. }
  290. /// Get global cell position from mouse position.
  291. Position getMouseOffset(double px, double py) {
  292. final col = ((px - widget.padding) / _cellSize.cellWidth).floor();
  293. final row = ((py - widget.padding) / _cellSize.cellHeight).floor();
  294. final x = col;
  295. final y = widget.terminal.convertViewLineToRawLine(row) -
  296. widget.terminal.scrollOffsetFromBottom;
  297. return Position(x, y);
  298. }
  299. double? _width;
  300. double? _height;
  301. void onWidgetSize(double width, double height) {
  302. if (!widget.terminal.isReady) {
  303. return;
  304. }
  305. _width = width;
  306. _height = height;
  307. updateTerminalSize();
  308. }
  309. int? _lastTerminalWidth;
  310. int? _lastTerminalHeight;
  311. void updateTerminalSize() {
  312. assert(_width != null);
  313. assert(_height != null);
  314. final termWidth = (_width! / _cellSize.cellWidth).floor();
  315. final termHeight = (_height! / _cellSize.cellHeight).floor();
  316. if (_lastTerminalWidth == termWidth && _lastTerminalHeight == termHeight) {
  317. return;
  318. }
  319. _lastTerminalWidth = termWidth;
  320. _lastTerminalHeight = termHeight;
  321. widget.terminal.resize(
  322. termWidth,
  323. termHeight,
  324. (termWidth * _cellSize.cellWidth).floor(),
  325. (termHeight * _cellSize.cellHeight).floor(),
  326. );
  327. }
  328. TextEditingValue? onInput(TextEditingValue value) {
  329. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  330. }
  331. void onKeyStroke(RawKeyEvent event) {
  332. blinkOscillator.restart();
  333. // TODO: find a way to stop scrolling immediately after key stroke.
  334. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  335. widget.terminal.setScrollOffsetFromBottom(0);
  336. }
  337. void onFocus(bool focused) {
  338. SchedulerBinding.instance!.addPostFrameCallback((_) {
  339. widget.terminal.refresh();
  340. });
  341. }
  342. void onAction(TextInputAction action) {
  343. widget.inputBehavior.onAction(action, widget.terminal);
  344. }
  345. // synchronize flutter scroll offset to terminal
  346. void onScroll(double offset) {
  347. final topOffset = (offset / _cellSize.cellHeight).ceil();
  348. final bottomOffset = widget.terminal.invisibleHeight - topOffset;
  349. widget.terminal.setScrollOffsetFromBottom(bottomOffset);
  350. }
  351. }
  352. class CursorView extends StatefulWidget {
  353. final CellSize cellSize;
  354. final TerminalUiInteraction terminal;
  355. final FocusNode? focusNode;
  356. final Oscillator blinkOscillator;
  357. final TerminalStyle style;
  358. final TextLayoutCache textLayoutCache;
  359. CursorView({
  360. required this.terminal,
  361. required this.cellSize,
  362. required this.focusNode,
  363. required this.blinkOscillator,
  364. required this.style,
  365. required this.textLayoutCache,
  366. });
  367. @override
  368. State<StatefulWidget> createState() => _CursorViewState();
  369. }
  370. class _CursorViewState extends State<CursorView> {
  371. bool get focused {
  372. return widget.focusNode?.hasFocus ?? false;
  373. }
  374. var _isOscillatorCallbackRegistered = false;
  375. @override
  376. void initState() {
  377. _isOscillatorCallbackRegistered = true;
  378. widget.blinkOscillator.addListener(onOscillatorTick);
  379. widget.terminal.addListener(onTerminalChange);
  380. super.initState();
  381. }
  382. @override
  383. Widget build(BuildContext context) {
  384. return CustomPaint(
  385. painter: CursorPainter(
  386. visible: _isCursorVisible(),
  387. focused: focused,
  388. charSize: widget.cellSize,
  389. blinkVisible: widget.blinkOscillator.value,
  390. cursorColor: widget.terminal.cursorColor,
  391. textColor: widget.terminal.backgroundColor,
  392. style: widget.style,
  393. composingString: widget.terminal.composingString,
  394. textLayoutCache: widget.textLayoutCache,
  395. ),
  396. );
  397. }
  398. bool _isCursorVisible() {
  399. final screenCursorY =
  400. widget.terminal.cursorY + widget.terminal.scrollOffsetFromBottom;
  401. if (screenCursorY < 0 || screenCursorY >= widget.terminal.terminalHeight) {
  402. return false;
  403. }
  404. return widget.terminal.showCursor;
  405. }
  406. @override
  407. void dispose() {
  408. widget.terminal.removeListener(onTerminalChange);
  409. widget.blinkOscillator.removeListener(onOscillatorTick);
  410. super.dispose();
  411. }
  412. void onTerminalChange() {
  413. if (!mounted) {
  414. return;
  415. }
  416. setState(() {
  417. if (_isCursorVisible() /*&& widget.terminal.blinkingCursor*/ && focused) {
  418. if (!_isOscillatorCallbackRegistered) {
  419. _isOscillatorCallbackRegistered = true;
  420. widget.blinkOscillator.addListener(onOscillatorTick);
  421. }
  422. } else {
  423. if (_isOscillatorCallbackRegistered) {
  424. _isOscillatorCallbackRegistered = false;
  425. widget.blinkOscillator.removeListener(onOscillatorTick);
  426. }
  427. }
  428. });
  429. }
  430. void onOscillatorTick() {
  431. setState(() {});
  432. }
  433. }
  434. /// A scroll activity that does nothing. Used to suppress unexpected behaviors
  435. /// from [Scrollable] during viewport building process.
  436. class _EmptyScrollActivity extends IdleScrollActivity {
  437. _EmptyScrollActivity(ScrollActivityDelegate delegate) : super(delegate);
  438. @override
  439. void applyNewDimensions() {}
  440. /// set [isScrolling] to ture to prevent flutter from calling the old scroll
  441. /// activity.
  442. @override
  443. final isScrolling = true;
  444. void dispatchScrollStartNotification(
  445. ScrollMetrics metrics, BuildContext? context) {}
  446. void dispatchScrollUpdateNotification(
  447. ScrollMetrics metrics, BuildContext context, double scrollDelta) {}
  448. void dispatchOverscrollNotification(
  449. ScrollMetrics metrics, BuildContext context, double overscroll) {}
  450. void dispatchScrollEndNotification(
  451. ScrollMetrics metrics, BuildContext context) {}
  452. }