terminal_view.dart 17 KB

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