import 'dart:convert'; /// Characters of output one tab holds before its oldest are dropped (about /// the server's 1 MiB tail). const int terminalHeldLimit = 1 << 20; /// The text of [text] after its first [bytes] UTF-8 bytes (a cut inside a /// character drops that character's remaining bytes). String terminalSkipBytes(String text, int bytes) { if (bytes <= 0) return text; final encoded = utf8.encode(text); if (bytes >= encoded.length) return ''; var cut = bytes; while (cut < encoded.length && (encoded[cut] & 0xC0) == 0x80) { cut++; } return utf8.decode(encoded.sublist(cut), allowMalformed: true); } /// One terminal's output as the client holds it: the text covering /// absolute bytes [start, end) of the server's stream named [stream]. class TerminalStream { String text = ''; int start = 0; int end = 0; String stream = ''; /// Whether nothing was received yet. bool get empty => stream.isEmpty && end == 0; /// Replaces the held copy with a read of the server's retained tail. void reset(String output, int outputStart, String name) { text = output; start = outputStart; end = outputStart + utf8.encode(output).length; stream = name; _bound(); } /// Adds the part of [chunk] (covering [offset, chunkEnd)) past [end] and /// returns it; null when the chunk starts after [end] (a gap). String? add(String chunk, int offset, int chunkEnd) { if (chunkEnd <= end) return ''; if (offset > end) return null; final fresh = terminalSkipBytes(chunk, end - offset); text += fresh; end = chunkEnd; _bound(); return fresh; } void _bound() { if (text.length <= terminalHeldLimit + terminalHeldLimit ~/ 2) return; var cut = text.length - terminalHeldLimit; // Never split a surrogate pair. final unit = text.codeUnitAt(cut); if (unit >= 0xDC00 && unit <= 0xDFFF) cut++; text = text.substring(cut); start = end - utf8.encode(text).length; } }