recording_canvas.dart 7.24 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/rendering.dart';
9
import 'package:flutter/src/rendering/layer.dart';
10

11 12 13 14 15 16 17 18
/// An [Invocation] and the [stack] trace that led to it.
///
/// Used by [TestRecordingCanvas] to trace canvas calls.
class RecordedInvocation {
  /// Create a record for an invocation list.
  const RecordedInvocation(this.invocation, { this.stack });

  /// The method that was called and its arguments.
19 20 21 22 23 24
  ///
  /// The arguments preserve identity, but not value. Thus, if two invocations
  /// were made with the same [Paint] object, but with that object configured
  /// differently each time, then they will both have the same object as their
  /// argument, and inspecting that object will return the object's current
  /// values (mostly likely those passed to the second call).
25 26 27 28 29 30 31 32 33
  final Invocation invocation;

  /// The stack trace at the time of the method call.
  final StackTrace stack;

  @override
  String toString() => _describeInvocation(invocation);

  /// Converts [stack] to a string using the [FlutterError.defaultStackFilter] logic.
34
  String stackToString({ String indent = '' }) {
35 36 37 38 39 40 41
    assert(indent != null);
    return indent + FlutterError.defaultStackFilter(
      stack.toString().trimRight().split('\n')
    ).join('\n$indent');
  }
}

42 43
/// A [Canvas] for tests that records its method calls.
///
44
/// This class can be used in conjunction with [TestRecordingPaintingContext]
45 46 47 48
/// to record the [Canvas] method calls made by a renderer. For example:
///
/// ```dart
/// RenderBox box = tester.renderObject(find.text('ABC'));
49 50
/// TestRecordingCanvas canvas = TestRecordingCanvas();
/// TestRecordingPaintingContext context = TestRecordingPaintingContext(canvas);
51 52 53 54 55
/// box.paint(context, Offset.zero);
/// // Now test the expected canvas.invocations.
/// ```
///
/// In some cases it may be useful to define a subclass that overrides the
56
/// [Canvas] methods the test is checking and squirrels away the parameters
57
/// that the test requires.
58 59 60
///
/// For simple tests, consider using the [paints] matcher, which overlays a
/// pattern matching API over [TestRecordingCanvas].
61 62
class TestRecordingCanvas implements Canvas {
  /// All of the method calls on this canvas.
63
  final List<RecordedInvocation> invocations = <RecordedInvocation>[];
64 65 66 67 68 69 70 71 72

  int _saveCount = 0;

  @override
  int getSaveCount() => _saveCount;

  @override
  void save() {
    _saveCount += 1;
73
    invocations.add(RecordedInvocation(_MethodCall(#save), stack: StackTrace.current));
74 75
  }

76 77 78
  @override
  void saveLayer(Rect bounds, Paint paint) {
    _saveCount += 1;
79
    invocations.add(RecordedInvocation(_MethodCall(#saveLayer, <dynamic>[bounds, paint]), stack: StackTrace.current));
80 81
  }

82 83 84 85
  @override
  void restore() {
    _saveCount -= 1;
    assert(_saveCount >= 0);
86
    invocations.add(RecordedInvocation(_MethodCall(#restore), stack: StackTrace.current));
87 88 89 90
  }

  @override
  void noSuchMethod(Invocation invocation) {
91
    invocations.add(RecordedInvocation(invocation, stack: StackTrace.current));
92 93 94 95
  }
}

/// A [PaintingContext] for tests that use [TestRecordingCanvas].
96
class TestRecordingPaintingContext extends ClipContext implements PaintingContext {
97 98 99 100 101 102 103 104 105 106 107 108
  /// Creates a [PaintingContext] for tests that use [TestRecordingCanvas].
  TestRecordingPaintingContext(this.canvas);

  @override
  final Canvas canvas;

  @override
  void paintChild(RenderObject child, Offset offset) {
    child.paint(this, offset);
  }

  @override
109 110 111 112 113 114 115 116
  ClipRectLayer pushClipRect(
    bool needsCompositing,
    Offset offset,
    Rect clipRect,
    PaintingContextCallback painter, {
    Clip clipBehavior = Clip.hardEdge,
    ClipRectLayer oldLayer,
  }) {
117
    clipRectAndPaint(clipRect.shift(offset), clipBehavior, clipRect.shift(offset), () => painter(this, offset));
118
    return null;
119 120
  }

121
  @override
122 123 124 125 126 127 128 129 130
  ClipRRectLayer pushClipRRect(
    bool needsCompositing,
    Offset offset,
    Rect bounds,
    RRect clipRRect,
    PaintingContextCallback painter, {
    Clip clipBehavior = Clip.antiAlias,
    ClipRRectLayer oldLayer,
  }) {
131 132
    assert(clipBehavior != null);
    clipRRectAndPaint(clipRRect.shift(offset), clipBehavior, bounds.shift(offset), () => painter(this, offset));
133
    return null;
134 135
  }

136
  @override
137 138 139 140 141 142 143 144 145
  ClipPathLayer pushClipPath(
    bool needsCompositing,
    Offset offset,
    Rect bounds,
    Path clipPath,
    PaintingContextCallback painter, {
    Clip clipBehavior = Clip.antiAlias,
    ClipPathLayer oldLayer,
  }) {
146
    clipPathAndPaint(clipPath.shift(offset), clipBehavior, bounds.shift(offset), () => painter(this, offset));
147
    return null;
148 149
  }

150
  @override
151 152 153 154 155 156 157
  TransformLayer pushTransform(
    bool needsCompositing,
    Offset offset,
    Matrix4 transform,
    PaintingContextCallback painter, {
    TransformLayer oldLayer,
  }) {
158 159 160 161
    canvas.save();
    canvas.transform(transform.storage);
    painter(this, offset);
    canvas.restore();
162
    return null;
163
  }
164 165

  @override
166 167
  OpacityLayer pushOpacity(Offset offset, int alpha, PaintingContextCallback painter,
      { OpacityLayer oldLayer }) {
168 169 170
    canvas.saveLayer(null, null); // TODO(ianh): Expose the alpha somewhere.
    painter(this, offset);
    canvas.restore();
171
    return null;
172
  }
173

174
  @override
175 176
  void pushLayer(Layer childLayer, PaintingContextCallback painter, Offset offset,
      { Rect childPaintBounds }) {
177 178 179
    painter(this, offset);
  }

180
  @override
181
  void noSuchMethod(Invocation invocation) { }
182 183 184
}

class _MethodCall implements Invocation {
185
  _MethodCall(this._name, [ this._arguments = const <dynamic>[], this._typeArguments = const <Type> []]);
186
  final Symbol _name;
187
  final List<dynamic> _arguments;
188
  final List<Type> _typeArguments;
189 190 191 192 193 194 195 196 197 198 199 200 201
  @override
  bool get isAccessor => false;
  @override
  bool get isGetter => false;
  @override
  bool get isMethod => true;
  @override
  bool get isSetter => false;
  @override
  Symbol get memberName => _name;
  @override
  Map<Symbol, dynamic> get namedArguments => <Symbol, dynamic>{};
  @override
202
  List<dynamic> get positionalArguments => _arguments;
203 204
  @override
  List<Type> get typeArguments => _typeArguments;
205
}
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

String _valueName(Object value) {
  if (value is double)
    return value.toStringAsFixed(1);
  return value.toString();
}

// Workaround for https://github.com/dart-lang/sdk/issues/28372
String _symbolName(Symbol symbol) {
  // WARNING: Assumes a fixed format for Symbol.toString which is *not*
  // guaranteed anywhere.
  final String s = '$symbol';
  return s.substring(8, s.length - 2);
}

// Workaround for https://github.com/dart-lang/sdk/issues/28373
String _describeInvocation(Invocation call) {
223
  final StringBuffer buffer = StringBuffer();
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
  buffer.write(_symbolName(call.memberName));
  if (call.isSetter) {
    buffer.write(call.positionalArguments[0].toString());
  } else if (call.isMethod) {
    buffer.write('(');
    buffer.writeAll(call.positionalArguments.map<String>(_valueName), ', ');
    String separator = call.positionalArguments.isEmpty ? '' : ', ';
    call.namedArguments.forEach((Symbol name, Object value) {
      buffer.write(separator);
      buffer.write(_symbolName(name));
      buffer.write(': ');
      buffer.write(_valueName(value));
      separator = ', ';
    });
    buffer.write(')');
  }
  return buffer.toString();
}