text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart'; /// Serves [handler] on [InternetAddress.anyIPv4] using the port returned by /// [listenPort]. /// /// The returned [Future] will complete using [terminateRequestFuture] after /// closing the server. Future<void> serveHandler(Handler handler) async { final port = listenPort(); final server = await serve( handler, InternetAddress.anyIPv4, // Allows external connections port, ); print('Serving at http://${server.address.host}:${server.port}'); await terminateRequestFuture(); await server.close(); } /// Returns the port to listen on from environment variable or uses the default /// `8080`. /// /// See https://cloud.google.com/run/docs/reference/container-contract#port int listenPort() => int.parse(Platform.environment['PORT'] ?? '8080'); /// Returns a [Future] that completes when the process receives a /// [ProcessSignal] requesting a shutdown. /// /// [ProcessSignal.sigint] is listened to on all platforms. /// /// [ProcessSignal.sigterm] is listened to on all platforms except Windows. Future<void> terminateRequestFuture() { final completer = Completer<bool>.sync(); // sigIntSub is copied below to avoid a race condition - ignoring this lint // ignore: cancel_subscriptions StreamSubscription? sigIntSub, sigTermSub; Future<void> signalHandler(ProcessSignal signal) async { print('Received signal $signal - closing'); final subCopy = sigIntSub; if (subCopy != null) { sigIntSub = null; await subCopy.cancel(); sigIntSub = null; if (sigTermSub != null) { await sigTermSub!.cancel(); sigTermSub = null; } completer.complete(true); } } sigIntSub = ProcessSignal.sigint.watch().listen(signalHandler); // SIGTERM is not supported on Windows. Attempting to register a SIGTERM // handler raises an exception. if (!Platform.isWindows) { sigTermSub = ProcessSignal.sigterm.watch().listen(signalHandler); } return completer.future; }
codelabs/in_app_purchases/complete/dart-backend/lib/helpers.dart/0
{ "file_path": "codelabs/in_app_purchases/complete/dart-backend/lib/helpers.dart", "repo_id": "codelabs", "token_count": 723 }
50
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:firebase_backend_dart/helpers.dart'; import 'package:shelf_router/shelf_router.dart'; Future<void> main() async { final router = Router(); // Start service await serveHandler(router.call); }
codelabs/in_app_purchases/step_00/dart-backend/bin/server.dart/0
{ "file_path": "codelabs/in_app_purchases/step_00/dart-backend/bin/server.dart", "repo_id": "codelabs", "token_count": 130 }
51
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:firebase_backend_dart/app_store_purchase_handler.dart'; import 'package:firebase_backend_dart/google_play_purchase_handler.dart'; import 'package:firebase_backend_dart/helpers.dart'; import 'package:firebase_backend_dart/iap_repository.dart'; import 'package:firebase_backend_dart/products.dart'; import 'package:firebase_backend_dart/purchase_handler.dart'; import 'package:googleapis/androidpublisher/v3.dart' as ap; import 'package:googleapis/firestore/v1.dart' as fs; import 'package:googleapis_auth/auth_io.dart' as auth; import 'package:shelf/shelf.dart'; import 'package:shelf_router/shelf_router.dart'; /// Creates the Google Play and Apple Store [PurchaseHandler] /// and their dependencies Future<Map<String, PurchaseHandler>> _createPurchaseHandlers() async { // Configure Android Publisher API access final serviceAccountGooglePlay = File('assets/service-account-google-play.json').readAsStringSync(); final clientCredentialsGooglePlay = auth.ServiceAccountCredentials.fromJson(serviceAccountGooglePlay); final clientGooglePlay = await auth.clientViaServiceAccount(clientCredentialsGooglePlay, [ ap.AndroidPublisherApi.androidpublisherScope, ]); final androidPublisher = ap.AndroidPublisherApi(clientGooglePlay); // Configure Firestore API access final serviceAccountFirebase = File('assets/service-account-firebase.json').readAsStringSync(); final clientCredentialsFirebase = auth.ServiceAccountCredentials.fromJson(serviceAccountFirebase); final clientFirebase = await auth.clientViaServiceAccount(clientCredentialsFirebase, [ fs.FirestoreApi.cloudPlatformScope, ]); final firestoreApi = fs.FirestoreApi(clientFirebase); final dynamic json = jsonDecode(serviceAccountFirebase); final projectId = json['project_id'] as String; final iapRepository = IapRepository(firestoreApi, projectId); return { 'google_play': GooglePlayPurchaseHandler( androidPublisher, iapRepository, ), 'app_store': AppStorePurchaseHandler( iapRepository, ), }; } Future<void> main() async { final router = Router(); final purchaseHandlers = await _createPurchaseHandlers(); /// Warning: This endpoint has no security /// and does not implement user authentication. /// Production applications should implement authentication. // ignore: avoid_types_on_closure_parameters router.post('/verifypurchase', (Request request) async { final dynamic payload = json.decode(await request.readAsString()); // NOTE: userId should be obtained using authentication methods. // source from PurchaseDetails.verificationData.source // productData product data based on the productId // token from PurchaseDetails.verificationData.serverVerificationData final (:userId, :source, :productData, :token) = getPurchaseData(payload); // Will call to verifyPurchase on // [GooglePlayPurchaseHandler] or [AppleStorePurchaseHandler] final result = await purchaseHandlers[source]!.verifyPurchase( userId: userId, productData: productData, token: token, ); if (result) { // Note: Better success response recommended return Response.ok('all good!'); } else { // Note: Better error handling recommended return Response.internalServerError(); } }); // Start service await serveHandler(router.call); } ({ String userId, String source, ProductData productData, String token, }) getPurchaseData(dynamic payload) { if (payload case { 'userId': String userId, 'source': String source, 'productId': String productId, 'verificationData': String token, }) { return ( userId: userId, source: source, productData: productDataMap[productId]!, token: token, ); } else { throw const FormatException('Unexpected JSON'); } }
codelabs/in_app_purchases/step_09/dart-backend/bin/server.dart/0
{ "file_path": "codelabs/in_app_purchases/step_09/dart-backend/bin/server.dart", "repo_id": "codelabs", "token_count": 1349 }
52
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/namer/step_05_c_card_padding/android/gradle.properties/0
{ "file_path": "codelabs/namer/step_05_c_card_padding/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
53
#include "Generated.xcconfig"
codelabs/namer/step_05_e_text_style/ios/Flutter/Release.xcconfig/0
{ "file_path": "codelabs/namer/step_05_e_text_style/ios/Flutter/Release.xcconfig", "repo_id": "codelabs", "token_count": 12 }
54
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/namer/step_05_e_text_style/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "codelabs/namer/step_05_e_text_style/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "codelabs", "token_count": 19 }
55
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/namer/step_05_f_accessibility/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/namer/step_05_f_accessibility/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
56
#include "Generated.xcconfig"
codelabs/namer/step_06_a_business_logic/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/namer/step_06_a_business_logic/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
57
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/namer/step_06_a_business_logic/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "codelabs/namer/step_06_a_business_logic/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "codelabs", "token_count": 19 }
58
#import "GeneratedPluginRegistrant.h"
codelabs/namer/step_06_b_add_row/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/namer/step_06_b_add_row/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
59
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/namer/step_06_b_add_row/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/namer/step_06_b_add_row/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
60
// Copyright 2023 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:extra_alignments/extra_alignments.dart'; import 'package:flutter/material.dart'; import 'package:gap/gap.dart'; import '../assets.dart'; import '../common/ui_scaler.dart'; import '../styles.dart'; class TitleScreenUi extends StatelessWidget { const TitleScreenUi({ super.key, }); @override Widget build(BuildContext context) { return const Padding( padding: EdgeInsets.symmetric(vertical: 40, horizontal: 50), child: Stack( children: [ /// Title Text TopLeft( child: UiScaler( alignment: Alignment.topLeft, child: _TitleText(), ), ), ], ), ); } } class _TitleText extends StatelessWidget { const _TitleText(); @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Gap(20), Row( mainAxisSize: MainAxisSize.min, children: [ Transform.translate( offset: Offset(-(TextStyles.h1.letterSpacing! * .5), 0), child: Text('OUTPOST', style: TextStyles.h1), ), Image.asset(AssetPaths.titleSelectedLeft, height: 65), Text('57', style: TextStyles.h2), Image.asset(AssetPaths.titleSelectedRight, height: 65), ], ), Text('INTO THE UNKNOWN', style: TextStyles.h3), ], ); } }
codelabs/next-gen-ui/step_03_a/lib/title_screen/title_screen_ui.dart/0
{ "file_path": "codelabs/next-gen-ui/step_03_a/lib/title_screen/title_screen_ui.dart", "repo_id": "codelabs", "token_count": 749 }
61
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/next-gen-ui/step_03_a/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/next-gen-ui/step_03_a/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
62
#import "GeneratedPluginRegistrant.h"
codelabs/next-gen-ui/step_03_b/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/next-gen-ui/step_03_b/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
63
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
codelabs/next-gen-ui/step_04_a/android/gradle.properties/0
{ "file_path": "codelabs/next-gen-ui/step_04_a/android/gradle.properties", "repo_id": "codelabs", "token_count": 30 }
64
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/next-gen-ui/step_05_a/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/next-gen-ui/step_05_a/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
65
#import "GeneratedPluginRegistrant.h"
codelabs/next-gen-ui/step_05_b/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/next-gen-ui/step_05_b/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
66
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/testing_codelab/step_04/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/testing_codelab/step_04/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
67
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/tfagents-flutter/step0/frontend/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/tfagents-flutter/step0/frontend/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
68
#import "GeneratedPluginRegistrant.h"
codelabs/tfagents-flutter/step3/frontend/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/tfagents-flutter/step3/frontend/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
69
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
codelabs/tfagents-flutter/step3/frontend/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "codelabs/tfagents-flutter/step3/frontend/macos/Runner/Configs/Debug.xcconfig", "repo_id": "codelabs", "token_count": 32 }
70
#include "Generated.xcconfig"
codelabs/tfagents-flutter/step4/frontend/ios/Flutter/Debug.xcconfig/0
{ "file_path": "codelabs/tfagents-flutter/step4/frontend/ios/Flutter/Debug.xcconfig", "repo_id": "codelabs", "token_count": 12 }
71
#include "ephemeral/Flutter-Generated.xcconfig"
codelabs/tfagents-flutter/step4/frontend/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "codelabs/tfagents-flutter/step4/frontend/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "codelabs", "token_count": 19 }
72
#include "Generated.xcconfig"
codelabs/tfrs-flutter/finished/frontend/ios/Flutter/Release.xcconfig/0
{ "file_path": "codelabs/tfrs-flutter/finished/frontend/ios/Flutter/Release.xcconfig", "repo_id": "codelabs", "token_count": 12 }
73
#import "GeneratedPluginRegistrant.h"
codelabs/tfrs-flutter/step1/frontend/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "codelabs/tfrs-flutter/step1/frontend/ios/Runner/Runner-Bridging-Header.h", "repo_id": "codelabs", "token_count": 13 }
74
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
codelabs/tfrs-flutter/step1/frontend/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "codelabs/tfrs-flutter/step1/frontend/macos/Runner/Configs/Release.xcconfig", "repo_id": "codelabs", "token_count": 32 }
75
#include "Generated.xcconfig"
codelabs/tfserving-flutter/codelab2/finished/ios/Flutter/Release.xcconfig/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/finished/ios/Flutter/Release.xcconfig", "repo_id": "codelabs", "token_count": 12 }
76
// // Generated file. Do not edit. // // clang-format off #ifndef GeneratedPluginRegistrant_h #define GeneratedPluginRegistrant_h #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN @interface GeneratedPluginRegistrant : NSObject + (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry; @end NS_ASSUME_NONNULL_END #endif /* GeneratedPluginRegistrant_h */
codelabs/tfserving-flutter/codelab2/starter/ios/Runner/GeneratedPluginRegistrant.h/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/ios/Runner/GeneratedPluginRegistrant.h", "repo_id": "codelabs", "token_count": 138 }
77
/// // Generated code. Do not modify. // source: tensorflow/core/example/feature.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/example/feature.pbenum.dart/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/example/feature.pbenum.dart", "repo_id": "codelabs", "token_count": 115 }
78
/// // Generated code. Do not modify. // source: tensorflow/core/framework/node_def.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package import 'dart:core' as $core; import 'dart:convert' as $convert; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use nodeDefDescriptor instead') const NodeDef$json = const { '1': 'NodeDef', '2': const [ const {'1': 'name', '3': 1, '4': 1, '5': 9, '10': 'name'}, const {'1': 'op', '3': 2, '4': 1, '5': 9, '10': 'op'}, const {'1': 'input', '3': 3, '4': 3, '5': 9, '10': 'input'}, const {'1': 'device', '3': 4, '4': 1, '5': 9, '10': 'device'}, const { '1': 'attr', '3': 5, '4': 3, '5': 11, '6': '.tensorflow.NodeDef.AttrEntry', '10': 'attr' }, const { '1': 'experimental_debug_info', '3': 6, '4': 1, '5': 11, '6': '.tensorflow.NodeDef.ExperimentalDebugInfo', '10': 'experimentalDebugInfo' }, const { '1': 'experimental_type', '3': 7, '4': 1, '5': 11, '6': '.tensorflow.FullTypeDef', '10': 'experimentalType' }, ], '3': const [NodeDef_AttrEntry$json, NodeDef_ExperimentalDebugInfo$json], }; @$core.Deprecated('Use nodeDefDescriptor instead') const NodeDef_AttrEntry$json = const { '1': 'AttrEntry', '2': const [ const {'1': 'key', '3': 1, '4': 1, '5': 9, '10': 'key'}, const { '1': 'value', '3': 2, '4': 1, '5': 11, '6': '.tensorflow.AttrValue', '10': 'value' }, ], '7': const {'7': true}, }; @$core.Deprecated('Use nodeDefDescriptor instead') const NodeDef_ExperimentalDebugInfo$json = const { '1': 'ExperimentalDebugInfo', '2': const [ const { '1': 'original_node_names', '3': 1, '4': 3, '5': 9, '10': 'originalNodeNames' }, const { '1': 'original_func_names', '3': 2, '4': 3, '5': 9, '10': 'originalFuncNames' }, ], }; /// Descriptor for `NodeDef`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List nodeDefDescriptor = $convert.base64Decode( 'CgdOb2RlRGVmEhIKBG5hbWUYASABKAlSBG5hbWUSDgoCb3AYAiABKAlSAm9wEhQKBWlucHV0GAMgAygJUgVpbnB1dBIWCgZkZXZpY2UYBCABKAlSBmRldmljZRIxCgRhdHRyGAUgAygLMh0udGVuc29yZmxvdy5Ob2RlRGVmLkF0dHJFbnRyeVIEYXR0chJhChdleHBlcmltZW50YWxfZGVidWdfaW5mbxgGIAEoCzIpLnRlbnNvcmZsb3cuTm9kZURlZi5FeHBlcmltZW50YWxEZWJ1Z0luZm9SFWV4cGVyaW1lbnRhbERlYnVnSW5mbxJEChFleHBlcmltZW50YWxfdHlwZRgHIAEoCzIXLnRlbnNvcmZsb3cuRnVsbFR5cGVEZWZSEGV4cGVyaW1lbnRhbFR5cGUaTgoJQXR0ckVudHJ5EhAKA2tleRgBIAEoCVIDa2V5EisKBXZhbHVlGAIgASgLMhUudGVuc29yZmxvdy5BdHRyVmFsdWVSBXZhbHVlOgI4ARp3ChVFeHBlcmltZW50YWxEZWJ1Z0luZm8SLgoTb3JpZ2luYWxfbm9kZV9uYW1lcxgBIAMoCVIRb3JpZ2luYWxOb2RlTmFtZXMSLgoTb3JpZ2luYWxfZnVuY19uYW1lcxgCIAMoCVIRb3JpZ2luYWxGdW5jTmFtZXM=');
codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/node_def.pbjson.dart/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/node_def.pbjson.dart", "repo_id": "codelabs", "token_count": 1629 }
79
/// // Generated code. Do not modify. // source: tensorflow/core/framework/variable.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields import 'dart:core' as $core; import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:protobuf/protobuf.dart' as $pb; import 'variable.pbenum.dart'; export 'variable.pbenum.dart'; class VariableDef extends $pb.GeneratedMessage { static final $pb.BuilderInfo _i = $pb.BuilderInfo( const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'VariableDef', package: const $pb.PackageName( const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'tensorflow'), createEmptyInstance: create) ..aOS( 1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'variableName') ..aOS( 2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'initializerName') ..aOS( 3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'snapshotName') ..aOM<SaveSliceInfoDef>( 4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'saveSliceInfoDef', subBuilder: SaveSliceInfoDef.create) ..aOB( 5, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'isResource') ..aOS( 6, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'initialValueName') ..aOB( 7, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'trainable') ..e<VariableSynchronization>( 8, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'synchronization', $pb.PbFieldType.OE, defaultOrMaker: VariableSynchronization.VARIABLE_SYNCHRONIZATION_AUTO, valueOf: VariableSynchronization.valueOf, enumValues: VariableSynchronization.values) ..e<VariableAggregation>( 9, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'aggregation', $pb.PbFieldType.OE, defaultOrMaker: VariableAggregation.VARIABLE_AGGREGATION_NONE, valueOf: VariableAggregation.valueOf, enumValues: VariableAggregation.values) ..hasRequiredFields = false; VariableDef._() : super(); factory VariableDef({ $core.String? variableName, $core.String? initializerName, $core.String? snapshotName, SaveSliceInfoDef? saveSliceInfoDef, $core.bool? isResource, $core.String? initialValueName, $core.bool? trainable, VariableSynchronization? synchronization, VariableAggregation? aggregation, }) { final _result = create(); if (variableName != null) { _result.variableName = variableName; } if (initializerName != null) { _result.initializerName = initializerName; } if (snapshotName != null) { _result.snapshotName = snapshotName; } if (saveSliceInfoDef != null) { _result.saveSliceInfoDef = saveSliceInfoDef; } if (isResource != null) { _result.isResource = isResource; } if (initialValueName != null) { _result.initialValueName = initialValueName; } if (trainable != null) { _result.trainable = trainable; } if (synchronization != null) { _result.synchronization = synchronization; } if (aggregation != null) { _result.aggregation = aggregation; } return _result; } factory VariableDef.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); factory VariableDef.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); @$core.Deprecated('Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' 'Will be removed in next major version') VariableDef clone() => VariableDef()..mergeFromMessage(this); @$core.Deprecated('Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Will be removed in next major version') VariableDef copyWith(void Function(VariableDef) updates) => super.copyWith((message) => updates(message as VariableDef)) as VariableDef; // ignore: deprecated_member_use $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static VariableDef create() => VariableDef._(); VariableDef createEmptyInstance() => create(); static $pb.PbList<VariableDef> createRepeated() => $pb.PbList<VariableDef>(); @$core.pragma('dart2js:noInline') static VariableDef getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<VariableDef>(create); static VariableDef? _defaultInstance; @$pb.TagNumber(1) $core.String get variableName => $_getSZ(0); @$pb.TagNumber(1) set variableName($core.String v) { $_setString(0, v); } @$pb.TagNumber(1) $core.bool hasVariableName() => $_has(0); @$pb.TagNumber(1) void clearVariableName() => clearField(1); @$pb.TagNumber(2) $core.String get initializerName => $_getSZ(1); @$pb.TagNumber(2) set initializerName($core.String v) { $_setString(1, v); } @$pb.TagNumber(2) $core.bool hasInitializerName() => $_has(1); @$pb.TagNumber(2) void clearInitializerName() => clearField(2); @$pb.TagNumber(3) $core.String get snapshotName => $_getSZ(2); @$pb.TagNumber(3) set snapshotName($core.String v) { $_setString(2, v); } @$pb.TagNumber(3) $core.bool hasSnapshotName() => $_has(2); @$pb.TagNumber(3) void clearSnapshotName() => clearField(3); @$pb.TagNumber(4) SaveSliceInfoDef get saveSliceInfoDef => $_getN(3); @$pb.TagNumber(4) set saveSliceInfoDef(SaveSliceInfoDef v) { setField(4, v); } @$pb.TagNumber(4) $core.bool hasSaveSliceInfoDef() => $_has(3); @$pb.TagNumber(4) void clearSaveSliceInfoDef() => clearField(4); @$pb.TagNumber(4) SaveSliceInfoDef ensureSaveSliceInfoDef() => $_ensure(3); @$pb.TagNumber(5) $core.bool get isResource => $_getBF(4); @$pb.TagNumber(5) set isResource($core.bool v) { $_setBool(4, v); } @$pb.TagNumber(5) $core.bool hasIsResource() => $_has(4); @$pb.TagNumber(5) void clearIsResource() => clearField(5); @$pb.TagNumber(6) $core.String get initialValueName => $_getSZ(5); @$pb.TagNumber(6) set initialValueName($core.String v) { $_setString(5, v); } @$pb.TagNumber(6) $core.bool hasInitialValueName() => $_has(5); @$pb.TagNumber(6) void clearInitialValueName() => clearField(6); @$pb.TagNumber(7) $core.bool get trainable => $_getBF(6); @$pb.TagNumber(7) set trainable($core.bool v) { $_setBool(6, v); } @$pb.TagNumber(7) $core.bool hasTrainable() => $_has(6); @$pb.TagNumber(7) void clearTrainable() => clearField(7); @$pb.TagNumber(8) VariableSynchronization get synchronization => $_getN(7); @$pb.TagNumber(8) set synchronization(VariableSynchronization v) { setField(8, v); } @$pb.TagNumber(8) $core.bool hasSynchronization() => $_has(7); @$pb.TagNumber(8) void clearSynchronization() => clearField(8); @$pb.TagNumber(9) VariableAggregation get aggregation => $_getN(8); @$pb.TagNumber(9) set aggregation(VariableAggregation v) { setField(9, v); } @$pb.TagNumber(9) $core.bool hasAggregation() => $_has(8); @$pb.TagNumber(9) void clearAggregation() => clearField(9); } class SaveSliceInfoDef extends $pb.GeneratedMessage { static final $pb.BuilderInfo _i = $pb.BuilderInfo( const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'SaveSliceInfoDef', package: const $pb.PackageName( const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'tensorflow'), createEmptyInstance: create) ..aOS( 1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'fullName') ..p<$fixnum.Int64>( 2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'fullShape', $pb.PbFieldType.P6) ..p<$fixnum.Int64>( 3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'varOffset', $pb.PbFieldType.P6) ..p<$fixnum.Int64>( 4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'varShape', $pb.PbFieldType.P6) ..hasRequiredFields = false; SaveSliceInfoDef._() : super(); factory SaveSliceInfoDef({ $core.String? fullName, $core.Iterable<$fixnum.Int64>? fullShape, $core.Iterable<$fixnum.Int64>? varOffset, $core.Iterable<$fixnum.Int64>? varShape, }) { final _result = create(); if (fullName != null) { _result.fullName = fullName; } if (fullShape != null) { _result.fullShape.addAll(fullShape); } if (varOffset != null) { _result.varOffset.addAll(varOffset); } if (varShape != null) { _result.varShape.addAll(varShape); } return _result; } factory SaveSliceInfoDef.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); factory SaveSliceInfoDef.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); @$core.Deprecated('Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' 'Will be removed in next major version') SaveSliceInfoDef clone() => SaveSliceInfoDef()..mergeFromMessage(this); @$core.Deprecated('Using this can add significant overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Will be removed in next major version') SaveSliceInfoDef copyWith(void Function(SaveSliceInfoDef) updates) => super.copyWith((message) => updates(message as SaveSliceInfoDef)) as SaveSliceInfoDef; // ignore: deprecated_member_use $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SaveSliceInfoDef create() => SaveSliceInfoDef._(); SaveSliceInfoDef createEmptyInstance() => create(); static $pb.PbList<SaveSliceInfoDef> createRepeated() => $pb.PbList<SaveSliceInfoDef>(); @$core.pragma('dart2js:noInline') static SaveSliceInfoDef getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<SaveSliceInfoDef>(create); static SaveSliceInfoDef? _defaultInstance; @$pb.TagNumber(1) $core.String get fullName => $_getSZ(0); @$pb.TagNumber(1) set fullName($core.String v) { $_setString(0, v); } @$pb.TagNumber(1) $core.bool hasFullName() => $_has(0); @$pb.TagNumber(1) void clearFullName() => clearField(1); @$pb.TagNumber(2) $core.List<$fixnum.Int64> get fullShape => $_getList(1); @$pb.TagNumber(3) $core.List<$fixnum.Int64> get varOffset => $_getList(2); @$pb.TagNumber(4) $core.List<$fixnum.Int64> get varShape => $_getList(3); }
codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/variable.pb.dart/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/variable.pb.dart", "repo_id": "codelabs", "token_count": 4912 }
80
/// // Generated code. Do not modify. // source: tensorflow/core/protobuf/struct.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields // ignore_for_file: UNDEFINED_SHOWN_NAME import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; class TypeSpecProto_TypeSpecClass extends $pb.ProtobufEnum { static const TypeSpecProto_TypeSpecClass UNKNOWN = TypeSpecProto_TypeSpecClass._( 0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'UNKNOWN'); static const TypeSpecProto_TypeSpecClass SPARSE_TENSOR_SPEC = TypeSpecProto_TypeSpecClass._( 1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'SPARSE_TENSOR_SPEC'); static const TypeSpecProto_TypeSpecClass INDEXED_SLICES_SPEC = TypeSpecProto_TypeSpecClass._( 2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'INDEXED_SLICES_SPEC'); static const TypeSpecProto_TypeSpecClass RAGGED_TENSOR_SPEC = TypeSpecProto_TypeSpecClass._( 3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'RAGGED_TENSOR_SPEC'); static const TypeSpecProto_TypeSpecClass TENSOR_ARRAY_SPEC = TypeSpecProto_TypeSpecClass._( 4, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'TENSOR_ARRAY_SPEC'); static const TypeSpecProto_TypeSpecClass DATA_DATASET_SPEC = TypeSpecProto_TypeSpecClass._( 5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DATA_DATASET_SPEC'); static const TypeSpecProto_TypeSpecClass DATA_ITERATOR_SPEC = TypeSpecProto_TypeSpecClass._( 6, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'DATA_ITERATOR_SPEC'); static const TypeSpecProto_TypeSpecClass OPTIONAL_SPEC = TypeSpecProto_TypeSpecClass._( 7, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'OPTIONAL_SPEC'); static const TypeSpecProto_TypeSpecClass PER_REPLICA_SPEC = TypeSpecProto_TypeSpecClass._( 8, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PER_REPLICA_SPEC'); static const TypeSpecProto_TypeSpecClass VARIABLE_SPEC = TypeSpecProto_TypeSpecClass._( 9, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'VARIABLE_SPEC'); static const TypeSpecProto_TypeSpecClass ROW_PARTITION_SPEC = TypeSpecProto_TypeSpecClass._( 10, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ROW_PARTITION_SPEC'); static const TypeSpecProto_TypeSpecClass REGISTERED_TYPE_SPEC = TypeSpecProto_TypeSpecClass._( 12, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'REGISTERED_TYPE_SPEC'); static const TypeSpecProto_TypeSpecClass EXTENSION_TYPE_SPEC = TypeSpecProto_TypeSpecClass._( 13, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'EXTENSION_TYPE_SPEC'); static const $core.List<TypeSpecProto_TypeSpecClass> values = <TypeSpecProto_TypeSpecClass>[ UNKNOWN, SPARSE_TENSOR_SPEC, INDEXED_SLICES_SPEC, RAGGED_TENSOR_SPEC, TENSOR_ARRAY_SPEC, DATA_DATASET_SPEC, DATA_ITERATOR_SPEC, OPTIONAL_SPEC, PER_REPLICA_SPEC, VARIABLE_SPEC, ROW_PARTITION_SPEC, REGISTERED_TYPE_SPEC, EXTENSION_TYPE_SPEC, ]; static final $core.Map<$core.int, TypeSpecProto_TypeSpecClass> _byValue = $pb.ProtobufEnum.initByValue(values); static TypeSpecProto_TypeSpecClass? valueOf($core.int value) => _byValue[value]; const TypeSpecProto_TypeSpecClass._($core.int v, $core.String n) : super(v, n); }
codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/protobuf/struct.pbenum.dart/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/protobuf/struct.pbenum.dart", "repo_id": "codelabs", "token_count": 2036 }
81
/// // Generated code. Do not modify. // source: tensorflow_serving/apis/input.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package import 'dart:core' as $core; import 'dart:convert' as $convert; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use exampleListDescriptor instead') const ExampleList$json = const { '1': 'ExampleList', '2': const [ const { '1': 'examples', '3': 1, '4': 3, '5': 11, '6': '.tensorflow.Example', '10': 'examples' }, ], }; /// Descriptor for `ExampleList`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List exampleListDescriptor = $convert.base64Decode( 'CgtFeGFtcGxlTGlzdBIvCghleGFtcGxlcxgBIAMoCzITLnRlbnNvcmZsb3cuRXhhbXBsZVIIZXhhbXBsZXM='); @$core.Deprecated('Use exampleListWithContextDescriptor instead') const ExampleListWithContext$json = const { '1': 'ExampleListWithContext', '2': const [ const { '1': 'examples', '3': 1, '4': 3, '5': 11, '6': '.tensorflow.Example', '10': 'examples' }, const { '1': 'context', '3': 2, '4': 1, '5': 11, '6': '.tensorflow.Example', '10': 'context' }, ], }; /// Descriptor for `ExampleListWithContext`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List exampleListWithContextDescriptor = $convert.base64Decode( 'ChZFeGFtcGxlTGlzdFdpdGhDb250ZXh0Ei8KCGV4YW1wbGVzGAEgAygLMhMudGVuc29yZmxvdy5FeGFtcGxlUghleGFtcGxlcxItCgdjb250ZXh0GAIgASgLMhMudGVuc29yZmxvdy5FeGFtcGxlUgdjb250ZXh0'); @$core.Deprecated('Use inputDescriptor instead') const Input$json = const { '1': 'Input', '2': const [ const { '1': 'example_list', '3': 1, '4': 1, '5': 11, '6': '.tensorflow.serving.ExampleList', '8': const {'5': true}, '9': 0, '10': 'exampleList', }, const { '1': 'example_list_with_context', '3': 2, '4': 1, '5': 11, '6': '.tensorflow.serving.ExampleListWithContext', '8': const {'5': true}, '9': 0, '10': 'exampleListWithContext', }, ], '8': const [ const {'1': 'kind'}, ], }; /// Descriptor for `Input`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List inputDescriptor = $convert.base64Decode( 'CgVJbnB1dBJICgxleGFtcGxlX2xpc3QYASABKAsyHy50ZW5zb3JmbG93LnNlcnZpbmcuRXhhbXBsZUxpc3RCAigBSABSC2V4YW1wbGVMaXN0EmsKGWV4YW1wbGVfbGlzdF93aXRoX2NvbnRleHQYAiABKAsyKi50ZW5zb3JmbG93LnNlcnZpbmcuRXhhbXBsZUxpc3RXaXRoQ29udGV4dEICKAFIAFIWZXhhbXBsZUxpc3RXaXRoQ29udGV4dEIGCgRraW5k');
codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/input.pbjson.dart/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/input.pbjson.dart", "repo_id": "codelabs", "token_count": 1389 }
82
// Protocol messages for describing input data Examples for machine learning // model training or inference. syntax = "proto3"; package tensorflow; import "tensorflow/core/example/feature.proto"; option cc_enable_arenas = true; option java_outer_classname = "ExampleProtos"; option java_multiple_files = true; option java_package = "org.tensorflow.example"; option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/example/example_protos_go_proto"; // An Example is a mostly-normalized data format for storing data for // training and inference. It contains a key-value store (features); where // each key (string) maps to a Feature message (which is oneof packed BytesList, // FloatList, or Int64List). This flexible and compact format allows the // storage of large amounts of typed data, but requires that the data shape // and use be determined by the configuration files and parsers that are used to // read and write this format. That is, the Example is mostly *not* a // self-describing format. In TensorFlow, Examples are read in row-major // format, so any configuration that describes data with rank-2 or above // should keep this in mind. If you flatten a matrix into a FloatList it should // be stored as [ row 0 ... row 1 ... row M-1 ] // // An Example for a movie recommendation application: // features { // feature { // key: "age" // value { float_list { // value: 29.0 // }} // } // feature { // key: "movie" // value { bytes_list { // value: "The Shawshank Redemption" // value: "Fight Club" // }} // } // feature { // key: "movie_ratings" // value { float_list { // value: 9.0 // value: 9.7 // }} // } // feature { // key: "suggestion" // value { bytes_list { // value: "Inception" // }} // } // # Note that this feature exists to be used as a label in training. // # E.g., if training a logistic regression model to predict purchase // # probability in our learning tool we would set the label feature to // # "suggestion_purchased". // feature { // key: "suggestion_purchased" // value { float_list { // value: 1.0 // }} // } // # Similar to "suggestion_purchased" above this feature exists to be used // # as a label in training. // # E.g., if training a linear regression model to predict purchase // # price in our learning tool we would set the label feature to // # "purchase_price". // feature { // key: "purchase_price" // value { float_list { // value: 9.99 // }} // } // } // // A conformant Example data set obeys the following conventions: // - If a Feature K exists in one example with data type T, it must be of // type T in all other examples when present. It may be omitted. // - The number of instances of Feature K list data may vary across examples, // depending on the requirements of the model. // - If a Feature K doesn't exist in an example, a K-specific default will be // used, if configured. // - If a Feature K exists in an example but contains no items, the intent // is considered to be an empty tensor and no default will be used. message Example { Features features = 1; } // A SequenceExample is an Example representing one or more sequences, and // some context. The context contains features which apply to the entire // example. The feature_lists contain a key, value map where each key is // associated with a repeated set of Features (a FeatureList). // A FeatureList thus represents the values of a feature identified by its key // over time / frames. // // Below is a SequenceExample for a movie recommendation application recording a // sequence of ratings by a user. The time-independent features ("locale", // "age", "favorites") describing the user are part of the context. The sequence // of movies the user rated are part of the feature_lists. For each movie in the // sequence we have information on its name and actors and the user's rating. // This information is recorded in three separate feature_list(s). // In the example below there are only two movies. All three feature_list(s), // namely "movie_ratings", "movie_names", and "actors" have a feature value for // both movies. Note, that "actors" is itself a bytes_list with multiple // strings per movie. // // context: { // feature: { // key : "locale" // value: { // bytes_list: { // value: [ "pt_BR" ] // } // } // } // feature: { // key : "age" // value: { // float_list: { // value: [ 19.0 ] // } // } // } // feature: { // key : "favorites" // value: { // bytes_list: { // value: [ "Majesty Rose", "Savannah Outen", "One Direction" ] // } // } // } // } // feature_lists: { // feature_list: { // key : "movie_ratings" // value: { // feature: { // float_list: { // value: [ 4.5 ] // } // } // feature: { // float_list: { // value: [ 5.0 ] // } // } // } // } // feature_list: { // key : "movie_names" // value: { // feature: { // bytes_list: { // value: [ "The Shawshank Redemption" ] // } // } // feature: { // bytes_list: { // value: [ "Fight Club" ] // } // } // } // } // feature_list: { // key : "actors" // value: { // feature: { // bytes_list: { // value: [ "Tim Robbins", "Morgan Freeman" ] // } // } // feature: { // bytes_list: { // value: [ "Brad Pitt", "Edward Norton", "Helena Bonham Carter" ] // } // } // } // } // } // // A conformant SequenceExample data set obeys the following conventions: // // Context: // - All conformant context features K must obey the same conventions as // a conformant Example's features (see above). // Feature lists: // - A FeatureList L may be missing in an example; it is up to the // parser configuration to determine if this is allowed or considered // an empty list (zero length). // - If a FeatureList L exists, it may be empty (zero length). // - If a FeatureList L is non-empty, all features within the FeatureList // must have the same data type T. Even across SequenceExamples, the type T // of the FeatureList identified by the same key must be the same. An entry // without any values may serve as an empty feature. // - If a FeatureList L is non-empty, it is up to the parser configuration // to determine if all features within the FeatureList must // have the same size. The same holds for this FeatureList across multiple // examples. // - For sequence modeling, e.g.: // http://colah.github.io/posts/2015-08-Understanding-LSTMs/ // https://github.com/tensorflow/nmt // the feature lists represent a sequence of frames. // In this scenario, all FeatureLists in a SequenceExample have the same // number of Feature messages, so that the ith element in each FeatureList // is part of the ith frame (or time step). // Examples of conformant and non-conformant examples' FeatureLists: // // Conformant FeatureLists: // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0 ] } } } // } } // // Non-conformant FeatureLists (mismatched types): // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { int64_list: { value: [ 5 ] } } } // } } // // Conditionally conformant FeatureLists, the parser configuration determines // if the feature sizes must match: // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0, 6.0 ] } } } // } } // // Conformant pair of SequenceExample // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0 ] } } } // } } // and: // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0 ] } } // feature: { float_list: { value: [ 2.0 ] } } } // } } // // Conformant pair of SequenceExample // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0 ] } } } // } } // and: // feature_lists: { feature_list: { // key: "movie_ratings" // value: { } // } } // // Conditionally conformant pair of SequenceExample, the parser configuration // determines if the second feature_lists is consistent (zero-length) or // invalid (missing "movie_ratings"): // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0 ] } } } // } } // and: // feature_lists: { } // // Non-conformant pair of SequenceExample (mismatched types) // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0 ] } } } // } } // and: // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { int64_list: { value: [ 4 ] } } // feature: { int64_list: { value: [ 5 ] } } // feature: { int64_list: { value: [ 2 ] } } } // } } // // Conditionally conformant pair of SequenceExample; the parser configuration // determines if the feature sizes must match: // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.5 ] } } // feature: { float_list: { value: [ 5.0 ] } } } // } } // and: // feature_lists: { feature_list: { // key: "movie_ratings" // value: { feature: { float_list: { value: [ 4.0 ] } } // feature: { float_list: { value: [ 5.0, 3.0 ] } } // } } message SequenceExample { Features context = 1; FeatureLists feature_lists = 2; }
codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/example/example.proto/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/example/example.proto", "repo_id": "codelabs", "token_count": 4099 }
83
syntax = "proto3"; package tensorflow; option cc_enable_arenas = true; option java_outer_classname = "SaverProtos"; option java_multiple_files = true; option java_package = "org.tensorflow.util"; option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/protobuf/for_core_protos_go_proto"; // Protocol buffer representing the configuration of a Saver. message SaverDef { // The name of the tensor in which to specify the filename when saving or // restoring a model checkpoint. string filename_tensor_name = 1; // The operation to run when saving a model checkpoint. string save_tensor_name = 2; // The operation to run when restoring a model checkpoint. string restore_op_name = 3; // Maximum number of checkpoints to keep. If 0, no checkpoints are deleted. int32 max_to_keep = 4; // Shard the save files, one per device that has Variable nodes. bool sharded = 5; // How often to keep an additional checkpoint. If not specified, only the last // "max_to_keep" checkpoints are kept; if specified, in addition to keeping // the last "max_to_keep" checkpoints, an additional checkpoint will be kept // for every n hours of training. float keep_checkpoint_every_n_hours = 6; // A version number that identifies a different on-disk checkpoint format. // Usually, each subclass of BaseSaverBuilder works with a particular // version/format. However, it is possible that the same builder may be // upgraded to support a newer checkpoint format in the future. enum CheckpointFormatVersion { // Internal legacy format. LEGACY = 0; // Deprecated format: tf.Saver() which works with tensorflow::table::Table. V1 = 1; // Current format: more efficient. V2 = 2; } CheckpointFormatVersion version = 7; }
codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/protobuf/saver.proto/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/protobuf/saver.proto", "repo_id": "codelabs", "token_count": 517 }
84
import 'package:flutter_test/flutter_test.dart'; import 'package:tfserving_flutter/main.dart'; void main() { testWidgets(' smoke test', (tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const TFServingDemo()); // Verify that our counter starts at 0. expect(find.text('Classify'), findsOneWidget); expect(find.text('Reset'), findsOneWidget); }); }
codelabs/tfserving-flutter/codelab2/starter/test/widget_test.dart/0
{ "file_path": "codelabs/tfserving-flutter/codelab2/starter/test/widget_test.dart", "repo_id": "codelabs", "token_count": 140 }
85
include: ../../analysis_options.yaml
codelabs/webview_flutter/step_11/analysis_options.yaml/0
{ "file_path": "codelabs/webview_flutter/step_11/analysis_options.yaml", "repo_id": "codelabs", "token_count": 12 }
86
# Build DevTools This page describes the fastest way to build DevTools with the goal to use it. Do not mix this setup with development environment. If you want to make code changes, follow [contributing guidance](https://github.com/flutter/devtools/blob/master/CONTRIBUTING.md). You may want to build DevTools locally to: 1. Try experimental features 2. Run DevTools on Flutter Desktop instead of Flutter Web. This will eliminate issues like the browser memory limit, for example, to be able to analyze heap snapshots of large applications. These steps are tested for Mac and may require adjustments for other platforms. Contributions to make these instructions more platform-agnostic are welcome. ## Prerequisites (first time only) ### Set up Dart & Flutter [Configure](https://docs.flutter.dev/get-started/install) Dart & Flutter on your local machine. After doing so, typing `which flutter` and `which dart` (or `where.exe flutter` and `where.exe dart` for Windows) into your terminal should print the path to your Flutter and Dart executables. ### Set up your DevTools environment 1. Ensure you have a clone of the DevTools repository on your machine. This can be a clone of `flutter/devtools` or a clone of a DevTools [fork](https://docs.github.com/en/get-started/quickstart/fork-a-repo) from your own Github account. You may want to fork Devtools to your own Github account if you plan to contribute to the project. In your terminal, navigate to a directory where you want to clone DevTools: `cd some/directory`. This folder must not already contain a folder named 'devtools'. **To clone flutter/devtools**: - Clone the DevTools repo: `git clone [email protected]:flutter/devtools.git` - If you haven't already, you may need to [generate a new SSH key](https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh) to connect to Github with SSH. **To clone your fork of flutter/devtools**: - [Fork](https://docs.github.com/en/get-started/quickstart/fork-a-repo) the DevTools repo to your own Github account. - Clone your fork of the DevTools repo: `git clone [email protected]:your_github_account/devtools.git` - If you haven't already, you may need to [generate a new SSH key](https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh) to connect to Github with SSH. - Make sure to [configure Git to keep your fork in sync](https://docs.github.com/en/get-started/quickstart/fork-a-repo#configuring-git-to-sync-your-fork-with-the-upstream-repository) with the upstream DevTools repo. 2. Ensure that you have access to the `devtools_tool` executable by: - Running `flutter pub get` on the `devtools/tool` directory - Adding the `devtools/tool/bin` folder to your `PATH` environment variable: - **MacOS Users** - add the following to your `~/.zshrc` file (or `~/.bashrc`, `~/.bash_profile` if you use Bash), replacing `<DEVTOOLS_DIR>` with the local path to your DevTools repo: ``` export PATH=$PATH:<DEVTOOLS_DIR>/tool/bin ``` - **Windows Users** - Open "Edit environment variables for your account" from Control Panel - Locate the `Path` variable and click **Edit** - Click the **New** button and paste in `<DEVTOOLS_DIR>/tool/bin`, replacing `<DEVTOOLS_DIR>` with the local path to your DevTools repo. Explore the commands and helpers that the `devtools_tool` provides by running `devtools_tool -h`. ## Prepare to build DevTools To ensure your DevTools repository is up to date and ready to build, run the following from the `devtools` directory (this will delete any local changes you have made to your DevTools clone): ```bash git checkout master git reset --hard origin/master devtools_tool update-flutter-sdk devtools_tool pub-get --only-main --upgrade ``` ## Start DevTools and connect to an app 1. From the main `devtools/packages/devtools_app` directory, run the following, where `<platform>` is one of `chrome`, `macos`, or `windows` depending on which platform you are targeting: ```bash ../../tool/flutter-sdk/bin/flutter run --release -d <platform> ``` - Add `--dart-define=enable_experiments=true` to enable experimental features. 2. Run the application that you want to debug or profile with DevTools. 3. Paste the VM Service URL of your application into the DevTools connect dialog. See this [example](https://github.com/flutter/devtools/blob/master/CONTRIBUTING.md#connect-devtools-to-a-test-application).
devtools/BETA_TESTING.md/0
{ "file_path": "devtools/BETA_TESTING.md", "repo_id": "devtools", "token_count": 1376 }
87
# code_size_images A Flutter project demonstrating code size issues with images
devtools/case_study/code_size/optimized/code_size_images/README.md/0
{ "file_path": "devtools/case_study/code_size/optimized/code_size_images/README.md", "repo_id": "devtools", "token_count": 19 }
88
org.gradle.jvmargs=-Xmx1536M android.enableR8=true android.useAndroidX=true android.enableJetifier=true
devtools/case_study/code_size/unoptimized/code_size_images/android/gradle.properties/0
{ "file_path": "devtools/case_study/code_size/unoptimized/code_size_images/android/gradle.properties", "repo_id": "devtools", "token_count": 39 }
89
#import <UIKit/UIKit.h> #import <Flutter/Flutter.h> @interface AppDelegate : FlutterAppDelegate @end
devtools/case_study/memory_leaks/memory_leak_app/ios/Runner/AppDelegate.h/0
{ "file_path": "devtools/case_study/memory_leaks/memory_leak_app/ios/Runner/AppDelegate.h", "repo_id": "devtools", "token_count": 41 }
90
# This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: 58bd39cd235e669f0014856ce65f36027c7a8b9c channel: master project_type: app
devtools/case_study/platform_channel/.metadata/0
{ "file_path": "devtools/case_study/platform_channel/.metadata", "repo_id": "devtools", "token_count": 87 }
91
--- redirect_to: https://flutter.dev/docs/development/tools/devtools/logging ---
devtools/docs/logging.md/0
{ "file_path": "devtools/docs/logging.md", "repo_id": "devtools", "token_count": 28 }
92
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:web_benchmarks/analysis.dart'; import 'utils.dart'; /// Compares two sets of web benchmarks and calculates the delta between each /// matching metric. void main(List<String> args) { if (args.length != 2) { throw Exception( 'Expected 2 arguments (<baseline-file>, <test-file>), but instead there ' 'were ${args.length}.', ); } final baselineSource = args[0]; final testSource = args[1]; stdout ..writeln('Comparing the following benchmark results:') ..writeln(' "$testSource" (test)') ..writeln(' "$baselineSource" (baseline)'); final baselineFile = checkFileExists(baselineSource); final testFile = checkFileExists(testSource); if (baselineFile == null || testFile == null) { if (baselineFile == null) { throw Exception('Cannot find baseline file $baselineSource'); } if (testFile == null) { throw Exception('Cannot find test file $testSource'); } } final baselineResults = BenchmarkResults.parse(jsonDecode(baselineFile.readAsStringSync())); final testResults = BenchmarkResults.parse(jsonDecode(testFile.readAsStringSync())); compareBenchmarks( baselineResults, testResults, baselineSource: baselineSource, ); } void compareBenchmarks( BenchmarkResults baseline, BenchmarkResults test, { required String baselineSource, }) { stdout.writeln('Starting baseline comparison...'); final delta = computeDelta(baseline, test); stdout.writeln('Baseline comparison finished.'); stdout ..writeln('==== Comparison with baseline $baselineSource ====') ..writeln(const JsonEncoder.withIndent(' ').convert(delta.toJson())) ..writeln('==== End of baseline comparison ===='); }
devtools/packages/devtools_app/benchmark/scripts/compare_benchmarks.dart/0
{ "file_path": "devtools/packages/devtools_app/benchmark/scripts/compare_benchmarks.dart", "repo_id": "devtools", "token_count": 628 }
93
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/memory/panes/control/primary_controls.dart'; import 'package:devtools_app/src/screens/memory/panes/diff/widgets/snapshot_list.dart'; import 'package:devtools_app/src/screens/memory/shared/primitives/instance_context_menu.dart'; import 'package:devtools_app/src/shared/console/widgets/console_pane.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class EvalTester { EvalTester(this.tester); final WidgetTester tester; /// Tests if eval returns expected response by searching for response text. Future<void> testEval(String expression, Finder expectedResponse) async { await tapAndPump(find.byType(AutoCompleteSearchField)); await tester.enterText(find.byType(AutoCompleteSearchField), expression); await tester.pump(safePumpDuration); await _pressEnter(); expect(expectedResponse, findsOneWidget); } Future<void> _pressEnter() async { // TODO(polina-c): Figure out why one time sometimes is not enough. // https://github.com/flutter/devtools/issues/5436 await simulateKeyDownEvent(LogicalKeyboardKey.enter); await simulateKeyUpEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); await simulateKeyDownEvent(LogicalKeyboardKey.enter); await simulateKeyUpEvent(LogicalKeyboardKey.enter); await tester.pump(longPumpDuration); } /// Prepares the UI of the memory screen so that the eval-related elements are /// visible on the screen for testing. Future<void> prepareMemoryUI() async { // Open memory screen. await switchToScreen( tester, tabIcon: ScreenMetaData.memory.icon!, screenId: ScreenMetaData.memory.id, ); // Close warning and chart to get screen space. await tapAndPump( find.descendant( of: find.byType(BannerWarning), matching: find.byIcon(Icons.close), ), ); await tapAndPump(find.text(PrimaryControls.memoryChartText)); // Make console wider. // The distance is big enough to see more items in console, // but not too big to make classes in snapshot hidden. const dragDistance = -320.0; await tester.drag( find.byType(ConsolePaneHeader), const Offset(0, dragDistance), ); await tester.pumpAndSettle(); } /// Prepares the UI of the inspector screen so that the eval-related /// elements are visible on the screen for testing. Future<void> prepareInspectorUI() async { // Open the inspector screen. await switchToScreen( tester, tabIcon: ScreenMetaData.inspector.icon!, screenId: ScreenMetaData.inspector.id, ); await tester.pumpAndSettle(); } /// Selects a widget to run evaluation on. Future<void> selectWidgetTreeNode(Finder finder) async { await tapAndPump( find.descendant( of: find.byKey(InspectorScreenBodyState.summaryTreeKey), matching: finder, ), ); await tester.pumpAndSettle(); } Future<void> switchToSnapshotsAndTakeOne() async { // Switch to diff tab. await tapAndPump(find.text('Diff Snapshots')); logStatus('Started taking snapshot.'); // Take snapshot. const snapshotDuration = Duration(seconds: 20); await tapAndPump( find.byIcon(iconToTakeSnapshot), duration: snapshotDuration, ); logStatus('Finished taking snapshot.'); // Sort by class. await tapAndPump(find.text('Class')); // Select class. await tapAndPump(find.text('MyApp')); } /// Taps and settles. /// /// If [next] is provided, will repeat the tap untill [next] returns results. /// Returns [next]. Future<Finder?> tapAndPump( Finder finder, { Duration? duration, Finder? next, String? description, }) async { Future<void> action(int tryNumber) async { logStatus('\nattempt #$tryNumber, tapping'); logStatus(description ?? finder.toString()); tryNumber++; await tester.tap(finder); await tester.pump(duration); await tester.pumpAndSettle(); } await action(0); if (next == null) return null; // These tries are needed because tap in console is flaky. for (var tryNumber = 1; tryNumber < 10; tryNumber++) { try { final items = tester.widgetList(next); if (items.isNotEmpty) return next; await action(tryNumber); } on StateError { // tester.widgetList throws StateError if no widgets found. await action(tryNumber); } } throw StateError('Could not find $next'); } Future<void> openContextMenuForClass(String className) async { await tapAndPump(find.text(className)); await tapAndPump( find.descendant( of: find.byType(InstanceViewWithContextMenu), matching: find.byType(ContextMenuButton), ), ); } } Future<void> testBasicEval(EvalTester tester) async { await tester.testEval('21 + 34', find.text('55')); } Future<void> testAssignment(EvalTester tester) async { await tester.testEval('DateTime(2023)', find.text('DateTime')); await tester.testEval( r'var x = $0', find.textContaining('Variable x is created '), ); await tester.testEval( 'x.toString()', find.text("'${DateTime(2023).toString()}'"), ); }
devtools/packages/devtools_app/integration_test/test/live_connection/eval_utils.dart/0
{ "file_path": "devtools/packages/devtools_app/integration_test/test/live_connection/eval_utils.dart", "repo_id": "devtools", "token_count": 2012 }
94
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import '../shared/globals.dart'; import '../shared/offline_mode.dart'; import '../shared/screen.dart'; import '../shared/utils.dart'; /// This is an example implementation of a conditional screen that supports /// offline mode and uses a provided controller [ExampleController]. /// /// This class exists solely as an example and should not be used in the /// DevTools app. class ExampleConditionalScreen extends Screen { const ExampleConditionalScreen() : super.conditional( id: id, requiresLibrary: 'package:flutter/', title: 'Example', icon: Icons.palette, worksOffline: true, ); static const id = 'example'; @override Widget buildScreenBody(BuildContext context) { return const _ExampleConditionalScreenBody(); } } class _ExampleConditionalScreenBody extends StatefulWidget { const _ExampleConditionalScreenBody(); @override _ExampleConditionalScreenBodyState createState() => _ExampleConditionalScreenBodyState(); } class _ExampleConditionalScreenBodyState extends State<_ExampleConditionalScreenBody> with ProvidedControllerMixin<ExampleController, _ExampleConditionalScreenBody> { @override void didChangeDependencies() { super.didChangeDependencies(); initController(); } @override Widget build(BuildContext context) { return ValueListenableBuilder<ExampleScreenData>( valueListenable: controller.data, builder: (context, data, _) { return Center(child: Text(data.title)); }, ); } } class ExampleController extends DisposableController with AutoDisposeControllerMixin, OfflineScreenControllerMixin<ExampleScreenData> { ExampleController() { unawaited(_init()); } final data = ValueNotifier<ExampleScreenData>(ExampleScreenData('Example screen')); final _initialized = Completer<void>(); Future<void> get initialized => _initialized.future; Future<void> _init() async { await _initHelper(); _initialized.complete(); } Future<void> _initHelper() async { if (!offlineController.offlineMode.value) { // Do some initialization for online mode. } else { await maybeLoadOfflineData( ExampleConditionalScreen.id, createData: (json) => ExampleScreenData.parse(json), shouldLoad: (data) => data.title.isNotEmpty, ); } } // Overrides for [OfflineScreenControllerMixin] @override FutureOr<void> processOfflineData(ExampleScreenData offlineData) { data.value = offlineData; } @override OfflineScreenData screenDataForExport() { return OfflineScreenData( screenId: ExampleConditionalScreen.id, data: data.value.json, ); } } class ExampleScreenData { ExampleScreenData(this.title); factory ExampleScreenData.parse(Map<String, Object?> json) { return ExampleScreenData(json[_titleKey] as String); } static const _titleKey = 'title'; final String title; Map<String, Object?> get json => {_titleKey: title}; }
devtools/packages/devtools_app/lib/src/example/conditional_screen.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/example/conditional_screen.dart", "repo_id": "devtools", "token_count": 1105 }
95
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/service.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:devtools_shared/service.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart'; import '../../devtools.dart' as devtools show version; import '../extensions/extension_service.dart'; import '../screens/debugger/breakpoint_manager.dart'; import '../service/service_manager.dart'; import '../service/vm_service_wrapper.dart'; import '../shared/banner_messages.dart'; import '../shared/console/eval/eval_service.dart'; import '../shared/framework_controller.dart'; import '../shared/globals.dart'; import '../shared/notifications.dart'; import '../shared/offline_mode.dart'; import '../shared/primitives/message_bus.dart'; import '../shared/scripts/script_manager.dart'; import '../shared/survey.dart'; typedef ErrorReporter = void Function(String title, Object error); final _log = Logger('framework_core'); // TODO(jacobr): refactor this class to not use static members. // ignore: avoid_classes_with_only_static_members class FrameworkCore { static void initGlobals() { setGlobal(ServiceConnectionManager, ServiceConnectionManager()); setGlobal(MessageBus, MessageBus()); setGlobal(FrameworkController, FrameworkController()); setGlobal(SurveyService, SurveyService()); setGlobal(OfflineModeController, OfflineModeController()); setGlobal(ScriptManager, ScriptManager()); setGlobal(NotificationService, NotificationService()); setGlobal(BannerMessagesController, BannerMessagesController()); setGlobal(BreakpointManager, BreakpointManager()); setGlobal(EvalService, EvalService()); setGlobal(ExtensionService, ExtensionService()); setGlobal(IdeTheme, getIdeTheme()); setGlobal(DTDManager, DTDManager()); } static void init() { // Print the version number at startup. _log.info('DevTools version ${devtools.version}.'); } static bool initializationInProgress = false; /// Returns true if we're able to connect to a device and false otherwise. static Future<bool> initVmService({ required String serviceUriAsString, ErrorReporter? errorReporter = _defaultErrorReporter, bool logException = true, }) async { if (serviceConnection.serviceManager.hasConnection) { // TODO(https://github.com/flutter/devtools/issues/1568): why do we call // this multiple times? return true; } final uri = normalizeVmServiceUri(serviceUriAsString); if (uri != null) { initializationInProgress = true; final finishedCompleter = Completer<void>(); try { final VmServiceWrapper service = await connect<VmServiceWrapper>( uri: uri, finishedCompleter: finishedCompleter, serviceFactory: ({ // ignore: avoid-dynamic, mirrors types of [VmServiceFactory]. required Stream<dynamic> /*String|List<int>*/ inStream, required void Function(String message) writeMessage, Log? log, DisposeHandler? disposeHandler, Future? streamClosed, String? wsUri, bool trackFutures = false, }) => VmServiceWrapper.defaultFactory( inStream: inStream, writeMessage: writeMessage, log: log, disposeHandler: disposeHandler, streamClosed: streamClosed, wsUri: wsUri, trackFutures: integrationTestMode, ), ); await serviceConnection.serviceManager.vmServiceOpened( service, onClosed: finishedCompleter.future, ); await breakpointManager.initialize(); return true; } catch (e, st) { if (logException) { _log.shout(e, e, st); } errorReporter!('Unable to connect to VM service at $uri: $e', e); return false; } finally { initializationInProgress = false; } } else { // Don't report an error here because we do not have a URI to connect to. return false; } } static void _defaultErrorReporter(String title, Object error) { notificationService.pushError( '$title, $error', isReportable: false, ); } }
devtools/packages/devtools_app/lib/src/framework/framework_core.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/framework/framework_core.dart", "repo_id": "devtools", "token_count": 1678 }
96
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math' as math; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart' hide Stack; import '../../shared/common_widgets.dart'; import '../../shared/console/widgets/expandable_variable.dart'; import '../../shared/diagnostics/dart_object_node.dart'; import '../../shared/diagnostics/primitives/source_location.dart'; import '../../shared/diagnostics/tree_builder.dart'; import '../../shared/globals.dart'; import '../../shared/history_viewport.dart'; import '../../shared/primitives/flutter_widgets/linked_scroll_controller.dart'; import '../../shared/primitives/listenable.dart'; import '../../shared/primitives/utils.dart'; import '../../shared/ui/hover.dart'; import '../../shared/ui/search.dart'; import '../../shared/ui/utils.dart'; import '../../shared/utils.dart'; import '../vm_developer/vm_service_private_extensions.dart'; import 'breakpoints.dart'; import 'codeview_controller.dart'; import 'common.dart'; import 'debugger_controller.dart'; import 'debugger_model.dart'; import 'file_search.dart'; import 'key_sets.dart'; final _log = Logger('codeview'); final debuggerCodeViewFileOpenerKey = GlobalKey(debugLabel: 'DebuggerCodeViewFileOpenerKey'); // TODO(kenz): consider moving lines / pausedPositions calculations to the // controller. class CodeView extends StatefulWidget { const CodeView({ Key? key, required this.codeViewController, required this.scriptRef, required this.parsedScript, this.debuggerController, this.lineRange, this.initialPosition, this.onSelected, this.enableHistory = true, }) : super(key: key); static const debuggerCodeViewHorizontalScrollbarKey = Key('debuggerCodeViewHorizontalScrollbarKey'); static const debuggerCodeViewVerticalScrollbarKey = Key('debuggerCodeViewVerticalScrollbarKey'); static double get rowHeight => scaleByFontFactor(16.0); final CodeViewController codeViewController; final DebuggerController? debuggerController; final ScriptLocation? initialPosition; final ScriptRef? scriptRef; final ParsedScript? parsedScript; // TODO(bkonyi): consider changing this to (or adding support for) // `highlightedLineRange`, which would tell the code view to display the // the script's source in its entirety, with lines outside of the range being // rendered as if they have been greyed out. final LineRange? lineRange; final bool enableHistory; final void Function(ScriptRef scriptRef, int line)? onSelected; @override State<CodeView> createState() => _CodeViewState(); } class _CodeViewState extends State<CodeView> with AutoDisposeMixin { static const searchFieldRightPadding = 75.0; late final LinkedScrollControllerGroup verticalController; late final ScrollController gutterController; ScrollController? profileController; late final ScrollController textController; late final ScrollController horizontalController; ScriptRef? get scriptRef => widget.scriptRef; ParsedScript? get parsedScript => widget.parsedScript; ScriptLocation? get initialPosition => widget.initialPosition; // Used to ensure we don't update the scroll position when expanding or // collapsing the file explorer. ScriptRef? _lastScriptRef; @override void initState() { super.initState(); verticalController = LinkedScrollControllerGroup(); gutterController = verticalController.addAndGet(); textController = verticalController.addAndGet(); if (widget.codeViewController.showProfileInformation.value) { profileController = verticalController.addAndGet(); } horizontalController = ScrollController(); _lastScriptRef = widget.scriptRef; final lineCount = initialPosition?.location?.line; if (lineCount != null) { // Lines are 1-indexed. Scrolling to line 1 required a scroll position of // 0. final lineIndex = lineCount - 1; final scrollPosition = lineIndex * CodeView.rowHeight; verticalController.jumpTo(scrollPosition); } addAutoDisposeListener( widget.codeViewController.scriptLocation, _handleScriptLocationChanged, ); // Create and dispose the controller used for the profile information // gutter to ensure that the scroll position is kept in sync with the main // gutter and code view when the widget is toggled on/off. If we don't do // this, the profile information gutter will always be at position 0 when // first enabled until the user scrolls. addAutoDisposeListener( widget.codeViewController.showProfileInformation, () { if (widget.codeViewController.showProfileInformation.value) { profileController = verticalController.addAndGet(); } else { profileController!.dispose(); profileController = null; } }, ); } @override void didUpdateWidget(CodeView oldWidget) { super.didUpdateWidget(oldWidget); if (widget.codeViewController != oldWidget.codeViewController) { cancelListeners(); widget.codeViewController.initSearch(); addAutoDisposeListener( widget.codeViewController.scriptLocation, _handleScriptLocationChanged, ); } if (oldWidget.scriptRef != widget.scriptRef) { _updateScrollPosition(); } } @override void dispose() { gutterController.dispose(); profileController?.dispose(); textController.dispose(); horizontalController.dispose(); widget.codeViewController.scriptLocation .removeListener(_handleScriptLocationChanged); super.dispose(); } void _handleScriptLocationChanged() { if (mounted) { _updateScrollPosition(); } } void _updateScrollPosition({bool animate = true}) { if (widget.codeViewController.scriptLocation.value?.scriptRef.uri != scriptRef?.uri) { return; } void updateScrollPositionImpl() { if (!verticalController.hasAttachedControllers) { // TODO(devoncarew): I'm uncertain why this occurs. _log.info('LinkedScrollControllerGroup has no attached controllers'); return; } final line = widget.codeViewController.scriptLocation.value?.location?.line; if (line == null) { // Don't scroll to top if we're just rebuilding the code view for the // same script. if (_lastScriptRef?.uri != scriptRef?.uri) { // Default to scrolling to the top of the script. if (animate) { unawaited( verticalController.animateTo( 0, duration: longDuration, curve: defaultCurve, ), ); } else { verticalController.jumpTo(0); } _lastScriptRef = scriptRef; } return; } final position = verticalController.position; final extent = position.extentInside; // TODO(devoncarew): Adjust this so we don't scroll if we're already in the // middle third of the screen. final lineCount = parsedScript?.lineCount; if (lineCount != null && lineCount * CodeView.rowHeight > extent) { final lineIndex = line - 1; var scrollPosition = lineIndex * CodeView.rowHeight - ((extent - CodeView.rowHeight) / 2); scrollPosition = scrollPosition.clamp(0.0, position.extentTotal); if (animate) { unawaited( verticalController.animateTo( scrollPosition, duration: longDuration, curve: defaultCurve, ), ); } else { verticalController.jumpTo(scrollPosition); } } _lastScriptRef = scriptRef; } verticalController.hasAttachedControllers ? updateScrollPositionImpl() : WidgetsBinding.instance.addPostFrameCallback( (_) => updateScrollPositionImpl(), ); } @override Widget build(BuildContext context) { if (parsedScript == null) { return const CenteredCircularProgressIndicator(); } return Stack( children: [ scriptRef == null ? CodeViewEmptyState(widget: widget) : buildCodeArea(context), PositionedPopup( isVisibleListenable: widget.codeViewController.showFileOpener, left: noPadding, right: noPadding, child: buildFileSearchField(), ), PositionedPopup( isVisibleListenable: widget.codeViewController.showSearchInFileField, top: denseSpacing, right: searchFieldRightPadding, child: buildSearchInFileField(), ), ], ); } Widget buildCodeArea(BuildContext context) { final theme = Theme.of(context); final lines = <TextSpan>[]; // Ensure the syntax highlighter has been initialized. final script = parsedScript; final scriptSource = parsedScript?.script.source; if (script != null && scriptSource != null) { // It takes ~1 second to syntax highlight 100,000 characters. Therefore, // we only highlight scripts with less than 100,000 characters. If we want // to support larger files, we should process the source for highlighting // on a separate isolate. if (scriptSource.length < 100000) { final highlighted = script.highlighter.highlight( context, lineRange: widget.lineRange, ); // Look for [InlineSpan]s which only contain '\n' to manually break the // output from the syntax highlighter into individual lines. var currentLine = <InlineSpan>[]; highlighted.visitChildren((span) { currentLine.add(span); if (span.toPlainText() == '\n') { lines.add( TextSpan( style: theme.fixedFontStyle, children: currentLine, ), ); currentLine = <InlineSpan>[]; } return true; }); lines.add( TextSpan( style: theme.fixedFontStyle, children: currentLine, ), ); } else { lines.addAll( [ for (final line in scriptSource.split('\n')) TextSpan( style: theme.fixedFontStyle, text: line, ), ], ); } } Widget contentBuilder(_, ScriptRef? script) { if (lines.isNotEmpty) { return DefaultTextStyle( style: theme.fixedFontStyle, child: Scrollbar( key: CodeView.debuggerCodeViewVerticalScrollbarKey, controller: textController, thumbVisibility: true, // Only listen for vertical scroll notifications (ignore those // from the nested horizontal SingleChildScrollView): notificationPredicate: (ScrollNotification notification) => notification.depth == 1, child: ValueListenableBuilder<StackFrameAndSourcePosition?>( valueListenable: widget.debuggerController?.selectedStackFrame ?? const FixedValueListenable<StackFrameAndSourcePosition?>( null, ), builder: (context, frame, _) { final pausedFrame = frame?.scriptRef == scriptRef ? frame : null; return ValueListenableBuilder<bool>( valueListenable: widget.codeViewController.showProfileInformation, builder: (context, showProfileInformation, _) { return Row( children: [ Gutters( scriptRef: script, gutterController: gutterController, profileController: profileController, codeViewController: widget.codeViewController, debuggerController: widget.debuggerController, lines: lines, lineRange: widget.lineRange, onSelected: widget.onSelected, pausedFrame: pausedFrame, parsedScript: parsedScript, showProfileInformation: showProfileInformation, ), Expanded( child: LayoutBuilder( builder: (context, constraints) { final double fileWidth = calculateTextSpanWidth( findLongestTextSpan(lines), ); return Scrollbar( key: CodeView .debuggerCodeViewHorizontalScrollbarKey, thumbVisibility: true, controller: horizontalController, child: SingleChildScrollView( scrollDirection: Axis.horizontal, controller: horizontalController, child: SizedBox( height: constraints.maxHeight, width: math.max( constraints.maxWidth, fileWidth, ), child: Lines( height: constraints.maxHeight, codeViewController: widget.codeViewController, scrollController: textController, lines: lines, selectedFrameNotifier: widget .debuggerController ?.selectedStackFrame, searchMatchesNotifier: widget .codeViewController.searchMatches, activeSearchMatchNotifier: widget .codeViewController.activeSearchMatch, showProfileInformation: showProfileInformation, ), ), ), ); }, ), ), ], ); }, ); }, ), ), ); } else { return Center( child: Text( 'No source available', style: theme.textTheme.titleMedium, ), ); } } if (widget.enableHistory) { return HistoryViewport( history: widget.codeViewController.scriptsHistory, generateTitle: (ScriptRef? script) { final scriptUri = script?.uri; if (scriptUri == null) return ''; return scriptUri; }, titleIcon: Icons.search, onTitleTap: () => widget.codeViewController ..toggleFileOpenerVisibility(true) ..toggleSearchInFileVisibility(false), controls: [ ScriptPopupMenu(widget.codeViewController), ScriptHistoryPopupMenu( itemBuilder: _buildScriptMenuFromHistory, onSelected: (scriptRef) async { await widget.codeViewController .showScriptLocation(ScriptLocation(scriptRef)); }, enabled: widget.codeViewController.scriptsHistory.hasScripts, ), ], contentBuilder: (context, ScriptRef? scriptRef) { return Expanded( child: contentBuilder(context, scriptRef), ); }, ); } return contentBuilder(context, widget.scriptRef); } Widget buildFileSearchField() { return ElevatedCard( key: debuggerCodeViewFileOpenerKey, width: extraWideSearchFieldWidth, height: defaultTextFieldHeight, padding: EdgeInsets.zero, child: FileSearchField( codeViewController: widget.codeViewController, ), ); } Widget buildSearchInFileField() { return ElevatedCard( width: wideSearchFieldWidth, height: defaultTextFieldHeight + 2 * denseSpacing, child: SearchField<CodeViewController>( searchController: widget.codeViewController, searchFieldEnabled: parsedScript != null, shouldRequestFocus: true, searchFieldWidth: wideSearchFieldWidth, onClose: () => widget.codeViewController.toggleSearchInFileVisibility(false), ), ); } List<PopupMenuEntry<ScriptRef>> _buildScriptMenuFromHistory( BuildContext context, ) { const scriptHistorySize = 16; return widget.codeViewController.scriptsHistory.openedScripts .take(scriptHistorySize) .map((scriptRef) { return PopupMenuItem( value: scriptRef, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( ScriptRefUtils.fileName(scriptRef), maxLines: 1, overflow: TextOverflow.ellipsis, ), Text( scriptRef.uri ?? '', overflow: TextOverflow.ellipsis, maxLines: 1, style: Theme.of(context).subtleTextStyle, ), ], ), ); }).toList(); } } class CodeViewEmptyState extends StatelessWidget { const CodeViewEmptyState({ super.key, required this.widget, }); final CodeView widget; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Center( child: ElevatedButton( autofocus: true, onPressed: () => widget.codeViewController.toggleFileOpenerVisibility(true), child: Text( 'Open a file ($openFileKeySetDescription)', style: theme.textTheme.titleMedium, ), ), ); } } class ProfileInformationGutter extends StatelessWidget { const ProfileInformationGutter({ super.key, required this.scrollController, required this.lineOffset, required this.lineCount, required this.sourceReport, }); final ScrollController scrollController; final int lineOffset; final int lineCount; final ProcessedSourceReport sourceReport; static const totalTimeTooltip = 'Percent of time that a sampled line spent executing its own\n code as ' 'well as the code for any methods it called.'; static const selfTimeTooltip = 'Percent of time that a sampled line spent executing only its own code.'; @override Widget build(BuildContext context) { // Gutter width accounts for: // - a maximum of 16 characters of text (e.g., '100.00 %' x 2) // - Spacing for the vertical divider final gutterWidth = assumedMonospaceCharacterWidth * 16 + denseSpacing; return OutlineDecoration.onlyRight( child: SizedBox( width: gutterWidth, child: Stack( children: [ Column( children: [ const _ProfileInformationGutterHeader( totalTimeTooltip: totalTimeTooltip, selfTimeTooltip: selfTimeTooltip, ), Expanded( child: ListView.builder( controller: scrollController, itemExtent: CodeView.rowHeight, itemCount: lineCount, itemBuilder: (context, index) { final lineNum = lineOffset + index + 1; final data = sourceReport.profilerEntries[lineNum]; if (data == null) { return const SizedBox(); } return ProfileInformationGutterItem(profilerData: data); }, ), ), ], ), const Center( child: VerticalDivider(), ), ], ), ), ); } } class _ProfileInformationGutterHeader extends StatelessWidget { const _ProfileInformationGutterHeader({ required this.totalTimeTooltip, required this.selfTimeTooltip, }); final String totalTimeTooltip; final String selfTimeTooltip; @override Widget build(BuildContext context) { return SizedBox( height: CodeView.rowHeight, child: Column( children: [ Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Expanded( child: DevToolsTooltip( message: totalTimeTooltip, child: const Text( 'Total %', textAlign: TextAlign.center, ), ), ), const SizedBox(width: denseSpacing), Expanded( child: DevToolsTooltip( message: selfTimeTooltip, child: const Text( 'Self %', textAlign: TextAlign.center, ), ), ), ], ), ), const Divider( height: 0, ), ], ), ); } } class ProfileInformationGutterItem extends StatelessWidget { const ProfileInformationGutterItem({ Key? key, required this.profilerData, }) : super(key: key); final ProfileReportEntry profilerData; @override Widget build(BuildContext context) { return SizedBox( height: CodeView.rowHeight, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: ProfilePercentageItem( percentage: profilerData.inclusivePercentage, hoverText: ProfileInformationGutter.totalTimeTooltip, ), ), Expanded( child: ProfilePercentageItem( percentage: profilerData.exclusivePercentage, hoverText: ProfileInformationGutter.selfTimeTooltip, ), ), ], ), ); } } class ProfilePercentageItem extends StatelessWidget { const ProfilePercentageItem({ super.key, required this.percentage, required this.hoverText, }); final double percentage; final String hoverText; @override Widget build(BuildContext context) { final theme = Theme.of(context); final colorScheme = theme.colorScheme; final textStyle = theme.regularTextStyleWithColor( colorScheme.coverageAndPerformanceTextColor, ); Color? color; if (percentage > 5) { color = colorScheme.performanceHighImpactColor; } else if (percentage > 1) { color = colorScheme.performanceMediumImpactColor; } else { color = colorScheme.performanceLowImpactColor; } return DevToolsTooltip( message: hoverText, child: Container( color: color, padding: const EdgeInsets.symmetric( horizontal: densePadding, ), child: Text( '${percentage.toStringAsFixed(2)} %', textAlign: TextAlign.end, style: textStyle, ), ), ); } } typedef IntCallback = void Function(int value); class Gutters extends StatelessWidget { const Gutters({ super.key, required this.scriptRef, this.debuggerController, required this.codeViewController, required this.lines, required this.lineRange, required this.gutterController, required this.showProfileInformation, required this.profileController, required this.parsedScript, this.pausedFrame, this.onSelected, }); final ScriptRef? scriptRef; final DebuggerController? debuggerController; final CodeViewController codeViewController; final ScrollController gutterController; final ScrollController? profileController; final StackFrameAndSourcePosition? pausedFrame; final List<TextSpan> lines; final LineRange? lineRange; final ParsedScript? parsedScript; final void Function(ScriptRef scriptRef, int line)? onSelected; final bool showProfileInformation; @override Widget build(BuildContext context) { final lineCount = lineRange?.size ?? lines.length; final lineOffset = (lineRange?.begin ?? 1) - 1; final sourceReport = parsedScript?.sourceReport ?? const ProcessedSourceReport.empty(); // Apply the log change-of-base formula to get the max number of digits in // a line number. Add a character width space for: // - each character in the longest line number // - one for the breakpoint dot // - two for the paused arrow final gutterWidth = assumedMonospaceCharacterWidth * 4 + assumedMonospaceCharacterWidth * (defaultEpsilon + math.log(math.max(lines.length, 100)) / math.ln10) .truncateToDouble(); return Row( children: [ MultiValueListenableBuilder( listenables: [ breakpointManager.breakpointsWithLocation, codeViewController.showCodeCoverage, ], builder: (context, values, _) { final breakpoints = values.first as List<BreakpointAndSourcePosition>; final showCodeCoverage = values.second as bool; return Gutter( gutterWidth: gutterWidth, scrollController: gutterController, lineCount: lineCount, lineOffset: lineOffset, pausedFrame: pausedFrame, breakpoints: breakpoints.where((bp) => bp.scriptRef == scriptRef).toList(), executableLines: parsedScript?.executableLines ?? const <int>{}, sourceReport: sourceReport, onPressed: _onPressed, // Disable dots for possible breakpoint locations. allowInteraction: !(debuggerController?.isSystemIsolate ?? false), showCodeCoverage: showCodeCoverage, showProfileInformation: showProfileInformation, ); }, ), !showProfileInformation ? const SizedBox(width: denseSpacing) : Padding( padding: const EdgeInsets.only(right: denseSpacing), child: ProfileInformationGutter( scrollController: profileController!, lineCount: lineCount, lineOffset: lineOffset, sourceReport: sourceReport, ), ), ], ); } void _onPressed(int line) { final onSelectedLocal = onSelected!; final script = scriptRef; if (onSelected != null && script != null) { onSelectedLocal(script, line); } } } class Gutter extends StatelessWidget { const Gutter({ super.key, required this.gutterWidth, required this.scrollController, required this.lineOffset, required this.lineCount, required this.pausedFrame, required this.breakpoints, required this.executableLines, required this.onPressed, required this.allowInteraction, required this.sourceReport, required this.showCodeCoverage, required this.showProfileInformation, }); final double gutterWidth; final ScrollController scrollController; final int lineOffset; final int lineCount; final StackFrameAndSourcePosition? pausedFrame; final List<BreakpointAndSourcePosition> breakpoints; final Set<int> executableLines; final ProcessedSourceReport sourceReport; final IntCallback onPressed; final bool allowInteraction; final bool showCodeCoverage; final bool showProfileInformation; @override Widget build(BuildContext context) { final bpLineSet = Set.of(breakpoints.map((bp) => bp.line)); final theme = Theme.of(context); final coverageLines = sourceReport.coverageHitLines.union(sourceReport.coverageMissedLines); // Used to account for the presence of `_ProfileInformationGutterHeader` at // the top of the profiler gutter columns. Everything needs to be shifted // down a single line so profiling information for line 1 isn't hidden by // the header. final profileInformationHeaderOffset = showProfileInformation ? 1 : 0; return Container( width: gutterWidth, decoration: BoxDecoration( border: Border(right: defaultBorderSide(theme)), ), child: ListView.builder( controller: scrollController, physics: const ClampingScrollPhysics(), itemExtent: CodeView.rowHeight, itemCount: lineCount + profileInformationHeaderOffset, itemBuilder: (context, index) { if (showProfileInformation && index == 0) { return SizedBox(height: CodeView.rowHeight); } final lineNum = lineOffset - profileInformationHeaderOffset + index + 1; bool? coverageHit; if (showCodeCoverage && coverageLines.contains(lineNum)) { coverageHit = sourceReport.coverageHitLines.contains(lineNum); } return GutterItem( lineNumber: lineNum, onPressed: () => onPressed(lineNum), isBreakpoint: bpLineSet.contains(lineNum), isExecutable: executableLines.contains(lineNum), isPausedHere: pausedFrame?.line == lineNum, allowInteraction: allowInteraction, coverageHit: coverageHit, ); }, ), ); } } class GutterItem extends StatelessWidget { const GutterItem({ Key? key, required this.lineNumber, required this.isBreakpoint, required this.isExecutable, required this.isPausedHere, required this.onPressed, required this.allowInteraction, required this.coverageHit, }) : super(key: key); final int lineNumber; final bool isBreakpoint; final bool isExecutable; final bool allowInteraction; final bool? coverageHit; /// Whether the execution point is currently paused here. final bool isPausedHere; final VoidCallback onPressed; @override Widget build(BuildContext context) { final theme = Theme.of(context); final breakpointColor = theme.colorScheme.primary; final subtleColor = theme.unselectedWidgetColor; final bpBoxSize = breakpointRadius * 2; final executionPointIndent = scaleByFontFactor(10.0); Color? color; TextStyle? coverageTextStyleOverride; final hasCoverage = coverageHit; if (hasCoverage != null) { color = hasCoverage ? theme.colorScheme.coverageHitColor : theme.colorScheme.coverageMissColor; coverageTextStyleOverride = theme.regularTextStyleWithColor( theme.colorScheme.coverageAndPerformanceTextColor, ); } return InkWell( onTap: onPressed, // Force usage of default mouse pointer when gutter interaction is // disabled. mouseCursor: allowInteraction ? null : SystemMouseCursors.basic, child: Container( color: color, height: CodeView.rowHeight, padding: const EdgeInsets.only(right: 4.0), child: Stack( alignment: AlignmentDirectional.centerStart, fit: StackFit.expand, children: [ if (allowInteraction && (isExecutable || isBreakpoint)) Align( alignment: Alignment.centerLeft, child: SizedBox( width: bpBoxSize, height: bpBoxSize, child: Center( child: createAnimatedCircleWidget( isBreakpoint ? breakpointRadius : executableLineRadius, isBreakpoint ? breakpointColor : subtleColor, ), ), ), ), Text( '$lineNumber', textAlign: TextAlign.end, style: coverageTextStyleOverride, ), Container( padding: EdgeInsets.only(left: executionPointIndent), alignment: Alignment.centerLeft, child: AnimatedOpacity( duration: defaultDuration, curve: defaultCurve, opacity: isPausedHere ? 1.0 : 0.0, child: Icon( Icons.label, size: defaultIconSize, color: breakpointColor, ), ), ), ], ), ), ); } } class Lines extends StatefulWidget { const Lines({ Key? key, required this.height, required this.codeViewController, required this.scrollController, required this.lines, required this.searchMatchesNotifier, required this.activeSearchMatchNotifier, required this.selectedFrameNotifier, required this.showProfileInformation, }) : super(key: key); final double height; final CodeViewController codeViewController; final ScrollController scrollController; final List<TextSpan> lines; final ValueListenable<List<SourceToken>> searchMatchesNotifier; final ValueListenable<SourceToken?> activeSearchMatchNotifier; final ValueListenable<StackFrameAndSourcePosition?>? selectedFrameNotifier; final bool showProfileInformation; @override State<Lines> createState() => _LinesState(); } class _LinesState extends State<Lines> with AutoDisposeMixin { late List<SourceToken> searchMatches; SourceToken? activeSearch; @override void initState() { super.initState(); cancelListeners(); searchMatches = widget.searchMatchesNotifier.value; addAutoDisposeListener(widget.searchMatchesNotifier, () { setState(() { searchMatches = widget.searchMatchesNotifier.value; }); }); activeSearch = widget.activeSearchMatchNotifier.value; addAutoDisposeListener(widget.activeSearchMatchNotifier, () { setState(() { activeSearch = widget.activeSearchMatchNotifier.value; }); final activeSearchLine = activeSearch?.position.line; _maybeScrollToLine(activeSearchLine); }); addAutoDisposeListener(widget.selectedFrameNotifier, () { final selectedFrame = widget.selectedFrameNotifier?.value; SchedulerBinding.instance.addPostFrameCallback((_) { _maybeScrollToLine(selectedFrame?.line); }); }); } @override Widget build(BuildContext context) { final pausedFrame = widget.selectedFrameNotifier?.value; final pausedLine = pausedFrame?.line; // Used to account for the presence of `_ProfileInformationGutterHeader` at // the top of the profiler gutter columns. Everything needs to be shifted // down a single line so profiling information for line 1 isn't hidden by // the header. final profileInformationHeaderOffset = widget.showProfileInformation ? 1 : 0; return SelectionArea( child: ListView.builder( controller: widget.scrollController, physics: const ClampingScrollPhysics(), itemExtent: CodeView.rowHeight, itemCount: widget.lines.length + profileInformationHeaderOffset, itemBuilder: (context, index) { if (widget.showProfileInformation && index == 0) { return SizedBox(height: CodeView.rowHeight); } final dataIndex = index - profileInformationHeaderOffset; final lineNum = dataIndex + 1; final isPausedLine = pausedLine == lineNum; return ValueListenableBuilder<int>( valueListenable: widget.codeViewController.focusLine, builder: (context, focusLine, _) { final isFocusedLine = focusLine == lineNum; return LineItem( lineContents: widget.lines[dataIndex], pausedFrame: isPausedLine ? pausedFrame : null, focused: isPausedLine || isFocusedLine, searchMatches: _searchMatchesForLine( dataIndex, ), activeSearchMatch: activeSearch?.position.line == dataIndex ? activeSearch : null, ); }, ); }, ), ); } List<SourceToken> _searchMatchesForLine(int index) { return searchMatches .where((searchToken) => searchToken.position.line == index) .toList(); } void _maybeScrollToLine(int? lineNumber) { if (lineNumber == null) return; final isOutOfViewTop = lineNumber * CodeView.rowHeight < widget.scrollController.offset + CodeView.rowHeight; final isOutOfViewBottom = lineNumber * CodeView.rowHeight > widget.scrollController.offset + widget.height - CodeView.rowHeight; if (isOutOfViewTop || isOutOfViewBottom) { // Scroll this search token to the middle of the view. final targetOffset = math.max<double>( lineNumber * CodeView.rowHeight - widget.height / 2, 0.0, ); unawaited( widget.scrollController.animateTo( targetOffset, duration: defaultDuration, curve: defaultCurve, ), ); } } } class LineItem extends StatefulWidget { const LineItem({ Key? key, required this.lineContents, this.pausedFrame, this.focused = false, this.searchMatches, this.activeSearchMatch, }) : super(key: key); static double get _hoverWidth => scaleByFontFactor(400.0); final TextSpan lineContents; final StackFrameAndSourcePosition? pausedFrame; final bool focused; final List<SourceToken>? searchMatches; final SourceToken? activeSearchMatch; @override State<LineItem> createState() => _LineItemState(); } class _LineItemState extends State<LineItem> with ProvidedControllerMixin<DebuggerController, LineItem> { Future<HoverCardData?> _generateHoverCardData({ required PointerEvent event, required bool Function() isHoverStale, }) async { if (!serviceConnection.serviceManager.isMainIsolatePaused) return null; final word = wordForHover( event.localPosition.dx, widget.lineContents, ); if (word != '') { try { final response = await evalService.evalAtCurrentFrame(word); final isolateRef = serviceConnection .serviceManager.isolateManager.selectedIsolate.value; if (response is! InstanceRef) return null; final variable = DartObjectNode.fromValue( value: response, isolateRef: isolateRef, ); await buildVariablesTree(variable); return HoverCardData( title: word, contents: Material( child: ExpandableVariable( variable: variable, ), ), width: LineItem._hoverWidth, ); } catch (_) { // Silently fail and don't display a HoverCard. return null; } } return null; } @override void didChangeDependencies() { super.didChangeDependencies(); initController(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); Widget child; final column = widget.pausedFrame?.column; if (column != null) { final breakpointColor = theme.colorScheme.primary; final widthToCurrentColumn = calculateTextSpanWidth( truncateTextSpan(widget.lineContents, column - 1), ); // The following constants are tweaked for using the // 'Icons.label_important' icon. const colIconSize = 13.0; // Subtract 3 to offset the icon at the start of the character: final colLeftOffset = widthToCurrentColumn - 3.0; const colBottomOffset = 13.0; const colIconRotate = -90 * math.pi / 180; // TODO: support selecting text across multiples lines. child = Stack( children: [ Row( children: [ Transform.translate( offset: Offset(colLeftOffset, colBottomOffset), child: Transform.rotate( angle: colIconRotate, child: Icon( Icons.label_important, size: colIconSize, color: breakpointColor, ), ), ), ], ), _hoverableLine(), ], ); } else { child = _hoverableLine(); } final backgroundColor = widget.focused ? theme.colorScheme.selectedRowBackgroundColor : null; return Container( alignment: Alignment.centerLeft, height: CodeView.rowHeight, color: backgroundColor, child: child, ); } Widget _hoverableLine() => HoverCardTooltip.async( enabled: () => true, asyncTimeout: 100, asyncGenerateHoverCardData: _generateHoverCardData, child: Text.rich( searchAwareLineContents(), maxLines: 1, ), ); TextSpan searchAwareLineContents() { // If syntax highlighting is disabled for the script, then // `widget.lineContents` is simply a `TextSpan` with no children. final lineContents = widget.lineContents.children ?? [widget.lineContents]; final activeSearchAwareContents = _activeSearchAwareLineContents(lineContents); final allSearchAwareContents = _searchMatchAwareLineContents(activeSearchAwareContents!); return TextSpan( children: allSearchAwareContents, style: widget.lineContents.style, ); } List<InlineSpan> _contentsWithMatch( List<InlineSpan> startingContents, SourceToken match, Color matchColor, ) { final contentsWithMatch = <InlineSpan>[]; var startColumnForSpan = 0; for (final span in startingContents) { final spanText = span.toPlainText(); final startColumnForMatch = match.position.column!; if (startColumnForSpan <= startColumnForMatch && startColumnForSpan + spanText.length > startColumnForMatch) { // The active search is part of this [span]. final matchStartInSpan = startColumnForMatch - startColumnForSpan; final matchEndInSpan = matchStartInSpan + match.length; // Add the part of [span] that occurs before the search match. contentsWithMatch.add( TextSpan( text: spanText.substring(0, matchStartInSpan), style: span.style, ), ); final matchStyle = (span.style ?? DefaultTextStyle.of(context).style).copyWith( color: Colors.black, backgroundColor: matchColor, ); if (matchEndInSpan <= spanText.length) { final matchText = spanText.substring(matchStartInSpan, matchEndInSpan); final trailingText = spanText.substring(matchEndInSpan); // Add the match and any part of [span] that occurs after the search // match. contentsWithMatch.addAll([ TextSpan( text: matchText, style: matchStyle, ), if (trailingText.isNotEmpty) TextSpan( text: spanText.substring(matchEndInSpan), style: span.style, ), ]); } else { // In this case, the active search match exists across multiple spans, // so we need to add the part of the match that is in this [span] and // continue looking for the remaining part of the match in the spans // to follow. contentsWithMatch.add( TextSpan( text: spanText.substring(matchStartInSpan), style: matchStyle, ), ); final remainingMatchLength = match.length - (spanText.length - matchStartInSpan); match = SourceToken( position: SourcePosition( line: match.position.line, column: startColumnForMatch + match.length - remainingMatchLength, ), length: remainingMatchLength, ); } } else { contentsWithMatch.add(span); } startColumnForSpan += spanText.length; } return contentsWithMatch; } List<InlineSpan>? _activeSearchAwareLineContents( List<InlineSpan> startingContents, ) { final activeSearchMatch = widget.activeSearchMatch; if (activeSearchMatch == null) return startingContents; return _contentsWithMatch( startingContents, activeSearchMatch, activeSearchMatchColor, ); } List<InlineSpan> _searchMatchAwareLineContents( List<InlineSpan> startingContents, ) { final searchMatches = widget.searchMatches; if (searchMatches == null || searchMatches.isEmpty) return startingContents; final searchMatchesToFind = List<SourceToken>.of(searchMatches) ..remove(widget.activeSearchMatch); var contentsWithMatch = startingContents; for (final match in searchMatchesToFind) { contentsWithMatch = _contentsWithMatch( contentsWithMatch, match, searchMatchColor, ); } return contentsWithMatch; } } class ScriptPopupMenu extends StatelessWidget { const ScriptPopupMenu(this._controller, {super.key}); final CodeViewController _controller; @override Widget build(BuildContext context) { return PopupMenuButton<ScriptPopupMenuOption>( onSelected: (option) => option.onSelected(context, _controller), itemBuilder: (_) => [ for (final menuOption in defaultScriptPopupMenuOptions) menuOption.build(), for (final extensionMenuOption in devToolsExtensionPoints .buildExtraDebuggerScriptPopupMenuOptions()) extensionMenuOption.build(), ], child: Icon( Icons.more_vert, size: actionsIconSize, ), ); } } class ScriptHistoryPopupMenu extends StatelessWidget { const ScriptHistoryPopupMenu({ super.key, required this.itemBuilder, required this.onSelected, required this.enabled, }); final PopupMenuItemBuilder<ScriptRef> itemBuilder; final void Function(ScriptRef) onSelected; final bool enabled; @override Widget build(BuildContext context) { return PopupMenuButton<ScriptRef>( itemBuilder: itemBuilder, tooltip: 'Select recent script', enabled: enabled, onSelected: onSelected, offset: Offset( actionsIconSize + denseSpacing, buttonMinWidth + denseSpacing, ), child: Icon( Icons.history, size: actionsIconSize, ), ); } } class ScriptPopupMenuOption { const ScriptPopupMenuOption({ required this.label, required this.onSelected, this.icon, }); final String label; final void Function(BuildContext, CodeViewController) onSelected; final IconData? icon; PopupMenuItem<ScriptPopupMenuOption> build() { return PopupMenuItem<ScriptPopupMenuOption>( value: this, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(label), if (icon != null) Icon( icon, size: actionsIconSize, ), ], ), ); } } final defaultScriptPopupMenuOptions = [ copyPackagePathOption, copyFilePathOption, goToLineOption, openFileOption, ]; final copyPackagePathOption = ScriptPopupMenuOption( label: 'Copy package path', icon: Icons.content_copy, onSelected: (_, controller) => Clipboard.setData( ClipboardData(text: controller.scriptLocation.value?.scriptRef.uri ?? ''), ), ); final copyFilePathOption = ScriptPopupMenuOption( label: 'Copy file path', icon: Icons.content_copy, onSelected: (_, controller) { unawaited(() async { final filePath = await fetchScriptLocationFullFilePath(controller); await Clipboard.setData( ClipboardData(text: filePath ?? ''), ); }()); }, ); @visibleForTesting Future<String?> fetchScriptLocationFullFilePath( CodeViewController controller, ) async { String? filePath; final packagePath = controller.scriptLocation.value!.scriptRef.uri; if (packagePath != null) { final isolateId = serviceConnection .serviceManager.isolateManager.selectedIsolate.value!.id!; filePath = serviceConnection.serviceManager.resolvedUriManager.lookupFileUri( isolateId, packagePath, ); if (filePath == null) { await serviceConnection.serviceManager.resolvedUriManager.fetchFileUris( isolateId, [packagePath], ); filePath = serviceConnection.serviceManager.resolvedUriManager.lookupFileUri( isolateId, packagePath, ); } } return filePath; } void showGoToLineDialog(BuildContext context, CodeViewController controller) { unawaited( showDialog( context: context, builder: (context) => GoToLineDialog(controller), ), ); } final goToLineOption = ScriptPopupMenuOption( label: 'Go to line number ($goToLineNumberKeySetDescription)', icon: Icons.list, onSelected: showGoToLineDialog, ); void showFileOpener(BuildContext _, CodeViewController controller) { controller.toggleFileOpenerVisibility(true); } final openFileOption = ScriptPopupMenuOption( label: 'Open file ($openFileKeySetDescription)', icon: Icons.folder_open, onSelected: showFileOpener, ); class GoToLineDialog extends StatelessWidget { const GoToLineDialog(this._codeViewController, {super.key}); final CodeViewController _codeViewController; @override Widget build(BuildContext context) { return DevToolsDialog( title: const DialogTitleText('Go To'), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ TextField( autofocus: true, onSubmitted: (value) async { final scriptRef = _codeViewController.scriptLocation.value?.scriptRef; if (value.isNotEmpty && scriptRef != null) { Navigator.of(context).pop(dialogDefaultContext); final line = int.parse(value); await _codeViewController.showScriptLocation( ScriptLocation( scriptRef, location: SourcePosition(line: line, column: 0), ), ); } }, decoration: InputDecoration( labelText: 'Line Number', contentPadding: EdgeInsets.all(scaleByFontFactor(5.0)), ), keyboardType: TextInputType.number, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly, ], ), ], ), actions: const [ DialogCancelButton(), ], ); } } class PositionedPopup extends StatelessWidget { const PositionedPopup({ super.key, required this.isVisibleListenable, required this.child, this.top, this.left, this.right, }); final ValueListenable<bool> isVisibleListenable; final double? top; final double? left; final double? right; final Widget child; @override Widget build(BuildContext context) { return ValueListenableBuilder<bool>( valueListenable: isVisibleListenable, builder: (context, isVisible, _) { return isVisible ? Positioned( top: top, left: left, right: right, child: child, ) : const SizedBox.shrink(); }, ); } } extension CodeViewColorScheme on ColorScheme { Color get performanceLowImpactColor => const Color(0xFF5CB246); Color get performanceMediumImpactColor => const Color(0xFFF7AC2A); Color get performanceHighImpactColor => const Color(0xFFC94040); Color get coverageHitColor => performanceLowImpactColor; Color get coverageMissColor => performanceHighImpactColor; // The default text color for dark mode is difficult to read when drawn on // top of the profiler and coverage gutter items. Color get coverageAndPerformanceTextColor => lightColorScheme.onSurface; }
devtools/packages/devtools_app/lib/src/screens/debugger/codeview.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/debugger/codeview.dart", "repo_id": "devtools", "token_count": 22730 }
97
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_deeplink.dart'; import 'package:flutter/material.dart'; import '../../shared/analytics/analytics.dart' as ga; import '../../shared/analytics/constants.dart' as gac; import '../../shared/globals.dart'; import '../../shared/server/server.dart' as server; import 'deep_links_model.dart'; import 'deep_links_services.dart'; typedef _DomainAndPath = ({String domain, String path}); const domainAssetLinksJsonFileErrors = { DomainError.existence, DomainError.appIdentifier, DomainError.fingerprints, }; const domainHostingErrors = { DomainError.contentType, DomainError.httpsAccessibility, DomainError.nonRedirect, DomainError.hostForm, }; /// The phase of the deep link page. enum PagePhase { // The empty state. emptyState, // Loading links from the flutter project. linksLoading, // Loading completed but no link to validate noLinks, // Validating links. linksValidating, // Links are validated. linksValidated, // Error page. errorPage, } enum FilterOption { http('http://, https://'), custom('Custom scheme'), android('Android'), ios('iOS'), noIssue('No issues found'), failedDomainCheck('Failed domain checks '), failedPathCheck('Failed path checks'); const FilterOption(this.description); final String description; } enum SortingOption { aToZ('A-Z'), zToA('Z-A'), errorOnTop('Error on top'); const SortingOption(this.description); final String description; } class DisplayOptions { DisplayOptions({ this.domainErrorCount = 0, this.pathErrorCount = 0, this.showSplitScreen = false, this.filters = const { FilterOption.http, FilterOption.custom, FilterOption.android, FilterOption.ios, FilterOption.noIssue, FilterOption.failedDomainCheck, FilterOption.failedPathCheck, }, this.searchContent = '', // Default to show result with error first. this.domainSortingOption = SortingOption.errorOnTop, this.pathSortingOption = SortingOption.errorOnTop, }); int domainErrorCount = 0; int pathErrorCount = 0; bool showSplitScreen = false; String searchContent; SortingOption? domainSortingOption; SortingOption? pathSortingOption; final Set<FilterOption> filters; DisplayOptions updateFilter(FilterOption option, bool value) { final newFilter = Set<FilterOption>.of(filters); if (value) { newFilter.add(option); } else { newFilter.remove(option); } return DisplayOptions( domainErrorCount: domainErrorCount, pathErrorCount: pathErrorCount, showSplitScreen: showSplitScreen, filters: newFilter, searchContent: searchContent, domainSortingOption: domainSortingOption, pathSortingOption: pathSortingOption, ); } DisplayOptions copyWith({ int? domainErrorCount, int? pathErrorCount, bool? showSplitScreen, String? searchContent, SortingOption? domainSortingOption, SortingOption? pathSortingOption, }) { return DisplayOptions( domainErrorCount: domainErrorCount ?? this.domainErrorCount, pathErrorCount: pathErrorCount ?? this.pathErrorCount, showSplitScreen: showSplitScreen ?? this.showSplitScreen, filters: filters, searchContent: searchContent ?? '', domainSortingOption: domainSortingOption ?? this.domainSortingOption, pathSortingOption: pathSortingOption ?? this.pathSortingOption, ); } } class DeepLinksController extends DisposableController { DeepLinksController() { selectedVariantIndex.addListener(_handleSelectedVariantIndexChanged); } @override void dispose() { super.dispose(); selectedVariantIndex.removeListener(_handleSelectedVariantIndexChanged); } DisplayOptions get displayOptions => displayOptionsNotifier.value; String get applicationId => _androidAppLinks[selectedVariantIndex.value]?.applicationId ?? ''; List<LinkData> get getLinkDatasByPath { final linkDatasByPath = <String, LinkData>{}; for (var linkData in allValidatedLinkDatas!) { final previousRecord = linkDatasByPath[linkData.path]; linkDatasByPath[linkData.path] = LinkData( domain: linkData.domain, path: linkData.path, os: [ if (previousRecord?.os.contains(PlatformOS.android) ?? false || linkData.os.contains(PlatformOS.android)) PlatformOS.android, if (previousRecord?.os.contains(PlatformOS.ios) ?? false || linkData.os.contains(PlatformOS.ios)) PlatformOS.ios, ], associatedDomains: [ ...previousRecord?.associatedDomains ?? [], linkData.domain, ], pathErrors: linkData.pathErrors, ); } return getFilterredLinks(linkDatasByPath.values.toList()); } List<LinkData> get getLinkDatasByDomain { final linkDatasByDomain = <String, LinkData>{}; for (var linkData in allValidatedLinkDatas!) { final previousRecord = linkDatasByDomain[linkData.domain]; linkDatasByDomain[linkData.domain] = LinkData( domain: linkData.domain, path: linkData.path, os: linkData.os, associatedPath: [ ...previousRecord?.associatedPath ?? [], linkData.path, ], domainErrors: linkData.domainErrors, ); } return getFilterredLinks(linkDatasByDomain.values.toList()); } final Map<int, AppLinkSettings> _androidAppLinks = <int, AppLinkSettings>{}; late final selectedVariantIndex = ValueNotifier<int>(0); void _handleSelectedVariantIndexChanged() { unawaited(_loadAndroidAppLinks()); } Future<void> _loadAndroidAppLinks() async { pagePhase.value = PagePhase.linksLoading; if (!_androidAppLinks.containsKey(selectedVariantIndex.value)) { final variant = selectedProject.value!.androidVariants[selectedVariantIndex.value]; await ga.timeAsync( gac.deeplink, gac.AnalyzeFlutterProject.loadAppLinks.name, asyncOperation: () async { late AppLinkSettings result; try { result = await server.requestAndroidAppLinkSettings( selectedProject.value!.path, buildVariant: variant, ); } catch (_) { pagePhase.value = PagePhase.errorPage; } _androidAppLinks[selectedVariantIndex.value] = result; }, ); } if (pagePhase.value == PagePhase.errorPage) { return; } await validateLinks(); } Future<String?> packageDirectoryForMainIsolate() async { if (!serviceConnection.serviceManager.hasConnection) { return null; } final packageUriString = await serviceConnection.rootPackageDirectoryForMainIsolate(); if (packageUriString == null) return null; return Uri.parse(packageUriString).toFilePath(); } Set<PathError> _getPathErrorsFromIntentFilterChecks( IntentFilterChecks intentFilterChecks, ) { return { if (!intentFilterChecks.hasActionView) PathError.intentFilterActionView, if (!intentFilterChecks.hasBrowsableCategory) PathError.intentFilterBrowsable, if (!intentFilterChecks.hasDefaultCategory) PathError.intentFilterDefault, if (!intentFilterChecks.hasAutoVerify) PathError.intentFilterAutoVerify, }; } /// Get all unverified link data. List<LinkData> get _allRawLinkDatas { final appLinks = _androidAppLinks[selectedVariantIndex.value]?.deeplinks; if (appLinks == null) { return const <LinkData>[]; } final domainPathToLinkData = <_DomainAndPath, LinkData>{}; for (final appLink in appLinks) { final domainAndPath = (domain: appLink.host, path: appLink.path); if (domainPathToLinkData[domainAndPath] == null) { domainPathToLinkData[domainAndPath] = LinkData( domain: appLink.host, path: appLink.path, pathErrors: _getPathErrorsFromIntentFilterChecks(appLink.intentFilterChecks), os: [PlatformOS.android], scheme: [appLink.scheme], ); } else { final linkData = domainPathToLinkData[domainAndPath]!; if (!linkData.scheme.contains(appLink.scheme)) { linkData.scheme.add(appLink.scheme); } final pathErrors = { ...linkData.pathErrors, ..._getPathErrorsFromIntentFilterChecks(appLink.intentFilterChecks), }; linkData.pathErrors = pathErrors; } } return domainPathToLinkData.values.toList(); } final selectedProject = ValueNotifier<FlutterProject?>(null); final googlePlayFingerprintsAvailability = ValueNotifier<bool>(false); final localFingerprint = ValueNotifier<String?>(null); final selectedLink = ValueNotifier<LinkData?>(null); final pagePhase = ValueNotifier<PagePhase>(PagePhase.emptyState); List<LinkData>? allValidatedLinkDatas; final displayLinkDatasNotifier = ValueNotifier<List<LinkData>?>(null); final generatedAssetLinksForSelectedLink = ValueNotifier<GenerateAssetLinksResult?>(null); final displayOptionsNotifier = ValueNotifier<DisplayOptions>(DisplayOptions()); /// The [TextEditingController] for the search text field. final textEditingController = TextEditingController(); final deepLinksServices = DeepLinksServices(); bool addLocalFingerprint(String fingerprint) { // A valid fingerprint consists of 32 pairs of hexadecimal digits separated by colons. bool isValidFingerpint(String input) { final RegExp pattern = RegExp(r'^([0-9a-f]{2}:){31}[0-9a-f]{2}$', caseSensitive: false); return pattern.hasMatch(input); } if (!isValidFingerpint(fingerprint)) { return false; } if (localFingerprint.value != fingerprint) { localFingerprint.value = fingerprint; // If the local fingerprint is updated, re-generate asset link file. unawaited(_generateAssetLinks()); } return true; } Future<void> _generateAssetLinks() async { generatedAssetLinksForSelectedLink.value = null; generatedAssetLinksForSelectedLink.value = await deepLinksServices.generateAssetLinks( domain: selectedLink.value!.domain, applicationId: applicationId, localFingerprint: localFingerprint.value, ); } Future<List<LinkData>> _validateAndroidDomain( List<LinkData> linkdatas, ) async { final domains = linkdatas .where((linkdata) => linkdata.os.contains(PlatformOS.android)) .map((linkdata) => linkdata.domain) .toSet() .toList(); late final Map<String, List<DomainError>> domainErrors; try { final result = await deepLinksServices.validateAndroidDomain( domains: domains, applicationId: applicationId, localFingerprint: localFingerprint.value, ); domainErrors = result.domainErrors; googlePlayFingerprintsAvailability.value = result.googlePlayFingerprintsAvailability; } catch (_) { //TODO(hangyujin): Add more error handling for cases like RPC error and invalid json. pagePhase.value = PagePhase.errorPage; return linkdatas; } return linkdatas.map((linkdata) { final errors = domainErrors[linkdata.domain]; if (errors != null && errors.isNotEmpty) { return LinkData( domain: linkdata.domain, domainErrors: errors, path: linkdata.path, pathErrors: linkdata.pathErrors, os: linkdata.os, scheme: linkdata.scheme, associatedDomains: linkdata.associatedDomains, associatedPath: linkdata.associatedPath, ); } return linkdata; }).toList(); } Future<List<LinkData>> _validatePath(List<LinkData> linkdatas) async { for (final linkData in linkdatas) { if (!(linkData.path.startsWith('/') || linkData.path == '.*')) { linkData.pathErrors.add(PathError.pathFormat); } } return linkdatas; } Future<void> validateLinks() async { List<LinkData> linkdata = _allRawLinkDatas; if (linkdata.isEmpty) { pagePhase.value = PagePhase.noLinks; return; } pagePhase.value = PagePhase.linksValidating; linkdata = await _validateAndroidDomain(linkdata); if (pagePhase.value == PagePhase.errorPage) { return; } linkdata = await _validatePath(linkdata); if (pagePhase.value == PagePhase.errorPage) { return; } allValidatedLinkDatas = linkdata; pagePhase.value = PagePhase.linksValidated; displayLinkDatasNotifier.value = getFilterredLinks(allValidatedLinkDatas!); displayOptionsNotifier.value = displayOptionsNotifier.value.copyWith( domainErrorCount: getLinkDatasByDomain .where((element) => element.domainErrors.isNotEmpty) .length, pathErrorCount: getLinkDatasByPath .where((element) => element.pathErrors.isNotEmpty) .length, ); } void selectLink(LinkData linkdata) async { selectedLink.value = linkdata; if (linkdata.domainErrors.isNotEmpty) { await _generateAssetLinks(); } } set searchContent(String content) { displayOptionsNotifier.value = displayOptionsNotifier.value.copyWith(searchContent: content); displayLinkDatasNotifier.value = getFilterredLinks(allValidatedLinkDatas!); } void updateDisplayOptions({ int? domainErrorCount, int? pathErrorCount, bool? showSplitScreen, SortingOption? domainSortingOption, SortingOption? pathSortingOption, FilterOption? addedFilter, FilterOption? removedFilter, }) { displayOptionsNotifier.value = displayOptionsNotifier.value.copyWith( domainErrorCount: domainErrorCount, pathErrorCount: pathErrorCount, showSplitScreen: showSplitScreen, domainSortingOption: domainSortingOption, pathSortingOption: pathSortingOption, ); if (addedFilter != null) { displayOptionsNotifier.value = displayOptionsNotifier.value.updateFilter(addedFilter, true); } if (removedFilter != null) { displayOptionsNotifier.value = displayOptionsNotifier.value.updateFilter(removedFilter, false); } displayLinkDatasNotifier.value = getFilterredLinks(allValidatedLinkDatas!); } @visibleForTesting List<LinkData> getFilterredLinks(List<LinkData> linkDatas) { final String searchContent = displayOptions.searchContent; linkDatas = linkDatas.where((linkData) { if (searchContent.isNotEmpty && !linkData.matchesSearchToken( RegExp(searchContent, caseSensitive: false), )) { return false; } if (!((linkData.os.contains(PlatformOS.android) && displayOptions.filters.contains(FilterOption.android)) || (linkData.os.contains(PlatformOS.ios) && displayOptions.filters.contains(FilterOption.ios)))) { return false; } if (!((linkData.domainErrors.isNotEmpty && displayOptions.filters .contains(FilterOption.failedDomainCheck)) || (linkData.pathErrors.isNotEmpty && displayOptions.filters.contains(FilterOption.failedPathCheck)) || (linkData.domainErrors.isEmpty && linkData.pathErrors.isEmpty && displayOptions.filters.contains(FilterOption.noIssue)))) { return false; } return true; }).toList(); return linkDatas; } }
devtools/packages/devtools_app/lib/src/screens/deep_link_validation/deep_links_controller.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/deep_link_validation/deep_links_controller.dart", "repo_id": "devtools", "token_count": 5929 }
98
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; const defaultArrowColor = Colors.white; const defaultArrowStrokeWidth = 2.0; const defaultDistanceToArrow = 4.0; enum ArrowType { up, left, right, down, } Axis axis(ArrowType type) => (type == ArrowType.up || type == ArrowType.down) ? Axis.vertical : Axis.horizontal; /// Widget that draws a bidirectional arrow around another widget. /// /// This widget is typically used to help draw diagrams. @immutable class ArrowWrapper extends StatelessWidget { ArrowWrapper.unidirectional({ Key? key, this.child, required ArrowType type, this.arrowColor = defaultArrowColor, double? arrowHeadSize, this.arrowStrokeWidth = defaultArrowStrokeWidth, this.childMarginFromArrow = defaultDistanceToArrow, }) : assert(childMarginFromArrow > 0.0), direction = axis(type), isBidirectional = false, startArrowType = type, endArrowType = type, arrowHeadSize = arrowHeadSize ?? defaultIconSize, super(key: key); const ArrowWrapper.bidirectional({ Key? key, this.child, required this.direction, this.arrowColor = defaultArrowColor, required this.arrowHeadSize, this.arrowStrokeWidth = defaultArrowStrokeWidth, this.childMarginFromArrow = defaultDistanceToArrow, }) : assert(arrowHeadSize >= 0.0), assert(childMarginFromArrow >= 0.0), isBidirectional = true, startArrowType = direction == Axis.horizontal ? ArrowType.left : ArrowType.up, endArrowType = direction == Axis.horizontal ? ArrowType.right : ArrowType.down, super(key: key); final Color arrowColor; final double arrowHeadSize; final double arrowStrokeWidth; final Widget? child; final Axis direction; final double childMarginFromArrow; final bool isBidirectional; final ArrowType startArrowType; final ArrowType endArrowType; double get verticalMarginFromArrow { if (child == null || direction == Axis.horizontal) return 0.0; return childMarginFromArrow; } double get horizontalMarginFromArrow { if (child == null || direction == Axis.vertical) return 0.0; return childMarginFromArrow; } @override Widget build(BuildContext context) { return Flex( direction: direction, children: <Widget>[ Expanded( child: Container( margin: EdgeInsets.only( bottom: verticalMarginFromArrow, right: horizontalMarginFromArrow, ), child: ArrowWidget( color: arrowColor, headSize: arrowHeadSize, strokeWidth: arrowStrokeWidth, type: startArrowType, shouldDrawHead: isBidirectional ? true : (startArrowType == ArrowType.left || startArrowType == ArrowType.up), ), ), ), if (child != null) child!, Expanded( child: Container( margin: EdgeInsets.only( top: verticalMarginFromArrow, left: horizontalMarginFromArrow, ), child: ArrowWidget( color: arrowColor, headSize: arrowHeadSize, strokeWidth: arrowStrokeWidth, type: endArrowType, shouldDrawHead: isBidirectional ? true : (endArrowType == ArrowType.right || endArrowType == ArrowType.down), ), ), ), ], ); } } /// Widget that draws a fully sized, centered, unidirectional arrow according to its constraints @immutable class ArrowWidget extends StatelessWidget { ArrowWidget({ this.color = defaultArrowColor, required this.headSize, Key? key, this.shouldDrawHead = true, this.strokeWidth = defaultArrowStrokeWidth, required this.type, }) : assert(headSize > 0.0), assert(strokeWidth > 0.0), _painter = _ArrowPainter( headSize: headSize, color: color, strokeWidth: strokeWidth, type: type, shouldDrawHead: shouldDrawHead, ), super(key: key); final Color color; /// The arrow head is a Equilateral triangle final double headSize; final double strokeWidth; final ArrowType type; final CustomPainter _painter; final bool shouldDrawHead; @override Widget build(BuildContext context) { return CustomPaint( painter: _painter, child: Container(), ); } } class _ArrowPainter extends CustomPainter { _ArrowPainter({ required this.headSize, this.strokeWidth = defaultArrowStrokeWidth, this.color = defaultArrowColor, this.shouldDrawHead = true, required this.type, }) : // the height of an equilateral triangle headHeight = 0.5 * sqrt(3) * headSize; final Color color; final double headSize; final bool shouldDrawHead; final double strokeWidth; final ArrowType type; final double headHeight; bool headIsGreaterThanConstraint(Size size) { if (type == ArrowType.left || type == ArrowType.right) { return headHeight >= (size.width); } return headHeight >= (size.height); } @override bool shouldRepaint(CustomPainter oldDelegate) => !(oldDelegate is _ArrowPainter && headSize == oldDelegate.headSize && strokeWidth == oldDelegate.strokeWidth && color == oldDelegate.color && type == oldDelegate.type); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = color ..strokeWidth = strokeWidth; final originX = size.width / 2, originY = size.height / 2; Offset lineStartingPoint = Offset.zero; Offset lineEndingPoint = Offset.zero; if (!headIsGreaterThanConstraint(size) && shouldDrawHead) { Offset p1, p2, p3; final headSizeDividedBy2 = headSize / 2; switch (type) { case ArrowType.up: p1 = Offset(originX, 0); p2 = Offset(originX - headSizeDividedBy2, headHeight); p3 = Offset(originX + headSizeDividedBy2, headHeight); break; case ArrowType.left: p1 = Offset(0, originY); p2 = Offset(headHeight, originY - headSizeDividedBy2); p3 = Offset(headHeight, originY + headSizeDividedBy2); break; case ArrowType.right: final startingX = size.width - headHeight; p1 = Offset(size.width, originY); p2 = Offset(startingX, originY - headSizeDividedBy2); p3 = Offset(startingX, originY + headSizeDividedBy2); break; case ArrowType.down: final startingY = size.height - headHeight; p1 = Offset(originX, size.height); p2 = Offset(originX - headSizeDividedBy2, startingY); p3 = Offset(originX + headSizeDividedBy2, startingY); break; } final path = Path() ..moveTo(p1.dx, p1.dy) ..lineTo(p2.dx, p2.dy) ..lineTo(p3.dx, p3.dy) ..close(); canvas.drawPath(path, paint); switch (type) { case ArrowType.up: lineStartingPoint = Offset(originX, headHeight); lineEndingPoint = Offset(originX, size.height); break; case ArrowType.left: lineStartingPoint = Offset(headHeight, originY); lineEndingPoint = Offset(size.width, originY); break; case ArrowType.right: final arrowHeadStartingX = size.width - headHeight; lineStartingPoint = Offset(0, originY); lineEndingPoint = Offset(arrowHeadStartingX, originY); break; case ArrowType.down: final headStartingY = size.height - headHeight; lineStartingPoint = Offset(originX, 0); lineEndingPoint = Offset(originX, headStartingY); break; } } else { // draw full line switch (type) { case ArrowType.up: case ArrowType.down: lineStartingPoint = Offset(originX, 0); lineEndingPoint = Offset(originX, size.height); break; case ArrowType.left: case ArrowType.right: lineStartingPoint = Offset(0, originY); lineEndingPoint = Offset(size.width, originY); break; } } canvas.drawLine( lineStartingPoint, lineEndingPoint, paint, ); } }
devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/arrow.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/arrow.dart", "repo_id": "devtools", "token_count": 3724 }
99
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter/material.dart'; import '../../../../shared/charts/chart.dart'; import '../../../../shared/charts/chart_controller.dart'; import '../../../../shared/charts/chart_trace.dart' as trace; import '../../../../shared/charts/chart_trace.dart' show ChartType; import '../../../../shared/utils.dart'; import '../../framework/connected/memory_controller.dart'; import '../../shared/primitives/memory_timeline.dart'; // TODO(terry): Consider custom painter? const _base = 'assets/img/legend/'; const snapshotManualLegend = '${_base}snapshot_manual_glyph.png'; const snapshotAutoLegend = '${_base}snapshot_auto_glyph.png'; const monitorLegend = '${_base}monitor_glyph.png'; const resetDarkLegend = '${_base}reset_glyph_dark.png'; const resetLightLegend = '${_base}reset_glyph_light.png'; const gcManualLegend = '${_base}gc_manual_glyph.png'; const gcVMLegend = '${_base}gc_vm_glyph.png'; String eventLegendAsset(int eventCount) => '$_base${pluralize('event', eventCount)}_glyph.png'; /// Events trace name displayed const manualSnapshotLegendName = 'Snapshot'; const autoSnapshotLegendName = 'Auto'; const monitorLegendName = 'Monitor'; const resetLegendName = 'Reset'; const vmGCLegendName = 'GC VM'; const manualGCLegendName = 'Manual'; const eventLegendName = 'Event'; const eventsLegendName = 'Events'; class EventChartController extends ChartController { EventChartController(this._memoryController) : super( displayYLabels: false, displayXAxis: false, displayXLabels: false, name: 'Event Pane', ); final MemoryController _memoryController; // TODO(terry): Only load max visible data collected, when pruning of data // charted is added. /// Preload any existing data collected but not in the chart. @override void setupData() { final chartDataLength = timestampsLength; final dataLength = _memoryController.controllers.memoryTimeline.data.length; final dataRange = _memoryController.controllers.memoryTimeline.data.getRange( chartDataLength, dataLength, ); dataRange.forEach(addSample); } /// Loads all heap samples (live data or offline). void addSample(HeapSample sample) { // If paused don't update the chart (data is still collected). if (_memoryController.paused.value) return; addTimestamp(sample.timestamp); if (sample.isGC) { // Plot the VM GC on the VmEvent trace with a fixed Y coordinate. addDataToTrace( EventsTraceName.gc.index, trace.Data(sample.timestamp, MemoryEventsPaneState.visibleVmEvent), ); } final events = sample.memoryEventInfo; if (events.hasExtensionEvents) { final data = trace.DataAggregate( sample.timestamp, MemoryEventsPaneState.extensionEvent, (events.extensionEvents?.theEvents ?? []).length, ); addDataToTrace(EventsTraceName.extensionEvents.index, data); } // User events snapshot, auto-snapshot, manual GC, are plotted on the top-line // of the event pane (visible Events). final data = trace.Data( sample.timestamp, MemoryEventsPaneState.visibleEvent, ); if (events.isEventGC) { // Plot manual requested GC on the visibleEvent Y coordinate. addDataToTrace(EventsTraceName.manualGC.index, data); } if (events.isEventSnapshot) { // Plot snapshot on the visibleEvent Y coordinate. addDataToTrace(EventsTraceName.snapshot.index, data); } if (events.isEventSnapshotAuto) { // Plot auto-snapshot on the visibleEvent Y coordinate. addDataToTrace(EventsTraceName.autoSnapshot.index, data); } if (sample.memoryEventInfo.isEventAllocationAccumulator) { final allocationEvent = events.allocationAccumulator!; final data = trace.Data( sample.timestamp, MemoryEventsPaneState.visibleMonitorEvent, ); if (allocationEvent.isReset) { addDataToTrace(EventsTraceName.monitorReset.index, data); } else if (allocationEvent.isStart) { addDataToTrace(EventsTraceName.monitor.index, data); } } } void addDataToTrace(int traceIndex, trace.Data data) { this.trace(traceIndex).addDatum(data); } } class MemoryEventsPane extends StatefulWidget { const MemoryEventsPane(this.chartController, {Key? key}) : super(key: key); final EventChartController chartController; @override MemoryEventsPaneState createState() => MemoryEventsPaneState(); } /// Name of each trace being charted, index order is the trace index /// too (order of trace creation top-down order). enum EventsTraceName { extensionEvents, snapshot, autoSnapshot, manualGC, monitor, monitorReset, gc, } class MemoryEventsPaneState extends State<MemoryEventsPane> with AutoDisposeMixin, ProvidedControllerMixin<MemoryController, MemoryEventsPane> { /// Controller attached to this chart. EventChartController get _chartController => widget.chartController; /// Note: The event pane is a fixed size chart (y-axis does not scale). The /// Y-axis fixed range is (visibleVmEvent to extensionEvent) e.g., /// /// ____________________ /// extensionEvent -| * (3.7) /// | * (2.4) /// | * (1.4) /// visibleVmEvent -| * (0.4) /// 0.0 _|___________________ /// /// The *s in the above chart are plotted at each y position (3.7, 2.4, 1.4, 0.4). /// Their y-position is such that the symbols won't overlap. /// TODO(terry): Consider a better solution e.g., % in the Y-axis. /// Flutter events and user custom events. static const extensionEvent = 3.7; /// Event to display in the event pane (User initiated GC, snapshot, /// automatic snapshot, etc.) static const visibleEvent = 2.4; /// Monitor events Y axis. static const visibleMonitorEvent = 1.4; /// VM's GCs are displayed in a smaller glyph and closer to the heap graph. static const visibleVmEvent = 0.4; MemoryTimeline get _memoryTimeline => controller.controllers.memoryTimeline; @override void initState() { super.initState(); // Line chart fixed Y range. _chartController.setFixedYRange(visibleVmEvent, extensionEvent); } @override void didChangeDependencies() { super.didChangeDependencies(); if (!initController()) return; final themeData = Theme.of(context); cancelListeners(); setupTraces(isDarkMode: themeData.isDarkTheme); _chartController.setupData(); // Monitor heap samples. addAutoDisposeListener(_memoryTimeline.sampleAddedNotifier, () { final value = _memoryTimeline.sampleAddedNotifier.value; if (value == null) return; setState(() => _processHeapSample(value)); }); // Monitor event fired. addAutoDisposeListener(_memoryTimeline.eventNotifier, () { setState(() { // TODO(terry): New event received. //_processHeapSample(_memoryTimeline.eventNotifier.value); }); }); } @override Widget build(BuildContext context) { if (_chartController.timestamps.isNotEmpty) { return Chart(_chartController); } return const SizedBox(width: denseSpacing); } void setupTraces({bool isDarkMode = true}) { if (_chartController.traces.isNotEmpty) { assert(_chartController.traces.length == EventsTraceName.values.length); final extensionEventsIndex = EventsTraceName.extensionEvents.index; assert( _chartController.trace(extensionEventsIndex).name == EventsTraceName.values[extensionEventsIndex].toString(), ); final snapshotIndex = EventsTraceName.snapshot.index; assert( _chartController.trace(snapshotIndex).name == EventsTraceName.values[snapshotIndex].toString(), ); final autoSnapshotIndex = EventsTraceName.autoSnapshot.index; assert( _chartController.trace(autoSnapshotIndex).name == EventsTraceName.values[autoSnapshotIndex].toString(), ); final manualGCIndex = EventsTraceName.manualGC.index; assert( _chartController.trace(manualGCIndex).name == EventsTraceName.values[manualGCIndex].toString(), ); final monitorIndex = EventsTraceName.monitor.index; assert( _chartController.trace(monitorIndex).name == EventsTraceName.values[monitorIndex].toString(), ); final monitorResetIndex = EventsTraceName.monitorReset.index; assert( _chartController.trace(monitorResetIndex).name == EventsTraceName.values[monitorResetIndex].toString(), ); final gcIndex = EventsTraceName.gc.index; assert( _chartController.trace(gcIndex).name == EventsTraceName.values[gcIndex].toString(), ); return; } final extensionEventsIndex = _chartController.createTrace( trace.ChartType.symbol, trace.PaintCharacteristics( color: Colors.purpleAccent[100]!, colorAggregate: Colors.purpleAccent[400], symbol: trace.ChartSymbol.filledTriangle, height: 20, width: 20, fixedMinY: visibleVmEvent, fixedMaxY: extensionEvent, ), name: EventsTraceName.extensionEvents.toString(), ); assert(extensionEventsIndex == EventsTraceName.extensionEvents.index); assert( _chartController.trace(extensionEventsIndex).name == EventsTraceName.values[extensionEventsIndex].toString(), ); final snapshotIndex = _chartController.createTrace( trace.ChartType.symbol, trace.PaintCharacteristics( color: Colors.green, strokeWidth: 3, diameter: 6, fixedMinY: visibleVmEvent, fixedMaxY: extensionEvent, ), name: EventsTraceName.snapshot.toString(), ); assert(snapshotIndex == EventsTraceName.snapshot.index); assert( _chartController.trace(snapshotIndex).name == EventsTraceName.values[snapshotIndex].toString(), ); // Auto-snapshot final autoSnapshotIndex = _chartController.createTrace( ChartType.symbol, trace.PaintCharacteristics( color: Colors.red, strokeWidth: 3, diameter: 6, fixedMinY: visibleVmEvent, fixedMaxY: extensionEvent, ), name: EventsTraceName.autoSnapshot.toString(), ); assert(autoSnapshotIndex == EventsTraceName.autoSnapshot.index); assert( _chartController.trace(autoSnapshotIndex).name == EventsTraceName.values[autoSnapshotIndex].toString(), ); // Manual GC final manualGCIndex = _chartController.createTrace( ChartType.symbol, trace.PaintCharacteristics( color: Colors.blue, strokeWidth: 3, diameter: 6, fixedMinY: visibleVmEvent, fixedMaxY: extensionEvent, ), name: EventsTraceName.manualGC.toString(), ); assert(manualGCIndex == EventsTraceName.manualGC.index); assert( _chartController.trace(manualGCIndex).name == EventsTraceName.values[manualGCIndex].toString(), ); final mainMonitorColor = isDarkMode ? Colors.yellowAccent : Colors.yellowAccent.shade400; // Monitor final monitorIndex = _chartController.createTrace( ChartType.symbol, trace.PaintCharacteristics( color: mainMonitorColor, strokeWidth: 3, diameter: 6, fixedMinY: visibleVmEvent, fixedMaxY: extensionEvent, ), name: EventsTraceName.monitor.toString(), ); assert(monitorIndex == EventsTraceName.monitor.index); assert( _chartController.trace(monitorIndex).name == EventsTraceName.values[monitorIndex].toString(), ); final monitorResetIndex = _chartController.createTrace( ChartType.symbol, trace.PaintCharacteristics.concentric( color: Colors.grey[600]!, strokeWidth: 4, diameter: 6, fixedMinY: visibleVmEvent, fixedMaxY: extensionEvent, concentricCenterColor: mainMonitorColor, concentricCenterDiameter: 4, ), name: EventsTraceName.monitorReset.toString(), ); assert(monitorResetIndex == EventsTraceName.monitorReset.index); assert( _chartController.trace(monitorResetIndex).name == EventsTraceName.values[monitorResetIndex].toString(), ); // VM GC final gcIndex = _chartController.createTrace( ChartType.symbol, trace.PaintCharacteristics( color: Colors.blue, symbol: trace.ChartSymbol.disc, diameter: 4, fixedMinY: visibleVmEvent, fixedMaxY: extensionEvent, ), name: EventsTraceName.gc.toString(), ); assert(gcIndex == EventsTraceName.gc.index); assert( _chartController.trace(gcIndex).name == EventsTraceName.values[gcIndex].toString(), ); assert(_chartController.traces.length == EventsTraceName.values.length); } /// Loads all heap samples (live data or offline). void _processHeapSample(HeapSample sample) { // If paused don't update the chart (data is still collected). if (controller.isPaused) return; _chartController.addSample(sample); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/chart/memory_events_pane.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/chart/memory_events_pane.dart", "repo_id": "devtools", "token_count": 5186 }
100
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/widgets.dart'; import '../../../../../../shared/analytics/analytics.dart' as ga; import '../../../../../../shared/analytics/constants.dart' as gac; import '../../../../../../shared/primitives/byte_utils.dart'; import '../../../../../../shared/primitives/utils.dart'; import '../../../../../../shared/table/table.dart'; import '../../../../../../shared/table/table_data.dart'; import '../../../../shared/heap/heap.dart'; import '../../../../shared/primitives/simple_elements.dart'; class _RetainingPathColumn extends ColumnData<StatsByPathEntry> { _RetainingPathColumn(String className) : super.wide( 'Shortest Retaining Path for Instances of $className', titleTooltip: 'The shortest sequence of objects\n' 'retaining $className instances from garbage collection.', alignment: ColumnAlignment.left, ); @override String? getValue(StatsByPathEntry record) => record.key.toShortString(inverted: true); @override bool get supportsSorting => true; @override String getTooltip(StatsByPathEntry record) => ''; } class _InstanceColumn extends ColumnData<StatsByPathEntry> { _InstanceColumn(bool isDiff) : super( isDiff ? 'Instance\nDelta' : 'Instances', titleTooltip: 'Number of instances of the class\n' 'retained by the path.', fixedWidthPx: scaleByFontFactor(80.0), alignment: ColumnAlignment.right, ); @override int getValue(StatsByPathEntry record) => record.value.instanceCount; @override bool get numeric => true; } class _ShallowSizeColumn extends ColumnData<StatsByPathEntry> { _ShallowSizeColumn(bool isDiff) : super( isDiff ? 'Shallow\nSize Delta' : 'Shallow\nDart Size', titleTooltip: SizeType.shallow.description, fixedWidthPx: scaleByFontFactor(80.0), alignment: ColumnAlignment.right, ); @override int getValue(StatsByPathEntry record) => record.value.shallowSize; @override bool get numeric => true; @override String getDisplayValue(StatsByPathEntry record) => prettyPrintBytes(getValue(record), includeUnit: true)!; } class _RetainedSizeColumn extends ColumnData<StatsByPathEntry> { _RetainedSizeColumn(bool isDiff) : super( isDiff ? 'Retained\nSize Delta' : 'Retained\nDart Size', titleTooltip: SizeType.retained.description, fixedWidthPx: scaleByFontFactor(80.0), alignment: ColumnAlignment.right, ); @override int getValue(StatsByPathEntry record) => record.value.retainedSize; @override bool get numeric => true; @override String getDisplayValue(StatsByPathEntry record) => prettyPrintBytes(getValue(record), includeUnit: true)!; } class _RetainingPathTableColumns { _RetainingPathTableColumns(this.isDiff, this.className); final bool isDiff; final String className; late final retainedSizeColumn = _RetainedSizeColumn(isDiff); late final columnList = <ColumnData<StatsByPathEntry>>[ _RetainingPathColumn(className), _InstanceColumn(isDiff), _ShallowSizeColumn(isDiff), retainedSizeColumn, ]; } class RetainingPathTable extends StatelessWidget { const RetainingPathTable({ Key? key, required this.entries, required this.selection, required this.isDiff, required this.className, }) : super(key: key); final List<StatsByPathEntry> entries; final ValueNotifier<StatsByPathEntry?> selection; final bool isDiff; final String className; static final _columnStore = <String, _RetainingPathTableColumns>{}; static _RetainingPathTableColumns _columns( String dataKey, bool isDiff, String className, ) => _columnStore.putIfAbsent( dataKey, () => _RetainingPathTableColumns(isDiff, className), ); @override Widget build(BuildContext context) { final dataKey = 'RetainingPathTable-$isDiff-$className'; final columns = _columns(dataKey, isDiff, className); return FlatTable<StatsByPathEntry>( dataKey: dataKey, columns: columns.columnList, data: entries, keyFactory: (e) => Key(e.key.toLongString()), selectionNotifier: selection, onItemSelected: (_) => ga.select( gac.memory, '${gac.MemoryEvent.diffPathSelect}-${isDiff ? "diff" : "single"}', ), defaultSortColumn: columns.retainedSizeColumn, defaultSortDirection: SortDirection.descending, tallHeaders: true, ); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/class_details/paths.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/class_details/paths.dart", "repo_id": "devtools", "token_count": 1733 }
101
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../../../shared/globals.dart'; import '../../../../shared/primitives/simple_items.dart'; import '../../shared/widgets/shared_memory_widgets.dart'; import 'class_table.dart'; import 'tracing_pane_controller.dart'; import 'tracing_tree.dart'; class TracingPane extends StatefulWidget { const TracingPane({ Key? key, required this.controller, }) : super(key: key); final TracingPaneController controller; @override State<TracingPane> createState() => TracingPaneState(); } class TracingPaneState extends State<TracingPane> { @override void initState() { super.initState(); unawaited(widget.controller.initialize()); } @override Widget build(BuildContext context) { final isProfileMode = serviceConnection.serviceManager.connectedApp?.isProfileBuildNow ?? false; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _TracingControls( isProfileMode: isProfileMode, controller: widget.controller, ), Expanded( child: OutlineDecoration.onlyTop( child: SplitPane( axis: Axis.horizontal, initialFractions: const [0.25, 0.75], children: [ OutlineDecoration.onlyRight( child: AllocationTracingTable( controller: widget.controller, ), ), OutlineDecoration.onlyLeft( child: AllocationTracingTree( controller: widget.controller, ), ), ], ), ), ), ], ); } } class _TracingControls extends StatelessWidget { const _TracingControls({ required this.isProfileMode, required this.controller, }); final bool isProfileMode; final TracingPaneController controller; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(denseSpacing), child: Row( children: [ RefreshButton( tooltip: 'Request the set of updated allocation traces', gaScreen: gac.memory, gaSelection: gac.MemoryEvent.tracingRefresh, onPressed: isProfileMode ? null : controller.refresh, ), const SizedBox(width: denseSpacing), ClearButton( tooltip: 'Clear the set of previously collected traces', gaScreen: gac.memory, gaSelection: gac.MemoryEvent.tracingClear, onPressed: isProfileMode ? null : controller.clear, ), const SizedBox(width: denseSpacing), const _ProfileHelpLink(), ], ), ); } } class _ProfileHelpLink extends StatelessWidget { const _ProfileHelpLink({Key? key}) : super(key: key); static const _documentationTopic = gac.MemoryEvent.tracingHelp; @override Widget build(BuildContext context) { return HelpButtonWithDialog( gaScreen: gac.memory, gaSelection: gac.topicDocumentationButton(_documentationTopic), dialogTitle: 'Memory Allocation Tracing Help', actions: [ MoreInfoLink( url: DocLinks.trace.value, gaScreenName: gac.memory, gaSelectedItemDescription: gac.topicDocumentationLink(_documentationTopic), ), ], child: const Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( 'The allocation tracing tab allows for toggling allocation\n' 'tracing for specific types, which records the locations of\n' 'allocations of instances of traced types within the\n' 'currently selected isolate.\n' '\n' 'Allocation sites of traced types can be viewed by refreshing\n' 'the tracing profile before selecting the traced type from the\n' 'list, displaying a condensed view of locations where objects\n' 'were allocated.', ), SizedBox(height: denseSpacing), ClassTypeLegend(), ], ), ); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/tracing/tracing_view.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/tracing/tracing_view.dart", "repo_id": "devtools", "token_count": 1944 }
102
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../shared/analytics/constants.dart' as gac; import '../../shared/http/http_request_data.dart'; import '../../shared/ui/tab.dart'; import 'network_controller.dart'; import 'network_model.dart'; import 'network_request_inspector_views.dart'; /// A [Widget] which displays information about a network request. class NetworkRequestInspector extends StatelessWidget { const NetworkRequestInspector(this.controller, {super.key}); static const _overviewTabTitle = 'Overview'; static const _headersTabTitle = 'Headers'; static const _requestTabTitle = 'Request'; static const _responseTabTitle = 'Response'; static const _cookiesTabTitle = 'Cookies'; final NetworkController controller; DevToolsTab _buildTab({required String tabName, Widget? trailing}) { return DevToolsTab.create( tabName: tabName, gaPrefix: 'requestInspectorTab', trailing: trailing, ); } @override Widget build(BuildContext context) { return ValueListenableBuilder<NetworkRequest?>( valueListenable: controller.selectedRequest, builder: (context, data, _) { return RoundedOutlinedBorder( child: (data == null) ? Center( child: Text( 'No request selected', style: Theme.of(context).regularTextStyle, ), ) : ListenableBuilder( listenable: data, builder: (context, _) { return AnalyticsTabbedView( analyticsSessionIdentifier: data.id, tabs: _generateTabs(data), gaScreen: gac.network, ); }, ), ); }, ); } List<({DevToolsTab tab, Widget tabView})> _generateTabs( NetworkRequest data, ) => [ ( tab: _buildTab(tabName: NetworkRequestInspector._overviewTabTitle), tabView: NetworkRequestOverviewView(data), ), if (data is DartIOHttpRequestData) ...[ ( tab: _buildTab(tabName: NetworkRequestInspector._headersTabTitle), tabView: HttpRequestHeadersView(data), ), if (data.requestBody != null) ( tab: _buildTab( tabName: NetworkRequestInspector._requestTabTitle, trailing: HttpViewTrailingCopyButton( data, (data) => data.requestBody, ), ), tabView: HttpRequestView(data), ), if (data.responseBody != null) ( tab: _buildTab( tabName: NetworkRequestInspector._responseTabTitle, trailing: Row( children: [ HttpResponseTrailingDropDown( data, currentResponseViewType: controller.currentResponseViewType, onChanged: (value) => controller.setResponseViewType = value, ), HttpViewTrailingCopyButton( data, (data) => data.responseBody, ), ], ), ), tabView: HttpResponseView( data, currentResponseViewType: controller.currentResponseViewType, ), ), if (data.hasCookies) ( tab: _buildTab(tabName: NetworkRequestInspector._cookiesTabTitle), tabView: HttpRequestCookiesView(data), ), ], ] .map( (t) => ( tab: t.tab, tabView: OutlineDecoration.onlyTop(child: t.tabView), ), ) .toList(); }
devtools/packages/devtools_app/lib/src/screens/network/network_request_inspector.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/network/network_request_inspector.dart", "repo_id": "devtools", "token_count": 2089 }
103
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../../../service/service_extensions.dart' as extensions; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../../../shared/connected_app.dart'; import '../../../../shared/globals.dart'; import '../../../../shared/primitives/utils.dart'; import '../../performance_controller.dart'; import '../../performance_utils.dart'; import '../controls/enhance_tracing/enhance_tracing.dart'; import '../controls/enhance_tracing/enhance_tracing_controller.dart'; import '../controls/enhance_tracing/enhance_tracing_model.dart'; import 'frame_analysis_model.dart'; class FrameHints extends StatelessWidget { const FrameHints({ Key? key, required this.frameAnalysis, required this.enhanceTracingController, }) : super(key: key); final FrameAnalysis frameAnalysis; final EnhanceTracingController enhanceTracingController; @override Widget build(BuildContext context) { final performanceController = Provider.of<PerformanceController>(context); final frame = frameAnalysis.frame; final displayRefreshRate = performanceController.flutterFramesController.displayRefreshRate.value; final showUiJankHints = frame.isUiJanky(displayRefreshRate); final showRasterJankHints = frame.isRasterJanky(displayRefreshRate); if (!(showUiJankHints || showRasterJankHints)) { return const Text('No suggestions for this frame - no jank detected.'); } final saveLayerCount = frameAnalysis.saveLayerCount; final intrinsicOperationsCount = frameAnalysis.intrinsicOperationsCount; final uiHints = showUiJankHints ? [ const Text('UI Jank Detected'), const SizedBox(height: denseSpacing), EnhanceTracingHint( longestPhase: frameAnalysis.longestUiPhase, enhanceTracingState: frameAnalysis.frame.enhanceTracingState, enhanceTracingController: enhanceTracingController, ), const SizedBox(height: densePadding), if (intrinsicOperationsCount > 0) IntrinsicOperationsHint(intrinsicOperationsCount), ] : <Widget>[]; final rasterHints = showRasterJankHints ? [ const Text('Raster Jank Detected'), const SizedBox(height: denseSpacing), if (saveLayerCount > 0) CanvasSaveLayerHint(saveLayerCount), const SizedBox(height: denseSpacing), if (frame.hasShaderTime) ShaderCompilationHint(shaderTime: frame.shaderDuration), const SizedBox(height: denseSpacing), const RasterStatsHint(), ] : <Widget>[]; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ...uiHints, if (showUiJankHints && showRasterJankHints) const SizedBox(height: defaultSpacing), ...rasterHints, ], ); } } class _Hint extends StatelessWidget { const _Hint({Key? key, required this.message}) : super(key: key); final Widget message; @override Widget build(BuildContext context) { return Row( children: [ Icon( Icons.lightbulb_outline, size: defaultIconSize, ), const SizedBox(width: denseSpacing), Expanded(child: message), ], ); } } @visibleForTesting class EnhanceTracingHint extends StatelessWidget { const EnhanceTracingHint({ Key? key, required this.longestPhase, required this.enhanceTracingState, required this.enhanceTracingController, }) : super(key: key); /// The longest [FramePhase] for the [FlutterFrame] this hint is for. final FramePhase longestPhase; /// The [EnhanceTracingState] that was active while drawing the [FlutterFrame] /// that this hint is for. final EnhanceTracingState? enhanceTracingState; final EnhanceTracingController enhanceTracingController; @override Widget build(BuildContext context) { final theme = Theme.of(context); return _Hint( message: RichText( maxLines: 2, text: TextSpan( text: '', children: [ TextSpan( text: longestPhase.title, style: theme.fixedFontStyle, ), TextSpan( text: ' was the longest UI phase in this frame. ', style: theme.regularTextStyle, ), ..._hintForPhase(longestPhase, theme), ], ), ), ); } List<InlineSpan> _hintForPhase( FramePhase phase, ThemeData theme, ) { final phaseType = phase.type; // TODO(kenz): when [enhanceTracingState] is not available, use heuristics // to detect whether tracing was enhanced for a frame (e.g. the depth or // quantity of child events under build / layout / paint). final tracingEnhanced = enhanceTracingState?.enhancedFor(phaseType) ?? false; switch (phaseType) { case FramePhaseType.build: return _enhanceTracingHint( settingTitle: extensions.profileWidgetBuilds.title, eventDescription: 'widget built', tracingEnhanced: tracingEnhanced, theme: theme, ); case FramePhaseType.layout: return _enhanceTracingHint( settingTitle: extensions.profileRenderObjectLayouts.title, eventDescription: 'render object laid out', tracingEnhanced: tracingEnhanced, theme: theme, ); case FramePhaseType.paint: return _enhanceTracingHint( settingTitle: extensions.profileRenderObjectPaints.title, eventDescription: 'render object painted', tracingEnhanced: tracingEnhanced, theme: theme, ); default: return []; } } List<InlineSpan> _enhanceTracingHint({ required String settingTitle, required String eventDescription, required bool tracingEnhanced, required ThemeData theme, }) { if (tracingEnhanced) { return [ TextSpan( text: 'Since "$settingTitle" was enabled while this frame was drawn, ' 'you should be able to see timeline events for each ' '$eventDescription.', style: theme.regularTextStyle, ), ]; } final enhanceTracingButton = WidgetSpan( alignment: PlaceholderAlignment.middle, child: Padding( padding: const EdgeInsets.symmetric(horizontal: denseSpacing), child: SmallEnhanceTracingButton( enhanceTracingController: enhanceTracingController, ), ), ); return [ TextSpan( text: 'Consider enabling "$settingTitle" from the ', style: theme.regularTextStyle, ), enhanceTracingButton, TextSpan( text: ' options above and reproducing the behavior in your app.', style: theme.regularTextStyle, ), ]; } } @visibleForTesting class SmallEnhanceTracingButton extends StatelessWidget { const SmallEnhanceTracingButton({ Key? key, required this.enhanceTracingController, }) : super(key: key); final EnhanceTracingController enhanceTracingController; @override Widget build(BuildContext context) { return GaDevToolsButton( label: EnhanceTracingButton.title, icon: EnhanceTracingButton.icon, gaScreen: gac.performance, gaSelection: gac.PerformanceEvents.enhanceTracingButtonSmall.name, onPressed: enhanceTracingController.showEnhancedTracingMenu, ); } } @visibleForTesting class IntrinsicOperationsHint extends StatelessWidget { const IntrinsicOperationsHint( this.intrinsicOperationsCount, { Key? key, }) : super(key: key); static const _intrinsicOperationsDocs = 'https://docs.flutter.dev/perf/best-practices#minimize-layout-passes-caused-by-intrinsic-operations'; final int intrinsicOperationsCount; @override Widget build(BuildContext context) { final theme = Theme.of(context); return _Hint( message: _ExpensiveOperationHint( docsUrl: _intrinsicOperationsDocs, gaScreenName: gac.performance, gaSelectedItemDescription: gac.PerformanceDocs.intrinsicOperationsDocs.name, message: TextSpan( children: [ TextSpan( text: 'Intrinsic', style: theme.fixedFontStyle, ), TextSpan( text: ' passes were performed $intrinsicOperationsCount ' '${pluralize('time', intrinsicOperationsCount)} during this ' 'frame.', style: theme.regularTextStyle, ), ], ), ), ); } } // TODO(kenz): if the 'profileRenderObjectPaints' service extension is disabled, // suggest that the user turn it on to get information about the render objects // that are calling saveLayer. If the event has render object information in the // args, display it in the hint. @visibleForTesting class CanvasSaveLayerHint extends StatelessWidget { const CanvasSaveLayerHint( this.saveLayerCount, { Key? key, }) : super(key: key); static const _saveLayerDocs = 'https://docs.flutter.dev/perf/best-practices#use-savelayer-thoughtfully'; final int saveLayerCount; @override Widget build(BuildContext context) { final theme = Theme.of(context); return _Hint( message: _ExpensiveOperationHint( docsUrl: _saveLayerDocs, gaScreenName: gac.performance, gaSelectedItemDescription: gac.PerformanceDocs.canvasSaveLayerDocs.name, message: TextSpan( children: [ TextSpan( text: 'Canvas.saveLayer()', style: theme.fixedFontStyle, ), TextSpan( text: ' was called $saveLayerCount ' '${pluralize('time', saveLayerCount)} during this frame.', style: theme.regularTextStyle, ), ], ), ), ); } } @visibleForTesting class ShaderCompilationHint extends StatelessWidget { const ShaderCompilationHint({ Key? key, required this.shaderTime, }) : super(key: key); final Duration shaderTime; @override Widget build(BuildContext context) { final theme = Theme.of(context); return _Hint( message: _ExpensiveOperationHint( docsUrl: preCompileShadersDocsUrl, gaScreenName: gac.performance, gaSelectedItemDescription: gac.PerformanceDocs.shaderCompilationDocs.name, message: TextSpan( children: [ TextSpan( text: durationText( shaderTime, unit: DurationDisplayUnit.milliseconds, ), style: theme.fixedFontStyle, ), TextSpan( text: ' of shader compilation occurred during this frame.', style: theme.regularTextStyle, ), ], ), childrenSpans: serviceConnection.serviceManager.connectedApp!.isIosApp ? [ TextSpan( text: ' Note: pre-compiling shaders is a legacy solution with many ' 'pitfalls. Try ', style: theme.regularTextStyle, ), LinkTextSpan( link: Link( display: 'Impeller', url: impellerDocsUrl, gaScreenName: gac.performance, gaSelectedItemDescription: gac.PerformanceDocs.impellerDocsLink.name, ), context: context, ), TextSpan( text: ' instead!', style: theme.regularTextStyle, ), ] : [], ), ); } } @visibleForTesting class RasterStatsHint extends StatelessWidget { const RasterStatsHint({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final theme = Theme.of(context); return _Hint( message: RichText( text: TextSpan( children: [ TextSpan( text: 'Consider using the', style: theme.regularTextStyle, ), TextSpan( text: ' Raster Stats ', style: theme.subtleFixedFontStyle, ), TextSpan( text: 'tab to identify rendering layers that are expensive to ' 'rasterize.', style: theme.regularTextStyle, ), ], ), ), ); } } class _ExpensiveOperationHint extends StatelessWidget { const _ExpensiveOperationHint({ Key? key, required this.message, required this.docsUrl, required this.gaScreenName, required this.gaSelectedItemDescription, this.childrenSpans = const <TextSpan>[], }) : super(key: key); final TextSpan message; final String docsUrl; final String gaScreenName; final String gaSelectedItemDescription; final List<TextSpan> childrenSpans; @override Widget build(BuildContext context) { final theme = Theme.of(context); return RichText( text: TextSpan( children: [ message, TextSpan( text: ' This may ', style: theme.regularTextStyle, ), LinkTextSpan( context: context, link: Link( display: 'negatively affect your app\'s performance', url: docsUrl, gaScreenName: gaScreenName, gaSelectedItemDescription: 'frameAnalysis_$gaSelectedItemDescription', ), ), TextSpan( text: '.', style: theme.regularTextStyle, ), ...childrenSpans, ], ), ); } }
devtools/packages/devtools_app/lib/src/screens/performance/panes/frame_analysis/frame_hints.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/frame_analysis/frame_hints.dart", "repo_id": "devtools", "token_count": 6175 }
104
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../../../shared/globals.dart'; import '../../../../shared/http/http_service.dart' as http_service; import 'perfetto/perfetto.dart'; import 'timeline_events_controller.dart'; class TimelineEventsTabView extends StatelessWidget { const TimelineEventsTabView({super.key, required this.controller}); final TimelineEventsController controller; @override Widget build(BuildContext context) { return KeepAliveWrapper( child: EmbeddedPerfetto( perfettoController: controller.perfettoController, ), ); } } class TimelineEventsTabControls extends StatelessWidget { const TimelineEventsTabControls({super.key, required this.controller}); final TimelineEventsController controller; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Padding( padding: const EdgeInsets.only(right: densePadding), child: PerfettoHelpButton( perfettoController: controller.perfettoController, ), ), if (!offlineController.offlineMode.value) ...[ // TODO(kenz): add a switch to enable the CPU profiler once the // tracing format supports it (when we switch to protozero). const SizedBox(width: densePadding), TimelineSettingsButton(controller: controller), const SizedBox(width: densePadding), RefreshTimelineEventsButton(controller: controller), ], ], ); } } class TimelineSettingsButton extends StatelessWidget { const TimelineSettingsButton({required this.controller, super.key}); final TimelineEventsController controller; @override Widget build(BuildContext context) { return GaDevToolsButton.iconOnly( icon: Icons.settings_outlined, outlined: false, tooltip: 'Timeline settings', gaScreen: gac.performance, gaSelection: gac.PerformanceEvents.timelineSettings.name, onPressed: () => _openTimelineSettingsDialog(context), ); } void _openTimelineSettingsDialog(BuildContext context) { unawaited( showDialog( context: context, builder: (context) => const TimelineSettingsDialog(), ), ); } } class RefreshTimelineEventsButton extends StatelessWidget { const RefreshTimelineEventsButton({required this.controller, super.key}); final TimelineEventsController controller; @override Widget build(BuildContext context) { return ValueListenableBuilder<EventsControllerStatus>( valueListenable: controller.status, builder: (context, status, _) { return RefreshButton( iconOnly: true, outlined: false, onPressed: status == EventsControllerStatus.processing ? null : controller.forceRefresh, tooltip: 'Refresh timeline events', gaScreen: gac.performance, gaSelection: gac.PerformanceEvents.refreshTimelineEvents.name, ); }, ); } } class TimelineSettingsDialog extends StatefulWidget { const TimelineSettingsDialog({super.key}); @override State<TimelineSettingsDialog> createState() => _TimelineSettingsDialogState(); } class _TimelineSettingsDialogState extends State<TimelineSettingsDialog> with AutoDisposeMixin { late final ValueNotifier<bool?> _httpLogging; @override void initState() { super.initState(); // Mirror the value of [http_service.httpLoggingState] in the [_httpLogging] // notifier so that we can use [_httpLogging] for the [CheckboxSetting] // widget below. _httpLogging = ValueNotifier<bool>(http_service.httpLoggingEnabled); addAutoDisposeListener(http_service.httpLoggingState, () { _httpLogging.value = http_service.httpLoggingState.value.enabled; }); } @override void dispose() { cancelListeners(); _httpLogging.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); return DevToolsDialog( title: const DialogTitleText('Timeline Settings'), includeDivider: false, content: SizedBox( width: defaultDialogWidth, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ ..._defaultRecordedStreams(theme), const SizedBox(height: denseSpacing), ..._advancedStreams(theme), ], ), ), actions: const [ DialogCloseButton(), ], ); } List<Widget> _defaultRecordedStreams(ThemeData theme) { return [ ...dialogSubHeader(theme, 'General'), CheckboxSetting( notifier: preferences.performance.includeCpuSamplesInTimeline, title: 'Include CPU samples in the timeline', description: 'This may negatively affect performance.', ), const SizedBox(height: defaultSpacing), ...dialogSubHeader(theme, 'Trace categories'), RichText( text: TextSpan( text: 'Default', style: theme.subtleTextStyle, ), ), ..._timelineStreams(advanced: false), // Special case "Network Traffic" because it is not implemented as a // Timeline recorded stream in the VM. The user does not need to be aware of // the distinction, however. CheckboxSetting( title: 'Network', description: 'Http traffic', notifier: _httpLogging, onChanged: (value) => unawaited( http_service.toggleHttpRequestLogging(value ?? false), ), ), ]; } List<Widget> _advancedStreams(ThemeData theme) { return [ RichText( text: TextSpan( text: 'Advanced', style: theme.subtleTextStyle, ), ), ..._timelineStreams(advanced: true), ]; } List<Widget> _timelineStreams({ required bool advanced, }) { final streams = advanced ? serviceConnection.timelineStreamManager.advancedStreams : serviceConnection.timelineStreamManager.basicStreams; final settings = streams .map( (stream) => CheckboxSetting( title: stream.name, description: stream.description, notifier: stream.recorded as ValueNotifier<bool?>, onChanged: (newValue) => unawaited( serviceConnection.timelineStreamManager.updateTimelineStream( stream, newValue ?? false, ), ), ), ) .toList(); return settings; } }
devtools/packages/devtools_app/lib/src/screens/performance/panes/timeline_events/timeline_events_view.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/timeline_events/timeline_events_view.dart", "repo_id": "devtools", "token_count": 2693 }
105
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:developer'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../../../shared/common_widgets.dart'; import '../../../../shared/globals.dart'; import '../../../../shared/ui/filter.dart'; import '../../cpu_profile_model.dart'; import '../../cpu_profiler_controller.dart'; import '../../profiler_screen_controller.dart'; final profilerScreenSearchFieldKey = GlobalKey(debugLabel: 'ProfilerScreenSearchFieldKey'); class CpuProfileFilterDialog extends StatelessWidget { const CpuProfileFilterDialog({required this.controller, Key? key}) : super(key: key); static const filterQueryInstructions = ''' Type a filter query to show or hide specific stack frames. Any text that is not paired with an available filter key below will be queried against all categories (method, uri). Available filters: 'uri', 'u' (e.g. 'uri:my_dart_package/some_lib.dart', '-u:some_lib_to_hide') Example queries: 'someMethodName uri:my_dart_package,b_dart_package' '.toString -uri:flutter' '''; final CpuProfilerController controller; @override Widget build(BuildContext context) { return FilterDialog<CpuStackFrame>( controller: controller, queryInstructions: filterQueryInstructions, ); } } /// DropdownButton that controls the value of /// [ProfilerScreenController.userTagFilter]. class UserTagDropdown extends StatelessWidget { const UserTagDropdown(this.controller, {super.key}); final CpuProfilerController controller; @override Widget build(BuildContext context) { const filterByTag = 'Filter by tag:'; return ValueListenableBuilder<String>( valueListenable: controller.userTagFilter, builder: (context, userTag, _) { final userTags = controller.userTags; final tooltip = userTags.isNotEmpty ? 'Filter the CPU profile by the given UserTag' : 'No UserTags found for this CPU profile'; return SizedBox( height: defaultButtonHeight, child: DevToolsTooltip( message: tooltip, child: ValueListenableBuilder<bool>( valueListenable: preferences.vmDeveloperModeEnabled, builder: (context, vmDeveloperModeEnabled, _) { return RoundedDropDownButton<String>( isDense: true, value: userTag, items: [ _buildMenuItem( display: '$filterByTag ${CpuProfilerController.userTagNone}', value: CpuProfilerController.userTagNone, ), // We don't want to show the 'Default' tag if it is the only // tag available. The 'none' tag above is equivalent in this // case. if (!(userTags.length == 1 && userTags.first == UserTag.defaultTag.label)) ...[ for (final tag in userTags) _buildMenuItem( display: '$filterByTag $tag', value: tag, ), _buildMenuItem( display: 'Group by: User Tag', value: CpuProfilerController.groupByUserTag, ), ], if (vmDeveloperModeEnabled) _buildMenuItem( display: 'Group by: VM Tag', value: CpuProfilerController.groupByVmTag, ), ], onChanged: userTags.isEmpty || (userTags.length == 1 && userTags.first == UserTag.defaultTag.label) ? null : (String? tag) => _onUserTagChanged(tag!), ); }, ), ), ); }, ); } DropdownMenuItem<String> _buildMenuItem({ required String display, required String value, }) { return DropdownMenuItem<String>( value: value, child: Text(display), ); } void _onUserTagChanged(String newTag) async { try { await controller.loadDataWithTag(newTag); } catch (e) { notificationService.push(e.toString()); } } } /// DropdownButton that controls the value of /// [ProfilerScreenController.viewType]. class ModeDropdown extends StatelessWidget { const ModeDropdown(this.controller, {super.key}); final CpuProfilerController controller; @override Widget build(BuildContext context) { const mode = 'View:'; return ValueListenableBuilder<CpuProfilerViewType>( valueListenable: controller.viewType, builder: (context, viewType, _) { final tooltip = viewType == CpuProfilerViewType.function ? 'Display the profile in terms of the Dart call stack ' '(i.e., inlined frames are expanded)' : 'Display the profile in terms of native stack frames ' '(i.e., inlined frames are not expanded, display code objects ' 'rather than individual functions)'; return SizedBox( height: defaultButtonHeight, child: DevToolsTooltip( message: tooltip, child: RoundedDropDownButton<CpuProfilerViewType>( isDense: true, value: viewType, items: [ _buildMenuItem( display: '$mode ${CpuProfilerViewType.function}', value: CpuProfilerViewType.function, ), _buildMenuItem( display: '$mode ${CpuProfilerViewType.code}', value: CpuProfilerViewType.code, ), ], onChanged: (type) => controller.updateViewForType(type!), ), ), ); }, ); } DropdownMenuItem<CpuProfilerViewType> _buildMenuItem({ required String display, required CpuProfilerViewType value, }) { return DropdownMenuItem<CpuProfilerViewType>( value: value, child: Text(display), ); } }
devtools/packages/devtools_app/lib/src/screens/profiler/panes/controls/cpu_profiler_controls.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/profiler/panes/controls/cpu_profiler_controls.dart", "repo_id": "devtools", "token_count": 2904 }
106
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(rrousselGit) merge this code with the debugger view import 'dart:async'; import 'dart:math' as math; import 'package:devtools_app_shared/service.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../shared/diagnostics_text_styles.dart'; import '../sliver_iterable_child_delegate.dart'; import 'instance_details.dart'; import 'instance_providers.dart'; const typeColor = Color.fromARGB(255, 78, 201, 176); const boolColor = Color.fromARGB(255, 86, 156, 214); const nullColor = boolColor; const numColor = Color.fromARGB(255, 181, 206, 168); const stringColor = Color.fromARGB(255, 206, 145, 120); const double rowHeight = 20.0; final isExpandedProvider = StateProviderFamily<bool, InstancePath>((ref, path) { // expands the root by default, but not children return path.pathToProperty.isEmpty; }); final estimatedChildCountProvider = AutoDisposeProviderFamily<int, InstancePath>((ref, rootPath) { int estimatedChildCount(InstancePath path) { int one(InstanceDetails _) => 1; int expandableEstimatedChildCount(Iterable<PathToProperty> keys) { if (!ref.watch(isExpandedProvider(path))) { return 1; } return keys.fold(1, (acc, element) { return acc + estimatedChildCount( path.pathForChild(element), ); }); } return ref.watch(instanceProvider(path)).when( loading: () => 1, error: (err, stack) => 1, data: (instance) { return instance.map( nill: one, boolean: one, number: one, string: one, enumeration: one, map: (instance) { return expandableEstimatedChildCount( instance.keys.map( (key) => PathToProperty.mapKey(ref: key.instanceRefId), ), ); }, list: (instance) { return expandableEstimatedChildCount( List.generate(instance.length, $PathToProperty.listIndex), ); }, object: (instance) { return expandableEstimatedChildCount( instance.fields.map( (field) => PathToProperty.fromObjectField(field), ), ); }, ); }, ); } return estimatedChildCount(rootPath); }); void showErrorSnackBar(BuildContext context, Object error) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error: $error')), ); } class InstanceViewer extends ConsumerStatefulWidget { const InstanceViewer({ Key? key, required this.rootPath, required this.showInternalProperties, }) : super(key: key); final InstancePath rootPath; final bool showInternalProperties; @override ConsumerState<ConsumerStatefulWidget> createState() => _InstanceViewerState(); } class _InstanceViewerState extends ConsumerState<InstanceViewer> { final scrollController = ScrollController(); @override void dispose() { scrollController.dispose(); super.dispose(); } Iterable<Widget> _buildError( Object error, StackTrace? _, InstancePath __, ) { if (error is SentinelException) { final valueAsString = error.sentinel.valueAsString; if (valueAsString != null) return [Text(valueAsString)]; } return const [Text('<unknown error>')]; } Iterable<Widget?> _buildListViewItems( BuildContext context, WidgetRef ref, { required InstancePath path, bool disableExpand = false, }) { return ref.watch(instanceProvider(path)).when( loading: () => const [Text('loading...')], error: (err, stack) => _buildError(err, stack, path), data: (instance) sync* { final isExpanded = ref.watch(isExpandedProvider(path).state); yield _buildHeader( instance, path: path, isExpanded: isExpanded, disableExpand: disableExpand, ); if (isExpanded.state) { yield* instance.maybeMap( object: (instance) => _buildObjectItem( context, ref, instance, path: path, ), list: (list) => _buildListItem( context, ref, list, path: path, ), map: (map) => _buildMapItem( context, ref, map, path: path, ), // Reaches when the root of the instance tree is a string/numbers/bool/.... orElse: () => const [], ); } }, ); } Widget _buildHeader( InstanceDetails instance, { required InstancePath path, StateController<bool>? isExpanded, bool disableExpand = false, }) { return _Expandable( key: ValueKey(path), isExpandable: !disableExpand && instance.isExpandable, isExpanded: isExpanded, title: instance.map( enumeration: (instance) => _EditableField( setter: instance.setter, initialEditString: '${instance.type}.${instance.value}', child: Text.rich( TextSpan( children: [ TextSpan( text: instance.type, style: const TextStyle(color: typeColor), ), TextSpan(text: '.${instance.value}'), ], ), ), ), nill: (instance) => _EditableField( setter: instance.setter, initialEditString: 'null', child: const Text('null', style: TextStyle(color: nullColor)), ), string: (instance) => _EditableField( setter: instance.setter, initialEditString: '"${instance.displayString}"', child: Text.rich( TextSpan( children: [ const TextSpan(text: '"'), TextSpan( text: instance.displayString, style: const TextStyle(color: stringColor), ), const TextSpan(text: '"'), ], ), ), ), number: (instance) => _EditableField( setter: instance.setter, initialEditString: instance.displayString, child: Text( instance.displayString, style: const TextStyle(color: numColor), ), ), boolean: (instance) => _EditableField( setter: instance.setter, initialEditString: instance.displayString, child: Text( instance.displayString, style: const TextStyle(color: boolColor), ), ), map: (instance) => _ObjectHeader( startToken: '{', endToken: '}', hash: instance.hash, meta: instance.keys.isEmpty ? null : '${instance.keys.length} ${pluralize('element', instance.keys.length)}', ), list: (instance) => _ObjectHeader( startToken: '[', endToken: ']', hash: instance.hash, meta: instance.length == 0 ? null : '${instance.length} ${pluralize('element', instance.length)}', ), object: (instance) => _ObjectHeader( type: instance.type, hash: instance.hash, startToken: '', endToken: '', // Never show the number of elements when using custom objects meta: null, ), ), ); } Iterable<Widget> _buildMapItem( BuildContext context, WidgetRef ref, MapInstance instance, { required InstancePath path, }) sync* { for (final key in instance.keys) { final value = _buildListViewItems( context, ref, path: path.pathForChild(PathToProperty.mapKey(ref: key.instanceRefId)), ); final keyHeader = _buildHeader(key, disableExpand: true, path: path); var isFirstItem = true; for (final child in value) { yield child != null ? Padding( padding: const EdgeInsets.only(left: defaultSpacing), child: isFirstItem ? Row( children: [ keyHeader, const Text(': '), Expanded(child: child), ], ) : child, ) : const SizedBox(); isFirstItem = false; } assert( !isFirstItem, 'Bad state: the value of $key did not render any widget', ); } } Iterable<Widget> _buildListItem( BuildContext context, WidgetRef ref, ListInstance instance, { required InstancePath path, }) sync* { for (var index = 0; index < instance.length; index++) { final children = _buildListViewItems( context, ref, path: path.pathForChild(PathToProperty.listIndex(index)), ); bool isFirst = true; for (final child in children) { Widget? rowItem = child; // Add the item index only on the first line of the element if (isFirst && rowItem != null) { isFirst = false; rowItem = Row( children: [ Text('[$index]: '), Expanded(child: rowItem), ], ); } yield rowItem != null ? Padding( padding: const EdgeInsets.only(left: defaultSpacing), child: rowItem, ) : const SizedBox(); } } } Iterable<Widget> _buildObjectItem( BuildContext context, WidgetRef ref, ObjectInstance instance, { required InstancePath path, }) sync* { for (final field in instance.fields) { if (!widget.showInternalProperties && field.isDefinedByDependency && field.isPrivate) { // Hide private properties from classes defined by dependencies continue; } final children = _buildListViewItems( context, ref, path: path.pathForChild(PathToProperty.fromObjectField(field)), ); bool isFirst = true; for (final child in children) { Widget? rowItem = child; if (isFirst && rowItem != null) { isFirst = false; rowItem = Row( children: [ if (field.isFinal) Text( 'final ', style: DiagnosticsTextStyles.unimportant( Theme.of(context).colorScheme, ), ), Text('${field.name}: '), Expanded(child: rowItem), ], ); } yield rowItem != null ? Padding( padding: const EdgeInsets.only(left: defaultSpacing), child: rowItem, ) : const SizedBox(); } } } @override Widget build(BuildContext context) { return Scrollbar( thumbVisibility: true, controller: scrollController, child: ListView.custom( controller: scrollController, // TODO: item height should be based on font size itemExtent: rowHeight, padding: const EdgeInsets.symmetric( vertical: denseSpacing, horizontal: defaultSpacing, ), childrenDelegate: SliverIterableChildDelegate( _buildListViewItems( context, ref, path: widget.rootPath, disableExpand: true, ).cast<Widget?>(), // This cast is necessary to avoid Null type errors estimatedChildCount: ref.watch(estimatedChildCountProvider(widget.rootPath)), ), ), ); } } class _ObjectHeader extends StatelessWidget { const _ObjectHeader({ Key? key, this.type, required this.hash, required this.meta, required this.startToken, required this.endToken, }) : super(key: key); final String? type; final int hash; final String? meta; final String startToken; final String endToken; @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; return Text.rich( TextSpan( children: [ if (type != null) TextSpan( text: type, style: const TextStyle(color: typeColor), ), TextSpan( text: '#${shortHash(hash)}', style: DiagnosticsTextStyles.unimportant(colorScheme), ), TextSpan(text: startToken), if (meta != null) TextSpan(text: meta), TextSpan(text: endToken), ], ), ); } } class _EditableField extends StatefulWidget { const _EditableField({ Key? key, required this.setter, required this.child, required this.initialEditString, }) : super(key: key); final Widget child; final String initialEditString; final Future<void> Function(String)? setter; @override _EditableFieldState createState() => _EditableFieldState(); } class _EditableFieldState extends State<_EditableField> { final controller = TextEditingController(); final focusNode = FocusNode(debugLabel: 'editable-field'); final textFieldFocusNode = FocusNode(debugLabel: 'text-field'); var isHovering = false; final _isAlive = Disposable(); @override void dispose() { _isAlive.dispose(); controller.dispose(); focusNode.dispose(); textFieldFocusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (widget.setter == null) return widget.child; final colorScheme = Theme.of(context).colorScheme; final editingChild = TextField( autofocus: true, controller: controller, focusNode: textFieldFocusNode, onSubmitted: (value) async { try { final setter = widget.setter; if (setter != null) await setter(value); } catch (err) { if (!context.mounted) return; showErrorSnackBar(context, err); } }, decoration: InputDecoration( contentPadding: const EdgeInsets.all(densePadding), isDense: true, border: OutlineInputBorder( borderRadius: const BorderRadius.all(Radius.circular(5)), borderSide: BorderSide(color: colorScheme.surface), ), ), ); final displayChild = Stack( clipBehavior: Clip.none, children: [ if (isHovering) Positioned( bottom: -5, left: -5, top: -5, right: -5, child: DecoratedBox( decoration: BoxDecoration( borderRadius: defaultBorderRadius, border: Border.all(color: colorScheme.surface), ), ), ), GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { focusNode.requestFocus(); textFieldFocusNode.requestFocus(); controller.text = widget.initialEditString; controller.selection = TextSelection( baseOffset: 0, extentOffset: widget.initialEditString.length, ); }, child: Align( alignment: Alignment.centerLeft, heightFactor: 1, child: widget.child, ), ), ], ); return AnimatedBuilder( animation: focusNode, builder: (context, _) { final isEditing = focusNode.hasFocus; return Focus( focusNode: focusNode, onKeyEvent: (node, key) { if (key.physicalKey == PhysicalKeyboardKey.escape) { focusNode.unfocus(); return KeyEventResult.handled; } return KeyEventResult.ignored; }, child: MouseRegion( onEnter: (_) => setState(() => isHovering = true), onExit: (_) => setState(() => isHovering = false), // use a Stack to show the borders, to avoid the UI "moving" when hovering child: isEditing ? editingChild : displayChild, ), ); }, ); } } class _Expandable extends StatelessWidget { const _Expandable({ Key? key, required this.isExpanded, required this.isExpandable, required this.title, }) : super(key: key); final StateController<bool>? isExpanded; final bool isExpandable; final Widget title; @override Widget build(BuildContext context) { if (!isExpandable) { return Align( alignment: Alignment.centerLeft, child: title, ); } final isExpanded = this.isExpanded!; return GestureDetector( onTap: () => isExpanded.state = !isExpanded.state, behavior: HitTestBehavior.opaque, child: Row( children: [ TweenAnimationBuilder<double>( tween: Tween(end: isExpanded.state ? 0 : -math.pi / 2), duration: defaultDuration, builder: (context, angle, _) { return Transform.rotate( angle: angle, child: Icon( Icons.expand_more, size: defaultIconSize, ), ); }, ), title, ], ), ); } }
devtools/packages/devtools_app/lib/src/screens/provider/instance_viewer/instance_viewer.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/provider/instance_viewer/instance_viewer.dart", "repo_id": "devtools", "token_count": 8594 }
107
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import '../../../shared/globals.dart'; import '../vm_service_private_extensions.dart'; class ObjectStoreController extends DisposableController with AutoDisposeControllerMixin { ValueListenable<ObjectStore?> get selectedIsolateObjectStore => _selectedIsolateObjectStore; final _selectedIsolateObjectStore = ValueNotifier<ObjectStore?>(null); Future<void> refresh() async { final service = serviceConnection.serviceManager.service!; final isolate = serviceConnection.serviceManager.isolateManager.selectedIsolate.value; if (isolate == null) { return; } _selectedIsolateObjectStore.value = null; _selectedIsolateObjectStore.value = await service.getObjectStore(isolate.id!); } }
devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/object_store_controller.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/object_store_controller.dart", "repo_id": "devtools", "token_count": 313 }
108
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:vm_service/vm_service.dart' hide VmService; import '../../../service/vm_service_wrapper.dart'; import '../../../shared/charts/treemap.dart'; import '../../../shared/globals.dart'; /// Stores process memory usage state for the [VMProcessMemoryView]. class VMProcessMemoryViewController extends DisposableController { VMProcessMemoryViewController() { unawaited(refresh()); } /// Fetches the most up-to-date process memory information. Future<void> refresh() async { final processMemoryUsage = await _service.getProcessMemoryUsage(); TreemapNode processNode(ProcessMemoryItem memoryItem) { final node = TreemapNode( name: memoryItem.name!, byteSize: memoryItem.size!, caption: memoryItem.description, ); for (final child in memoryItem.children ?? const <ProcessMemoryItem>[]) { node.addChild(processNode(child)); } return node; } final currentRoot = processNode(processMemoryUsage.root!); // Insert a synthetic node for memory that isn't accounted for by the VM. // This value includes memory allocated through malloc and other mechanisms // that aren't explicitly tracked by the VM. currentRoot.addChild( TreemapNode( name: 'Other', byteSize: currentRoot.byteSize - currentRoot.children.fold<int>( 0, (sum, e) => sum + e.byteSize, ), ), ); // Expand the tree by default since the tree should be relatively small. currentRoot.expandCascading(); _treeRoot.value = currentRoot; _treeMapRoot.value = currentRoot; } VmServiceWrapper get _service => serviceConnection.serviceManager.service!; /// The root of the process memory tree, used by the tree view. ValueListenable<TreemapNode?> get treeRoot => _treeRoot; final _treeRoot = ValueNotifier<TreemapNode?>(null); /// The current root of the process memory tree being used by the tree map /// viewer. ValueListenable<TreemapNode?> get treeMapRoot => _treeMapRoot; final _treeMapRoot = ValueNotifier<TreemapNode?>(null); /// Called when a user interacts with the tree map viewer that results in the /// displayed root of the tree map being updated. void setTreeMapRoot(TreemapNode? newRoot) { _treeMapRoot.value = newRoot; } /// Expands all the entries in the tree viewer. void expandTree() { _treeRoot.value?.expandCascading(); } /// Collapses all the entries in the tree viewer. void collapseTree() { _treeRoot.value?.collapseCascading(); } }
devtools/packages/devtools_app/lib/src/screens/vm_developer/process_memory/process_memory_view_controller.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/process_memory/process_memory_view_controller.dart", "repo_id": "devtools", "token_count": 951 }
109
This folder contains code shared between screens. For clarity of contracts, it is preferred that code in this folder does not depend on any `devtools_app` code outside this folder. Code, that is not used by any screen, should go to the folder `framework`.
devtools/packages/devtools_app/lib/src/shared/README.md/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/README.md", "repo_id": "devtools", "token_count": 61 }
110
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: non_constant_identifier_names @JS() library; import 'package:flutter/foundation.dart'; import 'package:js/js.dart'; import '../../shared/development_helpers.dart'; import 'analytics.dart' as ga; /// For gtags API see https://developers.google.com/gtagjs/reference/api /// For debugging install the Chrome Plugin "Google Analytics Debugger". @JS('gtag') external void _gTagCommandName(String command, String name, [Object? params]); // TODO(jacobr): refactor this code if we do not migrate off gtags. // ignore: avoid_classes_with_only_static_members class GTag { static const String _event = 'event'; static const String _exception = 'exception'; /// Collect the analytic's event and its parameters. static void event( String eventName, { required GtagEvent Function() gaEventProvider, }) async { if (debugAnalytics || (kReleaseMode && await ga.isAnalyticsEnabled())) { _gTagCommandName(_event, eventName, gaEventProvider()); } } static void exception({ required GtagException Function() gaExceptionProvider, }) async { if (debugAnalytics || (kReleaseMode && await ga.isAnalyticsEnabled())) { _gTagCommandName(_event, _exception, gaExceptionProvider()); } } } @JS() @anonymous class GtagEvent { external factory GtagEvent({ String? event_category, String? event_label, // Event e.g., gaScreenViewEvent, gaSelectEvent, etc. String? send_to, // UA ID of target GA property to receive event data. int value = 0, bool non_interaction = false, Object? custom_map, }); external String? get event_category; external String? get event_label; external String? get send_to; external int get value; // Positive number. external bool get non_interaction; external Object? get custom_map; // Custom metrics } @JS() @anonymous class GtagException { external factory GtagException({ String? description, bool fatal = false, }); external String? get description; // Description of the error. external bool get fatal; // Fatal error. }
devtools/packages/devtools_app/lib/src/shared/analytics/gtags.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/analytics/gtags.dart", "repo_id": "devtools", "token_count": 688 }
111
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:web/web.dart'; import '../../globals.dart'; import '../../primitives/utils.dart'; import 'drag_and_drop.dart'; DragAndDropManagerWeb createDragAndDropManager(int viewId) { return DragAndDropManagerWeb(viewId); } class DragAndDropManagerWeb extends DragAndDropManager { DragAndDropManagerWeb(int viewId) : super.impl(viewId); late final StreamSubscription<MouseEvent> onDragOverSubscription; late final StreamSubscription<MouseEvent> onDropSubscription; late final StreamSubscription<MouseEvent> onDragLeaveSubscription; @override void init() { onDragOverSubscription = document.body!.onDragOver.listen(_onDragOver); onDragLeaveSubscription = document.body!.onDragLeave.listen(_onDragLeave); onDropSubscription = document.body!.onDrop.listen(_onDrop); } @override void dispose() { unawaited(onDragOverSubscription.cancel()); unawaited(onDragLeaveSubscription.cancel()); unawaited(onDropSubscription.cancel()); super.dispose(); } void _onDragOver(MouseEvent event) { dragOver(event.offsetX as double, event.offsetY as double); // This is necessary to allow us to drop. event.preventDefault(); (event as DragEvent).dataTransfer!.dropEffect = 'move'; } void _onDragLeave(MouseEvent _) { dragLeave(); } void _onDrop(MouseEvent event) async { drop(); // Stop the browser from redirecting. event.preventDefault(); // If there is no active state or the active state does not have a drop // handler, return early. if (activeState?.widget.handleDrop == null) return; final FileList files = (event as DragEvent).dataTransfer!.files; if (files.length > 1) { notificationService.push('You cannot import more than one file.'); return; } final droppedFile = files.item(0); if (droppedFile?.type != 'application/json') { notificationService.push( '${droppedFile?.type} is not a supported file type. Please import ' 'a .json file that was exported from Dart DevTools.', ); return; } final FileReader reader = FileReader(); (reader as Element).onLoad.listen((event) { try { final Object json = jsonDecode(reader.result as String); final devToolsJsonFile = DevToolsJsonFile( name: droppedFile!.name, lastModifiedTime: DateTime.fromMillisecondsSinceEpoch( droppedFile.lastModified, isUtc: true, ), data: json, ); activeState!.widget.handleDrop!(devToolsJsonFile); } on FormatException catch (e) { notificationService.push( 'JSON syntax error in imported file: "$e". Please make sure the ' 'imported file is a Dart DevTools file, and check that it has not ' 'been modified.', ); return; } }); try { reader.readAsText(droppedFile!); } catch (e) { notificationService.push('Could not import file: $e'); } } }
devtools/packages/devtools_app/lib/src/shared/config_specific/drag_and_drop/_drag_and_drop_web.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/drag_and_drop/_drag_and_drop_web.dart", "repo_id": "devtools", "token_count": 1163 }
112
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. import 'package:url_launcher/url_launcher.dart' as url_launcher; import '../../globals.dart'; import '_launch_url_desktop.dart' if (dart.library.js_interop) '_launch_url_web.dart'; Future<void> launchUrl(String url) async { final parsedUrl = Uri.tryParse(url); try { if (parsedUrl != null && await url_launcher.canLaunchUrl(parsedUrl)) { await url_launcher.launchUrl(parsedUrl); } else { notificationService.push('Unable to open $url.'); } } finally { // Always pass the request up to VS Code because we could fail both silently // (the usual behaviour) or with another error like // "Attempted to call Window.open with a null window" // https://github.com/flutter/devtools/issues/6105. // // In the case where we are not in VS Code, there will be nobody listening // to the postMessage this sends. launchUrlVSCode(url); } }
devtools/packages/devtools_app/lib/src/shared/config_specific/launch_url/launch_url.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/launch_url/launch_url.dart", "repo_id": "devtools", "token_count": 365 }
113
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../common_widgets.dart'; import '../primitives/utils.dart'; import 'console_service.dart'; import 'widgets/expandable_variable.dart'; // TODO(devoncarew): Allow scrolling horizontally as well. // TODO(devoncarew): Support hyperlinking to stack traces. /// Renders a Console widget with output [lines] and an optional [title] and /// [footer]. class Console extends StatelessWidget { const Console({ super.key, required this.lines, this.title, this.footer, }); final Widget? title; final Widget? footer; final ValueListenable<List<ConsoleLine>> lines; @override Widget build(BuildContext context) { return ConsoleFrame( title: title, child: _ConsoleOutput(lines: lines, footer: footer), ); } } class ConsoleFrame extends StatelessWidget { const ConsoleFrame({ super.key, required this.child, this.title, }); final Widget? title; final Widget child; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(bottom: densePadding), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (title != null) title!, Expanded( child: child, ), ], ), ); } } /// Renders a widget with the output of the console. /// /// This is a ListView of text lines, with a monospace font and a border. class _ConsoleOutput extends StatefulWidget { const _ConsoleOutput({ Key? key, required this.lines, this.footer, }) : super(key: key); final ValueListenable<List<ConsoleLine>> lines; final Widget? footer; @override _ConsoleOutputState createState() => _ConsoleOutputState(); } class _ConsoleOutputState extends State<_ConsoleOutput> with AutoDisposeMixin<_ConsoleOutput> { // The scroll controller must survive ConsoleOutput re-renders // to work as intended, so it must be part of the "state". final ScrollController _scroll = ScrollController(); static const _scrollBarKey = Key('console-scrollbar'); List<ConsoleLine> _currentLines = const []; bool _scrollToBottom = true; bool _considerScrollAtBottom = true; double _lastScrollOffset = 0.0; @override void initState() { super.initState(); _initHelper(); } void _onScrollChanged() { // Detect if the user has scrolled up and stop scrolling to the bottom if // they have scrolled up. if (_scroll.hasClients) { if (_scroll.atScrollBottom) { _considerScrollAtBottom = true; } else if (_lastScrollOffset > _scroll.offset) { _considerScrollAtBottom = false; } _lastScrollOffset = _scroll.offset; } } // Whenever the widget updates, refresh the scroll position if needed. @override void didUpdateWidget(_ConsoleOutput oldWidget) { if (oldWidget.lines != widget.lines) { _initHelper(); } super.didUpdateWidget(oldWidget); } void _initHelper() { cancelListeners(); addAutoDisposeListener(widget.lines, _onConsoleLinesChanged); addAutoDisposeListener(_scroll, _onScrollChanged); _onConsoleLinesChanged(); } void _onConsoleLinesChanged() { final nextLines = widget.lines.value; if (nextLines == _currentLines) return; var forceScrollIntoView = false; for (int i = _currentLines.length; i < nextLines.length; i++) { if (nextLines[i].forceScrollIntoView) { forceScrollIntoView = true; break; } } setState(() { _currentLines = nextLines; }); if (forceScrollIntoView || _considerScrollAtBottom || (_scroll.hasClients && _scroll.atScrollBottom)) { _scrollToBottom = true; } } @override Widget build(BuildContext context) { final theme = Theme.of(context); if (_scrollToBottom) { _scrollToBottom = false; WidgetsBinding.instance.addPostFrameCallback((timeStamp) { if (_scroll.hasClients) { unawaited(_scroll.autoScrollToBottom()); } else { // Set back to true to retry scrolling when we are back in view. // We expected to be in view after the frame but it turns out we were // not. _scrollToBottom = true; } }); } return Scrollbar( controller: _scroll, thumbVisibility: true, key: _scrollBarKey, child: Padding( padding: const EdgeInsets.symmetric(horizontal: denseSpacing), child: SelectionArea( child: ListView.separated( padding: const EdgeInsets.all(denseSpacing), itemCount: _currentLines.length + (widget.footer != null ? 1 : 0), controller: _scroll, // Scroll physics to try to keep content within view and avoid bouncing. physics: const ClampingScrollPhysics( parent: RangeMaintainingScrollPhysics(), ), separatorBuilder: (_, __) { return const PaddedDivider.noPadding(); }, itemBuilder: (context, index) { if (index == _currentLines.length && widget.footer != null) { return widget.footer!; } final line = _currentLines[index]; if (line is TextConsoleLine) { return Text.rich( TextSpan( // TODO(jacobr): consider caching the processed ansi terminal // codes. children: processAnsiTerminalCodes( line.text, theme.regularTextStyle, ), ), ); } else if (line is VariableConsoleLine) { return ExpandableVariable( variable: line.variable, isSelectable: false, ); } else { assert( false, 'ConsoleLine of unsupported type ${line.runtimeType} encountered', ); return const SizedBox(); } }, ), ), ), ); } } // CONTROLS /// A Console Control to "delete" the contents of the console. /// /// This just preconfigures a ConsoleControl with the `delete` icon, /// and the `onPressed` function passed from the outside. class DeleteControl extends StatelessWidget { const DeleteControl({ super.key, this.onPressed, this.tooltip = 'Clear contents', this.buttonKey, }); final VoidCallback? onPressed; final String tooltip; final Key? buttonKey; @override Widget build(BuildContext context) { return ToolbarAction( icon: Icons.delete, size: defaultIconSize, tooltip: tooltip, onPressed: onPressed, key: buttonKey, ); } }
devtools/packages/devtools_app/lib/src/shared/console/console.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/console/console.dart", "repo_id": "devtools", "token_count": 2919 }
114
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; const verboseLoggingLevel = Level.FINEST; /// The minimum level of logging that will be logged to the console. /// /// BE VERY CAREFUL ABOUT CHANGING THIS VALUE IN THE REPOSITORY. IF YOU EXPOSE /// MORE LOGS THEN THERE MAY BE PERFORMANCE IMPLICATIONS, AS A RESULT OF LOTS OF /// LOGS ALWAYS BEING PRINTED AND SAVED. const basicLoggingLevel = Level.INFO; /// The icon used for Hot Reload. const hotReloadIcon = Icons.electric_bolt_outlined; /// The icon used for Hot Restart. const hotRestartIcon = Icons.settings_backup_restore_outlined;
devtools/packages/devtools_app/lib/src/shared/constants.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/constants.dart", "repo_id": "devtools", "token_count": 235 }
115
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; // Enum-like static classes are ok. // ignore: avoid_classes_with_only_static_members class DiagnosticsTextStyles { static TextStyle unimportant(ColorScheme colorScheme) => TextStyle( color: colorScheme.isLight ? Colors.grey.shade500 : Colors.grey.shade600, ); static TextStyle regular(ColorScheme colorScheme) => TextStyle( // The font size when not specified seems to be 14, but specify here since we // are scaling based on this font size in [IdeTheme]. fontSize: defaultFontSize, color: colorScheme.onSurface, ); static TextStyle warning(ColorScheme colorScheme) => TextStyle( color: colorScheme.isLight ? Colors.orange.shade900 : Colors.orange.shade400, ); static TextStyle error(ColorScheme colorScheme) => TextStyle( color: colorScheme.error, ); static TextStyle link(ColorScheme colorScheme) => TextStyle( color: colorScheme.isLight ? Colors.blue.shade700 : Colors.blue.shade300, decoration: TextDecoration.underline, ); static const regularBold = TextStyle( fontWeight: FontWeight.w700, ); static TextStyle textStyleForLevel( DiagnosticLevel level, ColorScheme colorScheme, ) { switch (level) { case DiagnosticLevel.hidden: return unimportant(colorScheme); case DiagnosticLevel.warning: return warning(colorScheme); case DiagnosticLevel.error: return error(colorScheme); case DiagnosticLevel.debug: case DiagnosticLevel.info: case DiagnosticLevel.fine: default: return regular(colorScheme); } } }
devtools/packages/devtools_app/lib/src/shared/diagnostics_text_styles.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/diagnostics_text_styles.dart", "repo_id": "devtools", "token_count": 718 }
116
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../primitives/utils.dart'; import 'http_request_data.dart'; class CurlCommand { /// [CurlCommand] provides the ability to create a cURL command string /// based on the passed [DartIOHttpRequestData]. /// /// When [followRedirects] is false, the `--location` option is omitted from cURL. /// When [multiline] is false, the command will be forced to be in a single line. factory CurlCommand.from( DartIOHttpRequestData data, { bool followRedirects = true, bool multiline = true, }) { return CurlCommand._( commandParts: [ 'curl', if (followRedirects) '--location', '--request', data.method, _escapeString(data.uri), ..._headers(data, multiline: multiline), ..._body(data, multiline: multiline), ], ); } CurlCommand._({ required this.commandParts, }); static const _lineBreak = '\\\n'; final List<String> commandParts; /// Returns the cURL command as a string. @override String toString() { return _buildCommandString(commandParts); } static List<String> _headers( DartIOHttpRequestData data, { required bool multiline, }) { final parts = <String>[]; final headers = data.requestHeaders; if (headers != null && headers.isNotEmpty) { for (final header in headers.entries) { final headerKey = header.key.toLowerCase(); final headerValue = _unwrapHeaderValue(header.value); if (headerValue == null) continue; parts.addAll([ if (multiline) _lineBreak, '--header', _escapeString('$headerKey: $headerValue'), ]); } } return parts; } static List<String> _body( DartIOHttpRequestData data, { required bool multiline, }) { final requestBody = data.requestBody; if (requestBody == null) return []; return [ if (multiline) _lineBreak, '--data-raw', _escapeString(requestBody), ]; } /// Escapes an arbitrary string by wrapping it inside single quotes. /// /// Enclosing characters in single quotes preserves the literal value of each /// character in the string. Single quotes can't occur within, which is why it /// is necessary to replace all occurrences of the character ' with '\''. /// /// See: https://www.gnu.org/software/bash/manual/html_node/Quoting.html static String _escapeString(String text) { final content = text.replaceAll("'", "'\\''"); return "'$content'"; } static String? _unwrapHeaderValue(Object? value) { if (value is String) { return value; } else if (value is List<Object?>) { return value.safeFirst as String?; } return null; } /// Given a list of [commandParts], build the cURL command string. static String _buildCommandString(List<String> commandParts) { String commandString = ''; for (int index = 0; index < commandParts.length; index++) { final previousPart = commandParts.safeGet(index - 1); // Only insert a space when this is not the first element AND the previous // part is not a line break. if (index != 0 && previousPart != _lineBreak) { commandString += ' '; } commandString += commandParts[index]; } return commandString; } }
devtools/packages/devtools_app/lib/src/shared/http/curl_command.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/http/curl_command.dart", "repo_id": "devtools", "token_count": 1230 }
117
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of 'preferences.dart'; class ExtensionsPreferencesController extends DisposableController with AutoDisposeControllerMixin { final showOnlyEnabledExtensions = ValueNotifier<bool>(false); static final _showOnlyEnabledExtensionsId = '${gac.DevToolsExtensionEvents.extensionScreenId}.' '${gac.DevToolsExtensionEvents.showOnlyEnabledExtensionsSetting.name}'; Future<void> init() async { addAutoDisposeListener( showOnlyEnabledExtensions, () { storage.setValue( _showOnlyEnabledExtensionsId, showOnlyEnabledExtensions.value.toString(), ); ga.select( gac.DevToolsExtensionEvents.extensionScreenId.name, gac.DevToolsExtensionEvents.showOnlyEnabledExtensionsSetting.name, value: showOnlyEnabledExtensions.value ? 1 : 0, ); }, ); showOnlyEnabledExtensions.value = await boolValueFromStorage( _showOnlyEnabledExtensionsId, defaultsTo: false, ); } }
devtools/packages/devtools_app/lib/src/shared/preferences/_extension_preferences.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/preferences/_extension_preferences.dart", "repo_id": "devtools", "token_count": 421 }
118
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; /// A [ValueListenable] that ignores all added listeners and returns a fixed /// value. class FixedValueListenable<T> extends ValueListenable<T> { const FixedValueListenable(this._value); final T _value; @override void addListener(void Function() listener) {} @override void removeListener(void Function() listener) {} @override T get value => _value; }
devtools/packages/devtools_app/lib/src/shared/primitives/listenable.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/primitives/listenable.dart", "repo_id": "devtools", "token_count": 163 }
119
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. part of 'server.dart'; Future<List<String>> requestAndroidBuildVariants(String path) async { if (isDevToolsServerAvailable) { final uri = Uri( path: DeeplinkApi.androidBuildVariants, queryParameters: { DeeplinkApi.deeplinkRootPathPropertyName: path, }, ); final resp = await request(uri.toString()); if (resp?.statusOk ?? false) { return (jsonDecode(resp!.body) as List).cast<String>(); } else { logWarning(resp, DeeplinkApi.androidBuildVariants); } } return const <String>[]; } Future<AppLinkSettings> requestAndroidAppLinkSettings( String path, { required String buildVariant, }) async { if (isDevToolsServerAvailable) { final uri = Uri( path: DeeplinkApi.androidAppLinkSettings, queryParameters: { DeeplinkApi.deeplinkRootPathPropertyName: path, DeeplinkApi.androidBuildVariantPropertyName: buildVariant, }, ); final resp = await request(uri.toString()); if (resp?.statusOk ?? false) { return AppLinkSettings.fromJson(resp!.body); } else { logWarning(resp, DeeplinkApi.androidAppLinkSettings); } } return AppLinkSettings.empty; } Future<XcodeBuildOptions> requestIosBuildOptions(String path) async { if (isDevToolsServerAvailable) { final uri = Uri( path: DeeplinkApi.iosBuildOptions, queryParameters: { DeeplinkApi.deeplinkRootPathPropertyName: path, }, ); final resp = await request(uri.toString()); if (resp?.statusOk ?? false) { return XcodeBuildOptions.fromJson(resp!.body); } else { logWarning(resp, DeeplinkApi.iosBuildOptions); } } return XcodeBuildOptions.empty; } Future<UniversalLinkSettings> requestIosUniversalLinkSettings( String path, { required String configuration, required String target, }) async { if (isDevToolsServerAvailable) { final uri = Uri( path: DeeplinkApi.iosUniversalLinkSettings, queryParameters: { DeeplinkApi.deeplinkRootPathPropertyName: path, DeeplinkApi.xcodeConfigurationPropertyName: configuration, DeeplinkApi.xcodeTargetPropertyName: target, }, ); final resp = await request(uri.toString()); if (resp?.statusOk ?? false) { return UniversalLinkSettings.fromJson(resp!.body); } else { logWarning(resp, DeeplinkApi.iosUniversalLinkSettings); } } return UniversalLinkSettings.empty; }
devtools/packages/devtools_app/lib/src/shared/server/_deep_links_api.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/server/_deep_links_api.dart", "repo_id": "devtools", "token_count": 968 }
120
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../primitives/byte_utils.dart'; import '../primitives/trees.dart'; import '../primitives/utils.dart'; /// Defines how a column should display data in a table. /// /// [ColumnData] objects should be defined as static where possible, and should /// not manage any stateful data. The table controllers expect columns to be /// solely responsible for declaring how to layout table data. /// /// Any data that can't be stored on the [dataObject] may be accessed by passing /// a long-living controller to the constructor of the [ColumnData] subclass. /// /// The controller is expected to be alive for the duration of the app /// connection. abstract class ColumnData<T> { ColumnData( this.title, { required double this.fixedWidthPx, this.titleTooltip, this.alignment = ColumnAlignment.left, this.headerAlignment = TextAlign.left, }) : minWidthPx = null; ColumnData.wide( this.title, { this.titleTooltip, this.minWidthPx, this.alignment = ColumnAlignment.left, this.headerAlignment = TextAlign.left, }) : fixedWidthPx = null; final String title; final String? titleTooltip; /// Width of the column expressed as a fixed number of pixels. final double? fixedWidthPx; /// The minimum width that should be used for a variable width column. final double? minWidthPx; /// How much to indent the data object by. /// /// This should only be non-zero for [TreeColumnData]. double getNodeIndentPx(T dataObject) => 0.0; final ColumnAlignment alignment; final TextAlign headerAlignment; bool get numeric => false; bool get includeHeader => true; bool get supportsSorting => numeric; int compare(T a, T b) { final valueA = getValue(a); final valueB = getValue(b); if (valueA == null && valueB == null) return 0; if (valueA == null) return -1; if (valueB == null) return 1; return (valueA as Comparable).compareTo(valueB as Comparable); } /// Get the cell's value from the given [dataObject]. Object? getValue(T dataObject); /// Get the cell's display value from the given [dataObject]. String getDisplayValue(T dataObject) => getValue(dataObject)?.toString() ?? ''; String? getCaption(T dataObject) => null; /// Get the cell's tooltip value from the given [dataObject]. String getTooltip(T dataObject) => getDisplayValue(dataObject); /// Get the cell's rich tooltip span from the given [dataObject]. /// /// If both [getTooltip] and [getRichTooltip] are provided, the rich tooltip /// will take precedence. InlineSpan? getRichTooltip(T dataObject, BuildContext context) => null; /// Get the cell's text color from the given [dataObject]. Color? getTextColor(T dataObject) => null; TextStyle? contentTextStyle( BuildContext context, T dataObject, { bool isSelected = false, }) { final theme = Theme.of(context); final textColor = getTextColor(dataObject) ?? theme.colorScheme.onSurface; return theme.regularTextStyleWithColor(textColor); } @override String toString() => title; } abstract class TreeColumnData<T extends TreeNode<T>> extends ColumnData<T> { TreeColumnData(String title) : super.wide(title); static double get treeToggleWidth => scaleByFontFactor(14.0); @override double getNodeIndentPx(T dataObject) { return dataObject.level * treeToggleWidth; } } enum ColumnAlignment { left, right, center, } mixin PinnableListEntry { /// Determines if the row should be pinned to the top of the table. bool get pinToTop => false; } /// Defines a group of columns for use in a table. /// /// Use a column group when multiple columns should be grouped together in the /// table with a common title. In a table with column groups, visual dividers /// will be drawn between groups and an additional header row will be added to /// the table to display the column group titles. class ColumnGroup { ColumnGroup({required this.title, required this.range}); ColumnGroup.fromText({ required String title, required Range range, String? tooltip, }) : this( title: maybeWrapWithTooltip(child: Text(title), tooltip: tooltip), range: range, ); final Widget title; /// The range of column indices for columns that make up this group. final Range range; } extension ColumnDataExtension<T> on ColumnData<T> { MainAxisAlignment get mainAxisAlignment { switch (alignment) { case ColumnAlignment.center: return MainAxisAlignment.center; case ColumnAlignment.right: return MainAxisAlignment.end; case ColumnAlignment.left: default: return MainAxisAlignment.start; } } TextAlign get contentTextAlignment { switch (alignment) { case ColumnAlignment.center: return TextAlign.center; case ColumnAlignment.right: return TextAlign.right; case ColumnAlignment.left: default: return TextAlign.left; } } } typedef RichTooltipBuilder<T> = InlineSpan? Function(T, BuildContext); /// Column that, for each row, shows a time value in milliseconds and the /// percentage that the time value is of the total time for this data set. /// /// Both time and percentage are provided through callbacks [timeProvider] and /// [percentAsDoubleProvider], respectively. /// /// When [percentageOnly] is true, the time value will be omitted, and only the /// percentage will be displayed. abstract class TimeAndPercentageColumn<T> extends ColumnData<T> { TimeAndPercentageColumn({ required String title, required this.percentAsDoubleProvider, this.timeProvider, this.tooltipProvider, this.richTooltipProvider, this.secondaryCompare, this.percentageOnly = false, double columnWidth = _defaultTimeColumnWidth, super.titleTooltip, }) : super( title, fixedWidthPx: scaleByFontFactor(columnWidth), ); static const _defaultTimeColumnWidth = 120.0; Duration Function(T)? timeProvider; double Function(T) percentAsDoubleProvider; String Function(T)? tooltipProvider; RichTooltipBuilder<T>? richTooltipProvider; Comparable Function(T)? secondaryCompare; final bool percentageOnly; @override bool get numeric => true; @override int compare(T a, T b) { final int result = super.compare(a, b); if (result == 0 && secondaryCompare != null) { return secondaryCompare!(a).compareTo(secondaryCompare!(b)); } return result; } @override double getValue(T dataObject) => percentageOnly ? percentAsDoubleProvider(dataObject) : timeProvider!(dataObject).inMicroseconds.toDouble(); @override String getDisplayValue(T dataObject) { if (percentageOnly) return _percentDisplay(dataObject); return _timeAndPercentage(dataObject); } @override String getTooltip(T dataObject) { if (tooltipProvider != null) { return tooltipProvider!(dataObject); } if (percentageOnly && timeProvider != null) { return _timeAndPercentage(dataObject); } return ''; } @override InlineSpan? getRichTooltip(T dataObject, BuildContext context) => richTooltipProvider?.call(dataObject, context); String _timeAndPercentage(T dataObject) => '${durationText(timeProvider!(dataObject), fractionDigits: 2)} (${_percentDisplay(dataObject)})'; String _percentDisplay(T dataObject) => percent(percentAsDoubleProvider(dataObject)); } /// Column that, for each row, shows a memory value and the percentage that the /// memory value is of the total memory for this data set. /// /// Both memory and percentage are provided through callbacks [sizeProvider] and /// [percentAsDoubleProvider], respectively. /// /// When [percentageOnly] is true, the memory value will be omitted, and only the /// percentage will be displayed. abstract class SizeAndPercentageColumn<T> extends ColumnData<T> { SizeAndPercentageColumn({ required String title, required this.percentAsDoubleProvider, this.sizeProvider, this.tooltipProvider, this.richTooltipProvider, this.secondaryCompare, this.percentageOnly = false, double columnWidth = _defaultMemoryColumnWidth, super.titleTooltip, }) : super( title, fixedWidthPx: scaleByFontFactor(columnWidth), ); static const _defaultMemoryColumnWidth = TimeAndPercentageColumn._defaultTimeColumnWidth; int Function(T)? sizeProvider; double Function(T) percentAsDoubleProvider; String Function(T)? tooltipProvider; RichTooltipBuilder<T>? richTooltipProvider; Comparable Function(T)? secondaryCompare; final bool percentageOnly; @override bool get numeric => true; @override int compare(T a, T b) { final int result = super.compare(a, b); if (result == 0 && secondaryCompare != null) { return secondaryCompare!(a).compareTo(secondaryCompare!(b)); } return result; } @override double getValue(T dataObject) => percentageOnly ? percentAsDoubleProvider(dataObject) : sizeProvider!(dataObject).toDouble(); @override String getDisplayValue(T dataObject) { if (percentageOnly) return _percentDisplay(dataObject); return _memoryAndPercentage(dataObject); } @override String getTooltip(T dataObject) { if (tooltipProvider != null) { return tooltipProvider!(dataObject); } if (percentageOnly && sizeProvider != null) { return _memoryAndPercentage(dataObject); } return ''; } @override InlineSpan? getRichTooltip(T dataObject, BuildContext context) => richTooltipProvider?.call(dataObject, context); String _memoryAndPercentage(T dataObject) => '${prettyPrintBytes(sizeProvider!(dataObject), includeUnit: true, kbFractionDigits: 0)}' ' (${_percentDisplay(dataObject)})'; String _percentDisplay(T dataObject) => percent(percentAsDoubleProvider(dataObject)); }
devtools/packages/devtools_app/lib/src/shared/table/table_data.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/table/table_data.dart", "repo_id": "devtools", "token_count": 3254 }
121
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc_2; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'package:stream_channel/stream_channel.dart'; import '../../../shared/config_specific/logger/logger_helpers.dart'; import '../../../shared/config_specific/post_message/post_message.dart'; import '../../../shared/constants.dart'; import '../dart_tooling_api.dart'; import '../vs_code_api.dart'; import 'vs_code_api.dart'; // TODO(https://github.com/flutter/devtools/issues/7055): migrate away from // postMessage and use the Dart Tooling Daemon to communicate between Dart // tooling surfaces. /// Whether to enable verbose logging for postMessage communication. /// /// This is useful for debugging when running inside VS Code. /// /// TODO(dantup): Make a way for this to be enabled by users at runtime for /// troubleshooting. This could be via a message from VS Code, or something /// that passes a query param. const _enablePostMessageVerboseLogging = false; final _log = Logger('tooling_api'); /// An API used by Dart tooling surfaces to interact with Dart tools that expose /// APIs such as Dart-Code and the LSP server. class DartToolingApiImpl implements DartToolingApi { DartToolingApiImpl.rpc(this._rpc) { unawaited(_rpc.listen()); } /// Connects the API using 'postMessage'. This is only available when running /// on web and hosted inside an iframe (such as inside a VS Code webview). factory DartToolingApiImpl.postMessage() { if (_enablePostMessageVerboseLogging) { setDevToolsLoggingLevel(verboseLoggingLevel); } final postMessageController = StreamController<Object?>(); postMessageController.stream.listen((message) { // TODO(dantup): Using fine here doesn't work even though the // `setDevToolsLoggingLevel` call above seems like it should show finest // logs. For now, use info (which always logs) with a condition here // and below. if (_enablePostMessageVerboseLogging) { _log.info('==> $message'); } postMessage(message, '*'); }); final channel = StreamChannel( onPostMessage.map((event) { if (_enablePostMessageVerboseLogging) { _log.info('<== ${jsonEncode(event.data)}'); } return event.data; }), postMessageController, ); return DartToolingApiImpl.rpc(json_rpc_2.Peer.withoutJson(channel)); } final json_rpc_2.Peer _rpc; /// An API that provides Access to APIs related to VS Code, such as executing /// VS Code commands or interacting with the Dart/Flutter extensions. /// /// Lazy-initialized and completes with `null` if VS Code is not available. @override late final Future<VsCodeApi?> vsCode = VsCodeApiImpl.tryConnect(_rpc); void dispose() { unawaited(_rpc.close()); } } /// Base class for the different APIs that may be available. abstract base class ToolApiImpl { ToolApiImpl(this.rpc); static Future<Map<String, Object?>?> tryGetCapabilities( json_rpc_2.Peer rpc, String apiName, ) async { try { final response = await rpc.sendRequest('$apiName.getCapabilities') as Map<Object?, Object?>; return response.cast<String, Object?>(); } catch (_) { // Any error initializing should disable this functionality. return null; } } @protected final json_rpc_2.Peer rpc; @protected String get apiName; @protected Future<T> sendRequest<T>(String method, [Object? parameters]) async { return (await rpc.sendRequest('$apiName.$method', parameters)) as T; } /// Listens for an event '[apiName].[name]' that has a Map for parameters. @protected Stream<Map<String, Object?>> events(String name) { final streamController = StreamController<Map<String, Object?>>.broadcast(); unawaited(rpc.done.then((_) => streamController.close())); rpc.registerMethod('$apiName.$name', (json_rpc_2.Parameters parameters) { streamController.add(parameters.asMap.cast<String, Object?>()); }); return streamController.stream; } }
devtools/packages/devtools_app/lib/src/standalone_ui/api/impl/dart_tooling_api.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/standalone_ui/api/impl/dart_tooling_api.dart", "repo_id": "devtools", "token_count": 1454 }
122
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/profiler/cpu_profile_transformer.dart'; import 'package:devtools_app/src/screens/profiler/cpu_profiler_controller.dart'; import 'package:devtools_app/src/screens/profiler/panes/method_table/method_table_controller.dart'; import 'package:devtools_app/src/screens/profiler/panes/method_table/method_table_model.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../test_infra/test_data/cpu_profiler/simple_profile_1.dart'; import '../../test_infra/test_data/cpu_profiler/simple_profile_2.dart'; void main() { group('$MethodTableController', () { late MethodTableController controller; setUp(() { controller = MethodTableController( dataNotifier: FixedValueListenable<CpuProfileData>( CpuProfileData.empty(), ), ); }); Future<CpuProfileData> initSingleRootData({ required Map<String, dynamic> dataJson, required String profileGolden, }) async { final data = CpuProfileData.parse(dataJson); await CpuProfileTransformer().processData(data, processId: 'test'); expect(data.callTreeRoots.length, 1); expect(data.callTreeRoots.first.profileAsString(), profileGolden); return data; } Future<CpuProfileData> initSimpleData1() async { return await initSingleRootData( dataJson: simpleCpuProfile1, profileGolden: simpleProfile1Golden, ); } Future<CpuProfileData> initSimpleData2() async { return await initSingleRootData( dataJson: simpleCpuProfile2, profileGolden: simpleProfile2Golden, ); } test('createMethodTableGraph ', () async { var data = await initSimpleData1(); expect(controller.methods.value, isEmpty); controller.createMethodTableGraph(data); expect(controller.methods.value.length, 4); expect(controller.graphAsString(), simpleProfile1MethodTableGolden); controller.reset(); data = await initSimpleData2(); expect(controller.methods.value, isEmpty); controller.createMethodTableGraph(data); expect(controller.methods.value.length, 5); expect(controller.graphAsString(), simpleProfile2MethodTableGolden); }); test('createMethodTableGraph with user tags ', () async { final data = CpuProfileData.parse(simpleCpuProfile1); final fullDataPair = CpuProfilePair( functionProfile: data, codeProfile: null, ); final cpuProfilePair = CpuProfilePair.withTagRoots( fullDataPair, CpuProfilerTagType.user, ); await cpuProfilePair.process( transformer: CpuProfileTransformer(), processId: 'test', ); final processedData = cpuProfilePair.functionProfile; expect(processedData.callTreeRoots.length, 2); expect( processedData.cpuProfileRoot.profileAsString(), simpleProfile1GroupedByTagGolden, ); expect(controller.methods.value, isEmpty); controller.createMethodTableGraph(processedData); expect(controller.methods.value.length, 4); expect(controller.graphAsString(), simpleProfile1MethodTableGolden); }); test('selectedNode updates', () async { final data = await initSimpleData1(); controller.createMethodTableGraph(data); expect(controller.selectedNode.value, isNull); controller.selectedNode.value = controller.methods.value.first; expect(controller.selectedNode.value, controller.methods.value.first); controller.selectedNode.value = controller.methods.value[2]; expect(controller.selectedNode.value, controller.methods.value[2]); controller.reset(); expect(controller.selectedNode.value, isNull); }); test('matchesForSearch', () async { final data = await initSimpleData2(); controller.createMethodTableGraph(data); expect(controller.matchesForSearch(''), isEmpty); expect(controller.matchesForSearch('a.dart|b.dart').length, 2); expect(controller.matchesForSearch('package:my_app').length, 5); expect(controller.matchesForSearch('some_bogus_search'), isEmpty); }); group('caller and callee percentage', () { late List<MethodTableGraphNode> methods; setUp(() async { final data = await initSimpleData1(); controller.createMethodTableGraph(data); methods = controller.methods.value; expect(methods.length, 4); }); test('when selected node is null', () { expect(controller.selectedNode.value, isNull); expect(controller.callerPercentageFor(methods[1]), 0.0); expect(controller.calleePercentageFor(methods[1]), 0.0); }); test('when node is disconnected', () { controller.selectedNode.value = methods.first; final selectedNode = controller.selectedNode.value!; expect(selectedNode.name, 'A'); final disconnctedNode = methods[2]; expect(disconnctedNode.name, 'C'); expect(selectedNode.predecessors, isNot(contains(disconnctedNode))); expect(selectedNode.successors, isNot(contains(disconnctedNode))); expect(controller.callerPercentageFor(disconnctedNode), 0.0); expect(controller.calleePercentageFor(disconnctedNode), 0.0); }); test('when node is connected', () { final a = methods[0]; final b = methods[1]; final c = methods[2]; final d = methods[3]; controller.selectedNode.value = a; expect(controller.callerPercentageFor(a), 0.0); expect(controller.callerPercentageFor(b), 0.0); expect(controller.callerPercentageFor(c), 0.0); expect(controller.callerPercentageFor(d), 0.0); expect(controller.calleePercentageFor(a), 0.0); expect(controller.calleePercentageFor(b), 0.7777777777777778); expect(controller.calleePercentageFor(c), 0.0); expect(controller.calleePercentageFor(d), 0.2222222222222222); controller.selectedNode.value = b; expect(controller.callerPercentageFor(a), 1.0); expect(controller.callerPercentageFor(b), 0.0); expect(controller.callerPercentageFor(c), 0.0); expect(controller.callerPercentageFor(d), 0.0); expect(controller.calleePercentageFor(a), 0.0); expect(controller.calleePercentageFor(b), 0.0); expect(controller.calleePercentageFor(c), 1.0); expect(controller.calleePercentageFor(d), 0.0); controller.selectedNode.value = c; expect(controller.callerPercentageFor(a), 0.0); expect(controller.callerPercentageFor(b), 0.6666666666666666); expect(controller.callerPercentageFor(c), 0.0); expect(controller.callerPercentageFor(d), 0.3333333333333333); expect(controller.calleePercentageFor(a), 0.0); expect(controller.calleePercentageFor(b), 0.0); expect(controller.calleePercentageFor(c), 0.0); expect(controller.calleePercentageFor(d), 0.0); controller.selectedNode.value = d; expect(controller.callerPercentageFor(a), 1.0); expect(controller.callerPercentageFor(b), 0.0); expect(controller.callerPercentageFor(c), 0.0); expect(controller.callerPercentageFor(d), 0.0); expect(controller.calleePercentageFor(a), 0.0); expect(controller.calleePercentageFor(b), 0.0); expect(controller.calleePercentageFor(c), 1.0); expect(controller.calleePercentageFor(d), 0.0); }); }); }); }
devtools/packages/devtools_app/test/cpu_profiler/method_table/method_table_controller_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/cpu_profiler/method_table/method_table_controller_test.dart", "repo_id": "devtools", "token_count": 2997 }
123
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:dap/dap.dart' as dap; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/shared/diagnostics/dap_object_node.dart'; import 'package:devtools_app/src/shared/feature_flags.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; void main() { late FakeServiceConnectionManager fakeServiceConnection; late MockDebuggerController debuggerController; late MockScriptManager scriptManager; late MockVmServiceWrapper vmService; const windowSize = Size(2500, 1500); setUp(() { FeatureFlags.dapDebugging = true; vmService = createMockVmServiceWrapperWithDefaults(); fakeServiceConnection = FakeServiceConnectionManager(service: vmService); scriptManager = MockScriptManager(); mockConnectedApp( fakeServiceConnection.serviceManager.connectedApp!, isProfileBuild: false, isFlutterApp: true, isWebApp: false, ); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal(ScriptManager, scriptManager); setGlobal(NotificationService, NotificationService()); setGlobal(BreakpointManager, BreakpointManager()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); fakeServiceConnection.consoleService.ensureServiceInitialized(); when(fakeServiceConnection.errorBadgeManager.errorCountNotifier('debugger')) .thenReturn(ValueNotifier<int>(0)); debuggerController = createMockDebuggerControllerWithDefaults(); }); tearDown(() { fakeServiceConnection.appState.setDapVariables( [], ); }); Future<void> pumpDebuggerScreen( WidgetTester tester, DebuggerController controller, ) async { await tester.pumpWidget( wrapWithControllers( const DebuggerWindows(), debugger: controller, ), ); } testWidgetsWithWindowSize( 'Shows non-expandable variables', windowSize, (WidgetTester tester) async { final node = DapObjectNode( service: vmService, variable: dap.Variable( name: 'myInt', value: '10', variablesReference: 0, ), ); fakeServiceConnection.appState.setDapVariables( [node], ); await pumpDebuggerScreen(tester, debuggerController); expect(find.text('Variables'), findsOneWidget); // Variables should include the int. final intFinder = find.text('myInt: 10'); expect(intFinder, findsOneWidget); // The int is not expandable. final expandArrowFinder = find.byIcon(Icons.keyboard_arrow_down); expect(expandArrowFinder, findsNothing); }, ); testWidgetsWithWindowSize( 'Shows expandable variables', windowSize, (WidgetTester tester) async { when(vmService.dapVariablesRequest(any)).thenAnswer((_) async { return dap.VariablesResponseBody( variables: [ dap.Variable( name: 'myString', value: '"myString"', variablesReference: 0, ), ], ); }); final node = DapObjectNode( service: vmService, variable: dap.Variable( name: 'myList', value: 'List (1 item)', variablesReference: 1, ), ); await node.fetchChildren(); fakeServiceConnection.appState.setDapVariables( [node], ); await pumpDebuggerScreen(tester, debuggerController); expect(find.text('Variables'), findsOneWidget); // Variables should include the list. final listFinder = find.text('myList: List (1 item)'); expect(listFinder, findsOneWidget); // Initially the string is not visible. final stringFinder = find.text('myString: "myString"'); expect(stringFinder, findsNothing); // Expand the list. final expandArrowFinder = find.byIcon(Icons.keyboard_arrow_down); expect(expandArrowFinder, findsOneWidget); await tester.tap(expandArrowFinder.first); await tester.pump(); // String is now visible. expect(stringFinder, findsOneWidget); }, ); }
devtools/packages/devtools_app/test/debugger/debugger_screen_dap_variables_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/debugger/debugger_screen_dap_variables_test.dart", "repo_id": "devtools", "token_count": 1762 }
124
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/extensions/extension_settings.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_extensions.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../test_infra/matchers/matchers.dart'; import '../test_infra/test_data/extensions.dart'; void main() { late ExtensionSettingsDialog dialog; group('$ExtensionSettingsDialog', () { setUp(() async { dialog = const ExtensionSettingsDialog(); setGlobal(PreferencesController, PreferencesController()); setGlobal( ExtensionService, await createMockExtensionServiceWithDefaults(testExtensions), ); setGlobal(IdeTheme, IdeTheme()); }); testWidgets( 'builds dialog with no available extensions', (WidgetTester tester) async { setGlobal( ExtensionService, await createMockExtensionServiceWithDefaults([]), ); await tester.pumpWidget(wrapSimple(dialog)); expect(find.text('DevTools Extensions'), findsOneWidget); expect( find.textContaining('Extensions are provided by the pub packages'), findsOneWidget, ); expect(find.text('No extensions available.'), findsOneWidget); expect(find.byType(ListView), findsNothing); expect(find.byType(ExtensionSetting), findsNothing); }, ); testWidgets( 'builds dialog with available extensions', (WidgetTester tester) async { await tester.pumpWidget(wrapSimple(dialog)); expect(find.text('DevTools Extensions'), findsOneWidget); expect( find.textContaining('Extensions are provided by the pub packages'), findsOneWidget, ); expect(find.text('No extensions available.'), findsNothing); expect(find.byType(ListView), findsOneWidget); expect(find.byType(ExtensionSetting), findsNWidgets(3)); await expectLater( find.byWidget(dialog), matchesDevToolsGolden( '../test_infra/goldens/extensions/settings_state_none.png', ), ); }, ); testWidgets( 'pressing toggle buttons makes calls to the $ExtensionService', (WidgetTester tester) async { await tester.pumpWidget(wrapSimple(dialog)); expect( extensionService.enabledStateListenable(barExtension.name).value, ExtensionEnabledState.none, ); expect( extensionService.enabledStateListenable(fooExtension.name).value, ExtensionEnabledState.none, ); expect( extensionService.enabledStateListenable(providerExtension.name).value, ExtensionEnabledState.none, ); final barSetting = tester .widgetList<ExtensionSetting>(find.byType(ExtensionSetting)) .where( (setting) => setting.extension.name.caseInsensitiveEquals('bar'), ) .first; final fooSetting = tester .widgetList<ExtensionSetting>(find.byType(ExtensionSetting)) .where( (setting) => setting.extension.name.caseInsensitiveEquals('foo'), ) .first; final providerSetting = tester .widgetList<ExtensionSetting>(find.byType(ExtensionSetting)) .where( (setting) => setting.extension.name.caseInsensitiveEquals('provider'), ) .first; // Enable the 'bar' extension. await tester.tap( find.descendant( of: find.byWidget(barSetting), matching: find.text('Enabled'), ), ); expect( extensionService.enabledStateListenable(barExtension.name).value, ExtensionEnabledState.enabled, ); // Enable the 'foo' extension. await tester.tap( find.descendant( of: find.byWidget(fooSetting), matching: find.text('Enabled'), ), ); expect( extensionService.enabledStateListenable(fooExtension.name).value, ExtensionEnabledState.enabled, ); // Disable the 'provider' extension. await tester.tap( find.descendant( of: find.byWidget(providerSetting), matching: find.text('Disabled'), ), ); expect( extensionService.enabledStateListenable(providerExtension.name).value, ExtensionEnabledState.disabled, ); await tester.pumpWidget(wrapSimple(dialog)); await expectLater( find.byWidget(dialog), matchesDevToolsGolden( '../test_infra/goldens/extensions/settings_state_modified.png', ), ); }, ); testWidgets( 'toggle buttons update for changes to value notifiers', (WidgetTester tester) async { await tester.pumpWidget(wrapSimple(dialog)); await expectLater( find.byWidget(dialog), matchesDevToolsGolden( '../test_infra/goldens/extensions/settings_state_none.png', ), ); await extensionService.setExtensionEnabledState( barExtension, enable: true, ); await extensionService.setExtensionEnabledState( fooExtension, enable: true, ); await extensionService.setExtensionEnabledState( providerExtension, enable: false, ); await tester.pumpWidget(wrapSimple(dialog)); await expectLater( find.byWidget(dialog), matchesDevToolsGolden( '../test_infra/goldens/extensions/settings_state_modified.png', ), ); }, ); }); }
devtools/packages/devtools_app/test/extensions/extension_settings_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/extensions/extension_settings_test.dart", "repo_id": "devtools", "token_count": 2699 }
125
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/screens/memory/panes/chart/memory_charts.dart'; import 'package:devtools_app/src/service/service_manager.dart'; import 'package:devtools_app/src/shared/charts/chart.dart'; import 'package:devtools_app/src/shared/charts/chart_controller.dart'; import 'package:devtools_app/src/shared/charts/chart_trace.dart'; import 'package:devtools_app/src/shared/primitives/utils.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../test_infra/matchers/matchers.dart'; import '../../test_infra/test_data/memory.dart'; void main() { const windowSize = Size(2225.0, 1000.0); setUp(() { setGlobal(ServiceConnectionManager, FakeServiceConnectionManager()); setGlobal(IdeTheme, IdeTheme()); }); group( 'Chart Timeseries', () { late MemoryJson<HeapSample> memoryJson; bool memoryJasonInitialized = false; void loadData() { // Load canned data testHeapSampleData. if (!memoryJasonInitialized) { memoryJson = SamplesMemoryJson.decode(argJsonString: testHeapSampleData); memoryJasonInitialized = true; } expect(memoryJson.data.length, equals(104)); } /////////////////////////////////////////////////////////////////////////// // Scaled Y-axis chart. // /////////////////////////////////////////////////////////////////////////// // Used for test. final rawExternal = <Data>[]; final rawUsed = <Data>[]; final rawCapacity = <Data>[]; final rawRSS = <Data>[]; late int externalTraceIndex; late int usedTraceIndex; late int capacityTraceIndex; late int rssTraceIndex; void setupTraces(ChartController controller) { // External Heap externalTraceIndex = controller.createTrace( ChartType.line, PaintCharacteristics( color: Colors.lightGreen, symbol: ChartSymbol.disc, diameter: 1.5, ), name: externalDisplay, ); // Used Heap usedTraceIndex = controller.createTrace( ChartType.line, PaintCharacteristics( color: Colors.blue[200]!, symbol: ChartSymbol.disc, diameter: 1.5, ), name: usedDisplay, ); // Heap Capacity capacityTraceIndex = controller.createTrace( ChartType.line, PaintCharacteristics( color: Colors.grey[400]!, diameter: 0.0, symbol: ChartSymbol.dashedLine, ), name: allocatedDisplay, ); // RSS rssTraceIndex = controller.createTrace( ChartType.line, PaintCharacteristics( color: Colors.yellow, symbol: ChartSymbol.dashedLine, strokeWidth: 2, ), name: rssDisplay, ); expect(controller.traces.length, equals(4)); for (var index = 0; index < controller.traces.length; index++) { switch (index) { case 0: expect(externalTraceIndex, equals(0)); expect(controller.traces[index].name, externalDisplay); break; case 1: expect(usedTraceIndex, equals(1)); expect(controller.traces[index].name, usedDisplay); break; case 2: expect(capacityTraceIndex, equals(2)); expect(controller.traces[index].name, allocatedDisplay); break; case 3: expect(rssTraceIndex, equals(3)); expect(controller.traces[index].name, rssDisplay); break; } } } void addDataToTrace( ChartController controller, int traceIndex, Data data, ) { controller.trace(traceIndex).addDatum(data); } Future<void> pumpChart( WidgetTester tester, Key theKey, Chart theChart, double chartHeight, ) async { await tester.pumpWidget( wrap( LayoutBuilder( key: theKey, builder: (context, constraints) { return Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: chartHeight, child: Padding( padding: const EdgeInsets.all(0.0), child: theChart, ), ), ], ); }, ), ), ); await tester.pumpAndSettle(); } void chartAllData(ChartController controller) { for (var datumIndex = 0; datumIndex < memoryJson.data.length; datumIndex++) { final datum = memoryJson.data[datumIndex]; final external = datum.external.toDouble(); final used = datum.used.toDouble(); final capacity = datum.capacity.toDouble(); final rss = datum.rss.toDouble(); controller.addTimestamp(datum.timestamp); rawExternal.add(Data(datum.timestamp, external)); addDataToTrace(controller, externalTraceIndex, rawExternal.last); rawUsed.add(Data(datum.timestamp, external + used)); addDataToTrace(controller, usedTraceIndex, rawUsed.last); rawCapacity.add(Data(datum.timestamp, capacity)); addDataToTrace(controller, capacityTraceIndex, rawCapacity.last); rawRSS.add(Data(datum.timestamp, rss)); addDataToTrace(controller, rssTraceIndex, rawRSS.last); } } Future<void> setupScaledChart( WidgetTester tester, ChartController controller, Key chartKey, ) async { final theChart = Chart(controller, title: 'Scaled Chart'); setupTraces(controller); loadData(); await pumpChart(tester, chartKey, theChart, 250); expect(find.byWidget(theChart), findsOneWidget); // Validate the X axis before data added. expect(controller.visibleXAxisTicks, equals(215)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.0)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2150.0)); // Validate the Y axis before data added. expect(controller.yScale.labelTicks, equals(0.0)); expect(controller.yScale.labelUnitExponent, 0.0); expect(controller.yScale.tickSpacing, equals(1.0)); expect(controller.yScale.maxPoint, equals(0.0)); expect(controller.yScale.maxTicks, equals(185.0)); chartAllData(controller); } /// Validate the labels displayed on the y-axis. void validateScaledYLabels(ChartController controller) { // Validate the labels displayed on the y-axis. final yScale = controller.yScale; expect(yScale.labelTicks, equals(10)); for (var labelIndex = yScale.labelTicks; labelIndex >= 0; labelIndex--) { final labelName = ChartPainter.constructLabel( labelIndex.toInt(), yScale.labelUnitExponent.toInt(), ); // Ensure Y axis labels match. final expectedLabels = [ '0', '100M', '200M', '300M', '400M', '500M', '600M', '700M', '800M', '900M', '1000M', ]; expect(labelName, expectedLabels[labelIndex.toInt()]); } } testWidgetsWithWindowSize( 'Scaled Y-axis live', windowSize, (WidgetTester tester) async { const chartKey = Key('Chart'); final controller = ChartController(); await setupScaledChart(tester, controller, chartKey); // Check live view zoom. controller.zoomDuration = const Duration(); await tester.pumpAndSettle(const Duration(seconds: 2)); await expectLater( find.byKey(chartKey), matchesDevToolsGolden( '../../test_infra/goldens/memory_chart_scaled_live.png', ), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); // Validate the X axis after data added to all traces. expect(controller.visibleXAxisTicks, equals(215)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.0)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2150.0)); // Validate the Y axis after data added to all traces. expect(controller.yScale.labelTicks, equals(10.0)); expect(controller.yScale.labelUnitExponent, 8.0); expect(controller.yScale.tickSpacing, equals(5291005.291005291)); expect(controller.yScale.maxPoint, equals(717799424.0)); expect(controller.yScale.maxTicks, equals(190.0)); final externalTrace = controller.trace(externalTraceIndex); expect(externalTrace.dataYMax, equals(357446512.0)); expect(externalTrace.data.length, equals(rawExternal.length)); final usedTrace = controller.trace(usedTraceIndex); expect(usedTrace.dataYMax, equals(409913568.0)); expect(usedTrace.data.length, equals(rawUsed.length)); final capacityTrace = controller.trace(capacityTraceIndex); expect(capacityTrace.dataYMax, equals(422794096.0)); expect(capacityTrace.data.length, equals(rawCapacity.length)); final rssTrace = controller.trace(rssTraceIndex); expect(rssTrace.dataYMax, equals(717799424.0)); expect(rssTrace.data.length, equals(rawRSS.length)); expect(controller.timestampsLength, equals(104)); validateScaledYLabels(controller); // Validate the x-axis labels. expect(controller.labelTimestamps.length, equals(2)); expect(controller.labelTimestamps[0], equals(1611247510202)); expect(controller.labelTimestamps[1], equals(1611247530281)); // Validate using UTC timezone. expect( prettyTimestamp(controller.labelTimestamps[0], isUtc: true), equals('16:45:10'), ); expect( prettyTimestamp(controller.labelTimestamps[1], isUtc: true), equals('16:45:30'), ); }, ); void checkScaledXAxis2Labels(ChartController controller) { // Validate the x-axis labels. expect(controller.labelTimestamps.length, equals(1)); expect(controller.labelTimestamps[0], equals(1611247510202)); // Validate using UTC timezone. expect( prettyTimestamp(controller.labelTimestamps[0], isUtc: true), equals('16:45:10'), ); } testWidgetsWithWindowSize( 'Scaled Y-axis all', windowSize, (WidgetTester tester) async { const chartKey = Key('Chart'); final controller = ChartController(); await setupScaledChart(tester, controller, chartKey); // Check A=all data view zoom. controller.zoomDuration = null; await tester.pumpAndSettle(const Duration(seconds: 2)); await expectLater( find.byKey(chartKey), matchesDevToolsGolden( '../../test_infra/goldens/memory_chart_scaled_all.png', ), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); // Validate the X axis after data added to all traces. expect(controller.visibleXAxisTicks, equals(104)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.0)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2150.0)); // Validate the Y axis after data added to all traces. expect(controller.yScale.labelTicks, equals(10.0)); expect(controller.yScale.labelUnitExponent, 8.0); expect(controller.yScale.tickSpacing, equals(5291005.291005291)); expect(controller.yScale.maxPoint, equals(717799424.0)); expect(controller.yScale.maxTicks, equals(190.0)); validateScaledYLabels(controller); checkScaledXAxis2Labels(controller); }, ); testWidgetsWithWindowSize( 'Scaled Y-axis Five Minutes', windowSize, (WidgetTester tester) async { const chartKey = Key('Chart'); final controller = ChartController(); await setupScaledChart(tester, controller, chartKey); // Check 5 minute data view zoom. controller.zoomDuration = const Duration(minutes: 5); await tester.pumpAndSettle(const Duration(seconds: 2)); await expectLater( find.byKey(chartKey), matchesDevToolsGolden( '../../test_infra/goldens/memory_chart_scaled_five_minute.png', ), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); // Validate the X axis after data added to all traces. expect(controller.visibleXAxisTicks, equals(1704)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.6880000000001019)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2149.312)); // Validate the Y axis after data added to all traces. expect(controller.yScale.labelTicks, equals(10.0)); expect(controller.yScale.labelUnitExponent, 8.0); expect(controller.yScale.tickSpacing, equals(5291005.291005291)); expect(controller.yScale.maxPoint, equals(717799424.0)); expect(controller.yScale.maxTicks, equals(190.0)); validateScaledYLabels(controller); checkScaledXAxis2Labels(controller); }, ); /////////////////////////////////////////////////////////////////////////// // Fixed Y-axis chart. // /////////////////////////////////////////////////////////////////////////// final rawGcEvents = <Data>[]; final rawSnapshotEvents = <Data>[]; final rawAutoSnapshotEvents = <Data>[]; late int snapshotTraceIndex; late int autoSnapshotTraceIndex; late int manualGCTraceIndex; late int monitorTraceIndex; late int monitorResetTraceIndex; late int gcTraceIndex; void setupFixedTraces(ChartController controller) { // Snapshot snapshotTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.green, strokeWidth: 4, diameter: 6, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'Snapshot', ); // Auto-snapshot autoSnapshotTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.red, strokeWidth: 4, diameter: 6, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'Auto-Snapshot', ); // Manual GC manualGCTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.blue, strokeWidth: 4, diameter: 6, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'Manual GC', ); // Monitor monitorTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.yellow, strokeWidth: 4, diameter: 6, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'Monitor', ); monitorResetTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics.concentric( color: Colors.grey[600]!, strokeWidth: 4, diameter: 6, fixedMinY: 0.4, fixedMaxY: 2.4, concentricCenterColor: Colors.yellowAccent, concentricCenterDiameter: 4, ), name: 'Monitor Reset', ); // VM GC gcTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.blue, symbol: ChartSymbol.disc, diameter: 4, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'VM GC', ); } /// Event to display in the event pane (User initiated GC, snapshot, /// automatic snapshot, etc.) const visibleEvent = 2.4; /// Monitor events Y axis. const visibleMonitorEvent = 1.4; /// VM's GCs are displayed in a smaller glyph and closer to the heap graph. const visibleVmEvent = 0.4; // Load all data into the chart's traces. void chartAllFixedData(ChartController controller) { for (var datumIndex = 0; datumIndex < memoryJson.data.length; datumIndex++) { final datum = memoryJson.data[datumIndex]; controller.addTimestamp(datum.timestamp); final event = datum.memoryEventInfo; if (datum.isGC) { // VM GC rawGcEvents.add(Data(datum.timestamp, visibleVmEvent)); addDataToTrace(controller, gcTraceIndex, rawGcEvents.last); } else if (event.isEventGC) { // Manual GC final rawData = Data(datum.timestamp, visibleVmEvent); addDataToTrace(controller, manualGCTraceIndex, rawData); } else if (event.isEventSnapshot) { rawSnapshotEvents.add(Data(datum.timestamp, visibleEvent)); addDataToTrace( controller, snapshotTraceIndex, rawSnapshotEvents.last, ); } else if (event.isEventSnapshotAuto) { rawAutoSnapshotEvents.add(Data(datum.timestamp, visibleEvent)); addDataToTrace( controller, autoSnapshotTraceIndex, rawAutoSnapshotEvents.last, ); } else if (event.isEventAllocationAccumulator) { final monitorType = event.allocationAccumulator; final rawData = Data(datum.timestamp, visibleMonitorEvent); if (monitorType!.isEmpty) continue; if (monitorType.isStart) { addDataToTrace(controller, monitorTraceIndex, rawData); } else if (monitorType.isReset) { addDataToTrace(controller, monitorResetTraceIndex, rawData); } else { assert(false, 'Unknown monitor type'); } } else if (event.isEmpty) { assert(false, 'Unexpected EventSample of isEmpty.'); } } } Future<void> setupFixedChart( WidgetTester tester, ChartController controller, Key chartKey, ) async { controller.setFixedYRange(0.4, 2.4); final theChart = Chart(controller, title: 'Fixed Chart'); await pumpChart(tester, chartKey, theChart, 150); expect(find.byWidget(theChart), findsOneWidget); setupFixedTraces(controller); loadData(); // Validate the X axis before any data. expect(controller.visibleXAxisTicks, equals(215)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.0)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2150.0)); // Validate the Y axis before any data. expect(controller.yScale.labelTicks, equals(3.0)); expect(controller.yScale.labelUnitExponent, 0.0); expect(controller.yScale.tickSpacing, equals(0.033707865168539325)); expect(controller.yScale.maxPoint, equals(2.4)); expect(controller.yScale.maxTicks, equals(90.0)); // Load all data in the chart. chartAllFixedData(controller); } testWidgetsWithWindowSize( 'Fixed Y-axis', windowSize, (WidgetTester tester) async { const chartKey = Key('Chart'); final controller = ChartController(); await setupFixedChart(tester, controller, chartKey); // Check live view zoom. controller.zoomDuration = const Duration(); await tester.pumpAndSettle(const Duration(seconds: 2)); await expectLater( find.byKey(chartKey), matchesDevToolsGolden( '../../test_infra/goldens/memory_chart_fixed_live.png', ), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); // Validate the X axis after data added to all traces. expect(controller.visibleXAxisTicks, equals(215)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.0)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2150.0)); // Rest of data is out of view because we're live view max is now 1.4 // and only 2 labels visible. expect(controller.yScale.labelTicks, equals(3.0)); expect(controller.yScale.labelUnitExponent, 0.0); expect(controller.yScale.tickSpacing, equals(0.033707865168539325)); // Max live view max is 1.4 other data is not in the visible view. expect(controller.yScale.maxPoint, equals(2.4)); expect(controller.yScale.maxTicks, equals(90.0)); final snapshotTrace = controller.trace(snapshotTraceIndex); expect(snapshotTrace.dataYMax, equals(0.0)); expect(snapshotTrace.data.length, equals(1)); final autoSnapshotTrace = controller.trace(autoSnapshotTraceIndex); expect(autoSnapshotTrace.dataYMax, equals(0.0)); expect(autoSnapshotTrace.data.length, equals(0)); final manualGCTrace = controller.trace(manualGCTraceIndex); expect(manualGCTrace.dataYMax, equals(0.0)); expect(manualGCTrace.data.length, equals(0)); final monitorTrace = controller.trace(monitorTraceIndex); expect(monitorTrace.dataYMax, equals(0.0)); expect(monitorTrace.data.length, equals(2)); final monitorResetTrace = controller.trace(monitorResetTraceIndex); expect(monitorResetTrace.dataYMax, equals(0.0)); expect(monitorResetTrace.data.length, equals(1)); final gcTrace = controller.trace(gcTraceIndex); expect(gcTrace.dataYMax, equals(0.0)); expect(gcTrace.data.length, equals(46)); expect(controller.timestampsLength, equals(104)); // Validate the labels displayed on the y-axis. final yScale = controller.yScale; expect(yScale.labelTicks, equals(3.0)); for (var labelIndex = yScale.labelTicks; labelIndex >= 0; labelIndex--) { final labelName = ChartPainter.constructLabel( labelIndex.toInt(), yScale.labelUnitExponent.toInt(), ); final expectedLabels = ['0', '1', '2', '3']; expect(labelName, expectedLabels[labelIndex.toInt()]); } // Validate the x-axis labels. expect(controller.labelTimestamps.length, equals(2)); expect(controller.labelTimestamps[0], equals(1611247510202)); expect(controller.labelTimestamps[1], equals(1611247530281)); // Validate using UTC timezone. expect( prettyTimestamp(controller.labelTimestamps[0], isUtc: true), equals('16:45:10'), ); expect( prettyTimestamp(controller.labelTimestamps[1], isUtc: true), equals('16:45:30'), ); }, ); void checkFixedXAxis2Labels(ChartController controller) { // Validate the x-axis labels. expect(controller.labelTimestamps.length, equals(1)); expect(controller.labelTimestamps[0], equals(1611247510202)); // Validate using UTC timezone. expect( prettyTimestamp(controller.labelTimestamps[0], isUtc: true), equals('16:45:10'), ); } testWidgetsWithWindowSize( 'Fixed Y-axis all', windowSize, (WidgetTester tester) async { const chartKey = Key('Chart'); final controller = ChartController(); await setupFixedChart(tester, controller, chartKey); // Check all data view zoom. controller.zoomDuration = null; await tester.pumpAndSettle(const Duration(seconds: 15)); await expectLater( find.byKey(chartKey), matchesDevToolsGolden( '../../test_infra/goldens/memory_chart_fixed_all.png', ), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); // Validate the X axis after data added to all traces. expect(controller.visibleXAxisTicks, equals(104)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.0)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2150.0)); // Validate the Y axis after data added to all traces. expect(controller.yScale.labelTicks, equals(3.0)); expect(controller.yScale.labelUnitExponent, 0.0); expect(controller.yScale.tickSpacing, equals(0.033707865168539325)); expect(controller.yScale.maxPoint, equals(2.4)); expect(controller.yScale.maxTicks, equals(90.0)); // Validate the labels displayed on the y-axis. final yScale = controller.yScale; expect(yScale.labelTicks, equals(3)); for (var labelIndex = yScale.labelTicks; labelIndex >= 0; labelIndex--) { final labelName = ChartPainter.constructLabel( labelIndex.toInt(), yScale.labelUnitExponent.toInt(), ); final expectedLabels = ['0', '1', '2', '3']; expect(labelName, expectedLabels[labelIndex.toInt()]); } checkFixedXAxis2Labels(controller); }, ); testWidgetsWithWindowSize( 'Fixed Y-axis 5 Minutes', windowSize, (WidgetTester tester) async { const chartKey = Key('Chart'); final controller = ChartController(); await setupFixedChart(tester, controller, chartKey); // Check all data view zoom. controller.zoomDuration = const Duration(minutes: 5); await tester.pumpAndSettle(const Duration(seconds: 15)); await expectLater( find.byKey(chartKey), matchesDevToolsGolden( '../../test_infra/goldens/memory_chart_fixed_five_minutes.png', ), ); // Await delay for golden comparison. await tester.pumpAndSettle(const Duration(seconds: 2)); // Validate the X axis after data added to all traces. expect(controller.visibleXAxisTicks, equals(1704)); expect(controller.xCanvasChart, equals(50.0)); expect(controller.xPaddingRight, equals(0.6880000000001019)); expect(controller.displayXLabels, true); expect(controller.canvasChartWidth, equals(2149.312)); // Validate the Y axis after data added to all traces. expect(controller.yScale.labelTicks, equals(3.0)); expect(controller.yScale.labelUnitExponent, 0.0); expect(controller.yScale.tickSpacing, equals(0.033707865168539325)); expect(controller.yScale.maxPoint, equals(2.4)); expect(controller.yScale.maxTicks, equals(90.0)); // Validate the labels displayed on the y-axis. final yScale = controller.yScale; expect(yScale.labelTicks, equals(3)); for (var labelIndex = yScale.labelTicks; labelIndex >= 0; labelIndex--) { final labelName = ChartPainter.constructLabel( labelIndex.toInt(), yScale.labelUnitExponent.toInt(), ); final expectedLabels = ['0', '1', '2', '3']; expect(labelName, expectedLabels[labelIndex.toInt()]); } checkFixedXAxis2Labels(controller); }, ); }, ); }
devtools/packages/devtools_app/test/memory/chart/chart_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/memory/chart/chart_test.dart", "repo_id": "devtools", "token_count": 13602 }
126
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/memory/framework/connected/memory_tabs.dart'; import 'package:devtools_app/src/screens/memory/panes/tracing/tracing_pane_controller.dart'; import 'package:devtools_app/src/screens/memory/panes/tracing/tracing_tree.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:vm_service/vm_service.dart'; import '../../test_infra/scenes/memory/default.dart'; import '../../test_infra/scenes/scene_test_extensions.dart'; import '../../test_infra/utils/test_utils.dart'; // TODO(bkonyi): add tests for multi-isolate support. // See https://github.com/flutter/devtools/issues/4537. void main() { final classList = ClassList( classes: [ ClassRef(id: 'cls/1', name: 'ClassA'), ClassRef(id: 'cls/2', name: 'ClassB'), ClassRef(id: 'cls/3', name: 'ClassC'), ClassRef(id: 'cls/4', name: 'Foo'), ], ); /// Clears the class filter text field. Future<void> clearFilter( WidgetTester tester, TracingPaneController controller, ) async { final originalClassCount = classList.classes!.length; final clearFilterButton = find.byIcon(Icons.clear); expect(clearFilterButton, findsOneWidget); await tester.tap(clearFilterButton); await tester.pumpAndSettle(); expect( controller.stateForIsolate.value.filteredClassList.value.length, originalClassCount, ); } // Set a wide enough screen width that we do not run into overflow. const windowSize = Size(2225.0, 1000.0); group('Allocation Tracing', () { late MemoryDefaultScene scene; late final CpuSamples allocationTracingProfile; Future<void> pumpScene(WidgetTester tester) async { await tester.pumpScene(scene); // Delay to ensure the memory profiler has collected data. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.byType(MemoryBody), findsOneWidget); await tester.tap( find.byKey(MemoryScreenKeys.dartHeapAllocationTracingTab), ); await tester.pumpAndSettle(); } setUpAll(() { final rawProfile = File( 'test/test_infra/test_data/memory/allocation_tracing/allocation_trace.json', ).readAsStringSync(); allocationTracingProfile = CpuSamples.parse(jsonDecode(rawProfile))!; }); setUp(() async { setCharacterWidthForTables(); scene = MemoryDefaultScene(); await scene.setUp(classList: classList); mockConnectedApp( scene.fakeServiceConnection.serviceManager.connectedApp!, isFlutterApp: true, isProfileBuild: false, isWebApp: false, ); final mockScriptManager = MockScriptManager(); when(mockScriptManager.sortedScripts).thenReturn( ValueNotifier<List<ScriptRef>>([]), ); when(mockScriptManager.scriptRefForUri(any)).thenReturn( ScriptRef( uri: 'package:test/script.dart', id: 'script.dart', ), ); setGlobal(ScriptManager, mockScriptManager); }); tearDown(() { scene.tearDown(); }); testWidgetsWithWindowSize( 'basic tracing flow', windowSize, (WidgetTester tester) async { await pumpScene(tester); final controller = scene.controller.controllers.tracing; final state = controller.stateForIsolate.value; expect(state.filteredClassList.value.isNotEmpty, isTrue); expect(controller.initializing.value, isFalse); expect(controller.refreshing.value, isFalse); expect(state.selectedTracedClass.value, isNull); expect(state.selectedTracedClassAllocationData, isNull); final refresh = find.text('Refresh'); expect(refresh, findsOneWidget); expect(find.text('Trace'), findsOneWidget); expect(find.text('Class'), findsOneWidget); expect(find.text('Delta'), findsOneWidget); // There should be classes in the example class list. expect(find.byType(Checkbox), findsNWidgets(classList.classes!.length)); for (final cls in state.filteredClassList.value) { expect(find.byKey(Key(cls.cls.id!)), findsOneWidget); } // Enable allocation tracing for one of them. await tester.tap(find.byType(Checkbox).first); await tester.pumpAndSettle(); expect( state.filteredClassList.value .map((e) => e.traceAllocations) .where((e) => e) .length, 1, ); final selectedTrace = state.filteredClassList.value.firstWhere( (e) => e.traceAllocations, ); expect(find.byType(TracingTable), findsNothing); final traceElement = find.byKey(Key(selectedTrace.cls.id!)); expect(traceElement, findsOneWidget); // Select the list item for the traced class and refresh to fetch data. await tester.tap(traceElement); await tester.pumpAndSettle(); await tester.tap(refresh); await tester.pumpAndSettle(); // No allocations have occurred, so the trace viewer shows an error message. expect(state.selectedTracedClass.value, selectedTrace); expect(state.selectedTracedClassAllocationData, isNotNull); expect( find.text( 'No allocation samples have been collected for class ${selectedTrace.cls.name}.\n', ), findsOneWidget, ); // Set fake sample data and refresh to populate the trace view. final fakeService = serviceConnection.serviceManager.service as FakeVmServiceWrapper; fakeService.allocationSamples = allocationTracingProfile; await tester.tap(refresh); await tester.pumpAndSettle(); expect( find.byType(TracingTable), findsOneWidget, ); // Verify the expected widget components are present. expect(find.textContaining('Traced allocations for: '), findsOneWidget); expect(find.text('Bottom Up'), findsOneWidget); expect(find.text('Call Tree'), findsOneWidget); expect(find.text('Expand All'), findsOneWidget); expect(find.text('Collapse All'), findsOneWidget); expect(find.text('Inclusive'), findsOneWidget); expect(find.text('Exclusive'), findsOneWidget); expect(find.text('Method'), findsOneWidget); final bottomUpRoots = state.selectedTracedClassAllocationData!.bottomUpRoots; final callTreeRoots = state.selectedTracedClassAllocationData!.callTreeRoots; for (final root in bottomUpRoots) { expect(root.isExpanded, false); } for (final root in callTreeRoots) { expect(root.isExpanded, false); } await tester.tap(find.text('Expand All')); await tester.pumpAndSettle(); // Check all nodes in the bottom up tree have been expanded. for (final root in bottomUpRoots) { breadthFirstTraversal<CpuStackFrame>( root, action: (e) { expect(e.isExpanded, true); }, ); } // But also make sure that the call tree nodes haven't been expanded. for (final root in callTreeRoots) { expect(root.isExpanded, false); } await tester.tap(find.text('Collapse All')); await tester.pumpAndSettle(); // Check all nodes have been collapsed. for (final root in bottomUpRoots) { breadthFirstTraversal<CpuStackFrame>( root, action: (e) { expect(e.isExpanded, false); }, ); } // Switch from bottom up view to call tree view. await tester.tap(find.text('Call Tree')); await tester.pumpAndSettle(); // Expand the call tree. await tester.tap(find.text('Expand All')); await tester.pumpAndSettle(); // Check all nodes in the call tree have been expanded. for (final root in callTreeRoots) { breadthFirstTraversal<CpuStackFrame>( root, action: (e) { expect(e.isExpanded, true); }, ); } // But also make sure that the bottom up tree nodes haven't been expanded. for (final root in bottomUpRoots) { expect(root.isExpanded, false); } await tester.tap(find.text('Collapse All')); await tester.pumpAndSettle(); // Check all nodes have been collapsed. for (final root in callTreeRoots) { breadthFirstTraversal<CpuStackFrame>( root, action: (e) { expect(e.isExpanded, false); }, ); } }, ); testWidgetsWithWindowSize( 'clear state', windowSize, (WidgetTester tester) async { await pumpScene(tester); final controller = scene.controller.controllers.tracing; final state = controller.stateForIsolate.value; expect(state.filteredClassList.value.isNotEmpty, isTrue); expect(controller.initializing.value, isFalse); expect(controller.refreshing.value, isFalse); expect(state.selectedTracedClass.value, isNull); expect(state.selectedTracedClassAllocationData, isNull); final refresh = find.text('Refresh'); expect(refresh, findsOneWidget); expect(find.text('Trace'), findsOneWidget); expect(find.text('Class'), findsOneWidget); expect(find.text('Delta'), findsOneWidget); // There should be classes in the example class list. expect(find.byType(Checkbox), findsNWidgets(classList.classes!.length)); for (final cls in state.filteredClassList.value) { expect(find.byKey(Key(cls.cls.id!)), findsOneWidget); } // Enable allocation tracing for one of them. await tester.tap(find.byType(Checkbox).first); await tester.pumpAndSettle(); expect( state.filteredClassList.value .map((e) => e.traceAllocations) .where((e) => e) .length, 1, ); final selectedTrace = state.filteredClassList.value.firstWhere( (e) => e.traceAllocations, ); expect(find.byType(TracingTable), findsNothing); final traceElement = find.byKey(Key(selectedTrace.cls.id!)); expect(traceElement, findsOneWidget); // Select the list item for the traced class and refresh to fetch data. await tester.tap(traceElement); await tester.pumpAndSettle(); await tester.tap(refresh); await tester.pumpAndSettle(); // No allocations have occurred, so the trace viewer shows an error message. expect(state.selectedTracedClass.value, selectedTrace); expect(state.selectedTracedClassAllocationData, isNotNull); expect( find.text( 'No allocation samples have been collected for class ${selectedTrace.cls.name}.\n', ), findsOneWidget, ); // Set fake sample data and refresh to populate the trace view. final fakeService = serviceConnection.serviceManager.service as FakeVmServiceWrapper; fakeService.allocationSamples = allocationTracingProfile; await tester.tap(refresh); await tester.pumpAndSettle(); expect( find.byType(TracingTable), findsOneWidget, ); final clearButton = find.byType(ClearButton); expect(clearButton, findsOneWidget); await tester.tap(clearButton); await tester.pumpAndSettle(); // Clearing should zero out all the instance counts. expect(state.selectedTracedClass.value, isNotNull); for (final cls in state.filteredClassList.value) { expect(cls.instances, 0); } // Clear the fake sample data to emulate no additional samples collected // after a clear. fakeService.allocationSamples = CpuSamples( functions: [], samples: [], sampleCount: 0, timeOriginMicros: 0, timeExtentMicros: 0, ); await tester.tap(refresh); await tester.pumpAndSettle(); // Expect no new samples. expect(state.selectedTracedClass.value, isNotNull); for (final cls in state.filteredClassList.value) { expect(cls.instances, 0); } }, ); group('filtering', () { testWidgetsWithWindowSize('simple', windowSize, (tester) async { await pumpScene(tester); final controller = scene.controller.controllers.tracing; final state = controller.stateForIsolate.value; final filterTextField = find.byType(DevToolsClearableTextField); expect(filterTextField, findsOneWidget); // Filter for 'F' await tester.enterText(filterTextField, 'F'); await tester.pumpAndSettle(); expect(state.filteredClassList.value.length, 1); expect(state.filteredClassList.value.first.cls.name, 'Foo'); // Filter for 'Fooo' await tester.enterText(filterTextField, 'Fooo'); await tester.pumpAndSettle(); expect(state.filteredClassList.value.isEmpty, true); // Clear filter await clearFilter(tester, controller); }); testWidgetsWithWindowSize( 'persisted tracing state', windowSize, (tester) async { await pumpScene(tester); final controller = scene.controller.controllers.tracing; final state = controller.stateForIsolate.value; final checkboxes = find.byType(Checkbox); expect(checkboxes, findsNWidgets(classList.classes!.length)); // Enable allocation tracing for one of them await tester.tap(checkboxes.first); await tester.pumpAndSettle(); final tracedClassList = state.filteredClassList.value .where((e) => e.traceAllocations) .toList(); expect(tracedClassList.length, 1); expect(tracedClassList.first.cls, classList.classes!.first); // Filter out all classes and then clear the filter final filterTextField = find.byType(DevToolsClearableTextField); expect(filterTextField, findsOneWidget); await tester.enterText(filterTextField, 'Garbage'); await tester.pumpAndSettle(); expect(state.filteredClassList.value.isEmpty, true); await clearFilter(tester, controller); // Check tracing state wasn't corrupted final updatedTracedClassList = state.filteredClassList.value .where((e) => e.traceAllocations) .toList(); expect(updatedTracedClassList, containsAll(tracedClassList)); expect(updatedTracedClassList.first.traceAllocations, true); }, ); testWidgetsWithWindowSize( 'persisted selection state', windowSize, (tester) async { await pumpScene(tester); final controller = scene.controller.controllers.tracing; final state = controller.stateForIsolate.value; expect(state.selectedTracedClass.value, isNull); // Select one of the class entries. final selection = find.richTextContaining( classList.classes!.last.name!, ); expect(selection, findsOneWidget); await tester.tap(selection); await tester.pumpAndSettle(); expect(state.selectedTracedClass.value, isNotNull); final originalSelection = state.selectedTracedClass.value; // Filter out all classes, ensure the selection is still valid, then // clear the filter and check again. final filterTextField = find.byType(DevToolsClearableTextField); expect(filterTextField, findsOneWidget); await tester.enterText(filterTextField, 'Garbage'); await tester.pumpAndSettle(); expect(state.filteredClassList.value.isEmpty, true); expect(state.selectedTracedClass.value, originalSelection); await clearFilter(tester, controller); expect(state.selectedTracedClass.value, originalSelection); }, ); }); }); }
devtools/packages/devtools_app/test/memory/tracing/tracing_view_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/memory/tracing/tracing_view_test.dart", "repo_id": "devtools", "token_count": 7009 }
127
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app_shared/service.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; // TODO(kenz): add better test coverage for [PerformanceController]. void main() { late PerformanceController controller; late MockServiceConnectionManager mockServiceConnection; group('$PerformanceController', () { setUp(() { setGlobal(IdeTheme, IdeTheme()); setGlobal(OfflineModeController, OfflineModeController()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); mockServiceConnection = createMockServiceConnectionWithDefaults(); final mockServiceManager = mockServiceConnection.serviceManager as MockServiceManager; final connectedApp = MockConnectedApp(); mockConnectedApp( connectedApp, isFlutterApp: true, isProfileBuild: false, isWebApp: false, ); when(mockServiceManager.connectedApp).thenReturn(connectedApp); when(mockServiceManager.connectedState) .thenReturn(ValueNotifier(const ConnectedState(true))); setGlobal(ServiceConnectionManager, mockServiceConnection); offlineController.enterOfflineMode( offlineApp: serviceConnection.serviceManager.connectedApp!, ); controller = PerformanceController(); }); test('setActiveFeature', () async { expect(controller.flutterFramesController.isActiveFeature, isFalse); expect(controller.timelineEventsController.isActiveFeature, isFalse); expect(controller.rasterStatsController.isActiveFeature, isFalse); await controller.setActiveFeature(controller.timelineEventsController); expect(controller.flutterFramesController.isActiveFeature, isTrue); expect(controller.timelineEventsController.isActiveFeature, isTrue); expect(controller.rasterStatsController.isActiveFeature, isFalse); await controller.setActiveFeature(controller.rasterStatsController); expect(controller.flutterFramesController.isActiveFeature, isTrue); expect(controller.timelineEventsController.isActiveFeature, isFalse); expect(controller.rasterStatsController.isActiveFeature, isTrue); }); }); }
devtools/packages/devtools_app/test/performance/performance_controller_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/performance/performance_controller_test.dart", "repo_id": "devtools", "token_count": 863 }
128
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools.dart' as devtools; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/framework/about_dialog.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; void main() { late DevToolsAboutDialog aboutDialog; group('About Dialog', () { setUp(() { aboutDialog = DevToolsAboutDialog(ReleaseNotesController()); final fakeServiceConnection = FakeServiceConnectionManager(); when(fakeServiceConnection.serviceManager.vm.version).thenReturn('1.9.1'); when(fakeServiceConnection.serviceManager.vm.targetCPU) .thenReturn('arm64'); when(fakeServiceConnection.serviceManager.vm.architectureBits) .thenReturn(64); when(fakeServiceConnection.serviceManager.vm.operatingSystem) .thenReturn('android'); mockConnectedApp( fakeServiceConnection.serviceManager.connectedApp!, isFlutterApp: true, isProfileBuild: false, isWebApp: false, ); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(IdeTheme, IdeTheme()); }); testWidgets('builds dialog', (WidgetTester tester) async { await tester.pumpWidget(wrap(aboutDialog)); expect(find.text('About DevTools'), findsOneWidget); }); testWidgets('content renders correctly', (WidgetTester tester) async { await tester.pumpWidget(wrap(aboutDialog)); expect(find.text('About DevTools'), findsOneWidget); expect(findSubstring(devtools.version), findsOneWidget); expect(find.text('release notes'), findsOneWidget); expect(find.textContaining('Encountered an issue?'), findsOneWidget); expect( findSubstring('github.com/flutter/devtools/issues/new'), findsOneWidget, ); expect(find.text('Contributing'), findsOneWidget); expect( find.textContaining('Want to contribute to DevTools?'), findsOneWidget, ); expect(findSubstring('CONTRIBUTING'), findsOneWidget); expect(find.textContaining('connect with us on'), findsOneWidget); expect( findSubstring('Discord'), findsOneWidget, ); }); }); }
devtools/packages/devtools_app/test/shared/about_dialog_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/about_dialog_test.dart", "repo_id": "devtools", "token_count": 983 }
129
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('vm') import 'package:devtools_app/src/shared/primitives/custom_pointer_scroll_view.dart'; import 'package:devtools_app/src/shared/primitives/extent_delegate_list.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('ExtentDelegateListView', () { final children = [1.0, 2.0, 3.0, 4.0]; Future<void> wrapAndPump( WidgetTester tester, Widget listView, ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: listView, ), ); } testWidgets('builds successfully', (tester) async { await wrapAndPump( tester, ExtentDelegateListView( controller: ScrollController(), extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ); for (final child in children) { expect(find.text('$child'), findsOneWidget); } }); testWidgets( 'builds successfully with customPointerSignalHandler', (tester) async { int pointerSignalEventCount = 0; void handlePointerSignal(PointerSignalEvent _) { pointerSignalEventCount++; } await wrapAndPump( tester, ExtentDelegateListView( controller: ScrollController(), extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), customPointerSignalHandler: handlePointerSignal, ), ); final scrollEventLocation = tester.getCenter(find.byType(ExtentDelegateListView)); final testPointer = TestPointer(1, PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when // generating the scroll. testPointer.hover(scrollEventLocation); await tester.sendEventToBinding( testPointer.scroll(const Offset(0.0, 10.0)), ); expect(pointerSignalEventCount, equals(1)); }, ); testWidgets( 'inherits PrimaryScrollController automatically', (tester) async { final ScrollController controller = ScrollController(); await wrapAndPump( tester, PrimaryScrollController( controller: controller, child: ExtentDelegateListView( extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ), ); expect(controller.hasClients, isTrue); }, ); testWidgets('inherits PrimaryScrollController explicitly', (tester) async { final ScrollController controller = ScrollController(); await wrapAndPump( tester, PrimaryScrollController( controller: controller, child: ExtentDelegateListView( primary: true, extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ), ); expect(controller.hasClients, isTrue); }); testWidgets( 'inherits PrimaryScrollController explicitly - horizontal', (tester) async { final ScrollController controller = ScrollController(); await wrapAndPump( tester, PrimaryScrollController( controller: controller, child: ExtentDelegateListView( primary: true, scrollDirection: Axis.horizontal, extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ), ); expect(controller.hasClients, isTrue); }, ); testWidgets( 'does not inherit PrimaryScrollController - horizontal', (tester) async { final ScrollController controller = ScrollController(); await wrapAndPump( tester, PrimaryScrollController( controller: controller, child: ExtentDelegateListView( controller: ScrollController(), scrollDirection: Axis.horizontal, extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ), ); expect(controller.hasClients, isFalse); }, ); testWidgets( 'does not inherit PrimaryScrollController - explicitly set', (tester) async { final ScrollController controller = ScrollController(); await wrapAndPump( tester, PrimaryScrollController( controller: controller, child: ExtentDelegateListView( primary: false, controller: ScrollController(), scrollDirection: Axis.horizontal, extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ), ); expect(controller.hasClients, isFalse); }, ); testWidgets( 'does not inherit PrimaryScrollController - other controller set', (tester) async { final ScrollController primaryController = ScrollController(); final ScrollController listController = ScrollController(); await wrapAndPump( tester, PrimaryScrollController( controller: primaryController, child: ExtentDelegateListView( controller: listController, scrollDirection: Axis.horizontal, extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ), ); expect(primaryController.hasClients, isFalse); expect(listController.hasClients, isTrue); }, ); testWidgets('asserts there is a scroll controller', (tester) async { final ScrollController controller = ScrollController(); await wrapAndPump( tester, PrimaryScrollController( controller: controller, child: ExtentDelegateListView( scrollDirection: Axis.horizontal, extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) => Text('${children[index]}'), childCount: children.length, ), ), ), ); final AssertionError error = tester.takeException() as AssertionError; expect( error.message, 'No ScrollController has been provided to the CustomPointerScrollView.', ); }); testWidgets('implements devicePixelRatio', (tester) async { late final BuildContext capturedContext; await wrapAndPump( tester, ExtentDelegateListView( controller: ScrollController(), extentDelegate: FixedExtentDelegate( computeLength: () => children.length, computeExtent: (index) => children[index], ), childrenDelegate: SliverChildBuilderDelegate( (context, index) { if (index == 0) { capturedContext = context; } return Text('${children[index]}'); }, childCount: children.length, ), ), ); expect( CustomPointerScrollable.of(capturedContext)!.devicePixelRatio, 3.0, ); }); }); }
devtools/packages/devtools_app/test/shared/extent_delegate_list_view_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/extent_delegate_list_view_test.dart", "repo_id": "devtools", "token_count": 4474 }
130
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/shared/primitives/message_bus.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { defineTests(); } void defineTests() { group('message_bus', () { test('fire one event', () async { final MessageBus bus = MessageBus(); final Future<List<BusEvent>> future = bus.onEvent(type: 'app.restart').toList(); _fireEvents(bus); bus.close(); final List<BusEvent> list = await future; expect(list, hasLength(1)); }); test('fire two events', () async { final MessageBus bus = MessageBus(); final Future<List<BusEvent>> future = bus.onEvent(type: 'file.saved').toList(); _fireEvents(bus); bus.close(); final List<BusEvent> list = await future; expect(list, hasLength(2)); expect(list[0].data, 'foo.dart'); expect(list[1].data, 'bar.dart'); }); test('receive all events', () async { final MessageBus bus = MessageBus(); final Future<List<BusEvent>> future = bus.onEvent().toList(); _fireEvents(bus); bus.close(); final List<BusEvent> list = await future; expect(list, hasLength(3)); }); }); } void _fireEvents(MessageBus bus) { bus.addEvent(BusEvent('app.restart')); bus.addEvent(BusEvent('file.saved', data: 'foo.dart')); bus.addEvent(BusEvent('file.saved', data: 'bar.dart')); }
devtools/packages/devtools_app/test/shared/message_bus_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/message_bus_test.dart", "repo_id": "devtools", "token_count": 606 }
131
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/shared/server/server_api_client.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('computes the correct api URI', () { const apiUriFor = DevToolsServerConnection.apiUriFor; test('for a root URI without trailing slash', () { expect( apiUriFor(Uri.parse('https://localhost:123?uri=x')), Uri.parse('https://localhost:123/api/'), ); }); test('for a root URI with trailing slash', () { expect( apiUriFor(Uri.parse('https://localhost:123/?uri=x')), Uri.parse('https://localhost:123/api/'), ); }); test('for a /devtools/ URI with trailing slash', () { expect( apiUriFor(Uri.parse('https://localhost:123/devtools/?uri=x')), Uri.parse('https://localhost:123/devtools/api/'), ); }); test('for a /devtools URI without trailing slash', () { expect( apiUriFor(Uri.parse('https://localhost:123/devtools?uri=x')), Uri.parse('https://localhost:123/devtools/api/'), ); }); test('for a /devtools/inspector URI', () { expect( apiUriFor(Uri.parse('https://localhost:123/devtools/inspector?uri=x')), Uri.parse('https://localhost:123/devtools/api/'), ); }); }); }
devtools/packages/devtools_app/test/shared/server_api_client_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/server_api_client_test.dart", "repo_id": "devtools", "token_count": 590 }
132
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/screens/inspector/layout_explorer/ui/widgets_theme.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('Test WidgetTheme', () { test('Correct asset from widget with a type', () { const String widgetName = 'AnimatedBuilder<String>'; final theme = WidgetTheme.fromName(widgetName); expect(theme.iconAsset, 'icons/inspector/widget_icons/animated.png'); }); test('Has default theme for custom widget', () { const String widgetName = 'CustomWidget'; final theme = WidgetTheme.fromName(widgetName); expect(theme.color, WidgetTheme.otherWidgetColor); }); }); }
devtools/packages/devtools_app/test/shared/widget_theme_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/widget_theme_test.dart", "repo_id": "devtools", "token_count": 278 }
133
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/standalone_ui/vs_code/flutter_panel.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import 'package:stager/stager.dart'; import '../../../test_infra/test_data/dart_tooling_api/mock_api.dart'; import 'vs_code_mock_editor.dart'; final _api = FakeDartToolingApi(); /// To run, use the "standalone_ui/vs_code" launch configuration with the /// `devtools/packages/` folder open in VS Code, or run: /// /// flutter run -t test/test_infra/scenes/standalone_ui/vs_code.stager_app.g.dart --dart-define=enable_experiments=true -d chrome class VsCodeScene extends Scene { late PerformanceController controller; @override Widget build(BuildContext context) { return MaterialApp( theme: themeFor( isDarkTheme: false, ideTheme: _ideTheme(const VsCodeTheme.light()), theme: ThemeData(useMaterial3: true, colorScheme: lightColorScheme), ), darkTheme: themeFor( isDarkTheme: true, ideTheme: _ideTheme(const VsCodeTheme.dark()), theme: ThemeData(useMaterial3: true, colorScheme: darkColorScheme), ), home: Scaffold( body: VsCodeFlutterPanelMockEditor( api: _api, child: VsCodeFlutterPanel(_api), ), ), ); } /// Creates an [IdeTheme] using the colours from the mock editor. IdeTheme _ideTheme(VsCodeTheme vsCodeTheme) { return IdeTheme( backgroundColor: vsCodeTheme.editorBackgroundColor, foregroundColor: vsCodeTheme.foregroundColor, embed: true, ); } @override String get title => '$VsCodeScene'; @override Future<void> setUp() async { setStagerMode(); setGlobal(IdeTheme, IdeTheme()); setGlobal(PreferencesController, PreferencesController()); } }
devtools/packages/devtools_app/test/test_infra/scenes/standalone_ui/vs_code.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/scenes/standalone_ui/vs_code.dart", "repo_id": "devtools", "token_count": 769 }
134
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:vm_service/vm_service.dart'; final testLib = Library( id: testLibRef.id!, uri: testLibRef.uri!, name: testLibRef.name!, dependencies: <LibraryDependency>[], classes: [testClass], scripts: [testScript], variables: [], functions: [], ); final testLibRef = LibraryRef( name: 'fooLib', uri: 'fooScript.dart', id: '1234', ); final testClassRef = ClassRef( id: '1234', name: 'FooClass', library: testLibRef, location: SourceLocation( script: testScript, tokenPos: 10, line: 10, ), ); final testClass = Class( name: testClassRef.name, library: testClassRef.library, isAbstract: false, isConst: false, traceAllocations: false, superClass: testSuperClass, superType: testSuperType, fields: [testField], functions: [testFunction], id: '1234', location: testClassRef.location, ); // We need to invoke `Script.parse` to build the internal token position table. final testScript = Script.parse( Script( uri: 'fooScript.dart', library: testLibRef, id: '1234', tokenPosTable: [ [10, 10, 1], [20, 20, 1], [30, 30, 1], ], ).toJson(), )!; final testFunction = Func( name: 'fooFunction', owner: testClassRef, isStatic: false, isConst: false, implicit: false, location: SourceLocation( script: testScript, tokenPos: 20, line: 20, ), signature: InstanceRef(id: '1234'), id: '1234', ); final testField = Field( name: 'fooField', location: SourceLocation( script: testScript, tokenPos: 30, line: 30, ), declaredType: InstanceRef(id: '1234'), owner: testClassRef, isStatic: false, isConst: false, isFinal: false, id: '1234', ); final testSuperClass = ClassRef( name: 'fooSuperClass', library: testLibRef, id: '1234', ); final testSuperType = InstanceRef( kind: '', id: '1234', name: 'fooSuperType', );
devtools/packages/devtools_app/test/test_infra/test_data/debugger/vm_service_object_tree.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/test_data/debugger/vm_service_object_tree.dart", "repo_id": "devtools", "token_count": 769 }
135
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. void simplePrint() { print('hello world'); } noReturnValue() { print('hello world'); } Future<void> asyncPrint() async { await Future.delayed(const Duration(seconds: 1)); print('hello world'); }
devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/functions.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/functions.dart", "repo_id": "devtools", "token_count": 108 }
136
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/debugger/program_explorer.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/object_inspector_view.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/object_viewport.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:vm_service/vm_service.dart'; import '../vm_developer_test_utils.dart'; void main() { late ObjectInspectorView objectInspector; late FakeServiceConnectionManager fakeServiceConnection; late MockScriptManager scriptManager; const windowSize = Size(2560.0, 1338.0); setUp(() { objectInspector = ObjectInspectorView(); fakeServiceConnection = FakeServiceConnectionManager(); scriptManager = MockScriptManager(); when(scriptManager.sortedScripts).thenReturn( ValueNotifier(<ScriptRef>[testScript]), ); // ignore: discarded_futures, test code. when(scriptManager.retrieveAndSortScripts(any)).thenAnswer( (_) => Future.value([testScript]), ); when(fakeServiceConnection.serviceManager.connectedApp!.isProfileBuildNow) .thenReturn(false); when(fakeServiceConnection.serviceManager.connectedApp!.isDartWebAppNow) .thenReturn(false); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(ScriptManager, scriptManager); setGlobal(IdeTheme, IdeTheme()); setGlobal(NotificationService, NotificationService()); VmServiceWrapper.enablePrivateRpcs = true; }); testWidgetsWithWindowSize( 'builds screen', windowSize, (WidgetTester tester) async { await tester.pumpWidget( wrapWithControllers( Builder( builder: objectInspector.build, ), vmDeveloperTools: VMDeveloperToolsController( objectInspectorViewController: ObjectInspectorViewController( classHierarchyController: TestClassHierarchyExplorerController(), ), ), ), ); expect(find.byType(SplitPane), findsNWidgets(2)); expect(find.byType(ProgramExplorer), findsOneWidget); expect(find.byType(ObjectViewport), findsOneWidget); expect(find.text('Program Explorer'), findsOneWidget); expect(find.text('Outline'), findsOneWidget); expect(find.text('No object selected.'), findsOneWidget); expect(find.byTooltip('Refresh'), findsOneWidget); }, ); }
devtools/packages/devtools_app/test/vm_developer/object_inspector/object_inspector_view_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/vm_developer/object_inspector/object_inspector_view_test.dart", "repo_id": "devtools", "token_count": 1082 }
137
<!DOCTYPE html> <!-- Copyright 2018 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Note: This tag is replaced when served through DDS! --> <base href="/"> <title></title> <link href="favicon.png" rel="icon" sizes="64x64"> <!-- Global site tag (gtag.js) - Google Analytics --> <script> // The value of DEVTOOLS_GOOGLE_TAG_ID here must match the value of the '?id=' // query parameter below in the 'https://www.googletagmanager.com' script. // This is the value of the "Dart DevTools - GA4" Google Tag, which is linked // to the DevTools GA4 analytics property. const DEVTOOLS_GOOGLE_TAG_ID = 'G-69MPZE94D5'; // function getDevToolsPropertyID() { return DEVTOOLS_GOOGLE_TAG_ID; } </script> <!-- The below URI ?id= must match the DEVTOOLS_GOOGLE_TAG_ID above. --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-69MPZE94D5"></script> <script src="devtools_analytics.js"></script> <!-- End of DevTools Google Analytics --> <!-- DO NOT REMOVE: --> <!-- OBSERVER SCRIPT PLACEHOLDER --> <script> function supportsES6Classes() { "use strict"; try { eval("class Foo {}"); } catch (e) { return false; } return true; } if (!supportsES6Classes()) { window.location.href = '/unsupported-browser.html'; } </script> <script> // The value below is injected by flutter build, do not touch. var serviceWorkerVersion = null; </script> <!-- This script adds the flutter initialization JS code --> <script src="flutter.js" defer></script> <!-- TODO(elliette): Remove once https://github.com/flutter/flutter/issues/122541 is fixed. --> <link rel="stylesheet" href="styles.css"> </head> <body> <script> // Unregister the old custom DevTools service worker (if it exists). It was // removed in: https://github.com/flutter/devtools/pull/5331 function unregisterDevToolsServiceWorker() { if ('serviceWorker' in navigator) { const DEVTOOLS_SW = 'service_worker.js'; const FLUTTER_SW = 'flutter_service_worker.js'; navigator.serviceWorker.getRegistrations().then(function(registrations) { for (let registration of registrations) { const activeWorker = registration.active; if (activeWorker != null) { const url = activeWorker.scriptURL; if (url.includes(DEVTOOLS_SW) && !url.includes(FLUTTER_SW)) { registration.unregister(); } } } }); } } // Bootstrap app for 3P environments: function bootstrapAppFor3P() { window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, }, onEntrypointLoaded: function(engineInitializer) { engineInitializer.initializeEngine({ renderer: 'canvaskit', canvasKitBaseUrl: 'canvaskit/' }) .then(function(appRunner) { appRunner.runApp(); }); } }); }); } // Bootstrap app for 1P environments: function bootstrapAppFor1P() { window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ entrypointUrl: 'main.dart.js', onEntrypointLoaded: function(engineInitializer) { engineInitializer.initializeEngine({ renderer: 'canvaskit', }) .then(function(appRunner) { appRunner.runApp(); }); } }); }); } unregisterDevToolsServiceWorker(); bootstrapAppFor3P(); </script> </body> </html>
devtools/packages/devtools_app/web/index.html/0
{ "file_path": "devtools/packages/devtools_app/web/index.html", "repo_id": "devtools", "token_count": 1733 }
138
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/utils.dart'; /// This example demonstrates using shared utility methods from /// 'package:devtools_app_shared/utils.dart'. void main() { helperExample(); immediateValueNotifierExample(); } /// This method demonstrates using a helper methods [pluralize] and /// [equalsWithinEpsilon] provided by 'package:devtools_app_shared/utils.dart'. /// /// Other helper methods in this file can be used in a similar manner, as they /// are documented. void helperExample() { pluralize('dog', 1); // 'dog' pluralize('dog', 2); // 'dogs' pluralize('dog', 0); // 'dogs' pluralize('index', 1, plural: 'indices'); // 'index' pluralize('index', 2, plural: 'indices'); // 'indices' // Note: the [defaultEpsilon] this method uses is equal to 1 / 1000. // [defaultEpsilon] is also exposed by 'utils.dart'. equalsWithinEpsilon(1.111, 1.112); // true equalsWithinEpsilon(1.111, 1.113); // false } /// This method demonstrates using an [ImmediateValueNotifier] from /// 'package:devtools_app_shared/utils.dart'. void immediateValueNotifierExample() { final fooNotifier = ImmediateValueNotifier<int>(0); var count = 0; fooNotifier.addListener(() { count++; }); print('count: $count'); // count = 1, since the listener is called immediately // change the value of the notifier to trigger the listener. fooNotifier.value = 1; print('count: $count'); // count = 2 }
devtools/packages/devtools_app_shared/example/utils/utils_example.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/example/utils/utils_example.dart", "repo_id": "devtools", "token_count": 485 }
139
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'eval_on_dart_library.dart'; import 'flutter_version.dart'; import 'service_manager.dart'; final _log = Logger('connected_app'); const flutterLibraryUri = 'package:flutter/src/widgets/binding.dart'; // TODO(kenz): if we want to support debugging dart2wasm web apps, we will need // to check for the presence of a different library. const dartHtmlLibraryUri = 'dart:html'; // TODO(https://github.com/flutter/devtools/issues/6239): try to remove this. @sealed class ConnectedApp { ConnectedApp(this.serviceManager); static const isFlutterAppKey = 'isFlutterApp'; static const isProfileBuildKey = 'isProfileBuild'; static const isDartWebAppKey = 'isDartWebApp'; static const isRunningOnDartVMKey = 'isRunningOnDartVM'; static const operatingSystemKey = 'operatingSystem'; static const flutterVersionKey = 'flutterVersion'; final ServiceManager? serviceManager; Completer<bool> initialized = Completer(); bool get connectedAppInitialized => _isFlutterApp != null && (_isFlutterApp == false || _isDartWebApp == true || _flutterVersion != null) && _isProfileBuild != null && _isDartWebApp != null && _operatingSystem != null; static const unknownOS = 'unknown_OS'; String get operatingSystem => _operatingSystem!; String? _operatingSystem; // TODO(kenz): investigate if we can use `libraryUriAvailableNow` instead. Future<bool> get isFlutterApp async => _isFlutterApp ??= await serviceManager!.libraryUriAvailable(flutterLibraryUri); bool? get isFlutterAppNow { assert(_isFlutterApp != null); return _isFlutterApp == true; } bool? _isFlutterApp; FlutterVersion? get flutterVersionNow { return isFlutterAppNow! ? _flutterVersion : null; } FlutterVersion? _flutterVersion; final _flutterVersionCompleter = Completer<FlutterVersion?>(); static const _flutterVersionTimeout = Duration(seconds: 3); Future<bool> get isProfileBuild async { _isProfileBuild ??= await _connectedToProfileBuild(); return _isProfileBuild!; } bool? get isProfileBuildNow { assert(_isProfileBuild != null); return _isProfileBuild!; } bool? _isProfileBuild; // TODO(kenz): investigate if we can use `libraryUriAvailableNow` instead. Future<bool> get isDartWebApp async => _isDartWebApp ??= await serviceManager!.libraryUriAvailable(dartHtmlLibraryUri); bool? get isDartWebAppNow { assert(_isDartWebApp != null); return _isDartWebApp!; } bool? _isDartWebApp; bool get isFlutterWebAppNow => isFlutterAppNow! && isDartWebAppNow!; bool get isFlutterNativeAppNow => isFlutterAppNow! && !isDartWebAppNow!; bool get isDebugFlutterAppNow => isFlutterAppNow! && !isProfileBuildNow!; bool? get isRunningOnDartVM => serviceManager!.vm!.name != 'ChromeDebugProxy'; Future<bool> get isDartCliApp async => isRunningOnDartVM! && !(await isFlutterApp); bool get isDartCliAppNow => isRunningOnDartVM! && !isFlutterAppNow!; Future<bool> _connectedToProfileBuild() async { // If Dart or Flutter web, assume profile is false. if (!isRunningOnDartVM!) { return false; } // If eval works we're not a profile build. final io = EvalOnDartLibrary( 'dart:io', serviceManager!.service!, serviceManager: serviceManager!, ); // Do not log the error if this eval fails - we expect it to fail for a // profile build. final value = await io.eval( 'Platform.isAndroid', isAlive: null, shouldLogError: false, ); return !(value?.kind == 'Bool'); // TODO(terry): Disabled below code, it will hang if flutter run --start-paused // see issue https://github.com/flutter/devtools/issues/2082. // Currently, if eval (see above) doesn't work then we're // running in Profile mode. /* assert(serviceConnectionManager.isServiceAvailable); // Only flutter apps have profile and non-profile builds. If this changes in // the future (flutter web), we can modify this check. if (!isRunningOnDartVM || !await isFlutterApp) return false; await serviceConnectionManager.manager.serviceExtensionManager.extensionStatesUpdated.future; // The debugAllowBanner extension is only available in debug builds final hasDebugExtension = serviceConnectionManager.manager.serviceExtensionManager .isServiceExtensionAvailable(extensions.debugAllowBanner.extension); return !hasDebugExtension; */ } Future<void> initializeValues({void Function()? onComplete}) async { // Return early if already initialized. if (initialized.isCompleted) return; assert(serviceManager!.isServiceAvailable); await Future.wait([isFlutterApp, isProfileBuild, isDartWebApp]); _operatingSystem = serviceManager!.vm!.operatingSystem ?? unknownOS; if (isFlutterAppNow!) { final flutterVersionServiceListenable = serviceManager! .registeredServiceListenable(flutterVersionService.service); void Function() listener; flutterVersionServiceListenable.addListener( listener = () async { final registered = flutterVersionServiceListenable.value; if (registered) { _flutterVersionCompleter.complete( FlutterVersion.parse( (await serviceManager!.flutterVersion).json!, ), ); } }, ); _flutterVersion = await _flutterVersionCompleter.future.timeout( _flutterVersionTimeout, onTimeout: () { _log.info( 'Timed out trying to fetch flutter version from ' '`ConnectedApp.initializeValues`.', ); return Future<FlutterVersion?>.value(FlutterVersion.unknown()); }, ); flutterVersionServiceListenable.removeListener(listener); } onComplete?.call(); initialized.complete(true); } Map<String, Object?> toJson() => { isFlutterAppKey: isFlutterAppNow, isProfileBuildKey: isProfileBuildNow, isDartWebAppKey: isDartWebAppNow, isRunningOnDartVMKey: isRunningOnDartVM, operatingSystemKey: operatingSystem, if (flutterVersionNow != null && !flutterVersionNow!.unknown) flutterVersionKey: flutterVersionNow!.version, }; } final class OfflineConnectedApp extends ConnectedApp { OfflineConnectedApp({ this.isFlutterAppNow, this.isProfileBuildNow, this.isDartWebAppNow, this.isRunningOnDartVM, this.operatingSystem = ConnectedApp.unknownOS, }) : super(null); factory OfflineConnectedApp.parse(Map<String, Object?>? json) { if (json == null) return OfflineConnectedApp(); return OfflineConnectedApp( isFlutterAppNow: json[ConnectedApp.isFlutterAppKey] as bool?, isProfileBuildNow: json[ConnectedApp.isProfileBuildKey] as bool?, isDartWebAppNow: json[ConnectedApp.isDartWebAppKey] as bool?, isRunningOnDartVM: json[ConnectedApp.isRunningOnDartVMKey] as bool?, operatingSystem: (json[ConnectedApp.operatingSystemKey] as String?) ?? ConnectedApp.unknownOS, ); } @override final bool? isFlutterAppNow; @override final bool? isProfileBuildNow; @override final bool? isDartWebAppNow; @override final bool? isRunningOnDartVM; @override final String operatingSystem; }
devtools/packages/devtools_app_shared/lib/src/service/connected_app.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/service/connected_app.dart", "repo_id": "devtools", "token_count": 2745 }
140
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:logging/logging.dart'; import 'package:web/web.dart'; import '../../utils/url/url.dart'; import '../../utils/utils.dart'; import 'ide_theme.dart'; import 'theme.dart'; final _log = Logger('ide_theme_web'); /// Load any IDE-supplied theming. IdeTheme getIdeTheme() { final queryParams = loadQueryParams(); final overrides = IdeTheme( backgroundColor: _tryParseColor(queryParams['backgroundColor']), foregroundColor: _tryParseColor(queryParams['foregroundColor']), fontSize: _tryParseDouble(queryParams['fontSize']) ?? unscaledDefaultFontSize, embed: queryParams['embed'] == 'true', isDarkMode: queryParams['theme'] != 'light', ); // If the environment has provided a background color, set it immediately // to avoid a white page until the first Flutter frame is rendered. if (overrides.backgroundColor != null) { document.body!.style.backgroundColor = toCssHexColor(overrides.backgroundColor!); } return overrides; } Color? _tryParseColor(String? input) { if (input == null) return null; try { return parseCssHexColor(input); } catch (e, st) { // The user can manipulate the query string so if the value is invalid // print the value but otherwise continue. _log.warning( 'Failed to parse "$input" as a color from the querystring, ignoring: $e', e, st, ); return null; } } double? _tryParseDouble(String? input) { try { if (input != null) { return double.parse(input); } } catch (e, st) { // The user can manipulate the query string so if the value is invalid // print the value but otherwise continue. _log.warning( 'Failed to parse "$input" as a double from the querystring, ignoring: $e', e, st, ); } return null; }
devtools/packages/devtools_app_shared/lib/src/ui/theme/_ide_theme_web.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/ui/theme/_ide_theme_web.dart", "repo_id": "devtools", "token_count": 699 }
141
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/service.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('FlutterVersion', () { test('infers semantic version', () { var flutterVersion = FlutterVersion.parse({'frameworkVersion': '1.10.7-pre.42'}); expect(flutterVersion.major, equals(1)); expect(flutterVersion.minor, equals(10)); expect(flutterVersion.patch, equals(7)); expect(flutterVersion.preReleaseMajor, equals(42)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '1.10.7-pre42'}); expect(flutterVersion.major, equals(1)); expect(flutterVersion.minor, equals(10)); expect(flutterVersion.patch, equals(7)); expect(flutterVersion.preReleaseMajor, equals(42)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '1.10.11-pre42'}); expect(flutterVersion.major, equals(1)); expect(flutterVersion.minor, equals(10)); expect(flutterVersion.patch, equals(11)); expect(flutterVersion.preReleaseMajor, equals(42)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0-17.0.pre.355'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, equals(17)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0-17.0.pre'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, equals(17)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0-17'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, equals(17)); expect(flutterVersion.preReleaseMinor, equals(0)); flutterVersion = FlutterVersion.parse({'frameworkVersion': '2.3.0'}); expect(flutterVersion.major, equals(2)); expect(flutterVersion.minor, equals(3)); expect(flutterVersion.patch, equals(0)); expect(flutterVersion.preReleaseMajor, isNull); expect(flutterVersion.preReleaseMinor, isNull); flutterVersion = FlutterVersion.parse({'frameworkVersion': 'bad-version'}); expect(flutterVersion.major, equals(0)); expect(flutterVersion.minor, equals(0)); expect(flutterVersion.patch, equals(0)); }); test('parses dart version correctly', () { var flutterVersion = FlutterVersion.parse({ 'frameworkVersion': '2.8.0', 'dartSdkVersion': '2.15.0', }); expect(flutterVersion.dartSdkVersion.toString(), equals('2.15.0')); flutterVersion = FlutterVersion.parse({ 'frameworkVersion': '2.8.0', 'dartSdkVersion': '2.15.0 (build 2.15.0-178.1.beta)', }); expect(flutterVersion.dartSdkVersion.toString(), equals('2.15.0-178.1')); }); }); }
devtools/packages/devtools_app_shared/test/service/flutter_version_test.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/test/service/flutter_version_test.dart", "repo_id": "devtools", "token_count": 1370 }
142
#import "GeneratedPluginRegistrant.h"
devtools/packages/devtools_extensions/example/app_that_uses_foo/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "devtools/packages/devtools_extensions/example/app_that_uses_foo/ios/Runner/Runner-Bridging-Header.h", "repo_id": "devtools", "token_count": 13 }
143
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of 'devtools_extension.dart'; final _log = Logger('devtools_extensions/extension_manager'); const _vmServiceQueryParameter = 'uri'; const _dtdQueryParameter = 'dtdUri'; class ExtensionManager { final _registeredEventHandlers = <DevToolsExtensionEventType, ExtensionEventHandler>{}; /// Whether dark theme is enabled for DevTools. /// /// The DevTools extension will rebuild with the appropriate theme on /// notifications from this notifier. final darkThemeEnabled = ValueNotifier<bool>(useDarkThemeAsDefault); /// Registers an event handler for [DevToolsExtensionEvent]s of type [type]. /// /// When an event of type [type] is received by the extension, [handler] will /// be called after any default event handling takes place for event [type]. /// See [_handleExtensionEvent]. void registerEventHandler( DevToolsExtensionEventType type, ExtensionEventHandler handler, ) { _registeredEventHandlers[type] = handler; } /// Unregisters an event handler for [DevToolsExtensionEvent]s of type [type] /// that was originally registered by calling [registerEventHandler]. void unregisterEventHandler(DevToolsExtensionEventType type) { _registeredEventHandlers.remove(type); } /// The listener that is added to the extension iFrame to receive messages /// from DevTools. /// /// We need to store this in a variable so that the listener is properly /// removed in [dispose]. EventListener? _handleMessageListener; // ignore: unused_element, false positive due to part files Future<void> _init({required bool connectToVmService}) async { window.addEventListener( 'message', _handleMessageListener = _handleMessage.toJS, ); // TODO(kenz): handle the ide theme that may be part of the query params. final queryParams = loadQueryParams(); final themeValue = queryParams[ExtensionEventParameters.theme]; _setThemeForValue(themeValue); final dtdUri = queryParams[_dtdQueryParameter]; if (dtdUri != null) { await _connectToDtd(dtdUri); } final vmServiceUri = queryParams[_vmServiceQueryParameter]; if (connectToVmService) { if (vmServiceUri == null) { // Request the vm service uri for the connected app. DevTools will // respond with a [DevToolsPluginEventType.connectedVmService] event // containing the currently connected app's vm service URI. postMessageToDevTools( DevToolsExtensionEvent( DevToolsExtensionEventType.vmServiceConnection, ), ); } else { unawaited(_connectToVmService(vmServiceUri)); } } } // ignore: unused_element, false positive due to part files void _dispose() { _registeredEventHandlers.clear(); window.removeEventListener('message', _handleMessageListener); _handleMessageListener = null; } void _handleMessage(Event e) { final extensionEvent = tryParseExtensionEvent(e); if (extensionEvent != null) { _handleExtensionEvent(extensionEvent, e as MessageEvent); } } void _handleExtensionEvent( DevToolsExtensionEvent extensionEvent, MessageEvent e, ) { // Ignore events that come from the [ExtensionManager] itself. if (extensionEvent.source == '$ExtensionManager') return; // Ignore events that are not supported for the DevTools => Extension // direction. if (!extensionEvent.type .supportedForDirection(ExtensionEventDirection.toExtension)) { return; } switch (extensionEvent.type) { case DevToolsExtensionEventType.ping: postMessageToDevTools( DevToolsExtensionEvent(DevToolsExtensionEventType.pong), targetOrigin: e.origin, ); break; case DevToolsExtensionEventType.vmServiceConnection: final vmServiceUri = extensionEvent .data?[ExtensionEventParameters.vmServiceConnectionUri] as String?; unawaited(_connectToVmService(vmServiceUri)); break; case DevToolsExtensionEventType.themeUpdate: final value = extensionEvent.data?[ExtensionEventParameters.theme] as String?; _setThemeForValue(value); break; case DevToolsExtensionEventType.forceReload: window.location.reload(); default: _log.warning( 'Unrecognized event received by extension: ' '(${extensionEvent.type} - ${e.data}', ); } _registeredEventHandlers[extensionEvent.type]?.call(extensionEvent); } /// Posts a [DevToolsExtensionEvent] to the DevTools extension host. /// /// If [targetOrigin] is null, the message will be posed to /// [html.window.origin]. /// /// When [_useSimulatedEnvironment] is true, this message will be posted /// to the same [html.window] that the extension is hosted in. void postMessageToDevTools( DevToolsExtensionEvent event, { String? targetOrigin, }) { final postWindow = _useSimulatedEnvironment ? window : window.parent; postWindow?.postMessage( { ...event.toJson(), DevToolsExtensionEvent.sourceKey: '$ExtensionManager', }.jsify(), (targetOrigin ?? window.origin).toJS, ); } Future<void> _connectToVmService(String? vmServiceUri) async { // TODO(kenz): investigate. this is weird but `vmServiceUri` != null even // when the `toString()` representation is 'null'. if (vmServiceUri == null || vmServiceUri == 'null') { if (serviceManager.hasConnection) { await serviceManager.manuallyDisconnect(); } if (loadQueryParams().containsKey(_vmServiceQueryParameter)) { _updateQueryParameter(_vmServiceQueryParameter, null); } return; } try { final finishedCompleter = Completer<void>(); final normalizedUri = normalizeVmServiceUri(vmServiceUri); if (normalizedUri == null) { throw Exception('unable to normalize uri because it is not absolute'); } final vmService = await connect<VmService>( uri: normalizedUri, finishedCompleter: finishedCompleter, serviceFactory: VmService.defaultFactory, ); await serviceManager.vmServiceOpened( vmService, onClosed: finishedCompleter.future, ); _updateQueryParameter( _vmServiceQueryParameter, serviceManager.serviceUri!, ); } catch (e) { final errorMessage = 'Unable to connect extension to VM service at $vmServiceUri: $e'; showNotification('Error: $errorMessage'); _log.shout(errorMessage); } } Future<void> _connectToDtd(String? dtdUri) async { // TODO(kenz): investigate. this is weird but `dtdUri` != null even // when the `toString()` representation is 'null'. if (dtdUri == null || dtdUri == 'null') { if (dtdManager.hasConnection) { await dtdManager.disconnect(); } if (loadQueryParams().containsKey(_dtdQueryParameter)) { _updateQueryParameter(_dtdQueryParameter, null); } return; } try { await dtdManager.connect(Uri.parse(dtdUri)); _updateQueryParameter( _dtdQueryParameter, dtdManager.uri.toString(), ); } catch (e) { final errorMessage = 'Unable to connect extension to the Dart Tooling Daemon at $dtdUri: $e'; showNotification('Error: $errorMessage'); _log.shout(errorMessage); } } void _setThemeForValue(String? themeValue) { final useDarkTheme = (themeValue == null && useDarkThemeAsDefault) || themeValue == ExtensionEventParameters.themeValueDark; darkThemeEnabled.value = useDarkTheme; // Use a post frame callback so that we do not try to update this while a // build is in progress. WidgetsBinding.instance.addPostFrameCallback((_) { _updateQueryParameter( 'theme', useDarkTheme ? ExtensionEventParameters.themeValueDark : ExtensionEventParameters.themeValueLight, ); }); } /// Show a notification in DevTools. /// /// This message will appear as a notification in the lower left corner of /// DevTools and will be automatically dismissed after a short time period /// (7 seconds). /// /// [message] the content of this notification. /// /// See also [ShowNotificationExtensionEvent]. void showNotification(String message) { postMessageToDevTools( ShowNotificationExtensionEvent(message: message), ); } /// Show a banner message in DevTools. /// /// This message will float at the top of the DevTools on an extension's /// screen until the user dismisses it. /// /// [key] should be a unique identifier for this particular message. This is /// how DevTools will determine whether this message has already been shown. /// /// [type] should be one of 'warning' or 'error', which will determine the /// styling of the banner message. /// /// [message] the content of this banner message. /// /// [extensionName] must match the 'name' field in your DevTools extension's /// `config.yaml` file. This should also match the name of the extension's /// parent package. /// /// When [ignoreIfAlreadyDismissed] is true (the default case), this message /// can only be shown and dismissed once. Any subsequent call to show the /// same banner message will be ignored by DevTools. If you intend for a /// banner message to be shown more than once, set this value to true or /// consider using [showNotification] instead, which shows a notification in /// DevTools that automatically dismisses after a short time period. /// /// See also [ShowBannerMessageExtensionEvent]. void showBannerMessage({ required String key, required String type, required String message, required String extensionName, bool ignoreIfAlreadyDismissed = true, }) { postMessageToDevTools( ShowBannerMessageExtensionEvent( id: key, bannerMessageType: type, message: message, extensionName: extensionName, ignoreIfAlreadyDismissed: ignoreIfAlreadyDismissed, ), ); } void _updateQueryParameter(String key, String? value) { final newQueryParams = Map.of(loadQueryParams()); if (value == null) { newQueryParams.remove(key); } else { newQueryParams[key] = value; } final newUri = Uri.parse(window.location.toString()) .replace(queryParameters: newQueryParams); window.history.replaceState( window.history.state, '', newUri.toString(), ); } }
devtools/packages/devtools_extensions/lib/src/template/extension_manager.dart/0
{ "file_path": "devtools/packages/devtools_extensions/lib/src/template/extension_manager.dart", "repo_id": "devtools", "token_count": 3734 }
144
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'adb_memory_info.dart'; import 'event_sample.dart'; /// DevTools Plotted and JSON persisted memory information. class HeapSample { HeapSample( this.timestamp, this.rss, this.capacity, this.used, this.external, this.isGC, AdbMemoryInfo? adbMemoryInfo, EventSample? memoryEventInfo, RasterCache? rasterCache, ) : adbMemoryInfo = adbMemoryInfo ?? AdbMemoryInfo.empty(), memoryEventInfo = memoryEventInfo ?? EventSample.empty(), rasterCache = rasterCache ?? RasterCache.empty(); factory HeapSample.fromJson(Map<String, dynamic> json) { final adbMemoryInfo = json['adb_memoryInfo']; final memoryEventInfo = json['memory_eventInfo']; final rasterCache = json['raster_cache']; return HeapSample( json['timestamp'] as int, json['rss'] as int, json['capacity'] as int, json['used'] as int, json['external'] as int, json['gc'] as bool, adbMemoryInfo != null ? AdbMemoryInfo.fromJson(adbMemoryInfo) : AdbMemoryInfo.empty(), memoryEventInfo != null ? EventSample.fromJson(memoryEventInfo) : EventSample.empty(), rasterCache != null ? RasterCache.fromJson(rasterCache) : RasterCache.empty(), ); } Map<String, dynamic> toJson() => <String, dynamic>{ 'timestamp': timestamp, 'rss': rss, 'capacity': capacity, 'used': used, 'external': external, 'gc': isGC, 'adb_memoryInfo': adbMemoryInfo.toJson(), 'memory_eventInfo': memoryEventInfo.toJson(), 'raster_cache': rasterCache.toJson(), }; /// Version of HeapSample JSON payload. static const version = 1; final int timestamp; final int rss; final int capacity; final int used; final int external; final bool isGC; EventSample memoryEventInfo; AdbMemoryInfo adbMemoryInfo; RasterCache rasterCache; @override String toString() => '[HeapSample timestamp: $timestamp, ' '${const JsonEncoder.withIndent(' ').convert(toJson())}]'; }
devtools/packages/devtools_shared/lib/src/memory/heap_sample.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/memory/heap_sample.dart", "repo_id": "devtools", "token_count": 893 }
145
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:vm_service/utils.dart'; import 'package:vm_service/vm_service.dart'; import 'package:vm_service/vm_service_io.dart'; import 'test_utils.dart'; class AppFixture { AppFixture._( this.process, this.lines, this.serviceUri, this.serviceConnection, this.isolates, this.onTeardown, ) { // "starting app" _onAppStarted = lines.first; unawaited(serviceConnection.streamListen(EventStreams.kIsolate)); _isolateEventStreamSubscription = serviceConnection.onIsolateEvent.listen((Event event) { if (event.kind == EventKind.kIsolateExit) { isolates.remove(event.isolate); } else { if (!isolates.contains(event.isolate)) { isolates.add(event.isolate); } } }); } final Process process; final Stream<String> lines; final Uri serviceUri; final VmService serviceConnection; final List<IsolateRef?> isolates; late final StreamSubscription<Event> _isolateEventStreamSubscription; final Future<void> Function()? onTeardown; late Future<void> _onAppStarted; Future<void> get onAppStarted => _onAppStarted; IsolateRef? get mainIsolate => isolates.isEmpty ? null : isolates.first; Future<Response> invoke(String expression) async { final IsolateRef isolateRef = mainIsolate!; final String isolateId = isolateRef.id!; final Isolate isolate = await serviceConnection.getIsolate(isolateId); return await serviceConnection.evaluate( isolateId, isolate.rootLib!.id!, expression, ); } Future<void> teardown() async { if (onTeardown != null) { await onTeardown!(); } await _isolateEventStreamSubscription.cancel(); await serviceConnection.dispose(); process.kill(); } } // This is the fixture for Dart CLI applications. class CliAppFixture extends AppFixture { CliAppFixture._( this.appScriptPath, Process process, Stream<String> lines, Uri serviceUri, VmService serviceConnection, List<IsolateRef> isolates, Future<void> Function()? onTeardown, ) : super._( process, lines, serviceUri, serviceConnection, isolates, onTeardown, ); final String appScriptPath; static Future<CliAppFixture> create(String appScriptPath) async { final dartVmServicePrefix = RegExp('(Observatory|The Dart VM service is) listening on '); final Process process = await Process.start( Platform.resolvedExecutable, <String>['--observe=0', '--pause-isolates-on-start', appScriptPath], ); final Stream<String> lines = process.stdout.transform(utf8.decoder).transform(const LineSplitter()); final StreamController<String> lineController = StreamController<String>.broadcast(); final Completer<String> completer = Completer<String>(); final linesSubscription = lines.listen((String line) { if (completer.isCompleted) { lineController.add(line); } else if (line.contains(dartVmServicePrefix)) { completer.complete(line); } else { // Often something like: // "Waiting for another flutter command to release the startup lock...". print(line); } }); // Observatory listening on http://127.0.0.1:9595/(token) final String observatoryText = await completer.future; final String observatoryUri = observatoryText.replaceAll(dartVmServicePrefix, ''); var uri = Uri.parse(observatoryUri); if (!uri.isAbsolute) { throw 'Could not parse VM Service URI: "$observatoryText"'; } // Map to WS URI. uri = convertToWebSocketUrl(serviceProtocolUrl: uri); final VmService serviceConnection = await vmServiceConnectUri(uri.toString()); final VM vm = await serviceConnection.getVM(); final Isolate isolate = await _waitForIsolate(serviceConnection, 'PauseStart'); await serviceConnection.resume(isolate.id!); Future<void> onTeardown() async { await linesSubscription.cancel(); await lineController.close(); } return CliAppFixture._( appScriptPath, process, lineController.stream, uri, serviceConnection, vm.isolates!, onTeardown, ); } static Future<Isolate> _waitForIsolate( VmService serviceConnection, String pauseEventKind, ) async { Isolate? foundIsolate; await waitFor(() async { const skipId = 'skip'; final vm = await serviceConnection.getVM(); final List<Isolate?> isolates = await Future.wait( vm.isolates!.map( (ref) => serviceConnection .getIsolate(ref.id!) // Calling getIsolate() can sometimes return a collected sentinel // for an isolate that hasn't started yet. We can just ignore these // as on the next trip around the Isolate will be returned. // https://github.com/dart-lang/sdk/issues/33747 .catchError((Object error) { print('getIsolate(${ref.id}) failed, skipping\n$error'); return Future<Isolate>.value(Isolate(id: skipId)); }), ), ); foundIsolate = isolates.firstWhere( (isolate) => isolate!.id != skipId && isolate.pauseEvent?.kind == pauseEventKind, orElse: () => null, ); return foundIsolate != null; }); return foundIsolate!; } String get scriptSource { return File(appScriptPath).readAsStringSync(); } static List<int> parseBreakpointLines(String source) { return _parseLines(source, 'breakpoint'); } static List<int> parseSteppingLines(String source) { return _parseLines(source, 'step'); } static List<int> parseExceptionLines(String source) { return _parseLines(source, 'exception'); } static List<int> _parseLines(String source, String keyword) { final List<String> lines = source.replaceAll('\r', '').split('\n'); final List<int> matches = []; for (int i = 0; i < lines.length; i++) { if (lines[i].endsWith('// $keyword')) { matches.add(i); } } return matches; } }
devtools/packages/devtools_shared/lib/src/test/cli_test_driver.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/test/cli_test_driver.dart", "repo_id": "devtools", "token_count": 2481 }
146
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:devtools_shared/src/extensions/extension_manager.dart'; import 'package:devtools_shared/src/server/server_api.dart'; import 'package:shelf/shelf.dart'; import 'package:test/test.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../fakes.dart'; void main() { group('$DtdApi', () { test('handle ${DtdApi.apiGetDtdUri} succeeds', () async { const dtdUri = 'ws://dtd:uri'; final request = Request( 'get', Uri( scheme: 'https', host: 'localhost', path: DtdApi.apiGetDtdUri, ), ); final response = await ServerApi.handle( request, extensionsManager: ExtensionsManager(buildDir: '/'), deeplinkManager: FakeDeeplinkManager(), dtd: (uri: dtdUri, secret: null), analytics: const NoOpAnalytics(), ); expect(response.statusCode, HttpStatus.ok); expect( await response.readAsString(), jsonEncode({DtdApi.uriPropertyName: dtdUri}), ); }); }); }
devtools/packages/devtools_shared/test/server/dtd_api_test.dart/0
{ "file_path": "devtools/packages/devtools_shared/test/server/dtd_api_test.dart", "repo_id": "devtools", "token_count": 542 }
147
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:ui' as ui; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/main.dart' as app; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import '../helpers/utils.dart'; import '../test_data/sample_data.dart'; /// Required to have multiple test cases in a file. Future<void> resetHistory() async { // ignore: avoid-dynamic, necessary here. await (ui.PlatformDispatcher.instance.views.single as dynamic /* EngineFlutterWindow */) // This dynamic call is necessary as `EngineFlutterWindow` is declared in // the web-specific implementation of the Flutter Engine, at // `lib/web_ui/lib/src/engine/window.dart` in the Flutter engine // repository. // ignore: avoid_dynamic_calls .resetHistory(); } Future<void> pumpAndConnectDevTools( WidgetTester tester, TestApp testApp, ) async { await pumpDevTools(tester); expect(find.byType(ConnectInput), findsOneWidget); expect(find.byType(ConnectedAppSummary), findsNothing); expect(find.text('No client connection'), findsOneWidget); _verifyFooterColor(tester, null); logStatus('verify that we can connect to an app'); await connectToTestApp(tester, testApp); expect(find.byType(ConnectInput), findsNothing); expect(find.byType(ConnectedAppSummary), findsOneWidget); expect(find.text('No client connection'), findsNothing); _verifyFooterColor(tester, darkColorScheme.primary); // If the release notes viewer is open, close it. final releaseNotesView = tester.widget<ReleaseNotesViewer>(find.byType(ReleaseNotesViewer)); if (releaseNotesView.controller.isVisible.value) { final closeReleaseNotesButton = find.descendant( of: find.byType(ReleaseNotesViewer), matching: find.byType(IconButton), ); expect(closeReleaseNotesButton, findsOneWidget); await tester.tap(closeReleaseNotesButton); } } void _verifyFooterColor(WidgetTester tester, Color? expectedColor) { final Container statusLineContainer = tester.widget( find .descendant( of: find.byType(StatusLine), matching: find.byType(Container), ) .first, ); expect( (statusLineContainer.decoration! as BoxDecoration).color, expectedColor, ); } Future<void> pumpDevTools(WidgetTester tester) async { // TODO(kenz): how can we share code across integration_test/test and // integration_test/test_infra? When trying to import, we get an error: // Error when reading 'org-dartlang-app:/test_infra/shared.dart': File not found const shouldEnableExperiments = bool.fromEnvironment('enable_experiments'); app.externalRunDevTools( integrationTestMode: true, // ignore: avoid_redundant_argument_values, by design shouldEnableExperiments: shouldEnableExperiments, sampleData: sampleData, ); // Await a delay to ensure the widget tree has loaded. await tester.pumpAndSettle(veryLongPumpDuration); expect(find.byType(DevToolsApp), findsOneWidget); } Future<void> connectToTestApp(WidgetTester tester, TestApp testApp) async { final textFieldFinder = find.byType(TextField); // TODO(https://github.com/flutter/flutter/issues/89749): use // `tester.enterText` once this issue is fixed. (tester.firstWidget(textFieldFinder) as TextField).controller?.text = testApp.vmServiceUri; await tester.tap( find.ancestor( of: find.text('Connect'), matching: find.byType(ElevatedButton), ), ); await tester.pumpAndSettle(longPumpDuration); } Future<void> disconnectFromTestApp(WidgetTester tester) async { await tester.tap( find.descendant( of: find.byType(DevToolsAppBar), matching: find.byIcon(Icons.home_rounded), ), ); await tester.pumpAndSettle(); await tester.tap(find.byType(ConnectToNewAppButton)); await tester.pump(safePumpDuration); } class TestApp { TestApp._({required this.vmServiceUri}); factory TestApp.parse(Map<String, Object> json) { final serviceUri = json[serviceUriKey] as String?; if (serviceUri == null) { throw Exception('Cannot create a TestApp with a null service uri.'); } return TestApp._(vmServiceUri: serviceUri); } factory TestApp.fromEnvironment() { const testArgs = String.fromEnvironment('test_args'); final argsMap = (jsonDecode(testArgs) as Map).cast<String, Object>(); return TestApp.parse(argsMap); } static const serviceUriKey = 'service_uri'; final String vmServiceUri; } Future<void> verifyScreenshot( IntegrationTestWidgetsFlutterBinding binding, String screenshotName, { // TODO(https://github.com/flutter/flutter/issues/118470): remove this. bool lastScreenshot = false, }) async { const updateGoldens = bool.fromEnvironment('update_goldens'); logStatus('verify $screenshotName screenshot'); await binding.takeScreenshot( screenshotName, { 'update_goldens': updateGoldens, 'last_screenshot': lastScreenshot, }, ); }
devtools/packages/devtools_test/lib/src/integration_test/integration_test_utils.dart/0
{ "file_path": "devtools/packages/devtools_test/lib/src/integration_test/integration_test_utils.dart", "repo_id": "devtools", "token_count": 1796 }
148
## 0.0.2 * Correct repository url ## 0.0.1 * Initial set of icons
devtools/third_party/packages/widget_icons/CHANGELOG.md/0
{ "file_path": "devtools/third_party/packages/widget_icons/CHANGELOG.md", "repo_id": "devtools", "token_count": 26 }
149