text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_06_a/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_06_a/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 12 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_06_b/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_06_b/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 13 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/dart-patterns-and-records/step_07_a/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_07_a/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 14 |
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_11_b/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_11_b/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 15 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_12/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_12/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 16 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/deeplink_cookbook/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/deeplink_cookbook/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 17 |
import 'package:ffigen_app/ffigen_app.dart';
import 'package:ffigen_app_example/main.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('DuktapeApp displays the title', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const ProviderScope(child: DuktapeApp()));
// Verify that our app displays the title
expect(find.text('Duktape REPL'), findsOneWidget);
});
test('Duktape.evalString', () {
final duktape = Duktape();
final response = duktape.evalString('1+2');
expect(response, '3');
});
}
| codelabs/ffigen_codelab/step_07/example/test/widget_test.dart/0 | {
"file_path": "codelabs/ffigen_codelab/step_07/example/test/widget_test.dart",
"repo_id": "codelabs",
"token_count": 238
} | 18 |
import 'package:flutter/material.dart';
import 'entry.dart';
class EntryView extends StatelessWidget {
final Entry entry;
const EntryView({super.key, required this.entry});
@override
Widget build(BuildContext context) {
return Card(
elevation: 6,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: Text(
entry.title,
style: Theme.of(context).textTheme.titleLarge,
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Date: ${entry.date}',
style: Theme.of(context).textTheme.labelMedium,
),
),
const Divider(),
Expanded(
child: Text(
entry.text,
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
height: 1.3,
wordSpacing: 1.2,
letterSpacing: 1.05,
),
),
),
],
),
),
);
}
}
| codelabs/firebase-emulator-suite/complete/lib/journal_entry_widget.dart/0 | {
"file_path": "codelabs/firebase-emulator-suite/complete/lib/journal_entry_widget.dart",
"repo_id": "codelabs",
"token_count": 731
} | 19 |
#import "GeneratedPluginRegistrant.h"
| codelabs/firebase-get-to-know-flutter/step_04/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_04/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 20 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/firebase-get-to-know-flutter/step_05/android/gradle.properties/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_05/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 21 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/firebase-get-to-know-flutter/step_07/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_07/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 22 |
// Copyright 2022 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart'
hide EmailAuthProvider, PhoneAuthProvider;
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ui_auth/firebase_ui_auth.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
import 'guest_book_message.dart';
enum Attending { yes, no, unknown }
class ApplicationState extends ChangeNotifier {
ApplicationState() {
init();
}
bool _loggedIn = false;
bool get loggedIn => _loggedIn;
bool _emailVerified = false;
bool get emailVerified => _emailVerified;
StreamSubscription<QuerySnapshot>? _guestBookSubscription;
List<GuestBookMessage> _guestBookMessages = [];
List<GuestBookMessage> get guestBookMessages => _guestBookMessages;
int _attendees = 0;
int get attendees => _attendees;
static Map<String, dynamic> defaultValues = <String, dynamic>{
'event_date': 'October 18, 2022',
'enable_free_swag': false,
'call_to_action': 'Join us for a day full of Firebase Workshops and Pizza!',
};
// ignoring lints on these fields since we are modifying them in a different
// part of the codelab
// ignore: prefer_final_fields
bool _enableFreeSwag = defaultValues['enable_free_swag'] as bool;
bool get enableFreeSwag => _enableFreeSwag;
// ignore: prefer_final_fields
String _eventDate = defaultValues['event_date'] as String;
String get eventDate => _eventDate;
// ignore: prefer_final_fields
String _callToAction = defaultValues['call_to_action'] as String;
String get callToAction => _callToAction;
Attending _attending = Attending.unknown;
StreamSubscription<DocumentSnapshot>? _attendingSubscription;
Attending get attending => _attending;
set attending(Attending attending) {
final userDoc = FirebaseFirestore.instance
.collection('attendees')
.doc(FirebaseAuth.instance.currentUser!.uid);
if (attending == Attending.yes) {
userDoc.set(<String, dynamic>{'attending': true});
} else {
userDoc.set(<String, dynamic>{'attending': false});
}
}
Future<void> init() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
FirebaseUIAuth.configureProviders([
EmailAuthProvider(),
]);
FirebaseFirestore.instance
.collection('attendees')
.where('attending', isEqualTo: true)
.snapshots()
.listen((snapshot) {
_attendees = snapshot.docs.length;
notifyListeners();
});
FirebaseAuth.instance.userChanges().listen((user) {
if (user != null) {
_loggedIn = true;
_emailVerified = user.emailVerified;
_guestBookSubscription = FirebaseFirestore.instance
.collection('guestbook')
.orderBy('timestamp', descending: true)
.snapshots()
.listen((snapshot) {
_guestBookMessages = [];
for (final document in snapshot.docs) {
_guestBookMessages.add(
GuestBookMessage(
name: document.data()['name'] as String,
message: document.data()['text'] as String,
),
);
}
notifyListeners();
});
_attendingSubscription = FirebaseFirestore.instance
.collection('attendees')
.doc(user.uid)
.snapshots()
.listen((snapshot) {
if (snapshot.data() != null) {
if (snapshot.data()!['attending'] as bool) {
_attending = Attending.yes;
} else {
_attending = Attending.no;
}
} else {
_attending = Attending.unknown;
}
notifyListeners();
});
} else {
_loggedIn = false;
_emailVerified = false;
_guestBookMessages = [];
_guestBookSubscription?.cancel();
_attendingSubscription?.cancel();
}
notifyListeners();
});
}
Future<void> refreshLoggedInUser() async {
final currentUser = FirebaseAuth.instance.currentUser;
if (currentUser == null) {
return;
}
await currentUser.reload();
}
Future<DocumentReference> addMessageToGuestBook(String message) {
if (!_loggedIn) {
throw Exception('Must be logged in');
}
return FirebaseFirestore.instance
.collection('guestbook')
.add(<String, dynamic>{
'text': message,
'timestamp': DateTime.now().millisecondsSinceEpoch,
'name': FirebaseAuth.instance.currentUser!.displayName,
'userId': FirebaseAuth.instance.currentUser!.uid,
});
}
}
| codelabs/firebase-get-to-know-flutter/step_09/lib/app_state.dart/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_09/lib/app_state.dart",
"repo_id": "codelabs",
"token_count": 1931
} | 23 |
include: ../../analysis_options.yaml
| codelabs/github-client/step_03/analysis_options.yaml/0 | {
"file_path": "codelabs/github-client/step_03/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 12
} | 24 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_03/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/github-client/step_03/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 25 |
// 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 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:oauth2/oauth2.dart' as oauth2;
import 'package:url_launcher/url_launcher.dart';
final _authorizationEndpoint =
Uri.parse('https://github.com/login/oauth/authorize');
final _tokenEndpoint = Uri.parse('https://github.com/login/oauth/access_token');
class GithubLoginWidget extends StatefulWidget {
const GithubLoginWidget({
required this.builder,
required this.githubClientId,
required this.githubClientSecret,
required this.githubScopes,
super.key,
});
final AuthenticatedBuilder builder;
final String githubClientId;
final String githubClientSecret;
final List<String> githubScopes;
@override
State<GithubLoginWidget> createState() => _GithubLoginState();
}
typedef AuthenticatedBuilder = Widget Function(
BuildContext context, oauth2.Client client);
class _GithubLoginState extends State<GithubLoginWidget> {
HttpServer? _redirectServer;
oauth2.Client? _client;
@override
Widget build(BuildContext context) {
final client = _client;
if (client != null) {
return widget.builder(context, client);
}
return Scaffold(
appBar: AppBar(
title: const Text('Github Login'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
await _redirectServer?.close();
// Bind to an ephemeral port on localhost
_redirectServer = await HttpServer.bind('localhost', 0);
var authenticatedHttpClient = await _getOAuth2Client(
Uri.parse('http://localhost:${_redirectServer!.port}/auth'));
setState(() {
_client = authenticatedHttpClient;
});
},
child: const Text('Login to Github'),
),
),
);
}
Future<oauth2.Client> _getOAuth2Client(Uri redirectUrl) async {
if (widget.githubClientId.isEmpty || widget.githubClientSecret.isEmpty) {
throw const GithubLoginException(
'githubClientId and githubClientSecret must be not empty. '
'See `lib/github_oauth_credentials.dart` for more detail.');
}
var grant = oauth2.AuthorizationCodeGrant(
widget.githubClientId,
_authorizationEndpoint,
_tokenEndpoint,
secret: widget.githubClientSecret,
httpClient: _JsonAcceptingHttpClient(),
);
var authorizationUrl =
grant.getAuthorizationUrl(redirectUrl, scopes: widget.githubScopes);
await _redirect(authorizationUrl);
var responseQueryParameters = await _listen();
var client =
await grant.handleAuthorizationResponse(responseQueryParameters);
return client;
}
Future<void> _redirect(Uri authorizationUrl) async {
if (await canLaunchUrl(authorizationUrl)) {
await launchUrl(authorizationUrl);
} else {
throw GithubLoginException('Could not launch $authorizationUrl');
}
}
Future<Map<String, String>> _listen() async {
var request = await _redirectServer!.first;
var params = request.uri.queryParameters;
request.response.statusCode = 200;
request.response.headers.set('content-type', 'text/plain');
request.response.writeln('Authenticated! You can close this tab.');
await request.response.close();
await _redirectServer!.close();
_redirectServer = null;
return params;
}
}
class _JsonAcceptingHttpClient extends http.BaseClient {
final _httpClient = http.Client();
@override
Future<http.StreamedResponse> send(http.BaseRequest request) {
request.headers['Accept'] = 'application/json';
return _httpClient.send(request);
}
}
class GithubLoginException implements Exception {
const GithubLoginException(this.message);
final String message;
@override
String toString() => message;
}
| codelabs/github-client/step_04/lib/src/github_login.dart/0 | {
"file_path": "codelabs/github-client/step_04/lib/src/github_login.dart",
"repo_id": "codelabs",
"token_count": 1526
} | 26 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_04/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/github-client/step_04/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 27 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_05/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/github-client/step_05/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 28 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_06/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/github-client/step_06/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 29 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/github-client/step_07/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/github-client/step_07/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 30 |
# google_maps_in_flutter
The code steps for the [Google Maps in Flutter codelab][codelab].
## Code steps
The naming of the step directories follows the steps of the associated code
lab. The directories are as follows:
- `step_3` contains the code as at the end of _Getting Started_
- `step_4` contains the code as at the end of _Adding Google Maps to the app_
- `step_5` contains the code as at the end of _Put Google on the Map_
Note, these projects do not contain API Keys. You will need to follow the steps in the tutorial to add them.
[codelab]: https://codelabs.developers.google.com/codelabs/google-maps-in-flutter | codelabs/google-maps-in-flutter/README.md/0 | {
"file_path": "codelabs/google-maps-in-flutter/README.md",
"repo_id": "codelabs",
"token_count": 182
} | 31 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/haiku_generator/finished/android/gradle.properties/0 | {
"file_path": "codelabs/haiku_generator/finished/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 32 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/haiku_generator/finished/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/finished/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 33 |
#import "GeneratedPluginRegistrant.h"
| codelabs/haiku_generator/step0/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/haiku_generator/step0/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 34 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/haiku_generator/step1/android/gradle.properties/0 | {
"file_path": "codelabs/haiku_generator/step1/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 35 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/haiku_generator/step1/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/step1/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 36 |
#import "GeneratedPluginRegistrant.h"
| codelabs/haiku_generator/step2/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/haiku_generator/step2/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 37 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/haiku_generator/step3/android/gradle.properties/0 | {
"file_path": "codelabs/haiku_generator/step3/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 38 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/haiku_generator/step3/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/step3/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 39 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/homescreen_codelab/step_06/android/gradle.properties/0 | {
"file_path": "codelabs/homescreen_codelab/step_06/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 40 |
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:in_app_purchase/in_app_purchase.dart';
import '../constants.dart';
import '../main.dart';
import '../model/purchasable_product.dart';
import '../model/store_state.dart';
import '../repo/iap_repo.dart';
import 'dash_counter.dart';
import 'firebase_notifier.dart';
class DashPurchases extends ChangeNotifier {
DashCounter counter;
FirebaseNotifier firebaseNotifier;
IAPRepo iapRepo;
StoreState storeState = StoreState.loading;
late StreamSubscription<List<PurchaseDetails>> _subscription;
List<PurchasableProduct> products = [];
bool get beautifiedDash => _beautifiedDashUpgrade;
bool _beautifiedDashUpgrade = false;
final iapConnection = IAPConnection.instance;
DashPurchases(this.counter, this.firebaseNotifier, this.iapRepo) {
final purchaseUpdated = iapConnection.purchaseStream;
_subscription = purchaseUpdated.listen(
_onPurchaseUpdate,
onDone: _updateStreamOnDone,
onError: _updateStreamOnError,
);
iapRepo.addListener(purchasesUpdate);
loadPurchases();
}
Future<void> loadPurchases() async {
final available = await iapConnection.isAvailable();
if (!available) {
storeState = StoreState.notAvailable;
notifyListeners();
return;
}
const ids = <String>{
storeKeyConsumable,
storeKeySubscription,
storeKeyUpgrade,
};
final response = await iapConnection.queryProductDetails(ids);
products =
response.productDetails.map((e) => PurchasableProduct(e)).toList();
storeState = StoreState.available;
notifyListeners();
}
@override
void dispose() {
iapRepo.removeListener(purchasesUpdate);
_subscription.cancel();
super.dispose();
}
Future<void> buy(PurchasableProduct product) async {
final purchaseParam = PurchaseParam(productDetails: product.productDetails);
switch (product.id) {
case storeKeyConsumable:
await iapConnection.buyConsumable(purchaseParam: purchaseParam);
case storeKeySubscription:
case storeKeyUpgrade:
await iapConnection.buyNonConsumable(purchaseParam: purchaseParam);
default:
throw ArgumentError.value(
product.productDetails, '${product.id} is not a known product');
}
}
Future<void> _onPurchaseUpdate(
List<PurchaseDetails> purchaseDetailsList) async {
for (var purchaseDetails in purchaseDetailsList) {
await _handlePurchase(purchaseDetails);
}
notifyListeners();
}
Future<void> _handlePurchase(PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.purchased) {
// Send to server
var validPurchase = await _verifyPurchase(purchaseDetails);
if (validPurchase) {
// Apply changes locally
switch (purchaseDetails.productID) {
case storeKeySubscription:
counter.applyPaidMultiplier();
case storeKeyConsumable:
counter.addBoughtDashes(2000);
case storeKeyUpgrade:
_beautifiedDashUpgrade = true;
}
}
}
if (purchaseDetails.pendingCompletePurchase) {
await iapConnection.completePurchase(purchaseDetails);
}
}
Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
final url = Uri.parse('http://$serverIp:8080/verifypurchase');
const headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response = await http.post(
url,
body: jsonEncode({
'source': purchaseDetails.verificationData.source,
'productId': purchaseDetails.productID,
'verificationData':
purchaseDetails.verificationData.serverVerificationData,
'userId': firebaseNotifier.user?.uid,
}),
headers: headers,
);
if (response.statusCode == 200) {
print('Successfully verified purchase');
return true;
} else {
print('failed request: ${response.statusCode} - ${response.body}');
return false;
}
}
void _updateStreamOnDone() {
_subscription.cancel();
}
void _updateStreamOnError(dynamic error) {
print(error);
}
void purchasesUpdate() {
var subscriptions = <PurchasableProduct>[];
var upgrades = <PurchasableProduct>[];
// Get a list of purchasable products for the subscription and upgrade.
// This should be 1 per type.
if (products.isNotEmpty) {
subscriptions = products
.where((element) => element.productDetails.id == storeKeySubscription)
.toList();
upgrades = products
.where((element) => element.productDetails.id == storeKeyUpgrade)
.toList();
}
// Set the subscription in the counter logic and show/hide purchased on the
// purchases page.
if (iapRepo.hasActiveSubscription) {
counter.applyPaidMultiplier();
for (final element in subscriptions) {
_updateStatus(element, ProductStatus.purchased);
}
} else {
counter.removePaidMultiplier();
for (final element in subscriptions) {
_updateStatus(element, ProductStatus.purchasable);
}
}
// Set the dash beautifier and show/hide purchased on
// the purchases page.
if (iapRepo.hasUpgrade != _beautifiedDashUpgrade) {
_beautifiedDashUpgrade = iapRepo.hasUpgrade;
for (final element in upgrades) {
_updateStatus(
element,
_beautifiedDashUpgrade
? ProductStatus.purchased
: ProductStatus.purchasable);
}
notifyListeners();
}
}
void _updateStatus(PurchasableProduct product, ProductStatus status) {
if (product.status != status) {
product.status = status;
notifyListeners();
}
}
}
| codelabs/in_app_purchases/complete/app/lib/logic/dash_purchases.dart/0 | {
"file_path": "codelabs/in_app_purchases/complete/app/lib/logic/dash_purchases.dart",
"repo_id": "codelabs",
"token_count": 2222
} | 41 |
## 1.0.0
- Initial version.
| codelabs/in_app_purchases/complete/dart-backend/CHANGELOG.md/0 | {
"file_path": "codelabs/in_app_purchases/complete/dart-backend/CHANGELOG.md",
"repo_id": "codelabs",
"token_count": 13
} | 42 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/in_app_purchases/step_00/app/android/gradle.properties/0 | {
"file_path": "codelabs/in_app_purchases/step_00/app/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 43 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/in_app_purchases/step_07/app/android/gradle.properties/0 | {
"file_path": "codelabs/in_app_purchases/step_07/app/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 44 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/in_app_purchases/step_08/app/android/gradle.properties/0 | {
"file_path": "codelabs/in_app_purchases/step_08/app/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 45 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/in_app_purchases/step_09/app/android/gradle.properties/0 | {
"file_path": "codelabs/in_app_purchases/step_09/app/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 46 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_03/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_03/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 47 |
#include "Generated.xcconfig"
| codelabs/namer/step_05_b_extract/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_b_extract/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 48 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_05_b_extract/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_b_extract/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 49 |
#import "GeneratedPluginRegistrant.h"
| codelabs/namer/step_05_c_card_padding/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/namer/step_05_c_card_padding/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 50 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_05_c_card_padding/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_c_card_padding/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 51 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/namer/step_06_b_add_row/android/gradle.properties/0 | {
"file_path": "codelabs/namer/step_06_b_add_row/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 52 |
#include "Generated.xcconfig"
| codelabs/namer/step_07_a_split_my_home_page/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_a_split_my_home_page/ios/Flutter/Release.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-Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_a_split_my_home_page/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 54 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_07_b_convert_to_stateful/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_b_convert_to_stateful/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 55 |
#include "Generated.xcconfig"
| codelabs/namer/step_08/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_08/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 56 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_08/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_08/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 57 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_02_a/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_02_a/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 58 |
#import "GeneratedPluginRegistrant.h"
| codelabs/next-gen-ui/step_02_b/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/next-gen-ui/step_02_b/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 59 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_04_b/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_04_b/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 60 |
#import "GeneratedPluginRegistrant.h"
| codelabs/next-gen-ui/step_04_c/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/next-gen-ui/step_04_c/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 61 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/next-gen-ui/step_04_e/android/gradle.properties/0 | {
"file_path": "codelabs/next-gen-ui/step_04_e/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 62 |
include: ../../analysis_options.yaml
| codelabs/testing_codelab/step_06/analysis_options.yaml/0 | {
"file_path": "codelabs/testing_codelab/step_06/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 12
} | 63 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/tfagents-flutter/step3/frontend/android/gradle.properties/0 | {
"file_path": "codelabs/tfagents-flutter/step3/frontend/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 64 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/tfrs-flutter/step0/frontend/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step0/frontend/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 65 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/tfrs-flutter/step1/frontend/android/gradle.properties/0 | {
"file_path": "codelabs/tfrs-flutter/step1/frontend/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 66 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfrs-flutter/step5/frontend/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step5/frontend/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 67 |
include: ../../../analysis_options.yaml
analyzer:
exclude: [lib/proto/generated/**]
linter:
rules:
| codelabs/tfserving-flutter/codelab2/finished/analysis_options.yaml/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/finished/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 40
} | 68 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/tfserving-flutter/codelab2/starter/android/gradle.properties/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 69 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/tfserving-flutter/codelab2/starter/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 70 |
// Copyright 2023 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:convert';
import 'dart:io';
import 'package:claat_export_images/claat_export_images.dart';
import 'package:googleapis/docs/v1.dart' as gdoc;
import 'package:test/test.dart';
void main() async {
final items = (jsonDecode(await File('test/data/data.json').readAsString())
as List<dynamic>)
.map((e) => e.toString());
test('load data.json', () async {
expect(items.length, 8);
for (final item in items) {
var jsonContent = await File(item).readAsString();
expect(jsonContent, isNotNull);
expect(jsonDecode(jsonContent), isNotNull);
final document = gdoc.Document.fromJson(jsonDecode(jsonContent));
final uris = claatImageUris(document);
expect(uris, isNotNull);
expect(uris.length, greaterThan(0));
}
});
}
| codelabs/tooling/claat_export_images/test/claat_export_images_test.dart/0 | {
"file_path": "codelabs/tooling/claat_export_images/test/claat_export_images_test.dart",
"repo_id": "codelabs",
"token_count": 360
} | 71 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/webview_flutter/step_08/android/gradle.properties/0 | {
"file_path": "codelabs/webview_flutter/step_08/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 72 |
h1 {
color: blue;
}
| codelabs/webview_flutter/step_12/assets/www/styles/style.css/0 | {
"file_path": "codelabs/webview_flutter/step_12/assets/www/styles/style.css",
"repo_id": "codelabs",
"token_count": 12
} | 73 |
Testing for DevTools
=======================
DevTools is test covered by multiple types of tests, all of which are run on the CI for each DevTools PR / commit:
1. Unit tests
- tests for business logic
2. Widget tests
- tests for DevTools UI components using mock or fake data
- some widget tests may contain golden image testing
3. Partial integration tests
- tests for DevTools UI and business logic with a real VM service connection to a test app
4. Full integration tests
- Flutter web integration tests that run DevTools as a Flutter web app and connect it to a real test app
on multiple platforms (Flutter mobile, Flutter web, and Dart CLI)
**The following instructions are for unit tests, widget tests, and partial integration tests** in DevTools. For instructions
on running and writing full integration tests, please see [integration_test/README.md](integration_test/README.md).
In general, we should first try to test cover new features and bug fixes with unit tests or widget tests
before writing new integration tests, which are slower to run and are not as easy to debug or iterate upon.
## Running DevTools tests
Before running tests, make sure your Flutter SDK matches the version that will be used on
the CI. To update your local flutter version, run:
```
./tool/update_flutter_sdk.sh --local
```
> Note: Running this command requires that you have followed the [set up instructions](CONTRIBUTING.md#set-up-your-devtools-environment)
in the DevTools contributing guide regarding cloning the Flutter SDK from GitHub.
Now you can proceed with running DevTools tests:
```
cd packages/devtools_app
flutter test test/
```
### Updating golden image files
> Note: golden images should only be generated on MacOS.
Golden image tests will fail for one of three reasons:
1. The UI has been _intentionally_ modified.
2. Something changed in the Flutter framework that would cause downstream changes for our tests.
3. The UI has been _unintentionally_ modified, in which case we should not accept the changes.
For valid golden image updates (1 and 2 above), the failing golden images will need to be updated. This can
be done in one of two ways:
1. If the tests failed on the CI for a PR, we can download the generated golden images directly from GitHub.
> If you are developing on a non-MacOS machine, this is the only way you'll be able to update the golden images.
- Natvigate to the failed Actions run for your PR on GitHub. Example:

- Scroll to the bottom of the Summary view to see the errors from the `macos goldens` job, and the notice containing the golden update command:

2. Update the goldens locally by running the failing test(s) with the `--update-goldens` flag.
- Before updating the goldens, ensure your version of Flutter matches the version of Flutter that is used
on the CI. To update your local flutter version, run:
```
./tool/update_flutter_sdk.sh --local
```
- Then proceed with updating the goldens:
```
flutter test <path/to/my/test> --update-goldens
```
or to update goldens for all tests:
```
flutter test test/ --update-goldens
```
## Writing DevTools tests
When you add a new feature or fix a bug, please add a corresponding test for your change.
- If there is an existing test file for the feature your code touches, you can add the test case
there.
- Otherwise, create a new test file with the `_test.dart` suffix, and place it in an appropriate
location under the `test/` directory for the DevTools package you are working on.
| devtools/TESTING.md/0 | {
"file_path": "devtools/TESTING.md",
"repo_id": "devtools",
"token_count": 1059
} | 74 |
#include "ephemeral/Flutter-Generated.xcconfig"
| devtools/case_study/code_size/optimized/code_size_package/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "devtools/case_study/code_size/optimized/code_size_package/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "devtools",
"token_count": 19
} | 75 |
#include "ephemeral/Flutter-Generated.xcconfig"
| devtools/case_study/code_size/unoptimized/code_size_package/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "devtools/case_study/code_size/unoptimized/code_size_package/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "devtools",
"token_count": 19
} | 76 |
#include "ephemeral/Flutter-Generated.xcconfig"
| devtools/case_study/memory_leaks/images_1/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "devtools/case_study/memory_leaks/images_1/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "devtools",
"token_count": 19
} | 77 |
// 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:flutter/material.dart';
import 'about.dart';
import 'common.dart';
import 'logging.dart';
import 'tabs/logger.dart';
import 'tabs/settings.dart';
void main() {
Logging.logging.add('Starting...');
runApp(
MaterialApp(
// Title
title: appName,
// Home
home: MyHome(),
),
);
}
class MyHome extends StatefulWidget {
@override
State<MyHome> createState() => MyHomeState();
}
/// Setup Tabs
class MyHomeState extends State<MyHome> with SingleTickerProviderStateMixin {
// Create a tab controller
late final TabController controller;
@override
void initState() {
super.initState();
// Initialize the Tab Controller
controller = TabController(length: 1, vsync: this);
}
@override
void dispose() {
// Dispose of the Tab Controller
controller.dispose();
super.dispose();
}
/// Setup the tabs.
@override
Widget build(BuildContext context) {
return Scaffold(
// Appbar
appBar: AppBar(
// Title
title: const Text(appName),
actions: <Widget>[
PopupMenuButton<String>(
onSelected: showMenuSelection,
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
const PopupMenuItem<String>(
value: logMenu,
child: Text(logMenu),
),
const PopupMenuItem<String>(
value: aboutMenu,
child: Text(aboutMenu),
),
],
),
],
// Set the background color of the App Bar
backgroundColor: Colors.blue,
// Set the bottom property of the Appbar to include a Tab Bar
),
body: Settings(),
);
}
void showMenuSelection(String value) {
switch (value) {
case logMenu:
unawaited(
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Logger()),
),
);
break;
case aboutMenu:
unawaited(
Navigator.push(
context,
MaterialPageRoute(builder: (context) => About()),
),
);
break;
default:
print('ERROR: Unhandled Menu.');
}
}
}
| devtools/case_study/memory_leaks/memory_leak_app/lib/main.dart/0 | {
"file_path": "devtools/case_study/memory_leaks/memory_leak_app/lib/main.dart",
"repo_id": "devtools",
"token_count": 1062
} | 78 |
include: package:flutter_lints/flutter.yaml
analyzer:
language:
# strict-casts: true # Over 300 issues; mostly parsing JSON
# Enabling strict-inference requires adding type annotations to a bunch of
# silly locations; namely `Future.delayed`. Does not seem pragmatic right
# now.
# strict-inference: true # 34 issues
# strict-raw-types: true # Over 100 issues.
errors:
# treat missing required parameters as a warning (not a hint)
missing_required_param: warning
exclude:
- build/**
- '**.freezed.dart'
- flutter-sdk/
linter:
rules:
# Added on top of the flutter/flutter lints:
- prefer_generic_function_type_aliases
# From flutter/flutter:
# these rules are documented on and in the same order as
# the Dart Lint rules page to make maintenance easier
# https://github.com/dart-lang/linter/blob/master/example/all.yaml
- always_declare_return_types
# - always_put_control_body_on_new_line
# - always_put_required_named_parameters_first # we prefer having parameters in the same order as fields https://github.com/flutter/flutter/issues/10219
# - always_specify_types
- annotate_overrides
# - avoid_annotating_with_dynamic # conflicts with always_specify_types
# - avoid_as # we use 'as' in this codebase
# - avoid_bool_literals_in_conditional_expressions # not yet tested
# - avoid_catches_without_on_clauses # we do this commonly
# - avoid_catching_errors # we do this commonly
- avoid_classes_with_only_static_members
# - avoid_double_and_int_checks # only useful when targeting JS runtime
- avoid_empty_else
- avoid_dynamic_calls
- avoid_field_initializers_in_const_classes
- avoid_function_literals_in_foreach_calls
- avoid_init_to_null
# - avoid_js_rounded_ints # only useful when targeting JS runtime
- avoid_null_checks_in_equality_operators
# - avoid_positional_boolean_parameters # not yet tested
- avoid_print
# - avoid_private_typedef_functions # we prefer having typedef (discussion in https://github.com/flutter/flutter/pull/16356)
- avoid_redundant_argument_values
- avoid_relative_lib_imports
- avoid_renaming_method_parameters
- avoid_return_types_on_setters
# - avoid_returning_null # we do this commonly
# - avoid_returning_this # https://github.com/dart-lang/linter/issues/842
# - avoid_setters_without_getters # not yet tested
# - avoid_single_cascade_in_expression_statements # not yet tested
- avoid_slow_async_io
# - avoid_types_as_parameter_names # https://github.com/dart-lang/linter/pull/954/files
# - avoid_types_on_closure_parameters # conflicts with always_specify_types
- avoid_unnecessary_containers
# - avoid_unused_constructor_parameters # https://github.com/dart-lang/linter/pull/847
- await_only_futures
- camel_case_types
- cancel_subscriptions
# - cascade_invocations # not yet tested
# - close_sinks # https://github.com/flutter/flutter/issues/5789
# - comment_references # blocked on https://github.com/dart-lang/dartdoc/issues/1153
# - constant_identifier_names # https://github.com/dart-lang/linter/issues/204
- control_flow_in_finally
- directives_ordering
- discarded_futures
- empty_catches
- empty_constructor_bodies
- empty_statements
- hash_and_equals
- implementation_imports
# - join_return_with_assignment # not yet tested
- library_names
- library_prefixes
# - literal_only_boolean_expressions # https://github.com/flutter/flutter/issues/5791
- no_adjacent_strings_in_list
- no_duplicate_case_values
- non_constant_identifier_names
# - omit_local_variable_types # opposite of always_specify_types
# - one_member_abstracts # too many false positives
# - only_throw_errors # https://github.com/flutter/flutter/issues/5792
- overridden_fields
- package_api_docs
- package_names
- package_prefixed_library_names
# - parameter_assignments # we do this commonly
- prefer_adjacent_string_concatenation
- prefer_asserts_in_initializer_lists
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_const_constructors
- prefer_const_constructors_in_immutables
- prefer_const_declarations
- prefer_const_literals_to_create_immutables
# - prefer_constructors_over_static_methods # not yet tested
- prefer_contains
# - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods
- prefer_final_fields
- prefer_final_locals
- prefer_foreach
# - prefer_function_declarations_over_variables # not yet tested
- prefer_initializing_formals
# - prefer_interpolation_to_compose_strings # not yet tested
# - prefer_iterable_whereType # https://github.com/dart-lang/sdk/issues/32463
- prefer_is_empty
- prefer_is_not_empty
- prefer_relative_imports
- prefer_single_quotes
- prefer_typing_uninitialized_variables
- require_trailing_commas
- recursive_getters
- slash_for_doc_comments
- sort_child_properties_last
- sort_constructors_first
- sort_unnamed_constructors_first
- test_types_in_equals
- throw_in_finally
# - type_annotate_public_apis # subset of always_specify_types
- type_init_formals
- unawaited_futures
- unnecessary_brace_in_string_interps
- unnecessary_const
- unnecessary_getters_setters
# - unnecessary_lambdas # https://github.com/dart-lang/linter/issues/498
- unnecessary_library_directive
- unnecessary_new
- unnecessary_null_aware_assignments
- unnecessary_null_in_if_null_operators
- unnecessary_overrides
- unnecessary_parenthesis
- unnecessary_statements
- unnecessary_this
- unrelated_type_equality_checks
- unsafe_html
- use_rethrow_when_possible
# - use_setters_to_change_properties # not yet tested
# - use_string_buffers # https://github.com/dart-lang/linter/pull/664
- use_string_in_part_of_directives
# - use_to_and_as_if_applicable # has false positives, so we prefer to catch this by code-review
- valid_regexps
# - void_checks # not yet tested
dart_code_metrics:
metrics:
cyclomatic-complexity: 20
number-of-parameters: 4
maximum-nesting-level: 5
metrics-exclude:
- test/**
rules:
# - arguments-ordering Too strict
# - avoid-banned-imports # TODO(polina-c): add configuration
- avoid-cascade-after-if-null
- avoid-collection-methods-with-unrelated-types
- avoid-duplicate-exports
- avoid-dynamic
# - avoid-global-state TODO(jacobr): bunch of false positives around boolean flags.
# - avoid-ignoring-return-values
# - avoid-late-keyword
- avoid-missing-enum-constant-in-map
# - avoid-nested-conditional-expressions Worth enabling but currently too many violators.
# - avoid-non-ascii-symbols TODO(jacobr): probably worth enabling.
# - avoid-non-null-assertion
# - avoid-passing-async-when-sync-expected TODO(jacobr): consider re-enabliing.
- avoid-redundant-async
- avoid-throw-in-catch-block:
exclude:
- '*test.dart'
# - avoid-top-level-members-in-tests Doesn't seem to match our style.
- avoid-unnecessary-type-assertions
- avoid-unnecessary-type-casts
- avoid-unrelated-type-assertions
- avoid-unused-parameters
# - ban-name # TODO(polina-c): add configuration
# - binary-expression-operand-order Some nice catches but too many false positives to enable.
- double-literal-format
# - format-comment TODO(jacobr): enable this one after fixing violations.
# TODO(jacobr): enable member-ordering. This catches a bunch of real style
# issues but would be alot of work to migrate.
# - member-ordering
# - newline-before-return TODO(jacobr): should be in the formatter if it was a rule to adopt.
- no-boolean-literal-compare
# - no-empty-block Too many false positives. However it does flag a bunch of code smells so possibly worth re-enabling.
# This one seems interesting but has too many false positives. Gave it a try.
# - no-equal-arguments:
# ignored-parameters:
# - height
# - width
# - double-literal-format
# - defaultSortColumn
# - left
# - right
# - top
# - bottom
# - bottomLeft
# - topLeft
# - enabledBorder
- no-equal-then-else
# - no-magic-number
# - no-object-declaration Too difficult to use along with avoiding dynamic particular for JSON decoding logic.
# - prefer-async-await TODO(jacobr): evaluate enabling.
- prefer-commenting-analyzer-ignores
# - prefer-conditional-expressions Too many false positives involving large conditional expressions.
# - prefer-correct-identifier-length Too many false positives with fine names like i and id.
# - prefer-correct-test-file-name TODO(jacobr): enable and fix violations.
- prefer-correct-type-name
# - prefer-enums-by-name Cannot able unless lint adds a special case for orElse
# - prefer-first TODO(jacobr): enable as a follow up PR.
# - prefer-immediate-return TODO(jacobr): enable as a follow up PR.
- prefer-iterable-of
- prefer-last
# - prefer-match-file-name
# TODO(jacobr): consider enabling or enabling to periodically audit.
# This one has a lot of false positives but is also quite nice.
# - prefer-moving-to-variable:
# allowed-duplicated-chains: 2
# - prefer-static-class
- prefer-trailing-comma
- always-remove-listener
# - avoid-border-all Micro-optimization to avoid a const constructor.
# - avoid-returning-widgets This one is nice but has a lot of false positives.
- avoid-shrink-wrap-in-lists
# - avoid-unnecessary-setstate It is unclear why to "Avoid calling sync methods that call 'setState'."
- avoid-expanded-as-spacer
- avoid-wrapping-in-padding
- check-for-equals-in-render-object-setters
- consistent-update-render-object
# - prefer-const-border-radius TODO(jacobr): enable.
- prefer-correct-edge-insets-constructor
# - prefer-extracting-callbacks I'm not clear this is always a good idea. Seems like a workaround.
# - prefer-single-widget-per-file
- prefer-using-list-view
| devtools/packages/analysis_options.yaml/0 | {
"file_path": "devtools/packages/analysis_options.yaml",
"repo_id": "devtools",
"token_count": 3752
} | 79 |
// Copyright 2023 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app/devtools_app.dart';
import 'package:devtools_app/initialization.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/material.dart';
import 'package:web_benchmarks/client.dart';
import 'automators/devtools_automator.dart';
import 'common.dart';
/// A recorder that measures frame building durations for the DevTools.
class DevToolsRecorder extends WidgetRecorder {
DevToolsRecorder({required this.benchmark})
: super(name: benchmark.id, useCustomWarmUp: true);
/// The name of the DevTools benchmark to be run.
///
/// See `common.dart` for the list of the names of all benchmarks.
final DevToolsBenchmark benchmark;
DevToolsAutomater? _devToolsAutomator;
bool get _finished => _devToolsAutomator?.finished ?? false;
/// Whether we should continue recording.
@override
bool shouldContinue() => !_finished || profile.shouldContinue();
/// Creates the [DevToolsAutomater] widget.
@override
Widget createWidget() {
_devToolsAutomator = DevToolsAutomater(
benchmark: benchmark,
stopWarmingUpCallback: profile.stopWarmingUp,
);
return _devToolsAutomator!.createWidget();
}
@override
Future<Profile> run() async {
// Set the environment parameters global.
setGlobal(
DevToolsEnvironmentParameters,
ExternalDevToolsEnvironmentParameters(),
);
// ignore: invalid_use_of_visible_for_testing_member, valid use for benchmark tests.
await initializeDevTools();
return super.run();
}
}
| devtools/packages/devtools_app/benchmark/test_infra/devtools_recorder.dart/0 | {
"file_path": "devtools/packages/devtools_app/benchmark/test_infra/devtools_recorder.dart",
"repo_id": "devtools",
"token_count": 523
} | 80 |
// 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.
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:devtools_shared/devtools_test_utils.dart';
import '_utils.dart';
class TestFlutterApp extends IntegrationTestApp {
TestFlutterApp({
String appPath = 'test/test_infra/fixtures/flutter_app',
TestAppDevice appDevice = TestAppDevice.flutterTester,
}) : super(appPath, appDevice);
String? _currentRunningAppId;
@override
Future<void> startProcess() async {
runProcess = await Process.start(
'flutter',
[
'run',
'--machine',
'-d',
testAppDevice.argName,
// Do not serve DevTools from Flutter Tools.
'--no-devtools',
],
workingDirectory: testAppPath,
);
}
@override
Future<void> waitForAppStart() async {
// Set this up now, but we don't await it yet. We want to make sure we don't
// miss it while waiting for debugPort below.
final started = waitFor(
event: FlutterDaemonConstants.appStarted.key,
timeout: IntegrationTestApp._appStartTimeout,
);
final debugPort = await waitFor(
event: FlutterDaemonConstants.appDebugPort.key,
timeout: IntegrationTestApp._appStartTimeout,
);
final wsUriString = (debugPort[FlutterDaemonConstants.params.key]!
as Map<String, Object?>)[FlutterDaemonConstants.wsUri.key] as String;
_vmServiceWsUri = Uri.parse(wsUriString);
// Map to WS URI.
_vmServiceWsUri =
convertToWebSocketUrl(serviceProtocolUrl: _vmServiceWsUri);
// Now await the started event; if it had already happened the future will
// have already completed.
final startedResult = await started;
final params = startedResult[FlutterDaemonConstants.params.key]!
as Map<String, Object?>;
_currentRunningAppId = params[FlutterDaemonConstants.appId.key] as String?;
}
@override
Future<void> manuallyStopApp() async {
if (_currentRunningAppId != null) {
_debugPrint('Stopping app');
await Future.any<void>(<Future<void>>[
runProcess!.exitCode,
_sendFlutterDaemonRequest(
'app.stop',
<String, dynamic>{'appId': _currentRunningAppId},
),
]).timeout(
IOMixin.killTimeout,
onTimeout: () {
_debugPrint('app.stop did not return within ${IOMixin.killTimeout}');
},
);
_currentRunningAppId = null;
}
}
int _requestId = 1;
// ignore: avoid-dynamic, dynamic by design.
Future<dynamic> _sendFlutterDaemonRequest(
String method,
Object? params,
) async {
final int requestId = _requestId++;
final Map<String, dynamic> request = <String, dynamic>{
'id': requestId,
'method': method,
'params': params,
};
final String jsonEncoded = json.encode(<Map<String, dynamic>>[request]);
_debugPrint(jsonEncoded);
// Set up the response future before we send the request to avoid any
// races. If the method we're calling is app.stop then we tell waitFor not
// to throw if it sees an app.stop event before the response to this request.
final Future<Map<String, dynamic>> responseFuture = waitFor(
id: requestId,
ignoreAppStopEvent: method == 'app.stop',
);
runProcess!.stdin.writeln(jsonEncoded);
final Map<String, dynamic> response = await responseFuture;
if (response['error'] != null || response['result'] == null) {
throw Exception('Unexpected error response');
}
return response['result'];
}
Future<Map<String, Object?>> waitFor({
String? event,
int? id,
Duration? timeout,
bool ignoreAppStopEvent = false,
}) {
final response = Completer<Map<String, Object?>>();
late StreamSubscription<String> sub;
sub = stdoutController.stream.listen(
(String line) => _handleStdout(
line,
subscription: sub,
response: response,
event: event,
id: id,
ignoreAppStopEvent: ignoreAppStopEvent,
),
);
return _timeoutWithMessages<Map<String, Object?>>(
() => response.future,
timeout: timeout,
message: event != null
? 'Did not receive expected $event event.'
: 'Did not receive response to request "$id".',
).whenComplete(() => sub.cancel());
}
void _handleStdout(
String line, {
required StreamSubscription<String> subscription,
required Completer<Map<String, Object?>> response,
required String? event,
required int? id,
bool ignoreAppStopEvent = false,
}) async {
final json = _parseFlutterResponse(line);
if (json == null) {
return;
} else if ((event != null &&
json[FlutterDaemonConstants.event.key] == event) ||
(id != null && json[FlutterDaemonConstants.id.key] == id)) {
await subscription.cancel();
response.complete(json);
} else if (!ignoreAppStopEvent &&
json[FlutterDaemonConstants.event.key] ==
FlutterDaemonConstants.appStop.key) {
await subscription.cancel();
final error = StringBuffer();
error.write('Received app.stop event while waiting for ');
error.write(
'${event != null ? '$event event' : 'response to request $id.'}.\n\n',
);
final errorFromJson = (json[FlutterDaemonConstants.params.key]
as Map<String, Object?>?)?[FlutterDaemonConstants.error.key];
if (errorFromJson != null) {
error.write('$errorFromJson\n\n');
}
final traceFromJson = (json[FlutterDaemonConstants.params.key]
as Map<String, Object?>?)?[FlutterDaemonConstants.trace.key];
if (traceFromJson != null) {
error.write('$traceFromJson\n\n');
}
response.completeError(error.toString());
}
}
Map<String, Object?>? _parseFlutterResponse(String line) {
if (line.startsWith('[') && line.endsWith(']')) {
try {
return (json.decode(line) as List)[0];
} catch (e) {
// Not valid JSON, so likely some other output that was surrounded by
// [brackets].
return null;
}
}
return null;
}
}
class TestDartCliApp extends IntegrationTestApp {
TestDartCliApp({
String appPath = 'test/test_infra/fixtures/empty_app.dart',
}) : super(appPath, TestAppDevice.cli);
static const vmServicePrefix = 'The Dart VM service is listening on ';
@override
Future<void> startProcess() async {
const separator = '/';
final parts = testAppPath.split(separator);
final scriptName = parts.removeLast();
final workingDir = parts.join(separator);
runProcess = await Process.start(
'dart',
[
'--observe=0',
'run',
scriptName,
],
workingDirectory: workingDir,
);
}
@override
Future<void> waitForAppStart() async {
final vmServiceUri = await waitFor(
message: vmServicePrefix,
timeout: IntegrationTestApp._appStartTimeout,
);
final parsedVmServiceUri = Uri.parse(vmServiceUri);
// Map to WS URI.
_vmServiceWsUri =
convertToWebSocketUrl(serviceProtocolUrl: parsedVmServiceUri);
}
Future<String> waitFor({required String message, Duration? timeout}) {
final response = Completer<String>();
late StreamSubscription<String> sub;
sub = stdoutController.stream.listen(
(String line) => _handleStdout(
line,
subscription: sub,
response: response,
message: message,
),
);
return _timeoutWithMessages<String>(
() => response.future,
timeout: timeout,
message: 'Did not receive expected message: $message.',
).whenComplete(() => sub.cancel());
}
void _handleStdout(
String line, {
required StreamSubscription<String> subscription,
required Completer<String> response,
required String message,
}) async {
if (message == vmServicePrefix && line.startsWith(vmServicePrefix)) {
final vmServiceUri = line
.substring(line.indexOf(vmServicePrefix) + vmServicePrefix.length);
await subscription.cancel();
response.complete(vmServiceUri);
}
}
}
abstract class IntegrationTestApp with IOMixin {
IntegrationTestApp(this.testAppPath, this.testAppDevice);
static const _appStartTimeout = Duration(seconds: 240);
static const _defaultTimeout = Duration(seconds: 40);
/// The path relative to the 'devtools_app' directory where the test app
/// lives.
///
/// This will either be a file path or a directory path depending on the type
/// of app.
final String testAppPath;
/// The device the test app should run on, e.g. flutter-tester, chrome.
final TestAppDevice testAppDevice;
late Process? runProcess;
int get runProcessId => runProcess!.pid;
final _allMessages = StreamController<String>.broadcast();
Uri get vmServiceUri => _vmServiceWsUri;
late Uri _vmServiceWsUri;
Future<void> startProcess();
Future<void> waitForAppStart();
Future<void> manuallyStopApp() async {}
Future<void> start() async {
_debugPrint('starting the test app process for $testAppPath');
await startProcess();
assert(
runProcess != null,
'\'runProcess\' cannot be null. Assign \'runProcess\' inside the '
'\'startProcess\' method.',
);
_debugPrint('process started (pid $runProcessId)');
// This class doesn't use the result of the future. It's made available
// via a getter for external uses.
unawaited(
runProcess!.exitCode.then((int code) {
_debugPrint('Process exited ($code)');
}),
);
listenToProcessOutput(runProcess!, printCallback: _debugPrint);
_debugPrint('waiting for app start...');
await waitForAppStart();
}
Future<int> stop({Future<int>? onTimeout}) async {
await manuallyStopApp();
_debugPrint('Waiting for process to end');
return runProcess!.exitCode.timeout(
IOMixin.killTimeout,
onTimeout: () => killGracefully(
runProcess!,
debugLogging: debugTestScript,
),
);
}
Future<T> _timeoutWithMessages<T>(
Future<T> Function() f, {
Duration? timeout,
String? message,
}) {
// Capture output to a buffer so if we don't get the response we want we can show
// the output that did arrive in the timeout error.
final messages = StringBuffer();
final start = DateTime.now();
void logMessage(String m) {
final int ms = DateTime.now().difference(start).inMilliseconds;
messages.writeln('[+ ${ms.toString().padLeft(5)}] $m');
}
final sub = _allMessages.stream.listen(logMessage);
return f().timeout(
timeout ?? _defaultTimeout,
onTimeout: () {
logMessage('<timed out>');
throw '$message';
},
).catchError((Object? error) {
throw '$error\nReceived:\n${messages.toString()}';
}).whenComplete(() => sub.cancel());
}
String _debugPrint(String msg) {
const maxLength = 500;
final truncatedMsg =
msg.length > maxLength ? '${msg.substring(0, maxLength)}...' : msg;
_allMessages.add(truncatedMsg);
debugLog('_TestApp - $truncatedMsg');
return msg;
}
}
/// Map the URI to a WebSocket URI for the VM service protocol.
///
/// If the URI is already a VM Service WebSocket URI it will not be modified.
Uri convertToWebSocketUrl({required Uri serviceProtocolUrl}) {
final isSecure = serviceProtocolUrl.isScheme('wss') ||
serviceProtocolUrl.isScheme('https');
final scheme = isSecure ? 'wss' : 'ws';
final path = serviceProtocolUrl.path.endsWith('/ws')
? serviceProtocolUrl.path
: (serviceProtocolUrl.path.endsWith('/')
? '${serviceProtocolUrl.path}ws'
: '${serviceProtocolUrl.path}/ws');
return serviceProtocolUrl.replace(scheme: scheme, path: path);
}
// TODO(kenz): consider moving these constants to devtools_shared if they are
// used outside of these integration tests. Optionally, we could consider making
// these constants where the flutter daemon is defined in flutter tools.
enum FlutterDaemonConstants {
event,
error,
id,
appId,
params,
trace,
wsUri,
pid,
appStop(nameOverride: 'app.stop'),
appStarted(nameOverride: 'app.started'),
appDebugPort(nameOverride: 'app.debugPort'),
daemonConnected(nameOverride: 'daemon.connected');
const FlutterDaemonConstants({String? nameOverride})
: _nameOverride = nameOverride;
final String? _nameOverride;
String get key => _nameOverride ?? name;
}
enum TestAppDevice {
flutterTester('flutter-tester'),
flutterChrome('chrome'),
cli('cli');
const TestAppDevice(this.argName);
final String argName;
/// A mapping of test app device to the unsupported tests for that device.
static final _unsupportedTestsForDevice = <TestAppDevice, List<String>>{
TestAppDevice.flutterTester: [],
TestAppDevice.flutterChrome: [
'eval_and_browse_test.dart',
// TODO(https://github.com/flutter/devtools/issues/7145): Figure out why
// this fails on bots but passes locally and enable.
'eval_and_inspect_test.dart',
'perfetto_test.dart',
'performance_screen_event_recording_test.dart',
'service_connection_test.dart',
],
TestAppDevice.cli: [
'debugger_panel_test.dart',
'eval_and_browse_test.dart',
'eval_and_inspect_test.dart',
'perfetto_test.dart',
'performance_screen_event_recording_test.dart',
'service_connection_test.dart',
],
};
static final _argNameToDeviceMap =
TestAppDevice.values.fold(<String, TestAppDevice>{}, (map, device) {
map[device.argName] = device;
return map;
});
static TestAppDevice? fromArgName(String argName) {
return _argNameToDeviceMap[argName];
}
bool supportsTest(String testPath) {
final unsupportedTests = _unsupportedTestsForDevice[this] ?? [];
return unsupportedTests
.none((unsupportedTestPath) => testPath.endsWith(unsupportedTestPath));
}
}
| devtools/packages/devtools_app/integration_test/test_infra/run/_test_app_driver.dart/0 | {
"file_path": "devtools/packages/devtools_app/integration_test/test_infra/run/_test_app_driver.dart",
"repo_id": "devtools",
"token_count": 5262
} | 81 |
// Copyright 2023 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_extensions/api.dart';
import 'package:devtools_shared/devtools_extensions.dart';
import 'package:flutter/material.dart';
import '../shared/analytics/analytics.dart' as ga;
import '../shared/analytics/constants.dart' as gac;
import '../shared/common_widgets.dart';
import '../shared/globals.dart';
import '../shared/screen.dart';
import 'embedded/controller.dart';
import 'embedded/view.dart';
import 'extension_screen_controls.dart';
class ExtensionScreen extends Screen {
ExtensionScreen(this.extensionConfig)
: super.conditional(
// TODO(kenz): we may need to ensure this is a unique id.
id: extensionConfig.screenId,
title: extensionConfig.name,
icon: extensionConfig.icon,
// TODO(kenz): support static DevTools extensions.
requiresConnection: true,
);
final DevToolsExtensionConfig extensionConfig;
@override
Widget buildScreenBody(BuildContext context) =>
_ExtensionScreenBody(extensionConfig: extensionConfig);
}
class _ExtensionScreenBody extends StatefulWidget {
const _ExtensionScreenBody({required this.extensionConfig});
final DevToolsExtensionConfig extensionConfig;
@override
State<_ExtensionScreenBody> createState() => _ExtensionScreenBodyState();
}
class _ExtensionScreenBodyState extends State<_ExtensionScreenBody> {
EmbeddedExtensionController? extensionController;
@override
void initState() {
super.initState();
_init();
}
void _init() {
ga.screen(
gac.DevToolsExtensionEvents.extensionScreenName(widget.extensionConfig),
);
extensionController =
createEmbeddedExtensionController(widget.extensionConfig)..init();
}
@override
void dispose() {
extensionController?.dispose();
super.dispose();
}
@override
void didUpdateWidget(_ExtensionScreenBody oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.extensionConfig != widget.extensionConfig) {
extensionController?.dispose();
_init();
}
}
@override
Widget build(BuildContext context) {
return ExtensionView(
controller: extensionController!,
extension: widget.extensionConfig,
);
}
}
class ExtensionView extends StatelessWidget {
const ExtensionView({
super.key,
required this.controller,
required this.extension,
});
final EmbeddedExtensionController controller;
final DevToolsExtensionConfig extension;
@override
Widget build(BuildContext context) {
return Column(
children: [
EmbeddedExtensionHeader(
extension: extension,
onForceReload: () =>
controller.postMessage(DevToolsExtensionEventType.forceReload),
),
const SizedBox(height: intermediateSpacing),
Expanded(
child: ValueListenableBuilder<ExtensionEnabledState>(
valueListenable: extensionService.enabledStateListenable(
extension.name,
),
builder: (context, activationState, _) {
if (activationState == ExtensionEnabledState.enabled) {
return KeepAliveWrapper(
child: Center(
child: EmbeddedExtensionView(controller: controller),
),
);
}
return EnableExtensionPrompt(
extension: controller.extensionConfig,
);
},
),
),
],
);
}
}
extension ExtensionConfigExtension on DevToolsExtensionConfig {
IconData get icon => IconData(
materialIconCodePoint,
fontFamily: 'MaterialIcons',
);
String get screenId => '${name}_ext';
}
| devtools/packages/devtools_app/lib/src/extensions/extension_screen.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/extensions/extension_screen.dart",
"repo_id": "devtools",
"token_count": 1466
} | 82 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app_shared/service.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:flutter/material.dart';
import 'package:vm_service/vm_service.dart';
import '../shared/analytics/constants.dart' as gac;
import '../shared/common_widgets.dart';
import '../shared/globals.dart';
import '../shared/primitives/utils.dart';
import '../shared/screen.dart';
import '../shared/ui/utils.dart';
import '../shared/utils.dart';
import 'scaffold.dart';
/// The status line widget displayed at the bottom of DevTools.
///
/// This displays information global to the application, as well as gives pages
/// a mechanism to display page-specific information.
class StatusLine extends StatelessWidget {
const StatusLine({
super.key,
required this.currentScreen,
required this.isEmbedded,
required this.isConnected,
});
final Screen currentScreen;
final bool isEmbedded;
final bool isConnected;
static const deviceInfoTooltip = 'Device Info';
/// The padding around the footer in the DevTools UI.
EdgeInsets get padding => const EdgeInsets.fromLTRB(
defaultSpacing,
densePadding,
defaultSpacing,
densePadding,
);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final color = isConnected ? theme.colorScheme.onPrimary : null;
final height = statusLineHeight + padding.top + padding.bottom;
return ValueListenableBuilder<bool>(
valueListenable: currentScreen.showIsolateSelector,
builder: (context, showIsolateSelector, _) {
return DefaultTextStyle.merge(
style: TextStyle(color: color),
child: Container(
decoration: BoxDecoration(
color: isConnected ? theme.colorScheme.primary : null,
border: Border(
top: Divider.createBorderSide(context, width: 1.0),
),
),
padding: EdgeInsets.only(left: padding.left, right: padding.right),
height: height,
alignment: Alignment.centerLeft,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: _getStatusItems(context, showIsolateSelector),
),
),
);
},
);
}
List<Widget> _getStatusItems(BuildContext context, bool showIsolateSelector) {
final theme = Theme.of(context);
final color = isConnected ? theme.colorScheme.onPrimary : null;
final screenWidth = ScreenSize(context).width;
final Widget? pageStatus = currentScreen.buildStatus(context);
final widerThanXxs = screenWidth > MediaSize.xxs;
final screenMetaData = ScreenMetaData.lookup(currentScreen.screenId);
final showVideoTutorial = screenMetaData?.tutorialVideoTimestamp != null;
return [
Row(
mainAxisSize: MainAxisSize.min,
children: [
DocumentationLink(
screen: currentScreen,
screenWidth: screenWidth,
isConnected: isConnected,
),
if (showVideoTutorial) ...[
BulletSpacer(color: color),
VideoTutorialLink(
screenMetaData: screenMetaData!,
screenWidth: screenWidth,
isConnected: isConnected,
),
],
],
),
BulletSpacer(color: color),
if (widerThanXxs && showIsolateSelector) ...[
const IsolateSelector(),
BulletSpacer(color: color),
],
if (screenWidth > MediaSize.xs && pageStatus != null) ...[
pageStatus,
BulletSpacer(color: color),
],
buildConnectionStatus(context, screenWidth),
if (widerThanXxs && isEmbedded) ...[
BulletSpacer(color: color),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: DevToolsScaffold.defaultActions(color: color),
),
],
];
}
Widget buildConnectionStatus(BuildContext context, MediaSize screenWidth) {
final theme = Theme.of(context);
const noConnectionMsg = 'No client connection';
return ValueListenableBuilder<ConnectedState>(
valueListenable: serviceConnection.serviceManager.connectedState,
builder: (context, connectedState, child) {
if (connectedState.connected) {
final app = serviceConnection.serviceManager.connectedApp!;
String description;
if (!app.isRunningOnDartVM!) {
description = 'web app';
} else {
final vm = serviceConnection.serviceManager.vm!;
description = vm.deviceDisplay;
}
final color = isConnected
? theme.colorScheme.onPrimary
: theme.regularTextStyle.color;
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ValueListenableBuilder(
valueListenable: serviceConnection.serviceManager.deviceBusy,
builder: (context, bool isBusy, _) {
return SizedBox(
width: smallProgressSize,
height: smallProgressSize,
child: isBusy
? SmallCircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color?>(color),
)
: const SizedBox(),
);
},
),
const SizedBox(width: denseSpacing),
DevToolsTooltip(
message: 'Connected device',
child: Text(
description,
style: isConnected
? theme.regularTextStyle
.copyWith(color: theme.colorScheme.onPrimary)
: theme.regularTextStyle,
overflow: TextOverflow.clip,
),
),
],
);
} else {
return child!;
}
},
child: screenWidth <= MediaSize.xxs
? DevToolsTooltip(
message: noConnectionMsg,
child: Icon(
Icons.warning_amber_rounded,
size: actionsIconSize,
),
)
: Text(
noConnectionMsg,
style: theme.regularTextStyle,
),
);
}
}
/// A widget that links to DevTools documentation on docs.flutter.dev for the
/// given [screen].
class DocumentationLink extends StatelessWidget {
const DocumentationLink({
super.key,
required this.screen,
required this.screenWidth,
required this.isConnected,
});
final Screen screen;
final MediaSize screenWidth;
final bool isConnected;
@override
Widget build(BuildContext context) {
final color = isConnected ? Theme.of(context).colorScheme.onPrimary : null;
final docPageId = screen.docPageId ?? '';
return LinkIconLabel(
icon: Icons.library_books_outlined,
link: Link(
display: screenWidth <= MediaSize.xs ? 'Docs' : 'Read docs',
url: screen.docsUrl ??
'https://docs.flutter.dev/tools/devtools/$docPageId',
gaScreenName: screen.screenId,
gaSelectedItemDescription: gac.documentationLink,
),
color: color,
);
}
}
/// A widget that links to the "Dive in to DevTools" YouTube video at the
/// chapter for the given [screenMetaData].
class VideoTutorialLink extends StatelessWidget {
const VideoTutorialLink({
super.key,
required this.screenMetaData,
required this.screenWidth,
required this.isConnected,
});
final ScreenMetaData screenMetaData;
final MediaSize screenWidth;
final bool isConnected;
static const _devToolsYouTubeVideoUrl = 'https://youtu.be/_EYk-E29edo';
@override
Widget build(BuildContext context) {
final color = isConnected ? Theme.of(context).colorScheme.onPrimary : null;
return LinkIconLabel(
icon: Icons.ondemand_video_rounded,
link: Link(
display: screenWidth <= MediaSize.xs ? 'Tutorial' : 'Watch tutorial',
url:
'$_devToolsYouTubeVideoUrl${screenMetaData.tutorialVideoTimestamp}',
gaScreenName: screenMetaData.id,
gaSelectedItemDescription:
'${gac.videoTutorialLink}-${screenMetaData.id}',
),
color: color,
);
}
}
class IsolateSelector extends StatelessWidget {
const IsolateSelector({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final IsolateManager isolateManager =
serviceConnection.serviceManager.isolateManager;
return MultiValueListenableBuilder(
listenables: [
isolateManager.isolates,
isolateManager.selectedIsolate,
],
builder: (context, values, _) {
final theme = Theme.of(context);
final isolates = values.first as List<IsolateRef>;
final selectedIsolateRef = values.second as IsolateRef?;
return PopupMenuButton<IsolateRef?>(
tooltip: 'Selected Isolate',
initialValue: selectedIsolateRef,
onSelected: isolateManager.selectIsolate,
itemBuilder: (BuildContext context) => isolates.map(
(ref) {
return PopupMenuItem<IsolateRef>(
value: ref,
child: IsolateOption(
ref,
color: theme.colorScheme.onSurface,
),
);
},
).toList(),
child: IsolateOption(
isolateManager.selectedIsolate.value,
color: theme.colorScheme.onPrimary,
),
);
},
);
}
}
class IsolateOption extends StatelessWidget {
const IsolateOption(
this.ref, {
required this.color,
super.key,
});
final IsolateRef? ref;
final Color color;
@override
Widget build(BuildContext context) {
return Row(
children: [
Icon(
ref?.isSystemIsolate ?? false
? Icons.settings_applications
: Icons.call_split,
color: color,
),
const SizedBox(width: denseSpacing),
Text(
ref == null ? 'isolate' : _isolateName(ref!),
style: Theme.of(context).regularTextStyle.copyWith(color: color),
),
],
);
}
String _isolateName(IsolateRef ref) {
final name = ref.name;
return '$name #${serviceConnection.serviceManager.isolateManager.isolateIndex(ref)}';
}
}
| devtools/packages/devtools_app/lib/src/framework/status_line.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/framework/status_line.dart",
"repo_id": "devtools",
"token_count": 4610
} | 83 |
// 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/material.dart';
import 'package:flutter/services.dart';
import '../../shared/config_specific/host_platform/host_platform.dart';
import '../../shared/primitives/utils.dart';
final LogicalKeySet goToLineNumberKeySet = LogicalKeySet(
HostPlatform.instance.isMacOS
? LogicalKeyboardKey.meta
: LogicalKeyboardKey.control,
LogicalKeyboardKey.keyG,
);
final String goToLineNumberKeySetDescription =
goToLineNumberKeySet.describeKeys(isMacOS: HostPlatform.instance.isMacOS);
final LogicalKeySet searchInFileKeySet = LogicalKeySet(
HostPlatform.instance.isMacOS
? LogicalKeyboardKey.meta
: LogicalKeyboardKey.control,
LogicalKeyboardKey.keyF,
);
final LogicalKeySet escapeKeySet = LogicalKeySet(
LogicalKeyboardKey.escape,
);
final LogicalKeySet openFileKeySet = LogicalKeySet(
HostPlatform.instance.isMacOS
? LogicalKeyboardKey.meta
: LogicalKeyboardKey.control,
LogicalKeyboardKey.keyP,
);
final String openFileKeySetDescription =
openFileKeySet.describeKeys(isMacOS: HostPlatform.instance.isMacOS);
| devtools/packages/devtools_app/lib/src/screens/debugger/key_sets.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/debugger/key_sets.dart",
"repo_id": "devtools",
"token_count": 420
} | 84 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import '../../shared/diagnostics/diagnostics_node.dart';
import '../../shared/primitives/enum_utils.dart';
import '../../shared/primitives/math_utils.dart';
import '../../shared/primitives/utils.dart';
import 'layout_explorer/flex/utils.dart';
const overflowEpsilon = 0.1;
/// Compute real widget sizes into rendered sizes to be displayed on the details tab.
/// The sum of the resulting render sizes may or may not be greater than the [maxSizeAvailable]
/// In the case where it is greater, we should render it with scrolling capability.
///
/// Variables:
/// - [sizes] : real size for widgets that want to be rendered / scaled
/// - [smallestSize] : the smallest element in the array [sizes]
/// - [largestSize] : the largest element in the array [sizes]
/// - [smallestRenderSize] : render size for smallest element
/// - [largestRenderSize] : render size for largest element
/// - [maxSizeAvailable] : maximum size available for rendering the widget
/// - [useMaxSizeAvailable] : flag for forcing the widget dimension to be at least [maxSizeAvailable]
///
/// if [useMaxSizeAvailable] is set to true,
/// this method will ignore the largestRenderSize
/// and compute its own largestRenderSize to force
/// the sum of the render size to be equals to [maxSizeAvailable]
///
/// Formula for computing render size:
/// renderSize[i] = (size[i] - smallestSize)
/// * (largestRenderSize - smallestRenderSize)
/// / (largestSize - smallestSize) + smallestRenderSize
/// Explanation:
/// - The computation formula for transforming size to renderSize is based on these two things:
/// - smallest element will be rendered to [smallestRenderSize]
/// - largest element will be rendered to [largestRenderSize]
/// - any other size will be scaled accordingly
/// - The formula above is derived from:
/// (renderSize[i] - smallestRenderSize) / (largestRenderSize - smallestRenderSize)
/// = (size[i] - smallestSize) / (size[i] - smallestSize)
///
/// Formula for computing forced [largestRenderSize]:
/// largestRenderSize = (maxSizeAvailable - sizes.length * smallestRenderSize)
/// * (largestSize - smallestSize) / sum(s[i] - ss) + smallestRenderSize
/// Explanation:
/// - This formula is derived from the equation:
/// sum(renderSize) = maxSizeAvailable
///
List<double> computeRenderSizes({
required Iterable<double> sizes,
required double smallestSize,
required double largestSize,
required double smallestRenderSize,
required double largestRenderSize,
required double maxSizeAvailable,
bool useMaxSizeAvailable = true,
}) {
final n = sizes.length;
if (smallestSize == largestSize) {
// It means that all widget have the same size
// and we can just divide the size evenly
// but it should be at least as big as [smallestRenderSize]
final renderSize = math.max(smallestRenderSize, maxSizeAvailable / n);
return [for (var _ in sizes) renderSize];
}
List<double> transformToRenderSize(double largestRenderSize) => [
for (var s in sizes)
(s - smallestSize) *
(largestRenderSize - smallestRenderSize) /
(largestSize - smallestSize) +
smallestRenderSize,
];
var renderSizes = transformToRenderSize(largestRenderSize);
if (useMaxSizeAvailable && sum(renderSizes) < maxSizeAvailable) {
largestRenderSize = (maxSizeAvailable - n * smallestRenderSize) *
(largestSize - smallestSize) /
sum([for (var s in sizes) s - smallestSize]) +
smallestRenderSize;
renderSizes = transformToRenderSize(largestRenderSize);
}
return renderSizes;
}
// TODO(albertusangga): Move this to [RemoteDiagnosticsNode] once dart:html app is removed
/// Represents parsed layout information for a specific [RemoteDiagnosticsNode].
class LayoutProperties {
LayoutProperties(this.node, {int copyLevel = 1})
: description = node.description,
size = node.size,
constraints = node.constraints,
isFlex = node.isFlex,
flexFactor = node.flexFactor,
flexFit = node.flexFit,
children = copyLevel == 0
? []
: node.childrenNow
.map(
(child) => LayoutProperties(child, copyLevel: copyLevel - 1),
)
.toList(growable: false) {
for (var child in children) {
child.parent = this;
}
}
LayoutProperties.values({
required this.node,
required this.children,
required this.constraints,
required this.description,
required this.flexFactor,
required this.isFlex,
required this.size,
required this.flexFit,
}) {
for (var child in children) {
child.parent = this;
}
}
LayoutProperties? parent;
final RemoteDiagnosticsNode node;
final List<LayoutProperties> children;
final BoxConstraints? constraints;
final String? description;
final num? flexFactor;
final FlexFit? flexFit;
final bool isFlex;
final Size size;
/// Represents the order of [children] to be displayed.
List<LayoutProperties> get displayChildren => children;
bool get hasFlexFactor {
final flexFactorLocal = flexFactor;
if (flexFactorLocal == null) return false;
return flexFactorLocal > 0;
}
int get totalChildren => children.length;
bool get hasChildren => children.isNotEmpty;
double get width => size.width;
double get height => size.height;
double dimension(Axis axis) => axis == Axis.horizontal ? width : height;
List<double> childrenDimensions(Axis axis) {
return displayChildren.map((child) => child.dimension(axis)).toList();
}
List<double> get childrenWidths => childrenDimensions(Axis.horizontal);
List<double> get childrenHeights => childrenDimensions(Axis.vertical);
String describeWidthConstraints() {
final constraintsLocal = constraints;
if (constraintsLocal == null) return '';
return constraintsLocal.hasBoundedWidth
? describeAxis(
constraintsLocal.minWidth,
constraintsLocal.maxWidth,
'w',
)
: 'width is unconstrained';
}
String describeHeightConstraints() {
final constraintsLocal = constraints;
if (constraintsLocal == null) return '';
return constraintsLocal.hasBoundedHeight
? describeAxis(
constraintsLocal.minHeight,
constraintsLocal.maxHeight,
'h',
)
: 'height is unconstrained';
}
String describeWidth() => 'w=${toStringAsFixed(size.width)}';
String describeHeight() => 'h=${toStringAsFixed(size.height)}';
bool get isOverflowWidth {
final parentWidth = parent?.width;
if (parentWidth == null) return false;
final parentData = node.parentData;
double widthUsed = width;
widthUsed += parentData.offset.dx;
// TODO(jacobr): certain widgets may allow overflow so this may false
// positive a bit for cases like Stack.
return widthUsed > parentWidth + overflowEpsilon;
}
bool get isOverflowHeight {
final parentHeight = parent?.height;
if (parentHeight == null) return false;
final parentData = node.parentData;
double heightUsed = height;
heightUsed += parentData.offset.dy;
return heightUsed > parentHeight + overflowEpsilon;
}
static String describeAxis(double min, double max, String axis) {
if (min == max) return '$axis=${min.toStringAsFixed(1)}';
return '${min.toStringAsFixed(1)}<=$axis<=${max.toStringAsFixed(1)}';
}
LayoutProperties copyWith({
List<LayoutProperties>? children,
BoxConstraints? constraints,
String? description,
int? flexFactor,
FlexFit? flexFit,
bool? isFlex,
Size? size,
}) {
return LayoutProperties.values(
node: node,
children: children ?? this.children,
constraints: constraints ?? this.constraints,
description: description ?? this.description,
flexFactor: flexFactor ?? this.flexFactor,
isFlex: isFlex ?? this.isFlex,
size: size ?? this.size,
flexFit: flexFit ?? this.flexFit,
);
}
}
/// Enum object to represent which side of the widget is overflowing.
///
/// See also:
/// * [OverflowIndicatorPainter]
enum OverflowSide {
right,
bottom,
}
// TODO(jacobr): is it possible to overflow on multiple sides?
// TODO(jacobr): do we need to worry about overflowing on the left side in RTL
// layouts? We need to audit the Flutter semantics for determining overflow to
// make sure we are consistent.
extension LayoutPropertiesExtension on LayoutProperties {
OverflowSide? get overflowSide {
if (isOverflowWidth) return OverflowSide.right;
if (isOverflowHeight) return OverflowSide.bottom;
return null;
}
}
final Expando<FlexLayoutProperties> _flexLayoutExpando = Expando();
extension MainAxisAlignmentExtension on MainAxisAlignment {
MainAxisAlignment get reversed {
switch (this) {
case MainAxisAlignment.start:
return MainAxisAlignment.end;
case MainAxisAlignment.end:
return MainAxisAlignment.start;
default:
return this;
}
}
}
/// TODO(albertusangga): Move this to [RemoteDiagnosticsNode] once dart:html app is removed.
class FlexLayoutProperties extends LayoutProperties {
FlexLayoutProperties({
required Size size,
required List<LayoutProperties> children,
required RemoteDiagnosticsNode node,
BoxConstraints? constraints,
bool isFlex = false,
String? description,
num? flexFactor,
FlexFit? flexFit,
this.direction = Axis.vertical,
this.mainAxisAlignment,
this.crossAxisAlignment,
this.mainAxisSize,
required this.textDirection,
required this.verticalDirection,
this.textBaseline,
}) : super.values(
size: size,
children: children,
node: node,
constraints: constraints,
isFlex: isFlex,
description: description,
flexFactor: flexFactor,
flexFit: flexFit,
);
FlexLayoutProperties._fromNode(
RemoteDiagnosticsNode node, {
this.direction = Axis.vertical,
this.mainAxisAlignment,
this.mainAxisSize,
this.crossAxisAlignment,
required this.textDirection,
required this.verticalDirection,
this.textBaseline,
}) : super(node);
factory FlexLayoutProperties.fromDiagnostics(RemoteDiagnosticsNode node) {
// Cache the properties on an expando so that local tweaks to
// FlexLayoutProperties persist across multiple lookups from an
// RemoteDiagnosticsNode.
return _flexLayoutExpando[node] ??= _buildNode(node);
}
@override
FlexLayoutProperties copyWith({
Size? size,
List<LayoutProperties>? children,
BoxConstraints? constraints,
bool? isFlex,
String? description,
num? flexFactor,
FlexFit? flexFit,
Axis? direction,
MainAxisAlignment? mainAxisAlignment,
MainAxisSize? mainAxisSize,
CrossAxisAlignment? crossAxisAlignment,
TextDirection? textDirection,
VerticalDirection? verticalDirection,
TextBaseline? textBaseline,
}) {
return FlexLayoutProperties(
size: size ?? this.size,
children: children ?? this.children,
node: node,
constraints: constraints ?? this.constraints,
isFlex: isFlex ?? this.isFlex,
description: description ?? this.description,
flexFactor: flexFactor ?? this.flexFactor,
flexFit: flexFit ?? this.flexFit,
direction: direction ?? this.direction,
mainAxisAlignment: mainAxisAlignment ?? this.mainAxisAlignment,
mainAxisSize: mainAxisSize ?? this.mainAxisSize,
crossAxisAlignment: crossAxisAlignment ?? this.crossAxisAlignment,
textDirection: textDirection ?? this.textDirection,
verticalDirection: verticalDirection ?? this.verticalDirection,
textBaseline: textBaseline ?? this.textBaseline,
);
}
static FlexLayoutProperties _buildNode(RemoteDiagnosticsNode node) {
final Map<String, Object?> renderObjectJson = node.renderObject!.json;
final properties = (renderObjectJson['properties'] as List<Object?>)
.cast<Map<String, Object?>>();
final data = {
for (final property in properties)
property['name']: property['description'] as String?,
};
return FlexLayoutProperties._fromNode(
node,
direction: _directionUtils.enumEntry(data['direction']) ?? Axis.vertical,
mainAxisAlignment:
_mainAxisAlignmentUtils.enumEntry(data['mainAxisAlignment']),
mainAxisSize: _mainAxisSizeUtils.enumEntry(data['mainAxisSize']),
crossAxisAlignment:
_crossAxisAlignmentUtils.enumEntry(data['crossAxisAlignment']),
textDirection: _textDirectionUtils.enumEntry(data['textDirection']) ??
TextDirection.ltr,
verticalDirection:
_verticalDirectionUtils.enumEntry(data['verticalDirection']) ??
VerticalDirection.down,
textBaseline: _textBaselineUtils.enumEntry(data['textBaseline']),
);
}
final Axis direction;
final MainAxisAlignment? mainAxisAlignment;
final CrossAxisAlignment? crossAxisAlignment;
final MainAxisSize? mainAxisSize;
final TextDirection textDirection;
final VerticalDirection verticalDirection;
final TextBaseline? textBaseline;
List<LayoutProperties>? _displayChildren;
@override
List<LayoutProperties> get displayChildren {
final displayChildren = _displayChildren;
if (displayChildren != null) return displayChildren;
return _displayChildren =
startIsTopLeft ? children : children.reversed.toList();
}
int? _totalFlex;
bool get isMainAxisHorizontal => direction == Axis.horizontal;
bool get isMainAxisVertical => direction == Axis.vertical;
String get horizontalDirectionDescription {
return direction == Axis.horizontal ? 'Main Axis' : 'Cross Axis';
}
String get verticalDirectionDescription {
return direction == Axis.vertical ? 'Main Axis' : 'Cross Axis';
}
String get type => direction.flexType;
num get totalFlex {
if (children.isEmpty) return 0;
_totalFlex ??= children
.map((child) => child.flexFactor ?? 0)
.reduce((value, element) => value + element)
.toInt();
return _totalFlex!;
}
Axis get crossAxisDirection {
return direction == Axis.horizontal ? Axis.vertical : Axis.horizontal;
}
double get mainAxisDimension => dimension(direction);
double get crossAxisDimension => dimension(crossAxisDirection);
@override
bool get isOverflowWidth {
if (direction == Axis.horizontal) {
return width + overflowEpsilon < sum(childrenWidths);
}
return width + overflowEpsilon < max(childrenWidths);
}
@override
bool get isOverflowHeight {
if (direction == Axis.vertical) {
return height + overflowEpsilon < sum(childrenHeights);
}
return height + overflowEpsilon < max(childrenHeights);
}
bool get startIsTopLeft {
switch (direction) {
case Axis.horizontal:
switch (textDirection) {
case TextDirection.ltr:
return true;
case TextDirection.rtl:
return false;
}
case Axis.vertical:
switch (verticalDirection) {
case VerticalDirection.down:
return true;
case VerticalDirection.up:
return false;
}
}
}
/// render properties for laying out rendered Flex & Flex children widgets
/// the computation is similar to [RenderFlex].performLayout() method
List<RenderProperties> childrenRenderProperties({
required double smallestRenderWidth,
required double largestRenderWidth,
required double smallestRenderHeight,
required double largestRenderHeight,
required double Function(Axis) maxSizeAvailable,
}) {
/// calculate the render empty spaces
final freeSpace = dimension(direction) - sum(childrenDimensions(direction));
final displayMainAxisAlignment =
startIsTopLeft ? mainAxisAlignment : mainAxisAlignment?.reversed;
double leadingSpace(double freeSpace) {
if (children.isEmpty) return 0.0;
switch (displayMainAxisAlignment) {
case MainAxisAlignment.start:
case MainAxisAlignment.end:
return freeSpace;
case MainAxisAlignment.center:
return freeSpace * 0.5;
case MainAxisAlignment.spaceBetween:
return 0.0;
case MainAxisAlignment.spaceAround:
final spaceBetweenChildren = freeSpace / children.length;
return spaceBetweenChildren * 0.5;
case MainAxisAlignment.spaceEvenly:
return freeSpace / (children.length + 1);
default:
return 0.0;
}
}
double betweenSpace(double freeSpace) {
if (children.isEmpty) return 0.0;
switch (displayMainAxisAlignment) {
case MainAxisAlignment.start:
case MainAxisAlignment.end:
case MainAxisAlignment.center:
return 0.0;
case MainAxisAlignment.spaceBetween:
if (children.length == 1) return freeSpace;
return freeSpace / (children.length - 1);
case MainAxisAlignment.spaceAround:
return freeSpace / children.length;
case MainAxisAlignment.spaceEvenly:
return freeSpace / (children.length + 1);
default:
return 0.0;
}
}
double smallestRenderSize(Axis axis) {
return axis == Axis.horizontal
? smallestRenderWidth
: smallestRenderHeight;
}
double largestRenderSize(Axis axis) {
final lrs =
axis == Axis.horizontal ? largestRenderWidth : largestRenderHeight;
// use all the space when visualizing cross axis
return (axis == direction) ? lrs : maxSizeAvailable(axis);
}
List<double> renderSizes(Axis axis) {
final sizes = childrenDimensions(axis);
if (freeSpace > 0.0 && axis == direction) {
/// include free space in the computation
sizes.add(freeSpace);
}
final smallestSize = min(sizes);
final largestSize = max(sizes);
if (axis == direction ||
(crossAxisAlignment != CrossAxisAlignment.stretch &&
smallestSize != largestSize)) {
return computeRenderSizes(
sizes: sizes,
smallestSize: smallestSize,
largestSize: largestSize,
smallestRenderSize: smallestRenderSize(axis),
largestRenderSize: largestRenderSize(axis),
maxSizeAvailable: maxSizeAvailable(axis),
);
} else {
// uniform cross axis sizes.
double size = crossAxisAlignment == CrossAxisAlignment.stretch
? maxSizeAvailable(axis)
: largestSize /
math.max(dimension(axis), 1.0) *
maxSizeAvailable(axis);
size = math.max(size, smallestRenderSize(axis));
return sizes.map((_) => size).toList();
}
}
final widths = renderSizes(Axis.horizontal);
final heights = renderSizes(Axis.vertical);
final renderFreeSpace = freeSpace > 0.0
? (isMainAxisHorizontal ? widths.last : heights.last)
: 0.0;
final renderLeadingSpace = leadingSpace(renderFreeSpace);
final renderBetweenSpace = betweenSpace(renderFreeSpace);
final childrenRenderProps = <RenderProperties>[];
double lastMainAxisOffset() {
if (childrenRenderProps.isEmpty) return 0.0;
return childrenRenderProps.last.mainAxisOffset;
}
double lastMainAxisDimension() {
if (childrenRenderProps.isEmpty) return 0.0;
return childrenRenderProps.last.mainAxisDimension;
}
double space(int index) {
if (index == 0) {
if (displayMainAxisAlignment == MainAxisAlignment.start) return 0.0;
return renderLeadingSpace;
}
return renderBetweenSpace;
}
double calculateMainAxisOffset(int i) {
return lastMainAxisOffset() + lastMainAxisDimension() + space(i);
}
double calculateCrossAxisOffset(int i) {
final maxDimension = maxSizeAvailable(crossAxisDirection);
final usedDimension =
crossAxisDirection == Axis.horizontal ? widths[i] : heights[i];
if (crossAxisAlignment == CrossAxisAlignment.start ||
crossAxisAlignment == CrossAxisAlignment.stretch ||
maxDimension == usedDimension) return 0.0;
final emptySpace = math.max(0.0, maxDimension - usedDimension);
if (crossAxisAlignment == CrossAxisAlignment.end) return emptySpace;
return emptySpace * 0.5;
}
for (var i = 0; i < children.length; ++i) {
childrenRenderProps.add(
RenderProperties(
axis: direction,
size: Size(widths[i], heights[i]),
offset: Offset.zero,
realSize: displayChildren[i].size,
)
..mainAxisOffset = calculateMainAxisOffset(i)
..crossAxisOffset = calculateCrossAxisOffset(i)
..layoutProperties = displayChildren[i],
);
}
final spaces = <RenderProperties>[];
final actualLeadingSpace = leadingSpace(freeSpace);
final actualBetweenSpace = betweenSpace(freeSpace);
final renderPropsWithFullCrossAxisDimension =
RenderProperties(axis: direction)
..crossAxisDimension = maxSizeAvailable(crossAxisDirection)
..crossAxisRealDimension = dimension(crossAxisDirection)
..crossAxisOffset = 0.0
..isFreeSpace = true
..layoutProperties = this;
if (actualLeadingSpace > 0.0 &&
displayMainAxisAlignment != MainAxisAlignment.start) {
spaces.add(
renderPropsWithFullCrossAxisDimension.clone()
..mainAxisOffset = 0.0
..mainAxisDimension = renderLeadingSpace
..mainAxisRealDimension = actualLeadingSpace,
);
}
if (actualBetweenSpace > 0.0) {
for (var i = 0; i < childrenRenderProps.length - 1; ++i) {
final child = childrenRenderProps[i];
spaces.add(
renderPropsWithFullCrossAxisDimension.clone()
..mainAxisDimension = renderBetweenSpace
..mainAxisRealDimension = actualBetweenSpace
..mainAxisOffset = child.mainAxisOffset + child.mainAxisDimension,
);
}
}
if (actualLeadingSpace > 0.0 &&
displayMainAxisAlignment != MainAxisAlignment.end) {
spaces.add(
renderPropsWithFullCrossAxisDimension.clone()
..mainAxisOffset = childrenRenderProps.last.mainAxisDimension +
childrenRenderProps.last.mainAxisOffset
..mainAxisDimension = renderLeadingSpace
..mainAxisRealDimension = actualLeadingSpace,
);
}
return [...childrenRenderProps, ...spaces];
}
List<RenderProperties> crossAxisSpaces({
required List<RenderProperties> childrenRenderProperties,
required double Function(Axis) maxSizeAvailable,
}) {
if (crossAxisAlignment == CrossAxisAlignment.stretch) return [];
final spaces = <RenderProperties>[];
for (var i = 0; i < children.length; ++i) {
if (dimension(crossAxisDirection) ==
displayChildren[i].dimension(crossAxisDirection) ||
childrenRenderProperties[i].crossAxisDimension ==
maxSizeAvailable(crossAxisDirection)) continue;
final renderProperties = childrenRenderProperties[i];
final space = renderProperties.clone()..isFreeSpace = true;
space.crossAxisRealDimension =
crossAxisDimension - space.crossAxisRealDimension;
space.crossAxisDimension =
maxSizeAvailable(crossAxisDirection) - space.crossAxisDimension;
if (space.crossAxisDimension <= 0.0) continue;
if (crossAxisAlignment == CrossAxisAlignment.center) {
space.crossAxisDimension *= 0.5;
final crossAxisRealDimension = space.crossAxisRealDimension;
space.crossAxisRealDimension = crossAxisRealDimension * 0.5;
spaces.add(space.clone()..crossAxisOffset = 0.0);
spaces.add(
space.clone()
..crossAxisOffset = renderProperties.crossAxisDimension +
renderProperties.crossAxisOffset,
);
} else {
space.crossAxisOffset = crossAxisAlignment == CrossAxisAlignment.end
? 0
: renderProperties.crossAxisDimension;
spaces.add(space);
}
}
return spaces;
}
static final _directionUtils = EnumUtils<Axis>(Axis.values);
static final _mainAxisAlignmentUtils =
EnumUtils<MainAxisAlignment>(MainAxisAlignment.values);
static final _mainAxisSizeUtils =
EnumUtils<MainAxisSize>(MainAxisSize.values);
static final _crossAxisAlignmentUtils =
EnumUtils<CrossAxisAlignment>(CrossAxisAlignment.values);
static final _textDirectionUtils =
EnumUtils<TextDirection>(TextDirection.values);
static final _verticalDirectionUtils =
EnumUtils<VerticalDirection>(VerticalDirection.values);
static final _textBaselineUtils =
EnumUtils<TextBaseline>(TextBaseline.values);
}
/// RenderProperties contains information for rendering a [LayoutProperties] node
class RenderProperties {
RenderProperties({
required this.axis,
Size? size,
Offset? offset,
Size? realSize,
this.layoutProperties,
this.isFreeSpace = false,
}) : width = size?.width ?? 0.0,
height = size?.height ?? 0.0,
realWidth = realSize?.width ?? 0.0,
realHeight = realSize?.height ?? 0.0,
dx = offset?.dx ?? 0.0,
dy = offset?.dy ?? 0.0;
final Axis axis;
/// represents which node is rendered for this object.
LayoutProperties? layoutProperties;
double dx, dy;
double width, height;
double realWidth, realHeight;
bool isFreeSpace;
Size get size => Size(width, height);
Size get realSize => Size(realWidth, realHeight);
Offset get offset => Offset(dx, dy);
double get mainAxisDimension => axis == Axis.horizontal ? width : height;
set mainAxisDimension(double dim) {
if (axis == Axis.horizontal) {
width = dim;
} else {
height = dim;
}
}
double get crossAxisDimension => axis == Axis.horizontal ? height : width;
set crossAxisDimension(double dim) {
if (axis == Axis.horizontal) {
height = dim;
} else {
width = dim;
}
}
double get mainAxisOffset => axis == Axis.horizontal ? dx : dy;
set mainAxisOffset(double offset) {
if (axis == Axis.horizontal) {
dx = offset;
} else {
dy = offset;
}
}
double get crossAxisOffset => axis == Axis.horizontal ? dy : dx;
set crossAxisOffset(double offset) {
if (axis == Axis.horizontal) {
dy = offset;
} else {
dx = offset;
}
}
double get mainAxisRealDimension =>
axis == Axis.horizontal ? realWidth : realHeight;
set mainAxisRealDimension(double newVal) {
if (axis == Axis.horizontal) {
realWidth = newVal;
} else {
realHeight = newVal;
}
}
double get crossAxisRealDimension =>
axis == Axis.horizontal ? realHeight : realWidth;
set crossAxisRealDimension(double newVal) {
if (axis == Axis.horizontal) {
realHeight = newVal;
} else {
realWidth = newVal;
}
}
RenderProperties clone() {
return RenderProperties(
axis: axis,
size: size,
offset: offset,
realSize: realSize,
layoutProperties: layoutProperties,
isFreeSpace: isFreeSpace,
);
}
@override
int get hashCode =>
axis.hashCode ^
size.hashCode ^
offset.hashCode ^
realSize.hashCode ^
isFreeSpace.hashCode;
@override
bool operator ==(Object other) {
return other is RenderProperties &&
axis == other.axis &&
size.closeTo(other.size) &&
offset.closeTo(other.offset) &&
realSize.closeTo(other.realSize) &&
isFreeSpace == other.isFreeSpace;
}
@override
String toString() {
return '{ axis: $axis, size: $size, offset: $offset, realSize: $realSize, isFreeSpace: $isFreeSpace }';
}
}
bool _closeTo(double a, double b, {int precision = 1}) {
return a.toStringAsPrecision(precision) == b.toStringAsPrecision(precision);
}
extension on Size {
bool closeTo(Size other) {
return _closeTo(width, other.width) && _closeTo(height, other.height);
}
}
extension on Offset {
bool closeTo(Offset other) {
return _closeTo(dx, other.dx) && _closeTo(dy, other.dy);
}
}
| devtools/packages/devtools_app/lib/src/screens/inspector/inspector_data_models.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/inspector_data_models.dart",
"repo_id": "devtools",
"token_count": 10565
} | 85 |
// 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/material.dart';
class WidgetTheme {
const WidgetTheme({
this.iconAsset,
this.color = otherWidgetColor,
});
final String? iconAsset;
final Color color;
static WidgetTheme fromName(String? widgetType) {
if (widgetType == null) {
return const WidgetTheme();
}
return themeMap[_stripBrackets(widgetType)] ?? const WidgetTheme();
}
/// Strips the brackets off the widget name.
///
/// For example: `AnimatedBuilder<String>` -> `AnimatedBuilder`.
static String _stripBrackets(String widgetType) {
final bracketIndex = widgetType.indexOf('<');
if (bracketIndex == -1) {
return widgetType;
}
return widgetType.substring(0, bracketIndex);
}
static const contentWidgetColor = Color(0xff06AC3B);
static const highLevelWidgetColor = Color(0xffAEAEB1);
static const animationWidgetColor = Color(0xffE09D0E);
static const otherWidgetColor = Color(0xff0EA7E0);
static const animatedTheme = WidgetTheme(
iconAsset: WidgetIcons.animated,
color: animationWidgetColor,
);
static const transitionTheme = WidgetTheme(
iconAsset: WidgetIcons.transition,
color: animationWidgetColor,
);
static const textTheme = WidgetTheme(
iconAsset: WidgetIcons.text,
color: contentWidgetColor,
);
static const imageTheme = WidgetTheme(
iconAsset: WidgetIcons.image,
color: contentWidgetColor,
);
static const tabTheme = WidgetTheme(iconAsset: WidgetIcons.tab);
static const scrollTheme = WidgetTheme(iconAsset: WidgetIcons.scroll);
static const highLevelTheme = WidgetTheme(color: highLevelWidgetColor);
static const listTheme = WidgetTheme(iconAsset: WidgetIcons.listView);
static const expandTheme = WidgetTheme(iconAsset: WidgetIcons.expand);
static const alignTheme = WidgetTheme(iconAsset: WidgetIcons.align);
static const gestureTheme = WidgetTheme(iconAsset: WidgetIcons.gesture);
static const textButtonTheme = WidgetTheme(iconAsset: WidgetIcons.textButton);
static const toggleTheme = WidgetTheme(
iconAsset: WidgetIcons.toggle,
color: contentWidgetColor,
);
static const Map<String, WidgetTheme> themeMap = {
// High-level
'RenderObjectToWidgetAdapter': WidgetTheme(
iconAsset: WidgetIcons.root,
color: highLevelWidgetColor,
),
'CupertinoApp': highLevelTheme,
'MaterialApp': WidgetTheme(iconAsset: WidgetIcons.materialApp),
'WidgetsApp': highLevelTheme,
// Text
'DefaultTextStyle': textTheme,
'RichText': textTheme,
'SelectableText': textTheme,
'Text': textTheme,
// Images
'Icon': imageTheme,
'Image': imageTheme,
'RawImage': imageTheme,
// Animations
'AnimatedAlign': animatedTheme,
'AnimatedBuilder': animatedTheme,
'AnimatedContainer': animatedTheme,
'AnimatedCrossFade': animatedTheme,
'AnimatedDefaultTextStyle': animatedTheme,
'AnimatedListState': animatedTheme,
'AnimatedModalBarrier': animatedTheme,
'AnimatedOpacity': animatedTheme,
'AnimatedPhysicalModel': animatedTheme,
'AnimatedPositioned': animatedTheme,
'AnimatedSize': animatedTheme,
'AnimatedWidget': animatedTheme,
// Transitions
'DecoratedBoxTransition': transitionTheme,
'FadeTransition': transitionTheme,
'PositionedTransition': transitionTheme,
'RotationTransition': transitionTheme,
'ScaleTransition': transitionTheme,
'SizeTransition': transitionTheme,
'SlideTransition': transitionTheme,
'Hero': WidgetTheme(
iconAsset: WidgetIcons.hero,
color: animationWidgetColor,
),
// Scroll
'CustomScrollView': scrollTheme,
'DraggableScrollableSheet': scrollTheme,
'SingleChildScrollView': scrollTheme,
'Scrollable': scrollTheme,
'Scrollbar': scrollTheme,
'ScrollConfiguration': scrollTheme,
'GridView': WidgetTheme(iconAsset: WidgetIcons.gridView),
'ListView': listTheme,
'ReorderableListView': listTheme,
'NestedScrollView': listTheme,
// Input
'Checkbox': WidgetTheme(
iconAsset: WidgetIcons.checkbox,
color: contentWidgetColor,
),
'Radio': WidgetTheme(
iconAsset: WidgetIcons.radio,
color: contentWidgetColor,
),
'Switch': toggleTheme,
'CupertinoSwitch': toggleTheme,
// Layout
'Container': WidgetTheme(iconAsset: WidgetIcons.container),
'Center': WidgetTheme(iconAsset: WidgetIcons.center),
'Row': WidgetTheme(iconAsset: WidgetIcons.row),
'Column': WidgetTheme(iconAsset: WidgetIcons.column),
'Padding': WidgetTheme(iconAsset: WidgetIcons.padding),
'SizedBox': WidgetTheme(iconAsset: WidgetIcons.sizedBox),
'ConstrainedBox': WidgetTheme(iconAsset: WidgetIcons.constrainedBox),
'Align': alignTheme,
'Positioned': alignTheme,
'Expanded': expandTheme,
'Flexible': expandTheme,
'Stack': WidgetTheme(iconAsset: WidgetIcons.stack),
'Wrap': WidgetTheme(iconAsset: WidgetIcons.wrap),
// Buttons
'FloatingActionButton': WidgetTheme(
iconAsset: WidgetIcons.floatingActionButton,
color: contentWidgetColor,
),
'InkWell': WidgetTheme(iconAsset: WidgetIcons.inkWell),
'GestureDetector': gestureTheme,
'RawGestureDetector': gestureTheme,
'TextButton': textButtonTheme,
'CupertinoButton': textButtonTheme,
'ElevatedButton': textButtonTheme,
'OutlinedButton': WidgetTheme(iconAsset: WidgetIcons.outlinedButton),
// Tabs
'Tab': tabTheme,
'TabBar': tabTheme,
'TabBarView': tabTheme,
'BottomNavigationBar':
WidgetTheme(iconAsset: WidgetIcons.bottomNavigationBar),
'CupertinoTabScaffold': tabTheme,
'CupertinoTabView': tabTheme,
// Other
'Scaffold': WidgetTheme(iconAsset: WidgetIcons.scaffold),
'CircularProgressIndicator':
WidgetTheme(iconAsset: WidgetIcons.circularProgress),
'Card': WidgetTheme(iconAsset: WidgetIcons.card),
'Divider': WidgetTheme(iconAsset: WidgetIcons.divider),
'AlertDialog': WidgetTheme(iconAsset: WidgetIcons.alertDialog),
'CircleAvatar': WidgetTheme(iconAsset: WidgetIcons.circleAvatar),
'Opacity': WidgetTheme(iconAsset: WidgetIcons.opacity),
'Drawer': WidgetTheme(iconAsset: WidgetIcons.drawer),
'PageView': WidgetTheme(iconAsset: WidgetIcons.pageView),
'Material': WidgetTheme(iconAsset: WidgetIcons.material),
'AppBar': WidgetTheme(iconAsset: WidgetIcons.appBar),
};
}
class WidgetIcons {
static const String root = 'icons/inspector/widget_icons/root.png';
static const String text = 'icons/inspector/widget_icons/text.png';
static const String icon = 'icons/inspector/widget_icons/icon.png';
static const String image = 'icons/inspector/widget_icons/image.png';
static const String floatingActionButton =
'icons/inspector/widget_icons/floatingab.png';
static const String checkbox = 'icons/inspector/widget_icons/checkbox.png';
static const String radio = 'icons/inspector/widget_icons/radio.png';
static const String toggle = 'icons/inspector/widget_icons/toggle.png';
static const String animated = 'icons/inspector/widget_icons/animated.png';
static const String transition =
'icons/inspector/widget_icons/transition.png';
static const String hero = 'icons/inspector/widget_icons/hero.png';
static const String container = 'icons/inspector/widget_icons/container.png';
static const String center = 'icons/inspector/widget_icons/center.png';
static const String row = 'icons/inspector/widget_icons/row.png';
static const String column = 'icons/inspector/widget_icons/column.png';
static const String padding = 'icons/inspector/widget_icons/padding.png';
static const String scaffold = 'icons/inspector/widget_icons/scaffold.png';
static const String sizedBox = 'icons/inspector/widget_icons/sizedbox.png';
static const String align = 'icons/inspector/widget_icons/align.png';
static const String scroll = 'icons/inspector/widget_icons/scroll.png';
static const String stack = 'icons/inspector/widget_icons/stack.png';
static const String inkWell = 'icons/inspector/widget_icons/inkwell.png';
static const String gesture = 'icons/inspector/widget_icons/gesture.png';
static const String textButton =
'icons/inspector/widget_icons/textbutton.png';
static const String outlinedButton =
'icons/inspector/widget_icons/outlinedbutton.png';
static const String gridView = 'icons/inspector/widget_icons/gridview.png';
static const String listView = 'icons/inspector/widget_icons/listView.png';
static const String alertDialog =
'icons/inspector/widget_icons/alertdialog.png';
static const String card = 'icons/inspector/widget_icons/card.png';
static const String circleAvatar =
'icons/inspector/widget_icons/circleavatar.png';
static const String circularProgress =
'icons/inspector/widget_icons/circularprogress.png';
static const String constrainedBox =
'icons/inspector/widget_icons/constrainedbox.png';
static const String divider = 'icons/inspector/widget_icons/divider.png';
static const String drawer = 'icons/inspector/widget_icons/drawer.png';
static const String expand = 'icons/inspector/widget_icons/expand.png';
static const String material = 'icons/inspector/widget_icons/material.png';
static const String opacity = 'icons/inspector/widget_icons/opacity.png';
static const String tab = 'icons/inspector/widget_icons/tab.png';
static const String wrap = 'icons/inspector/widget_icons/wrap.png';
static const String pageView = 'icons/inspector/widget_icons/pageView.png';
static const String appBar = 'icons/inspector/widget_icons/appbar.png';
static const String materialApp =
'icons/inspector/widget_icons/materialapp.png';
static const String bottomNavigationBar =
'icons/inspector/widget_icons/bottomnavigationbar.png';
}
| devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/widgets_theme.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/widgets_theme.dart",
"repo_id": "devtools",
"token_count": 3379
} | 86 |
Panes in this folder should not depend on each other.
If they need to share code, move the code to `memory/primitives` (if it is one library or less),
or to `memory/shared` (if it is more than one library).
| devtools/packages/devtools_app/lib/src/screens/memory/panes/README.md/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/README.md",
"repo_id": "devtools",
"token_count": 58
} | 87 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import '../../../../../shared/analytics/analytics.dart' as ga;
import '../../../../../shared/analytics/constants.dart' as gac;
import '../../../../../shared/config_specific/import_export/import_export.dart';
import '../../../../../shared/file_import.dart';
import '../../../../../shared/globals.dart';
import '../../../../../shared/memory/class_name.dart';
import '../../../../../shared/memory/retaining_path.dart';
import '../../../shared/heap/class_filter.dart';
import '../../../shared/heap/heap.dart';
import '../../../shared/heap/model.dart';
import '../../../shared/primitives/memory_utils.dart';
import '../data/classes_diff.dart';
import '../data/heap_diff_store.dart';
import 'class_data.dart';
import 'item_controller.dart';
import 'utils.dart';
class DiffPaneController extends DisposableController {
DiffPaneController(this.snapshotTaker);
final SnapshotTaker snapshotTaker;
final retainingPathController = RetainingPathController();
final core = CoreData();
late final derived = DerivedData(core);
/// True, if the list contains snapshots, i.e. items beyond the first
/// informational item.
bool get hasSnapshots => core.snapshots.value.length > 1;
Future<void> takeSnapshot() async {
ga.select(
gac.memory,
gac.MemoryEvent.diffTakeSnapshotControlPane,
);
final item = SnapshotInstanceItem(
displayNumber: _nextDisplayNumber(),
defaultName: selectedIsolateName ?? '<isolate-not-detected>',
);
await _addSnapshot(snapshotTaker, item);
derived._updateValues();
}
/// Imports snapshots from files.
///
/// Opens file selector and loads snapshots from the selected files.
Future<void> importSnapshots() async {
ga.select(
gac.memory,
gac.importFile,
);
final files = await importRawFilesFromPicker();
if (files.isEmpty) return;
final importers = files.map((file) async {
final item = SnapshotInstanceItem(defaultName: file.name);
await _addSnapshot(SnapshotTakerFromFile(file), item);
});
await Future.wait(importers);
derived._updateValues();
}
Future<void> _addSnapshot(
SnapshotTaker snapshotTaker,
SnapshotInstanceItem item,
) async {
final snapshots = core._snapshots;
snapshots.add(item);
try {
final heapData = await snapshotTaker.take();
await item.initializeHeapData(heapData);
} catch (e) {
snapshots.remove(item);
rethrow;
} finally {
final newElementIndex = snapshots.value.length - 1;
core._selectedSnapshotIndex.value = newElementIndex;
}
}
void clearSnapshots() {
final snapshots = core._snapshots;
for (var i = 1; i < snapshots.value.length; i++) {
snapshots.value[i].dispose();
}
snapshots.removeRange(1, snapshots.value.length);
core._selectedSnapshotIndex.value = 0;
derived._updateValues();
}
int _nextDisplayNumber() {
final numbers = core._snapshots.value.map((e) => e.displayNumber ?? 0);
assert(numbers.isNotEmpty);
return numbers.max + 1;
}
void deleteCurrentSnapshot() {
deleteSnapshot(core.selectedItem);
}
void deleteSnapshot(SnapshotItem item) {
assert(item is SnapshotInstanceItem);
item.dispose();
final index = core.selectedSnapshotIndex.value;
core._snapshots.removeAt(index);
// We change the selectedIndex, because:
// 1. It is convenient UX
// 2. Otherwise the content will not be re-rendered.
core._selectedSnapshotIndex.value = max(index - 1, 0);
derived._updateValues();
}
void setSnapshotIndex(int index) {
core._selectedSnapshotIndex.value = index;
derived._updateValues();
}
void setDiffing(
SnapshotInstanceItem diffItem,
SnapshotInstanceItem? withItem,
) {
diffItem.diffWith.value = withItem;
derived._updateValues();
}
void downloadCurrentItemToCsv() {
final classes = derived.heapClasses.value!;
final item = core.selectedItem as SnapshotInstanceItem;
final diffWith = item.diffWith.value;
late String filePrefix;
filePrefix = diffWith == null ? item.name : '${item.name}-${diffWith.name}';
ExportController().downloadFile(
classesToCsv(classes.classStatsList),
type: ExportFileType.csv,
fileName: ExportController.generateFileName(
type: ExportFileType.csv,
prefix: filePrefix,
),
);
}
}
/// Values that define what data to show on diff screen.
///
/// Widgets should not update the fields directly, they should use
/// [DiffPaneController] or [DerivedData] for this.
class CoreData {
late final rootPackage =
serviceConnection.serviceManager.rootInfoNow().package;
/// The list contains one item that show information and all others
/// are snapshots.
ValueListenable<List<SnapshotItem>> get snapshots => _snapshots;
final _snapshots = ListValueNotifier(<SnapshotItem>[SnapshotDocItem()]);
/// Selected snapshot.
ValueListenable<int> get selectedSnapshotIndex => _selectedSnapshotIndex;
final _selectedSnapshotIndex = ValueNotifier<int>(0);
SnapshotItem get selectedItem =>
_snapshots.value[_selectedSnapshotIndex.value];
/// Full name for the selected class (cross-snapshot).
HeapClassName? className;
/// Selected retaining path (cross-snapshot).
PathFromRoot? path;
/// Current class filter.
ValueListenable<ClassFilter> get classFilter => _classFilter;
final _classFilter = ValueNotifier(ClassFilter.empty());
}
/// Values that can be calculated from [CoreData] and notifiers that take signal
/// from widgets.
class DerivedData extends DisposableController with AutoDisposeControllerMixin {
DerivedData(this._core) {
_selectedItem = ValueNotifier<SnapshotItem>(_core.selectedItem);
final classFilterData = ClassFilterData(
filter: _core.classFilter,
onChanged: applyFilter,
);
classesTableSingle = ClassesTableSingleData(
heap: () => (_core.selectedItem as SnapshotInstanceItem).heap!.data,
totalHeapSize: () =>
(_core.selectedItem as SnapshotInstanceItem).totalSize!,
filterData: classFilterData,
);
classesTableDiff = ClassesTableDiffData(
filterData: classFilterData,
before: () => (heapClasses.value as DiffHeapClasses).before,
after: () => (heapClasses.value as DiffHeapClasses).after,
);
addAutoDisposeListener(
classesTableSingle.selection,
() => _setClassIfNotNull(classesTableSingle.selection.value?.heapClass),
);
addAutoDisposeListener(
classesTableDiff.selection,
() => _setClassIfNotNull(classesTableDiff.selection.value?.heapClass),
);
addAutoDisposeListener(
selectedPathEntry,
() => _setPathIfNotNull(selectedPathEntry.value?.key),
);
}
final CoreData _core;
/// Currently selected item, to take signal from the list widget.
ValueListenable<SnapshotItem> get selectedItem => _selectedItem;
late final ValueNotifier<SnapshotItem> _selectedItem;
/// Classes to show.
final heapClasses = ValueNotifier<HeapClasses?>(null);
late final ClassesTableSingleData classesTableSingle;
late final ClassesTableDiffData classesTableDiff;
/// Classes to show for currently selected item, if the item is diffed.
ValueListenable<List<DiffClassData>?> get diffClassesToShow =>
_diffClassesToShow;
final _diffClassesToShow = ValueNotifier<List<DiffClassData>?>(null);
/// Classes to show for currently selected item, if the item is not diffed.
ValueListenable<List<SingleClassStats>?> get singleClassesToShow =>
_singleClassesToShow;
final _singleClassesToShow = ValueNotifier<List<SingleClassStats>?>(null);
/// List of retaining paths to show for the selected class.
final pathEntries = ValueNotifier<List<StatsByPathEntry>?>(null);
/// Selected retaining path record in a concrete snapshot, to take signal from the table widget.
final selectedPathEntry = ValueNotifier<StatsByPathEntry?>(null);
/// Storage for already calculated diffs between snapshots.
late final _diffStore = HeapDiffStore();
void applyFilter(ClassFilter filter) {
if (filter.equals(_core.classFilter.value)) return;
_core._classFilter.value = filter;
_updateValues();
}
/// Updates cross-snapshot class if the argument is not null.
void _setClassIfNotNull(HeapClassName? theClass) {
if (theClass == null || theClass == _core.className) return;
_core.className = theClass;
_updateValues();
}
/// Updates cross-snapshot path if the argument is not null.
void _setPathIfNotNull(PathFromRoot? path) {
if (path == null || path == _core.path) return;
_core.path = path;
_updateValues();
}
void _assertIntegrity() {
assert(() {
assert(!_updatingValues);
var singleHidden = true;
var diffHidden = true;
var details = 'no data';
final item = selectedItem.value;
if (item is SnapshotInstanceItem && item.hasData) {
diffHidden = item.diffWith.value == null;
singleHidden = !diffHidden;
details = diffHidden ? 'single' : 'diff';
}
assert(singleHidden || diffHidden);
if (singleHidden) {
assert(classesTableSingle.selection.value == null, details);
}
if (diffHidden) assert(classesTableDiff.selection.value == null, details);
assert((singleClassesToShow.value == null) == singleHidden, details);
assert((diffClassesToShow.value == null) == diffHidden, details);
return true;
}());
}
/// Classes for the selected snapshot with diffing applied.
HeapClasses? _snapshotClassesAfterDiffing() {
final theItem = _core.selectedItem;
if (theItem is! SnapshotInstanceItem) return null;
final heap = theItem.heap;
if (heap == null) return null;
final itemToDiffWith = theItem.diffWith.value;
if (itemToDiffWith == null) return heap.classes;
return _diffStore.compare(heap, itemToDiffWith.heap!);
}
void _updateClasses({
required HeapClasses? classes,
required HeapClassName? className,
}) {
final filter = _core.classFilter.value;
if (classes is SingleHeapClasses) {
_singleClassesToShow.value = classes.filtered(filter, _core.rootPackage);
_diffClassesToShow.value = null;
classesTableSingle.selection.value =
_filter(classes.classesByName[className]);
classesTableDiff.selection.value = null;
} else if (classes is DiffHeapClasses) {
_singleClassesToShow.value = null;
_diffClassesToShow.value = classes.filtered(filter, _core.rootPackage);
classesTableSingle.selection.value = null;
classesTableDiff.selection.value =
_filter(classes.classesByName[className]);
} else if (classes == null) {
_singleClassesToShow.value = null;
_diffClassesToShow.value = null;
classesTableSingle.selection.value = null;
classesTableDiff.selection.value = null;
} else {
throw StateError('Unexpected type: ${classes.runtimeType}.');
}
}
/// Returns [classStats] if it matches the current filter.
T? _filter<T extends ClassData>(T? classStats) {
if (classStats == null) return null;
if (_core.classFilter.value.apply(
classStats.heapClass,
_core.rootPackage,
)) {
return classStats;
}
return null;
}
bool get updatingValues => _updatingValues;
bool _updatingValues = false;
/// Updates fields in this instance based on the values in [core].
void _updateValues() {
_startUpdatingValues();
// Set class to show.
final classes = _snapshotClassesAfterDiffing();
heapClasses.value = classes;
_selectClassAndPath();
_updateClasses(
classes: classes,
className: _core.className,
);
// Set paths to show.
final theClass =
classesTableSingle.selection.value ?? classesTableDiff.selection.value;
final thePathEntries = pathEntries.value = theClass?.statsByPathEntries;
final paths = theClass?.statsByPath;
StatsByPathEntry? thePathEntry;
if (_core.path != null && paths != null && thePathEntries != null) {
final pathStats = paths[_core.path];
if (pathStats != null) {
thePathEntry =
thePathEntries.firstWhereOrNull((e) => e.key == _core.path);
}
}
selectedPathEntry.value = thePathEntry;
// Set current snapshot.
_selectedItem.value = _core.selectedItem;
_endUpdatingValues();
}
void _startUpdatingValues() {
// Make sure the method does not trigger itself recursively.
assert(!_updatingValues);
ga.timeStart(
gac.memory,
gac.MemoryTime.updateValues,
);
_updatingValues = true;
}
void _endUpdatingValues() {
_updatingValues = false;
ga.timeEnd(
gac.memory,
gac.MemoryTime.updateValues,
);
_assertIntegrity();
}
/// Set initial selection of class and path, for discoverability of detailed view.
void _selectClassAndPath() {
if (_core.className != null) return;
assert(_core.path == null);
final classes = heapClasses.value;
if (classes == null) return;
SingleClassStats singleWithMaxRetainedSize(
SingleClassStats a,
SingleClassStats b,
) =>
a.objects.retainedSize > b.objects.retainedSize ? a : b;
DiffClassData diffWithMaxRetainedSize(
DiffClassData a,
DiffClassData b,
) =>
a.total.delta.retainedSize > b.total.delta.retainedSize ? a : b;
// Get class with max retained size.
final ClassData theClass;
if (classes is SingleHeapClasses) {
final classStatsList = classes.filtered(
_core.classFilter.value,
_core.rootPackage,
);
if (classStatsList.isEmpty) return;
theClass = classStatsList.reduce(singleWithMaxRetainedSize);
} else if (classes is DiffHeapClasses) {
final classStatsList = classes.filtered(
_core.classFilter.value,
_core.rootPackage,
);
if (classStatsList.isEmpty) return;
theClass = classStatsList.reduce(diffWithMaxRetainedSize);
} else {
throw StateError('Unexpected type ${classes.runtimeType}');
}
_core.className = theClass.heapClass;
assert(theClass.statsByPathEntries.isNotEmpty);
// Get path with max retained size.
final path = theClass.statsByPathEntries.reduce((v, e) {
if (v.value.retainedSize > e.value.retainedSize) return v;
return e;
});
_core.path = path.key;
}
}
| devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/controller/diff_pane_controller.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/controller/diff_pane_controller.dart",
"repo_id": "devtools",
"token_count": 5143
} | 88 |
// 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/constants.dart';
import '../../../../shared/memory/class_name.dart';
import '../../shared/heap/sampler.dart';
import '../../shared/primitives/instance_context_menu.dart';
/// Right aligned table cell, shat shows number of instances.
///
/// If the row is selected and count of instances is positive, the table cell
/// includes a "more" icon button with a context menu for the instance set.
class ProfileInstanceTableCell extends StatelessWidget {
ProfileInstanceTableCell(
this.heapClass,
this.gaContext, {
super.key,
required bool isSelected,
required this.count,
}) : _shouldShowMenu = isSelected && count > 0;
final MemoryAreas gaContext;
final int count;
final bool _shouldShowMenu;
final HeapClassName heapClass;
late final ClassSampler _sampler = ClassSampler(heapClass);
@override
Widget build(BuildContext context) {
return InstanceViewWithContextMenu(
count: count,
menuBuilder: _shouldShowMenu ? _buildHeapInstancesMenu : null,
);
}
List<Widget> _buildHeapInstancesMenu() {
return [
_StoreAsOneVariableMenu(_sampler),
_StoreAllAsVariableMenu(_sampler),
];
}
}
class _StoreAllAsVariableMenu extends StatelessWidget {
const _StoreAllAsVariableMenu(this.sampler);
final ClassSampler sampler;
@override
Widget build(BuildContext context) {
const menuText = 'Store all class instances';
MenuItemButton item(
String title, {
required bool subclasses,
required bool implementers,
}) =>
MenuItemButton(
onPressed: () async => await sampler.allLiveToConsole(
includeImplementers: implementers,
includeSubclasses: subclasses,
),
child: Text(title),
);
return SubmenuButton(
menuChildren: <Widget>[
item('Direct instances', implementers: false, subclasses: false),
item('Direct and subclasses', implementers: false, subclasses: false),
item('Direct and implementers', implementers: false, subclasses: false),
item(
'Direct, subclasses, and implementers',
implementers: false,
subclasses: false,
),
],
child: const Text(menuText),
);
}
}
class _StoreAsOneVariableMenu extends StatelessWidget {
const _StoreAsOneVariableMenu(this.sampler);
final ClassSampler sampler;
@override
Widget build(BuildContext context) {
return MenuItemButton(
onPressed: sampler.oneLiveToConsole,
child: const Text('Store one instance as a console variable'),
);
}
}
| devtools/packages/devtools_app/lib/src/screens/memory/panes/profile/instances.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/profile/instances.dart",
"repo_id": "devtools",
"token_count": 981
} | 89 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_shared/devtools_shared.dart';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:vm_service/vm_service.dart';
import '../../../../shared/primitives/utils.dart';
enum ContinuesState {
none,
start,
stop,
next,
}
/// All Raw data received from the VM and offline data loaded from a memory log file.
class MemoryTimeline {
static const delayMs = 500;
static const Duration updateDelay = Duration(milliseconds: delayMs);
/// This flag will be needed for offline mode implementation.
final offline = false;
/// Return the data payload that is active.
List<HeapSample> get data => offline ? offlineData : liveData;
int get startingIndex => offline ? offlineStartingIndex : liveStartingIndex;
set startingIndex(int value) {
offline ? offlineStartingIndex = value : liveStartingIndex = value;
}
int get endingIndex => data.isNotEmpty ? data.length - 1 : -1;
/// Raw Heap sampling data from the VM.
final List<HeapSample> liveData = [];
/// Start index of liveData plotted for MPChartData/MPEngineChartData sets.
int liveStartingIndex = 0;
/// Data of the last selected offline memory source (JSON file in /tmp).
final List<HeapSample> offlineData = [];
/// Start index of offlineData plotted for MPChartData/MPEngineChartData sets.
int offlineStartingIndex = 0;
/// Extension Events.
final _eventFiredNotifier = ValueNotifier<Event?>(null);
ValueListenable<Event?> get eventNotifier => _eventFiredNotifier;
/// Notifies that a new Heap sample has been added to the timeline.
final _sampleAddedNotifier = ValueNotifier<HeapSample?>(null);
ValueListenable<HeapSample?> get sampleAddedNotifier => _sampleAddedNotifier;
/// List of events awaiting to be posted to HeapSample.
final _eventSamples = <EventSample>[];
ContinuesState monitorContinuesState = ContinuesState.none;
void postEventSample(EventSample event) {
/*
final lastEvent = _eventSamples.safeLast;
if (lastEvent != null) {
final lastTime = Duration(milliseconds: lastEvent.timestamp);
final eventTime = Duration(milliseconds: event.timestamp);
if ((lastTime + MemoryTimeline.updateDelay).compareTo(eventTime) <= 0) {
// Coalesce new event to old event.
_eventSamples.add(EventSample(
// lastEvent.timestamp,
event.timestamp,
lastEvent.isEventGC || event.isEventGC,
lastEvent.isEventSnapshot || event.isEventSnapshot,
lastEvent.isEventSnapshotAuto || event.isEventSnapshotAuto,
lastEvent.allocationAccumulator,
));
}
}
*/
_eventSamples.add(event);
}
void addSnapshotEvent({bool auto = false}) {
postEventSample(
EventSample.snapshotEvent(
DateTime.now().millisecondsSinceEpoch,
snapshotAuto: auto,
events: extensionEvents,
),
);
}
void addGCEvent() {
final timestamp = DateTime.now().millisecondsSinceEpoch;
postEventSample(
EventSample.gcEvent(
timestamp,
events: extensionEvents,
),
);
}
bool get anyEvents => peekEventTimestamp != -1;
/// Peek at next event to pull, if no event return -1 timestamp.
int get peekEventTimestamp {
final event = _eventSamples.safeFirst;
return event != null ? event.timestamp : -1;
}
/// Grab and remove the event to be posted.
EventSample pullEventSample() {
final result = _eventSamples.first;
_eventSamples.removeAt(0);
return result;
}
final _sampleEventNotifier = ValueNotifier<int>(0);
ValueNotifier<int> get sampleEventNotifier => _sampleEventNotifier;
/// Whether the timeline has been manually paused via the Pause button.
bool manuallyPaused = false;
void reset() {
liveData.clear();
startingIndex = 0;
}
/// Common utility function to handle loading of the data into the
/// chart for either offline or live Feed.
static final DateFormat _milliFormat = DateFormat('HH:mm:ss.SSS');
static String fineGrainTimestampFormat(int timestamp) =>
_milliFormat.format(DateTime.fromMillisecondsSinceEpoch(timestamp));
void addSample(HeapSample sample) {
// Always record the heap sample in the raw set of data (liveFeed).
liveData.add(sample);
// Only notify that new sample has arrived if the
// memory source is 'Live Feed'.
if (!offline) {
_sampleAddedNotifier.value = sample;
sampleEventNotifier.value++;
}
}
static const customDevToolsEvent = 'DevTools.Event';
static const devToolsExtensionEvent = '${customDevToolsEvent}_';
static bool isCustomEvent(String extensionEvent) =>
extensionEvent.startsWith(devToolsExtensionEvent);
static String customEventName(String extensionEventKind) =>
extensionEventKind.substring(
MemoryTimeline.devToolsExtensionEvent.length,
);
final _extensionEvents = <ExtensionEvent>[];
bool get anyPendingExtensionEvents => _extensionEvents.isNotEmpty;
ExtensionEvents? get extensionEvents {
if (_extensionEvents.isNotEmpty) {
final eventsToProcess = ExtensionEvents(_extensionEvents.toList());
_extensionEvents.clear();
return eventsToProcess;
}
return null;
}
void addExtensionEvent(
int? timestamp,
String? eventKind,
Map<String, Object> json, {
String? customEventName,
}) {
final extensionEvent = customEventName == null
? ExtensionEvent(timestamp, eventKind, json)
: ExtensionEvent.custom(timestamp, eventKind, customEventName, json);
_extensionEvents.add(extensionEvent);
}
}
| devtools/packages/devtools_app/lib/src/screens/memory/shared/primitives/memory_timeline.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/memory/shared/primitives/memory_timeline.dart",
"repo_id": "devtools",
"token_count": 1883
} | 90 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app_shared/ui.dart';
import 'package:flutter/material.dart';
import '../../../../service/service_extension_widgets.dart';
import '../../../../service/service_extensions.dart' as extensions;
import '../../../../shared/feature_flags.dart';
import '../../../../shared/globals.dart';
import 'performance_controls.dart';
class MoreDebuggingOptionsButton extends StatelessWidget {
const MoreDebuggingOptionsButton({Key? key}) : super(key: key);
static const _width = 620.0;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return ServiceExtensionCheckboxGroupButton(
title: 'More debugging options',
icon: Icons.build,
tooltip: 'Opens a list of options you can use to help debug performance',
minScreenWidthForTextBeforeScaling:
PerformanceControls.minScreenWidthForTextBeforeScaling,
extensions: [
extensions.disableClipLayers,
extensions.disableOpacityLayers,
extensions.disablePhysicalShapeLayers,
if (FeatureFlags.widgetRebuildstats) extensions.trackRebuildWidgets,
],
overlayDescription: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'After toggling a rendering layer on/off, '
'reproduce the activity in your app to see the effects. '
'All layers are rendered by default - disabling a '
'layer might help identify expensive operations in your app.',
style: theme.subtleTextStyle,
),
if (serviceConnection
.serviceManager.connectedApp!.isProfileBuildNow!) ...[
const SizedBox(height: denseSpacing),
RichText(
text: TextSpan(
text:
"These debugging options aren't available in profile mode. "
'To use them, run your app in debug mode.',
style: theme.subtleTextStyle
.copyWith(color: theme.colorScheme.error),
),
),
],
],
),
overlayWidthBeforeScaling: _width,
);
}
}
| devtools/packages/devtools_app/lib/src/screens/performance/panes/controls/more_debugging_options.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/controls/more_debugging_options.dart",
"repo_id": "devtools",
"token_count": 928
} | 91 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui_web' as ui_web;
import 'package:flutter/foundation.dart';
import 'package:vm_service_protos/vm_service_protos.dart';
import 'package:web/web.dart';
import '../../../../../shared/globals.dart';
import '../../../../../shared/primitives/utils.dart';
import 'perfetto_controller.dart';
import 'tracing/model.dart';
/// Flag to enable embedding an instance of the Perfetto UI running on
/// localhost.
///
/// The version running on localhost will not include the DevTools styling
/// modifications for dark mode, as those CSS changes are defined in
/// [devtools_app/assets/perfetto] and will not be served with the Perfetto web
/// app running locally.
const _debugUseLocalPerfetto = false;
/// Incrementer for the Perfetto iFrame view that will live for the entire
/// DevTools lifecycle.
///
/// A new instance of [PerfettoController] will be created for each connected
/// app and for each load of offline data. Each time [PerfettoController.init]
/// is called, we create a new [html.IFrameElement] and register it to
/// [PerfettoController.viewId] via
/// [ui_web.platformViewRegistry.registerViewFactory]. Each new [html.IFrameElement]
/// must have a unique id in the [PlatformViewRegistry], which
/// [_viewIdIncrementer] is used to create.
var _viewIdIncrementer = 0;
/// Events that are passed between DevTools and the embedded Perfetto iFrame via
/// [window.postMessage].
enum EmbeddedPerfettoEvent {
/// Id for an event Perfetto expects to verify the trace viewer is ready.
ping('PING'),
/// Id for an event that Perfetto will send back after receiving a [ping]
/// event.
pong('PONG'),
/// Id for an event that signals to Perfetto that the modal help dialog should
/// be opened.
showHelp('SHOW-HELP'),
/// Id for an event that signals to Perfetto that the CSS constants need to be
/// re-initialized.
reloadCssConstants('RELOAD-CSS-CONSTANTS'),
/// Id for a [postMessage] request that is sent before trying to change the
/// DevTools theme (see [devtoolsThemeChange]).
///
/// Once the DevTools theme handler in the bundled Perfetto web app has been
/// registered, a "pong" event [devtoolsThemePong] will be returned, at which
/// point we can safely change the theme [devtoolsThemeChange].
///
/// This message must be sent with the argument 'perfettoIgnore' set to true
/// so that the message handler in the Perfetto codebase
/// [post_message_handler.ts] will not try to handle this message and warn
/// "Unknown postMessage() event received".
devtoolsThemePing('DART-DEVTOOLS-THEME-PING'),
/// Id for a [postMessage] response that should be received when the DevTools
/// theme handler has been registered.
///
/// We will send a "ping" event [devtoolsThemePing] to the DevTools theme
/// handler in the bundled Perfetto web app, and the handler will return this
/// "pong" event when it is ready. We must wait for this event to be returned
/// before we can send a theme change request [devtoolsThemeChange].
devtoolsThemePong('DART-DEVTOOLS-THEME-PONG'),
/// Id for a [postMessage] request that is sent on DevTools theme changes.
///
/// This message must be sent with the argument 'perfettoIgnore' set to true
/// so that the message handler in the Perfetto codebase
/// [post_message_handler.ts] will not try to handle this message and warn
/// "Unknown postMessage() event received".
devtoolsThemeChange('DART-DEVTOOLS-THEME-CHANGE');
const EmbeddedPerfettoEvent(this.event);
final String event;
}
class PerfettoControllerImpl extends PerfettoController {
PerfettoControllerImpl(
super.performanceController,
super.timelineEventsController,
);
/// The view id for the Perfetto iFrame.
///
/// See [_viewIdIncrementer] for an explanation of why we use an incrementer
/// in the id.
late final viewId = 'embedded-perfetto-${_viewIdIncrementer++}';
/// Url when running Perfetto locally following the instructions here:
/// https://perfetto.dev/docs/contributing/build-instructions#ui-development
static const _debugPerfettoUrl = 'http://127.0.0.1:10000/$_embeddedModeQuery';
/// These query parameters have side effects in the Perfetto web app.
static const _embeddedModeQuery = '?mode=embedded&hideSidebar=true';
/// Delay to allow the Perfetto UI to load a trace.
///
/// This is a heuristic to continue blocking UI elements on the DevTools side
/// while the trace is still loading on the Perfetto side (for example,
/// the [RefreshTimelineEventsButton]).
static const _postTraceDelay = Duration(seconds: 1);
String get perfettoUrl {
if (_debugUseLocalPerfetto) {
return _debugPerfettoUrl;
}
final basePath = devtoolsAssetsBasePath(
origin: window.location.origin,
path: window.location.pathname,
);
final indexFilePath = ui_web.assetManager
.getAssetUrl(devToolsExtensionPoints.perfettoIndexLocation);
final baseUrl = '$basePath/$indexFilePath';
return '$baseUrl$_embeddedModeQuery';
}
HTMLIFrameElement get perfettoIFrame => _perfettoIFrame;
late final HTMLIFrameElement _perfettoIFrame;
/// The Perfetto trace data that should be shown in the Perfetto trace viewer.
///
/// This will start in a null state before the first trace is been loaded.
final activeTrace = PerfettoTrace(null);
/// The time range that should be scrolled to, or focused, in the Perfetto
/// trace viewer.
ValueListenable<TimeRange?> get activeScrollToTimeRange =>
_activeScrollToTimeRange;
final _activeScrollToTimeRange = ValueNotifier<TimeRange?>(null);
/// Trace data that we should load, but have not yet since the trace viewer
/// is not visible (i.e. [TimelineEventsController.isActiveFeature] is false).
Trace? pendingTraceToLoad;
/// Time range we should scroll to, but have not yet since the trace viewer
/// is not visible (i.e. [TimelineEventsController.isActiveFeature] is false).
TimeRange? pendingScrollToTimeRange;
final perfettoPostEventStream = StreamController<String>.broadcast();
bool _initialized = false;
@override
void init() {
assert(
!_initialized,
'PerfettoController.init() should only be called once.',
);
_initialized = true;
_perfettoIFrame = createIFrameElement()
// This url is safe because we built it ourselves and it does not include
// any user input.
// ignore: unsafe_html
..src = perfettoUrl
..allow = 'usb';
_perfettoIFrame.style
..border = 'none'
..height = '100%'
..width = '100%';
final registered = ui_web.platformViewRegistry.registerViewFactory(
viewId,
(int viewId) => _perfettoIFrame,
);
assert(registered, 'Failed to register view factory for $viewId.');
}
@override
void dispose() async {
await perfettoPostEventStream.close();
processor.dispose();
super.dispose();
}
@override
void onBecomingActive() {
assert(timelineEventsController.isActiveFeature);
if (pendingTraceToLoad != null) {
unawaited(loadTrace(pendingTraceToLoad!));
pendingTraceToLoad = null;
}
if (pendingScrollToTimeRange != null) {
scrollToTimeRange(pendingScrollToTimeRange!);
pendingScrollToTimeRange = null;
}
}
@override
Future<void> loadTrace(Trace trace) async {
if (!timelineEventsController.isActiveFeature) {
pendingTraceToLoad = trace;
return;
}
pendingTraceToLoad = null;
activeTrace.trace = trace;
await Future.delayed(_postTraceDelay);
}
@override
void scrollToTimeRange(TimeRange timeRange) {
if (!timelineEventsController.isActiveFeature) {
pendingScrollToTimeRange = timeRange;
return;
}
pendingScrollToTimeRange = null;
_activeScrollToTimeRange.value = timeRange;
}
@override
void showHelpMenu() {
perfettoPostEventStream.add(EmbeddedPerfettoEvent.showHelp.event);
}
@override
Future<void> clear() async {
processor.clear();
await loadTrace(Trace());
}
}
| devtools/packages/devtools_app/lib/src/screens/performance/panes/timeline_events/perfetto/_perfetto_controller_web.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/timeline_events/perfetto/_perfetto_controller_web.dart",
"repo_id": "devtools",
"token_count": 2601
} | 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 'package:flutter/foundation.dart';
enum ProfilerTab {
bottomUp('Bottom Up', _bottomUpTab),
callTree('Call Tree', _callTreeTab),
methodTable('Method Table', _methodTableTab),
cpuFlameChart('CPU Flame Chart', _flameChartTab);
const ProfilerTab(this.title, this.key);
final String title;
final Key key;
// When content of the selected DevToolsTab from the tab controller has any
// of these three keys, we will not show the expand/collapse buttons.
static const Key _flameChartTab = Key('cpu profile flame chart tab');
static const Key _methodTableTab = Key('cpu profile method table tab');
static const Key _bottomUpTab = Key('cpu profile bottom up tab');
static const Key _callTreeTab = Key('cpu profile call tree tab');
static ProfilerTab byKey(Key? k) {
return ProfilerTab.values.firstWhere((tab) => tab.key == k);
}
}
| devtools/packages/devtools_app/lib/src/screens/profiler/common.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/profiler/common.dart",
"repo_id": "devtools",
"token_count": 295
} | 93 |
// 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:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:vm_service/vm_service.dart';
import '../../shared/config_specific/logger/allowed_error.dart';
import '../../shared/globals.dart';
import '../../shared/offline_mode.dart';
import '../../shared/primitives/utils.dart';
import 'cpu_profile_model.dart';
import 'cpu_profile_service.dart';
import 'cpu_profiler_controller.dart';
import 'profiler_screen.dart';
import 'sampling_rate.dart';
class ProfilerScreenController extends DisposableController
with
AutoDisposeControllerMixin,
OfflineScreenControllerMixin<CpuProfileData> {
ProfilerScreenController() {
unawaited(_init());
}
final _initialized = Completer<void>();
Future<void> get initialized => _initialized.future;
Future<void> _init() async {
await _initHelper();
_initialized.complete();
}
Future<void> _initHelper() async {
initReviewHistoryOnDisconnectListener();
if (!offlineController.offlineMode.value) {
await allowedError(
serviceConnection.serviceManager.service!
.setProfilePeriod(mediumProfilePeriod),
logError: false,
);
_currentIsolate =
serviceConnection.serviceManager.isolateManager.selectedIsolate.value;
addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.selectedIsolate,
() {
final selectedIsolate = serviceConnection
.serviceManager.isolateManager.selectedIsolate.value;
if (selectedIsolate != null) {
switchToIsolate(selectedIsolate);
}
},
);
addAutoDisposeListener(preferences.vmDeveloperModeEnabled, () async {
if (preferences.vmDeveloperModeEnabled.value) {
// If VM developer mode was just enabled, clear the profile store
// since the existing entries won't have code profiles and cannot be
// constructed from function profiles.
cpuProfilerController.cpuProfileStore.clear();
cpuProfilerController.reset();
} else {
// If VM developer mode is disabled and we're grouping by VM tags, we
// need to default to the basic view of the profile.
final userTagFilter = cpuProfilerController.userTagFilter.value;
if (userTagFilter == CpuProfilerController.groupByVmTag) {
await cpuProfilerController
.loadDataWithTag(CpuProfilerController.userTagNone);
}
}
// Always reset to the function view when the VM developer mode state
// changes. The selector is hidden when VM developer mode is disabled
// and data for code profiles won't be requested.
cpuProfilerController.updateViewForType(CpuProfilerViewType.function);
});
} else {
await maybeLoadOfflineData(
ProfilerScreen.id,
createData: (json) => CpuProfileData.parse(json),
shouldLoad: (data) => !data.isEmpty,
);
}
}
final cpuProfilerController = CpuProfilerController();
CpuProfileData? get cpuProfileData =>
cpuProfilerController.dataNotifier.value;
final _previousProfileByIsolateId = <String?, CpuProfileData?>{};
/// Notifies that a CPU profile is currently being recorded.
ValueListenable<bool> get recordingNotifier => _recordingNotifier;
final _recordingNotifier = ValueNotifier<bool>(false);
IsolateRef? _currentIsolate;
void switchToIsolate(IsolateRef? ref) {
// Store the data for the current isolate.
if (_currentIsolate?.id != null) {
_previousProfileByIsolateId[_currentIsolate?.id] =
cpuProfilerController.dataNotifier.value;
}
// Update the current isolate.
_currentIsolate = ref;
// Load any existing data for the new isolate.
final previousData = _previousProfileByIsolateId[ref?.id];
_recordingNotifier.value = false;
cpuProfilerController.reset(data: previousData);
}
int _profileRequestId = 0;
Future<void> startRecording() async {
await clear();
_recordingNotifier.value = true;
}
Future<void> stopRecording() async {
_recordingNotifier.value = false;
await cpuProfilerController.pullAndProcessProfile(
// We start at 0 every time because [startRecording] clears the cpu
// samples on the VM.
startMicros: 0,
// Using [maxJsInt] as [extentMicros] for the getCpuProfile requests will
// give us all cpu samples we have available
extentMicros: maxJsInt,
processId: 'Profile ${++_profileRequestId}',
);
}
@override
OfflineScreenData screenDataForExport() => OfflineScreenData(
screenId: ProfilerScreen.id,
data: cpuProfileData!.toJson,
);
@override
FutureOr<void> processOfflineData(CpuProfileData offlineData) async {
await cpuProfilerController.transformer.processData(
offlineData,
processId: 'offline data processing',
);
cpuProfilerController.loadProcessedData(
CpuProfilePair(
functionProfile: offlineData,
codeProfile: null,
),
storeAsUserTagNone: true,
);
}
Future<void> clear() async {
await cpuProfilerController.clear();
}
@override
void dispose() {
_recordingNotifier.dispose();
cpuProfilerController.dispose();
super.dispose();
}
}
| devtools/packages/devtools_app/lib/src/screens/profiler/profiler_screen_controller.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/profiler/profiler_screen_controller.dart",
"repo_id": "devtools",
"token_count": 1990
} | 94 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app_shared/ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:vm_service/vm_service.dart';
import '../../../shared/analytics/constants.dart' as gac;
import '../../../shared/common_widgets.dart';
import '../../../shared/primitives/byte_utils.dart';
import '../../../shared/primitives/utils.dart';
import '../../../shared/table/table.dart';
import '../../../shared/table/table_data.dart';
import '../../profiler/profiler_status.dart';
import '../vm_developer_common_widgets.dart';
import '../vm_developer_tools_screen.dart';
import '../vm_service_private_extensions.dart';
import 'isolate_statistics_view_controller.dart';
/// Displays general information about the state of the currently selected
/// isolate.
class IsolateStatisticsView extends VMDeveloperView {
const IsolateStatisticsView()
: super(
title: 'Isolates',
icon: Icons.bar_chart,
);
static const id = 'isolate-statistics';
@override
bool get showIsolateSelector => true;
@override
Widget build(BuildContext context) => IsolateStatisticsViewBody();
}
class IsolateStatisticsViewBody extends StatelessWidget {
IsolateStatisticsViewBody({super.key});
final controller = IsolateStatisticsViewController();
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: controller.refreshing,
builder: (context, refreshing, _) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RefreshButton(
gaScreen: gac.vmTools,
gaSelection: gac.refreshIsolateStatistics,
onPressed: controller.refresh,
),
const SizedBox(height: denseRowSpacing),
Flexible(
child: Column(
children: [
Flexible(
child: _buildTopRow(),
),
Flexible(
child: IsolatePortsWidget(
controller: controller,
),
),
],
),
),
],
);
},
);
}
Widget _buildTopRow() {
return Row(
children: [
Flexible(
child: Column(
children: [
Expanded(
child: GeneralIsolateStatisticsWidget(
controller: controller,
),
),
Expanded(
child: IsolateMemoryStatisticsWidget(
controller: controller,
),
),
],
),
),
Flexible(
child: TagStatisticsWidget(
controller: controller,
),
),
Flexible(
child: ServiceExtensionsWidget(
controller: controller,
),
),
],
);
}
}
/// Displays general information about the current isolate, including:
/// - Isolate debug name
/// - Start time and uptime
/// - Root library
/// - Isolate ID
class GeneralIsolateStatisticsWidget extends StatelessWidget {
const GeneralIsolateStatisticsWidget({super.key, required this.controller});
final IsolateStatisticsViewController controller;
String? _startTime(Isolate? isolate) {
if (isolate == null) {
return null;
}
final startedAtFormatter = DateFormat.yMMMMd().add_jms();
return startedAtFormatter.format(
DateTime.fromMillisecondsSinceEpoch(
isolate.startTime!,
).toLocal(),
);
}
String? _uptime(Isolate? isolate) {
if (isolate == null) {
return null;
}
final uptimeFormatter = DateFormat.Hms();
return uptimeFormatter.format(
DateTime.now()
.subtract(
Duration(milliseconds: isolate.startTime!),
)
.toUtc(),
);
}
@override
Widget build(BuildContext context) {
final isolate = controller.isolate;
return OutlineDecoration(
showRight: false,
showBottom: false,
child: VMInfoCard(
title: 'General',
roundedTopBorder: false,
rowKeyValues: [
selectableTextBuilderMapEntry('Name', isolate?.name),
selectableTextBuilderMapEntry('Started at', _startTime(isolate)),
selectableTextBuilderMapEntry('Uptime', _uptime(isolate)),
selectableTextBuilderMapEntry('Root Library', isolate?.rootLib?.uri),
selectableTextBuilderMapEntry('ID', isolate?.id),
],
),
);
}
}
/// Displays memory statistics for the isolate, including:
/// - Total Dart heap size
/// - New + Old space capacity and usage
class IsolateMemoryStatisticsWidget extends StatelessWidget {
const IsolateMemoryStatisticsWidget({super.key, required this.controller});
final IsolateStatisticsViewController controller;
String _buildMemoryString(num? usage, num? capacity) {
if (usage == null || capacity == null) {
return '--';
}
return '${prettyPrintBytes(usage, includeUnit: true)}'
' of ${prettyPrintBytes(capacity, includeUnit: true)}';
}
@override
Widget build(BuildContext context) {
final isolate = controller.isolate;
return OutlineDecoration(
showRight: false,
showBottom: false,
child: VMInfoCard(
title: 'Memory',
roundedTopBorder: false,
rowKeyValues: [
selectableTextBuilderMapEntry(
'Dart Heap',
_buildMemoryString(
isolate?.dartHeapSize,
isolate?.dartHeapCapacity,
),
),
selectableTextBuilderMapEntry(
'New Space',
_buildMemoryString(
isolate?.newSpaceUsage,
isolate?.newSpaceUsage,
),
),
selectableTextBuilderMapEntry(
'Old Space',
_buildMemoryString(
isolate?.oldSpaceUsage,
isolate?.oldSpaceCapacity,
),
),
],
),
);
}
}
/// A table which displays the amount of time the VM is performing certain
/// tagged tasks.
class TagStatisticsWidget extends StatelessWidget {
const TagStatisticsWidget({super.key, required this.controller});
static final _name = _TagColumn();
static final _percentage = _PercentageColumn();
static final _columns = <ColumnData<VMTag>>[_name, _percentage];
final IsolateStatisticsViewController controller;
@override
Widget build(BuildContext context) {
return OutlineDecoration(
showBottom: false,
child: VMInfoCard(
title: 'Execution Time',
roundedTopBorder: false,
table: Flexible(
child: controller.cpuProfilerController.profilerEnabled
? FlatTable<VMTag>(
keyFactory: (VMTag tag) => ValueKey<String>(tag.name),
data: controller.tags,
dataKey: 'tag-statistics',
columns: _columns,
defaultSortColumn: _percentage,
defaultSortDirection: SortDirection.descending,
)
: CpuProfilerDisabled(
controller.cpuProfilerController,
),
),
),
);
}
}
class _TagColumn extends ColumnData<VMTag> {
_TagColumn() : super.wide('Tag');
@override
String getValue(VMTag dataObject) => dataObject.name;
}
class _PercentageColumn extends ColumnData<VMTag> {
_PercentageColumn()
: super.wide('Percentage', alignment: ColumnAlignment.right);
@override
double getValue(VMTag dataObject) => dataObject.percentage;
@override
String getDisplayValue(VMTag dataObject) => percent(dataObject.percentage);
}
class _PortIDColumn extends ColumnData<InstanceRef> {
_PortIDColumn() : super.wide('ID');
@override
String getValue(InstanceRef port) => port.portId.toString();
}
class _PortNameColumn extends ColumnData<InstanceRef> {
_PortNameColumn() : super.wide('Name');
@override
String getValue(InstanceRef port) {
final debugName = port.debugName!;
return debugName.isEmpty ? 'N/A' : debugName;
}
}
class _StackTraceViewerFrameColumn extends ColumnData<String> {
_StackTraceViewerFrameColumn() : super.wide('Frame');
@override
String getValue(String frame) => frame;
@override
int compare(String f1, String f2) {
return _frameNumber(f1).compareTo(_frameNumber(f2));
}
int _frameNumber(String frame) {
return int.parse(frame.split(' ').first.substring(1));
}
}
// TODO(bkonyi): merge with debugger stack trace viewer.
/// A simple table to display a stack trace, sorted by frame number.
class StackTraceViewerWidget extends StatelessWidget {
const StackTraceViewerWidget({
super.key,
required this.stackTrace,
});
static final frame = _StackTraceViewerFrameColumn();
final ValueListenable<InstanceRef?> stackTrace;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<InstanceRef?>(
valueListenable: stackTrace,
builder: (context, stackTrace, _) {
final List<String>? lines = stackTrace
?.allocationLocation?.valueAsString
?.split('\n')
.where((e) => e.isNotEmpty)
.toList();
return VMInfoList(
title: 'Allocation Location',
roundedTopBorder: false,
table: lines == null
? const Expanded(
child: Center(
child: Text('No port selected'),
),
)
: Flexible(
child: FlatTable<String>(
keyFactory: (String s) => ValueKey<String>(s),
data: lines,
dataKey: 'stack-trace-viewer',
columns: [frame],
defaultSortColumn: frame,
defaultSortDirection: SortDirection.ascending,
),
),
);
},
);
}
}
/// Displays information about open ReceivePorts, including:
/// - Debug name (if provided, but all instances from the core libraries
/// will report this)
/// - Internal port ID
/// - Allocation location stack trace
class IsolatePortsWidget extends StatefulWidget {
const IsolatePortsWidget({super.key, required this.controller});
final IsolateStatisticsViewController controller;
@override
State<IsolatePortsWidget> createState() => _IsolatePortsWidgetState();
}
class _IsolatePortsWidgetState extends State<IsolatePortsWidget> {
static final _id = _PortIDColumn();
static final _name = _PortNameColumn();
static final _columns = <ColumnData<InstanceRef>>[_name, _id];
final selectedPort = ValueNotifier<InstanceRef?>(null);
@override
Widget build(BuildContext context) {
final ports = widget.controller.ports;
return OutlineDecoration(
child: SplitPane(
axis: Axis.horizontal,
initialFractions: const [
0.3,
0.7,
],
children: [
OutlineDecoration.onlyRight(
child: Column(
children: [
AreaPaneHeader(
includeTopBorder: false,
roundedTopBorder: false,
title: Text(
'Open Ports (${ports.length})',
),
),
Flexible(
child: FlatTable<InstanceRef?>(
keyFactory: (InstanceRef? port) =>
ValueKey<String>(port!.debugName!),
data: ports,
dataKey: 'isolate-ports',
columns: _columns,
defaultSortColumn: _id,
defaultSortDirection: SortDirection.ascending,
selectionNotifier: selectedPort,
),
),
],
),
),
OutlineDecoration.onlyLeft(
child: StackTraceViewerWidget(
stackTrace: selectedPort,
),
),
],
),
);
}
}
class _ServiceExtensionNameColumn extends ColumnData<String> {
_ServiceExtensionNameColumn() : super.wide('Name');
@override
String getValue(String s) => s;
}
/// A table displaying the list of service extensions registered with an
/// isolate.
class ServiceExtensionsWidget extends StatelessWidget {
const ServiceExtensionsWidget({super.key, required this.controller});
static final _name = _ServiceExtensionNameColumn();
static final _columns = <ColumnData<String>>[_name];
final IsolateStatisticsViewController controller;
@override
Widget build(BuildContext context) {
final extensions = controller.isolate?.extensionRPCs ?? [];
return OutlineDecoration(
showBottom: false,
showLeft: false,
child: VMInfoCard(
title: 'Service Extensions (${extensions.length})',
roundedTopBorder: false,
table: Flexible(
child: FlatTable<String>(
keyFactory: (String extension) => ValueKey<String>(extension),
data: extensions,
dataKey: 'registered-service-extensions',
columns: _columns,
defaultSortColumn: _name,
defaultSortDirection: SortDirection.ascending,
),
),
),
);
}
}
| devtools/packages/devtools_app/lib/src/screens/vm_developer/isolate_statistics/isolate_statistics_view.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/isolate_statistics/isolate_statistics_view.dart",
"repo_id": "devtools",
"token_count": 5863
} | 95 |
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app_shared/ui.dart';
import 'package:flutter/material.dart';
import 'package:vm_service/vm_service.dart';
import '../vm_developer_common_widgets.dart';
import 'object_inspector_view_controller.dart';
import 'vm_object_model.dart';
/// A widget for the object inspector historyViewport displaying information
/// related to library objects in the Dart VM.
class VmLibraryDisplay extends StatelessWidget {
const VmLibraryDisplay({
super.key,
required this.controller,
required this.library,
});
final ObjectInspectorViewController controller;
final LibraryObject library;
@override
Widget build(BuildContext context) {
final dependencies = library.obj.dependencies;
return ObjectInspectorCodeView(
codeViewController: controller.codeViewController,
script: library.scriptRef!,
object: library.obj,
child: VmObjectDisplayBasicLayout(
controller: controller,
object: library,
generalDataRows: _libraryDataRows(library),
expandableWidgets: [
if (dependencies != null)
LibraryDependencies(dependencies: dependencies),
],
),
);
}
/// Generates a list of key-value pairs (map entries) containing the general
/// information of the library object [library].
List<MapEntry<String, WidgetBuilder>> _libraryDataRows(
LibraryObject library,
) {
return [
...vmObjectGeneralDataRows(
controller,
library,
),
serviceObjectLinkBuilderMapEntry(
controller: controller,
key: 'URI',
preferUri: true,
object:
(library.obj.uri?.isEmpty ?? false) ? library.script! : library.obj,
),
selectableTextBuilderMapEntry(
'VM Name',
library.vmName,
),
];
}
}
/// An expandable tile displaying a list of library dependencies
class LibraryDependencies extends StatelessWidget {
const LibraryDependencies({
super.key,
required this.dependencies,
});
final List<LibraryDependency> dependencies;
List<Row> dependencyRows(BuildContext context) {
final textStyle = Theme.of(context).fixedFontStyle;
return <Row>[
for (final dep in dependencies)
Row(
children: [
Flexible(
child: SelectableText(
dep.description,
style: textStyle,
),
),
],
),
];
}
@override
Widget build(BuildContext context) {
return VmExpansionTile(
title: 'Dependencies (${dependencies.length})',
children: prettyRows(
context,
dependencyRows(context),
),
);
}
}
extension LibraryDependencyExtension on LibraryDependency {
String get description {
final description = StringBuffer();
void addSpace() => description.write(description.isEmpty ? '' : ' ');
final libIsImport = isImport;
if (libIsImport != null) {
description.write(libIsImport ? 'import' : 'export');
}
addSpace();
description.write(
target?.name ?? target?.uri ?? '<Library name>',
);
final libPrefix = prefix;
if (libPrefix != null && libPrefix.isNotEmpty) {
addSpace();
description.write('as $libPrefix');
}
if (isDeferred == true) {
addSpace();
description.write('deferred');
}
return description.toString();
}
}
| devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_library_display.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_library_display.dart",
"repo_id": "devtools",
"token_count": 1352
} | 96 |
// 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 'dart:math' as math;
import 'package:devtools_app_shared/service.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
import '../shared/analytics/analytics.dart' as ga;
import '../shared/analytics/constants.dart' as gac;
import '../shared/common_widgets.dart';
import '../shared/constants.dart';
import '../shared/globals.dart';
import '../shared/primitives/message_bus.dart';
import '../shared/primitives/utils.dart';
import '../shared/ui/colors.dart';
import '../shared/ui/hover.dart';
import 'service_extensions.dart';
import 'service_registrations.dart';
final _log = Logger('service_extension_widgets');
/// Data class tracking the state of a single service extension.
class ExtensionState {
ExtensionState(this.description);
final ToggleableServiceExtensionDescription description;
bool isSelected = false;
bool isAvailable = false;
}
/// Group of buttons where each button toggles the state of a VMService
/// extension.
///
/// Use this class any time you need to write UI code that exposes button(s) to
/// control VMServiceExtension. This class handles error handling and lifecycle
/// states for keeping state on the client and device consistent so you don't
/// have to.
class ServiceExtensionButtonGroup extends StatefulWidget {
const ServiceExtensionButtonGroup({
super.key,
this.minScreenWidthForTextBeforeScaling,
required this.extensions,
});
final double? minScreenWidthForTextBeforeScaling;
final List<ToggleableServiceExtensionDescription> extensions;
@override
State<ServiceExtensionButtonGroup> createState() =>
_ServiceExtensionButtonGroupState();
}
class _ServiceExtensionButtonGroupState
extends State<ServiceExtensionButtonGroup>
with
AutoDisposeMixin<ServiceExtensionButtonGroup>,
MainIsolateChangeMixin<ServiceExtensionButtonGroup> {
late List<ExtensionState> _extensionStates;
@override
void initState() {
super.initState();
// To use ToggleButtons we have to track states for all buttons in the
// group here rather than tracking state with the individual button widgets
// which would be more natural.
_initExtensionState();
}
@override
void _onMainIsolateChanged() => _initExtensionState();
void _initExtensionState() {
_extensionStates = [for (var e in widget.extensions) ExtensionState(e)];
for (var extension in _extensionStates) {
// Listen for changes to the state of each service extension using the
// VMServiceManager.
final extensionName = extension.description.extension;
// Update the button state to match the latest state on the VM.
final state = serviceConnection.serviceManager.serviceExtensionManager
.getServiceExtensionState(extensionName);
extension.isSelected = state.value.enabled;
addAutoDisposeListener(state, () {
setState(() {
extension.isSelected = state.value.enabled;
});
});
// Track whether the extension is actually exposed by the VM.
final listenable = serviceConnection
.serviceManager.serviceExtensionManager
.hasServiceExtension(extensionName);
extension.isAvailable = listenable.value;
addAutoDisposeListener(
listenable,
() {
setState(() {
extension.isAvailable = listenable.value;
});
},
);
}
}
@override
void didUpdateWidget(ServiceExtensionButtonGroup oldWidget) {
if (!listEquals(oldWidget.extensions, widget.extensions)) {
cancelListeners();
_initExtensionState();
}
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
// TODO(jacobr): respect _available better by displaying whether individual
// widgets are available (not currently supported by ToggleButtons).
final available = _extensionStates.any((e) => e.isAvailable);
return SizedBox(
height: defaultButtonHeight,
child: DevToolsToggleButtonGroup(
selectedStates: [for (var e in _extensionStates) e.isSelected],
onPressed: available ? _onPressed : null,
children: <Widget>[
for (var extensionState in _extensionStates)
ServiceExtensionButton(
extensionState: extensionState,
minScreenWidthForTextBeforeScaling:
widget.minScreenWidthForTextBeforeScaling,
),
],
),
);
}
void _onPressed(int index) {
final extensionState = _extensionStates[index];
if (extensionState.isAvailable) {
setState(() {
final gaScreenName = extensionState.description.gaScreenName;
final gaItem = extensionState.description.gaItem;
if (gaScreenName != null && gaItem != null) {
ga.select(gaScreenName, gaItem);
}
final wasSelected = extensionState.isSelected;
unawaited(
serviceConnection.serviceManager.serviceExtensionManager
.setServiceExtensionState(
extensionState.description.extension,
enabled: !wasSelected,
value: wasSelected
? extensionState.description.disabledValue
: extensionState.description.enabledValue,
),
);
});
} else {
// TODO(jacobr): display a toast warning that the extension is
// not available. That could happen as entire groups have to
// be enabled or disabled at a time.
}
}
}
class ServiceExtensionButton extends StatelessWidget {
const ServiceExtensionButton({
super.key,
required this.extensionState,
required this.minScreenWidthForTextBeforeScaling,
});
final ExtensionState extensionState;
final double? minScreenWidthForTextBeforeScaling;
@override
Widget build(BuildContext context) {
final description = extensionState.description;
return ServiceExtensionTooltip(
description: description,
child: Container(
height: defaultButtonHeight,
padding: EdgeInsets.symmetric(
horizontal:
isScreenWiderThan(context, minScreenWidthForTextBeforeScaling)
? defaultSpacing
: 0.0,
),
child: ImageIconLabel(
ServiceExtensionIcon(extensionState: extensionState),
description.title,
unscaledMinIncludeTextWidth: minScreenWidthForTextBeforeScaling,
),
),
);
}
}
/// Button that performs a hot reload on the [serviceConnection].
class HotReloadButton extends StatelessWidget {
const HotReloadButton({super.key, this.callOnVmServiceDirectly = false});
/// Whether to initiate hot reload via [VmService.reloadSources] instead of by
/// calling a registered service from Flutter.
final bool callOnVmServiceDirectly;
static const _hotReloadTooltip = 'Hot reload';
@override
Widget build(BuildContext context) {
// TODO(devoncarew): Show as disabled when reload service calls are in progress.
return callOnVmServiceDirectly
// We cannot use a [_RegisteredServiceExtensionButton] here because
// there is no hot reload service extension when we are calling hot
// reload directly on the VM service (e.g. for Dart CLI apps).
? _HotReloadScaffoldAction()
: DevToolsTooltip(
message: _hotReloadTooltip,
child: _RegisteredServiceExtensionButton._(
serviceDescription: hotReload,
action: _callHotReload,
completedText: 'Hot reload completed.',
describeError: (error) => 'Unable to hot reload the app: $error',
),
);
}
}
class _HotReloadScaffoldAction extends ScaffoldAction {
_HotReloadScaffoldAction({Color? color})
: super(
icon: hotReloadIcon,
tooltip: HotReloadButton._hotReloadTooltip,
color: color,
onPressed: (context) {
ga.select(gac.devToolsMain, gac.hotReload);
_callHotReload();
},
);
}
Future<void> _callHotReload() {
// The future is returned.
// ignore: discarded_futures
return serviceConnection.serviceManager.runDeviceBusyTask(
// The future is returned.
// ignore: discarded_futures
_wrapReloadCall(
'reload',
serviceConnection.serviceManager.performHotReload,
),
);
}
/// Button that performs a hot restart on the [serviceConnection].
class HotRestartButton extends StatelessWidget {
const HotRestartButton({super.key});
@override
Widget build(BuildContext context) {
// TODO(devoncarew): Show as disabled when reload service calls are in progress.
return DevToolsTooltip(
message: 'Hot restart',
child: _RegisteredServiceExtensionButton._(
serviceDescription: hotRestart,
action: () {
// The future is returned.
// ignore: discarded_futures
return serviceConnection.serviceManager.runDeviceBusyTask(
// The future is returned.
// ignore: discarded_futures
_wrapReloadCall(
'restart',
serviceConnection.serviceManager.performHotRestart,
),
);
},
completedText: 'Hot restart completed.',
describeError: (error) => 'Unable to hot restart the app: $error',
),
);
}
}
Future<void> _wrapReloadCall(
String name,
Future<void> Function() reloadCall,
) async {
try {
final Stopwatch timer = Stopwatch()..start();
messageBus.addEvent(BusEvent('$name.start'));
await reloadCall();
timer.stop();
// 'restarted in 1.6s'
final String message = '${name}ed in ${durationText(timer.elapsed)}';
messageBus.addEvent(BusEvent('$name.end', data: message));
// TODO(devoncarew): Add analytics.
//ga.select(ga.devToolsMain, ga.hotRestart, timer.elapsed.inMilliseconds);
} catch (_) {
final String message = 'error performing $name';
messageBus.addEvent(BusEvent('$name.end', data: message));
rethrow;
}
}
/// Button that when clicked invokes a VM Service , such as hot reload or hot
/// restart.
///
/// This button will attempt to register to the given service description.
class _RegisteredServiceExtensionButton extends ServiceExtensionWidget {
const _RegisteredServiceExtensionButton._({
required this.serviceDescription,
required this.action,
required String completedText,
required String Function(Object? error) describeError,
}) : super(completedText: completedText, describeError: describeError);
/// The service to subscribe to.
final RegisteredServiceDescription serviceDescription;
/// The action to perform when clicked.
final Future<void> Function() action;
@override
_RegisteredServiceExtensionButtonState createState() =>
_RegisteredServiceExtensionButtonState();
}
class _RegisteredServiceExtensionButtonState
extends State<_RegisteredServiceExtensionButton>
with ServiceExtensionMixin, AutoDisposeMixin {
bool _hidden = true;
@override
void initState() {
super.initState();
// Only show the button if the device supports the given service.
final serviceRegisteredListenable = serviceConnection.serviceManager
.registeredServiceListenable(widget.serviceDescription.service);
addAutoDisposeListener(serviceRegisteredListenable, () {
final registered = serviceRegisteredListenable.value;
setState(() {
_hidden = !registered;
});
});
}
@override
Widget build(BuildContext context) {
if (_hidden) return const SizedBox.shrink();
return InkWell(
onTap: () => unawaited(
invokeAndCatchErrors(() async {
final gaScreenName = widget.serviceDescription.gaScreenName;
final gaItem = widget.serviceDescription.gaItem;
if (gaScreenName != null && gaItem != null) {
ga.select(gaScreenName, gaItem);
}
await widget.action();
}),
),
child: Container(
constraints: BoxConstraints.tightFor(
width: actionWidgetSize,
height: actionWidgetSize,
),
alignment: Alignment.center,
// TODO(djshuckerow): Just make these icons the right size to fit this
// box. The current size is a little tiny by comparison to our other
// material icons.
child: widget.serviceDescription.icon,
),
);
}
}
/// Control that toggles the value of [structuredErrors].
class StructuredErrorsToggle extends StatelessWidget {
const StructuredErrorsToggle({super.key});
@override
Widget build(BuildContext context) {
return _ServiceExtensionToggle(
service: structuredErrors,
describeError: (error) =>
'Failed to update structuredError settings: $error',
);
}
}
/// [Switch] that stays synced with the value of a service extension.
///
/// Service extensions can be found in [service_extensions.dart].
class _ServiceExtensionToggle extends ServiceExtensionWidget {
const _ServiceExtensionToggle({
Key? key,
required this.service,
required String Function(Object?) describeError,
}) : super(
key: key,
// Don't show messages on success or when this toggle is in progress.
completedText: null,
describeError: describeError,
);
final ToggleableServiceExtensionDescription service;
@override
ServiceExtensionMixin<ServiceExtensionWidget> createState() =>
_ServiceExtensionToggleState();
}
class _ServiceExtensionToggleState extends State<_ServiceExtensionToggle>
with
ServiceExtensionMixin,
AutoDisposeMixin<_ServiceExtensionToggle>,
MainIsolateChangeMixin<_ServiceExtensionToggle> {
bool value = false;
@override
void initState() {
super.initState();
_initExtensionState();
}
@override
void _onMainIsolateChanged() => _initExtensionState();
void _initExtensionState() {
final state = serviceConnection.serviceManager.serviceExtensionManager
.getServiceExtensionState(widget.service.extension);
value = state.value.enabled;
addAutoDisposeListener(state, () {
setState(() {
value = state.value.enabled;
});
});
}
@override
Widget build(BuildContext context) {
return ServiceExtensionTooltip(
description: widget.service,
child: InkWell(
onTap: _onClick,
child: Row(
children: <Widget>[
DevToolsSwitch(
padding: const EdgeInsets.only(right: denseSpacing),
value: value,
onChanged: _onClick,
),
Text(widget.service.title),
],
),
),
);
}
void _onClick([_]) {
setState(() {
value = !value;
});
unawaited(
invokeAndCatchErrors(() async {
await serviceConnection.serviceManager.serviceExtensionManager
.setServiceExtensionState(
widget.service.extension,
enabled: value,
value: value
? widget.service.enabledValue
: widget.service.disabledValue,
);
}),
);
}
}
/// [Checkbox] that stays synced with the value of a service extension.
///
/// Service extensions can be found in [service_extensions.dart].
class ServiceExtensionCheckbox extends ServiceExtensionWidget {
ServiceExtensionCheckbox({
Key? key,
required this.serviceExtension,
this.showDescription = true,
}) : super(
key: key,
// Don't show messages on success or when this toggle is in progress.
completedText: null,
describeError: (error) => _errorMessage(
serviceExtension.extension,
error,
),
);
static String _errorMessage(String extensionName, Object? error) {
return 'Failed to update $extensionName setting: $error';
}
final ToggleableServiceExtensionDescription serviceExtension;
final bool showDescription;
@override
ServiceExtensionMixin<ServiceExtensionWidget> createState() =>
_ServiceExtensionCheckboxState();
}
class _ServiceExtensionCheckboxState extends State<ServiceExtensionCheckbox>
with
ServiceExtensionMixin,
AutoDisposeMixin<ServiceExtensionCheckbox>,
MainIsolateChangeMixin<ServiceExtensionCheckbox> {
/// Whether this checkbox value is set to true.
///
/// This notifier listens to extension state changes from the service manager
/// and will propagate those changes to the checkbox accordingly.
final value = ValueNotifier<bool>(false);
/// Whether the extension for this checkbox is available.
final extensionAvailable = ValueNotifier<bool>(false);
@override
void initState() {
super.initState();
_initExtensionState();
}
@override
void _onMainIsolateChanged() => _initExtensionState();
void _initExtensionState() {
if (serviceConnection.serviceManager.serviceExtensionManager
.isServiceExtensionAvailable(widget.serviceExtension.extension)) {
final state = serviceConnection.serviceManager.serviceExtensionManager
.getServiceExtensionState(widget.serviceExtension.extension);
_setValueFromState(state.value);
}
unawaited(
serviceConnection.serviceManager.serviceExtensionManager
.waitForServiceExtensionAvailable(widget.serviceExtension.extension)
.then((isServiceAvailable) {
if (isServiceAvailable) {
extensionAvailable.value = true;
final state = serviceConnection.serviceManager.serviceExtensionManager
.getServiceExtensionState(widget.serviceExtension.extension);
_setValueFromState(state.value);
addAutoDisposeListener(state, () {
_setValueFromState(state.value);
});
}
}),
);
}
void _setValueFromState(ServiceExtensionState state) {
final valueFromState = state.enabled;
value.value =
widget.serviceExtension.inverted ? !valueFromState : valueFromState;
}
@override
Widget build(BuildContext context) {
final docsUrl = widget.serviceExtension.documentationUrl;
return ValueListenableBuilder<bool>(
valueListenable: extensionAvailable,
builder: (context, available, _) {
return Row(
children: [
Expanded(
child: CheckboxSetting(
notifier: value,
title: widget.serviceExtension.title,
description: widget.showDescription
? widget.serviceExtension.description
: null,
tooltip: widget.serviceExtension.tooltip,
onChanged: _onChanged,
enabled: available,
gaScreenName: widget.serviceExtension.gaScreenName,
gaItem: widget.serviceExtension.gaItem,
),
),
if (docsUrl != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: denseSpacing),
child: MoreInfoLink(
url: docsUrl,
gaScreenName: widget.serviceExtension.gaScreenName!,
gaSelectedItemDescription:
widget.serviceExtension.gaDocsItem!,
padding: const EdgeInsets.symmetric(vertical: denseSpacing),
),
),
],
);
},
);
}
void _onChanged(bool? value) {
unawaited(
invokeAndCatchErrors(() async {
var enabled = value == true;
if (widget.serviceExtension.inverted) enabled = !enabled;
await serviceConnection.serviceManager.serviceExtensionManager
.setServiceExtensionState(
widget.serviceExtension.extension,
enabled: enabled,
value: enabled
? widget.serviceExtension.enabledValue
: widget.serviceExtension.disabledValue,
);
}),
);
}
}
/// A button that, when pressed, will display an overlay directly below that has
/// a list of service extension checkbox settings.
class ServiceExtensionCheckboxGroupButton extends StatefulWidget {
ServiceExtensionCheckboxGroupButton({
Key? key,
required this.title,
required this.icon,
required this.extensions,
required this.overlayDescription,
this.forceShowOverlayController,
this.customExtensionUi = const <String, Widget>{},
this.tooltip,
double overlayWidthBeforeScaling = _defaultWidth,
this.minScreenWidthForTextBeforeScaling,
}) : overlayWidth = scaleByFontFactor(overlayWidthBeforeScaling),
super(key: key);
/// Title for the button.
final String title;
/// Icon for the button.
final IconData icon;
/// The minimum screen width for which this button should include text.
final double? minScreenWidthForTextBeforeScaling;
/// Extensions to be surfaced as checkbox settings in the overlay.
final List<ToggleableServiceExtensionDescription> extensions;
/// Maps service extensions to custom visualizations.
///
/// If this map does not contain an entry for a service extension,
/// [ServiceExtensionCheckbox] will be used to build the service extension
/// setting in [_ServiceExtensionCheckboxGroupOverlay].
final Map<String, Widget> customExtensionUi;
/// Description for the checkbox settings overlay.
///
/// This may contain instructions, a warning, or any message that is helpful
/// to describe what the settings in this overlay are for. This widget should
/// likely be a [Text] or [RichText] widget, but any widget can be used here.
final Widget overlayDescription;
final StreamController<void>? forceShowOverlayController;
final String? tooltip;
final double overlayWidth;
static const _defaultWidth = 600.0;
@override
State<ServiceExtensionCheckboxGroupButton> createState() =>
_ServiceExtensionCheckboxGroupButtonState();
}
class _ServiceExtensionCheckboxGroupButtonState
extends State<ServiceExtensionCheckboxGroupButton>
with
AutoDisposeMixin<ServiceExtensionCheckboxGroupButton>,
MainIsolateChangeMixin<ServiceExtensionCheckboxGroupButton> {
static const _hoverYOffset = 10.0;
/// Whether this button should have the enabled state, which makes the
/// button appear with an enabled background color to indicate some
/// non-default options are enabled.
final _enabled = ValueNotifier(false);
late List<bool> _extensionStates;
OverlayEntry? _overlay;
bool _overlayHovered = false;
@override
void initState() {
super.initState();
_initExtensionState();
}
@override
void _onMainIsolateChanged() => _initExtensionState();
void _initExtensionState() {
_extensionStates = List.filled(widget.extensions.length, false);
for (int i = 0; i < widget.extensions.length; i++) {
final extension = widget.extensions[i];
final state = serviceConnection.serviceManager.serviceExtensionManager
.getServiceExtensionState(extension.extension);
_extensionStates[i] = state.value.enabled;
// Listen for extension state changes so that we can update the value of
// [_activated].
addAutoDisposeListener(state, () {
_extensionStates[i] = state.value.enabled;
_enabled.value = _isEnabled();
});
}
_enabled.value = _isEnabled();
if (widget.forceShowOverlayController != null) {
cancelStreamSubscriptions();
autoDisposeStreamSubscription(
widget.forceShowOverlayController!.stream.listen(
(_) => _insertOverlay(context),
),
);
}
}
bool _isEnabled() {
for (final state in _extensionStates) {
if (state) {
return true;
}
}
return false;
}
@override
Widget build(BuildContext context) {
Widget label = Padding(
padding: const EdgeInsets.symmetric(horizontal: defaultSpacing),
child: MaterialIconLabel(
label: widget.title,
iconData: widget.icon,
minScreenWidthForTextBeforeScaling:
widget.minScreenWidthForTextBeforeScaling,
),
);
if (widget.tooltip != null && widget.tooltip!.isNotEmpty) {
label = DevToolsTooltip(message: widget.tooltip, child: label);
}
return ValueListenableBuilder<bool>(
valueListenable: _enabled,
builder: (context, enabled, _) {
return DevToolsToggleButtonGroup(
selectedStates: [enabled],
onPressed: (_) => _insertOverlay(context),
children: [label],
);
},
);
}
/// Inserts an overlay with service extension toggles that will enhance the
/// timeline trace.
///
/// The overlay will appear directly below the button, and will be dismissed
/// if there is a click outside of the list of toggles.
void _insertOverlay(BuildContext context) {
final width = math.min(
widget.overlayWidth,
MediaQuery.of(context).size.width - 2 * denseSpacing,
);
final offset = _calculateOverlayPosition(width, context);
_overlay?.remove();
Overlay.of(context).insert(
_overlay = OverlayEntry(
maintainState: true,
builder: (context) {
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: _maybeRemoveOverlay,
child: Stack(
children: [
Positioned(
left: offset.dx,
top: offset.dy,
child: MouseRegion(
onEnter: _mouseEnter,
onExit: _mouseExit,
child: _ServiceExtensionCheckboxGroupOverlay(
description: widget.overlayDescription,
extensions: widget.extensions,
width: width,
customExtensionUi: widget.customExtensionUi,
),
),
),
],
),
);
},
),
);
}
Offset _calculateOverlayPosition(double width, BuildContext context) {
final overlayBox =
Overlay.of(context).context.findRenderObject() as RenderBox;
final box = context.findRenderObject() as RenderBox;
final maxX = overlayBox.size.width - width - denseSpacing;
final maxY = overlayBox.size.height;
final offset = box.localToGlobal(
box.size.bottomCenter(Offset.zero).translate(-width / 2, _hoverYOffset),
ancestor: overlayBox,
);
return Offset(
offset.dx.clamp(denseSpacing, maxX),
offset.dy.clamp(0.0, maxY),
);
}
void _mouseEnter(PointerEnterEvent _) {
_overlayHovered = true;
}
void _mouseExit(PointerExitEvent _) {
_overlayHovered = false;
}
void _maybeRemoveOverlay() {
if (!_overlayHovered) {
_overlay?.remove();
_overlay = null;
}
}
}
class _ServiceExtensionCheckboxGroupOverlay extends StatelessWidget {
const _ServiceExtensionCheckboxGroupOverlay({
Key? key,
required this.description,
required this.extensions,
required this.width,
this.customExtensionUi = const <String, Widget>{},
}) : super(key: key);
/// Description for this checkbox settings overlay.
///
/// This may contain instructions, a warning, or any message that is helpful
/// to describe what the settings in this overlay are for. This widget should
/// likely be a [Text] or [RichText] widget, but any widget can be used here.
final Widget description;
final List<ToggleableServiceExtensionDescription> extensions;
final double width;
/// Maps service extensions to custom visualizations.
///
/// If this map does not contain an entry for a service extension,
/// [ServiceExtensionCheckbox] will be used to build the service extension
/// setting.
final Map<String, Widget> customExtensionUi;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Material(
child: PointerInterceptor(
child: Container(
width: width,
padding: const EdgeInsets.all(defaultSpacing),
decoration: BoxDecoration(
color: theme.colorScheme.defaultBackgroundColor,
border: Border.all(
color: theme.focusColor,
width: hoverCardBorderSize,
),
borderRadius: defaultBorderRadius,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
description,
const SizedBox(height: denseSpacing),
for (final serviceExtension in extensions)
_extensionSetting(serviceExtension),
],
),
),
),
);
}
Widget _extensionSetting(ToggleableServiceExtensionDescription extension) {
assert(extensions.contains(extension));
final customUi = customExtensionUi[extension.extension];
return customUi ?? ServiceExtensionCheckbox(serviceExtension: extension);
}
}
/// Widget that knows how to talk to a service extension and surface the relevant errors.
abstract class ServiceExtensionWidget extends StatefulWidget {
const ServiceExtensionWidget({
Key? key,
required this.completedText,
required this.describeError,
}) : super(key: key);
/// The text to show when the action is completed.
///
/// This will be shown in a [SnackBar], replacing the [inProgressText].
final String? completedText;
/// Callback that describes any error that occurs.
///
/// This will replace the [inProgressText] in a [SnackBar].
final String Function(Object? error) describeError;
@override
ServiceExtensionMixin<ServiceExtensionWidget> createState();
}
/// State mixin that manages calling an async service extension and reports
/// errors.
mixin ServiceExtensionMixin<T extends ServiceExtensionWidget> on State<T> {
/// Whether an action is currently in progress.
///
/// When [disabled], [invokeAndCatchErrors] will not accept new actions.
@protected
bool disabled = false;
/// Invokes [action], showing [SnackBar]s for the action's progress,
/// completion, and any errors it produces.
@protected
Future<void> invokeAndCatchErrors(Future<void> Function() action) async {
if (disabled) {
return;
}
setState(() {
disabled = true;
});
try {
await action();
if (mounted && widget.completedText != null) {
notificationService.push(widget.completedText!);
}
} catch (e, st) {
_log.info(e, e, st);
if (mounted) {
notificationService.push(widget.describeError(e));
}
} finally {
if (mounted) {
setState(() {
disabled = false;
});
}
}
}
}
class ServiceExtensionTooltip extends StatelessWidget {
const ServiceExtensionTooltip({
Key? key,
required this.description,
required this.child,
}) : super(key: key);
final ToggleableServiceExtensionDescription description;
final Widget child;
@override
Widget build(BuildContext context) {
if (description.documentationUrl != null) {
return ServiceExtensionRichTooltip(
description: description,
child: child,
);
}
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final focusColor = theme.focusColor;
return DevToolsTooltip(
message: description.tooltip,
preferBelow: true,
decoration: BoxDecoration(
color: colorScheme.surface,
border: Border.all(
color: focusColor,
width: hoverCardBorderSize,
),
borderRadius: defaultBorderRadius,
),
textStyle: theme.regularTextStyle.copyWith(color: colorScheme.onSurface),
child: child,
);
}
}
/// Rich tooltip with a description and "more info" link
class ServiceExtensionRichTooltip extends StatelessWidget {
const ServiceExtensionRichTooltip({
Key? key,
required this.description,
required this.child,
}) : super(key: key);
final ToggleableServiceExtensionDescription description;
final Widget child;
static const double _tooltipWidth = 300.0;
@override
Widget build(BuildContext context) {
return HoverCardTooltip.sync(
enabled: () => true,
generateHoverCardData: (_) => _buildCardData(),
child: child,
);
}
HoverCardData _buildCardData() {
return HoverCardData(
position: HoverCardPosition.element,
width: _tooltipWidth,
contents: Material(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
description.tooltip,
),
if (description.documentationUrl != null &&
description.gaScreenName != null)
Align(
alignment: Alignment.bottomRight,
child: MoreInfoLink(
url: description.documentationUrl!,
gaScreenName: description.gaScreenName!,
gaSelectedItemDescription: description.gaItemTooltipLink,
),
),
],
),
),
);
}
}
class ServiceExtensionIcon extends StatelessWidget {
const ServiceExtensionIcon({required this.extensionState, super.key});
final ExtensionState extensionState;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final color = extensionState.isSelected
? theme.colorScheme.primary
: theme.colorScheme.onSurface;
final description = extensionState.description;
if (description.iconData != null) {
return Icon(
description.iconData,
color: color,
);
}
return Image(
image: AssetImage(extensionState.description.iconAsset!),
height: defaultIconSize,
width: defaultIconSize,
color: color,
);
}
}
mixin MainIsolateChangeMixin<T extends StatefulWidget>
on State<T>, AutoDisposeMixin<T> {
static const _mainIsolateListenerId = 'mainIsolateListener';
@override
void initState() {
super.initState();
addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.mainIsolate,
() {
setState(() {
cancelListeners(excludeIds: [_mainIsolateListenerId]);
_onMainIsolateChanged();
});
},
_mainIsolateListenerId,
);
}
void _onMainIsolateChanged();
}
// TODO(jacobr): port these classes to Flutter.
/*
/// Dropdown selector that calls a service extension.
///
/// Service extensions can be found in [service_extensions.dart].
class ServiceExtensionSelector {
ServiceExtensionSelector(this.extensionDescription) : selector = PSelect() {
selector
..small()
..clazz('button-bar-dropdown')
..change(_handleSelect)
..tooltip = extensionDescription.tooltips.first ??
extensionDescription.description;
final extensionName = extensionDescription.extension;
// Disable selector for unavailable service extensions.
selector.disabled = !serviceManager.manager.serviceExtensionManager
.isServiceExtensionAvailable(extensionName);
serviceManager.manager.serviceExtensionManager.hasServiceExtension(
extensionName, (available) => selector.disabled = !available);
addOptions();
updateState();
}
final ServiceExtensionDescription extensionDescription;
final PSelect selector;
String _selectedValue;
void _handleSelect() {
if (selector.value == _selectedValue) return;
ga.select(extensionDescription.gaScreenName, extensionDescription.gaItem);
final extensionValue = extensionDescription
.values[extensionDescription.displayValues.indexOf(selector.value)];
serviceManager.manager.serviceExtensionManager.setServiceExtensionState(
extensionDescription.extension,
true,
extensionValue,
);
_selectedValue = selector.value;
}
void addOptions() {
extensionDescription.displayValues.forEach(selector.option);
}
void updateState() {
// Select option whose state is already enabled.
serviceManager.manager.serviceExtensionManager
.getServiceExtensionState(extensionDescription.extension, (state) {
updateSelection(state);
});
}
void updateSelection(ServiceExtensionState state) {
if (state.value != null) {
final selectedIndex = extensionDescription.values.indexOf(state.value);
selector.selectedIndex = selectedIndex;
_selectedValue = extensionDescription.displayValues[selectedIndex];
}
}
}
class TogglePlatformSelector extends ServiceExtensionSelector {
TogglePlatformSelector() : super(togglePlatformMode);
static const fuchsia = 'Fuchsia';
@override
void addOptions() {
extensionDescription.displayValues
.where((displayValue) => !displayValue.contains(fuchsia))
.forEach(selector.option);
}
@override
void updateState() {
// Select option whose state is already enabled.
serviceManager.manager.serviceExtensionManager
.getServiceExtensionState(extensionDescription.extension, (state) {
if (state.value == fuchsia.toLowerCase()) {
selector.option(extensionDescription.displayValues
.firstWhere((displayValue) => displayValue.contains(fuchsia)));
}
updateSelection(state);
});
}
}
*/
| devtools/packages/devtools_app/lib/src/service/service_extension_widgets.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/service/service_extension_widgets.dart",
"repo_id": "devtools",
"token_count": 13963
} | 97 |
// 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_shared/devtools_extensions.dart';
import '../screen.dart';
part 'constants/_cpu_profiler_constants.dart';
part 'constants/_deep_links_constants.dart';
part 'constants/_extension_constants.dart';
part 'constants/_memory_constants.dart';
part 'constants/_performance_constants.dart';
part 'constants/_vs_code_sidebar_constants.dart';
part 'constants/_inspector_constants.dart';
// Type of events (event_category):
const screenViewEvent = 'screen'; // Active screen (tab selected).
const selectEvent = 'select'; // User selected something.
const timingEvent = 'timing'; // Timed operation.
const impressionEvent = 'impression'; // Something was viewed.
// DevTools GA screenNames:
// These screen ids must match the `screenId` for each respective subclass of
// [Screen]. This is to ensure that the analytics for documentation links match
// the screen id for other analytics on the same screen.
final home = ScreenMetaData.home.id;
final inspector = ScreenMetaData.inspector.id;
final performance = ScreenMetaData.performance.id;
final cpuProfiler = ScreenMetaData.cpuProfiler.id;
final memory = ScreenMetaData.memory.id;
final network = ScreenMetaData.network.id;
final debugger = ScreenMetaData.debugger.id;
final logging = ScreenMetaData.logging.id;
final appSize = ScreenMetaData.appSize.id;
final vmTools = ScreenMetaData.vmTools.id;
const console = 'console';
final simple = ScreenMetaData.simple.id;
final deeplink = ScreenMetaData.deepLinks.id;
// GA events not associated with a any screen e.g., hotReload, hotRestart, etc
const devToolsMain = 'main';
const appDisconnected = 'appDisconnected';
// DevTools UI action selected (clicked).
// Main bar UX actions:
const hotReload = 'hotReload';
const hotRestart = 'hotRestart';
const importFile = 'importFile';
const feedbackLink = 'feedback';
const feedbackButton = 'feedbackButton';
const contributingLink = 'contributing';
const discordLink = 'discord';
// Inspector UX actions:
const refresh = 'refresh';
const refreshEmptyTree = 'refreshEmptyTree';
const debugPaint = 'debugPaint';
const debugPaintDocs = 'debugPaintDocs';
const paintBaseline = 'paintBaseline';
const paintBaselineDocs = 'paintBaselineDocs';
const slowAnimation = 'slowAnimation';
const slowAnimationDocs = 'slowAnimationDocs';
const repaintRainbow = 'repaintRainbow';
const repaintRainbowDocs = 'repaintRainbowDocs';
const debugBanner = 'debugBanner';
const togglePlatform = 'togglePlatform';
const highlightOversizedImages = 'highlightOversizedImages';
const highlightOversizedImagesDocs = 'highlightOversizedImagesDocs';
const selectWidgetMode = 'selectWidgetMode';
const enableOnDeviceInspector = 'enableOnDeviceInspector';
const showOnDeviceInspector = 'showInspector';
const treeNodeSelection = 'treeNodeSelection';
const inspectorSettings = 'inspectorSettings';
const loggingSettings = 'loggingSettings';
const refreshPubRoots = 'refreshPubRoots';
enum HomeScreenEvents {
connectToApp,
connectToNewApp,
viewVmFlags,
}
// Debugger UX actions:
const refreshStatistics = 'refreshStatistics';
const showFileExplorer = 'showFileExplorer';
const hideFileExplorer = 'hideFileExplorer';
const pausedWithNoFrames = 'pausedWithNoFrames';
// Logging UX actions:
const structuredErrors = 'structuredErrors';
const trackRebuildWidgets = 'trackRebuildWidgets';
// App Size Tools UX actions:
const importFileSingle = 'importFileSingle';
const importFileDiffFirst = 'importFileDiffFirst';
const importFileDiffSecond = 'importFileDiffSecond';
const analyzeSingle = 'analyzeSingle';
const analyzeDiff = 'analyzeDiff';
// VM Tools UX Actions:
const refreshIsolateStatistics = 'refreshIsolateStatistics';
const refreshVmStatistics = 'refreshVmStatistics';
const refreshProcessMemoryStatistics = 'refreshProcessMemoryStatistics';
const requestSize = 'requestSize';
// Settings actions:
const settingsDialog = 'settings';
const darkTheme = 'darkTheme';
const denseMode = 'denseMode';
const analytics = 'analytics';
const vmDeveloperMode = 'vmDeveloperMode';
const verboseLogging = 'verboseLogging';
const inspectorHoverEvalMode = 'inspectorHoverEvalMode';
const clearLogs = 'clearLogs';
const copyLogs = 'copyLogs';
// Object explorer:
const objectInspectorScreen = 'objectInspector';
const objectInspectorDropDown = 'dropdown';
const programExplorer = 'programExplorer';
const objectStore = 'objectStore';
const classHierarchy = 'classHierarchy';
// Network Events:
const inspectorTreeControllerInitialized = 'InspectorTreeControllerInitialized';
const inspectorTreeControllerRootChange = 'InspectorTreeControllerRootChange';
// Common actions shared across screens.
// These actions will be tracked per screen, so they will still be
// distinguishable from one screen to the other.
const pause = 'pause';
const resume = 'resume';
const clear = 'clear';
const record = 'record';
const stop = 'stop';
const openFile = 'openFile';
const saveFile = 'saveFile';
const expandAll = 'expandAll';
const collapseAll = 'collapseAll';
const profileModeDocs = 'profileModeDocs';
const visibilityButton = 'visibilityButton';
const exitOfflineMode = 'exitOfflineMode';
// This should track the time from `initState` for a screen to the time when
// the page data has loaded and is ready to interact with.
const pageReady = 'pageReady';
/// Documentation actions shared across screens.
const documentationLink = 'documentationLink';
const videoTutorialLink = 'videoTutorialLink';
String topicDocumentationButton(String topic) => '${topic}DocumentationButton';
String topicDocumentationLink(String topic) => '${topic}DocumentationLink';
/// Analytic event constants specific for console.
class ConsoleEvent {
static const helpInline = 'consoleHelpInline';
static const String evalInStoppedApp = 'consoleEvalInStoppedApp';
static const String evalInRunningApp = 'consoleEvalInRunningApp';
}
| devtools/packages/devtools_app/lib/src/shared/analytics/constants.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/analytics/constants.dart",
"repo_id": "devtools",
"token_count": 1669
} | 98 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'package:collection/collection.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../common_widgets.dart';
import '../primitives/extent_delegate_list.dart';
import '../primitives/flutter_widgets/linked_scroll_controller.dart';
import '../primitives/trees.dart';
import '../primitives/utils.dart';
import '../ui/colors.dart';
import '../ui/search.dart';
import '../ui/utils.dart';
import '../utils.dart';
const double rowPadding = 2.0;
// Flame chart rows contain text so are not readable if they do not scale with
// the font factor.
double get chartRowHeight => scaleByFontFactor(22.0);
double get rowHeightWithPadding => chartRowHeight + rowPadding;
// This spacing needs to be scaled by the font factor otherwise section
// labels will not have enough room. Typically spacing values should not depend
// on the font size scale factor. TODO(jacobr): clean up the section spacing so
// it is not used in a case where it is not really spacing.
double get sectionSpacing => scaleByFontFactor(16.0);
const double sideInset = 70.0;
const double sideInsetSmall = 60.0;
double get baseTimelineGridIntervalPx => scaleByFontFactor(150.0);
// TODO(kenz): add some indication that we are scrolled out of the relevant area
// so that users don't get lost in the extra pixels at the end of the chart.
// TODO(kenz): consider cleaning up by changing to a flame chart code to use a
// composition pattern instead of a class extension pattern.
abstract class FlameChart<T, V> extends StatefulWidget {
const FlameChart(
this.data, {
super.key,
required this.time,
required this.containerWidth,
required this.containerHeight,
required this.selectionNotifier,
required this.onDataSelected,
this.searchMatchesNotifier,
this.activeSearchMatchNotifier,
this.startInset = sideInset,
this.endInset = sideInset,
});
static const minZoomLevel = 1.0;
static const zoomMultiplier = 0.01;
static const minScrollOffset = 0.0;
static const rowOffsetForBottomPadding = 1;
static const rowOffsetForSectionSpacer = 1;
/// Maximum scroll delta allowed for scroll wheel based zooming.
///
/// This isn't really needed but is a reasonable for safety in case we
/// aren't handling some mouse based scroll wheel behavior well, etc.
static const double maxScrollWheelDelta = 20.0;
final T data;
final TimeRange time;
final double containerWidth;
final double containerHeight;
final double startInset;
final double endInset;
final ValueListenable<V?> selectionNotifier;
final ValueListenable<List<V>>? searchMatchesNotifier;
final ValueListenable<V?>? activeSearchMatchNotifier;
final void Function(V data) onDataSelected;
double get startingContentWidth => containerWidth - startInset - endInset;
}
// TODO(kenz): cap number of nodes we can show per row at once - need this for
// performance improvements. Optionally we could also do something clever with
// grouping nodes that are close together until they are zoomed in (quad tree
// like implementation).
abstract class FlameChartState<T extends FlameChart,
V extends FlameChartDataMixin<V>> extends State<T>
with AutoDisposeMixin, FlameChartColorMixin, TickerProviderStateMixin {
int get rowOffsetForTopPadding => 2;
// The "top" positional value for each flame chart node will be 0.0 because
// each node is positioned inside its own list.
final flameChartNodeTop = 0.0;
final List<FlameChartRow<V>> rows = [];
final List<FlameChartSection> sections = [];
final focusNode = FocusNode(debugLabel: 'flame-chart');
double? mouseHoverX;
final _hoveredNodeNotifier = ValueNotifier<V?>(null);
late final FixedExtentDelegate verticalExtentDelegate;
late final LinkedScrollControllerGroup verticalControllerGroup;
late final LinkedScrollControllerGroup horizontalControllerGroup;
late final ScrollController _verticalFlameChartScrollController;
/// Animation controller for animating flame chart zoom changes.
@visibleForTesting
late final AnimationController zoomController;
double currentZoom = FlameChart.minZoomLevel;
double horizontalScrollOffset = FlameChart.minScrollOffset;
double verticalScrollOffset = FlameChart.minScrollOffset;
// Scrolling via WASD controls will pan the left/right 25% of the view.
double get keyboardScrollUnit => widget.containerWidth * 0.25;
// Zooming in via WASD controls will zoom the view in by 50% on each zoom. For
// example, if the zoom level is 2.0, zooming by one unit would increase the
// level to 3.0 (e.g. 2 + (2 * 0.5) = 3).
double get keyboardZoomInUnit => currentZoom * 0.5;
// Zooming out via WASD controls will zoom the view out to the previous zoom
// level. For example, if the zoom level is 3.0, zooming out by one unit would
// decrease the level to 2.0 (e.g. 3 - 3 * 1/3 = 2). See [wasdZoomInUnit]
// for an explanation of how we previously zoomed from level 2.0 to level 3.0.
double get keyboardZoomOutUnit => currentZoom * 1 / 3;
double get contentWidthWithZoom => widget.startingContentWidth * currentZoom;
double get widthWithZoom =>
contentWidthWithZoom + widget.startInset + widget.endInset;
TimeRange get visibleTimeRange {
final horizontalScrollOffset = horizontalControllerGroup.offset;
final startMicros = horizontalScrollOffset < widget.startInset
? startTimeOffset
: startTimeOffset +
(horizontalScrollOffset - widget.startInset) /
currentZoom /
startingPxPerMicro;
final endMicros = startTimeOffset +
(horizontalScrollOffset - widget.startInset + widget.containerWidth) /
currentZoom /
startingPxPerMicro;
return TimeRange()
..start = Duration(microseconds: startMicros.round())
..end = Duration(microseconds: endMicros.round());
}
/// Starting pixels per microsecond in order to fit all the data in view at
/// start.
double get startingPxPerMicro =>
widget.startingContentWidth / widget.time.duration.inMicroseconds;
int get startTimeOffset => widget.time.start!.inMicroseconds;
double get maxZoomLevel {
// The max zoom level is hit when 1 microsecond is the width of each grid
// interval (this may bottom out at 2 micros per interval due to rounding).
return math.max(
FlameChart.minZoomLevel,
baseTimelineGridIntervalPx *
widget.time.duration.inMicroseconds /
widget.startingContentWidth,
);
}
/// Provides widgets to be layered on top of the flame chart, if overridden.
///
/// The widgets will be layered in a [Stack] in the order that they are
/// returned.
List<Widget> buildChartOverlays(
BoxConstraints constraints,
BuildContext buildContext,
) {
return const [];
}
@override
void initState() {
super.initState();
initFlameChartElements();
horizontalControllerGroup = LinkedScrollControllerGroup();
verticalControllerGroup = LinkedScrollControllerGroup();
addAutoDisposeListener(horizontalControllerGroup.offsetNotifier, () {
setState(() {
horizontalScrollOffset = horizontalControllerGroup.offset;
});
});
addAutoDisposeListener(verticalControllerGroup.offsetNotifier, () {
setState(() {
verticalScrollOffset = verticalControllerGroup.offset;
});
});
_verticalFlameChartScrollController = verticalControllerGroup.addAndGet();
zoomController = AnimationController(
value: FlameChart.minZoomLevel,
lowerBound: FlameChart.minZoomLevel,
upperBound: maxZoomLevel,
vsync: this,
)..addListener(_handleZoomControllerValueUpdate);
verticalExtentDelegate = FixedExtentDelegate(
computeExtent: (index) =>
rows[index].nodes.isEmpty ? sectionSpacing : rowHeightWithPadding,
computeLength: () => rows.length,
);
if (widget.activeSearchMatchNotifier != null) {
addAutoDisposeListener(widget.activeSearchMatchNotifier, () async {
final activeSearch = widget.activeSearchMatchNotifier!.value as V?;
if (activeSearch == null) return;
// Ensure the [activeSearch] is vertically in view.
if (!isDataVerticallyInView(activeSearch)) {
await scrollVerticallyToData(activeSearch);
}
// TODO(kenz): zoom if the event is less than some min width.
// Ensure the [activeSearch] is horizontally in view.
if (!isDataHorizontallyInView(activeSearch)) {
await scrollHorizontallyToData(activeSearch);
}
});
}
autoDisposeFocusNode(focusNode);
}
@override
void didUpdateWidget(T oldWidget) {
if (widget.data != oldWidget.data) {
initFlameChartElements();
horizontalControllerGroup.resetScroll();
verticalControllerGroup.resetScroll();
zoomController.reset();
verticalExtentDelegate.recompute();
}
FocusScope.of(context).requestFocus(focusNode);
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
zoomController.dispose();
_verticalFlameChartScrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MouseRegion(
onHover: _handleMouseHover,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: _handleTapUp,
child: Focus(
autofocus: true,
focusNode: focusNode,
onKeyEvent: (node, event) => _handleKeyEvent(event),
// Scrollbar needs to wrap [LayoutBuilder] so that the scroll bar is
// rendered on top of the custom painters defined in [buildCustomPaints]
child: Scrollbar(
controller: _verticalFlameChartScrollController,
thumbVisibility: true,
child: LayoutBuilder(
builder: (context, constraints) {
final chartOverlays = buildChartOverlays(constraints, context);
final flameChart = _buildFlameChart(constraints);
return chartOverlays.isNotEmpty
? Stack(
children: [
flameChart,
...chartOverlays,
],
)
: flameChart;
},
),
),
),
),
);
}
Widget _buildFlameChart(BoxConstraints constraints) {
return ExtentDelegateListView(
physics: const ClampingScrollPhysics(),
controller: _verticalFlameChartScrollController,
extentDelegate: verticalExtentDelegate,
childrenDelegate: SliverChildBuilderDelegate(
(context, index) {
final nodes = rows[index].nodes;
var rowBackgroundColor = Colors.transparent;
if (index >= rowOffsetForTopPadding && nodes.isEmpty) {
// If this is a spacer row, we should use the background color of
// the previous row with nodes.
for (int i = index; i >= rowOffsetForTopPadding; i--) {
// Look back until we find the first non-empty row.
if (rows[i].nodes.isNotEmpty) {
rowBackgroundColor = alternatingColorForIndex(
rows[i].nodes.first.sectionIndex,
Theme.of(context).colorScheme,
);
break;
}
}
} else if (nodes.isNotEmpty) {
rowBackgroundColor = alternatingColorForIndex(
nodes.first.sectionIndex,
Theme.of(context).colorScheme,
);
}
// TODO(polinach): figure out how to get rid of the type cast.
// See https://github.com/flutter/devtools/pull/3738#discussion_r817135162
return ScrollingFlameChartRow<V>(
linkedScrollControllerGroup: horizontalControllerGroup,
nodes: nodes,
width: math.max(constraints.maxWidth, widthWithZoom),
startInset: widget.startInset,
hoveredNotifier: _hoveredNodeNotifier,
selectionNotifier: widget.selectionNotifier as ValueListenable<V?>,
searchMatchesNotifier:
widget.searchMatchesNotifier as ValueListenable<List<V>>?,
activeSearchMatchNotifier:
widget.activeSearchMatchNotifier as ValueListenable<V?>?,
backgroundColor: rowBackgroundColor,
zoom: currentZoom,
);
},
childCount: rows.length,
addAutomaticKeepAlives: false,
),
);
}
// This method must be overridden by all subclasses.
@mustCallSuper
void initFlameChartElements() {
rows.clear();
sections.clear();
}
void expandRows(int newRowLength) {
final currentLength = rows.length;
for (int i = currentLength; i < newRowLength; i++) {
rows.add(FlameChartRow<V>(i));
}
}
void _handleMouseHover(PointerHoverEvent event) {
mouseHoverX = event.localPosition.dx;
final mouseHoverY = event.localPosition.dy;
final topPaddingHeight = rowOffsetForTopPadding * sectionSpacing;
if (mouseHoverY <= topPaddingHeight) {
_hoveredNodeNotifier.value = null;
return;
}
final nodes = _nodesForRowAtY(mouseHoverY);
if (nodes == null) {
_hoveredNodeNotifier.value = null;
return;
}
final hoverNodeData = _binarySearchForNode(
x: event.localPosition.dx + horizontalControllerGroup.offset,
nodesInRow: nodes,
)?.data;
_hoveredNodeNotifier.value = hoverNodeData;
}
/// Returns the nodes for the row at the given [dy] mouse position.
///
/// Returns null if there is not a row at the given position.
List<FlameChartNode<V>>? _nodesForRowAtY(double dy) {
final rowIndex = _rowIndexForY(dy);
if (rowIndex == -1) {
return null;
}
return rows[rowIndex].nodes;
}
/// Returns the flame chart row index for the given [dy] mouse position.
///
/// Returns -1 if the row index is out of range for [rows].
int _rowIndexForY(double dy) {
final topPaddingHeight = rowOffsetForTopPadding * sectionSpacing;
final adjustedDy = verticalControllerGroup.offset + dy;
final rowIndex = ((adjustedDy - topPaddingHeight) ~/ rowHeightWithPadding) +
rowOffsetForTopPadding;
if (rowIndex < 0 || rowIndex >= rows.length) {
return -1;
}
return rowIndex;
}
void _handleTapUp(TapUpDetails details) {
final referenceBox = context.findRenderObject() as RenderBox;
final tapPosition = referenceBox.globalToLocal(details.globalPosition);
final nodes = _nodesForRowAtY(tapPosition.dy);
if (nodes != null) {
final nodeToSelect = _binarySearchForNode(
x: tapPosition.dx + horizontalControllerGroup.offset,
nodesInRow: nodes,
);
nodeToSelect?.onSelected(nodeToSelect.data);
}
focusNode.requestFocus();
}
FlameChartNode<V>? _binarySearchForNode({
required double x,
required List<FlameChartNode<V>> nodesInRow,
}) {
return binarySearchForNodeHelper(
x: x,
nodesInRow: nodesInRow,
zoom: currentZoom,
startInset: widget.startInset,
);
}
KeyEventResult _handleKeyEvent(KeyEvent event) {
if (!event.isKeyDownOrRepeat) return KeyEventResult.ignored;
// Only handle down events so logic is not duplicated on key up.
// TODO(kenz): zoom in/out faster if key is held. It actually zooms slower
// if the key is held currently.
// Handle zooming / navigation from WASD keys. Use physical keys to match
// other keyboard mappings like Dvorak, for which these keys would
// translate to ,AOE keys. See
// https://api.flutter.dev/flutter/services/KeyEvent/physicalKey.html.
final eventKey = event.physicalKey;
if (eventKey == PhysicalKeyboardKey.keyW) {
unawaited(
zoomTo(
math.min(
maxZoomLevel,
currentZoom + keyboardZoomInUnit,
),
),
);
return KeyEventResult.handled;
} else if (eventKey == PhysicalKeyboardKey.keyS) {
unawaited(
zoomTo(
math.max(
FlameChart.minZoomLevel,
currentZoom - keyboardZoomOutUnit,
),
),
);
return KeyEventResult.handled;
} else if (eventKey == PhysicalKeyboardKey.keyA) {
// `unawaited` does not work for FutureOr
// ignore: discarded_futures
scrollToX(horizontalControllerGroup.offset - keyboardScrollUnit);
return KeyEventResult.handled;
} else if (eventKey == PhysicalKeyboardKey.keyD) {
// `unawaited` does not work for FutureOr
// ignore: discarded_futures
scrollToX(horizontalControllerGroup.offset + keyboardScrollUnit);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
void _handleZoomControllerValueUpdate() {
final previousZoom = currentZoom;
final newZoom = zoomController.value;
if (previousZoom == newZoom) return;
// Store current scroll values for re-calculating scroll location on zoom.
final lastScrollOffset = horizontalControllerGroup.offset;
final safeMouseHoverX = mouseHoverX ?? widget.containerWidth / 2;
// Position in the zoomable coordinate space that we want to keep fixed.
final fixedX = safeMouseHoverX + lastScrollOffset - widget.startInset;
// Calculate the new horizontal scroll position.
final newScrollOffset = fixedX >= 0
? fixedX * newZoom / previousZoom + widget.startInset - safeMouseHoverX
// We are in the fixed portion of the window - no need to transform.
: lastScrollOffset;
setState(() {
currentZoom = zoomController.value;
// TODO(kenz): consult with Flutter team to see if there is a better place
// to call this that guarantees the scroll controller offsets will be
// updated for the new zoom level and layout size
// https://github.com/flutter/devtools/issues/2012.
// `unawaited` does not work for FutureOr
// ignore: discarded_futures
scrollToX(newScrollOffset, jump: true);
});
}
Future<void> zoomTo(
double zoom, {
double? forceMouseX,
bool jump = false,
}) async {
if (forceMouseX != null) {
mouseHoverX = forceMouseX;
}
await zoomController.animateTo(
zoom.clamp(FlameChart.minZoomLevel, maxZoomLevel),
duration: jump ? Duration.zero : shortDuration,
);
}
/// Scroll the flame chart horizontally to [offset] scroll position.
///
/// If this is being called immediately after a zoom call, without a chance
/// for the UI to build between the zoom call and the call to
/// this method, the call to this method should be placed inside of a
/// postFrameCallback:
/// `WidgetsBinding.instance.addPostFrameCallback((_) { ... });`.
FutureOr<void> scrollToX(
double offset, {
bool jump = false,
}) async {
final target = offset.clamp(
FlameChart.minScrollOffset,
horizontalControllerGroup.position.maxScrollExtent,
);
if (jump) {
horizontalControllerGroup.jumpTo(target);
} else {
await horizontalControllerGroup.animateTo(
target,
curve: defaultCurve,
duration: shortDuration,
);
}
}
Future<void> scrollVerticallyToData(V data) async {
await verticalControllerGroup.animateTo(
// Subtract [2 * rowHeightWithPadding] to give the target scroll event top padding.
(topYForData(data) - 2 * rowHeightWithPadding).clamp(
FlameChart.minScrollOffset,
verticalControllerGroup.position.maxScrollExtent,
),
duration: shortDuration,
curve: defaultCurve,
);
}
/// Scroll the flame chart horizontally to put [data] in view.
///
/// If this is being called immediately after a zoom call, the call to
/// this method should be placed inside of a postFrameCallback:
/// `WidgetsBinding.instance.addPostFrameCallback((_) { ... });`.
Future<void> scrollHorizontallyToData(V data) async {
final offset =
startXForData(data) + widget.startInset - widget.containerWidth * 0.1;
await scrollToX(offset);
}
Future<void> zoomAndScrollToData({
required int startMicros,
required int durationMicros,
required V data,
bool scrollVertically = true,
bool jumpZoom = false,
}) async {
await zoomToTimeRange(
startMicros: startMicros,
durationMicros: durationMicros,
jump: jumpZoom,
);
// Call these in a post frame callback so that the scroll controllers have
// had time to update their scroll extents. Otherwise, we can hit a race
// where are trying to scroll to an offset that is beyond what the scroll
// controller thinks its max scroll extent is.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
unawaited(scrollHorizontallyToData(data));
if (scrollVertically) unawaited(scrollVerticallyToData(data));
}
});
}
Future<void> zoomToTimeRange({
required int startMicros,
required int durationMicros,
double? targetWidth,
bool jump = false,
}) async {
targetWidth ??= widget.containerWidth * 0.8;
final startingWidth = durationMicros * startingPxPerMicro;
final zoom = targetWidth / startingWidth;
final mouseXForZoom = (startMicros - startTimeOffset + durationMicros / 2) *
startingPxPerMicro +
widget.startInset;
await zoomTo(zoom, forceMouseX: mouseXForZoom, jump: jump);
}
bool isDataVerticallyInView(V data);
bool isDataHorizontallyInView(V data);
double topYForData(V data);
double startXForData(V data);
}
class ScrollingFlameChartRow<V extends FlameChartDataMixin<V>>
extends StatefulWidget {
const ScrollingFlameChartRow({
super.key,
required this.linkedScrollControllerGroup,
required this.nodes,
required this.width,
required this.startInset,
required this.hoveredNotifier,
required this.selectionNotifier,
required this.searchMatchesNotifier,
required this.activeSearchMatchNotifier,
required this.backgroundColor,
required this.zoom,
});
final LinkedScrollControllerGroup linkedScrollControllerGroup;
final List<FlameChartNode<V>> nodes;
final double width;
final double startInset;
final ValueListenable<V?> hoveredNotifier;
final ValueListenable<V?> selectionNotifier;
final ValueListenable<List<V>>? searchMatchesNotifier;
final ValueListenable<V?>? activeSearchMatchNotifier;
final Color backgroundColor;
final double zoom;
@override
ScrollingFlameChartRowState<V> createState() =>
ScrollingFlameChartRowState<V>();
}
class ScrollingFlameChartRowState<V extends FlameChartDataMixin<V>>
extends State<ScrollingFlameChartRow<V>> with AutoDisposeMixin {
late final ScrollController scrollController;
late final _ScrollingFlameChartRowExtentDelegate _extentDelegate;
/// Convenience getter for widget.nodes.
List<FlameChartNode<V>> get nodes => widget.nodes;
late List<V> _nodeData;
V? selected;
V? hovered;
@override
void initState() {
super.initState();
scrollController = widget.linkedScrollControllerGroup.addAndGet();
_extentDelegate = _ScrollingFlameChartRowExtentDelegate(
nodeIntervals: nodes.toPaddedZoomedIntervals(
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
),
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
);
_initNodeDataList();
selected = widget.selectionNotifier.value;
addAutoDisposeListener(widget.selectionNotifier, () {
final containsPreviousSelected =
selected != null && _nodeData.contains(selected);
selected = widget.selectionNotifier.value;
final containsNewSelected = _nodeData.contains(selected);
// We only want to rebuild the row if it contains the previous or new
// selected node.
if (containsPreviousSelected || containsNewSelected) {
setState(() {});
}
});
hovered = widget.hoveredNotifier.value;
addAutoDisposeListener(widget.hoveredNotifier, () {
setState(() {
hovered = widget.hoveredNotifier.value;
});
});
if (widget.searchMatchesNotifier != null) {
addAutoDisposeListener(widget.searchMatchesNotifier);
}
if (widget.activeSearchMatchNotifier != null) {
addAutoDisposeListener(widget.activeSearchMatchNotifier);
}
}
@override
void didUpdateWidget(ScrollingFlameChartRow<V> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.nodes != widget.nodes) {
_initNodeDataList();
}
if (oldWidget.nodes != widget.nodes ||
oldWidget.zoom != widget.zoom ||
oldWidget.width != widget.width ||
oldWidget.startInset != widget.startInset) {
_extentDelegate.recomputeWith(
nodeIntervals: nodes.toPaddedZoomedIntervals(
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
),
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
);
}
_resetHovered();
}
@override
void dispose() {
super.dispose();
scrollController.dispose();
_resetHovered();
}
void _initNodeDataList() {
_nodeData = nodes.map((node) => node.data).toList();
}
@override
Widget build(BuildContext context) {
if (nodes.isEmpty) {
return EmptyFlameChartRow(
height: sectionSpacing,
width: widget.width,
backgroundColor: widget.backgroundColor,
);
}
return Container(
height: rowHeightWithPadding,
width: widget.width,
color: widget.backgroundColor,
// TODO(kenz): investigate if `addAutomaticKeepAlives: false` and
// `addRepaintBoundaries: false` are needed here for perf improvement.
child: ExtentDelegateListView(
controller: scrollController,
scrollDirection: Axis.horizontal,
extentDelegate: _extentDelegate,
childrenDelegate: SliverChildBuilderDelegate(
(context, index) {
final node = nodes[index];
return FlameChartNodeWidget(
index: index,
nodes: nodes,
zoom: widget.zoom,
startInset: widget.startInset,
chartWidth: widget.width,
selected: node.data == selected,
hovered: node.data == hovered,
);
},
childCount: nodes.length,
addRepaintBoundaries: false,
addAutomaticKeepAlives: false,
),
),
);
}
void _resetHovered() {
hovered = null;
}
}
class FlameChartNodeWidget extends StatelessWidget {
const FlameChartNodeWidget({
Key? key,
required this.index,
required this.nodes,
required this.zoom,
required this.startInset,
required this.chartWidth,
required this.selected,
required this.hovered,
}) : super(key: key);
final int index;
final List<FlameChartNode> nodes;
final double zoom;
final double startInset;
final double chartWidth;
final bool selected;
final bool hovered;
@override
Widget build(BuildContext context) {
final node = nodes[index];
return Padding(
padding: EdgeInsets.only(
left: FlameChartUtils.leftPaddingForNode(
index,
nodes,
chartZoom: zoom,
chartStartInset: startInset,
),
right: FlameChartUtils.rightPaddingForNode(
index,
nodes,
chartZoom: zoom,
chartStartInset: startInset,
chartWidth: chartWidth,
),
bottom: rowPadding,
),
child: node.buildWidget(
selected: selected,
hovered: hovered,
searchMatch: node.data.isSearchMatch,
activeSearchMatch: node.data.isActiveSearchMatch,
zoom: FlameChartUtils.zoomForNode(node, zoom),
theme: Theme.of(context),
),
);
}
}
extension NodeListExtension on List<FlameChartNode> {
List<Range> toPaddedZoomedIntervals({
required double zoom,
required double chartStartInset,
required double chartWidth,
}) {
return List<Range>.generate(
length,
(index) => FlameChartUtils.paddedZoomedInterval(
index,
this,
chartZoom: zoom,
chartStartInset: chartStartInset,
chartWidth: chartWidth,
),
);
}
}
// TODO(jacobr): cleanup up this util class with just static members.
// ignore: avoid_classes_with_only_static_members
class FlameChartUtils {
static double leftPaddingForNode(
int index,
List<FlameChartNode> nodes, {
required double chartZoom,
required double chartStartInset,
}) {
final node = nodes[index];
double padding;
if (index != 0) {
padding = 0.0;
} else if (!node.selectable) {
padding = node.rect.left;
} else {
padding =
(node.rect.left - chartStartInset) * zoomForNode(node, chartZoom) +
chartStartInset;
}
// Floating point rounding error can result in slightly negative padding.
return math.max(0.0, padding);
}
static double rightPaddingForNode(
int index,
List<FlameChartNode> nodes, {
required double chartZoom,
required double chartStartInset,
required double chartWidth,
}) {
// TODO(kenz): workaround for https://github.com/flutter/devtools/issues/2012.
// This is a ridiculous amount of padding but it ensures that we don't hit
// the issue described in the bug where the scroll extent is smaller than
// where we want to `jumpTo`. Smaller values were experimented with but the
// issue still persisted, so we are using a very large number.
if (index == nodes.length - 1) return 1000000000000.0;
final node = nodes[index];
final nextNode = index == nodes.length - 1 ? null : nodes[index + 1];
final nodeZoom = zoomForNode(node, chartZoom);
final nextNodeZoom = zoomForNode(nextNode, chartZoom);
// Node right with zoom and insets taken into consideration.
final nodeRight =
(node.rect.right - chartStartInset) * nodeZoom + chartStartInset;
final padding = nextNode == null
? chartWidth - nodeRight
: ((nextNode.rect.left - chartStartInset) * nextNodeZoom +
chartStartInset) -
nodeRight;
// Floating point rounding error can result in slightly negative padding.
return math.max(0.0, padding);
}
static double zoomForNode(FlameChartNode? node, double chartZoom) {
return node != null && node.selectable
? chartZoom
: FlameChart.minZoomLevel;
}
static Range paddedZoomedInterval(
int index,
List<FlameChartNode> nodes, {
required double chartZoom,
required double chartStartInset,
required double chartWidth,
}) {
final node = nodes[index];
final zoomedRect = node.zoomedRect(chartZoom, chartStartInset);
final leftPadding = leftPaddingForNode(
index,
nodes,
chartZoom: chartZoom,
chartStartInset: chartStartInset,
);
final rightPadding = rightPaddingForNode(
index,
nodes,
chartZoom: chartZoom,
chartStartInset: chartStartInset,
chartWidth: chartWidth,
);
final left = zoomedRect.left - leftPadding;
final width = leftPadding + zoomedRect.width + rightPadding;
return Range(left, left + width);
}
}
class FlameChartSection {
FlameChartSection(
this.index, {
required this.startRow,
required this.endRow,
});
final int index;
/// Start row (inclusive) for this section.
final int startRow;
/// End row (exclusive) for this section.
final int endRow;
}
class FlameChartRow<T extends FlameChartDataMixin<T>> {
FlameChartRow(this.index);
final List<FlameChartNode<T>> nodes = [];
final int index;
/// Adds a node to [nodes] and assigns [this] to the nodes [row] property.
///
/// If [index] is specified and in range of the list, [node] will be added at
/// [index]. Otherwise, [node] will be added to the end of [nodes]
void addNode(FlameChartNode<T> node, {int? index}) {
if (index != null && index >= 0 && index < nodes.length) {
nodes.insert(index, node);
} else {
nodes.add(node);
}
node.row = this;
}
}
mixin FlameChartDataMixin<T extends TreeNode<T>>
on TreeDataSearchStateMixin<T> {
String get tooltip;
}
// TODO(kenz): consider de-coupling this API from the dual background color
// scheme.
class FlameChartNode<T extends FlameChartDataMixin<T>> {
FlameChartNode({
this.key,
required this.text,
required this.rect,
required this.colorPair,
required this.data,
required this.onSelected,
this.selectable = true,
this.sectionIndex = 0,
});
static const _darkTextColor = Colors.black;
// We would like this value to be smaller, but zoom performance does not allow
// for that. We should decrease this value if we can improve flame chart zoom
// performance.
static const _minWidthForText = 30.0;
final Key? key;
final Rect rect;
final String text;
final ThemedColorPair colorPair;
final T data;
final void Function(T) onSelected;
final bool selectable;
late FlameChartRow row;
int sectionIndex;
Widget buildWidget({
required bool selected,
required bool hovered,
required bool searchMatch,
required bool activeSearchMatch,
required double zoom,
required ThemeData theme,
}) {
// This math.max call prevents using a rect with negative width for
// small events that have padding.
//
// See https://github.com/flutter/devtools/issues/1503 for details.
final zoomedWidth = math.max(0.0, rect.width * zoom);
// TODO(kenz): this is intended to improve performance but can probably be
// improved. Perhaps we should still show a solid line and fade it out?
if (zoomedWidth < 0.5) {
return SizedBox(width: zoomedWidth);
}
selected = selectable ? selected : false;
hovered = selectable ? hovered : false;
final node = Container(
key: hovered ? null : key,
width: zoomedWidth,
height: rect.height,
padding: const EdgeInsets.symmetric(horizontal: 6.0),
alignment: Alignment.centerLeft,
color: _backgroundColor(
selected: selected,
searchMatch: searchMatch,
activeSearchMatch: activeSearchMatch,
colorScheme: theme.colorScheme,
),
child: zoomedWidth >= _minWidthForText
? Text(
text,
textAlign: TextAlign.left,
overflow: TextOverflow.ellipsis,
style: theme.regularTextStyleWithColor(
_textColor(
selected: selected,
searchMatch: searchMatch,
activeSearchMatch: activeSearchMatch,
colorScheme: theme.colorScheme,
),
),
)
: const SizedBox(),
);
return (hovered || !selectable)
? DevToolsTooltip(
key: key,
message: data.tooltip,
child: node,
)
: node;
}
Color _backgroundColor({
required bool selected,
required bool searchMatch,
required bool activeSearchMatch,
required ColorScheme colorScheme,
}) {
// The primary color for the Dart theme works best for selection color in
// the flame chart.
// TODO(kenz): revisit this style when we perform a V2 style upgrade on the
// more complex data structures in DevTools.
if (selected) return darkColorScheme.primary;
if (activeSearchMatch) return activeSearchMatchColor;
if (searchMatch) return searchMatchColor;
return colorPair.background.colorFor(colorScheme);
}
Color _textColor({
required bool selected,
required bool searchMatch,
required bool activeSearchMatch,
required ColorScheme colorScheme,
}) {
if (selected || searchMatch || activeSearchMatch) return _darkTextColor;
return colorPair.foreground.colorFor(colorScheme);
}
Rect zoomedRect(double zoom, double chartStartInset) {
// If a node is not selectable (e.g. section labels "UI", "Raster", etc.), it
// will not be zoomed, so return the original rect.
if (!selectable) return rect;
// These math.max calls prevent using a rect with negative width for
// small events that have padding.
//
// See https://github.com/flutter/devtools/issues/1503 for details.
final zoomedLeft =
math.max(0.0, (rect.left - chartStartInset) * zoom + chartStartInset);
final zoomedWidth = math.max(0.0, rect.width * zoom);
return Rect.fromLTWH(zoomedLeft, rect.top, zoomedWidth, rect.height);
}
}
mixin FlameChartColorMixin {
ColorPair nextUiColor(int row) {
return uiColorPalette[row % uiColorPalette.length];
}
ColorPair nextRasterColor(int row) {
return rasterColorPalette[row % rasterColorPalette.length];
}
ColorPair nextAsyncColor(int row) {
return asyncColorPalette[row % asyncColorPalette.length];
}
ColorPair nextUnknownColor(int row) {
return unknownColorPalette[row % unknownColorPalette.length];
}
}
/// [ExtentDelegate] implementation for the case where size and position is
/// known for each list item.
class _ScrollingFlameChartRowExtentDelegate extends ExtentDelegate {
_ScrollingFlameChartRowExtentDelegate({
required this.nodeIntervals,
required this.zoom,
required this.chartStartInset,
required this.chartWidth,
}) {
recompute();
}
List<Range> nodeIntervals = [];
double zoom;
double chartStartInset;
double chartWidth;
void recomputeWith({
required List<Range> nodeIntervals,
required double zoom,
required double chartStartInset,
required double chartWidth,
}) {
this.nodeIntervals = nodeIntervals;
this.zoom = zoom;
this.chartStartInset = chartStartInset;
this.chartWidth = chartWidth;
recompute();
}
@override
double itemExtent(int index) {
if (index >= length) return 0;
return nodeIntervals[index].size as double;
}
@override
double layoutOffset(int? index) {
if (index! <= 0) return 0.0;
if (index >= length) return nodeIntervals.last.end as double;
return nodeIntervals[index].begin as double;
}
@override
int get length => nodeIntervals.length;
@override
int minChildIndexForScrollOffset(double scrollOffset) {
final boundInterval = Range(scrollOffset, scrollOffset + 1);
int index = lowerBound(
nodeIntervals,
boundInterval,
compare: (Range a, Range b) => a.begin.compareTo(b.begin),
);
if (index == 0) return 0;
if (index >= nodeIntervals.length ||
(nodeIntervals[index].begin - scrollOffset).abs() >
precisionErrorTolerance) {
index--;
}
assert(
nodeIntervals[index].begin <= scrollOffset + precisionErrorTolerance,
);
return index;
}
@override
int maxChildIndexForScrollOffset(double endScrollOffset) {
final boundInterval = Range(endScrollOffset, endScrollOffset + 1);
int index = lowerBound(
nodeIntervals,
boundInterval,
compare: (Range a, Range b) => a.begin.compareTo(b.begin),
);
if (index == 0) return 0;
index--;
assert(nodeIntervals[index].begin < endScrollOffset);
return index;
}
}
abstract class FlameChartPainter extends CustomPainter {
FlameChartPainter({
required this.zoom,
required this.constraints,
required this.verticalScrollOffset,
required this.horizontalScrollOffset,
required this.chartStartInset,
required this.colorScheme,
});
final double zoom;
final BoxConstraints constraints;
final double verticalScrollOffset;
final double horizontalScrollOffset;
final double chartStartInset;
/// The absolute coordinates of the flame chart's visible section.
Rect get visibleRect {
return Rect.fromLTWH(
horizontalScrollOffset,
verticalScrollOffset,
constraints.maxWidth,
constraints.maxHeight,
);
}
final ColorScheme colorScheme;
@override
bool shouldRepaint(CustomPainter oldDelegate) {
if (oldDelegate is FlameChartPainter) {
return verticalScrollOffset != oldDelegate.verticalScrollOffset ||
horizontalScrollOffset != oldDelegate.horizontalScrollOffset ||
constraints != oldDelegate.constraints ||
zoom != oldDelegate.zoom ||
chartStartInset != oldDelegate.chartStartInset ||
oldDelegate.colorScheme != colorScheme;
}
return true;
}
}
class TimelineGridPainter extends FlameChartPainter {
TimelineGridPainter({
required double zoom,
required BoxConstraints constraints,
required double verticalScrollOffset,
required double horizontalScrollOffset,
required double chartStartInset,
required this.chartEndInset,
required this.flameChartWidth,
required this.duration,
required ColorScheme colorScheme,
}) : super(
zoom: zoom,
constraints: constraints,
verticalScrollOffset: verticalScrollOffset,
horizontalScrollOffset: horizontalScrollOffset,
chartStartInset: chartStartInset,
colorScheme: colorScheme,
);
static const timestampOffset = 6.0;
final double chartEndInset;
final double flameChartWidth;
final Duration duration;
@override
void paint(Canvas canvas, Size size) {
// Paint background for the section that will contain the timestamps. This
// section will appear sticky to the top of the viewport.
final visible = visibleRect;
canvas.drawRect(
Rect.fromLTWH(
0.0,
0.0,
constraints.maxWidth,
math.min(constraints.maxHeight, chartRowHeight),
),
Paint()..color = colorScheme.defaultBackgroundColor,
);
// Paint the timeline grid lines and corresponding timestamps in the flame
// chart.
final intervalWidth = _intervalWidth();
final microsPerInterval = _microsPerInterval(intervalWidth);
int timestampMicros = _startingTimestamp(intervalWidth, microsPerInterval);
double lineX;
lineX = visible.left <= chartStartInset
? chartStartInset - visible.left
: intervalWidth - ((visible.left - chartStartInset) % intervalWidth);
while (lineX < constraints.maxWidth) {
_paintTimestamp(canvas, timestampMicros, intervalWidth, lineX);
_paintGridLine(canvas, lineX);
lineX += intervalWidth;
timestampMicros += microsPerInterval;
}
}
void _paintTimestamp(
Canvas canvas,
int timestampMicros,
double intervalWidth,
double lineX,
) {
final timestampText = durationText(
Duration(microseconds: timestampMicros),
fractionDigits: timestampMicros == 0 ? 1 : 3,
);
final textPainter = TextPainter(
text: TextSpan(
text: timestampText,
style: TextStyle(
color: colorScheme.contrastTextColor,
fontSize: defaultFontSize,
),
),
textAlign: TextAlign.right,
textDirection: TextDirection.ltr,
)..layout(maxWidth: intervalWidth);
// TODO(kenz): figure out a way for the timestamps to scroll out of view
// smoothly instead of dropping off. Consider using a horizontal list view
// of text widgets for the timestamps instead of painting them.
final xOffset = lineX - textPainter.width - timestampOffset;
if (xOffset > 0) {
textPainter.paint(canvas, Offset(xOffset, rowPadding));
}
}
void _paintGridLine(Canvas canvas, double lineX) {
canvas.drawLine(
Offset(lineX, 0.0),
Offset(lineX, constraints.maxHeight),
Paint()..color = colorScheme.chartAccentColor,
);
}
double _intervalWidth() {
final log2ZoomLevel = log2(zoom);
final gridZoomFactor = math.pow(2, log2ZoomLevel);
final gridIntervalPx = baseTimelineGridIntervalPx / gridZoomFactor;
/// The physical pixel width of the grid interval at [zoom].
return gridIntervalPx * zoom;
}
int _microsPerInterval(double intervalWidth) {
final contentWidth = flameChartWidth - chartStartInset - chartEndInset;
final numCompleteIntervals = contentWidth ~/ intervalWidth;
final remainderContentWidth =
contentWidth - (numCompleteIntervals * intervalWidth);
final remainderMicros =
remainderContentWidth * duration.inMicroseconds / contentWidth;
return ((duration.inMicroseconds - remainderMicros) / numCompleteIntervals)
.round();
}
int _startingTimestamp(double intervalWidth, int microsPerInterval) {
final startingIntervalIndex = horizontalScrollOffset < chartStartInset
? 0
: (horizontalScrollOffset - chartStartInset) ~/ intervalWidth + 1;
return startingIntervalIndex * microsPerInterval;
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => this != oldDelegate;
@override
bool operator ==(Object other) {
if (other is! TimelineGridPainter) return false;
return zoom == other.zoom &&
constraints == other.constraints &&
flameChartWidth == other.flameChartWidth &&
horizontalScrollOffset == other.horizontalScrollOffset &&
duration == other.duration &&
colorScheme == other.colorScheme;
}
@override
int get hashCode => Object.hash(
zoom,
constraints,
flameChartWidth,
horizontalScrollOffset,
duration,
colorScheme,
);
}
class FlameChartHelpButton extends StatelessWidget {
const FlameChartHelpButton({
Key? key,
required this.gaScreen,
required this.gaSelection,
this.additionalInfo = const <Widget>[],
}) : super(key: key);
final String gaScreen;
final String gaSelection;
final List<Widget> additionalInfo;
/// A fixed width for the first column in the help dialog to ensure that the
/// subsections are aligned.
double get firstColumnWidth => scaleByFontFactor(120.0);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return HelpButtonWithDialog(
gaScreen: gaScreen,
gaSelection: gaSelection,
dialogTitle: 'Flame Chart Help',
outlined: false,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...dialogSubHeader(theme, 'Navigation & Zoom'),
_buildNavigationInstructions(theme),
if (additionalInfo.isNotEmpty) const SizedBox(height: denseSpacing),
...additionalInfo,
],
),
);
}
Widget _buildNavigationInstructions(ThemeData theme) {
return Row(
children: [
SizedBox(
width: firstColumnWidth,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'WASD • ',
style: theme.fixedFontStyle,
),
Text(
'click + drag • ',
style: theme.fixedFontStyle,
),
Text(
'click + fling • ',
style: theme.fixedFontStyle,
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Pan chart left / right and zoom in / out',
style: theme.subtleTextStyle,
),
Text(
'Pan chart up / down / left / right',
style: theme.subtleTextStyle,
),
Text(
'Fling chart up / down / left / right',
style: theme.subtleTextStyle,
),
],
),
],
);
}
}
class EmptyFlameChartRow extends StatelessWidget {
const EmptyFlameChartRow({
super.key,
required this.height,
required this.width,
required this.backgroundColor,
});
final double height;
final double width;
final Color backgroundColor;
@override
Widget build(BuildContext context) {
return Container(
height: height,
width: width,
color: backgroundColor,
);
}
}
// Helper method to enable easier testing of this method. Do not use directly
// outside of this file.
@visibleForTesting
FlameChartNode<V>? binarySearchForNodeHelper<V extends FlameChartDataMixin<V>>({
required double x,
required List<FlameChartNode<V>> nodesInRow,
required double zoom,
required double startInset,
}) {
int min = 0;
int max = nodesInRow.length;
while (min < max) {
final mid = min + ((max - min) >> 1);
final node = nodesInRow[mid];
final zoomedNodeRect = node.zoomedRect(zoom, startInset);
if (x >= zoomedNodeRect.left && x <= zoomedNodeRect.right) {
return node;
}
if (x < zoomedNodeRect.left) {
max = mid;
}
if (x > zoomedNodeRect.right) {
min = mid + 1;
}
}
return null;
}
| devtools/packages/devtools_app/lib/src/shared/charts/flame_chart.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/charts/flame_chart.dart",
"repo_id": "devtools",
"token_count": 18318
} | 99 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
import 'dart:io';
class HostPlatform {
HostPlatform._();
static final HostPlatform instance = HostPlatform._();
bool get isMacOS => Platform.isMacOS;
}
| devtools/packages/devtools_app/lib/src/shared/config_specific/host_platform/_host_platform_desktop.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/host_platform/_host_platform_desktop.dart",
"repo_id": "devtools",
"token_count": 90
} | 100 |
// 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.
class Notification {
Notification(String title, {String? body}) {
throw Exception('unsupported platform');
}
static Future<String> requestPermission() {
throw Exception('unsupported platform');
}
void close() {
throw Exception('unsupported platform');
}
}
| devtools/packages/devtools_app/lib/src/shared/config_specific/notifications/_notifications_desktop.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/notifications/_notifications_desktop.dart",
"repo_id": "devtools",
"token_count": 121
} | 101 |
// 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:vm_service/vm_service.dart';
import '../../globals.dart';
import '../../vm_utils.dart';
class EvalScope {
/// Parameter `scope` for `serviceManager.manager.service!.evaluate(...)`.
///
/// Maps variable name to targetId.
Map<String, String> value({required String isolateId}) =>
(_refs[isolateId] ?? {}).map((key, value) => MapEntry(key, value.id!));
/// Maps isolate name to list of context variables.
final _refs = <String, Map<String, InstanceRef>>{};
void add(String isolateId, String variableName, InstanceRef ref) {
_refs.putIfAbsent(isolateId, () => {});
_refs[isolateId]![variableName] = ref;
}
/// List of variables, removed during last refresh.
final removedVariables = <String>[];
/// Refreshes variables in scope in response to failed eval.
///
/// Returns true, if eval should retry.
/// Sets [refreshScopeChangeMessage] if scope changed.
Future<bool> refreshRefs(String isolateId) async {
removedVariables.clear();
final isolateItems = _refs[isolateId] ?? {};
var result = false;
final variableNames = [...isolateItems.keys];
for (final name in variableNames) {
final oldItem = isolateItems[name]!;
final refreshedItem = await _refreshRef(oldItem, isolateId);
if (refreshedItem != oldItem) result = true;
if (refreshedItem == null) {
isolateItems.remove(name);
removedVariables.add(name);
}
}
return result;
}
Future<InstanceRef?> _refreshRef(
InstanceRef ref,
String isolateId,
) async {
Obj? object;
try {
object = await serviceConnection.serviceManager.service!.getObject(
isolateId,
ref.id!,
);
} on RPCError {
// If we could not get object, we need to recover it.
} on SentinelException {
// If we could not get object, we need to recover it.
}
if (object != null) return ref;
return await findInstance(
isolateId,
ref.classRef?.id,
ref.identityHashCode,
);
}
}
| devtools/packages/devtools_app/lib/src/shared/console/primitives/scope.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/console/primitives/scope.dart",
"repo_id": "devtools",
"token_count": 780
} | 102 |
// Copyright 2023 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:devtools_app_shared/service.dart';
import 'package:flutter/foundation.dart';
import 'package:vm_service/vm_service.dart';
import 'primitives/instance_ref.dart';
abstract class InspectorObjectGroupApi<T extends DiagnosticableTree>
implements Disposable {
bool get canSetSelectionInspector => false;
Future<bool> setSelectionInspector(
InspectorInstanceRef selection,
bool uiAlreadyUpdated,
) =>
throw UnimplementedError();
Future<Map<String, InstanceRef>?> getEnumPropertyValues(
InspectorInstanceRef ref,
);
Future<Map<String, InstanceRef>?> getDartObjectProperties(
InspectorInstanceRef inspectorInstanceRef,
final List<String> propertyNames,
);
Future<List<T>> getChildren(
InspectorInstanceRef instanceRef,
bool summaryTree,
T? parent,
);
bool isLocalClass(T node);
Future<InstanceRef?> toObservatoryInstanceRef(
InspectorInstanceRef inspectorInstanceRef,
);
Future<List<T>> getProperties(InspectorInstanceRef instanceRef);
}
| devtools/packages/devtools_app/lib/src/shared/diagnostics/object_group_api.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/diagnostics/object_group_api.dart",
"repo_id": "devtools",
"token_count": 373
} | 103 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'package:devtools_app_shared/ui.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'analytics/analytics.dart' as ga;
import 'analytics/constants.dart' as gac;
import 'common_widgets.dart';
import 'config_specific/drag_and_drop/drag_and_drop.dart';
import 'config_specific/import_export/import_export.dart';
import 'globals.dart';
import 'primitives/utils.dart';
class OpenSaveButtonGroup extends StatelessWidget {
const OpenSaveButtonGroup({
super.key,
required this.screenId,
required this.onSave,
});
final String screenId;
final VoidCallback? onSave;
@override
Widget build(BuildContext context) {
return RoundedButtonGroup(
items: [
ButtonGroupItemData(
icon: Icons.file_upload,
tooltip: 'Open a file that was previously saved from DevTools',
onPressed: () async {
ga.select(screenId, gac.openFile);
final importedFile =
await importFileFromPicker(acceptedTypes: const ['json']);
if (importedFile != null) {
// ignore: use_build_context_synchronously, intentional use.
Provider.of<ImportController>(context, listen: false)
.importData(importedFile, expectedScreenId: screenId);
} else {
notificationService.push(
'Something went wrong. Could not open selected file.',
);
}
},
),
ButtonGroupItemData(
icon: Icons.file_download,
tooltip: 'Save this screen\'s data for offline viewing',
onPressed: onSave != null
? () {
ga.select(screenId, gac.saveFile);
onSave!.call();
}
: null,
),
],
);
}
}
class FileImportContainer extends StatefulWidget {
const FileImportContainer({
required this.instructions,
required this.gaScreen,
required this.gaSelectionImport,
this.title,
this.gaSelectionAction,
this.actionText,
this.onAction,
this.onFileSelected,
this.onFileCleared,
this.extensions = const ['json'],
super.key,
});
final String? title;
final String instructions;
/// The title of the action button.
final String? actionText;
final DevToolsJsonFileHandler? onAction;
final DevToolsJsonFileHandler? onFileSelected;
final VoidCallback? onFileCleared;
/// The file's extensions where we are going to get the data from.
final List<String> extensions;
final String gaScreen;
final String gaSelectionImport;
final String? gaSelectionAction;
@override
State<FileImportContainer> createState() => _FileImportContainerState();
}
class _FileImportContainerState extends State<FileImportContainer> {
DevToolsJsonFile? importedFile;
@override
Widget build(BuildContext context) {
final title = widget.title;
return Column(
children: [
if (title != null) ...[
Text(
title,
style: TextStyle(fontSize: scaleByFontFactor(18.0)),
),
const SizedBox(height: defaultSpacing),
],
Expanded(
// TODO(kenz): improve drag over highlight.
child: DragAndDrop(
handleDrop: _handleImportedFile,
child: RoundedOutlinedBorder(
clip: true,
child: Container(
color: Theme.of(context).scaffoldBackgroundColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildImportInstructions(),
_buildImportFileRow(),
if (widget.actionText != null && widget.onAction != null)
_buildActionButton(),
],
),
),
),
),
),
],
);
}
Widget _buildImportInstructions() {
return Padding(
padding: const EdgeInsets.all(defaultSpacing),
child: Text(
widget.instructions,
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).textTheme.displayLarge!.color,
),
),
);
}
Widget _buildImportFileRow() {
final rowHeight = defaultButtonHeight;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Spacer(),
Flexible(
flex: 4,
fit: FlexFit.tight,
child: RoundedOutlinedBorder(
child: Container(
height: rowHeight,
padding: const EdgeInsets.symmetric(horizontal: defaultSpacing),
child: _buildImportedFileDisplay(),
),
),
),
const SizedBox(width: denseSpacing),
FileImportButton(
onPressed: _importFile,
gaScreen: widget.gaScreen,
gaSelection: widget.gaSelectionImport,
),
const Spacer(),
],
);
}
Widget _buildImportedFileDisplay() {
return Row(
children: [
Expanded(
child: Text(
importedFile?.path ?? 'No File Selected',
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Theme.of(context).textTheme.displayLarge!.color,
),
textAlign: TextAlign.left,
),
),
if (importedFile != null) clearInputButton(_clearFile),
],
);
}
Widget _buildActionButton() {
assert(widget.actionText != null);
assert(widget.onAction != null);
assert(widget.gaSelectionAction != null);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: defaultSpacing),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GaDevToolsButton(
gaScreen: widget.gaScreen,
gaSelection: widget.gaSelectionAction!,
label: widget.actionText!,
elevated: true,
onPressed: importedFile != null
? () => widget.onAction!(importedFile!)
: null,
),
],
),
],
);
}
Future<void> _importFile() async {
final importedFile =
await importFileFromPicker(acceptedTypes: widget.extensions);
if (importedFile != null) {
_handleImportedFile(importedFile);
}
}
void _clearFile() {
if (mounted) {
setState(() {
importedFile = null;
});
}
if (widget.onFileCleared != null) {
widget.onFileCleared!();
}
}
// TODO(kenz): add error handling to ensure we only allow importing supported
// files.
void _handleImportedFile(DevToolsJsonFile file) {
// TODO(peterdjlee): Investigate why setState is called after the state is disposed.
if (mounted) {
setState(() {
importedFile = file;
});
}
if (widget.onFileSelected != null) {
widget.onFileSelected!(file);
}
}
}
Future<DevToolsJsonFile?> importFileFromPicker({
required List<String> acceptedTypes,
}) async {
final acceptedTypeGroups = [XTypeGroup(extensions: acceptedTypes)];
final file = await openFile(acceptedTypeGroups: acceptedTypeGroups);
if (file == null) return null;
return await _toDevToolsFile(file);
}
Future<List<XFile>> importRawFilesFromPicker({
List<String>? acceptedTypes,
}) async {
final acceptedTypeGroups = [XTypeGroup(extensions: acceptedTypes)];
return await openFiles(acceptedTypeGroups: acceptedTypeGroups);
}
Future<DevToolsJsonFile> _toDevToolsFile(XFile file) async {
final data = jsonDecode(await file.readAsString());
final lastModifiedTime = await file.lastModified();
// TODO(kenz): this will need to be modified if we need to support other file
// extensions than .json. We will need to return a more generic file type.
return DevToolsJsonFile(
data: data,
name: file.name,
lastModifiedTime: lastModifiedTime,
);
}
class FileImportButton extends StatelessWidget {
const FileImportButton({
super.key,
required this.onPressed,
required this.gaScreen,
required this.gaSelection,
this.elevatedButton = false,
});
final VoidCallback onPressed;
final bool elevatedButton;
final String gaScreen;
final String gaSelection;
@override
Widget build(BuildContext context) {
return GaDevToolsButton(
onPressed: onPressed,
icon: Icons.file_upload,
label: 'Open file',
gaScreen: gaScreen,
gaSelection: gaSelection,
elevated: elevatedButton,
);
}
}
class DualFileImportContainer extends StatefulWidget {
const DualFileImportContainer({
super.key,
required this.firstFileTitle,
required this.secondFileTitle,
required this.firstInstructions,
required this.secondInstructions,
required this.actionText,
required this.onAction,
required this.gaScreen,
required this.gaSelectionImportFirst,
required this.gaSelectionImportSecond,
required this.gaSelectionAction,
});
final String firstFileTitle;
final String secondFileTitle;
final String firstInstructions;
final String secondInstructions;
final String gaScreen;
final String gaSelectionImportFirst;
final String gaSelectionImportSecond;
final String gaSelectionAction;
/// The title of the action button.
final String actionText;
final void Function(
DevToolsJsonFile firstImportedFile,
DevToolsJsonFile secondImportedFile,
void Function(String error) onError,
) onAction;
@override
State<DualFileImportContainer> createState() =>
_DualFileImportContainerState();
}
class _DualFileImportContainerState extends State<DualFileImportContainer> {
DevToolsJsonFile? firstImportedFile;
DevToolsJsonFile? secondImportedFile;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: FileImportContainer(
title: widget.firstFileTitle,
instructions: widget.firstInstructions,
onFileSelected: onFirstFileSelected,
onFileCleared: onFirstFileCleared,
gaScreen: widget.gaScreen,
gaSelectionImport: widget.gaSelectionImportFirst,
),
),
const SizedBox(width: defaultSpacing),
Center(child: _buildActionButton()),
const SizedBox(width: defaultSpacing),
Expanded(
child: FileImportContainer(
title: widget.secondFileTitle,
instructions: widget.secondInstructions,
onFileSelected: onSecondFileSelected,
onFileCleared: onSecondFileCleared,
gaScreen: widget.gaScreen,
gaSelectionImport: widget.gaSelectionImportSecond,
),
),
],
);
}
void onFirstFileSelected(DevToolsJsonFile selectedFile) {
// TODO(peterdjlee): Investigate why setState is called after the state is disposed.
if (mounted) {
setState(() {
firstImportedFile = selectedFile;
});
}
}
void onSecondFileSelected(DevToolsJsonFile selectedFile) {
// TODO(peterdjlee): Investigate why setState is called after the state is disposed.
if (mounted) {
setState(() {
secondImportedFile = selectedFile;
});
}
}
void onFirstFileCleared() {
if (mounted) {
setState(() {
firstImportedFile = null;
});
}
}
void onSecondFileCleared() {
if (mounted) {
setState(() {
secondImportedFile = null;
});
}
}
Widget _buildActionButton() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: defaultSpacing),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GaDevToolsButton(
gaScreen: widget.gaScreen,
gaSelection: widget.gaSelectionAction,
label: widget.actionText,
icon: Icons.highlight,
elevated: true,
onPressed: firstImportedFile != null && secondImportedFile != null
? () => widget.onAction(
firstImportedFile!,
secondImportedFile!,
(error) => notificationService.push(error),
)
: null,
),
],
),
],
);
}
}
| devtools/packages/devtools_app/lib/src/shared/file_import.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/file_import.dart",
"repo_id": "devtools",
"token_count": 5397
} | 104 |
// Copyright 2024 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'adapted_heap_object.dart';
import 'simple_items.dart';
/// Mark the object as deeply immutable.
///
/// There is no strong protection from mutation, just some asserts.
mixin Sealable {
/// See doc for the mixin [Sealable].
void seal() {
_isSealed = true;
}
/// See doc for the mixin [Sealable].
bool get isSealed => _isSealed;
bool _isSealed = false;
}
/// Statistical size-information about objects.
class ObjectSetStats with Sealable {
static ObjectSetStats? subtract({
required ObjectSetStats? subtract,
required ObjectSetStats? from,
}) {
from ??= _empty;
subtract ??= _empty;
final result = ObjectSetStats()
..instanceCount = from.instanceCount - subtract.instanceCount
..shallowSize = from.shallowSize - subtract.shallowSize
..retainedSize = from.retainedSize - subtract.retainedSize;
if (result.isZero) return null;
return result;
}
static final _empty = ObjectSetStats()..seal();
int instanceCount = 0;
int shallowSize = 0;
int retainedSize = 0;
bool get isZero =>
shallowSize == 0 && retainedSize == 0 && instanceCount == 0;
void countInstance(
AdaptedHeapObject object, {
required bool excludeFromRetained,
}) {
assert(!isSealed);
if (!excludeFromRetained) retainedSize += object.retainedSize!;
shallowSize += object.shallowSize;
instanceCount++;
}
void uncountInstance(
AdaptedHeapObject object, {
required bool excludeFromRetained,
}) {
assert(!isSealed);
if (!excludeFromRetained) retainedSize -= object.retainedSize!;
shallowSize -= object.shallowSize;
instanceCount--;
}
}
/// Statistical and detailed size-information about objects.
class ObjectSet extends ObjectSetStats {
static ObjectSet empty = ObjectSet()..seal();
final objectsByCodes = <IdentityHashCode, AdaptedHeapObject>{};
/// Subset of objects that are excluded from the retained size
/// calculation for this set.
///
/// See [countInstance].
final objectsExcludedFromRetainedSize = <IdentityHashCode>{};
@override
bool get isZero => objectsByCodes.isEmpty;
@override
void countInstance(
AdaptedHeapObject object, {
required bool excludeFromRetained,
}) {
if (objectsByCodes.containsKey(object.code)) return;
super.countInstance(object, excludeFromRetained: excludeFromRetained);
objectsByCodes[object.code] = object;
if (excludeFromRetained) objectsExcludedFromRetainedSize.add(object.code);
}
@override
void uncountInstance(
AdaptedHeapObject object, {
required bool excludeFromRetained,
}) {
throw AssertionError('uncountInstance is not valid for $ObjectSet');
}
}
| devtools/packages/devtools_app/lib/src/shared/memory/classes.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/memory/classes.dart",
"repo_id": "devtools",
"token_count": 918
} | 105 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
/// A [ScrollView] that uses a single child layout model and allows for custom
/// handling of [PointerSignalEvent]s.
///
/// This class is copied from the Flutter framework [BoxScrollView] and
/// overrides [ScrollView.build] to use [CustomPointerScrollable] in place of
/// [Scrollable].
abstract class CustomPointerScrollView extends BoxScrollView {
/// Creates a [ScrollView] uses a single child layout model.
///
/// If the [primary] argument is true, the [controller] must be null.
const CustomPointerScrollView({
Key? key,
Axis scrollDirection = Axis.vertical,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
double? cacheExtent,
int? semanticChildCount,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
this.customPointerSignalHandler,
}) : _primary = primary ??
controller == null && identical(scrollDirection, Axis.vertical),
super(
key: key,
scrollDirection: scrollDirection,
reverse: reverse,
controller: controller,
padding: padding,
primary: primary,
physics: physics,
shrinkWrap: shrinkWrap,
cacheExtent: cacheExtent,
semanticChildCount: semanticChildCount,
dragStartBehavior: dragStartBehavior,
);
final void Function(PointerSignalEvent event)? customPointerSignalHandler;
// TODO(Piinks): Restore once PSC changes have landed, or keep to maintain
// original primary behavior.
final bool _primary;
@override
Widget build(BuildContext context) {
final List<Widget> slivers = buildSlivers(context);
final AxisDirection axisDirection = getDirection(context);
final ScrollController? scrollController =
_primary ? PrimaryScrollController.of(context) : controller;
assert(
scrollController != null,
'No ScrollController has been provided to the CustomPointerScrollView.',
);
final CustomPointerScrollable scrollable = CustomPointerScrollable(
dragStartBehavior: dragStartBehavior,
axisDirection: axisDirection,
controller: scrollController,
physics: physics,
semanticChildCount: semanticChildCount,
viewportBuilder: (BuildContext context, ViewportOffset offset) {
return buildViewport(context, offset, axisDirection, slivers);
},
customPointerSignalHandler: customPointerSignalHandler,
);
return _primary
? PrimaryScrollController.none(child: scrollable)
: scrollable;
}
}
/// A widget that scrolls and allows custom pointer signal event handling.
///
/// This widget is a copy of [Scrollable] with additional support for custom
/// pointer signal event handling via [customPointerSignalHandler].
class CustomPointerScrollable extends StatefulWidget {
const CustomPointerScrollable({
Key? key,
this.axisDirection = AxisDirection.down,
this.controller,
this.physics,
required this.viewportBuilder,
this.incrementCalculator,
this.excludeFromSemantics = false,
this.semanticChildCount,
this.dragStartBehavior = DragStartBehavior.start,
this.customPointerSignalHandler,
}) : assert(semanticChildCount == null || semanticChildCount >= 0),
super(key: key);
/// The direction in which this widget scrolls.
///
/// For example, if the [axisDirection] is [AxisDirection.down], increasing
/// the scroll position will cause content below the bottom of the viewport to
/// become visible through the viewport. Similarly, if [axisDirection] is
/// [AxisDirection.right], increasing the scroll position will cause content
/// beyond the right edge of the viewport to become visible through the
/// viewport.
///
/// Defaults to [AxisDirection.down].
final AxisDirection axisDirection;
/// An object that can be used to control the position to which this widget is
/// scrolled.
///
/// A [ScrollController] serves several purposes. It can be used to control
/// the initial scroll position (see [ScrollController.initialScrollOffset]).
/// It can be used to control whether the scroll view should automatically
/// save and restore its scroll position in the [PageStorage] (see
/// [ScrollController.keepScrollOffset]). It can be used to read the current
/// scroll position (see [ScrollController.offset]), or change it (see
/// [ScrollController.animateTo]).
///
/// See also:
///
/// * [ensureVisible], which animates the scroll position to reveal a given
/// [BuildContext].
final ScrollController? controller;
/// How the widgets should respond to user input.
///
/// For example, determines how the widget continues to animate after the
/// user stops dragging the scroll view.
///
/// Defaults to matching platform conventions via the physics provided from
/// the ambient [ScrollConfiguration].
///
/// The physics can be changed dynamically, but new physics will only take
/// effect if the _class_ of the provided object changes. Merely constructing
/// a new instance with a different configuration is insufficient to cause the
/// physics to be reapplied. (This is because the final object used is
/// generated dynamically, which can be relatively expensive, and it would be
/// inefficient to speculatively create this object each frame to see if the
/// physics should be updated.)
///
/// See also:
///
/// * [AlwaysScrollableScrollPhysics], which can be used to indicate that the
/// scrollable should react to scroll requests (and possible overscroll)
/// even if the scrollable's contents fit without scrolling being necessary.
final ScrollPhysics? physics;
/// Builds the viewport through which the scrollable content is displayed.
///
/// A typical viewport uses the given [ViewportOffset] to determine which part
/// of its content is actually visible through the viewport.
///
/// See also:
///
/// * [Viewport], which is a viewport that displays a list of slivers.
/// * [ShrinkWrappingViewport], which is a viewport that displays a list of
/// slivers and sizes itself based on the size of the slivers.
final ViewportBuilder viewportBuilder;
/// An optional function that will be called to calculate the distance to
/// scroll when the scrollable is asked to scroll via the keyboard using a
/// [ScrollAction].
///
/// If not supplied, the [Scrollable] will scroll a default amount when a
/// keyboard navigation key is pressed (e.g. pageUp/pageDown, control-upArrow,
/// etc.), or otherwise invoked by a [ScrollAction].
///
/// If [incrementCalculator] is null, the default for
/// [ScrollIncrementType.page] is 80% of the size of the scroll window, and
/// for [ScrollIncrementType.line], 50 logical pixels.
final ScrollIncrementCalculator? incrementCalculator;
/// Whether the scroll actions introduced by this [Scrollable] are exposed
/// in the semantics tree.
///
/// Text fields with an overflow are usually scrollable to make sure that the
/// user can get to the beginning/end of the entered text. However, these
/// scrolling actions are generally not exposed to the semantics layer.
///
/// See also:
///
/// * [GestureDetector.excludeFromSemantics], which is used to accomplish the
/// exclusion.
final bool excludeFromSemantics;
/// The number of children that will contribute semantic information.
///
/// The value will be null if the number of children is unknown or unbounded.
///
/// Some subtypes of [ScrollView] can infer this value automatically. For
/// example [ListView] will use the number of widgets in the child list,
/// while the [ListView.separated] constructor will use half that amount.
///
/// For [CustomScrollView] and other types which do not receive a builder
/// or list of widgets, the child count must be explicitly provided.
///
/// See also:
///
/// * [CustomScrollView], for an explanation of scroll semantics.
/// * [SemanticsConfiguration.scrollChildCount], the corresponding semantics property.
final int? semanticChildCount;
// TODO(jslavitz): Set the DragStartBehavior default to be start across all widgets.
/// {@template flutter.widgets.scrollable.dragStartBehavior}
/// Determines the way that drag start behavior is handled.
///
/// If set to [DragStartBehavior.start], scrolling drag behavior will
/// begin upon the detection of a drag gesture. If set to
/// [DragStartBehavior.down] it will begin when a down event is first detected.
///
/// In general, setting this to [DragStartBehavior.start] will make drag
/// animation smoother and setting it to [DragStartBehavior.down] will make
/// drag behavior feel slightly more reactive.
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which gives an example for
/// the different behaviors.
///
/// {@endtemplate}
final DragStartBehavior dragStartBehavior;
/// The axis along which the scroll view scrolls.
///
/// Determined by the [axisDirection].
Axis get axis => axisDirectionToAxis(axisDirection);
final void Function(PointerSignalEvent event)? customPointerSignalHandler;
@override
State<CustomPointerScrollable> createState() =>
CustomPointerScrollableState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
properties.add(DiagnosticsProperty<ScrollPhysics>('physics', physics));
}
/// The state from the closest instance of this class that encloses the given context.
///
/// Typical usage is as follows:
///
/// ```dart
/// _CustomPointerScrollableState scrollable = Scrollable.of(context);
/// ```
///
/// Calling this method will create a dependency on the closest [Scrollable]
/// in the [context], if there is one.
static CustomPointerScrollableState? of(BuildContext context) {
final _ScrollableScope? widget =
context.dependOnInheritedWidgetOfExactType<_ScrollableScope>();
return widget?.scrollable;
}
/// Scrolls the scrollables that enclose the given context so as to make the
/// given context visible.
static Future<void> ensureVisible(
BuildContext context, {
double alignment = 0.0,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
ScrollPositionAlignmentPolicy alignmentPolicy =
ScrollPositionAlignmentPolicy.explicit,
}) {
final List<Future<void>> futures = <Future<void>>[];
CustomPointerScrollableState? scrollable =
CustomPointerScrollable.of(context);
while (scrollable != null) {
futures.add(
scrollable.position!.ensureVisible(
context.findRenderObject()!,
alignment: alignment,
duration: duration,
curve: curve,
alignmentPolicy: alignmentPolicy,
),
);
context = scrollable.context;
scrollable = CustomPointerScrollable.of(context);
}
if (futures.isEmpty || duration == Duration.zero) {
return Future<void>.value();
}
if (futures.length == 1) return futures.single;
return Future.wait<void>(futures).then<void>((List<void> _) => null);
}
}
/// State object for [CustomPointerScrollable].
///
/// This state object is a copy of [ScrollableState] and replaces the handler
/// [ScrollableState._receivedPointerSignal] with
/// [CustomPointerScrollable.customPointerSignalHandler] when non-null.
class CustomPointerScrollableState extends State<CustomPointerScrollable>
with TickerProviderStateMixin
implements ScrollContext {
/// The manager for this [Scrollable] widget's viewport position.
///
/// To control what kind of [ScrollPosition] is created for a [Scrollable],
/// provide it with custom [ScrollController] that creates the appropriate
/// [ScrollPosition] in its [ScrollController.createScrollPosition] method.
ScrollPosition? get position => _position;
ScrollPosition? _position;
@override
AxisDirection get axisDirection => widget.axisDirection;
@override
double get devicePixelRatio => _devicePixelRatio;
late double _devicePixelRatio;
late ScrollBehavior _configuration;
ScrollPhysics? _physics;
// Only call this from places that will definitely trigger a rebuild.
void _updatePosition() {
_configuration = ScrollConfiguration.of(context);
_physics = _configuration.getScrollPhysics(context);
if (widget.physics != null) _physics = widget.physics!.applyTo(_physics);
final ScrollController? controller = widget.controller;
final ScrollPosition? oldPosition = position;
if (oldPosition != null) {
controller?.detach(oldPosition);
// It's important that we not dispose the old position until after the
// viewport has had a chance to unregister its listeners from the old
// position. So, schedule a microtask to do it.
scheduleMicrotask(oldPosition.dispose);
}
_position =
controller?.createScrollPosition(_physics!, this, oldPosition) ??
ScrollPositionWithSingleContext(
physics: _physics!,
context: this,
oldPosition: oldPosition,
);
assert(position != null);
controller?.attach(position!);
}
@override
void saveOffset(double offset) {
assert(debugIsSerializableForRestoration(offset));
// TODO(goderbauer): enable state restoration once the framework is stable.
}
@override
void didChangeDependencies() {
_devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context) ??
View.of(context).devicePixelRatio;
_updatePosition();
super.didChangeDependencies();
}
bool _shouldUpdatePosition(CustomPointerScrollable oldWidget) {
ScrollPhysics? newPhysics = widget.physics;
ScrollPhysics? oldPhysics = oldWidget.physics;
do {
if (newPhysics?.runtimeType != oldPhysics?.runtimeType) return true;
newPhysics = newPhysics?.parent;
oldPhysics = oldPhysics?.parent;
} while (newPhysics != null || oldPhysics != null);
return widget.controller?.runtimeType != oldWidget.controller?.runtimeType;
}
@override
void didUpdateWidget(CustomPointerScrollable oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller != oldWidget.controller) {
oldWidget.controller?.detach(position!);
widget.controller?.attach(position!);
}
if (_shouldUpdatePosition(oldWidget)) _updatePosition();
}
@override
void dispose() {
widget.controller?.detach(position!);
position!.dispose();
super.dispose();
}
// SEMANTICS
final GlobalKey _scrollSemanticsKey = GlobalKey();
@override
@protected
void setSemanticsActions(Set<SemanticsAction> actions) {
if (_gestureDetectorKey.currentState != null) {
_gestureDetectorKey.currentState!.replaceSemanticsActions(actions);
}
}
// GESTURE RECOGNITION AND POINTER IGNORING
final GlobalKey<RawGestureDetectorState> _gestureDetectorKey =
GlobalKey<RawGestureDetectorState>();
final GlobalKey _ignorePointerKey = GlobalKey();
// This field is set during layout, and then reused until the next time it is set.
Map<Type, GestureRecognizerFactory> _gestureRecognizers =
const <Type, GestureRecognizerFactory>{};
bool _shouldIgnorePointer = false;
bool? _lastCanDrag;
Axis? _lastAxisDirection;
@override
@protected
void setCanDrag(bool canDrag) {
if (canDrag == _lastCanDrag &&
(!canDrag || widget.axis == _lastAxisDirection)) return;
if (!canDrag) {
_gestureRecognizers = const <Type, GestureRecognizerFactory>{};
} else {
switch (widget.axis) {
case Axis.vertical:
_gestureRecognizers = <Type, GestureRecognizerFactory>{
VerticalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<
VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer(),
(VerticalDragGestureRecognizer instance) {
instance
..onDown = _handleDragDown
..onStart = _handleDragStart
..onUpdate = _handleDragUpdate
..onEnd = _handleDragEnd
..onCancel = _handleDragCancel
..minFlingDistance = _physics?.minFlingDistance
..minFlingVelocity = _physics?.minFlingVelocity
..maxFlingVelocity = _physics?.maxFlingVelocity
..dragStartBehavior = widget.dragStartBehavior;
},
),
};
break;
case Axis.horizontal:
_gestureRecognizers = <Type, GestureRecognizerFactory>{
HorizontalDragGestureRecognizer:
GestureRecognizerFactoryWithHandlers<
HorizontalDragGestureRecognizer>(
() => HorizontalDragGestureRecognizer(),
(HorizontalDragGestureRecognizer instance) {
instance
..onDown = _handleDragDown
..onStart = _handleDragStart
..onUpdate = _handleDragUpdate
..onEnd = _handleDragEnd
..onCancel = _handleDragCancel
..minFlingDistance = _physics?.minFlingDistance
..minFlingVelocity = _physics?.minFlingVelocity
..maxFlingVelocity = _physics?.maxFlingVelocity
..dragStartBehavior = widget.dragStartBehavior;
},
),
};
break;
}
}
_lastCanDrag = canDrag;
_lastAxisDirection = widget.axis;
if (_gestureDetectorKey.currentState != null) {
_gestureDetectorKey.currentState!
.replaceGestureRecognizers(_gestureRecognizers);
}
}
@override
TickerProvider get vsync => this;
@override
@protected
void setIgnorePointer(bool value) {
if (_shouldIgnorePointer == value) return;
_shouldIgnorePointer = value;
if (_ignorePointerKey.currentContext != null) {
final RenderIgnorePointer renderBox = _ignorePointerKey.currentContext!
.findRenderObject() as RenderIgnorePointer;
renderBox.ignoring = _shouldIgnorePointer;
}
}
@override
BuildContext? get notificationContext => _gestureDetectorKey.currentContext;
@override
BuildContext get storageContext => context;
// TOUCH HANDLERS
Drag? _drag;
ScrollHoldController? _hold;
void _handleDragDown(DragDownDetails _) {
assert(_drag == null);
assert(_hold == null);
_hold = position!.hold(_disposeHold);
}
void _handleDragStart(DragStartDetails details) {
// It's possible for _hold to become null between _handleDragDown and
// _handleDragStart, for example if some user code calls jumpTo or otherwise
// triggers a new activity to begin.
assert(_drag == null);
_drag = position!.drag(details, _disposeDrag);
assert(_drag != null);
assert(_hold == null);
}
void _handleDragUpdate(DragUpdateDetails details) {
// _drag might be null if the drag activity ended and called _disposeDrag.
assert(_hold == null || _drag == null);
_drag?.update(details);
}
void _handleDragEnd(DragEndDetails details) {
// _drag might be null if the drag activity ended and called _disposeDrag.
assert(_hold == null || _drag == null);
_drag?.end(details);
assert(_drag == null);
}
void _handleDragCancel() {
// _hold might be null if the drag started.
// _drag might be null if the drag activity ended and called _disposeDrag.
assert(_hold == null || _drag == null);
_hold?.cancel();
_drag?.cancel();
assert(_hold == null);
assert(_drag == null);
}
void _disposeHold() {
_hold = null;
}
void _disposeDrag() {
_drag = null;
}
// SCROLL WHEEL
// Returns the offset that should result from applying [event] to the current
// position, taking min/max scroll extent into account.
double _targetScrollOffsetForPointerScroll(PointerScrollEvent event) {
double delta = widget.axis == Axis.horizontal
? event.scrollDelta.dx
: event.scrollDelta.dy;
if (axisDirectionIsReversed(widget.axisDirection)) {
delta *= -1;
}
return math.min(
math.max(position!.pixels + delta, position!.minScrollExtent),
position!.maxScrollExtent,
);
}
void _receivedPointerSignal(PointerSignalEvent event) {
if (event is PointerScrollEvent && position != null) {
final double targetScrollOffset =
_targetScrollOffsetForPointerScroll(event);
// Only express interest in the event if it would actually result in a scroll.
if (targetScrollOffset != position!.pixels) {
GestureBinding.instance.pointerSignalResolver
.register(event, _handlePointerScroll);
}
}
}
void _handlePointerScroll(PointerEvent event) {
assert(event is PointerScrollEvent);
if (_physics != null && !_physics!.shouldAcceptUserOffset(position!)) {
return;
}
final double targetScrollOffset =
_targetScrollOffsetForPointerScroll(event as PointerScrollEvent);
if (targetScrollOffset != position!.pixels) {
position!.jumpTo(targetScrollOffset);
}
}
// DESCRIPTION
@override
Widget build(BuildContext context) {
assert(position != null);
// _ScrollableScope must be placed above the BuildContext returned by
// notificationContext so that we can get this _CustomPointerScrollableState
// by doing the following:
//
// ScrollNotification notification;
// CustomPointerScrollable.of(notification.context)
//
// Since notificationContext is pointing to _gestureDetectorKey.context, _ScrollableScope
// must be placed above the widget using it: RawGestureDetector
Widget result = _ScrollableScope(
scrollable: this,
position: position!,
// TODO(ianh): Having all these global keys is sad.
child: Listener(
onPointerSignal:
widget.customPointerSignalHandler ?? _receivedPointerSignal,
child: RawGestureDetector(
key: _gestureDetectorKey,
gestures: _gestureRecognizers,
behavior: HitTestBehavior.opaque,
excludeFromSemantics: widget.excludeFromSemantics,
child: Semantics(
explicitChildNodes: !widget.excludeFromSemantics,
child: IgnorePointer(
key: _ignorePointerKey,
ignoring: _shouldIgnorePointer,
child: widget.viewportBuilder(context, position!),
),
),
),
),
);
if (!widget.excludeFromSemantics) {
result = _ScrollSemantics(
key: _scrollSemanticsKey,
position: position!,
allowImplicitScrolling: widget.physics?.allowImplicitScrolling ??
_physics!.allowImplicitScrolling,
semanticChildCount: widget.semanticChildCount,
child: result,
);
}
// In contrast to scrollable.dart, _configuration.buildScrollbar is not
// called since scrollbars are added manually where needed.
return _configuration.buildOverscrollIndicator(
context,
result,
ScrollableDetails(
controller: widget.controller!,
direction: axisDirection,
),
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ScrollPosition>('position', position));
}
}
// The following classes were copied from the Flutter framework with minor
// changes to use with [CustomPointerScrollable] instead of [Scrollable]. See
// flutter/lib/src/widgets/scrollable.dart for original classes.
// Enable Scrollable.of() to work as if _CustomPointerScrollableState was an
// inherited widget. _CustomPointerScrollableState.build() always rebuilds its
// _ScrollableScope.
class _ScrollableScope extends InheritedWidget {
const _ScrollableScope({
Key? key,
required this.scrollable,
required this.position,
required Widget child,
}) : super(key: key, child: child);
final CustomPointerScrollableState scrollable;
final ScrollPosition position;
@override
bool updateShouldNotify(_ScrollableScope old) {
return position != old.position;
}
}
/// With [_ScrollSemantics] certain child [SemanticsNode]s can be
/// excluded from the scrollable area for semantics purposes.
///
/// Nodes, that are to be excluded, have to be tagged with
/// [RenderViewport.excludeFromScrolling] and the [RenderAbstractViewport] in
/// use has to add the [RenderViewport.useTwoPaneSemantics] tag to its
/// [SemanticsConfiguration] by overriding
/// [RenderObject.describeSemanticsConfiguration].
///
/// If the tag [RenderViewport.useTwoPaneSemantics] is present on the viewport,
/// two semantics nodes will be used to represent the [Scrollable]: The outer
/// node will contain all children, that are excluded from scrolling. The inner
/// node, which is annotated with the scrolling actions, will house the
/// scrollable children.
class _ScrollSemantics extends SingleChildRenderObjectWidget {
const _ScrollSemantics({
Key? key,
required this.position,
required this.allowImplicitScrolling,
required this.semanticChildCount,
Widget? child,
}) : assert(semanticChildCount == null || semanticChildCount >= 0),
super(key: key, child: child);
final ScrollPosition position;
final bool allowImplicitScrolling;
final int? semanticChildCount;
@override
_RenderScrollSemantics createRenderObject(BuildContext context) {
return _RenderScrollSemantics(
position: position,
allowImplicitScrolling: allowImplicitScrolling,
semanticChildCount: semanticChildCount,
);
}
@override
void updateRenderObject(
BuildContext context,
_RenderScrollSemantics renderObject,
) {
renderObject
..allowImplicitScrolling = allowImplicitScrolling
..position = position
..semanticChildCount = semanticChildCount;
}
}
class _RenderScrollSemantics extends RenderProxyBox {
_RenderScrollSemantics({
required ScrollPosition position,
required bool allowImplicitScrolling,
required int? semanticChildCount,
RenderBox? child,
}) : _position = position,
_allowImplicitScrolling = allowImplicitScrolling,
_semanticChildCount = semanticChildCount,
super(child) {
position.addListener(markNeedsSemanticsUpdate);
}
/// Whether this render object is excluded from the semantic tree.
ScrollPosition get position => _position;
ScrollPosition _position;
set position(ScrollPosition value) {
if (value == _position) return;
_position.removeListener(markNeedsSemanticsUpdate);
_position = value;
_position.addListener(markNeedsSemanticsUpdate);
markNeedsSemanticsUpdate();
}
/// Whether this node can be scrolled implicitly.
bool get allowImplicitScrolling => _allowImplicitScrolling;
bool _allowImplicitScrolling;
set allowImplicitScrolling(bool value) {
if (value == _allowImplicitScrolling) return;
_allowImplicitScrolling = value;
markNeedsSemanticsUpdate();
}
int? get semanticChildCount => _semanticChildCount;
int? _semanticChildCount;
set semanticChildCount(int? value) {
if (value == semanticChildCount) return;
_semanticChildCount = value;
markNeedsSemanticsUpdate();
}
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config.isSemanticBoundary = true;
if (position.haveDimensions) {
config
..hasImplicitScrolling = allowImplicitScrolling
..scrollPosition = _position.pixels
..scrollExtentMax = _position.maxScrollExtent
..scrollExtentMin = _position.minScrollExtent
..scrollChildCount = semanticChildCount;
}
}
SemanticsNode? _innerNode;
@override
void assembleSemanticsNode(
SemanticsNode node,
SemanticsConfiguration config,
Iterable<SemanticsNode> children,
) {
if (children.isEmpty ||
!children.first.isTagged(RenderViewport.useTwoPaneSemantics)) {
super.assembleSemanticsNode(node, config, children);
return;
}
(_innerNode ??= SemanticsNode(showOnScreen: showOnScreen)).rect = node.rect;
int? firstVisibleIndex;
final List<SemanticsNode> excluded = <SemanticsNode>[_innerNode!];
final List<SemanticsNode> included = <SemanticsNode>[];
for (final SemanticsNode child in children) {
assert(child.isTagged(RenderViewport.useTwoPaneSemantics));
if (child.isTagged(RenderViewport.excludeFromScrolling)) {
excluded.add(child);
} else {
if (!child.hasFlag(SemanticsFlag.isHidden)) {
firstVisibleIndex ??= child.indexInParent;
}
included.add(child);
}
}
config.scrollIndex = firstVisibleIndex;
node.updateWith(config: null, childrenInInversePaintOrder: excluded);
_innerNode!
.updateWith(config: config, childrenInInversePaintOrder: included);
}
@override
void clearSemantics() {
super.clearSemantics();
_innerNode = null;
}
}
| devtools/packages/devtools_app/lib/src/shared/primitives/custom_pointer_scroll_view.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/primitives/custom_pointer_scroll_view.dart",
"repo_id": "devtools",
"token_count": 9964
} | 106 |
// 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.
/// Extracts the current DevTools page from the given [url].
String extractCurrentPageFromUrl(String url) {
// The url can be in one of two forms:
// - /page?uri=xxx
// - /?page=xxx&uri=yyy (original formats IDEs may use)
// Use the path in preference to &page= as it's the one DevTools is updating
final uri = Uri.parse(url);
return uri.path == '/'
? uri.queryParameters['page'] ?? ''
: uri.path.substring(1);
}
/// Maps DevTools URLs in the original fragment format onto the equivalent URLs
/// in the new URL format.
///
/// Returns `null` if [url] is not a legacy URL.
String? mapLegacyUrl(String url) {
final uri = Uri.parse(url);
// Old formats include:
// http://localhost:123/#/inspector?uri=ws://...
// http://localhost:123/#/?page=inspector&uri=ws://...
final isRootRequest = uri.path == '/' || uri.path.endsWith('/devtools/');
if (isRootRequest && uri.fragment.isNotEmpty) {
final basePath = uri.path;
// Convert the URL by removing the fragment separator.
final newUrl = url
// Handle localhost:123/#/inspector?uri=xxx
.replaceFirst('/#/', '/')
// Handle localhost:123/#?page=inspector&uri=xxx
.replaceFirst('/#', '');
// Move page names from the querystring into the path.
var newUri = Uri.parse(newUrl);
final page = newUri.queryParameters['page'];
if (newUri.path == basePath && page != null) {
final newParams = {...newUri.queryParameters}..remove('page');
newUri = newUri.replace(
path: '$basePath$page',
queryParameters: newParams,
);
}
return newUri.toString();
}
return null;
}
| devtools/packages/devtools_app/lib/src/shared/primitives/url_utils.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/primitives/url_utils.dart",
"repo_id": "devtools",
"token_count": 652
} | 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 'dart:convert';
import 'package:clock/clock.dart';
import 'package:devtools_shared/devtools_shared.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart';
import 'package:logging/logging.dart';
import '../../../devtools.dart' as devtools show version;
import '../shared/notifications.dart';
import 'analytics/analytics.dart' as ga;
import 'config_specific/launch_url/launch_url.dart';
import 'development_helpers.dart';
import 'globals.dart';
import 'primitives/utils.dart';
import 'server/server.dart' as server;
final _log = Logger('survey');
class SurveyService {
static const _noThanksLabel = 'NO THANKS';
static const _takeSurveyLabel = 'TAKE SURVEY';
static const _maxShowSurveyCount = 5;
static final _metadataUrl = Uri.https(
'storage.googleapis.com',
'flutter-uxr/surveys/devtools-survey-metadata.json',
);
/// Duration for which we should show the survey notification.
///
/// We use a very long time here to give the appearance of a persistent
/// notification. The user will need to interact with the prompt to dismiss
/// it.
static const _notificationDuration = Duration(days: 1);
DevToolsSurvey? _cachedSurvey;
Future<DevToolsSurvey?> get activeSurvey async {
// If the server is unavailable we don't need to do anything survey related.
if (!server.isDevToolsServerAvailable) return null;
_cachedSurvey ??= await fetchSurveyContent();
if (_cachedSurvey?.id != null) {
await server.setActiveSurvey(_cachedSurvey!.id!);
}
if (await _shouldShowSurvey()) {
return _cachedSurvey;
}
return null;
}
void maybeShowSurveyPrompt() async {
final survey = await activeSurvey;
if (survey != null) {
final message = survey.title!;
final actions = [
NotificationAction(
_noThanksLabel,
() => _noThanksPressed(
message: message,
),
),
NotificationAction(
_takeSurveyLabel,
() => _takeSurveyPressed(
surveyUrl: _generateSurveyUrl(survey.url!),
message: message,
),
isPrimary: true,
),
];
WidgetsBinding.instance.addPostFrameCallback((_) {
final didPush = notificationService.pushNotification(
NotificationMessage(
message,
actions: actions,
duration: _notificationDuration,
),
allowDuplicates: false,
);
if (didPush) {
server.incrementSurveyShownCount();
}
});
}
}
String _generateSurveyUrl(String surveyUrl) {
final uri = Uri.parse(surveyUrl);
final queryParams = ga.generateSurveyQueryParameters();
return Uri(
scheme: uri.scheme,
host: uri.host,
path: uri.path,
queryParameters: queryParams,
).toString();
}
Future<bool> _shouldShowSurvey() async {
if (_cachedSurvey == null) return false;
final surveyShownCount = await server.surveyShownCount();
if (surveyShownCount >= _maxShowSurveyCount) return false;
final surveyActionTaken = await server.surveyActionTaken();
if (surveyActionTaken) return false;
return _cachedSurvey!.shouldShow;
}
@visibleForTesting
Future<DevToolsSurvey?> fetchSurveyContent() async {
try {
if (debugSurvey) {
return debugSurveyMetadata;
}
final response = await get(_metadataUrl);
if (response.statusCode == 200) {
final Map<String, dynamic> contents = json.decode(response.body);
return DevToolsSurvey.parse(contents);
}
} on Error catch (e, st) {
_log.shout('Error fetching survey content: $e', e, st);
}
return null;
}
void _noThanksPressed({
required String message,
}) async {
await server.setSurveyActionTaken();
notificationService.dismiss(message);
}
void _takeSurveyPressed({
required String surveyUrl,
required String message,
}) async {
await launchUrl(surveyUrl);
await server.setSurveyActionTaken();
notificationService.dismiss(message);
}
}
class DevToolsSurvey {
DevToolsSurvey._(
this.id,
this.startDate,
this.endDate,
this.title,
this.url,
this.minDevToolsVersion,
this.devEnvironments,
);
factory DevToolsSurvey.parse(Map<String, dynamic> json) {
final id = json[_uniqueIdKey];
final startDate = json[_startDateKey] != null
? DateTime.parse(json[_startDateKey])
: null;
final endDate =
json[_endDateKey] != null ? DateTime.parse(json[_endDateKey]) : null;
final title = json[_titleKey];
final surveyUrl = json[_urlKey];
final minDevToolsVersion = json[_minDevToolsVersionKey] != null
? SemanticVersion.parse(json[_minDevToolsVersionKey])
: null;
final devEnvironments =
(json[_devEnvironmentsKey] as List?)?.cast<String>().toList();
return DevToolsSurvey._(
id,
startDate,
endDate,
title,
surveyUrl,
minDevToolsVersion,
devEnvironments,
);
}
static const _uniqueIdKey = 'uniqueId';
static const _startDateKey = 'startDate';
static const _endDateKey = 'endDate';
static const _titleKey = 'title';
static const _urlKey = 'url';
static const _minDevToolsVersionKey = 'minDevToolsVersion';
static const _devEnvironmentsKey = 'devEnvironments';
final String? id;
final DateTime? startDate;
final DateTime? endDate;
final String? title;
/// The url for the survey that the user will open in a browser when they
/// respond to the survey prompt.
final String? url;
/// The minimum DevTools version that this survey should is for.
///
/// If the current version of DevTools is older than [minDevToolsVersion], the
/// survey prompt in DevTools will not be shown.
///
/// If [minDevToolsVersion] is null, the survey will be shown for any version
/// of DevTools as long as all the other requirements are satisfied.
final SemanticVersion? minDevToolsVersion;
/// A list of development environments to show the survey for (e.g. 'VSCode',
/// 'Android-Studio', 'IntelliJ-IDEA', 'CLI', etc.).
///
/// If [devEnvironments] is null, the survey can be shown to any platform.
///
/// The possible values for this list correspond to the possible values of
/// [_ideLaunched] from [shared/analytics/_analytics_web.dart].
final List<String>? devEnvironments;
}
extension ShowSurveyExtension on DevToolsSurvey {
bool get meetsDateRequirement => (startDate == null || endDate == null)
? false
: Range(
startDate!.millisecondsSinceEpoch,
endDate!.millisecondsSinceEpoch,
).contains(clock.now().millisecondsSinceEpoch);
bool get meetsMinVersionRequirement =>
minDevToolsVersion == null ||
SemanticVersion.parse(devtools.version)
.isSupported(minSupportedVersion: minDevToolsVersion!);
bool get meetsEnvironmentRequirement =>
devEnvironments == null || devEnvironments!.contains(ga.ideLaunched);
bool get shouldShow =>
meetsDateRequirement &&
meetsMinVersionRequirement &&
meetsEnvironmentRequirement;
}
| devtools/packages/devtools_app/lib/src/shared/survey.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/survey.dart",
"repo_id": "devtools",
"token_count": 2667
} | 108 |
// Copyright 2017 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.
/// Platform independent definition of icons.
///
/// See [HtmlIconRenderer] for a browser specific implementation of icon
/// rendering. If you add an Icon class you also need to add a renderer class
/// to handle the actual platform specific icon rendering.
/// The benefit of this approach is that icons can be const objects and tests
/// of code that uses icons can run on the Dart VM.
library;
import 'package:devtools_app_shared/ui.dart';
import 'package:flutter/material.dart';
import '../../screens/inspector/layout_explorer/ui/widgets_theme.dart';
import 'colors.dart';
class CustomIcon extends StatelessWidget {
const CustomIcon({
super.key,
required this.kind,
required this.text,
this.isAbstract = false,
});
final IconKind kind;
final String text;
final bool isAbstract;
AssetImageIcon get baseIcon => kind.icon;
@override
Widget build(BuildContext context) {
return SizedBox(
width: baseIcon.width,
height: baseIcon.height,
child: Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[
baseIcon,
Text(
text,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: scaleByFontFactor(9.0),
color: const Color(0xFF231F20),
),
),
],
),
);
}
}
/// An icon with one character
class CircleIcon extends StatelessWidget {
const CircleIcon({
super.key,
required this.text,
required this.color,
this.textColor = const Color(0xFF231F20),
});
/// Text to display. Should be one character.
final String text;
/// Background circle color.
final Color color;
/// Background circle color.
final Color textColor;
@override
Widget build(BuildContext context) {
return Container(
width: defaultIconSize,
height: defaultIconSize,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color,
),
alignment: Alignment.center,
child: Text(
text,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: scaleByFontFactor(9.0),
color: textColor,
),
),
);
}
}
class CustomIconMaker {
final Map<String, Widget> iconCache = {};
Widget? getCustomIcon(
String fromText, {
IconKind? kind,
bool isAbstract = false,
}) {
final theKind = kind ?? IconKind.classIcon;
if (fromText.isEmpty) {
return null;
}
final String text = fromText[0].toUpperCase();
final String mapKey = '${text}_${theKind.name}_$isAbstract';
return iconCache.putIfAbsent(mapKey, () {
return CustomIcon(kind: theKind, text: text, isAbstract: isAbstract);
});
}
Widget? fromWidgetName(String? name) {
if (name == null) {
return null;
}
while (name!.isNotEmpty && !isAlphabetic(name.codeUnitAt(0))) {
name = name.substring(1);
}
if (name.isEmpty) {
return null;
}
final widgetTheme = WidgetTheme.fromName(name);
final icon = widgetTheme.iconAsset;
if (icon != null) {
return iconCache.putIfAbsent(name, () {
return AssetImageIcon(asset: icon);
});
}
final text = name[0].toUpperCase();
return iconCache.putIfAbsent(name, () {
return CircleIcon(text: text, color: widgetTheme.color);
});
}
CustomIcon fromInfo(String name) {
return getCustomIcon(name, kind: IconKind.info) as CustomIcon;
}
bool isAlphabetic(int char) {
return (char < '0'.codeUnitAt(0) || char > '9'.codeUnitAt(0)) &&
char != '_'.codeUnitAt(0) &&
char != r'$'.codeUnitAt(0);
}
}
class IconKind {
const IconKind(this.name, this.icon, [AssetImageIcon? abstractIcon])
: abstractIcon = abstractIcon ?? icon;
static IconKind classIcon = const IconKind(
'class',
AssetImageIcon(asset: 'icons/custom/class.png'),
AssetImageIcon(asset: 'icons/custom/class_abstract.png'),
);
static IconKind field = const IconKind(
'fields',
AssetImageIcon(asset: 'icons/custom/fields.png'),
);
static IconKind interface = const IconKind(
'interface',
AssetImageIcon(asset: 'icons/custom/interface.png'),
);
static IconKind method = const IconKind(
'method',
AssetImageIcon(asset: 'icons/custom/method.png'),
AssetImageIcon(asset: 'icons/custom/method_abstract.png'),
);
static IconKind property = const IconKind(
'property',
AssetImageIcon(asset: 'icons/custom/property.png'),
);
static IconKind info = const IconKind(
'info',
AssetImageIcon(asset: 'icons/custom/info.png'),
);
final String name;
final AssetImageIcon icon;
final AssetImageIcon abstractIcon;
}
class ColorIcon extends StatelessWidget {
const ColorIcon(this.color, {super.key});
final Color color;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return CustomPaint(
painter: _ColorIconPainter(color, colorScheme),
size: Size(defaultIconSize, defaultIconSize),
);
}
}
class ColorIconMaker {
final Map<Color, ColorIcon> iconCache = {};
ColorIcon getCustomIcon(Color color) {
return iconCache.putIfAbsent(color, () => ColorIcon(color));
}
}
class _ColorIconPainter extends CustomPainter {
const _ColorIconPainter(this.color, this.colorScheme);
final Color color;
final ColorScheme colorScheme;
static const double iconMargin = 1;
@override
void paint(Canvas canvas, Size size) {
// draw a black and gray grid to use as the background to disambiguate
// opaque colors from translucent colors.
final greyPaint = Paint()..color = colorScheme.grey;
final iconRect = Rect.fromLTRB(
iconMargin,
iconMargin,
size.width - iconMargin,
size.height - iconMargin,
);
canvas
..drawRect(
Rect.fromLTRB(
iconMargin,
iconMargin,
size.width - iconMargin,
size.height - iconMargin,
),
Paint()..color = colorScheme.surface,
)
..drawRect(
Rect.fromLTRB(
iconMargin,
iconMargin,
size.width * 0.5,
size.height * 0.5,
),
greyPaint,
)
..drawRect(
Rect.fromLTRB(
size.width * 0.5,
size.height * 0.5,
size.width - iconMargin,
size.height - iconMargin,
),
greyPaint,
)
..drawRect(
iconRect,
Paint()..color = color,
)
..drawRect(
iconRect,
Paint()
..style = PaintingStyle.stroke
..color = colorScheme.onPrimary,
);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
if (oldDelegate is _ColorIconPainter) {
return oldDelegate.colorScheme.isLight != colorScheme.isLight;
}
return true;
}
}
class FlutterMaterialIcons {
FlutterMaterialIcons._();
static Icon getIconForCodePoint(int charCode, ColorScheme colorScheme) {
return Icon(IconData(charCode), color: colorScheme.onPrimary);
}
}
class AssetImageIcon extends StatelessWidget {
const AssetImageIcon({
super.key,
required this.asset,
double? height,
double? width,
}) : _width = width,
_height = height;
final String asset;
final double? _height;
final double? _width;
double get width => _width ?? defaultIconSize;
double get height => _height ?? defaultIconSize;
@override
Widget build(BuildContext context) {
return Image(
image: AssetImage(asset),
height: height,
width: width,
fit: BoxFit.fill,
);
}
}
class Octicons {
static const IconData bug = IconData(61714, fontFamily: 'Octicons');
static const IconData info = IconData(61778, fontFamily: 'Octicons');
static const IconData deviceMobile = IconData(61739, fontFamily: 'Octicons');
static const IconData fileZip = IconData(61757, fontFamily: 'Octicons');
static const IconData clippy = IconData(61724, fontFamily: 'Octicons');
static const IconData package = IconData(61812, fontFamily: 'Octicons');
static const IconData dashboard = IconData(61733, fontFamily: 'Octicons');
static const IconData pulse = IconData(61823, fontFamily: 'Octicons');
}
| devtools/packages/devtools_app/lib/src/shared/ui/icons.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/shared/ui/icons.dart",
"repo_id": "devtools",
"token_count": 3255
} | 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.
import 'package:ansicolor/ansicolor.dart';
import 'package:devtools_app/devtools_app.dart';
import 'package:devtools_app/src/shared/console/widgets/console_pane.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:devtools_test/devtools_test.dart';
import 'package:devtools_test/helpers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import '../test_infra/utils/test_utils.dart';
void main() {
final fakeServiceConnection = FakeServiceConnectionManager();
final debuggerController = createMockDebuggerControllerWithDefaults();
const windowSize = Size(4000.0, 4000.0);
when(fakeServiceConnection.serviceManager.connectedApp!.isProfileBuildNow)
.thenReturn(false);
when(fakeServiceConnection.serviceManager.connectedApp!.isDartWebAppNow)
.thenReturn(false);
setGlobal(ServiceConnectionManager, fakeServiceConnection);
setGlobal(IdeTheme, IdeTheme());
setGlobal(ScriptManager, MockScriptManager());
setGlobal(NotificationService, NotificationService());
setGlobal(EvalService, MockEvalService());
setGlobal(
DevToolsEnvironmentParameters,
ExternalDevToolsEnvironmentParameters(),
);
setGlobal(PreferencesController, PreferencesController());
fakeServiceConnection.consoleService.ensureServiceInitialized();
when(fakeServiceConnection.errorBadgeManager.errorCountNotifier('debugger'))
.thenReturn(ValueNotifier<int>(0));
Future<void> pumpConsole(
WidgetTester tester,
DebuggerController controller,
) async {
await tester.pumpWidget(
wrapWithControllers(
Row(
children: [
Flexible(child: ConsolePaneHeader()),
const Expanded(child: ConsolePane()),
],
),
debugger: controller,
),
);
}
group('ConsoleControls', () {
final stdio = ['First line', _ansiCodesOutput(), 'Third line'];
void appendStdioLines() {
for (var line in stdio) {
serviceConnection.consoleService.appendStdio('$line\n');
}
}
testWidgetsWithWindowSize(
'Tapping the Console Clear button clears stdio.',
windowSize,
(WidgetTester tester) async {
serviceConnection.consoleService.clearStdio();
serviceConnection.consoleService.appendStdio(_ansiCodesOutput());
await pumpConsole(tester, debuggerController);
final clearButton = find.byKey(ConsolePane.clearStdioButtonKey);
expect(clearButton, findsOneWidget);
await tester.tap(clearButton);
expect(serviceConnection.consoleService.stdio.value, isEmpty);
},
);
group('Clipboard', () {
String clipboardContents = '';
final expected = stdio.join('\n');
setUp(() {
appendStdioLines();
setupClipboardCopyListener(
clipboardContentsCallback: (contents) {
clipboardContents = contents ?? '';
},
);
});
tearDown(() {
// Cleanup the SystemChannel
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null);
});
testWidgetsWithWindowSize(
'Tapping the Copy to Clipboard button attempts to copy stdio to clipboard.',
windowSize,
(WidgetTester tester) async {
await pumpConsole(tester, debuggerController);
final copyButton = find.byKey(ConsolePane.copyToClipboardButtonKey);
expect(copyButton, findsOneWidget);
expect(clipboardContents, isEmpty);
await tester.tap(copyButton);
expect(clipboardContents, equals(expected));
},
);
});
});
}
String _ansiCodesOutput() {
final sb = StringBuffer();
sb.write('Ansi color codes processed for ');
final pen = AnsiPen()..rgb(r: 0.8, g: 0.3, b: 0.4, bg: true);
sb.write(pen('console'));
return sb.toString();
}
| devtools/packages/devtools_app/test/debugger/debugger_console_test.dart/0 | {
"file_path": "devtools/packages/devtools_app/test/debugger/debugger_console_test.dart",
"repo_id": "devtools",
"token_count": 1551
} | 110 |
// 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:collection/collection.dart';
import 'package:devtools_app/devtools_app.dart';
import 'package:devtools_app/src/screens/debugger/debugger_model.dart';
import 'package:devtools_app/src/screens/debugger/program_explorer.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:devtools_test/devtools_test.dart';
import 'package:devtools_test/helpers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:vm_service/vm_service.dart';
import '../test_infra/test_data/debugger/vm_service_object_tree.dart';
import '../test_infra/utils/tree_utils.dart';
void main() {
group('Mock ProgramExplorer', () {
late MockProgramExplorerController mockProgramExplorerController;
setUp(() {
final fakeServiceConnection = FakeServiceConnectionManager();
mockConnectedApp(
fakeServiceConnection.serviceManager.connectedApp!,
isFlutterApp: true,
isProfileBuild: false,
isWebApp: false,
);
mockProgramExplorerController =
createMockProgramExplorerControllerWithDefaults();
setGlobal(IdeTheme, IdeTheme());
setGlobal(ServiceConnectionManager, fakeServiceConnection);
setGlobal(
DevToolsEnvironmentParameters,
ExternalDevToolsEnvironmentParameters(),
);
setGlobal(PreferencesController, PreferencesController());
});
testWidgets('builds when not initialized', (WidgetTester tester) async {
when(mockProgramExplorerController.initialized)
.thenReturn(const FixedValueListenable(false));
await tester.pumpWidget(
wrap(
ProgramExplorer(controller: mockProgramExplorerController),
),
);
expect(find.byType(CenteredCircularProgressIndicator), findsOneWidget);
});
testWidgets('builds when initialized', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
ProgramExplorer(controller: mockProgramExplorerController),
),
);
expect(find.byType(AreaPaneHeader), findsNWidgets(2));
expect(find.text('File Explorer'), findsOneWidget);
expect(find.text('Outline'), findsOneWidget);
expect(find.byType(FlexSplitColumn), findsOneWidget);
});
});
// TODO(https://github.com/flutter/devtools/issues/4227): write more thorough
// tests for the ProgramExplorer widget.
group('Fake ProgramExplorer', () {
late final FakeServiceConnectionManager fakeServiceConnection;
setUpAll(() {
fakeServiceConnection = FakeServiceConnectionManager();
when(fakeServiceConnection.serviceManager.connectedApp!.isProfileBuildNow)
.thenReturn(false);
when(fakeServiceConnection.serviceManager.connectedApp!.isDartWebAppNow)
.thenReturn(false);
final mockScriptManager = MockScriptManager();
//`then` is used
// ignore: discarded_futures
when(mockScriptManager.getScript(any)).thenAnswer(
(_) => Future<Script>.value(testScript),
);
setGlobal(ScriptManager, mockScriptManager);
setGlobal(ServiceConnectionManager, fakeServiceConnection);
setGlobal(IdeTheme, IdeTheme());
setGlobal(NotificationService, NotificationService());
});
Future<TestProgramExplorerController> initializeProgramExplorer(
WidgetTester tester,
) async {
final programExplorerController = TestProgramExplorerController(
initializer: (controller) {
final libraryNode =
VMServiceObjectNode(controller, 'fooLib', testLib);
libraryNode.script = testScript;
libraryNode.location = ScriptLocation(testScript);
controller.rootObjectNodesInternal.add(libraryNode);
},
);
final explorer = ProgramExplorer(controller: programExplorerController);
await programExplorerController.initialize();
await tester.pumpWidget(
wrap(
Builder(
builder: explorer.build,
),
),
);
expect(programExplorerController.initialized.value, true);
expect(programExplorerController.rootObjectNodes.value.numNodes, 1);
return programExplorerController;
}
testWidgets('correctly builds nodes', (WidgetTester tester) async {
final programExplorerController = await initializeProgramExplorer(tester);
final libNode = programExplorerController.rootObjectNodes.value.first;
final outline = (await libNode.outline)!;
// The outline should only contain a single Class node.
expect(outline.length, 1);
final clsNode = outline.first;
expect(clsNode.object, const TypeMatcher<Class>());
expect(clsNode.name, testClassRef.name);
// The class should contain a function and a field.
expect(clsNode.children.length, 2);
for (final child in clsNode.children) {
if (child.object is Func) {
expect(child.object, testFunction);
} else if (child.object is Field) {
expect(child.object, testField);
} else {
fail('Unexpected node type: ${child.object.runtimeType}');
}
}
});
testWidgets(
'selection',
(WidgetTester tester) async {
final programExplorerController =
await initializeProgramExplorer(tester);
final libNode = programExplorerController.rootObjectNodes.value.first;
// No node has been selected yet, so the outline should be empty.
expect(programExplorerController.outlineNodes.value.isEmpty, true);
expect(programExplorerController.scriptSelection, isNull);
expect(
programExplorerController.outlineNodes.value
.where((e) => e.isSelected),
isEmpty,
);
// Select the library node and ensure the outline is populated.
final libNodeFinder = find.text(libNode.name);
expect(libNodeFinder, findsOneWidget);
await tester.tap(libNodeFinder);
await tester.pumpAndSettle();
expect(programExplorerController.scriptSelection, libNode);
expect(
programExplorerController.outlineNodes.value
.where((e) => e.isSelected),
isEmpty,
);
// There should be three children total, one root with two children.
expect(programExplorerController.outlineNodes.value.length, 1);
expect(programExplorerController.outlineNodes.value.numNodes, 3);
// Select one of them and check that the outline selection has been
// updated.
final outlineNode = programExplorerController.outlineNodes.value.first;
final outlineNodeFinder = find.text(outlineNode.name);
expect(outlineNodeFinder, findsOneWidget);
await tester.tap(outlineNodeFinder);
await tester.pumpAndSettle();
expect(programExplorerController.scriptSelection, libNode);
expect(
programExplorerController.outlineNodes.value
.singleWhereOrNull((e) => e.isSelected),
outlineNode,
);
},
);
});
}
| devtools/packages/devtools_app/test/debugger/program_explorer_test.dart/0 | {
"file_path": "devtools/packages/devtools_app/test/debugger/program_explorer_test.dart",
"repo_id": "devtools",
"token_count": 2740
} | 111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.