terminal_view.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. child: Container(), //to get the size
  266. ),
  267. Positioned(
  268. key: _keyCursor,
  269. child: CursorView(
  270. terminal: widget.terminal,
  271. cellSize: _cellSize,
  272. focusNode: widget.focusNode,
  273. blinkOscillator: blinkOscillator,
  274. style: widget.style,
  275. textLayoutCache: textLayoutCache,
  276. ),
  277. width: _cellSize.cellWidth,
  278. height: _cellSize.cellHeight,
  279. left: _getCursorOffset().dx,
  280. top: _getCursorOffset().dy,
  281. ),
  282. ],
  283. ),
  284. ),
  285. color: Color(widget.terminal.backgroundColor).withOpacity(
  286. widget.opacity,
  287. ),
  288. ),
  289. );
  290. }
  291. Offset _getCursorOffset() {
  292. final screenCursorY = widget.terminal.cursorY;
  293. final offsetX = _cellSize.cellWidth * widget.terminal.cursorX;
  294. final offsetY = _cellSize.cellHeight * screenCursorY;
  295. return Offset(offsetX, offsetY);
  296. }
  297. /// Get global cell position from mouse position.
  298. Position getMouseOffset(double px, double py) {
  299. final col = ((px - widget.padding) / _cellSize.cellWidth).floor();
  300. final row = ((py - widget.padding) / _cellSize.cellHeight).floor();
  301. final x = col;
  302. final y = widget.terminal.convertViewLineToRawLine(row) -
  303. widget.terminal.scrollOffsetFromBottom;
  304. return Position(x, y);
  305. }
  306. double? _width;
  307. double? _height;
  308. void onWidgetSize(double width, double height) {
  309. if (!widget.terminal.isReady) {
  310. return;
  311. }
  312. _width = width;
  313. _height = height;
  314. updateTerminalSize();
  315. }
  316. int? _lastTerminalWidth;
  317. int? _lastTerminalHeight;
  318. void updateTerminalSize() {
  319. assert(_width != null);
  320. assert(_height != null);
  321. final termWidth = (_width! / _cellSize.cellWidth).floor();
  322. final termHeight = (_height! / _cellSize.cellHeight).floor();
  323. if (_lastTerminalWidth == termWidth && _lastTerminalHeight == termHeight) {
  324. return;
  325. }
  326. _lastTerminalWidth = termWidth;
  327. _lastTerminalHeight = termHeight;
  328. widget.terminal.resize(
  329. termWidth,
  330. termHeight,
  331. (termWidth * _cellSize.cellWidth).floor(),
  332. (termHeight * _cellSize.cellHeight).floor(),
  333. );
  334. }
  335. TextEditingValue? onInput(TextEditingValue value) {
  336. return widget.inputBehavior.onTextEdit(value, widget.terminal);
  337. }
  338. void onKeyStroke(RawKeyEvent event) {
  339. blinkOscillator.restart();
  340. // TODO: find a way to stop scrolling immediately after key stroke.
  341. widget.inputBehavior.onKeyStroke(event, widget.terminal);
  342. widget.terminal.setScrollOffsetFromBottom(0);
  343. }
  344. void onFocus(bool focused) {
  345. SchedulerBinding.instance!.addPostFrameCallback((_) {
  346. widget.terminal.refresh();
  347. });
  348. }
  349. void onAction(TextInputAction action) {
  350. widget.inputBehavior.onAction(action, widget.terminal);
  351. }
  352. // synchronize flutter scroll offset to terminal
  353. void onScroll(double offset) {
  354. final topOffset = (offset / _cellSize.cellHeight).ceil();
  355. final bottomOffset = widget.terminal.invisibleHeight - topOffset;
  356. widget.terminal.setScrollOffsetFromBottom(bottomOffset);
  357. }
  358. }
  359. class CursorView extends StatefulWidget {
  360. final CellSize cellSize;
  361. final TerminalUiInteraction terminal;
  362. final FocusNode? focusNode;
  363. final Oscillator blinkOscillator;
  364. final TerminalStyle style;
  365. final TextLayoutCache textLayoutCache;
  366. CursorView({
  367. required this.terminal,
  368. required this.cellSize,
  369. required this.focusNode,
  370. required this.blinkOscillator,
  371. required this.style,
  372. required this.textLayoutCache,
  373. });
  374. @override
  375. State<StatefulWidget> createState() => _CursorViewState();
  376. }
  377. class _CursorViewState extends State<CursorView> {
  378. bool get focused {
  379. return widget.focusNode?.hasFocus ?? false;
  380. }
  381. var _isOscillatorCallbackRegistered = false;
  382. @override
  383. void initState() {
  384. _isOscillatorCallbackRegistered = true;
  385. widget.blinkOscillator.addListener(onOscillatorTick);
  386. widget.terminal.addListener(onTerminalChange);
  387. super.initState();
  388. }
  389. @override
  390. Widget build(BuildContext context) {
  391. return CustomPaint(
  392. painter: CursorPainter(
  393. visible: _isCursorVisible(),
  394. focused: focused,
  395. charSize: widget.cellSize,
  396. blinkVisible: widget.blinkOscillator.value,
  397. cursorColor: widget.terminal.cursorColor,
  398. textColor: widget.terminal.backgroundColor,
  399. style: widget.style,
  400. composingString: widget.terminal.composingString,
  401. textLayoutCache: widget.textLayoutCache,
  402. ),
  403. );
  404. }
  405. bool _isCursorVisible() {
  406. final screenCursorY =
  407. widget.terminal.cursorY + widget.terminal.scrollOffsetFromBottom;
  408. if (screenCursorY < 0 || screenCursorY >= widget.terminal.terminalHeight) {
  409. return false;
  410. }
  411. return widget.terminal.showCursor;
  412. }
  413. @override
  414. void dispose() {
  415. widget.terminal.removeListener(onTerminalChange);
  416. widget.blinkOscillator.removeListener(onOscillatorTick);
  417. super.dispose();
  418. }
  419. void onTerminalChange() {
  420. if (!mounted) {
  421. return;
  422. }
  423. setState(() {
  424. if (_isCursorVisible() /*&& widget.terminal.blinkingCursor*/ && focused) {
  425. if (!_isOscillatorCallbackRegistered) {
  426. _isOscillatorCallbackRegistered = true;
  427. widget.blinkOscillator.addListener(onOscillatorTick);
  428. }
  429. } else {
  430. if (_isOscillatorCallbackRegistered) {
  431. _isOscillatorCallbackRegistered = false;
  432. widget.blinkOscillator.removeListener(onOscillatorTick);
  433. }
  434. }
  435. });
  436. }
  437. void onOscillatorTick() {
  438. setState(() {});
  439. }
  440. }
  441. /// A scroll activity that does nothing. Used to suppress unexpected behaviors
  442. /// from [Scrollable] during viewport building process.
  443. class _EmptyScrollActivity extends IdleScrollActivity {
  444. _EmptyScrollActivity(ScrollActivityDelegate delegate) : super(delegate);
  445. @override
  446. void applyNewDimensions() {}
  447. /// set [isScrolling] to ture to prevent flutter from calling the old scroll
  448. /// activity.
  449. @override
  450. final isScrolling = true;
  451. void dispatchScrollStartNotification(
  452. ScrollMetrics metrics, BuildContext? context) {}
  453. void dispatchScrollUpdateNotification(
  454. ScrollMetrics metrics, BuildContext context, double scrollDelta) {}
  455. void dispatchOverscrollNotification(
  456. ScrollMetrics metrics, BuildContext context, double overscroll) {}
  457. void dispatchScrollEndNotification(
  458. ScrollMetrics metrics, BuildContext context) {}
  459. }