import 'dart:async'; import 'dart:collection'; import 'chat_shell_terminal_yield.dart'; /// UTF-16 units one emulator write takes at most. const int chatShellFeedSlice = 16 * 1024; /// How long one turn of the event loop writes output before yielding, so a /// large replay or burst never holds a UI frame for long. const Duration chatShellFeedBudget = Duration(milliseconds: 6); /// While output streams, the view is shown the emulator's state at most /// this often (about 30 frames a second), so a flood spends its time /// parsing rather than drawing screens nobody can read. Output after a /// quiet spell (an echo, a prompt) is shown at once. const Duration chatShellFeedShowGap = Duration(milliseconds: 32); /// The fewest units a write takes while more waits, however slow the /// output has been to write. const int _minimumSlice = 1024; /// The units the first write takes, before the speed is known. const int _firstSlice = 4096; /// Output on its way into one emulator, in order: written in slices of at /// most [slice] units, and after [budget] of writing the rest waits for the /// next turn of the event loop ([chatShellYield]). A slice is cut to what /// the measured speed writes in the budget left, so a turn ends close to /// the budget however costly the output is to parse. Each piece carries /// the server's absolute byte offset its text ends at; [drawn] is the end /// of the last piece written whole (what a terminal acknowledges as /// consumed). /// /// With [show], writes do not notify the view themselves: [show] is called /// once everything queued is written, before an action queued with [then], /// and while output still waits after a turn at most every [showGap]. A /// burst draws its final state per frame instead of one frame per turn. /// With [deferShows] (the web, where frames rasterise on the parsing /// thread) written output is also shown at most every [showGap]: output /// written less than a gap after the last show is shown when the gap has /// passed, so a stream draws about 30 frames a second, not one per piece. class ChatShellTerminalFeed { ChatShellTerminalFeed( this._write, { this.show, this.budget = chatShellFeedBudget, this.slice = chatShellFeedSlice, this.showGap = chatShellFeedShowGap, this.deferShows = chatShellRasterSharesThread, }); /// Writes [text] into the emulator; [replay] marks a redraw of old output. final void Function(String text, bool replay) _write; /// Lets the view show what was written (the emulator's listeners). final void Function()? show; final Duration budget; final int slice; final Duration showGap; final bool deferShows; /// Since [show] was last called (not running before the first call); /// whether anything was written since; the show waiting for the gap. final Stopwatch _sinceShown = Stopwatch(); bool _unshown = false; Timer? _showLater; /// Called with a piece's end once it is drawn. void Function(int end)? onDrawn; final Queue<_Piece> _pieces = Queue(); void Function()? _cancel; bool _pumping = false; int _drawn = 0; int _end = 0; /// Units written per millisecond, as last measured (0 before a write /// took measurable time). double _speed = 0; /// The end of the output drawn so far. int get drawn => _drawn; /// The end of the output drawn or waiting to be. int get end => _end; /// Whether nothing waits to be written. bool get idle => _pieces.isEmpty; /// Drops what waits: the emulator is redrawn and continues from [end]. void restart(int end) { _pieces.clear(); _cancel?.call(); _cancel = null; _drawn = end; _end = end; } /// Queues [text] ending at byte [end]; as much as the budget allows is /// written at once. void add(String text, int end, {bool replay = false}) { _pieces.add(_Piece(text, end, replay, null)); _end = end; _schedule(); } /// Runs [action] once everything queued before it is written. void then(void Function() action) { if (_pieces.isEmpty && !_pumping) { _show(); action(); return; } _pieces.add(_Piece('', _end, false, action)); } void dispose() { _pieces.clear(); _cancel?.call(); _cancel = null; _showLater?.cancel(); _showLater = null; } void _schedule() { if (_cancel == null && !_pumping) _pump(); } /// Units the next write takes, [elapsed] microseconds into the turn. int _sliceAt(int elapsed) { // Unmeasured (the first write, cold code): a small slice to measure. if (_speed <= 0) return slice < _firstSlice ? slice : _firstSlice; final left = (budget.inMicroseconds - elapsed) / 1000; final fits = (_speed * left).floor(); if (fits >= slice) return slice; final least = slice < _minimumSlice ? slice : _minimumSlice; return fits < least ? least : fits; } void _pump() { _cancel = null; _pumping = true; final clock = Stopwatch()..start(); try { while (_pieces.isNotEmpty) { final piece = _pieces.first; if (piece.at < piece.text.length) { final started = clock.elapsedMicroseconds; var cut = piece.at + _sliceAt(started); if (cut >= piece.text.length) { cut = piece.text.length; } else if (_highSurrogate(piece.text.codeUnitAt(cut - 1))) { // Never split a surrogate pair between two writes. cut++; } _write(piece.text.substring(piece.at, cut), piece.replay); _unshown = true; final took = clock.elapsedMicroseconds - started; // Small writes (an echo) say little about the speed. final units = cut - piece.at; if (took > 0 && units >= _minimumSlice) _speed = units * 1000 / took; piece.at = cut; } if (piece.at >= piece.text.length) { _pieces.removeFirst(); if (piece.action != null) { _show(); piece.action!(); } else { _drawn = piece.end; onDrawn?.call(piece.end); } } if (_pieces.isNotEmpty && clock.elapsed >= budget) { if (_gapPassed) _show(); _cancel = chatShellYield(_pump); return; } } if (!deferShows || _gapPassed) { _show(); } else if (_unshown) { _showLater ??= Timer(showGap - _sinceShown.elapsed, _show); } } finally { _pumping = false; } } bool get _gapPassed => !_sinceShown.isRunning || _sinceShown.elapsed >= showGap; void _show() { _showLater?.cancel(); _showLater = null; if (!_unshown) return; _unshown = false; _sinceShown ..reset() ..start(); show?.call(); } } class _Piece { _Piece(this.text, this.end, this.replay, this.action); final String text; final int end; final bool replay; final void Function()? action; int at = 0; } bool _highSurrogate(int unit) => unit >= 0xD800 && unit <= 0xDBFF;