terminal_view.dart 16 KB

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