terminal_view.dart 17 KB

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