From bff6b93683de8be01d53a39b6183f230518541ac Mon Sep 17 00:00:00 2001 From: Polina Cherkasova Date: Thu, 6 Jul 2023 12:19:18 -0700 Subject: [PATCH] Next attempt to make inspector weakly referencing the inspected objects. (#129962) --- .../lib/src/foundation/diagnostics.dart | 2 + .../flutter/lib/src/widgets/framework.dart | 2 +- .../lib/src/widgets/widget_inspector.dart | 117 +++++++++++++++--- .../flutter/test/widgets/framework_test.dart | 8 +- .../test/widgets/widget_inspector_test.dart | 43 ++++++- 5 files changed, 147 insertions(+), 25 deletions(-) diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index 280a8818d1..f4f9d5c4c0 100644 --- a/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/packages/flutter/lib/src/foundation/diagnostics.dart @@ -3292,6 +3292,8 @@ mixin Diagnosticable { /// {@end-tool} /// /// Used by [toDiagnosticsNode] and [toString]. + /// + /// Do not add values, that have lifetime shorter than the object. @protected @mustCallSuper void debugFillProperties(DiagnosticPropertiesBuilder properties) { } diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 2c0e3ca01b..c6d8f056fd 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -4794,7 +4794,7 @@ abstract class Element extends DiagnosticableTree implements BuildContext { final List diagnosticsDependencies = sortedDependencies .map((InheritedElement element) => element.widget.toDiagnosticsNode(style: DiagnosticsTreeStyle.sparse)) .toList(); - properties.add(DiagnosticsProperty>('dependencies', diagnosticsDependencies)); + properties.add(DiagnosticsProperty>('dependencies', deps, description: diagnosticsDependencies.toString())); } } diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index 8d2d591543..7a88e928e8 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -680,11 +680,39 @@ typedef InspectorSelectionChangedCallback = void Function(); /// Structure to help reference count Dart objects referenced by a GUI tool /// using [WidgetInspectorService]. -class _InspectorReferenceData { - _InspectorReferenceData(this.object); +/// +/// Does not hold the object from garbage collection. +@visibleForTesting +class InspectorReferenceData { + /// Creates an instance of [InspectorReferenceData]. + InspectorReferenceData(Object object, this.id) { + // These types are not supported by [WeakReference]. + // See https://api.dart.dev/stable/3.0.2/dart-core/WeakReference-class.html + if (object is String || object is num || object is bool) { + _value = object; + return; + } - final Object object; + _ref = WeakReference(object); + } + + WeakReference? _ref; + + Object? _value; + + /// The id of the object in the widget inspector records. + final String id; + + /// The number of times the object has been referenced. int count = 1; + + /// The value. + Object? get value { + if (_ref != null) { + return _ref!.target; + } + return _value; + } } // Production implementation of [WidgetInspectorService]. @@ -742,9 +770,9 @@ mixin WidgetInspectorService { /// The VM service protocol does not keep alive object references so this /// class needs to manually manage groups of objects that should be kept /// alive. - final Map> _groups = >{}; - final Map _idToReferenceData = {}; - final Map _objectToId = Map.identity(); + final Map> _groups = >{}; + final Map _idToReferenceData = {}; + final WeakMap _objectToId = WeakMap(); int _nextId = 0; /// The pubRootDirectories that are currently configured for the widget inspector. @@ -1270,20 +1298,22 @@ mixin WidgetInspectorService { /// references from a different group. @protected void disposeGroup(String name) { - final Set<_InspectorReferenceData>? references = _groups.remove(name); + final Set? references = _groups.remove(name); if (references == null) { return; } references.forEach(_decrementReferenceCount); } - void _decrementReferenceCount(_InspectorReferenceData reference) { + void _decrementReferenceCount(InspectorReferenceData reference) { reference.count -= 1; assert(reference.count >= 0); if (reference.count == 0) { - final String? id = _objectToId.remove(reference.object); - assert(id != null); - _idToReferenceData.remove(id); + final Object? value = reference.value; + if (value != null) { + _objectToId.remove(value); + } + _idToReferenceData.remove(reference.id); } } @@ -1295,14 +1325,16 @@ mixin WidgetInspectorService { return null; } - final Set<_InspectorReferenceData> group = _groups.putIfAbsent(groupName, () => Set<_InspectorReferenceData>.identity()); + final Set group = _groups.putIfAbsent(groupName, () => Set.identity()); String? id = _objectToId[object]; - _InspectorReferenceData referenceData; + InspectorReferenceData referenceData; if (id == null) { + // TODO(polina-c): comment here why we increase memory footprint by the prefix 'inspector-'. + // https://github.com/flutter/devtools/issues/5995 id = 'inspector-$_nextId'; _nextId += 1; _objectToId[object] = id; - referenceData = _InspectorReferenceData(object); + referenceData = InspectorReferenceData(object, id); _idToReferenceData[id] = referenceData; group.add(referenceData); } else { @@ -1332,11 +1364,11 @@ mixin WidgetInspectorService { return null; } - final _InspectorReferenceData? data = _idToReferenceData[id]; + final InspectorReferenceData? data = _idToReferenceData[id]; if (data == null) { throw FlutterError.fromParts([ErrorSummary('Id does not exist.')]); } - return data.object; + return data.value; } /// Returns the object to introspect to determine the source location of an @@ -1368,7 +1400,7 @@ mixin WidgetInspectorService { return; } - final _InspectorReferenceData? referenceData = _idToReferenceData[id]; + final InspectorReferenceData? referenceData = _idToReferenceData[id]; if (referenceData == null) { throw FlutterError.fromParts([ErrorSummary('Id does not exist')]); } @@ -3731,3 +3763,54 @@ class _WidgetFactory { // recognize the annotation. // ignore: library_private_types_in_public_api const _WidgetFactory widgetFactory = _WidgetFactory(); + +/// Does not hold keys from garbage collection. +@visibleForTesting +class WeakMap { + Expando _objects = Expando(); + + /// Strings, numbers, booleans. + final Map _primitives = {}; + + bool _isPrimitive(Object? key) { + return key == null || key is String || key is num || key is bool; + } + + /// Returns the value for the given [key] or null if [key] is not in the map + /// or garbage collected. + /// + /// Does not support records to act as keys. + V? operator [](K key){ + if (_isPrimitive(key)) { + return _primitives[key]; + } else { + return _objects[key!] as V?; + } + } + + /// Associates the [key] with the given [value]. + void operator []=(K key, V value){ + if (_isPrimitive(key)) { + _primitives[key] = value; + } else { + _objects[key!] = value; + } + } + + /// Removes the value for the given [key] from the map. + V? remove(K key) { + if (_isPrimitive(key)) { + return _primitives.remove(key); + } else { + final V? result = _objects[key!] as V?; + _objects[key] = null; + return result; + } + } + + /// Removes all pairs from the map. + void clear() { + _objects = Expando(); + _primitives.clear(); + } +} diff --git a/packages/flutter/test/widgets/framework_test.dart b/packages/flutter/test/widgets/framework_test.dart index 11e445aea9..4d82aa8530 100644 --- a/packages/flutter/test/widgets/framework_test.dart +++ b/packages/flutter/test/widgets/framework_test.dart @@ -1592,13 +1592,13 @@ void main() { builder.properties.any((DiagnosticsNode property) => property.name == 'dependencies' && property.value != null), isTrue, ); - final DiagnosticsProperty> dependenciesProperty = - builder.properties.firstWhere((DiagnosticsNode property) => property.name == 'dependencies') as DiagnosticsProperty>; + final DiagnosticsProperty> dependenciesProperty = + builder.properties.firstWhere((DiagnosticsNode property) => property.name == 'dependencies') as DiagnosticsProperty>; expect(dependenciesProperty, isNotNull); - final List dependencies = dependenciesProperty.value!; + final Set dependencies = dependenciesProperty.value!; expect(dependencies.length, equals(3)); - expect(dependencies.toString(), '[ButtonBarTheme, Directionality, FocusTraversalOrder]'); + expect(dependenciesProperty.toDescription(), '[ButtonBarTheme, Directionality, FocusTraversalOrder]'); }); testWidgets('BuildOwner.globalKeyCount keeps track of in-use global keys', (WidgetTester tester) async { diff --git a/packages/flutter/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart index 0321ea2fc6..743b4da59e 100644 --- a/packages/flutter/test/widgets/widget_inspector_test.dart +++ b/packages/flutter/test/widgets/widget_inspector_test.dart @@ -240,7 +240,41 @@ extension TextFromString on String { } } +final List _weakValueTests = [1, 1.0, 'hello', true, false, Object(), [3, 4], DateTime(2023)]; + void main() { + group('$InspectorReferenceData', (){ + for (final Object item in _weakValueTests) { + test('can be created for any type but $Record, $item', () async { + final InspectorReferenceData weakValue = InspectorReferenceData(item, 'id'); + expect(weakValue.value, item); + }); + } + + test('throws for $Record', () async { + expect(()=> InspectorReferenceData((1, 2), 'id'), throwsA(isA())); + }); + }); + + group('$WeakMap', (){ + for (final Object item in _weakValueTests) { + test('assigns and removes value, $item', () async { + final WeakMap weakMap = WeakMap(); + weakMap[item] = 1; + expect(weakMap[item], 1); + expect(weakMap.remove(item), 1); + expect(weakMap[item], null); + }); + } + + for (final Object item in _weakValueTests) { + test('returns null for absent value, $item', () async { + final WeakMap weakMap = WeakMap(); + expect(weakMap[item], null); + }); + } + }); + _TestWidgetInspectorService.runTests(); } @@ -2184,7 +2218,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final List expectedProperties = element.toDiagnosticsNode().getProperties(); final Iterable propertyValues = expectedProperties.map((DiagnosticsNode e) => e.value.toString()); for (final Map propertyJson in propertiesJson.cast>()) { - final String property = service.toObject(propertyJson['valueId']! as String)!.toString(); + final String id = propertyJson['valueId']! as String; + final String property = service.toObject(id)!.toString(); expect(propertyValues, contains(property)); } } @@ -2227,7 +2262,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final List expectedProperties = element.toDiagnosticsNode().getProperties(); final Iterable propertyValues = expectedProperties.map((DiagnosticsNode e) => e.value.toString()); for (final Map propertyJson in propertiesJson.cast>()) { - final String property = service.toObject(propertyJson['valueId']! as String)!.toString(); + final String id = propertyJson['valueId']! as String; + final String property = service.toObject(id)!.toString(); expect(propertyValues, contains(property)); } } @@ -2283,7 +2319,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { testWidgets('ext.flutter.inspector.getRootWidgetSummaryTree', (WidgetTester tester) async { const String group = 'test-group'; - await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, @@ -2296,6 +2331,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), ), ); + final Element elementA = find.text('a').evaluate().first; service.disposeAllGroups(); @@ -2311,6 +2347,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name, {'objectGroup': group}, ))! as Map; + // We haven't yet properly specified which directories are summary tree // directories so we get an empty tree other than the root that is always // included.