text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:steel_crypt/steel_crypt.dart' as encrypt; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Unoptimized Encryption Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Unoptimized Encryption Demo'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { late TextEditingController textEditingController; late String encryptedText; @override void initState() { super.initState(); encryptedText = ''; textEditingController = TextEditingController( text: 'Lorem ipsum dolor sit amet', ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ TextField( controller: textEditingController, ), Column( children: [ ElevatedButton( child: const Text('Encrypt'), onPressed: () { setState(() { encryptedText = encryptText(textEditingController.text); }); }, ), TextButton( child: const Text( 'Clear', style: TextStyle(color: Colors.black54), ), onPressed: () { textEditingController.clear(); setState(() { encryptedText = ''; }); }, ), ], ), Column( children: [ const Text( 'Encrypted Text:', style: TextStyle(fontWeight: FontWeight.bold), ), Text(encryptedText), ], ), ], ), ), ); } String encryptText(String stringToEncrypt) { final key = base64.encode( Uint8List.fromList( utf8.encode('my 32 length key................'), ), ); final iv = base64.encode(Uint8List(16)); final aesEncrypter = encrypt.AesCrypt(key: key, padding: encrypt.PaddingAES.pkcs7); final encryptedText = aesEncrypter.ctr.encrypt( inp: stringToEncrypt, iv: iv, ); return encryptedText; } }
devtools/case_study/code_size/optimized/code_size_package/lib/main.dart/0
{ "file_path": "devtools/case_study/code_size/optimized/code_size_package/lib/main.dart", "repo_id": "devtools", "token_count": 1476 }
79
#include "Generated.xcconfig"
devtools/case_study/code_size/unoptimized/code_size_images/ios/Flutter/Release.xcconfig/0
{ "file_path": "devtools/case_study/code_size/unoptimized/code_size_images/ios/Flutter/Release.xcconfig", "repo_id": "devtools", "token_count": 12 }
80
name: code_size_images description: A Flutter project demonstrating code size issues with images. publish_to: none environment: sdk: ^3.0.0 dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true # The assets are not compressed in this version of code_size_images. assets: - assets/
devtools/case_study/code_size/unoptimized/code_size_images/pubspec.yaml/0
{ "file_path": "devtools/case_study/code_size/unoptimized/code_size_images/pubspec.yaml", "repo_id": "devtools", "token_count": 129 }
81
#import "GeneratedPluginRegistrant.h"
devtools/case_study/code_size/unoptimized/code_size_package/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "devtools/case_study/code_size/unoptimized/code_size_package/ios/Runner/Runner-Bridging-Header.h", "repo_id": "devtools", "token_count": 13 }
82
#import "GeneratedPluginRegistrant.h"
devtools/case_study/memory_leaks/images_1/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "devtools/case_study/memory_leaks/images_1/ios/Runner/Runner-Bridging-Header.h", "repo_id": "devtools", "token_count": 13 }
83
#import "GeneratedPluginRegistrant.h"
devtools/case_study/memory_leaks/leaking_counter_1/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "devtools/case_study/memory_leaks/leaking_counter_1/ios/Runner/Runner-Bridging-Header.h", "repo_id": "devtools", "token_count": 13 }
84
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
devtools/case_study/memory_leaks/leaking_counter_1/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "devtools/case_study/memory_leaks/leaking_counter_1/macos/Runner/Configs/Release.xcconfig", "repo_id": "devtools", "token_count": 32 }
85
// 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:flutter/material.dart'; import 'common.dart'; class About extends StatefulWidget { @override State<About> createState() => AboutState(); } class AboutState extends State<About> { static const String heading = '$aboutMenu\n\n'; static const String helpText = ''' This application makes Restful HTTP GET requests to three different Restful servers. Selecting a request e.g., Weather will display the results of the received data on another page. Navigating back to the main page to select another Restful request. The menu, on the main page, has options: '''; static const String logOption = '\n $logMenu'; static const String aboutOption = '\n $aboutMenu'; static const String logDescr = ' display all messages.'; static const String aboutDescr = ' display this page.'; final TextStyle defaultStyle = const TextStyle( fontSize: 20, color: Colors.blueGrey, ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // Title title: const Text(aboutMenu), ), body: Container( padding: const EdgeInsets.all(16.0), child: RichText( text: TextSpan( style: defaultStyle, children: const [ TextSpan( text: heading, style: TextStyle( color: Colors.blueGrey, fontSize: 38, fontWeight: FontWeight.w700, ), ), TextSpan( text: helpText, ), TextSpan( text: logOption, style: TextStyle( fontWeight: FontWeight.w700, ), ), TextSpan( text: logDescr, ), TextSpan( text: aboutOption, style: TextStyle( fontWeight: FontWeight.w700, ), ), TextSpan( text: aboutDescr, ), ], ), ), ), ); } }
devtools/case_study/memory_leaks/memory_leak_app/lib/about.dart/0
{ "file_path": "devtools/case_study/memory_leaks/memory_leak_app/lib/about.dart", "repo_id": "devtools", "token_count": 1085 }
86
package com.example.platform_channel import android.os.Bundle import io.flutter.app.FlutterActivity import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.StringCodec; import io.flutter.plugins.GeneratedPluginRegistrant class MainActivity: FlutterActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GeneratedPluginRegistrant.registerWith(this) var channel: BasicMessageChannel<String> = BasicMessageChannel<String>(getFlutterView(), "shuttle", StringCodec.INSTANCE) channel.setMessageHandler({ message, reply -> try { reply.reply("Done!") Thread.sleep(2000) channel.send("Response from Java") } catch (e: Exception) {} }) } }
devtools/case_study/platform_channel/android/app/src/main/kotlin/com/example/platform_channel/MainActivity.kt/0
{ "file_path": "devtools/case_study/platform_channel/android/app/src/main/kotlin/com/example/platform_channel/MainActivity.kt", "repo_id": "devtools", "token_count": 259 }
87
name: platform_channel description: A Flutter example that uses a platform channel. version: 1.0.0+1 environment: sdk: ^3.0.0 dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true
devtools/case_study/platform_channel/pubspec.yaml/0
{ "file_path": "devtools/case_study/platform_channel/pubspec.yaml", "repo_id": "devtools", "token_count": 101 }
88
{ "recommendations": [ "streetsidesoftware.code-spell-checker" ] }
devtools/packages/.vscode/extensions.json/0
{ "file_path": "devtools/packages/.vscode/extensions.json", "repo_id": "devtools", "token_count": 41 }
89
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: invalid_use_of_visible_for_testing_member, valid use for benchmark tests. import 'dart:async'; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_test/helpers.dart'; import 'package:devtools_test/test_data.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../common.dart'; import '_cpu_profiler_automator.dart'; import '_performance_automator.dart'; /// A class that automates the DevTools web app. class DevToolsAutomater { DevToolsAutomater({ required this.benchmark, required this.stopWarmingUpCallback, }); /// The current benchmark. final DevToolsBenchmark benchmark; /// A function to call when warm-up is finished. /// /// This function is intended to ask `Recorder` to mark the warm-up phase /// as over. final void Function() stopWarmingUpCallback; /// Whether the automation has ended. bool finished = false; /// A widget controller for automation. late LiveWidgetController controller; /// The [DevToolsApp] widget with automation. Widget createWidget() { // There is no `catchError` here, because all errors are caught by // the zone set up in `lib/web_benchmarks.dart` in `flutter/flutter`. Future<void>.delayed(safePumpDuration, automateDevToolsGestures); return DevToolsApp( defaultScreens(sampleData: sampleData), AnalyticsController( enabled: false, firstRun: false, consentMessage: 'fake message', ), ); } Future<void> automateDevToolsGestures() async { await warmUp(); switch (benchmark) { case DevToolsBenchmark.navigateThroughOfflineScreens: await _handleNavigateThroughOfflineScreens(); case DevToolsBenchmark.offlineCpuProfilerScreen: await CpuProfilerScreenAutomator(controller).run(); case DevToolsBenchmark.offlinePerformanceScreen: await PerformanceScreenAutomator(controller).run(); } // At the end of the test, mark as finished. finished = true; } /// Warm up the animation. Future<void> warmUp() async { logStatus('Warming up.'); // Let animation stop. await animationStops(); // Set controller. controller = LiveWidgetController(WidgetsBinding.instance); await controller.pumpAndSettle(); // TODO(kenz): investigate if we need to do something like the Flutter // Gallery benchmark tests to warn up the Flutter engine. // When warm-up finishes, inform the recorder. stopWarmingUpCallback(); logStatus('Warm-up finished.'); } Future<void> _handleNavigateThroughOfflineScreens() async { logStatus('Navigate through offline DevTools tabs'); await navigateThroughDevToolsScreens( controller, runWithExpectations: false, ); logStatus('End navigate through offline DevTools tabs'); } } const Duration _animationCheckingInterval = Duration(milliseconds: 50); Future<void> animationStops() async { if (!WidgetsBinding.instance.hasScheduledFrame) return; final stopped = Completer<void>(); Timer.periodic(_animationCheckingInterval, (timer) { if (!WidgetsBinding.instance.hasScheduledFrame) { stopped.complete(); timer.cancel(); } }); await stopped.future; }
devtools/packages/devtools_app/benchmark/test_infra/automators/devtools_automator.dart/0
{ "file_path": "devtools/packages/devtools_app/benchmark/test_infra/automators/devtools_automator.dart", "repo_id": "devtools", "token_count": 1122 }
90
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"> <g fill="#6E6E6E" fill-rule="evenodd" transform="translate(1 3)"> <path d="M2,0 L12,0 L12,10 L2,10 L2,0 Z M3,1 L3,9 L11,9 L11,1 L3,1 Z"/> <rect width="1" height="10"/> <rect width="1" height="10" x="13"/> </g> </svg>
devtools/packages/devtools_app/icons/general/tbShown.svg/0
{ "file_path": "devtools/packages/devtools_app/icons/general/tbShown.svg", "repo_id": "devtools", "token_count": 159 }
91
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:js_interop'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_extensions/api.dart'; import 'package:devtools_extensions/utils.dart'; import 'package:flutter/material.dart'; import 'package:web/web.dart'; import '../../shared/banner_messages.dart'; import '../../shared/common_widgets.dart'; import '../../shared/globals.dart'; import '_controller_web.dart'; import 'controller.dart'; class EmbeddedExtension extends StatefulWidget { const EmbeddedExtension({super.key, required this.controller}); final EmbeddedExtensionController controller; @override State<EmbeddedExtension> createState() => _EmbeddedExtensionState(); } class _EmbeddedExtensionState extends State<EmbeddedExtension> with AutoDisposeMixin { late final EmbeddedExtensionControllerImpl _embeddedExtensionController; late final _ExtensionIFrameController iFrameController; @override void initState() { super.initState(); _embeddedExtensionController = widget.controller as EmbeddedExtensionControllerImpl; iFrameController = _ExtensionIFrameController(_embeddedExtensionController) ..init(); } @override void dispose() { iFrameController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( color: Theme.of(context).scaffoldBackgroundColor, child: ValueListenableBuilder<bool>( valueListenable: extensionService.refreshInProgress, builder: (context, refreshing, _) { if (refreshing) { return const CenteredCircularProgressIndicator(); } return HtmlElementView( viewType: _embeddedExtensionController.viewId, ); }, ), ); } } class _ExtensionIFrameController extends DisposableController with AutoDisposeControllerMixin implements DevToolsExtensionHostInterface { _ExtensionIFrameController(this.embeddedExtensionController); final EmbeddedExtensionControllerImpl embeddedExtensionController; /// Completes when the extension iFrame has received the first event on the /// 'onLoad' stream. late final Completer<void> _iFrameReady; /// Completes when the extension's postMessage handler is ready. /// /// We know this handler is ready when we receive a /// [DevToolsExtensionEventType.pong] event from the /// extension, which it will send in response to a /// [DevToolsExtensionEventType.ping] event sent from DevTools. late final Completer<void> _extensionHandlerReady; /// Timer that will poll until [_extensionHandlerReady] is complete or until /// [_pollUntilReadyTimeout] has passed. Timer? _pollForExtensionHandlerReady; static const _pollUntilReadyTimeout = Duration(seconds: 10); /// The listener that is added to DevTools' [html.window] to receive messages /// from the extension. /// /// We need to store this in a variable so that the listener is properly /// removed in [dispose]. Otherwise, we will end up in a state where we are /// leaking listeners when an extension is disabled and re-enabled. EventListener? _handleMessageListener; void init() { _iFrameReady = Completer<void>(); _extensionHandlerReady = Completer<void>(); unawaited( embeddedExtensionController.extensionIFrame.onLoad.first.then((_) { _iFrameReady.complete(); }), ); window.addEventListener( 'message', _handleMessageListener = _handleMessage.toJS, ); autoDisposeStreamSubscription( embeddedExtensionController.extensionPostEventStream.stream .listen((event) async { final ready = await _pingExtensionUntilReady(); if (ready) { switch (event.type) { case DevToolsExtensionEventType.forceReload: forceReload(); break; default: _postMessage(event); } } else { // TODO(kenz): we may want to give the user a way to retry the failed // request or show a more permanent error UI where we guide them to // file an issue against the extension package. notificationService.pushError( 'Something went wrong. The ' '${embeddedExtensionController.extensionConfig.name} extension is ' 'not ready.', reportExplanation: 'The extension did not respond to multiple ' 'DevToolsExtensionEventType.ping events with the expected ' 'DevToolsExtensionEventType.pong event.', ); } }), ); addAutoDisposeListener(preferences.darkModeTheme, () { updateTheme( theme: preferences.darkModeTheme.value ? ExtensionEventParameters.themeValueDark : ExtensionEventParameters.themeValueLight, ); }); } void _postMessage(DevToolsExtensionEvent event) async { // In [integrationTestMode] we are loading a placeholder url // (https://flutter.dev/) in the extension iFrame, so trying to post a // message causes a cross-origin security error. Return early when // [integrationTestMode] is true so that [_postMessage] calls are a no-op. if (integrationTestMode) return; await _iFrameReady.future; final message = event.toJson(); assert( embeddedExtensionController.extensionIFrame.contentWindow != null, 'Something went wrong. The iFrame\'s contentWindow is null after the' ' _iFrameReady future completed.', ); embeddedExtensionController.extensionIFrame.contentWindow!.postMessage( message.jsify(), embeddedExtensionController.extensionUrl.toJS, ); } void _handleMessage(Event e) { final extensionEvent = tryParseExtensionEvent(e); if (extensionEvent != null) { onEventReceived( extensionEvent, onUnknownEvent: () => notificationService.push( 'Unknown event received from extension: $extensionEvent}', ), ); } } /// Sends [DevToolsExtensionEventType.ping] events to the extension until we /// receive the expected [DevToolsExtensionEventType.pong] response, or until /// [_pollUntilReadyTimeout] has passed. /// /// Returns whether the extension eventually became ready. Future<bool> _pingExtensionUntilReady() async { var ready = true; if (!_extensionHandlerReady.isCompleted) { _pollForExtensionHandlerReady = Timer.periodic(const Duration(milliseconds: 200), (_) { // Once the extension UI is ready, the extension will receive this // [DevToolsExtensionEventType.ping] message and return a // [DevToolsExtensionEventType.pong] message, handled in [_handleMessage]. ping(); }); await _extensionHandlerReady.future.timeout( _pollUntilReadyTimeout, onTimeout: () { ready = false; _pollForExtensionHandlerReady?.cancel(); }, ); _pollForExtensionHandlerReady?.cancel(); } return ready; } @override void dispose() { window.removeEventListener('message', _handleMessageListener); _handleMessageListener = null; _pollForExtensionHandlerReady?.cancel(); super.dispose(); } @override void ping() { _postMessage(DevToolsExtensionEvent(DevToolsExtensionEventType.ping)); } @override void updateVmServiceConnection({required String? uri}) { _postMessage( DevToolsExtensionEvent( DevToolsExtensionEventType.vmServiceConnection, data: {ExtensionEventParameters.vmServiceConnectionUri: uri}, ), ); } @override void updateTheme({required String theme}) { assert( theme == ExtensionEventParameters.themeValueLight || theme == ExtensionEventParameters.themeValueDark, ); _postMessage( DevToolsExtensionEvent( DevToolsExtensionEventType.themeUpdate, data: {ExtensionEventParameters.theme: theme}, ), ); } @override void forceReload() { _postMessage( DevToolsExtensionEvent(DevToolsExtensionEventType.forceReload), ); } @override void onEventReceived( DevToolsExtensionEvent event, { void Function()? onUnknownEvent, }) { // Ignore events that are not supported for the Extension => DevTools // direction. if (!event.type.supportedForDirection(ExtensionEventDirection.toDevTools)) { return; } switch (event.type) { case DevToolsExtensionEventType.pong: if (!_extensionHandlerReady.isCompleted) { _extensionHandlerReady.complete(); } break; case DevToolsExtensionEventType.vmServiceConnection: updateVmServiceConnection( uri: serviceConnection.serviceManager.serviceUri, ); break; case DevToolsExtensionEventType.showNotification: _handleShowNotification(event); case DevToolsExtensionEventType.showBannerMessage: _handleShowBannerMessage(event); default: onUnknownEvent?.call(); } } void _handleShowNotification(DevToolsExtensionEvent event) { final showNotificationEvent = ShowNotificationExtensionEvent.from(event); notificationService.push(showNotificationEvent.message); } void _handleShowBannerMessage(DevToolsExtensionEvent event) { final showBannerMessageEvent = ShowBannerMessageExtensionEvent.from(event); final bannerMessageType = BannerMessageType.parse(showBannerMessageEvent.bannerMessageType) ?? BannerMessageType.warning; final bannerMessage = BannerMessage( messageType: bannerMessageType, key: Key( 'ExtensionBannerMessage - ${showBannerMessageEvent.extensionName} - ' '${showBannerMessageEvent.messageId}', ), screenId: '${showBannerMessageEvent.extensionName}_ext', textSpans: [ TextSpan( text: showBannerMessageEvent.message, style: TextStyle(fontSize: defaultFontSize), ), ], ); bannerMessages.addMessage( bannerMessage, callInPostFrameCallback: false, ignoreIfAlreadyDismissed: showBannerMessageEvent.ignoreIfAlreadyDismissed, ); } }
devtools/packages/devtools_app/lib/src/extensions/embedded/_view_web.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/extensions/embedded/_view_web.dart", "repo_id": "devtools", "token_count": 3719 }
92
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/material.dart'; import '../shared/analytics/analytics.dart' as ga; import '../shared/analytics/constants.dart' as gac; import '../shared/common_widgets.dart'; import '../shared/config_specific/launch_url/launch_url.dart'; import '../shared/globals.dart'; /// Button that, when clicked, will open the DevTools issue tracker in the /// browser. class ReportFeedbackButton extends ScaffoldAction { ReportFeedbackButton({super.key, Color? color}) : super( icon: Icons.bug_report_outlined, tooltip: 'Report feedback', color: color, onPressed: (_) { ga.select( gac.devToolsMain, gac.feedbackButton, ); unawaited( launchUrl( devToolsExtensionPoints.issueTrackerLink().url, ), ); }, ); }
devtools/packages/devtools_app/lib/src/framework/report_feedback_button.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/framework/report_feedback_button.dart", "repo_id": "devtools", "token_count": 459 }
93
// 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:vm_service/vm_service.dart'; import '../../shared/diagnostics/primitives/source_location.dart'; import '../../shared/primitives/simple_items.dart'; import '../../shared/primitives/trees.dart'; import '../../shared/ui/search.dart'; /// Whether to include properties surfaced through Diagnosticable objects as /// part of the generic Debugger view of an object. bool includeDiagnosticPropertiesInDebugger = true; /// Whether to include children surfaced through Diagnosticable objects as part /// of the generic Debugger view of an object. /// /// It is safer to set to false as it is hard to avoid confusing overlap between /// the children visible under fields for typical objects and we don't have a /// way of clarifying that these are children from the Diagnostic view of the /// object which might be different from children on fields for the Inspector /// summary tree case which has a filtered view of children. bool includeDiagnosticChildren = false; /// A tuple of a script and an optional location. class ScriptLocation { ScriptLocation( this.scriptRef, { this.location, }); final ScriptRef scriptRef; final SourcePosition? location; @override bool operator ==(Object other) { return other is ScriptLocation && other.scriptRef == scriptRef && other.location == location; } @override int get hashCode => Object.hash(scriptRef, location); @override String toString() => '${scriptRef.uri} $location'; } class SourceToken with SearchableDataMixin { SourceToken({required this.position, required this.length}); final SourcePosition position; final int length; @override String toString() { return '$position-${position.column! + length}'; } } /// A tuple of a breakpoint and a source position. abstract class BreakpointAndSourcePosition implements Comparable<BreakpointAndSourcePosition> { BreakpointAndSourcePosition._(this.breakpoint, [this.sourcePosition]); factory BreakpointAndSourcePosition.create( Breakpoint breakpoint, [ SourcePosition? sourcePosition, ]) { if (breakpoint.location is SourceLocation) { return _BreakpointAndSourcePositionResolved( breakpoint, sourcePosition, breakpoint.location as SourceLocation, ); } else if (breakpoint.location is UnresolvedSourceLocation) { return _BreakpointAndSourcePositionUnresolved( breakpoint, sourcePosition, breakpoint.location as UnresolvedSourceLocation, ); } else { throw 'invalid value for breakpoint.location'; } } final Breakpoint breakpoint; final SourcePosition? sourcePosition; bool get resolved => breakpoint.resolved ?? false; ScriptRef? get scriptRef; String? get scriptUri; int? get line; int? get column; int? get tokenPos; String? get id => breakpoint.id; @override int get hashCode => breakpoint.hashCode; @override bool operator ==(Object other) { return other is BreakpointAndSourcePosition && other.breakpoint == breakpoint; } @override int compareTo(BreakpointAndSourcePosition other) { final result = scriptUri!.compareTo(other.scriptUri!); if (result != 0) return result; if (resolved != other.resolved) return resolved ? 1 : -1; if (resolved) { final otherTokenPos = other.tokenPos; if (tokenPos != null && otherTokenPos != null) { return tokenPos! - otherTokenPos; } } else { final otherLine = other.line; if (line != null && otherLine != null) { return line! - otherLine; } } return 0; } } class _BreakpointAndSourcePositionResolved extends BreakpointAndSourcePosition { _BreakpointAndSourcePositionResolved( Breakpoint breakpoint, SourcePosition? sourcePosition, this.location, ) : super._(breakpoint, sourcePosition); final SourceLocation location; @override ScriptRef? get scriptRef => location.script; @override String? get scriptUri => location.script?.uri; @override int? get tokenPos => location.tokenPos; @override int? get line => sourcePosition?.line; @override int? get column => sourcePosition?.column; } class _BreakpointAndSourcePositionUnresolved extends BreakpointAndSourcePosition { _BreakpointAndSourcePositionUnresolved( Breakpoint breakpoint, SourcePosition? sourcePosition, this.location, ) : super._(breakpoint, sourcePosition); final UnresolvedSourceLocation location; @override ScriptRef? get scriptRef => location.script; @override String? get scriptUri => location.script?.uri ?? location.scriptUri; @override int? get tokenPos => location.tokenPos; @override int? get line => sourcePosition?.line ?? location.line; @override int? get column => sourcePosition?.column ?? location.column; } /// A tuple of a stack frame and a source position. class StackFrameAndSourcePosition { StackFrameAndSourcePosition( this.frame, { this.position, }); final Frame frame; /// This can be null. final SourcePosition? position; ScriptRef? get scriptRef => frame.location?.script; String? get scriptUri => frame.location?.script?.uri; int? get line => position?.line; int? get column => position?.column; String get callStackDisplay { final asyncMarker = frame.kind == FrameKind.kAsyncSuspensionMarker; return '$description${asyncMarker ? null : ' ($location)'}'; } String get description { const unoptimized = '[Unoptimized] '; const none = '<none>'; const asyncBreak = '<async break>'; if (frame.kind == FrameKind.kAsyncSuspensionMarker) { return asyncBreak; } var name = frame.code?.name ?? none; if (name.startsWith(unoptimized)) { name = name.substring(unoptimized.length); } name = name.replaceAll(anonymousClosureName, closureName); if (frame.code?.kind == CodeKind.kNative) { return '<native code: $name>'; } return name; } String? get location { final uri = scriptUri; if (uri == null) { return uri; } final file = uri.split('/').last; return line == null ? file : '$file:$line'; } } /// A node in a tree of scripts. /// /// A node can either be a directory (a name with potentially some child nodes), /// a script reference (where [scriptRef] is non-null), or a combination of both /// (where the node has a non-null [scriptRef] but also contains child nodes). class FileNode extends TreeNode<FileNode> { FileNode(this.name); final String name; ScriptRef? scriptRef; /// This exists to allow for O(1) lookup of children when building the tree. final Map<String, FileNode> _childrenAsMap = {}; /// Given a flat list of service protocol scripts, return a tree of scripts /// representing the best hierarchical grouping. static List<FileNode> createRootsFrom(List<ScriptRef> scripts) { // The name of this node is not exposed to users. final root = FileNode('<root>'); for (var script in scripts) { final directoryParts = ScriptRefUtils.splitDirectoryParts(script); FileNode node = root; for (var name in directoryParts) { node = node._getCreateChild(name); } node.scriptRef = script; } // Clear out the _childrenAsMap map. root._trimChildrenAsMapEntries(); return root.children; } FileNode _getCreateChild(String name) { return _childrenAsMap.putIfAbsent(name, () { final child = FileNode(name); child.parent = this; children.add(child); return child; }); } /// Clear the _childrenAsMap map recursively to save memory. void _trimChildrenAsMapEntries() { _childrenAsMap.clear(); for (var child in children) { child._trimChildrenAsMapEntries(); } } @override FileNode shallowCopy() { throw UnimplementedError( 'This method is not implemented. Implement if you ' 'need to call `shallowCopy` on an instance of this class.', ); } @override int get hashCode => scriptRef?.hashCode ?? name.hashCode; @override bool operator ==(Object other) { if (other is! FileNode) return false; final FileNode node = other; if (scriptRef == null) { return node.scriptRef != null ? false : name == node.name; } else { return node.scriptRef == null ? false : scriptRef == node.scriptRef; } } } // TODO(jacobr): refactor this code. // ignore: avoid_classes_with_only_static_members class ScriptRefUtils { static String fileName(ScriptRef scriptRef) => Uri.parse(scriptRef.uri!).path.split('/').last; /// Return the Uri for the given ScriptRef split into path segments. /// /// This is useful for converting a flat list of scripts into a directory tree /// structure. static List<String> splitDirectoryParts(ScriptRef scriptRef) { final uri = Uri.parse(scriptRef.uri!); final scheme = uri.scheme; var parts = uri.path.split('/'); // handle google3:///foo/bar if (parts.first.isEmpty) { parts = parts.where((part) => part.isNotEmpty).toList(); // Combine the first non-empty path segment with the scheme: // 'google3:foo'. parts = [ '$scheme:${parts.first}', ...parts.sublist(1), ]; } else if (parts.first.contains('.')) { // Look for and handle dotted package names (package:foo.bar). final dottedParts = parts.first.split('.'); parts = [ '$scheme:${dottedParts.first}', ...dottedParts.sublist(1), ...parts.sublist(1), ]; } else { parts = [ '$scheme:${parts.first}', ...parts.sublist(1), ]; } return parts.length > 1 ? [ parts.first, parts.sublist(1).join('/'), ] : parts; } }
devtools/packages/devtools_app/lib/src/screens/debugger/debugger_model.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/debugger/debugger_model.dart", "repo_id": "devtools", "token_count": 3360 }
94
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../shared/common_widgets.dart'; import '../../shared/config_specific/launch_url/launch_url.dart'; import '../../shared/ui/colors.dart'; import 'deep_link_list_view.dart'; import 'deep_links_controller.dart'; import 'deep_links_model.dart'; import 'deep_links_services.dart'; class ValidationDetailView extends StatelessWidget { const ValidationDetailView({ super.key, required this.linkData, required this.viewType, required this.controller, }); final LinkData linkData; final TableViewType viewType; final DeepLinksController controller; @override Widget build(BuildContext context) { return ListTileTheme( // TODO(hangyujin): Set `minTileHeight` when it is available for devtool. // related PR: https://github.com/flutter/flutter/pull/145244 data: const ListTileThemeData( dense: true, minVerticalPadding: 0, contentPadding: EdgeInsets.zero, ), child: ListView( children: [ ValidationDetailHeader(viewType: viewType, controller: controller), Padding( padding: const EdgeInsets.symmetric( horizontal: extraLargeSpacing, vertical: defaultSpacing, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'This tool helps you diagnose issues with App Links in your application.' 'Web checks are done for the web association' ' file on your website. App checks are done for the intent filters in' ' the manifest and info.plist files, routing issues, URL format, etc.', style: Theme.of(context).subtleTextStyle, ), if (viewType == TableViewType.domainView || viewType == TableViewType.singleUrlView) _DomainCheckTable(controller: controller), if (viewType == TableViewType.pathView || viewType == TableViewType.singleUrlView) _PathCheckTable(controller: controller), const SizedBox(height: extraLargeSpacing), if (linkData.domainErrors.isNotEmpty) Align( alignment: Alignment.bottomRight, child: FilledButton( onPressed: () async => await controller.validateLinks(), child: const Text('Recheck all'), ), ), const _ViewDeveloperGuide(), if (viewType == TableViewType.domainView) _DomainAssociatedLinksPanel(controller: controller), ], ), ), ], ), ); } } class ValidationDetailHeader extends StatelessWidget { const ValidationDetailHeader({ super.key, required this.viewType, required this.controller, }); final TableViewType viewType; final DeepLinksController controller; @override Widget build(BuildContext context) { return OutlineDecoration( showLeft: false, child: Container( height: actionWidgetSize, padding: const EdgeInsets.symmetric(horizontal: defaultSpacing), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( viewType == TableViewType.domainView ? 'Selected domain validation details' : 'Selected Deep link validation details', style: Theme.of(context).textTheme.titleSmall, ), IconButton( onPressed: () => controller.updateDisplayOptions(showSplitScreen: false), icon: const Icon(Icons.close), ), ], ), ), ); } } class _DomainCheckTable extends StatelessWidget { const _DomainCheckTable({ required this.controller, }); final DeepLinksController controller; @override Widget build(BuildContext context) { final linkData = controller.selectedLink.value!; final theme = Theme.of(context); return ValueListenableBuilder<String?>( valueListenable: controller.localFingerprint, builder: (context, localFingerprint, _) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const SizedBox(height: intermediateSpacing), Text('Web check', style: theme.textTheme.titleSmall), const SizedBox(height: denseSpacing), const _CheckTableHeader(), _CheckExpansionTile( initiallyExpanded: true, checkName: 'Digital assets link file', status: _CheckStatusText(hasError: linkData.domainErrors.isNotEmpty), children: <Widget>[ _Fingerprint(controller: controller), // The following checks are only displayed if a fingerprint exists. if (controller.googlePlayFingerprintsAvailability.value || localFingerprint != null) ...[ _AssetLinksJsonFileIssues(controller: controller), _HostingIssues(controller: controller), ], ], ), const SizedBox(height: intermediateSpacing), ], ); }, ); } } /// There is a general fix for the asset links json file issues: /// Update it with the generated asset link file. class _AssetLinksJsonFileIssues extends StatelessWidget { const _AssetLinksJsonFileIssues({ required this.controller, }); final DeepLinksController controller; @override Widget build(BuildContext context) { final errors = controller.selectedLink.value!.domainErrors .where( (error) => domainAssetLinksJsonFileErrors.contains(error), ) .toList(); return ExpansionTile( controlAffinity: ListTileControlAffinity.leading, title: _VerifiedOrErrorText( 'Digital Asset Links JSON file related issues', isError: errors.isNotEmpty, ), children: [ if (errors.isNotEmpty) _IssuesBorderWrap( children: [ _FailureDetails( errors: errors, oneFixGuideForAll: 'To fix above issues, publish the recommended Digital Asset Links' ' JSON file below to all of the failed website domains at the following' ' location: https://${controller.selectedLink.value!.domain}/.well-known/assetlinks.json.', ), const SizedBox(height: denseSpacing), _GenerateAssetLinksPanel(controller: controller), ], ), ], ); } } /// Hosting issue cannot be fixed by generated asset link file. /// There is a fix guide for each hosting issue. class _HostingIssues extends StatelessWidget { const _HostingIssues({required this.controller}); final DeepLinksController controller; @override Widget build(BuildContext context) { final errors = controller.selectedLink.value!.domainErrors .where((error) => domainHostingErrors.contains(error)) .toList(); return ExpansionTile( controlAffinity: ListTileControlAffinity.leading, title: _VerifiedOrErrorText( 'Hosting related issues', isError: errors.isNotEmpty, ), children: [ for (final error in errors) _IssuesBorderWrap( children: [ _FailureDetails(errors: [error]), ], ), ], ); } } class _Fingerprint extends StatelessWidget { const _Fingerprint({ required this.controller, }); final DeepLinksController controller; @override Widget build(BuildContext context) { final theme = Theme.of(context); final hasPdcFingerprint = controller.googlePlayFingerprintsAvailability.value; final haslocalFingerprint = controller.localFingerprint.value != null; late String title; if (hasPdcFingerprint && haslocalFingerprint) { title = 'PDC fingerprint and Local fingerprint are detected'; } if (hasPdcFingerprint && !haslocalFingerprint) { title = 'PDC fingerprint detected, enter a local fingerprint if needed'; } if (!hasPdcFingerprint && haslocalFingerprint) { title = 'Local fingerprint detected'; } if (!hasPdcFingerprint && !haslocalFingerprint) { title = 'Can\'t proceed check due to no fingerprint detected'; } return ExpansionTile( controlAffinity: ListTileControlAffinity.leading, title: _VerifiedOrErrorText( title, isError: !hasPdcFingerprint && !haslocalFingerprint, ), children: [ _IssuesBorderWrap( children: [ if (hasPdcFingerprint && !haslocalFingerprint) ...[ Text( 'Your PDC fingerprint has been detected. If you have local fingerprint, you can enter it below.', style: theme.subtleTextStyle, ), const SizedBox(height: denseSpacing), ], if (!hasPdcFingerprint && !haslocalFingerprint) ...[ const Text( 'Issue: no fingerprint detached locally or on PDC', ), const SizedBox(height: denseSpacing), const Text('Fix guide:'), const SizedBox(height: denseSpacing), Text( 'To fix this issue, release your app on Play Developer Console to get a fingerprint. ' 'If you are not ready to release your app, enter a local fingerprint below can also allow you' 'to proceed Android domain check.', style: theme.subtleTextStyle, ), const SizedBox(height: denseSpacing), ], // User can add local fingerprint no matter PDC fingerprint is detected or not. _LocalFingerprint(controller: controller), ], ), ], ); } } class _LocalFingerprint extends StatelessWidget { const _LocalFingerprint({ required this.controller, }); final DeepLinksController controller; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Local fingerprint'), const SizedBox(height: intermediateSpacing), controller.localFingerprint.value == null ? TextField( decoration: const InputDecoration( labelText: 'Enter your local fingerprint', hintText: 'eg: A1:B2:C3:D4:A1:B2:C3:D4:A1:B2:C3:D4:A1:B2:C3:D4:A1:B2:C3:D4:A1:B2:C3:D4:A1:B2:C3:D4:A1:B2:C3:D4', filled: true, ), onSubmitted: (fingerprint) async { final validFingerprintAdded = controller.addLocalFingerprint(fingerprint); if (!validFingerprintAdded) { await showDialog( context: context, builder: (_) { return const AlertDialog( title: Text('This is not a valid fingerprint'), content: Text( 'A valid fingerprint consists of 32 pairs of hexadecimal digits separated by colons.' 'It should be the same encoding and format as in the assetlinks.json', ), actions: [ DialogCloseButton(), ], ); }, ); } }, ) : _CodeCard( content: controller.localFingerprint.value, hasCopyAction: false, ), ], ); } } class _ViewDeveloperGuide extends StatelessWidget { const _ViewDeveloperGuide(); @override Widget build(BuildContext context) { return Align( alignment: Alignment.centerLeft, child: DevToolsButton( onPressed: () { unawaited( launchUrl( 'https://developer.android.com/training/app-links/verify-android-applinks', ), ); }, label: 'View developer guide', ), ); } } class _CodeCard extends StatelessWidget { const _CodeCard({ this.content, this.hasCopyAction = true, }); final String? content; final bool hasCopyAction; @override Widget build(BuildContext context) { return Card( color: Theme.of(context).colorScheme.alternatingBackgroundColor1, elevation: 0.0, child: Padding( padding: const EdgeInsets.all(denseSpacing), child: content != null ? Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Flexible(child: SelectionArea(child: Text(content!))), if (hasCopyAction) CopyToClipboardControl(dataProvider: () => content), ], ) : const CenteredCircularProgressIndicator(), ), ); } } class _GenerateAssetLinksPanel extends StatelessWidget { const _GenerateAssetLinksPanel({ required this.controller, }); final DeepLinksController controller; @override Widget build(BuildContext context) { final theme = Theme.of(context); return ValueListenableBuilder( valueListenable: controller.generatedAssetLinksForSelectedLink, builder: ( _, GenerateAssetLinksResult? generatedAssetLinks, __, ) { return (generatedAssetLinks != null && generatedAssetLinks.errorCode.isNotEmpty) ? Text( 'Not able to generate assetlinks.json, because the app ${controller.applicationId} is not uploaded to Google Play.', style: theme.subtleTextStyle, ) : _CodeCard(content: generatedAssetLinks?.generatedString); }, ); } } class _FailureDetails extends StatelessWidget { const _FailureDetails({ required this.errors, this.oneFixGuideForAll, }); final List<CommonError> errors; final String? oneFixGuideForAll; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ for (final error in errors) ...[ const SizedBox(height: densePadding), Text('Issue: ${error.title}'), const SizedBox(height: densePadding), Text( error.explanation, style: Theme.of(context).subtleTextStyle, ), if (oneFixGuideForAll == null) ...[ const SizedBox(height: defaultSpacing), const Text('Fix guide:'), const SizedBox(height: densePadding), Text( error.fixDetails, style: Theme.of(context).subtleTextStyle, ), ], ], if (oneFixGuideForAll != null) ...[ const SizedBox(height: defaultSpacing), const Text('Fix guide:'), const SizedBox(height: densePadding), Text( oneFixGuideForAll!, style: Theme.of(context).subtleTextStyle, ), ], ], ); } } class _DomainAssociatedLinksPanel extends StatelessWidget { const _DomainAssociatedLinksPanel({ required this.controller, }); final DeepLinksController controller; @override Widget build(BuildContext context) { final theme = Theme.of(context); final linkData = controller.selectedLink.value!; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( 'Associated deep link URL', style: theme.textTheme.titleSmall, ), Card( color: theme.colorScheme.surface, shape: const RoundedRectangleBorder(), child: Padding( padding: const EdgeInsets.all(denseSpacing), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: linkData.associatedPath .map( (path) => Padding( padding: const EdgeInsets.symmetric( vertical: denseRowSpacing, ), child: Row( children: <Widget>[ if (linkData.domainErrors.isNotEmpty) Icon( Icons.error, color: theme.colorScheme.error, size: defaultIconSize, ), const SizedBox(width: denseSpacing), Text('${linkData.domain}$path'), ], ), ), ) .toList(), ), ), ), ], ); } } class _PathCheckTable extends StatelessWidget { const _PathCheckTable({required this.controller}); final DeepLinksController controller; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const SizedBox(height: intermediateSpacing), Text( 'Path check', style: theme.textTheme.titleSmall, ), const SizedBox(height: intermediateSpacing), const _CheckTableHeader(), const Divider(height: 1.0), _IntentFilterCheck(controller: controller), const Divider(height: 1.0), _PathFormatCheck(controller: controller), ], ); } } class _IntentFilterCheck extends StatelessWidget { const _IntentFilterCheck({required this.controller}); final DeepLinksController controller; @override Widget build(BuildContext context) { final linkData = controller.selectedLink.value!; final errors = intentFilterErrors .where((error) => linkData.pathErrors.contains(error)) .toList(); return _CheckExpansionTile( checkName: 'IntentFiler', status: _CheckStatusText(hasError: errors.isNotEmpty), children: <Widget>[ if (errors.isNotEmpty) _IssuesBorderWrap( children: [ _FailureDetails( errors: errors, oneFixGuideForAll: 'Copy the following code into your Manifest file.', ), const _CodeCard( content: '''<intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> </intent-filter>''', ), ], ), ], ); } } class _PathFormatCheck extends StatelessWidget { const _PathFormatCheck({required this.controller}); final DeepLinksController controller; @override Widget build(BuildContext context) { final linkData = controller.selectedLink.value!; final hasError = linkData.pathErrors.contains(PathError.pathFormat); return _CheckExpansionTile( checkName: 'URL format', status: _CheckStatusText(hasError: hasError), children: <Widget>[ if (hasError) const _IssuesBorderWrap( children: [ _FailureDetails(errors: [PathError.pathFormat]), ], ), ], ); } } class _CheckTableHeader extends StatelessWidget { const _CheckTableHeader(); @override Widget build(BuildContext context) { return ListTile( tileColor: Theme.of(context).colorScheme.deeplinkTableHeaderColor, title: const Padding( padding: EdgeInsets.symmetric(horizontal: defaultSpacing), child: Row( children: [ Expanded(child: Text('OS')), Expanded(child: Text('Issue type')), Expanded(child: Text('Status')), ], ), ), ); } } class _CheckExpansionTile extends StatelessWidget { const _CheckExpansionTile({ required this.checkName, required this.status, required this.children, this.initiallyExpanded = false, }); final String checkName; final Widget status; final bool initiallyExpanded; final List<Widget> children; @override Widget build(BuildContext context) { final theme = Theme.of(context); return ExpansionTile( backgroundColor: theme.colorScheme.alternatingBackgroundColor2, collapsedBackgroundColor: theme.colorScheme.alternatingBackgroundColor2, initiallyExpanded: initiallyExpanded, title: Row( children: [ const SizedBox(width: defaultSpacing), const Expanded(child: Text('Android')), Expanded(child: Text(checkName)), Expanded(child: status), ], ), children: children, ); } } class _IssuesBorderWrap extends StatelessWidget { const _IssuesBorderWrap({required this.children}); final List<Widget> children; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric( horizontal: largeSpacing, vertical: densePadding, ), child: RoundedOutlinedBorder( child: Padding( padding: const EdgeInsets.symmetric( horizontal: largeSpacing, vertical: densePadding, ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: children, ), ), ), ); } } class _CheckStatusText extends StatelessWidget { const _CheckStatusText({required this.hasError}); final bool hasError; @override Widget build(BuildContext context) { final theme = Theme.of(context); return hasError ? Text( 'Check failed', style: theme.errorTextStyle, ) : Text( 'No issues found', style: TextStyle(color: theme.colorScheme.green), ); } } class _VerifiedOrErrorText extends StatelessWidget { const _VerifiedOrErrorText(this.text, {required this.isError}); final String text; final bool isError; @override Widget build(BuildContext context) { return Row( children: [ isError ? Icon( Icons.error, color: Theme.of(context).colorScheme.error, size: defaultIconSize, ) : Icon( Icons.verified, color: Theme.of(context).colorScheme.green, size: defaultIconSize, ), const SizedBox(width: denseSpacing), Text(text), ], ); } }
devtools/packages/devtools_app/lib/src/screens/deep_link_validation/validation_details_view.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/deep_link_validation/validation_details_view.dart", "repo_id": "devtools", "token_count": 10590 }
95
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; const margin = 6.0; double get arrowHeadSize => scaleByFontFactor(8.0); double get arrowMargin => scaleByFontFactor(4.0); const arrowStrokeWidth = 1.5; /// Hardcoded sizes for scaling the flex children widget properly. double get minRenderWidth => scaleByFontFactor(250.0); double get minRenderHeight => scaleByFontFactor(250.0); const minPadding = 2.0; const overflowTextHorizontalPadding = 8.0; /// The size to shrink a widget by when animating it in. const entranceMargin = 50.0; double get defaultMaxRenderWidth => scaleByFontFactor(400.0); double get defaultMaxRenderHeight => scaleByFontFactor(400.0); const widgetTitleMaxWidthPercentage = 0.75; /// Hardcoded arrow size respective to its cross axis (because it's unconstrained). double get heightAndConstraintIndicatorSize => scaleByFontFactor(48.0); double get widthAndConstraintIndicatorSize => scaleByFontFactor(56.0); double get mainAxisArrowIndicatorSize => scaleByFontFactor(48.0); double get crossAxisArrowIndicatorSize => scaleByFontFactor(48.0); double get heightOnlyIndicatorSize => scaleByFontFactor(72.0); /// Minimum size to display width/height inside the arrow double get minWidthToDisplayWidthInsideArrow => scaleByFontFactor(200.0); double get minHeightToDisplayHeightInsideArrow => scaleByFontFactor(200.0); const smallTextScaleFactor = 0.8; /// Height for limiting asset image (selected one in the drop down). double get axisAlignmentAssetImageHeight => scaleByFontFactor(24.0); double get minHeightToAllowTruncating => scaleByFontFactor(375.0); double get minWidthToAllowTruncating => scaleByFontFactor(375.0); // Story of Layout colors const mainAxisLightColor = Color(0xff2c5daa); const mainAxisDarkColor = Color(0xff2c5daa); const textColor = Color(0xff55767f); const emphasizedTextColor = Color(0xff009aca); const crossAxisLightColor = Color(0xff8ac652); const crossAxisDarkColor = Color(0xff8ac652); const mainAxisTextColorLight = Color(0xFF1375bc); const mainAxisTextColorDark = Color(0xFF1375bc); const crossAxisTextColorLight = Color(0xFF66672C); const crossAxisTextColorsDark = Color(0xFFB3D25A); const overflowBackgroundColorDark = Color(0xFFB00020); const overflowBackgroundColorLight = Color(0xFFB00020); const overflowTextColorDark = Color(0xfff5846b); const overflowTextColorLight = Color(0xffdea089); const backgroundColorSelectedDark = Color( 0x4d474747, ); // TODO(jacobr): we would like Color(0x4dedeeef) but that makes the background show through. const backgroundColorSelectedLight = Color(0x4dedeeef); extension LayoutExplorerColorScheme on ColorScheme { Color get mainAxisColor => isLight ? mainAxisLightColor : mainAxisDarkColor; Color get widgetNameColor => isLight ? Colors.white : Colors.black; Color get crossAxisColor => isLight ? crossAxisLightColor : crossAxisDarkColor; Color get mainAxisTextColor => isLight ? mainAxisTextColorLight : mainAxisTextColorDark; Color get crossAxisTextColor => isLight ? crossAxisTextColorLight : crossAxisTextColorsDark; Color get overflowBackgroundColor => isLight ? overflowBackgroundColorLight : overflowBackgroundColorDark; Color get overflowTextColor => isLight ? overflowTextColorLight : overflowTextColorDark; Color get backgroundColorSelected => isLight ? backgroundColorSelectedLight : backgroundColorSelectedDark; Color get unconstrainedColor => isLight ? unconstrainedLightColor : unconstrainedDarkColor; } const backgroundColorDark = Color(0xff30302f); const backgroundColorLight = Color(0xffffffff); const unconstrainedDarkColor = Color(0xffdea089); const unconstrainedLightColor = Color(0xfff5846b); const widthIndicatorColor = textColor; const heightIndicatorColor = textColor; const negativeSpaceDarkAssetName = 'assets/img/layout_explorer/negative_space_dark.png'; const negativeSpaceLightAssetName = 'assets/img/layout_explorer/negative_space_light.png'; final dimensionIndicatorTextStyle = TextStyle( height: 1.0, letterSpacing: 1.1, color: emphasizedTextColor, fontSize: defaultFontSize, ); TextStyle overflowingDimensionIndicatorTextStyle(ColorScheme colorScheme) => dimensionIndicatorTextStyle.merge( TextStyle( fontWeight: FontWeight.bold, color: colorScheme.overflowTextColor, ), ); Widget buildUnderline() { return Container( height: 1.0, decoration: const BoxDecoration( border: Border( bottom: BorderSide( color: textColor, width: 0.0, ), ), ), ); }
devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/theme.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/theme.dart", "repo_id": "devtools", "token_count": 1500 }
96
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../../../shared/ui/tab.dart'; import '../../panes/diff/diff_pane.dart'; import '../../panes/profile/profile_view.dart'; import '../../panes/tracing/tracing_view.dart'; import 'memory_controller.dart'; @visibleForTesting class MemoryScreenKeys { static const dartHeapTableProfileTab = Key('Dart Heap Profile Tab'); static const dartHeapAllocationTracingTab = Key('Dart Heap Allocation Tracing Tab'); static const diffTab = Key('Diff Tab'); } class MemoryTabView extends StatelessWidget { const MemoryTabView( this.controller, { super.key, }); static const _gaPrefix = 'memoryTab'; final MemoryController controller; @override Widget build(BuildContext context) { return AnalyticsTabbedView( tabs: _generateTabRecords(), initialSelectedIndex: controller.selectedFeatureTabIndex, gaScreen: gac.memory, onTabChanged: (int index) { controller.selectedFeatureTabIndex = index; }, ); } List<({DevToolsTab tab, Widget tabView})> _generateTabRecords() { return [ ( tab: DevToolsTab.create( key: MemoryScreenKeys.dartHeapTableProfileTab, tabName: 'Profile Memory', gaPrefix: _gaPrefix, ), tabView: KeepAliveWrapper( child: AllocationProfileTableView( controller: controller.controllers.profile, ), ), ), ( tab: DevToolsTab.create( key: MemoryScreenKeys.diffTab, gaPrefix: _gaPrefix, tabName: 'Diff Snapshots', ), tabView: KeepAliveWrapper( child: DiffPane( diffController: controller.controllers.diff, ), ), ), ( tab: DevToolsTab.create( key: MemoryScreenKeys.dartHeapAllocationTracingTab, tabName: 'Trace Instances', gaPrefix: _gaPrefix, ), tabView: KeepAliveWrapper( child: TracingPane(controller: controller.controllers.tracing), ), ), ]; } }
devtools/packages/devtools_app/lib/src/screens/memory/framework/connected/memory_tabs.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/framework/connected/memory_tabs.dart", "repo_id": "devtools", "token_count": 971 }
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 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../framework/connected/memory_controller.dart'; import '../../shared/primitives/simple_elements.dart'; import 'settings_dialog.dart'; /// Controls related to the entire memory screen. class SecondaryControls extends StatelessWidget { const SecondaryControls({ Key? key, required this.controller, }) : super(key: key); final MemoryController controller; @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ GaDevToolsButton( onPressed: controller.isGcing ? null : _gc, icon: Icons.delete, label: 'GC', tooltip: 'Trigger full garbage collection.', minScreenWidthForTextBeforeScaling: memoryControlsMinVerboseWidth, gaScreen: gac.memory, gaSelection: gac.MemoryEvent.gc, ), const SizedBox(width: denseSpacing), SettingsOutlinedButton( gaScreen: gac.memory, gaSelection: gac.MemoryEvent.settings, onPressed: () => _openSettingsDialog(context), tooltip: 'Open memory settings', ), ], ); } void _openSettingsDialog(BuildContext context) { unawaited( showDialog( context: context, builder: (context) => const MemorySettingsDialog(), ), ); } Future<void> _gc() async { controller.controllers.memoryTimeline.addGCEvent(); await controller.gc(); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/control/secondary_controls.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/control/secondary_controls.dart", "repo_id": "devtools", "token_count": 699 }
98
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; import '../../../../../shared/analytics/analytics.dart' as ga; import '../../../../../shared/analytics/constants.dart' as gac; import '../../../../../shared/common_widgets.dart'; import '../../../../../shared/dialogs.dart'; import '../../../../../shared/primitives/byte_utils.dart'; import '../../../../../shared/primitives/utils.dart'; import '../controller/diff_pane_controller.dart'; import '../controller/item_controller.dart'; final _log = Logger('snapshot_list'); class SnapshotList extends StatelessWidget { const SnapshotList({Key? key, required this.controller}) : super(key: key); final DiffPaneController controller; @override Widget build(BuildContext context) { return Column( children: [ OutlineDecoration.onlyBottom( child: Padding( padding: const EdgeInsets.symmetric( vertical: denseSpacing, horizontal: densePadding, ), child: _ListControlPane(controller: controller), ), ), Expanded( child: _SnapshotListItems(controller: controller), ), ], ); } } @visibleForTesting const iconToTakeSnapshot = Icons.fiber_manual_record; class _ListControlPane extends StatelessWidget { const _ListControlPane({Key? key, required this.controller}) : super(key: key); final DiffPaneController controller; Future<void> _takeSnapshot(BuildContext context) async { try { await controller.takeSnapshot(); } catch (e, trace) { _log.shout(e, e, trace); if (!context.mounted) return; await showDialog( context: context, builder: (context) => UnexpectedErrorDialog( additionalInfo: 'Encountered an error while taking a heap snapshot:\n${e.runtimeType}\n$e\n$trace', ), ); } } @override Widget build(BuildContext context) { return Row( children: [ ToolbarAction( icon: iconToTakeSnapshot, size: defaultIconSize, tooltip: 'Take heap snapshot for the selected isolate', onPressed: () => unawaited(_takeSnapshot(context)), ), const SizedBox(width: densePadding), ValueListenableBuilder( valueListenable: controller.core.snapshots, builder: (context, snapshots, _) { return ToolbarAction( icon: Icons.delete, size: defaultIconSize, tooltip: 'Delete all snapshots', onPressed: controller.hasSnapshots ? () { ga.select( gac.memory, gac.MemoryEvent.diffClearSnapshots, ); controller.clearSnapshots(); } : null, ); }, ), const Spacer(), ToolbarAction( icon: Icons.file_upload, tooltip: 'Import snapshot(s) from disk', onPressed: () => unawaited(controller.importSnapshots()), ), ], ); } } @visibleForTesting class SnapshotListTitle extends StatelessWidget { const SnapshotListTitle({ Key? key, required this.item, required this.index, required this.selected, required this.editIndex, required this.onEdit, required this.onEditingComplete, required this.onDelete, }) : super(key: key); final SnapshotItem item; final int index; final bool selected; /// The index in the list for the [SnapshotListTitle] actively being edited. final ValueListenable<int?> editIndex; /// Called when the 'Rename' context menu item is selected. final VoidCallback onEdit; /// Called when the snapshot name editing is complete. final VoidCallback onEditingComplete; /// Called when the 'Delete' context menu item is selected. final VoidCallback onDelete; @override Widget build(BuildContext context) { final theItem = item; final theme = Theme.of(context); late final Widget leading; final trailing = <Widget>[]; if (theItem is SnapshotDocItem) { leading = Icon( Icons.help_outline, size: defaultIconSize, color: theme.colorScheme.onSurface, ); } else if (theItem is SnapshotInstanceItem) { leading = Expanded( child: ValueListenableBuilder( valueListenable: editIndex, builder: (context, editIndex, _) { return _EditableSnapshotName( item: theItem, editMode: index == editIndex, onEditingComplete: onEditingComplete, ); }, ), ); const menuButtonWidth = ContextMenuButton.defaultWidth + ContextMenuButton.densePadding; trailing.addAll([ if (theItem.totalSize != null) Text( prettyPrintBytes(theItem.totalSize, includeUnit: true)!, ), Padding( padding: const EdgeInsets.only(left: ContextMenuButton.densePadding), child: selected ? ContextMenuButton( menuChildren: <Widget>[ MenuItemButton( onPressed: onEdit, child: const Text('Rename'), ), MenuItemButton( onPressed: onDelete, child: const Text('Delete'), ), ], ) : const SizedBox(width: menuButtonWidth), ), ]); } return ValueListenableBuilder<bool>( valueListenable: theItem.isProcessing, builder: (_, isProcessing, __) => Padding( padding: const EdgeInsets.symmetric(horizontal: denseRowSpacing), child: Row( children: [ leading, if (isProcessing) CenteredCircularProgressIndicator(size: smallProgressSize) else ...trailing, ], ), ), ); } } class _EditableSnapshotName extends StatefulWidget { const _EditableSnapshotName({ required this.item, required this.editMode, required this.onEditingComplete, }); final SnapshotInstanceItem item; final bool editMode; final VoidCallback onEditingComplete; @override State<_EditableSnapshotName> createState() => _EditableSnapshotNameState(); } class _EditableSnapshotNameState extends State<_EditableSnapshotName> with AutoDisposeMixin { late final TextEditingController textEditingController; final textFieldFocusNode = FocusNode(); @override void initState() { super.initState(); textEditingController = TextEditingController(); textEditingController.text = widget.item.name; _updateFocus(); addAutoDisposeListener(textFieldFocusNode, () { if (!textFieldFocusNode.hasPrimaryFocus) { textFieldFocusNode.unfocus(); widget.onEditingComplete(); } }); } @override void dispose() { cancelListeners(); textEditingController.dispose(); textFieldFocusNode.dispose(); super.dispose(); } @override void didUpdateWidget(_EditableSnapshotName oldWidget) { super.didUpdateWidget(oldWidget); textEditingController.text = widget.item.name; _updateFocus(); } void _updateFocus() { WidgetsBinding.instance.addPostFrameCallback((_) { if (widget.editMode) { textFieldFocusNode.requestFocus(); } else { textFieldFocusNode.unfocus(); } }); } @override Widget build(BuildContext context) { // TODO(polina-c): start using ellipsis when it is available, https://github.com/flutter/devtools/issues/7130 return TextField( controller: textEditingController, focusNode: textFieldFocusNode, autofocus: true, showCursor: widget.editMode, enabled: widget.editMode, style: Theme.of(context).regularTextStyle, decoration: const InputDecoration( isDense: true, border: InputBorder.none, ), onChanged: (value) => widget.item.nameOverride = value, onSubmitted: _updateName, ); } void _updateName(String value) { widget.item.nameOverride = value; widget.onEditingComplete(); textFieldFocusNode.unfocus(); } } class _SnapshotListItems extends StatefulWidget { const _SnapshotListItems({required this.controller}); final DiffPaneController controller; @override State<_SnapshotListItems> createState() => _SnapshotListItemsState(); } class _SnapshotListItemsState extends State<_SnapshotListItems> with AutoDisposeMixin { final _headerHeight = 1.2 * defaultRowHeight; final _scrollController = ScrollController(); /// The index in the list for the snapshot name actively being edited. ValueListenable<int?> get editIndex => _editIndex; final _editIndex = ValueNotifier<int?>(null); @override void initState() { super.initState(); _init(); } @override void dispose() { _scrollController.dispose(); _editIndex.dispose(); super.dispose(); } @override void didUpdateWidget(covariant _SnapshotListItems oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.controller != widget.controller) _init(); } void _init() { cancelListeners(); addAutoDisposeListener( widget.controller.core.selectedSnapshotIndex, scrollIfLast, ); } Future<void> scrollIfLast() async { final core = widget.controller.core; final newLength = core.snapshots.value.length; final newIndex = core.selectedSnapshotIndex.value; if (newIndex == newLength - 1) await _scrollController.autoScrollToBottom(); } @override Widget build(BuildContext context) { final core = widget.controller.core; return MultiValueListenableBuilder( listenables: [ core.snapshots, core.selectedSnapshotIndex, ], builder: (_, values, __) { final snapshots = values.first as List<SnapshotItem>; final selectedIndex = values.second as int; return ListView.builder( controller: _scrollController, itemCount: snapshots.length, itemExtent: defaultRowHeight, itemBuilder: (context, index) { final selected = selectedIndex == index; return Container( height: _headerHeight, color: selected ? Theme.of(context).colorScheme.selectedRowBackgroundColor : null, child: InkWell( canRequestFocus: false, onTap: () { widget.controller.setSnapshotIndex(index); _editIndex.value = null; }, child: SnapshotListTitle( item: snapshots[index], index: index, selected: selected, editIndex: editIndex, onEdit: () => _editIndex.value = index, onEditingComplete: () => _editIndex.value = null, onDelete: () { if (_editIndex.value == index) { _editIndex.value = null; } final item = widget.controller.core.snapshots.value[index]; widget.controller.deleteSnapshot(item); }, ), ), ); }, ); }, ); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/snapshot_list.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/snapshot_list.dart", "repo_id": "devtools", "token_count": 5025 }
99
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:collection/collection.dart'; import 'package:vm_service/vm_service.dart'; import '../../../../shared/analytics/analytics.dart' as ga; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/globals.dart'; import '../../../../shared/memory/adapted_heap_data.dart'; import '../../../../shared/memory/class_name.dart'; import '../../../../shared/memory/classes.dart'; import '../../../../shared/vm_utils.dart'; class _HeapObjects { _HeapObjects(this.objects, this.heap); final ObjectSet objects; final AdaptedHeapData heap; } class ClassSampler { ClassSampler( this.heapClass, { ObjectSet? objects, AdaptedHeapData? heap, }) : assert(objects?.objectsByCodes.isNotEmpty ?? true), assert((objects == null) == (heap == null)), _objects = objects == null ? null : _HeapObjects(objects, heap!); final HeapClassName heapClass; final _HeapObjects? _objects; IsolateRef get _mainIsolateRef => serviceConnection.serviceManager.isolateManager.mainIsolate.value!; Future<InstanceRef?> _liveInstance() async { try { final isolateId = _mainIsolateRef.id!; final theClass = await findClass(isolateId, heapClass); if (theClass == null) return null; final object = (await serviceConnection.serviceManager.service!.getInstances( isolateId, theClass.id!, 1, )) .instances?[0]; if (object is InstanceRef) return object; return null; } catch (error, trace) { _outputError(error, trace); return null; } } Future<InstanceSet?> _liveInstances() async { try { final isolateId = _mainIsolateRef.id!; final theClass = await findClass(isolateId, heapClass); if (theClass == null) return null; return await serviceConnection.serviceManager.service!.getInstances( isolateId, theClass.id!, preferences.memory.refLimit.value, ); } catch (error, trace) { _outputError(error, trace); return null; } } Future<InstanceRef?> _liveInstancesAsList() async { try { final isolateId = _mainIsolateRef.id!; final theClass = await findClass(isolateId, heapClass); if (theClass == null) return null; return await serviceConnection.serviceManager.service!.getInstancesAsList( isolateId, theClass.id!, ); } catch (error, trace) { _outputError(error, trace); return null; } } void _outputError(Object error, StackTrace trace) { serviceConnection.consoleService.appendStdio('$error\n$trace'); } bool get isEvalEnabled => heapClass .classType(serviceConnection.serviceManager.rootInfoNow().package) != ClassType.runtime; Future<void> allLiveToConsole({ required bool includeSubclasses, required bool includeImplementers, }) async { ga.select( gac.memory, gac.MemoryEvent.dropAllLiveToConsole( includeImplementers: includeImplementers, includeSubclasses: includeSubclasses, ), ); final list = await _liveInstancesAsList(); if (list == null) { serviceConnection.consoleService.appendStdio( 'Unable to select instances for the class ${heapClass.fullName}.', ); return; } final selection = _objects; // drop to console serviceConnection.consoleService.appendBrowsableInstance( instanceRef: list, isolateRef: _mainIsolateRef, heapSelection: selection == null ? null : HeapObjectSelection(selection.heap, object: null), ); } Future<void> oneLiveToConsole() async { ga.select(gac.memory, gac.MemoryEvent.dropOneLiveVariable); // drop to console serviceConnection.consoleService.appendBrowsableInstance( instanceRef: await _liveInstance(), isolateRef: _mainIsolateRef, heapSelection: null, ); } } class HeapClassSampler extends ClassSampler { HeapClassSampler( HeapClassName heapClass, ObjectSet objects, AdaptedHeapData heap, ) : super(heapClass, heap: heap, objects: objects); Future<void> oneLiveStaticToConsole() async { final selection = _objects!; ga.select(gac.memory, gac.MemoryEvent.dropOneLiveVariable); final instances = (await _liveInstances())?.instances; final instanceRef = instances?.firstWhereOrNull( (objRef) => objRef is InstanceRef && selection.objects.objectsByCodes.containsKey(objRef.identityHashCode), ) as InstanceRef?; if (instanceRef == null) { serviceConnection.consoleService.appendStdio( 'Unable to select instance that exist in snapshot and still alive in application.\n' 'You may want to increase "${preferences.memory.refLimitTitle}" in memory settings.', ); return; } final heapObject = selection.objects.objectsByCodes[instanceRef.identityHashCode!]!; final heapSelection = HeapObjectSelection(selection.heap, object: heapObject); // drop to console serviceConnection.consoleService.appendBrowsableInstance( instanceRef: instanceRef, isolateRef: _mainIsolateRef, heapSelection: heapSelection, ); } void oneStaticToConsole() { final selection = _objects!; ga.select(gac.memory, gac.MemoryEvent.dropOneStaticVariable); final heapObject = selection.objects.objectsByCodes.values.first; final heapSelection = HeapObjectSelection(selection.heap, object: heapObject); // drop to console serviceConnection.consoleService.appendBrowsableInstance( instanceRef: null, isolateRef: _mainIsolateRef, heapSelection: heapSelection, ); } }
devtools/packages/devtools_app/lib/src/screens/memory/shared/heap/sampler.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/shared/heap/sampler.dart", "repo_id": "devtools", "token_count": 2205 }
100
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/service.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import '../../../../../service/service_extension_widgets.dart'; import '../../../../../service/service_extensions.dart' as extensions; import '../../../../../shared/common_widgets.dart'; import '../../../../../shared/globals.dart'; import '../../../../../shared/primitives/utils.dart'; import '../performance_controls.dart'; import 'enhance_tracing_controller.dart'; class EnhanceTracingButton extends StatelessWidget { const EnhanceTracingButton( this.enhanceTracingController, { Key? key, }) : super(key: key); static const title = 'Enhance Tracing'; static const icon = Icons.auto_awesome; final EnhanceTracingController enhanceTracingController; @override Widget build(BuildContext context) { final theme = Theme.of(context); final textStyle = theme.subtleTextStyle; return ServiceExtensionCheckboxGroupButton( title: title, icon: icon, tooltip: 'Add more detail to the Timeline trace', minScreenWidthForTextBeforeScaling: PerformanceControls.minScreenWidthForTextBeforeScaling, extensions: enhanceTracingExtensions, forceShowOverlayController: enhanceTracingController.showMenuStreamController, customExtensionUi: { extensions.profileWidgetBuilds.extension: const TrackWidgetBuildsSetting(), extensions.profileUserWidgetBuilds.extension: const SizedBox(), }, overlayDescription: RichText( text: TextSpan( text: 'These options can be used to add more detail to the ' 'timeline, but be aware that ', style: textStyle, children: [ TextSpan( text: 'frame times may be negatively affected', style: textStyle.copyWith(color: theme.colorScheme.error), ), TextSpan( text: '.\n\n', style: textStyle, ), TextSpan( text: 'When toggling on/off a tracing option, you will need ' 'to reproduce activity in your app to see the enhanced ' 'tracing in the timeline.', style: textStyle, ), ], ), ), ); } } enum TrackWidgetBuildsScope { all, userCreated, } extension TrackWidgetBuildsScopeExtension on TrackWidgetBuildsScope { String get radioDisplay { switch (this) { case TrackWidgetBuildsScope.all: return 'within all code'; case TrackWidgetBuildsScope.userCreated: return 'within your code'; } } /// Returns the opposite [TrackWidgetBuildsScope] from [this]. TrackWidgetBuildsScope get opposite { switch (this) { case TrackWidgetBuildsScope.all: return TrackWidgetBuildsScope.userCreated; case TrackWidgetBuildsScope.userCreated: return TrackWidgetBuildsScope.all; } } /// Returns the service extension for this [TrackWidgetBuildsScope]. extensions.ToggleableServiceExtensionDescription<bool> get extensionForScope { switch (this) { case TrackWidgetBuildsScope.all: return extensions.profileWidgetBuilds; case TrackWidgetBuildsScope.userCreated: return extensions.profileUserWidgetBuilds; } } } class TrackWidgetBuildsSetting extends StatefulWidget { const TrackWidgetBuildsSetting({Key? key}) : super(key: key); @override State<TrackWidgetBuildsSetting> createState() => _TrackWidgetBuildsSettingState(); } class _TrackWidgetBuildsSettingState extends State<TrackWidgetBuildsSetting> with AutoDisposeMixin { static const _scopeSelectorPadding = 32.0; /// Service extensions for tracking widget builds. final _trackWidgetBuildsExtensions = { TrackWidgetBuildsScope.all: extensions.profileWidgetBuilds, TrackWidgetBuildsScope.userCreated: extensions.profileUserWidgetBuilds, }; /// The selected track widget builds scope, which may be any value in /// [TrackWidgetBuildsScope] or null if widget builds are not being tracked. final _selectedScope = ValueNotifier<TrackWidgetBuildsScope?>(null); /// Whether either of the extensions in [_trackWidgetBuildsExtensions.values] /// are enabled. final _tracked = ValueNotifier<bool>(false); /// Whether either of the extensions in [_trackWidgetBuildsExtensions.values] /// are available. final _trackingAvailable = ValueNotifier<bool>(false); @override void initState() { super.initState(); // Listen for service extensions to become available and add a listener to // respond to their state changes. for (final type in TrackWidgetBuildsScope.values) { final extension = _trackWidgetBuildsExtensions[type]!; unawaited( serviceConnection.serviceManager.serviceExtensionManager .waitForServiceExtensionAvailable(extension.extension) .then((isServiceAvailable) { if (isServiceAvailable) { _trackingAvailable.value = true; final state = serviceConnection .serviceManager.serviceExtensionManager .getServiceExtensionState(extension.extension); _updateForServiceExtensionState(state.value, type); addAutoDisposeListener(state, () { _updateForServiceExtensionState(state.value, type); }); } }), ); } } Future<void> _updateForServiceExtensionState( ServiceExtensionState newState, TrackWidgetBuildsScope type, ) async { final otherState = serviceConnection.serviceManager.serviceExtensionManager .getServiceExtensionState(type.opposite.extensionForScope.extension) .value .enabled; final trackAllWidgets = type == TrackWidgetBuildsScope.all ? newState.enabled : otherState; final trackUserWidgets = type == TrackWidgetBuildsScope.userCreated ? newState.enabled : otherState; await _updateTracking( trackAllWidgets: trackAllWidgets, trackUserWidgets: trackUserWidgets, ); } Future<void> _updateTracking({ required bool trackAllWidgets, required bool trackUserWidgets, }) async { if (trackUserWidgets && trackAllWidgets) { // If both the debug setting for tracking all widgets and tracking only // user-created widgets are true, default to tracking only user-created // widgets. Disable the service extension for tracking all widgets. await serviceConnection.serviceManager.serviceExtensionManager .setServiceExtensionState( extensions.profileWidgetBuilds.extension, enabled: false, value: extensions.profileWidgetBuilds.disabledValue, ); trackAllWidgets = false; } assert(!(trackAllWidgets && trackUserWidgets)); _tracked.value = trackUserWidgets || trackAllWidgets; // Double nested conditinoal expressions are hard to read. // ignore: prefer-conditional-expression if (_tracked.value) { _selectedScope.value = trackUserWidgets ? TrackWidgetBuildsScope.userCreated : TrackWidgetBuildsScope.all; } else { _selectedScope.value = null; } } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ValueListenableBuilder<bool>( valueListenable: _trackingAvailable, builder: (context, trackingAvailable, _) { return TrackWidgetBuildsCheckbox( trackingNotifier: _tracked, enabled: trackingAvailable, ); }, ), MultiValueListenableBuilder( listenables: [ _tracked, _selectedScope, ], builder: (context, values, _) { final tracked = values.first as bool; final selectedScope = values.second as TrackWidgetBuildsScope?; return Padding( padding: const EdgeInsets.only(left: _scopeSelectorPadding), child: TrackWidgetBuildsScopeSelector( scope: selectedScope, enabled: tracked, ), ); }, ), ], ); } } class TrackWidgetBuildsCheckbox extends StatelessWidget { const TrackWidgetBuildsCheckbox({ Key? key, required this.trackingNotifier, required this.enabled, }) : super(key: key); final ValueNotifier<bool> trackingNotifier; final bool enabled; @override Widget build(BuildContext context) { final extension = extensions.profileWidgetBuilds; final docsUrl = extension.documentationUrl; return Row( children: [ Expanded( child: CheckboxSetting( notifier: trackingNotifier, title: extension.title, description: extension.description, tooltip: extension.tooltip, onChanged: _checkboxChanged, enabled: enabled, gaScreenName: extension.gaScreenName, gaItem: extension.gaItem, ), ), if (docsUrl != null) Padding( padding: const EdgeInsets.symmetric(horizontal: denseSpacing), child: MoreInfoLink( url: docsUrl, gaScreenName: extension.gaScreenName!, gaSelectedItemDescription: extension.gaDocsItem!, padding: const EdgeInsets.symmetric(vertical: denseSpacing), ), ), ], ); } void _checkboxChanged(bool? value) async { final enabled = value == true; final trackingExtensions = TrackWidgetBuildsScope.values.map((scope) => scope.extensionForScope); if (enabled) { // Default to tracking only user-created widgets. final extension = extensions.profileUserWidgetBuilds; await serviceConnection.serviceManager.serviceExtensionManager .setServiceExtensionState( extension.extension, enabled: true, value: extension.enabledValue, ); } else { await Future.wait([ for (final extension in trackingExtensions) serviceConnection.serviceManager.serviceExtensionManager .setServiceExtensionState( extension.extension, enabled: false, value: extension.disabledValue, ), ]); } } } class TrackWidgetBuildsScopeSelector extends StatelessWidget { const TrackWidgetBuildsScopeSelector({ Key? key, required this.scope, required this.enabled, }) : super(key: key); final TrackWidgetBuildsScope? scope; final bool enabled; @override Widget build(BuildContext context) { final theme = Theme.of(context); final textStyle = enabled ? theme.regularTextStyle : theme.subtleTextStyle; return Row( children: [ ..._scopeSetting( TrackWidgetBuildsScope.userCreated, textStyle: textStyle, ), const SizedBox(width: defaultSpacing), ..._scopeSetting( TrackWidgetBuildsScope.all, textStyle: textStyle, ), ], ); } List<Widget> _scopeSetting( TrackWidgetBuildsScope type, { TextStyle? textStyle, }) { return [ Radio<TrackWidgetBuildsScope>( value: type, groupValue: scope, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, onChanged: enabled ? _changeScope : null, ), Text( type.radioDisplay, style: textStyle, ), ]; } Future<void> _changeScope(TrackWidgetBuildsScope? type) async { assert(enabled); final extension = type!.extensionForScope; final opposite = type.opposite.extensionForScope; await Future.wait( [ serviceConnection.serviceManager.serviceExtensionManager .setServiceExtensionState( opposite.extension, enabled: false, value: opposite.disabledValue, ), serviceConnection.serviceManager.serviceExtensionManager .setServiceExtensionState( extension.extension, enabled: true, value: extension.enabledValue, ), ], ); } }
devtools/packages/devtools_app/lib/src/screens/performance/panes/controls/enhance_tracing/enhance_tracing.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/controls/enhance_tracing/enhance_tracing.dart", "repo_id": "devtools", "token_count": 4879 }
101
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/service.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../../../../service/service_extension_widgets.dart'; import '../../../../service/service_extensions.dart' as extensions; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../../../shared/globals.dart'; import '../../../../shared/primitives/utils.dart'; import '../../../../shared/table/table.dart'; import '../../../../shared/table/table_data.dart'; import '../flutter_frames/flutter_frame_model.dart'; import 'rebuild_stats_model.dart'; class RebuildStatsView extends StatefulWidget { const RebuildStatsView({ Key? key, required this.model, required this.selectedFrame, }) : super(key: key); final RebuildCountModel model; final ValueListenable<FlutterFrame?> selectedFrame; @override State<RebuildStatsView> createState() => _RebuildStatsViewState(); } class _RebuildStatsViewState extends State<RebuildStatsView> with AutoDisposeMixin { var metricNames = const <String>[]; var metrics = const <RebuildLocationStats>[]; @override void initState() { super.initState(); _init(); } @override void didUpdateWidget(covariant RebuildStatsView oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.model != widget.model || oldWidget.selectedFrame != widget.selectedFrame) { cancelListeners(); _init(); } } void _init() { addAutoDisposeListener(widget.model.locationStats, computeMetrics); addAutoDisposeListener(widget.selectedFrame, computeMetrics); computeMetrics(); } void computeMetrics() { final names = <String>[]; final data = <List<RebuildLocation>>[]; final selectedFrame = widget.selectedFrame.value; List<RebuildLocation>? rebuildsForFrame; if (selectedFrame != null) { rebuildsForFrame = widget.model.rebuildsForFrame(selectedFrame.id); } if (rebuildsForFrame != null) { names.add('Selected frame'); data.add(rebuildsForFrame); } else if (selectedFrame == null) { final rebuildsForLastFrame = widget.model.rebuildsForLastFrame; if (rebuildsForLastFrame != null) { names.add('Latest frame'); data.add(rebuildsForLastFrame); } } names.add('Overall'); data.add(widget.model.locationStats.value); setState(() { metrics = combineStats(data); metricNames = names; }); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ OutlineDecoration.onlyBottom( child: Padding( padding: const EdgeInsets.all(denseSpacing), child: Row( children: [ ClearButton( gaScreen: gac.performance, gaSelection: gac.PerformanceEvents.clearRebuildStats.name, onPressed: widget.model.clearAllCounts, ), const SizedBox(width: denseSpacing), Flexible( child: ServiceExtensionCheckbox( serviceExtension: extensions.trackRebuildWidgets, ), ), const Spacer(), ], ), ), ), Expanded( child: ValueListenableBuilder<ServiceExtensionState>( valueListenable: serviceConnection .serviceManager.serviceExtensionManager .getServiceExtensionState( extensions.trackRebuildWidgets.extension, ), builder: (context, state, _) { if (metrics.isEmpty && !state.enabled) { return const Center( child: Text( 'Track widget build counts must be enabled to see data.', ), ); } if (metrics.isEmpty) { return const Center( child: Text( 'Interact with the app to trigger rebuilds.', ), ); // No data to display but there should be data soon. } return RebuildTable( key: const Key('Rebuild Table'), metricNames: metricNames, metrics: metrics, ); }, ), ), ], ); } } class RebuildTable extends StatefulWidget { const RebuildTable({ Key? key, required this.metricNames, required this.metrics, }) : super(key: key); final List<String> metricNames; final List<RebuildLocationStats> metrics; @override State<RebuildTable> createState() => _RebuildTableState(); } class _RebuildTableState extends State<RebuildTable> { SortDirection sortDirection = SortDirection.descending; /// Cache of columns so we don't confuse the Table by returning different /// column objects for the same column. final _columnCache = <String, _RebuildCountColumn>{}; List<_RebuildCountColumn> get _metricsColumns { final columns = <_RebuildCountColumn>[]; for (var i = 0; i < widget.metricNames.length; i++) { final name = widget.metricNames[i]; var cached = _columnCache[name]; if (cached == null || cached.metricIndex != i) { cached = _RebuildCountColumn(name, i); _columnCache[name] = cached; } columns.add(cached); } return columns; } static final _widgetColumn = _WidgetColumn(); static final _locationColumn = _LocationColumn(); List<ColumnData<RebuildLocationStats>> get _columns => [_widgetColumn, ..._metricsColumns, _locationColumn]; @override Widget build(BuildContext context) { final borderSide = defaultBorderSide(Theme.of(context)); return Container( decoration: BoxDecoration( border: Border(right: borderSide), ), child: FlatTable<RebuildLocationStats>( dataKey: 'RebuildMetricsTable', columns: _columns, data: widget.metrics, keyFactory: (RebuildLocationStats location) => ValueKey<String?>('${location.location.id}'), defaultSortColumn: _metricsColumns.first, defaultSortDirection: sortDirection, onItemSelected: (item) { // TODO(jacobr): navigate to selected widget in IDE or display the // content side by side with the rebuild table. }, ), ); } } class _WidgetColumn extends ColumnData<RebuildLocationStats> { _WidgetColumn() : super( 'Widget', fixedWidthPx: scaleByFontFactor(200), ); @override String getValue(RebuildLocationStats dataObject) { return dataObject.location.name ?? '???'; } } class _LocationColumn extends ColumnData<RebuildLocationStats> { _LocationColumn() : super.wide('Location'); @override String getValue(RebuildLocationStats dataObject) { final path = dataObject.location.path; if (path == null) { return '<resolving location>'; } return '${path.split('/').last}:${dataObject.location.line}'; } @override String getTooltip(RebuildLocationStats dataObject) { if (dataObject.location.path == null) { return '<resolving location>'; } return '${dataObject.location.path}:${dataObject.location.line}'; } } class _RebuildCountColumn extends ColumnData<RebuildLocationStats> { _RebuildCountColumn(String name, this.metricIndex) : super( name, fixedWidthPx: scaleByFontFactor(130), ); final int metricIndex; @override int getValue(RebuildLocationStats dataObject) => dataObject.buildCounts[metricIndex]; @override bool get numeric => true; }
devtools/packages/devtools_app/lib/src/screens/performance/panes/rebuild_stats/rebuild_stats.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/rebuild_stats/rebuild_stats.dart", "repo_id": "devtools", "token_count": 3273 }
102
// 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. // TODO(jacobr): we should remove this file from the app and move it to the // testing directory leveraging stager for this functionality. // Having this test code in the core app is confusing and bloats the code size // of the shipping app as this data is unlikely to be treeshaken by Dart2JS // as currently used. final simpleTraceEvents = { 'traceEvents': [ { 'name': 'thread_name', 'ph': 'M', 'pid': 51385, 'tid': 4875, 'args': {'name': 'Dart ThreadPool Worker (4875)', 'mode': 'basic'}, }, { 'name': 'thread_name', 'ph': 'M', 'pid': 51385, 'tid': 4363, 'args': {'name': 'Dart ThreadPool Worker (4363)', 'mode': 'basic'}, }, { 'name': 'thread_name', 'ph': 'M', 'pid': 51385, 'tid': 4103, 'args': {'name': 'Dart ThreadPool Worker (4103)', 'mode': 'basic'}, }, { 'name': 'thread_name', 'ph': 'M', 'pid': 51385, 'tid': 4611, 'args': {'name': 'Dart ThreadPool Worker (4611)', 'mode': 'basic'}, }, { 'name': 'thread_name', 'ph': 'M', 'pid': 51385, 'tid': 3843, 'args': { 'name': 'Dart Profiler ThreadInterrupter (3843)', 'mode': 'basic', }, }, { 'name': 'thread_name', 'ph': 'M', 'pid': 51385, 'tid': 775, 'args': {'name': 'Dart_Initialize (775)', 'mode': 'basic'}, }, { 'name': 'A', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937056864, 'ph': 'b', 'id': '1', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Aa', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937061035, 'ph': 'b', 'id': '7', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'B', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937113560, 'ph': 'b', 'id': '2', 'args': {'parentId': '1', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Bb', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937117450, 'ph': 'b', 'id': '8', 'args': {'parentId': '7', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'B1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937141769, 'ph': 'b', 'id': 'd', 'args': {'parentId': '2', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Bb1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937141961, 'ph': 'b', 'id': 'f', 'args': {'parentId': '8', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'C', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937168961, 'ph': 'b', 'id': '3', 'args': {'parentId': '1', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Cc', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937169662, 'ph': 'b', 'id': '9', 'args': {'parentId': '7', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'B2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937173019, 'ph': 'b', 'id': 'e', 'args': {'parentId': '2', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Bb2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937173132, 'ph': 'b', 'id': '10', 'args': {'parentId': '8', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'C1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937220903, 'ph': 'b', 'id': '11', 'args': {'parentId': '3', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Cc1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937221087, 'ph': 'b', 'id': '13', 'args': {'parentId': '9', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'B1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937225475, 'ph': 'e', 'id': 'd', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Bb1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937225615, 'ph': 'e', 'id': 'f', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'B2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937281185, 'ph': 'e', 'id': 'e', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Bb2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937281309, 'ph': 'e', 'id': '10', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'C1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937326225, 'ph': 'e', 'id': '11', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Cc1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937326380, 'ph': 'e', 'id': '13', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'C2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937378812, 'ph': 'b', 'id': '12', 'args': {'parentId': '3', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Cc2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937378989, 'ph': 'b', 'id': '14', 'args': {'parentId': '9', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'B', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937382819, 'ph': 'e', 'id': '2', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Bb', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937382931, 'ph': 'e', 'id': '8', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'C2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937432875, 'ph': 'e', 'id': '12', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Cc2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937432991, 'ph': 'e', 'id': '14', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'C', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937485018, 'ph': 'e', 'id': '3', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Cc', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937485110, 'ph': 'e', 'id': '9', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'D', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937574832, 'ph': 'b', 'id': '4', 'args': {'parentId': '1', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Dd', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937575344, 'ph': 'b', 'id': 'a', 'args': {'parentId': '7', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937630473, 'ph': 'b', 'id': '5', 'args': {'parentId': '1', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937631341, 'ph': 'b', 'id': 'b', 'args': {'parentId': '7', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'D', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937679798, 'ph': 'e', 'id': '4', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Dd', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937679953, 'ph': 'e', 'id': 'a', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937681385, 'ph': 'b', 'id': '15', 'args': {'parentId': '5', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937682955, 'ph': 'b', 'id': '19', 'args': {'parentId': '11', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'F', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937735555, 'ph': 'b', 'id': '6', 'args': {'parentId': '1', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ff', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937736205, 'ph': 'b', 'id': 'c', 'args': {'parentId': '7', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937736389, 'ph': 'b', 'id': '16', 'args': {'parentId': '5', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937736537, 'ph': 'b', 'id': '1a', 'args': {'parentId': '11', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'W', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937575692, 'tts': 28634, 'ph': 'X', 'dur': 206139, 'tdur': 5960, 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E3', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937788218, 'ph': 'b', 'id': '17', 'args': {'parentId': '5', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee3', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937788380, 'ph': 'b', 'id': '1b', 'args': {'parentId': '11', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937893341, 'ph': 'e', 'id': '15', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee1', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937893466, 'ph': 'e', 'id': '19', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'F', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937940107, 'ph': 'e', 'id': '6', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ff', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937940216, 'ph': 'e', 'id': 'c', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'V', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937371774, 'tts': 25658, 'ph': 'X', 'dur': 615393, 'tdur': 10615, 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937994780, 'ph': 'e', 'id': '16', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee2', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937994900, 'ph': 'e', 'id': '1a', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E3', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938050919, 'ph': 'e', 'id': '17', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee3', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938051050, 'ph': 'e', 'id': '1b', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E4', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938105406, 'ph': 'b', 'id': '18', 'args': {'parentId': '5', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee4', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938105579, 'ph': 'b', 'id': '1c', 'args': {'parentId': '11', 'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E4', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938160387, 'ph': 'e', 'id': '18', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee4', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938160492, 'ph': 'e', 'id': '1c', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'U', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937167696, 'tts': 20888, 'ph': 'X', 'dur': 1024347, 'tdur': 17484, 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'E', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938264425, 'ph': 'e', 'id': '5', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Ee', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938264519, 'ph': 'e', 'id': 'b', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'T', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193937064411, 'tts': 12287, 'ph': 'X', 'dur': 1332000, 'tdur': 26683, 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'A', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938740982, 'ph': 'e', 'id': '1', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Aa', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938741076, 'ph': 'e', 'id': '7', 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'Y', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938601826, 'tts': 39935, 'ph': 'X', 'dur': 203898, 'tdur': 866, 'args': {'isolateId': 'isolates/2139247553966975'}, }, { 'name': 'X', 'cat': 'Dart', 'tid': 4875, 'pid': 51385, 'ts': 193938396852, 'tts': 39411, 'ph': 'X', 'dur': 614409, 'tdur': 1891, 'args': {'isolateId': 'isolates/2139247553966975'}, }, ], };
devtools/packages/devtools_app/lib/src/screens/performance/simple_trace_example.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/simple_trace_example.dart", "repo_id": "devtools", "token_count": 9041 }
103
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import '../../../../shared/primitives/trees.dart'; import '../../../../shared/primitives/utils.dart'; import '../../../../shared/ui/search.dart'; import '../../cpu_profile_model.dart'; import '../../cpu_profiler_controller.dart'; import 'method_table_model.dart'; /// Controller for the CPU profile method table. /// /// This controller is responsible for managing state of the Method table UI /// and for providing utility methods to interact with the active data. class MethodTableController extends DisposableController with SearchControllerMixin<MethodTableGraphNode>, AutoDisposeControllerMixin { MethodTableController({ required ValueListenable<CpuProfileData?> dataNotifier, }) { createMethodTableGraph(dataNotifier.value); addAutoDisposeListener(dataNotifier, () { createMethodTableGraph(dataNotifier.value); }); } final selectedNode = ValueNotifier<MethodTableGraphNode?>(null); ValueListenable<List<MethodTableGraphNode>> get methods => _methods; final _methods = ValueNotifier<List<MethodTableGraphNode>>([]); void _setData(List<MethodTableGraphNode> data) { _methods.value = data; refreshSearchMatches(); } @visibleForTesting void createMethodTableGraph(CpuProfileData? cpuProfileData) { reset(); if (cpuProfileData == null || cpuProfileData == CpuProfilerController.baseStateCpuProfileData || cpuProfileData == CpuProfilerController.emptyAppStartUpProfile || !cpuProfileData.processed) { return; } List<CpuStackFrame> profileRoots = cpuProfileData.callTreeRoots; // For a profile rooted at tags, treat it as if it is not. Otherwise, the // tags will show up in the method table. if (cpuProfileData.rootedAtTags) { profileRoots = []; for (final tagRoot in cpuProfileData.callTreeRoots) { profileRoots.addAll(tagRoot.children); } } final methodMap = <String, MethodTableGraphNode>{}; for (final root in profileRoots) { depthFirstTraversal( root, action: (CpuStackFrame frame) { final parentNode = frame.parent != null && frame.parentId != CpuProfileData.rootId && !frame.parent!.isTag // Since we are performing a DFS, the parent should always be in // the map. ? methodMap[frame.parent!.methodTableId]! : null; var graphNode = MethodTableGraphNode.fromStackFrame(frame); final existingNode = methodMap[frame.methodTableId]; if (existingNode != null) { // Do not merge the total time if the [existingNode] already counted // the total time for one of [frame]'s ancestors. final shouldMergeTotalTime = !existingNode.stackFrameIds.containsAny(frame.ancestorIds); // If the graph node already exists, merge the new one with the old // one and use the existing instance. existingNode.merge(graphNode, mergeTotalTime: shouldMergeTotalTime); graphNode = existingNode; } methodMap[graphNode.id] = graphNode; parentNode?.outgoingEdge( graphNode, edgeWeight: frame.inclusiveSampleCount, ); }, ); } _setData(methodMap.values.toList()); } double callerPercentageFor(MethodTableGraphNode node) { return selectedNode.value?.predecessorEdgePercentage(node) ?? 0.0; } double calleePercentageFor(MethodTableGraphNode node) { return selectedNode.value?.successorEdgePercentage(node) ?? 0.0; } void reset({bool shouldResetSearch = false}) { selectedNode.value = null; if (shouldResetSearch) { resetSearch(); } _setData([]); } @visibleForTesting String graphAsString() { methods.value.sort((m1, m2) => m2.totalCount.compareTo(m1.totalCount)); return methods.value.map((node) => node.toString()).toList().join('\n'); } @override Iterable<MethodTableGraphNode> get currentDataToSearchThrough => methods.value; }
devtools/packages/devtools_app/lib/src/screens/profiler/panes/method_table/method_table_controller.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/profiler/panes/method_table/method_table_controller.dart", "repo_id": "devtools", "token_count": 1613 }
104
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:collection/collection.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../shared/analytics/analytics.dart' as ga; import '../../shared/banner_messages.dart'; import '../../shared/common_widgets.dart'; import '../../shared/globals.dart'; import '../../shared/screen.dart'; import 'instance_viewer/eval.dart'; import 'instance_viewer/instance_details.dart'; import 'instance_viewer/instance_providers.dart'; import 'instance_viewer/instance_viewer.dart'; import 'provider_list.dart'; import 'provider_nodes.dart'; final _hasErrorProvider = Provider.autoDispose<bool>((ref) { if (ref.watch(sortedProviderNodesProvider) is AsyncError) return true; final selectedProviderId = ref.watch(selectedProviderIdProvider); if (selectedProviderId == null) return false; final instance = ref.watch( instanceProvider(InstancePath.fromProviderId(selectedProviderId)), ); return instance is AsyncError; }); final _selectedProviderNode = AutoDisposeProvider<ProviderNode?>((ref) { final selectedId = ref.watch(selectedProviderIdProvider); return ref.watch(sortedProviderNodesProvider).asData?.value.firstWhereOrNull( (node) => node.id == selectedId, ); }); final _showInternals = StateProvider<bool>((ref) => false); class ProviderScreen extends Screen { ProviderScreen() : super.fromMetaData(ScreenMetaData.provider); static final id = ScreenMetaData.provider.id; @override Widget buildScreenBody(BuildContext context) { return const ProviderScreenWrapper(); } } class ProviderScreenWrapper extends StatefulWidget { const ProviderScreenWrapper({Key? key}) : super(key: key); @override State<ProviderScreenWrapper> createState() => _ProviderScreenWrapperState(); } class _ProviderScreenWrapperState extends State<ProviderScreenWrapper> with AutoDisposeMixin { @override void initState() { super.initState(); ga.screen(ProviderScreen.id); cancelListeners(); addAutoDisposeListener(serviceConnection.serviceManager.connectedState, () { if (serviceConnection.serviceManager.connectedState.value.connected) { setServiceConnectionForProviderScreen( serviceConnection.serviceManager.service!, ); } }); } @override Widget build(BuildContext context) { return const ProviderScreenBody(); } } class ProviderScreenBody extends ConsumerWidget { const ProviderScreenBody({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final splitAxis = SplitPane.axisFor(context, 0.85); // A provider will automatically be selected as soon as one is detected final selectedProviderId = ref.watch(selectedProviderIdProvider); final detailsTitleText = selectedProviderId != null ? ref.watch(_selectedProviderNode)?.type ?? '' : '[No provider selected]'; ref.listen<bool>(_hasErrorProvider, (_, hasError) { if (hasError) showProviderErrorBanner(); }); return SplitPane( axis: splitAxis, initialFractions: const [0.33, 0.67], children: [ const RoundedOutlinedBorder( clip: true, child: Column( children: [ AreaPaneHeader( roundedTopBorder: false, includeTopBorder: false, title: Text('Providers'), ), Expanded( child: ProviderList(), ), ], ), ), RoundedOutlinedBorder( clip: true, child: Column( children: [ AreaPaneHeader( roundedTopBorder: false, includeTopBorder: false, title: Text(detailsTitleText), actions: [ ToolbarAction( icon: Icons.settings, onPressed: () { unawaited( showDialog( context: context, builder: (_) => _StateInspectorSettingsDialog(), ), ); }, ), ], ), if (selectedProviderId != null) Expanded( child: InstanceViewer( rootPath: InstancePath.fromProviderId(selectedProviderId), showInternalProperties: ref.watch(_showInternals), ), ), ], ), ), ], ); } } void showProviderErrorBanner() { bannerMessages.addMessage( ProviderUnknownErrorBanner(screenId: ProviderScreen.id).build(), ); } class _StateInspectorSettingsDialog extends ConsumerWidget { static const title = 'State inspector configurations'; @override Widget build(BuildContext context, WidgetRef ref) { return DevToolsDialog( title: const DialogTitleText(title), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ InkWell( onTap: () => ref.read(_showInternals.notifier).update((state) => !state), child: Row( children: [ Checkbox( value: ref.watch(_showInternals), onChanged: (_) => ref .read(_showInternals.notifier) .update((state) => !state), ), const Text( 'Show private properties inherited from SDKs/packages', ), ], ), ), ], ), actions: const [ DialogCloseButton(), ], ); } }
devtools/packages/devtools_app/lib/src/screens/provider/provider_screen.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/provider/provider_screen.dart", "repo_id": "devtools", "token_count": 2629 }
105
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:vm_service/vm_service.dart'; import '../vm_developer_common_widgets.dart'; import '../vm_service_private_extensions.dart'; import 'object_inspector_view_controller.dart'; import 'vm_object_model.dart'; // TODO(mtaylee): Finish implementation of [ICDataArrayWidget] and add it to // the [VmFuncDisplay]. /// A widget for the object inspector historyViewport displaying information /// related to function (Func type) objects in the Dart VM. class VmFuncDisplay extends StatelessWidget { const VmFuncDisplay({ super.key, required this.controller, required this.function, }); final ObjectInspectorViewController controller; final FuncObject function; @override Widget build(BuildContext context) { return ObjectInspectorCodeView( codeViewController: controller.codeViewController, script: function.scriptRef!, object: function.obj, child: VmObjectDisplayBasicLayout( controller: controller, object: function, generalDataRows: vmObjectGeneralDataRows(controller, function), sideCardDataRows: _functionDetailRows(function), sideCardTitle: 'Function Details', expandableWidgets: [ if (function.icDataArray != null) CallSiteDataArrayWidget( controller: controller, callSiteDataArray: function.icDataArray!, ), ], ), ); } /// Returns a list of key-value pairs (map entries) /// containing detailed information of a VM Func object [function]. List<MapEntry<String, Widget Function(BuildContext)>> _functionDetailRows( FuncObject function, ) { String? boolYesOrNo(bool? condition) { if (condition == null) { return null; } return condition ? 'Yes' : 'No'; } return [ selectableTextBuilderMapEntry( 'Kind', _kindDescription(function.kind), ), selectableTextBuilderMapEntry( 'Deoptimizations', function.deoptimizations?.toString(), ), selectableTextBuilderMapEntry( 'Optimizable', boolYesOrNo(function.isOptimizable), ), selectableTextBuilderMapEntry( 'Inlinable', boolYesOrNo(function.isInlinable), ), selectableTextBuilderMapEntry( 'Intrinsic', boolYesOrNo(function.hasIntrinsic), ), selectableTextBuilderMapEntry( 'Recognized', boolYesOrNo(function.isRecognized), ), selectableTextBuilderMapEntry( 'Native', boolYesOrNo(function.isNative), ), selectableTextBuilderMapEntry('VM Name', function.vmName), ]; } String? _kindDescription(FunctionKind? funcKind) { if (funcKind == null) { return 'Unrecognized function kind: ${function.obj.kind}'; } final kind = StringBuffer(); void addSpace() => kind.write(kind.isNotEmpty ? ' ' : ''); if (function.obj.isStatic == true) { kind.write('static'); } if (function.obj.isConst == true) { addSpace(); kind.write('const'); } addSpace(); kind.write( funcKind.kindDescription().toLowerCase(), ); return kind.toString(); } } class CallSiteDataArrayWidget extends StatelessWidget { const CallSiteDataArrayWidget({ super.key, required this.controller, required this.callSiteDataArray, }); final ObjectInspectorViewController controller; final Instance callSiteDataArray; @override Widget build(BuildContext context) { return VmExpansionTile( title: 'Call Site Data (${callSiteDataArray.length})', children: prettyRows( context, [ for (final entry in callSiteDataArray.elements!) Row( children: [ VmServiceObjectLink( object: entry as ObjRef, onTap: controller.findAndSelectNodeForObject, ), ], ), ], ), ); } }
devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_function_display.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_function_display.dart", "repo_id": "devtools", "token_count": 1671 }
106
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '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/primitives/byte_utils.dart'; import '../../../shared/primitives/utils.dart'; import '../../../shared/table/table.dart'; import '../../../shared/table/table_data.dart'; import '../vm_developer_common_widgets.dart'; import '../vm_developer_tools_screen.dart'; import '../vm_service_private_extensions.dart'; import 'vm_statistics_view_controller.dart'; class VMStatisticsView extends VMDeveloperView { const VMStatisticsView() : super( title: 'VM', icon: Icons.devices, ); static const id = 'vm-statistics'; @override Widget build(BuildContext context) => VMStatisticsViewBody(); } /// Displays general information about the state of the Dart VM. class VMStatisticsViewBody extends StatelessWidget { VMStatisticsViewBody({super.key}); final controller = VMStatisticsViewController(); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ RefreshButton( gaScreen: gac.vmTools, gaSelection: gac.refreshVmStatistics, onPressed: controller.refresh, ), const SizedBox(height: denseRowSpacing), Expanded( child: ValueListenableBuilder( valueListenable: controller.refreshing, builder: (context, _, __) { return VMStatisticsWidget( controller: controller, ); }, ), ), ], ); } } class VMStatisticsWidget extends StatelessWidget { const VMStatisticsWidget({super.key, required this.controller}); final VMStatisticsViewController controller; @override Widget build(BuildContext context) { return Row( children: [ Flexible( flex: 3, child: Column( children: [ Expanded( child: GeneralVMStatisticsWidget( controller: controller, ), ), Expanded( child: ProcessStatisticsWidget( controller: controller, ), ), ], ), ), Flexible( flex: 4, child: Column( children: [ Flexible( child: IsolatesPreviewWidget( controller: controller, ), ), Flexible( child: IsolatesPreviewWidget( controller: controller, systemIsolates: true, ), ), ], ), ), ], ); } } /// Displays general information about the VM instance, including: /// - VM debug name /// - Dart version /// - Embedder name /// - Start time /// - Profiler mode /// - Current memory consumption class GeneralVMStatisticsWidget extends StatelessWidget { const GeneralVMStatisticsWidget({super.key, required this.controller}); final VMStatisticsViewController controller; @override Widget build(BuildContext context) { final vm = controller.vm; return OutlineDecoration( child: VMInfoCard( title: 'VM', roundedTopBorder: false, rowKeyValues: [ selectableTextBuilderMapEntry('Name', vm?.name), selectableTextBuilderMapEntry('Version', vm?.version), selectableTextBuilderMapEntry('Embedder', vm?.embedder), selectableTextBuilderMapEntry( 'Started', vm == null ? null : formatDateTime( DateTime.fromMillisecondsSinceEpoch(vm.startTime!), ), ), selectableTextBuilderMapEntry('Profiler Mode', vm?.profilerMode), selectableTextBuilderMapEntry( 'Current Memory', prettyPrintBytes( vm?.currentMemory, includeUnit: true, ), ), ], ), ); } } /// Displays information about the current VM process, including: /// - Process ID /// - Host CPU /// - Target CPU /// - OS /// - Current and maximum resident set size (RSS) utilization /// - Zone allocator memory utilization class ProcessStatisticsWidget extends StatelessWidget { const ProcessStatisticsWidget({super.key, required this.controller}); final VMStatisticsViewController controller; @override Widget build(BuildContext context) { final vm = controller.vm; return OutlineDecoration( showTop: false, child: VMInfoCard( title: 'Process', roundedTopBorder: false, rowKeyValues: [ selectableTextBuilderMapEntry('PID', vm?.pid?.toString()), selectableTextBuilderMapEntry( 'Host CPU', vm == null ? null : '${vm.hostCPU} (${vm.architectureBits}-bits)', ), selectableTextBuilderMapEntry('Target CPU', vm?.targetCPU), selectableTextBuilderMapEntry( 'Operating System', vm?.operatingSystem, ), selectableTextBuilderMapEntry( 'Max Memory (RSS)', prettyPrintBytes( vm?.maxRSS, includeUnit: true, ), ), selectableTextBuilderMapEntry( 'Current Memory (RSS)', prettyPrintBytes( vm?.currentRSS, includeUnit: true, ), ), selectableTextBuilderMapEntry( 'Zone Memory', prettyPrintBytes( vm?.nativeZoneMemoryUsage, includeUnit: true, ), ), ], ), ); } } class _IsolateNameColumn extends ColumnData<Isolate> { _IsolateNameColumn() : super.wide('Name'); @override String getValue(Isolate i) => i.name!; } class _IsolateIDColumn extends ColumnData<Isolate> { _IsolateIDColumn() : super.wide('ID'); @override String getValue(Isolate i) => i.number!; } abstract class _IsolateMemoryColumn extends ColumnData<Isolate> { _IsolateMemoryColumn(String title) : super.wide(title); int getCapacity(Isolate i); int getUsage(Isolate i); @override String getValue(Isolate i) { return '${prettyPrintBytes(getUsage(i), includeUnit: true)} ' 'of ${prettyPrintBytes(getCapacity(i), includeUnit: true)}'; } } class _IsolateNewSpaceColumn extends _IsolateMemoryColumn { _IsolateNewSpaceColumn() : super('New Space'); @override int getCapacity(Isolate i) => i.newSpaceCapacity; @override int getUsage(Isolate i) => i.newSpaceUsage; } class _IsolateOldSpaceColumn extends _IsolateMemoryColumn { _IsolateOldSpaceColumn() : super('Old Space'); @override int getCapacity(Isolate i) => i.oldSpaceCapacity; @override int getUsage(Isolate i) => i.oldSpaceUsage; } class _IsolateHeapColumn extends _IsolateMemoryColumn { _IsolateHeapColumn() : super('Heap'); @override int getCapacity(Isolate i) => i.dartHeapCapacity; @override int getUsage(Isolate i) => i.dartHeapSize; } /// Displays general statistics about running isolates including: /// - Isolate debug name /// - VM Isolate ID /// - New / old space usage /// - Dart heap usage class IsolatesPreviewWidget extends StatelessWidget { const IsolatesPreviewWidget({ super.key, required this.controller, this.systemIsolates = false, }); static final name = _IsolateNameColumn(); static final number = _IsolateIDColumn(); static final newSpace = _IsolateNewSpaceColumn(); static final oldSpace = _IsolateOldSpaceColumn(); static final heap = _IsolateHeapColumn(); static List<ColumnData<Isolate>> columns = [ name, number, newSpace, oldSpace, heap, ]; final VMStatisticsViewController controller; final bool systemIsolates; @override Widget build(BuildContext context) { final title = systemIsolates ? 'System Isolates' : 'Isolates'; final isolates = systemIsolates ? controller.systemIsolates : controller.isolates; return OutlineDecoration( showLeft: false, showTop: !systemIsolates, child: VMInfoCard( title: '$title (${isolates.length})', roundedTopBorder: false, table: Flexible( child: FlatTable<Isolate>( keyFactory: (Isolate i) => ValueKey<String>(i.id!), data: isolates, dataKey: 'isolate-statistics', columns: columns, defaultSortColumn: name, defaultSortDirection: SortDirection.descending, ), ), ), ); } }
devtools/packages/devtools_app/lib/src/screens/vm_developer/vm_statistics/vm_statistics_view.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/vm_statistics/vm_statistics_view.dart", "repo_id": "devtools", "token_count": 3818 }
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:math'; import 'dart:ui'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; import '../primitives/utils.dart'; import 'chart_controller.dart'; import 'chart_trace.dart'; typedef DrawCodeCallback = void Function(Canvas canvas); final _log = Logger('chart'); /// Perform some draw operations on a canvas after applying translate. /// /// This helper function performs basic booking for translate tasks: /// 1. save canvas state /// 2. translate coordinates /// 3. draw to the canvas with respect to translation coordinates /// 4. restore canvas state back to the saved state. void drawTranslate( Canvas canvas, double x, double y, DrawCodeCallback drawCode, ) { canvas.save(); canvas.translate(x, y); drawCode(canvas); canvas.restore(); } class Chart extends StatefulWidget { Chart( this.controller, { super.key, String title = '', }) { controller.title = title; } final ChartController controller; @override ChartState createState() => ChartState(); } class ChartState extends State<Chart> with AutoDisposeMixin { ChartState(); ChartController get controller => widget.controller; /// Helper to hookup notifiers. void _initSetup() { addAutoDisposeListener(controller.traceChanged, () { setState(() { if (controller.isZoomAll) { controller.computeZoomRatio(); } controller.computeChartArea(); }); }); } @override void initState() { super.initState(); _initSetup(); } @override void didUpdateWidget(Chart oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.controller != controller) { _initSetup(); } } @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; // Chart's Custom Painter (paint) can be expensive for lots of data points (10,000s). // A repaint boundary is necessary. // TODO(terry): Optimize the 10,000s of data points to just the number of pixels in the // chart - this will make paint very fast. return RepaintBoundary( child: LayoutBuilder( // Inner container builder: (_, constraints) => GestureDetector( onTapDown: (TapDownDetails details) { final xLocalPosition = details.localPosition.dx; final timestampIndex = controller.xCoordToTimestampIndex(xLocalPosition); final timestamp = controller.xCoordToTimestamp(xLocalPosition); controller.tapLocation.value = TapLocation( details, timestamp, timestampIndex, ); }, child: SizedBox( width: constraints.widthConstraints().maxWidth, height: constraints.widthConstraints().maxHeight, child: CustomPaint( painter: ChartPainter(controller, colorScheme), ), ), ), ), ); } } /// Used to track current and previous x,y position. The parameter yBase /// is for stacked traces. If the Trace is stacked then yBase is the previous /// trace's Y position. If a trace is not stacked then yBase is always 0. class PointAndBase { PointAndBase( this.x, this.y, { double? yBase, }) : base = yBase; final double x; final double y; final double? base; } class ChartPainter extends CustomPainter { ChartPainter(this.chartController, this.colorScheme) { // marginTopY = createText(chartController.title, 1.5).height + paddingY; } final debugTrackPaintTime = false; final ChartController chartController; final ColorScheme colorScheme; static const double axisWidth = 2; @override void paint(Canvas canvas, Size size) { // TODO(terry): Used to monitor total painting time. For large // datasets e.g., offline files of 10,000s of data // points time can be kind of slows. Consider only // sampling 1 point per horizontal pixel. final startTime = DateTime.now(); final axis = Paint() ..strokeWidth = axisWidth ..color = Colors.grey; if (size != chartController.size) { chartController.size = size; chartController.computeChartArea(); } drawTranslate( canvas, chartController.xCanvasChart, chartController.yCanvasChart, (canavas) { drawAxes( canvas, axis, displayX: chartController.displayXAxis, ); }, ); final traces = chartController.traces; final tracesDataIndex = List<int>.generate( traces.length, (int index) { final length = traces[index].data.length; return length > 0 ? length - 1 : -1; }, ); /// Key is trace index and value is x,y point. final previousTracesData = <int, PointAndBase>{}; /// Key is trace index and value is x,y point. final currentTracesData = <int, PointAndBase>{}; // Visible Y max. var visibleYMax = 0.0; // TODO(terry): Need to compute x-axis left-most position for last timestamp. // May need to do the other direction so it looks better. final endVisibleIndex = chartController.timestampsLength - chartController.visibleXAxisTicks; final xTranslation = chartController.xCoordLeftMostVisibleTimestamp; final yTranslation = chartController.zeroYPosition; int xTickIndex = chartController.timestampsLength; while (--xTickIndex >= 0) { final currentTimestamp = chartController.timestamps[xTickIndex]; if (xTickIndex < endVisibleIndex) { // Once outside of visible range of data skip the rest of the collected data. break; } final tracesLength = traces.length; // Short-circuit if no traceDataIndexes left (all are -1) then we're done. if (!tracesDataIndex.any((element) => element >= 0)) continue; // Remember old cliprect. canvas.save(); // Clip to the just the area being plotted. This is important so symbols // larger than the tick area doesn't spill out on the left-side. clipChart(canvas); // Y base (stackedY) used for stacked traces each Y base for stack traces // starts at zero. Then Y base for the current data point is the previous Y // base (previous Y's datapoint). Then current data point's Y is added to Y base. double stackedY = 0.0; for (var index = 0; index < tracesLength; index++) { final traceDataIndex = tracesDataIndex[index]; if (traceDataIndex >= 0) { final trace = traces[index]; final traceData = trace.data[traceDataIndex]; final yValue = (trace.stacked) ? stackedY + traceData.y : traceData.y; final xTimestamp = traceData.timestamp; final xCanvasCoord = chartController.timestampToXCanvasCoord(xTimestamp); if (currentTimestamp == xTimestamp) { // Get ready to render on canvas. Remember old canvas state // and setup translations for x,y coordinates into the rendering // area of the chart. drawTranslate( canvas, xTranslation, yTranslation, (canvas) { final xCoord = xCanvasCoord; final yCoord = chartController.yPositionToYCanvasCoord(yValue); final hasMultipleExtensionEvents = traceData is DataAggregate ? traceData.count > 1 : false; // Is the visible Y-axis max larger. if (yValue > visibleYMax) { visibleYMax = yValue; } currentTracesData[index] = PointAndBase( xCoord, yCoord, yBase: chartController.yPositionToYCanvasCoord(stackedY), ); if (trace.chartType == ChartType.symbol) { assert(!trace.stacked); drawSymbol( canvas, trace.characteristics, xCoord, yCoord, hasMultipleExtensionEvents, trace.symbolPath, ); } else if (trace.chartType == ChartType.line) { if (trace.characteristics.symbol == ChartSymbol.dashedLine) { // TODO(terry): Collect all points and draw a dashed line using // path_drawing package. drawDashed( canvas, trace.characteristics, xCoord, yCoord, chartController.tickWidth - 4, ); } else if (previousTracesData[index] != null) { final previous = previousTracesData[index]!; final current = currentTracesData[index]!; // Stacked lines. // Drawline from previous plotted point to new point. drawConnectedLine( canvas, trace.characteristics, xCoord, yCoord, previous.x, previous.y, ); drawSymbol( canvas, trace.characteristics, xCoord, yCoord, hasMultipleExtensionEvents, trace.symbolPath, ); // TODO(terry): Honor z-order and also maybe path just on the traces e.g., // fill from top of trace 0 to top of trace 1 don't origin // from zero. // Fill area between traces. drawFillArea( canvas, trace.characteristics, previous.x, previous.y, previous.base!, current.x, current.y, current.base!, ); } else { // Draw point drawSymbol( canvas, trace.characteristics, xCoord, yCoord, hasMultipleExtensionEvents, trace.symbolPath, ); } } tracesDataIndex[index]--; }, ); final tapLocation = chartController.tapLocation.value; if (tapLocation?.index == xTickIndex || tapLocation?.timestamp == currentTimestamp) { drawTranslate( canvas, xTranslation, yTranslation, (canavas) { drawSelection( canvas, xCanvasCoord, ); }, ); } } if (trace.stacked) { stackedY += traceData.y; } } previousTracesData.addAll(currentTracesData); currentTracesData.clear(); } // Undo the clipRect at beginning of for loop. canvas.restore(); } chartController.computeChartArea(); chartController.buildLabelTimestamps(); if (chartController.displayXAxis || chartController.displayXLabels) { // Y translation is below X-axis line. drawTranslate( canvas, xTranslation, chartController.zeroYPosition + 1, (canvas) { // Draw the X-axis labels. for (var timestamp in chartController.labelTimestamps) { final xCoord = chartController.timestampToXCanvasCoord(timestamp); drawXTick(canvas, timestamp, xCoord, axis, displayTime: true); } }, ); // X translation is left-most edge of chart widget. drawTranslate( canvas, chartController.xCanvasChart, yTranslation, (canvas) { // Rescale Y-axis to max visible Y range. chartController.resetYMaxValue(visibleYMax); // Draw Y-axis ticks and labels. // TODO(terry): Optimization add a listener for Y-axis range changing // only need to redraw Y-axis if the range changed. if (chartController.displayYLabels) { drawYTicks(canvas, chartController, axis); } }, ); } drawTitle(canvas, size, chartController.title); final elapsedTime = DateTime.now().difference(startTime).inMilliseconds; if (debugTrackPaintTime && elapsedTime > 500) { _log.info( '${chartController.name} ${chartController.timestampsLength} ' 'CustomPainter paint elapsed time $elapsedTime', ); } // Once painted we're not dirty anymore. chartController.dirty = false; } void clipChart(Canvas canvas, {ClipOp op = ClipOp.intersect}) { final leftSideSide = chartController.xCanvasChart; final topChartSide = chartController.yCanvasChart; final r = Rect.fromLTRB( leftSideSide, topChartSide, chartController.canvasChartWidth + leftSideSide - chartController.xPaddingRight, topChartSide + chartController.canvasChartHeight, ); canvas.clipRect(r, clipOp: op); } // TODO(terry): Use drawText? void drawTitle(Canvas canvas, Size size, String title) { final tp = createText(title, 1.5); tp.paint(canvas, Offset(size.width / 2 - tp.width / 2, 0)); } void drawAxes( Canvas canvas, Paint axis, { bool displayX = true, bool displayY = true, }) { final chartWidthPosition = chartController.canvasChartWidth - chartController.xPaddingRight; final chartHeight = chartController.canvasChartHeight; // Left-side of chart if (displayY) { canvas.drawLine( const Offset(0, 0), Offset(0, chartHeight), axis, ); } // Bottom line of chart. if (displayX) { canvas.drawLine( Offset(0, chartHeight), Offset(chartWidthPosition, chartHeight), axis, ); } } void drawSelection(Canvas canvas, double x) { final paint = Paint() ..strokeWidth = 2.0 ..color = colorScheme.hoverSelectionBarColor; // Draw the vertical selection bar. canvas.drawLine( Offset(x, 0), // zero y-position of chart. Offset(x, -chartController.canvasChartHeight), paint, ); } /// Separated out from drawAxis because we don't know range until plotted. void drawYTicks(Canvas canvas, ChartController chartController, Paint axis) { final yScale = chartController.yScale; for (var labelIndex = yScale.labelTicks; labelIndex >= 0; labelIndex--) { final unit = pow(10, yScale.labelUnitExponent).floor(); final y = labelIndex * unit; // Need to be zero based final yCoord = chartController.yPositionToYCanvasCoord(y); final labelName = constructLabel( labelIndex.floor(), yScale.labelUnitExponent.floor(), ); // Label starts at left edge. drawText(labelName, canvas, -chartController.xCanvasChart / 2, yCoord); // Draw horizontal tick 6 pixels from Y-axis line. canvas.drawLine( Offset(0, yCoord), Offset(-6, yCoord), axis, ); } } /// Return Y axis labels using the exponent to signal unit type and the /// label value e.g. static String constructLabel(int labelValue, int unitExponent) { var unit = ''; switch (unitExponent) { case 0: case 1: case 2: case 3: labelValue = labelValue * (pow(10, unitExponent) as int); break; // Return units in K e.g., 10K, 80K, 100K, 700K, etc. // Notice that anything < 10K will return as 500, 2050, 5000, 9000, etc. case 4: case 5: labelValue = labelValue * (pow(10, unitExponent - 4) as int); unit = 'K'; break; // Return units in M e.g., 1M, 8M, 10M, 30M, 100M, 400M, etc. case 6: case 7: case 8: labelValue = labelValue * (pow(10, unitExponent - 6) as int); unit = 'M'; break; // Return units in B e.g., 1B, 7B, 10B, 50B, 100B, 900B, etc. case 9: case 10: case 11: labelValue = labelValue * (pow(10, unitExponent - 9) as int); unit = 'B'; break; // Return units in T e.g., 1T, 5T, 10T, 40T, 100T, 300T, etc. case 12: case 13: case 14: labelValue = labelValue * (pow(10, unitExponent - 12) as int); unit = 'T'; break; default: unit = 'e+$unitExponent'; } final label = labelValue.toInt(); return label == 0 ? '0' : '$label$unit'; } void drawXTick( Canvas canvas, int timestamp, double xTickCoord, Paint axis, { bool shortTick = true, bool displayTime = false, }) { if (displayTime) { // Draw vertical tick (short or long). canvas.drawLine( Offset(xTickCoord, 0), Offset(xTickCoord, shortTick ? 2 : 6), axis, ); final tp = createText(prettyTimestamp(timestamp), 1); tp.paint( canvas, Offset( xTickCoord - tp.width ~/ 2, 15.0 - tp.height ~/ 2, ), ); } } void drawText(String textValue, Canvas canvas, double x, double y) { final tp = createText(textValue, 1); tp.paint(canvas, Offset(x + -tp.width / 2, y - tp.height / 2)); } TextPainter createText(String textValue, double scale) { final span = TextSpan( // TODO(terry): All text in a chart is grey. A chart like a Trace // should have PaintCharacteristics. style: TextStyle( color: Colors.grey[600], fontSize: unscaledSmallFontSize, ), text: textValue, ); final tp = TextPainter( text: span, textAlign: TextAlign.right, textScaler: TextScaler.linear(scale), textDirection: TextDirection.ltr, ); tp.layout(); return tp; } void drawSymbol( Canvas canvas, PaintCharacteristics characteristics, double x, double y, bool aggregateEvents, Path? symbolPathToDraw, ) { late PaintingStyle firstStyle; late PaintingStyle secondStyle; switch (characteristics.symbol) { case ChartSymbol.disc: case ChartSymbol.filledSquare: case ChartSymbol.filledTriangle: case ChartSymbol.filledTriangleDown: firstStyle = PaintingStyle.fill; break; case ChartSymbol.ring: case ChartSymbol.square: case ChartSymbol.triangle: case ChartSymbol.triangleDown: firstStyle = PaintingStyle.stroke; break; case ChartSymbol.concentric: firstStyle = PaintingStyle.stroke; secondStyle = PaintingStyle.fill; break; case ChartSymbol.dashedLine: break; } final paintFirst = Paint() ..style = firstStyle ..strokeWidth = characteristics.strokeWidth ..color = aggregateEvents ? characteristics.colorAggregate! : characteristics.color; switch (characteristics.symbol) { case ChartSymbol.dashedLine: drawDashed( canvas, characteristics, x, y, chartController.tickWidth - 4, ); break; case ChartSymbol.disc: case ChartSymbol.ring: canvas.drawCircle(Offset(x, y), characteristics.diameter, paintFirst); break; case ChartSymbol.concentric: // Outer ring. canvas.drawCircle(Offset(x, y), characteristics.diameter, paintFirst); // Inner disc. final paintSecond = Paint() ..style = secondStyle ..strokeWidth = 0 // TODO(terry): Aggregate for concentric maybe needed someday. ..color = aggregateEvents ? characteristics.colorAggregate! : characteristics.concentricCenterColor; canvas.drawCircle( Offset(x, y), characteristics.concentricCenterDiameter, paintSecond, ); // Circle break; case ChartSymbol.filledSquare: case ChartSymbol.filledTriangle: case ChartSymbol.filledTriangleDown: case ChartSymbol.square: case ChartSymbol.triangle: case ChartSymbol.triangleDown: // Draw symbol centered on [x,y] point (*). final path = symbolPathToDraw!.shift( Offset( x - characteristics.width / 2, y - characteristics.height / 2, ), ); canvas.drawPath(path, paintFirst); break; default: final message = 'Unknown symbol ${characteristics.symbol}'; assert(false, message); _log.shout(message); } } // TODO(terry): Use bezier path. void drawDashed( Canvas canvas, PaintCharacteristics characteristics, double x, double y, double tickWidth, ) { assert(characteristics.symbol == ChartSymbol.dashedLine); drawLine( canvas, characteristics, x, y, tickWidth, ); } void drawConnectedLine( Canvas canvas, PaintCharacteristics characteristics, double startX, double startY, double endX, double endY, ) { final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = characteristics.strokeWidth ..color = characteristics.color; canvas.drawLine(Offset(startX, startY), Offset(endX, endY), paint); } void drawLine( Canvas canvas, PaintCharacteristics characteristics, double x, double y, double tickWidth, ) { final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = characteristics.strokeWidth ..color = characteristics.color; canvas.drawLine(Offset(x, y), Offset(x + tickWidth, y), paint); } /// Used to fill in the area for a tick from X-coordinate 0 to the tick's /// Y-coordinate with the current tick's width. void drawFillArea( Canvas canvas, PaintCharacteristics characteristics, double x0, double y0, double y0Bottom, double x1, double y1, double y1Bottom, ) { final paint = Paint() ..style = PaintingStyle.fill ..strokeWidth = characteristics.strokeWidth ..color = characteristics.color.withAlpha(140); final fillArea = Path() ..moveTo(x0, y0) ..lineTo(x1, y1) ..lineTo(x1, y1Bottom) ..lineTo(x0, y0Bottom); fillArea.close(); canvas.drawPath(fillArea, paint); fillArea.reset(); } @override bool shouldRepaint(ChartPainter oldDelegate) => chartController.isDirty; } extension ChartColorExtension on ColorScheme { // Bar color for current selection (hover). Color get hoverSelectionBarColor => isLight ? Colors.lime[600]! : Colors.yellowAccent; }
devtools/packages/devtools_app/lib/src/shared/charts/chart.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/charts/chart.dart", "repo_id": "devtools", "token_count": 10400 }
108
// 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 'dart:io'; import 'package:devtools_app_shared/utils.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as path; import '../../primitives/storage.dart'; final _log = Logger('_framework_initialize_desktop'); /// Return the url the application is launched from. Future<String> initializePlatform() async { setGlobal(Storage, FlutterDesktopStorage()); return ''; } class FlutterDesktopStorage implements Storage { late final Map<String, dynamic> _values = _readValues(); bool _fileAndDirVerified = false; @override Future<String?> getValue(String key) async { return _values[key]; } @override Future setValue(String key, String value) async { _values[key] = value; const encoder = JsonEncoder.withIndent(' '); if (!_fileAndDirVerified) { File(_preferencesFile.path).createSync(recursive: true); _fileAndDirVerified = true; } _preferencesFile.writeAsStringSync('${encoder.convert(_values)}\n'); } Map<String, dynamic> _readValues() { final File file = _preferencesFile; try { if (file.existsSync()) { return jsonDecode(file.readAsStringSync()) ?? {}; } else { return {}; } } catch (e, st) { // ignore the error reading _log.info(e, e, st); return {}; } } static File get _preferencesFile => File(path.join(_userHomeDir(), '.flutter-devtools/.devtools')); static String _userHomeDir() { final String envKey = Platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME'; final String? value = Platform.environment[envKey]; return value ?? '.'; } }
devtools/packages/devtools_app/lib/src/shared/config_specific/framework_initialize/_framework_initialize_desktop.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/framework_initialize/_framework_initialize_desktop.dart", "repo_id": "devtools", "token_count": 658 }
109
This folder contains independent libraries, i.e. libraries that do not depend on other libraries in the folder `console`.
devtools/packages/devtools_app/lib/src/shared/console/primitives/README.md/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/console/primitives/README.md", "repo_id": "devtools", "token_count": 26 }
110
// 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 '../memory/adapted_heap_data.dart'; import '../memory/simple_items.dart'; import '../vm_utils.dart'; import 'diagnostics_node.dart'; /// True, if [ref] contains static or live information about references and thus /// makes the node expandable. bool isRootForReferences(GenericInstanceRef? ref) { if (ref == null) return false; if (ref is! ObjectReferences) { return ref.heapSelection != null; } if (ref.instanceRef?.length == 0 || isPrimitiveInstanceKind(ref.instanceRef?.kind)) return false; return ref.refNodeType.isRoot; } /// A generic [InstanceRef] using either format used by the [InspectorService] /// or Dart VM. /// /// Either one or both of [value] and [diagnostic] may be provided. The /// `valueRef` getter on the [diagnostic] should refer to the same object as /// [instanceRef] although using the [InspectorInstanceRef] scheme. /// A [RemoteDiagnosticsNode] is used rather than an [InspectorInstanceRef] as /// the additional data provided by [RemoteDiagnosticsNode] is helpful to /// correctly display the object and [RemoteDiagnosticsNode] includes a /// reference to an [InspectorInstanceRef]. [value] must be a VM service type, /// Sentinel, or primitive type. class GenericInstanceRef { GenericInstanceRef({ required this.isolateRef, this.value, this.diagnostic, this.heapSelection, }); final Object? value; final HeapObjectSelection? heapSelection; InstanceRef? get instanceRef => value is InstanceRef ? value as InstanceRef? : null; /// If both [diagnostic] and [instanceRef] are provided, [diagnostic.valueRef] /// must reference the same underlying object just using the /// [InspectorInstanceRef] scheme. final RemoteDiagnosticsNode? diagnostic; final IsolateRef? isolateRef; } class ObjectReferences extends GenericInstanceRef { ObjectReferences({ required this.refNodeType, required IsolateRef super.isolateRef, required super.value, required HeapObjectSelection super.heapSelection, }) { if (refNodeType.isLive) assert(value != null); } ObjectReferences.copyWith( ObjectReferences ref, { RefNodeType? refNodeType, HeapObjectSelection? heapSelection, }) : refNodeType = refNodeType ?? ref.refNodeType, super( isolateRef: ref.isolateRef, value: ref.value, heapSelection: heapSelection ?? ref.heapSelection, ); final RefNodeType refNodeType; @override HeapObjectSelection get heapSelection => super.heapSelection!; @override IsolateRef get isolateRef => super.isolateRef!; int? get childCount { final result = heapSelection.countOfReferences(refNodeType.direction); if (result != null) return result; final instance = value; if (instance is! InstanceRef) return null; return instance.length; } } enum RefNodeType { /// Root item for references. refRoot, /// Subitem of [refRoot] for static references. staticRefRoot, /// Subitem of [staticRefRoot] for inbound static references. staticInRefs(RefDirection.inbound), /// Subitem of [staticRefRoot] for outbound static references. staticOutRefs(RefDirection.outbound), /// Subitem of [refRoot] for live references. liveRefRoot, /// Subitem of [liveRefRoot] for inbound live references. liveInRefs(RefDirection.inbound), /// Subitem of [liveRefRoot] for outbound live references. liveOutRefs(RefDirection.outbound), ; const RefNodeType([this.direction]); final RefDirection? direction; bool get isRoot => const {refRoot, staticRefRoot, liveRefRoot}.contains(this); bool get isLive => const {liveOutRefs, liveInRefs, liveRefRoot}.contains(this); }
devtools/packages/devtools_app/lib/src/shared/diagnostics/generic_instance_reference.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/diagnostics/generic_instance_reference.dart", "repo_id": "devtools", "token_count": 1230 }
111
// 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/foundation.dart'; import '../../screens/debugger/codeview.dart'; import '../analytics/constants.dart' as gac; import '../common_widgets.dart'; import '../diagnostics/inspector_service.dart'; import '../globals.dart'; import '../utils.dart'; import 'environment_parameters_base.dart'; class ExternalDevToolsEnvironmentParameters implements DevToolsEnvironmentParameters { @override List<ScriptPopupMenuOption> buildExtraDebuggerScriptPopupMenuOptions() => <ScriptPopupMenuOption>[]; @override Link issueTrackerLink({String? additionalInfo, String? issueTitle}) { return Link( display: _newDevToolsIssueUriDisplay, url: newDevToolsGitHubIssueUriLengthSafe( additionalInfo: additionalInfo, issueTitle: issueTitle, environment: issueLinkDetails(), ).toString(), gaScreenName: gac.devToolsMain, gaSelectedItemDescription: gac.feedbackLink, ); } @override String? username() { // This should always return a null value for 3p users. return null; } @override Link? enableSourceMapsLink() { // This should always return a null value for 3p users. return null; } @override String loadingAppSizeDataMessage() { return 'Loading app size data. Please wait...'; } @override InspectorServiceBase? inspectorServiceProvider() => serviceConnection.serviceManager.connectedApp!.isFlutterAppNow == true ? InspectorService() : null; @override String get perfettoIndexLocation => 'packages/perfetto_ui_compiled/dist/index.html'; @override String? chrome115BreakpointBug() { // This should always return a null value for 3p users. return null; } } const _newDevToolsIssueUriDisplay = 'github.com/flutter/devtools/issues/new'; @visibleForTesting const maxGitHubUriLength = 8190; @visibleForTesting Uri newDevToolsGitHubIssueUriLengthSafe({ required List<String> environment, String? additionalInfo, String? issueTitle, }) { final fullUri = _newDevToolsGitHubIssueUri( additionalInfo: additionalInfo, issueTitle: issueTitle, environment: environment, ); final lengthToCut = fullUri.toString().length - maxGitHubUriLength; if (lengthToCut <= 0) return fullUri; if (additionalInfo == null) { return Uri.parse(fullUri.toString().substring(0, maxGitHubUriLength)); } // Truncate the additional info if the URL is too long: final truncatedInfo = additionalInfo.substring(0, additionalInfo.length - lengthToCut); final truncatedUri = _newDevToolsGitHubIssueUri( additionalInfo: truncatedInfo, issueTitle: issueTitle, environment: environment, ); assert(truncatedUri.toString().length <= maxGitHubUriLength); return truncatedUri; } Uri _newDevToolsGitHubIssueUri({ required List<String> environment, String? additionalInfo, String? issueTitle, }) { final issueBody = [ if (additionalInfo != null) additionalInfo, ...environment, ].join('\n'); return Uri.parse('https://$_newDevToolsIssueUriDisplay').replace( queryParameters: { 'title': issueTitle, 'body': issueBody, }, ); }
devtools/packages/devtools_app/lib/src/shared/environment_parameters/environment_parameters_external.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/environment_parameters/environment_parameters_external.dart", "repo_id": "devtools", "token_count": 1130 }
112
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:vm_service/vm_service.dart'; import '../primitives/utils.dart'; import 'adapted_heap_object.dart'; import 'simple_items.dart'; @immutable class HeapObjectSelection { const HeapObjectSelection(this.heap, {required this.object}); final AdaptedHeapData heap; /// If object is null, it exists in live app, but is not /// located in heap. final AdaptedHeapObject? object; Iterable<int>? _refs(RefDirection direction) { switch (direction) { case RefDirection.inbound: return object?.inRefs; case RefDirection.outbound: return object?.outRefs; } } List<HeapObjectSelection> references(RefDirection direction) => (_refs(direction) ?? []) .map((i) => HeapObjectSelection(heap, object: heap.objects[i])) .toList(); int? countOfReferences(RefDirection? direction) => direction == null ? null : _refs(direction)?.length; HeapObjectSelection withoutObject() { if (object == null) return this; return HeapObjectSelection(heap, object: null); } } typedef HeapDataCallback = AdaptedHeapData Function(); /// Contains information from [HeapSnapshotGraph], /// needed for memory screen. class AdaptedHeapData { AdaptedHeapData( this.objects, { this.rootIndex = _defaultRootIndex, DateTime? created, }) : assert(objects.isNotEmpty), assert(objects.length > rootIndex) { this.created = created ?? DateTime.now(); } static final _uiReleaser = UiReleaser(); static Future<AdaptedHeapData> fromHeapSnapshot( HeapSnapshotGraph graph, ) async { final objects = <AdaptedHeapObject>[]; for (final i in Iterable<int>.generate(graph.objects.length)) { if (_uiReleaser.step()) await _uiReleaser.releaseUi(); final object = AdaptedHeapObject.fromHeapSnapshotObject(graph.objects[i], i); objects.add(object); } return AdaptedHeapData(objects); } static Future<AdaptedHeapData> fromBytes( Uint8List bytes, ) { final data = bytes.buffer.asByteData(); final graph = HeapSnapshotGraph.fromChunks([data]); return fromHeapSnapshot(graph); } /// Default value for rootIndex is taken from the doc: /// https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/heap_snapshot.md#object-ids static const int _defaultRootIndex = 1; final int rootIndex; AdaptedHeapObject get root => objects[rootIndex]; final List<AdaptedHeapObject> objects; /// Total size of all objects in the heap. /// /// Should be set externally. late int totalDartSize; bool allFieldsCalculated = false; late DateTime created; String snapshotName = ''; /// Heap objects by `identityHashCode`. late final _objectsByCode = <IdentityHashCode, int?>{ for (var i in Iterable<int>.generate(objects.length)) objects[i].code: i, }; int? objectIndexByIdentityHashCode(IdentityHashCode code) => _objectsByCode[code]; HeapPath? retainingPath(int objectIndex) { assert(allFieldsCalculated); if (objects[objectIndex].retainer == null) return null; final result = <AdaptedHeapObject>[]; while (objectIndex >= 0) { final object = objects[objectIndex]; result.add(object); objectIndex = object.retainer!; } return HeapPath(result.reversed.toList(growable: false)); } late final totalReachableSize = () { if (!allFieldsCalculated) throw StateError('Spanning tree should be built'); return objects[rootIndex].retainedSize!; }(); } /// Sequence of ids of objects in the heap. class HeapPath { HeapPath(this.objects); final List<AdaptedHeapObject> objects; late final bool isRetainedBySameClass = () { if (objects.length < 2) return false; final theClass = objects.last.heapClass; return objects .take(objects.length - 1) .any((object) => object.heapClass == theClass); }(); /// Retaining path for the object in string format. String shortPath() => '/${objects.map((o) => o.shortName).join('/')}/'; /// Retaining path for the object as an array of the retaining objects. List<String> detailedPath() => objects.map((o) => o.name).toList(growable: false); }
devtools/packages/devtools_app/lib/src/shared/memory/adapted_heap_data.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/memory/adapted_heap_data.dart", "repo_id": "devtools", "token_count": 1530 }
113
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; final _log = Logger('syntax_highlighting'); //Future<String> loadPolyfillScript() { // return asset.loadString('assets/scripts/inspector_polyfill_script.dart'); //} // https://macromates.com/manual/en/language_grammars void main() { final String source = File('assets/syntax/dart.json').readAsStringSync(); final TextmateGrammar dartGrammar = TextmateGrammar(source); _log.info(dartGrammar); } // todo: test basic parsing class TextmateGrammar { TextmateGrammar(String syntaxDefinition) { _definition = jsonDecode(syntaxDefinition); _parseFileRules(); _parseRules(); } final List<Rule> _fileRules = []; final Map<String, Rule> _ruleMap = {}; late final Map _definition; /// The name of the grammar. String? get name => _definition['name']; /// The file type extensions that the grammar should be used with. List<String> get fileTypes => (_definition['fileTypes'] as List).cast<String>(); void _parseRules() { final Map repository = _definition['repository']; for (String name in repository.keys.cast<String>()) { _ruleMap[name] = Rule(name); } for (String name in _ruleMap.keys) { _ruleMap[name]!._parse(repository[name]); } _log.info('rules: ${_ruleMap.keys.toList()}'); } void _parseFileRules() { final List<Object?> patterns = _definition['patterns']; for (Map info in patterns.cast<Map<Object?, Object?>>()) { _fileRules.add(Rule(info['name']).._parse(info)); } _log.info('fileRules: $_fileRules'); } @override String toString() => '$name: $fileTypes'; } // todo: make abstract // todo: have a forwarding rule // todo: have a match rule, and a begin / end rule class Rule { Rule(this.name); final String? name; void _parse(Map<Object?, Object?>? _) { // todo: } @override String toString() => '$name'; }
devtools/packages/devtools_app/lib/src/shared/primitives/syntax_highlighting.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/primitives/syntax_highlighting.dart", "repo_id": "devtools", "token_count": 739 }
114
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:devtools_shared/devtools_deeplink.dart'; import 'package:devtools_shared/devtools_extensions.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart'; import 'package:logging/logging.dart'; import '../development_helpers.dart'; import '../primitives/utils.dart'; part '_analytics_api.dart'; part '_app_size_api.dart'; part '_deep_links_api.dart'; part '_extensions_api.dart'; part '_release_notes_api.dart'; part '_survey_api.dart'; part '_dtd_api.dart'; final _log = Logger('devtools_server_client'); // The DevTools server is only available in release mode right now. // TODO(kenz): design a way to run the DevTools server and DevTools app together // in debug mode. bool get isDevToolsServerAvailable => kReleaseMode; /// Helper to catch any server request which could fail. /// /// Returns HttpRequest or null (if server failure). Future<Response?> request(String url) async { Response? response; try { _log.fine('requesting $url'); response = await post(Uri.parse(url)); } catch (_) {} return response; } // currently unused /// Requests all .devtools properties to be reset to their default values in the /// file '~/.flutter-devtools/.devtools'. Future<void> resetDevToolsFile() async { if (isDevToolsServerAvailable) { final resp = await request(apiResetDevTools); if (resp?.statusOk ?? false) { assert(json.decode(resp!.body)); } else { logWarning(resp, apiResetDevTools); } } } Future<DevToolsJsonFile?> requestFile({ required String api, required String fileKey, required String filePath, }) async { if (isDevToolsServerAvailable) { final url = Uri(path: api, queryParameters: {fileKey: filePath}); final resp = await request(url.toString()); if (resp?.statusOk ?? false) { return _devToolsJsonFileFromResponse(resp!, filePath); } else { logWarning(resp, api); } } return null; } Future<void> notifyForVmServiceConnection({ required String vmServiceUri, required bool connected, }) async { if (isDevToolsServerAvailable) { final uri = Uri( path: apiNotifyForVmServiceConnection, queryParameters: { apiParameterValueKey: vmServiceUri, apiParameterVmServiceConnected: connected.toString(), }, ); final resp = await request(uri.toString()); final statusOk = resp?.statusOk ?? false; if (!statusOk) { logWarning(resp, apiNotifyForVmServiceConnection); } } } DevToolsJsonFile _devToolsJsonFileFromResponse( Response resp, String filePath, ) { final data = json.decode(resp.body) as Map; final lastModified = data['lastModifiedTime']; final lastModifiedTime = lastModified != null ? DateTime.parse(lastModified) : DateTime.now(); return DevToolsJsonFile( name: filePath, lastModifiedTime: lastModifiedTime, data: data, ); } void logWarning(Response? response, String apiType) { final respText = response?.body; _log.warning( 'HttpRequest $apiType failed status = ${response?.statusCode}' '${respText != null ? ', responseText = $respText' : ''}', ); } extension ResponseExtension on Response { bool get statusOk => statusCode == 200; bool get statusForbidden => statusCode == 403; bool get statusError => statusCode == 500; }
devtools/packages/devtools_app/lib/src/shared/server/server.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/server/server.dart", "repo_id": "devtools", "token_count": 1216 }
115
// 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:collection/collection.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../analytics/analytics.dart' as ga; import '../common_widgets.dart'; /// A [DropDownButton] implementation that reports selection changes to our /// analytics. class AnalyticsDropDownButton<T> extends StatelessWidget { const AnalyticsDropDownButton({ super.key, required this.gaScreen, required this.gaDropDownId, required this.message, required this.value, required this.items, required this.onChanged, this.sendAnalytics = true, this.isDense = false, this.isExpanded = false, this.roundedCornerOptions, }); /// The GA ID for the screen this widget is displayed on. final String gaScreen; /// The GA ID for this widget. final String gaDropDownId; /// Whether to send analytics events to GA. /// /// Only set this to false if [AnalyticsDropDownButton] is being used for /// experimental code we do not want to send GA events for yet. final bool sendAnalytics; /// The message to be displayed in the widget's tooltip. final String? message; /// The currently selected value. final T? value; /// The list of options available in the drop down with their associated GA /// IDs. final List<({DropdownMenuItem<T> item, String gaId})>? items; /// Invoked when the selected drop down item has changed. final void Function(T?)? onChanged; final bool isDense; final bool isExpanded; final RoundedCornerOptions? roundedCornerOptions; @override Widget build(BuildContext context) { return SizedBox( height: defaultButtonHeight, child: DevToolsTooltip( message: message, child: RoundedDropDownButton<T>( isDense: isDense, isExpanded: isExpanded, value: value, items: items?.map((e) => e.item).toList(), onChanged: _onChanged, roundedCornerOptions: roundedCornerOptions, ), ), ); } void _onChanged(T? newValue) { if (sendAnalytics && items != null) { final gaId = items?.firstWhereOrNull((element) => element.item == newValue)?.gaId; if (gaId != null) { ga.select(gaScreen, '$gaDropDownId $gaId'); } } onChanged?.call(newValue); } }
devtools/packages/devtools_app/lib/src/shared/ui/drop_down_button.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/ui/drop_down_button.dart", "repo_id": "devtools", "token_count": 865 }
116
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../shared/analytics/analytics.dart' as ga; import '../../shared/analytics/constants.dart' as gac; import '../api/vs_code_api.dart'; class Devices extends StatelessWidget { Devices( this.api, { required this.devices, required this.unsupportedDevices, required this.selectedDeviceId, super.key, }) : unsupportedDevicePlatformTypes = unsupportedDevices .map((device) => device.platformType) .nonNulls .toSet(); final VsCodeApi api; final List<VsCodeDevice> devices; final List<VsCodeDevice> unsupportedDevices; final Set<String> unsupportedDevicePlatformTypes; final String? selectedDeviceId; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Devices', style: theme.textTheme.titleMedium, ), if (devices.isEmpty) const Text('Connect a device or enable web/desktop platforms.') else Table( defaultVerticalAlignment: TableCellVerticalAlignment.middle, children: [ for (final device in devices) _createDeviceRow( theme, device, isSelected: device.id == selectedDeviceId, ), for (final platformType in unsupportedDevicePlatformTypes) _createPlatformTypeEnablerRow( theme, platformType, ), ], ), ], ); } TableRow _createDeviceRow( ThemeData theme, VsCodeDevice device, { required bool isSelected, }) { final backgroundColor = isSelected ? theme.colorScheme.secondary : null; final foregroundColor = isSelected ? theme.colorScheme.onSecondary : theme.colorScheme.secondary; return TableRow( decoration: BoxDecoration(color: backgroundColor), children: [ SizedBox( width: double.infinity, child: TextButton.icon( style: TextButton.styleFrom( alignment: Alignment.centerLeft, shape: const ContinuousRectangleBorder(), textStyle: theme.regularTextStyle, ), icon: Icon( device.iconData, size: actionsIconSize, color: foregroundColor, ), label: Text( device.name, style: theme.regularTextStyle.copyWith(color: foregroundColor), ), onPressed: () { ga.select( gac.VsCodeFlutterSidebar.id, gac.VsCodeFlutterSidebar.changeSelectedDevice.name, ); unawaited(api.selectDevice(device.id)); }, ), ), ], ); } TableRow _createPlatformTypeEnablerRow(ThemeData theme, String platformType) { final foregroundColor = theme.colorScheme.secondary; return TableRow( children: [ SizedBox( width: double.infinity, child: TextButton( style: TextButton.styleFrom( alignment: Alignment.centerLeft, shape: const ContinuousRectangleBorder(), textStyle: theme.regularTextStyle, ), child: Text( 'Enable $platformType for this project', style: theme.regularTextStyle.copyWith(color: foregroundColor), ), onPressed: () { ga.select( gac.VsCodeFlutterSidebar.id, gac.VsCodeFlutterSidebar.enablePlatformType(platformType), ); unawaited(api.enablePlatformType(platformType)); }, ), ), ], ); } } extension on VsCodeDevice { IconData get iconData { return switch ((category, platformType)) { ('desktop', 'macos') => Icons.desktop_mac_outlined, ('desktop', 'windows') => Icons.desktop_windows_outlined, ('desktop', _) => Icons.computer_outlined, ('mobile', 'android') => Icons.phone_android_outlined, ('mobile', 'ios') => Icons.phone_iphone_outlined, ('mobile', _) => Icons.smartphone_outlined, ('web', _) => Icons.web_outlined, _ => Icons.device_unknown_outlined, }; } }
devtools/packages/devtools_app/lib/src/standalone_ui/vs_code/devices.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/standalone_ui/vs_code/devices.dart", "repo_id": "devtools", "token_count": 2138 }
117
This is draft for future release notes, that are going to land on [the Flutter website](https://docs.flutter.dev/tools/devtools/release-notes). # DevTools 2.34.0 release notes The 2.34.0 release of the Dart and Flutter DevTools includes the following changes among other general improvements. To learn more about DevTools, check out the [DevTools overview]({{site.url}}/tools/devtools/overview). ## General updates * Fixed an issue preventing DevTools from connecting to Flutter apps that are not launched from Flutter Tools. - [#6848](https://github.com/flutter/devtools/issues/6848) ## Inspector updates TODO: Remove this section if there are not any general updates. ## Performance updates * Add a setting to include CPU samples in the Timeline. - [#7333](https://github.com/flutter/devtools/pull/7333), [#7369](https://github.com/flutter/devtools/pull/7369) * Removed the legacy trace viewer. The legacy trace viwer was replaced with the embedded Perfetto trace viewer in DevTools version 2.21.1, but was available behind a setting to ensure a smooth rollout. This release of DevTools removes the legacy trace viewer entirely. - [#7316](https://github.com/flutter/devtools/pull/7316) ## CPU profiler updates TODO: Remove this section if there are not any general updates. ## Memory updates TODO: Remove this section if there are not any general updates. ## Debugger updates TODO: Remove this section if there are not any general updates. ## Network profiler updates * Improved Network profiler performance. [#7266](https://github.com/flutter/devtools/pull/7266) * Fixed a bug where selected pending requests weren't refreshing the tab once updated. [#7266](https://github.com/flutter/devtools/pull/7266) * Fixed JsonViewer where all of the expanded sections would snap closed. [#7367](https://github.com/flutter/devtools/pull/7367) ## Logging updates TODO: Remove this section if there are not any general updates. ## App size tool updates TODO: Remove this section if there are not any general updates. ## VS Code Sidebar updates TODO: Remove this section if there are not any general updates. ## DevTools Extension updates TODO: Remove this section if there are not any general updates. ## Full commit history To find a complete list of changes in this release, check out the [DevTools git log](https://github.com/flutter/devtools/tree/v2.34.0).
devtools/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md/0
{ "file_path": "devtools/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md", "repo_id": "devtools", "token_count": 666 }
118
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/service/service_manager.dart'; import 'package:devtools_app/src/shared/diagnostics/dart_object_node.dart'; import 'package:devtools_app/src/shared/diagnostics/tree_builder.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:vm_service/vm_service.dart'; const isolateId = '433'; const objectId = '123'; final libraryRef = LibraryRef( name: 'some library', uri: 'package:foo/foo.dart', id: 'lib-id-1', ); void main() { late ServiceConnectionManager manager; setUp(() { final service = createMockVmServiceWrapperWithDefaults(); manager = FakeServiceConnectionManager(service: service); setGlobal(ServiceConnectionManager, manager); }); test( 'Creates bound variables for Map with String key and Double value', () async { final instance = Instance( kind: InstanceKind.kMap, id: objectId, length: 2, associations: [ MapAssociation( key: InstanceRef( id: '4', kind: InstanceKind.kString, valueAsString: 'Hey', ), value: InstanceRef( id: '5', kind: InstanceKind.kDouble, valueAsString: '12.34', ), ), ], ); final isolateRef = IsolateRef( id: isolateId, number: '1', name: 'my-isolate', isSystemIsolate: false, ); final variable = DartObjectNode.create( BoundVariable( name: 'test', value: instance, ), isolateRef, ); when(manager.serviceManager.service!.getObject(isolateId, objectId)) .thenAnswer((_) async { return instance; }); await buildVariablesTree(variable); expect(variable.children, [ matchesVariable(name: 'Hey', value: '12.34'), ]); }, ); test( 'Creates bound variables for Map with Int key and Double value', () async { final isolateRef = IsolateRef( id: isolateId, number: '1', name: 'my-isolate', isSystemIsolate: false, ); final instance = Instance( kind: InstanceKind.kMap, id: objectId, length: 2, associations: [ MapAssociation( key: InstanceRef( id: '4', kind: InstanceKind.kInt, valueAsString: '1', ), value: InstanceRef( id: '5', kind: InstanceKind.kDouble, valueAsString: '12.34', ), ), ], ); final variable = DartObjectNode.create( BoundVariable( name: 'test', value: instance, ), isolateRef, ); when(manager.serviceManager.service!.getObject(isolateId, objectId)) .thenAnswer((_) async { return instance; }); await buildVariablesTree(variable); expect(variable.children, [ matchesVariable(name: '1', value: '12.34'), ]); }, ); test( 'Creates bound variables for Map with Object key and Double value', () async { final isolateRef = IsolateRef( id: isolateId, number: '1', name: 'my-isolate', isSystemIsolate: false, ); final instance = Instance( kind: InstanceKind.kMap, id: objectId, length: 2, associations: [ MapAssociation( key: InstanceRef( classRef: ClassRef(id: 'a', name: 'Foo', library: libraryRef), id: '4', kind: InstanceKind.kPlainInstance, ), value: InstanceRef( id: '5', kind: InstanceKind.kDouble, valueAsString: '12.34', ), ), ], ); final variable = DartObjectNode.create( BoundVariable( name: 'test', value: instance, ), isolateRef, ); when(manager.serviceManager.service!.getObject(isolateId, objectId)) .thenAnswer((_) async { return instance; }); await buildVariablesTree(variable); expect(variable.children, [ matchesVariable(name: null, value: '[Entry 0]'), ]); expect(variable.children.first.children, [ matchesVariable(name: '[key]', value: 'Foo'), matchesVariable(name: '[val]', value: '12.34'), ]); }, ); } Matcher matchesVariable({ required String? name, required Object value, }) { return const TypeMatcher<DartObjectNode>() .having( (v) => v.displayValue, 'displayValue', equals(value), ) .having( (v) => v.name, 'name', equals(name), ); }
devtools/packages/devtools_app/test/debugger/association_variable_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/debugger/association_variable_test.dart", "repo_id": "devtools", "token_count": 2409 }
119
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/debugger/codeview.dart'; import 'package:devtools_app/src/screens/debugger/debugger_model.dart'; import 'package:devtools_app/src/shared/diagnostics/primitives/source_location.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/utils/test_utils.dart'; void main() { late CodeViewController codeViewController; late MockDebuggerController mockDebuggerController; const smallWindowSize = Size(1200.0, 1000.0); void initializeGlobalsAndMockApp() { final fakeServiceConnection = FakeServiceConnectionManager(); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(BreakpointManager, BreakpointManager()); setGlobal(IdeTheme, IdeTheme()); setGlobal(ScriptManager, MockScriptManager()); setGlobal(NotificationService, NotificationService()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); mockConnectedApp( fakeServiceConnection.serviceManager.connectedApp!, isProfileBuild: false, isFlutterApp: true, isWebApp: false, ); } Future<void> pumpDebuggerScreen( WidgetTester tester, DebuggerController controller, ) async { await tester.pumpWidget( wrapWithControllers( DebuggerSourceAndControls( shownFirstScript: () => true, setShownFirstScript: (_) {}, ), debugger: controller, ), ); } Future<void> showScript(ScriptRef scriptRef) async { await codeViewController.showScriptLocation( ScriptLocation( scriptRef, location: const SourcePosition(line: 1, column: 1), ), ); } setUpAll(() async { initializeGlobalsAndMockApp(); await SyntaxHighlighter.initialize(); codeViewController = CodeViewController(); mockDebuggerController = createMockDebuggerControllerWithDefaults( codeViewController: codeViewController, ); }); group('for a script with < 100000 lines', () { setUpAll(() { when(scriptManager.getScriptCached(mockScriptRef)).thenReturn(mockScript); }); testWidgetsWithWindowSize( 'lines of the script are visible', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockScriptRef); await tester.pumpAndSettle(); expectFirstNLinesContain( [ '// Copyright 2019 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.', ], ); }, ); testWidgetsWithWindowSize( 'lines of the script are highlighted', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockScriptRef); await tester.pumpAndSettle(); expect(firstNLinesAreHighlighted(10), isTrue); }, ); testWidgetsWithWindowSize( 'script name is visible', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockScriptRef); await tester.pumpAndSettle(); expect( find.text('package:gallery/main.dart'), findsOneWidget, ); }, ); }); group('for a script with > 100000 lines', () { setUpAll(() { when(scriptManager.getScriptCached(mockLargeScriptRef)) .thenReturn(mockLargeScript); }); testWidgetsWithWindowSize( 'script name is visible', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockLargeScriptRef); await tester.pumpAndSettle(); expect( find.text('package:front_end/src/fasta/kernel/body_builder.dart'), findsOneWidget, ); }, ); testWidgetsWithWindowSize( 'lines of the script are visible', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockLargeScriptRef); await tester.pumpAndSettle(); expectFirstNLinesContain( [ '// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file', '// for details. All rights reserved. Use of this source code is governed by a', '// BSD-style license that can be found in the LICENSE file.', ], ); }, ); testWidgetsWithWindowSize( 'lines of the script are not highlighted', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockLargeScriptRef); await tester.pumpAndSettle(); expect(firstNLinesAreHighlighted(10), isFalse); }, ); }); group('for a script with no source', () { setUpAll(() { when(scriptManager.getScriptCached(mockScriptRef)).thenReturn(mockScript); when(scriptManager.getScriptCached(mockEmptyScriptRef)) .thenReturn(mockEmptyScript); }); testWidgetsWithWindowSize( 'script name does not update', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockScriptRef); await tester.pumpAndSettle(); expect( find.text('package:gallery/main.dart'), findsOneWidget, ); await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockEmptyScriptRef); await tester.pumpAndSettle(); expect( find.text('package:gallery/main.dart'), findsOneWidget, ); }, ); testWidgetsWithWindowSize( 'lines of the script do not update', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockScriptRef); await tester.pumpAndSettle(); expectFirstNLinesContain( [ '// Copyright 2019 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.', ], ); await pumpDebuggerScreen(tester, mockDebuggerController); await showScript(mockEmptyScriptRef); await tester.pumpAndSettle(); expectFirstNLinesContain( [ '// Copyright 2019 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.', ], ); }, ); testWidgetsWithWindowSize( 'an error message is shown', smallWindowSize, (WidgetTester tester) async { await pumpDebuggerScreen(tester, mockDebuggerController); // Dismiss any previous notifications: notificationService .dismiss('Failed to parse package:gallery/src/unknown.dart.'); await tester.pumpAndSettle(); await showScript(mockEmptyScriptRef); await tester.pumpAndSettle(); expect( notificationService.activeMessages.first.text, equals('Failed to parse package:gallery/src/unknown.dart.'), ); }, ); }); } bool firstNLinesAreHighlighted(int n) { bool containsNonHighlightedLine = false; final lines = find.byType(LineItem); for (int i = 0; i < n; i++) { final line = getWidgetFromFinder<LineItem>(lines.at(i)); if (line.lineContents.children == null) { containsNonHighlightedLine = true; } } return !containsNonHighlightedLine; } void expectFirstNLinesContain(List<String> stringMatches) { final lines = find.byType(LineItem); expect(lines, findsAtLeastNWidgets(stringMatches.length)); for (int i = 0; i < stringMatches.length; i++) { final stringMatch = stringMatches[i]; final line = getWidgetFromFinder<LineItem>(lines.at(i)); expect(line.lineContents.toPlainText(), contains(stringMatch)); } }
devtools/packages/devtools_app/test/debugger/debugger_scripts_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/debugger/debugger_scripts_test.dart", "repo_id": "devtools", "token_count": 3511 }
120
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Fake construction requires number of unawaited calls. // ignore_for_file: discarded_futures import 'dart:convert'; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/inspector/layout_explorer/flex/flex.dart'; import 'package:devtools_app/src/screens/inspector/layout_explorer/layout_explorer.dart'; import 'package:devtools_app/src/service/service_extensions.dart' as extensions; 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' hide Fake; import 'package:mockito/mockito.dart'; import '../test_infra/flutter_test_storage.dart'; void main() { final screen = InspectorScreen(); late FakeServiceConnectionManager fakeServiceConnection; late FakeServiceExtensionManager fakeExtensionManager; late InspectorController inspectorController; const windowSize = Size(2600.0, 1200.0); final debuggerController = createMockDebuggerControllerWithDefaults(); Widget buildInspectorScreen() { return wrapWithControllers( Builder(builder: screen.build), debugger: debuggerController, inspector: inspectorController, ); } setUp(() { fakeServiceConnection = FakeServiceConnectionManager(); fakeExtensionManager = fakeServiceConnection.serviceManager.serviceExtensionManager; mockConnectedApp( fakeServiceConnection.serviceManager.connectedApp!, isFlutterApp: true, isProfileBuild: false, isWebApp: false, ); when( fakeServiceConnection.errorBadgeManager.errorCountNotifier('inspector'), ).thenReturn(ValueNotifier<int>(0)); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal(PreferencesController, PreferencesController()); setGlobal(Storage, FlutterTestStorage()); setGlobal(NotificationService, NotificationService()); fakeServiceConnection.consoleService.ensureServiceInitialized(); inspectorController = InspectorController( inspectorTree: InspectorTreeController(), detailsTree: InspectorTreeController(), treeType: FlutterTreeType.widget, )..firstInspectorTreeLoadCompleted = true; }); Future<void> mockExtensions() async { fakeExtensionManager.extensionValueOnDevice = { extensions.toggleSelectWidgetMode.extension: true, extensions.enableOnDeviceInspector.extension: true, extensions.toggleOnDeviceWidgetInspector.extension: true, extensions.debugPaint.extension: false, }; await fakeExtensionManager.fakeAddServiceExtension( extensions.toggleOnDeviceWidgetInspector.extension, ); await fakeExtensionManager .fakeAddServiceExtension(extensions.toggleSelectWidgetMode.extension); await fakeExtensionManager .fakeAddServiceExtension(extensions.enableOnDeviceInspector.extension); await fakeExtensionManager .fakeAddServiceExtension(extensions.debugPaint.extension); await fakeExtensionManager.fakeFrame(); } void mockNoExtensionsAvailable() { fakeExtensionManager.extensionValueOnDevice = { extensions.toggleOnDeviceWidgetInspector.extension: true, extensions.toggleSelectWidgetMode.extension: false, extensions.debugPaint.extension: false, }; // Don't actually send any events to the client indicating that service // extensions are avaiable. fakeExtensionManager.fakeFrame(); } testWidgetsWithWindowSize( 'builds its tab', windowSize, (WidgetTester tester) async { await tester.pumpWidget(buildInspectorScreen()); await tester.pumpAndSettle(); expect(find.byType(InspectorScreenBody), findsOneWidget); }, ); group('Widget Errors', () { // Display of error navigator/indicators is tested by a golden in // inspector_integration_test.dart testWidgetsWithWindowSize( 'does not render error navigator if no errors', windowSize, (WidgetTester tester) async { await tester.pumpWidget(buildInspectorScreen()); expect(find.byType(ErrorNavigator), findsNothing); }, ); }); testWidgetsWithWindowSize( 'builds with no data', windowSize, (WidgetTester tester) async { // Make sure the window is wide enough to display description text. await tester.pumpWidget(buildInspectorScreen()); expect(find.byType(InspectorScreenBody), findsOneWidget); expect(find.byTooltip('Refresh Tree'), findsOneWidget); expect(find.text(extensions.debugPaint.title), findsOneWidget); // Make sure there is not an overflow if the window is narrow. // TODO(jacobr): determine why there are overflows in the test environment // but not on the actual device for this cae. // await setWindowSize(const Size(1000.0, 1200.0)); // Verify that description text is no-longer shown. // expect(find.text(extensions.debugPaint.description), findsOneWidget); }, ); testWidgetsWithWindowSize( 'Test toggling service extension buttons', windowSize, (WidgetTester tester) async { await mockExtensions(); expect( fakeExtensionManager .extensionValueOnDevice[extensions.debugPaint.extension], isFalse, ); expect( fakeExtensionManager.extensionValueOnDevice[ extensions.toggleOnDeviceWidgetInspector.extension], isTrue, ); await tester.pumpWidget(buildInspectorScreen()); expect( fakeExtensionManager.extensionValueOnDevice[ extensions.toggleSelectWidgetMode.extension], isTrue, ); // We need a frame to find out that the service extension state has changed. expect(find.byType(InspectorScreenBody), findsOneWidget); expect( find.text(extensions.toggleSelectWidgetMode.title), findsOneWidget, ); expect(find.text(extensions.debugPaint.title), findsOneWidget); await tester.pump(); await tester.tap(find.text(extensions.toggleSelectWidgetMode.title)); expect( fakeExtensionManager.extensionValueOnDevice[ extensions.toggleSelectWidgetMode.extension], isFalse, ); // Verify the other service extension's state hasn't changed. expect( fakeExtensionManager .extensionValueOnDevice[extensions.debugPaint.extension], isFalse, ); await tester.tap(find.text(extensions.toggleSelectWidgetMode.title)); expect( fakeExtensionManager.extensionValueOnDevice[ extensions.toggleSelectWidgetMode.extension], isTrue, ); await tester.tap(find.text(extensions.debugPaint.title)); expect( fakeExtensionManager .extensionValueOnDevice[extensions.debugPaint.extension], isTrue, ); }, ); testWidgetsWithWindowSize( 'Test toggling service extension buttons with no extensions available', windowSize, (WidgetTester tester) async { mockNoExtensionsAvailable(); expect( fakeExtensionManager .extensionValueOnDevice[extensions.debugPaint.extension], isFalse, ); expect( fakeExtensionManager.extensionValueOnDevice[ extensions.toggleOnDeviceWidgetInspector.extension], isTrue, ); await tester.pumpWidget(buildInspectorScreen()); await tester.pump(); expect(find.byType(InspectorScreenBody), findsOneWidget); expect( find.text(extensions.toggleOnDeviceWidgetInspector.title), findsOneWidget, ); expect(find.text(extensions.debugPaint.title), findsOneWidget); await tester.pump(); await tester .tap(find.text(extensions.toggleOnDeviceWidgetInspector.title)); // Verify the service extension state has not changed. expect( fakeExtensionManager.extensionValueOnDevice[ extensions.toggleOnDeviceWidgetInspector.extension], isTrue, ); await tester .tap(find.text(extensions.toggleOnDeviceWidgetInspector.title)); // Verify the service extension state has not changed. expect( fakeExtensionManager.extensionValueOnDevice[ extensions.toggleOnDeviceWidgetInspector.extension], isTrue, ); // TODO(jacobr): also verify that the service extension buttons look // visually disabled. }, ); group('LayoutDetailsTab', () { final renderObjectJson = jsonDecode( ''' { "properties": [ { "description": "horizontal", "name": "direction" }, { "description": "start", "name": "mainAxisAlignment" }, { "description": "max", "name": "mainAxisSize" }, { "description": "center", "name": "crossAxisAlignment" }, { "description": "ltr", "name": "textDirection" }, { "description": "down", "name": "verticalDirection" } ] } ''', ); final diagnostic = RemoteDiagnosticsNode( <String, Object?>{ 'widgetRuntimeType': 'Row', 'renderObject': renderObjectJson, 'hasChildren': false, 'children': [], }, null, false, null, ); final treeNode = InspectorTreeNode()..diagnostic = diagnostic; testWidgetsWithWindowSize( 'should render StoryOfYourFlexWidget', windowSize, (WidgetTester tester) async { final controller = TestInspectorController()..setSelectedNode(treeNode); await tester.pumpWidget( MaterialApp( home: Scaffold( body: LayoutExplorerTab( controller: controller, ), ), ), ); expect(find.byType(FlexLayoutExplorerWidget), findsOneWidget); }, ); testWidgetsWithWindowSize( 'should listen to controller selection event', windowSize, (WidgetTester tester) async { final controller = TestInspectorController(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: LayoutExplorerTab( controller: controller, ), ), ), ); expect(find.byType(FlexLayoutExplorerWidget), findsNothing); controller.setSelectedNode(treeNode); await tester.pumpAndSettle(); expect(find.byType(FlexLayoutExplorerWidget), findsOneWidget); }, ); }); group( 'FlutterInspectorSettingsDialog', () { const startingHoverEvalModeValue = false; setUp(() { preferences.inspector.setHoverEvalMode(startingHoverEvalModeValue); }); testWidgetsWithWindowSize( 'can update hover inspection setting', windowSize, (WidgetTester tester) async { await tester.pumpWidget(buildInspectorScreen()); await tester.tap(find.byType(SettingsOutlinedButton)); await tester.pumpAndSettle(); expect( find.byType(FlutterInspectorSettingsDialog), findsOneWidget, ); final hoverCheckBoxSetting = find.ancestor( of: find.richTextContaining('Enable hover inspection'), matching: find.byType(CheckboxSetting), ); final hoverModeCheckBox = find.descendant( of: hoverCheckBoxSetting, matching: find.byType(NotifierCheckbox), ); await tester.tap(hoverModeCheckBox); await tester.pumpAndSettle(); expect( preferences.inspector.hoverEvalModeEnabled.value, !startingHoverEvalModeValue, ); }, ); }, ); // TODO(jacobr): add screenshot tests that connect to a test application // in the same way the inspector_controller test does today and take golden // images. Alternately: support an offline inspector mode and add tests of // that mode which would enable faster tests that run as unittests. }
devtools/packages/devtools_app/test/inspector/inspector_screen_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/inspector/inspector_screen_test.dart", "repo_id": "devtools", "token_count": 5021 }
121
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; /// Create an `InspectorTreeControllerFlutter` from a single `RemoteDiagnosticsNode` InspectorTreeController inspectorTreeControllerFromNode( RemoteDiagnosticsNode node, ) { final controller = InspectorTreeController() ..config = InspectorTreeConfig( onNodeAdded: (_, __) {}, onClientActiveChange: (_) {}, ); controller.root = InspectorTreeNode() ..appendChild( InspectorTreeNode()..diagnostic = node, ); return controller; } /// Replicates the functionality of `getRootWidgetSummaryTreeWithPreviews` from /// inspector_polyfill_script.dart Future<RemoteDiagnosticsNode> widgetToInspectorTreeDiagnosticsNode({ required Widget widget, required WidgetTester tester, }) async { await tester.pumpWidget(wrap(widget)); final element = find.byWidget(widget).evaluate().first; final nodeJson = element.toDiagnosticsNode(style: DiagnosticsTreeStyle.dense).toJsonMap( InspectorSerializationDelegate( service: WidgetInspectorService.instance, subtreeDepth: 1000000, summaryTree: true, addAdditionalPropertiesCallback: (node, delegate) { final additionalJson = <String, Object>{}; final value = node.value; if (value is Element) { final renderObject = value.renderObject; if (renderObject is RenderParagraph) { additionalJson['textPreview'] = renderObject.text.toPlainText(); } } return additionalJson; }, ), ); return RemoteDiagnosticsNode(nodeJson, null, false, null); }
devtools/packages/devtools_app/test/inspector/utils/inspector_tree.dart/0
{ "file_path": "devtools/packages/devtools_app/test/inspector/utils/inspector_tree.dart", "repo_id": "devtools", "token_count": 825 }
122
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/memory/framework/connected/memory_tabs.dart'; import 'package:devtools_app/src/screens/memory/panes/diff/diff_pane.dart'; import 'package:devtools_app/src/screens/memory/panes/diff/widgets/snapshot_list.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../../test_infra/matchers/matchers.dart'; import '../../../test_infra/scenes/memory/default.dart'; import '../../../test_infra/scenes/scene_test_extensions.dart'; void main() { group('Diff pane', () { late MemoryDefaultScene scene; Future<void> pumpScene(WidgetTester tester) async { await tester.pumpScene(scene); // Delay to ensure the memory profiler has collected data. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.byType(MemoryBody), findsOneWidget); await tester.tap( find.byKey(MemoryScreenKeys.diffTab), ); await tester.pumpAndSettle(); } // Set a wide enough screen width that we do not run into overflow. const windowSize = Size(2225.0, 1000.0); setUp(() async { scene = MemoryDefaultScene(); await scene.setUp(); }); tearDown(() { scene.tearDown(); }); testWidgetsWithWindowSize( 'records and deletes snapshots', windowSize, (WidgetTester tester) async { final snapshots = scene.controller.controllers.diff.core.snapshots; // Check the list contains only documentation item. expect(snapshots.value.length, equals(1)); await pumpScene(tester); // Check initial golden. await expectLater( find.byType(DiffPane), matchesDevToolsGolden( '../../../test_infra/goldens/memory_diff_empty1.png', ), ); // Record three snapshots. for (var i in Iterable<int>.generate(3)) { await tester.tap(find.byIcon(Icons.fiber_manual_record).first); await tester.pumpAndSettle(); expect(find.text('selected-isolate-${i + 1}'), findsOneWidget); } await expectLater( find.byType(DiffPane), matchesDevToolsGolden( '../../../test_infra/goldens/memory_diff_three_snapshots1.png', ), ); expect(snapshots.value.length, equals(1 + 3)); await expectLater( find.byType(DiffPane), matchesDevToolsGolden( '../../../test_infra/goldens/memory_diff_selected_class.png', ), ); // Delete a snapshot. await tester.tap( find.descendant( of: find.byType(SnapshotListTitle), matching: find.byType(ContextMenuButton), ), ); await tester.pumpAndSettle(); await tester.tap( find.descendant( of: find.byType(MenuItemButton), matching: find.text('Delete'), ), ); await tester.pumpAndSettle(); expect(snapshots.value.length, equals(1 + 3 - 1)); // Record snapshot await tester.tap(find.byIcon(Icons.fiber_manual_record)); await tester.pumpAndSettle(); await expectLater( find.byType(DiffPane), matchesDevToolsGolden( '../../../test_infra/goldens/memory_diff_three_snapshots2.png', ), ); expect(snapshots.value.length, equals(1 + 3 - 1 + 1)); // Clear all await tester.tap(find.byTooltip('Delete all snapshots')); await tester.pumpAndSettle(); await expectLater( find.byType(DiffPane), matchesDevToolsGolden( '../../../test_infra/goldens/memory_diff_empty2.png', ), ); expect(snapshots.value.length, equals(1)); }, ); }); }
devtools/packages/devtools_app/test/memory/diff/widgets/diff_pane_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/memory/diff/widgets/diff_pane_test.dart", "repo_id": "devtools", "token_count": 1784 }
123
// 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/devtools_app.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; void main() { late NetworkScreen screen; late FakeServiceConnectionManager fakeServiceConnection; group('NetworkScreen', () { setUp(() { fakeServiceConnection = FakeServiceConnectionManager(); when(fakeServiceConnection.serviceManager.connectedApp!.isDartWebAppNow) .thenReturn(false); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); when( fakeServiceConnection.errorBadgeManager.errorCountNotifier('network'), ).thenReturn(ValueNotifier<int>(0)); screen = NetworkScreen(); }); testWidgets('builds its tab', (WidgetTester tester) async { await tester.pumpWidget(wrap(Builder(builder: screen.buildTab))); expect(find.text('Network'), findsOneWidget); }); }); }
devtools/packages/devtools_app/test/network/network_screen_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/network/network_screen_test.dart", "repo_id": "devtools", "token_count": 448 }
124
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/performance/panes/raster_stats/raster_stats_model.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/test_data.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:vm_service/vm_service.dart'; void main() { group('$RasterStatsController', () { late RasterStatsController controller; late MockServiceConnectionManager mockServiceConnection; setUp(() { mockServiceConnection = createMockServiceConnectionWithDefaults(); when(mockServiceConnection.renderFrameWithRasterStats).thenAnswer( (_) => Future.value(Response.parse(rasterStatsFromServiceJson)), ); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(ServiceConnectionManager, mockServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal(NotificationService, NotificationService()); controller = RasterStatsController(createMockPerformanceControllerWithDefaults()); }); test('calling collectRasterStats sets data', () async { var rasterStats = controller.rasterStats.value; expect(rasterStats, isNull); await controller.collectRasterStats(); rasterStats = controller.rasterStats.value; expect(rasterStats, isNotNull); expect(rasterStats!.layerSnapshots.length, equals(2)); expect(rasterStats.selectedSnapshot, isNotNull); expect(rasterStats.originalFrameSize, isNotNull); expect(rasterStats.totalRasterTime, isNot(equals(Duration.zero))); }); test( 'calling collectRasterStats sets null data for bad service response', () async { var rasterStats = controller.rasterStats.value; expect(rasterStats, isNull); when(mockServiceConnection.renderFrameWithRasterStats) .thenAnswer((_) => throw Exception('something went wrong')); await controller.collectRasterStats(); rasterStats = controller.rasterStats.value; expect(rasterStats, isNull); }, ); test('calling clear nulls out raster stats', () async { await controller.collectRasterStats(); var rasterStats = controller.rasterStats.value; expect(rasterStats, isNotNull); expect(rasterStats!.layerSnapshots.length, equals(2)); expect(rasterStats.selectedSnapshot, isNotNull); expect(rasterStats.originalFrameSize, isNotNull); expect(rasterStats.totalRasterTime, isNot(equals(Duration.zero))); controller.clearData(); rasterStats = controller.rasterStats.value; expect(rasterStats, isNull); }); test('setOfflineData', () async { final rasterStats = RasterStats.parse(rasterStatsFromServiceJson); // Ensure we are starting in a null state. expect(controller.rasterStats.value, isNull); final offlineData = OfflinePerformanceData(rasterStats: rasterStats); await controller.setOfflineData(offlineData); expect(controller.rasterStats.value, isNotNull); expect(controller.rasterStats.value!.layerSnapshots.length, equals(2)); }); }); }
devtools/packages/devtools_app/test/performance/raster_stats/raster_stats_controller_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/performance/raster_stats/raster_stats_controller_test.dart", "repo_id": "devtools", "token_count": 1224 }
125
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.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'; // TODO(kenz): add tests for other widgets in common_widgets.dart void main() { const windowSize = Size(1000.0, 1000.0); setUp(() { setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); setGlobal(ServiceConnectionManager, FakeServiceConnectionManager()); setGlobal(IdeTheme, IdeTheme()); }); group('Common widgets', () { testWidgetsWithWindowSize( 'processingInfo builds for progressValue', windowSize, (WidgetTester tester) async { await tester.pumpWidget( wrap( const ProcessingInfo( progressValue: 0.0, processedObject: 'fake object', ), ), ); final progressIndicatorFinder = find.byType(LinearProgressIndicator); LinearProgressIndicator progressIndicator = tester.widget(progressIndicatorFinder); expect(progressIndicator.value, equals(0.0)); await tester.pumpWidget( wrap( const ProcessingInfo( progressValue: 0.5, processedObject: 'fake object', ), ), ); progressIndicator = tester.widget(progressIndicatorFinder); expect(progressIndicator.value, equals(0.5)); }, ); }); group('NotifierCheckbox', () { bool? findCheckboxValue() { final Checkbox checkboxWidget = find.byType(Checkbox).evaluate().first.widget as Checkbox; return checkboxWidget.value; } testWidgets('tap checkbox', (WidgetTester tester) async { final notifier = ValueNotifier<bool>(false); await tester.pumpWidget(wrap(NotifierCheckbox(notifier: notifier))); final checkbox = find.byType(Checkbox); expect(checkbox, findsOneWidget); expect(notifier.value, isFalse); expect(findCheckboxValue(), isFalse); await tester.tap(checkbox); await tester.pump(); expect(notifier.value, isTrue); expect(findCheckboxValue(), isTrue); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(notifier.value, isFalse); expect(findCheckboxValue(), isFalse); }); testWidgets('change notifier value', (WidgetTester tester) async { final notifier = ValueNotifier<bool>(false); await tester.pumpWidget(wrap(NotifierCheckbox(notifier: notifier))); expect(notifier.value, isFalse); expect(findCheckboxValue(), isFalse); notifier.value = true; await tester.pump(); expect(notifier.value, isTrue); expect(findCheckboxValue(), isTrue); notifier.value = false; await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(notifier.value, isFalse); expect(findCheckboxValue(), isFalse); }); testWidgets('change notifier', (WidgetTester tester) async { final falseNotifier = ValueNotifier<bool>(false); final trueNotifier = ValueNotifier<bool>(true); await tester.pumpWidget(wrap(NotifierCheckbox(notifier: falseNotifier))); expect(findCheckboxValue(), isFalse); await tester.pumpWidget(wrap(NotifierCheckbox(notifier: trueNotifier))); expect(findCheckboxValue(), isTrue); await tester.pumpWidget(wrap(NotifierCheckbox(notifier: falseNotifier))); expect(findCheckboxValue(), isFalse); await tester.pumpWidget(wrap(NotifierCheckbox(notifier: trueNotifier))); expect(findCheckboxValue(), isTrue); // ensure we can modify the value of the notifier and changes are // reflected even though this is different than the initial notifier. trueNotifier.value = false; await tester.pump(); expect(findCheckboxValue(), isFalse); trueNotifier.value = true; await tester.pump(); expect(findCheckboxValue(), isTrue); }); }); }
devtools/packages/devtools_app/test/shared/common_widgets_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/common_widgets_test.dart", "repo_id": "devtools", "token_count": 1696 }
126
// 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:ui'; import 'package:devtools_app/src/shared/primitives/geometry.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('LineSegment', () { test('zoomedXPosition', () { expect( LineSegment.zoomedXPosition(x: 10, zoom: 2.0, unzoomableOffset: 5), equals(15.0), ); expect( LineSegment.zoomedXPosition(x: 10, zoom: 2.0, unzoomableOffset: 10), equals(10.0), ); expect( () { LineSegment.zoomedXPosition(x: 10, zoom: 2.0, unzoomableOffset: 11); }, throwsA(const TypeMatcher<AssertionError>()), ); }); }); group('VerticalLineSegment', () { test('constructor enforces vertical', () { expect( () { VerticalLineSegment(const Offset(10, 20), const Offset(11, 40)); }, throwsA(const TypeMatcher<AssertionError>()), ); expect( () { VerticalLineSegment(const Offset(10, 20), const Offset(10, 40)); }, isNot(throwsA(const TypeMatcher<AssertionError>())), ); }); test('intersection', () { final line = VerticalLineSegment( const Offset(10, 10), const Offset(10, 20), ); var rect = const Rect.fromLTRB(0.0, 0.0, 5.0, 5.0); expect(line.crossAxisIntersects(rect), isFalse); expect(line.intersects(rect), isFalse); rect = const Rect.fromLTRB(5.0, 5.0, 15.0, 15.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isTrue); rect = const Rect.fromLTRB(5.0, 15.0, 15.0, 25.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isTrue); rect = const Rect.fromLTRB(5.0, 11.0, 15.0, 19.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isTrue); rect = const Rect.fromLTRB(5.0, 25.0, 15.0, 30.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isFalse); }); test('compareTo', () { final a = VerticalLineSegment( const Offset(0.0, 0.0), const Offset(0.0, 10.0), ); final b = VerticalLineSegment( const Offset(1.0, 0.0), const Offset(1.0, 10.0), ); final c = VerticalLineSegment( const Offset(2.0, 0.0), const Offset(2.0, 10.0), ); final d = VerticalLineSegment( const Offset(0.0, 11.0), const Offset(0.0, 20.0), ); expect(a.compareTo(b), equals(-1)); expect(a.compareTo(d), equals(-1)); expect(d.compareTo(b), equals(-1)); expect(c.compareTo(b), equals(1)); }); test('toZoomed', () { final line = VerticalLineSegment( const Offset(10, 10), const Offset(10, 20), ); var zoomedLine = line.toZoomed( zoom: 2.0, unzoomableOffsetLineStart: 5.0, unzoomableOffsetLineEnd: 5.0, ); expect(zoomedLine.x, equals(15.0)); zoomedLine = line.toZoomed( zoom: 2.0, unzoomableOffsetLineStart: 9.0, unzoomableOffsetLineEnd: 9.0, ); expect(zoomedLine.x, equals(11.0)); zoomedLine = line.toZoomed( zoom: 2.0, unzoomableOffsetLineStart: 10.0, unzoomableOffsetLineEnd: 10.0, ); expect(zoomedLine.x, equals(10.0)); }); }); group('HorizontalLineSegment', () { test('constructor enforces horizontal', () { expect( () { HorizontalLineSegment(const Offset(10, 20), const Offset(40, 21)); }, throwsA(const TypeMatcher<AssertionError>()), ); expect( () { HorizontalLineSegment(const Offset(10, 20), const Offset(40, 20)); }, isNot(throwsA(const TypeMatcher<AssertionError>())), ); }); test('intersection', () { final line = HorizontalLineSegment( const Offset(10, 10), const Offset(20, 10), ); var rect = const Rect.fromLTRB(0.0, 0.0, 5.0, 5.0); expect(line.crossAxisIntersects(rect), isFalse); expect(line.intersects(rect), isFalse); rect = const Rect.fromLTRB(5.0, 5.0, 15.0, 15.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isTrue); rect = const Rect.fromLTRB(15.0, 5.0, 25.0, 15.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isTrue); rect = const Rect.fromLTRB(11.0, 5.0, 19.0, 15.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isTrue); rect = const Rect.fromLTRB(25.0, 5.0, 30.0, 15.0); expect(line.crossAxisIntersects(rect), isTrue); expect(line.intersects(rect), isFalse); }); test('compareTo', () { final a = HorizontalLineSegment( const Offset(0.0, 0.0), const Offset(10.0, 0.0), ); final b = HorizontalLineSegment( const Offset(0.0, 1.0), const Offset(10.0, 1.0), ); final c = HorizontalLineSegment( const Offset(0.0, 2.0), const Offset(10.0, 2.0), ); final d = HorizontalLineSegment( const Offset(11.0, 0.0), const Offset(20.0, 0.0), ); expect(a.compareTo(b), equals(-1)); expect(a.compareTo(d), equals(-1)); expect(d.compareTo(b), equals(-1)); expect(c.compareTo(b), equals(1)); }); test('toZoomed', () { final line = HorizontalLineSegment( const Offset(10, 10), const Offset(20, 10), ); var zoomedLine = line.toZoomed( zoom: 2.0, unzoomableOffsetLineStart: 6.0, unzoomableOffsetLineEnd: 5.0, ); expect(zoomedLine.start.dx, equals(14.0)); expect(zoomedLine.end.dx, equals(35.0)); zoomedLine = line.toZoomed( zoom: 2.0, unzoomableOffsetLineStart: 9.0, unzoomableOffsetLineEnd: 9.0, ); expect(zoomedLine.start.dx, equals(11.0)); expect(zoomedLine.end.dx, equals(31.0)); zoomedLine = line.toZoomed( zoom: 2.0, unzoomableOffsetLineStart: 10.0, unzoomableOffsetLineEnd: 10.0, ); expect(zoomedLine.start.dx, equals(10.0)); expect(zoomedLine.end.dx, equals(30.0)); }); }); }
devtools/packages/devtools_app/test/shared/geometry_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/geometry_test.dart", "repo_id": "devtools", "token_count": 3158 }
127
// 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_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; void main() { group('$ReleaseNotesController', () { late ReleaseNotesController controller; setUp(() { setGlobal(IdeTheme, IdeTheme()); debugTestReleaseNotes = true; controller = ReleaseNotesController(); }); test('latestVersionToCheckForReleaseNotes', () { var version = controller.latestVersionToCheckForReleaseNotes( SemanticVersion.parse('2.24.5-dev.1'), ); expect(version.toString(), '2.23.10'); version = controller.latestVersionToCheckForReleaseNotes( SemanticVersion.parse('2.24.1'), ); expect(version.toString(), '2.24.1'); }); test('Fails gracefully when index is unavailable', () async { await http.runWithClient( () async { final response = await controller.retrieveReleasesFromIndex(); expect(response, isNull); }, () => MockClient((request) async { expect(request.method, equalsIgnoringCase('GET')); expect(request.url, equals(ReleaseNotesController.releaseIndexUrl)); // Respond with a valid release index to test the http error handling, // not the parsing of the returned body. return http.Response(_validReleaseTestIndex, 404); }), ); }); test('Fails gracefully when index is formatted incorrectly', () async { await http.runWithClient( () async { final response = await controller.retrieveReleasesFromIndex(); expect(response, isNull); }, () => MockClient((request) async { expect(request.method, equalsIgnoringCase('GET')); expect(request.url, equals(ReleaseNotesController.releaseIndexUrl)); return http.Response(_invalidReleaseTestIndex, 200); }), ); }); test('Parses expected index format correctly', () async { await http.runWithClient( () async { final response = await controller.retrieveReleasesFromIndex(); expect(response!.keys, hasLength(2)); expect(response['latest'], equals('2.32.0')); expect( response['releases'], equals({ '2.32.0': '/tools/devtools/release-notes/release-notes-2.32.0-src.md', '2.31.0': '/tools/devtools/release-notes/release-notes-2.31.0-src.md', }), ); }, () => MockClient((request) async { expect(request.method, equalsIgnoringCase('GET')); expect(request.url, equals(ReleaseNotesController.releaseIndexUrl)); return http.Response(_validReleaseTestIndex, 200); }), ); }); }); } /// An invalid release index due to the `releases` field being `release`. const _invalidReleaseTestIndex = ''' { "latest": "2.32.0", "release": { "2.32.0": "/tools/devtools/release-notes/release-notes-2.32.0-src.md", "2.31.0": "/tools/devtools/release-notes/release-notes-2.31.0-src.md" } } '''; /// A correctly formatted release index file. const _validReleaseTestIndex = ''' { "latest": "2.32.0", "releases": { "2.32.0": "/tools/devtools/release-notes/release-notes-2.32.0-src.md", "2.31.0": "/tools/devtools/release-notes/release-notes-2.31.0-src.md" } } ''';
devtools/packages/devtools_app/test/shared/release_notes_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/release_notes_test.dart", "repo_id": "devtools", "token_count": 1522 }
128
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/shared/table/column_widths.dart'; import 'package:devtools_app/src/shared/table/table.dart'; import 'package:devtools_app/src/shared/table/table_controller.dart'; import 'package:devtools_app/src/shared/table/table_data.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' hide TableRow, Table; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class _NonSortableFlatNameColumn extends ColumnData<TestData> { _NonSortableFlatNameColumn.wide(super.title) : super.wide(); @override String getValue(TestData dataObject) { return dataObject.name; } @override bool get supportsSorting => false; } class _NonSortableFlatNumColumn extends ColumnData<TestData> { _NonSortableFlatNumColumn.wide(super.title) : super.wide(); @override int getValue(TestData dataObject) { return dataObject.number; } @override bool get supportsSorting => false; @override bool get numeric => true; } const windowSize = Size(4000.0, 500.0); void main() { setUp(() { setGlobal(ServiceConnectionManager, FakeServiceConnectionManager()); setGlobal(IdeTheme, IdeTheme()); TableUiStateStore.clear(); }); group('FlatTable view', () { late List<TestData> flatData; late ColumnData<TestData> flatNameColumn; setUp(() { flatNameColumn = _FlatNameColumn(); flatData = [ TestData('Foo', 0), TestData('Bar', 1), TestData('Baz', 2), TestData('Qux', 3), TestData('Snap', 4), TestData('Crackle', 5), TestData('Pop', 5), TestData('Baz', 6), TestData('Qux', 7), ]; }); testWidgetsWithWindowSize( 'displays with simple content', windowSize, (WidgetTester tester) async { final table = FlatTable<TestData>( columns: [flatNameColumn], data: [TestData('empty', 0)], dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); expect(find.text('FlatName'), findsOneWidget); final FlatTableState state = tester.state(find.byWidget(table)); final columnWidths = state.tableController.computeColumnWidthsSizeToFit(1000); expect(columnWidths.length, 1); expect(columnWidths.first, 300); expect(find.byKey(const Key('empty')), findsOneWidget); }, ); testWidgetsWithWindowSize( 'displays with simple content size to content', windowSize, (WidgetTester tester) async { final table = FlatTable<TestData>( columns: [flatNameColumn], data: [TestData('empty', 0)], dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, sizeColumnsToFit: false, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); expect(find.text('FlatName'), findsOneWidget); final FlatTableState state = tester.state(find.byWidget(table)); expect(state.tableController.columnWidths, isNotNull); final columnWidths = state.tableController.columnWidths!; expect(columnWidths.length, 1); expect(columnWidths.first, 300); expect(find.byKey(const Key('empty')), findsOneWidget); }, ); testWidgetsWithWindowSize( 'displays with full content', windowSize, (WidgetTester tester) async { final table = FlatTable<TestData>( columns: [ flatNameColumn, _NumberColumn(), ], data: flatData, dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); // Column headers. expect(find.text('FlatName'), findsOneWidget); expect(find.text('Number'), findsOneWidget); // Table data. expect(find.byKey(const Key('Foo')), findsOneWidget); expect(find.byKey(const Key('Bar')), findsOneWidget); // Note that two keys with the same name are allowed but not necessarily a // good idea. We should be using unique identifiers for keys. expect(find.byKey(const Key('Baz')), findsNWidgets(2)); expect(find.byKey(const Key('Qux')), findsNWidgets(2)); expect(find.byKey(const Key('Snap')), findsOneWidget); expect(find.byKey(const Key('Crackle')), findsOneWidget); expect(find.byKey(const Key('Pop')), findsOneWidget); }, ); testWidgetsWithWindowSize( 'displays with column groups', windowSize, (WidgetTester tester) async { final table = FlatTable<TestData>( columns: [ flatNameColumn, _NumberColumn(), ], columnGroups: [ ColumnGroup.fromText( title: 'Group 1', range: const Range(0, 1), ), ColumnGroup.fromText( title: 'Group 2', range: const Range(1, 2), ), ], data: flatData, dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); // Column group headers. expect(find.text('Group 1'), findsOneWidget); expect(find.text('Group 2'), findsOneWidget); // Column headers. expect(find.text('FlatName'), findsOneWidget); expect(find.text('Number'), findsOneWidget); // Table data. expect(find.byKey(const Key('Foo')), findsOneWidget); expect(find.byKey(const Key('Bar')), findsOneWidget); // Note that two keys with the same name are allowed but not necessarily a // good idea. We should be using unique identifiers for keys. expect(find.byKey(const Key('Baz')), findsNWidgets(2)); expect(find.byKey(const Key('Qux')), findsNWidgets(2)); expect(find.byKey(const Key('Snap')), findsOneWidget); expect(find.byKey(const Key('Crackle')), findsOneWidget); expect(find.byKey(const Key('Pop')), findsOneWidget); }, ); testWidgets('starts with sorted data', (WidgetTester tester) async { expect(flatData[0].name, 'Foo'); expect(flatData[1].name, 'Bar'); expect(flatData[2].name, 'Baz'); expect(flatData[3].name, 'Qux'); expect(flatData[4].name, 'Snap'); expect(flatData[5].name, 'Crackle'); expect(flatData[6].name, 'Pop'); expect(flatData[7].name, 'Baz'); expect(flatData[8].name, 'Qux'); final table = FlatTable<TestData>( columns: [ flatNameColumn, _NumberColumn(), ], data: flatData, dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); final FlatTableState<TestData> state = tester.state(find.byWidget(table)); final data = state.tableController.tableData.value.data; expect(data[0].name, 'Bar'); expect(data[1].name, 'Baz'); expect(data[2].name, 'Baz'); expect(data[3].name, 'Crackle'); expect(data[4].name, 'Foo'); expect(data[5].name, 'Pop'); expect(data[6].name, 'Qux'); expect(data[7].name, 'Qux'); expect(data[8].name, 'Snap'); }); testWidgets('sorts data by column', (WidgetTester tester) async { final table = FlatTable<TestData>( columns: [ flatNameColumn, _NumberColumn(), ], data: flatData, dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); final FlatTableState<TestData> state = tester.state(find.byWidget(table)); { final data = state.tableController.tableData.value.data; expect(data[0].name, 'Bar'); expect(data[1].name, 'Baz'); expect(data[2].name, 'Baz'); expect(data[3].name, 'Crackle'); expect(data[4].name, 'Foo'); expect(data[5].name, 'Pop'); expect(data[6].name, 'Qux'); expect(data[7].name, 'Qux'); expect(data[8].name, 'Snap'); } // Reverse the sort direction. await tester.tap(find.text('FlatName')); await tester.pumpAndSettle(); { final data = state.tableController.tableData.value.data; expect(data[8].name, 'Bar'); expect(data[7].name, 'Baz'); expect(data[6].name, 'Baz'); expect(data[5].name, 'Crackle'); expect(data[4].name, 'Foo'); expect(data[3].name, 'Pop'); expect(data[2].name, 'Qux'); expect(data[1].name, 'Qux'); expect(data[0].name, 'Snap'); } // Change the sort column. await tester.tap(find.text('Number')); await tester.pumpAndSettle(); { final data = state.tableController.tableData.value.data; expect(data[0].name, 'Foo'); expect(data[1].name, 'Bar'); expect(data[2].name, 'Baz'); expect(data[3].name, 'Qux'); expect(data[4].name, 'Snap'); expect(data[5].name, 'Crackle'); expect(data[6].name, 'Pop'); expect(data[7].name, 'Baz'); expect(data[8].name, 'Qux'); } }); testWidgets( 'does not sort with supportsSorting == false', (WidgetTester tester) async { final nonSortableFlatNameColumn = _NonSortableFlatNameColumn.wide('FlatName'); final nonSortableFlatNumColumn = _NonSortableFlatNumColumn.wide('Number'); final table = FlatTable<TestData>( columns: [ nonSortableFlatNameColumn, nonSortableFlatNumColumn, ], data: flatData, dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: nonSortableFlatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); final FlatTableState<TestData> state = tester.state(find.byWidget(table)); { final data = state.tableController.tableData.value.data; expect(data[0].name, 'Bar'); expect(data[1].name, 'Baz'); expect(data[2].name, 'Baz'); expect(data[3].name, 'Crackle'); expect(data[4].name, 'Foo'); expect(data[5].name, 'Pop'); expect(data[6].name, 'Qux'); expect(data[7].name, 'Qux'); expect(data[8].name, 'Snap'); } // Attempt to reverse the sort direction. await tester.tap(find.text('FlatName')); await tester.pumpAndSettle(); { final data = state.tableController.tableData.value.data; expect(data[0].name, 'Bar'); expect(data[1].name, 'Baz'); expect(data[2].name, 'Baz'); expect(data[3].name, 'Crackle'); expect(data[4].name, 'Foo'); expect(data[5].name, 'Pop'); expect(data[6].name, 'Qux'); expect(data[7].name, 'Qux'); expect(data[8].name, 'Snap'); } // Attempt to change the sort column. await tester.tap(find.text('Number')); await tester.pumpAndSettle(); { final data = state.tableController.tableData.value.data; expect(data[0].name, 'Bar'); expect(data[1].name, 'Baz'); expect(data[2].name, 'Baz'); expect(data[3].name, 'Crackle'); expect(data[4].name, 'Foo'); expect(data[5].name, 'Pop'); expect(data[6].name, 'Qux'); expect(data[7].name, 'Qux'); expect(data[8].name, 'Snap'); } }, ); testWidgets( 'sorts data by column and secondary column', (WidgetTester tester) async { final numberColumn = _NumberColumn(); final table = FlatTable<TestData>( columns: [ flatNameColumn, numberColumn, ], data: [ TestData('Foo', 0), TestData('1 Bar', 1), TestData('# Baz', 2), TestData('Qux', 3), TestData('Snap', 4), TestData('Crackle', 4), TestData('Pop', 4), TestData('Bang', 4), TestData('Qux', 5), ], dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: numberColumn, defaultSortDirection: SortDirection.ascending, secondarySortColumn: flatNameColumn, ); await tester.pumpWidget(wrap(table)); final FlatTableState<TestData> state = tester.state(find.byWidget(table)); { final data = state.tableController.tableData.value.data; expect(data[0].name, 'Foo'); expect(data[1].name, '1 Bar'); expect(data[2].name, '# Baz'); expect(data[3].name, 'Qux'); expect(data[4].name, 'Bang'); expect(data[5].name, 'Crackle'); expect(data[6].name, 'Pop'); expect(data[7].name, 'Snap'); expect(data[8].name, 'Qux'); } // Reverse the sort direction. await tester.tap(find.text('Number')); await tester.pumpAndSettle(); { final data = state.tableController.tableData.value.data; expect(data[8].name, 'Foo'); expect(data[7].name, '1 Bar'); expect(data[6].name, '# Baz'); expect(data[5].name, 'Qux'); expect(data[4].name, 'Bang'); expect(data[3].name, 'Crackle'); expect(data[2].name, 'Pop'); expect(data[1].name, 'Snap'); expect(data[0].name, 'Qux'); } // Change the sort column. await tester.tap(find.text('FlatName')); await tester.pumpAndSettle(); { final data = state.tableController.tableData.value.data; expect(data[0].name, '# Baz'); expect(data[1].name, '1 Bar'); expect(data[2].name, 'Bang'); expect(data[3].name, 'Crackle'); expect(data[4].name, 'Foo'); expect(data[5].name, 'Pop'); expect(data[6].name, 'Qux'); expect(data[7].name, 'Qux'); expect(data[8].name, 'Snap'); } }, ); // TODO(jacobr): add a golden image tests for column width tests. testWidgets('displays with many columns', (WidgetTester tester) async { final table = FlatTable<TestData>( columns: [ _NumberColumn(), _CombinedColumn(), flatNameColumn, _CombinedColumn(), ], data: flatData, dataKey: 'test-data', keyFactory: (data) => Key(data.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget( wrap( SizedBox( width: 200.0, height: 200.0, child: table, ), ), ); expect(find.byWidget(table), findsOneWidget); }); group('column width calculation', () { Future<void> pumpTable( WidgetTester tester, List<ColumnData<TestData>> columns, { required bool sizeColumnsToFit, required ValueNotifier<Size> viewSize, }) async { await tester.pumpWidget( wrap( ValueListenableBuilder<Size>( valueListenable: viewSize, builder: (context, size, _) { return Center( child: SizedBox( width: size.width, height: size.height, child: FlatTable<TestData>( columns: columns, data: flatData, dataKey: 'test-data', keyFactory: (data) => Key(data.name), defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, sizeColumnsToFit: sizeColumnsToFit, ), ), ); }, ), ), ); } group('size to fit', () { testWidgetsWithWindowSize( 'single wide column', windowSize, (WidgetTester tester) async { final viewSize = ValueNotifier<Size>(windowSize); final columns = [ flatNameColumn, _NumberColumn(), _WideColumn(), ]; await pumpTable( tester, columns, sizeColumnsToFit: true, viewSize: viewSize, ); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 3); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 400.0); // Fixed width column. expect(columnWidths[2], 3252.0); // Variable width column. expect(adjustedColumnWidths.length, 3); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 400.0); expect(adjustedColumnWidths[2], 3252.0); } viewSize.value = const Size(800.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 3); expect(columnWidths[0], 300.0); expect(columnWidths[1], 400.0); expect(columnWidths[2], 52.0); expect(adjustedColumnWidths.length, 3); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 400.0); expect(adjustedColumnWidths[2], 52.0); } viewSize.value = const Size(200.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 3); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 400.0); // Fixed width column. expect(columnWidths[2], 0.0); // Variable width column. expect(adjustedColumnWidths.length, 3); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 400.0); expect(adjustedColumnWidths[2], 0.0); } }, ); testWidgetsWithWindowSize( 'multiple wide columns', windowSize, (WidgetTester tester) async { final viewSize = ValueNotifier<Size>(windowSize); final columns = [ flatNameColumn, _WideMinWidthColumn(), _NumberColumn(), _WideColumn(), ]; await pumpTable( tester, columns, sizeColumnsToFit: true, viewSize: viewSize, ); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 4); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 1620.0); // Min width wide column expect(columnWidths[2], 400.0); // Fixed width column. expect(columnWidths[3], 1620.0); // Variable width wide column. expect(adjustedColumnWidths.length, 4); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 1620.0); expect(adjustedColumnWidths[2], 400.0); expect(adjustedColumnWidths[3], 1620.0); } viewSize.value = const Size(1000.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 4); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 120.0); // Min width wide column expect(columnWidths[2], 400.0); // Fixed width column. expect(columnWidths[3], 120.0); // Variable width wide column. expect(adjustedColumnWidths.length, 4); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 120.0); expect(adjustedColumnWidths[2], 400.0); expect(adjustedColumnWidths[3], 120.0); } viewSize.value = const Size(200.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 4); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 100.0); // Min width wide column expect(columnWidths[2], 400.0); // Fixed width column. expect(columnWidths[3], 0.0); // Variable width wide column. expect(adjustedColumnWidths.length, 4); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 100.0); expect(adjustedColumnWidths[2], 400.0); expect(adjustedColumnWidths[3], 0.0); } }, ); testWidgetsWithWindowSize( 'multiple min width wide columns', windowSize, (WidgetTester tester) async { final viewSize = ValueNotifier<Size>(windowSize); final columns = [ flatNameColumn, _WideMinWidthColumn(), _VeryWideMinWidthColumn(), _NumberColumn(), _WideColumn(), ]; await pumpTable( tester, columns, sizeColumnsToFit: true, viewSize: viewSize, ); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 5); expect(columnWidths[0], 300.0); // Fixed width column expect(columnWidths[1], 1076.0); // Min width wide column // Very wide min width wide column expect(columnWidths[2], 1076.0); expect(columnWidths[3], 400.0); // Fixed width column. expect(columnWidths[4], 1076.0); // Variable width wide column. expect(adjustedColumnWidths.length, 5); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 1076.0); expect(adjustedColumnWidths[2], 1076.0); expect(adjustedColumnWidths[3], 400.0); expect(adjustedColumnWidths[4], 1076.0); } viewSize.value = const Size(1501.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 5); expect(columnWidths[0], 300.0); // Fixed width column expect(columnWidths[1], 243.0); // Min width wide column // Very wide min width wide column expect(columnWidths[2], 243.0); expect(columnWidths[3], 400.0); // Fixed width column. expect(columnWidths[4], 243.0); // Variable width wide column. expect(adjustedColumnWidths.length, 5); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 243.0); expect(adjustedColumnWidths[2], 243.0); expect(adjustedColumnWidths[3], 400.0); expect(adjustedColumnWidths[4], 243.0); } viewSize.value = const Size(1200.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 5); expect(columnWidths[0], 300.0); // Fixed width column expect(columnWidths[1], 134.0); // Min width wide column // Very wide min width wide column expect(columnWidths[2], 160.0); expect(columnWidths[3], 400.0); // Fixed width column. expect(columnWidths[4], 134.0); // Variable width wide column. expect(adjustedColumnWidths.length, 5); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 134.0); expect(adjustedColumnWidths[2], 160.0); expect(adjustedColumnWidths[3], 400.0); expect(adjustedColumnWidths[4], 134.0); } viewSize.value = const Size(1000.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 5); expect(columnWidths[0], 300.0); // Fixed width column expect(columnWidths[1], 100.0); // Min width wide column // Very wide min width wide column expect(columnWidths[2], 160.0); expect(columnWidths[3], 400.0); // Fixed width column. expect(columnWidths[4], 0.0); // Variable width wide column. expect(adjustedColumnWidths.length, 5); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 100.0); expect(adjustedColumnWidths[2], 160.0); expect(adjustedColumnWidths[3], 400.0); expect(adjustedColumnWidths[4], 0.0); } }, ); }); group('size to content', () { testWidgetsWithWindowSize( 'single wide column', windowSize, (WidgetTester tester) async { final viewSize = ValueNotifier<Size>(windowSize); final columns = [ flatNameColumn, _NumberColumn(), _WideColumn(), ]; await pumpTable( tester, columns, sizeColumnsToFit: false, viewSize: viewSize, ); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 3); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 400.0); // Fixed width column. expect(columnWidths[2], 1200.0); // Variable width column. expect(adjustedColumnWidths.length, 3); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 400.0); expect(adjustedColumnWidths[2], 3252.0); } viewSize.value = const Size(800.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 3); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 400.0); // Fixed width column. expect(columnWidths[2], 1200.0); // Variable width column. expect(adjustedColumnWidths.length, 3); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 400.0); expect(adjustedColumnWidths[2], 1200.0); } viewSize.value = const Size(200.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 3); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 400.0); // Fixed width column. expect(columnWidths[2], 1200.0); // Variable width column. expect(adjustedColumnWidths.length, 3); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 400.0); expect(adjustedColumnWidths[2], 1200.0); } }, ); testWidgetsWithWindowSize( 'multiple wide columns', windowSize, (WidgetTester tester) async { final viewSize = ValueNotifier<Size>(windowSize); final columns = [ flatNameColumn, _WideMinWidthColumn(), _NumberColumn(), _WideColumn(), ]; await pumpTable( tester, columns, sizeColumnsToFit: false, viewSize: viewSize, ); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 4); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 100.0); // Min width wide column expect(columnWidths[2], 400.0); // Fixed width column. expect(columnWidths[3], 1200.0); // Variable width wide column. expect(adjustedColumnWidths.length, 4); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 1620.0); expect(adjustedColumnWidths[2], 400.0); expect(adjustedColumnWidths[3], 1620.0); } viewSize.value = const Size(1000.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 4); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 100.0); // Min width wide column expect(columnWidths[2], 400.0); // Fixed width column. expect(columnWidths[3], 1200.0); // Variable width wide column. expect(adjustedColumnWidths.length, 4); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 100.0); expect(adjustedColumnWidths[2], 400.0); expect(adjustedColumnWidths[3], 1200.0); } viewSize.value = const Size(200.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 4); expect(columnWidths[0], 300.0); // Fixed width column. expect(columnWidths[1], 100.0); // Min width wide column expect(columnWidths[2], 400.0); // Fixed width column. expect(columnWidths[3], 1200.0); // Variable width wide column. expect(adjustedColumnWidths.length, 4); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 100.0); expect(adjustedColumnWidths[2], 400.0); expect(adjustedColumnWidths[3], 1200.0); } }, ); testWidgetsWithWindowSize( 'multiple min width wide columns', windowSize, (WidgetTester tester) async { final viewSize = ValueNotifier<Size>(windowSize); final columns = [ flatNameColumn, _WideMinWidthColumn(), _VeryWideMinWidthColumn(), _NumberColumn(), _WideColumn(), ]; await pumpTable( tester, columns, sizeColumnsToFit: false, viewSize: viewSize, ); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths.length, 5); expect(columnWidths[0], 300.0); // Fixed width column expect(columnWidths[1], 100.0); // Min width wide column expect(columnWidths[2], 160.0); // Very wide min width wide column expect(columnWidths[3], 400.0); // Fixed width column. expect(columnWidths[4], 1200.0); // Variable width wide column. expect(adjustedColumnWidths.length, 5); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 1014.0); expect(adjustedColumnWidths[2], 1014.0); expect(adjustedColumnWidths[3], 400.0); expect(adjustedColumnWidths[4], 1200.0); } viewSize.value = const Size(1200.0, 200.0); await tester.pumpAndSettle(); { final DevToolsTableState<TestData> tableState = tester.state(find.byType(DevToolsTable<TestData>)); final columnWidths = tableState.widget.columnWidths; final adjustedColumnWidths = tableState.adjustedColumnWidths; expect(columnWidths[0], 300.0); // Fixed width column expect(columnWidths[1], 100.0); // Min width wide column expect(columnWidths[2], 160.0); // Very wide min width wide column expect(columnWidths[3], 400.0); // Fixed width column. expect(columnWidths[4], 1200.0); // Variable width wide column. expect(adjustedColumnWidths.length, 5); expect(adjustedColumnWidths[0], 300.0); expect(adjustedColumnWidths[1], 100.0); expect(adjustedColumnWidths[2], 160.0); expect(adjustedColumnWidths[3], 400.0); expect(adjustedColumnWidths[4], 1200.0); } }, ); }); }); testWidgets('can select an item', (WidgetTester tester) async { TestData? selected; final testData = TestData('empty', 0); const key = Key('empty'); final table = FlatTable<TestData>( columns: [flatNameColumn], data: [testData], dataKey: 'test-data', keyFactory: (d) => Key(d.name), onItemSelected: (item) => selected = item, defaultSortColumn: flatNameColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); expect(find.byKey(key), findsOneWidget); expect(selected, isNull); await tester.tap(find.byKey(key)); expect(selected, testData); }); testWidgets('can pin items (original)', (WidgetTester tester) async { final column = _PinnableFlatNameColumn(); final testData = [ for (int i = 0; i < 10; ++i) PinnableTestData(name: i.toString(), enabled: i % 2 == 0), ]; final table = FlatTable<PinnableTestData>( columns: [column], data: testData, dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: column, defaultSortDirection: SortDirection.ascending, pinBehavior: FlatTablePinBehavior.pinOriginalToTop, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); final FlatTableState<PinnableTestData> state = tester.state( find.byWidget(table), ); var pinnedData = state.tableController.pinnedData; expect(pinnedData.length, testData.length / 2); for (int i = 0; i < pinnedData.length; ++i) { expect(pinnedData[i].name, (i * 2).toString()); expect(pinnedData[i].enabled, true); } var data = state.tableController.tableData.value.data; expect(data.length, testData.length / 2); for (int i = 0; i < data.length; ++i) { expect(data[i].name, ((i * 2) + 1).toString()); expect(data[i].enabled, false); } // Sorting should apply to both pinned and unpinned items. await tester.tap(find.text(column.title)); await tester.pumpAndSettle(); data = state.tableController.tableData.value.data; pinnedData = state.tableController.pinnedData; expect(pinnedData.length, testData.length / 2); for (int i = 0; i < pinnedData.length; ++i) { final index = data.length - i - 1; expect(pinnedData[i].name, (index * 2).toString()); expect(pinnedData[i].enabled, true); } expect(data.length, testData.length / 2); for (int i = 0; i < data.length; ++i) { final index = data.length - i - 1; expect( data[i].name, ((index * 2) + 1).toString(), ); expect(data[i].enabled, false); } }); testWidgets('can pin items (copy)', (WidgetTester tester) async { final column = _PinnableFlatNameColumn(); final testData = [ for (int i = 0; i < 10; ++i) PinnableTestData(name: i.toString(), enabled: i % 2 == 0), ]; final table = FlatTable<PinnableTestData>( columns: [column], data: testData, dataKey: 'test-data', keyFactory: (d) => Key(d.name), defaultSortColumn: column, defaultSortDirection: SortDirection.ascending, pinBehavior: FlatTablePinBehavior.pinCopyToTop, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); final FlatTableState<PinnableTestData> state = tester.state( find.byWidget(table), ); var data = state.tableController.tableData.value.data; var pinnedData = state.tableController.pinnedData; expect(pinnedData.length, testData.length / 2); for (int i = 0; i < pinnedData.length; ++i) { expect(pinnedData[i].name, (i * 2).toString()); expect(pinnedData[i].enabled, true); } expect(data.length, testData.length); for (int i = 0; i < data.length; ++i) { expect(data[i].name, i.toString()); expect(data[i].enabled, i % 2 == 0); } // Sorting should apply to both pinned and unpinned items. await tester.tap(find.text(column.title)); await tester.pumpAndSettle(); data = state.tableController.tableData.value.data; pinnedData = state.tableController.pinnedData; expect(pinnedData.length, testData.length / 2); for (int i = 0; i < pinnedData.length; ++i) { final index = pinnedData.length - i - 1; expect(pinnedData[i].name, (index * 2).toString()); expect(pinnedData[i].enabled, true); } expect(data.length, testData.length); for (int i = 0; i < data.length; ++i) { final index = data.length - i - 1; expect( data[i].name, index.toString(), ); expect(data[i].enabled, index % 2 == 0); } }); }); group('TreeTable view', () { late TestData tree1; late TestData tree2; late TreeColumnData<TestData> treeColumn; setUp(() { treeColumn = _NameColumn(); _NumberColumn(); tree1 = TestData('Foo', 0) ..children.addAll([ TestData('Bar', 1) ..children.addAll([ TestData('Baz', 2), TestData('Qux', 3), TestData('Snap', 4), TestData('Crackle', 5), TestData('Pop', 5), ]), TestData('Baz', 7), TestData('Qux', 6), ]) ..expandCascading(); tree2 = TestData('Foo_2', 0) ..children.add( TestData('Bar_2', 1) ..children.add( TestData('Snap_2', 2), ), ) ..expandCascading(); }); testWidgets('displays with simple content', (WidgetTester tester) async { final table = TreeTable<TestData>( columns: [treeColumn], dataRoots: [TestData('empty', 0)], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); expect(find.byKey(const Key('empty')), findsOneWidget); }); testWidgets( 'displays with multiple data roots', (WidgetTester tester) async { final table = TreeTable<TestData>( columns: [treeColumn], dataRoots: [tree1, tree2], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); expect(find.byKey(const Key('Foo')), findsOneWidget); expect(find.byKey(const Key('Bar')), findsOneWidget); expect(find.byKey(const Key('Snap')), findsOneWidget); expect(find.byKey(const Key('Foo_2')), findsOneWidget); expect(find.byKey(const Key('Bar_2')), findsOneWidget); expect(find.byKey(const Key('Snap_2')), findsOneWidget); expect(tree1.isExpanded, isTrue); expect(tree2.isExpanded, isTrue); await tester.tap(find.byKey(const Key('Foo'))); await tester.pumpAndSettle(); expect(tree1.isExpanded, isFalse); expect(tree2.isExpanded, isTrue); await tester.tap(find.byKey(const Key('Foo_2'))); expect(tree1.isExpanded, isFalse); expect(tree2.isExpanded, isFalse); await tester.tap(find.byKey(const Key('Foo'))); expect(tree1.isExpanded, isTrue); expect(tree2.isExpanded, isFalse); }, ); testWidgets( 'displays when widget changes dataRoots', (WidgetTester tester) async { final table = TreeTable<TestData>( columns: [treeColumn], dataRoots: [tree1, tree2], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); expect(find.byKey(const Key('Foo')), findsOneWidget); expect(find.byKey(const Key('Bar')), findsOneWidget); expect(find.byKey(const Key('Snap')), findsOneWidget); expect(find.byKey(const Key('Foo_2')), findsOneWidget); expect(find.byKey(const Key('Bar_2')), findsOneWidget); expect(find.byKey(const Key('Snap_2')), findsOneWidget); expect(tree1.isExpanded, isTrue); expect(tree2.isExpanded, isTrue); final newTable = TreeTable<TestData>( columns: [treeColumn], dataRoots: [TestData('root1', 0), TestData('root2', 1)], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.descending, ); await tester.pumpWidget(wrap(newTable)); expect(find.byKey(const Key('Foo')), findsNothing); expect(find.byKey(const Key('Bar')), findsNothing); expect(find.byKey(const Key('Snap')), findsNothing); expect(find.byKey(const Key('Foo_2')), findsNothing); expect(find.byKey(const Key('Bar_2')), findsNothing); expect(find.byKey(const Key('Snap_2')), findsNothing); expect(find.byKey(const Key('root1')), findsOneWidget); expect(find.byKey(const Key('root2')), findsOneWidget); }, ); testWidgetsWithWindowSize( 'displays with tree column first', const Size(800.0, 1200.0), (WidgetTester tester) async { final table = TreeTable<TestData>( columns: [ treeColumn, _NumberColumn(), ], dataRoots: [tree1], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.descending, ); await tester.pumpWidget(wrap(table)); expect(find.byWidget(table), findsOneWidget); expect(find.byKey(const Key('Foo')), findsOneWidget); expect(find.byKey(const Key('Bar')), findsOneWidget); // Note that two keys with the same name are allowed but not necessarily a // good idea. We should be using unique identifiers for keys. expect(find.byKey(const Key('Baz')), findsNWidgets(2)); expect(find.byKey(const Key('Qux')), findsNWidgets(2)); expect(find.byKey(const Key('Snap')), findsOneWidget); expect(find.byKey(const Key('Crackle')), findsOneWidget); expect(find.byKey(const Key('Pop')), findsOneWidget); }, ); testWidgets('displays with many columns', (WidgetTester tester) async { final table = TreeTable<TestData>( columns: [ _NumberColumn(), _CombinedColumn(), treeColumn, _CombinedColumn(), ], dataRoots: [tree1], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget( wrap( SizedBox( width: 200.0, height: 200.0, child: table, ), ), ); expect(find.byWidget(table), findsOneWidget); }); testWidgets( 'displays wide data with many columns', (WidgetTester tester) async { const strings = <String>[ 'All work', 'and no play', 'makes Ben', 'a dull boy', // String is maybe a little easier to read this way. // ignore: no_adjacent_strings_in_list 'The quick brown fox jumps over the lazy dog, although the fox ' "can't jump very high and the dog is very, very small, so it really" " isn't much of an achievement on the fox's part, so I'm not sure why " "we're even talking about it.", ]; final root = TestData('Root', 0); var current = root; for (int i = 0; i < 1000; ++i) { final next = TestData(strings[i % strings.length], i); current.addChild(next); current = next; } root.expandCascading(); final table = TreeTable<TestData>( columns: [ _NumberColumn(), _CombinedColumn(), treeColumn, _CombinedColumn(), ], dataRoots: [root], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget( wrap( SizedBox( width: 200.0, height: 200.0, child: table, ), ), ); expect(find.byWidget(table), findsOneWidget); // Regression test for https://github.com/flutter/devtools/issues/4786 expect( find.text( '\u2026', // Unicode '...' findRichText: true, skipOffstage: false, ), findsNothing, ); expect( find.text( 'Root', findRichText: true, skipOffstage: false, ), findsOneWidget, ); for (final str in strings) { expect( find.text( str, findRichText: true, skipOffstage: false, ), findsWidgets, ); } }, ); testWidgets( 'properly collapses and expands the tree', (WidgetTester tester) async { final table = TreeTable<TestData>( columns: [ _NumberColumn(), treeColumn, ], dataRoots: [tree1], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); await tester.pumpAndSettle(); expect(tree1.isExpanded, true); await tester.tap(find.byKey(const Key('Foo'))); await tester.pumpAndSettle(); expect(tree1.isExpanded, false); await tester.tap(find.byKey(const Key('Foo'))); await tester.pumpAndSettle(); expect(tree1.isExpanded, true); await tester.tap(find.byKey(const Key('Bar'))); await tester.pumpAndSettle(); expect(tree1.children[0].isExpanded, false); }, ); testWidgets('starts with sorted data', (WidgetTester tester) async { expect(tree1.children[0].name, 'Bar'); expect(tree1.children[0].children[0].name, 'Baz'); expect(tree1.children[0].children[1].name, 'Qux'); expect(tree1.children[0].children[2].name, 'Snap'); expect(tree1.children[0].children[3].name, 'Crackle'); expect(tree1.children[0].children[4].name, 'Pop'); expect(tree1.children[1].name, 'Baz'); expect(tree1.children[2].name, 'Qux'); final table = TreeTable<TestData>( columns: [ _NumberColumn(), treeColumn, ], dataRoots: [tree1], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); final TreeTableState<TestData> state = tester.state(find.byWidget(table)); final tree = state.tableController.dataRoots[0]; expect(tree.children[0].name, 'Bar'); expect(tree.children[0].children[0].name, 'Baz'); expect(tree.children[0].children[1].name, 'Crackle'); expect(tree.children[0].children[2].name, 'Pop'); expect(tree.children[0].children[3].name, 'Qux'); expect(tree.children[0].children[4].name, 'Snap'); expect(tree.children[1].name, 'Baz'); expect(tree.children[2].name, 'Qux'); }); testWidgetsWithWindowSize( 'sorts data by column', windowSize, (WidgetTester tester) async { final table = TreeTable<TestData>( columns: [ _NumberColumn(), treeColumn, ], dataRoots: [tree1], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); await tester.pumpWidget(wrap(table)); final TreeTableState<TestData> state = tester.state(find.byWidget(table)); expect(state.tableController.columnWidths![0], 400); expect(state.tableController.columnWidths![1], 1242.0); final tree = state.tableController.dataRoots[0]; expect(tree.children[0].name, 'Bar'); expect(tree.children[0].children[0].name, 'Baz'); expect(tree.children[0].children[1].name, 'Crackle'); expect(tree.children[0].children[2].name, 'Pop'); expect(tree.children[0].children[4].name, 'Snap'); expect(tree.children[1].name, 'Baz'); expect(tree.children[2].name, 'Qux'); // Reverse the sort direction. await tester.tap(find.text('Name')); await tester.pumpAndSettle(); expect(tree.children[2].name, 'Bar'); expect(tree.children[2].children[4].name, 'Baz'); expect(tree.children[2].children[3].name, 'Crackle'); expect(tree.children[2].children[2].name, 'Pop'); expect(tree.children[2].children[1].name, 'Qux'); expect(tree.children[2].children[0].name, 'Snap'); expect(tree.children[1].name, 'Baz'); expect(tree.children[0].name, 'Qux'); // Change the sort column. await tester.tap(find.text('Number')); await tester.pumpAndSettle(); expect(tree.children[0].name, 'Bar'); expect(tree.children[0].children[0].name, 'Baz'); expect(tree.children[0].children[1].name, 'Qux'); expect(tree.children[0].children[2].name, 'Snap'); expect(tree.children[0].children[3].name, 'Pop'); expect(tree.children[0].children[4].name, 'Crackle'); expect(tree.children[1].name, 'Qux'); expect(tree.children[2].name, 'Baz'); }, ); group('keyboard navigation', () { late TestData data; late TreeTable<TestData> table; setUp(() { data = TestData('Foo', 0); data.addAllChildren([ TestData('Bar', 1), TestData('Crackle', 5), ]); table = TreeTable<TestData>( columns: [ _NumberColumn(), treeColumn, ], dataRoots: [data], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); }); testWidgets( 'selection changes with up/down arrow keys', (WidgetTester tester) async { data.expand(); await tester.pumpWidget(wrap(table)); await tester.pumpAndSettle(); final TreeTableState state = tester.state(find.byWidget(table)); state.focusNode!.requestFocus(); await tester.pumpAndSettle(); expect(state.widget.selectionNotifier.value.node, null); // the root is selected by default when there is no selection. Pressing // arrowDown should take us to the first child, Bar await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pumpAndSettle(); expect( state.widget.selectionNotifier.value.node, data.children[0], ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); expect(state.widget.selectionNotifier.value.node, data.root); }, ); testWidgets( 'selection changes with left/right arrow keys', (WidgetTester tester) async { await tester.pumpWidget(wrap(table)); await tester.pumpAndSettle(); final TreeTableState state = tester.state(find.byWidget(table)); state.focusNode!.requestFocus(); await tester.pumpAndSettle(); // left arrow on collapsed node with no parent should succeed but have // no effect. await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); expect(state.widget.selectionNotifier.value.node, data.root); expect( state.widget.selectionNotifier.value.node!.isExpanded, isFalse, ); // Expand root and navigate down twice await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); expect( state.widget.selectionNotifier.value.node, data.root.children[1], ); // Back to parent await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); expect(state.widget.selectionNotifier.value.node, data.root); expect(state.widget.selectionNotifier.value.node!.isExpanded, isTrue); }, ); }); testWidgets( 'properly colors rows with alternating colors', (WidgetTester tester) async { final data = TestData('Foo', 0) ..children.addAll([ TestData('Bar', 1) ..children.addAll([ TestData('Baz', 2), TestData('Qux', 3), TestData('Snap', 4), ]), TestData('Crackle', 5), ]) ..expandCascading(); final table = TreeTable<TestData>( columns: [ _NumberColumn(), treeColumn, ], dataRoots: [data], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); final fooFinder = find.byKey(const Key('Foo')); final barFinder = find.byKey(const Key('Bar')); final bazFinder = find.byKey(const Key('Baz')); final quxFinder = find.byKey(const Key('Qux')); final snapFinder = find.byKey(const Key('Snap')); final crackleFinder = find.byKey(const Key('Crackle')); // Expected values returned through accessing Color.value property. const color1Value = 4294111476; const color2Value = 4294967295; const rowSelectedColorValue = 4294967295; await tester.pumpWidget(wrap(table)); await tester.pumpAndSettle(); expect(tree1.isExpanded, true); expect(fooFinder, findsOneWidget); expect(barFinder, findsOneWidget); expect(bazFinder, findsOneWidget); expect(quxFinder, findsOneWidget); expect(snapFinder, findsOneWidget); expect(crackleFinder, findsOneWidget); TableRow fooRow = tester.widget(fooFinder); TableRow barRow = tester.widget(barFinder); final TableRow bazRow = tester.widget(bazFinder); final TableRow quxRow = tester.widget(quxFinder); final TableRow snapRow = tester.widget(snapFinder); TableRow crackleRow = tester.widget(crackleFinder); expect(fooRow.backgroundColor!.value, color1Value); expect(barRow.backgroundColor!.value, color2Value); expect(bazRow.backgroundColor!.value, color1Value); expect(quxRow.backgroundColor!.value, color2Value); expect(snapRow.backgroundColor!.value, color1Value); expect(crackleRow.backgroundColor!.value, color2Value); await tester.tap(barFinder); await tester.pumpAndSettle(); expect(fooFinder, findsOneWidget); expect(barFinder, findsOneWidget); expect(bazFinder, findsNothing); expect(quxFinder, findsNothing); expect(snapFinder, findsNothing); expect(crackleFinder, findsOneWidget); fooRow = tester.widget(fooFinder); barRow = tester.widget(barFinder); crackleRow = tester.widget(crackleFinder); expect(fooRow.backgroundColor!.value, color1Value); // [barRow] has the rowSelected color after being tapped. expect(barRow.backgroundColor!.value, rowSelectedColorValue); // [crackleRow] has a different background color after collapsing previous // row (Bar). expect(crackleRow.backgroundColor!.value, color1Value); }, ); test('fails when TreeColumn is not in column list', () { expect( () { TreeTable<TestData>( columns: const [], dataRoots: [tree1], dataKey: 'test-data', treeColumn: treeColumn, keyFactory: (d) => Key(d.name), defaultSortColumn: treeColumn, defaultSortDirection: SortDirection.ascending, ); }, throwsAssertionError, ); }); }); } class TestData extends TreeNode<TestData> { TestData(this.name, this.number); final String name; final int number; @override String toString() => '$name - $number'; @override TestData shallowCopy() { throw UnimplementedError( 'This method is not implemented. Implement if you ' 'need to call `shallowCopy` on an instance of this class.', ); } } class PinnableTestData implements PinnableListEntry { PinnableTestData({ required this.name, required this.enabled, }); final String name; final bool enabled; @override bool get pinToTop => enabled; @override String toString() => name; } class _NameColumn extends TreeColumnData<TestData> { _NameColumn() : super('Name'); @override String getValue(TestData dataObject) => dataObject.name; @override bool get supportsSorting => true; } class _NumberColumn extends ColumnData<TestData> { _NumberColumn() : super( 'Number', fixedWidthPx: 400.0, ); @override int getValue(TestData dataObject) => dataObject.number; @override bool get supportsSorting => true; } class _FlatNameColumn extends ColumnData<TestData> { _FlatNameColumn() : super( 'FlatName', fixedWidthPx: 300.0, ); @override String getValue(TestData dataObject) => dataObject.name; @override bool get supportsSorting => true; } class _PinnableFlatNameColumn extends ColumnData<PinnableTestData> { _PinnableFlatNameColumn() : super( 'FlatName', fixedWidthPx: 300.0, ); @override String getValue(PinnableTestData dataObject) => dataObject.name; @override bool get supportsSorting => true; } class _CombinedColumn extends ColumnData<TestData> { _CombinedColumn() : super( 'Name & Number', fixedWidthPx: 400.0, ); @override String getValue(TestData dataObject) => '${dataObject.name} ${dataObject.number}'; } class _WideColumn extends ColumnData<TestData> { _WideColumn() : super.wide('Wide Column'); @override String getValue(TestData dataObject) => '${dataObject.name} ${dataObject.number} bla bla bla bla bla bla bla bla'; } class _WideMinWidthColumn extends ColumnData<TestData> { _WideMinWidthColumn() : super.wide( 'Wide MinWidth Column', minWidthPx: scaleByFontFactor(100.0), ); @override String getValue(TestData dataObject) => '${dataObject.name} ${dataObject.number} with min width'; } class _VeryWideMinWidthColumn extends ColumnData<TestData> { _VeryWideMinWidthColumn() : super.wide( 'Very Wide MinWidth Column', minWidthPx: scaleByFontFactor(160.0), ); @override String getValue(TestData dataObject) => '${dataObject.name} ${dataObject.number} with min width'; }
devtools/packages/devtools_app/test/shared/table_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/table_test.dart", "repo_id": "devtools", "token_count": 31212 }
129
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'dart:async'; void main() { print('starting debugging app (exception)'); void run() { Timer(const Duration(milliseconds: 200), () { performAction(); run(); }); } run(); } void performAction() { int foo = 1; print(foo++); try { throw StateError('bad state'); // exception } catch (e) { // ignore } }
devtools/packages/devtools_app/test/test_infra/fixtures/debugging_app_exception.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/fixtures/debugging_app_exception.dart", "repo_id": "devtools", "token_count": 193 }
130
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. void values() { final i = 1; final j = 2; print('the value of \$i is $i'); print('the value after \$i is ${i + 1}'); print('the value of \$i + \$j is ${i + j}'); } void functions() { print('${() { return 'Hello'; }}'); print('print(${() { return 'Hello'; }()})'); print('${() => 'Hello'}'); print('print(${(() => 'Hello')()})'); }
devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/string_interpolation.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/string_interpolation.dart", "repo_id": "devtools", "token_count": 193 }
131
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_field_display.dart'; import 'package:devtools_app/src/screens/vm_developer/vm_developer_common_widgets.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:vm_service/vm_service.dart'; import '../vm_developer_test_utils.dart'; void main() { late MockFieldObject mockFieldObject; const windowSize = Size(4000.0, 4000.0); late Field testFieldCopy; late InstanceRef fieldStaticValue; setUp(() { setUpMockScriptManager(); setGlobal(ServiceConnectionManager, FakeServiceConnectionManager()); setGlobal(BreakpointManager, BreakpointManager()); setGlobal(IdeTheme, IdeTheme()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); setGlobal(NotificationService, NotificationService()); mockFieldObject = MockFieldObject(); final fieldJson = testField.toJson(); testFieldCopy = Field.parse(fieldJson)!; final instanceJson = testInstance.toJson(); fieldStaticValue = Instance.parse(instanceJson)!; fieldStaticValue.name = 'FooNumberType'; fieldStaticValue.valueAsString = '100'; testFieldCopy.size = 256; testFieldCopy.staticValue = fieldStaticValue; mockVmObject(mockFieldObject); when(mockFieldObject.obj).thenReturn(testFieldCopy); when(mockFieldObject.scriptRef).thenReturn(testScript); }); group('field data display tests', () { testWidgetsWithWindowSize( 'basic layout', windowSize, (WidgetTester tester) async { await tester.pumpWidget( wrap( VmFieldDisplay( field: mockFieldObject, controller: ObjectInspectorViewController(), ), ), ); expect(find.byType(VmObjectDisplayBasicLayout), findsOneWidget); expect(find.byType(VMInfoCard), findsOneWidget); expect(find.text('General Information'), findsOneWidget); expect(find.text('Field'), findsOneWidget); expect(find.text('256 B'), findsOneWidget); expect(find.text('Owner:'), findsOneWidget); expect(find.text('fooLib', findRichText: true), findsOneWidget); expect( find.text('fooScript.dart:10:4', findRichText: true), findsOneWidget, ); expect(find.text('Observed types not found'), findsOneWidget); expect(find.text('Static Value:'), findsOneWidget); expect(find.text('100', findRichText: true), findsOneWidget); expect(find.byType(RequestableSizeWidget), findsNWidgets(2)); expect(find.byType(RetainingPathWidget), findsOneWidget); expect(find.byType(InboundReferencesTree), findsOneWidget); }, ); testWidgetsWithWindowSize( 'observed type single - nullable', windowSize, (WidgetTester tester) async { when(mockFieldObject.guardClass).thenReturn(testClass); when(mockFieldObject.guardNullable).thenReturn(true); when(mockFieldObject.guardClassKind).thenReturn(GuardClassKind.single); await tester.pumpWidget( wrap( VmFieldDisplay( field: mockFieldObject, controller: ObjectInspectorViewController(), ), ), ); expect(find.text('FooClass - null observed'), findsOneWidget); }, ); testWidgetsWithWindowSize( 'observed type dynamic - non-nullable', windowSize, (WidgetTester tester) async { when(mockFieldObject.guardClass).thenReturn(null); when(mockFieldObject.guardNullable).thenReturn(false); when(mockFieldObject.guardClassKind).thenReturn(GuardClassKind.dynamic); await tester.pumpWidget( wrap( VmFieldDisplay( field: mockFieldObject, controller: ObjectInspectorViewController(), ), ), ); expect(find.text('various - null not observed'), findsOneWidget); }, ); testWidgetsWithWindowSize( 'observed type unknown - null unknown', windowSize, (WidgetTester tester) async { when(mockFieldObject.guardClass).thenReturn(null); when(mockFieldObject.guardNullable).thenReturn(null); when(mockFieldObject.guardClassKind).thenReturn(GuardClassKind.unknown); await tester.pumpWidget( wrap( VmFieldDisplay( field: mockFieldObject, controller: ObjectInspectorViewController(), ), ), ); expect( find.text('none'), findsOneWidget, ); }, ); testWidgetsWithWindowSize( 'static value is not InstanceRef', windowSize, (WidgetTester tester) async { testFieldCopy.staticValue = testClass; await tester.pumpWidget( wrap( VmFieldDisplay( field: mockFieldObject, controller: ObjectInspectorViewController(), ), ), ); expect(find.text('Static Value:'), findsNothing); }, ); }); }
devtools/packages/devtools_app/test/vm_developer/object_inspector/vm_field_display_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/vm_developer/object_inspector/vm_field_display_test.dart", "repo_id": "devtools", "token_count": 2312 }
132
## 0.1.0 * Remove deprecated `background` and `onBackground` values for `lightColorScheme` and `darkColorScheme`. * Rename `Split` to `SplitPane`. * Add `ServiceManager.serviceUri` field to store the connected VM service URI. ## 0.0.10 * Add `DTDManager` class and export from `service.dart`. * Add `showDevToolsDialog` helper method. * Add `FlexSplitColumn` and `BlankHeader` common widgets. * Bump `package:vm_service` dependency to ^14.0.0. ## 0.0.9 * Bump `package:web` to `^0.4.1`. * Densify overall UI. * Add public members: `PaddedDivider.noPadding`, `singleLineDialogTextFieldDecoration`, `extraLargeSpacing`, `regularTextStyleWithColor`. * Remove public members: `areaPaneHeaderHeight`, `defaultSwitchHeight`,` `dialogTextFieldDecoration` * Automatically show tooltips for `DevToolsButton` whose labels have been hidden due to hitting a narrow screen threshold, specified by `minScreenWidthForTextBeforeScaling`. * Add an optional parameter `borderColor` to `DevToolsToggleButtonGroup`. * Add a strict type on `DialogApplyButton.onPressed` and `ToggleableServiceExtension`. * Change default styling of `regularTextStyle` to inherit from `TextTheme.bodySmall`. * Change default styling of `TextTheme.bodySmall`, `TextTheme.bodyMedium`, `TextTheme.titleSmall` in the base theme. ## 0.0.8 * Add `ServiceManager.resolvedUriManager` for looking up package and file uris from a VM service connection. * Migrate from `dart:html` to `package:web`. ## 0.0.7 * Bump minimum Dart SDK version to `3.3.0-91.0.dev` and minimum Flutter SDK version to `3.17.0-0.0.pre`. * Bump `package:vm_service` dependency to ^13.0.0. * Bump the `package:devtools_shared` dependency to ^6.0.1. * Remove public getter `libraryRef`, and public methods `getLibrary` and `retrieveFullValueAsString` from `EvalOnDartLibrary`. * Change `toString` output for `UnknownEvalException`, `EvalSentinelException`, and `EvalErrorException`. * Remove public getters `flutterVersionSummary`, `frameworkVersionSummary`, and `engineVersionSummary` from `FlutterVersion`. * Remove public getters `onIsolateCreated` and `onIsolateExited` from `IsolateManager`. * Remove public getter `firstFrameReceived` from `ServiceExtensionManager`. * Add `RoundedButtonGroup` common widget. ## 0.0.6 * Add `profilePlatformChannels` to known service extensions. * Fix a bug where service extension states were not getting cleared on app disconnect. * Add optional parameter `id` to `DisposerMixin.addAutoDisposeListener` and `AutoDisposeMixin.addAutoDisposeListener` that allows for tagging a listener with a specific id. * Add optional parameter `excludeIds` to `DisposerMixin.cancelListeners` and `AutoDisposeMixin.cancelListeners` that allows for excluding listeners with a specific id from the cancel operation. ## 0.0.5 * Fix bug where registered services were not getting cleared on app disconnect. * Fix a bug with the logic to wait for a service extension's availability. * Fixed an exception on hot restart. ## 0.0.4 * Add `useDarkThemeAsDefault` constant for defining the default theme behavior. ## 0.0.3 * Bump `package:vm_service` dependency to ^11.10.0 ## 0.0.2 * Remove public `hasService` getter from `ServiceManager`. * Add optional `timeout` parameter to the `whenValueNonNull` utility. * Rename `includeText` utility to `isScreenWiderThan`. * Move `ideTheme` getter from `devtools_app_shared/utils.dart` to `devtools_app_shared/ui.dart`. ## 0.0.1 * Add README.md with usage examples. * Seal all possible classes for safeguarding against breaking changes. * Trim shared theme features down to only what is needed. ## 0.0.1-dev.0 * Initial commit. This package is under construction.
devtools/packages/devtools_app_shared/CHANGELOG.md/0
{ "file_path": "devtools/packages/devtools_app_shared/CHANGELOG.md", "repo_id": "devtools", "token_count": 1086 }
133
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:core'; import 'package:flutter/foundation.dart'; import 'package:meta/meta.dart'; import 'package:vm_service/vm_service.dart' hide Error; // TODO(https://github.com/flutter/devtools/issues/6239): try to remove this. @sealed class IsolateState { IsolateState(this.isolateRef); final IsolateRef isolateRef; /// Returns null if only this instance of [IsolateState] is disposed. Future<Isolate?> get isolate => _isolateLoadCompleter.future; Completer<Isolate?> _isolateLoadCompleter = Completer(); Future<void> waitForIsolateLoad() async => _isolateLoadCompleter; Isolate? get isolateNow => _isolateNow; Isolate? _isolateNow; RootInfo? rootInfo; ValueListenable<bool> get isPaused => _isPaused; final _isPaused = ValueNotifier<bool>(false); void handleIsolateLoad(Isolate isolate) { _isolateNow = isolate; _isPaused.value = isolate.pauseEvent != null && isolate.pauseEvent!.kind != EventKind.kResume; rootInfo = RootInfo(_isolateNow!.rootLib?.uri); _isolateLoadCompleter.complete(isolate); } void dispose() { _isolateNow = null; if (!_isolateLoadCompleter.isCompleted) { _isolateLoadCompleter.complete(null); } else { _isolateLoadCompleter = Completer()..complete(null); } } void handleDebugEvent(String? kind) { switch (kind) { case EventKind.kResume: _isPaused.value = false; break; case EventKind.kPauseStart: case EventKind.kPauseExit: case EventKind.kPauseBreakpoint: case EventKind.kPauseInterrupted: case EventKind.kPauseException: case EventKind.kPausePostRequest: _isPaused.value = true; break; } } } class RootInfo { RootInfo(this.library) : package = _libraryToPackage(library); final String? library; final String? package; static String? _libraryToPackage(String? library) { if (library == null) return null; final slashIndex = library.indexOf('/'); if (slashIndex == -1) return library; return library.substring(0, slashIndex); } }
devtools/packages/devtools_app_shared/lib/src/service/isolate_state.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/service/isolate_state.dart", "repo_id": "devtools", "token_count": 811 }
134
// 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. final Map<Type, Object> globals = <Type, Object>{}; void setGlobal(Type clazz, Object instance) { globals[clazz] = instance; } void removeGlobal(Type clazz) { globals.remove(clazz); assert(globals[clazz] == null); }
devtools/packages/devtools_app_shared/lib/src/utils/globals.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/utils/globals.dart", "repo_id": "devtools", "token_count": 125 }
135
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { setUpAll(() { setGlobal(IdeTheme, IdeTheme()); }); group('Theme', () { ThemeData theme; test('can be used without override', () { theme = themeFor( isDarkTheme: true, ideTheme: IdeTheme(), theme: ThemeData( useMaterial3: true, colorScheme: darkColorScheme, ), ); expect(theme.brightness, equals(Brightness.dark)); expect( theme.scaffoldBackgroundColor, equals(darkColorScheme.surface), ); theme = themeFor( isDarkTheme: false, ideTheme: IdeTheme(), theme: ThemeData( useMaterial3: true, colorScheme: lightColorScheme, ), ); expect(theme.brightness, equals(Brightness.light)); expect( theme.scaffoldBackgroundColor, equals(lightColorScheme.surface), ); }); test('can be inferred from override background color', () { theme = themeFor( isDarkTheme: false, // Will be overridden by white BG ideTheme: IdeTheme(backgroundColor: Colors.white70), theme: ThemeData( useMaterial3: true, colorScheme: lightColorScheme, ), ); expect(theme.brightness, equals(Brightness.light)); expect(theme.scaffoldBackgroundColor, equals(Colors.white70)); theme = themeFor( isDarkTheme: true, // Will be overridden by black BG ideTheme: IdeTheme(backgroundColor: Colors.black), theme: ThemeData( useMaterial3: true, colorScheme: darkColorScheme, ), ); expect(theme.brightness, equals(Brightness.dark)); expect(theme.scaffoldBackgroundColor, equals(Colors.black)); }); test('will not be inferred for colors that are not dark/light enough', () { theme = themeFor( isDarkTheme: false, // Will not be overridden - not dark enough ideTheme: IdeTheme(backgroundColor: Colors.orange), theme: ThemeData( useMaterial3: true, colorScheme: lightColorScheme, ), ); expect(theme.brightness, equals(Brightness.light)); expect( theme.scaffoldBackgroundColor, equals(lightColorScheme.surface), ); theme = themeFor( isDarkTheme: true, // Will not be overridden - not light enough ideTheme: IdeTheme(backgroundColor: Colors.orange), theme: ThemeData( useMaterial3: true, colorScheme: darkColorScheme, ), ); expect(theme.brightness, equals(Brightness.dark)); expect( theme.scaffoldBackgroundColor, equals(darkColorScheme.surface), ); }); }); }
devtools/packages/devtools_app_shared/test/ui/theme_test.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/test/ui/theme_test.dart", "repo_id": "devtools", "token_count": 1267 }
136
# DevTools extension examples This directory contains end-to-end examples of DevTools extensions. Each end-to-end example is made up of three components: 1. **Parent package**: Dart package that provides the extension 2. **DevTools extension**: the tool itself 3. **End-user application**: the app that the extension is used on ## Parent package This is the Dart package that provides a DevTools extension for end-user applications to use in DevTools. There are multiple extension-providing pacakges in the `example` directory. - `package:foo` from `packages_with_extensions/foo/packages/foo`: a package for Flutter apps - `package:dart_foo` from `packages_with_extensions/dart_foo/packages/dart_foo`: a pure Dart package for Dart or Flutter apps <!-- TODO(kenz): build this example. --> <!-- - `package:standalone_tool` from `packages_with_extensions/dart_foo/packages/stanalone_tool`, which is a package that is strictly meant to provide a tool as a DevTools extension. This is different from the other packages in that it is not an extension shipped with an existing Dart package. It is a package published solely to provide a DevTools extension. --> <!-- TODO(kenz): build this example, or pull in Khan's extension. --> <!-- - `package:gemini_ai_tool` from `packages_with_extensions/dart_foo/packages/gemini_ai_tool`, which is a standalone tool (like `package:standalone_tool`) that provides an example of using the Gemini SDK to build an AI powered tool as a DevTools extension. --> ## DevTools extension These are Flutter web apps that will be embedded in DevTools when connected to an app that depends on the [parent package](#parent-package). - `packages_with_extensions/foo/packages/foo_devtools_extension`: this is the Flutter web app whose built assets are included in `package:foo`'s `extension/devtools/build` directory. - `packages_with_extensions/dart_foo/packages/dart_foo_devtools_extension`: this is the Flutter web app whose built assets are included in `package:dart_foo`'s `extension/devtools/build` directory. ## End-user application These are the applications that depend on the [parent package](#parent-package) and can connect to the [DevTools extension](#devtools-extension) provided by the parent package. ### `app_that_uses_foo` This Flutter app depends on `package:foo` and `package:dart_foo`. When debugging `app_that_uses_foo`, or one if its `bin/` or `test/` libraries, the provided DevTools extensions will load in their own tab in DevTools. - `flutter run` the `app_that_uses_foo` app and open DevTools to see both the `package:foo` and `package:dart_foo` extensions in DevTools connected to a Flutter app. - Run `dart run --observe bin/script.dart` and open DevTools to see the `package_dart_foo` extension in DevTools connected to a Dart CLI app. <!-- TODO(kenz): uncomment once https://github.com/flutter/devtools/issues/7183 is resolved. --> <!-- - Run `dart test test/nested/simple_test.dart --pause-after-load` and open DevTools to see the `package:dart_foo` extension connected to a Dart test. - Run `flutter test test/app_that_uses_foo_test.dart --start-paused` and open DevTools to see both the `package:foo` and `package:dart_foo` extensions connected to a Flutter test. --> ## Learn how to structure your Dart package The examples will show you how to structure your package for optimal extension development and publishing. 1. If you are adding a DevTools extension to an existing Dart package, this is the recommended structure: ``` foo/ # formerly the repository root of your pub package packages/ foo/ # your pub package extension/ devtools/ build/ ... # pre-compiled build output of foo_devtools_extension config.yaml foo_devtools_extension/ # source code for your extension ``` `package:foo` and `package:dart_foo` provide an example of this structure. 2. If you are creating a DevTools extension as a standalone package, this is the recommended structure: ``` standalone_tool/ # your new pub package extension/ devtools/ build/ ... # pre-compiled build output of standalone_tool config.yaml lib/ # source code for your extension ``` <!-- TODO(kenz): uncomment once these examples are provided. --> <!-- `package:standalone_tool` and `package:gemini_ai_tool` provide an example of this structure. --> The pre-compiled build output included in the example packages' `extension/devtools/build` directories were included using the `build_and_copy` command provided by `package:devtools_extensions`. - For example, `package:foo`'s `extension/devtools/build` directory was populated by running the following command from the `foo_devtools_extension/` directory: ```sh flutter pub get && dart run devtools_extensions build_and_copy \ --source=. \ --dest=../foo/extension/devtools ``` ## Learn how to configure your extension's `config.yaml` file In these examples, you will also learn how to properly configure your extension's `config.yaml` file. DevTools reads this file in order to embed your extension in its own tab. This file must be configured as shown. ```yaml name: foo issueTracker: <link_to_your_issue_tracker.com> version: 0.0.1 materialIconCodePoint: '0xe0b1' ``` For the most up-to-date documentation on the `config.yaml` spec, see [extension_config_spec.md](https://github.com/flutter/devtools/blob/master/packages/devtools_extensions/extension_config_spec.md) ## Learn how to use shared packages from DevTools To learn how to use the shared packages from Devtools (`package:devtools_extensions` and `package:devtools_app_shared`), see the source for the `package:foo` extension. `packages_with_extensions/foo/packages/foo_devtools_extension` provides in-depth examples of how to do things like interact with the connected app's VM service, read / write to the user's project files over the Dart Tooling Daemon, interact with the DevTools extension framework APIs, etc.
devtools/packages/devtools_extensions/example/README.md/0
{ "file_path": "devtools/packages/devtools_extensions/example/README.md", "repo_id": "devtools", "token_count": 1904 }
137
// 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 'package:dart_foo/dart_foo.dart'; import 'package:test/test.dart'; // This test can be run to verify that the `package:foo` DevTools extension // loads properly when debugging a Dart test target with DevTools. // // This doubles as a test to make sure the DevTools extension loads properly // when the test target is in a subdirectory of 'test/'. // // To test this, run the following command and copy the VM service URI to // connect to DevTools: // // dart run test/dart_test/example_dart_test.dart --start-paused void main() { test('a simple dart test', () { final dartFoo = DartFoo(); dartFoo.foo(); expect(1 + 1, 2); expect(1 + 2, 3); }); }
devtools/packages/devtools_extensions/example/app_that_uses_foo/test/nested/simple_test.dart/0
{ "file_path": "devtools/packages/devtools_extensions/example/app_that_uses_foo/test/nested/simple_test.dart", "repo_id": "devtools", "token_count": 262 }
138
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "dart_foo_devtools_extension + simulated environment", "request": "launch", "type": "dart", "args": [ "--dart-define=use_simulated_environment=true" ], }, { "name": "dart_foo_devtools_extension + simulated environment (profile mode)", "request": "launch", "type": "dart", "flutterMode": "profile", "args": [ "--dart-define=use_simulated_environment=true" ], }, { "name": "dart_foo_devtools_extension + simulated environment (release mode)", "request": "launch", "type": "dart", "flutterMode": "release", "args": [ "--dart-define=use_simulated_environment=true" ], } ] }
devtools/packages/devtools_extensions/example/packages_with_extensions/dart_foo/packages/dart_foo_devtools_extension/.vscode/launch.json/0
{ "file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/dart_foo/packages/dart_foo_devtools_extension/.vscode/launch.json", "repo_id": "devtools", "token_count": 571 }
139
// 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_extensions/devtools_extensions.dart'; import 'package:flutter/material.dart'; /// This widget shows an example of how you can call public APIs exposed by /// [ExtensionManager]. /// /// * [extensionManager.postMessageToDevTools] - how to post an arbitrary /// message to DevTools, though the use for this is limited to what DevTools /// is setup to handle. /// * [extensionManager.showNotification] - how to show a notification in /// DevTools. /// * [extensionManager.showBannerMessage] - how to show a banner message /// warning in DevTools . class CallingDevToolsExtensionsAPIsExample extends StatelessWidget { const CallingDevToolsExtensionsAPIsExample({super.key}); @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '4. Example of calling DevTools extension APIs', style: Theme.of(context).textTheme.titleMedium, ), const PaddedDivider.thin(), ElevatedButton( onPressed: () => extensionManager.postMessageToDevTools( DevToolsExtensionEvent( DevToolsExtensionEventType.unknown, data: {'foo': 'bar'}, ), ), child: const Text('Send a message to DevTools'), ), const SizedBox(height: 16.0), ElevatedButton( onPressed: () => extensionManager.showNotification('Yay, DevTools Extensions!'), child: const Text('Show DevTools notification'), ), const SizedBox(height: 16.0), ElevatedButton( onPressed: () => extensionManager.showBannerMessage( key: 'example_message_single_dismiss', type: 'warning', message: 'Warning: with great power, comes great ' 'responsibility. I\'m not going to tell you twice.\n' '(This message can only be shown once)', extensionName: 'foo', ), child: const Text( 'Show DevTools warning (ignore if already dismissed)', ), ), const SizedBox(height: 16.0), ElevatedButton( onPressed: () => extensionManager.showBannerMessage( key: 'example_message_multi_dismiss', type: 'warning', message: 'Warning: with great power, comes great ' 'responsibility. I\'ll keep reminding you if you ' 'forget.\n(This message can be shown multiple times)', extensionName: 'foo', ignoreIfAlreadyDismissed: false, ), child: const Text( 'Show DevTools warning (can show again after dismiss)', ), ), ], ); } }
devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo_devtools_extension/lib/src/devtools_extension_api_example.dart/0
{ "file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo_devtools_extension/lib/src/devtools_extension_api_example.dart", "repo_id": "devtools", "token_count": 1260 }
140
// 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. @TestOn('browser') import 'package:devtools_extensions/devtools_extensions.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('Global managers', () { test('accessing early throws error', () { expect(() => serviceManager, throwsStateError); expect(() => extensionManager, throwsStateError); expect(() => dtdManager, throwsStateError); }); testWidgets( 'building $DevToolsExtension initializes globals', (tester) async { await tester.pumpWidget(const DevToolsExtension(child: SizedBox())); expect(serviceManager, isNotNull); expect(extensionManager, isNotNull); expect(dtdManager, isNotNull); }, ); }); }
devtools/packages/devtools_extensions/test/web/devtools_extension_test.dart/0
{ "file_path": "devtools/packages/devtools_extensions/test/web/devtools_extension_test.dart", "repo_id": "devtools", "token_count": 326 }
141
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; class DeeplinkManager { /// A regex to retrieve the json part from the stdout of Android analyzer. /// /// Example stdout: /// /// Running Gradle task 'printBuildVariants'... 10.4s /// ["debug","release","profile"] static final _androidBuildVariantJsonRegex = RegExp(r'(\[.*\])'); /// A regex to retrieve the json part of the stdout of iOS analyzer. /// /// Example stdout: /// /// {"configurations":["Debug","Release","Profile"],"targets":["Runner","RunnerTests"]} static final _iosBuildOptionsJsonRegex = RegExp(r'({.*})'); /// The key to retrieve error message from the returning map of this class's /// APIs. static const kErrorField = 'error'; /// The key to retrieve output json from the returning map of this class's /// APIs. static const kOutputJsonField = 'json'; /// A regex to retrieve the file path from the stdout of iOS or Android /// analyzers. /// /// Example stdout: /// /// result saved in /path/to/json/file.json static final _outputFilePathRegex = RegExp(r'result saved in (.*.json)'); @visibleForTesting Future<ProcessResult> runProcess( String executable, { required List<String> arguments, }) { return Process.run( executable, arguments, ); } @visibleForTesting String getFlutterBinary() { // FLUTTER_ROOT can be set by Dart-Code VSCode extension or dart shell // script shipped with flutter sdk. var flutterRoot = Platform.environment['FLUTTER_ROOT']; if (flutterRoot == null) { // Attempt to find flutter root from dart binary path. final dartPathSegments = path.split(Platform.resolvedExecutable); final flutterFolderSegmentIndex = dartPathSegments.lastIndexOf('flutter'); if (flutterFolderSegmentIndex != -1 && dartPathSegments[flutterFolderSegmentIndex + 1] == 'bin') { flutterRoot = path.joinAll( dartPathSegments.sublist(0, flutterFolderSegmentIndex + 1), ); } } if (flutterRoot == null) { // Fallback to use flutter from PATH. return Platform.isWindows ? 'flutter.bat' : 'flutter'; } return path.join( flutterRoot, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter', ); } Future<String> _runFlutterCommand( List<String> arguments, { required RegExp outputMatcher, }) async { final flutterPath = getFlutterBinary(); final result = await runProcess(flutterPath, arguments: arguments); if (result.exitCode != 0) { throw _FlutterProcessError( 'Flutter command exit with non-zero error code ${result.exitCode}\n${result.stderr}', ); } final match = outputMatcher.firstMatch(result.stdout); if (match == null) { throw _FlutterProcessError("Can't parse output: ${result.stdout}"); } else { return match.group(1)!; //await File(match.group(1)!).readAsString(); } } Map<String, Object?> _handleRunFlutterError( covariant _FlutterProcessError error, ) { return <String, String?>{ kErrorField: error.message, }; } Future<Map<String, Object?>> _handleReadJsonFile(String filePath) { return File(filePath) .readAsString() .then<Map<String, Object?>>(_handleJsonOutput); } Future<Map<String, Object?>> _handleJsonOutput(String jsonOutput) async { try { jsonEncode(jsonOutput); } on Error catch (e) { return <String, String?>{ kErrorField: e.toString(), }; } return <String, String?>{ kOutputJsonField: jsonOutput, }; } Future<Map<String, Object?>> getAndroidBuildVariants({ required String rootPath, }) { return _runFlutterCommand( <String>['analyze', '--android', '--list-build-variants', rootPath], outputMatcher: _androidBuildVariantJsonRegex, ).then<Map<String, Object?>>( _handleJsonOutput, onError: _handleRunFlutterError, ); } Future<Map<String, Object?>> getAndroidAppLinkSettings({ required String rootPath, required String buildVariant, }) { return _runFlutterCommand( <String>[ 'analyze', '--android', '--output-app-link-settings', '--build-variant=$buildVariant', rootPath, ], outputMatcher: _outputFilePathRegex, ).then<Map<String, Object?>>( _handleReadJsonFile, onError: _handleRunFlutterError, ); } Future<Map<String, Object?>> getIosBuildOptions({ required String rootPath, }) { return _runFlutterCommand( <String>['analyze', '--ios', '--list-build-options', rootPath], outputMatcher: _iosBuildOptionsJsonRegex, ).then<Map<String, Object?>>( _handleJsonOutput, onError: _handleRunFlutterError, ); } Future<Map<String, Object?>> getIosUniversalLinkSettings({ required String rootPath, required String configuration, required String target, }) { return _runFlutterCommand( <String>[ 'analyze', '--ios', '--output-universal-link-settings', '--configuration=$configuration', '--target=$target', rootPath, ], outputMatcher: _outputFilePathRegex, ).then<Map<String, Object?>>( _handleReadJsonFile, onError: _handleRunFlutterError, ); } } class _FlutterProcessError extends Error { _FlutterProcessError(this.message); /// The error message. final String message; @override String toString() => 'Error: $message'; }
devtools/packages/devtools_shared/lib/src/deeplink/deeplink_manager.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/deeplink/deeplink_manager.dart", "repo_id": "devtools", "token_count": 2175 }
142
// 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. // ignore_for_file: avoid_classes_with_only_static_members part of '../server_api.dart'; abstract class _ExtensionsApiHandler { static Future<shelf.Response> handleServeAvailableExtensions( ServerApi api, Map<String, String> queryParams, ExtensionsManager extensionsManager, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( [ExtensionsApi.extensionRootPathPropertyName], queryParams: queryParams, api: api, requestName: ExtensionsApi.apiServeAvailableExtensions, ); if (missingRequiredParams != null) return missingRequiredParams; final logs = <String>[]; final rootPath = queryParams[ExtensionsApi.extensionRootPathPropertyName]; final result = <String, Object?>{}; try { await extensionsManager.serveAvailableExtensions(rootPath, logs); } on ExtensionParsingException catch (e) { // For [ExtensionParsingException]s, we should return a success response // with a warning message. result[ExtensionsApi.extensionsResultWarningPropertyName] = e.message; } catch (e) { // For all other exceptions, return an error response. return api.serverError('$e', logs); } final extensions = extensionsManager.devtoolsExtensions.map((p) => p.toJson()).toList(); result[ExtensionsApi.extensionsResultPropertyName] = extensions; return ServerApi._encodeResponse( ServerApi._wrapWithLogs(result, logs), api: api, ); } static shelf.Response handleExtensionEnabledState( ServerApi api, Map<String, String> queryParams, ) { final missingRequiredParams = ServerApi._checkRequiredParameters( [ ExtensionsApi.extensionRootPathPropertyName, ExtensionsApi.extensionNamePropertyName, ], queryParams: queryParams, api: api, requestName: ExtensionsApi.apiExtensionEnabledState, ); if (missingRequiredParams != null) return missingRequiredParams; final rootPath = queryParams[ExtensionsApi.extensionRootPathPropertyName]!; final rootUri = Uri.parse(rootPath); final extensionName = queryParams[ExtensionsApi.extensionNamePropertyName]!; final activate = queryParams[ExtensionsApi.enabledStatePropertyName]; if (activate != null) { final newState = ServerApi._devToolsOptions.setExtensionEnabledState( rootUri: rootUri, extensionName: extensionName, enable: bool.parse(activate), ); return ServerApi._encodeResponse(newState.name, api: api); } final activationState = ServerApi._devToolsOptions.lookupExtensionEnabledState( rootUri: rootUri, extensionName: extensionName, ); return ServerApi._encodeResponse(activationState.name, api: api); } }
devtools/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart", "repo_id": "devtools", "token_count": 1025 }
143
// 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. /// Attempts to detect the package root of [fileUriString]. /// /// This method uses the heuristics that a Dart executable within a Dart package /// should reside in one of the following top-level folders: 'lib', 'bin', /// 'integration_test', 'test', or 'benchmark'. String packageRootFromFileUriString(String fileUriString) { // TODO(kenz): for robustness, consider sending the root library uri to the // server and having the server look for the package folder that contains the // `.dart_tool` directory. final directoryRegExp = RegExp(r'\/(lib|bin|integration_test|test|benchmark)\/.+\.dart'); final directoryIndex = fileUriString.indexOf(directoryRegExp); if (directoryIndex != -1) { fileUriString = fileUriString.substring(0, directoryIndex); } return fileUriString; }
devtools/packages/devtools_shared/lib/src/utils/file_utils.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/utils/file_utils.dart", "repo_id": "devtools", "token_count": 285 }
144
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: invalid_use_of_visible_for_testing_member, devtools_test is only used in test code. import 'dart:async'; import 'package:devtools_app_shared/service_extensions.dart'; // ignore: implementation_imports, intentional import from src/ import 'package:devtools_app_shared/src/service/service_extension_manager.dart'; import 'package:flutter/foundation.dart'; import 'package:mockito/mockito.dart'; // ignore: subtype_of_sealed_class, fake for testing. /// Fake that simplifies writing UI tests that depend on the /// ServiceExtensionManager. // TODO(jacobr): refactor ServiceExtensionManager so this fake can reuse more // code from ServiceExtensionManager instead of reimplementing it. base class FakeServiceExtensionManager extends Fake with TestServiceExtensionManager { bool _firstFrameEventReceived = false; final _serviceExtensionStateController = <String, ValueNotifier<ServiceExtensionState>>{}; final _serviceExtensionAvailable = <String, ValueNotifier<bool>>{}; /// All available service extensions. final _serviceExtensions = <String>{}; /// All service extensions that are currently enabled. final _enabledServiceExtensions = <String, ServiceExtensionState>{}; /// Temporarily stores service extensions that we need to add. We should not /// add extensions until the first frame event has been received /// [_firstFrameEventReceived]. final _pendingServiceExtensions = <String>{}; /// Hook to simulate receiving the first frame event. /// /// Service extensions are only reported once a frame has been received. Future<void> fakeFrame() async { await _onFrameEventReceived(); } Map<String, dynamic> extensionValueOnDevice = {}; @override ValueListenable<bool> hasServiceExtension(String name) { return _hasServiceExtension(name); } ValueNotifier<bool> _hasServiceExtension(String name) { return _serviceExtensionAvailable.putIfAbsent( name, () => ValueNotifier(_hasServiceExtensionNow(name)), ); } bool _hasServiceExtensionNow(String name) { return _serviceExtensions.contains(name); } @override Future<bool> waitForServiceExtensionAvailable(String name) { return Future.value(true); } /// Hook for tests to call to simulate adding a service extension. Future<void> fakeAddServiceExtension(String name) async { if (_firstFrameEventReceived) { assert(_pendingServiceExtensions.isEmpty); await _addServiceExtension(name); } else { _pendingServiceExtensions.add(name); } } /// Hook for tests to call to fake changing the state of a service /// extension. void fakeServiceExtensionStateChanged( final String name, String valueFromJson, ) async { final extension = serviceExtensionsAllowlist[name]; if (extension != null) { final Object? value = _getExtensionValueFromJson(name, valueFromJson); final enabled = extension is ToggleableServiceExtension ? value == extension.enabledValue // For extensions that have more than two states // (enabled / disabled), we will always consider them to be // enabled with the current value. : true; await setServiceExtensionState( name, enabled: enabled, value: value, callExtension: false, ); } } Object? _getExtensionValueFromJson(String name, String valueFromJson) { return switch (serviceExtensionsAllowlist[name]!.values.first) { bool() => valueFromJson == 'true' ? true : false, num() => num.parse(valueFromJson), _ => valueFromJson, }; } Future<void> _onFrameEventReceived() async { if (_firstFrameEventReceived) { // The first frame event was already received. return; } _firstFrameEventReceived = true; for (String extension in _pendingServiceExtensions) { await _addServiceExtension(extension); } _pendingServiceExtensions.clear(); } Future<void> _addServiceExtension(String name) { _hasServiceExtension(name).value = true; _serviceExtensions.add(name); if (_enabledServiceExtensions.containsKey(name)) { // Restore any previously enabled states by calling their service // extension. This will restore extension states on the device after a hot // restart. [_enabledServiceExtensions] will be empty on page refresh or // initial start. return callServiceExtension(name, _enabledServiceExtensions[name]!.value); } else { // Set any extensions that are already enabled on the device. This will // enable extension states in DevTools on page refresh or initial start. return _restoreExtensionFromDevice(name); } } @override ValueListenable<ServiceExtensionState> getServiceExtensionState(String name) { return _serviceExtensionState(name); } ValueNotifier<ServiceExtensionState> _serviceExtensionState(String name) { return _serviceExtensionStateController.putIfAbsent( name, () { return ValueNotifier<ServiceExtensionState>( _enabledServiceExtensions.containsKey(name) ? _enabledServiceExtensions[name]! : ServiceExtensionState(enabled: false, value: null), ); }, ); } Future<void> _restoreExtensionFromDevice(String name) async { if (!serviceExtensionsAllowlist.containsKey(name)) { return; } final extensionDescription = serviceExtensionsAllowlist[name]; final value = extensionValueOnDevice[name]; if (extensionDescription is ToggleableServiceExtension) { await setServiceExtensionState( name, enabled: value == extensionDescription.enabledValue, value: value, callExtension: false, ); } else { await setServiceExtensionState( name, enabled: true, value: value, callExtension: false, ); } } Future<void> callServiceExtension(String name, Object? value) { extensionValueOnDevice[name] = value; return Future.value(); } @override void vmServiceClosed() { _firstFrameEventReceived = false; _pendingServiceExtensions.clear(); _serviceExtensions.clear(); for (var listenable in _serviceExtensionAvailable.values) { listenable.value = false; } } /// Sets the state for a service extension and makes the call to the VMService. @override Future<void> setServiceExtensionState( String name, { required bool enabled, required Object? value, bool callExtension = true, }) async { if (callExtension && _serviceExtensions.contains(name)) { await callServiceExtension(name, value); } _serviceExtensionState(name).value = ServiceExtensionState( enabled: enabled, value: value, ); // Add or remove service extension from [enabledServiceExtensions]. if (enabled) { _enabledServiceExtensions[name] = ServiceExtensionState( enabled: enabled, value: value, ); } else { _enabledServiceExtensions.remove(name); } } @override bool isServiceExtensionAvailable(String name) { return _serviceExtensions.contains(name) || _pendingServiceExtensions.contains(name); } }
devtools/packages/devtools_test/lib/src/mocks/fake_service_extension_manager.dart/0
{ "file_path": "devtools/packages/devtools_test/lib/src/mocks/fake_service_extension_manager.dart", "repo_id": "devtools", "token_count": 2478 }
145
## 1.0.0 * Migrate to null safety. ## 0.0.2 * Implemented `decodeAnsiColorEscapeCodes` in dart - now no longer using JS interop
devtools/third_party/packages/ansi_up/CHANGELOG.md/0
{ "file_path": "devtools/third_party/packages/ansi_up/CHANGELOG.md", "repo_id": "devtools", "token_count": 49 }
146
#!/bin/bash # TODO(kenz): delete this script once we can confirm it is not used in the # Dart SDK or in infra tooling. # 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. # Contains a path to this script, relative to the directory it was called from. RELATIVE_PATH_TO_SCRIPT="${BASH_SOURCE[0]}" # The directory that this script is located in. TOOL_DIR=`dirname "${RELATIVE_PATH_TO_SCRIPT}"` # The devtools root directory is assumed to be the parent of this directory. DEVTOOLS_DIR="${TOOL_DIR}/.." pushd $TOOL_DIR if [[ $1 = "--no-update-flutter" ]] then # Use the Flutter SDK that is already on the user's PATH. FLUTTER_EXE=`which flutter` echo "Using the Flutter SDK that is already on PATH: $FLUTTER_EXE" else # Use the Flutter SDK from flutter-sdk/. FLUTTER_DIR="`pwd`/flutter-sdk" PATH="$FLUTTER_DIR/bin":$PATH # Make sure the flutter sdk is on the correct branch. devtools_tool update-flutter-sdk fi popd # echo on set -ex echo "Flutter Path: $(which flutter)" echo "Flutter Version: $(flutter --version)" if [[ $1 = "--update-perfetto" ]]; then devtools_tool update-perfetto fi pushd $DEVTOOLS_DIR/packages/devtools_shared flutter pub get popd pushd $DEVTOOLS_DIR/packages/devtools_extensions flutter pub get popd pushd $DEVTOOLS_DIR/packages/devtools_app flutter clean rm -rf build/web flutter pub get flutter build web \ --web-renderer canvaskit \ --pwa-strategy=offline-first \ --dart2js-optimization=O1 \ --release \ --no-tree-shake-icons # Ensure permissions are set correctly on canvaskit binaries. chmod 0755 build/web/canvaskit/canvaskit.* popd
devtools/tool/build_release.sh/0
{ "file_path": "devtools/tool/build_release.sh", "repo_id": "devtools", "token_count": 611 }
147
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:io/io.dart'; import 'package:path/path.dart' as path; import '../utils.dart'; const _runIdArg = 'run-id'; /// A command for downloading and applying golden fixes, when they are broken. class FixGoldensCommand extends Command { FixGoldensCommand() { argParser.addOption( _runIdArg, help: 'The ID of the workflow run where the goldens are failing. ' 'e.g.https://github.com/flutter/devtools/actions/runs/<run-id>/job/16691428186', valueHelp: '12345', mandatory: true, ); } @override String get description => 'A command for downloading and applying golden fixes when they are broken on the CI.'; @override String get name => 'fix-goldens'; final processManager = ProcessManager(); @override FutureOr? run() async { // Change the CWD to the repo root Directory.current = pathFromRepoRoot(""); final runId = argResults![_runIdArg] as String; final tmpDownloadDir = await Directory.systemTemp.createTemp(); try { print('Downloading the artifacts to ${tmpDownloadDir.path}'); await processManager.runProcess( CliCommand( 'gh', [ 'run', 'download', runId, '-p', '*golden_image_failures*', '-R', 'github.com/flutter/devtools', '-D', tmpDownloadDir.path, ], ), ); final downloadedGoldens = tmpDownloadDir .listSync(recursive: true) .where((e) => e.path.endsWith('testImage.png')); final allLocalGoldenPngs = Directory(pathFromRepoRoot("packages/devtools_app/test/")) .listSync(recursive: true) ..where((e) => e.path.endsWith('.png')); for (final downloadedGolden in downloadedGoldens) { final downloadedGoldenBaseName = path.basename(downloadedGolden.path); final expectedGoldenFileName = '${RegExp(r'(^.*)_testImage.png').firstMatch(downloadedGoldenBaseName)?.group(1)}.png'; final fileMatches = allLocalGoldenPngs.where( (e) => e.path.endsWith(expectedGoldenFileName), ); final String destinationPath; if (fileMatches.isEmpty) { throw 'Could not find a golden Image for $downloadedGoldenBaseName using $expectedGoldenFileName as ' 'the name of the search.'; } else if (fileMatches.length == 1) { destinationPath = fileMatches.first.path; } else { print("Multiple goldens found for ${downloadedGolden.path}"); print("Select which golden should be overridden:"); for (int i = 0; i < fileMatches.length; i++) { final fileMatch = fileMatches.elementAt(i); print('${i + 1}) ${fileMatch.path}'); } final userSelection = int.parse(stdin.readLineSync()!); destinationPath = fileMatches.elementAt(userSelection - 1).path; } await downloadedGolden.rename(destinationPath); print("Fixed: $destinationPath"); } print('Done updating ${downloadedGoldens.length} goldens'); } finally { tmpDownloadDir.deleteSync(recursive: true); } } }
devtools/tool/lib/commands/fix_goldens.dart/0
{ "file_path": "devtools/tool/lib/commands/fix_goldens.dart", "repo_id": "devtools", "token_count": 1433 }
148
// 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'; import 'package:path/path.dart' as path; class DevToolsRepo { DevToolsRepo._create(this.repoPath); /// The path to the DevTools repository root. final String repoPath; /// The path to the DevTools 'tool' directory. String get toolDirectoryPath => path.join(repoPath, 'tool'); /// The path to the 'tool/flutter-sdk' directory. String get toolFlutterSdkPath => path.join(toolDirectoryPath, sdkDirectoryName); /// The name of the Flutter SDK directory. String get sdkDirectoryName => 'flutter-sdk'; /// The path to the DevTools 'devtools_app' directory. String get devtoolsAppDirectoryPath => path.join(repoPath, 'packages', 'devtools_app'); @override String toString() => '[DevTools $repoPath]'; /// This returns the DevToolsRepo instance based on the current working /// directory. /// /// Throws if the current working directory is not contained within a git /// checkout of DevTools. static DevToolsRepo getInstance() { final repoPath = _findRepoRoot(Directory.current); if (repoPath == null) { throw Exception( 'devtools_tool must be run from inside of the DevTools repository directory', ); } return DevToolsRepo._create(repoPath); } List<Package> getPackages() { final result = <Package>[]; final repoDir = Directory(repoPath); for (FileSystemEntity entity in repoDir.listSync()) { final name = path.basename(entity.path); if (entity is Directory && !name.startsWith('.')) { _collectPackages(entity, result); } } result.sort((a, b) => a.packagePath.compareTo(b.packagePath)); return result; } static String? _findRepoRoot(Directory dir) { // Look for README.md, packages, tool. if (_fileExists(dir, 'README.md') && _dirExists(dir, 'packages') && _dirExists(dir, 'tool')) { return dir.path; } if (dir.path == dir.parent.path) { return null; } else { return _findRepoRoot(dir.parent); } } void _collectPackages(Directory dir, List<Package> result) { // Do not collect packages from the Flutter SDK that is stored in the tool/ // directory. if (dir.path.contains('flutter-sdk/')) return; // Do not include the top level devtools/packages directory in the results // even though it has a pubspec.yaml file. if (_fileExists(dir, 'pubspec.yaml') && !dir.path.endsWith('/devtools/packages')) { result.add(Package._(this, dir.path)); } for (FileSystemEntity entity in dir.listSync(followLinks: false)) { final name = path.basename(entity.path); if (entity is Directory && !name.startsWith('.') && name != 'build') { _collectPackages(entity, result); } } } /// Reads the file at [uri], which should be a relative path from [repoPath]. String readFile(Uri uri) { return File(path.join(repoPath, uri.path)).readAsStringSync(); } } class FlutterSdk { FlutterSdk._(this.sdkPath); static FlutterSdk? _current; /// The current located Flutter SDK. /// /// Tries to locate from the running Dart VM. If not found, will print a /// warning and use Flutter from PATH. static FlutterSdk get current { if (_current == null) { throw Exception( 'Cannot use FlutterSdk.current before SDK has been selected.' 'SDK selection is done by DevToolsCommandRunner.runCommand().', ); } return _current!; } /// Sets the active Flutter SDK to the one that contains the Dart VM being /// used to run this script. /// /// Throws if the current VM is not inside a Flutter SDK. static void useFromCurrentVm() { _current = findFromCurrentVm(); } /// Sets the active Flutter SDK to the one found in the `PATH` environment /// variable (by running which/where). /// /// Throws if an SDK is not found on PATH. static void useFromPathEnvironmentVariable() { _current = findFromPathEnvironmentVariable(); } /// Finds the Flutter SDK that contains the Dart VM being used to run this /// script. /// /// Throws if the current VM is not inside a Flutter SDK. static FlutterSdk findFromCurrentVm() { // Look for it relative to the current Dart process. final dartVmPath = Platform.resolvedExecutable; final pathSegments = path.split(dartVmPath); // TODO(dantup): Should we add tool/flutter-sdk to the front here, to // ensure we _only_ ever use this one, to avoid potentially updating a // different Flutter if the user runs explicitly with another Flutter? final expectedSegments = path.posix.split('bin/cache/dart-sdk/bin/dart'); if (pathSegments.length >= expectedSegments.length) { // Remove the trailing 'dart'. pathSegments.removeLast(); expectedSegments.removeLast(); while (expectedSegments.isNotEmpty) { if (expectedSegments.last == pathSegments.last) { pathSegments.removeLast(); expectedSegments.removeLast(); } else { break; } } if (expectedSegments.isEmpty) { final flutterSdkRoot = path.joinAll(pathSegments); return FlutterSdk._(flutterSdkRoot); } } throw Exception( 'Unable to locate the Flutter SDK from the current running Dart VM:\n' '${Platform.resolvedExecutable}', ); } /// Finds a Flutter SDK in the `PATH` environment variable /// (by running which/where). /// /// Throws if an SDK is not found on PATH. static FlutterSdk findFromPathEnvironmentVariable() { final whichCommand = Platform.isWindows ? 'where.exe' : 'which'; final result = Process.runSync(whichCommand, ['flutter']); if (result.exitCode == 0) { final sdkPath = result.stdout.toString().split('\n').first.trim(); // 'flutter/bin' if (path.basename(path.dirname(sdkPath)) == 'bin') { return FlutterSdk._(path.dirname(path.dirname(sdkPath))); } } throw Exception( 'Unable to locate the Flutter SDK on PATH', ); } final String sdkPath; static String get flutterExecutableName => Platform.isWindows ? 'flutter.bat' : 'flutter'; /// On windows, 'dart' is fine for running the .exe from the Dart SDK directly /// but the wrapper in the Flutter bin folder is a .bat and needs an explicit /// extension. static String get dartWrapperExecutableName => Platform.isWindows ? 'dart.bat' : 'dart'; String get flutterExePath => path.join(sdkPath, 'bin', flutterExecutableName); String get dartExePath => path.join(sdkPath, 'bin', dartWrapperExecutableName); String get dartSdkPath => path.join(sdkPath, 'bin', 'cache', 'dart-sdk'); String get pubToolPath => path.join(dartSdkPath, 'bin', 'pub'); @override String toString() => '[Flutter sdk: $sdkPath]'; } class Package { Package._(this.repo, this.packagePath); final DevToolsRepo repo; final String packagePath; String get relativePath => path.relative(packagePath, from: repo.repoPath); bool get hasAnyDartCode { final dartFiles = <String>[]; _collectDartFiles(Directory(packagePath), dartFiles); return dartFiles.isNotEmpty; } void _collectDartFiles(Directory dir, List<String> result) { for (FileSystemEntity entity in dir.listSync(followLinks: false)) { final name = path.basename(entity.path); if (entity is Directory && !name.startsWith('.') && name != 'build') { _collectDartFiles(entity, result); } else if (entity is File && name.endsWith('.dart')) { result.add(entity.path); } } } @override String toString() => '[Package $relativePath]'; } bool _fileExists(Directory parent, String name) { return FileSystemEntity.isFileSync(path.join(parent.path, name)); } bool _dirExists(Directory parent, String name) { return FileSystemEntity.isDirectorySync(path.join(parent.path, name)); }
devtools/tool/lib/model.dart/0
{ "file_path": "devtools/tool/lib/model.dart", "repo_id": "devtools", "token_count": 2833 }
149
# Contributing to the Flutter engine _See also: [Flutter's code of conduct][code_of_conduct]_ ## Welcome For an introduction to contributing to Flutter, see [our contributor guide][contrib_guide]. For specific instructions regarding building Flutter's engine, see [Setting up the Engine development environment][engine_dev_setup] on our wiki. Those instructions are part of the broader onboarding instructions described in the contributing guide. ## Style The Flutter engine follows Google style for the languages it uses: - [C++](https://google.github.io/styleguide/cppguide.html) - **Note**: The Linux embedding generally follows idiomatic GObject-based C style. Use of C++ is discouraged in that embedding to avoid creating hybrid code that feels unfamiliar to either developers used to working with `GObject` or C++ developers. For example, do not use STL collections or `std::string`. Exceptions: - C-style casts are forbidden; use C++ casts. - Use `nullptr` rather than `NULL`. - Avoid `#define`; for internal constants use `static constexpr` instead. - [Objective-C][objc_style] (including [Objective-C++][objcc_style]) - [Java][java_style] C/C++ and Objective-C/C++ files are formatted with `clang-format`, and GN files with `gn format`. [code_of_conduct]: https://github.com/flutter/flutter/blob/master/CODE_OF_CONDUCT.md [contrib_guide]: https://github.com/flutter/flutter/blob/master/CONTRIBUTING.md [engine_dev_setup]: https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment [objc_style]: https://google.github.io/styleguide/objcguide.html [objcc_style]: https://google.github.io/styleguide/objcguide.html#objective-c [java_style]: https://google.github.io/styleguide/javaguide.html ## Testing The testing policy for contributing to the flutter engine can be found at the [Tree Hygiene Wiki][tree_hygiene_wiki]. The summary is that all PR's to the engine should be tested or have an explicit test exemption. Because the engine targets multiple platforms the testing infrastructure is fairly complicated. Here are some more resources to help guide writing tests: - [Testing the engine wiki][testing_the_engine_wiki] - A guide on writing tests for the engine including an overview of the different tests and the different technologies the engine uses. - [`//testing`](./testing) - This is where the `run_tests.py` script is located. All tests will have the ability to be executed with `run_tests.py`. - [`//ci/builders`](./ci/builders) - The JSON files that determine how tests are executed on CI. Tests will be executed on CI, but some tests will be executed before PR's can be merged (presubmit) and others after they have been merged (postsubmit). Ideally everything would be presubmit but tests that take up more resources are executed in postsubmit. ### Skia Gold The Flutter engine uses [Skia Gold][skia_gold] for image comparison tests which fail if: - The image is different from an accepted baseline. - An image is not uploaded but is expected to be (see [`dir_contents_diff`][dir_contents_diff]). [skia_gold]: https://flutter-engine-gold.skia.org/ [dir_contents_diff]: ./tools/dir_contents_diff/ Any untriaged failures will block presubmit and postsubmit tests. ### Example run_tests.py invocation ```sh # Configure host build for macOS arm64 debug. $ flutter/tools/gn --runtime-mode=debug --unoptimized --no-lto --mac-cpu=arm64 # Compile default targets (should cover all applicable run_tests.py requirements). $ ninja -j100 -C out/host_debug_unopt_arm64 # Run all cross-platform C++ tests for the debug build arm64 variant. $ cd flutter/testing $ ./run_tests.py --variant=host_debug_unopt_arm64 --type=engine` ``` ### Directory | Name | run_tests.py type | Description | | ---------------------------------------- | ------------------- | --------------------------------------------------------------- | | accessibility_unittests | engine | | | client_wrapper_glfw_unittests | engine | | | client_wrapper_unittests | engine | | | common_cpp_core_unittests | engine | | | common_cpp_unittests | engine | | | dart_plugin_registrant_unittests | engine | | | display_list_rendertests | engine | | | display_list_unittests | engine | | | embedder_a11y_unittests | engine | | | embedder_proctable_unittests | engine | | | embedder_unittests | engine | | | felt | n/a | The test runner for flutter web. See //lib/web_ui | | flow_unittests | engine | | | flutter_tester | dart | Launcher for engine dart tests. | | fml_arc_unittests | engine | | | fml_unittests | engine | Unit tests for //fml | | framework_common_unittests | engine(mac) | | | gpu_surface_metal_unittests | engine(mac) | | | impeller_dart_unittests | engine | | | impeller_golden_tests | engine(mac) | Generates golden images for impeller (vulkan, metal, opengles). | | impeller_unittests | engine | impeller unit tests and interactive tests | | ios_test_flutter | objc | dynamic library of objc tests to be run with XCTest | | jni_unittests | engine(not windows) | | | no_dart_plugin_registrant_unittests | engine | | | platform_view_android_delegate_unittests | engine(not windows) | | | runtime_unittests | engine | | | shell_unittests | engine(not windows) | | | scenario_app | android | Integration and golden tests for Android, iOS | | testing_unittests | engine | | | tonic_unittests | engine | Unit tests for //third_party/tonic | | txt_unittests | engine(linux) | | | ui_unittests | engine | | [tree_hygiene_wiki]: https://github.com/flutter/flutter/wiki/Tree-hygiene#tests [testing_the_engine_wiki]: https://github.com/flutter/flutter/wiki/Testing-the-engine ## Fuchsia Contributions from Googlers Googlers contributing to Fuchsia should follow the additional steps at: go/flutter-fuchsia-pr-policy.
engine/CONTRIBUTING.md/0
{ "file_path": "engine/CONTRIBUTING.md", "repo_id": "engine", "token_count": 4543 }
150
# Copyright 2016 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. config("benchmark_config") { visibility = [ ":*" ] include_dirs = [ "include" ] } static_library("benchmark") { testonly = true sources = [ "//flutter/third_party/benchmark/src/arraysize.h", "//flutter/third_party/benchmark/src/benchmark.cc", "//flutter/third_party/benchmark/src/benchmark_api_internal.cc", "//flutter/third_party/benchmark/src/benchmark_api_internal.h", "//flutter/third_party/benchmark/src/benchmark_main.cc", "//flutter/third_party/benchmark/src/benchmark_name.cc", "//flutter/third_party/benchmark/src/benchmark_register.cc", "//flutter/third_party/benchmark/src/benchmark_register.h", "//flutter/third_party/benchmark/src/benchmark_runner.cc", "//flutter/third_party/benchmark/src/benchmark_runner.h", "//flutter/third_party/benchmark/src/check.h", "//flutter/third_party/benchmark/src/colorprint.cc", "//flutter/third_party/benchmark/src/colorprint.h", "//flutter/third_party/benchmark/src/commandlineflags.cc", "//flutter/third_party/benchmark/src/commandlineflags.h", "//flutter/third_party/benchmark/src/complexity.cc", "//flutter/third_party/benchmark/src/complexity.h", "//flutter/third_party/benchmark/src/console_reporter.cc", "//flutter/third_party/benchmark/src/counter.cc", "//flutter/third_party/benchmark/src/counter.h", "//flutter/third_party/benchmark/src/csv_reporter.cc", "//flutter/third_party/benchmark/src/cycleclock.h", "//flutter/third_party/benchmark/src/internal_macros.h", "//flutter/third_party/benchmark/src/json_reporter.cc", "//flutter/third_party/benchmark/src/log.h", "//flutter/third_party/benchmark/src/mutex.h", "//flutter/third_party/benchmark/src/perf_counters.cc", "//flutter/third_party/benchmark/src/perf_counters.h", "//flutter/third_party/benchmark/src/re.h", "//flutter/third_party/benchmark/src/reporter.cc", "//flutter/third_party/benchmark/src/sleep.cc", "//flutter/third_party/benchmark/src/sleep.h", "//flutter/third_party/benchmark/src/statistics.cc", "//flutter/third_party/benchmark/src/statistics.h", "//flutter/third_party/benchmark/src/string_util.cc", "//flutter/third_party/benchmark/src/string_util.h", "//flutter/third_party/benchmark/src/sysinfo.cc", "//flutter/third_party/benchmark/src/thread_manager.h", "//flutter/third_party/benchmark/src/thread_timer.h", "//flutter/third_party/benchmark/src/timers.cc", "//flutter/third_party/benchmark/src/timers.h", ] public_configs = [ ":benchmark_config" ] defines = [ "HAVE_STD_REGEX", "HAVE_THREAD_SAFETY_ATTRIBUTES", ] }
engine/build/secondary/flutter/third_party/benchmark/BUILD.gn/0
{ "file_path": "engine/build/secondary/flutter/third_party/benchmark/BUILD.gn", "repo_id": "engine", "token_count": 1136 }
151
# Copyright 2021 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. # TODO(flutter/flutter#85356): This file was originally generated by the # fuchsia.git script: `package_importer.py`. The generated `BUILD.gn` files were # copied to the flutter repo to support `dart_library` targets used for # Flutter-Fuchsia integration tests. This file can be maintained by hand, but it # would be better to implement a script for Flutter, to either generate these # BUILD.gn files or dynamically generate the GN targets. import("//flutter/tools/fuchsia/dart/dart_library.gni") dart_library("matcher") { package_name = "matcher" language_version = "2.12" deps = [ "$dart_src/third_party/pkg/stack_trace" ] sources = [ "expect.dart", "matcher.dart", "mirror_matchers.dart", "src/core_matchers.dart", "src/custom_matcher.dart", "src/description.dart", "src/equals_matcher.dart", "src/error_matchers.dart", "src/expect/async_matcher.dart", "src/expect/expect.dart", "src/expect/expect_async.dart", "src/expect/future_matchers.dart", "src/expect/never_called.dart", "src/expect/prints_matcher.dart", "src/expect/stream_matcher.dart", "src/expect/stream_matchers.dart", "src/expect/throws_matcher.dart", "src/expect/throws_matchers.dart", "src/expect/util/placeholder.dart", "src/expect/util/pretty_print.dart", "src/feature_matcher.dart", "src/having_matcher.dart", "src/interfaces.dart", "src/iterable_matchers.dart", "src/map_matchers.dart", "src/numeric_matchers.dart", "src/operator_matchers.dart", "src/order_matchers.dart", "src/pretty_print.dart", "src/string_matchers.dart", "src/type_matcher.dart", "src/util.dart", ] }
engine/build/secondary/third_party/dart/third_party/pkg/matcher/BUILD.gn/0
{ "file_path": "engine/build/secondary/third_party/dart/third_party/pkg/matcher/BUILD.gn", "repo_id": "engine", "token_count": 754 }
152
# Copyright 2021 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. # TODO(flutter/flutter#85356): This file was originally generated by the # fuchsia.git script: `package_importer.py`. The generated `BUILD.gn` files were # copied to the flutter repo to support `dart_library` targets used for # Flutter-Fuchsia integration tests. This file can be maintained by hand, but it # would be better to implement a script for Flutter, to either generate these # BUILD.gn files or dynamically generate the GN targets. import("//flutter/tools/fuchsia/dart/dart_library.gni") dart_library("quiver") { package_name = "quiver" # The current version of this library is not null safe language_version = "2.0" deps = [ "$dart_src/pkg/meta", "$dart_src/third_party/pkg/matcher", ] sources = [ "async.dart", "cache.dart", "check.dart", "collection.dart", "core.dart", "io.dart", "iterables.dart", "mirrors.dart", "pattern.dart", "src/async/collect.dart", "src/async/concat.dart", "src/async/countdown_timer.dart", "src/async/enumerate.dart", "src/async/future_stream.dart", "src/async/iteration.dart", "src/async/metronome.dart", "src/async/stream_buffer.dart", "src/async/stream_router.dart", "src/async/string.dart", "src/cache/cache.dart", "src/cache/map_cache.dart", "src/collection/bimap.dart", "src/collection/delegates/iterable.dart", "src/collection/delegates/list.dart", "src/collection/delegates/map.dart", "src/collection/delegates/queue.dart", "src/collection/delegates/set.dart", "src/collection/lru_map.dart", "src/collection/multimap.dart", "src/collection/treeset.dart", "src/core/hash.dart", "src/core/optional.dart", "src/iterables/concat.dart", "src/iterables/count.dart", "src/iterables/cycle.dart", "src/iterables/enumerate.dart", "src/iterables/generating_iterable.dart", "src/iterables/infinite_iterable.dart", "src/iterables/merge.dart", "src/iterables/min_max.dart", "src/iterables/partition.dart", "src/iterables/range.dart", "src/iterables/zip.dart", "src/time/clock.dart", "src/time/duration_unit_constants.dart", "src/time/util.dart", "strings.dart", "testing/async.dart", "testing/equality.dart", "testing/runtime.dart", "testing/src/async/fake_async.dart", "testing/src/equality/equality.dart", "testing/src/runtime/checked_mode.dart", "testing/src/time/time.dart", "testing/time.dart", "time.dart", ] }
engine/build/secondary/third_party/pkg/quiver/BUILD.gn/0
{ "file_path": "engine/build/secondary/third_party/pkg/quiver/BUILD.gn", "repo_id": "engine", "token_count": 1117 }
153
# Copyright 2013 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("//flutter/common/config.gni") import("//flutter/shell/version/version.gni") if (flutter_runtime_mode == "jit_release") { android_zip_archive_dir = "android-$target_cpu-jit-release" } else { android_zip_archive_dir = "android-$target_cpu" if (flutter_runtime_mode != "debug") { android_zip_archive_dir += "-$flutter_runtime_mode" } } # Creates a zip file in the $root_build_dir/zip_archives folder. # # The output variable specifies the name of the zip file to create. # The files variable is an array of scopes that specify a source file or # directory and a destination path in the archive to create. # # For example, to create a zip file named archive.zip with all files in the # root directory of the archive: # # zip_bundle("sample") { # output = "archive.zip" # files = [ # { # source = "$root_build_dir/some/path/to/lib.so" # destination = "lib.so" # }, # { # source = "$root_build_dir/some/other/path/with/files" # destination = "other_files" # }, # ] # } template("zip_bundle") { assert(defined(invoker.output), "output must be defined") assert(defined(invoker.files), "files must be defined as a list of scopes") license_readme = "$target_gen_dir/LICENSE.$target_name.md" license_target = "_${target_name}_license_md" generated_file(license_target) { source_path = rebase_path(".", "//flutter") license_path = rebase_path("//flutter/sky/packages/sky_engine/LICENSE", "//flutter") git_url = "https://github.com/flutter/engine/tree/$engine_version" sky_engine_url = "https://storage.googleapis.com/flutter_infra_release/flutter/$engine_version/sky_engine.zip" outputs = [ license_readme ] contents = [ "# $target_name", "", "This bundle is part of the the Flutter SDK.", "", "The source code is hosted at [flutter/engine/$source_path]($git_url/$source_path).", "The license for this bundle is hosted at [flutter/engine/sky/packages/sky_engine/LICENSE]($git_url/$license_path) ", "and [sky_engine.zip]($sky_engine_url).", ] } action(target_name) { script = "//flutter/build/zip.py" outputs = [ "$root_build_dir/zip_archives/${invoker.output}" ] sources = [ license_readme ] forward_variables_from(invoker, [ "visibility" ]) deps = [ ":$license_target" ] + invoker.deps args = [ "-o", rebase_path(outputs[0]), "-i", rebase_path(license_readme), "LICENSE.$target_name.md", ] foreach(input, invoker.files) { args += [ "-i", rebase_path(input.source), input.destination, ] sources += [ input.source ] } } } # Creates a zip file in the $root_build_dir/zip_archives folder. # # The output variable specifies the name of the zip file to create. # The files variable is an array of scopes that specify a source file or # directory and a destination path in the archive to create. # # For example, to create a zip file named archive.zip with all files in the # root directory of the archive: # # zip_bundle("sample") { # output = "archive.zip" # files = [ # { # source = rebase_path("$root_build_dir/some/path/to/lib.so") # destination = "lib.so" # }, # { # source = rebase_path("$root_build_dir/some/other/path/with/files") # destination = "other_files" # }, # ] # } template("zip_bundle_from_file") { assert(defined(invoker.output), "output must be defined") assert(defined(invoker.files), "files must be defined as a list of scopes") action(target_name) { forward_variables_from(invoker, [ "visibility", "deps", ]) script = "//flutter/build/zip.py" outputs = [ "$root_build_dir/zip_archives/${invoker.output}" ] sources = [] location_source_path = "$target_gen_dir/zip_bundle.txt" write_file(location_source_path, invoker.files, "json") args = [ "-o", rebase_path(outputs[0]), "-f", rebase_path(location_source_path), ] } }
engine/build/zip_bundle.gni/0
{ "file_path": "engine/build/zip_bundle.gni", "repo_id": "engine", "token_count": 1720 }
154
#!/bin/bash # # Copyright 2013 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. # Run a tool that generates a treemap showing the contribution of each # component to the size of a binary. # # Usage: # binary_size_treemap.sh [binary_path] [output_dir] set -e INPUT_PATH="$(cd $(dirname "$1"); pwd -P)/$(basename "$1")" DEST_DIR="$(cd $(dirname "$2"); pwd -P)/$(basename "$2")" CI_DIRECTORY=$(cd $(dirname "${BASH_SOURCE[0]}"); pwd -P) ENGINE_BUILDROOT=$(cd "$CI_DIRECTORY/../.."; pwd -P) if [ "$(uname)" == "Darwin" ]; then NDK_PLATFORM="darwin-x86_64" else NDK_PLATFORM="linux-x86_64" fi ADDR2LINE="third_party/android_tools/ndk/toolchains/llvm/prebuilt/$NDK_PLATFORM/bin/llvm-addr2line" NM="third_party/android_tools/ndk/toolchains/llvm/prebuilt/$NDK_PLATFORM/bin/llvm-nm" # Run the binary size script from the buildroot directory so the treemap path # navigation will start from there. cd "$ENGINE_BUILDROOT" RUN_BINARY_SIZE_ANALYSIS="third_party/dart/third_party/binary_size/src/run_binary_size_analysis.py" python3 "$RUN_BINARY_SIZE_ANALYSIS" --library "$INPUT_PATH" --destdir "$DEST_DIR" --addr2line-binary "$ADDR2LINE" --nm-binary "$NM" --jobs 1 --no-check-support
engine/ci/binary_size_treemap.sh/0
{ "file_path": "engine/ci/binary_size_treemap.sh", "repo_id": "engine", "token_count": 497 }
155
{ "builds": [ { "archives": [ { "base_path": "out/android_profile/zip_archives/", "type": "gcs", "include_paths": [ "out/android_profile/zip_archives/android-arm-profile/darwin-x64.zip" ], "name": "android_profile", "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Mac-13", "cpu=x86" ], "gclient_variables": { "download_android_deps": false }, "gn": [ "--runtime-mode", "profile", "--android" ], "name": "android_profile", "ninja": { "config": "android_profile", "targets": [ "flutter/lib/snapshot", "flutter/shell/platform/android:gen_snapshot" ] }, "properties": { "$flutter/osx_sdk": { "sdk_version": "15a240d" } } }, { "archives": [ { "base_path": "out/android_profile_arm64/zip_archives/", "type": "gcs", "include_paths": [ "out/android_profile_arm64/zip_archives/android-arm64-profile/darwin-x64.zip" ], "name": "android_profile_arm64", "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Mac-13", "cpu=x86" ], "gclient_variables": { "download_android_deps": false }, "gn": [ "--runtime-mode", "profile", "--android", "--android-cpu=arm64" ], "name": "android_profile_arm64", "ninja": { "config": "android_profile_arm64", "targets": [ "flutter/lib/snapshot", "flutter/shell/platform/android:gen_snapshot" ] }, "properties": { "$flutter/osx_sdk": { "sdk_version": "15a240d" } } }, { "archives": [ { "base_path": "out/android_profile_x64/zip_archives/", "type": "gcs", "include_paths": [ "out/android_profile_x64/zip_archives/android-x64-profile/darwin-x64.zip" ], "name": "android_profile_x64", "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Mac-13", "cpu=x86" ], "gclient_variables": { "download_android_deps": false }, "gn": [ "--runtime-mode", "profile", "--android", "--android-cpu=x64" ], "name": "android_profile_x64", "ninja": { "config": "android_profile_x64", "targets": [ "flutter/lib/snapshot", "flutter/shell/platform/android:gen_snapshot" ] }, "properties": { "$flutter/osx_sdk": { "sdk_version": "15a240d" } } }, { "archives": [ { "base_path": "out/android_release/zip_archives/", "type": "gcs", "include_paths": [ "out/android_release/zip_archives/android-arm-release/darwin-x64.zip" ], "name": "android_release", "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Mac-13", "cpu=x86" ], "gclient_variables": { "download_android_deps": false }, "gn": [ "--runtime-mode", "release", "--android" ], "name": "android_release", "ninja": { "config": "android_release", "targets": [ "flutter/lib/snapshot", "flutter/shell/platform/android:gen_snapshot" ] }, "properties": { "$flutter/osx_sdk": { "sdk_version": "15a240d" } } }, { "archives": [ { "base_path": "out/android_release_arm64/zip_archives/", "type": "gcs", "include_paths": [ "out/android_release_arm64/zip_archives/android-arm64-release/darwin-x64.zip" ], "name": "android_release_arm64", "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Mac-13", "cpu=x86" ], "gclient_variables": { "download_android_deps": false }, "gn": [ "--runtime-mode", "release", "--android", "--android-cpu=arm64" ], "name": "android_release_arm64", "ninja": { "config": "android_release_arm64", "targets": [ "flutter/lib/snapshot", "flutter/shell/platform/android:gen_snapshot" ] }, "properties": { "$flutter/osx_sdk": { "sdk_version": "15a240d" } } }, { "archives": [ { "base_path": "out/android_release_x64/zip_archives/", "type": "gcs", "include_paths": [ "out/android_release_x64/zip_archives/android-x64-release/darwin-x64.zip" ], "name": "android_release_x64", "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Mac-13", "cpu=x86" ], "gclient_variables": { "download_android_deps": false }, "gn": [ "--runtime-mode", "release", "--android", "--android-cpu=x64" ], "name": "android_release_x64", "ninja": { "config": "android_release_x64", "targets": [ "flutter/lib/snapshot", "flutter/shell/platform/android:gen_snapshot" ] }, "properties": { "$flutter/osx_sdk": { "sdk_version": "15a240d" } } } ], "generators": {}, "archives": [] }
engine/ci/builders/mac_android_aot_engine.json/0
{ "file_path": "engine/ci/builders/mac_android_aot_engine.json", "repo_id": "engine", "token_count": 5168 }
156
#!/bin/bash # # Copyright 2013 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. # TODO(dnfield): delete this script once recipes point to the python version. set -e CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" python $CURRENT_DIR/firebase_testlab.py
engine/ci/firebase_testlab.sh/0
{ "file_path": "engine/ci/firebase_testlab.sh", "repo_id": "engine", "token_count": 130 }
157
// Copyright 2013 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:io' as io; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; import '../bin/format.dart' as target; final io.File script = io.File.fromUri(io.Platform.script).absolute; final io.Directory repoDir = script.parent.parent.parent; class FileContentPair { FileContentPair(this.original, this.formatted); final String original; final String formatted; } final FileContentPair ccContentPair = FileContentPair( 'int main(){return 0;}\n', 'int main() {\n return 0;\n}\n'); final FileContentPair hContentPair = FileContentPair('int\nmain\n()\n;\n', 'int main();\n'); final FileContentPair gnContentPair = FileContentPair( 'test\n(){testvar=true}\n', 'test() {\n testvar = true\n}\n'); final FileContentPair javaContentPair = FileContentPair( 'class Test{public static void main(String args[]){System.out.println("Test");}}\n', 'class Test {\n public static void main(String args[]) {\n System.out.println("Test");\n }\n}\n'); final FileContentPair pythonContentPair = FileContentPair( "if __name__=='__main__':\n sys.exit(\nMain(sys.argv)\n)\n", "if __name__ == '__main__':\n sys.exit(Main(sys.argv))\n"); final FileContentPair whitespaceContentPair = FileContentPair( 'int main() {\n return 0; \n}\n', 'int main() {\n return 0;\n}\n'); final FileContentPair headerContentPair = FileContentPair( <String>[ '#ifndef FOO_H_', '#define FOO_H_', '', '#endif // FOO_H_', ].join('\n'), <String>[ '#ifndef FLUTTER_FORMAT_TEST_H_', '#define FLUTTER_FORMAT_TEST_H_', '', '#endif // FLUTTER_FORMAT_TEST_H_', '', ].join('\n'), ); class TestFileFixture { TestFileFixture(this.type) { switch (type) { case target.FormatCheck.clang: final io.File ccFile = io.File('${repoDir.path}/format_test.cc'); ccFile.writeAsStringSync(ccContentPair.original); files.add(ccFile); final io.File hFile = io.File('${repoDir.path}/format_test.h'); hFile.writeAsStringSync(hContentPair.original); files.add(hFile); case target.FormatCheck.gn: final io.File gnFile = io.File('${repoDir.path}/format_test.gn'); gnFile.writeAsStringSync(gnContentPair.original); files.add(gnFile); case target.FormatCheck.java: final io.File javaFile = io.File('${repoDir.path}/format_test.java'); javaFile.writeAsStringSync(javaContentPair.original); files.add(javaFile); case target.FormatCheck.python: final io.File pyFile = io.File('${repoDir.path}/format_test.py'); pyFile.writeAsStringSync(pythonContentPair.original); files.add(pyFile); case target.FormatCheck.whitespace: final io.File whitespaceFile = io.File('${repoDir.path}/format_test.c'); whitespaceFile.writeAsStringSync(whitespaceContentPair.original); files.add(whitespaceFile); case target.FormatCheck.header: final io.File headerFile = io.File('${repoDir.path}/format_test.h'); headerFile.writeAsStringSync(headerContentPair.original); files.add(headerFile); } } final target.FormatCheck type; final List<io.File> files = <io.File>[]; void gitAdd() { final List<String> args = <String>['add']; for (final io.File file in files) { args.add(file.path); } io.Process.runSync('git', args); } void gitRemove() { final List<String> args = <String>['rm', '-f']; for (final io.File file in files) { args.add(file.path); } io.Process.runSync('git', args); } Iterable<FileContentPair> getFileContents() { return files.map((io.File file) { String content = file.readAsStringSync(); // Avoid clang-tidy formatting CRLF EOL on Windows content = content.replaceAll('\r\n', '\n'); switch (type) { case target.FormatCheck.clang: return FileContentPair( content, path.extension(file.path) == '.cc' ? ccContentPair.formatted : hContentPair.formatted, ); case target.FormatCheck.gn: return FileContentPair( content, gnContentPair.formatted, ); case target.FormatCheck.java: return FileContentPair( content, javaContentPair.formatted, ); case target.FormatCheck.python: return FileContentPair( content, pythonContentPair.formatted, ); case target.FormatCheck.whitespace: return FileContentPair( content, whitespaceContentPair.formatted, ); case target.FormatCheck.header: return FileContentPair( content, headerContentPair.formatted, ); } }); } } void main() { final String formatterPath = '${repoDir.path}/ci/format.${io.Platform.isWindows ? 'bat' : 'sh'}'; test('Can fix C++ formatting errors', () { final TestFileFixture fixture = TestFileFixture(target.FormatCheck.clang); try { fixture.gitAdd(); io.Process.runSync(formatterPath, <String>['--check', 'clang', '--fix'], workingDirectory: repoDir.path); final Iterable<FileContentPair> files = fixture.getFileContents(); for (final FileContentPair pair in files) { expect(pair.original, equals(pair.formatted)); } } finally { fixture.gitRemove(); } }); test('Can fix GN formatting errors', () { final TestFileFixture fixture = TestFileFixture(target.FormatCheck.gn); try { fixture.gitAdd(); io.Process.runSync(formatterPath, <String>['--check', 'gn', '--fix'], workingDirectory: repoDir.path); final Iterable<FileContentPair> files = fixture.getFileContents(); for (final FileContentPair pair in files) { expect(pair.original, equals(pair.formatted)); } } finally { fixture.gitRemove(); } }); test('Can fix Java formatting errors', () { final TestFileFixture fixture = TestFileFixture(target.FormatCheck.java); try { fixture.gitAdd(); io.Process.runSync(formatterPath, <String>['--check', 'java', '--fix'], workingDirectory: repoDir.path); final Iterable<FileContentPair> files = fixture.getFileContents(); for (final FileContentPair pair in files) { expect(pair.original, equals(pair.formatted)); } } finally { fixture.gitRemove(); } // TODO(mtolmacs): Fails if Java dependency is unavailable, // https://github.com/flutter/flutter/issues/129221 }, skip: true); test('Can fix Python formatting errors', () { final TestFileFixture fixture = TestFileFixture(target.FormatCheck.python); try { fixture.gitAdd(); io.Process.runSync(formatterPath, <String>['--check', 'python', '--fix'], workingDirectory: repoDir.path); final Iterable<FileContentPair> files = fixture.getFileContents(); for (final FileContentPair pair in files) { expect(pair.original, equals(pair.formatted)); } } finally { fixture.gitRemove(); } }); test('Can fix whitespace formatting errors', () { final TestFileFixture fixture = TestFileFixture(target.FormatCheck.whitespace); try { fixture.gitAdd(); io.Process.runSync( formatterPath, <String>['--check', 'whitespace', '--fix'], workingDirectory: repoDir.path); final Iterable<FileContentPair> files = fixture.getFileContents(); for (final FileContentPair pair in files) { expect(pair.original, equals(pair.formatted)); } } finally { fixture.gitRemove(); } }); test('Can fix header guard formatting errors', () { final TestFileFixture fixture = TestFileFixture(target.FormatCheck.header); try { fixture.gitAdd(); io.Process.runSync( formatterPath, <String>['--check', 'header', '--fix'], workingDirectory: repoDir.path, ); final Iterable<FileContentPair> files = fixture.getFileContents(); for (final FileContentPair pair in files) { expect(pair.original, equals(pair.formatted)); } } finally { fixture.gitRemove(); } }); }
engine/ci/test/format_test.dart/0
{ "file_path": "engine/ci/test/format_test.dart", "repo_id": "engine", "token_count": 3504 }
158
// Copyright 2013 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. #include "flutter/common/graphics/texture.h" namespace flutter { ContextListener::ContextListener() = default; ContextListener::~ContextListener() = default; Texture::Texture(int64_t id) : id_(id) {} Texture::~Texture() = default; TextureRegistry::TextureRegistry() = default; void TextureRegistry::RegisterTexture(const std::shared_ptr<Texture>& texture) { if (!texture) { return; } mapping_[texture->Id()] = texture; } void TextureRegistry::RegisterContextListener( uintptr_t id, std::weak_ptr<ContextListener> image) { size_t next_id = image_counter_++; auto const result = image_indices_.insert({id, next_id}); if (!result.second) { ordered_images_.erase(result.first->second); result.first->second = next_id; } ordered_images_[next_id] = {next_id, std::move(image)}; } void TextureRegistry::UnregisterTexture(int64_t id) { auto found = mapping_.find(id); if (found == mapping_.end()) { return; } found->second->OnTextureUnregistered(); mapping_.erase(found); } void TextureRegistry::UnregisterContextListener(uintptr_t id) { ordered_images_.erase(image_indices_[id]); image_indices_.erase(id); } void TextureRegistry::OnGrContextCreated() { for (auto& it : mapping_) { it.second->OnGrContextCreated(); } // Calling OnGrContextCreated may result in a subsequent call to // RegisterContextListener from the listener, which may modify the map. std::vector<InsertionOrderMap::value_type> ordered_images( ordered_images_.begin(), ordered_images_.end()); for (const auto& [id, pair] : ordered_images) { auto index_id = pair.first; auto weak_image = pair.second; if (auto image = weak_image.lock()) { image->OnGrContextCreated(); } else { image_indices_.erase(index_id); ordered_images_.erase(id); } } } void TextureRegistry::OnGrContextDestroyed() { for (auto& it : mapping_) { it.second->OnGrContextDestroyed(); } auto it = ordered_images_.begin(); while (it != ordered_images_.end()) { auto index_id = it->second.first; auto weak_image = it->second.second; if (auto image = weak_image.lock()) { image->OnGrContextDestroyed(); it++; } else { image_indices_.erase(index_id); it = ordered_images_.erase(it); } } } std::shared_ptr<Texture> TextureRegistry::GetTexture(int64_t id) { auto it = mapping_.find(id); return it != mapping_.end() ? it->second : nullptr; } } // namespace flutter
engine/common/graphics/texture.cc/0
{ "file_path": "engine/common/graphics/texture.cc", "repo_id": "engine", "token_count": 924 }
159
// Copyright 2013 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. #include "flutter/display_list/dl_op_flags.h" #include "flutter/display_list/effects/dl_path_effect.h" namespace flutter { const DisplayListSpecialGeometryFlags DisplayListAttributeFlags::WithPathEffect( const DlPathEffect* effect, bool is_stroked) const { if (is_geometric() && effect) { switch (effect->type()) { case DlPathEffectType::kDash: { // Dashing has no effect on filled geometry. if (is_stroked) { // A dash effect has a very simple impact. It cannot introduce any // miter joins that weren't already present in the original path // and it does not grow the bounds of the path, but it can add // end caps to areas that might not have had them before so all // we need to do is to indicate the potential for diagonal // end caps and move on. return special_flags_.with(kMayHaveCaps | kMayHaveDiagonalCaps); } } } } return special_flags_; } } // namespace flutter
engine/display_list/dl_op_flags.cc/0
{ "file_path": "engine/display_list/dl_op_flags.cc", "repo_id": "engine", "token_count": 415 }
160
// Copyright 2013 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. #include "flutter/display_list/effects/dl_color_filter.h" #include "flutter/display_list/testing/dl_test_equality.h" namespace flutter { namespace testing { static const float kMatrix[20] = { 1, 2, 3, 4, 5, // 6, 7, 8, 9, 10, // 11, 12, 13, 14, 15, // 16, 17, 18, 19, 20, // }; TEST(DisplayListColorFilter, BlendConstructor) { DlBlendColorFilter filter(DlColor::kRed(), DlBlendMode::kDstATop); } TEST(DisplayListColorFilter, BlendShared) { DlBlendColorFilter filter(DlColor::kRed(), DlBlendMode::kDstATop); ASSERT_NE(filter.shared().get(), &filter); ASSERT_EQ(*filter.shared(), filter); } TEST(DisplayListColorFilter, BlendAsBlend) { DlBlendColorFilter filter(DlColor::kRed(), DlBlendMode::kDstATop); ASSERT_NE(filter.asBlend(), nullptr); ASSERT_EQ(filter.asBlend(), &filter); } TEST(DisplayListColorFilter, BlendContents) { DlBlendColorFilter filter(DlColor::kRed(), DlBlendMode::kDstATop); ASSERT_EQ(filter.color(), DlColor::kRed()); ASSERT_EQ(filter.mode(), DlBlendMode::kDstATop); } TEST(DisplayListColorFilter, BlendEquals) { DlBlendColorFilter filter1(DlColor::kRed(), DlBlendMode::kDstATop); DlBlendColorFilter filter2(DlColor::kRed(), DlBlendMode::kDstATop); TestEquals(filter1, filter2); } TEST(DisplayListColorFilter, BlendNotEquals) { DlBlendColorFilter filter1(DlColor::kRed(), DlBlendMode::kDstATop); DlBlendColorFilter filter2(DlColor::kBlue(), DlBlendMode::kDstATop); DlBlendColorFilter filter3(DlColor::kRed(), DlBlendMode::kDstIn); TestNotEquals(filter1, filter2, "Color differs"); TestNotEquals(filter1, filter3, "Blend mode differs"); } TEST(DisplayListColorFilter, NopBlendShouldNotCrash) { DlBlendColorFilter filter(DlColor::kTransparent(), DlBlendMode::kSrcOver); ASSERT_FALSE(filter.modifies_transparent_black()); } TEST(DisplayListColorFilter, MatrixConstructor) { DlMatrixColorFilter filter(kMatrix); } TEST(DisplayListColorFilter, MatrixShared) { DlMatrixColorFilter filter(kMatrix); ASSERT_NE(filter.shared().get(), &filter); ASSERT_EQ(*filter.shared(), filter); } TEST(DisplayListColorFilter, MatrixAsMatrix) { DlMatrixColorFilter filter(kMatrix); ASSERT_NE(filter.asMatrix(), nullptr); ASSERT_EQ(filter.asMatrix(), &filter); } TEST(DisplayListColorFilter, MatrixContents) { float matrix[20]; memcpy(matrix, kMatrix, sizeof(matrix)); DlMatrixColorFilter filter(matrix); // Test deref operator [] for (int i = 0; i < 20; i++) { ASSERT_EQ(filter[i], matrix[i]); } // Test get_matrix float matrix2[20]; filter.get_matrix(matrix2); for (int i = 0; i < 20; i++) { ASSERT_EQ(matrix2[i], matrix[i]); } // Test perturbing original array does not affect filter float original_value = matrix[4]; matrix[4] += 101; ASSERT_EQ(filter[4], original_value); } TEST(DisplayListColorFilter, MatrixEquals) { DlMatrixColorFilter filter1(kMatrix); DlMatrixColorFilter filter2(kMatrix); TestEquals(filter1, filter2); } TEST(DisplayListColorFilter, MatrixNotEquals) { float matrix[20]; memcpy(matrix, kMatrix, sizeof(matrix)); DlMatrixColorFilter filter1(matrix); matrix[4] += 101; DlMatrixColorFilter filter2(matrix); TestNotEquals(filter1, filter2, "Matrix differs"); } TEST(DisplayListColorFilter, NopMatrixShouldNotCrash) { float matrix[20] = { 1, 0, 0, 0, 0, // 0, 1, 0, 0, 0, // 0, 0, 1, 0, 0, // 0, 0, 0, 1, 0, // }; DlMatrixColorFilter filter(matrix); ASSERT_FALSE(filter.modifies_transparent_black()); } TEST(DisplayListColorFilter, SrgbToLinearConstructor) { DlSrgbToLinearGammaColorFilter filter; } TEST(DisplayListColorFilter, SrgbToLinearShared) { DlSrgbToLinearGammaColorFilter filter; ASSERT_NE(filter.shared().get(), &filter); ASSERT_EQ(*filter.shared(), filter); } TEST(DisplayListColorFilter, SrgbToLinearEquals) { DlSrgbToLinearGammaColorFilter filter1; DlSrgbToLinearGammaColorFilter filter2; TestEquals(filter1, filter2); TestEquals(filter1, *DlSrgbToLinearGammaColorFilter::kInstance); } TEST(DisplayListColorFilter, LinearToSrgbConstructor) { DlLinearToSrgbGammaColorFilter filter; } TEST(DisplayListColorFilter, LinearToSrgbShared) { DlLinearToSrgbGammaColorFilter filter; ASSERT_NE(filter.shared().get(), &filter); ASSERT_EQ(*filter.shared(), filter); } TEST(DisplayListColorFilter, LinearToSrgbEquals) { DlLinearToSrgbGammaColorFilter filter1; DlLinearToSrgbGammaColorFilter filter2; TestEquals(filter1, filter2); TestEquals(filter1, *DlLinearToSrgbGammaColorFilter::kInstance); } } // namespace testing } // namespace flutter
engine/display_list/effects/dl_color_filter_unittests.cc/0
{ "file_path": "engine/display_list/effects/dl_color_filter_unittests.cc", "repo_id": "engine", "token_count": 1826 }
161
// Copyright 2013 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. #ifndef FLUTTER_DISPLAY_LIST_GEOMETRY_DL_REGION_H_ #define FLUTTER_DISPLAY_LIST_GEOMETRY_DL_REGION_H_ #include "third_party/skia/include/core/SkRect.h" #include <memory> #include <vector> namespace flutter { /// Represents a region as a collection of non-overlapping rectangles. /// Implements a subset of SkRegion functionality optimized for quickly /// converting set of overlapping rectangles to non-overlapping rectangles. class DlRegion { public: /// Creates an empty region. DlRegion() = default; /// Creates region by bulk adding the rectangles. /// Matches SkRegion::op(rect, SkRegion::kUnion_Op) behavior. explicit DlRegion(const std::vector<SkIRect>& rects); /// Creates region covering area of a rectangle. explicit DlRegion(const SkIRect& rect); DlRegion(const DlRegion&) = default; DlRegion(DlRegion&&) = default; DlRegion& operator=(const DlRegion&) = default; DlRegion& operator=(DlRegion&&) = default; /// Creates union region of region a and b. /// Matches SkRegion a; a.op(b, SkRegion::kUnion_Op) behavior. static DlRegion MakeUnion(const DlRegion& a, const DlRegion& b); /// Creates intersection region of region a and b. /// Matches SkRegion a; a.op(b, SkRegion::kIntersect_Op) behavior. static DlRegion MakeIntersection(const DlRegion& a, const DlRegion& b); /// Returns list of non-overlapping rectangles that cover current region. /// If |deband| is false, each span line will result in separate rectangles, /// closely matching SkRegion::Iterator behavior. /// If |deband| is true, matching rectangles from adjacent span lines will be /// merged into single rectangle. std::vector<SkIRect> getRects(bool deband = true) const; /// Returns maximum and minimum axis values of rectangles in this region. /// If region is empty returns SKIRect::MakeEmpty(). const SkIRect& bounds() const { return bounds_; } /// Returns whether this region intersects with a rectangle. bool intersects(const SkIRect& rect) const; /// Returns whether this region intersects with another region. bool intersects(const DlRegion& region) const; /// Returns true if region is empty (contains no rectangles). bool isEmpty() const { return lines_.empty(); } /// Returns true if region is not empty and contains more than one rectangle. bool isComplex() const; /// Returns true if region can be represented by single rectangle or is /// empty. bool isSimple() const { return !isComplex(); } private: typedef std::uint32_t SpanChunkHandle; struct Span { int32_t left; int32_t right; Span() = default; Span(int32_t left, int32_t right) : left(left), right(right) {} }; /// Holds spans for the region. Having custom allocated memory that doesn't /// do zero initialization every time the buffer gets resized improves /// performance measurably. class SpanBuffer { public: SpanBuffer() = default; SpanBuffer(const SpanBuffer&); SpanBuffer(SpanBuffer&& m); SpanBuffer& operator=(const SpanBuffer&); SpanBuffer& operator=(SpanBuffer&& m); void reserve(size_t capacity); size_t capacity() const { return capacity_; } SpanChunkHandle storeChunk(const Span* begin, const Span* end); size_t getChunkSize(SpanChunkHandle handle) const; void getSpans(SpanChunkHandle handle, const DlRegion::Span*& begin, const DlRegion::Span*& end) const; ~SpanBuffer(); private: void setChunkSize(SpanChunkHandle handle, size_t size); size_t capacity_ = 0; size_t size_ = 0; // Spans for the region chunks. First span in each chunk contains the // chunk size. Span* spans_ = nullptr; }; struct SpanLine { int32_t top; int32_t bottom; SpanChunkHandle chunk_handle; }; void setRects(const std::vector<SkIRect>& rects); void appendLine(int32_t top, int32_t bottom, const Span* begin, const Span* end); void appendLine(int32_t top, int32_t bottom, const SpanBuffer& buffer, SpanChunkHandle handle) { const Span *begin, *end; buffer.getSpans(handle, begin, end); appendLine(top, bottom, begin, end); } typedef std::vector<Span> SpanVec; SpanLine makeLine(int32_t top, int32_t bottom, const SpanVec&); SpanLine makeLine(int32_t top, int32_t bottom, const Span* begin, const Span* end); static size_t unionLineSpans(std::vector<Span>& res, const SpanBuffer& a_buffer, SpanChunkHandle a_handle, const SpanBuffer& b_buffer, SpanChunkHandle b_handle); static size_t intersectLineSpans(std::vector<Span>& res, const SpanBuffer& a_buffer, SpanChunkHandle a_handle, const SpanBuffer& b_buffer, SpanChunkHandle b_handle); bool spansEqual(SpanLine& line, const Span* begin, const Span* end) const; static bool spansIntersect(const Span* begin1, const Span* end1, const Span* begin2, const Span* end2); static void getIntersectionIterators( const std::vector<SpanLine>& a_lines, const std::vector<SpanLine>& b_lines, std::vector<SpanLine>::const_iterator& a_it, std::vector<SpanLine>::const_iterator& b_it); std::vector<SpanLine> lines_; SkIRect bounds_ = SkIRect::MakeEmpty(); SpanBuffer span_buffer_; }; } // namespace flutter #endif // FLUTTER_DISPLAY_LIST_GEOMETRY_DL_REGION_H_
engine/display_list/geometry/dl_region.h/0
{ "file_path": "engine/display_list/geometry/dl_region.h", "repo_id": "engine", "token_count": 2304 }
162
// Copyright 2013 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. #include "flutter/display_list/skia/dl_sk_paint_dispatcher.h" #include <math.h> #include <optional> #include <type_traits> #include "flutter/display_list/dl_blend_mode.h" #include "flutter/display_list/skia/dl_sk_conversions.h" #include "flutter/fml/logging.h" #include "third_party/skia/include/core/SkColorFilter.h" namespace flutter { // clang-format off constexpr float kInvertColorMatrix[20] = { -1.0, 0, 0, 1.0, 0, 0, -1.0, 0, 1.0, 0, 0, 0, -1.0, 1.0, 0, 1.0, 1.0, 1.0, 1.0, 0 }; // clang-format on void DlSkPaintDispatchHelper::save_opacity(SkScalar child_opacity) { save_stack_.emplace_back(opacity_); set_opacity(child_opacity); } void DlSkPaintDispatchHelper::restore_opacity() { if (save_stack_.empty()) { return; } set_opacity(save_stack_.back().opacity); save_stack_.pop_back(); } void DlSkPaintDispatchHelper::setAntiAlias(bool aa) { paint_.setAntiAlias(aa); } void DlSkPaintDispatchHelper::setInvertColors(bool invert) { invert_colors_ = invert; paint_.setColorFilter(makeColorFilter()); } void DlSkPaintDispatchHelper::setStrokeCap(DlStrokeCap cap) { paint_.setStrokeCap(ToSk(cap)); } void DlSkPaintDispatchHelper::setStrokeJoin(DlStrokeJoin join) { paint_.setStrokeJoin(ToSk(join)); } void DlSkPaintDispatchHelper::setDrawStyle(DlDrawStyle style) { paint_.setStyle(ToSk(style)); } void DlSkPaintDispatchHelper::setStrokeWidth(SkScalar width) { paint_.setStrokeWidth(width); } void DlSkPaintDispatchHelper::setStrokeMiter(SkScalar limit) { paint_.setStrokeMiter(limit); } void DlSkPaintDispatchHelper::setColor(DlColor color) { current_color_ = ToSk(color); paint_.setColor(ToSk(color)); if (has_opacity()) { paint_.setAlphaf(paint_.getAlphaf() * opacity()); } } void DlSkPaintDispatchHelper::setBlendMode(DlBlendMode mode) { paint_.setBlendMode(ToSk(mode)); } void DlSkPaintDispatchHelper::setColorSource(const DlColorSource* source) { // On the Impeller backend, we only support dithering of *gradients*, and // so we need to set the dither flag whenever we render a gradient. // // In this method we can determine whether or not the source is a gradient, // but we don't have the other half of the information which is what // rendering op is being performed. So, we simply record whether the // source is a gradient here and let the |paint()| method figure out // the rest (i.e. whether the color source will be used). color_source_gradient_ = source && source->isGradient(); paint_.setShader(ToSk(source)); } void DlSkPaintDispatchHelper::setImageFilter(const DlImageFilter* filter) { paint_.setImageFilter(ToSk(filter)); } void DlSkPaintDispatchHelper::setColorFilter(const DlColorFilter* filter) { sk_color_filter_ = ToSk(filter); paint_.setColorFilter(makeColorFilter()); } void DlSkPaintDispatchHelper::setPathEffect(const DlPathEffect* effect) { paint_.setPathEffect(ToSk(effect)); } void DlSkPaintDispatchHelper::setMaskFilter(const DlMaskFilter* filter) { paint_.setMaskFilter(ToSk(filter)); } sk_sp<SkColorFilter> DlSkPaintDispatchHelper::makeColorFilter() const { if (!invert_colors_) { return sk_color_filter_; } sk_sp<SkColorFilter> invert_filter = SkColorFilters::Matrix(kInvertColorMatrix); if (sk_color_filter_) { invert_filter = invert_filter->makeComposed(sk_color_filter_); } return invert_filter; } } // namespace flutter
engine/display_list/skia/dl_sk_paint_dispatcher.cc/0
{ "file_path": "engine/display_list/skia/dl_sk_paint_dispatcher.cc", "repo_id": "engine", "token_count": 1308 }
163
// Copyright 2013 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. #ifndef FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_SOFTWARE_H_ #define FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_SOFTWARE_H_ #include "flutter/display_list/testing/dl_test_surface_provider.h" namespace flutter { namespace testing { class DlSoftwareSurfaceProvider : public DlSurfaceProvider { public: DlSoftwareSurfaceProvider() = default; virtual ~DlSoftwareSurfaceProvider() = default; bool InitializeSurface(size_t width, size_t height, PixelFormat format) override; std::shared_ptr<DlSurfaceInstance> GetPrimarySurface() const override { return primary_; } std::shared_ptr<DlSurfaceInstance> MakeOffscreenSurface( size_t width, size_t height, PixelFormat format) const override; const std::string backend_name() const override { return "Software"; } BackendType backend_type() const override { return kSoftwareBackend; } bool supports(PixelFormat format) const override { return true; } private: std::shared_ptr<DlSurfaceInstance> primary_; }; } // namespace testing } // namespace flutter #endif // FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_SOFTWARE_H_
engine/display_list/testing/dl_test_surface_software.h/0
{ "file_path": "engine/display_list/testing/dl_test_surface_software.h", "repo_id": "engine", "token_count": 471 }
164
# Copyright 2013 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. declare_args() { # The example embedders may use dependencies not suitable on all platforms. # Use this GN arg to enable building the examples. build_embedder_examples = false }
engine/examples/examples.gni/0
{ "file_path": "engine/examples/examples.gni", "repo_id": "engine", "token_count": 92 }
165
# Copyright 2013 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. executable("vulkan_glfw") { output_name = "embedder_example_vulkan" configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code" ] sources = [ "src/main.cc" ] deps = [ "//flutter/shell/platform/embedder:embedder", "//flutter/third_party/glfw", "//flutter/third_party/vulkan-deps/vulkan-headers/src:vulkan_headers", ] }
engine/examples/vulkan_glfw/BUILD.gn/0
{ "file_path": "engine/examples/vulkan_glfw/BUILD.gn", "repo_id": "engine", "token_count": 204 }
166
// Copyright 2013 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. #ifndef FLUTTER_FLOW_FLOW_TEST_UTILS_H_ #define FLUTTER_FLOW_FLOW_TEST_UTILS_H_ #include <string> namespace flutter { const std::string& GetGoldenDir(); void SetGoldenDir(const std::string& dir); const std::string& GetFontFile(); void SetFontFile(const std::string& dir); } // namespace flutter #endif // FLUTTER_FLOW_FLOW_TEST_UTILS_H_
engine/flow/flow_test_utils.h/0
{ "file_path": "engine/flow/flow_test_utils.h", "repo_id": "engine", "token_count": 182 }
167
// Copyright 2013 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. #include "flutter/flow/layers/clip_rect_layer.h" namespace flutter { ClipRectLayer::ClipRectLayer(const SkRect& clip_rect, Clip clip_behavior) : ClipShapeLayer(clip_rect, clip_behavior) {} const SkRect& ClipRectLayer::clip_shape_bounds() const { return clip_shape(); } void ClipRectLayer::ApplyClip(LayerStateStack::MutatorContext& mutator) const { mutator.clipRect(clip_shape(), clip_behavior() != Clip::kHardEdge); } } // namespace flutter
engine/flow/layers/clip_rect_layer.cc/0
{ "file_path": "engine/flow/layers/clip_rect_layer.cc", "repo_id": "engine", "token_count": 197 }
168
// Copyright 2013 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. #include "flutter/flow/layers/display_list_raster_cache_item.h" #include <optional> #include <utility> #include "flutter/display_list/benchmarking/dl_complexity.h" #include "flutter/display_list/display_list.h" #include "flutter/flow/layers/layer.h" #include "flutter/flow/raster_cache.h" #include "flutter/flow/raster_cache_item.h" #include "flutter/flow/raster_cache_key.h" #include "flutter/flow/raster_cache_util.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { static bool IsDisplayListWorthRasterizing( const DisplayList* display_list, bool will_change, bool is_complex, DisplayListComplexityCalculator* complexity_calculator) { if (will_change) { // If the display list is going to change in the future, there is no point // in doing to extra work to rasterize. return false; } if (display_list == nullptr || !RasterCacheUtil::CanRasterizeRect(display_list->bounds())) { // No point in deciding whether the display list is worth rasterizing if it // cannot be rasterized at all. return false; } if (is_complex) { // The caller seems to have extra information about the display list and // thinks the display list is always worth rasterizing. return true; } unsigned int complexity_score = complexity_calculator->Compute(display_list); return complexity_calculator->ShouldBeCached(complexity_score); } DisplayListRasterCacheItem::DisplayListRasterCacheItem( const sk_sp<DisplayList>& display_list, const SkPoint& offset, bool is_complex, bool will_change) : RasterCacheItem(RasterCacheKeyID(display_list->unique_id(), RasterCacheKeyType::kDisplayList), CacheState::kCurrent), display_list_(display_list), offset_(offset), is_complex_(is_complex), will_change_(will_change) {} std::unique_ptr<DisplayListRasterCacheItem> DisplayListRasterCacheItem::Make( const sk_sp<DisplayList>& display_list, const SkPoint& offset, bool is_complex, bool will_change) { return std::make_unique<DisplayListRasterCacheItem>(display_list, offset, is_complex, will_change); } void DisplayListRasterCacheItem::PrerollSetup(PrerollContext* context, const SkMatrix& matrix) { cache_state_ = CacheState::kNone; DisplayListComplexityCalculator* complexity_calculator = context->gr_context ? DisplayListComplexityCalculator::GetForBackend( context->gr_context->backend()) : DisplayListComplexityCalculator::GetForSoftware(); if (!IsDisplayListWorthRasterizing(display_list(), will_change_, is_complex_, complexity_calculator)) { // We only deal with display lists that are worthy of rasterization. return; } transformation_matrix_ = matrix; transformation_matrix_.preTranslate(offset_.x(), offset_.y()); if (!transformation_matrix_.invert(nullptr)) { // The matrix was singular. No point in going further. return; } if (context->raster_cached_entries && context->raster_cache) { context->raster_cached_entries->push_back(this); cache_state_ = CacheState::kCurrent; } return; } void DisplayListRasterCacheItem::PrerollFinalize(PrerollContext* context, const SkMatrix& matrix) { if (cache_state_ == CacheState::kNone || !context->raster_cache || !context->raster_cached_entries) { return; } auto* raster_cache = context->raster_cache; SkRect bounds = display_list_->bounds().makeOffset(offset_.x(), offset_.y()); bool visible = !context->state_stack.content_culled(bounds); RasterCache::CacheInfo cache_info = raster_cache->MarkSeen(key_id_, matrix, visible); if (!visible || cache_info.accesses_since_visible <= raster_cache->access_threshold()) { cache_state_ = kNone; } else { if (cache_info.has_image) { context->renderable_state_flags |= LayerStateStack::kCallerCanApplyOpacity; } cache_state_ = kCurrent; } return; } bool DisplayListRasterCacheItem::Draw(const PaintContext& context, const DlPaint* paint) const { return Draw(context, context.canvas, paint); } bool DisplayListRasterCacheItem::Draw(const PaintContext& context, DlCanvas* canvas, const DlPaint* paint) const { if (!context.raster_cache || !canvas) { return false; } if (cache_state_ == CacheState::kCurrent) { return context.raster_cache->Draw(key_id_, *canvas, paint, context.rendering_above_platform_view); } return false; } static const auto* flow_type = "RasterCacheFlow::DisplayList"; bool DisplayListRasterCacheItem::TryToPrepareRasterCache( const PaintContext& context, bool parent_cached) const { // If we don't have raster_cache we should not cache the current display_list. // If the current node's ancestor has been cached we also should not cache the // current node. In the current frame, the raster_cache will collect all // display_list or picture_list to calculate the memory they used, we // shouldn't cache the current node if the memory is more significant than the // limit. auto id = GetId(); FML_DCHECK(id.has_value()); if (cache_state_ == kNone || !context.raster_cache || parent_cached || !context.raster_cache->GenerateNewCacheInThisFrame() || !id.has_value()) { return false; } SkRect bounds = display_list_->bounds().makeOffset(offset_.x(), offset_.y()); RasterCache::Context r_context = { // clang-format off .gr_context = context.gr_context, .dst_color_space = context.dst_color_space, .matrix = transformation_matrix_, .logical_rect = bounds, .flow_type = flow_type, // clang-format on }; return context.raster_cache->UpdateCacheEntry( id.value(), r_context, [display_list = display_list_](DlCanvas* canvas) { canvas->DrawDisplayList(display_list); }, display_list_->rtree()); } } // namespace flutter
engine/flow/layers/display_list_raster_cache_item.cc/0
{ "file_path": "engine/flow/layers/display_list_raster_cache_item.cc", "repo_id": "engine", "token_count": 2555 }
169
// Copyright 2013 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. #ifndef FLUTTER_FLOW_LAYERS_OFFSCREEN_SURFACE_H_ #define FLUTTER_FLOW_LAYERS_OFFSCREEN_SURFACE_H_ #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "flutter/display_list/dl_canvas.h" #include "flutter/display_list/skia/dl_sk_canvas.h" #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkSurface.h" class GrDirectContext; namespace flutter { class OffscreenSurface { public: explicit OffscreenSurface(GrDirectContext* surface_context, const SkISize& size); ~OffscreenSurface() = default; sk_sp<SkData> GetRasterData(bool compressed) const; DlCanvas* GetCanvas(); bool IsValid() const; private: sk_sp<SkSurface> offscreen_surface_; DlSkCanvasAdapter adapter_; FML_DISALLOW_COPY_AND_ASSIGN(OffscreenSurface); }; } // namespace flutter #endif // FLUTTER_FLOW_LAYERS_OFFSCREEN_SURFACE_H_
engine/flow/layers/offscreen_surface.h/0
{ "file_path": "engine/flow/layers/offscreen_surface.h", "repo_id": "engine", "token_count": 463 }
170
// Copyright 2013 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. #include "flutter/flow/layers/texture_layer.h" #include "flutter/flow/testing/diff_context_test.h" #include "flutter/flow/testing/layer_test.h" #include "flutter/flow/testing/mock_layer.h" #include "flutter/flow/testing/mock_texture.h" #include "flutter/fml/macros.h" #include "flutter/testing/display_list_testing.h" namespace flutter { namespace testing { using TextureLayerTest = LayerTest; TEST_F(TextureLayerTest, InvalidTexture) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); const SkSize layer_size = SkSize::Make(8.0f, 8.0f); auto layer = std::make_shared<TextureLayer>( layer_offset, layer_size, 0, false, DlImageSampling::kNearestNeighbor); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), (SkRect::MakeSize(layer_size) .makeOffset(layer_offset.fX, layer_offset.fY))); EXPECT_TRUE(layer->needs_painting(paint_context())); layer->Paint(display_list_paint_context()); EXPECT_TRUE(display_list()->Equals(DisplayList())); } #ifndef NDEBUG TEST_F(TextureLayerTest, PaintingEmptyLayerDies) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); const SkSize layer_size = SkSize::Make(0.0f, 0.0f); const int64_t texture_id = 0; auto mock_texture = std::make_shared<MockTexture>(texture_id); auto layer = std::make_shared<TextureLayer>(layer_offset, layer_size, texture_id, false, DlImageSampling::kNearestNeighbor); // Ensure the texture is located by the Layer. preroll_context()->texture_registry->RegisterTexture(mock_texture); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), kEmptyRect); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(TextureLayerTest, PaintBeforePrerollDies) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); const SkSize layer_size = SkSize::Make(8.0f, 8.0f); const int64_t texture_id = 0; auto mock_texture = std::make_shared<MockTexture>(texture_id); auto layer = std::make_shared<TextureLayer>( layer_offset, layer_size, texture_id, false, DlImageSampling::kLinear); // Ensure the texture is located by the Layer. preroll_context()->texture_registry->RegisterTexture(mock_texture); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } #endif TEST_F(TextureLayerTest, PaintingWithLinearSampling) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); const SkSize layer_size = SkSize::Make(8.0f, 8.0f); const SkRect layer_bounds = SkRect::MakeSize(layer_size).makeOffset(layer_offset.fX, layer_offset.fY); const int64_t texture_id = 0; const auto texture_image = MockTexture::MakeTestTexture(20, 20, 5); auto mock_texture = std::make_shared<MockTexture>(texture_id, texture_image); auto layer = std::make_shared<TextureLayer>( layer_offset, layer_size, texture_id, false, DlImageSampling::kLinear); // Ensure the texture is located by the Layer. preroll_context()->texture_registry->RegisterTexture(mock_texture); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), layer_bounds); EXPECT_TRUE(layer->needs_painting(paint_context())); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (Texture)layer::Paint */ { expected_builder.DrawImageRect(texture_image, layer_bounds, DlImageSampling::kLinear); } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } using TextureLayerDiffTest = DiffContextTest; TEST_F(TextureLayerDiffTest, TextureInRetainedLayer) { MockLayerTree tree1; auto container = std::make_shared<ContainerLayer>(); tree1.root()->Add(container); auto layer = std::make_shared<TextureLayer>(SkPoint::Make(0, 0), SkSize::Make(100, 100), 0, false, DlImageSampling::kLinear); container->Add(layer); MockLayerTree tree2; tree2.root()->Add(container); // retained layer auto damage = DiffLayerTree(tree1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 100, 100)); damage = DiffLayerTree(tree2, tree1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 100, 100)); } TEST_F(TextureLayerTest, OpacityInheritance) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); const SkSize layer_size = SkSize::Make(8.0f, 8.0f); const SkRect layer_bounds = SkRect::MakeSize(layer_size).makeOffset(layer_offset.fX, layer_offset.fY); const int64_t texture_id = 0; const auto texture_image = MockTexture::MakeTestTexture(20, 20, 5); auto mock_texture = std::make_shared<MockTexture>(texture_id, texture_image); SkAlpha alpha = 0x7f; auto texture_layer = std::make_shared<TextureLayer>( layer_offset, layer_size, texture_id, false, DlImageSampling::kLinear); auto layer = std::make_shared<OpacityLayer>(alpha, SkPoint::Make(0.0f, 0.0f)); layer->Add(texture_layer); // Ensure the texture is located by the Layer. PrerollContext* context = preroll_context(); context->texture_registry->RegisterTexture(mock_texture); // The texture layer always reports opacity compatibility. texture_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); // Reset has_texture_layer since it is not supposed to be sent as we // descend a tree in Preroll, but it was set by the previous test. context->has_texture_layer = false; layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); DlPaint texture_paint; texture_paint.setAlpha(alpha); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (Opacity)layer::Paint */ { expected_builder.Save(); { /* texture_layer::Paint */ { expected_builder.DrawImageRect(texture_image, layer_bounds, DlImageSampling::kLinear, &texture_paint); } } expected_builder.Restore(); } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } // namespace testing } // namespace flutter
engine/flow/layers/texture_layer_unittests.cc/0
{ "file_path": "engine/flow/layers/texture_layer_unittests.cc", "repo_id": "engine", "token_count": 2548 }
171
// Copyright 2013 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. #ifndef FLUTTER_FLOW_RASTER_CACHE_UTIL_H_ #define FLUTTER_FLOW_RASTER_CACHE_UTIL_H_ #include "flutter/fml/logging.h" #include "include/core/SkM44.h" #include "include/core/SkMatrix.h" #include "include/core/SkRect.h" namespace flutter { struct RasterCacheUtil { // The default max number of picture and display list raster caches to be // generated per frame. Generating too many caches in one frame may cause jank // on that frame. This limit allows us to throttle the cache and distribute // the work across multiple frames. static constexpr int kDefaultPictureAndDisplayListCacheLimitPerFrame = 3; // The ImageFilterLayer might cache the filtered output of this layer // if the layer remains stable (if it is not animating for instance). // If the ImageFilterLayer is not the same between rendered frames, // though, it will cache its children instead and filter their cached // output on the fly. // Caching just the children saves the time to render them and also // avoids a rendering surface switch to draw them. // Caching the layer itself avoids all of that and additionally avoids // the cost of applying the filter, but can be worse than caching the // children if the filter itself is not stable from frame to frame. // This constant controls how many times we will Preroll and Paint this // same ImageFilterLayer before we consider the layer and filter to be // stable enough to switch from caching the children to caching the // filtered output of this layer. static constexpr int kMinimumRendersBeforeCachingFilterLayer = 3; static bool CanRasterizeRect(const SkRect& cull_rect) { if (cull_rect.isEmpty()) { // No point in ever rasterizing an empty display list. return false; } if (!cull_rect.isFinite()) { // Cannot attempt to rasterize into an infinitely large surface. FML_LOG(INFO) << "Attempted to raster cache non-finite display list"; return false; } return true; } static SkRect GetDeviceBounds(const SkRect& rect, const SkMatrix& ctm) { SkRect device_rect; ctm.mapRect(&device_rect, rect); return device_rect; } static SkRect GetRoundedOutDeviceBounds(const SkRect& rect, const SkMatrix& ctm) { SkRect device_rect; ctm.mapRect(&device_rect, rect); device_rect.roundOut(&device_rect); return device_rect; } /** * @brief Snap the translation components of the matrix to integers. * * The snapping will only happen if the matrix only has scale and translation * transformations. This is used, along with GetRoundedOutDeviceBounds, to * ensure that the textures drawn by the raster cache are exactly aligned to * physical pixels. Any layers that participate in raster caching must align * themselves to physical pixels even when not cached to prevent a change in * apparent location if caching is later applied. * * @param ctm the current transformation matrix. * @return SkMatrix the snapped transformation matrix. */ static SkMatrix GetIntegralTransCTM(const SkMatrix& ctm) { SkMatrix integral; return ComputeIntegralTransCTM(ctm, &integral) ? integral : ctm; } /** * @brief Snap the translation components of the |in| matrix to integers * and store the snapped matrix in |out|. * * The snapping will only happen if the matrix only has scale and translation * transformations. This is used, along with GetRoundedOutDeviceBounds, to * ensure that the textures drawn by the raster cache are exactly aligned to * physical pixels. Any layers that participate in raster caching must align * themselves to physical pixels even when not cached to prevent a change in * apparent location if caching is later applied. * * The |out| matrix will not be modified if this method returns false. * * @param in the current transformation matrix. * @param out the storage for the snapped matrix. * @return true if the integral modification was needed, false otherwise. */ static bool ComputeIntegralTransCTM(const SkMatrix& in, SkMatrix* out); /** * @brief Snap the translation components of the matrix to integers. * * The snapping will only happen if the matrix only has scale and translation * transformations. This is used, along with GetRoundedOutDeviceBounds, to * ensure that the textures drawn by the raster cache are exactly aligned to * physical pixels. Any layers that participate in raster caching must align * themselves to physical pixels even when not cached to prevent a change in * apparent location if caching is later applied. * * @param ctm the current transformation matrix. * @return SkM44 the snapped transformation matrix. */ static SkM44 GetIntegralTransCTM(const SkM44& ctm) { SkM44 integral; return ComputeIntegralTransCTM(ctm, &integral) ? integral : ctm; } /** * @brief Snap the translation components of the |in| matrix to integers * and store the snapped matrix in |out|. * * The snapping will only happen if the matrix only has scale and translation * transformations. This is used, along with GetRoundedOutDeviceBounds, to * ensure that the textures drawn by the raster cache are exactly aligned to * physical pixels. Any layers that participate in raster caching must align * themselves to physical pixels even when not cached to prevent a change in * apparent location if caching is later applied. * * The |out| matrix will not be modified if this method returns false. * * @param in the current transformation matrix. * @param out the storage for the snapped matrix. * @return true if the integral modification was needed, false otherwise. */ static bool ComputeIntegralTransCTM(const SkM44& in, SkM44* out); }; } // namespace flutter #endif // FLUTTER_FLOW_RASTER_CACHE_UTIL_H_
engine/flow/raster_cache_util.h/0
{ "file_path": "engine/flow/raster_cache_util.h", "repo_id": "engine", "token_count": 1768 }
172
// Copyright 2013 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. #include "diff_context_test.h" #include <utility> #include "flutter/display_list/dl_builder.h" namespace flutter { namespace testing { DiffContextTest::DiffContextTest() {} Damage DiffContextTest::DiffLayerTree(MockLayerTree& layer_tree, const MockLayerTree& old_layer_tree, const SkIRect& additional_damage, int horizontal_clip_alignment, int vertical_clip_alignment, bool use_raster_cache, bool impeller_enabled) { FML_CHECK(layer_tree.size() == old_layer_tree.size()); DiffContext dc(layer_tree.size(), layer_tree.paint_region_map(), old_layer_tree.paint_region_map(), use_raster_cache, impeller_enabled); dc.PushCullRect( SkRect::MakeIWH(layer_tree.size().width(), layer_tree.size().height())); layer_tree.root()->Diff(&dc, old_layer_tree.root()); return dc.ComputeDamage(additional_damage, horizontal_clip_alignment, vertical_clip_alignment); } sk_sp<DisplayList> DiffContextTest::CreateDisplayList(const SkRect& bounds, DlColor color) { DisplayListBuilder builder; builder.DrawRect(bounds, DlPaint().setColor(color)); return builder.Build(); } std::shared_ptr<DisplayListLayer> DiffContextTest::CreateDisplayListLayer( const sk_sp<DisplayList>& display_list, const SkPoint& offset) { return std::make_shared<DisplayListLayer>(offset, display_list, false, false); } std::shared_ptr<ContainerLayer> DiffContextTest::CreateContainerLayer( std::initializer_list<std::shared_ptr<Layer>> layers) { auto res = std::make_shared<ContainerLayer>(); for (const auto& l : layers) { res->Add(l); } return res; } std::shared_ptr<OpacityLayer> DiffContextTest::CreateOpacityLater( std::initializer_list<std::shared_ptr<Layer>> layers, SkAlpha alpha, const SkPoint& offset) { auto res = std::make_shared<OpacityLayer>(alpha, offset); for (const auto& l : layers) { res->Add(l); } return res; } } // namespace testing } // namespace flutter
engine/flow/testing/diff_context_test.cc/0
{ "file_path": "engine/flow/testing/diff_context_test.cc", "repo_id": "engine", "token_count": 1027 }
173
// Copyright 2013 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. #include "flutter/fml/ascii_trie.h" #include "gtest/gtest.h" using fml::AsciiTrie; TEST(AsciiTableTest, Simple) { AsciiTrie trie; auto entries = std::vector<std::string>{"foo"}; trie.Fill(entries); ASSERT_TRUE(trie.Query("foobar")); ASSERT_FALSE(trie.Query("google")); } TEST(AsciiTableTest, ExactMatch) { AsciiTrie trie; auto entries = std::vector<std::string>{"foo"}; trie.Fill(entries); ASSERT_TRUE(trie.Query("foo")); } TEST(AsciiTableTest, Empty) { AsciiTrie trie; ASSERT_TRUE(trie.Query("foo")); } TEST(AsciiTableTest, MultipleEntries) { AsciiTrie trie; auto entries = std::vector<std::string>{"foo", "bar"}; trie.Fill(entries); ASSERT_TRUE(trie.Query("foozzz")); ASSERT_TRUE(trie.Query("barzzz")); }
engine/fml/ascii_trie_unittests.cc/0
{ "file_path": "engine/fml/ascii_trie_unittests.cc", "repo_id": "engine", "token_count": 378 }
174
// Copyright 2013 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. #ifndef FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_ #define FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_ #include <condition_variable> #include <map> #include <queue> #include <thread> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/fml/task_runner.h" namespace fml { class ConcurrentTaskRunner; class ConcurrentMessageLoop : public std::enable_shared_from_this<ConcurrentMessageLoop> { public: static std::shared_ptr<ConcurrentMessageLoop> Create( size_t worker_count = std::thread::hardware_concurrency()); virtual ~ConcurrentMessageLoop(); size_t GetWorkerCount() const; std::shared_ptr<ConcurrentTaskRunner> GetTaskRunner(); void Terminate(); void PostTaskToAllWorkers(const fml::closure& task); bool RunsTasksOnCurrentThread(); protected: explicit ConcurrentMessageLoop(size_t worker_count); virtual void ExecuteTask(const fml::closure& task); private: friend ConcurrentTaskRunner; size_t worker_count_ = 0; std::vector<std::thread> workers_; std::mutex tasks_mutex_; std::condition_variable tasks_condition_; std::queue<fml::closure> tasks_; std::vector<std::thread::id> worker_thread_ids_; std::map<std::thread::id, std::vector<fml::closure>> thread_tasks_; bool shutdown_ = false; void WorkerMain(); void PostTask(const fml::closure& task); bool HasThreadTasksLocked() const; std::vector<fml::closure> GetThreadTasksLocked(); FML_DISALLOW_COPY_AND_ASSIGN(ConcurrentMessageLoop); }; class ConcurrentTaskRunner : public BasicTaskRunner { public: explicit ConcurrentTaskRunner(std::weak_ptr<ConcurrentMessageLoop> weak_loop); virtual ~ConcurrentTaskRunner(); void PostTask(const fml::closure& task) override; private: friend ConcurrentMessageLoop; std::weak_ptr<ConcurrentMessageLoop> weak_loop_; FML_DISALLOW_COPY_AND_ASSIGN(ConcurrentTaskRunner); }; } // namespace fml #endif // FLUTTER_FML_CONCURRENT_MESSAGE_LOOP_H_
engine/fml/concurrent_message_loop.h/0
{ "file_path": "engine/fml/concurrent_message_loop.h", "repo_id": "engine", "token_count": 702 }
175
// Copyright 2013 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. #ifndef FLUTTER_FML_HASH_COMBINE_H_ #define FLUTTER_FML_HASH_COMBINE_H_ #include <functional> namespace fml { template <class Type> constexpr void HashCombineSeed(std::size_t& seed, Type arg) { seed ^= std::hash<Type>{}(arg) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } template <class Type, class... Rest> constexpr void HashCombineSeed(std::size_t& seed, Type arg, Rest... other_args) { HashCombineSeed(seed, arg); HashCombineSeed(seed, other_args...); } [[nodiscard]] constexpr std::size_t HashCombine() { return 0xdabbad00; } template <class... Type> [[nodiscard]] constexpr std::size_t HashCombine(Type... args) { std::size_t seed = HashCombine(); HashCombineSeed(seed, args...); return seed; } } // namespace fml #endif // FLUTTER_FML_HASH_COMBINE_H_
engine/fml/hash_combine.h/0
{ "file_path": "engine/fml/hash_combine.h", "repo_id": "engine", "token_count": 416 }
176
// Copyright 2013 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. #include "flutter/fml/mapping.h" #include <algorithm> #include <cstring> #include <memory> #include <sstream> namespace fml { // FileMapping uint8_t* FileMapping::GetMutableMapping() { return mutable_mapping_; } std::unique_ptr<FileMapping> FileMapping::CreateReadOnly( const std::string& path) { return CreateReadOnly(OpenFile(path.c_str(), false, FilePermission::kRead), ""); } std::unique_ptr<FileMapping> FileMapping::CreateReadOnly( const fml::UniqueFD& base_fd, const std::string& sub_path) { if (!sub_path.empty()) { return CreateReadOnly( OpenFile(base_fd, sub_path.c_str(), false, FilePermission::kRead), ""); } auto mapping = std::make_unique<FileMapping>( base_fd, std::initializer_list<Protection>{Protection::kRead}); if (!mapping->IsValid()) { return nullptr; } return mapping; } std::unique_ptr<FileMapping> FileMapping::CreateReadExecute( const std::string& path) { return CreateReadExecute( OpenFile(path.c_str(), false, FilePermission::kRead)); } std::unique_ptr<FileMapping> FileMapping::CreateReadExecute( const fml::UniqueFD& base_fd, const std::string& sub_path) { if (!sub_path.empty()) { return CreateReadExecute( OpenFile(base_fd, sub_path.c_str(), false, FilePermission::kRead), ""); } auto mapping = std::make_unique<FileMapping>( base_fd, std::initializer_list<Protection>{Protection::kRead, Protection::kExecute}); if (!mapping->IsValid()) { return nullptr; } return mapping; } // Data Mapping DataMapping::DataMapping(std::vector<uint8_t> data) : data_(std::move(data)) {} DataMapping::DataMapping(const std::string& string) : data_(string.begin(), string.end()) {} DataMapping::~DataMapping() = default; size_t DataMapping::GetSize() const { return data_.size(); } const uint8_t* DataMapping::GetMapping() const { return data_.data(); } bool DataMapping::IsDontNeedSafe() const { return false; } // NonOwnedMapping NonOwnedMapping::NonOwnedMapping(const uint8_t* data, size_t size, const ReleaseProc& release_proc, bool dontneed_safe) : data_(data), size_(size), release_proc_(release_proc), dontneed_safe_(dontneed_safe) {} NonOwnedMapping::~NonOwnedMapping() { if (release_proc_) { release_proc_(data_, size_); } } size_t NonOwnedMapping::GetSize() const { return size_; } const uint8_t* NonOwnedMapping::GetMapping() const { return data_; } bool NonOwnedMapping::IsDontNeedSafe() const { return dontneed_safe_; } // MallocMapping MallocMapping::MallocMapping() : data_(nullptr), size_(0) {} MallocMapping::MallocMapping(uint8_t* data, size_t size) : data_(data), size_(size) {} MallocMapping::MallocMapping(fml::MallocMapping&& mapping) : data_(mapping.data_), size_(mapping.size_) { mapping.data_ = nullptr; mapping.size_ = 0; } MallocMapping::~MallocMapping() { free(data_); data_ = nullptr; } MallocMapping MallocMapping::Copy(const void* begin, size_t length) { auto result = MallocMapping(reinterpret_cast<uint8_t*>(malloc(length)), length); FML_CHECK(result.GetMapping() != nullptr); memcpy(const_cast<uint8_t*>(result.GetMapping()), begin, length); return result; } size_t MallocMapping::GetSize() const { return size_; } const uint8_t* MallocMapping::GetMapping() const { return data_; } bool MallocMapping::IsDontNeedSafe() const { return false; } uint8_t* MallocMapping::Release() { uint8_t* result = data_; data_ = nullptr; size_ = 0; return result; } // Symbol Mapping SymbolMapping::SymbolMapping(fml::RefPtr<fml::NativeLibrary> native_library, const char* symbol_name) : native_library_(std::move(native_library)) { if (native_library_ && symbol_name != nullptr) { mapping_ = native_library_->ResolveSymbol(symbol_name); if (mapping_ == nullptr) { // Apparently, dart_bootstrap seems to account for the Mac behavior of // requiring the underscore prefixed symbol name on non-Mac platforms as // well. As a fallback, check the underscore prefixed variant of the // symbol name and allow callers to not have handle this on a per platform // toolchain quirk basis. std::stringstream underscore_symbol_name; underscore_symbol_name << "_" << symbol_name; mapping_ = native_library_->ResolveSymbol(underscore_symbol_name.str().c_str()); } } } SymbolMapping::~SymbolMapping() = default; size_t SymbolMapping::GetSize() const { return 0; } const uint8_t* SymbolMapping::GetMapping() const { return mapping_; } bool SymbolMapping::IsDontNeedSafe() const { return true; } } // namespace fml
engine/fml/mapping.cc/0
{ "file_path": "engine/fml/mapping.cc", "repo_id": "engine", "token_count": 1982 }
177
// Copyright 2013 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. #include "flutter/fml/memory/weak_ptr_internal.h" #include "flutter/fml/logging.h" namespace fml { namespace internal { WeakPtrFlag::WeakPtrFlag() : is_valid_(true) {} WeakPtrFlag::~WeakPtrFlag() { // Should be invalidated before destruction. FML_DCHECK(!is_valid_); } void WeakPtrFlag::Invalidate() { // Invalidation should happen exactly once. FML_DCHECK(is_valid_); is_valid_ = false; } } // namespace internal } // namespace fml
engine/fml/memory/weak_ptr_internal.cc/0
{ "file_path": "engine/fml/memory/weak_ptr_internal.cc", "repo_id": "engine", "token_count": 201 }
178