forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinspector_service.dart
More file actions
1304 lines (1161 loc) · 41.6 KB
/
inspector_service.dart
File metadata and controls
1304 lines (1161 loc) · 41.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd.
// This code is directly based on src/io/flutter/InspectorService.java.
//
// If you add methods to this class you should also add them to
// InspectorService.java.
/// @docImport '../../screens/performance/panes/rebuild_stats/rebuild_stats_model.dart';
library;
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:devtools_app_shared/service.dart';
import 'package:devtools_app_shared/service_extensions.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:vm_service/vm_service.dart';
import '../console/primitives/simple_items.dart';
import '../globals.dart';
import '../utils/utils.dart';
import 'diagnostics_node.dart';
import 'generic_instance_reference.dart';
import 'object_group_api.dart';
import 'primitives/instance_ref.dart';
import 'primitives/source_location.dart';
const _inspectorLibraryUri =
'package:flutter/src/widgets/widget_inspector.dart';
abstract class InspectorServiceBase extends DisposableController
with AutoDisposeControllerMixin {
InspectorServiceBase({
required this.clientInspectorName,
required this.serviceExtensionPrefix,
required String inspectorLibraryUri,
ValueListenable<IsolateRef?>? evalIsolate,
}) : assert(serviceConnection.serviceManager.connectedAppInitialized),
assert(serviceConnection.serviceManager.service != null),
clients = {},
inspectorLibrary = EvalOnDartLibrary(
inspectorLibraryUri,
serviceConnection.serviceManager.service!,
serviceManager: serviceConnection.serviceManager,
isolate: evalIsolate,
) {
_lastMainIsolate =
serviceConnection.serviceManager.isolateManager.mainIsolate.value;
addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.mainIsolate,
() {
final mainIsolate =
serviceConnection.serviceManager.isolateManager.mainIsolate.value;
if (mainIsolate != _lastMainIsolate) {
onIsolateStopped();
}
_lastMainIsolate = mainIsolate;
},
);
}
static int nextGroupId = 0;
// The class name of the inspector that [InspectorServiceBase] is connecting
// to, for use when running evals. For example, this should be set to
// "WidgetInspectorService" when connecting to the Flutter inspector.
final String clientInspectorName;
// The prefix added when invoking all registered inspector service extensions.
// For example, this should be set to "ext.flutter.inspector" when invoking
// service extensions registered by the Flutter inspector.
final String serviceExtensionPrefix;
final Set<InspectorServiceClient> clients;
final EvalOnDartLibrary inspectorLibrary;
IsolateRef? _lastMainIsolate;
/// Reference to the isolate running the inspector that [InspectorServiceBase]
/// is connecting to. This isolate should always be the main isolate.
IsolateRef? get isolateRef => inspectorLibrary.isolateRef;
/// Called when the main isolate is stopped. Should be overridden in order to
/// clear data that is obsolete on an isolate restart.
void onIsolateStopped();
/// Returns true if the given node's class is declared beneath one of the root
/// directories of the app's package.
bool isLocalClass(RemoteDiagnosticsNode node);
/// Returns a new [InspectorObjectGroupBase] with the given group name.
InspectorObjectGroupBase createObjectGroup(String debugName);
bool get isDisposed => _isDisposed;
bool _isDisposed = false;
void addClient(InspectorServiceClient client) {
clients.add(client);
}
void removeClient(InspectorServiceClient client) {
clients.remove(client);
}
/// Returns whether to use the Daemon API or the VM Service protocol directly.
///
/// The VM Service protocol must be used when paused at a breakpoint as the
/// Daemon API calls won't execute until after the current frame is done
/// rendering.
bool get useDaemonApi =>
!serviceConnection.serviceManager.isMainIsolatePaused;
@override
void dispose() {
_isDisposed = true;
inspectorLibrary.dispose();
super.dispose();
}
bool get hoverEvalModeEnabledByDefault;
Future<bool> invokeBoolServiceMethodNoArgs(String methodName) async {
return useDaemonApi
? await invokeServiceMethodDaemonNoGroupArgs(methodName) == true
: (await invokeServiceMethodObservatoryNoGroup(
methodName,
))?.valueAsString ==
'true';
}
Future<Object?> invokeServiceMethodDaemonNoGroupArgs(
String methodName, [
List<String>? args,
]) {
final params = <String, Object?>{};
if (args != null) {
for (int i = 0; i < args.length; ++i) {
params['arg$i'] = args[i];
}
}
return invokeServiceMethodDaemonNoGroup(methodName, args: params);
}
Future<InstanceRef?> invokeServiceMethodObservatoryNoGroup(
String methodName,
) {
return inspectorLibrary.eval(
'$clientInspectorName.instance.$methodName()',
isAlive: null,
);
}
Future<Object?> invokeServiceMethodDaemonNoGroup(
String methodName, {
Map<String, Object?>? args,
}) async {
final callMethodName = '$serviceExtensionPrefix.$methodName';
if (!serviceConnection.serviceManager.serviceExtensionManager
.isServiceExtensionAvailable(callMethodName)) {
final available = await serviceConnection
.serviceManager
.serviceExtensionManager
.waitForServiceExtensionAvailable(callMethodName);
if (!available) return {'result': null};
}
final r = await serviceConnection.serviceManager.service!
.callServiceExtension(
callMethodName,
isolateId: isolateRef!.id,
args: args,
);
final json = r.json!;
if (json['errorMessage'] != null) {
throw Exception('$methodName -- ${json['errorMessage']}');
}
return json['result'];
}
}
/// Manages communication between inspector code running in the Flutter app and
/// the inspector.
class InspectorService extends InspectorServiceBase {
InspectorService()
: super(
clientInspectorName: 'WidgetInspectorService',
serviceExtensionPrefix: inspectorExtensionPrefix,
inspectorLibraryUri: _inspectorLibraryUri,
evalIsolate:
serviceConnection.serviceManager.isolateManager.mainIsolate,
) {
// Note: We do not need to listen to event history here because the
// inspector uses a separate API to get the current inspector selection.
autoDisposeStreamSubscription(
serviceConnection.serviceManager.service!.onExtensionEvent.listen(
onExtensionVmServiceReceived,
),
);
autoDisposeStreamSubscription(
serviceConnection.serviceManager.service!.onDebugEvent.listen(
onDebugVmServiceReceived,
),
);
}
final _rootDirectories = ValueNotifier<List<String>>(<String>[]);
@visibleForTesting
List<String> get rootPackagePrefixes => _rootPackagePrefixes;
late List<String> _rootPackagePrefixes;
@visibleForTesting
final localClasses = <String, ClassRef>{};
@override
void onIsolateStopped() {
_currentSelection = null;
_cachedSelectionGroups?.clear(true);
_expectedSelectionChanges.clear();
}
@override
ObjectGroup createObjectGroup(String debugName) {
return ObjectGroup(debugName, this);
}
@override
bool isLocalClass(RemoteDiagnosticsNode node) {
// TODO(https://github.com/flutter/devtools/issues/4393): localClasses is
// not currently being filled.
if (node.widgetRuntimeType == null) return false;
// widgetRuntimeType may contain some generic type arguments which we need
// to strip out. If widgetRuntimeType is "FooWidget<Bar>" then we are only
// interested in the raw type "FooWidget".
final rawType = node.widgetRuntimeType!.split('<').first;
return localClasses.containsKey(rawType);
}
@override
void dispose() {
_cachedSelectionGroups?.clear(false);
_cachedSelectionGroups = null;
super.dispose();
}
// When DevTools is embedded, default hover eval mode to off.
@override
bool get hoverEvalModeEnabledByDefault => !isEmbedded();
void onExtensionVmServiceReceived(Event e) {
if (e.extensionKind == FlutterEvent.frame) {
for (final client in clients) {
try {
client.onFlutterFrame();
} catch (e) {
log('Error handling frame event', error: e);
}
}
}
}
void onDebugVmServiceReceived(Event event) {
if (event.kind == EventKind.kInspect) {
// Update the UI in IntelliJ.
notifySelectionChanged();
}
}
/// Map from InspectorInstanceRef to list of timestamps when a selection
/// change to that ref was triggered by this application.
///
/// This is needed to handle the case where we may send multiple selection
/// change notifications to the device before we get a notification back that
/// the selection has actually changed. Without this fix it was rare but
/// possible to trigger an infinite loop ping-ponging back and forth between
/// selecting two different nodes in the inspector tree if the selection was
/// changed more rapidly than the running flutter app could update.
final _expectedSelectionChanges = <InspectorInstanceRef, List<int>>{};
/// Maximum time in milliseconds that we ever expect it will take for a
/// selection change to apply.
///
/// In general this heuristic based time should not matter but we keep it
/// anyway so that in the unlikely event that package:flutter changes and we
/// do not received all of the selection notification events we expect, we
/// will not be impacted if there is at least the following delay between
/// when selection was set to exactly the same location by both the on device
/// inspector and DevTools.
static const _maxTimeDelaySelectionNotification = 5000;
void _trackClientSelfTriggeredSelection(InspectorInstanceRef ref) {
_expectedSelectionChanges
.putIfAbsent(ref, () => [])
.add(DateTime.now().millisecondsSinceEpoch);
}
/// Returns whether the selection change was originally triggered by this
/// application.
///
/// This method is needed to avoid a race condition when there is a queue of
/// inspector selection changes due to extremely rapidly navigating through
/// the inspector tree such as when using the keyboard to navigate.
bool _isClientTriggeredSelectionChange(InspectorInstanceRef? ref) {
// TODO(jacobr): once https://github.com/flutter/flutter/issues/39366 is
// fixed in all versions of flutter we support, remove this logic and
// determine the source of the inspector selection change directly from the
// inspector selection changed event.
final currentTime = DateTime.now().millisecondsSinceEpoch;
if (ref != null) {
if (_expectedSelectionChanges.containsKey(ref)) {
final times = _expectedSelectionChanges.remove(ref)!;
while (times.isNotEmpty) {
final time = times.removeAt(0);
if (time + _maxTimeDelaySelectionNotification >= currentTime) {
// We triggered this selection change ourselves. This logic would
// work fine without the timestamps for the typical case but we use
// the timestamps to be safe in case there is a bug and selection
// change events were somehow lost.
return true;
}
}
}
}
return false;
}
void _onRootDirectoriesChanged(List<String> directories) {
_rootDirectories.value = directories;
_rootPackagePrefixes = [];
for (final directory in directories) {
// TODO(jacobr): add an API to DDS to provide the actual mapping to and
// from absolute file paths to packages instead of having to guess it
// here.
assert(!directory.startsWith('package:'));
final parts = directory
.split('/')
.where((element) => element.isNotEmpty)
.toList();
final libIndex = parts.lastIndexOf('lib');
final path = libIndex > 0 ? parts.sublist(0, libIndex) : parts;
// Special case handling of bazel packages.
if (isGoogle3Path(path)) {
var packageParts = stripGoogle3(path);
// A well formed third_party dart package should be in a directory of
// the form
// third_party/dart/packageName (package:packageName)
// or
// third_party/dart_src/long/package/name (package:long.package.name)
// so its path should be at minimum depth 3.
const minThirdPartyPathDepth = 3;
if (packageParts.first == 'third_party' &&
packageParts.length >= minThirdPartyPathDepth) {
assert(packageParts[1] == 'dart' || packageParts[1] == 'dart_src');
packageParts = packageParts.sublist(2);
}
final google3PackageName = packageParts.join('.');
_rootPackagePrefixes.add('$google3PackageName.');
}
}
}
Future<void> addPubRootDirectories(List<String> rootDirectories) async {
await _addPubRootDirectories(rootDirectories);
_onRootDirectoriesChanged(rootDirectories);
}
Future<void> removePubRootDirectories(List<String> rootDirectories) async {
await _removePubRootDirectories(rootDirectories);
_onRootDirectoriesChanged(rootDirectories);
}
Future<void> _addPubRootDirectories(List<String> pubDirectories) async {
await serviceConnection.serviceManager.waitUntilNotPaused();
assert(useDaemonApi);
await invokeServiceMethodDaemonNoGroupArgs(
WidgetInspectorServiceExtensions.addPubRootDirectories.name,
pubDirectories,
);
}
Future<void> _removePubRootDirectories(List<String> pubDirectories) async {
await serviceConnection.serviceManager.waitUntilNotPaused();
assert(useDaemonApi);
await invokeServiceMethodDaemonNoGroupArgs(
WidgetInspectorServiceExtensions.removePubRootDirectories.name,
pubDirectories,
);
}
Future<List<String>?> getPubRootDirectories() async {
await serviceConnection.serviceManager.waitUntilNotPaused();
assert(useDaemonApi);
final response = await invokeServiceMethodDaemonNoGroupArgs(
WidgetInspectorServiceExtensions.getPubRootDirectories.name,
);
if (response is! List<Object?>) {
return [];
}
return response.map<String>((e) => e.toString()).toList();
}
/// Requests the full mapping of widget ids to source locations.
///
/// See [LocationMap] which provides support to parse this JSON.
Future<Map<String, Object?>> widgetLocationIdMap() async {
await serviceConnection.serviceManager.waitUntilNotPaused();
assert(useDaemonApi);
final response = await invokeServiceMethodDaemonNoGroupArgs(
'widgetLocationIdMap',
);
if (response is! Map) {
return {};
}
return response as Map<String, Object?>;
}
RemoteDiagnosticsNode? _currentSelection;
InspectorObjectGroupManager get _selectionGroups {
return _cachedSelectionGroups ??= InspectorObjectGroupManager(
this,
'selection',
);
}
InspectorObjectGroupManager? _cachedSelectionGroups;
void notifySelectionChanged() async {
// The previous selection changed event is obsolete.
_selectionGroups.cancelNext();
final group = _selectionGroups.next;
final pendingSelection = await group.getSelection(
_currentSelection,
FlutterTreeType.widget,
);
if (!group.disposed &&
group == _selectionGroups.next &&
!_isClientTriggeredSelectionChange(pendingSelection?.valueRef)) {
_currentSelection = pendingSelection;
assert(group == _selectionGroups.next);
_selectionGroups.promoteNext();
for (final client in clients) {
client.onInspectorSelectionChanged();
}
}
}
/// If the widget tree is not ready, the application should wait for the next
/// Flutter.Frame event before attempting to display the widget tree. If the
/// application is ready, the next Flutter.Frame event may never come as no
/// new frames will be triggered to draw unless something changes in the UI.
Future<bool> isWidgetTreeReady() {
return invokeBoolServiceMethodNoArgs(
WidgetInspectorServiceExtensions.isWidgetTreeReady.name,
);
}
Future<bool> isWidgetCreationTracked() {
return invokeBoolServiceMethodNoArgs(
WidgetInspectorServiceExtensions.isWidgetCreationTracked.name,
);
}
}
/// This class has additional descenders in Google3.
abstract class InspectorObjectGroupBase
extends InspectorObjectGroupApi<RemoteDiagnosticsNode> {
InspectorObjectGroupBase(String debugName)
: groupName = '${debugName}_${InspectorServiceBase.nextGroupId}' {
InspectorServiceBase.nextGroupId++;
}
/// Object group all objects in this arena are allocated with.
final String groupName;
InspectorServiceBase get inspectorService;
@override
bool disposed = false;
EvalOnDartLibrary get inspectorLibrary => inspectorService.inspectorLibrary;
bool get useDaemonApi => inspectorService.useDaemonApi;
/// Once an ObjectGroup has been disposed, all methods returning
/// DiagnosticsNode objects will return a placeholder dummy node and all methods
/// returning lists or maps will return empty lists and all other methods will
/// return null. Generally code should never call methods on a disposed object
/// group but sometimes due to chained futures that can be difficult to avoid
/// and it is simpler return an empty result that will be ignored anyway than to
/// attempt carefully cancel futures.
@override
Future<void> dispose() {
var disposeComplete = Future<void>.value();
try {
// Only dispose the group if the isolate still exists.
if (inspectorService.isolateRef != null) {
disposeComplete = invokeVoidServiceMethod(
WidgetInspectorServiceExtensions.disposeGroup.name,
groupName,
);
}
} on RPCError catch (e) {
if (!e.isServiceDisposedError) {
// Swallow exceptions related to trying to dispose an Inspector group on
// an already disposed service connection. Otherwise, rethrow.
rethrow;
}
}
disposed = true;
return disposeComplete;
}
Future<RemoteDiagnosticsNode?> invokeServiceMethodReturningNodeInspectorRef(
String methodName,
InspectorInstanceRef? ref,
) async {
if (disposed) return null;
return useDaemonApi
? parseDiagnosticsNodeDaemon(
invokeServiceMethodDaemonInspectorRef(methodName, ref),
)
: parseDiagnosticsNodeObservatory(
invokeServiceMethodObservatoryInspectorRef(methodName, ref),
);
}
Future<RemoteDiagnosticsNode?> invokeServiceMethodWithArgReturningNode(
String methodName,
String arg,
) async {
if (disposed) return null;
return useDaemonApi
? parseDiagnosticsNodeDaemon(
invokeServiceMethodDaemonArg(methodName, arg, groupName),
)
: parseDiagnosticsNodeObservatory(
invokeServiceMethodObservatoryWithGroupName1(methodName, arg),
);
}
Future<Object?> invokeServiceMethodDaemonArg(
String methodName,
String? arg,
String objectGroup,
) {
final args = {'objectGroup': objectGroup};
if (arg != null) {
args['arg'] = arg;
}
return invokeServiceMethodDaemonParams(methodName, args);
}
Future<Object?> invokeServiceMethodDaemonInspectorRef(
String methodName,
InspectorInstanceRef? arg,
) {
return invokeServiceMethodDaemonArg(methodName, arg?.id, groupName);
}
Future<InstanceRef?> invokeServiceMethodObservatoryInspectorRef(
String methodName,
InspectorInstanceRef? arg,
) {
return inspectorLibrary.eval(
"${inspectorService.clientInspectorName}.instance.$methodName('${arg?.id}', '$groupName')",
isAlive: this,
);
}
Future<void> invokeVoidServiceMethod(String methodName, String arg1) async {
if (disposed) return;
if (useDaemonApi) {
await invokeServiceMethodDaemon(methodName, arg1);
} else {
await invokeServiceMethodObservatory1(methodName, arg1);
}
}
Future<Object?> invokeServiceMethodDaemon(
String methodName, [
String? objectGroup,
]) {
return invokeServiceMethodDaemonParams(methodName, {
'objectGroup': objectGroup ?? groupName,
});
}
Future<InstanceRef?> invokeServiceMethodObservatory1(
String methodName,
String arg1,
) {
return inspectorLibrary.eval(
"${inspectorService.clientInspectorName}.instance.$methodName('$arg1')",
isAlive: this,
);
}
Future<InstanceRef?> invokeServiceMethodObservatoryWithGroupName1(
String methodName,
String arg1,
) {
return inspectorLibrary.eval(
"${inspectorService.clientInspectorName}.instance.$methodName('$arg1', '$groupName')",
isAlive: this,
);
}
// All calls to invokeServiceMethodDaemon bottom out to this call.
Future<Object?> invokeServiceMethodDaemonParams(
String methodName,
Map<String, Object?> params,
) async {
final callMethodName =
'${inspectorService.serviceExtensionPrefix}.$methodName';
if (!serviceConnection.serviceManager.serviceExtensionManager
.isServiceExtensionAvailable(callMethodName)) {
final available = await serviceConnection
.serviceManager
.serviceExtensionManager
.waitForServiceExtensionAvailable(callMethodName);
if (!available) return null;
}
return await _callServiceExtension(callMethodName, params);
}
Future<Object?> _callServiceExtension(
String extension,
Map<String, Object?> args,
) {
if (disposed) {
return Future.value();
}
return inspectorLibrary.addRequest(this, () async {
final r = await serviceConnection.serviceManager.service!
.callServiceExtension(
extension,
isolateId: inspectorService.isolateRef!.id,
args: args,
);
if (disposed) return null;
final json = r.json!;
if (json['errorMessage'] != null) {
throw Exception('$extension -- ${json['errorMessage']}');
}
return json['result'];
});
}
Future<RemoteDiagnosticsNode?> parseDiagnosticsNodeDaemon(
Future<Object?> json,
) async {
if (disposed) return null;
return parseDiagnosticsNodeHelper(await json as Map<String, Object?>?);
}
Future<RemoteDiagnosticsNode?> parseDiagnosticsNodeObservatory(
FutureOr<InstanceRef?> instanceRefFuture,
) async {
return parseDiagnosticsNodeHelper(
await instanceRefToJson(await instanceRefFuture) as Map<String, Object?>?,
);
}
RemoteDiagnosticsNode? parseDiagnosticsNodeHelper(
Map<String, Object?>? jsonElement,
) {
if (disposed) return null;
if (jsonElement == null) return null;
return RemoteDiagnosticsNode(jsonElement, this, false, null);
}
Future<List<RemoteDiagnosticsNode>> parseDiagnosticsNodesObservatory(
FutureOr<InstanceRef?> instanceRefFuture,
RemoteDiagnosticsNode? parent,
bool isProperty,
) async {
if (disposed || instanceRefFuture == null) return [];
final instanceRef = await instanceRefFuture;
if (disposed || instanceRefFuture == null) return [];
return parseDiagnosticsNodesHelper(
await instanceRefToJson(instanceRef) as List<Object?>?,
parent,
isProperty,
);
}
List<RemoteDiagnosticsNode> parseDiagnosticsNodesHelper(
List<Object?>? jsonObject,
RemoteDiagnosticsNode? parent,
bool isProperty,
) {
if (disposed || jsonObject == null) return const [];
final nodes = <RemoteDiagnosticsNode>[];
for (final element in jsonObject.cast<Map<String, Object?>>()) {
nodes.add(RemoteDiagnosticsNode(element, this, isProperty, parent));
}
return nodes;
}
Future<List<RemoteDiagnosticsNode>> parseDiagnosticsNodesDaemon(
FutureOr<Object?> jsonFuture,
RemoteDiagnosticsNode? parent,
bool isProperty,
) async {
if (disposed || jsonFuture == null) return const [];
return parseDiagnosticsNodesHelper(
await jsonFuture as List<Object?>?,
parent,
isProperty,
);
}
/// Requires that the InstanceRef is really referring to a String that is valid JSON.
Future<Object?> instanceRefToJson(InstanceRef? instanceRef) async {
if (disposed || instanceRef == null) return null;
final instance = await inspectorLibrary.getInstance(instanceRef, this);
if (disposed || instance == null) return null;
final json = instance.valueAsString;
if (json == null) return null;
return jsonDecode(json);
}
@override
Future<InstanceRef?> toObservatoryInstanceRef(
InspectorInstanceRef inspectorInstanceRef,
) async {
if (inspectorInstanceRef.id == null) {
return null;
}
return await invokeServiceMethodObservatoryInspectorRef(
'toObject',
inspectorInstanceRef,
);
}
Future<Instance?> getInstance(FutureOr<InstanceRef?> instanceRef) async {
if (disposed) {
return null;
}
return inspectorLibrary.getInstance(await instanceRef as InstanceRef, this);
}
/// Returns a Future with a Map of property names to Observatory
/// InstanceRef objects. This method is shorthand for individually evaluating
/// each of the getters specified by property names.
///
/// It would be nice if the Observatory protocol provided a built in method
/// to get InstanceRef objects for a list of properties but this is
/// sufficient although slightly less efficient. The Observatory protocol
/// does provide fast access to all fields as part of an Instance object
/// but that is inadequate as for many Flutter data objects that we want
/// to display visually we care about properties that are not necessarily
/// fields.
///
/// The future will immediately complete to null if the inspectorInstanceRef is null.
@override
Future<Map<String, InstanceRef>?> getDartObjectProperties(
InspectorInstanceRef inspectorInstanceRef,
final List<String> propertyNames,
) async {
final instanceRef = await toObservatoryInstanceRef(inspectorInstanceRef);
if (disposed) return null;
const objectName = 'that';
final expression =
'[${propertyNames.map((propertyName) => '$objectName.$propertyName').join(',')}]';
final scope = {objectName: instanceRef!.id!};
final instance = await getInstance(
inspectorLibrary.eval(expression, isAlive: this, scope: scope),
);
if (disposed) return null;
// We now have an instance object that is a Dart array of all the
// property values. Convert it back to a map from property name to
// property values.
final properties = <String, InstanceRef>{};
final values = instance!.elements!.toList().cast<InstanceRef>();
assert(values.length == propertyNames.length);
for (int i = 0; i < propertyNames.length; ++i) {
properties[propertyNames[i]] = values[i];
}
return properties;
}
@override
Future<Map<String, InstanceRef>?> getEnumPropertyValues(
InspectorInstanceRef ref,
) async {
if (disposed) return null;
if (ref.id == null) return null;
final instance = await getInstance(await toObservatoryInstanceRef(ref));
if (disposed || instance == null) return null;
final clazz = await inspectorLibrary.getClass(instance.classRef!, this);
if (disposed || clazz == null) return null;
final properties = <String, InstanceRef>{};
for (final field in clazz.fields!) {
final name = field.name!;
if (isPrivateMember(name)) {
// Needed to filter out _deleted_enum_sentinel synthetic property.
// If showing enum values is useful we could special case
// just the _deleted_enum_sentinel property name.
continue;
}
if (name == 'values') {
// Need to filter out the synthetic 'values' member.
// TODO(jacobr): detect that this properties return type is
// different and filter that way.
continue;
}
if (field.isConst! && field.isStatic!) {
properties[field.name!] = field.declaredType!;
}
}
return properties;
}
Future<SourcePosition?> getPropertyLocationHelper(
ClassRef classRef,
String name,
) async {
final clazz = await inspectorLibrary.getClass(classRef, this) as Class;
for (final f in clazz.functions!) {
// TODO(pq): check for properties that match name.
if (f.name == name) {
final func = await inspectorLibrary.getFunc(f, this) as Func;
final location = func.location;
throw UnimplementedError(
'getSourcePosition not implemented. $location',
);
}
}
final superClass = clazz.superClass;
return superClass == null
? null
: getPropertyLocationHelper(superClass, name);
}
Future<List<RemoteDiagnosticsNode>> getListHelper(
InspectorInstanceRef? instanceRef,
String methodName,
RemoteDiagnosticsNode? parent,
bool isProperty,
) async {
if (disposed) return const [];
return useDaemonApi
? parseDiagnosticsNodesDaemon(
invokeServiceMethodDaemonInspectorRef(methodName, instanceRef),
parent,
isProperty,
)
: parseDiagnosticsNodesObservatory(
invokeServiceMethodObservatoryInspectorRef(methodName, instanceRef),
parent,
isProperty,
);
}
/// Evaluate an expression where `object` references the `inspectorRef` or
/// `instanceRef` passed in.
Future<InstanceRef?> evalOnRef(
String expression,
GenericInstanceRef? ref,
) async {
final inspectorRef = ref?.diagnostic?.valueRef;
if (inspectorRef != null && inspectorRef.id != null) {
return await inspectorLibrary.eval(
"((object) => $expression)(${inspectorService.clientInspectorName}.instance.toObject('${inspectorRef.id}'))",
isAlive: this,
);
}
final instanceRef = ref!.instanceRef!;
return await inspectorLibrary.eval(
expression,
isAlive: this,
scope: <String, String>{'object': instanceRef.id!},
);
}
Future<bool> isInspectable(GenericInstanceRef ref) async {
if (disposed) {
return false;
}
try {
final result = await evalOnRef(
'object is Element || object is RenderObject',
ref,
);
if (disposed) return false;
return 'true' == result?.valueAsString;
} catch (e) {
// If the ref is invalid it is not inspectable.
return false;
}
}
@override
Future<List<RemoteDiagnosticsNode>> getProperties(
InspectorInstanceRef instanceRef,
) {
return getListHelper(
instanceRef,
WidgetInspectorServiceExtensions.getProperties.name,
null,
true,
);
}
@override
Future<List<RemoteDiagnosticsNode>> getChildren(
InspectorInstanceRef instanceRef,
bool summaryTree,
RemoteDiagnosticsNode? parent,
) {
return getListHelper(
instanceRef,
summaryTree
? WidgetInspectorServiceExtensions.getChildrenSummaryTree.name
: WidgetInspectorServiceExtensions.getChildrenDetailsSubtree.name,
parent,
false,
);
}
@override
bool isLocalClass(RemoteDiagnosticsNode node) =>
inspectorService.isLocalClass(node);
}
/// Class managing a group of inspector objects that can be freed by
/// a single call to dispose().
///
/// After dispose is called, all pending requests made with the ObjectGroup
/// will be skipped. This means that clients should not have to write any
/// special logic to handle orphaned requests.
class ObjectGroup extends InspectorObjectGroupBase {
ObjectGroup(super.debugName, this.inspectorService);
@override
final InspectorService inspectorService;
@override
bool canSetSelectionInspector = true;
Future<RemoteDiagnosticsNode?> getRoot(
FlutterTreeType type, {
bool isSummaryTree = false,
bool includeFullDetails = true,
}) {
// There is no excuse to call this method on a disposed group.
assert(!disposed);
switch (type) {
case FlutterTreeType.widget:
return getRootWidgetTree(
isSummaryTree: isSummaryTree,
includeFullDetails: includeFullDetails,
);
}
}
Future<RemoteDiagnosticsNode?> getRootWidgetTree({
required bool isSummaryTree,
required bool includeFullDetails,
}) {
return parseDiagnosticsNodeDaemon(
invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions.getRootWidgetTree.name,
{
'groupName': groupName,
'isSummaryTree': '$isSummaryTree',
'withPreviews': 'true',
'fullDetails': '$includeFullDetails',
},
),
);
}
// TODO these ones could be not needed.
/* TODO(jacobr): this probably isn't needed.
Future<List<DiagnosticsPathNode>> getParentChain(DiagnosticsNode target) async {
if (disposed) return null;
if (useDaemonApi) {