terminal_view.dart 16 KB

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