1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This file implements debugPrint in terms of print, so avoiding
6// calling "print" is sort of a non-starter here...
7// ignore_for_file: avoid_print
8
9import 'dart:async';
10import 'dart:collection';
11
12/// Signature for [debugPrint] implementations.
13///
14/// If a [wrapWidth] is provided, each line of the [message] is word-wrapped to
15/// that width. (Lines may be separated by newline characters, as in '\n'.)
16///
17/// By default, this function very crudely attempts to throttle the rate at
18/// which messages are sent to avoid data loss on Android. This means that
19/// interleaving calls to this function (directly or indirectly via, e.g.,
20/// [debugDumpRenderTree] or [debugDumpApp]) and to the Dart [print] method can
21/// result in out-of-order messages in the logs.
22///
23/// The implementation of this function can be replaced by setting the
24/// [debugPrint] variable to a new implementation that matches the
25/// [DebugPrintCallback] signature. For example, flutter_test does this.
26///
27/// The default value is [debugPrintThrottled]. For a version that acts
28/// identically but does not throttle, use [debugPrintSynchronously].
29typedef DebugPrintCallback = void Function(String? message, { int? wrapWidth });
30
31/// Prints a message to the console, which you can access using the "flutter"
32/// tool's "logs" command ("flutter logs").
33///
34/// See also:
35///
36/// * [DebugPrintCallback], for function parameters and usage details.
37/// * [debugPrintThrottled], the default implementation.
38DebugPrintCallback debugPrint = debugPrintThrottled;
39
40/// Alternative implementation of [debugPrint] that does not throttle.
41/// Used by tests.
42void debugPrintSynchronously(String? message, { int? wrapWidth }) {
43 if (message != null && wrapWidth != null) {
44 print(message.split('\n').expand<String>((String line) => debugWordWrap(line, wrapWidth)).join('\n'));
45 } else {
46 print(message);
47 }
48}
49
50/// Implementation of [debugPrint] that throttles messages. This avoids dropping
51/// messages on platforms that rate-limit their logging (for example, Android).
52///
53/// If `wrapWidth` is not null, the message is wrapped using [debugWordWrap].
54void debugPrintThrottled(String? message, { int? wrapWidth }) {
55 final List<String> messageLines = message?.split('\n') ?? <String>['null'];
56 if (wrapWidth != null) {
57 _debugPrintBuffer.addAll(messageLines.expand<String>((String line) => debugWordWrap(line, wrapWidth)));
58 } else {
59 _debugPrintBuffer.addAll(messageLines);
60 }
61 if (!_debugPrintScheduled) {
62 _debugPrintTask();
63 }
64}
65int _debugPrintedCharacters = 0;
66const int _kDebugPrintCapacity = 12 * 1024;
67const Duration _kDebugPrintPauseTime = Duration(seconds: 1);
68final Queue<String> _debugPrintBuffer = Queue<String>();
69final Stopwatch _debugPrintStopwatch = Stopwatch();
70Completer<void>? _debugPrintCompleter;
71bool _debugPrintScheduled = false;
72void _debugPrintTask() {
73 _debugPrintScheduled = false;
74 if (_debugPrintStopwatch.elapsed > _kDebugPrintPauseTime) {
75 _debugPrintStopwatch.stop();
76 _debugPrintStopwatch.reset();
77 _debugPrintedCharacters = 0;
78 }
79 while (_debugPrintedCharacters < _kDebugPrintCapacity && _debugPrintBuffer.isNotEmpty) {
80 final String line = _debugPrintBuffer.removeFirst();
81 _debugPrintedCharacters += line.length; // TODO(ianh): Use the UTF-8 byte length instead
82 print(line);
83 }
84 if (_debugPrintBuffer.isNotEmpty) {
85 _debugPrintScheduled = true;
86 _debugPrintedCharacters = 0;
87 Timer(_kDebugPrintPauseTime, _debugPrintTask);
88 _debugPrintCompleter ??= Completer<void>();
89 } else {
90 _debugPrintStopwatch.start();
91 _debugPrintCompleter?.complete();
92 _debugPrintCompleter = null;
93 }
94}
95
96/// A Future that resolves when there is no longer any buffered content being
97/// printed by [debugPrintThrottled] (which is the default implementation for
98/// [debugPrint], which is used to report errors to the console).
99Future<void> get debugPrintDone => _debugPrintCompleter?.future ?? Future<void>.value();
100
101final RegExp _indentPattern = RegExp('^ *(?:[-+*] |[0-9]+[.):] )?');
102enum _WordWrapParseMode { inSpace, inWord, atBreak }
103
104/// Wraps the given string at the given width.
105///
106/// The `message` should not contain newlines (`\n`, U+000A). Strings that may
107/// contain newlines should be [String.split] before being wrapped.
108///
109/// Wrapping occurs at space characters (U+0020). Lines that start with an
110/// octothorpe ("#", U+0023) are not wrapped (so for example, Dart stack traces
111/// won't be wrapped).
112///
113/// Subsequent lines attempt to duplicate the indentation of the first line, for
114/// example if the first line starts with multiple spaces. In addition, if a
115/// `wrapIndent` argument is provided, each line after the first is prefixed by
116/// that string.
117///
118/// This is not suitable for use with arbitrary Unicode text. For example, it
119/// doesn't implement UAX #14, can't handle ideographic text, doesn't hyphenate,
120/// and so forth. It is only intended for formatting error messages.
121///
122/// The default [debugPrint] implementation uses this for its line wrapping.
123Iterable<String> debugWordWrap(String message, int width, { String wrapIndent = '' }) {
124 if (message.length < width || message.trimLeft()[0] == '#') {
125 return <String>[message];
126 }
127 final List<String> wrapped = <String>[];
128 final Match prefixMatch = _indentPattern.matchAsPrefix(message)!;
129 final String prefix = wrapIndent + ' ' * prefixMatch.group(0)!.length;
130 int start = 0;
131 int startForLengthCalculations = 0;
132 bool addPrefix = false;
133 int index = prefix.length;
134 _WordWrapParseMode mode = _WordWrapParseMode.inSpace;
135 late int lastWordStart;
136 int? lastWordEnd;
137 while (true) {
138 switch (mode) {
139 case _WordWrapParseMode.inSpace: // at start of break point (or start of line); can't break until next break
140 while ((index < message.length) && (message[index] == ' ')) {
141 index += 1;
142 }
143 lastWordStart = index;
144 mode = _WordWrapParseMode.inWord;
145 case _WordWrapParseMode.inWord: // looking for a good break point
146 while ((index < message.length) && (message[index] != ' ')) {
147 index += 1;
148 }
149 mode = _WordWrapParseMode.atBreak;
150 case _WordWrapParseMode.atBreak: // at start of break point
151 if ((index - startForLengthCalculations > width) || (index == message.length)) {
152 // we are over the width line, so break
153 if ((index - startForLengthCalculations <= width) || (lastWordEnd == null)) {
154 // we should use this point, because either it doesn't actually go over the
155 // end (last line), or it does, but there was no earlier break point
156 lastWordEnd = index;
157 }
158 if (addPrefix) {
159 wrapped.add(prefix + message.substring(start, lastWordEnd));
160 } else {
161 wrapped.add(message.substring(start, lastWordEnd));
162 addPrefix = true;
163 }
164 if (lastWordEnd >= message.length) {
165 return wrapped;
166 }
167 // just yielded a line
168 if (lastWordEnd == index) {
169 // we broke at current position
170 // eat all the spaces, then set our start point
171 while ((index < message.length) && (message[index] == ' ')) {
172 index += 1;
173 }
174 start = index;
175 mode = _WordWrapParseMode.inWord;
176 } else {
177 // we broke at the previous break point, and we're at the start of a new one
178 assert(lastWordStart > lastWordEnd);
179 start = lastWordStart;
180 mode = _WordWrapParseMode.atBreak;
181 }
182 startForLengthCalculations = start - prefix.length;
183 assert(addPrefix);
184 lastWordEnd = null;
185 } else {
186 // save this break point, we're not yet over the line width
187 lastWordEnd = index;
188 // skip to the end of this break point
189 mode = _WordWrapParseMode.inSpace;
190 }
191 }
192 }
193}
194