text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
#import "GeneratedPluginRegistrant.h"
| codelabs/boring_to_beautiful/step_04/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/boring_to_beautiful/step_04/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 12 |
#import "GeneratedPluginRegistrant.h"
| codelabs/boring_to_beautiful/step_06/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/boring_to_beautiful/step_06/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 13 |
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import '../brick_breaker.dart';
import 'play_area.dart';
class Ball extends CircleComponent
with CollisionCallbacks, HasGameReference<BrickBreaker> {
Ball({
required this.velocity,
required super.position,
required double radius,
}) : super(
radius: radius,
anchor: Anchor.center,
paint: Paint()
..color = const Color(0xff1e6091)
..style = PaintingStyle.fill,
children: [CircleHitbox()]);
final Vector2 velocity;
@override
void update(double dt) {
super.update(dt);
position += velocity * dt;
}
@override
void onCollisionStart(
Set<Vector2> intersectionPoints, PositionComponent other) {
super.onCollisionStart(intersectionPoints, other);
if (other is PlayArea) {
if (intersectionPoints.first.y <= 0) {
velocity.y = -velocity.y;
} else if (intersectionPoints.first.x <= 0) {
velocity.x = -velocity.x;
} else if (intersectionPoints.first.x >= game.width) {
velocity.x = -velocity.x;
} else if (intersectionPoints.first.y >= game.height) {
removeFromParent();
}
} else {
debugPrint('collision with $other');
}
}
}
| codelabs/brick_breaker/step_06/lib/src/components/ball.dart/0 | {
"file_path": "codelabs/brick_breaker/step_06/lib/src/components/ball.dart",
"repo_id": "codelabs",
"token_count": 545
} | 14 |
#import "GeneratedPluginRegistrant.h"
| codelabs/brick_breaker/step_07/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/brick_breaker/step_07/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 15 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/dart-patterns-and-records/step_04/android/gradle.properties/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_04/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 16 |
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_06_b/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_06_b/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 17 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_06_b/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_06_b/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 18 |
#import "GeneratedPluginRegistrant.h"
| codelabs/dart-patterns-and-records/step_07_a/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_07_a/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 19 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/dart-patterns-and-records/step_07_b/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_07_b/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 20 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/dart-patterns-and-records/step_10/android/gradle.properties/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_10/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 21 |
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_12/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_12/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 22 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_12/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_12/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 23 |
#import "GeneratedPluginRegistrant.h"
| codelabs/deeplink_cookbook/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/deeplink_cookbook/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 24 |
import 'package:flutter/material.dart';
import 'entry.dart';
typedef SubmitCallback = void Function(Entry);
class EntryForm extends StatefulWidget {
final SubmitCallback onSubmit;
const EntryForm({super.key, required this.onSubmit});
@override
State<EntryForm> createState() => _EntryFormState();
}
class _EntryFormState extends State<EntryForm> {
final _formKey = GlobalKey<FormState>();
late String title;
late String text;
late String date;
@override
Widget build(BuildContext context) {
return Card(
elevation: 6,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Title'),
// The validator receives the text that the user has entered.
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
title = value;
return null;
},
),
TextFormField(
decoration:
const InputDecoration(labelText: 'Date (DD/MM/YYYY):'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
date = value;
return null;
},
),
TextFormField(
decoration: const InputDecoration(labelText: 'Text'),
maxLines: 10,
minLines: 5,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
text = value;
return null;
},
),
Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: FilledButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
final entry = Entry(
title: title,
text: text,
date: date,
);
widget.onSubmit(entry);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
),
),
],
),
),
),
);
}
}
| codelabs/firebase-emulator-suite/complete/lib/journal_entry_form.dart/0 | {
"file_path": "codelabs/firebase-emulator-suite/complete/lib/journal_entry_form.dart",
"repo_id": "codelabs",
"token_count": 1695
} | 25 |
include: ../../analysis_options.yaml
| codelabs/firebase-get-to-know-flutter/step_05/analysis_options.yaml/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_05/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 12
} | 26 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/firebase-get-to-know-flutter/step_09/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_09/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 27 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_03/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/github-client/step_03/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 28 |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'github_oauth_credentials.dart';
import 'src/github_login.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GitHub Client',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
visualDensity: VisualDensity.adaptivePlatformDensity,
useMaterial3: true,
),
home: const MyHomePage(title: 'GitHub Client'),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return GithubLoginWidget(
builder: (context, httpClient) {
return Scaffold(
appBar: AppBar(
title: Text(title),
elevation: 2,
),
body: const Center(
child: Text(
'You are logged in to GitHub!',
),
),
);
},
githubClientId: githubClientId,
githubClientSecret: githubClientSecret,
githubScopes: githubScopes,
);
}
}
| codelabs/github-client/step_04/lib/main.dart/0 | {
"file_path": "codelabs/github-client/step_04/lib/main.dart",
"repo_id": "codelabs",
"token_count": 671
} | 29 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_04/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/github-client/step_04/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 30 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_05/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/github-client/step_05/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 31 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_06/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/github-client/step_06/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 32 |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:github/github.dart';
import 'package:window_to_front/window_to_front.dart';
import 'github_oauth_credentials.dart';
import 'src/github_login.dart';
import 'src/github_summary.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GitHub Client',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
visualDensity: VisualDensity.adaptivePlatformDensity,
useMaterial3: true,
),
home: const MyHomePage(title: 'GitHub Client'),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return GithubLoginWidget(
builder: (context, httpClient) {
WindowToFront.activate();
return Scaffold(
appBar: AppBar(
title: Text(title),
elevation: 2,
),
body: GitHubSummary(
gitHub: _getGitHub(httpClient.credentials.accessToken),
),
);
},
githubClientId: githubClientId,
githubClientSecret: githubClientSecret,
githubScopes: githubScopes,
);
}
}
GitHub _getGitHub(String accessToken) {
return GitHub(auth: Authentication.withToken(accessToken));
}
| codelabs/github-client/step_07/lib/main.dart/0 | {
"file_path": "codelabs/github-client/step_07/lib/main.dart",
"repo_id": "codelabs",
"token_count": 742
} | 33 |
include: ../../analysis_options.yaml
| codelabs/github-client/window_to_front/analysis_options.yaml/0 | {
"file_path": "codelabs/github-client/window_to_front/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 12
} | 34 |
#import "GeneratedPluginRegistrant.h"
| codelabs/google-maps-in-flutter/step_5/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/google-maps-in-flutter/step_5/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 35 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/haiku_generator/finished/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/finished/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 36 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/haiku_generator/step1/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/step1/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 37 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/haiku_generator/step3/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/step3/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 38 |
include: ../../../analysis_options.yaml
| codelabs/in_app_purchases/step_00/app/analysis_options.yaml/0 | {
"file_path": "codelabs/in_app_purchases/step_00/app/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 13
} | 39 |
#import "GeneratedPluginRegistrant.h"
| codelabs/in_app_purchases/step_00/app/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/in_app_purchases/step_00/app/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 40 |
include: ../../../analysis_options.yaml
| codelabs/in_app_purchases/step_07/app/analysis_options.yaml/0 | {
"file_path": "codelabs/in_app_purchases/step_07/app/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 13
} | 41 |
#import "GeneratedPluginRegistrant.h"
| codelabs/in_app_purchases/step_07/app/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/in_app_purchases/step_07/app/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 42 |
include: ../../../analysis_options.yaml
| codelabs/in_app_purchases/step_08/app/analysis_options.yaml/0 | {
"file_path": "codelabs/in_app_purchases/step_08/app/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 13
} | 43 |
#import "GeneratedPluginRegistrant.h"
| codelabs/in_app_purchases/step_08/app/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/in_app_purchases/step_08/app/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 44 |
include: ../../../analysis_options.yaml
| codelabs/in_app_purchases/step_09/app/analysis_options.yaml/0 | {
"file_path": "codelabs/in_app_purchases/step_09/app/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 13
} | 45 |
#import "GeneratedPluginRegistrant.h"
| codelabs/in_app_purchases/step_09/app/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/in_app_purchases/step_09/app/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 46 |
#import "GeneratedPluginRegistrant.h"
| codelabs/namer/step_03/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/namer/step_03/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 47 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_03/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_03/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 48 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/namer/step_05_f_accessibility/android/gradle.properties/0 | {
"file_path": "codelabs/namer/step_05_f_accessibility/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 49 |
#include "Generated.xcconfig"
| codelabs/namer/step_05_h_center_horizontal/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_h_center_horizontal/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 50 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_05_h_center_horizontal/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_h_center_horizontal/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 51 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_05_i_optional_changes/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_i_optional_changes/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 52 |
#include "Generated.xcconfig"
| codelabs/namer/step_07_a_split_my_home_page/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_a_split_my_home_page/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 53 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_07_a_split_my_home_page/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_a_split_my_home_page/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 54 |
#import "GeneratedPluginRegistrant.h"
| codelabs/namer/step_07_b_convert_to_stateful/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/namer/step_07_b_convert_to_stateful/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 55 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_07_b_convert_to_stateful/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_b_convert_to_stateful/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 56 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_02_a/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_02_a/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 57 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_04_b/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_04_b/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 58 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/testing_codelab/step_06/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/testing_codelab/step_06/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 59 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/tfagents-flutter/step0/frontend/android/gradle.properties/0 | {
"file_path": "codelabs/tfagents-flutter/step0/frontend/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 60 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/tfagents-flutter/step5/frontend/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step5/frontend/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 61 |
#include "Generated.xcconfig"
| codelabs/tfagents-flutter/step6/frontend/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step6/frontend/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 62 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfagents-flutter/step6/frontend/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step6/frontend/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 63 |
#include "Generated.xcconfig"
| codelabs/tfrs-flutter/step0/frontend/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step0/frontend/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 64 |
#import "GeneratedPluginRegistrant.h"
| codelabs/tfrs-flutter/step2/frontend/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/tfrs-flutter/step2/frontend/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 65 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/tfrs-flutter/step2/frontend/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step2/frontend/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 66 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfserving-flutter/codelab2/finished/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/finished/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 67 |
include: ../../../analysis_options.yaml
analyzer:
exclude: [lib/proto/generated/**]
errors:
unused_import: ignore
unused_field: ignore
linter:
rules:
| codelabs/tfserving-flutter/codelab2/starter/analysis_options.yaml/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 62
} | 68 |
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| codelabs/tfserving-flutter/codelab2/starter/android/build.gradle/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/android/build.gradle",
"repo_id": "codelabs",
"token_count": 252
} | 69 |
///
// Generated code. Do not modify.
// source: google/protobuf/any.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/google/protobuf/any.pbenum.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/google/protobuf/any.pbenum.dart",
"repo_id": "codelabs",
"token_count": 113
} | 70 |
///
// Generated code. Do not modify.
// source: tensorflow/core/framework/full_type.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 fullTypeIdDescriptor instead')
const FullTypeId$json = const {
'1': 'FullTypeId',
'2': const [
const {'1': 'TFT_UNSET', '2': 0},
const {'1': 'TFT_VAR', '2': 1},
const {'1': 'TFT_ANY', '2': 2},
const {'1': 'TFT_PRODUCT', '2': 3},
const {'1': 'TFT_NAMED', '2': 4},
const {'1': 'TFT_FOR_EACH', '2': 20},
const {'1': 'TFT_CALLABLE', '2': 100},
const {'1': 'TFT_TENSOR', '2': 1000},
const {'1': 'TFT_ARRAY', '2': 1001},
const {'1': 'TFT_OPTIONAL', '2': 1002},
const {'1': 'TFT_LITERAL', '2': 1003},
const {'1': 'TFT_BOOL', '2': 200},
const {'1': 'TFT_UINT8', '2': 201},
const {'1': 'TFT_UINT16', '2': 202},
const {'1': 'TFT_UINT32', '2': 203},
const {'1': 'TFT_UINT64', '2': 204},
const {'1': 'TFT_INT8', '2': 205},
const {'1': 'TFT_INT16', '2': 206},
const {'1': 'TFT_INT32', '2': 207},
const {'1': 'TFT_INT64', '2': 208},
const {'1': 'TFT_HALF', '2': 209},
const {'1': 'TFT_FLOAT', '2': 210},
const {'1': 'TFT_DOUBLE', '2': 211},
const {'1': 'TFT_BFLOAT16', '2': 215},
const {'1': 'TFT_COMPLEX64', '2': 212},
const {'1': 'TFT_COMPLEX128', '2': 213},
const {'1': 'TFT_STRING', '2': 214},
const {'1': 'TFT_DATASET', '2': 10102},
const {'1': 'TFT_RAGGED', '2': 10103},
const {'1': 'TFT_MUTEX_LOCK', '2': 10202},
const {'1': 'TFT_LEGACY_VARIANT', '2': 10203},
],
};
/// Descriptor for `FullTypeId`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List fullTypeIdDescriptor = $convert.base64Decode(
'CgpGdWxsVHlwZUlkEg0KCVRGVF9VTlNFVBAAEgsKB1RGVF9WQVIQARILCgdURlRfQU5ZEAISDwoLVEZUX1BST0RVQ1QQAxINCglURlRfTkFNRUQQBBIQCgxURlRfRk9SX0VBQ0gQFBIQCgxURlRfQ0FMTEFCTEUQZBIPCgpURlRfVEVOU09SEOgHEg4KCVRGVF9BUlJBWRDpBxIRCgxURlRfT1BUSU9OQUwQ6gcSEAoLVEZUX0xJVEVSQUwQ6wcSDQoIVEZUX0JPT0wQyAESDgoJVEZUX1VJTlQ4EMkBEg8KClRGVF9VSU5UMTYQygESDwoKVEZUX1VJTlQzMhDLARIPCgpURlRfVUlOVDY0EMwBEg0KCFRGVF9JTlQ4EM0BEg4KCVRGVF9JTlQxNhDOARIOCglURlRfSU5UMzIQzwESDgoJVEZUX0lOVDY0ENABEg0KCFRGVF9IQUxGENEBEg4KCVRGVF9GTE9BVBDSARIPCgpURlRfRE9VQkxFENMBEhEKDFRGVF9CRkxPQVQxNhDXARISCg1URlRfQ09NUExFWDY0ENQBEhMKDlRGVF9DT01QTEVYMTI4ENUBEg8KClRGVF9TVFJJTkcQ1gESEAoLVEZUX0RBVEFTRVQQ9k4SDwoKVEZUX1JBR0dFRBD3ThITCg5URlRfTVVURVhfTE9DSxDaTxIXChJURlRfTEVHQUNZX1ZBUklBTlQQ208=');
@$core.Deprecated('Use fullTypeDefDescriptor instead')
const FullTypeDef$json = const {
'1': 'FullTypeDef',
'2': const [
const {
'1': 'type_id',
'3': 1,
'4': 1,
'5': 14,
'6': '.tensorflow.FullTypeId',
'10': 'typeId'
},
const {
'1': 'args',
'3': 2,
'4': 3,
'5': 11,
'6': '.tensorflow.FullTypeDef',
'10': 'args'
},
const {'1': 's', '3': 3, '4': 1, '5': 9, '9': 0, '10': 's'},
const {'1': 'i', '3': 4, '4': 1, '5': 3, '9': 0, '10': 'i'},
],
'8': const [
const {'1': 'attr'},
],
};
/// Descriptor for `FullTypeDef`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List fullTypeDefDescriptor = $convert.base64Decode(
'CgtGdWxsVHlwZURlZhIvCgd0eXBlX2lkGAEgASgOMhYudGVuc29yZmxvdy5GdWxsVHlwZUlkUgZ0eXBlSWQSKwoEYXJncxgCIAMoCzIXLnRlbnNvcmZsb3cuRnVsbFR5cGVEZWZSBGFyZ3MSDgoBcxgDIAEoCUgAUgFzEg4KAWkYBCABKANIAFIBaUIGCgRhdHRy');
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/full_type.pbjson.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/full_type.pbjson.dart",
"repo_id": "codelabs",
"token_count": 2030
} | 71 |
///
// Generated code. Do not modify.
// source: tensorflow/core/framework/tensor.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 'tensor_shape.pb.dart' as $0;
import 'resource_handle.pb.dart' as $1;
import 'types.pbenum.dart' as $2;
class TensorProto extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'TensorProto',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'tensorflow'),
createEmptyInstance: create)
..e<$2.DataType>(
1,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'dtype',
$pb.PbFieldType.OE,
defaultOrMaker: $2.DataType.DT_INVALID,
valueOf: $2.DataType.valueOf,
enumValues: $2.DataType.values)
..aOM<$0.TensorShapeProto>(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'tensorShape',
subBuilder: $0.TensorShapeProto.create)
..a<$core.int>(
3,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'versionNumber',
$pb.PbFieldType.O3)
..a<$core.List<$core.int>>(
4,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'tensorContent',
$pb.PbFieldType.OY)
..p<$core.double>(
5,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'floatVal',
$pb.PbFieldType.KF)
..p<$core.double>(
6,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'doubleVal',
$pb.PbFieldType.KD)
..p<$core.int>(
7,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'intVal',
$pb.PbFieldType.K3)
..p<$core.List<$core.int>>(
8,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'stringVal',
$pb.PbFieldType.PY)
..p<$core.double>(
9,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'scomplexVal',
$pb.PbFieldType.KF)
..p<$fixnum.Int64>(
10,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'int64Val',
$pb.PbFieldType.K6)
..p<$core.bool>(
11,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'boolVal',
$pb.PbFieldType.KB)
..p<$core.double>(
12,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'dcomplexVal',
$pb.PbFieldType.KD)
..p<$core.int>(
13,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'halfVal',
$pb.PbFieldType.K3)
..pc<$1.ResourceHandleProto>(
14,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'resourceHandleVal',
$pb.PbFieldType.PM,
subBuilder: $1.ResourceHandleProto.create)
..pc<VariantTensorDataProto>(
15,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'variantVal',
$pb.PbFieldType.PM,
subBuilder: VariantTensorDataProto.create)
..p<$core.int>(
16,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'uint32Val',
$pb.PbFieldType.KU3)
..p<$fixnum.Int64>(
17,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'uint64Val',
$pb.PbFieldType.KU6)
..hasRequiredFields = false;
TensorProto._() : super();
factory TensorProto({
$2.DataType? dtype,
$0.TensorShapeProto? tensorShape,
$core.int? versionNumber,
$core.List<$core.int>? tensorContent,
$core.Iterable<$core.double>? floatVal,
$core.Iterable<$core.double>? doubleVal,
$core.Iterable<$core.int>? intVal,
$core.Iterable<$core.List<$core.int>>? stringVal,
$core.Iterable<$core.double>? scomplexVal,
$core.Iterable<$fixnum.Int64>? int64Val,
$core.Iterable<$core.bool>? boolVal,
$core.Iterable<$core.double>? dcomplexVal,
$core.Iterable<$core.int>? halfVal,
$core.Iterable<$1.ResourceHandleProto>? resourceHandleVal,
$core.Iterable<VariantTensorDataProto>? variantVal,
$core.Iterable<$core.int>? uint32Val,
$core.Iterable<$fixnum.Int64>? uint64Val,
}) {
final _result = create();
if (dtype != null) {
_result.dtype = dtype;
}
if (tensorShape != null) {
_result.tensorShape = tensorShape;
}
if (versionNumber != null) {
_result.versionNumber = versionNumber;
}
if (tensorContent != null) {
_result.tensorContent = tensorContent;
}
if (floatVal != null) {
_result.floatVal.addAll(floatVal);
}
if (doubleVal != null) {
_result.doubleVal.addAll(doubleVal);
}
if (intVal != null) {
_result.intVal.addAll(intVal);
}
if (stringVal != null) {
_result.stringVal.addAll(stringVal);
}
if (scomplexVal != null) {
_result.scomplexVal.addAll(scomplexVal);
}
if (int64Val != null) {
_result.int64Val.addAll(int64Val);
}
if (boolVal != null) {
_result.boolVal.addAll(boolVal);
}
if (dcomplexVal != null) {
_result.dcomplexVal.addAll(dcomplexVal);
}
if (halfVal != null) {
_result.halfVal.addAll(halfVal);
}
if (resourceHandleVal != null) {
_result.resourceHandleVal.addAll(resourceHandleVal);
}
if (variantVal != null) {
_result.variantVal.addAll(variantVal);
}
if (uint32Val != null) {
_result.uint32Val.addAll(uint32Val);
}
if (uint64Val != null) {
_result.uint64Val.addAll(uint64Val);
}
return _result;
}
factory TensorProto.fromBuffer($core.List<$core.int> i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory TensorProto.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')
TensorProto clone() => TensorProto()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
TensorProto copyWith(void Function(TensorProto) updates) =>
super.copyWith((message) => updates(message as TensorProto))
as TensorProto; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static TensorProto create() => TensorProto._();
TensorProto createEmptyInstance() => create();
static $pb.PbList<TensorProto> createRepeated() => $pb.PbList<TensorProto>();
@$core.pragma('dart2js:noInline')
static TensorProto getDefault() => _defaultInstance ??=
$pb.GeneratedMessage.$_defaultFor<TensorProto>(create);
static TensorProto? _defaultInstance;
@$pb.TagNumber(1)
$2.DataType get dtype => $_getN(0);
@$pb.TagNumber(1)
set dtype($2.DataType v) {
setField(1, v);
}
@$pb.TagNumber(1)
$core.bool hasDtype() => $_has(0);
@$pb.TagNumber(1)
void clearDtype() => clearField(1);
@$pb.TagNumber(2)
$0.TensorShapeProto get tensorShape => $_getN(1);
@$pb.TagNumber(2)
set tensorShape($0.TensorShapeProto v) {
setField(2, v);
}
@$pb.TagNumber(2)
$core.bool hasTensorShape() => $_has(1);
@$pb.TagNumber(2)
void clearTensorShape() => clearField(2);
@$pb.TagNumber(2)
$0.TensorShapeProto ensureTensorShape() => $_ensure(1);
@$pb.TagNumber(3)
$core.int get versionNumber => $_getIZ(2);
@$pb.TagNumber(3)
set versionNumber($core.int v) {
$_setSignedInt32(2, v);
}
@$pb.TagNumber(3)
$core.bool hasVersionNumber() => $_has(2);
@$pb.TagNumber(3)
void clearVersionNumber() => clearField(3);
@$pb.TagNumber(4)
$core.List<$core.int> get tensorContent => $_getN(3);
@$pb.TagNumber(4)
set tensorContent($core.List<$core.int> v) {
$_setBytes(3, v);
}
@$pb.TagNumber(4)
$core.bool hasTensorContent() => $_has(3);
@$pb.TagNumber(4)
void clearTensorContent() => clearField(4);
@$pb.TagNumber(5)
$core.List<$core.double> get floatVal => $_getList(4);
@$pb.TagNumber(6)
$core.List<$core.double> get doubleVal => $_getList(5);
@$pb.TagNumber(7)
$core.List<$core.int> get intVal => $_getList(6);
@$pb.TagNumber(8)
$core.List<$core.List<$core.int>> get stringVal => $_getList(7);
@$pb.TagNumber(9)
$core.List<$core.double> get scomplexVal => $_getList(8);
@$pb.TagNumber(10)
$core.List<$fixnum.Int64> get int64Val => $_getList(9);
@$pb.TagNumber(11)
$core.List<$core.bool> get boolVal => $_getList(10);
@$pb.TagNumber(12)
$core.List<$core.double> get dcomplexVal => $_getList(11);
@$pb.TagNumber(13)
$core.List<$core.int> get halfVal => $_getList(12);
@$pb.TagNumber(14)
$core.List<$1.ResourceHandleProto> get resourceHandleVal => $_getList(13);
@$pb.TagNumber(15)
$core.List<VariantTensorDataProto> get variantVal => $_getList(14);
@$pb.TagNumber(16)
$core.List<$core.int> get uint32Val => $_getList(15);
@$pb.TagNumber(17)
$core.List<$fixnum.Int64> get uint64Val => $_getList(16);
}
class VariantTensorDataProto extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'VariantTensorDataProto',
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')
? ''
: 'typeName')
..a<$core.List<$core.int>>(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'metadata',
$pb.PbFieldType.OY)
..pc<TensorProto>(
3,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'tensors',
$pb.PbFieldType.PM,
subBuilder: TensorProto.create)
..hasRequiredFields = false;
VariantTensorDataProto._() : super();
factory VariantTensorDataProto({
$core.String? typeName,
$core.List<$core.int>? metadata,
$core.Iterable<TensorProto>? tensors,
}) {
final _result = create();
if (typeName != null) {
_result.typeName = typeName;
}
if (metadata != null) {
_result.metadata = metadata;
}
if (tensors != null) {
_result.tensors.addAll(tensors);
}
return _result;
}
factory VariantTensorDataProto.fromBuffer($core.List<$core.int> i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory VariantTensorDataProto.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')
VariantTensorDataProto clone() =>
VariantTensorDataProto()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
VariantTensorDataProto copyWith(
void Function(VariantTensorDataProto) updates) =>
super.copyWith((message) => updates(message as VariantTensorDataProto))
as VariantTensorDataProto; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static VariantTensorDataProto create() => VariantTensorDataProto._();
VariantTensorDataProto createEmptyInstance() => create();
static $pb.PbList<VariantTensorDataProto> createRepeated() =>
$pb.PbList<VariantTensorDataProto>();
@$core.pragma('dart2js:noInline')
static VariantTensorDataProto getDefault() => _defaultInstance ??=
$pb.GeneratedMessage.$_defaultFor<VariantTensorDataProto>(create);
static VariantTensorDataProto? _defaultInstance;
@$pb.TagNumber(1)
$core.String get typeName => $_getSZ(0);
@$pb.TagNumber(1)
set typeName($core.String v) {
$_setString(0, v);
}
@$pb.TagNumber(1)
$core.bool hasTypeName() => $_has(0);
@$pb.TagNumber(1)
void clearTypeName() => clearField(1);
@$pb.TagNumber(2)
$core.List<$core.int> get metadata => $_getN(1);
@$pb.TagNumber(2)
set metadata($core.List<$core.int> v) {
$_setBytes(1, v);
}
@$pb.TagNumber(2)
$core.bool hasMetadata() => $_has(1);
@$pb.TagNumber(2)
void clearMetadata() => clearField(2);
@$pb.TagNumber(3)
$core.List<TensorProto> get tensors => $_getList(2);
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/tensor.pb.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/tensor.pb.dart",
"repo_id": "codelabs",
"token_count": 6265
} | 72 |
///
// Generated code. Do not modify.
// source: tensorflow/core/protobuf/meta_graph.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/protobuf/meta_graph.pbenum.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/protobuf/meta_graph.pbenum.dart",
"repo_id": "codelabs",
"token_count": 119
} | 73 |
///
// Generated code. Do not modify.
// source: tensorflow_serving/apis/classification.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 classDescriptor instead')
const Class$json = const {
'1': 'Class',
'2': const [
const {'1': 'label', '3': 1, '4': 1, '5': 9, '10': 'label'},
const {'1': 'score', '3': 2, '4': 1, '5': 2, '10': 'score'},
],
};
/// Descriptor for `Class`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List classDescriptor = $convert.base64Decode(
'CgVDbGFzcxIUCgVsYWJlbBgBIAEoCVIFbGFiZWwSFAoFc2NvcmUYAiABKAJSBXNjb3Jl');
@$core.Deprecated('Use classificationsDescriptor instead')
const Classifications$json = const {
'1': 'Classifications',
'2': const [
const {
'1': 'classes',
'3': 1,
'4': 3,
'5': 11,
'6': '.tensorflow.serving.Class',
'10': 'classes'
},
],
};
/// Descriptor for `Classifications`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List classificationsDescriptor = $convert.base64Decode(
'Cg9DbGFzc2lmaWNhdGlvbnMSMwoHY2xhc3NlcxgBIAMoCzIZLnRlbnNvcmZsb3cuc2VydmluZy5DbGFzc1IHY2xhc3Nlcw==');
@$core.Deprecated('Use classificationResultDescriptor instead')
const ClassificationResult$json = const {
'1': 'ClassificationResult',
'2': const [
const {
'1': 'classifications',
'3': 1,
'4': 3,
'5': 11,
'6': '.tensorflow.serving.Classifications',
'10': 'classifications'
},
],
};
/// Descriptor for `ClassificationResult`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List classificationResultDescriptor = $convert.base64Decode(
'ChRDbGFzc2lmaWNhdGlvblJlc3VsdBJNCg9jbGFzc2lmaWNhdGlvbnMYASADKAsyIy50ZW5zb3JmbG93LnNlcnZpbmcuQ2xhc3NpZmljYXRpb25zUg9jbGFzc2lmaWNhdGlvbnM=');
@$core.Deprecated('Use classificationRequestDescriptor instead')
const ClassificationRequest$json = const {
'1': 'ClassificationRequest',
'2': const [
const {
'1': 'model_spec',
'3': 1,
'4': 1,
'5': 11,
'6': '.tensorflow.serving.ModelSpec',
'10': 'modelSpec'
},
const {
'1': 'input',
'3': 2,
'4': 1,
'5': 11,
'6': '.tensorflow.serving.Input',
'10': 'input'
},
],
};
/// Descriptor for `ClassificationRequest`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List classificationRequestDescriptor = $convert.base64Decode(
'ChVDbGFzc2lmaWNhdGlvblJlcXVlc3QSPAoKbW9kZWxfc3BlYxgBIAEoCzIdLnRlbnNvcmZsb3cuc2VydmluZy5Nb2RlbFNwZWNSCW1vZGVsU3BlYxIvCgVpbnB1dBgCIAEoCzIZLnRlbnNvcmZsb3cuc2VydmluZy5JbnB1dFIFaW5wdXQ=');
@$core.Deprecated('Use classificationResponseDescriptor instead')
const ClassificationResponse$json = const {
'1': 'ClassificationResponse',
'2': const [
const {
'1': 'model_spec',
'3': 2,
'4': 1,
'5': 11,
'6': '.tensorflow.serving.ModelSpec',
'10': 'modelSpec'
},
const {
'1': 'result',
'3': 1,
'4': 1,
'5': 11,
'6': '.tensorflow.serving.ClassificationResult',
'10': 'result'
},
],
};
/// Descriptor for `ClassificationResponse`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List classificationResponseDescriptor =
$convert.base64Decode(
'ChZDbGFzc2lmaWNhdGlvblJlc3BvbnNlEjwKCm1vZGVsX3NwZWMYAiABKAsyHS50ZW5zb3JmbG93LnNlcnZpbmcuTW9kZWxTcGVjUgltb2RlbFNwZWMSQAoGcmVzdWx0GAEgASgLMigudGVuc29yZmxvdy5zZXJ2aW5nLkNsYXNzaWZpY2F0aW9uUmVzdWx0UgZyZXN1bHQ=');
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/classification.pbjson.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/classification.pbjson.dart",
"repo_id": "codelabs",
"token_count": 1832
} | 74 |
///
// Generated code. Do not modify.
// source: tensorflow_serving/apis/prediction_service.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;
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/prediction_service.pb.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/prediction_service.pb.dart",
"repo_id": "codelabs",
"token_count": 132
} | 75 |
syntax = "proto3";
package tensorflow;
import "tensorflow/core/framework/attr_value.proto";
import "tensorflow/core/framework/full_type.proto";
import "tensorflow/core/framework/resource_handle.proto";
import "tensorflow/core/framework/types.proto";
option cc_enable_arenas = true;
option java_outer_classname = "OpDefProtos";
option java_multiple_files = true;
option java_package = "org.tensorflow.framework";
option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/op_def_go_proto";
// Defines an operation. A NodeDef in a GraphDef specifies an Op by
// using the "op" field which should match the name of a OpDef.
// LINT.IfChange
message OpDef {
// Op names starting with an underscore are reserved for internal use.
// Names should be CamelCase and match the regexp "[A-Z][a-zA-Z0-9>_]*".
string name = 1;
// For describing inputs and outputs.
message ArgDef {
// Name for the input/output. Should match the regexp "[a-z][a-z0-9_]*".
string name = 1;
// Human readable description.
string description = 2;
// Describes the type of one or more tensors that are accepted/produced
// by this input/output arg. The only legal combinations are:
// * For a single tensor: either the "type" field is set or the
// "type_attr" field is set to the name of an attr with type "type".
// * For a sequence of tensors with the same type: the "number_attr"
// field will be set to the name of an attr with type "int", and
// either the "type" or "type_attr" field will be set as for
// single tensors.
// * For a sequence of tensors, the "type_list_attr" field will be set
// to the name of an attr with type "list(type)".
DataType type = 3;
string type_attr = 4; // if specified, attr must have type "type"
string number_attr = 5; // if specified, attr must have type "int"
// If specified, attr must have type "list(type)", and none of
// type, type_attr, and number_attr may be specified.
string type_list_attr = 6;
// The handle data for resource inputs.
repeated ResourceHandleProto.DtypeAndShape handle_data = 7;
// For inputs: if true, the inputs are required to be refs.
// By default, inputs can be either refs or non-refs.
// For outputs: if true, outputs are refs, otherwise they are not.
bool is_ref = 16;
// Experimental. Full type declaration for this argument.
// The full type specification combines type, type_attr, type_list_attr,
// etc. into a unified representation.
// This declaration may contain non-concrete types (for example,
// Tensor<TypeVar<'T'>> is a valid type declaration.
//
// Note: this is a transient field. The long-term aim is to represent the
// entire OpDef as a single type: a callable. In that context, this field is
// just the type of a single argument.
FullTypeDef experimental_full_type = 17;
}
// Description of the input(s).
repeated ArgDef input_arg = 2;
// Description of the output(s).
repeated ArgDef output_arg = 3;
// Named control outputs for this operation. Useful only for composite
// operations (i.e. functions) which want to name different control outputs.
repeated string control_output = 20;
// Description of the graph-construction-time configuration of this
// Op. That is to say, this describes the attr fields that will
// be specified in the NodeDef.
message AttrDef {
// A descriptive name for the argument. May be used, e.g. by the
// Python client, as a keyword argument name, and so should match
// the regexp "[a-z][a-z0-9_]+".
string name = 1;
// One of the type names from attr_value.proto ("string", "list(string)",
// "int", etc.).
string type = 2;
// A reasonable default for this attribute if the user does not supply
// a value. If not specified, the user must supply a value.
AttrValue default_value = 3;
// Human-readable description.
string description = 4;
// TODO(josh11b): bool is_optional?
// --- Constraints ---
// These constraints are only in effect if specified. Default is no
// constraints.
// For type == "int", this is a minimum value. For "list(___)"
// types, this is the minimum length.
bool has_minimum = 5;
int64 minimum = 6;
// The set of allowed values. Has type that is the "list" version
// of the "type" field above (uses the "list" field of AttrValue).
// If type == "type" or "list(type)" above, then the "type" field
// of "allowed_values.list" has the set of allowed DataTypes.
// If type == "string" or "list(string)", then the "s" field of
// "allowed_values.list" has the set of allowed strings.
AttrValue allowed_values = 7;
}
repeated AttrDef attr = 4;
// Optional deprecation based on GraphDef versions.
OpDeprecation deprecation = 8;
// One-line human-readable description of what the Op does.
string summary = 5;
// Additional, longer human-readable description of what the Op does.
string description = 6;
// -------------------------------------------------------------------------
// Which optimizations this operation can participate in.
// True if the operation is commutative ("op(a,b) == op(b,a)" for all inputs)
bool is_commutative = 18;
// If is_aggregate is true, then this operation accepts N >= 2
// inputs and produces 1 output all of the same type. Should be
// associative and commutative, and produce output with the same
// shape as the input. The optimizer may replace an aggregate op
// taking input from multiple devices with a tree of aggregate ops
// that aggregate locally within each device (and possibly within
// groups of nearby devices) before communicating.
// TODO(josh11b): Implement that optimization.
bool is_aggregate = 16; // for things like add
// Other optimizations go here, like
// can_alias_input, rewrite_when_output_unused, partitioning_strategy, etc.
// -------------------------------------------------------------------------
// Optimization constraints.
// Ops are marked as stateful if their behavior depends on some state beyond
// their input tensors (e.g. variable reading op) or if they have
// a side-effect (e.g. printing or asserting ops). Equivalently, stateless ops
// must always produce the same output for the same input and have
// no side-effects.
//
// By default Ops may be moved between devices. Stateful ops should
// either not be moved, or should only be moved if that state can also
// be moved (e.g. via some sort of save / restore).
// Stateful ops are guaranteed to never be optimized away by Common
// Subexpression Elimination (CSE).
bool is_stateful = 17; // for things like variables, queue
// -------------------------------------------------------------------------
// Non-standard options.
// By default, all inputs to an Op must be initialized Tensors. Ops
// that may initialize tensors for the first time should set this
// field to true, to allow the Op to take an uninitialized Tensor as
// input.
bool allows_uninitialized_input = 19; // for Assign, etc.
// Indicates whether the op implementation uses distributed communication.
// If True, the op is allowed to return errors for network disconnection and
// trigger TF network failure handling logics.
bool is_distributed_communication = 21;
}
// LINT.ThenChange(
// https://www.tensorflow.org/code/tensorflow/core/framework/op_def_util.cc)
// Information about version-dependent deprecation of an op
message OpDeprecation {
// First GraphDef version at which the op is disallowed.
int32 version = 1;
// Explanation of why it was deprecated and what to use instead.
string explanation = 2;
}
// A collection of OpDefs
message OpList {
repeated OpDef op = 1;
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/framework/op_def.proto/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/framework/op_def.proto",
"repo_id": "codelabs",
"token_count": 2334
} | 76 |
syntax = "proto3";
package tensorflow.serving;
option cc_enable_arenas = true;
import "google/protobuf/wrappers.proto";
// Metadata for an inference request such as the model name and version.
message ModelSpec {
// Required servable name.
string name = 1;
// Optional choice of which version of the model to use.
//
// Recommended to be left unset in the common case. Should be specified only
// when there is a strong version consistency requirement.
//
// When left unspecified, the system will serve the best available version.
// This is typically the latest version, though during version transitions,
// notably when serving on a fleet of instances, may be either the previous or
// new version.
oneof version_choice {
// Use this specific version number.
google.protobuf.Int64Value version = 2;
// Use the version associated with the given label.
string version_label = 4;
}
// A named signature to evaluate. If unspecified, the default signature will
// be used.
string signature_name = 3;
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow_serving/apis/model.proto/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow_serving/apis/model.proto",
"repo_id": "codelabs",
"token_count": 284
} | 77 |
name: claat_export_images
description: A tool to export images from a CLAAT codelab
version: 1.0.0
repository: https://github.com/flutter/codelabs
environment:
sdk: ^3.2.0
dependencies:
args: ^2.4.2
googleapis: ^11.2.0
googleapis_auth: ^1.4.1
http: ^1.1.0
image: ^4.0.17
json_annotation: ^4.8.1
path: ^1.8.3
dev_dependencies:
build_runner: ^2.4.5
json_serializable: ^6.7.0
lints: ">=2.0.0 <4.0.0"
test: ^1.21.0
| codelabs/tooling/claat_export_images/pubspec.yaml/0 | {
"file_path": "codelabs/tooling/claat_export_images/pubspec.yaml",
"repo_id": "codelabs",
"token_count": 210
} | 78 |
// Copyright 2022 The Flutter team. 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:io';
import 'package:codelab_rebuild/codelab_rebuild.dart';
import 'package:logging/logging.dart';
void main(List<String> arguments) {
Logger.root.level = Level.ALL; // defaults to Level.INFO
Logger.root.onRecord.listen((record) {
print('${record.level.name}: ${record.time}: ${record.message}');
});
if (arguments.length != 1) {
Logger('main')
.severe('Usage: codelab_rebuild path/to/codelab_rebuild.yaml');
exit(1);
}
final source = arguments.single;
final blueprint = Blueprint.load(File(source));
blueprint.rebuild(File(source).parent);
}
| codelabs/tooling/codelab_rebuild/bin/codelab_rebuild.dart/0 | {
"file_path": "codelabs/tooling/codelab_rebuild/bin/codelab_rebuild.dart",
"repo_id": "codelabs",
"token_count": 262
} | 79 |
include: ../../analysis_options.yaml
| codelabs/webview_flutter/step_08/analysis_options.yaml/0 | {
"file_path": "codelabs/webview_flutter/step_08/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 12
} | 80 |
#import "GeneratedPluginRegistrant.h"
| codelabs/webview_flutter/step_10/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/webview_flutter/step_10/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 81 |
# DevTools style guide
We fully follow [Effective Dart](https://dart.dev/guides/language/effective-dart)
and some items of
[Style guide for Flutter repo](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo):
## Order of getters and setters
When an object owns and exposes a (listenable) value,
more complicated than just public field
we declare the related class members always in the same order,
in compliance with
[Flutter repo style guide]( https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#order-other-class-members-in-a-way-that-makes-sense):
1. Public getter
2. Private field
3. Public setter (when needed)
## Naming for typedefs and function variables
Follow [Flutter repo naming rules for typedefs and function variables](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#naming-rules-for-typedefs-and-function-variables).
## Overriding equality
Use [boilerplaite](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#common-boilerplates-for-operator--and-hashcode).
## URIs and File Paths
Care should be taken when using file paths to ensure compatibility with both
Windows and POSIX style paths. File URIs should generally be preferred and only
converted to paths when required to interact with the file system.
`String` variables that hold paths or URIs should be named explicitly with a
`Path` or `Uri` suffix, such as `appRootPath` or `appRootUri`.
Additionally:
- `Uri.parse()` should not be used for converting file paths to URIs, instead
`Uri.file()` should be used
- `Uri.path` should not be used for extracting a file path from a URI, instead
`uri.toFilePath()` should be used
- In code compiled to run in the browser, `Uri.file()` and `uri.toFilePath()`
will assume POSIX-style paths even on Windows, so care should be taken to
handle these correctly (if possible, avoid converting between URIs and file
paths in code running in a browser)
## Text styles
The default text style for DevTools is `Theme.of(context).regularTextStyle`. The default
value for `Theme.of(context).bodyMedium` is equivalent to `Theme.of(context).regularTextStyle`.
When creating a `Text` widget, this is the default style that will be applied.
| devtools/STYLE.md/0 | {
"file_path": "devtools/STYLE.md",
"repo_id": "devtools",
"token_count": 648
} | 82 |
import 'package:flutter/material.dart';
class Animals extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView(
itemExtent: 75.0,
children: _buildListItems(),
);
}
List<Widget> _buildListItems() {
final items = <Widget>[];
for (int i = 1; i <= 1000; i++) {
final asset = _assets[i % (_assets.length - 1)];
items.add(_buildListItem(asset));
}
return items;
}
Widget _buildListItem(String assetName) {
final title = assetName.split('.').first.split('/').last;
return ListTile(
leading: Image.asset(
assetName,
height: 48.0,
width: 48.0,
fit: BoxFit.fill,
),
title: Text(title),
subtitle: Text('This is a $title. It is neat.'),
);
}
}
final _assets = [
'assets/buck.jpeg',
'assets/dog.jpeg',
'assets/flamingo.jpeg',
'assets/fox.jpeg',
'assets/gorilla.jpeg',
'assets/horse.jpeg',
'assets/husky.jpeg',
'assets/kangaroo.jpeg',
'assets/lion.jpeg',
'assets/parrot.jpeg',
'assets/puppy.jpeg',
'assets/rooster.jpeg',
'assets/white_tiger.jpeg',
'assets/yak.jpeg',
'assets/zebra.jpeg',
];
| devtools/case_study/code_size/optimized/code_size_images/lib/animals.dart/0 | {
"file_path": "devtools/case_study/code_size/optimized/code_size_images/lib/animals.dart",
"repo_id": "devtools",
"token_count": 512
} | 83 |
#include "ephemeral/Flutter-Generated.xcconfig"
| devtools/case_study/code_size/optimized/code_size_package/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "devtools/case_study/code_size/optimized/code_size_package/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "devtools",
"token_count": 19
} | 84 |
#import "GeneratedPluginRegistrant.h"
| devtools/case_study/code_size/unoptimized/code_size_images/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "devtools/case_study/code_size/unoptimized/code_size_images/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "devtools",
"token_count": 13
} | 85 |
# Using Tab Bar
A material design widget that displays a horizontal row of tabs.
Read ([Documentation](https://api.flutter.dev/flutter/material/TabBar-class.html)) ([Material Design Spec](https://m2.material.io/components/tabs))
<img src="demo_img.gif" height="600em" />
| devtools/case_study/memory_leaks/memory_leak_app/README.md/0 | {
"file_path": "devtools/case_study/memory_leaks/memory_leak_app/README.md",
"repo_id": "devtools",
"token_count": 86
} | 86 |
// 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:intl/intl.dart';
class Logging {
Logging() {
model = TimeModel(this)..start();
}
late final TimeModel model;
static Logging? _theLogging;
static Logging get logging {
_theLogging ??= Logging();
return _theLogging!;
}
final List<String> _logs = [];
void add(String entry) {
final TimeStamp newTimeStamp = TimeStamp.record(DateTime.now());
_logs.add('[${model.log.length}] : ${newTimeStamp.time}] $entry');
}
List<String> get logs => _logs;
}
class TimeStamp {
TimeStamp({
time = '',
date = '',
meridiem = '',
});
factory TimeStamp.record(DateTime now) {
return TimeStamp(
time: currentTime.format(now),
date: currentDate.format(now),
meridiem: currentMeridiem.format(now),
);
}
late String time;
late String date;
late String meridiem;
static DateFormat currentTime = DateFormat('H:mm:ss', 'en_US');
static DateFormat currentDate = DateFormat('EEEE, MMM d', 'en_US');
static DateFormat currentMeridiem = DateFormat('aaa', 'en_US');
}
class TimeModel {
TimeModel(this._logging);
final Logging _logging;
List<TimeStamp> log = <TimeStamp>[];
final String _time = '';
final String _date = '';
final String _meridiem = '';
Timer? _clockUpdateTimer;
DateTime now = DateTime.now();
/// Start updating.
void start() {
log.add(TimeStamp());
_updateLog();
_clockUpdateTimer = Timer.periodic(
const Duration(milliseconds: 100),
(_) => _updateLog(),
);
}
/// Stop updating.
void stop() {
_clockUpdateTimer?.cancel();
_clockUpdateTimer = null;
}
/// The current time in the ambient format.
String get time => _time;
/// The current date in the ambient format.
String get date => _date;
/// The current meridiem in the ambient format.
String get meridiem => _meridiem;
String get partOfDay {
if (now.hour < 5) {
return 'night';
}
if (now.hour < 12) {
return 'morning';
}
if (now.hour < 12 + 5) {
return 'afternoon';
}
if (now.hour < 12 + 8) {
return 'evening';
}
return 'night';
}
void _updateLog() {
now = DateTime.now();
final year = now.year;
/// Due to a bug, need to verify the date has the current year before
/// returning a date and time.
if (year < 2019) {
return;
}
final TimeStamp newTimeStamp = TimeStamp.record(now);
log.add(newTimeStamp);
if (newTimeStamp.time != log.last.time ||
newTimeStamp.date != log.last.date ||
newTimeStamp.meridiem != log.last.meridiem) {
_logging.add('${newTimeStamp.time} idle...');
}
}
}
| devtools/case_study/memory_leaks/memory_leak_app/lib/logging.dart/0 | {
"file_path": "devtools/case_study/memory_leaks/memory_leak_app/lib/logging.dart",
"repo_id": "devtools",
"token_count": 1085
} | 87 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>platform_channel</title>
</head>
<body>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
| devtools/case_study/platform_channel/web/index.html/0 | {
"file_path": "devtools/case_study/platform_channel/web/index.html",
"repo_id": "devtools",
"token_count": 76
} | 88 |
{
// Set current working directory to devtools_app.
"terminal.integrated.cwd": "devtools_app",
"dart.showTodos": false,
}
| devtools/packages/.vscode/settings.json/0 | {
"file_path": "devtools/packages/.vscode/settings.json",
"repo_id": "devtools",
"token_count": 54
} | 89 |
// 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.
/// The initial page to load upon opening the DevTools benchmark app or
/// reloading it in Chrome.
//
// We use an empty initial page so that the benchmark server does not attempt
// to load the default page 'index.html', which will show up as "page not
// found" in DevTools.
const String benchmarkInitialPage = '';
const String devtoolsBenchmarkPrefix = 'devtools';
enum DevToolsBenchmark {
navigateThroughOfflineScreens,
offlineCpuProfilerScreen,
offlinePerformanceScreen;
String get id => '${devtoolsBenchmarkPrefix}_$name';
}
| devtools/packages/devtools_app/benchmark/test_infra/common.dart/0 | {
"file_path": "devtools/packages/devtools_app/benchmark/test_infra/common.dart",
"repo_id": "devtools",
"token_count": 188
} | 90 |
// 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 '_test_app_driver.dart';
enum TestFileArgItems {
experimentsOn,
appPath,
}
const _defaultFlutterAppPath = 'test/test_infra/fixtures/flutter_app';
const _defaultDartCliAppPath = 'test/test_infra/fixtures/empty_app.dart';
/// Test arguments, defined inside the test file as a comment.
class TestFileArgs {
factory TestFileArgs(
String testFilePath, {
required TestAppDevice testAppDevice,
}) {
final content = File(testFilePath).readAsStringSync();
return TestFileArgs.fromFileContent(content, testAppDevice: testAppDevice);
}
factory TestFileArgs.fromFileContent(
String fileContent, {
required TestAppDevice testAppDevice,
}) {
final testFileArgItems = _parseFileContent(fileContent);
for (final arg in testFileArgItems.keys) {
testFileArgItems.putIfAbsent(arg, () => null);
}
return TestFileArgs.parse(testFileArgItems, testAppDevice: testAppDevice);
}
TestFileArgs.parse(
Map<TestFileArgItems, dynamic> map, {
required TestAppDevice testAppDevice,
}) : experimentsOn = map[TestFileArgItems.experimentsOn] ?? false,
appPath = map[TestFileArgItems.appPath] ??
(testAppDevice == TestAppDevice.cli
? _defaultDartCliAppPath
: _defaultFlutterAppPath);
/// If true, experiments will be enabled in the test.
final bool experimentsOn;
/// Path to the application to connect to.
final String appPath;
}
final _argRegex = RegExp(
r'^\/\/\s*test-argument\s*:\s*(\w*)\s*=\s*(\S*)\s*$',
multiLine: true,
);
Map<TestFileArgItems, dynamic> _parseFileContent(String fileContent) {
final matches = _argRegex.allMatches(fileContent);
final entries = matches.map<MapEntry<TestFileArgItems, dynamic>>(
(RegExpMatch m) {
final name = m.group(1) ?? '';
if (name.isEmpty) {
throw ArgumentError(
'Name of test argument should be provided: [${m.group(0)}].',
);
}
final value = m.group(2) ?? '';
return MapEntry(TestFileArgItems.values.byName(name), jsonDecode(value));
},
);
return Map.fromEntries(entries);
}
| devtools/packages/devtools_app/integration_test/test_infra/run/_in_file_args.dart/0 | {
"file_path": "devtools/packages/devtools_app/integration_test/test_infra/run/_in_file_args.dart",
"repo_id": "devtools",
"token_count": 847
} | 91 |
// 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 '../../shared/analytics/analytics.dart' as ga;
import '../../shared/analytics/constants.dart' as gac;
import '_view_desktop.dart' if (dart.library.js_interop) '_view_web.dart';
import 'controller.dart';
/// A widget that displays a DevTools extension in an embedded iFrame.
///
/// A DevTools extension is provided by a pub package and is served by the
/// DevTools server when present for a connected application.
///
/// When DevTools is run on Desktop for development, this widget displays a
/// placeholder, since Flutter Desktop does not currently support web views.
class EmbeddedExtensionView extends StatefulWidget {
const EmbeddedExtensionView({Key? key, required this.controller})
: super(key: key);
final EmbeddedExtensionController controller;
@override
State<EmbeddedExtensionView> createState() => _EmbeddedExtensionViewState();
}
class _EmbeddedExtensionViewState extends State<EmbeddedExtensionView> {
@override
void initState() {
super.initState();
ga.impression(
gac.DevToolsExtensionEvents.extensionScreenName(
widget.controller.extensionConfig,
),
gac.DevToolsExtensionEvents.embeddedExtension.name,
);
}
@override
Widget build(BuildContext context) {
return EmbeddedExtension(controller: widget.controller);
}
}
| devtools/packages/devtools_app/lib/src/extensions/embedded/view.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/extensions/embedded/view.dart",
"repo_id": "devtools",
"token_count": 459
} | 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:async';
import 'package:devtools_app_shared/ui.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../shared/analytics/analytics_controller.dart';
import '../shared/analytics/constants.dart' as gac;
import '../shared/common_widgets.dart';
import '../shared/config_specific/copy_to_clipboard/copy_to_clipboard.dart';
import '../shared/globals.dart';
import '../shared/log_storage.dart';
import '../shared/server/server.dart';
class OpenSettingsAction extends ScaffoldAction {
OpenSettingsAction({super.key, Color? color})
: super(
icon: Icons.settings_outlined,
tooltip: 'Settings',
color: color,
onPressed: (context) {
unawaited(
showDialog(
context: context,
builder: (context) => const SettingsDialog(),
),
);
},
);
}
class SettingsDialog extends StatelessWidget {
const SettingsDialog({super.key});
@override
Widget build(BuildContext context) {
final analyticsController = Provider.of<AnalyticsController>(context);
return DevToolsDialog(
title: const DialogTitleText('Settings'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: CheckboxSetting(
title: 'Use a dark theme',
notifier: preferences.darkModeTheme,
onChanged: preferences.toggleDarkModeTheme,
gaItem: gac.darkTheme,
),
),
if (isExternalBuild && isDevToolsServerAvailable)
Flexible(
child: CheckboxSetting(
title: 'Enable analytics',
notifier: analyticsController.analyticsEnabled,
onChanged: (enable) => unawaited(
analyticsController.toggleAnalyticsEnabled(enable),
),
gaItem: gac.analytics,
),
),
Flexible(
child: CheckboxSetting(
title: 'Enable VM developer mode',
notifier: preferences.vmDeveloperModeEnabled,
onChanged: preferences.toggleVmDeveloperMode,
gaItem: gac.vmDeveloperMode,
),
),
const PaddedDivider(),
const _VerboseLoggingSetting(),
],
),
actions: const [
DialogCloseButton(),
],
);
}
}
class _VerboseLoggingSetting extends StatelessWidget {
const _VerboseLoggingSetting();
static const _minScreenWidthForTextBeforeScaling = 500.0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Flexible(
child: CheckboxSetting(
title: 'Enable verbose logging',
notifier: preferences.verboseLoggingEnabled,
onChanged: (enable) => preferences.toggleVerboseLogging(enable),
gaItem: gac.verboseLogging,
),
),
const SizedBox(width: defaultSpacing),
GaDevToolsButton(
label: 'Copy logs',
icon: Icons.copy_outlined,
gaScreen: gac.settingsDialog,
gaSelection: gac.copyLogs,
minScreenWidthForTextBeforeScaling:
_minScreenWidthForTextBeforeScaling,
onPressed: () async => await copyToClipboard(
LogStorage.root.toString(),
'Successfully copied logs',
),
),
const SizedBox(width: denseSpacing),
ClearButton(
label: 'Clear logs',
gaScreen: gac.settingsDialog,
gaSelection: gac.clearLogs,
minScreenWidthForTextBeforeScaling:
_minScreenWidthForTextBeforeScaling,
onPressed: LogStorage.root.clear,
),
],
),
const SizedBox(height: denseSpacing),
const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.warning),
SizedBox(width: defaultSpacing),
Flexible(
child: Text(
'Logs may contain sensitive information.\n'
'Always check their contents before sharing.',
),
),
],
),
],
);
}
}
| devtools/packages/devtools_app/lib/src/framework/settings_dialog.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/framework/settings_dialog.dart",
"repo_id": "devtools",
"token_count": 2233
} | 93 |
// 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/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:vm_service/vm_service.dart';
import '../../shared/globals.dart';
import '../../shared/primitives/utils.dart';
import '../../shared/ui/search.dart';
import 'codeview_controller.dart';
import 'debugger_model.dart';
const int numOfMatchesToShow = 10;
const noResultsMsg = 'No files found.';
final _fileNamesCache = <String, String>{};
class FileSearchField extends StatefulWidget {
const FileSearchField({
super.key,
required this.codeViewController,
});
final CodeViewController codeViewController;
@override
FileSearchFieldState createState() => FileSearchFieldState();
}
class FileSearchFieldState extends State<FileSearchField>
with AutoDisposeMixin, SearchFieldMixin {
static final fileSearchFieldKey = GlobalKey(debugLabel: 'fileSearchFieldKey');
final autoCompleteController = AutoCompleteController(fileSearchFieldKey);
final _scriptsCache = <String, ScriptRef>{};
late String _query;
late FileSearchResults _searchResults;
@override
SearchControllerMixin get searchController => autoCompleteController;
@override
void initState() {
super.initState();
autoCompleteController.setCurrentHoveredIndexValue(0);
addAutoDisposeListener(
autoCompleteController.searchNotifier,
_handleSearch,
);
addAutoDisposeListener(
autoCompleteController.searchAutoCompleteNotifier,
_handleAutoCompleteOverlay,
);
_query = autoCompleteController.search;
_searchResults = FileSearchResults.emptyQuery(
scriptManager.sortedScripts.value,
);
// Open the autocomplete results immediately before a query is entered:
SchedulerBinding.instance.addPostFrameCallback((_) => _handleSearch());
}
@override
Widget build(BuildContext context) {
return AutoCompleteSearchField(
controller: autoCompleteController,
searchFieldEnabled: true,
shouldRequestFocus: true,
keyEventsToIgnore: {LogicalKeyboardKey.escape},
onSelection: _onSelection,
onClose: _onClose,
label: 'Open file',
onFocusLost: _onClose,
);
}
@override
void dispose() {
_onClose();
autoCompleteController.dispose();
super.dispose();
}
void _handleSearch() {
final previousQuery = _query;
final currentQuery = autoCompleteController.search.trim();
// If the current query is a continuation of the previous query, then
// filter down the previous matches. Otherwise search through all scripts:
final scripts = currentQuery.startsWith(previousQuery)
? _searchResults.scriptRefs
: scriptManager.sortedScripts.value;
final searchResults = _createSearchResults(currentQuery, scripts);
if (searchResults.scriptRefs.isEmpty) {
autoCompleteController.searchAutoComplete.value = [
AutoCompleteMatch(noResultsMsg),
];
} else {
searchResults.topMatches.scriptRefs.forEach(_addScriptRefToCache);
autoCompleteController.searchAutoComplete.value =
searchResults.topMatches.autoCompleteMatches;
}
_query = currentQuery;
_searchResults = searchResults;
}
void _handleAutoCompleteOverlay() {
autoCompleteController.handleAutoCompleteOverlay(
context: context,
searchFieldKey: fileSearchFieldKey,
onTap: _onSelection,
);
}
void _addScriptRefToCache(ScriptRef scriptRef) {
final uri = scriptRef.uri;
if (uri == null) return;
_scriptsCache.putIfAbsent(uri, () => scriptRef);
}
Future<void> _onSelection(String scriptUri) async {
if (scriptUri == noResultsMsg) {
_onClose();
return;
}
final scriptRef = _scriptsCache[scriptUri]!;
await widget.codeViewController
.showScriptLocation(ScriptLocation(scriptRef));
_onClose();
}
void _onClose() {
autoCompleteController.closeAutoCompleteOverlay();
widget.codeViewController.toggleFileOpenerVisibility(false);
_fileNamesCache.clear();
_scriptsCache.clear();
}
FileSearchResults _createSearchResults(
String query,
List<ScriptRef> scriptRefs,
) {
if (query.isEmpty) {
return FileSearchResults.emptyQuery(scriptRefs);
}
return FileSearchResults.withQuery(
allScripts: scriptRefs,
query: FileQuery(query),
);
}
}
class FileQuery {
FileQuery(this.query) : assert(query.isNotEmpty);
FileQuery.empty() : query = '';
final String query;
bool get isEmpty => query.isEmpty;
bool get isMultiToken => query.contains(' ');
List<String> get tokens => query.split(' ');
bool isExactFileNameMatch(ScriptRef script) {
if (isEmpty) return false;
final scriptUri = script.uri!;
final fileName = _fileName(scriptUri);
if (isMultiToken) {
return tokens.every((token) => fileName.caseInsensitiveContains(token));
}
return fileName.caseInsensitiveContains(query);
}
AutoCompleteMatch createExactFileNameAutoCompleteMatch(ScriptRef script) {
final scriptUri = script.uri!;
if (isEmpty) return AutoCompleteMatch(scriptUri);
final fileName = _fileName(scriptUri);
final fileNameIndex = scriptUri.lastIndexOf(fileName);
final matchedSegments = _findExactSegments(fileName)
.map(
(range) =>
Range(range.begin + fileNameIndex, range.end + fileNameIndex),
)
.toList();
return AutoCompleteMatch(scriptUri, matchedSegments: matchedSegments);
}
bool isExactFullPathMatch(ScriptRef script) {
if (isEmpty) return false;
final scriptUri = script.uri!;
if (isMultiToken) {
return tokens.every((token) => scriptUri.caseInsensitiveContains(token));
}
return scriptUri.caseInsensitiveContains(query);
}
AutoCompleteMatch createExactFullPathAutoCompleteMatch(ScriptRef script) {
final scriptUri = script.uri!;
if (isEmpty) return AutoCompleteMatch(scriptUri);
final matchedSegments = _findExactSegments(scriptUri);
return AutoCompleteMatch(scriptUri, matchedSegments: matchedSegments);
}
bool isFuzzyMatch(ScriptRef script) {
if (isEmpty) return false;
final scriptUri = script.uri!;
if (isMultiToken) {
return scriptUri.caseInsensitiveFuzzyMatch(query.replaceAll(' ', ''));
}
return _fileName(scriptUri).caseInsensitiveFuzzyMatch(query);
}
AutoCompleteMatch createFuzzyMatchAutoCompleteMatch(ScriptRef script) {
final scriptUri = script.uri!;
if (isEmpty) return AutoCompleteMatch(scriptUri);
List<Range> matchedSegments;
if (isMultiToken) {
matchedSegments =
_findFuzzySegments(scriptUri, query.replaceAll(' ', ''));
} else {
final fileName = _fileName(scriptUri);
final fileNameIndex = scriptUri.lastIndexOf(fileName);
matchedSegments = _findFuzzySegments(fileName, query)
.map(
(range) =>
Range(range.begin + fileNameIndex, range.end + fileNameIndex),
)
.toList();
}
return AutoCompleteMatch(scriptUri, matchedSegments: matchedSegments);
}
List<Range> _findExactSegments(String file) {
final matchedSegments = <Range>[];
for (final token in isMultiToken ? tokens : [query]) {
final start = file.indexOf(token);
final end = start + token.length;
matchedSegments.add(Range(start, end));
}
matchedSegments
.sort((rangeA, rangeB) => rangeA.begin.compareTo(rangeB.begin));
return matchedSegments;
}
List<Range> _findFuzzySegments(String file, String query) {
final autoCompleteResultSegments = <Range>[];
var queryIndex = 0;
for (int matchIndex = 0; matchIndex < file.length; matchIndex++) {
if (queryIndex == query.length) break;
if (file[matchIndex] == query[queryIndex]) {
final start = matchIndex;
final end = matchIndex + 1;
autoCompleteResultSegments.add(Range(start, end));
queryIndex++;
}
}
return autoCompleteResultSegments;
}
String _fileName(String fullPath) {
return _fileNamesCache[fullPath] ??= fullPath.split('/').last;
}
}
class FileSearchResults {
factory FileSearchResults.emptyQuery(List<ScriptRef> allScripts) {
return FileSearchResults._(
query: FileQuery.empty(),
allScripts: allScripts,
exactFileNameMatches: [],
exactFullPathMatches: [],
fuzzyMatches: [],
);
}
factory FileSearchResults.withQuery({
required FileQuery query,
required List<ScriptRef> allScripts,
}) {
assert(!query.isEmpty);
final List<ScriptRef> exactFileNameMatches = [];
final List<ScriptRef> exactFullPathMatches = [];
final List<ScriptRef> fuzzyMatches = [];
for (final scriptRef in allScripts) {
if (query.isExactFileNameMatch(scriptRef)) {
exactFileNameMatches.add(scriptRef);
} else if (query.isExactFullPathMatch(scriptRef)) {
exactFullPathMatches.add(scriptRef);
} else if (query.isFuzzyMatch(scriptRef)) {
fuzzyMatches.add(scriptRef);
}
}
return FileSearchResults._(
query: query,
allScripts: allScripts,
exactFileNameMatches: exactFileNameMatches,
exactFullPathMatches: exactFullPathMatches,
fuzzyMatches: fuzzyMatches,
);
}
FileSearchResults._({
required this.query,
required this.allScripts,
required List<ScriptRef> exactFileNameMatches,
required List<ScriptRef> exactFullPathMatches,
required List<ScriptRef> fuzzyMatches,
}) : _exactFileNameMatches = exactFileNameMatches,
_exactFullPathMatches = exactFullPathMatches,
_fuzzyMatches = fuzzyMatches;
final List<ScriptRef> allScripts;
final FileQuery query;
final List<ScriptRef> _exactFileNameMatches;
final List<ScriptRef> _exactFullPathMatches;
final List<ScriptRef> _fuzzyMatches;
FileSearchResults get topMatches => _buildTopMatches();
List<ScriptRef> get scriptRefs => query.isEmpty
? allScripts
: [
..._exactFileNameMatches,
..._exactFullPathMatches,
..._fuzzyMatches,
];
List<AutoCompleteMatch> get autoCompleteMatches => query.isEmpty
? allScripts.map((script) => AutoCompleteMatch(script.uri!)).toList()
: [
..._exactFileNameMatches
.map(query.createExactFileNameAutoCompleteMatch)
.toList(),
..._exactFullPathMatches
.map(query.createExactFullPathAutoCompleteMatch)
.toList(),
..._fuzzyMatches
.map(query.createFuzzyMatchAutoCompleteMatch)
.toList(),
];
FileSearchResults copyWith({
List<ScriptRef>? allScripts,
FileQuery? query,
List<ScriptRef>? exactFileNameMatches,
List<ScriptRef>? exactFullPathMatches,
List<ScriptRef>? fuzzyMatches,
}) {
return FileSearchResults._(
query: query ?? this.query,
allScripts: allScripts ?? this.allScripts,
exactFileNameMatches: exactFileNameMatches ?? _exactFileNameMatches,
exactFullPathMatches: exactFullPathMatches ?? _exactFullPathMatches,
fuzzyMatches: fuzzyMatches ?? _fuzzyMatches,
);
}
FileSearchResults _buildTopMatches() {
if (query.isEmpty) {
return copyWith(
allScripts: allScripts.sublist(0, numOfMatchesToShow),
);
}
if (scriptRefs.length <= numOfMatchesToShow) {
return copyWith();
}
final topMatches = <List<ScriptRef>>[];
int matchesLeft = numOfMatchesToShow;
for (final matches in [
_exactFileNameMatches,
_exactFullPathMatches,
_fuzzyMatches,
]) {
final selected = _takeMatches(matches, matchesLeft);
topMatches.add(selected);
matchesLeft -= selected.length;
}
return copyWith(
exactFileNameMatches: topMatches[0],
exactFullPathMatches: topMatches[1],
fuzzyMatches: topMatches[2],
);
}
List<ScriptRef> _takeMatches(List<ScriptRef> matches, int numToTake) {
if (numToTake <= 0) {
return [];
}
if (matches.length > numToTake) {
return matches.sublist(0, numToTake);
}
return matches;
}
}
| devtools/packages/devtools_app/lib/src/screens/debugger/file_search.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/debugger/file_search.dart",
"repo_id": "devtools",
"token_count": 4597
} | 94 |
// 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.
/// This library must not have direct dependencies on dart:html.
///
/// This allows tests of the complicated logic in this class to run on the VM
/// and will help simplify porting this code to work with Hummingbird.
///
/// This code is directly based on
/// src/io/flutter/view/InspectorPanel.java
/// with some refactors to make the code more of a controller than a combination
/// of view and controller. View specific portions of InspectorPanel.java have
/// been moved to inspector.dart.
library;
import 'dart:async';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:vm_service/vm_service.dart';
import '../../service/service_extensions.dart' as extensions;
import '../../shared/console/eval/inspector_tree.dart';
import '../../shared/console/primitives/simple_items.dart';
import '../../shared/diagnostics/diagnostics_node.dart';
import '../../shared/diagnostics/inspector_service.dart';
import '../../shared/diagnostics/primitives/instance_ref.dart';
import '../../shared/globals.dart';
import '../../shared/primitives/utils.dart';
import 'inspector_screen.dart';
import 'inspector_tree_controller.dart';
final _log = Logger('inspector_controller');
const inspectorRefQueryParam = 'inspectorRef';
/// This class is based on the InspectorPanel class from the Flutter IntelliJ
/// plugin with some refactors to make it more of a true controller than a view.
class InspectorController extends DisposableController
with AutoDisposeControllerMixin
implements InspectorServiceClient {
InspectorController({
required this.inspectorTree,
InspectorTreeController? detailsTree,
required this.treeType,
this.parent,
this.isSummaryTree = true,
}) : assert((detailsTree != null) == isSummaryTree) {
unawaited(_init(detailsTree: detailsTree));
}
Future<void> _init({
InspectorTreeController? detailsTree,
}) async {
_refreshRateLimiter = RateLimiter(refreshFramesPerSecond, refresh);
inspectorTree.config = InspectorTreeConfig(
onNodeAdded: _onNodeAdded,
onSelectionChange: selectionChanged,
onExpand: _onExpand,
onClientActiveChange: _onClientChange,
);
details = isSummaryTree
? InspectorController(
inspectorTree: detailsTree!,
treeType: treeType,
parent: this,
isSummaryTree: false,
)
: null;
await serviceConnection.serviceManager.onServiceAvailable;
if (inspectorService is InspectorService) {
_treeGroups = InspectorObjectGroupManager(
serviceConnection.inspectorService as InspectorService,
'tree',
);
_selectionGroups = InspectorObjectGroupManager(
serviceConnection.inspectorService as InspectorService,
'selection',
);
}
addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.mainIsolate,
() {
final isolate =
serviceConnection.serviceManager.isolateManager.mainIsolate.value;
if (isolate != _mainIsolate) {
onIsolateStopped();
}
_mainIsolate = isolate;
},
);
// This logic only needs to be run once so run it in the outermost
// controller.
if (parent == null) {
// If select mode is available, enable the on device inspector as it
// won't interfere with users.
addAutoDisposeListener(_supportsToggleSelectWidgetMode, () {
if (_supportsToggleSelectWidgetMode.value) {
serviceConnection.serviceManager.serviceExtensionManager
.setServiceExtensionState(
extensions.enableOnDeviceInspector.extension,
enabled: true,
value: true,
);
}
});
}
addAutoDisposeListener(serviceConnection.serviceManager.connectedState, () {
if (serviceConnection.serviceManager.connectedState.value.connected) {
_handleConnectionStart();
} else {
_handleConnectionStop();
}
});
if (serviceConnection.serviceManager.connectedAppInitialized) {
_handleConnectionStart();
}
serviceConnection.consoleService.ensureServiceInitialized();
}
void _handleConnectionStart() {
// Clear any existing badge/errors for older errors that were collected.
// Do this in a post frame callback so that we are not trying to clear the
// error notifiers for this screen while the framework is already in the
// process of building widgets.
// TODO(kenz): When this method is called outside createState(), this post
// frame callback can be removed.
WidgetsBinding.instance.addPostFrameCallback((_) {
serviceConnection.errorBadgeManager.clearErrors(InspectorScreen.id);
});
filterErrors();
}
void _handleConnectionStop() {
setActivate(false);
if (isSummaryTree) {
dispose();
}
}
IsolateRef? _mainIsolate;
ValueListenable<bool> get _supportsToggleSelectWidgetMode =>
serviceConnection.serviceManager.serviceExtensionManager
.hasServiceExtension(extensions.toggleSelectWidgetMode.extension);
void _onClientChange(bool added) {
if (!added && _clientCount == 0) {
// Don't try to remove clients if there are none
return;
}
_clientCount += added ? 1 : -1;
assert(_clientCount >= 0);
if (_clientCount == 1) {
setVisibleToUser(true);
setActivate(true);
} else if (_clientCount == 0) {
setVisibleToUser(false);
}
}
int _clientCount = 0;
/// Maximum frame rate to refresh the inspector at to avoid taxing the
/// physical device with too many requests to recompute properties and trees.
///
/// A value up to around 30 frames per second could be reasonable for
/// debugging highly interactive cases particularly when the user is on a
/// simulator or high powered native device. The frame rate is set low
/// for now mainly to minimize risk.
static const double refreshFramesPerSecond = 5.0;
final bool isSummaryTree;
/// Parent InspectorController if this is a details subtree.
InspectorController? parent;
InspectorController? details;
InspectorTreeController inspectorTree;
final FlutterTreeType treeType;
bool _disposed = false;
late RateLimiter _refreshRateLimiter;
InspectorServiceBase get inspectorService =>
serviceConnection.inspectorService as InspectorServiceBase;
/// Groups used to manage and cancel requests to load data to display directly
/// in the tree.
InspectorObjectGroupManager? _treeGroups;
/// Groups used to manage and cancel requests to determine what the current
/// selection is.
///
/// This group needs to be kept separate from treeGroups as the selection is
/// shared more with the details subtree.
/// TODO(jacobr): is there a way we can unify the selection and tree groups?
InspectorObjectGroupManager? _selectionGroups;
/// Node being highlighted due to the current hover.
InspectorTreeNode? get currentShowNode => inspectorTree.hover;
set currentShowNode(InspectorTreeNode? node) => inspectorTree.hover = node;
bool flutterAppFrameReady = false;
bool treeLoadStarted = false;
RemoteDiagnosticsNode? subtreeRoot;
bool programmaticSelectionChangeInProgress = false;
ValueListenable<InspectorTreeNode?> get selectedNode => _selectedNode;
final ValueNotifier<InspectorTreeNode?> _selectedNode = ValueNotifier(null);
InspectorTreeNode? lastExpanded;
bool isActive = false;
final Map<InspectorInstanceRef, InspectorTreeNode> valueToInspectorTreeNode =
{};
/// When visibleToUser is false we should dispose all allocated objects and
/// not perform any actions.
bool visibleToUser = false;
bool highlightNodesShownInBothTrees = false;
bool get detailsSubtree => parent != null;
RemoteDiagnosticsNode? get selectedDiagnostic =>
selectedNode.value?.diagnostic;
final ValueNotifier<int?> _selectedErrorIndex = ValueNotifier<int?>(null);
ValueListenable<int?> get selectedErrorIndex => _selectedErrorIndex;
/// Tracks whether the first load of the inspector tree has been completed.
///
/// This field is used to prevent sending multiple analytics events for
/// inspector tree load timing.
bool firstInspectorTreeLoadCompleted = false;
FlutterTreeType getTreeType() {
return treeType;
}
void setVisibleToUser(bool visible) {
if (visibleToUser == visible) {
return;
}
visibleToUser = visible;
if (visibleToUser) {
if (parent == null) {
unawaited(maybeLoadUI());
}
} else {
shutdownTree(false);
}
}
bool hasDiagnosticsValue(InspectorInstanceRef ref) {
return valueToInspectorTreeNode.containsKey(ref);
}
RemoteDiagnosticsNode? findDiagnosticsValue(InspectorInstanceRef ref) {
return valueToInspectorTreeNode[ref]?.diagnostic;
}
void endShowNode() {
highlightShowNode(null);
}
bool highlightShowFromNodeInstanceRef(InspectorInstanceRef ref) {
return highlightShowNode(valueToInspectorTreeNode[ref]);
}
bool highlightShowNode(InspectorTreeNode? node) {
if (node == null && parent != null) {
// If nothing is highlighted, highlight the node selected in the parent
// tree so user has context of where the node selected in the parent is
// in the details tree.
node = findMatchingInspectorTreeNode(parent?.selectedDiagnostic);
}
currentShowNode = node;
return true;
}
InspectorTreeNode? findMatchingInspectorTreeNode(
RemoteDiagnosticsNode? node,
) {
final valueRef = node?.valueRef;
if (valueRef == null) {
return null;
}
return valueToInspectorTreeNode[valueRef];
}
Future<void> _waitForPendingUpdateDone() async {
// Wait for the selection to be resolved followed by waiting for the tree to be computed.
await _selectionGroups?.pendingUpdateDone;
await _treeGroups?.pendingUpdateDone;
// TODO(jacobr): are there race conditions we need to think more carefully about here?
}
Future<void> refresh() {
if (!visibleToUser) {
// We will refresh again once we are visible.
// There is a risk a refresh got triggered before the view was visble.
return Future.value();
}
// TODO(jacobr): refresh the tree as well as just the properties.
final detailsLocal = details;
if (detailsLocal == null) return _waitForPendingUpdateDone();
return Future.wait([
_waitForPendingUpdateDone(),
detailsLocal._waitForPendingUpdateDone(),
]);
}
// Note that this may be called after the controller is disposed. We need to handle nulls in the fields.
void shutdownTree(bool isolateStopped) {
// It is critical we clear all data that is kept alive by inspector object
// references in this method as that stale data will trigger inspector
// exceptions.
programmaticSelectionChangeInProgress = true;
_treeGroups?.clear(isolateStopped);
_selectionGroups?.clear(isolateStopped);
currentShowNode = null;
_selectedNode.value = null;
lastExpanded = null;
subtreeRoot = null;
inspectorTree.root = inspectorTree.createNode();
programmaticSelectionChangeInProgress = false;
valueToInspectorTreeNode.clear();
}
void onIsolateStopped() {
flutterAppFrameReady = false;
treeLoadStarted = false;
shutdownTree(true);
}
@override
Future<void> onForceRefresh() async {
assert(!_disposed);
if (!visibleToUser || _disposed) {
return;
}
await _recomputeTreeRoot(null, null, false);
if (_disposed) {
return;
}
filterErrors();
return _waitForPendingUpdateDone();
}
void filterErrors() {
if (isSummaryTree) {
serviceConnection.errorBadgeManager.filterErrors(
InspectorScreen.id,
(id) => hasDiagnosticsValue(InspectorInstanceRef(id)),
);
}
}
void setActivate(bool enabled) {
if (!enabled) {
onIsolateStopped();
isActive = false;
return;
}
if (isActive) {
// Already activated.
return;
}
isActive = true;
inspectorService.addClient(this);
unawaited(maybeLoadUI());
}
Future<void> maybeLoadUI() async {
if (parent != null) {
// The parent controller will drive loading the UI.
return;
}
if (!visibleToUser || !isActive) {
return;
}
if (flutterAppFrameReady) {
if (_disposed) return;
// We need to start by querying the inspector service to find out the
// current state of the UI.
final queryParams = loadQueryParams();
final inspectorRef = queryParams.containsKey(inspectorRefQueryParam)
? queryParams[inspectorRefQueryParam]
: null;
await updateSelectionFromService(
firstFrame: true,
inspectorRef: inspectorRef,
);
} else {
if (_disposed) return;
if (inspectorService is InspectorService) {
final widgetTreeReady =
await (inspectorService as InspectorService).isWidgetTreeReady();
flutterAppFrameReady = widgetTreeReady;
}
if (isActive && flutterAppFrameReady) {
await maybeLoadUI();
}
}
}
Future<void> _recomputeTreeRoot(
RemoteDiagnosticsNode? newSelection,
RemoteDiagnosticsNode? detailsSelection,
bool setSubtreeRoot, {
int subtreeDepth = 2,
}) async {
assert(!_disposed);
final treeGroups = _treeGroups;
if (_disposed || treeGroups == null) {
return;
}
treeGroups.cancelNext();
try {
final group = treeGroups.next;
final node = await (detailsSubtree
? group.getDetailsSubtree(subtreeRoot, subtreeDepth: subtreeDepth)
: group.getRoot(treeType));
if (node == null || group.disposed || _disposed) {
return;
}
// TODO(jacobr): as a performance optimization we should check if the
// new tree is identical to the existing tree in which case we should
// dispose the new tree and keep the old tree.
treeGroups.promoteNext();
_clearValueToInspectorTreeNodeMapping();
final InspectorTreeNode rootNode = inspectorTree.setupInspectorTreeNode(
inspectorTree.createNode(),
node,
expandChildren: true,
expandProperties: false,
);
inspectorTree.root = rootNode;
refreshSelection(newSelection, detailsSelection, setSubtreeRoot);
} catch (error, st) {
_log.shout(error, error, st);
treeGroups.cancelNext();
return;
}
}
void _clearValueToInspectorTreeNodeMapping() {
valueToInspectorTreeNode.clear();
}
/// Show the details subtree starting with node subtreeRoot highlighting
/// node subtreeSelection.
void _showDetailSubtrees(
RemoteDiagnosticsNode? subtreeRoot,
RemoteDiagnosticsNode? subtreeSelection,
) {
this.subtreeRoot = subtreeRoot;
details?.setSubtreeRoot(subtreeRoot, subtreeSelection);
}
void setSubtreeRoot(
RemoteDiagnosticsNode? node,
RemoteDiagnosticsNode? selection,
) {
assert(detailsSubtree);
selection ??= node;
if (node != null && node == subtreeRoot) {
// Select the new node in the existing subtree.
applyNewSelection(selection, null, false);
return;
}
subtreeRoot = node;
if (node == null) {
// Passing in a null node indicates we should clear the subtree and free any memory allocated.
shutdownTree(false);
return;
}
// Clear now to eliminate frame of highlighted nodes flicker.
_clearValueToInspectorTreeNodeMapping();
unawaited(_recomputeTreeRoot(selection, null, false));
}
InspectorTreeNode? getSubtreeRootNode() {
if (subtreeRoot == null) {
return null;
}
return valueToInspectorTreeNode[subtreeRoot!.valueRef];
}
void refreshSelection(
RemoteDiagnosticsNode? newSelection,
RemoteDiagnosticsNode? detailsSelection,
bool setSubtreeRoot,
) {
newSelection ??= selectedDiagnostic;
setSelectedNode(findMatchingInspectorTreeNode(newSelection));
syncSelectionHelper(
maybeRerootDetailsTree: setSubtreeRoot,
selection: newSelection,
detailsSelection: detailsSelection,
);
final detailsLocal = details;
if (detailsLocal != null) {
if (subtreeRoot != null && getSubtreeRootNode() == null) {
subtreeRoot = newSelection;
detailsLocal.setSubtreeRoot(newSelection, detailsSelection);
}
}
syncTreeSelection();
}
void syncTreeSelection() {
programmaticSelectionChangeInProgress = true;
inspectorTree.selection = selectedNode.value;
inspectorTree.expandPath(selectedNode.value);
programmaticSelectionChangeInProgress = false;
animateTo(selectedNode.value);
}
void selectAndShowNode(RemoteDiagnosticsNode? node) {
if (node == null) {
return;
}
selectAndShowInspectorInstanceRef(node.valueRef);
}
void selectAndShowInspectorInstanceRef(InspectorInstanceRef ref) {
final node = valueToInspectorTreeNode[ref];
if (node == null) {
return;
}
setSelectedNode(node);
syncTreeSelection();
}
InspectorTreeNode? getTreeNode(RemoteDiagnosticsNode node) {
return valueToInspectorTreeNode[node.valueRef];
}
void maybeUpdateValueUI(InspectorInstanceRef valueRef) {
final node = valueToInspectorTreeNode[valueRef];
if (node == null) {
// The value isn't shown in the parent tree. Nothing to do.
return;
}
inspectorTree.nodeChanged(node);
}
@override
void onFlutterFrame() {
flutterAppFrameReady = true;
if (!visibleToUser) {
return;
}
if (!treeLoadStarted) {
treeLoadStarted = true;
// This was the first frame.
unawaited(maybeLoadUI());
}
_refreshRateLimiter.scheduleRequest();
}
@override
void onInspectorSelectionChanged() {
if (!visibleToUser) {
// Don't do anything. We will update the view once it is visible again.
return;
}
if (detailsSubtree) {
// Wait for the master to update.
return;
}
unawaited(updateSelectionFromService(firstFrame: false));
}
Future<void> updateSelectionFromService({
required bool firstFrame,
String? inspectorRef,
}) async {
if (parent != null) {
// If we have a parent controller we should wait for the parent to update
// our selection rather than updating it our self.
return;
}
final selectionGroups = _selectionGroups;
if (selectionGroups == null) {
// Already disposed. Ignore this requested to update selection.
return;
}
treeLoadStarted = true;
selectionGroups.cancelNext();
final group = selectionGroups.next;
if (inspectorRef != null) {
await group.setSelectionInspector(
InspectorInstanceRef(inspectorRef),
false,
);
if (_disposed) return;
}
final pendingSelectionFuture = group.getSelection(
selectedDiagnostic,
treeType,
isSummaryTree: isSummaryTree,
);
final Future<RemoteDiagnosticsNode?>? pendingDetailsFuture = isSummaryTree
? group.getSelection(selectedDiagnostic, treeType, isSummaryTree: false)
: null;
try {
final RemoteDiagnosticsNode? newSelection = await pendingSelectionFuture;
if (_disposed || group.disposed) return;
RemoteDiagnosticsNode? detailsSelection;
if (pendingDetailsFuture != null) {
detailsSelection = await pendingDetailsFuture;
if (_disposed || group.disposed) return;
}
if (!firstFrame &&
detailsSelection?.valueRef == details?.selectedDiagnostic?.valueRef &&
newSelection?.valueRef == selectedDiagnostic?.valueRef) {
// No need to change the selection as it didn't actually change.
selectionGroups.cancelNext();
return;
}
selectionGroups.promoteNext();
subtreeRoot = newSelection;
applyNewSelection(newSelection, detailsSelection, true);
} catch (error, st) {
if (selectionGroups.next == group) {
_log.shout(error, error, st);
selectionGroups.cancelNext();
}
}
}
void applyNewSelection(
RemoteDiagnosticsNode? newSelection,
RemoteDiagnosticsNode? detailsSelection,
bool setSubtreeRoot,
) {
final InspectorTreeNode? nodeInTree =
findMatchingInspectorTreeNode(newSelection);
if (nodeInTree == null) {
// The tree has probably changed since we last updated. Do a full refresh
// so that the tree includes the new node we care about.
unawaited(
_recomputeTreeRoot(newSelection, detailsSelection, setSubtreeRoot),
);
}
refreshSelection(newSelection, detailsSelection, setSubtreeRoot);
}
void animateTo(InspectorTreeNode? node) {
if (node == null) {
return;
}
inspectorTree.animateToTargets([node]);
}
void setSelectedNode(InspectorTreeNode? newSelection) {
if (newSelection == selectedNode.value) {
return;
}
_selectedNode.value = newSelection;
lastExpanded = null; // New selected node takes precedence.
endShowNode();
final detailsLocal = details;
final parantLocal = parent;
if (detailsLocal != null) {
detailsLocal.endShowNode();
} else if (parantLocal != null) {
parantLocal.endShowNode();
}
_updateSelectedErrorFromNode(_selectedNode.value);
animateTo(selectedNode.value);
}
/// Update the index of the selected error based on a node that has been
/// selected in the tree.
void _updateSelectedErrorFromNode(InspectorTreeNode? node) {
final inspectorRef = node?.diagnostic?.valueRef.id;
final errors = serviceConnection.errorBadgeManager
.erroredItemsForPage(InspectorScreen.id)
.value;
// Check whether the node that was just selected has any errors associated
// with it.
var errorIndex = inspectorRef != null
? errors.keys.toList().indexOf(inspectorRef)
: null;
if (errorIndex == -1) {
errorIndex = null;
}
_selectedErrorIndex.value = errorIndex;
if (errorIndex != null) {
// Mark the error as "seen" as this will render slightly differently
// so the user can track which errored nodes they've viewed.
serviceConnection.errorBadgeManager
.markErrorAsRead(InspectorScreen.id, errors[inspectorRef!]!);
// Also clear the error badge since new errors may have arrived while
// the inspector was visible (normally they're cleared when visiting
// the screen) and visiting an errored node seems an appropriate
// acknowledgement of the errors.
serviceConnection.errorBadgeManager.clearErrors(InspectorScreen.id);
}
}
/// Updates the index of the selected error and selects its node in the tree.
void selectErrorByIndex(int index) {
_selectedErrorIndex.value = index;
final errors = serviceConnection.errorBadgeManager
.erroredItemsForPage(InspectorScreen.id)
.value;
unawaited(
updateSelectionFromService(
firstFrame: false,
inspectorRef: errors.keys.elementAt(index),
),
);
}
void _onExpand(InspectorTreeNode node) {
unawaited(inspectorTree.maybePopulateChildren(node));
}
Future<void> _addNodeToConsole(InspectorTreeNode node) async {
final valueRef = node.diagnostic!.valueRef;
final isolateRef = inspectorService.isolateRef;
final instanceRef = await node.diagnostic!.objectGroupApi
?.toObservatoryInstanceRef(valueRef);
if (_disposed) return;
if (instanceRef != null) {
serviceConnection.consoleService.appendInstanceRef(
value: instanceRef,
diagnostic: node.diagnostic,
isolateRef: isolateRef,
forceScrollIntoView: true,
);
}
}
void selectionChanged() {
if (!visibleToUser) {
return;
}
final InspectorTreeNode? node = inspectorTree.selection;
if (node != null) {
unawaited(inspectorTree.maybePopulateChildren(node));
}
if (programmaticSelectionChangeInProgress) {
return;
}
if (node != null) {
setSelectedNode(node);
unawaited(_addNodeToConsole(node));
// Don't reroot if the selected value is already visible in the details tree.
final bool maybeReroot = isSummaryTree &&
details != null &&
selectedDiagnostic != null &&
!details!.hasDiagnosticsValue(selectedDiagnostic!.valueRef);
syncSelectionHelper(
maybeRerootDetailsTree: maybeReroot,
selection: selectedDiagnostic,
detailsSelection: selectedDiagnostic,
);
if (!maybeReroot) {
final parantLocal = parent;
final detailsLocal = details;
if (isSummaryTree && detailsLocal != null) {
detailsLocal.selectAndShowNode(selectedDiagnostic);
} else if (parantLocal != null) {
parantLocal
.selectAndShowNode(firstAncestorInParentTree(selectedNode.value));
}
}
}
}
RemoteDiagnosticsNode? firstAncestorInParentTree(InspectorTreeNode? node) {
final parentLocal = parent;
if (parentLocal == null) {
return node?.diagnostic;
}
while (node != null) {
final diagnostic = node.diagnostic;
if (diagnostic != null &&
parentLocal.hasDiagnosticsValue(diagnostic.valueRef)) {
return parentLocal.findDiagnosticsValue(diagnostic.valueRef);
}
node = node.parent;
}
return null;
}
void syncSelectionHelper({
required bool maybeRerootDetailsTree,
required RemoteDiagnosticsNode? selection,
required RemoteDiagnosticsNode? detailsSelection,
}) {
if (selection != null) {
if (selection.isCreatedByLocalProject) {
_navigateTo(selection);
}
}
if (detailsSubtree || details == null) {
if (selection != null) {
var toSelect = selectedNode.value;
while (toSelect != null && toSelect.diagnostic!.isProperty) {
toSelect = toSelect.parent;
}
if (toSelect != null) {
final diagnosticToSelect = toSelect.diagnostic!;
unawaited(diagnosticToSelect.setSelectionInspector(true));
}
}
}
if (maybeRerootDetailsTree) {
_showDetailSubtrees(selection, detailsSelection);
} else if (selection != null) {
// We can't rely on the details tree to update the selection on the server in this case.
unawaited(selection.setSelectionInspector(true));
}
}
// TODO(jacobr): implement this method and use the parameter.
// ignore: avoid-unused-parameters
void _navigateTo(RemoteDiagnosticsNode diagnostic) {
// TODO(jacobr): dispatch an event over the inspectorService requesting a
// navigate operation.
}
@override
void dispose() {
assert(!_disposed);
_disposed = true;
if (serviceConnection.inspectorService != null) {
shutdownTree(false);
}
_treeGroups?.clear(false);
_treeGroups = null;
_selectionGroups?.clear(false);
_selectionGroups = null;
details?.dispose();
super.dispose();
}
void _onNodeAdded(
InspectorTreeNode node,
RemoteDiagnosticsNode diagnosticsNode,
) {
final InspectorInstanceRef valueRef = diagnosticsNode.valueRef;
// Properties do not have unique values so should not go in the valueToInspectorTreeNode map.
if (valueRef.id != null && !diagnosticsNode.isProperty) {
valueToInspectorTreeNode[valueRef] = node;
}
}
Future<void> expandAllNodesInDetailsTree() async {
final detailsLocal = details!;
await detailsLocal._recomputeTreeRoot(
inspectorTree.selection?.diagnostic,
detailsLocal.inspectorTree.selection?.diagnostic ??
detailsLocal.inspectorTree.root?.diagnostic,
false,
subtreeDepth: maxJsInt,
);
}
void collapseDetailsToSelected() {
final detailsLocal = details!;
detailsLocal.inspectorTree.collapseToSelected();
detailsLocal.animateTo(detailsLocal.inspectorTree.selection);
}
}
| devtools/packages/devtools_app/lib/src/screens/inspector/inspector_controller.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/inspector_controller.dart",
"repo_id": "devtools",
"token_count": 9976
} | 95 |
// 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/primitives/math_utils.dart';
import '../../../../shared/primitives/utils.dart';
import '../../inspector_data_models.dart';
import 'arrow.dart';
import 'dimension.dart';
import 'theme.dart';
import 'utils.dart';
class VisualizeWidthAndHeightWithConstraints extends StatelessWidget {
VisualizeWidthAndHeightWithConstraints({
super.key,
required this.properties,
double? arrowHeadSize,
required this.child,
this.warnIfUnconstrained = true,
}) : arrowHeadSize = arrowHeadSize ?? defaultIconSize;
final Widget child;
final LayoutProperties properties;
final double arrowHeadSize;
final bool warnIfUnconstrained;
@override
Widget build(BuildContext context) {
final propertiesLocal = properties;
final showChildrenWidthsSum = propertiesLocal is FlexLayoutProperties &&
propertiesLocal.isOverflowWidth;
final bottomHeight = widthAndConstraintIndicatorSize;
final rightWidth = heightAndConstraintIndicatorSize;
final colorScheme = Theme.of(context).colorScheme;
final showOverflowHeight =
properties is FlexLayoutProperties && propertiesLocal.isOverflowHeight;
final heightDescription = RotatedBox(
quarterTurns: 1,
child: dimensionDescription(
TextSpan(
children: [
TextSpan(
text: propertiesLocal.describeHeight(),
),
if (propertiesLocal.constraints != null) ...[
if (!showOverflowHeight) const TextSpan(text: '\n'),
TextSpan(
text: ' (${propertiesLocal.describeHeightConstraints()})',
style: propertiesLocal.constraints!.hasBoundedHeight ||
!warnIfUnconstrained
? null
: TextStyle(
color: colorScheme.unconstrainedColor,
),
),
],
if (showOverflowHeight)
TextSpan(
text: '\nchildren take: '
'${toStringAsFixed(sum(propertiesLocal.childrenHeights.cast<double>()))}',
),
],
),
propertiesLocal.isOverflowHeight,
colorScheme,
),
);
final right = Container(
margin: EdgeInsets.only(
top: margin,
left: margin,
bottom: bottomHeight,
right: minPadding, // custom margin for not sticking to the corner
),
child: LayoutBuilder(
builder: (context, constraints) {
final displayHeightOutsideArrow =
constraints.maxHeight < minHeightToDisplayHeightInsideArrow;
return Row(
children: [
Truncateable(
truncate: !displayHeightOutsideArrow,
child: Container(
margin: EdgeInsets.symmetric(horizontal: arrowMargin),
child: ArrowWrapper.bidirectional(
arrowColor: heightIndicatorColor,
arrowStrokeWidth: arrowStrokeWidth,
arrowHeadSize: arrowHeadSize,
direction: Axis.vertical,
child: displayHeightOutsideArrow ? null : heightDescription,
),
),
),
if (displayHeightOutsideArrow)
Flexible(
child: heightDescription,
),
],
);
},
),
);
final widthDescription = dimensionDescription(
TextSpan(
children: [
TextSpan(text: '${propertiesLocal.describeWidth()}; '),
if (propertiesLocal.constraints != null) ...[
if (!showChildrenWidthsSum) const TextSpan(text: '\n'),
TextSpan(
text: '(${propertiesLocal.describeWidthConstraints()})',
style: propertiesLocal.constraints!.hasBoundedWidth ||
!warnIfUnconstrained
? null
: TextStyle(color: colorScheme.unconstrainedColor),
),
],
if (showChildrenWidthsSum)
TextSpan(
text: '\nchildren take '
'${toStringAsFixed(sum(propertiesLocal.childrenWidths.cast<double>()))}',
),
],
),
propertiesLocal.isOverflowWidth,
colorScheme,
);
final bottom = Container(
margin: EdgeInsets.only(
top: margin,
left: margin,
right: rightWidth,
bottom: minPadding,
),
child: LayoutBuilder(
builder: (context, constraints) {
final maxWidth = constraints.maxWidth;
final displayWidthOutsideArrow =
maxWidth < minWidthToDisplayWidthInsideArrow;
return Column(
children: [
Truncateable(
truncate: !displayWidthOutsideArrow,
child: Container(
margin: EdgeInsets.symmetric(vertical: arrowMargin),
child: ArrowWrapper.bidirectional(
arrowColor: widthIndicatorColor,
arrowHeadSize: arrowHeadSize,
arrowStrokeWidth: arrowStrokeWidth,
direction: Axis.horizontal,
child: displayWidthOutsideArrow ? null : widthDescription,
),
),
),
if (displayWidthOutsideArrow)
Flexible(
child: Container(
padding: const EdgeInsets.only(top: minPadding),
child: widthDescription,
),
),
],
);
},
),
);
return BorderLayout(
center: child,
right: right,
rightWidth: rightWidth,
bottom: bottom,
bottomHeight: bottomHeight,
);
}
}
| devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/widget_constraints.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/widget_constraints.dart",
"repo_id": "devtools",
"token_count": 2925
} | 96 |
// 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';
class StaticMemoryBody extends StatelessWidget {
const StaticMemoryBody({super.key});
@override
Widget build(BuildContext context) {
return const Text('static memory screen body will be here.');
}
}
| devtools/packages/devtools_app/lib/src/screens/memory/framework/static/static_screen_body.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/framework/static/static_screen_body.dart",
"repo_id": "devtools",
"token_count": 116
} | 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 'package:flutter/foundation.dart';
import '../../../../../shared/memory/adapted_heap_data.dart';
import '../../../shared/heap/class_filter.dart';
import '../../../shared/heap/heap.dart';
import '../../../shared/primitives/simple_elements.dart';
import '../data/classes_diff.dart';
class RetainingPathController {
final hideStandard = ValueNotifier<bool>(true);
final invert = ValueNotifier<bool>(true);
}
class ClassesTableSingleData {
ClassesTableSingleData({
required this.heap,
required this.totalHeapSize,
required this.filterData,
});
// We use functions, not [ValueListenable], where we do not want widgets
// to subscribe for the changes, for performance reasons.
/// Function to get currently selected heap.
final HeapDataCallback heap;
/// Function to get total currently selected heap size.
final int Function() totalHeapSize;
/// Current class filter data.
final ClassFilterData filterData;
/// Selected class.
final selection = ValueNotifier<SingleClassStats?>(null);
}
class ClassesTableDiffData {
ClassesTableDiffData({
required this.before,
required this.after,
required this.filterData,
});
/// Size type to show.
final selectedSizeType = ValueNotifier<SizeType>(SizeType.retained);
// We use functions, not [ValueListenable], where we do not want widgets
// to subscribe for the changes, for performance reasons.
/// Function to get selected first heap to diff.
final HeapDataCallback before;
/// Function to get selected second heap to diff.
final HeapDataCallback after;
/// Current class filter data.
final ClassFilterData filterData;
/// Selected class.
final selection = ValueNotifier<DiffClassData?>(null);
}
| devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/controller/class_data.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/controller/class_data.dart",
"repo_id": "devtools",
"token_count": 539
} | 98 |
Documentation: https://docs.flutter.dev/development/tools/devtools/memory#profile-tab | devtools/packages/devtools_app/lib/src/screens/memory/panes/profile/ALLOCATION_PROFILE.md/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/profile/ALLOCATION_PROFILE.md",
"repo_id": "devtools",
"token_count": 24
} | 99 |
// 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 '../../../../shared/common_widgets.dart';
import '../../../../shared/primitives/utils.dart';
typedef MenuBuilder = List<Widget> Function();
/// A display for count of instances that may include a context menu button.
class InstanceViewWithContextMenu extends StatelessWidget {
const InstanceViewWithContextMenu({
super.key,
required this.count,
required this.menuBuilder,
}) : assert(count >= 0);
final int count;
final MenuBuilder? menuBuilder;
@override
Widget build(BuildContext context) {
final menu = menuBuilder?.call() ?? [];
final shouldShowMenu = menu.isNotEmpty && count > 0;
const menuButtonWidth = ContextMenuButton.defaultWidth;
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Expanded(
child: Text(
nf.format(count),
textAlign: TextAlign.end,
),
),
if (shouldShowMenu)
ContextMenuButton(
// ignore: avoid_redundant_argument_values, ensures consistency with [SizedBox] below.
buttonWidth: menuButtonWidth,
menuChildren: menu,
)
else
const SizedBox(width: menuButtonWidth),
],
);
}
}
| devtools/packages/devtools_app/lib/src/screens/memory/shared/primitives/instance_context_menu.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/shared/primitives/instance_context_menu.dart",
"repo_id": "devtools",
"token_count": 560
} | 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:flutter/foundation.dart';
import '../../frame_analysis/frame_analysis_model.dart';
@immutable
class EnhanceTracingState {
const EnhanceTracingState({
required this.builds,
required this.layouts,
required this.paints,
});
final bool builds;
final bool layouts;
final bool paints;
bool enhancedFor(FramePhaseType type) {
switch (type) {
case FramePhaseType.build:
return builds;
case FramePhaseType.layout:
return layouts;
case FramePhaseType.paint:
return paints;
default:
return false;
}
}
}
| devtools/packages/devtools_app/lib/src/screens/performance/panes/controls/enhance_tracing/enhance_tracing_model.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/controls/enhance_tracing/enhance_tracing_model.dart",
"repo_id": "devtools",
"token_count": 268
} | 101 |
// 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:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:vm_service/vm_service.dart' hide Stack;
import '../../shared/analytics/analytics.dart' as ga;
import '../../shared/analytics/constants.dart' as gac;
import '../../shared/banner_messages.dart';
import '../../shared/common_widgets.dart';
import '../../shared/config_specific/import_export/import_export.dart';
import '../../shared/file_import.dart';
import '../../shared/globals.dart';
import '../../shared/primitives/listenable.dart';
import '../../shared/screen.dart';
import '../../shared/utils.dart';
import 'cpu_profile_model.dart';
import 'cpu_profiler.dart';
import 'cpu_profiler_controller.dart';
import 'panes/controls/profiler_screen_controls.dart';
import 'profiler_screen_controller.dart';
import 'profiler_status.dart';
class ProfilerScreen extends Screen {
ProfilerScreen() : super.fromMetaData(ScreenMetaData.cpuProfiler);
static final id = ScreenMetaData.cpuProfiler.id;
@override
String get docPageId => id;
@override
ValueListenable<bool> get showIsolateSelector =>
const FixedValueListenable<bool>(true);
@override
Widget buildScreenBody(BuildContext context) {
return const ProfilerScreenBody();
}
@override
Widget buildDisconnectedScreenBody(BuildContext context) {
return const DisconnectedCpuProfilerScreenBody();
}
}
class ProfilerScreenBody extends StatefulWidget {
const ProfilerScreenBody({super.key});
@override
State<ProfilerScreenBody> createState() => _ProfilerScreenBodyState();
}
class _ProfilerScreenBodyState extends State<ProfilerScreenBody>
with
AutoDisposeMixin,
ProvidedControllerMixin<ProfilerScreenController, ProfilerScreenBody> {
bool recording = false;
late CpuProfilerBusyStatus profilerBusyStatus;
bool get profilerBusy => profilerBusyStatus != CpuProfilerBusyStatus.none;
@override
void initState() {
super.initState();
ga.screen(ProfilerScreen.id);
addAutoDisposeListener(offlineController.offlineMode);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
maybePushDebugModePerformanceMessage(context, ProfilerScreen.id);
if (!initController()) return;
cancelListeners();
addAutoDisposeListener(controller.loadingOfflineData);
recording = controller.recordingNotifier.value;
addAutoDisposeListener(controller.recordingNotifier, () {
setState(() {
recording = controller.recordingNotifier.value;
});
});
profilerBusyStatus =
controller.cpuProfilerController.profilerBusyStatus.value;
addAutoDisposeListener(
controller.cpuProfilerController.profilerBusyStatus,
() {
setState(() {
profilerBusyStatus =
controller.cpuProfilerController.profilerBusyStatus.value;
});
},
);
}
@override
Widget build(BuildContext context) {
if (offlineController.offlineMode.value) {
return _buildProfilerScreenBody(controller);
}
return ValueListenableBuilder<Flag>(
valueListenable: controller.cpuProfilerController.profilerFlagNotifier!,
builder: (context, profilerFlag, _) {
return profilerFlag.valueAsString == 'true'
? _buildProfilerScreenBody(controller)
: CpuProfilerDisabled(controller.cpuProfilerController);
},
);
}
Widget _buildProfilerScreenBody(ProfilerScreenController controller) {
return FutureBuilder(
future: controller.initialized,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done ||
controller.loadingOfflineData.value) {
return Container(
color: Theme.of(context).scaffoldBackgroundColor,
child: const CenteredCircularProgressIndicator(),
);
}
final status = recording || profilerBusy
? (recording
? const RecordingStatus()
: ProfilerBusyStatus(status: profilerBusyStatus))
: null;
return Column(
children: [
ProfilerScreenControls(
controller: controller,
recording: recording,
processing: profilerBusy,
offline: offlineController.offlineMode.value,
),
const SizedBox(height: intermediateSpacing),
Expanded(
child: status ??
ValueListenableBuilder<CpuProfileData?>(
valueListenable:
controller.cpuProfilerController.dataNotifier,
builder: (context, cpuProfileData, _) {
if (cpuProfileData == null ||
cpuProfileData ==
CpuProfilerController.baseStateCpuProfileData) {
return const ProfileRecordingInstructions();
}
if (cpuProfileData ==
CpuProfilerController.emptyAppStartUpProfile) {
return const EmptyAppStartUpProfile();
}
if (cpuProfileData.isEmpty &&
!controller.cpuProfilerController.isFilterActive) {
return const EmptyProfileView();
}
return CpuProfiler(
data: cpuProfileData,
controller: controller.cpuProfilerController,
);
},
),
),
],
);
},
);
}
}
class DisconnectedCpuProfilerScreenBody extends StatelessWidget {
const DisconnectedCpuProfilerScreenBody({super.key});
static const importInstructions =
'Open a CPU profile that was previously saved from DevTools';
@override
Widget build(BuildContext context) {
return FileImportContainer(
instructions: importInstructions,
actionText: 'Load data',
gaScreen: gac.appSize,
gaSelectionImport: gac.CpuProfilerEvents.openDataFile.name,
gaSelectionAction: gac.CpuProfilerEvents.loadDataFromFile.name,
onAction: (jsonFile) {
Provider.of<ImportController>(context, listen: false)
.importData(jsonFile, expectedScreenId: ProfilerScreen.id);
},
);
}
}
| devtools/packages/devtools_app/lib/src/screens/profiler/profiler_screen.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/profiler/profiler_screen.dart",
"repo_id": "devtools",
"token_count": 2715
} | 102 |
// 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:flutter/widgets.dart';
/// A delegate that allows using ListView with an undetermined list length
/// while preserve the "build only what is visible" behaviour.
class SliverIterableChildDelegate extends SliverChildDelegate {
SliverIterableChildDelegate(
this.children, {
this.estimatedChildCount,
});
final Iterable<Widget?> children;
int? _lastAccessedIndex;
late Iterator<Widget?> _lastAccessedIterator;
@override
Widget? build(BuildContext context, int index) {
if (_lastAccessedIndex == null || _lastAccessedIndex! > index) {
_lastAccessedIndex = -1;
_lastAccessedIterator = children.iterator;
}
while (_lastAccessedIndex! < index) {
_lastAccessedIterator.moveNext();
_lastAccessedIndex = _lastAccessedIndex! + 1;
}
return _lastAccessedIterator.current;
}
@override
final int? estimatedChildCount;
@override
bool shouldRebuild(SliverIterableChildDelegate oldDelegate) {
return children != oldDelegate.children ||
_lastAccessedIndex != oldDelegate._lastAccessedIndex ||
_lastAccessedIterator != oldDelegate._lastAccessedIterator;
}
}
| devtools/packages/devtools_app/lib/src/screens/provider/sliver_iterable_child_delegate.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/provider/sliver_iterable_child_delegate.dart",
"repo_id": "devtools",
"token_count": 424
} | 103 |
// 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:flutter/material.dart';
import 'package:vm_service/vm_service.dart';
import '../../../shared/common_widgets.dart';
import '../../../shared/console/widgets/expandable_variable.dart';
import '../../../shared/diagnostics/dart_object_node.dart';
import '../../../shared/diagnostics/tree_builder.dart';
import '../../../shared/globals.dart';
import '../../../shared/primitives/utils.dart';
import '../../../shared/ui/colors.dart';
import '../vm_developer_common_widgets.dart';
import 'object_inspector_view_controller.dart';
import 'vm_object_model.dart';
class VmInstanceDisplay extends StatefulWidget {
const VmInstanceDisplay({
super.key,
required this.controller,
required this.instance,
});
final ObjectInspectorViewController controller;
final InstanceObject instance;
@override
State<StatefulWidget> createState() => _VmInstanceDisplayState();
}
class _VmInstanceDisplayState extends State<VmInstanceDisplay> {
late Future<void> _initialized;
late DartObjectNode _root;
@override
void initState() {
super.initState();
_populate();
}
@override
void didUpdateWidget(VmInstanceDisplay oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.instance == oldWidget.instance) {
return;
}
_populate();
}
void _populate() {
final isolateRef =
serviceConnection.serviceManager.isolateManager.selectedIsolate.value;
_root = DartObjectNode.fromValue(
name: 'value',
value: widget.instance.obj,
isolateRef: isolateRef,
artificialName: true,
);
unawaited(
_initialized = buildVariablesTree(_root)
.then(
(_) => _root.expand(),
)
.then(
(_) => unawaited(
Future.wait([
for (final child in _root.children) buildVariablesTree(child),
]),
),
),
);
}
@override
Widget build(BuildContext context) {
return SplitPane(
axis: Axis.vertical,
initialFractions: const [0.5, 0.5],
children: [
OutlineDecoration.onlyBottom(
child: _InstanceViewer(
controller: widget.controller,
instance: widget.instance,
),
),
OutlineDecoration.onlyTop(
child: Column(
children: [
const AreaPaneHeader(
title: Text('Properties'),
includeTopBorder: false,
),
Flexible(
child: FutureBuilder(
future: _initialized,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CenteredCircularProgressIndicator();
}
return ExpandableVariable(
variable: _root,
dataDisplayProvider: (variable, onPressed) {
return DisplayProvider(
controller: widget.controller,
variable: variable,
onTap: onPressed,
);
},
);
},
),
),
],
),
),
],
);
}
}
class _InstanceViewer extends StatelessWidget {
const _InstanceViewer({
required this.controller,
required this.instance,
});
final ObjectInspectorViewController controller;
final InstanceObject instance;
@override
Widget build(BuildContext context) {
return VmObjectDisplayBasicLayout(
controller: controller,
object: instance,
generalDataRows: [
serviceObjectLinkBuilderMapEntry(
controller: controller,
key: 'Object Class',
object: instance.obj.classRef!,
),
shallowSizeRowBuilder(instance),
reachableSizeRowBuilder(instance),
retainedSizeRowBuilder(instance),
],
);
}
}
class DisplayProvider extends StatelessWidget {
const DisplayProvider({
super.key,
required this.variable,
required this.onTap,
required this.controller,
});
final DartObjectNode variable;
final VoidCallback onTap;
final ObjectInspectorViewController controller;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (variable.text != null) {
return SelectableText.rich(
TextSpan(
children: processAnsiTerminalCodes(
variable.text,
theme.subtleFixedFontStyle,
),
),
onTap: onTap,
);
}
final hasName = variable.name?.isNotEmpty ?? false;
return Row(
children: [
SelectableText.rich(
TextSpan(
text: hasName ? variable.name : null,
style: variable.artificialName
? theme.subtleFixedFontStyle
: theme.fixedFontStyle.apply(
color: theme.colorScheme.controlFlowSyntaxColor,
),
children: [
if (hasName)
TextSpan(
text: ': ',
style: theme.fixedFontStyle,
),
if (variable.ref!.value is Sentinel)
TextSpan(
text: 'Sentinel ${variable.displayValue.toString()}',
style: theme.subtleFixedFontStyle,
),
],
),
onTap: onTap,
),
if (variable.ref!.value is! Sentinel && variable.ref!.value is ObjRef?)
VmServiceObjectLink(
object: variable.ref!.value as ObjRef?,
textBuilder: (object) {
if (object is InstanceRef &&
object.kind == InstanceKind.kString) {
return "'${object.valueAsString}'";
}
return null;
},
onTap: controller.findAndSelectNodeForObject,
)
else
Text(
variable.ref!.value.toString(),
style: Theme.of(context).subtleFixedFontStyle,
),
],
);
}
}
| devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_instance_display.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_instance_display.dart",
"repo_id": "devtools",
"token_count": 2991
} | 104 |
// 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:flutter/foundation.dart';
import 'package:vm_service/vm_service.dart';
/// Converts JSON strings to fake VM service response objects, allowing for
/// the reuse of various data structures that require package:vm_service types.
class JsonToServiceCache {
final _cache = <String, Instance>{
_kTrue.id!: _kTrue,
_kFalse.id!: _kFalse,
_kNull.id!: _kNull,
};
int _idCount = 0;
String _nextId() => 'json-cache-${_idCount++}';
static final _kTrue = Instance(
kind: InstanceKind.kBool,
identityHashCode: -1,
classRef: ClassRef(
name: 'bool',
id: 'json-cache-bool',
),
valueAsString: 'true',
id: 'json-cache-true',
);
static final _kFalse = Instance(
kind: InstanceKind.kBool,
identityHashCode: -1,
classRef: ClassRef(
name: 'bool',
id: 'json-cache-bool',
),
valueAsString: 'false',
id: 'json-cache-false',
);
static final _kNull = Instance(
kind: InstanceKind.kNull,
identityHashCode: -1,
classRef: ClassRef(
name: 'Null',
id: 'json-cache-null-cls',
),
id: 'json-cache-null',
);
static final _kListClass = ClassRef(
name: 'List',
id: 'json-cache-list-class',
);
static final _kMapClass = ClassRef(
name: 'Map',
id: 'json-cache-map-class',
);
/// The current number of non-constant elements in the cache.
@visibleForTesting
int get length => _cache.length - 3;
/// A 'fake' implementation of `VmService.getObject`, used to retrieve a fake
/// service instance from the cache. If `objectId` isn't a valid reference,
/// `null` is returned.
///
/// If provided, `offset` is the start of the range within a collection that
/// should be returned. If `offset` is provided, `count` must also be provided.
/// The result will be an `Instance` containing `count` objects, starting from
/// `offset`.
Instance? getObject({
required String objectId,
int? offset,
int? count,
}) {
final obj = _cache[objectId];
if (obj == null) return null;
if (offset != null && count != null) {
// TODO(bkonyi): consider caching responses for objects with offsets and
// counts.
if (obj.kind == InstanceKind.kList) {
final list = Instance(
kind: InstanceKind.kList,
identityHashCode: -1,
classRef: _kListClass,
id: _nextId(),
offset: offset,
count: count,
elements: obj.elements!.getRange(offset, offset + count).toList(),
);
return list;
} else if (obj.kind == InstanceKind.kMap) {
final map = Instance(
kind: InstanceKind.kMap,
identityHashCode: -1,
classRef: _kMapClass,
id: _nextId(),
offset: offset,
count: count,
associations:
obj.associations!.getRange(offset, offset + count).toList(),
);
return map;
}
}
return obj;
}
/// Recursively inserts fake [Instance] entries in the cache, returning the
/// root [Instance] of the JSON object.
Instance insertJsonObject(Object? json) {
if (json is List) {
return _insertList(json);
} else if (json is Map) {
return _insertMap(json.cast<String, Object?>());
}
return _insertPrimitive(json);
}
/// Recursively removes [Instance] entries in the cache starting from a root
/// [Instance].
void removeJsonObject(Instance root) {
// Don't remove constants from the cache.
if (root.kind == InstanceKind.kBool || root.kind == InstanceKind.kNull) {
return;
}
assert(_cache.containsKey(root.id));
_cache.remove(root.id);
if (root.kind == InstanceKind.kMap) {
for (final entry in root.associations!) {
removeJsonObject(entry.key);
removeJsonObject(entry.value);
}
} else if (root.kind == InstanceKind.kList) {
root.elements!.cast<Instance>().forEach(removeJsonObject);
}
}
Instance _insertMap(Map<String, Object?> json) {
final map = Instance(
kind: InstanceKind.kMap,
identityHashCode: -1,
classRef: _kMapClass,
id: _nextId(),
);
map.associations = <MapAssociation>[
for (final entry in json.entries)
MapAssociation(
key: insertJsonObject(entry.key),
value: insertJsonObject(entry.value),
),
];
map.length = json.length;
_cache[map.id!] = map;
return map;
}
Instance _insertList(List<Object?> json) {
final list = Instance(
kind: InstanceKind.kList,
identityHashCode: -1,
classRef: _kListClass,
id: _nextId(),
);
list.elements = <Instance>[
for (final e in json) insertJsonObject(e),
];
list.length = json.length;
_cache[list.id!] = list;
return list;
}
Instance _insertPrimitive(Object? json) {
assert(
json == null ||
json is String ||
json is int ||
json is double ||
json is bool,
);
Instance instance;
if (json == null) {
instance = _kNull;
} else if (json is String) {
instance = Instance(
kind: InstanceKind.kString,
identityHashCode: -1,
classRef: ClassRef(
name: 'String',
id: 'json-cache-string',
),
id: _nextId(),
valueAsString: json,
);
} else if (json is int) {
instance = Instance(
kind: InstanceKind.kInt,
identityHashCode: json,
classRef: ClassRef(
name: 'int',
id: 'json-cache-int',
),
valueAsString: json.toString(),
id: _nextId(),
);
} else if (json is double) {
instance = Instance(
kind: InstanceKind.kDouble,
identityHashCode: -1,
classRef: ClassRef(
name: 'double',
id: 'json-cache-double',
),
valueAsString: json.toString(),
id: _nextId(),
);
} else if (json is bool) {
instance = json ? _kTrue : _kFalse;
} else {
throw '';
}
_cache[instance.id!] = instance;
return instance;
}
}
| devtools/packages/devtools_app/lib/src/service/json_to_service_cache.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/service/json_to_service_cache.dart",
"repo_id": "devtools",
"token_count": 2644
} | 105 |
// 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 'dart:async';
import 'package:flutter/foundation.dart';
import '_analytics_controller_stub.dart'
if (dart.library.js_interop) '_analytics_controller_web.dart';
Future<AnalyticsController> get analyticsController async =>
await devToolsAnalyticsController;
typedef AsyncAnalyticsCallback = FutureOr<void> Function();
class AnalyticsController {
AnalyticsController({
required bool enabled,
required bool firstRun,
required this.consentMessage,
this.onEnableAnalytics,
this.onDisableAnalytics,
this.onSetupAnalytics,
AsyncAnalyticsCallback? markConsentMessageAsShown,
}) : analyticsEnabled = ValueNotifier<bool>(enabled),
_shouldPrompt =
ValueNotifier<bool>(firstRun && consentMessage.isNotEmpty),
_markConsentMessageAsShown = markConsentMessageAsShown {
if (_shouldPrompt.value) {
unawaited(toggleAnalyticsEnabled(true));
}
if (analyticsEnabled.value) {
setUpAnalytics();
}
}
final ValueNotifier<bool> analyticsEnabled;
ValueListenable<bool> get shouldPrompt => _shouldPrompt;
final ValueNotifier<bool> _shouldPrompt;
bool get analyticsInitialized => _analyticsInitialized;
bool _analyticsInitialized = false;
final AsyncAnalyticsCallback? onEnableAnalytics;
final AsyncAnalyticsCallback? onDisableAnalytics;
/// Method to call to confirm with package:unified_analytics the user has
/// seen the consent message.
final AsyncAnalyticsCallback? _markConsentMessageAsShown;
Future<void> markConsentMessageAsShown() async =>
await _markConsentMessageAsShown?.call();
final VoidCallback? onSetupAnalytics;
/// Consent message for package:unified_analytics to be shown on first run.
final String consentMessage;
Future<void> toggleAnalyticsEnabled(bool? enable) async {
if (enable == true) {
analyticsEnabled.value = true;
if (!_analyticsInitialized) {
setUpAnalytics();
}
if (onEnableAnalytics != null) {
await onEnableAnalytics!();
}
} else {
analyticsEnabled.value = false;
hidePrompt();
if (onDisableAnalytics != null) {
await onDisableAnalytics!();
}
}
}
void setUpAnalytics() {
if (_analyticsInitialized) return;
assert(analyticsEnabled.value = true);
if (onSetupAnalytics != null) {
onSetupAnalytics!();
}
_analyticsInitialized = true;
}
void hidePrompt() {
_shouldPrompt.value = false;
}
}
| devtools/packages/devtools_app/lib/src/shared/analytics/analytics_controller.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/analytics/analytics_controller.dart",
"repo_id": "devtools",
"token_count": 896
} | 106 |
// 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:math';
import 'package:flutter/material.dart';
import 'chart_controller.dart';
class Data {
Data(this.timestamp, this.y);
final int timestamp;
final double y;
}
/// Stores the count of number of same points collected @ timestamp. Used for
/// ExtensionEvents to coallase multiple events to one plotted symbol.
class DataAggregate extends Data {
DataAggregate(int timestamp, double y, this.count) : super(timestamp, y);
final int count;
}
class PaintCharacteristics {
PaintCharacteristics({
required this.color,
this.colorAggregate,
this.symbol = ChartSymbol.ring,
this.strokeWidth = 1,
this.diameter = 1,
this.concentricCenterColor = Colors.black,
this.concentricCenterDiameter = 1,
this.width = 1,
this.height = 1,
this.fixedMinY,
this.fixedMaxY,
});
PaintCharacteristics.concentric({
required this.color,
this.colorAggregate,
this.symbol = ChartSymbol.concentric,
this.strokeWidth = 1,
this.diameter = 1,
this.concentricCenterColor = Colors.black,
this.concentricCenterDiameter = 1,
this.width = 1,
this.height = 1,
this.fixedMinY,
this.fixedMaxY,
});
/// If specified Y scale is computed and min value is fixed.
/// Will assert if new data point is less than min specified.
double? fixedMinY;
/// If specified Y scale is computed and max value is fixed.
/// Will assert if new data point is more than max specified.
double? fixedMaxY;
/// Primary color.
Color color;
/// Center circle color.
Color concentricCenterColor;
/// Center circle size.
double concentricCenterDiameter;
/// Color to use if count > 1.
///
/// See [DataAggregate.count].
Color? colorAggregate;
ChartSymbol symbol;
double strokeWidth;
/// Used for disc or ring (circle).
double diameter;
/// Height and Width used for square or triangle.
double height;
double width;
}
class Trace {
Trace(this.controller, this._chartType, this.characteristics) {
final double minY = characteristics.fixedMinY ?? 0.0;
final double maxY = characteristics.fixedMaxY ?? 0.0;
yAxis = AxisScale(minY, maxY, 30);
}
final ChartController controller;
final ChartType _chartType;
final PaintCharacteristics characteristics;
/// All traces, stacked == true, are aligned to previous stacked trace.
/// E.g., Trace 1, 2, and 3 are all stacked,
///
/// | /'''''''''\ / <--- Trace 3
/// | / \ /
/// |-------/ \ /
/// | /\ _______ \/
/// |/ \____/ \
/// | ___/'''''''\ \ /'''''' <--- Trace 2 (lowest Y is zero)
/// |/ \____\/_____/'' <--- Trace 1
/// -------------------------------
late bool stacked;
String? name;
double dataYMax = 0;
final _data = <Data>[];
Path? get symbolPath {
if (_symbolPath != null) return _symbolPath;
switch (characteristics.symbol) {
case ChartSymbol.filledSquare:
case ChartSymbol.square:
_symbolPath = _createSquare();
break;
case ChartSymbol.filledTriangle:
case ChartSymbol.triangle:
_symbolPath = _createTriangle();
break;
case ChartSymbol.filledTriangleDown:
case ChartSymbol.triangleDown:
_symbolPath = _createTriangleDown();
break;
default:
_symbolPath = null;
}
return _symbolPath;
}
/// Path to draw symbol.
Path? _symbolPath;
// TODO(terry): Consider UnmodifiableListView if data is loaded from offline file (not live).
List<Data> get data => _data;
void addAllData(List<Data> data) {
_data.addAll(data);
controller.dirty = true;
}
ChartType get chartType => _chartType;
AxisScale? yAxis;
void clearData() {
_data.clear();
controller.dirty = true;
}
void addDatum(Data datum) {
_data.add(datum);
controller.dirty = true;
if (characteristics.fixedMaxY != null) {
assert(
datum.y <= characteristics.fixedMaxY!,
'y=${datum.y} fixedMaxY=${characteristics.fixedMaxY}',
);
} else if (datum.y > dataYMax) {
dataYMax = datum.y.toDouble();
yAxis = AxisScale(0, dataYMax, 30);
}
if (datum.y > controller.yMaxValue) {
controller.yMaxValue = datum.y;
}
// New data has arrived notify listeners this data needs to be plotted.
// TODO(polina-c): should we use stream instead notifier?
// https://github.com/flutter/devtools/pull/5301#discussion_r1126792303
controller.traceChanged.value = TraceNotifier();
}
/// Draw square centered on [x,y] point (*).
/// 0_____ .___.
/// | |
/// | * |
/// !___!
///
Path _createSquare() {
if (_symbolPath == null) {
_symbolPath = Path();
_symbolPath!.addRect(
Rect.fromLTWH(
0,
0,
characteristics.width,
characteristics.height,
),
);
_symbolPath!.close();
}
return _symbolPath!;
}
/// Draw triangle centered on [x,y] point (*).
/// 0____ .
/// / \
/// / * \
/// ./_____\.
///
Path _createTriangle() {
if (_symbolPath == null) {
final width = characteristics.width;
final height = characteristics.height;
_symbolPath = Path();
// Top point.
_symbolPath!.moveTo(width / 2, 0);
// Diagonal line from top point to bottom right-side.
_symbolPath!.lineTo(width, height);
// Horizontal line from bottom right-side to bottom left-side.
_symbolPath!.lineTo(0, height);
// Closing path finishes left-side diagonal line from bottom-left corner
// to top point.
_symbolPath!.close();
}
return _symbolPath!;
}
// Draw triangle centered on [x,y] point (*).
// 0 _____ ._______.
// \ /
// \ * /
// \ /
// `
Path _createTriangleDown() {
if (_symbolPath == null) {
final width = characteristics.width;
final height = characteristics.height;
_symbolPath = Path();
// Straight horizontal line to top-right corner (moveTo starts at 0,0).
_symbolPath!.lineTo(width, 0);
// Diagonal right-side line to bottom tip point.
_symbolPath!.lineTo(width / 2, height);
// Closing path finishes left-side diagonal line from bottom tip point to
// top-left corner.
_symbolPath!.close();
}
return _symbolPath!;
}
}
class TraceNotifier {
TraceNotifier();
}
enum ChartType {
symbol,
line,
}
enum ChartSymbol {
ring, // Lined circle
disc, // Filled circle
concentric, // outer ring and inner disc
square, // Lined square
filledSquare, // Filled square
triangle, // Lined triangle
filledTriangle,
triangleDown, // Lined triangle points down
filledTriangleDown,
dashedLine,
}
double log10(num x) => log(x) / ln10;
class AxisScale {
factory AxisScale(double minPoint, double maxPoint, double maxTicks) {
final range = _niceNum(maxPoint, false);
final double tickSpacing;
final double exponent;
final double fraction;
if (range != 0) {
tickSpacing = range / (maxTicks - 1);
(:exponent, :fraction) = _exponentFraction(range);
} else {
tickSpacing = 1;
exponent = 0;
fraction = 0;
}
return AxisScale._(
minPoint: minPoint,
maxPoint: maxPoint,
maxTicks: maxTicks,
tickSpacing: tickSpacing,
labelUnitExponent: exponent,
labelTicks: fraction,
);
}
AxisScale._({
required this.minPoint,
required this.maxPoint,
required this.maxTicks,
required this.tickSpacing,
required this.labelUnitExponent,
required this.labelTicks,
});
final double minPoint, maxPoint;
final double maxTicks;
final double tickSpacing;
/// Unit for the label (exponent) e.g., 6 = 10^6.
final double labelUnitExponent;
/// Number of labels.
final double labelTicks;
static ({double exponent, double fraction}) _exponentFraction(double range) {
assert(range != 0);
final exponent = log10(range).floor().toDouble();
final fraction = range / pow(10, exponent);
return (exponent: exponent, fraction: fraction.roundToDouble());
}
/// Produce a whole number for the Y-axis scale and its unit using
/// the exponent. Goal is to compute the range of values for min, max
/// and exponent (our unit of measurement e.g., K, M, B, etc.). The axis
/// labels are displayed in 1s, 10s and 100s e.g., 10M, 50M, 100M or
/// 1B, 2B, 3B.
///
/// @param round if false, chunks the whole number to keep more available
/// space above the max Y value highpoint to handle future bigger data
/// values w/o having to rescale too quickly e.g., over 3e+3 displays:
/// 10K, 20K, 30K, 40K, 50K
/// This allows new data points >30K to be plotted w/o having to
/// re-layout new Y-axis scale.
static double _niceNum(double range, bool round) {
if (range == 0) return 0;
// Exponent of range.
final exponent = log10(range).floor().toDouble();
// Fractional part of range.
final fraction = range / pow(10, exponent);
// Nice, rounded fraction.
final niceFraction = round
? fraction.roundToDouble()
: switch (fraction) {
<= 1 => 1.0,
<= 2 => 2.0,
<= 3 => 3.0,
<= 5 => 5.0,
<= 7 => 7.0,
_ => 10.0,
};
return niceFraction * pow(10, exponent);
}
double tickFromValue(double value) =>
(value / tickSpacing).truncateToDouble();
}
| devtools/packages/devtools_app/lib/src/shared/charts/chart_trace.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/charts/chart_trace.dart",
"repo_id": "devtools",
"token_count": 3716
} | 107 |
// 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 '../../../framework/framework_core.dart';
import '_framework_initialize_desktop.dart'
if (dart.library.js_interop) '_framework_initialize_web.dart';
Future<void> initializeFramework() async {
FrameworkCore.initGlobals();
await initializePlatform();
FrameworkCore.init();
}
| devtools/packages/devtools_app/lib/src/shared/config_specific/framework_initialize/framework_initialize.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/framework_initialize/framework_initialize.dart",
"repo_id": "devtools",
"token_count": 136
} | 108 |
// 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:logging/logging.dart';
import '../../constants.dart';
import '../../log_storage.dart';
import 'logger.dart';
/// Helper for setting the log level for the global [Logger].
void setDevToolsLoggingLevel(Level level) {
Logger.root.level = level;
Logger.root.warning('DevTools log level changed to ${level.name}');
}
/// Helper for initializing the [Logger] record handler.
void initDevToolsLogging() {
Logger.root.onRecord.listen((record) {
// As long as a log was recorded then it should be added to the LogStorage.
LogStorage.root.addLog(record);
// All logs with level [basicLoggingLevel] and above, should be printed to the
// console.
if (record.level >= basicLoggingLevel) {
var logLevel = LogLevel.debug;
if (record.level == Level.WARNING) {
logLevel = LogLevel.warning;
} else if (record.level == Level.SEVERE) {
logLevel = LogLevel.error;
} else if (record.level == Level.SHOUT) {
logLevel = LogLevel.error;
}
printToConsole(record.message, logLevel);
}
});
}
| devtools/packages/devtools_app/lib/src/shared/config_specific/logger/logger_helpers.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/logger/logger_helpers.dart",
"repo_id": "devtools",
"token_count": 432
} | 109 |
// 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.
/// Store and manipulate the expression evaluation history.
class EvalHistory {
var _historyPosition = -1;
/// Get the expression evaluation history.
List<String> get evalHistory => _evalHistory.toList();
final _evalHistory = <String>[];
/// Push a new entry onto the expression evaluation history.
void pushEvalHistory(String expression) {
if (_evalHistory.isNotEmpty && _evalHistory.last == expression) {
return;
}
_evalHistory.add(expression);
_historyPosition = -1;
}
bool get canNavigateUp {
return _evalHistory.isNotEmpty && _historyPosition != 0;
}
void navigateUp() {
if (_historyPosition == -1) {
_historyPosition = _evalHistory.length - 1;
} else if (_historyPosition > 0) {
_historyPosition--;
}
}
bool get canNavigateDown {
return _evalHistory.isNotEmpty && _historyPosition != -1;
}
void navigateDown() {
if (_historyPosition != -1) {
_historyPosition++;
}
if (_historyPosition >= _evalHistory.length) {
_historyPosition = -1;
}
}
String? get currentText {
return _historyPosition == -1 ? null : _evalHistory[_historyPosition];
}
}
| devtools/packages/devtools_app/lib/src/shared/console/primitives/eval_history.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/console/primitives/eval_history.dart",
"repo_id": "devtools",
"token_count": 430
} | 110 |
// 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.
// This code is directly based on src/io/flutter/InspectorService.java.
//
// If you add methods to this class you should also add them to
// InspectorService.java.
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:devtools_app_shared/service.dart';
import 'package:devtools_app_shared/service_extensions.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:vm_service/vm_service.dart';
import '../console/primitives/simple_items.dart';
import '../globals.dart';
import '../utils.dart';
import 'diagnostics_node.dart';
import 'generic_instance_reference.dart';
import 'object_group_api.dart';
import 'primitives/instance_ref.dart';
import 'primitives/source_location.dart';
const _inspectorLibraryUri =
'package:flutter/src/widgets/widget_inspector.dart';
abstract class InspectorServiceBase extends DisposableController
with AutoDisposeControllerMixin {
InspectorServiceBase({
required this.clientInspectorName,
required this.serviceExtensionPrefix,
required String inspectorLibraryUri,
ValueListenable<IsolateRef?>? evalIsolate,
}) : assert(serviceConnection.serviceManager.connectedAppInitialized),
assert(serviceConnection.serviceManager.service != null),
clients = {},
inspectorLibrary = EvalOnDartLibrary(
inspectorLibraryUri,
serviceConnection.serviceManager.service!,
serviceManager: serviceConnection.serviceManager,
isolate: evalIsolate,
) {
_lastMainIsolate =
serviceConnection.serviceManager.isolateManager.mainIsolate.value;
addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.mainIsolate,
() {
final mainIsolate =
serviceConnection.serviceManager.isolateManager.mainIsolate.value;
if (mainIsolate != _lastMainIsolate) {
onIsolateStopped();
}
_lastMainIsolate = mainIsolate;
},
);
}
static int nextGroupId = 0;
// The class name of the inspector that [InspectorServiceBase] is connecting
// to, for use when running evals. For example, this should be set to
// "WidgetInspectorService" when connecting to the Flutter inspector.
final String clientInspectorName;
// The prefix added when invoking all registered inspector service extensions.
// For example, this should be set to "ext.flutter.inspector" when invoking
// service extensions registered by the Flutter inspector.
final String serviceExtensionPrefix;
final Set<InspectorServiceClient> clients;
final EvalOnDartLibrary inspectorLibrary;
IsolateRef? _lastMainIsolate;
/// Reference to the isolate running the inspector that [InspectorServiceBase]
/// is connecting to. This isolate should always be the main isolate.
IsolateRef? get isolateRef => inspectorLibrary.isolateRef;
/// Called when the main isolate is stopped. Should be overridden in order to
/// clear data that is obsolete on an isolate restart.
void onIsolateStopped();
/// Returns true if the given node's class is declared beneath one of the root
/// directories of the app's package.
bool isLocalClass(RemoteDiagnosticsNode node);
/// Returns a new [InspectorObjectGroupBase] with the given group name.
InspectorObjectGroupBase createObjectGroup(String debugName);
bool get isDisposed => _isDisposed;
bool _isDisposed = false;
void addClient(InspectorServiceClient client) {
clients.add(client);
}
void removeClient(InspectorServiceClient client) {
clients.remove(client);
}
/// Returns whether to use the Daemon API or the VM Service protocol directly.
///
/// The VM Service protocol must be used when paused at a breakpoint as the
/// Daemon API calls won't execute until after the current frame is done
/// rendering.
bool get useDaemonApi =>
!serviceConnection.serviceManager.isMainIsolatePaused;
@override
void dispose() {
_isDisposed = true;
inspectorLibrary.dispose();
super.dispose();
}
bool get hoverEvalModeEnabledByDefault;
Future<bool> invokeBoolServiceMethodNoArgs(String methodName) async {
return useDaemonApi
? await invokeServiceMethodDaemonNoGroupArgs(methodName) == true
: (await invokeServiceMethodObservatoryNoGroup(methodName))
?.valueAsString ==
'true';
}
Future<Object?> invokeServiceMethodDaemonNoGroupArgs(
String methodName, [
List<String>? args,
]) {
final Map<String, Object?> params = {};
if (args != null) {
for (int i = 0; i < args.length; ++i) {
params['arg$i'] = args[i];
}
}
return invokeServiceMethodDaemonNoGroup(methodName, args: params);
}
Future<InstanceRef?> invokeServiceMethodObservatoryNoGroup(
String methodName,
) {
return inspectorLibrary.eval(
'$clientInspectorName.instance.$methodName()',
isAlive: null,
);
}
Future<Object?> invokeServiceMethodDaemonNoGroup(
String methodName, {
Map<String, Object?>? args,
}) async {
final callMethodName = '$serviceExtensionPrefix.$methodName';
if (!serviceConnection.serviceManager.serviceExtensionManager
.isServiceExtensionAvailable(callMethodName)) {
final available = await serviceConnection
.serviceManager.serviceExtensionManager
.waitForServiceExtensionAvailable(callMethodName);
if (!available) return {'result': null};
}
final r =
await serviceConnection.serviceManager.service!.callServiceExtension(
callMethodName,
isolateId: isolateRef!.id,
args: args,
);
final json = r.json!;
if (json['errorMessage'] != null) {
throw Exception('$methodName -- ${json['errorMessage']}');
}
return json['result'];
}
}
/// Manages communication between inspector code running in the Flutter app and
/// the inspector.
class InspectorService extends InspectorServiceBase {
InspectorService()
: super(
clientInspectorName: 'WidgetInspectorService',
serviceExtensionPrefix: inspectorExtensionPrefix,
inspectorLibraryUri: _inspectorLibraryUri,
evalIsolate:
serviceConnection.serviceManager.isolateManager.mainIsolate,
) {
// Note: We do not need to listen to event history here because the
// inspector uses a separate API to get the current inspector selection.
autoDisposeStreamSubscription(
serviceConnection.serviceManager.service!.onExtensionEvent
.listen(onExtensionVmServiceReceived),
);
autoDisposeStreamSubscription(
serviceConnection.serviceManager.service!.onDebugEvent
.listen(onDebugVmServiceReceived),
);
}
final ValueNotifier<List<String>> _rootDirectories = ValueNotifier([]);
@visibleForTesting
Set<String> get rootPackages => _rootPackages;
late Set<String> _rootPackages;
@visibleForTesting
List<String> get rootPackagePrefixes => _rootPackagePrefixes;
late List<String> _rootPackagePrefixes;
@visibleForTesting
final localClasses = <String, ClassRef>{};
@override
void onIsolateStopped() {
_currentSelection = null;
_cachedSelectionGroups?.clear(true);
_expectedSelectionChanges.clear();
}
@override
ObjectGroup createObjectGroup(String debugName) {
return ObjectGroup(debugName, this);
}
@override
bool isLocalClass(RemoteDiagnosticsNode node) {
// TODO(https://github.com/flutter/devtools/issues/4393): localClasses is
// not currently being filled.
if (node.widgetRuntimeType == null) return false;
// widgetRuntimeType may contain some generic type arguments which we need
// to strip out. If widgetRuntimeType is "FooWidget<Bar>" then we are only
// interested in the raw type "FooWidget".
final rawType = node.widgetRuntimeType!.split('<').first;
return localClasses.containsKey(rawType);
}
@override
void dispose() {
_cachedSelectionGroups?.clear(false);
_cachedSelectionGroups = null;
super.dispose();
}
// When DevTools is embedded, default hover eval mode to off.
@override
bool get hoverEvalModeEnabledByDefault => !ideTheme.embed;
void onExtensionVmServiceReceived(Event e) {
if ('Flutter.Frame' == e.extensionKind) {
for (InspectorServiceClient client in clients) {
try {
client.onFlutterFrame();
} catch (e) {
log('Error handling frame event', error: e);
}
}
}
}
void onDebugVmServiceReceived(Event event) {
if (event.kind == EventKind.kInspect) {
// Update the UI in IntelliJ.
notifySelectionChanged();
}
}
/// Map from InspectorInstanceRef to list of timestamps when a selection
/// change to that ref was triggered by this application.
///
/// This is needed to handle the case where we may send multiple selection
/// change notifications to the device before we get a notification back that
/// the selection has actually changed. Without this fix it was rare but
/// possible to trigger an infinite loop ping-ponging back and forth between
/// selecting two different nodes in the inspector tree if the selection was
/// changed more rapidly than the running flutter app could update.
final Map<InspectorInstanceRef, List<int>> _expectedSelectionChanges = {};
/// Maximum time in milliseconds that we ever expect it will take for a
/// selection change to apply.
///
/// In general this heuristic based time should not matter but we keep it
/// anyway so that in the unlikely event that package:flutter changes and we
/// do not received all of the selection notification events we expect, we
/// will not be impacted if there is at least the following delay between
/// when selection was set to exactly the same location by both the on device
/// inspector and DevTools.
static const _maxTimeDelaySelectionNotification = 5000;
void _trackClientSelfTriggeredSelection(InspectorInstanceRef ref) {
_expectedSelectionChanges
.putIfAbsent(ref, () => [])
.add(DateTime.now().millisecondsSinceEpoch);
}
/// Returns whether the selection change was originally triggered by this
/// application.
///
/// This method is needed to avoid a race condition when there is a queue of
/// inspector selection changes due to extremely rapidly navigating through
/// the inspector tree such as when using the keyboard to navigate.
bool _isClientTriggeredSelectionChange(InspectorInstanceRef? ref) {
// TODO(jacobr): once https://github.com/flutter/flutter/issues/39366 is
// fixed in all versions of flutter we support, remove this logic and
// determine the source of the inspector selection change directly from the
// inspector selection changed event.
final currentTime = DateTime.now().millisecondsSinceEpoch;
if (ref != null) {
if (_expectedSelectionChanges.containsKey(ref)) {
final times = _expectedSelectionChanges.remove(ref)!;
while (times.isNotEmpty) {
final time = times.removeAt(0);
if (time + _maxTimeDelaySelectionNotification >= currentTime) {
// We triggered this selection change ourselves. This logic would
// work fine without the timestamps for the typical case but we use
// the timestamps to be safe in case there is a bug and selection
// change events were somehow lost.
return true;
}
}
}
}
return false;
}
Future<void> _onRootDirectoriesChanged(List<String> directories) async {
_rootDirectories.value = directories;
_rootPackages = {};
_rootPackagePrefixes = [];
for (var directory in directories) {
// TODO(jacobr): add an API to DDS to provide the actual mapping to and
// from absolute file paths to packages instead of having to guess it
// here.
assert(!directory.startsWith('package:'));
final parts =
directory.split('/').where((element) => element.isNotEmpty).toList();
final libIndex = parts.lastIndexOf('lib');
final path = libIndex > 0 ? parts.sublist(0, libIndex) : parts;
// Special case handling of bazel packages.
if (isGoogle3Path(path)) {
var packageParts = stripGoogle3(path);
// A well formed third_party dart package should be in a directory of
// the form
// third_party/dart/packageName (package:packageName)
// or
// third_party/dart_src/long/package/name (package:long.package.name)
// so its path should be at minimum depth 3.
const minThirdPartyPathDepth = 3;
if (packageParts.first == 'third_party' &&
packageParts.length >= minThirdPartyPathDepth) {
assert(packageParts[1] == 'dart' || packageParts[1] == 'dart_src');
packageParts = packageParts.sublist(2);
}
final google3PackageName = packageParts.join('.');
_rootPackages.add(google3PackageName);
_rootPackagePrefixes.add('$google3PackageName.');
} else {
_rootPackages.add(path.last);
}
}
await _updateLocalClasses();
}
Future<void> _updateLocalClasses() {
return Future.value();
// TODO(https://github.com/flutter/devtools/issues/4393)
// localClasses.clear();
// if (_rootDirectories.value.isNotEmpty) {
// final isolate = inspectorLibrary.isolate!;
// for (var libraryRef in isolate.libraries!) {
// if (isLocalUri(libraryRef.uri!)) {
// try {
// final Library library = await inspectorLibrary.service
// .getObject(isolate.id!, libraryRef.id!) as Library;
// for (var classRef in library.classes!) {
// localClasses[classRef.name!] = classRef;
// }
// } catch (e) {
// // Workaround until https://github.com/flutter/devtools/issues/3110
// // is fixed.
// assert(serviceManager.manager.connectedApp!.isDartWebAppNow!);
// }
// }
// }
// }
}
@visibleForTesting
bool isLocalUri(String rawUri) {
final uri = Uri.parse(rawUri);
if (uri.scheme != 'file' && uri.scheme != 'dart') {
// package scheme or some other dart specific scheme.
final packageName = uri.pathSegments.first;
if (_rootPackages.contains(packageName)) return true;
// This attempts to gracefully handle the bazel package case.
return _rootPackagePrefixes
.any((prefix) => packageName.startsWith(prefix));
}
for (var root in _rootDirectories.value) {
if (root.endsWith(rawUri)) {
return true;
}
}
return false;
}
Future<void> addPubRootDirectories(List<String> rootDirectories) async {
await _addPubRootDirectories(rootDirectories);
await _onRootDirectoriesChanged(rootDirectories);
}
Future<void> removePubRootDirectories(List<String> rootDirectories) async {
await _removePubRootDirectories(rootDirectories);
await _onRootDirectoriesChanged(rootDirectories);
}
Future<void> _addPubRootDirectories(List<String> pubDirectories) {
assert(useDaemonApi);
return invokeServiceMethodDaemonNoGroupArgs(
WidgetInspectorServiceExtensions.addPubRootDirectories.name,
pubDirectories,
);
}
Future<void> _removePubRootDirectories(List<String> pubDirectories) {
assert(useDaemonApi);
return invokeServiceMethodDaemonNoGroupArgs(
WidgetInspectorServiceExtensions.removePubRootDirectories.name,
pubDirectories,
);
}
Future<List<String>?> getPubRootDirectories() async {
assert(useDaemonApi);
final response = await invokeServiceMethodDaemonNoGroupArgs(
WidgetInspectorServiceExtensions.getPubRootDirectories.name,
);
if (response is! List<Object?>) {
return [];
}
return response.map<String>((e) => e.toString()).toList();
}
/// Requests the full mapping of widget ids to source locations.
///
/// See [LocationMap] which provides support to parse this JSON.
Future<Map<String, dynamic>> widgetLocationIdMap() async {
assert(useDaemonApi);
final response = await invokeServiceMethodDaemonNoGroupArgs(
'widgetLocationIdMap',
);
if (response is! Map) {
return {};
}
return response as Map<String, dynamic>;
}
RemoteDiagnosticsNode? _currentSelection;
InspectorObjectGroupManager get _selectionGroups {
return _cachedSelectionGroups ??=
InspectorObjectGroupManager(this, 'selection');
}
InspectorObjectGroupManager? _cachedSelectionGroups;
void notifySelectionChanged() async {
// The previous selection changed event is obsolete.
_selectionGroups.cancelNext();
final group = _selectionGroups.next;
final pendingSelection = await group.getSelection(
_currentSelection,
FlutterTreeType.widget,
isSummaryTree: false,
);
if (!group.disposed &&
group == _selectionGroups.next &&
!_isClientTriggeredSelectionChange(pendingSelection?.valueRef)) {
_currentSelection = pendingSelection;
assert(group == _selectionGroups.next);
_selectionGroups.promoteNext();
for (InspectorServiceClient client in clients) {
client.onInspectorSelectionChanged();
}
}
}
/// If the widget tree is not ready, the application should wait for the next
/// Flutter.Frame event before attempting to display the widget tree. If the
/// application is ready, the next Flutter.Frame event may never come as no
/// new frames will be triggered to draw unless something changes in the UI.
Future<bool> isWidgetTreeReady() {
return invokeBoolServiceMethodNoArgs(
WidgetInspectorServiceExtensions.isWidgetTreeReady.name,
);
}
Future<bool> isWidgetCreationTracked() {
return invokeBoolServiceMethodNoArgs(
WidgetInspectorServiceExtensions.isWidgetCreationTracked.name,
);
}
}
/// This class has additional descenders in Google3.
abstract class InspectorObjectGroupBase
extends InspectorObjectGroupApi<RemoteDiagnosticsNode> {
InspectorObjectGroupBase(
String debugName,
) : groupName = '${debugName}_${InspectorServiceBase.nextGroupId}' {
InspectorServiceBase.nextGroupId++;
}
/// Object group all objects in this arena are allocated with.
final String groupName;
InspectorServiceBase get inspectorService;
@override
bool disposed = false;
EvalOnDartLibrary get inspectorLibrary => inspectorService.inspectorLibrary;
bool get useDaemonApi => inspectorService.useDaemonApi;
/// Once an ObjectGroup has been disposed, all methods returning
/// DiagnosticsNode objects will return a placeholder dummy node and all methods
/// returning lists or maps will return empty lists and all other methods will
/// return null. Generally code should never call methods on a disposed object
/// group but sometimes due to chained futures that can be difficult to avoid
/// and it is simpler return an empty result that will be ignored anyway than to
/// attempt carefully cancel futures.
@override
Future<void> dispose() {
// No need to dispose the group if the isolate is already gone.
final disposeComplete = inspectorService.isolateRef != null
? invokeVoidServiceMethod(
WidgetInspectorServiceExtensions.disposeGroup.name,
groupName,
)
: Future<void>.value();
disposed = true;
return disposeComplete;
}
Future<RemoteDiagnosticsNode?> invokeServiceMethodReturningNodeInspectorRef(
String methodName,
InspectorInstanceRef? ref,
) async {
if (disposed) return null;
return useDaemonApi
? parseDiagnosticsNodeDaemon(
invokeServiceMethodDaemonInspectorRef(methodName, ref),
)
: parseDiagnosticsNodeObservatory(
invokeServiceMethodObservatoryInspectorRef(methodName, ref),
);
}
Future<RemoteDiagnosticsNode?> invokeServiceMethodWithArgReturningNode(
String methodName,
String arg,
) async {
if (disposed) return null;
return useDaemonApi
? parseDiagnosticsNodeDaemon(
invokeServiceMethodDaemonArg(methodName, arg, groupName),
)
: parseDiagnosticsNodeObservatory(
invokeServiceMethodObservatoryWithGroupName1(methodName, arg),
);
}
Future<Object?> invokeServiceMethodDaemonArg(
String methodName,
String? arg,
String objectGroup,
) {
final args = {'objectGroup': objectGroup};
if (arg != null) {
args['arg'] = arg;
}
return invokeServiceMethodDaemonParams(methodName, args);
}
Future<Object?> invokeServiceMethodDaemonInspectorRef(
String methodName,
InspectorInstanceRef? arg,
) {
return invokeServiceMethodDaemonArg(methodName, arg?.id, groupName);
}
Future<InstanceRef?> invokeServiceMethodObservatoryInspectorRef(
String methodName,
InspectorInstanceRef? arg,
) {
return inspectorLibrary.eval(
"${inspectorService.clientInspectorName}.instance.$methodName('${arg?.id}', '$groupName')",
isAlive: this,
);
}
Future<void> invokeVoidServiceMethod(String methodName, String arg1) async {
if (disposed) return;
if (useDaemonApi) {
await invokeServiceMethodDaemon(methodName, arg1);
} else {
await invokeServiceMethodObservatory1(methodName, arg1);
}
}
Future<Object?> invokeServiceMethodDaemon(
String methodName, [
String? objectGroup,
]) {
return invokeServiceMethodDaemonParams(
methodName,
{'objectGroup': objectGroup ?? groupName},
);
}
Future<InstanceRef?> invokeServiceMethodObservatory1(
String methodName,
String arg1,
) {
return inspectorLibrary.eval(
"${inspectorService.clientInspectorName}.instance.$methodName('$arg1')",
isAlive: this,
);
}
Future<InstanceRef?> invokeServiceMethodObservatoryWithGroupName1(
String methodName,
String arg1,
) {
return inspectorLibrary.eval(
"${inspectorService.clientInspectorName}.instance.$methodName('$arg1', '$groupName')",
isAlive: this,
);
}
// All calls to invokeServiceMethodDaemon bottom out to this call.
Future<Object?> invokeServiceMethodDaemonParams(
String methodName,
Map<String, Object?> params,
) async {
final callMethodName =
'${inspectorService.serviceExtensionPrefix}.$methodName';
if (!serviceConnection.serviceManager.serviceExtensionManager
.isServiceExtensionAvailable(callMethodName)) {
final available = await serviceConnection
.serviceManager.serviceExtensionManager
.waitForServiceExtensionAvailable(callMethodName);
if (!available) return null;
}
return await _callServiceExtension(callMethodName, params);
}
Future<Object?> _callServiceExtension(
String extension,
Map<String, Object?> args,
) {
if (disposed) {
return Future.value();
}
return inspectorLibrary.addRequest(this, () async {
final r =
await serviceConnection.serviceManager.service!.callServiceExtension(
extension,
isolateId: inspectorService.isolateRef!.id,
args: args,
);
if (disposed) return null;
final json = r.json!;
if (json['errorMessage'] != null) {
throw Exception('$extension -- ${json['errorMessage']}');
}
return json['result'];
});
}
Future<RemoteDiagnosticsNode?> parseDiagnosticsNodeDaemon(
Future<Object?> json,
) async {
if (disposed) return null;
return parseDiagnosticsNodeHelper(await json as Map<String, Object?>?);
}
Future<RemoteDiagnosticsNode?> parseDiagnosticsNodeObservatory(
FutureOr<InstanceRef?> instanceRefFuture,
) async {
return parseDiagnosticsNodeHelper(
await instanceRefToJson(await instanceRefFuture) as Map<String, Object?>?,
);
}
RemoteDiagnosticsNode? parseDiagnosticsNodeHelper(
Map<String, Object?>? jsonElement,
) {
if (disposed) return null;
if (jsonElement == null) return null;
return RemoteDiagnosticsNode(jsonElement, this, false, null);
}
Future<List<RemoteDiagnosticsNode>> parseDiagnosticsNodesObservatory(
FutureOr<InstanceRef?> instanceRefFuture,
RemoteDiagnosticsNode? parent,
bool isProperty,
) async {
if (disposed || instanceRefFuture == null) return [];
final instanceRef = await instanceRefFuture;
if (disposed || instanceRefFuture == null) return [];
return parseDiagnosticsNodesHelper(
await instanceRefToJson(instanceRef) as List<Object?>?,
parent,
isProperty,
);
}
List<RemoteDiagnosticsNode> parseDiagnosticsNodesHelper(
List<Object?>? jsonObject,
RemoteDiagnosticsNode? parent,
bool isProperty,
) {
if (disposed || jsonObject == null) return const [];
final nodes = <RemoteDiagnosticsNode>[];
for (var element in jsonObject.cast<Map<String, Object?>>()) {
nodes.add(RemoteDiagnosticsNode(element, this, isProperty, parent));
}
return nodes;
}
Future<List<RemoteDiagnosticsNode>> parseDiagnosticsNodesDaemon(
FutureOr<Object?> jsonFuture,
RemoteDiagnosticsNode? parent,
bool isProperty,
) async {
if (disposed || jsonFuture == null) return const [];
return parseDiagnosticsNodesHelper(
await jsonFuture as List<Object?>?,
parent,
isProperty,
);
}
/// Requires that the InstanceRef is really referring to a String that is valid JSON.
Future<Object?> instanceRefToJson(InstanceRef? instanceRef) async {
if (disposed || instanceRef == null) return null;
final instance = await inspectorLibrary.getInstance(instanceRef, this);
if (disposed || instance == null) return null;
final String? json = instance.valueAsString;
if (json == null) return null;
return jsonDecode(json);
}
@override
Future<InstanceRef?> toObservatoryInstanceRef(
InspectorInstanceRef inspectorInstanceRef,
) async {
if (inspectorInstanceRef.id == null) {
return null;
}
return await invokeServiceMethodObservatoryInspectorRef(
'toObject',
inspectorInstanceRef,
);
}
Future<Instance?> getInstance(FutureOr<InstanceRef?> instanceRef) async {
if (disposed) {
return null;
}
return inspectorLibrary.getInstance(await instanceRef as InstanceRef, this);
}
/// Returns a Future with a Map of property names to Observatory
/// InstanceRef objects. This method is shorthand for individually evaluating
/// each of the getters specified by property names.
///
/// It would be nice if the Observatory protocol provided a built in method
/// to get InstanceRef objects for a list of properties but this is
/// sufficient although slightly less efficient. The Observatory protocol
/// does provide fast access to all fields as part of an Instance object
/// but that is inadequate as for many Flutter data objects that we want
/// to display visually we care about properties that are not necessarily
/// fields.
///
/// The future will immediately complete to null if the inspectorInstanceRef is null.
@override
Future<Map<String, InstanceRef>?> getDartObjectProperties(
InspectorInstanceRef inspectorInstanceRef,
final List<String> propertyNames,
) async {
final instanceRef = await toObservatoryInstanceRef(inspectorInstanceRef);
if (disposed) return null;
const objectName = 'that';
final expression =
'[${propertyNames.map((propertyName) => '$objectName.$propertyName').join(',')}]';
final Map<String, String> scope = {objectName: instanceRef!.id!};
final instance = await getInstance(
inspectorLibrary.eval(expression, isAlive: this, scope: scope),
);
if (disposed) return null;
// We now have an instance object that is a Dart array of all the
// property values. Convert it back to a map from property name to
// property values.
final properties = <String, InstanceRef>{};
final List<InstanceRef> values =
instance!.elements!.toList().cast<InstanceRef>();
assert(values.length == propertyNames.length);
for (int i = 0; i < propertyNames.length; ++i) {
properties[propertyNames[i]] = values[i];
}
return properties;
}
@override
Future<Map<String, InstanceRef>?> getEnumPropertyValues(
InspectorInstanceRef ref,
) async {
if (disposed) return null;
if (ref.id == null) return null;
final instance = await getInstance(await toObservatoryInstanceRef(ref));
if (disposed || instance == null) return null;
final clazz = await inspectorLibrary.getClass(instance.classRef!, this);
if (disposed || clazz == null) return null;
final properties = <String, InstanceRef>{};
for (FieldRef field in clazz.fields!) {
final String name = field.name!;
if (isPrivateMember(name)) {
// Needed to filter out _deleted_enum_sentinel synthetic property.
// If showing enum values is useful we could special case
// just the _deleted_enum_sentinel property name.
continue;
}
if (name == 'values') {
// Need to filter out the synthetic 'values' member.
// TODO(jacobr): detect that this properties return type is
// different and filter that way.
continue;
}
if (field.isConst! && field.isStatic!) {
properties[field.name!] = field.declaredType!;
}
}
return properties;
}
Future<SourcePosition?> getPropertyLocationHelper(
ClassRef classRef,
String name,
) async {
final clazz = await inspectorLibrary.getClass(classRef, this) as Class;
for (FuncRef f in clazz.functions!) {
// TODO(pq): check for properties that match name.
if (f.name == name) {
final func = await inspectorLibrary.getFunc(f, this) as Func;
final SourceLocation? location = func.location;
throw UnimplementedError(
'getSourcePosition not implemented. $location',
);
}
}
final ClassRef? superClass = clazz.superClass;
return superClass == null
? null
: getPropertyLocationHelper(superClass, name);
}
Future<List<RemoteDiagnosticsNode>> getListHelper(
InspectorInstanceRef? instanceRef,
String methodName,
RemoteDiagnosticsNode? parent,
bool isProperty,
) async {
if (disposed) return const [];
return useDaemonApi
? parseDiagnosticsNodesDaemon(
invokeServiceMethodDaemonInspectorRef(methodName, instanceRef),
parent,
isProperty,
)
: parseDiagnosticsNodesObservatory(
invokeServiceMethodObservatoryInspectorRef(methodName, instanceRef),
parent,
isProperty,
);
}
/// Evaluate an expression where `object` references the [inspectorRef] or
/// [instanceRef] passed in.
///
/// If both [inspectorRef] and [instanceRef] are passed in they are assumed to
/// reference the same object and the [inspectorRef] is used as it is longer
/// lived than an InstanceRef.
Future<InstanceRef?> evalOnRef(
String expression,
GenericInstanceRef? ref,
) async {
final inspectorRef = ref?.diagnostic?.valueRef;
if (inspectorRef != null && inspectorRef.id != null) {
return await inspectorLibrary.eval(
"((object) => $expression)(${inspectorService.clientInspectorName}.instance.toObject('${inspectorRef.id}'))",
isAlive: this,
);
}
final instanceRef = ref!.instanceRef!;
return await inspectorLibrary.eval(
expression,
isAlive: this,
scope: <String, String>{'object': instanceRef.id!},
);
}
Future<bool> isInspectable(GenericInstanceRef ref) async {
if (disposed) {
return false;
}
try {
final result = await evalOnRef(
'object is Element || object is RenderObject',
ref,
);
if (disposed) return false;
return 'true' == result?.valueAsString;
} catch (e) {
// If the ref is invalid it is not inspectable.
return false;
}
}
@override
Future<List<RemoteDiagnosticsNode>> getProperties(
InspectorInstanceRef instanceRef,
) {
return getListHelper(
instanceRef,
WidgetInspectorServiceExtensions.getProperties.name,
null,
true,
);
}
@override
Future<List<RemoteDiagnosticsNode>> getChildren(
InspectorInstanceRef instanceRef,
bool summaryTree,
RemoteDiagnosticsNode? parent,
) {
return getListHelper(
instanceRef,
summaryTree
? WidgetInspectorServiceExtensions.getChildrenSummaryTree.name
: WidgetInspectorServiceExtensions.getChildrenDetailsSubtree.name,
parent,
false,
);
}
@override
bool isLocalClass(RemoteDiagnosticsNode node) =>
inspectorService.isLocalClass(node);
}
/// Class managing a group of inspector objects that can be freed by
/// a single call to dispose().
///
/// After dispose is called, all pending requests made with the ObjectGroup
/// will be skipped. This means that clients should not have to write any
/// special logic to handle orphaned requests.
class ObjectGroup extends InspectorObjectGroupBase {
ObjectGroup(
String debugName,
this.inspectorService,
) : super(debugName);
@override
final InspectorService inspectorService;
@override
bool canSetSelectionInspector = true;
Future<RemoteDiagnosticsNode?> getRoot(FlutterTreeType type) {
// There is no excuse to call this method on a disposed group.
assert(!disposed);
switch (type) {
case FlutterTreeType.widget:
return getRootWidget();
}
}
Future<RemoteDiagnosticsNode?> getRootWidget() {
return parseDiagnosticsNodeDaemon(
invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions
.getRootWidgetSummaryTreeWithPreviews.name,
{'groupName': groupName},
),
);
}
// TODO these ones could be not needed.
/* TODO(jacobr): this probably isn't needed.
Future<List<DiagnosticsPathNode>> getParentChain(DiagnosticsNode target) async {
if (disposed) return null;
if (useDaemonApi) {
return parseDiagnosticsPathDaemon(invokeServiceMethodDaemon('getParentChain', target.getValueRef()));
}
else {
return parseDiagnosticsPathObservatory(invokeServiceMethodObservatory('getParentChain', target.getValueRef()));
}
});
}
Future<List<DiagnosticsPathNode>> parseDiagnosticsPathObservatory(Future<InstanceRef> instanceRefFuture) {
return nullIfDisposed(() -> instanceRefFuture.thenComposeAsync(this::parseDiagnosticsPathObservatory));
}
Future<List<DiagnosticsPathNode>> parseDiagnosticsPathObservatory(InstanceRef pathRef) {
return nullIfDisposed(() -> instanceRefToJson(pathRef).thenApplyAsync(this::parseDiagnosticsPathHelper));
}
Future<List<DiagnosticsPathNode>> parseDiagnosticsPathDaemon(Future<JsonElement> jsonFuture) {
return nullIfDisposed(() -> jsonFuture.thenApplyAsync(this::parseDiagnosticsPathHelper));
}
List<DiagnosticsPathNode> parseDiagnosticsPathHelper(JsonElement jsonElement) {
return nullValueIfDisposed(() -> {
final JsonArray jsonArray = jsonElement.getAsJsonArray();
final List<DiagnosticsPathNode> pathNodes = new List<>();
for (JsonElement element : jsonArray) {
pathNodes.add(new DiagnosticsPathNode(element.getAsJsonObject(), this));
}
return pathNodes;
});
}
*/
Future<RemoteDiagnosticsNode?> getSelection(
RemoteDiagnosticsNode? previousSelection,
FlutterTreeType treeType, {
required bool isSummaryTree,
}) async {
// There is no reason to allow calling this method on a disposed group.
assert(!disposed);
if (disposed) return null;
RemoteDiagnosticsNode? newSelection;
final InspectorInstanceRef? previousSelectionRef =
previousSelection?.valueRef;
switch (treeType) {
case FlutterTreeType.widget:
newSelection = await invokeServiceMethodReturningNodeInspectorRef(
isSummaryTree
? WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name
: WidgetInspectorServiceExtensions.getSelectedWidget.name,
null,
);
break;
}
if (disposed) return null;
return newSelection != null && newSelection.valueRef == previousSelectionRef
? previousSelection
: newSelection;
}
@override
Future<bool> setSelectionInspector(
InspectorInstanceRef selection,
bool uiAlreadyUpdated,
) {
if (disposed) {
return Future.value(false);
}
if (uiAlreadyUpdated) {
inspectorService._trackClientSelfTriggeredSelection(selection);
}
return useDaemonApi
? handleSetSelectionDaemon(
invokeServiceMethodDaemonInspectorRef(
WidgetInspectorServiceExtensions.setSelectionById.name,
selection,
),
uiAlreadyUpdated,
)
: handleSetSelectionObservatory(
invokeServiceMethodObservatoryInspectorRef(
WidgetInspectorServiceExtensions.setSelectionById.name,
selection,
),
uiAlreadyUpdated,
);
}
Future<bool> setSelection(GenericInstanceRef selection) async {
if (disposed) {
return true;
}
return handleSetSelectionObservatory(
evalOnRef(
"${inspectorService.clientInspectorName}.instance.setSelection(object, '$groupName')",
selection,
),
false,
);
}
Future<bool> handleSetSelectionObservatory(
Future<InstanceRef?> setSelectionResult,
bool uiAlreadyUpdated,
) async {
// TODO(jacobr): we need to cancel if another inspect request comes in while we are trying this one.
if (disposed) return true;
final instanceRef = await setSelectionResult;
if (disposed) return true;
return handleSetSelectionHelper(
'true' == instanceRef?.valueAsString,
uiAlreadyUpdated,
);
}
bool handleSetSelectionHelper(bool selectionChanged, bool uiAlreadyUpdated) {
if (selectionChanged && !uiAlreadyUpdated && !disposed) {
inspectorService.notifySelectionChanged();
}
return selectionChanged && !disposed;
}
Future<bool> handleSetSelectionDaemon(
Future<Object?> setSelectionResult,
bool uiAlreadyUpdated,
) async {
if (disposed) return false;
// TODO(jacobr): we need to cancel if another inspect request comes in while we are trying this one.
final isSelectionChanged = await setSelectionResult;
if (disposed) return false;
return handleSetSelectionHelper(
isSelectionChanged as bool,
uiAlreadyUpdated,
);
}
Future<RemoteDiagnosticsNode?> getDetailsSubtree(
RemoteDiagnosticsNode? node, {
int subtreeDepth = 2,
}) async {
if (node == null) return null;
final args = {
'objectGroup': groupName,
'arg': node.valueRef.id,
'subtreeDepth': subtreeDepth.toString(),
};
final json = await invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions.getDetailsSubtree.name,
args,
);
return parseDiagnosticsNodeHelper(json as Map<String, Object?>?);
}
Future<void> invokeSetFlexProperties(
InspectorInstanceRef ref,
MainAxisAlignment? mainAxisAlignment,
CrossAxisAlignment? crossAxisAlignment,
) async {
await invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions.setFlexProperties.name,
{
'id': ref.id,
'mainAxisAlignment': '$mainAxisAlignment',
'crossAxisAlignment': '$crossAxisAlignment',
},
);
}
Future<void> invokeSetFlexFactor(
InspectorInstanceRef ref,
int? flexFactor,
) async {
await invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions.setFlexFactor.name,
{'id': ref.id, 'flexFactor': '$flexFactor'},
);
}
Future<void> invokeSetFlexFit(
InspectorInstanceRef ref,
FlexFit flexFit,
) async {
await invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions.setFlexFit.name,
{'id': ref.id, 'flexFit': '$flexFit'},
);
}
Future<RemoteDiagnosticsNode?> getLayoutExplorerNode(
RemoteDiagnosticsNode? node, {
int subtreeDepth = 1,
}) async {
if (node == null) return null;
return parseDiagnosticsNodeDaemon(
invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions.getLayoutExplorerNode.name,
{
'groupName': groupName,
'id': node.valueRef.id,
'subtreeDepth': '$subtreeDepth',
},
),
);
}
Future<List<String>> getPubRootDirectories() async {
final invocationResult = await invokeServiceMethodDaemonParams(
WidgetInspectorServiceExtensions.getPubRootDirectories.name,
{},
);
final directories = (invocationResult as List?)?.cast<Object>();
return List.from(directories ?? []);
}
}
abstract class InspectorServiceClient {
void onInspectorSelectionChanged();
void onFlutterFrame();
Future<void> onForceRefresh();
}
/// Manager that simplifies preventing memory leaks when using the
/// InspectorService.
///
/// This class is designed for the use case where you want to manage
/// object references associated with the current displayed UI and object
/// references associated with the candidate next frame of UI to display. Once
/// the next frame is ready, you determine whether you want to display it and
/// discard the current frame and promote the next frame to the current
/// frame if you want to display the next frame otherwise you discard the next
/// frame.
///
/// To use this class load all data you want for the next frame by using
/// the object group specified by [next] and then if you decide to switch
/// to display that frame, call promoteNext() otherwise call clearNext().
class InspectorObjectGroupManager {
InspectorObjectGroupManager(this.inspectorService, this.debugName);
final InspectorService inspectorService;
final String debugName;
ObjectGroup? _current;
ObjectGroup? _next;
Completer<void>? _pendingNext;
Future<void> get pendingUpdateDone {
if (_pendingNext != null) {
return _pendingNext!.future;
}
if (_next == null) {
// There is no pending update.
return Future.value();
}
_pendingNext = Completer();
return _pendingNext!.future;
}
ObjectGroup get next {
_next ??= inspectorService.createObjectGroup(debugName);
return _next!;
}
void clear(bool isolateStopped) {
if (isolateStopped) {
// The Dart VM will handle GCing the underlying memory.
_current = null;
_setNextNull();
} else {
clearCurrent();
cancelNext();
}
}
void promoteNext() {
clearCurrent();
_current = _next;
_setNextNull();
}
void clearCurrent() {
if (_current != null) {
unawaited(_current!.dispose());
_current = null;
}
}
void cancelNext() {
if (_next != null) {
unawaited(_next!.dispose());
_setNextNull();
}
}
void _setNextNull() {
_next = null;
if (_pendingNext != null) {
_pendingNext!.complete(null);
_pendingNext = null;
}
}
}
| devtools/packages/devtools_app/lib/src/shared/diagnostics/inspector_service.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/diagnostics/inspector_service.dart",
"repo_id": "devtools",
"token_count": 15169
} | 111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.