text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
#include "Generated.xcconfig"
devtools/case_study/code_size/optimized/code_size_package/ios/Flutter/Debug.xcconfig/0
{ "file_path": "devtools/case_study/code_size/optimized/code_size_package/ios/Flutter/Debug.xcconfig", "repo_id": "devtools", "token_count": 12 }
69
name: code_size_package description: A Flutter project demonstrating code size issues with packages. publish_to: none environment: sdk: ^3.0.0 dependencies: flutter: sdk: flutter steel_crypt: ^3.0.0 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true
devtools/case_study/code_size/optimized/code_size_package/pubspec.yaml/0
{ "file_path": "devtools/case_study/code_size/optimized/code_size_package/pubspec.yaml", "repo_id": "devtools", "token_count": 112 }
70
package com.example.memory_leaks_images import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
devtools/case_study/memory_leaks/images_1/android/app/src/main/kotlin/com/example/memory_leaks_images/MainActivity.kt/0
{ "file_path": "devtools/case_study/memory_leaks/images_1/android/app/src/main/kotlin/com/example/memory_leaks_images/MainActivity.kt", "repo_id": "devtools", "token_count": 41 }
71
package com.example.leaking_counter_1 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
devtools/case_study/memory_leaks/leaking_counter_1/android/app/src/main/kotlin/com/example/leaking_counter_1/MainActivity.kt/0
{ "file_path": "devtools/case_study/memory_leaks/leaking_counter_1/android/app/src/main/kotlin/com/example/leaking_counter_1/MainActivity.kt", "repo_id": "devtools", "token_count": 41 }
72
#include "ephemeral/Flutter-Generated.xcconfig"
devtools/case_study/memory_leaks/leaking_counter_1/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "devtools/case_study/memory_leaks/leaking_counter_1/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "devtools", "token_count": 19 }
73
buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' } } allprojects { repositories { google() jcenter() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir }
devtools/case_study/memory_leaks/memory_leak_app/android/build.gradle/0
{ "file_path": "devtools/case_study/memory_leaks/memory_leak_app/android/build.gradle", "repo_id": "devtools", "token_count": 194 }
74
# platform_channel A Flutter example that uses a platform channel
devtools/case_study/platform_channel/README.md/0
{ "file_path": "devtools/case_study/platform_channel/README.md", "repo_id": "devtools", "token_count": 16 }
75
--- redirect_to: https://flutter.dev/docs/development/tools/devtools/memory ---
devtools/docs/memory.md/0
{ "file_path": "devtools/docs/memory.md", "repo_id": "devtools", "token_count": 27 }
76
// 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:args/args.dart'; import 'package:web_benchmarks/analysis.dart'; import 'package:web_benchmarks/server.dart'; import '../test_infra/common.dart'; import '../test_infra/project_root_directory.dart'; import 'compare_benchmarks.dart'; import 'utils.dart'; /// Runs the DevTools web benchmarks and reports the benchmark data. /// /// To see available arguments, run this script with the `-h` flag. Future<void> main(List<String> args) async { if (args.isNotEmpty && args.first == '-h') { stdout.writeln(BenchmarkArgs._buildArgParser().usage); return; } final benchmarkArgs = BenchmarkArgs(args); final benchmarkResults = <BenchmarkResults>[]; for (var i = 0; i < benchmarkArgs.averageOf; i++) { stdout.writeln('Starting web benchmark tests (run #$i) ...'); benchmarkResults.add( await serveWebBenchmark( benchmarkAppDirectory: projectRootDirectory(), entryPoint: 'benchmark/test_infra/client.dart', compilationOptions: CompilationOptions( useWasm: benchmarkArgs.useWasm, renderer: benchmarkArgs.useSkwasm ? WebRenderer.skwasm : WebRenderer.canvaskit, ), treeShakeIcons: false, initialPage: benchmarkInitialPage, headless: !benchmarkArgs.useBrowser, ), ); stdout.writeln('Web benchmark tests finished (run #$i).'); } late final BenchmarkResults taskResult; if (benchmarkArgs.averageOf == 1) { taskResult = benchmarkResults.first; } else { stdout.writeln( 'Taking the average of ${benchmarkResults.length} benchmark runs.', ); taskResult = computeAverage(benchmarkResults); } final resultsAsMap = taskResult.toJson(); final resultsAsJsonString = const JsonEncoder.withIndent(' ').convert(resultsAsMap); if (benchmarkArgs.saveToFileLocation != null) { final location = Uri.parse(benchmarkArgs.saveToFileLocation!); File.fromUri(location) ..createSync() ..writeAsStringSync(resultsAsJsonString); } stdout ..writeln('==== Results ====') ..writeln(resultsAsJsonString) ..writeln('==== End of results ====') ..writeln(); final baselineSource = benchmarkArgs.baselineLocation; if (baselineSource != null) { final baselineFile = checkFileExists(baselineSource); if (baselineFile != null) { final baselineResults = BenchmarkResults.parse( jsonDecode(baselineFile.readAsStringSync()), ); final testResults = BenchmarkResults.parse( jsonDecode(resultsAsJsonString), ); compareBenchmarks( baselineResults, testResults, baselineSource: baselineSource, ); } } } class BenchmarkArgs { BenchmarkArgs(List<String> args) { argParser = _buildArgParser(); argResults = argParser.parse(args); } late final ArgParser argParser; late final ArgResults argResults; bool get useBrowser => argResults[_browserFlag]; bool get useWasm => argResults[_wasmFlag]; bool get useSkwasm => argResults[_skwasmFlag]; int get averageOf => int.parse(argResults[_averageOfOption]); String? get saveToFileLocation => argResults[_saveToFileOption]; String? get baselineLocation => argResults[_baselineOption]; static const _browserFlag = 'browser'; static const _wasmFlag = 'wasm'; static const _skwasmFlag = 'skwasm'; static const _saveToFileOption = 'save-to-file'; static const _baselineOption = 'baseline'; static const _averageOfOption = 'average-of'; /// Builds an arg parser for DevTools benchmarks. static ArgParser _buildArgParser() { return ArgParser() ..addFlag( _browserFlag, negatable: false, help: 'Runs the benchmark tests in browser mode (not headless mode).', ) ..addFlag( _wasmFlag, negatable: false, help: 'Runs the benchmark tests with dart2wasm', ) ..addFlag( _skwasmFlag, negatable: false, help: 'Runs the benchmark tests with the skwasm renderer instead of canvaskit.', ) ..addOption( _saveToFileOption, help: 'Saves the benchmark results to a JSON file at the given path.', valueHelp: '/Users/me/Downloads/output.json', ) ..addOption( _baselineOption, help: 'The baseline benchmark data to compare this test run to. The ' 'baseline file should be created by running this script with the ' '$_saveToFileOption in a separate test run.', valueHelp: '/Users/me/Downloads/baseline.json', ) ..addOption( _averageOfOption, defaultsTo: '1', help: 'The number of times to run the benchmark. The returned results ' 'will be the average of all the benchmark runs when this value is ' 'greater than 1.', valueHelp: '5', ); } }
devtools/packages/devtools_app/benchmark/scripts/run_benchmarks.dart/0
{ "file_path": "devtools/packages/devtools_app/benchmark/scripts/run_benchmarks.dart", "repo_id": "devtools", "token_count": 1902 }
77
// 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/performance/panes/timeline_events/timeline_events_view.dart'; import 'package:devtools_test/helpers.dart'; import 'package:devtools_test/integration_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; // To run: // dart run integration_test/run_tests.dart --target=integration_test/test/live_connection/performance_screen_event_recording_test.dart void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); late TestApp testApp; setUpAll(() { testApp = TestApp.fromEnvironment(); expect(testApp.vmServiceUri, isNotNull); }); testWidgets( 'can process and refresh timeline data', (tester) async { await pumpAndConnectDevTools(tester, testApp); logStatus( 'Open the Performance screen and switch to the Timeline Events tab', ); await switchToScreen( tester, tabIcon: ScreenMetaData.performance.icon!, screenId: ScreenMetaData.performance.id, ); await tester.pump(safePumpDuration); await tester.tap(find.widgetWithText(InkWell, 'Timeline Events')); await tester.pumpAndSettle(longPumpDuration); // Find the [PerformanceController] to access its data. final performanceScreenFinder = find.byType(PerformanceScreenBody); expect(performanceScreenFinder, findsOneWidget); final screenState = tester.state<PerformanceScreenBodyState>(performanceScreenFinder); final performanceController = screenState.controller; logStatus('Verifying that data is processed upon first load'); final initialTrace = List.of( performanceController .timelineEventsController.fullPerfettoTrace!.packet, growable: false, ); final initialTrackDescriptors = initialTrace.where((e) => e.hasTrackDescriptor()); expect(initialTrace, isNotEmpty); expect(initialTrackDescriptors, isNotEmpty); final trackEvents = initialTrace.where((e) => e.hasTrackEvent()); expect(trackEvents, isNotEmpty); expect( performanceController .timelineEventsController.perfettoController.processor.uiTrackId, isNotNull, reason: 'Expected uiTrackId to be non-null', ); expect( performanceController.timelineEventsController.perfettoController .processor.rasterTrackId, isNotNull, reason: 'Expected rasterTrackId to be non-null', ); expect( performanceController.timelineEventsController.perfettoController .processor.frameRangeFromTimelineEvents, isNotNull, reason: 'Expected frameRangeFromTimelineEvents to be non-null', ); logStatus( 'toggling the Performance Overlay to trigger new Flutter frames', ); final performanceOverlayFinder = find.text('Performance Overlay'); expect(performanceOverlayFinder, findsOneWidget); await tester.tap(performanceOverlayFinder); await tester.pump(longPumpDuration); logStatus('Refreshing the timeline to load new events'); await tester.tap(find.byType(RefreshTimelineEventsButton)); await tester.pump(longPumpDuration); logStatus('Verifying that we have recorded new events'); final refreshedTrace = List.of( performanceController .timelineEventsController.fullPerfettoTrace!.packet, growable: false, ); expect( refreshedTrace.length, greaterThan(initialTrace.length), reason: 'Expected new events to have been recorded, but none were.', ); }, ); }
devtools/packages/devtools_app/integration_test/test/live_connection/performance_screen_event_recording_test.dart/0
{ "file_path": "devtools/packages/devtools_app/integration_test/test/live_connection/performance_screen_event_recording_test.dart", "repo_id": "devtools", "token_count": 1450 }
78
## What are DevTools extensions? DevTools extensions are custom tooling screens provided by pub packages that can be loaded into DevTools at runtime. This feature is under construction - more documentation to come.
devtools/packages/devtools_app/lib/src/extensions/README.md/0
{ "file_path": "devtools/packages/devtools_app/lib/src/extensions/README.md", "repo_id": "devtools", "token_count": 46 }
79
// 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:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../shared/analytics/analytics.dart' as ga; import '../shared/analytics/constants.dart' as gac; import '../shared/common_widgets.dart'; import '../shared/config_specific/import_export/import_export.dart'; import '../shared/connection_info.dart'; import '../shared/feature_flags.dart'; import '../shared/globals.dart'; import '../shared/primitives/blocking_action_mixin.dart'; import '../shared/primitives/utils.dart'; import '../shared/routing.dart'; import '../shared/screen.dart'; import '../shared/title.dart'; import '../shared/ui/vm_flag_widgets.dart'; import 'framework_core.dart'; class HomeScreen extends Screen { HomeScreen({this.sampleData = const []}) : super.fromMetaData( ScreenMetaData.home, titleGenerator: () => devToolsTitle.value, ); static final id = ScreenMetaData.home.id; final List<DevToolsJsonFile> sampleData; @override Widget buildScreenBody(BuildContext context) { return HomeScreenBody(sampleData: sampleData); } } class HomeScreenBody extends StatefulWidget { const HomeScreenBody({super.key, this.sampleData = const []}); final List<DevToolsJsonFile> sampleData; @override State<HomeScreenBody> createState() => _HomeScreenBodyState(); } class _HomeScreenBodyState extends State<HomeScreenBody> with AutoDisposeMixin { @override void initState() { super.initState(); ga.screen(gac.home); addAutoDisposeListener(serviceConnection.serviceManager.connectedState); } @override Widget build(BuildContext context) { final connected = serviceConnection.serviceManager.hasConnection && serviceConnection.serviceManager.connectedAppInitialized; return Scrollbar( child: ListView( children: [ ConnectionSection(connected: connected), if (widget.sampleData.isNotEmpty && !kReleaseMode && !connected) ...[ SampleDataDropDownButton(sampleData: widget.sampleData), const SizedBox(height: defaultSpacing), ], // TODO(polina-c): make the MemoryScreen a static screen and remove // this section from the Home page. See this PR for more details: // https://github.com/flutter/devtools/pull/6010. if (FeatureFlags.memoryAnalysis) ...[ const SizedBox(height: defaultSpacing), const MemoryAnalysisInstructions(), ], ], ), ); } } class ConnectionSection extends StatelessWidget { const ConnectionSection({super.key, required this.connected}); static const _primaryMinScreenWidthForTextBeforeScaling = 480.0; static const _secondaryMinScreenWidthForTextBeforeScaling = 600.0; final bool connected; @override Widget build(BuildContext context) { if (connected) { return LandingScreenSection( title: 'Connected app', actions: [ ViewVmFlagsButton( gaScreen: gac.home, minScreenWidthForTextBeforeScaling: _secondaryMinScreenWidthForTextBeforeScaling, ), const SizedBox(width: defaultSpacing), ConnectToNewAppButton( gaScreen: gac.home, minScreenWidthForTextBeforeScaling: _primaryMinScreenWidthForTextBeforeScaling, ), ], child: const ConnectedAppSummary(narrowView: false), ); } return const ConnectInput(); } } class LandingScreenSection extends StatelessWidget { const LandingScreenSection({ Key? key, required this.title, required this.child, this.actions = const [], }) : super(key: key); final String title; final Widget child; final List<Widget> actions; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: Text( title, style: textTheme.titleMedium, ), ), ...actions, ], ), const PaddedDivider(), child, PaddedDivider.vertical(padding: 10.0), ], ); } } class ConnectInput extends StatefulWidget { const ConnectInput({Key? key}) : super(key: key); @override State<ConnectInput> createState() => _ConnectInputState(); } class _ConnectInputState extends State<ConnectInput> with BlockingActionMixin { late final TextEditingController connectDialogController; SharedPreferences? _debugSharedPreferences; static const _vmServiceUriKey = 'vmServiceUri'; @override void initState() { super.initState(); connectDialogController = TextEditingController(); assert(() { _debugInitSharedPreferences(); return true; }()); } void _debugInitSharedPreferences() async { // We only do this in debug mode as it speeds iteration for DevTools // developers who tend to repeatedly restart DevTools to debug the same // test application. _debugSharedPreferences = await SharedPreferences.getInstance(); if (_debugSharedPreferences != null && mounted) { final uri = _debugSharedPreferences!.getString(_vmServiceUriKey); if (uri != null) { connectDialogController.text = uri; } } } @override void dispose() { connectDialogController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final connectorInput = Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( children: [ SizedBox( height: defaultTextFieldHeight, width: scaleByFontFactor(350.0), child: DevToolsClearableTextField( labelText: 'VM service URL', onSubmitted: actionInProgress ? null : (str) => unawaited(_connect()), autofocus: true, controller: connectDialogController, ), ), const SizedBox(width: defaultSpacing), DevToolsButton( onPressed: actionInProgress ? null : () => unawaited(_connect()), elevated: true, label: 'Connect', ), ], ), Padding( padding: const EdgeInsets.symmetric(vertical: densePadding), child: Text( '(e.g., http://127.0.0.1:12345/auth_code=...)', textAlign: TextAlign.start, style: Theme.of(context).textTheme.bodySmall, ), ), ], ); return LandingScreenSection( title: 'Connect', child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Connect to a Running App', style: textTheme.titleSmall, ), const SizedBox(height: denseRowSpacing), Text( 'Enter a URL to a running Dart or Flutter application', style: textTheme.bodySmall, ), const SizedBox(height: denseSpacing), connectorInput, ], ), ); } Future<void> _connect() async { assert(!actionInProgress); await blockWhileInProgress(_connectHelper); } Future<void> _connectHelper() async { ga.select( gac.home, gac.HomeScreenEvents.connectToApp.name, ); final uri = connectDialogController.text; if (uri.isEmpty) { notificationService.push('Please enter a VM Service URL.'); return; } assert(() { if (_debugSharedPreferences != null) { _debugSharedPreferences!.setString(_vmServiceUriKey, uri); } return true; }()); // Cache the routerDelegate and notifications providers before the async // gap as the landing screen may not be displayed by the time the async gap // is complete but we still want to show notifications and change the route. // TODO(jacobr): better understand why this is the case. It is bit counter // intuitive that we don't want to just cancel the route change or // notification if we are already on a different screen. final routerDelegate = DevToolsRouterDelegate.of(context); final connected = await FrameworkCore.initVmService(serviceUriAsString: uri); if (connected) { final connectedUri = Uri.parse(serviceConnection.serviceManager.serviceUri!); routerDelegate.updateArgsIfChanged({'uri': '$connectedUri'}); final shortUri = connectedUri.replace(path: ''); notificationService.push('Successfully connected to $shortUri.'); } else if (normalizeVmServiceUri(uri) == null) { notificationService.push( 'Failed to connect to the VM Service at "${connectDialogController.text}".\n' 'The link was not valid.', ); } } } @visibleForTesting class MemoryAnalysisInstructions extends StatelessWidget { const MemoryAnalysisInstructions({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return LandingScreenSection( title: 'Memory Analysis', child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Analyze and diff the saved memory snapshots', style: textTheme.titleMedium, ), const SizedBox(height: denseRowSpacing), Text( // TODO(polina-c): make package:leak_tracker a link. // https://github.com/flutter/devtools/issues/5606 'Analyze heap snapshots that were previously saved from DevTools or package:leak_tracker.', style: textTheme.bodySmall, ), const SizedBox(height: defaultSpacing), ElevatedButton( child: const Text('Open memory analysis tool'), onPressed: () => _onOpen(context), ), ], ), ); } void _onOpen(BuildContext context) { DevToolsRouterDelegate.of(context).navigate(memoryAnalysisScreenId); } } class SampleDataDropDownButton extends StatefulWidget { const SampleDataDropDownButton({ super.key, this.sampleData = const [], }); final List<DevToolsJsonFile> sampleData; @override State<SampleDataDropDownButton> createState() => _SampleDataDropDownButtonState(); } class _SampleDataDropDownButtonState extends State<SampleDataDropDownButton> { DevToolsJsonFile? value; @override Widget build(BuildContext context) { return Row( children: [ RoundedDropDownButton<DevToolsJsonFile>( value: value, items: [ for (final data in widget.sampleData) _buildMenuItem(data), ], onChanged: (file) => setState(() { value = file; }), ), const SizedBox(width: defaultSpacing), ElevatedButton( onPressed: value == null ? null : () => Provider.of<ImportController>(context, listen: false) .importData(value!), child: const MaterialIconLabel( label: 'Load sample data', iconData: Icons.file_upload, ), ), ], ); } DropdownMenuItem<DevToolsJsonFile> _buildMenuItem(DevToolsJsonFile file) { return DropdownMenuItem<DevToolsJsonFile>( value: file, child: Text(file.path), ); } }
devtools/packages/devtools_app/lib/src/framework/home_screen.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/framework/home_screen.dart", "repo_id": "devtools", "token_count": 4812 }
80
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart'; import '../../framework/app_error_handling.dart'; import '../../shared/config_specific/launch_url/launch_url.dart'; import '../../shared/diagnostics/primitives/source_location.dart'; import '../../shared/globals.dart'; import '../../shared/notifications.dart'; import '../../shared/primitives/history_manager.dart'; import '../../shared/routing.dart'; import '../../shared/ui/search.dart'; import '../vm_developer/vm_service_private_extensions.dart'; import 'debugger_model.dart'; import 'program_explorer_controller.dart'; import 'syntax_highlighter.dart'; final _log = Logger('codeview_controller'); class CodeViewController extends DisposableController with AutoDisposeControllerMixin, SearchControllerMixin<SourceToken>, RouteStateHandlerMixin { CodeViewController() { _scriptHistoryListener = () async { final currentScriptValue = scriptsHistory.current.value; if (currentScriptValue != null) { await _showScriptLocation(ScriptLocation(currentScriptValue)); } }; scriptsHistory.current.addListener(_scriptHistoryListener); } @override void dispose() { super.dispose(); scriptsHistory.current.removeListener(_scriptHistoryListener); } /// Perform operations based on changes in navigation state. /// /// This method is only invoked if [subscribeToRouterEvents] has been called on /// this instance with a valid [DevToolsRouterDelegate]. @override Future<void> onRouteStateUpdate(DevToolsNavigationState state) async { switch (state.kind) { case CodeViewSourceLocationNavigationState.type: await _handleNavigationEvent(state); break; } } Future<void> _handleNavigationEvent(DevToolsNavigationState state) async { final processedState = CodeViewSourceLocationNavigationState._fromState(state); final object = processedState.object; _navigationInProgress = true; await showScriptLocation(processedState.location, focusLine: true); if (programExplorerController.initialized.value) { if (object != null) { final node = programExplorerController.findOutlineNode(object); if (node != null) { programExplorerController.selectOutlineNode(node); } else { // If the object isn't associated with an outline node, clear // the current outline selection. programExplorerController.clearOutlineSelection(); } } else { programExplorerController.clearOutlineSelection(); } } _navigationInProgress = false; } /// Whether there is a [CodeViewSourceLocationNavigationState] currently being /// processed and handled. bool get navigationInProgress => _navigationInProgress; bool _navigationInProgress = false; ValueListenable<ScriptLocation?> get scriptLocation => _scriptLocation; final _scriptLocation = ValueNotifier<ScriptLocation?>(null); ValueListenable<ScriptRef?> get currentScriptRef => _currentScriptRef; final _currentScriptRef = ValueNotifier<ScriptRef?>(null); ValueListenable<ParsedScript?> get currentParsedScript => parsedScript; @visibleForTesting final parsedScript = ValueNotifier<ParsedScript?>(null); ValueListenable<bool> get showSearchInFileField => _showSearchInFileField; final _showSearchInFileField = ValueNotifier<bool>(false); ValueListenable<bool> get showFileOpener => _showFileOpener; final _showFileOpener = ValueNotifier<bool>(false); ValueListenable<bool> get fileExplorerVisible => _librariesVisible; final _librariesVisible = ValueNotifier(false); final programExplorerController = ProgramExplorerController(); final ScriptsHistory scriptsHistory = ScriptsHistory(); late VoidCallback _scriptHistoryListener; ValueListenable<bool> get showCodeCoverage => _showCodeCoverage; final _showCodeCoverage = ValueNotifier<bool>(false); ValueListenable<bool> get showProfileInformation => _showProfileInformation; final _showProfileInformation = ValueNotifier<bool>(false); /// Specifies which line should have focus applied in [CodeView]. /// /// A line can be focused by invoking `showScriptLocation` with `focusLine` /// set to true. ValueListenable<int> get focusLine => _focusLine; final _focusLine = ValueNotifier<int>(-1); void toggleShowCodeCoverage() { _showCodeCoverage.value = !_showCodeCoverage.value; } void toggleShowProfileInformation() { _showProfileInformation.value = !_showProfileInformation.value; } void clearState() { // It would be nice to not clear the script history but it is currently // coupled to ScriptRef objects so that is unsafe. scriptsHistory.clear(); parsedScript.value = null; _currentScriptRef.value = null; _scriptLocation.value = null; _librariesVisible.value = false; } void clearScriptHistory() { scriptsHistory.clear(); } /// Callback to be called when the debugger screen is first loaded. /// /// We delay calling this method until the debugger screen is first loaded /// for performance reasons. None of the code here needs to be called when /// DevTools first connects to an app, and doing so inhibits DevTools from /// connecting to low-end devices. Future<void> maybeSetupProgramExplorer() async { await _maybeSetUpProgramExplorer(); addAutoDisposeListener( currentScriptRef, () => unawaited( _maybeSetUpProgramExplorer(), ), ); } Future<void> _maybeSetUpProgramExplorer() async { if (!programExplorerController.initialized.value) { programExplorerController.initListeners(); unawaited(programExplorerController.initialize()); } if (currentScriptRef.value != null) { await programExplorerController.selectScriptNode(currentScriptRef.value); programExplorerController.resetOutline(); } } Future<Script?> getScriptForRef(ScriptRef ref) async { final cachedScript = scriptManager.getScriptCached(ref); if (cachedScript == null) { return await scriptManager.getScript(ref); } return cachedScript; } /// Jump to the given ScriptRef and optional SourcePosition. Future<void> showScriptLocation( ScriptLocation scriptLocation, { bool focusLine = false, }) async { // TODO(elliette): This is here so that when a program is selected in the // program explorer, the file opener will close (if it was open). Instead, // give the program explorer focus so that the focus changes so the file // opener will close automatically when its focus is lost. toggleFileOpenerVisibility(false); final succeeded = await _showScriptLocation(scriptLocation, focusLine: focusLine); if (succeeded) { // Update the scripts history (and make sure we don't react to the // subsequent event). scriptsHistory.current.removeListener(_scriptHistoryListener); scriptsHistory.pushEntry(scriptLocation.scriptRef); scriptsHistory.current.addListener(_scriptHistoryListener); } } Future<void> refreshCodeStatistics() async { final current = parsedScript.value; if (current == null) { return; } final isolateRef = serviceConnection.serviceManager.isolateManager.selectedIsolate.value!; final processedReport = await _getSourceReport( isolateRef, current.script, ); parsedScript.value = ParsedScript( script: current.script, highlighter: current.highlighter, executableLines: current.executableLines, sourceReport: processedReport, ); } /// Resets the current script information before invoking [showScriptLocation]. Future<void> resetScriptLocation(ScriptLocation scriptLocation) async { _scriptLocation.value = null; _currentScriptRef.value = null; parsedScript.value = null; await showScriptLocation(scriptLocation); } /// Show the given script location (without updating the script navigation /// history). /// /// Returns a boolean value representing success or failure. Future<bool> _showScriptLocation( ScriptLocation scriptLocation, { bool focusLine = false, }) async { final scriptRef = scriptLocation.scriptRef; if (scriptRef.id != parsedScript.value?.script.id) { // Try to parse the script if it isn't the currently parsed script: final script = await _parseScript(scriptRef); if (script == null) { // Return early and indicate failure if parsing fails. reportError( 'Failed to parse ${scriptRef.uri}.', stack: StackTrace.current, notifyUser: true, ); return false; } parsedScript.value = script; } _currentScriptRef.value = scriptRef; if (focusLine) { _focusLine.value = scriptLocation.location?.line ?? -1; } // We want to notify regardless of the previous scriptLocation, temporarily // set to null to ensure that happens. _scriptLocation.value = null; _scriptLocation.value = scriptLocation; return true; } Future<ProcessedSourceReport> _getSourceReport( IsolateRef isolateRef, Script script, ) async { final hitLines = <int>{}; final missedLines = <int>{}; try { final report = await serviceConnection.serviceManager.service!.getSourceReport( isolateRef.id!, // TODO(bkonyi): make _Profile a public report type. // See https://github.com/dart-lang/sdk/issues/50641 const [ SourceReportKind.kCoverage, '_Profile', ], scriptId: script.id!, reportLines: true, ); for (final range in report.ranges!) { final coverage = range.coverage!; hitLines.addAll(coverage.hits!); missedLines.addAll(coverage.misses!); } final profileReport = report.asProfileReport(script); return ProcessedSourceReport( coverageHitLines: hitLines, coverageMissedLines: missedLines, profilerEntries: profileReport.profileRanges.fold<Map<int, ProfileReportEntry>>( {}, (last, e) => last..addAll(e.entries), ), ); } catch (e, st) { // Ignore - not supported for all vm service implementations. _log.warning(e, e, st); } return const ProcessedSourceReport.empty(); } /// Parses the given script into executable lines and prepares the script /// for syntax highlighting. Future<ParsedScript?> _parseScript(ScriptRef scriptRef) async { final isolateRef = serviceConnection.serviceManager.isolateManager.selectedIsolate.value; if (isolateRef == null) return null; final script = await getScriptForRef(scriptRef); if (script == null || script.source == null) return null; // Create a new SyntaxHighlighter with the script's source in preparation // for building the code view. final highlighter = SyntaxHighlighter(source: script.source); // Gather the data to display breakable lines. var executableLines = <int>{}; try { final positions = await breakpointManager.getBreakablePositions( isolateRef, script, ); executableLines = Set.from( positions.where((p) => p.line != null).map((p) => p.line), ); if (executableLines.isEmpty) { _maybeShowSourceMapsWarning(); } } catch (e, st) { // Ignore - not supported for all vm service implementations. _log.warning(e, e, st); } final processedReport = await _getSourceReport( isolateRef, script, ); return ParsedScript( script: script, highlighter: highlighter, executableLines: executableLines, sourceReport: processedReport, ); } /// Make the 'Libraries' view on the right-hand side of the screen visible or /// hidden. void toggleLibrariesVisible() { toggleFileOpenerVisibility(false); _librariesVisible.value = !_librariesVisible.value; } void toggleSearchInFileVisibility(bool visible) { final fileExists = _currentScriptRef.value != null; _showSearchInFileField.value = visible && fileExists; if (!visible) { resetSearch(); } } void toggleFileOpenerVisibility(bool visible) { _showFileOpener.value = visible; } void _maybeShowSourceMapsWarning() { final isWebApp = serviceConnection.serviceManager.connectedApp?.isDartWebAppNow ?? false; final enableSourceMapsLink = devToolsExtensionPoints.enableSourceMapsLink(); if (isWebApp && enableSourceMapsLink != null) { final enableSourceMapsAction = NotificationAction( 'Enable sourcemaps', () { unawaited( launchUrl( enableSourceMapsLink.url, ), ); }, ); notificationService.pushNotification( NotificationMessage( 'Cannot debug when sourcemaps are disabled.', isError: true, isDismissible: true, actions: [enableSourceMapsAction], ), ); } } // TODO(kenz): search through previous matches when possible. @override List<SourceToken> matchesForSearch( String search, { bool searchPreviousMatches = false, }) { if (search.isEmpty || parsedScript.value == null) { return []; } final matches = <SourceToken>[]; final caseInsensitiveSearch = search.toLowerCase(); final currentScript = parsedScript.value!; for (int i = 0; i < currentScript.lines.length; i++) { final line = currentScript.lines[i].toLowerCase(); final matchesForLine = caseInsensitiveSearch.allMatches(line); if (matchesForLine.isNotEmpty) { matches.addAll( matchesForLine.map( (m) => SourceToken( position: SourcePosition(line: i, column: m.start), length: m.end - m.start, ), ), ); } } return matches; } } class ProcessedSourceReport { ProcessedSourceReport({ required this.coverageHitLines, required this.coverageMissedLines, required this.profilerEntries, }); const ProcessedSourceReport.empty() : coverageHitLines = const <int>{}, coverageMissedLines = const <int>{}, profilerEntries = const <int, ProfileReportEntry>{}; final Set<int> coverageHitLines; final Set<int> coverageMissedLines; final Map<int, ProfileReportEntry> profilerEntries; } /// Maintains the navigation history of the debugger's code area - which files /// were opened, whether it's possible to navigate forwards and backwards in the /// history, ... class ScriptsHistory extends HistoryManager<ScriptRef> { // TODO(devoncarew): This class should also record and restore scroll // positions. final _openedScripts = <ScriptRef>{}; bool get hasScripts => _openedScripts.isNotEmpty; void pushEntry(ScriptRef ref) { if (ref == current.value) return; while (hasNext) { pop(); } _openedScripts.remove(ref); _openedScripts.add(ref); push(ref); } Iterable<ScriptRef> get openedScripts => _openedScripts.toList().reversed; } class ParsedScript { ParsedScript({ required this.script, required this.highlighter, required this.executableLines, required this.sourceReport, }) : lines = (script.source?.split('\n') ?? const []).toList(); final Script script; final SyntaxHighlighter highlighter; final Set<int> executableLines; final ProcessedSourceReport? sourceReport; final List<String> lines; int get lineCount => lines.length; } /// State used to inform [CodeViewController]s listening for /// [DevToolsNavigationState] changes to display a specific source location. class CodeViewSourceLocationNavigationState extends DevToolsNavigationState { CodeViewSourceLocationNavigationState({ required ScriptRef script, required int line, ObjRef? object, }) : super( kind: type, state: <String, String?>{ _kScriptId: script.id, _kUri: script.uri, _kLine: line.toString(), if (object != null) _kObject: json.encode(object.json), }, ); CodeViewSourceLocationNavigationState._fromState( DevToolsNavigationState state, ) : super( kind: type, state: state.state, ); static CodeViewSourceLocationNavigationState? fromState( DevToolsNavigationState? state, ) { if (state?.kind != type) return null; return CodeViewSourceLocationNavigationState._fromState(state!); } static const _kScriptId = 'scriptId'; static const _kUri = 'uri'; static const _kLine = 'line'; static const _kObject = 'object'; static const type = 'codeViewSourceLocation'; ScriptRef get script => ScriptRef( id: state[_kScriptId]!, uri: state[_kUri], ); int get line => int.parse(state[_kLine]!); ObjRef? get object { final obj = state[_kObject]; if (obj == null) { return null; } return createServiceObject(json.decode(obj), const []) as ObjRef?; } ScriptLocation get location => ScriptLocation( script, location: SourcePosition(line: line, column: 1), ); @override String toString() { return 'kind: $kind script: ${script.uri} line: $line object: ${object?.id}'; } }
devtools/packages/devtools_app/lib/src/screens/debugger/codeview_controller.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/debugger/codeview_controller.dart", "repo_id": "devtools", "token_count": 6136 }
81
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../shared/primitives/utils.dart'; import '../../shared/table/table.dart'; import '../../shared/table/table_data.dart'; import '../../shared/ui/colors.dart'; import '../../shared/ui/search.dart'; import 'deep_link_list_view.dart'; import 'deep_links_controller.dart'; const kDeeplinkTableCellDefaultWidth = 200.0; const kToolTipWidth = 344.0; enum PlatformOS { android('Android'), ios('iOS'); const PlatformOS(this.description); final String description; } class CommonError { const CommonError(this.title, this.explanation, this.fixDetails); final String title; final String explanation; final String fixDetails; } class DomainError extends CommonError { const DomainError(title, explanation, fixDetails) : super(title, explanation, fixDetails); // Existence of an asset link file. static const existence = DomainError( 'Digital Asset Links JSON file existence failed', 'This test checks whether the assetlinks.json file, ' 'which is used to verify the association between the app and the ' 'domain name, exists under your domain.', 'Add a Digital Asset Links JSON file to all of the ' 'failed website domains at the following location: ' 'https://[domain.name]/.well-known/assetlinks.json. See the following recommended asset link json file. ', ); // Asset link file should define a link to this app. static const appIdentifier = DomainError( 'Package name failed', 'The test checks your Digital Asset Links JSON file ' 'for package name validation, which the mobile device ' 'uses to verify ownership of the app.', 'Ensure your Digital Asset Links JSON file declares the ' 'correct package name with the "android_app" namespace for ' 'all of the failed website domains. Also, confirm that the ' 'app is available in the Google Play store. See the following recommended asset link json file. ', ); // Asset link file should contain the correct fingerprint. static const fingerprints = DomainError( 'Fingerprint validation failed', 'This test checks your Digital Asset Links JSON file for ' 'sha256 fingerprint validation, which the mobile device uses ' 'to verify ownership of the app.', 'Add sha256_cert_fingerprints to the Digital Asset Links JSON ' 'file for all of the failed website domains. If the fingerprint ' 'has already been added, make sure it\'s correct and that the ' '"android_app" namespace is declared on it. See the following recommended asset link json file. ', ); // Asset link file should be served with the correct content type. static const contentType = DomainError( 'JSON content type failed', 'This test checks your Digital Asset Links JSON file for content type ' 'validation, which defines the format of the JSON file. This allows ' 'the mobile device to verify ownership of the app.', 'Ensure the content-type is "application/json" for all of the failed website domains.', ); // Asset link file should be accessible via https. static const httpsAccessibility = DomainError( 'HTTPS accessibility failed', 'This test tries to access your Digital Asset Links ' 'JSON file over an HTTPS connection, which must be ' 'accessible to verify ownership of the app.', 'Ensure your Digital Asset Links JSON file is accessible ' 'over an HTTPS connection for all of the failed website domains (even if ' 'the app\'s intent filter declares HTTP as the data scheme).', ); // Asset link file should be accessible with no redirects. static const nonRedirect = DomainError( 'Domain non-redirect failed', 'This test checks that your domain is accessible without ' 'redirects. This domain must be directly accessible ' 'to verify ownership of the app.', 'Ensure your domain is accessible without any redirects ', ); // Asset link domain should be valid/not malformed. static const hostForm = DomainError( 'Host attribute formed properly failed', 'This test checks that your android:host attribute has a valid domain URL pattern.', 'Make sure the host is a properly formed web address such ' 'as google.com or www.google.com, without "http://" or "https://".', ); // Issues that are not covered by other checks. An example that may be in this // category is Android validation API failures. static const other = DomainError('Check failed', '', ''); } /// There are currently two types of path errors, errors from intent filters and path format errors. class PathError extends CommonError { const PathError(title, explanation, fixDetails) : super(title, explanation, fixDetails); // Intent filter should have action tag. static const intentFilterActionView = PathError( 'Intent filter is missing action tag', 'The intent filter must have a <action android:name="android.intent.action.VIEW" />', '', ); // Intent filter should have browsable tag. static const intentFilterBrowsable = PathError( 'Intent filter is missing browsable tag', 'The intent filter must have a <category android:name="android.intent.category.BROWSABLE" />', '', ); // Intent filter should have default tag. static const intentFilterDefault = PathError( 'Intent filter is missing default tag', 'The intent filter must have a <category android:name="android.intent.category.DEFAULT" />', '', ); // Intent filter should have autoVerify tag. static const intentFilterAutoVerify = PathError( 'Intent filter is missing autoVerify tag', 'The intent filter must have android:autoVerify="true"', '', ); // Path has format. static const pathFormat = PathError( 'Path format', '', 'Path must starts with “/” or “.*”', ); } Set<PathError> intentFilterErrors = <PathError>{ PathError.intentFilterActionView, PathError.intentFilterBrowsable, PathError.intentFilterDefault, PathError.intentFilterAutoVerify, }; /// Contains all data relevant to a deep link. class LinkData with SearchableDataMixin { LinkData({ required this.domain, required this.path, required this.os, this.scheme = const <String>['http://', 'https://'], this.domainErrors = const <DomainError>[], this.pathErrors = const <PathError>{}, this.associatedPath = const <String>[], this.associatedDomains = const <String>[], }); final String path; final String domain; final List<PlatformOS> os; final List<String> scheme; final List<DomainError> domainErrors; Set<PathError> pathErrors; final List<String> associatedPath; final List<String> associatedDomains; @override bool matchesSearchToken(RegExp regExpSearch) { return domain.caseInsensitiveContains(regExpSearch) || path.caseInsensitiveContains(regExpSearch); } @override String toString() => 'LinkData($domain $path)'; } class _ErrorAwareText extends StatelessWidget { const _ErrorAwareText({ required this.text, required this.isError, required this.controller, required this.link, }); final String text; final bool isError; final DeepLinksController controller; final LinkData link; @override Widget build(BuildContext context) { return Row( children: [ if (isError) DevToolsTooltip( padding: const EdgeInsets.only( top: defaultSpacing, left: defaultSpacing, right: defaultSpacing, ), preferBelow: true, enableTapToDismiss: false, richMessage: WidgetSpan( child: SizedBox( width: kToolTipWidth, child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( 'This m.shopping.com domain has ${link.domainErrors.length} issue to fix. ' 'Fixing this domain will fix ${link.associatedPath.length} associated deep links.', style: TextStyle( color: Theme.of(context).colorScheme.tooltipTextColor, fontSize: defaultFontSize, ), ), TextButton( onPressed: () { controller.updateDisplayOptions(showSplitScreen: true); controller.selectLink(link); }, child: Text( 'Fix this domain', style: TextStyle( color: Theme.of(context).colorScheme.inversePrimary, fontSize: defaultFontSize, ), ), ), ], ), ), ), child: Padding( padding: const EdgeInsets.only(right: denseSpacing), child: Icon( Icons.error, color: Theme.of(context).colorScheme.error, size: defaultIconSize, ), ), ), const SizedBox(width: denseSpacing), Flexible( child: Text( text, overflow: TextOverflow.ellipsis, ), ), ], ); } } class DomainColumn extends ColumnData<LinkData> implements ColumnRenderer<LinkData>, ColumnHeaderRenderer<LinkData> { DomainColumn(this.controller) : super.wide('Domain'); DeepLinksController controller; @override Widget? buildHeader( BuildContext context, Widget Function() defaultHeaderRenderer, ) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Domain'), PopupMenuButton<SortingOption>( itemBuilder: (BuildContext context) => _buildPopupMenuSortingEntries(controller, isPath: false), child: Icon( Icons.arrow_drop_down, size: actionsIconSize, ), ), ], ); } @override String getValue(LinkData dataObject) => dataObject.domain; @override Widget build( BuildContext context, LinkData dataObject, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { return _ErrorAwareText( isError: dataObject.domainErrors.isNotEmpty, controller: controller, text: dataObject.domain, link: dataObject, ); } @override int compare(LinkData a, LinkData b) => _compareLinkData( a, b, sortingOption: controller.displayOptions.domainSortingOption, compareDomain: true, ); } class PathColumn extends ColumnData<LinkData> implements ColumnRenderer<LinkData>, ColumnHeaderRenderer<LinkData> { PathColumn(this.controller) : super.wide('Path'); DeepLinksController controller; @override Widget? buildHeader( BuildContext context, Widget Function() defaultHeaderRenderer, ) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Path'), PopupMenuButton<SortingOption>( itemBuilder: (BuildContext context) => _buildPopupMenuSortingEntries(controller, isPath: true), child: Icon( Icons.arrow_drop_down, size: actionsIconSize, ), ), ], ); } @override String getValue(LinkData dataObject) => dataObject.path; @override Widget build( BuildContext context, LinkData dataObject, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { return _ErrorAwareText( isError: dataObject.pathErrors.isNotEmpty, controller: controller, text: dataObject.path, link: dataObject, ); } @override int compare(LinkData a, LinkData b) => _compareLinkData( a, b, sortingOption: controller.displayOptions.pathSortingOption, compareDomain: false, ); } class NumberOfAssociatedPathColumn extends ColumnData<LinkData> { NumberOfAssociatedPathColumn() : super.wide('Number of associated path'); @override String getValue(LinkData dataObject) => dataObject.associatedPath.length.toString(); } class NumberOfAssociatedDomainColumn extends ColumnData<LinkData> { NumberOfAssociatedDomainColumn() : super.wide('Number of associated domain'); @override String getValue(LinkData dataObject) => dataObject.associatedDomains.length.toString(); } class SchemeColumn extends ColumnData<LinkData> implements ColumnRenderer<LinkData>, ColumnHeaderRenderer<LinkData> { SchemeColumn(this.controller) : super.wide('Scheme'); DeepLinksController controller; @override Widget? buildHeader( BuildContext context, Widget Function() defaultHeaderRenderer, ) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Scheme'), PopupMenuButton<FilterOption>( itemBuilder: (BuildContext context) { return [ _buildPopupMenuFilterEntry(controller, FilterOption.http), _buildPopupMenuFilterEntry(controller, FilterOption.custom), ]; }, child: Icon( Icons.arrow_drop_down, size: actionsIconSize, ), ), ], ); } @override Widget build( BuildContext context, LinkData dataObject, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { return Text(getValue(dataObject)); } @override String getValue(LinkData dataObject) => dataObject.scheme.join(', '); } class OSColumn extends ColumnData<LinkData> implements ColumnRenderer<LinkData>, ColumnHeaderRenderer<LinkData> { OSColumn(this.controller) : super.wide('OS'); DeepLinksController controller; @override Widget? buildHeader( BuildContext context, Widget Function() defaultHeaderRenderer, ) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('OS'), PopupMenuButton<FilterOption>( itemBuilder: (BuildContext context) { return [ _buildPopupMenuFilterEntry(controller, FilterOption.android), _buildPopupMenuFilterEntry(controller, FilterOption.ios), ]; }, child: Icon( Icons.arrow_drop_down, size: actionsIconSize, ), ), ], ); } @override Widget build( BuildContext context, LinkData dataObject, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { return Text(getValue(dataObject)); } @override String getValue(LinkData dataObject) => dataObject.os.map((e) => e.description).toList().join(', '); } class StatusColumn extends ColumnData<LinkData> implements ColumnRenderer<LinkData>, ColumnHeaderRenderer<LinkData> { StatusColumn(this.controller, this.viewType) : super.wide('Status'); DeepLinksController controller; TableViewType viewType; @override String getValue(LinkData dataObject) { if (dataObject.domainErrors.isNotEmpty) { return 'Failed domain checks'; } else if (dataObject.pathErrors.isNotEmpty) { return 'Failed path checks'; } else { return 'No issues found'; } } @override Widget? buildHeader( BuildContext context, Widget Function() defaultHeaderRenderer, ) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Status'), PopupMenuButton<FilterOption>( itemBuilder: (BuildContext context) { return [ if (viewType != TableViewType.domainView) _buildPopupMenuFilterEntry( controller, FilterOption.failedPathCheck, ), if (viewType != TableViewType.pathView) _buildPopupMenuFilterEntry( controller, FilterOption.failedDomainCheck, ), _buildPopupMenuFilterEntry(controller, FilterOption.noIssue), ]; }, child: Icon( Icons.arrow_drop_down, size: actionsIconSize, ), ), ], ); } @override Widget build( BuildContext context, LinkData dataObject, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { if (dataObject.domainErrors.isNotEmpty || dataObject.pathErrors.isNotEmpty) { return Text( getValue(dataObject), overflow: TextOverflow.ellipsis, style: TextStyle(color: Theme.of(context).colorScheme.error), ); } else { return Text( 'No issues found', style: TextStyle(color: Theme.of(context).colorScheme.green), overflow: TextOverflow.ellipsis, ); } } } class NavigationColumn extends ColumnData<LinkData> implements ColumnRenderer<LinkData> { NavigationColumn() : super( '', fixedWidthPx: scaleByFontFactor(40), ); @override String getValue(LinkData dataObject) => ''; @override Widget build( BuildContext context, LinkData dataObject, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { return isRowHovered ? const Icon(Icons.arrow_forward) : const SizedBox.shrink(); } } PopupMenuEntry<FilterOption> _buildPopupMenuFilterEntry( DeepLinksController controller, FilterOption filterOption, ) { return PopupMenuItem<FilterOption>( value: filterOption, child: Row( children: [ ValueListenableBuilder<DisplayOptions>( valueListenable: controller.displayOptionsNotifier, builder: (context, option, _) => Checkbox( value: option.filters.contains(filterOption), onChanged: (bool? checked) => controller.updateDisplayOptions( removedFilter: checked! ? null : filterOption, addedFilter: checked ? filterOption : null, ), ), ), Text(filterOption.description), ], ), ); } List<PopupMenuEntry<SortingOption>> _buildPopupMenuSortingEntries( DeepLinksController controller, { required bool isPath, }) { return [ _buildPopupMenuSortingEntry( controller, SortingOption.errorOnTop, isPath: isPath, ), _buildPopupMenuSortingEntry( controller, SortingOption.aToZ, isPath: isPath, ), _buildPopupMenuSortingEntry( controller, SortingOption.zToA, isPath: isPath, ), ]; } PopupMenuEntry<SortingOption> _buildPopupMenuSortingEntry( DeepLinksController controller, SortingOption sortingOption, { required bool isPath, }) { return PopupMenuItem<SortingOption>( onTap: () { controller.updateDisplayOptions( pathSortingOption: isPath ? sortingOption : null, domainSortingOption: isPath ? null : sortingOption, ); }, value: sortingOption, child: Text(sortingOption.description), ); } class FlutterProject { FlutterProject({ required this.path, required this.androidVariants, }); final String path; final List<String> androidVariants; } int _compareLinkData( LinkData a, LinkData b, { SortingOption? sortingOption, required bool compareDomain, }) { if (sortingOption == null) return 0; switch (sortingOption) { case SortingOption.errorOnTop: if (compareDomain) { if (a.domainErrors.isNotEmpty) return -1; if (b.domainErrors.isNotEmpty) return 1; } else { if (a.pathErrors.isNotEmpty) return -1; if (b.pathErrors.isNotEmpty) return 1; } return 0; case SortingOption.aToZ: if (compareDomain) return a.domain.compareTo(b.domain); return a.path.compareTo(b.path); case SortingOption.zToA: if (compareDomain) return b.domain.compareTo(a.domain); return b.path.compareTo(a.path); } }
devtools/packages/devtools_app/lib/src/screens/deep_link_validation/deep_links_model.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/deep_link_validation/deep_links_model.dart", "repo_id": "devtools", "token_count": 7998 }
82
// 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 'theme.dart'; /// Text widget for displaying width / height. Widget dimensionDescription( TextSpan description, bool overflow, ColorScheme colorScheme, ) { final text = Text.rich( description, textAlign: TextAlign.center, style: overflow ? overflowingDimensionIndicatorTextStyle(colorScheme) : dimensionIndicatorTextStyle, overflow: TextOverflow.ellipsis, ); if (overflow) { return Container( padding: const EdgeInsets.symmetric( vertical: minPadding, horizontal: overflowTextHorizontalPadding, ), decoration: BoxDecoration( color: colorScheme.overflowBackgroundColor, borderRadius: BorderRadius.circular(4.0), ), child: Center(child: text), ); } return text; }
devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/dimension.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/dimension.dart", "repo_id": "devtools", "token_count": 353 }
83
This folder contains code not used by memory panes.
devtools/packages/devtools_app/lib/src/screens/memory/framework/README.md/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/framework/README.md", "repo_id": "devtools", "token_count": 12 }
84
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter/material.dart'; import '../../../../shared/charts/chart.dart'; import '../../../../shared/charts/chart_controller.dart'; import '../../../../shared/charts/chart_trace.dart' as trace; import '../../../../shared/charts/chart_trace.dart' show ChartType, ChartSymbol; import '../../../../shared/utils.dart'; import '../../framework/connected/memory_controller.dart'; import '../../shared/primitives/memory_timeline.dart'; class VMChartController extends ChartController { VMChartController(this._memoryController) : super(name: 'VM Memory'); final MemoryController _memoryController; // TODO(terry): Only load max visible data collected, when pruning of data // charted is added. /// Preload any existing data collected but not in the chart. @override void setupData() { final chartDataLength = timestampsLength; final dataLength = _memoryController.controllers.memoryTimeline.data.length; final dataRange = _memoryController.controllers.memoryTimeline.data.getRange( chartDataLength, dataLength, ); dataRange.forEach(addSample); } /// Loads all heap samples (live data or offline). void addSample(HeapSample sample) { // If paused don't update the chart (data is still collected). if (_memoryController.isPaused) return; addTimestamp(sample.timestamp); final timestamp = sample.timestamp; final externalValue = sample.external.toDouble(); addDataToTrace( VmTraceName.external.index, trace.Data(timestamp, externalValue), ); final usedValue = sample.used.toDouble(); addDataToTrace(VmTraceName.used.index, trace.Data(timestamp, usedValue)); final capacityValue = sample.capacity.toDouble(); addDataToTrace( VmTraceName.capacity.index, trace.Data(timestamp, capacityValue), ); final rssValue = sample.rss.toDouble(); addDataToTrace(VmTraceName.rSS.index, trace.Data(timestamp, rssValue)); final rasterLayerValue = sample.rasterCache.layerBytes.toDouble(); addDataToTrace( VmTraceName.rasterLayer.index, trace.Data(timestamp, rasterLayerValue), ); final rasterPictureValue = sample.rasterCache.pictureBytes.toDouble(); addDataToTrace( VmTraceName.rasterPicture.index, trace.Data(timestamp, rasterPictureValue), ); } void addDataToTrace(int traceIndex, trace.Data data) { this.trace(traceIndex).addDatum(data); } } class MemoryVMChart extends StatefulWidget { const MemoryVMChart(this.chartController, {Key? key}) : super(key: key); final VMChartController chartController; @override MemoryVMChartState createState() => MemoryVMChartState(); } /// Name of each trace being charted, index order is the trace index /// too (order of trace creation top-down order). enum VmTraceName { external, used, capacity, rSS, rasterLayer, rasterPicture, } class MemoryVMChartState extends State<MemoryVMChart> with AutoDisposeMixin, ProvidedControllerMixin<MemoryController, MemoryVMChart> { /// Controller attached to the chart. VMChartController get _chartController => widget.chartController; MemoryTimeline get _memoryTimeline => controller.controllers.memoryTimeline; @override void initState() { super.initState(); setupTraces(); } @override void didChangeDependencies() { super.didChangeDependencies(); if (!initController()) return; cancelListeners(); setupTraces(); _chartController.setupData(); addAutoDisposeListener(_memoryTimeline.sampleAddedNotifier, () { if (_memoryTimeline.sampleAddedNotifier.value != null) { setState(() { _processHeapSample(_memoryTimeline.sampleAddedNotifier.value!); }); } }); } @override Widget build(BuildContext context) { if (_chartController.timestamps.isNotEmpty) { return SizedBox( height: defaultChartHeight, child: Chart(_chartController), ); } return const SizedBox(width: denseSpacing); } // TODO(terry): Move colors to theme? static final capacityColor = Colors.grey[400]!; static const usedColor = Color(0xff33b5e5); static const externalColor = Color(0xff4ddeff); // TODO(terry): UX review of raster colors see https://github.com/flutter/devtools/issues/2616 final rasterLayerColor = Colors.greenAccent.shade400; static const rasterPictureColor = Color(0xffff4444); final rssColor = Colors.orange.shade700; void setupTraces() { if (_chartController.traces.isNotEmpty) { assert(_chartController.traces.length == VmTraceName.values.length); final externalIndex = VmTraceName.external.index; assert( _chartController.trace(externalIndex).name == VmTraceName.values[externalIndex].toString(), ); final usedIndex = VmTraceName.used.index; assert( _chartController.trace(usedIndex).name == VmTraceName.values[usedIndex].toString(), ); final capacityIndex = VmTraceName.capacity.index; assert( _chartController.trace(capacityIndex).name == VmTraceName.values[capacityIndex].toString(), ); final rSSIndex = VmTraceName.rSS.index; assert( _chartController.trace(rSSIndex).name == VmTraceName.values[rSSIndex].toString(), ); final rasterLayerIndex = VmTraceName.rasterLayer.index; assert( _chartController.trace(rasterLayerIndex).name == VmTraceName.values[rasterLayerIndex].toString(), ); final rasterPictureIndex = VmTraceName.rasterPicture.index; assert( _chartController.trace(rasterPictureIndex).name == VmTraceName.values[rasterPictureIndex].toString(), ); return; } final externalIndex = _chartController.createTrace( ChartType.line, trace.PaintCharacteristics( color: externalColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: VmTraceName.external.toString(), ); assert(externalIndex == VmTraceName.external.index); assert( _chartController.trace(externalIndex).name == VmTraceName.values[externalIndex].toString(), ); // Used Heap final usedIndex = _chartController.createTrace( ChartType.line, trace.PaintCharacteristics( color: usedColor, symbol: trace.ChartSymbol.disc, diameter: 1.5, ), stacked: true, name: VmTraceName.used.toString(), ); assert(usedIndex == VmTraceName.used.index); assert( _chartController.trace(usedIndex).name == VmTraceName.values[usedIndex].toString(), ); // Heap Capacity final capacityIndex = _chartController.createTrace( ChartType.line, trace.PaintCharacteristics( color: capacityColor, diameter: 0.0, symbol: ChartSymbol.dashedLine, ), name: VmTraceName.capacity.toString(), ); assert(capacityIndex == VmTraceName.capacity.index); assert( _chartController.trace(capacityIndex).name == VmTraceName.values[capacityIndex].toString(), ); // RSS final rSSIndex = _chartController.createTrace( ChartType.line, trace.PaintCharacteristics( color: rssColor, symbol: ChartSymbol.dashedLine, strokeWidth: 2, ), name: VmTraceName.rSS.toString(), ); assert(rSSIndex == VmTraceName.rSS.index); assert( _chartController.trace(rSSIndex).name == VmTraceName.values[rSSIndex].toString(), ); final rasterLayerIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: rasterLayerColor, symbol: trace.ChartSymbol.dashedLine, strokeWidth: 2, ), name: VmTraceName.rasterLayer.toString(), ); assert(rasterLayerIndex == VmTraceName.rasterLayer.index); assert( _chartController.trace(rasterLayerIndex).name == VmTraceName.values[rasterLayerIndex].toString(), ); final rasterPictureIndex = _chartController.createTrace( trace.ChartType.line, trace.PaintCharacteristics( color: rasterPictureColor, symbol: trace.ChartSymbol.dashedLine, strokeWidth: 2, ), name: VmTraceName.rasterPicture.toString(), ); assert(rasterPictureIndex == VmTraceName.rasterPicture.index); assert( _chartController.trace(rasterPictureIndex).name == VmTraceName.values[rasterPictureIndex].toString(), ); assert(_chartController.traces.length == VmTraceName.values.length); } /// Loads all heap samples (live data or offline). void _processHeapSample(HeapSample sample) { // If paused don't update the chart (data is still collected). if (controller.paused.value) return; _chartController.addSample(sample); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/chart/memory_vm_chart.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/chart/memory_vm_chart.dart", "repo_id": "devtools", "token_count": 3510 }
85
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../../../../shared/analytics/analytics.dart' as ga; import '../../../../../shared/analytics/constants.dart' as gac; import '../../../../../shared/common_widgets.dart'; import '../../../../../shared/globals.dart'; import '../../../../../shared/memory/classes.dart'; import '../../../../../shared/primitives/utils.dart'; import '../../../../../shared/table/table.dart'; import '../../../../../shared/table/table_data.dart'; import '../../../shared/primitives/simple_elements.dart'; import '../../../shared/widgets/class_filter.dart'; import '../../../shared/widgets/shared_memory_widgets.dart'; import '../controller/class_data.dart'; import '../data/classes_diff.dart'; import 'instances.dart'; enum _DataPart { created, deleted, delta, persisted, } class _ClassNameColumn extends ColumnData<DiffClassData> implements ColumnRenderer<DiffClassData>, ColumnHeaderRenderer<DiffClassData> { _ClassNameColumn(this.diffData) : super( 'Class', titleTooltip: 'Class name', fixedWidthPx: scaleByFontFactor(200.0), alignment: ColumnAlignment.left, ); final ClassesTableDiffData diffData; @override String? getValue(DiffClassData dataObject) => dataObject.heapClass.className; @override bool get supportsSorting => true; @override // We are removing the tooltip, because it is provided by [HeapClassView]. String getTooltip(DiffClassData dataObject) => ''; @override Widget build( BuildContext context, DiffClassData data, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { return HeapClassView( theClass: data.heapClass, showCopyButton: isRowSelected, copyGaItem: gac.MemoryEvent.diffClassDiffCopy, rootPackage: serviceConnection.serviceManager.rootInfoNow().package, ); } @override Widget? buildHeader( BuildContext context, Widget Function() defaultHeaderRenderer, ) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(child: defaultHeaderRenderer()), ClassFilterButton(diffData.filterData), ], ); } } class _InstanceColumn extends ColumnData<DiffClassData> implements ColumnRenderer<DiffClassData> { _InstanceColumn(this.dataPart, this.diffData) : super( columnTitle(dataPart), fixedWidthPx: scaleByFontFactor(110.0), alignment: ColumnAlignment.right, ); final _DataPart dataPart; final ClassesTableDiffData diffData; static String columnTitle(_DataPart dataPart) { switch (dataPart) { case _DataPart.created: return 'New'; case _DataPart.deleted: return 'Released'; case _DataPart.delta: return 'Delta'; case _DataPart.persisted: return 'Persisted'; } } @override int getValue(DiffClassData dataObject) => _instances(dataObject).instanceCount; ObjectSetStats _instances(DiffClassData classStats) { switch (dataPart) { case _DataPart.created: return classStats.total.created; case _DataPart.deleted: return classStats.total.deleted; case _DataPart.delta: return classStats.total.delta; case _DataPart.persisted: return classStats.total.persisted; } } @override String getDisplayValue(DiffClassData dataObject) { // Add leading sign for delta values. final value = getValue(dataObject); if (dataPart != _DataPart.delta || value <= 0) return value.toString(); return '+$value'; } @override bool get numeric => true; @override Widget? build( BuildContext context, DiffClassData data, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { final objects = _instances(data); if (dataPart == _DataPart.delta) { assert(objects is! ObjectSet); return null; } final heapCallback = dataPart == _DataPart.deleted ? diffData.before : diffData.after; if (objects is! ObjectSet) { throw StateError( 'All columns except ${_DataPart.delta} should have objects available.', ); } return HeapInstanceTableCell( objects, heapCallback, data.heapClass, isSelected: isRowSelected, liveItemsEnabled: dataPart != _DataPart.deleted, ); } } class _SizeColumn extends ColumnData<DiffClassData> { _SizeColumn(this.dataPart, this.sizeType) : super( columnTitle(dataPart), fixedWidthPx: scaleByFontFactor(80.0), alignment: ColumnAlignment.right, ); final _DataPart dataPart; final SizeType sizeType; static String columnTitle(_DataPart dataPart) { switch (dataPart) { case _DataPart.created: return 'Allocated'; case _DataPart.deleted: return 'Freed'; case _DataPart.delta: return 'Delta'; case _DataPart.persisted: return 'Persisted'; } } @override int getValue(DiffClassData classStats) { switch (sizeType) { case SizeType.shallow: switch (dataPart) { case _DataPart.created: return classStats.total.created.shallowSize; case _DataPart.deleted: return classStats.total.deleted.shallowSize; case _DataPart.delta: return classStats.total.delta.shallowSize; case _DataPart.persisted: return classStats.total.persisted.shallowSize; } case SizeType.retained: switch (dataPart) { case _DataPart.created: return classStats.total.created.retainedSize; case _DataPart.deleted: return classStats.total.deleted.retainedSize; case _DataPart.delta: return classStats.total.delta.retainedSize; case _DataPart.persisted: return classStats.total.persisted.retainedSize; } } } @override String getDisplayValue(DiffClassData classStats) { // Add leading sign for delta values. final value = getValue(classStats); final asSize = prettyPrintRetainedSize(value)!; if (dataPart != _DataPart.delta || value <= 0) return asSize; return '+$asSize'; } @override bool get numeric => true; } class ClassesTableDiffColumns { ClassesTableDiffColumns(this.sizeType, this.diffData); final SizeType sizeType; final ClassesTableDiffData diffData; late final sizeDeltaColumn = _SizeColumn(_DataPart.delta, sizeType); late final List<ColumnData<DiffClassData>> columnList = <ColumnData<DiffClassData>>[ _ClassNameColumn(diffData), _InstanceColumn(_DataPart.created, diffData), _InstanceColumn(_DataPart.deleted, diffData), _InstanceColumn(_DataPart.delta, diffData), _InstanceColumn(_DataPart.persisted, diffData), _SizeColumn(_DataPart.created, sizeType), _SizeColumn(_DataPart.deleted, sizeType), sizeDeltaColumn, _SizeColumn(_DataPart.persisted, sizeType), ]; } class _SizeGroupTitle extends StatelessWidget { const _SizeGroupTitle(this.diffData); final ClassesTableDiffData diffData; @override Widget build(BuildContext context) { final sizeType = diffData.selectedSizeType.value; return maybeWrapWithTooltip( child: Padding( padding: const EdgeInsets.all(densePadding), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ RoundedDropDownButton<SizeType>( isDense: true, value: sizeType, onChanged: (SizeType? value) => diffData.selectedSizeType.value = value!, items: SizeType.values .map( (sizeType) => DropdownMenuItem<SizeType>( value: sizeType, child: Text(sizeType.displayName), ), ) .toList(), ), const SizedBox(width: denseSpacing), const Text('Size'), ], ), ), tooltip: '${sizeType.displayName} size:\n${sizeType.description}', ); } } class ClassesTableDiff extends StatelessWidget { ClassesTableDiff({ Key? key, required this.classes, required this.diffData, }) : super(key: key) { _columns = { for (var sizeType in SizeType.values) sizeType: ClassesTableDiffColumns(sizeType, diffData), }; } final List<DiffClassData> classes; final ClassesTableDiffData diffData; List<ColumnGroup> _columnGroups() { return [ ColumnGroup.fromText( title: '', range: const Range(0, 1), ), ColumnGroup.fromText( title: 'Instances', range: const Range(1, 5), tooltip: nonGcableInstancesColumnTooltip, ), ColumnGroup( title: _SizeGroupTitle(diffData), range: const Range(5, 9), ), ]; } late final Map<SizeType, ClassesTableDiffColumns> _columns; @override Widget build(BuildContext context) { return ValueListenableBuilder<SizeType>( valueListenable: diffData.selectedSizeType, builder: (context, sizeType, _) { // We want to preserve the sorting and sort directions for ClassesTableDiff // no matter what the data passed to it is. const dataKey = 'ClassesTableDiff'; final columns = _columns[sizeType]!; return FlatTable<DiffClassData>( columns: columns.columnList, columnGroups: _columnGroups(), data: classes, dataKey: dataKey, keyFactory: (e) => Key(e.heapClass.fullName), selectionNotifier: diffData.selection, onItemSelected: (_) => ga.select( gac.memory, gac.MemoryEvent.diffClassDiffSelect, ), defaultSortColumn: columns.sizeDeltaColumn, defaultSortDirection: SortDirection.descending, ); }, ); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/classes_table_diff.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/classes_table_diff.dart", "repo_id": "devtools", "token_count": 4163 }
86
This folder contains code shared between memory screen panes. For clarity of contracts, it is preferred that code in this folder does not depend on any `memory` code outside this folder.
devtools/packages/devtools_app/lib/src/screens/memory/shared/README.md/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/shared/README.md", "repo_id": "devtools", "token_count": 41 }
87
// 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:convert'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:image/image.dart' as image; import '../../shared/common_widgets.dart'; import '../../shared/http/http.dart'; import '../../shared/http/http_request_data.dart'; import '../../shared/primitives/byte_utils.dart'; import '../../shared/primitives/utils.dart'; import '../../shared/ui/colors.dart'; import 'network_controller.dart'; import 'network_model.dart'; // Approximately double the indent of the expandable tile's title. const double _rowIndentPadding = 30; // No padding between the last element and the divider of a expandable tile. const double _rowSpacingPadding = 15; const EdgeInsets _rowPadding = EdgeInsets.only(left: _rowIndentPadding, bottom: _rowSpacingPadding); /// Helper to build ExpansionTile widgets for inspector views. ExpansionTile _buildTile( String title, List<Widget> children, { Key? key, }) { return ExpansionTile( key: key, title: Text( title, ), initiallyExpanded: true, children: children, ); } /// This widget displays general HTTP request / response information that is /// contained in the headers, in addition to the standard connection information. class HttpRequestHeadersView extends StatelessWidget { const HttpRequestHeadersView(this.data, {super.key}); @visibleForTesting static const generalKey = Key('General'); @visibleForTesting static const requestHeadersKey = Key('Request Headers'); @visibleForTesting static const responseHeadersKey = Key('Response Headers'); final DartIOHttpRequestData data; @override Widget build(BuildContext context) { final general = data.general; final responseHeaders = data.responseHeaders; final requestHeaders = data.requestHeaders; return LayoutBuilder( builder: (context, constraints) { return SelectionArea( child: ListView( children: [ _buildTile( 'General', [ for (final entry in general.entries) _Row( entry: entry, constraints: constraints, isErrorValue: data.didFail && entry.key == 'statusCode', ), ], key: generalKey, ), _buildTile( 'Response Headers', [ if (responseHeaders != null) for (final entry in responseHeaders.entries) _Row(entry: entry, constraints: constraints), ], key: responseHeadersKey, ), _buildTile( 'Request Headers', [ if (requestHeaders != null) for (final entry in requestHeaders.entries) _Row(entry: entry, constraints: constraints), ], key: requestHeadersKey, ), ], ), ); }, ); } } class _Row extends StatelessWidget { const _Row({ required this.entry, required this.constraints, this.isErrorValue = false, }); final MapEntry<String, Object?> entry; final BoxConstraints constraints; final bool isErrorValue; @override Widget build(BuildContext context) { return Container( width: constraints.minWidth, padding: _rowPadding, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '${entry.key}: ', style: Theme.of(context).textTheme.titleSmall, ), Expanded( child: Text( style: isErrorValue ? TextStyle(color: Theme.of(context).colorScheme.error) : null, '${entry.value}', ), ), ], ), ); } } class HttpRequestView extends StatelessWidget { const HttpRequestView(this.data, {super.key}); final DartIOHttpRequestData data; @override Widget build(BuildContext context) { return ListenableBuilder( listenable: data, builder: (context, __) { final theme = Theme.of(context); final requestHeaders = data.requestHeaders; final requestContentType = requestHeaders?['content-type'] ?? ''; final isLoading = data.isFetchingFullData; if (isLoading) { return CenteredCircularProgressIndicator( size: mediumProgressSize, ); } final isJson = switch (requestContentType) { List() => requestContentType.any((e) => (e as String).contains('json')), String() => requestContentType.contains('json'), _ => throw StateError( "Expected 'content-type' to be a List or String, but got: " '$requestContentType', ), }; Widget child; child = isJson ? JsonViewer(encodedJson: data.requestBody!) : TextViewer( text: data.requestBody!, style: theme.fixedFontStyle, ); return Padding( padding: const EdgeInsets.all(denseSpacing), child: SingleChildScrollView( child: child, ), ); }, ); } } /// A button for copying [DartIOHttpRequestData] contents. /// /// If there is no content to copy, the button will not show. The copy contents /// will update as the request's data is updated. class HttpViewTrailingCopyButton extends StatelessWidget { const HttpViewTrailingCopyButton(this.data, this.dataSelector, {super.key}); final DartIOHttpRequestData data; final String? Function(DartIOHttpRequestData) dataSelector; @override Widget build(BuildContext context) { return ListenableBuilder( listenable: data, builder: (context, __) { final dataToCopy = dataSelector(data); final isLoading = data.isFetchingFullData; if (dataToCopy == null || dataToCopy.isEmpty || isLoading) { return Container(); } return Align( alignment: Alignment.centerRight, child: CopyToClipboardControl( dataProvider: () => dataToCopy, ), ); }, ); } } /// A DropDownButton for selecting [NetworkResponseViewType]. /// /// If there is no content to visualise, the drop down will not show. Drop down /// values will update as the request's data is updated. class HttpResponseTrailingDropDown extends StatelessWidget { const HttpResponseTrailingDropDown( this.data, { super.key, required this.currentResponseViewType, required this.onChanged, }); final ValueListenable<NetworkResponseViewType> currentResponseViewType; final DartIOHttpRequestData data; final ValueChanged<NetworkResponseViewType> onChanged; bool isJsonDecodable() { try { json.decode(data.responseBody!); return true; } catch (_) { return false; } } @override Widget build(BuildContext context) { return ListenableBuilder( listenable: data, builder: (_, __) { final bool visible = (data.contentType != null && !data.contentType!.contains('image')) && data.responseBody!.isNotEmpty; final List<NetworkResponseViewType> availableResponseTypes = [ NetworkResponseViewType.auto, if (isJsonDecodable()) NetworkResponseViewType.json, NetworkResponseViewType.text, ]; return Visibility( visible: visible, replacement: const SizedBox(), child: ValueListenableBuilder<NetworkResponseViewType>( valueListenable: currentResponseViewType, builder: (_, currentType, __) { return RoundedDropDownButton<NetworkResponseViewType>( value: currentType, items: availableResponseTypes .map( (e) => DropdownMenuItem( value: e, child: Text(e.toString()), ), ) .toList(), onChanged: (value) { if (value == null) { return; } onChanged(value); }, ); }, ), ); }, ); } } class HttpResponseView extends StatelessWidget { const HttpResponseView( this.data, { super.key, required this.currentResponseViewType, }); final DartIOHttpRequestData data; final ValueListenable<NetworkResponseViewType> currentResponseViewType; @override Widget build(BuildContext context) { return ListenableBuilder( listenable: data, builder: (context, __) { Widget child; final theme = Theme.of(context); // We shouldn't try and display an image response view when using the // timeline profiler since it's possible for response body data to get // dropped. final contentType = data.contentType; final responseBody = data.responseBody!; final isLoading = data.isFetchingFullData; if (isLoading) { return CenteredCircularProgressIndicator( size: mediumProgressSize, ); } if (contentType != null && contentType.contains('image')) { child = ImageResponseView(data); } else { child = HttpTextResponseViewer( contentType: contentType, responseBody: responseBody, currentResponseNotifier: currentResponseViewType, textStyle: theme.fixedFontStyle, ); } return Padding( padding: const EdgeInsets.all(denseSpacing), child: SingleChildScrollView(child: child), ); }, ); } } class HttpTextResponseViewer extends StatelessWidget { const HttpTextResponseViewer({ super.key, required this.contentType, required this.responseBody, required this.currentResponseNotifier, required this.textStyle, }); final String? contentType; final String responseBody; final ValueListenable<NetworkResponseViewType> currentResponseNotifier; final TextStyle textStyle; @override Widget build(BuildContext context) { return ValueListenableBuilder( valueListenable: currentResponseNotifier, builder: (_, currentResponseType, __) { NetworkResponseViewType currentLocalResponseType = currentResponseType; if (currentResponseType == NetworkResponseViewType.auto) { if (contentType != null && contentType!.contains('json') && responseBody.isNotEmpty) { currentLocalResponseType = NetworkResponseViewType.json; } else { currentLocalResponseType = NetworkResponseViewType.text; } } return switch (currentLocalResponseType) { NetworkResponseViewType.json => JsonViewer(encodedJson: responseBody), NetworkResponseViewType.text => TextViewer( text: responseBody, style: textStyle, ), _ => const SizedBox(), }; }, ); } } class ImageResponseView extends StatelessWidget { const ImageResponseView(this.data, {super.key}); final DartIOHttpRequestData data; @override Widget build(BuildContext context) { final encodedResponse = data.encodedResponse!; final img = image.decodeImage(encodedResponse)!; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _buildTile( 'Image Preview', [ Padding( padding: const EdgeInsets.all( denseSpacing, ), child: Image.memory( encodedResponse, ), ), ], ), _buildTile( 'Metadata', [ _buildRow( context, 'Format', data.type, ), _buildRow( context, 'Size', prettyPrintBytes( encodedResponse.lengthInBytes, includeUnit: true, )!, ), _buildRow( context, 'Dimensions', '${img.width} x ${img.height}', ), ], ), ], ); } Widget _buildRow( BuildContext context, String key, String value, ) { return Padding( padding: _rowPadding, child: Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '$key: ', style: Theme.of(context).textTheme.titleSmall, ), Expanded( child: Text( value, // TODO(kenz): use top level overflow parameter if // https://github.com/flutter/flutter/issues/82722 is fixed. // TODO(kenz): add overflow after flutter 2.3.0 is stable. It was // added in commit 65388ee2eeaf0d2cf087eaa4a325e3689020c46a. // style: const TextStyle(overflow: TextOverflow.ellipsis), ), ), ], ), ); } } /// A [Widget] which displays [Cookie] information in a tab. class HttpRequestCookiesView extends StatelessWidget { const HttpRequestCookiesView(this.data, {super.key}); @visibleForTesting static const requestCookiesKey = Key('Request Cookies'); @visibleForTesting static const responseCookiesKey = Key('Response Cookies'); final DartIOHttpRequestData data; DataRow _buildRow(int index, Cookie cookie, {bool requestCookies = false}) { return DataRow.byIndex( index: index, // NOTE: if this list of cells change, the columns of the DataTable // below will need to be updated. cells: [ _buildCell(cookie.name), _buildCell(cookie.value), if (!requestCookies) ...[ _buildCell(cookie.domain), _buildCell(cookie.path), _buildCell(cookie.expires?.toString()), _buildCell(cookie.value!.length.toString()), _buildIconCell(!cookie.httpOnly ? Icons.check : Icons.close), _buildIconCell(!cookie.secure ? Icons.check : Icons.close), ], ], ); } DataCell _buildCell(String? value) => DataCell(Text(value ?? '--')); DataCell _buildIconCell(IconData icon) => DataCell(Icon(icon, size: defaultIconSize)); Widget _buildCookiesTable( BuildContext context, String title, List<Cookie> cookies, BoxConstraints constraints, Key key, { bool requestCookies = false, }) { final theme = Theme.of(context); DataColumn buildColumn( String title, { bool numeric = false, }) { return DataColumn( label: Expanded( child: Text( title, // TODO(kenz): use top level overflow parameter if // https://github.com/flutter/flutter/issues/82722 is fixed. // TODO(kenz): add overflow after flutter 2.3.0 is stable. It was // added in commit 65388ee2eeaf0d2cf087eaa4a325e3689020c46a. // style: theme.textTheme.titleMedium.copyWith( // overflow: TextOverflow.fade, // ), style: theme.textTheme.titleMedium, ), ), numeric: numeric, ); } return _buildTile( title, [ // Add a divider between the tile's title and the cookie table headers for // symmetry. const Divider( // Remove extra padding at the top of the divider; the tile's title // already has bottom padding. height: 0, ), Align( alignment: Alignment.centerLeft, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: ConstrainedBox( constraints: requestCookies ? const BoxConstraints() : BoxConstraints( minWidth: constraints.minWidth, ), child: DataTable( key: key, dataRowMinHeight: defaultRowHeight, dataRowMaxHeight: defaultRowHeight, // NOTE: if this list of columns change, _buildRow will need // to be updated to match. columns: [ buildColumn('Name'), buildColumn('Value'), if (!requestCookies) ...[ buildColumn('Domain'), buildColumn('Path'), buildColumn('Expires / Max Age'), buildColumn('Size', numeric: true), buildColumn('HttpOnly'), buildColumn('Secure'), ], ], rows: [ for (int i = 0; i < cookies.length; ++i) _buildRow( i, cookies[i], requestCookies: requestCookies, ), ], ), ), ), ), ], ); } @override Widget build(BuildContext context) { final requestCookies = data.requestCookies; final responseCookies = data.responseCookies; return LayoutBuilder( builder: (context, constraints) { return ListView( children: [ if (responseCookies.isNotEmpty) _buildCookiesTable( context, 'Response Cookies', responseCookies, constraints, responseCookiesKey, ), // Add padding between the cookie tables if displaying both // response and request cookies. if (responseCookies.isNotEmpty && requestCookies.isNotEmpty) const Padding( padding: EdgeInsets.only(bottom: 24.0), ), if (requestCookies.isNotEmpty) _buildCookiesTable( context, 'Request Cookies', requestCookies, constraints, requestCookiesKey, requestCookies: true, ), ], ); }, ); } } class NetworkRequestOverviewView extends StatelessWidget { const NetworkRequestOverviewView(this.data, {super.key}); static const _keyWidth = 110.0; static const _timingGraphHeight = 18.0; @visibleForTesting static const httpTimingGraphKey = Key('Http Timing Graph Key'); @visibleForTesting static const socketTimingGraphKey = Key('Socket Timing Graph Key'); final NetworkRequest data; @override Widget build(BuildContext context) { return SelectionArea( child: ListView( padding: const EdgeInsets.all(defaultSpacing), children: [ ..._buildGeneralRows(context), if (data is WebSocket) ..._buildSocketOverviewRows(context), const PaddedDivider( padding: EdgeInsets.only(bottom: denseRowSpacing), ), ..._buildTimingOverview(context), ], ), ); } List<Widget> _buildGeneralRows(BuildContext context) { return [ // TODO(kenz): show preview for requests (png, response body, proto) _buildRow( context: context, title: 'Request uri', child: _valueText(data.uri), ), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'Method', child: _valueText(data.method), ), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'Status', child: _valueText( data.status ?? '--', data.didFail ? TextStyle(color: Theme.of(context).colorScheme.error) : null, ), ), const SizedBox(height: defaultSpacing), if (data.port != null) ...[ _buildRow( context: context, title: 'Port', child: _valueText('${data.port}'), ), const SizedBox(height: defaultSpacing), ], if (data.contentType != null) ...[ _buildRow( context: context, title: 'Content type', child: _valueText(data.contentType ?? 'null'), ), const SizedBox(height: defaultSpacing), ], ]; } List<Widget> _buildTimingOverview(BuildContext context) { return [ _buildRow( context: context, title: 'Timing', child: data is WebSocket ? _buildSocketTimeGraph(context) : _buildHttpTimeGraph(), ), const SizedBox(height: denseSpacing), _buildRow( context: context, title: '', child: _valueText(data.durationDisplay), ), const SizedBox(height: defaultSpacing), ...data is WebSocket ? _buildSocketTimingRows(context) : _buildHttpTimingRows(context), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'Start time', child: _valueText(formatDateTime(data.startTimestamp!)), ), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'End time', child: _valueText( data.endTimestamp != null ? formatDateTime(data.endTimestamp!) : 'Pending', ), ), ]; } Widget _buildTimingRow( Color color, String label, Duration duration, ) { final flex = (duration.inMicroseconds / data.duration!.inMicroseconds * 100).round(); return Flexible( flex: flex, child: DevToolsTooltip( message: '$label - ${durationText(duration)}', child: Container( height: _timingGraphHeight, color: color, ), ), ); } Widget _buildHttpTimeGraph() { final data = this.data as DartIOHttpRequestData; if (data.duration == null || data.instantEvents.isEmpty) { return Container( key: httpTimingGraphKey, height: 18.0, color: mainRasterColor, ); } const colors = [ searchMatchColor, mainRasterColor, mainAsyncColor, ]; var colorIndex = 0; Color nextColor() { final color = colors[colorIndex % colors.length]; colorIndex++; return color; } // TODO(kenz): consider calculating these sizes by hand instead of using // flex so that we can set a minimum width for small timing chunks. final timingWidgets = <Widget>[]; for (final instant in data.instantEvents) { final duration = instant.timeRange!.duration; timingWidgets.add( _buildTimingRow(nextColor(), instant.name, duration), ); } final duration = Duration( microseconds: data.endTimestamp!.microsecondsSinceEpoch - data.instantEvents.last.timestamp.microsecondsSinceEpoch, ); timingWidgets.add( _buildTimingRow(nextColor(), 'Response', duration), ); return Row( key: httpTimingGraphKey, children: timingWidgets, ); } // TODO(kenz): add a "waterfall" like visualization with the same colors that // are used in the timing graph. List<Widget> _buildHttpTimingRows(BuildContext context) { final data = this.data as DartIOHttpRequestData; final result = <Widget>[]; for (final instant in data.instantEvents) { final instantEventStart = data.instantEvents.first.timeRange!.start!; final timeRange = instant.timeRange!; final startDisplay = durationText( timeRange.start! - instantEventStart, unit: DurationDisplayUnit.milliseconds, ); final endDisplay = durationText( timeRange.end! - instantEventStart, unit: DurationDisplayUnit.milliseconds, ); final totalDisplay = durationText( timeRange.duration, unit: DurationDisplayUnit.milliseconds, ); result.addAll([ _buildRow( context: context, title: instant.name, child: _valueText( '[$startDisplay - $endDisplay] → $totalDisplay total', ), ), if (instant != data.instantEvents.last) const SizedBox(height: defaultSpacing), ]); } return result; } List<Widget> _buildSocketOverviewRows(BuildContext context) { final socket = data as WebSocket; return [ _buildRow( context: context, title: 'Socket id', child: _valueText(socket.id), ), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'Socket type', child: _valueText(socket.socketType), ), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'Read bytes', child: _valueText('${socket.readBytes}'), ), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'Write bytes', child: _valueText('${socket.writeBytes}'), ), const SizedBox(height: defaultSpacing), ]; } Widget _buildSocketTimeGraph(BuildContext context) { return Container( key: socketTimingGraphKey, height: _timingGraphHeight, color: Theme.of(context).colorScheme.primary, ); } List<Widget> _buildSocketTimingRows(BuildContext context) { final data = this.data as WebSocket; final lastReadTimestamp = data.lastReadTimestamp; final lastWriteTimestamp = data.lastWriteTimestamp; return [ _buildRow( context: context, title: 'Last read time', child: lastReadTimestamp != null ? _valueText(formatDateTime(lastReadTimestamp)) : _valueText('--'), ), const SizedBox(height: defaultSpacing), _buildRow( context: context, title: 'Last write time', child: lastWriteTimestamp != null ? _valueText(formatDateTime(lastWriteTimestamp)) : _valueText('--'), ), ]; } Widget _buildRow({ required BuildContext context, required String title, required Widget child, }) { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: _keyWidth, child: Text( title.isEmpty ? '' : '$title: ', style: Theme.of(context).textTheme.titleSmall, ), ), Expanded( child: child, ), ], ); } Widget _valueText(String value, [TextStyle? style]) { return Text( style: style, value, ); } }
devtools/packages/devtools_app/lib/src/screens/network/network_request_inspector_views.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/network/network_request_inspector_views.dart", "repo_id": "devtools", "token_count": 12246 }
88
// 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:math' as math; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import '../../../../shared/primitives/utils.dart'; import '../../../../shared/ui/utils.dart'; import 'frame_analysis_model.dart'; class FrameTimeVisualizer extends StatefulWidget { const FrameTimeVisualizer({ Key? key, required this.frameAnalysis, }) : super(key: key); final FrameAnalysis frameAnalysis; @override State<FrameTimeVisualizer> createState() => _FrameTimeVisualizerState(); } class _FrameTimeVisualizerState extends State<FrameTimeVisualizer> { @override void initState() { super.initState(); // Do this in initState so that we do not have to pay the cost in build. widget.frameAnalysis.calculateFramePhaseFlexValues(); } @override void didUpdateWidget(FrameTimeVisualizer oldWidget) { super.didUpdateWidget(oldWidget); widget.frameAnalysis.calculateFramePhaseFlexValues(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _UiPhases(frameAnalysis: widget.frameAnalysis), const SizedBox(height: denseSpacing), _RasterPhases(frameAnalysis: widget.frameAnalysis), ], ); } } class _UiPhases extends StatelessWidget { const _UiPhases({Key? key, required this.frameAnalysis}) : super(key: key); final FrameAnalysis frameAnalysis; @override Widget build(BuildContext context) { return _FrameBlockGroup( title: 'UI phases:', data: _generateBlockData(frameAnalysis), hasData: frameAnalysis.hasUiData, ); } List<_FramePhaseBlockData> _generateBlockData(FrameAnalysis frameAnalysis) { final buildPhase = frameAnalysis.buildPhase; final layoutPhase = frameAnalysis.layoutPhase; final paintPhase = frameAnalysis.paintPhase; return [ _FramePhaseBlockData( title: buildPhase.title, duration: buildPhase.duration, flex: frameAnalysis.buildFlex!, icon: Icons.build, ), _FramePhaseBlockData( title: layoutPhase.title, duration: layoutPhase.duration, flex: frameAnalysis.layoutFlex!, icon: Icons.auto_awesome_mosaic, ), _FramePhaseBlockData( title: paintPhase.title, duration: paintPhase.duration, flex: frameAnalysis.paintFlex!, icon: Icons.format_paint, ), ]; } } class _RasterPhases extends StatelessWidget { const _RasterPhases({Key? key, required this.frameAnalysis}) : super(key: key); final FrameAnalysis frameAnalysis; @override Widget build(BuildContext context) { final data = _generateBlockData(frameAnalysis); return _FrameBlockGroup( title: 'Raster ${pluralize('phase', data.length)}:', data: data, hasData: frameAnalysis.hasRasterData, ); } List<_FramePhaseBlockData> _generateBlockData(FrameAnalysis frameAnalysis) { final frame = frameAnalysis.frame; if (frame.hasShaderTime) { return [ _FramePhaseBlockData( title: 'Shader compilation', duration: frame.shaderDuration, flex: frameAnalysis.shaderCompilationFlex!, icon: Icons.image_outlined, ), _FramePhaseBlockData( title: 'Other raster', duration: frame.rasterTime - frame.shaderDuration, flex: frameAnalysis.rasterFlex!, icon: Icons.grid_on, ), ]; } final rasterPhase = frameAnalysis.rasterPhase; return [ _FramePhaseBlockData( title: rasterPhase.title, duration: rasterPhase.duration, flex: frameAnalysis.rasterFlex!, icon: Icons.grid_on, ), ]; } } class _FrameBlockGroup extends StatelessWidget { const _FrameBlockGroup({ Key? key, required this.title, required this.data, required this.hasData, }) : super(key: key); final String title; final List<_FramePhaseBlockData> data; final bool hasData; @override Widget build(BuildContext context) { Widget content; if (hasData) { final totalFlex = data.fold<int>(0, (current, block) => current + block.flex); content = LayoutBuilder( builder: (context, constraints) { final adjustedBlockWidths = adjustedWidthsForBlocks(constraints, totalFlex); return Row( children: [ for (var i = 0; i < data.length; i++) _FramePhaseBlock( blockData: data[i], width: adjustedBlockWidths[i], ), ], ); }, ); } else { content = const Text('Data not available.'); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(title), const SizedBox(height: denseSpacing), content, ], ); } /// Returns a list of adjusted widths for each block. /// /// The adjusted widths will ensure each block is at least /// [_FramePhaseBlock.minBlockWidth] wide, and will modify surrounding block /// widths to accommodate. List<double> adjustedWidthsForBlocks( BoxConstraints constraints, int totalFlex, ) { final unadjustedBlockWidths = data .map( (blockData) => constraints.maxWidth * blockData.flex / totalFlex, ) .toList(); var adjustment = 0.0; var widestBlockIndex = 0; for (var i = 0; i < unadjustedBlockWidths.length; i++) { final unadjustedWidth = unadjustedBlockWidths[i]; final currentWidestBlock = unadjustedBlockWidths[widestBlockIndex]; if (unadjustedWidth > currentWidestBlock) { widestBlockIndex = i; } if (unadjustedWidth < _FramePhaseBlock.minBlockWidth) { adjustment += _FramePhaseBlock.minBlockWidth - unadjustedWidth; } } final adjustedBlockWidths = unadjustedBlockWidths .map( (blockWidth) => math.max(blockWidth, _FramePhaseBlock.minBlockWidth), ) .toList(); final widest = adjustedBlockWidths[widestBlockIndex]; adjustedBlockWidths[widestBlockIndex] = math.max( widest - adjustment, _FramePhaseBlock.minBlockWidth, ); return adjustedBlockWidths; } } class _FramePhaseBlock extends StatelessWidget { const _FramePhaseBlock({ Key? key, required this.blockData, required this.width, }) : super(key: key); static const _height = 30.0; static const minBlockWidth = defaultIconSizeBeforeScaling + densePadding * 8; static const _backgroundColor = ThemedColor( light: Color(0xFFEEEEEE), dark: Color(0xFF3C4043), ); final _FramePhaseBlockData blockData; final double width; @override Widget build(BuildContext context) { final theme = Theme.of(context); final colorScheme = theme.colorScheme; return DevToolsTooltip( message: blockData.display, child: Container( decoration: BoxDecoration( color: _backgroundColor.colorFor(colorScheme), border: Border.all(color: theme.focusColor), ), height: _height, width: width, padding: const EdgeInsets.symmetric(horizontal: densePadding), child: LayoutBuilder( builder: (context, constraints) { final minWidthForText = defaultIconSize + densePadding * 2 + denseSpacing + calculateTextSpanWidth(TextSpan(text: blockData.display)); bool includeText = true; if (constraints.maxWidth < minWidthForText) { includeText = false; } return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( blockData.icon, size: defaultIconSize, ), if (includeText) ...[ const SizedBox(width: denseSpacing), Text( blockData.display, overflow: TextOverflow.ellipsis, ), ], ], ); }, ), ), ); } } class _FramePhaseBlockData { _FramePhaseBlockData({ required this.title, required this.duration, required this.flex, required this.icon, }); final String title; final Duration duration; final int flex; final IconData icon; String get display { final text = duration != Duration.zero ? durationText( duration, unit: DurationDisplayUnit.milliseconds, allowRoundingToZero: false, ) : '--'; return '$title - $text'; } }
devtools/packages/devtools_app/lib/src/screens/performance/panes/frame_analysis/frame_time_visualizer.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/frame_analysis/frame_time_visualizer.dart", "repo_id": "devtools", "token_count": 3692 }
89
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/utils.dart'; import 'package:vm_service/vm_service.dart'; import '../../service/service_registrations.dart' as registrations; import '../../shared/diagnostics/inspector_service.dart'; import '../../shared/feature_flags.dart'; import '../../shared/globals.dart'; import '../../shared/offline_mode.dart'; import 'panes/controls/enhance_tracing/enhance_tracing_controller.dart'; import 'panes/flutter_frames/flutter_frame_model.dart'; import 'panes/flutter_frames/flutter_frames_controller.dart'; import 'panes/raster_stats/raster_stats_controller.dart'; import 'panes/rebuild_stats/rebuild_stats_model.dart'; import 'panes/timeline_events/timeline_events_controller.dart'; import 'performance_model.dart'; import 'performance_screen.dart'; /// This class contains the business logic for [performance_screen.dart]. /// /// The controller manages the performance data model and feature controllers, /// which handle things like data processing and communication with the view /// to give and receive data updates. class PerformanceController extends DisposableController with AutoDisposeControllerMixin, OfflineScreenControllerMixin<OfflinePerformanceData> { PerformanceController() { // TODO(https://github.com/flutter/devtools/issues/5100): clean this up to // only create a controller when it is needed, flutterFramesController = FlutterFramesController(this); timelineEventsController = TimelineEventsController(this); rasterStatsController = RasterStatsController(this); _featureControllers = [ flutterFramesController, timelineEventsController, rasterStatsController, ]; if (serviceConnection.serviceManager.connectedApp?.isDartWebAppNow ?? false) { // Do not perform initialization for web apps. return; } // See https://github.com/dart-lang/linter/issues/3801 // ignore: discarded_futures unawaited(_init()); } late final FlutterFramesController flutterFramesController; late final TimelineEventsController timelineEventsController; late final RasterStatsController rasterStatsController; late List<PerformanceFeatureController> _featureControllers; // TODO(jacobr): add the recount controller to [_featureControllers] once your // PR for rebuild indicators lands //(https://github.com/flutter/devtools/pull/4566). final rebuildCountModel = RebuildCountModel(); /// Index of the selected feature tab. /// /// This value is used to set the initial tab selection of the /// [TabbedPerformanceView]. This widget will be disposed and re-initialized /// on DevTools screen changes, so we must store this value in the controller /// instead of the widget state. int selectedFeatureTabIndex = 0; bool _fetchMissingLocationsStarted = false; IsolateRef? _currentRebuildWidgetsIsolate; final enhanceTracingController = EnhanceTracingController(); /// Performance screen data loaded via import. /// /// This is expected to be null when we are not in /// [offlineController.offlineMode]. /// /// This will contain the original data from the imported file, regardless of /// any selection modifications that occur while the data is displayed. OfflinePerformanceData? offlinePerformanceData; bool get impellerEnabled => _impellerEnabled; bool _impellerEnabled = false; final _initialized = Completer<void>(); Future<void> get initialized => _initialized.future; Future<void> _init() async { await _initHelper(); _initialized.complete(); } Future<void> _initHelper() async { initReviewHistoryOnDisconnectListener(); await _applyToFeatureControllersAsync((c) => c.init()); if (!offlineController.offlineMode.value) { await serviceConnection.serviceManager.onServiceAvailable; if (serviceConnection.serviceManager.connectedApp?.isFlutterAppNow ?? false) { final impellerEnabledResponse = await serviceConnection.serviceManager .callServiceExtensionOnMainIsolate( registrations.isImpellerEnabled, ); _impellerEnabled = impellerEnabledResponse.json?['enabled'] == true; } else { _impellerEnabled = false; } enhanceTracingController.init(); // Listen for Flutter.Frame events with frame timing data. // Listen for Flutter.RebuiltWidgets events. autoDisposeStreamSubscription( serviceConnection .serviceManager.service!.onExtensionEventWithHistorySafe .listen((event) { if (event.extensionKind == 'Flutter.Frame') { final frame = FlutterFrame.parse(event.extensionData!.data); enhanceTracingController.assignStateForFrame(frame); flutterFramesController.addFrame(frame); } else if (event.extensionKind == 'Flutter.RebuiltWidgets' && FeatureFlags.widgetRebuildstats) { if (_currentRebuildWidgetsIsolate != event.isolate) { rebuildCountModel.clearFromRestart(); } _currentRebuildWidgetsIsolate = event.isolate; // TODO(jacobr): need to make sure we don't get events from before // the last hot restart. Their data would be bogus. rebuildCountModel.processRebuildEvent(event.extensionData!.data); if (!rebuildCountModel.locationMap.locationsResolved.value && !_fetchMissingLocationsStarted) { _fetchMissingRebuildLocations(); } } }), ); } else { await maybeLoadOfflineData( PerformanceScreen.id, // TODO(kenz): make sure DevTools exports can be loaded into the full // Perfetto trace viewer (ui.perfetto.dev). createData: (json) => OfflinePerformanceData.parse(json), shouldLoad: (data) => !data.isEmpty, ); } } void _fetchMissingRebuildLocations() async { if (_fetchMissingLocationsStarted) return; // Some locations are missing. This occurs if rebuilds were // enabled before DevTools connected because rebuild events only // include locations that have not yet been sent with an event. _fetchMissingLocationsStarted = true; final inspectorService = serviceConnection.inspectorService! as InspectorService; final expectedIsolate = _currentRebuildWidgetsIsolate; final json = await inspectorService.widgetLocationIdMap(); // Don't apply the json if the isolate has been restarted // while we were waiting for a response. if (_currentRebuildWidgetsIsolate == expectedIsolate) { // It is strange if unresolved Locations have resolved on their // own. This wouldn't be a big deal but suggests a logic bug // somewhere. assert(!rebuildCountModel.locationMap.locationsResolved.value); rebuildCountModel.locationMap.processLocationMap(json); // Only one call to fetch missing locations should ever be // needed as rebuild events include all associated locations. assert(rebuildCountModel.locationMap.locationsResolved.value); } } /// Calls [callback] for each feature controller in [_featureControllers]. /// /// [callback] can return a [Future] or a [FutureOr] void _applyToFeatureControllers( void Function(PerformanceFeatureController) callback, ) { _featureControllers.forEach(callback); } /// Calls [callback] for each feature controller in [_featureControllers]. /// /// [callback] can return a [Future] or a [FutureOr] Future<void> _applyToFeatureControllersAsync( FutureOr<void> Function(PerformanceFeatureController) callback, ) async { Future<void> helper( FutureOr<void> Function(PerformanceFeatureController) futureOr, PerformanceFeatureController controller, ) async { await futureOr(controller); } final futures = <Future<void>>[]; for (final controller in _featureControllers) { futures.add(helper(callback, controller)); } await Future.wait(futures); } Future<void> setActiveFeature( PerformanceFeatureController? featureController, ) async { await _applyToFeatureControllersAsync( (c) async => await c.setIsActiveFeature( featureController != null && c == featureController, ), ); } /// Clears the timeline data currently stored by the controller as well the /// VM timeline if a connected app is present. Future<void> clearData() async { if (serviceConnection.serviceManager.connectedAppInitialized) { await serviceConnection.serviceManager.service!.clearVMTimeline(); } offlinePerformanceData = null; serviceConnection.errorBadgeManager.clearErrors(PerformanceScreen.id); await _applyToFeatureControllersAsync((c) => c.clearData()); } @override void dispose() { _applyToFeatureControllers((c) => c.dispose()); enhanceTracingController.dispose(); super.dispose(); } @override OfflineScreenData screenDataForExport() => OfflineScreenData( screenId: PerformanceScreen.id, data: OfflinePerformanceData( perfettoTraceBinary: timelineEventsController.fullPerfettoTrace?.writeToBuffer(), frames: flutterFramesController.flutterFrames.value, selectedFrame: flutterFramesController.selectedFrame.value, rasterStats: rasterStatsController.rasterStats.value, rebuildCountModel: rebuildCountModel, displayRefreshRate: flutterFramesController.displayRefreshRate.value, ).toJson(), ); @override FutureOr<void> processOfflineData(OfflinePerformanceData offlineData) async { await clearData(); offlinePerformanceData = offlineData; await _applyToFeatureControllersAsync( (c) => c.setOfflineData(offlinePerformanceData!), ); } } abstract class PerformanceFeatureController extends DisposableController { PerformanceFeatureController(this.performanceController); final PerformanceController performanceController; /// Whether this feature is active and visible to the user. bool get isActiveFeature => _isActiveFeature; bool _isActiveFeature = false; Future<void> setIsActiveFeature(bool value) async { // Before allowing any feature controller to become "active", verify that // the [performanceController] has completed initializing. await performanceController.initialized; _isActiveFeature = value; if (value) { onBecomingActive(); } } void onBecomingActive(); Future<void> init(); Future<void> setOfflineData(OfflinePerformanceData offlineData); FutureOr<void> clearData(); void handleSelectedFrame(FlutterFrame frame); }
devtools/packages/devtools_app/lib/src/screens/performance/performance_controller.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/performance_controller.dart", "repo_id": "devtools", "token_count": 3508 }
90
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../../../shared/file_import.dart'; import '../../../../shared/globals.dart'; import '../../../../shared/screen.dart'; import '../../../../shared/ui/vm_flag_widgets.dart'; import '../../profiler_screen_controller.dart'; class ProfilerScreenControls extends StatelessWidget { const ProfilerScreenControls({ super.key, required this.controller, required this.recording, required this.processing, required this.offline, }); final ProfilerScreenController controller; final bool recording; final bool processing; final bool offline; @override Widget build(BuildContext context) { // TODO(kenz): use the [OfflineAwareControls] helper widget. return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (offline) Padding( padding: const EdgeInsets.only(right: defaultSpacing), child: ExitOfflineButton(gaScreen: gac.cpuProfiler), ) else ...[ _PrimaryControls( controller: controller, recording: recording, ), const SizedBox(width: defaultSpacing), _SecondaryControls( controller: controller, profilerBusy: recording || processing, ), ], ], ); } } class _PrimaryControls extends StatelessWidget { const _PrimaryControls({ required this.controller, required this.recording, }); static const _primaryControlsMinIncludeTextWidth = 1170.0; final ProfilerScreenController controller; final bool recording; @override Widget build(BuildContext context) { return Row( children: [ RecordButton( recording: recording, gaScreen: gac.cpuProfiler, gaSelection: gac.record, minScreenWidthForTextBeforeScaling: _primaryControlsMinIncludeTextWidth, onPressed: controller.startRecording, ), const SizedBox(width: denseSpacing), StopRecordingButton( recording: recording, gaScreen: gac.cpuProfiler, gaSelection: gac.stop, minScreenWidthForTextBeforeScaling: _primaryControlsMinIncludeTextWidth, onPressed: controller.stopRecording, ), const SizedBox(width: denseSpacing), ClearButton( gaScreen: gac.cpuProfiler, gaSelection: gac.clear, minScreenWidthForTextBeforeScaling: _primaryControlsMinIncludeTextWidth, onPressed: recording ? null : controller.clear, ), ], ); } } class _SecondaryControls extends StatelessWidget { const _SecondaryControls({ required this.controller, required this.profilerBusy, }); static const _profilingControlsMinScreenWidthForText = 930.0; final ProfilerScreenController controller; final bool profilerBusy; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.end, children: [ if (serviceConnection .serviceManager.connectedApp!.isFlutterNativeAppNow) GaDevToolsButton( icon: Icons.timer, label: 'Profile app start up', tooltip: 'Load all Dart CPU samples that occurred before \n' 'the first Flutter frame was drawn (if available)', tooltipPadding: const EdgeInsets.all(denseSpacing), gaScreen: gac.cpuProfiler, gaSelection: gac.CpuProfilerEvents.profileAppStartUp.name, minScreenWidthForTextBeforeScaling: _profilingControlsMinScreenWidthForText, onPressed: !profilerBusy ? controller.cpuProfilerController.loadAppStartUpProfile : null, ), const SizedBox(width: denseSpacing), RefreshButton( label: 'Load all CPU samples', tooltip: 'Load all available CPU samples from the profiler', gaScreen: gac.cpuProfiler, gaSelection: gac.CpuProfilerEvents.loadAllCpuSamples.name, minScreenWidthForTextBeforeScaling: _profilingControlsMinScreenWidthForText, onPressed: !profilerBusy ? controller.cpuProfilerController.loadAllSamples : null, ), const SizedBox(width: denseSpacing), CpuSamplingRateDropdown( screenId: gac.cpuProfiler, profilePeriodFlagNotifier: controller.cpuProfilerController.profilePeriodFlag!, ), const SizedBox(width: denseSpacing), OpenSaveButtonGroup( screenId: ScreenMetaData.cpuProfiler.id, onSave: !profilerBusy && controller.cpuProfileData != null && controller.cpuProfileData?.isEmpty == false ? _exportPerformance : null, ), ], ); } void _exportPerformance() { controller.exportData(); // TODO(kenz): investigate if we need to do any error handling here. Is the // download always successful? } }
devtools/packages/devtools_app/lib/src/screens/profiler/panes/controls/profiler_screen_controls.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/profiler/panes/controls/profiler_screen_controls.dart", "repo_id": "devtools", "token_count": 2282 }
91
// 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:collection/collection.dart'; import 'package:devtools_app_shared/service.dart'; import 'package:flutter/foundation.dart'; import 'package:vm_service/vm_service.dart' hide SentinelException, Error; import 'fake_freezed_annotation.dart'; // This part is generated using `package:freezed`, but without the devtool depending // on the package. // To update the generated files, temporarily add freezed/freezed_annotation/build_runner // as dependencies; replace the `fake_freezed_annotation.dart` import with the // real annotation package, then execute `pub run build_runner build`. part 'result.freezed.dart'; @freezed class Result<T> with _$Result<T> { Result._(); factory Result.data(T value) = _ResultData<T>; factory Result.error(Object error, StackTrace stackTrace) = _ResultError<T>; factory Result.guard(T Function() cb) { try { return Result.data(cb()); } catch (err, stack) { return Result.error(err, stack); } } static Future<Result<T>> guardFuture<T>(Future<T> Function() cb) async { try { return Result.data(await cb()); } catch (err, stack) { return Result.error(err, stack); } } Result<Res> chain<Res>(Res Function(T value) cb) { return when( data: (value) { try { return Result.data(cb(value)); } catch (err, stack) { return Result.error(err, stack); } }, error: (err, stack) => Result.error(err, stack), ); } T get dataOrThrow { return when( data: (value) => value, error: Error.throwWithStackTrace, ); } } Result<T> parseSentinel<T>(Object? value) { if (value is T) return Result.data(value); if (value == null) { return Result.error( ArgumentError( 'Expected $value to be an instance of $T but received `null`', ), StackTrace.current, ); } if (value is Sentinel) { return Result.error( SentinelException(value), StackTrace.current, ); } return Result.error(value, StackTrace.current); }
devtools/packages/devtools_app/lib/src/screens/provider/instance_viewer/result.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/provider/instance_viewer/result.dart", "repo_id": "devtools", "token_count": 817 }
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 'package:flutter/material.dart'; import 'package:vm_service/vm_service.dart'; import '../../../shared/common_widgets.dart'; import '../../../shared/history_viewport.dart'; import '../../../shared/primitives/history_manager.dart'; import 'object_inspector_view_controller.dart'; import 'vm_class_display.dart'; import 'vm_code_display.dart'; import 'vm_field_display.dart'; import 'vm_function_display.dart'; import 'vm_ic_data_display.dart'; import 'vm_instance_display.dart'; import 'vm_library_display.dart'; import 'vm_object_model.dart'; import 'vm_object_pool_display.dart'; import 'vm_script_display.dart'; import 'vm_simple_list_display.dart'; import 'vm_unknown_object_display.dart'; /// Displays the VM information for the currently selected object in the /// program explorer. class ObjectViewport extends StatelessWidget { const ObjectViewport({ Key? key, required this.controller, }) : super(key: key); final ObjectInspectorViewController controller; @override Widget build(BuildContext context) { return HistoryViewport<VmObject>( history: controller.objectHistory, controls: [ ToolbarRefresh(onPressed: controller.refreshObject), ], generateTitle: viewportTitle, contentBuilder: (context, _) { return ValueListenableBuilder<bool>( valueListenable: controller.refreshing, builder: (context, refreshing, _) { late Widget child; if (refreshing) { child = const CenteredCircularProgressIndicator(); } else { final currentObject = controller.objectHistory.current.value; child = currentObject == null ? const SizedBox.shrink() : buildObjectDisplay(currentObject); } return Expanded(child: child); }, ); }, ); } @visibleForTesting static String viewportTitle(VmObject? object) { if (object == null) { return 'No object selected.'; } if (object.obj is Instance) { final instance = object.obj as Instance; return 'Instance of ${instance.classRef!.name}'; } if (object is UnknownObject) { return 'Instance of VM type ${object.name}'; } return '${object.obj.type} ${object.name ?? ''}'.trim(); } /// Calls the object VM statistics card builder according to the VM Object type. @visibleForTesting Widget buildObjectDisplay(VmObject obj) { if (obj is ClassObject) { return VmClassDisplay( controller: controller, clazz: obj, ); } if (obj is FuncObject) { return VmFuncDisplay( controller: controller, function: obj, ); } if (obj is FieldObject) { return VmFieldDisplay( controller: controller, field: obj, ); } if (obj is LibraryObject) { return VmLibraryDisplay( controller: controller, library: obj, ); } if (obj is ScriptObject) { return VmScriptDisplay( controller: controller, script: obj, ); } if (obj is InstanceObject) { return VmInstanceDisplay( controller: controller, instance: obj, ); } if (obj is CodeObject) { return VmCodeDisplay( controller: controller, code: obj, ); } if (obj is ObjectPoolObject) { return VmObjectPoolDisplay( controller: controller, objectPool: obj, ); } if (obj is ICDataObject) { return VmICDataDisplay( controller: controller, icData: obj, ); } if (obj is VmListObject) { return VmSimpleListDisplay( controller: controller, vmObject: obj, ); } if (obj is UnknownObject) { return VmUnknownObjectDisplay( controller: controller, object: obj, ); } return const SizedBox.shrink(); } } /// Manages the history of selected ObjRefs to make them accessible on a /// HistoryViewport. class ObjectHistory extends HistoryManager<VmObject> { void pushEntry(VmObject object) { if (object.obj == current.value?.obj) return; while (hasNext) { pop(); } push(object); } }
devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/object_viewport.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/object_viewport.dart", "repo_id": "devtools", "token_count": 1774 }
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 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:stack_trace/stack_trace.dart' as stack_trace; import 'package:vm_service/vm_service.dart'; import '../../shared/analytics/constants.dart' as gac; import '../../shared/common_widgets.dart'; import '../../shared/globals.dart'; import '../../shared/primitives/byte_utils.dart'; import '../../shared/primitives/utils.dart'; import '../../shared/tree.dart'; import '../debugger/codeview.dart'; import '../debugger/codeview_controller.dart'; import '../debugger/debugger_model.dart'; import 'object_inspector/inbound_references_tree.dart'; import 'object_inspector/object_inspector_view_controller.dart'; import 'object_inspector/vm_object_model.dart'; import 'vm_service_private_extensions.dart'; /// A convenience widget used to create non-scrollable information cards. /// /// `title` is displayed as the header of the card and is required. /// /// `rowKeyValues` takes a list of key-value pairs that are to be displayed as /// individual rows. These rows will have an alternating background color. /// /// `table` is a widget (typically a table) that is to be displayed after the /// rows specified for `rowKeyValues`. class VMInfoCard extends StatelessWidget implements PreferredSizeWidget { const VMInfoCard({ super.key, required this.title, this.roundedTopBorder = true, this.rowKeyValues, this.table, }); final String title; final bool roundedTopBorder; final List<MapEntry<String, WidgetBuilder>>? rowKeyValues; final Widget? table; @override Widget build(BuildContext context) { return SizedBox.fromSize( size: preferredSize, child: VMInfoList( title: title, roundedTopBorder: roundedTopBorder, rowKeyValues: rowKeyValues, table: table, ), ); } @override Size get preferredSize { if (table != null) { return Size.infinite; } return Size.fromHeight( defaultHeaderHeight + (rowKeyValues?.length ?? 0) * defaultRowHeight + defaultSpacing, ); } } MapEntry<String, WidgetBuilder> selectableTextBuilderMapEntry( String key, String? value, ) { return MapEntry( key, (context) => Text( value ?? '--', style: Theme.of(context).fixedFontStyle, ), ); } MapEntry<String, WidgetBuilder> serviceObjectLinkBuilderMapEntry({ required ObjectInspectorViewController controller, required String key, required Response? object, bool preferUri = false, String Function(Response?)? textBuilder, }) { return MapEntry( key, (context) => VmServiceObjectLink( object: object, textBuilder: textBuilder, preferUri: preferUri, onTap: controller.findAndSelectNodeForObject, ), ); } class VMInfoList extends StatelessWidget { const VMInfoList({ super.key, required this.title, this.roundedTopBorder = true, this.rowKeyValues, this.table, }); final String title; final bool roundedTopBorder; final List<MapEntry<String, WidgetBuilder>>? rowKeyValues; final Widget? table; @override Widget build(BuildContext context) { final theme = Theme.of(context); // Create shadow variables locally to avoid extra null checks. final rowKeyValues = this.rowKeyValues; final table = this.table; final listScrollController = ScrollController(); return Column( children: [ AreaPaneHeader( title: Text(title), includeTopBorder: false, roundedTopBorder: roundedTopBorder, ), if (rowKeyValues != null) Expanded( child: Scrollbar( thumbVisibility: true, controller: listScrollController, child: ListView( controller: listScrollController, children: prettyRows( context, [ for (final row in rowKeyValues) Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( '${row.key.toString()}:', style: theme.fixedFontStyle, ), const SizedBox(width: denseSpacing), Flexible( child: Builder(builder: row.value), ), ], ), ], ), ), ), ), if (table != null) table, ], ); } } List<Widget> prettyRows(BuildContext context, List<Row> rows) { return [ for (int i = 0; i < rows.length; ++i) _buildAlternatingRow(context, i, rows[i]), ]; } Widget _buildAlternatingRow(BuildContext context, int index, Widget row) { return Container( color: alternatingColorForIndex(index, Theme.of(context).colorScheme), height: defaultRowHeight, padding: const EdgeInsets.symmetric( horizontal: defaultSpacing, ), child: row, ); } /// Displays a RequestDataButton if the data provided by [sizeProvider] is null, /// otherwise displays the size data and a ToolbarRefresh button next /// to it, to request that data again if required. /// /// When the data is being requested (the value of [fetching] is true), /// a CircularProgressIndicator will be displayed. class RequestableSizeWidget extends StatelessWidget { const RequestableSizeWidget({ super.key, required this.fetching, required this.sizeProvider, required this.requestFunction, }); final ValueListenable<bool> fetching; final InstanceRef? Function() sizeProvider; final void Function() requestFunction; @override Widget build(BuildContext context) { return ValueListenableBuilder<bool>( valueListenable: fetching, builder: (context, fetching, _) { if (fetching) { return const AspectRatio( aspectRatio: 1, child: Padding( padding: EdgeInsets.all(densePadding), child: CircularProgressIndicator(), ), ); } else { final size = sizeProvider(); return size == null ? GaDevToolsButton( icon: Icons.call_made, label: 'Request', outlined: false, gaScreen: gac.vmTools, gaSelection: gac.requestSize, onPressed: requestFunction, ) : Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Text( size.valueAsString == null ? '--' : prettyPrintBytes( int.parse(size.valueAsString!), includeUnit: true, maxBytes: 512, )!, ), ToolbarRefresh(onPressed: requestFunction), ], ); } }, ); } } /// Returns the name of a function, qualified with the name of /// its owner added as a prefix, separated by a period. /// /// For example: for function build with owner class Foo, /// the qualified name would be Foo.build. /// If the owner of a function is another function, qualifiedName will /// recursively call itself until it reaches the owner class. /// If the owner is a library instead, the library name will not be /// included in the qualified name. String? qualifiedName(ObjRef? ref) { if (ref == null) return null; if (ref is ClassRef) { return '${ref.name}'; } else if (ref is FuncRef) { return ref.owner is! LibraryRef ? '${qualifiedName(ref.owner)}.${ref.name}' : '${ref.name}'; } throw Exception('Unexpected owner type: ${ref.type}'); } /// An ExpansionTile with an AreaPaneHeader as header and custom style /// for the VM tools tab. class VmExpansionTile extends StatelessWidget { const VmExpansionTile({ super.key, required this.title, required this.children, this.onExpanded, }); final String title; final List<Widget> children; final void Function(bool)? onExpanded; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Card( child: ListTileTheme( data: ListTileTheme.of(context).copyWith( dense: true, ), child: Theme( // Prevents divider lines appearing at the top and bottom of the // expanded ExpansionTile. data: theme.copyWith(dividerColor: Colors.transparent), child: ExpansionTile( title: DefaultTextStyle( style: theme.textTheme.titleSmall!, child: Text(title), ), onExpansionChanged: onExpanded, tilePadding: const EdgeInsets.only( left: defaultSpacing, right: defaultSpacing, ), children: children, ), ), ), ); } } class SizedCircularProgressIndicator extends StatelessWidget { const SizedCircularProgressIndicator({super.key}); @override Widget build(BuildContext context) { return SizedBox.fromSize( size: const Size.fromHeight( 2 * (defaultIconSizeBeforeScaling + denseSpacing), ), child: const CenteredCircularProgressIndicator(), ); } } class ExpansionTileInstanceList extends StatelessWidget { const ExpansionTileInstanceList({ super.key, required this.controller, required this.title, required this.elements, }); final ObjectInspectorViewController controller; final String title; final List<Response?> elements; @override Widget build(BuildContext context) { final theme = Theme.of(context); final children = <Row>[ for (int i = 0; i < elements.length; ++i) Row( children: [ Text( '[$i]: ', style: theme.subtleFixedFontStyle, ), VmServiceObjectLink( object: elements[i], onTap: controller.findAndSelectNodeForObject, ), ], ), ]; return VmExpansionTile( title: '$title (${elements.length})', children: prettyRows(context, children), ); } } /// An expandable list to display the retaining objects for a given RetainingPath. class RetainingPathWidget extends StatelessWidget { const RetainingPathWidget({ super.key, required this.controller, required this.retainingPath, this.onExpanded, }); final ObjectInspectorViewController controller; final ValueListenable<RetainingPath?> retainingPath; final void Function(bool)? onExpanded; @override Widget build(BuildContext context) { return ValueListenableBuilder<RetainingPath?>( valueListenable: retainingPath, builder: (context, retainingPath, _) { final retainingObjects = retainingPath == null ? const <Widget>[] : _retainingPathList( context, retainingPath, ); return VmExpansionTile( title: 'Retaining Path', onExpanded: onExpanded, children: [ retainingPath == null ? const SizedCircularProgressIndicator() : SizedBox.fromSize( size: Size.fromHeight( retainingObjects.length * defaultRowHeight + densePadding, ), child: Column(children: retainingObjects), ), ], ); }, ); } /// Returns a list of Widgets that will be the rows in the VmExpansionTile /// for RetainingPathWidget. List<Widget> _retainingPathList( BuildContext context, RetainingPath retainingPath, ) { Future<void> onTap(ObjRef? obj) async { if (obj == null) return; await controller.findAndSelectNodeForObject(obj); } final theme = Theme.of(context); final emptyList = Text( 'No retaining objects', style: theme.fixedFontStyle, ); if (retainingPath.elements == null) return [emptyList]; final firstRetainingObject = retainingPath.elements!.isNotEmpty ? VmServiceObjectLink( object: retainingPath.elements!.first.value, onTap: onTap, ) : emptyList; final retainingObjects = [ Row( children: [ firstRetainingObject, ], ), if (retainingPath.elements!.length > 1) for (RetainingObject object in retainingPath.elements!.sublist(1)) Row( children: [ Flexible( child: DefaultTextStyle( style: theme.fixedFontStyle, child: _RetainingObjectDescription( object: object, onTap: onTap, ), ), ), ], ), Row( children: [ Text( 'Retained by a GC root of type: ${retainingPath.gcRootType ?? '<unknown>'}', style: theme.fixedFontStyle, ), ], ), ]; return prettyRows(context, retainingObjects); } } class _RetainingObjectDescription extends StatelessWidget { const _RetainingObjectDescription({ required this.object, required this.onTap, }); final RetainingObject object; final void Function(ObjRef? obj) onTap; @override Widget build(BuildContext context) { final parentListIndex = object.parentListIndex; if (parentListIndex != null) { return RichText( text: TextSpan( children: [ TextSpan(text: 'Retained by element [$parentListIndex] of '), VmServiceObjectLink( object: object.value, onTap: onTap, ).buildTextSpan(context), ], ), ); } if (object.parentMapKey != null) { return RichText( text: TextSpan( children: [ const TextSpan(text: 'Retained by element at ['), VmServiceObjectLink(object: object.parentMapKey, onTap: onTap) .buildTextSpan(context), const TextSpan(text: '] of '), VmServiceObjectLink(object: object.value, onTap: onTap) .buildTextSpan(context), ], ), ); } final entries = <TextSpan>[ const TextSpan(text: 'Retained by '), ]; if (object.parentField is int) { assert((object.value as InstanceRef).kind == InstanceKind.kRecord); entries.add(TextSpan(text: '\$${object.parentField} of ')); } else if (object.parentField != null) { entries.add(TextSpan(text: '${object.parentField} of ')); } if (object.value is FieldRef) { final field = object.value as FieldRef; entries.addAll( [ VmServiceObjectLink( object: field.declaredType, onTap: onTap, ).buildTextSpan(context), const TextSpan(text: ' '), VmServiceObjectLink( object: field, onTap: onTap, ).buildTextSpan(context), const TextSpan(text: ' of '), VmServiceObjectLink( object: field.owner, onTap: onTap, ).buildTextSpan(context), ], ); } else if (object.value is FuncRef) { final func = object.value as FuncRef; entries.add( VmServiceObjectLink( object: func, onTap: onTap, ).buildTextSpan(context), ); } else { entries.add( VmServiceObjectLink( object: object.value, onTap: onTap, ).buildTextSpan(context), ); } return RichText( text: TextSpan(children: entries), ); } } class InboundReferencesTree extends StatelessWidget { const InboundReferencesTree({ super.key, required this.controller, required this.object, this.onExpanded, }); final ObjectInspectorViewController controller; final VmObject object; final void Function(bool)? onExpanded; @override Widget build(BuildContext context) { final theme = Theme.of(context); return VmExpansionTile( title: 'Inbound References', onExpanded: onExpanded, children: [ const Divider(height: 1), Container( color: theme.expansionTileTheme.backgroundColor, child: ValueListenableBuilder( valueListenable: object.inboundReferencesTree, builder: (context, references, _) { return TreeView<InboundReferencesTreeNode>( dataRootsListenable: object.inboundReferencesTree, dataDisplayProvider: (node, _) => InboundReferenceWidget( controller: controller, node: node, ), emptyTreeViewBuilder: () { return Padding( padding: EdgeInsets.all(defaultRowHeight / 2), child: const Text( 'There are no inbound references for this object', ), ); }, onItemExpanded: object.expandInboundRef, onItemSelected: (_) => null, ); }, ), ), ], ); } } /// An entry in a [InboundReferencesTree]. class InboundReferenceWidget extends StatelessWidget { const InboundReferenceWidget({ super.key, required this.controller, required this.node, }); final ObjectInspectorViewController controller; final InboundReferencesTreeNode node; @override Widget build(BuildContext context) { final theme = Theme.of(context); final rowContent = <Widget>[ const Text('Referenced by '), ]; final parentField = node.ref.parentField; if (parentField != null) { if (parentField is int) { // The parent field is an entry in a list rowContent.add(Text('element $parentField of ')); } else if (parentField is String) { rowContent.add(Text('$parentField in ')); } } rowContent.add( VmServiceObjectLink( object: node.ref.source, onTap: controller.findAndSelectNodeForObject, ), ); return DefaultTextStyle( style: theme.regularTextStyle, child: Row( children: rowContent, ), ); } } class VmServiceObjectLink extends StatelessWidget { const VmServiceObjectLink({ super.key, required this.object, required this.onTap, this.preferUri = false, this.textBuilder, }); final Response? object; final bool preferUri; final String? Function(Response?)? textBuilder; final FutureOr<void> Function(ObjRef) onTap; @visibleForTesting static String? defaultTextBuilder( Object? object, { bool preferUri = false, }) { if (object == null) return null; return switch (object) { FieldRef(:final name) || FuncRef(:final name) || CodeRef(:final name) || TypeArgumentsRef(:final name) => name, // If a class has an empty name, it's a special "top level" class. ClassRef(:final name) => name!.isEmpty ? 'top-level-class' : name, LibraryRef(:final uri, :final name) => uri!.startsWith('dart') || preferUri ? uri : (name!.isEmpty ? uri : name), ScriptRef(:final uri) => uri, ContextRef(:final length) => 'Context(length: $length)', Sentinel(:final valueAsString) => 'Sentinel $valueAsString', InstanceRef() => _textForInstanceRef(object), ObjRef(:final isICData) when isICData => 'ICData(${object.asICData.selector})', ObjRef(:final isObjectPool) when isObjectPool => 'Object Pool(length: ${object.asObjectPool.length})', ObjRef(:final isWeakArray) when isWeakArray => 'WeakArray(length: ${object.asWeakArray.length})', ObjRef(:final vmType) => vmType, _ => null, }; } static String? _textForInstanceRef(InstanceRef instance) { final valueAsString = instance.valueAsString; switch (instance.kind) { case InstanceKind.kList: return 'List(length: ${instance.length})'; case InstanceKind.kMap: return 'Map(length: ${instance.length})'; case InstanceKind.kRecord: return 'Record'; case InstanceKind.kType: case InstanceKind.kTypeParameter: return instance.name; case InstanceKind.kStackTrace: final trace = stack_trace.Trace.parse(valueAsString!); final depth = trace.frames.length; return 'StackTrace ($depth ${pluralize('frame', depth)})'; default: return valueAsString ?? '${instance.classRef!.name}'; } } TextSpan buildTextSpan(BuildContext context) { final theme = Theme.of(context); String? text = textBuilder?.call(object) ?? defaultTextBuilder(object, preferUri: preferUri); // Sentinels aren't objects that can be inspected. final isServiceObject = object is! Sentinel && text != null; text ??= object.toString(); final TextStyle style; if (isServiceObject) { style = theme.linkTextStyle; } else { style = theme.regularTextStyle; } return TextSpan( text: text, style: style.apply(overflow: TextOverflow.ellipsis), recognizer: isServiceObject ? (TapGestureRecognizer() ..onTap = () async { final obj = object; if (obj is ObjRef) { await onTap(obj); } }) : null, ); } @override Widget build(BuildContext context) { return RichText( maxLines: 1, text: TextSpan( children: [buildTextSpan(context)], ), ); } } /// A widget for the object inspector historyViewport containing the main /// layout of information widgets related to VM object types. class VmObjectDisplayBasicLayout extends StatelessWidget { const VmObjectDisplayBasicLayout({ super.key, required this.controller, required this.object, required this.generalDataRows, this.sideCardDataRows, this.generalInfoTitle = 'General Information', this.sideCardTitle = 'Object Details', this.expandableWidgets, }); final ObjectInspectorViewController controller; final VmObject object; final List<MapEntry<String, WidgetBuilder>> generalDataRows; final List<MapEntry<String, WidgetBuilder>>? sideCardDataRows; final String generalInfoTitle; final String sideCardTitle; final List<Widget>? expandableWidgets; @override Widget build(BuildContext context) { return ListView( children: [ IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Flexible( child: OutlineDecoration( showLeft: false, showTop: false, showRight: sideCardDataRows != null, child: VMInfoCard( title: generalInfoTitle, rowKeyValues: generalDataRows, roundedTopBorder: false, ), ), ), if (sideCardDataRows != null) Flexible( child: OutlineDecoration.onlyBottom( child: VMInfoCard( title: sideCardTitle, rowKeyValues: sideCardDataRows, ), ), ), ], ), ), RetainingPathWidget( controller: controller, retainingPath: object.retainingPath, onExpanded: _onExpandRetainingPath, ), InboundReferencesTree( controller: controller, object: object, onExpanded: _onExpandInboundRefs, ), ...?expandableWidgets, ], ); } void _onExpandRetainingPath(bool _) { if (object.retainingPath.value == null) { unawaited(object.requestRetainingPath()); } } void _onExpandInboundRefs(bool _) { if (object.inboundReferencesTree.value.isEmpty) { unawaited(object.requestInboundsRefs()); } } } MapEntry<String, WidgetBuilder> shallowSizeRowBuilder(VmObject object) { return selectableTextBuilderMapEntry( 'Shallow Size', prettyPrintBytes( object.obj.size ?? 0, includeUnit: true, maxBytes: 512, ), ); } MapEntry<String, WidgetBuilder> reachableSizeRowBuilder(VmObject object) { return MapEntry( 'Reachable Size', (context) => RequestableSizeWidget( fetching: object.fetchingReachableSize, sizeProvider: () => object.reachableSize, requestFunction: object.requestReachableSize, ), ); } MapEntry<String, WidgetBuilder> retainedSizeRowBuilder(VmObject object) { return MapEntry( 'Retained Size', (context) => RequestableSizeWidget( fetching: object.fetchingRetainedSize, sizeProvider: () => object.retainedSize, requestFunction: object.requestRetainedSize, ), ); } List<MapEntry<String, WidgetBuilder>> vmObjectGeneralDataRows( ObjectInspectorViewController controller, VmObject object, ) { return [ selectableTextBuilderMapEntry('Object Class', object.obj.type), shallowSizeRowBuilder(object), reachableSizeRowBuilder(object), retainedSizeRowBuilder(object), if (object is ClassObject && object.obj.library != null) serviceObjectLinkBuilderMapEntry( controller: controller, key: 'Library', object: object.obj.library!, ), if (object is ScriptObject) serviceObjectLinkBuilderMapEntry( controller: controller, key: 'Library', object: object.obj.library!, ), if (object is FieldObject) serviceObjectLinkBuilderMapEntry( controller: controller, key: 'Owner', object: object.obj.owner!, ), if (object is FuncObject) serviceObjectLinkBuilderMapEntry( controller: controller, key: 'Owner', object: object.obj.owner!, ), if (object is! ScriptObject && object is! LibraryObject && object.script != null) serviceObjectLinkBuilderMapEntry( controller: controller, key: 'Script', object: object.script!, textBuilder: (s) { final script = s as ScriptRef; return '${fileNameFromUri(script.uri) ?? ''}:${object.pos?.toString() ?? ''}'; }, ), ]; } /// Creates a simple [CodeView] which displays the code relevant to [object] in /// [script]. /// /// If [object] is synthetic and doesn't have actual token positions, /// [object]'s owner's code will be displayed instead. class ObjectInspectorCodeView extends StatefulWidget { ObjectInspectorCodeView({ required this.codeViewController, required this.script, required this.object, required this.child, }) : super(key: ValueKey(object)); final CodeViewController codeViewController; final ScriptRef script; final ObjRef object; final Widget child; @override State<ObjectInspectorCodeView> createState() => _ObjectInspectorCodeViewState(); } class _ObjectInspectorCodeViewState extends State<ObjectInspectorCodeView> { @override void didChangeDependencies() { super.didChangeDependencies(); unawaited(_maybeResetScriptLocation()); } @override void didUpdateWidget(ObjectInspectorCodeView oldWidget) { super.didUpdateWidget(oldWidget); unawaited(_maybeResetScriptLocation()); } Future<void> _maybeResetScriptLocation() async { if (widget.script != widget.codeViewController.currentScriptRef.value) { await widget.codeViewController.resetScriptLocation( ScriptLocation(widget.script), ); } } @override Widget build(BuildContext context) { return ValueListenableBuilder<ParsedScript?>( valueListenable: widget.codeViewController.currentParsedScript, builder: (context, currentParsedScript, _) { LineRange? lineRange; if (currentParsedScript != null) { final obj = widget.object; SourceLocation? location; if (obj is ClassRef) { location = obj.location!; } else if (obj is FuncRef) { location = obj.location!; // If there's no line associated with the location, we're likely // dealing with an artificial field / method like a constructor. // We'll display the owner's code instead of showing nothing, // although showing a "No Source Available" message is another // option. final owner = obj.owner; if (location.line == null && owner is ClassRef) { location = owner.location; } } else if (obj is FieldRef) { location = obj.location!; // If there's no line associated with the location, we're likely // dealing with an artificial field / method like a constructor. // We'll display the owner's code instead of showing nothing, // although showing a "No Source Available" message is another // option. final owner = obj.owner; if (location.line == null && owner is ClassRef) { location = owner.location; } } if (location != null && location.line != null && location.endTokenPos != null) { final script = currentParsedScript.script; final startLine = location.line!; final endLine = script.getLineNumberFromTokenPos( location.endTokenPos!, )!; lineRange = LineRange(startLine, endLine); } } return SplitPane( axis: Axis.vertical, initialFractions: const [0.5, 0.5], children: [ OutlineDecoration.onlyBottom( child: widget.child, ), Column( children: [ const AreaPaneHeader( roundedTopBorder: false, title: Text('Code Preview'), ), Expanded( child: CodeView( codeViewController: widget.codeViewController, scriptRef: widget.script, parsedScript: currentParsedScript, enableHistory: false, lineRange: lineRange, onSelected: breakpointManager.toggleBreakpoint, ), ), ], ), ], ); }, ); } }
devtools/packages/devtools_app/lib/src/screens/vm_developer/vm_developer_common_widgets.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/vm_developer_common_widgets.dart", "repo_id": "devtools", "token_count": 13570 }
94
// 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 'analytics.dart' as ga; import 'analytics_controller.dart'; FutureOr<AnalyticsController> get devToolsAnalyticsController async { return AnalyticsController( enabled: false, firstRun: false, consentMessage: await ga.fetchAnalyticsConsentMessage(), ); }
devtools/packages/devtools_app/lib/src/shared/analytics/_analytics_controller_stub.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/analytics/_analytics_controller_stub.dart", "repo_id": "devtools", "token_count": 138 }
95
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'analytics_common.dart'; class MemoryScreenMetrics extends ScreenAnalyticsMetrics { MemoryScreenMetrics({ this.heapObjectsTotal, this.heapDiffObjectsBefore, this.heapDiffObjectsAfter, }); /// The number of objects in the 'before' heap for a diff calculation (used to /// provide scale for timing measurements). final int? heapDiffObjectsBefore; /// The number of objects in the 'after' heap for a diff calculation (used to /// provide scale for timing measurements). final int? heapDiffObjectsAfter; /// The number of objects in a heap snapshot that was captured. final int? heapObjectsTotal; } class PerformanceScreenMetrics extends ScreenAnalyticsMetrics { PerformanceScreenMetrics({ this.uiDuration, this.rasterDuration, this.shaderCompilationDuration, this.traceEventCount, }); /// The duration in microseconds for the UI time of a selected [FlutterFrame]. final Duration? uiDuration; /// The duration in microseconds for the Raster time of a selected /// [FlutterFrame]. final Duration? rasterDuration; /// The duration in microseconds for the shader compilation time of a selected /// [FlutterFrame]. final Duration? shaderCompilationDuration; /// The number of trace events that were processed (used to provide scale for /// timing measurements). final int? traceEventCount; } class ProfilerScreenMetrics extends ScreenAnalyticsMetrics { ProfilerScreenMetrics({ required this.cpuSampleCount, required this.cpuStackDepth, }); /// The number of CPU samples that were processed for a profile (used along /// with [cpuStackDepth] to provide scale for timing measurements). final int cpuSampleCount; /// The stack depth for a profile (used along with [cpuSampleCount] to provide /// scale for timing measurements). final int cpuStackDepth; } class InspectorScreenMetrics extends ScreenAnalyticsMetrics { InspectorScreenMetrics({ required this.rootSetCount, required this.rowCount, required this.inspectorTreeControllerId, }); static const int summaryTreeGaId = 0; static const int detailsTreeGaId = 1; /// The number of times the root has been set, since the /// [InspectorTreeController] with id [inspectorTreeControllerId], has been /// initialized. final int? rootSetCount; /// The number of rows that are in the root being shown to the user, from the /// [InspectorTreeController] with id [inspectorTreeControllerId]. final int? rowCount; /// The id of the [InspectorTreeController], for which this event is tracking. final int? inspectorTreeControllerId; }
devtools/packages/devtools_app/lib/src/shared/analytics/metrics.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/analytics/metrics.dart", "repo_id": "devtools", "token_count": 759 }
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 'package:flutter/rendering.dart'; import '../../primitives/utils.dart'; import '_drag_and_drop_desktop.dart' if (dart.library.js_interop) '_drag_and_drop_web.dart'; abstract class DragAndDropManager { factory DragAndDropManager(int viewId) => createDragAndDropManager(viewId); DragAndDropManager.impl(int viewId) : _viewId = viewId { init(); } static DragAndDropManager getInstance(int viewId) { return _instances.putIfAbsent(viewId, () => DragAndDropManager(viewId)); } static final _instances = <int, DragAndDropManager>{}; int get viewId => _viewId; final int _viewId; final _dragAndDropStates = <DragAndDropState>{}; DragAndDropState? activeState; /// The method is abstract, because we want to force descendants to define it. /// /// The method is called in [impl], so any initialization the subclasses need, /// like initializing listeners, should happen ahead of time in this method. void init(); @mustCallSuper void dispose() { _dragAndDropStates.clear(); } void registerDragAndDrop(DragAndDropState state) { _dragAndDropStates.add(state); } void unregisterDragAndDrop(DragAndDropState state) { _dragAndDropStates.remove(state); } void dragOver(double x, double y) { hitTestAndUpdateActiveId(x, y); activeState?.dragOver(); } void dragLeave() { activeState?.dragLeave(); } void drop() { activeState?.drop(); } /// Performs a hit test to find the active [DragAndDrop] widget at the (x, y) /// coordinates, and updates the active state for the previously active and /// newly active [DragAndDrop] widgets accordingly. void hitTestAndUpdateActiveId(double x, double y) { final hitTestResult = HitTestResult(); RendererBinding.instance .hitTestInView(hitTestResult, Offset(x, y), _viewId); // Starting at bottom of [hitTestResult.path], look for the first // [DragAndDrop] widget. This widget will be marked by a [RenderMetaData] // target with [DragAndDropMetaData] metaData that contains the widget's // [DragAndDropState]. for (final result in hitTestResult.path) { final target = result.target; if (target is RenderMetaData) { final metaData = target.metaData; // The first [DragAndDropMetaData] we find will be for the active // [DragAndDrop] widget. if (metaData is DragAndDropMetaData) { final newActiveState = metaData.state; // Activate the new state and deactivate the previously active state. final previousActiveState = activeState; previousActiveState?.setIsActive(false); activeState = newActiveState; activeState!.setIsActive(true); return; } } } } } class DragAndDrop extends StatefulWidget { const DragAndDrop({ super.key, required this.child, this.handleDrop, }); /// Callback to handle parsed data from drag and drop. /// /// The current implementation expects data in json format. final DevToolsJsonFileHandler? handleDrop; final Widget child; @override State<DragAndDrop> createState() => DragAndDropState(); } class DragAndDropState extends State<DragAndDrop> { final _dragging = ValueNotifier<bool>(false); DragAndDropManager? _dragAndDropManager; bool _isActive = false; void _refreshDragAndDropManager(int viewId) { if (_dragAndDropManager != null) { final oldViewId = _dragAndDropManager!.viewId; // Already registered to the right drag and drop manager, so do nothing. if (oldViewId == viewId) return; _dragAndDropManager?.unregisterDragAndDrop(this); _dragAndDropManager = null; } _dragAndDropManager = DragAndDropManager.getInstance(viewId); _dragAndDropManager!.registerDragAndDrop(this); } @override void initState() { super.initState(); } @override void dispose() { _dragAndDropManager?.unregisterDragAndDrop(this); super.dispose(); } @override Widget build(BuildContext context) { // Each time the widget is rebuilt it may be in a a new view. So the // dragAndDropManager is refreshed to ensure that we are registered in the // right context. _refreshDragAndDropManager(View.of(context).viewId); return MetaData( metaData: DragAndDropMetaData(state: this), child: widget.handleDrop != null ? ValueListenableBuilder<bool>( valueListenable: _dragging, builder: (context, dragging, _) { // TODO(kenz): use AnimatedOpacity instead. return Opacity( opacity: dragging ? 0.5 : 1.0, child: widget.child, ); }, ) : widget.child, ); } void dragOver() { _dragging.value = _isActive; } void dragLeave() { _dragEnd(); } void drop() { _dragEnd(); } void setIsActive(bool active) { _isActive = active; if (!_isActive) { _dragEnd(); } } void _dragEnd() { _dragging.value = false; } } /// MetaData for widgets related to drag and drop functionality ([DragAndDrop], /// [DragAndDropEventAbsorber]). /// /// Drag and drop widgets will contain a [MetaData] widget with the `metaData` /// field set to an instance of this class. [value] must be a unique identifier /// for [DragAndDrop] widgets. class DragAndDropMetaData { const DragAndDropMetaData({required this.state}); final DragAndDropState state; }
devtools/packages/devtools_app/lib/src/shared/config_specific/drag_and_drop/drag_and_drop.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/drag_and_drop/drag_and_drop.dart", "repo_id": "devtools", "token_count": 2046 }
97
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:logging/logging.dart'; final _log = Logger('allowed_error_default'); /// Catch and print errors from the given future. These errors are part of /// normal operation for an app, and don't need to be reported to analytics /// (i.e., they're not DevTools crashes). Future<T> allowedError<T>(Future<T> future, {bool logError = true}) { return future.catchError((Object error) { if (logError) { final errorLines = error.toString().split('\n'); _log.shout('[${error.runtimeType}] ${errorLines.first}'); _log.shout(errorLines.skip(1).join('\n')); } // TODO(srawlins): This is an illegal return value (`null`) for all `T`. // This function must return an actual `T`. // ignore: null_argument_to_non_null_type return Future<T>.value(); }); }
devtools/packages/devtools_app/lib/src/shared/config_specific/logger/_allowed_error_default.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/logger/_allowed_error_default.dart", "repo_id": "devtools", "token_count": 321 }
98
// 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:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:vm_service/vm_service.dart'; import '../../service/vm_service_wrapper.dart'; import '../diagnostics/dart_object_node.dart'; import '../diagnostics/diagnostics_node.dart'; import '../diagnostics/generic_instance_reference.dart'; import '../diagnostics/inspector_service.dart'; import '../diagnostics/tree_builder.dart'; import '../globals.dart'; import '../memory/adapted_heap_data.dart'; import '../primitives/utils.dart'; /// A line in the console. /// /// TODO(jacobr): support console lines that are structured error messages as /// well. class ConsoleLine { factory ConsoleLine.text( String text, { bool forceScrollIntoView = false, }) => TextConsoleLine( text, forceScrollIntoView: forceScrollIntoView, ); factory ConsoleLine.dartObjectNode( DartObjectNode variable, { bool forceScrollIntoView = false, }) => VariableConsoleLine( variable, forceScrollIntoView: forceScrollIntoView, ); ConsoleLine._(this.forceScrollIntoView); // Whether this console line should be scrolled into view when it is added. final bool forceScrollIntoView; } class TextConsoleLine extends ConsoleLine { TextConsoleLine(this.text, {bool forceScrollIntoView = false}) : super._(forceScrollIntoView); final String text; @override String toString() { return text; } } class VariableConsoleLine extends ConsoleLine { VariableConsoleLine(this.variable, {bool forceScrollIntoView = false}) : super._( forceScrollIntoView, ); final DartObjectNode variable; @override String toString() { return variable.toString(); } } /// Source of truth for the state of the Console including both events from the /// VM and events emitted from other UI. class ConsoleService with DisposerMixin { void appendBrowsableInstance({ required InstanceRef? instanceRef, required IsolateRef? isolateRef, required HeapObjectSelection? heapSelection, }) async { if (instanceRef == null) { final object = heapSelection?.object; if (object == null || isolateRef == null) { serviceConnection.consoleService.appendStdio( 'Not enough information to browse the instance.', ); return; } instanceRef = await evalService.findObject(object, isolateRef); } // If instanceRef is null at this point, user will see static references. appendInstanceRef( value: instanceRef, diagnostic: null, isolateRef: isolateRef, forceScrollIntoView: true, heapSelection: heapSelection, ); } void appendInstanceRef({ String? name, required InstanceRef? value, required RemoteDiagnosticsNode? diagnostic, required IsolateRef? isolateRef, bool forceScrollIntoView = false, bool expandAll = false, HeapObjectSelection? heapSelection, }) async { _stdioTrailingNewline = false; final variable = DartObjectNode.fromValue( name: name, value: value, diagnostic: diagnostic, isolateRef: isolateRef, heapSelection: heapSelection, ); // TODO(jacobr): fix out of order issues by tracking raw order. await buildVariablesTree(variable, expandAll: expandAll); if (expandAll) { variable.expandCascading(); } _stdio.add( ConsoleLine.dartObjectNode( variable, forceScrollIntoView: forceScrollIntoView, ), ); } final _stdio = ListValueNotifier<ConsoleLine>([]); bool _stdioTrailingNewline = false; InspectorObjectGroupBase get objectGroup { final inspectorService = serviceConnection.inspectorService!; if (_objectGroup?.inspectorService == inspectorService) { return _objectGroup!; } unawaited(_objectGroup?.dispose()); _objectGroup = inspectorService.createObjectGroup('console'); return _objectGroup!; } InspectorObjectGroupBase? _objectGroup; /// Clears the contents of stdio. void clearStdio() { if (_stdio.value.isNotEmpty) { _stdio.clear(); } } DartObjectNode? itemAt(int invertedIndex) { assert(invertedIndex >= 0); final list = _stdio.value; if (invertedIndex > list.length - 1) return null; final item = list[list.length - 1 - invertedIndex]; if (item is! VariableConsoleLine) return null; return item.variable; } /// Append to the stdout / stderr buffer. void appendStdio(String text) { const int kMaxLogItemsLowerBound = 5000; const int kMaxLogItemsUpperBound = 5500; // Parse out the new lines and append to the end of the existing lines. final newLines = text.split('\n'); var last = _stdio.value.safeLast; if (_stdio.value.isNotEmpty && !_stdioTrailingNewline && last is TextConsoleLine) { _stdio.last = ConsoleLine.text('${last.text}${newLines.first}'); if (newLines.length > 1) { _stdio .addAll(newLines.sublist(1).map((text) => ConsoleLine.text(text))); } } else { _stdio.addAll(newLines.map((text) => ConsoleLine.text(text))); } _stdioTrailingNewline = text.endsWith('\n'); // Don't report trailing blank lines. last = _stdio.value.safeLast; if (_stdio.value.isNotEmpty && (last is TextConsoleLine && last.text.isEmpty)) { _stdio.trimToSublist(0, _stdio.value.length - 1); } // For performance reasons, we drop older lines in batches, so the lines // will grow to kMaxLogItemsUpperBound then truncate to // kMaxLogItemsLowerBound. if (_stdio.value.length > kMaxLogItemsUpperBound) { _stdio.trimToSublist(_stdio.value.length - kMaxLogItemsLowerBound); } } /// Return the stdout and stderr emitted from the application. /// /// Note that this output might be truncated after significant output. ValueListenable<List<ConsoleLine>> get stdio { ensureServiceInitialized(); return _stdio; } void _handleStdoutEvent(Event event) { final String text = decodeBase64(event.bytes!); appendStdio(text); } void _handleStderrEvent(Event event) { final String text = decodeBase64(event.bytes!); // TODO(devoncarew): Change to reporting stdio along with information about // whether the event was stdout or stderr. appendStdio(text); } void vmServiceOpened(VmServiceWrapper service) { cancelStreamSubscriptions(); cancelListeners(); // The debug stream listener must be added as soon as the service is opened // because this stream does not send event history upon the first // subscription like the streams in [ensureServiceInitialized]. autoDisposeStreamSubscription( service.onDebugEvent.listen(_handleDebugEvent), ); addAutoDisposeListener( serviceConnection.serviceManager.isolateManager.mainIsolate, () { clearStdio(); }, ); } /// Whether the console service has been initialized. bool _serviceInitialized = false; /// Initialize the console service. /// /// Consumers of [ConsoleService] should call this method before using the /// console service in any way. /// /// These stream listeners are added here instead of in [vmServiceOpened] for /// performance reasons. Since these streams have event history, we will not /// be missing any events by listening after [vmServiceOpened], and listening /// only when this data is needed will improve performance for connecting to /// low-end devices, as well as when DevTools pages that don't need the /// [ConsoleService] are being used. void ensureServiceInitialized() { assert(serviceConnection.serviceManager.isServiceAvailable); if (!_serviceInitialized && serviceConnection.serviceManager.isServiceAvailable) { autoDisposeStreamSubscription( serviceConnection.serviceManager.service!.onStdoutEventWithHistorySafe .listen(_handleStdoutEvent), ); autoDisposeStreamSubscription( serviceConnection.serviceManager.service!.onStderrEventWithHistorySafe .listen(_handleStderrEvent), ); autoDisposeStreamSubscription( serviceConnection .serviceManager.service!.onExtensionEventWithHistorySafe .listen(_handleExtensionEvent), ); _serviceInitialized = true; } } void _handleExtensionEvent(Event e) async { if (e.extensionKind == 'Flutter.Error' || e.extensionKind == 'Flutter.Print') { if (serviceConnection.serviceManager.connectedApp?.isProfileBuildNow != true) { // The app isn't a debug build. return; } // TODO(jacobr): events may be out of order. Use unique ids to ensure // consistent order of regular print statements and structured messages. appendInstanceRef( value: null, diagnostic: RemoteDiagnosticsNode( e.extensionData!.data, objectGroup, false, null, ), isolateRef: objectGroup.inspectorService.isolateRef, expandAll: true, ); } } void handleVmServiceClosed() { cancelStreamSubscriptions(); _serviceInitialized = false; } void _handleDebugEvent(Event event) async { // TODO(jacobr): keep events in order by tracking the original time and // sorting. if (event.kind == EventKind.kInspect) { final inspector = objectGroup; if (event.isolate == inspector.inspectorService.isolateRef) { try { if (await inspector.isInspectable( GenericInstanceRef( isolateRef: event.isolate, value: event.inspectee, ), )) { // This object will trigger the widget inspector so let the widget // inspector decide whether it wants to log it to the console or // not. // TODO(jacobr): if the widget inspector stops using the inspect // event to trigger changing inspector selection, remove this // case. Without this logic, we could double log objects to the // console after clicking in the inspector as clicking in the // inspector directly triggers an object to be logged and clicking // in the inspector leads the device to emit an inspect event back // to other clients. return; } } catch (e) { // Fail gracefully. TODO(jacobr) verify the error was only Sentinel // returned getting the inspector ref. } } appendInstanceRef( value: event.inspectee, isolateRef: event.isolate, diagnostic: null, ); } } }
devtools/packages/devtools_app/lib/src/shared/console/console_service.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/console/console_service.dart", "repo_id": "devtools", "token_count": 3932 }
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 'dart:async'; import 'package:devtools_shared/devtools_extensions.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'globals.dart'; import 'survey.dart'; final _log = Logger('dev_helpers'); /// Enable this flag to debug analytics when DevTools is run in debug or profile /// mode, otherwise analytics will only be sent in release builds. /// /// `ga.isAnalyticsEnabled()` still must return true for analytics to be sent. bool debugAnalytics = false; /// Whether to build DevTools for conveniently debugging DevTools extensions. /// /// Turning this flag to [true] allows for debugging the extensions framework /// without a server connection. /// /// This flag should never be checked in with a value of true - this is covered /// by a test. final debugDevToolsExtensions = _debugDevToolsExtensions || integrationTestMode || testMode || stagerMode; const _debugDevToolsExtensions = false; List<DevToolsExtensionConfig> debugHandleRefreshAvailableExtensions( // ignore: avoid-unused-parameters, false positive due to conditional imports Uri appRoot, ) { return debugExtensions; } ExtensionEnabledState debugHandleExtensionEnabledState({ // ignore: avoid-unused-parameters, false positive due to conditional imports required Uri appRoot, required String extensionName, bool? enable, }) { if (enable != null) { stubExtensionEnabledStates[extensionName] = enable ? ExtensionEnabledState.enabled : ExtensionEnabledState.disabled; } return stubExtensionEnabledStates.putIfAbsent( extensionName, () => ExtensionEnabledState.none, ); } @visibleForTesting void resetDevToolsExtensionEnabledStates() => stubExtensionEnabledStates.clear(); /// Stubbed activation states so we can develop DevTools extensions without a /// server connection. final stubExtensionEnabledStates = <String, ExtensionEnabledState>{}; /// Stubbed extensions so we can develop DevTools Extensions without a server /// connection. final List<DevToolsExtensionConfig> debugExtensions = [ DevToolsExtensionConfig.parse({ DevToolsExtensionConfig.nameKey: 'foo', DevToolsExtensionConfig.issueTrackerKey: 'www.google.com', DevToolsExtensionConfig.versionKey: '1.0.0', DevToolsExtensionConfig.pathKey: '/path/to/foo', DevToolsExtensionConfig.isPubliclyHostedKey: 'false', }), DevToolsExtensionConfig.parse({ DevToolsExtensionConfig.nameKey: 'bar', DevToolsExtensionConfig.issueTrackerKey: 'www.google.com', DevToolsExtensionConfig.versionKey: '2.0.0', DevToolsExtensionConfig.materialIconCodePointKey: 0xe638, DevToolsExtensionConfig.pathKey: '/path/to/bar', DevToolsExtensionConfig.isPubliclyHostedKey: 'false', }), DevToolsExtensionConfig.parse({ DevToolsExtensionConfig.nameKey: 'provider', DevToolsExtensionConfig.issueTrackerKey: 'https://github.com/rrousselGit/provider/issues', DevToolsExtensionConfig.versionKey: '3.0.0', DevToolsExtensionConfig.materialIconCodePointKey: 0xe50a, DevToolsExtensionConfig.pathKey: '/path/to/provider', DevToolsExtensionConfig.isPubliclyHostedKey: 'false', }), ]; /// Enable this flag to debug the DevTools survey logic. /// /// When this flag is true, [debugSurveyMetadata] will be used instead of what /// we normally fetch from /// 'docs.flutter.dev/f/dart-devtools-survey-metadata.json'. bool debugSurvey = false; /// The survey metadata that will be used instead of the live data from /// 'docs.flutter.dev/f/dart-devtools-survey-metadata.json' when [debugSurvey] /// is true; final debugSurveyMetadata = DevToolsSurvey.parse( { '_comments': [ 'uniqueId must be updated with each new survey so DevTools knows to re-prompt users.', 'title should not exceed 45 characters.', 'startDate and endDate should follow ISO 8601 standard with a timezone offset.', ], 'uniqueId': '2023-Q4', 'title': 'Help improve DevTools! Take our 2023 Q4 survey.', 'url': 'https://google.qualtrics.com/jfe/form/SV_2l4XcyscF8mQtDM', 'startDate': '2023-09-20T09:00:00-07:00', 'endDate': '2023-10-20T09:00:00-07:00', }, ); /// Enable this flag to debug Perfetto trace processing in the Performance /// screen. /// /// When this flag is true, helpful print debugging will be emitted signaling /// important data for the trace processing logic. /// /// This flag has performance implications, since printing a lot of data to the /// command line can be expensive. const debugPerfettoTraceProcessing = !kReleaseMode && false; /// Helper method to call a callback only when debugging issues related to trace /// event duplicates (for example https://github.com/dart-lang/sdk/issues/46605). void debugTraceCallback(void Function() callback) { if (debugPerfettoTraceProcessing) { callback(); } } /// Enable this flag to print timing information for callbacks wrapped in /// [debugTimeSync] or [debugTimeAsync]. const debugTimers = !kReleaseMode && false; /// Debug helper to run a synchronous [callback] and print the time it took to /// run to stdout. /// /// This will only time the operation when [debugTimers] is true. void debugTimeSync( void Function() callback, { required String debugName, }) { if (!debugTimers) { callback(); return; } final now = DateTime.now().millisecondsSinceEpoch; callback(); final time = DateTime.now().millisecondsSinceEpoch - now; _log.info('$debugName: $time ms'); } /// Debug helper to run an asynchronous [callback] and print the time it took to /// run to stdout. /// /// This will only time the operation when [debugTimers] is true. FutureOr<void> debugTimeAsync( FutureOr<void> Function() callback, { required String debugName, }) async { if (!debugTimers) { await callback(); return; } final now = DateTime.now().millisecondsSinceEpoch; await callback(); final time = DateTime.now().millisecondsSinceEpoch - now; _log.info('$debugName: $time ms'); }
devtools/packages/devtools_app/lib/src/shared/development_helpers.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/development_helpers.dart", "repo_id": "devtools", "token_count": 1886 }
100
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../shared/config_specific/launch_url/launch_url.dart'; import 'config_specific/copy_to_clipboard/copy_to_clipboard.dart'; import 'globals.dart'; /// A dialog, that reports unexpected error and allows to copy details and create issue. class UnexpectedErrorDialog extends StatelessWidget { const UnexpectedErrorDialog({ super.key, required this.additionalInfo, }); final String additionalInfo; @override Widget build(BuildContext context) { final theme = Theme.of(context); return DevToolsDialog( title: const Text('Unexpected Error'), content: Text( additionalInfo, style: theme.fixedFontStyle, ), actions: [ DialogTextButton( child: const Text('Copy details'), onPressed: () => unawaited( copyToClipboard( additionalInfo, 'Error details copied to clipboard', ), ), ), DialogTextButton( child: const Text('Create issue'), onPressed: () => unawaited( launchUrl( devToolsExtensionPoints .issueTrackerLink(additionalInfo: additionalInfo) .url, ), ), ), const DialogCloseButton(), ], ); } }
devtools/packages/devtools_app/lib/src/shared/dialogs.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/dialogs.dart", "repo_id": "devtools", "token_count": 649 }
101
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// This library contains code pulled from dart:io that is not platform specific. library; part '_http_cookies.dart'; part '_http_date.dart'; part '_http_exception.dart';
devtools/packages/devtools_app/lib/src/shared/http/http.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/http/http.dart", "repo_id": "devtools", "token_count": 98 }
102
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of 'preferences.dart'; class InspectorPreferencesController extends DisposableController with AutoDisposeControllerMixin { ValueListenable<bool> get hoverEvalModeEnabled => _hoverEvalMode; ListValueNotifier<String> get pubRootDirectories => _pubRootDirectories; ValueListenable<bool> get isRefreshingPubRootDirectories => _pubRootDirectoriesAreBusy; InspectorServiceBase? get _inspectorService => serviceConnection.inspectorService; final _hoverEvalMode = ValueNotifier<bool>(false); final _pubRootDirectories = ListValueNotifier<String>([]); final _pubRootDirectoriesAreBusy = ValueNotifier<bool>(false); final _busyCounter = ValueNotifier<int>(0); static const _hoverEvalModeStorageId = 'inspector.hoverEvalMode'; static const _customPubRootDirectoriesStoragePrefix = 'inspector.customPubRootDirectories'; String? _mainScriptDir; bool _checkedFlutterPubRoot = false; Future<void> _updateMainScriptRef() async { final rootLibUriString = (await serviceConnection.serviceManager.tryToDetectMainRootInfo()) ?.library; final rootLibUri = Uri.parse(rootLibUriString ?? ''); final directorySegments = rootLibUri.pathSegments.sublist(0, rootLibUri.pathSegments.length - 1); final rootLibDirectory = rootLibUri.replace( pathSegments: directorySegments, ); _mainScriptDir = rootLibDirectory.path; } Future<void> init() async { await _initHoverEvalMode(); // TODO(jacobr): consider initializing this first as it is not blocking. _initPubRootDirectories(); } Future<void> _initHoverEvalMode() async { await _updateHoverEvalMode(); addAutoDisposeListener(_hoverEvalMode, () { storage.setValue( _hoverEvalModeStorageId, _hoverEvalMode.value.toString(), ); }); } Future<void> _updateHoverEvalMode() async { String? hoverEvalModeEnabledValue = await storage.getValue(_hoverEvalModeStorageId); hoverEvalModeEnabledValue ??= (_inspectorService?.hoverEvalModeEnabledByDefault ?? false).toString(); setHoverEvalMode(hoverEvalModeEnabledValue == 'true'); } void _initPubRootDirectories() { addAutoDisposeListener( serviceConnection.serviceManager.connectedState, () async { if (serviceConnection.serviceManager.connectedState.value.connected) { await handleConnectionToNewService(); } else { _handleConnectionClosed(); } }, ); addAutoDisposeListener(_busyCounter, () { _pubRootDirectoriesAreBusy.value = _busyCounter.value != 0; }); addAutoDisposeListener( serviceConnection.serviceManager.isolateManager.mainIsolate, () { if (_mainScriptDir != null && serviceConnection.serviceManager.isolateManager.mainIsolate.value != null) { final debuggerState = serviceConnection.serviceManager.isolateManager.mainIsolateState; if (debuggerState?.isPaused.value == false) { // the isolate is already unpaused, we can try to load // the directories unawaited(preferences.inspector.loadPubRootDirectories()); } else { late void Function() pausedListener; pausedListener = () { if (debuggerState?.isPaused.value == false) { unawaited(preferences.inspector.loadPubRootDirectories()); debuggerState?.isPaused.removeListener(pausedListener); } }; // The isolate is still paused, listen for when it becomes unpaused. addAutoDisposeListener(debuggerState?.isPaused, pausedListener); } } }, ); } void _handleConnectionClosed() { _mainScriptDir = null; _pubRootDirectories.clear(); } @visibleForTesting Future<void> handleConnectionToNewService() async { _checkedFlutterPubRoot = false; await _updateMainScriptRef(); await _updateHoverEvalMode(); await loadPubRootDirectories(); } Future<void> loadPubRootDirectories() async { await _pubRootDirectoryBusyTracker(() async { await addPubRootDirectories(await _determinePubRootDirectories()); await _refreshPubRootDirectoriesFromService(); }); } Future<List<String>> _determinePubRootDirectories() async { final cachedDirectories = await readCachedPubRootDirectories(); final inferredDirectory = await _inferPubRootDirectory(); if (inferredDirectory == null) return cachedDirectories; return {inferredDirectory, ...cachedDirectories}.toList(); } @visibleForTesting Future<List<String>> readCachedPubRootDirectories() async { final cachedDirectoriesJson = await storage.getValue(_customPubRootStorageId()); if (cachedDirectoriesJson == null) return <String>[]; final cachedDirectories = List<String>.from( jsonDecode(cachedDirectoriesJson), ); // Remove the Flutter pub root directory if it was accidentally cached. // See: // - https://github.com/flutter/devtools/issues/6882 // - https://github.com/flutter/devtools/issues/6841 if (!_checkedFlutterPubRoot && cachedDirectories.any(_isFlutterPubRoot)) { // Set [_checkedFlutterPubRoot] to true to avoid an infinite loop on the // next call to [removePubRootDirectories]: _checkedFlutterPubRoot = true; final flutterPubRootDirectories = cachedDirectories.where(_isFlutterPubRoot).toList(); await removePubRootDirectories(flutterPubRootDirectories); cachedDirectories.removeWhere(_isFlutterPubRoot); } return cachedDirectories; } bool _isFlutterPubRoot(String directory) => directory.endsWith('packages/flutter'); /// As we aren't running from an IDE, we don't know exactly what the pub root /// directories are for the current project so we make a best guess based on /// the root library for the main isolate. Future<String?> _inferPubRootDirectory() async { final path = await serviceConnection.rootLibraryForMainIsolate(); if (path == null) { return null; } // TODO(jacobr): Once https://github.com/flutter/flutter/issues/26615 is // fixed we will be able to use package: paths. Temporarily all tools // tracking widget locations will need to support both path formats. // TODO(jacobr): use the list of loaded scripts to determine the appropriate // package root directory given that the root script of this project is in // this directory rather than guessing based on url structure. final parts = path.split('/'); String? pubRootDirectory; // For google3, we grab the top-level directory in the google3 directory // (e.g. /education), or the top-level directory in third_party (e.g. // /third_party/dart): if (isGoogle3Path(parts)) { pubRootDirectory = _pubRootDirectoryForGoogle3(parts); } else { final parts = path.split('/'); for (int i = parts.length - 1; i >= 0; i--) { final part = parts[i]; if (part == 'lib' || part == 'web') { pubRootDirectory = parts.sublist(0, i).join('/'); break; } if (part == 'packages') { pubRootDirectory = parts.sublist(0, i + 1).join('/'); break; } } } pubRootDirectory ??= (parts..removeLast()).join('/'); return pubRootDirectory; } String? _pubRootDirectoryForGoogle3(List<String> pathParts) { final strippedParts = stripGoogle3(pathParts); if (strippedParts.isEmpty) return null; final topLevelDirectory = strippedParts.first; if (topLevelDirectory == _thirdPartyPathSegment && strippedParts.length >= 2) { return '/${strippedParts.sublist(0, 2).join('/')}'; } else { return '/${strippedParts.first}'; } } Future<void> _cachePubRootDirectories( List<String> pubRootDirectories, ) async { final cachedDirectories = await readCachedPubRootDirectories(); await storage.setValue( _customPubRootStorageId(), jsonEncode([ ...cachedDirectories, ...pubRootDirectories, ]), ); } Future<void> _uncachePubRootDirectories( List<String> pubRootDirectories, ) async { final directoriesToCache = (await readCachedPubRootDirectories()) .where((dir) => !pubRootDirectories.contains(dir)) .toList(); await storage.setValue( _customPubRootStorageId(), jsonEncode(directoriesToCache), ); } Future<void> addPubRootDirectories( List<String> pubRootDirectories, { bool shouldCache = false, }) async { // TODO(https://github.com/flutter/devtools/issues/4380): // Add validation to EditableList Input. // Directories of just / will break the inspector tree local package checks. pubRootDirectories.removeWhere( (element) => RegExp('^[/\\s]*\$').firstMatch(element) != null, ); if (!serviceConnection.serviceManager.hasConnection) return; await _pubRootDirectoryBusyTracker(() async { final localInspectorService = _inspectorService; if (localInspectorService is! InspectorService) return; await localInspectorService.addPubRootDirectories(pubRootDirectories); if (shouldCache) { await _cachePubRootDirectories(pubRootDirectories); } await _refreshPubRootDirectoriesFromService(); }); } Future<void> removePubRootDirectories( List<String> pubRootDirectories, ) async { if (!serviceConnection.serviceManager.hasConnection) return; await _pubRootDirectoryBusyTracker(() async { final localInspectorService = _inspectorService; if (localInspectorService is! InspectorService) return; await localInspectorService.removePubRootDirectories(pubRootDirectories); await _uncachePubRootDirectories(pubRootDirectories); await _refreshPubRootDirectoriesFromService(); }); } Future<void> _refreshPubRootDirectoriesFromService() async { await _pubRootDirectoryBusyTracker(() async { final localInspectorService = _inspectorService; if (localInspectorService is! InspectorService) return; final freshPubRootDirectories = await localInspectorService.getPubRootDirectories(); if (freshPubRootDirectories != null) { final newSet = Set<String>.of(freshPubRootDirectories); final oldSet = Set<String>.of(_pubRootDirectories.value); final directoriesToAdd = newSet.difference(oldSet); final directoriesToRemove = oldSet.difference(newSet); _pubRootDirectories ..removeAll(directoriesToRemove) ..addAll(directoriesToAdd); } }); } String _customPubRootStorageId() { assert(_mainScriptDir != null); final packageId = _mainScriptDir ?? '_fallback'; return '${_customPubRootDirectoriesStoragePrefix}_$packageId'; } Future<void> _pubRootDirectoryBusyTracker( Future<void> Function() callback, ) async { try { _busyCounter.value++; await callback(); } finally { _busyCounter.value--; } } /// Change the value for the hover eval mode setting. void setHoverEvalMode(bool enableHoverEvalMode) { _hoverEvalMode.value = enableHoverEvalMode; } }
devtools/packages/devtools_app/lib/src/shared/preferences/_inspector_preferences.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/preferences/_inspector_preferences.dart", "repo_id": "devtools", "token_count": 4120 }
103
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; // TODO(jacobr): move more math utils over to this library. double sum(Iterable<double> numbers) => numbers.fold(0, (sum, cur) => sum + cur); double min(Iterable<double> numbers) => numbers.fold(double.infinity, (minimum, cur) => math.min(minimum, cur)); double max(Iterable<double> numbers) => numbers.fold(-double.infinity, (minimum, cur) => math.max(minimum, cur));
devtools/packages/devtools_app/lib/src/shared/primitives/math_utils.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/primitives/math_utils.dart", "repo_id": "devtools", "token_count": 185 }
104
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. part of 'server.dart'; /// Asks the Devtools Server to return a Dart Tooling Daemon uri if it has one. Future<Uri?> getDtdUri() async { if (isDevToolsServerAvailable) { final uri = Uri(path: DtdApi.apiGetDtdUri); final resp = await request(uri.toString()); if (resp?.statusOk ?? false) { final parsedResult = json.decode(resp!.body) as Map; final uriString = parsedResult[DtdApi.uriPropertyName] as String?; return uriString != null ? Uri.parse(uriString) : null; } } return null; }
devtools/packages/devtools_app/lib/src/shared/server/_dtd_api.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/server/_dtd_api.dart", "repo_id": "devtools", "token_count": 242 }
105
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'globals.dart'; void generateDevToolsTitle() { if (!serviceConnection.serviceManager.connectedAppInitialized) { _devToolsTitle.value = 'DevTools for Flutter & Dart'; return; } _devToolsTitle.value = serviceConnection.serviceManager.connectedApp!.isFlutterAppNow! ? 'Flutter DevTools' : 'Dart DevTools'; } ValueListenable<String> get devToolsTitle => _devToolsTitle; ValueNotifier<String> _devToolsTitle = ValueNotifier<String>('');
devtools/packages/devtools_app/lib/src/shared/title.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/title.dart", "repo_id": "devtools", "token_count": 224 }
106
// 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:json_rpc_2/json_rpc_2.dart' as json_rpc_2; import 'package:meta/meta.dart'; import '../vs_code_api.dart'; import 'dart_tooling_api.dart'; final class VsCodeApiImpl extends ToolApiImpl implements VsCodeApi { VsCodeApiImpl._(super.rpc, Map<String, Object?> capabilities) { this.capabilities = VsCodeCapabilitiesImpl(capabilities); devicesChanged = events(VsCodeApi.jsonDevicesChangedEvent) .map(VsCodeDevicesEventImpl.fromJson); debugSessionsChanged = events(VsCodeApi.jsonDebugSessionsChangedEvent) .map(VsCodeDebugSessionsEventImpl.fromJson); } static Future<VsCodeApi?> tryConnect(json_rpc_2.Peer rpc) async { final capabilities = await ToolApiImpl.tryGetCapabilities(rpc, VsCodeApi.jsonApiName); return capabilities != null ? VsCodeApiImpl._(rpc, capabilities) : null; } @override Future<void> initialize() => sendRequest(VsCodeApi.jsonInitializeMethod); @override @protected String get apiName => VsCodeApi.jsonApiName; @override late final Stream<VsCodeDevicesEvent> devicesChanged; @override late final Stream<VsCodeDebugSessionsEvent> debugSessionsChanged; @override late final VsCodeCapabilities capabilities; @override Future<Object?> executeCommand(String command, [List<Object?>? arguments]) { return sendRequest( VsCodeApi.jsonExecuteCommandMethod, { VsCodeApi.jsonCommandParameter: command, VsCodeApi.jsonArgumentsParameter: arguments, }, ); } @override Future<bool> selectDevice(String id) { return sendRequest( VsCodeApi.jsonSelectDeviceMethod, {VsCodeApi.jsonIdParameter: id}, ); } @override Future<bool> enablePlatformType(String platformType) { return sendRequest( VsCodeApi.jsonEnablePlatformTypeMethod, {VsCodeApi.jsonPlatformTypeParameter: platformType}, ); } @override Future<void> openDevToolsPage( String debugSessionId, { String? page, bool? forceExternal, }) { return sendRequest( VsCodeApi.jsonOpenDevToolsPageMethod, { VsCodeApi.jsonDebugSessionIdParameter: debugSessionId, VsCodeApi.jsonPageParameter: page, VsCodeApi.jsonForceExternalParameter: forceExternal, }, ); } @override Future<void> hotReload(String debugSessionId) { return sendRequest( VsCodeApi.jsonHotReloadMethod, { VsCodeApi.jsonDebugSessionIdParameter: debugSessionId, }, ); } @override Future<void> hotRestart(String debugSessionId) { return sendRequest( VsCodeApi.jsonHotRestartMethod, { VsCodeApi.jsonDebugSessionIdParameter: debugSessionId, }, ); } } class VsCodeDeviceImpl implements VsCodeDevice { VsCodeDeviceImpl({ required this.id, required this.name, required this.category, required this.emulator, required this.emulatorId, required this.ephemeral, required this.platform, required this.platformType, }); VsCodeDeviceImpl.fromJson(Map<String, Object?> json) : this( id: json[VsCodeDevice.jsonIdField] as String, name: json[VsCodeDevice.jsonNameField] as String, category: json[VsCodeDevice.jsonCategoryField] as String?, emulator: json[VsCodeDevice.jsonEmulatorField] as bool, emulatorId: json[VsCodeDevice.jsonEmulatorIdField] as String?, ephemeral: json[VsCodeDevice.jsonEphemeralField] as bool, platform: json[VsCodeDevice.jsonPlatformField] as String, platformType: json[VsCodeDevice.jsonPlatformTypeField] as String?, ); @override final String id; @override final String name; @override final String? category; @override final bool emulator; @override final String? emulatorId; @override final bool ephemeral; @override final String platform; @override final String? platformType; Map<String, Object?> toJson() => { VsCodeDevice.jsonIdField: id, VsCodeDevice.jsonNameField: name, VsCodeDevice.jsonCategoryField: category, VsCodeDevice.jsonEmulatorField: emulator, VsCodeDevice.jsonEmulatorIdField: emulatorId, VsCodeDevice.jsonEphemeralField: ephemeral, VsCodeDevice.jsonPlatformField: platform, VsCodeDevice.jsonPlatformTypeField: platformType, }; } class VsCodeDebugSessionImpl implements VsCodeDebugSession { VsCodeDebugSessionImpl({ required this.id, required this.name, required this.vmServiceUri, required this.flutterMode, required this.flutterDeviceId, required this.debuggerType, required this.projectRootPath, }); VsCodeDebugSessionImpl.fromJson(Map<String, Object?> json) : this( id: json[VsCodeDebugSession.jsonIdField] as String, name: json[VsCodeDebugSession.jsonNameField] as String, vmServiceUri: json[VsCodeDebugSession.jsonVmServiceUriField] as String?, flutterMode: json[VsCodeDebugSession.jsonFlutterModeField] as String?, flutterDeviceId: json[VsCodeDebugSession.jsonFlutterDeviceIdField] as String?, debuggerType: json[VsCodeDebugSession.jsonDebuggerTypeField] as String?, projectRootPath: json[VsCodeDebugSession.jsonProjectRootPathField] as String?, ); @override final String id; @override final String name; @override final String? vmServiceUri; @override final String? flutterMode; @override final String? flutterDeviceId; @override final String? debuggerType; @override final String? projectRootPath; Map<String, Object?> toJson() => { VsCodeDebugSession.jsonIdField: id, VsCodeDebugSession.jsonNameField: name, VsCodeDebugSession.jsonVmServiceUriField: vmServiceUri, VsCodeDebugSession.jsonFlutterModeField: flutterMode, VsCodeDebugSession.jsonFlutterDeviceIdField: flutterDeviceId, VsCodeDebugSession.jsonDebuggerTypeField: debuggerType, VsCodeDebugSession.jsonProjectRootPathField: projectRootPath, }; } class VsCodeDevicesEventImpl implements VsCodeDevicesEvent { VsCodeDevicesEventImpl({ required this.selectedDeviceId, required this.devices, required this.unsupportedDevices, }); VsCodeDevicesEventImpl.fromJson(Map<String, Object?> json) : this( selectedDeviceId: json[VsCodeDevicesEvent.jsonSelectedDeviceIdField] as String?, devices: (json[VsCodeDevicesEvent.jsonDevicesField] as List) .map((item) => Map<String, Object?>.from(item)) .map((map) => VsCodeDeviceImpl.fromJson(map)) .toList(), unsupportedDevices: (json[VsCodeDevicesEvent.jsonUnsupportedDevicesField] as List?) ?.map((item) => Map<String, Object?>.from(item)) .map((map) => VsCodeDeviceImpl.fromJson(map)) .toList(), ); @override final String? selectedDeviceId; @override final List<VsCodeDevice> devices; @override final List<VsCodeDevice>? unsupportedDevices; Map<String, Object?> toJson() => { VsCodeDevicesEvent.jsonSelectedDeviceIdField: selectedDeviceId, VsCodeDevicesEvent.jsonDevicesField: devices, VsCodeDevicesEvent.jsonUnsupportedDevicesField: unsupportedDevices, }; } class VsCodeDebugSessionsEventImpl implements VsCodeDebugSessionsEvent { VsCodeDebugSessionsEventImpl({ required this.sessions, }); VsCodeDebugSessionsEventImpl.fromJson(Map<String, Object?> json) : this( sessions: (json[VsCodeDebugSessionsEvent.jsonSessionsField] as List) .map((item) => Map<String, Object?>.from(item)) .map((map) => VsCodeDebugSessionImpl.fromJson(map)) .toList(), ); @override final List<VsCodeDebugSession> sessions; Map<String, Object?> toJson() => { VsCodeDebugSessionsEvent.jsonSessionsField: sessions, }; } class VsCodeCapabilitiesImpl implements VsCodeCapabilities { VsCodeCapabilitiesImpl(this._raw); final Map<String, Object?>? _raw; @override bool get executeCommand => _raw?[VsCodeCapabilities.jsonExecuteCommandField] == true; @override bool get selectDevice => _raw?[VsCodeCapabilities.jsonSelectDeviceField] == true; @override bool get openDevToolsPage => _raw?[VsCodeCapabilities.openDevToolsPageField] == true; @override bool get openDevToolsExternally => _raw?[VsCodeCapabilities.openDevToolsExternallyField] == true; @override bool get hotReload => _raw?[VsCodeCapabilities.hotReloadField] == true; @override bool get hotRestart => _raw?[VsCodeCapabilities.hotRestartField] == true; }
devtools/packages/devtools_app/lib/src/standalone_ui/api/impl/vs_code_api.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/standalone_ui/api/impl/vs_code_api.dart", "repo_id": "devtools", "token_count": 3410 }
107
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/profiler/panes/method_table/method_table_model.dart'; import 'package:devtools_app/src/shared/profiler_utils.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('$MethodTableGraphNode', () { final node1 = MethodTableGraphNode( name: 'node 1', packageUri: 'uri_1', sourceLine: 1, totalCount: 2, selfCount: 1, profileMetaData: ProfileMetaData( sampleCount: 10, time: TimeRange() ..start = Duration.zero ..end = const Duration(seconds: 1), ), stackFrameIds: {'1'}, ); final node2 = MethodTableGraphNode( name: 'node 1', packageUri: 'uri_1', sourceLine: 1, totalCount: 4, selfCount: 4, profileMetaData: ProfileMetaData( sampleCount: 10, time: TimeRange() ..start = Duration.zero ..end = const Duration(seconds: 1), ), stackFrameIds: {'2'}, ); final node3 = MethodTableGraphNode( name: 'node 1', packageUri: 'different_uri', sourceLine: 1, totalCount: 3, selfCount: 2, profileMetaData: ProfileMetaData( sampleCount: 10, time: TimeRange() ..start = Duration.zero ..end = const Duration(seconds: 1), ), stackFrameIds: {'3'}, ); final node4 = MethodTableGraphNode( name: 'different_name', packageUri: 'uri_1', sourceLine: 1, totalCount: 3, selfCount: 3, profileMetaData: ProfileMetaData( sampleCount: 10, time: TimeRange() ..start = Duration.zero ..end = const Duration(seconds: 1), ), stackFrameIds: {'4'}, ); test('shallowEquals ', () { expect(node1.shallowEquals(node2), isTrue); expect(node1.shallowEquals(node3), isFalse); expect(node1.shallowEquals(node4), isFalse); expect(node2.shallowEquals(node1), isTrue); expect(node2.shallowEquals(node3), isFalse); expect(node2.shallowEquals(node4), isFalse); expect(node3.shallowEquals(node1), isFalse); expect(node3.shallowEquals(node2), isFalse); expect(node3.shallowEquals(node4), isFalse); expect(node4.shallowEquals(node1), isFalse); expect(node4.shallowEquals(node2), isFalse); expect(node4.shallowEquals(node3), isFalse); }); test('merge ', () { // Make a copy so that we do not modify the original nodes. final node1Copy = node1.copy(); expect(node1Copy.totalCount, 2); expect(node1Copy.selfCount, 1); // Attempt the unsuccessful merges first and verify nothing is changed. node1Copy.merge(node3, mergeTotalTime: true); expect(node1Copy.totalCount, 2); expect(node1Copy.selfCount, 1); node1Copy.merge(node3, mergeTotalTime: true); expect(node1Copy.totalCount, 2); expect(node1Copy.selfCount, 1); expect(node2.totalCount, 4); expect(node2.selfCount, 4); node1Copy.merge(node2, mergeTotalTime: true); expect(node1Copy.totalCount, 6); expect(node1Copy.selfCount, 5); }); test('merge without total time', () { // Make a copy so that we do not modify the original nodes. final node1Copy = node1.copy(); expect(node1Copy.totalCount, 2); expect(node1Copy.selfCount, 1); expect(node2.totalCount, 4); expect(node2.selfCount, 4); node1Copy.merge(node2, mergeTotalTime: false); expect(node1Copy.totalCount, 2); expect(node1Copy.selfCount, 5); }); }); }
devtools/packages/devtools_app/test/cpu_profiler/method_table/method_table_model_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/cpu_profiler/method_table/method_table_model_test.dart", "repo_id": "devtools", "token_count": 1631 }
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 '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'; import 'package:vm_service/vm_service.dart'; void main() { const windowSize = Size(4000.0, 4000.0); late FakeServiceConnectionManager fakeServiceConnection; late MockScriptManager scriptManager; late MockDebuggerController debuggerController; late CodeViewController mockCodeViewController; final scripts = [ ScriptRef(uri: 'package:test/script.dart', id: 'test-script'), ]; group( 'FileExplorer', () { setUp(() { fakeServiceConnection = FakeServiceConnectionManager(); scriptManager = MockScriptManager(); mockConnectedApp( fakeServiceConnection.serviceManager.connectedApp!, isFlutterApp: true, isProfileBuild: false, isWebApp: false, ); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal(NotificationService, NotificationService()); setGlobal(ScriptManager, scriptManager); setGlobal(BreakpointManager, BreakpointManager()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); fakeServiceConnection.consoleService.ensureServiceInitialized(); when( fakeServiceConnection.errorBadgeManager .errorCountNotifier('debugger'), ).thenReturn(ValueNotifier<int>(0)); final mockProgramExplorerController = createMockProgramExplorerControllerWithDefaults(); mockCodeViewController = createMockCodeViewControllerWithDefaults( programExplorerController: mockProgramExplorerController, ); debuggerController = createMockDebuggerControllerWithDefaults( codeViewController: mockCodeViewController, ); when(scriptManager.sortedScripts).thenReturn(ValueNotifier(scripts)); when(mockProgramExplorerController.rootObjectNodes).thenReturn( ValueNotifier( [ VMServiceObjectNode( mockCodeViewController.programExplorerController, 'package:test', null, ), ], ), ); when(mockCodeViewController.showFileOpener) .thenReturn(ValueNotifier(false)); }); Future<void> pumpDebuggerScreen( WidgetTester tester, DebuggerController controller, ) async { await tester.pumpWidget( wrapWithControllers( DebuggerSourceAndControls( shownFirstScript: () => true, setShownFirstScript: (_) {}, ), debugger: controller, ), ); } testWidgetsWithWindowSize( 'visible', windowSize, (WidgetTester tester) async { // File Explorer view is shown when(mockCodeViewController.fileExplorerVisible) .thenReturn(ValueNotifier(true)); await pumpDebuggerScreen(tester, debuggerController); // One for the button and one for the title of the File Explorer view. expect(find.text('File Explorer'), findsNWidgets(2)); // test for items in the libraries tree expect( find.text(scripts.first.uri!.split('/').first), findsOneWidget, ); }, ); testWidgetsWithWindowSize( 'hidden', windowSize, (WidgetTester tester) async { // File Explorer view is hidden when(mockCodeViewController.fileExplorerVisible) .thenReturn(ValueNotifier(false)); await pumpDebuggerScreen(tester, debuggerController); expect(find.text('File Explorer'), findsOneWidget); }, ); }, ); }
devtools/packages/devtools_app/test/debugger/debugger_screen_explorer_visibility_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/debugger/debugger_screen_explorer_visibility_test.dart", "repo_id": "devtools", "token_count": 1779 }
109
// 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:typed_data'; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/shared/http/curl_command.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vm_service/vm_service.dart'; import '../test_infra/test_data/network.dart'; void main() { group('NetworkCurlCommand', () { test('parses simple GET request', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'GET', uri: Uri.parse('https://www.example.com'), ), ); expect( command.toString(), "curl --location --request GET 'https://www.example.com'", ); }); test('parses PUT request', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'PUT', uri: Uri.parse('https://www.example.com'), headers: {}, ), ); expect( command.toString(), "curl --location --request PUT 'https://www.example.com'", ); }); test('parses simple GET request with headers', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'GET', uri: Uri.parse('https://www.example.com'), headers: { 'accept-language': ['en-GB,de-DE'], 'user-agent': ['SomeUserAgent/5.0 (Macintosh; Intel Mac OS X)'], }, ), ); expect( command.toString(), "curl --location --request GET 'https://www.example.com' \\\n--header 'accept-language: en-GB,de-DE' \\\n--header 'user-agent: SomeUserAgent/5.0 (Macintosh; Intel Mac OS X)'", ); }); test('parses POST with body', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'POST', uri: Uri.parse('https://www.example.com'), headers: { 'accept-language': ['en-GB,de-DE'], 'user-agent': ['SomeUserAgent/5.0 (Macintosh; Intel Mac OS X)'], }, requestBody: Uint8List.fromList( 'It\'s a request body!\nHopefully this works.'.codeUnits, ), ), ); expect( command.toString(), "curl --location --request POST 'https://www.example.com' \\\n--header 'accept-language: en-GB,de-DE' \\\n--header 'user-agent: SomeUserAgent/5.0 (Macintosh; Intel Mac OS X)' \\\n--data-raw 'It'\\''s a request body!\nHopefully this works.'", ); }); test('parses null body', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'POST', uri: Uri.parse('https://www.example.com'), headers: {}, // Ignore this warning to make the `null` value used more apparent // ignore: avoid_redundant_argument_values requestBody: null, ), ); expect( command.toString(), "curl --location --request POST 'https://www.example.com'", ); }); test('parses empty body', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'POST', uri: Uri.parse('https://www.example.com'), headers: {}, requestBody: Uint8List(0), ), ); expect( command.toString(), "curl --location --request POST 'https://www.example.com' \\\n--data-raw ''", ); }); test('escapes \' character in url', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'GET', uri: Uri.parse('https://www.example.com/search?q=\'test\''), headers: { 'accept-language': ['en-GB,de-DE'], 'user-agent': ['SomeUserAgent/5.0 (Macintosh; Intel Mac OS X)'], }, ), ); expect( command.toString(), "curl --location --request GET 'https://www.example.com/search?q='\\''test'\\''' \\\n--header 'accept-language: en-GB,de-DE' \\\n--header 'user-agent: SomeUserAgent/5.0 (Macintosh; Intel Mac OS X)'", ); }); test('escapes \' character in headers', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'GET', uri: Uri.parse('https://www.example.com'), headers: { 'accept-language': ['en-GB,de-DE'], 'authorization': ['Bearer \'this is a\' test'], }, ), ); expect( command.toString(), "curl --location --request GET 'https://www.example.com' \\\n--header 'accept-language: en-GB,de-DE' \\\n--header 'authorization: Bearer '\\''this is a'\\'' test'", ); }); test('no line breaks when "multiline" is false', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'POST', uri: Uri.parse('https://www.example.com'), headers: { 'accept-language': ['en-GB,de-DE'], 'authorization': ['Bearer \'this is a\' test'], }, requestBody: Uint8List(0), ), multiline: false, ); expect( command.toString(), "curl --location --request POST 'https://www.example.com' --header 'accept-language: en-GB,de-DE' --header 'authorization: Bearer '\\''this is a'\\'' test' --data-raw ''", ); }); test('no --location when followRedirects is false', () { final command = CurlCommand.from( _testDartIOHttpRequestData( method: 'GET', uri: Uri.parse('https://www.example.com'), headers: {}, ), multiline: false, followRedirects: false, ); expect( command.toString(), "curl --request GET 'https://www.example.com'", ); }); test('parses GET request from test_data', () { final command = CurlCommand.from(httpGet); expect( command.toString(), "curl --location --request GET 'https://jsonplaceholder.typicode.com/albums/1' \\\n--header 'content-length: 0'", ); }); test('parses POST request from test_data', () { final command = CurlCommand.from(httpPost); expect( command.toString(), "curl --location --request POST 'https://jsonplaceholder.typicode.com/posts' \\\n--data-raw '{\n \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1\n}\n '", ); }); }); } class _TestDartIOHttpRequestData extends DartIOHttpRequestData { _TestDartIOHttpRequestData( this._request, ) : super(_request); final HttpProfileRequest _request; @override String? get requestBody { final body = super.requestBody; if (body != null) { return body; } if (_request.requestBody != null) { return String.fromCharCodes(_request.requestBody!); } return null; } @override Future<void> getFullRequestData() async { // Do nothing } } DartIOHttpRequestData _testDartIOHttpRequestData({ required String method, required Uri uri, Uint8List? requestBody, Map<String, dynamic>? headers, List<String>? cookies, }) { return _TestDartIOHttpRequestData( HttpProfileRequest( id: '0', isolateId: '0', method: method, uri: uri, requestBody: requestBody, events: [], startTime: DateTime.fromMicrosecondsSinceEpoch(0), endTime: DateTime.fromMicrosecondsSinceEpoch(0), response: HttpProfileResponseData( compressionState: '', connectionInfo: {}, contentLength: 0, cookies: [], headers: {}, isRedirect: false, persistentConnection: false, reasonPhrase: '', redirects: [], startTime: DateTime.fromMicrosecondsSinceEpoch(0), statusCode: 200, endTime: DateTime.fromMicrosecondsSinceEpoch(0), ), request: HttpProfileRequestData.buildSuccessfulRequest( headers: headers ?? {}, connectionInfo: {}, contentLength: requestBody?.length ?? 0, cookies: cookies ?? [], followRedirects: false, maxRedirects: 0, persistentConnection: false, ), ), ); }
devtools/packages/devtools_app/test/http/curl_command_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/http/curl_command_test.dart", "repo_id": "devtools", "token_count": 3700 }
110
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/screens/memory/framework/memory_screen.dart'; import 'package:devtools_app/src/screens/memory/panes/control/settings_dialog.dart'; import 'package:devtools_app/src/shared/common_widgets.dart'; import 'package:devtools_app/src/shared/globals.dart'; import 'package:devtools_app_shared/src/ui/dialogs.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() { late MemoryDefaultScene scene; Future<void> pumpMemoryScreen(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); } // 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( 'settings update preferences', windowSize, (WidgetTester tester) async { await pumpMemoryScreen(tester); // Open the dialog. await tester.tap(find.byType(SettingsOutlinedButton)); await tester.pumpAndSettle(); await expectLater( find.byType(MemorySettingsDialog), matchesDevToolsGolden( '../../test_infra/goldens/settings_dialog_default.png', ), ); // Modify settings and check the changes are reflected in the controller. expect( preferences.memory.androidCollectionEnabled.value, isFalse, ); await tester .tap(find.byKey(MemorySettingDialogKeys.showAndroidChartCheckBox)); await tester.pumpAndSettle(); await expectLater( find.byType(MemorySettingsDialog), matchesDevToolsGolden( '../../test_infra/goldens/settings_dialog_modified.png', ), ); expect( preferences.memory.androidCollectionEnabled.value, isTrue, ); // Reopen the dialog and check the settings are not changed. await tester.tap(find.byType(DialogCloseButton)); await tester.pumpAndSettle(); await tester.tap(find.byType(SettingsOutlinedButton)); await tester.pumpAndSettle(); await expectLater( find.byType(MemorySettingsDialog), matchesDevToolsGolden( '../../test_infra/goldens/settings_dialog_modified.png', ), ); }, ); }
devtools/packages/devtools_app/test/memory/control/settings_dialog_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/memory/control/settings_dialog_test.dart", "repo_id": "devtools", "token_count": 1086 }
111
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('vm') import 'package:devtools_app/src/screens/network/network_controller.dart'; import 'package:devtools_app/src/screens/network/network_model.dart'; import 'package:devtools_app/src/service/service_manager.dart'; import 'package:devtools_app/src/shared/http/http_request_data.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vm_service/vm_service.dart'; import 'utils/network_test_utils.dart'; void main() { group('NetworkController', () { late NetworkController controller; late FakeServiceConnectionManager fakeServiceConnection; late SocketProfile socketProfile; late HttpProfile httpProfile; setUp(() { socketProfile = loadSocketProfile(); httpProfile = loadHttpProfile(); fakeServiceConnection = FakeServiceConnectionManager( service: FakeServiceManager.createFakeService( socketProfile: socketProfile, httpProfile: httpProfile, ), ); setGlobal(ServiceConnectionManager, fakeServiceConnection); controller = NetworkController(); }); test('initialize recording state', () async { expect(controller.isPolling, false); // Fake service pretends HTTP timeline logging and socket profiling are // always enabled. await controller.startRecording(); expect(controller.isPolling, true); controller.stopRecording(); }); test('start and pause recording', () async { expect(controller.isPolling, false); final notifier = controller.recordingNotifier; await addListenerScope( listenable: notifier, listener: () { expect(notifier.value, true); expect(controller.isPolling, true); }, callback: () async { await controller.startRecording(); }, ); // Pause polling. controller.togglePolling(false); expect(notifier.value, false); expect(controller.isPolling, false); // Resume polling. controller.togglePolling(true); expect(notifier.value, true); expect(controller.isPolling, true); controller.stopRecording(); expect(notifier.value, false); expect(controller.isPolling, false); }); test('process network data', () async { await controller.startRecording(); final requestsNotifier = controller.requests; List<NetworkRequest> requests = requestsNotifier.value; // Check profile is initially empty. expect(requests.isEmpty, true); // The number of valid requests recorded in the test data. const numSockets = 2; const numHttpProfile = 7; const numRequests = numSockets + numHttpProfile; const httpMethods = <String>{ 'CONNECT', 'DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', }; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); requests = requestsNotifier.value; expect(requests.length, numRequests); final List<DartIOHttpRequestData> httpRequests = requests .whereType<DartIOHttpRequestData>() .cast<DartIOHttpRequestData>() .toList(); for (final request in httpRequests) { expect(request.duration, request.inProgress ? isNull : isNotNull); expect(request.general.length, greaterThan(0)); expect(httpMethods.contains(request.method), true); expect(request.status, request.inProgress ? isNull : isNotNull); } // Finally, call `clear()` and ensure the requests have been cleared. await controller.clear(); requests = requestsNotifier.value; expect(requests.isEmpty, true); controller.stopRecording(); }); test('matchesForSearch', () async { await controller.startRecording(); // The number of valid requests recorded in the test data. const numRequests = 9; final requestsNotifier = controller.requests; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); final profile = requestsNotifier.value; expect(profile.length, numRequests); expect(controller.matchesForSearch('jsonplaceholder').length, equals(5)); expect(controller.matchesForSearch('IPv6').length, equals(2)); expect(controller.matchesForSearch('').length, equals(0)); // Search with incorrect case. expect(controller.matchesForSearch('JSONPLACEHOLDER').length, equals(5)); }); test('matchesForSearch sets isSearchMatch property', () async { // The number of valid requests recorded in the test data. const numRequests = 9; await controller.startRecording(); final requestsNotifier = controller.requests; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); final profile = requestsNotifier.value; expect(profile.length, numRequests); controller.search = 'jsonplaceholder'; List<NetworkRequest> matches = controller.searchMatches.value; expect(matches.length, equals(5)); verifyIsSearchMatch(profile, matches); controller.search = 'IPv6'; matches = controller.searchMatches.value; expect(matches.length, equals(2)); verifyIsSearchMatch(profile, matches); }); test('filterData', () async { await controller.startRecording(); // The number of valid requests recorded in the test data. const numRequests = 9; final requestsNotifier = controller.requests; // Refresh network data and ensure requests are populated. await controller.networkService.refreshNetworkData(); final profile = requestsNotifier.value; expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(numRequests)); controller.setActiveFilter(query: 'jsonplaceholder'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(5)); controller.setActiveFilter(query: ''); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(numRequests)); controller.setActiveFilter(query: 'method:get'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(6)); controller.setActiveFilter(query: 'm:put'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(1)); controller.setActiveFilter(query: '-method:put'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(8)); controller.setActiveFilter(query: 'status:Error'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(1)); controller.setActiveFilter(query: 's:101'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(3)); controller.setActiveFilter(query: '-s:Error'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(8)); controller.setActiveFilter(query: 'type:json'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(4)); controller.setActiveFilter(query: 't:ws'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(2)); controller.setActiveFilter(query: '-t:ws'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(7)); controller.setActiveFilter(query: '-'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(0)); controller.setActiveFilter(query: 'nonsense'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(0)); controller.setActiveFilter(query: '-nonsense'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(0)); controller.setActiveFilter(); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(numRequests)); controller.setActiveFilter(query: '-t:ws,http'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(4)); controller.setActiveFilter(query: '-t:ws,http method:put'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(1)); controller.setActiveFilter(query: '-status:error method:get'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(5)); controller.setActiveFilter(query: '-status:error method:get t:http'); expect(profile, hasLength(numRequests)); expect(controller.filteredData.value, hasLength(2)); }); }); group('CurrentNetworkRequests', () { late CurrentNetworkRequests currentNetworkRequests; late int notifyCount; void notifyCountIncrement() => notifyCount++; setUp(() { currentNetworkRequests = CurrentNetworkRequests(); notifyCount = 0; currentNetworkRequests.addListener(notifyCountIncrement); }); tearDown(() { currentNetworkRequests.removeListener(notifyCountIncrement); }); group('http', () { final startTime = DateTime(2021).microsecondsSinceEpoch; final endTime = startTime + 1000000; final httpBaseObject = { 'id': '101', 'isolateId': '2', 'method': 'method1', 'uri': 'http://test.com', 'events': [], 'startTime': startTime, }; final socketStatObject = { 'id': '21', 'startTime': startTime, 'lastReadTime': 25, 'lastWriteTime': 30, 'address': '0.0.0.0', 'port': 1234, 'socketType': 'ws', 'readBytes': 20, 'writeBytes': 40, }; final request1Pending = HttpProfileRequest.parse(httpBaseObject)!; final request1Done = HttpProfileRequest.parse({ ...httpBaseObject, 'endTime': endTime, 'response': { 'startTime': startTime, 'endTime': endTime, 'redirects': [], 'statusCode': 200, }, })!; final request2Pending = HttpProfileRequest.parse({ ...httpBaseObject, 'id': '102', })!; final socketStats1Pending = SocketStatistic.parse({...socketStatObject})!; final socketStats1Done = SocketStatistic.parse({ ...socketStatObject, 'endTime': endTime, })!; final socketStats2Pending = SocketStatistic.parse({...socketStatObject, 'id': '22'})!; test( 'adding multiple socket and http requests notifies listeners only once', () { final reqs = [request1Pending, request2Pending]; final sockets = [socketStats1Pending, socketStats2Pending]; currentNetworkRequests.updateOrAddAll( requests: reqs, sockets: sockets, timelineMicrosOffset: 0, ); expect(notifyCount, 1); // Check that all requests ids are present and that there are no // endtimes expect( currentNetworkRequests.value.map((e) => [e.id, e.endTimestamp]), [ ['101', null], ['102', null], ['21', null], ['22', null], ], ); currentNetworkRequests.updateOrAddAll( requests: [request1Done], sockets: [socketStats1Done], timelineMicrosOffset: 0, ); expect(notifyCount, 2); // Check that all requests ids are present and that the endtimes have // been updated accordingly expect( currentNetworkRequests.value .map((e) => [e.id, e.endTimestamp?.microsecondsSinceEpoch]), [ ['101', endTime], ['102', null], ['21', endTime], ['22', null], ], ); }, ); }); }); }
devtools/packages/devtools_app/test/network/network_controller_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/network/network_controller_test.dart", "repo_id": "devtools", "token_count": 4836 }
112
// 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_test/test_data.dart'; import 'package:flutter_test/flutter_test.dart'; import '../test_infra/test_data/performance/sample_performance_data.dart'; void main() { group('$OfflinePerformanceData', () { test('create empty data object', () { final offlineData = OfflinePerformanceData(); expect(offlineData.perfettoTraceBinary, isNull); expect(offlineData.frames, isEmpty); expect(offlineData.selectedFrame, isNull); expect(offlineData.rasterStats, isNull); expect(offlineData.rebuildCountModel, isNull); expect(offlineData.displayRefreshRate, 60.0); }); test('init from parse', () { OfflinePerformanceData offlineData = OfflinePerformanceData.parse({}); expect(offlineData.frames, isEmpty); expect(offlineData.selectedFrame, isNull); expect(offlineData.selectedFrame, isNull); expect(offlineData.displayRefreshRate, equals(60.0)); expect(offlineData.rasterStats, isNull); offlineData = OfflinePerformanceData.parse(rawPerformanceData); expect(offlineData.perfettoTraceBinary, isNotNull); expect(offlineData.frames.length, 3); expect(offlineData.selectedFrame, isNotNull); expect(offlineData.selectedFrame!.id, equals(2)); expect(offlineData.displayRefreshRate, equals(60)); expect( offlineData.rasterStats!.json, equals(rasterStatsFromDevToolsJson), ); expect(offlineData.rebuildCountModel, isNull); }); test('to json', () { OfflinePerformanceData offlineData = OfflinePerformanceData.parse({}); expect( offlineData.toJson(), equals({ OfflinePerformanceData.traceBinaryKey: null, OfflinePerformanceData.flutterFramesKey: <Object?>[], OfflinePerformanceData.selectedFrameIdKey: null, OfflinePerformanceData.displayRefreshRateKey: 60, OfflinePerformanceData.rasterStatsKey: null, OfflinePerformanceData.rebuildCountModelKey: null, }), ); offlineData = OfflinePerformanceData.parse(rawPerformanceData); expect(offlineData.toJson(), rawPerformanceData); }); }); group('$FlutterTimelineEvent', () { test('isUiEvent', () { depthFirstTraversal( FlutterFrame6.uiEvent, action: (node) { expect( node.isUiEvent, true, reason: 'Expected ${node.name} event to have type ' '${TimelineEventType.ui}.', ); }, ); }); test('isRasterFrameIdentifier', () { depthFirstTraversal( FlutterFrame6.rasterEvent, action: (node) { expect( node.isRasterEvent, true, reason: 'Expected ${node.name} event to have type ' '${TimelineEventType.raster}.', ); }, ); }); }); }
devtools/packages/devtools_app/test/performance/performance_model_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/performance/performance_model_test.dart", "repo_id": "devtools", "token_count": 1263 }
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 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/shared/analytics/prompt.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:provider/provider.dart'; import 'package:unified_analytics/src/constants.dart' as unified_analytics; const windowSize = Size(2000.0, 1000.0); void main() { late AnalyticsController controller; late bool didCallEnableAnalytics; late bool didMarkConsentMessageAsShown; Widget wrapWithAnalytics( Widget child, { AnalyticsController? controllerToUse, }) { if (controllerToUse != null) { controller = controllerToUse; } return Provider<AnalyticsController>.value( value: controller, child: child, ); } test('Unit test parseAnalyticsConsentMessage with consent message', () { final result = parseAnalyticsConsentMessage(unified_analytics.kToolsMessage); expect(result, isNotEmpty); expect(result, hasLength(3)); }); group('AnalyticsPrompt', () { setUp(() { didCallEnableAnalytics = false; didMarkConsentMessageAsShown = false; setGlobal(ServiceConnectionManager, FakeServiceConnectionManager()); setGlobal(IdeTheme, IdeTheme()); }); group('with analytics enabled', () { group('on first run', () { setUp(() { didCallEnableAnalytics = false; controller = AnalyticsController( enabled: true, firstRun: true, onEnableAnalytics: () { didCallEnableAnalytics = true; }, consentMessage: 'fake message', markConsentMessageAsShown: () { didMarkConsentMessageAsShown = true; }, ); }); testWidgetsWithWindowSize( 'displays the prompt and calls enable analytics', windowSize, (WidgetTester tester) async { expect(controller.analyticsEnabled.value, isTrue); expect( didCallEnableAnalytics, isTrue, reason: 'Analytics is enabled on first run', ); expect(didMarkConsentMessageAsShown, isFalse); final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect( find.text('Send usage statistics for DevTools?'), findsOne, reason: 'The consent message should be shown on first run', ); expect(controller.analyticsEnabled.value, isTrue); expect( didMarkConsentMessageAsShown, isTrue, reason: 'The consent message should be marked as shown after displaying', ); }, ); testWidgetsWithWindowSize( 'sets up analytics on controller creation', windowSize, (WidgetTester tester) async { expect(controller.analyticsInitialized, isTrue); }, ); }); group('on non-first run', () { setUp(() { controller = AnalyticsController( enabled: true, firstRun: false, onEnableAnalytics: () { didCallEnableAnalytics = true; }, consentMessage: 'fake message', ); }); testWidgetsWithWindowSize( 'does not display prompt or call enable analytics', windowSize, (WidgetTester tester) async { expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isFalse); final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect( find.text('Send usage statistics for DevTools?'), findsNothing, ); expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isFalse); }, ); testWidgetsWithWindowSize( 'sets up analytics on controller creation', windowSize, (WidgetTester tester) async { expect(controller.analyticsInitialized, isTrue); }, ); }); testWidgetsWithWindowSize( 'displays the child', windowSize, (WidgetTester tester) async { final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), controllerToUse: AnalyticsController( enabled: true, firstRun: false, consentMessage: 'fake message', ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect(find.text('Child Text'), findsOneWidget); }, ); }); group('without analytics enabled', () { group('on first run', () { setUp(() { controller = AnalyticsController( enabled: false, firstRun: true, onEnableAnalytics: () { didCallEnableAnalytics = true; }, consentMessage: 'fake message', ); }); testWidgetsWithWindowSize( 'displays prompt and calls enables analytics', windowSize, (WidgetTester tester) async { expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect( find.text('Send usage statistics for DevTools?'), findsOneWidget, ); expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); }, ); testWidgetsWithWindowSize( 'sets up analytics on controller creation', windowSize, (WidgetTester tester) async { expect(controller.analyticsInitialized, isTrue); }, ); testWidgetsWithWindowSize( 'close button closes prompt without disabling analytics', windowSize, (WidgetTester tester) async { expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect( find.text('Send usage statistics for DevTools?'), findsOneWidget, ); expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); final closeButtonFinder = find.byType(IconButton); expect(closeButtonFinder, findsOneWidget); await tester.tap(closeButtonFinder); await tester.pumpAndSettle(); expect( find.text('Send usage statistics for DevTools?'), findsNothing, ); expect(controller.analyticsEnabled.value, isTrue); }, ); testWidgetsWithWindowSize( 'Sounds Good button closes prompt without disabling analytics', windowSize, (WidgetTester tester) async { expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect( find.text('Send usage statistics for DevTools?'), findsOneWidget, ); expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); final soundsGoodFinder = find.text('Sounds good!'); expect(soundsGoodFinder, findsOneWidget); await tester.tap(soundsGoodFinder); await tester.pumpAndSettle(); expect( find.text('Send usage statistics for DevTools?'), findsNothing, ); expect(controller.analyticsEnabled.value, isTrue); }, ); testWidgetsWithWindowSize( 'No Thanks button closes prompt and disables analytics', windowSize, (WidgetTester tester) async { expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect( find.text('Send usage statistics for DevTools?'), findsOneWidget, ); expect(controller.analyticsEnabled.value, isTrue); expect(didCallEnableAnalytics, isTrue); final noThanksFinder = find.text('No thanks.'); expect(noThanksFinder, findsOneWidget); await tester.tap(noThanksFinder); await tester.pumpAndSettle(); expect( find.text('Send usage statistics for DevTools?'), findsNothing, ); expect(controller.analyticsEnabled.value, isFalse); }, ); }); group('on non-first run', () { setUp(() { controller = AnalyticsController( enabled: false, firstRun: false, onEnableAnalytics: () { didCallEnableAnalytics = true; }, consentMessage: 'fake message', ); }); testWidgetsWithWindowSize( 'does not display prompt or enable analytics from prompt', windowSize, (WidgetTester tester) async { expect(controller.analyticsEnabled.value, isFalse); expect(didCallEnableAnalytics, isFalse); final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect( find.text('Send usage statistics for DevTools?'), findsNothing, ); expect(controller.analyticsEnabled.value, isFalse); expect(didCallEnableAnalytics, isFalse); }, ); testWidgetsWithWindowSize( 'does not set up analytics on controller creation', windowSize, (WidgetTester tester) async { expect(controller.analyticsInitialized, isFalse); }, ); }); testWidgetsWithWindowSize( 'displays the child', windowSize, (WidgetTester tester) async { final prompt = wrapWithAnalytics( const AnalyticsPrompt( child: Text('Child Text'), ), controllerToUse: AnalyticsController( enabled: false, firstRun: false, consentMessage: 'fake message', ), ); await tester.pumpWidget(wrap(prompt)); await tester.pump(); expect(find.text('Child Text'), findsOneWidget); }, ); }); }); }
devtools/packages/devtools_app/test/shared/analytics_prompt_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/analytics_prompt_test.dart", "repo_id": "devtools", "token_count": 5911 }
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. // ignore_for_file: avoid_print @TestOn('vm') import 'package:devtools_app/src/shared/primitives/extent_delegate_list.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../test_infra/utils/extent_delegate_utils.dart'; import '../test_infra/utils/rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); group('RenderSliverFixedExtentDelgate', () { group('extentDelegate', () { test('itemExtent', () { final extents = [100.0, 200.0, 50.0, 100.0]; final extentDelegate = FixedExtentDelegate( // Create items with increasing extents. computeExtent: (index) => extents[index], computeLength: () => extents.length, ); expect(extentDelegate.length, equals(4)); for (int i = 0; i < extents.length; i++) { expect(extentDelegate.itemExtent(i), extents[i]); } expect(extentDelegate.itemExtent(1), 200.0); extents[1] = 500.0; extentDelegate.recompute(); expect(extentDelegate.itemExtent(1), 500.0); }); test('getMinChildIndexForScrollOffset', () { final extents = [100.0, 200.0, 50.0, 100.0]; final extentDelegate = FixedExtentDelegate( // Create items with increasing extents. computeExtent: (index) => extents[index], computeLength: () => extents.length, ); expect(extentDelegate.minChildIndexForScrollOffset(0), 0); expect(extentDelegate.minChildIndexForScrollOffset(-1000), 0); expect(extentDelegate.minChildIndexForScrollOffset(99), 0); expect(extentDelegate.minChildIndexForScrollOffset(99.99999999999), 1); expect(extentDelegate.minChildIndexForScrollOffset(250), 1); expect(extentDelegate.minChildIndexForScrollOffset(299), 1); expect(extentDelegate.minChildIndexForScrollOffset(299.99999999999), 2); expect(extentDelegate.minChildIndexForScrollOffset(300), 2); expect(extentDelegate.minChildIndexForScrollOffset(330), 2); expect(extentDelegate.minChildIndexForScrollOffset(350), 3); expect(extentDelegate.minChildIndexForScrollOffset(449), 3); // Off the end of the list. expect(extentDelegate.minChildIndexForScrollOffset(450), 4); expect(extentDelegate.minChildIndexForScrollOffset(1000000), 4); }); try { test('getMaxChildIndexForScrollOffset', () { final extents = [100.0, 200.0, 50.0, 100.0]; final extentDelegate = FixedExtentDelegate( // Create items with increasing extents. computeExtent: (index) => extents[index], computeLength: () => extents.length, ); expect(extentDelegate.maxChildIndexForScrollOffset(0), 0); expect(extentDelegate.maxChildIndexForScrollOffset(-1000), 0); expect(extentDelegate.maxChildIndexForScrollOffset(99), 0); // The behavior is a bit counter intuitive but this matching the // existing fixed extent behavior. The max child for an offset is // actually intentionally less than the min child for the case that // the child is right on the boundary. expect( extentDelegate.maxChildIndexForScrollOffset(99.99999999999), 0, ); expect(extentDelegate.maxChildIndexForScrollOffset(250), 1); expect(extentDelegate.maxChildIndexForScrollOffset(299), 1); expect( extentDelegate.maxChildIndexForScrollOffset(299.99999999999), 1, ); expect(extentDelegate.maxChildIndexForScrollOffset(300), 1); expect(extentDelegate.maxChildIndexForScrollOffset(330), 2); expect(extentDelegate.maxChildIndexForScrollOffset(350), 2); expect(extentDelegate.maxChildIndexForScrollOffset(449), 3); // Off the end of the list. expect(extentDelegate.maxChildIndexForScrollOffset(450), 3); expect(extentDelegate.maxChildIndexForScrollOffset(1000000), 4); }); } catch (e, s) { print(s); } test('zeroHeightChildren', () { // Zero height children could cause problems for the logic to find the // min and max matching children. final extents = [100.0, 200.0, 0.0, 0.0, 0.0, 100.0]; final extentDelegate = FixedExtentDelegate( // Create items with increasing extents. computeExtent: (index) => extents[index], computeLength: () => extents.length, ); expect(extentDelegate.minChildIndexForScrollOffset(299), 1); expect(extentDelegate.maxChildIndexForScrollOffset(299), 1); expect(extentDelegate.minChildIndexForScrollOffset(299.999999999), 1); expect(extentDelegate.maxChildIndexForScrollOffset(299.999999999), 1); expect(extentDelegate.minChildIndexForScrollOffset(300), 2); expect(extentDelegate.maxChildIndexForScrollOffset(300), 1); expect(extentDelegate.minChildIndexForScrollOffset(301), 5); expect(extentDelegate.maxChildIndexForScrollOffset(301), 5); }); }); test('layout test - rounding error', () { // These heights are ignored as the FixedExtentDelegate determines the // size. final List<RenderBox> children = <RenderBox>[ RenderSizedBox(const Size(400.0, 100.0)), RenderSizedBox(const Size(400.0, 100.0)), RenderSizedBox(const Size(400.0, 100.0)), ]; // Value to tweak to change how large the items are. double extentFactor = 800.0; final extentDelegate = FixedExtentDelegate( // Create items with increasing extents. computeExtent: (index) => (index + 1) * extentFactor, computeLength: () => children.length, ); final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager( children: children, extentDelegate: extentDelegate, ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 0, children: <RenderSliver>[ childManager.createRenderSliverExtentDelegate(), ], ); layout(root); // viewport is 800x600 // items have height 800, 1600, and 2400. expect(children[0].attached, true); expect(children[1].attached, false); root.offset = ViewportOffset.fixed(800); pumpFrame(); expect(children[0].attached, false); expect(children[1].attached, true); expect(children[2].attached, false); // Simulate double precision error. root.offset = ViewportOffset.fixed(2399.999999999998); pumpFrame(); expect(children[0].attached, false); expect(children[1].attached, false); expect(children[2].attached, true); root.offset = ViewportOffset.fixed(800); pumpFrame(); expect(children[0].attached, false); expect(children[1].attached, true); expect(children[2].attached, false); // simulate an animation. extentFactor = 1000.0; extentDelegate.recompute(); pumpFrame(); expect(children[0].attached, true); expect(children[1].attached, true); expect(children[2].attached, false); }); }); }
devtools/packages/devtools_app/test/shared/extent_delegate_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/extent_delegate_test.dart", "repo_id": "devtools", "token_count": 3052 }
115
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/shared/navigation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('routeNameWithQueryParams', () { test('Generates a route name with params without a context', () { expect(routeNameWithQueryParams(null, '/'), '/'); expect(routeNameWithQueryParams(null, '/home'), '/home'); expect(routeNameWithQueryParams(null, '/', {}), '/?'); expect(routeNameWithQueryParams(null, '/', {'foo': 'bar'}), '/?foo=bar'); expect( routeNameWithQueryParams(null, '/', {'foo': 'bar', 'theme': 'dark'}), '/?foo=bar&theme=dark', ); }); /// Builds an app that calls [onBuild] when [initialRoute] loads. Widget routeTestingApp( void Function(BuildContext) onBuild, { String initialRoute = '/', }) { return MaterialApp( initialRoute: initialRoute, routes: { initialRoute: (context) { onBuild(context); return const SizedBox(); }, }, ); } testWidgets( 'Generates a route name with parameters with an empty route in the context', (WidgetTester tester) async { late String generatedRoute; await tester.pumpWidget( routeTestingApp((context) { generatedRoute = routeNameWithQueryParams( context, '/home', {'foo': 'bar', 'theme': 'dark'}, ); }), ); expect(generatedRoute, '/home?foo=bar&theme=dark'); }, ); testWidgets( 'Respects dark theme of the current route from the context', (WidgetTester tester) async { late String generatedRoute; await tester.pumpWidget( routeTestingApp( (context) { generatedRoute = routeNameWithQueryParams(context, '/home', {'foo': 'bar'}); }, initialRoute: '/?theme=dark', ), ); expect(generatedRoute, '/home?foo=bar&theme=dark'); }, ); testWidgets( 'Removes redundant light theme of the current route from the context', (WidgetTester tester) async { late String generatedRoute; await tester.pumpWidget( routeTestingApp( (context) { generatedRoute = routeNameWithQueryParams(context, '/home', {'foo': 'bar'}); }, initialRoute: '/?theme=light', ), ); expect(generatedRoute, '/home?foo=bar'); }, ); testWidgets( 'Overrides dark theme of the current route when a replacement theme is given', (WidgetTester tester) async { late String generatedRoute; await tester.pumpWidget( routeTestingApp( (context) { generatedRoute = routeNameWithQueryParams( context, '/home', {'foo': 'bar', 'theme': 'light'}, ); }, initialRoute: '/?snap=crackle&theme=dark', ), ); expect(generatedRoute, '/home?foo=bar&theme=light'); }, ); testWidgets( 'Overrides other parameters of the current route from the context', (WidgetTester tester) async { late String generatedRoute; await tester.pumpWidget( routeTestingApp( (context) { generatedRoute = routeNameWithQueryParams(context, '/home', {'foo': 'baz'}); }, initialRoute: '/?foo=bar&baz=quux', ), ); expect(generatedRoute, '/home?foo=baz'); }, ); group('in an unnamed route', () { // TODO(jacobr): rewrite these tests in a way that makes sense given how // we are now managing the dark and light themes. /* /// Builds an app that loads an unnamed route and calls [onBuild] when /// the unnamed route loads. Widget unnamedRouteApp(void Function(BuildContext) onUnnamedRouteBuild) { return routeTestingApp((context) { WidgetsBinding.instance.addPostFrameCallback((_) { Navigator.of(context) .push(MaterialPageRoute(builder: (innerContext) { onUnnamedRouteBuild(innerContext); return const SizedBox(); })); }); }); } testWidgets('Builds with global dark mode when dark mode is on', (WidgetTester tester) async { String generatedRoute; // ignore: deprecated_member_use_from_same_package setTheme(darkTheme: true); await tester.pumpWidget(unnamedRouteApp((context) { generatedRoute = routeNameWithQueryParams(context, '/home', {'foo': 'baz'}); })); await tester.pumpAndSettle(); expect(generatedRoute, '/home?foo=baz&theme=dark'); // Teardown the global theme change // ignore: deprecated_member_use_from_same_package setTheme(darkTheme: false); }); testWidgets('Builds with global light mode when dark mode is off', (WidgetTester tester) async { String generatedRoute; await tester.pumpWidget(unnamedRouteApp((context) { generatedRoute = routeNameWithQueryParams(context, '/home', {'foo': 'baz'}); })); await tester.pumpAndSettle(); expect(generatedRoute, '/home?foo=baz'); }); */ }); }); }
devtools/packages/devtools_app/test/shared/navigation_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/navigation_test.dart", "repo_id": "devtools", "token_count": 2548 }
116
// 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/src/service/service_extension_widgets.dart'; import 'package:devtools_app/src/service/service_extensions.dart' as extensions; import 'package:devtools_app/src/service/service_manager.dart'; import 'package:devtools_app/src/service/service_registrations.dart'; import 'package:devtools_app/src/shared/connected_app.dart'; import 'package:devtools_app/src/shared/notifications.dart'; import 'package:devtools_app/src/shared/primitives/message_bus.dart'; import 'package:devtools_app_shared/service.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; void main() { late MockServiceConnectionManager mockServiceConnection; late MockServiceManager mockServiceManager; setUp(() { mockServiceConnection = createMockServiceConnectionWithDefaults(); mockServiceManager = mockServiceConnection.serviceManager as MockServiceManager; when(mockServiceConnection.appState).thenReturn( AppState( mockServiceManager.isolateManager.selectedIsolate, ), ); when(unawaited(mockServiceManager.runDeviceBusyTask(any))) .thenAnswer((_) => Future<void>.value()); when(mockServiceManager.isMainIsolatePaused).thenReturn(false); setGlobal(ServiceConnectionManager, mockServiceConnection); setGlobal(NotificationService, NotificationService()); setGlobal(IdeTheme, IdeTheme()); }); group('Hot Reload Button', () { int reloads = 0; setUp(() { reloads = 0; // Intentionally unawaited. // ignore: discarded_futures when(mockServiceManager.performHotReload()).thenAnswer((invocation) { reloads++; return Future<void>.value(); }); setGlobal(IdeTheme, IdeTheme()); }); testWidgetsWithContext( 'performs a hot reload when pressed', (WidgetTester tester) async { registerServiceExtension(mockServiceManager, hotReload); const button = HotReloadButton(); await tester.pumpWidget( wrap( wrapWithNotifications( const Scaffold(body: Center(child: button)), ), ), ); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(reloads, 0); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(reloads, 1); }, context: { MessageBus: MessageBus(), }, ); testWidgets( 'does not perform a hot reload when the extension is not registered.', (WidgetTester tester) async { registerServiceExtension( mockServiceManager, hotReload, serviceAvailable: false, ); const button = HotReloadButton(); await tester .pumpWidget(wrap(const Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(reloads, 0); await tester.tap(find.byWidget(button), warnIfMissed: false); await tester.pumpAndSettle(); expect(reloads, 0); }, ); }); group('Hot Restart Button', () { int restarts = 0; setUp(() { restarts = 0; // Intentionally unawaited. // ignore: discarded_futures when(mockServiceManager.performHotRestart()).thenAnswer((invocation) { restarts++; return Future<void>.value(); }); }); testWidgetsWithContext( 'performs a hot restart when pressed', (WidgetTester tester) async { registerServiceExtension(mockServiceManager, hotRestart); const button = HotRestartButton(); await tester.pumpWidget( wrap( wrapWithNotifications( const Scaffold(body: Center(child: button)), ), ), ); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(restarts, 0); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(restarts, 1); }, context: { MessageBus: MessageBus(), }, ); testWidgets( 'does not perform a hot restart when the service is not available', (WidgetTester tester) async { registerServiceExtension( mockServiceManager, hotRestart, serviceAvailable: false, ); const button = HotRestartButton(); await tester .pumpWidget(wrap(const Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await tester.pumpAndSettle(); expect(restarts, 0); await tester.tap(find.byWidget(button), warnIfMissed: false); await tester.pumpAndSettle(); expect(restarts, 0); }, ); }); group('Structured Errors toggle', () { late ValueListenable<ServiceExtensionState> serviceState; late ServiceExtensionState mostRecentState; void serviceStateListener() { mostRecentState = serviceState.value; } setUp(() async { await (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeFrame(); serviceState = mockServiceConnection .serviceManager.serviceExtensionManager .getServiceExtensionState(extensions.structuredErrors.extension); serviceState.addListener(serviceStateListener); }); tearDown(() { serviceState.removeListener(serviceStateListener); }); testWidgets('toggles', (WidgetTester tester) async { await (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeAddServiceExtension(extensions.structuredErrors.extension); const button = StructuredErrorsToggle(); await tester .pumpWidget(wrap(const Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); await (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeFrame(); expect(mostRecentState.value, true); await tester.tap(find.byWidget(button)); await tester.pumpAndSettle(); expect(mostRecentState.value, false); }); testWidgets( 'updates based on the service extension', (WidgetTester tester) async { await (mockServiceManager.serviceExtensionManager as FakeServiceExtensionManager) .fakeAddServiceExtension(extensions.structuredErrors.extension); const button = StructuredErrorsToggle(); await tester .pumpWidget(wrap(const Scaffold(body: Center(child: button)))); expect(find.byWidget(button), findsOneWidget); await mockServiceManager.serviceExtensionManager .setServiceExtensionState( extensions.structuredErrors.extension, enabled: true, value: true, ); await tester.pumpAndSettle(); expect(toggle.value, true, reason: 'The extension is enabled.'); await mockServiceManager.serviceExtensionManager .setServiceExtensionState( extensions.structuredErrors.extension, enabled: false, value: false, ); await tester.pumpAndSettle(); expect(toggle.value, false, reason: 'The extension is disabled.'); }, ); }); } void registerServiceExtension( MockServiceManager mockServiceManager, RegisteredServiceDescription description, { bool serviceAvailable = true, }) { when( mockServiceManager.registeredServiceListenable(description.service), ).thenAnswer((invocation) { final listenable = ImmediateValueNotifier(serviceAvailable); return listenable; }); } Switch get toggle => find.byType(Switch).evaluate().first.widget as Switch;
devtools/packages/devtools_app/test/shared/service_extension_widgets_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/service_extension_widgets_test.dart", "repo_id": "devtools", "token_count": 3314 }
117
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/shared/constants.dart'; import 'package:devtools_app/src/standalone_ui/api/impl/vs_code_api.dart'; import 'package:devtools_app/src/standalone_ui/vs_code/debug_sessions.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/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import '../../test_infra/test_data/dart_tooling_api/mock_api.dart'; void main() { const windowSize = Size(2000.0, 2000.0); late MockVsCodeApi mockVsCodeApi; late final Map<String, VsCodeDevice> deviceMap; setUpAll(() { // Set test mode so that the debug list of extensions will be used. setTestMode(); final devices = stubbedDevices.map((d) => MapEntry(d.id, d)); deviceMap = {for (final d in devices) d.key: d.value}; }); setUp(() { mockVsCodeApi = MockVsCodeApi(); when(mockVsCodeApi.capabilities).thenReturn( VsCodeCapabilitiesImpl({ 'executeCommand': true, 'selectDevice': true, 'openDevToolsPage': true, 'openDevToolsExternally': true, 'hotReload': true, 'hotRestart': true, }), ); setGlobal(IdeTheme, IdeTheme()); setGlobal(PreferencesController, PreferencesController()); }); Future<void> pumpDebugSessions(WidgetTester tester) async { await tester.pumpWidget( wrap( DebugSessions( api: mockVsCodeApi, sessions: _debugSessions, deviceMap: deviceMap, ), ), ); } group('$DebugSessions', () { Finder iconButtonFinder(IconData icon, {required int index}) { return find .byWidgetPredicate( (widget) => widget.runtimeType == IconButton && ((widget as IconButton).icon as Icon).icon == icon, ) .at(index); } void verifyDebugSessionState( WidgetTester tester, { required int debugSessionIndex, required String sessionDisplayText, required bool hotButtonsEnabled, required bool devtoolsButtonEnabled, }) { expect(find.text(sessionDisplayText), findsOneWidget); final hotReloadButtonFinder = iconButtonFinder(hotReloadIcon, index: debugSessionIndex); final hotRestartButtonFinder = iconButtonFinder(hotRestartIcon, index: debugSessionIndex); final devtoolsButtonFinder = iconButtonFinder(Icons.construction, index: debugSessionIndex); expect(hotReloadButtonFinder, findsOneWidget); expect(hotRestartButtonFinder, findsOneWidget); expect(devtoolsButtonFinder, findsOneWidget); final hotReloadButton = tester.widget(hotReloadButtonFinder) as IconButton; final hotRestartButton = tester.widget(hotRestartButtonFinder) as IconButton; final devtoolsMenuButton = tester.widget(devtoolsButtonFinder) as IconButton; expect( hotReloadButton.onPressed, hotButtonsEnabled ? isNotNull : isNull, ); expect( hotRestartButton.onPressed, hotButtonsEnabled ? isNotNull : isNull, ); expect( devtoolsMenuButton.onPressed, devtoolsButtonEnabled ? isNotNull : isNull, ); } final tests = [ ( sessionDisplay: 'Session (Flutter) (macos) (debug)', hotButtonsEnabled: true, devtoolsButtonEnabled: true, ), ( sessionDisplay: 'Session (Flutter) (macos) (profile)', hotButtonsEnabled: false, devtoolsButtonEnabled: true, ), ( sessionDisplay: 'Session (Flutter) (macos) (release)', hotButtonsEnabled: false, devtoolsButtonEnabled: false, ), ( sessionDisplay: 'Session (Flutter) (macos) (jit_release)', hotButtonsEnabled: false, devtoolsButtonEnabled: false, ), ( sessionDisplay: 'Session (Flutter) (chrome) (debug)', hotButtonsEnabled: true, devtoolsButtonEnabled: true, ), ( sessionDisplay: 'Session (Flutter) (chrome) (profile)', hotButtonsEnabled: false, devtoolsButtonEnabled: true, ), ( sessionDisplay: 'Session (Flutter) (chrome) (release)', hotButtonsEnabled: false, devtoolsButtonEnabled: false, ), ( sessionDisplay: 'Session (Dart) (macos)', hotButtonsEnabled: true, devtoolsButtonEnabled: true, ), ]; testWidgetsWithWindowSize( 'rows render properly for run mode', windowSize, (tester) async { await pumpDebugSessions(tester); await tester.pump(const Duration(milliseconds: 500)); for (var i = 0; i < tests.length; i++) { final test = tests[i]; // ignore: avoid_print, defines individual test case. print('testing: ${test.sessionDisplay}'); verifyDebugSessionState( tester, debugSessionIndex: i, sessionDisplayText: test.sessionDisplay, hotButtonsEnabled: test.hotButtonsEnabled, devtoolsButtonEnabled: test.devtoolsButtonEnabled, ); } }, ); testWidgetsWithWindowSize( 'DevTools dropdown contains extensions submenu', windowSize, (tester) async { await pumpDebugSessions(tester); await tester.pump(const Duration(milliseconds: 500)); // Index 0 so that we are checking a debug desktop session, where the // DevTools button is enabled. final devtoolsButtonFinder = iconButtonFinder(Icons.construction, index: 0); expect(devtoolsButtonFinder, findsOneWidget); await tester.tap(devtoolsButtonFinder); await tester.pumpAndSettle(); final extensionsSubmenuButtonFinder = find.text('Extensions'); expect(extensionsSubmenuButtonFinder, findsOneWidget); // We should not see the extensions in the dropdown menu at this point. expect(find.text('bar'), findsNothing); expect(find.text('foo'), findsNothing); expect(find.text('provider'), findsNothing); final hoverLocation = tester.getCenter(extensionsSubmenuButtonFinder); await tester.startGesture(hoverLocation, kind: PointerDeviceKind.mouse); await tester.pumpAndSettle(); // We should now see the extensions in the dropdown menu. expect(find.text('bar'), findsOneWidget); expect(find.text('foo'), findsOneWidget); expect(find.text('provider'), findsOneWidget); }, ); }); } final _debugSessions = <VsCodeDebugSession>[ // Flutter native apps. generateDebugSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'debug', ), generateDebugSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'profile', ), generateDebugSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'release', ), generateDebugSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'jit_release', ), // Flutter web apps. generateDebugSession( debuggerType: 'Flutter', deviceId: 'chrome', flutterMode: 'debug', ), generateDebugSession( debuggerType: 'Flutter', deviceId: 'chrome', flutterMode: 'profile', ), generateDebugSession( debuggerType: 'Flutter', deviceId: 'chrome', flutterMode: 'release', ), // Dart CLI app. generateDebugSession( debuggerType: 'Dart', deviceId: 'macos', ), ]; VsCodeDebugSession generateDebugSession({ required String debuggerType, required String deviceId, String? flutterMode, }) { return VsCodeDebugSessionImpl( id: '$debuggerType-$deviceId-$flutterMode', name: 'Session ($debuggerType) ($deviceId)', vmServiceUri: 'ws://127.0.0.1:1234/ws', flutterMode: flutterMode, flutterDeviceId: deviceId, debuggerType: debuggerType, projectRootPath: Platform.isWindows ? r'C:\mock\root\path' : '/mock/root/path', ); }
devtools/packages/devtools_app/test/standalone_ui/vs_code/debug_sessions_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/standalone_ui/vs_code/debug_sessions_test.dart", "repo_id": "devtools", "token_count": 3424 }
118
// 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:collection'; import 'dart:convert'; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import '../../../test_infra/test_data/dart_tooling_api/mock_api.dart'; /// A simple UI that acts as a stand-in host IDE to simplify the development /// workflow when working on embedded tooling. /// /// This UI interacts with [FakeDartToolingApi] to allow triggering events that /// would normally be fired by the IDE and also shows a log of recent requests. class VsCodeFlutterPanelMockEditor extends StatefulWidget { const VsCodeFlutterPanelMockEditor({ super.key, required this.api, this.child, }); /// The mock API to interact with. final FakeDartToolingApi api; final Widget? child; @override State<VsCodeFlutterPanelMockEditor> createState() => _VsCodeFlutterPanelMockEditorState(); } class _VsCodeFlutterPanelMockEditorState extends State<VsCodeFlutterPanelMockEditor> { FakeDartToolingApi get api => widget.api; /// The number of communication messages to keep in the log. static const maxLogEvents = 20; /// The last [maxLogEvents] communication messages sent between the panel /// and the "host IDE". final logRing = DoubleLinkedQueue<String>(); /// A stream that emits each time the log is updated to allow the log widget /// to be rebuilt. Stream<void>? logUpdated; /// Flutter icon for the sidebar. final sidebarImageBytes = base64Decode( 'iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAABF1BMVEUAAAD///////+/v//MzMzb29vf39/j4+PV1erY2Njb29vS4eHX1+TZ2ebW1uDY2OLW3d3Y2N7Z2d/a2uDV2+DW2+DX3OHZ2eLZ2d7V2t/Y2OHX29/X29/Z2eDW2eDW2uDX2uHW2d/X2uDY2+HW2d/W2+HW2eHX2d/W2+DW2eDX2eHX2uHX29/X2d/Y2uDY2uDW2uDX2uDX2+DX2+DX2eDX2t/Y2+DX29/Y2eDW2eDX2uDX2uDW2d/X2uDX2uDY2uDX2uHX2eDX2uDX2uHY2t/X2+DX2uDY2uDX2uDX2uDX2+DW2uDX2eDX2uDX2uDX2uDX2eDX2uDX2uDX2uDX2uDX2uDX2uDX2uDX2uDX2uDX2uDX2uDX2uANs9umAAAAXHRSTlMAAgMEBQcICQwNDhETFBkaJScoKTEyMzU2Nzs/QElKS0xQU1VYXV5fY2RlbXh5e3yDi4yNjpmboaKjpKepqrO1ub7AwcLEzM/R2Nnc4OPk5efr7O3w8vT3+Pn7/A+G+WEAAAABYktHRAH/Ai3eAAAA0UlEQVQoz2NgQAKythCgwYAKFCLtTIHAO0YbVVw23AREqUTroYlH0FrcGK94FJq4HExcH5c4t5IyGAiCxeUjDUGUWrQOr0cMBJiDJYwiJYCkarQOt5sXP5Al4OvKBZZgsgqRBJsDERf0c+GE2sFsE2IAVy/k78wBt53ZJkYXKi4c4MCO5C4mCR53Tz4gQyTIng3VyVoxSiDK04cVLY6YLEOlQE4PN2NElzEPkwFS0qHWLNhlxIPt2LDLiAY6cmDaoygmJqYe4cSJLmMBDStNIAcAHhssjDYY1ccAAAAASUVORK5CYII=', ); @override void initState() { super.initState(); // Listen to the log stream to maintain our buffer and trigger rebuilds. logUpdated = api.log.map((log) { logRing.add(log); while (logRing.length > maxLogEvents) { logRing.removeFirst(); } }); } @override Widget build(BuildContext context) { final editorTheme = VsCodeTheme.of(context); final theme = Theme.of(context); return SplitPane( axis: Axis.horizontal, initialFractions: const [0.25, 0.75], minSizes: const [200, 200], children: [ Row( children: [ SizedBox( width: 48, child: Container( alignment: Alignment.topCenter, padding: const EdgeInsets.only(top: 60), constraints: const BoxConstraints.expand(width: 48), color: editorTheme.activityBarBackgroundColor, child: Image.memory(sidebarImageBytes), ), ), Expanded( child: Container( color: editorTheme.sidebarBackgroundColor, child: widget.child ?? const Placeholder(), ), ), ], ), SplitPane( axis: Axis.vertical, initialFractions: const [0.5, 0.5], minSizes: const [200, 200], children: [ Container( color: editorTheme.editorBackgroundColor, padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Mock Editor', style: theme.textTheme.headlineMedium, ), const SizedBox(height: defaultSpacing), const Text( 'Use these buttons to simulate actions that would usually occur in the IDE.', ), const SizedBox(height: defaultSpacing), Row( children: [ const Text('Devices: '), ElevatedButton( onPressed: api.connectDevices, child: const Text('Connect'), ), ElevatedButton( onPressed: api.disconnectDevices, child: const Text('Disconnect'), ), ], ), const SizedBox(height: defaultSpacing), const Text('Debug Sessions: '), const SizedBox(height: denseSpacing), Row( children: [ ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'debug', ), child: const Text('Desktop debug'), ), const SizedBox(width: denseSpacing), ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'profile', ), child: const Text('Desktop profile'), ), const SizedBox(width: denseSpacing), ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'release', ), child: const Text('Desktop release'), ), const SizedBox(width: denseSpacing), ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Flutter', deviceId: 'macos', flutterMode: 'jit_release', ), child: const Text('Desktop jit_release'), ), ], ), const SizedBox(height: denseSpacing), Row( children: [ ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Flutter', deviceId: 'chrome', flutterMode: 'debug', ), child: const Text('Web debug'), ), const SizedBox(width: denseSpacing), ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Flutter', deviceId: 'chrome', flutterMode: 'profile', ), child: const Text('Web profile'), ), const SizedBox(width: denseSpacing), ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Flutter', deviceId: 'chrome', flutterMode: 'release', ), child: const Text('Web release'), ), ], ), const SizedBox(height: denseSpacing), Row( children: [ ElevatedButton( onPressed: () => api.startSession( debuggerType: 'Dart', deviceId: 'macos', ), child: const Text('Dart CLI'), ), ], ), const SizedBox(height: denseSpacing), ElevatedButton( onPressed: () => api.endSessions(), style: theme.elevatedButtonTheme.style!.copyWith( backgroundColor: const MaterialStatePropertyAll( Colors.red, ), ), child: const Text('Stop All'), ), ], ), ), Container( color: editorTheme.editorBackgroundColor, padding: const EdgeInsets.all(10), child: StreamBuilder( stream: logUpdated, builder: (context, snapshot) { return SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ for (final log in logRing) OutlineDecoration.onlyBottom( child: Container( width: double.infinity, padding: const EdgeInsets.symmetric( vertical: denseSpacing, ), child: Text( log, style: Theme.of(context).fixedFontStyle, ), ), ), ], ), ); }, ), ), ], ), ], ); } } /// A basic theme that matches the default colours of VS Code dart/light themes /// so the mock environment can be displayed in either. class VsCodeTheme { const VsCodeTheme._({ required this.activityBarBackgroundColor, required this.editorBackgroundColor, required this.foregroundColor, required this.sidebarBackgroundColor, }); const VsCodeTheme.dark() : this._( activityBarBackgroundColor: const Color(0xFF333333), editorBackgroundColor: const Color(0xFF1E1E1E), foregroundColor: const Color(0xFFD4D4D4), sidebarBackgroundColor: const Color(0xFF252526), ); const VsCodeTheme.light() : this._( activityBarBackgroundColor: const Color(0xFF2C2C2C), editorBackgroundColor: const Color(0xFFFFFFFF), foregroundColor: const Color(0xFF000000), sidebarBackgroundColor: const Color(0xFFF3F3F3), ); static VsCodeTheme of(BuildContext context) { return Theme.of(context).isDarkTheme ? const VsCodeTheme.dark() : const VsCodeTheme.light(); } final Color activityBarBackgroundColor; final Color editorBackgroundColor; final Color foregroundColor; final Color sidebarBackgroundColor; }
devtools/packages/devtools_app/test/test_infra/scenes/standalone_ui/vs_code_mock_editor.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/scenes/standalone_ui/vs_code_mock_editor.dart", "repo_id": "devtools", "token_count": 6592 }
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_shared/src/extensions/extension_model.dart'; final testExtensions = [fooExtension, barExtension, providerExtension]; final fooExtension = DevToolsExtensionConfig.parse({ DevToolsExtensionConfig.nameKey: 'foo', DevToolsExtensionConfig.issueTrackerKey: 'www.google.com', DevToolsExtensionConfig.versionKey: '1.0.0', DevToolsExtensionConfig.pathKey: '/path/to/foo', DevToolsExtensionConfig.isPubliclyHostedKey: 'false', }); final barExtension = DevToolsExtensionConfig.parse({ DevToolsExtensionConfig.nameKey: 'bar', DevToolsExtensionConfig.issueTrackerKey: 'www.google.com', DevToolsExtensionConfig.versionKey: '2.0.0', DevToolsExtensionConfig.materialIconCodePointKey: 0xe638, DevToolsExtensionConfig.pathKey: '/path/to/bar', DevToolsExtensionConfig.isPubliclyHostedKey: 'false', }); final providerExtension = DevToolsExtensionConfig.parse({ DevToolsExtensionConfig.nameKey: 'provider', DevToolsExtensionConfig.issueTrackerKey: 'https://github.com/rrousselGit/provider/issues', DevToolsExtensionConfig.versionKey: '3.0.0', DevToolsExtensionConfig.materialIconCodePointKey: 0xe50a, DevToolsExtensionConfig.pathKey: '/path/to/provider', DevToolsExtensionConfig.isPubliclyHostedKey: 'true', });
devtools/packages/devtools_app/test/test_infra/test_data/extensions.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/test_data/extensions.dart", "repo_id": "devtools", "token_count": 455 }
120
// 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. library foo; import 'dart:async' deferred as deferredAsync show Future; import 'dart:io' as a show File hide Directory; export 'dart:io'; abstract class A {} class B extends A { B(); B.named(); B.other() {} static late final _b = B(); factory B.single() { return _b; } String get foo => ''; set foo(String value) {} @override bool operator ==(Object other) { return false; } } class C<T extends B> implements A {} mixin D on A {} class E extends A with D {} extension on E {} extension EExtension on E {} external int get externalInt; typedef StringAlias = String; typedef void FunctionAlias1(String a, String b); typedef FunctionAlias2 = void Function(String a, String b); Future<void> e() async { await Future.delayed(const Duration(seconds: 1)); } void returns() { return; } Iterable<String> syncYield() sync* { yield ''; } Iterable<String> syncYieldStar() sync* { yield* syncYield(); } Stream<String> asyncYield() async* { await Future.delayed(const Duration(seconds: 1)); yield ''; } Stream<String> asyncYieldStar() async* { await Future.delayed(const Duration(seconds: 1)); yield* asyncYield(); } void err() { try { throw ''; } on ArgumentError { rethrow; } catch (e) { print('e'); } } void loops() { while (1 > 2) { if (3 > 4) { continue; } else { break; } return; } do { print(''); } while (1 > 2); } void switches() { Object? i = 1; switch (i as int) { case 1: break; default: return; } } void conditions() { if (1 > 2) { } else if (3 > 4) { } else {} } void misc(int a, {required int b}) { assert(true); assert(1 == 1, 'fail'); var a = new String.fromCharCode(1); const b = int.fromEnvironment(''); final c = ''; late final d = ''; print(d is String); print(d is! String); } class Covariance<T> { void covariance(covariant List<T> items) {} }
devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/keywords.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/keywords.dart", "repo_id": "devtools", "token_count": 793 }
121
// 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/object_viewport.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_class_display.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_field_display.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_function_display.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_instance_display.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_library_display.dart'; import 'package:devtools_app/src/screens/vm_developer/object_inspector/vm_script_display.dart'; import 'package:devtools_app/src/shared/history_viewport.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:vm_service/vm_service.dart' hide Stack; import '../vm_developer_test_utils.dart'; void main() { late TestObjectInspectorViewController testObjectInspectorViewController; late FakeServiceConnectionManager fakeServiceConnection; const windowSize = Size(2560.0, 1338.0); setUp(() { fakeServiceConnection = FakeServiceConnectionManager(); setUpMockScriptManager(); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal(BreakpointManager, BreakpointManager()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); setGlobal(NotificationService, NotificationService()); testObjectInspectorViewController = TestObjectInspectorViewController(); }); testWidgets('builds object viewport', (WidgetTester tester) async { await tester.pumpWidget( wrap(ObjectViewport(controller: testObjectInspectorViewController)), ); expect(ObjectViewport.viewportTitle(null), 'No object selected.'); expect(find.text('No object selected.'), findsOneWidget); expect(find.byTooltip('Refresh'), findsOneWidget); expect(find.byType(HistoryViewport<VmObject>), findsOneWidget); }); group('test for class object:', () { late MockClassObject mockClassObject; setUp(() { mockClassObject = MockClassObject(); mockVmObject(mockClassObject); }); testWidgetsWithWindowSize( 'viewport shows class display', windowSize, (WidgetTester tester) async { testObjectInspectorViewController.fakeObjectHistory .setCurrentObject(mockClassObject); await tester.pumpWidget( wrap(ObjectViewport(controller: testObjectInspectorViewController)), ); expect(ObjectViewport.viewportTitle(mockClassObject), 'Class FooClass'); expect(find.text('Class FooClass'), findsOneWidget); expect(find.byType(VmClassDisplay), findsOneWidget); }, ); }); group('test for field object:', () { late MockFieldObject mockFieldObject; setUp(() { mockFieldObject = MockFieldObject(); mockVmObject(mockFieldObject); }); testWidgetsWithWindowSize( 'viewport shows field display', windowSize, (WidgetTester tester) async { testObjectInspectorViewController.fakeObjectHistory .setCurrentObject(mockFieldObject); await tester.pumpWidget( wrap(ObjectViewport(controller: testObjectInspectorViewController)), ); expect(ObjectViewport.viewportTitle(mockFieldObject), 'Field fooField'); expect(find.text('Field fooField'), findsOneWidget); expect(find.byType(VmFieldDisplay), findsOneWidget); }, ); }); group('test for function object:', () { late MockFuncObject mockFuncObject; late Func testFunctionCopy; setUp(() { mockFuncObject = MockFuncObject(); final funcJson = testFunction.toJson(); testFunctionCopy = Func.parse(funcJson)!; mockVmObject(mockFuncObject); when(mockFuncObject.obj).thenReturn(testFunctionCopy); }); testWidgetsWithWindowSize( 'viewport shows function display', windowSize, (WidgetTester tester) async { testObjectInspectorViewController.fakeObjectHistory .setCurrentObject(mockFuncObject); await tester.pumpWidget( wrap(ObjectViewport(controller: testObjectInspectorViewController)), ); expect( ObjectViewport.viewportTitle(mockFuncObject), 'Function fooFunction', ); expect(find.text('Function fooFunction'), findsOneWidget); expect(find.byType(VmFuncDisplay), findsOneWidget); }, ); }); group('test for script object:', () { late MockScriptObject mockScriptObject; setUp(() { mockScriptObject = MockScriptObject(); mockVmObject(mockScriptObject); }); testWidgetsWithWindowSize( 'viewport shows script display', windowSize, (WidgetTester tester) async { testObjectInspectorViewController.fakeObjectHistory .setCurrentObject(mockScriptObject); await tester.pumpWidget( wrap(ObjectViewport(controller: testObjectInspectorViewController)), ); expect( ObjectViewport.viewportTitle(mockScriptObject), 'Script fooScript.dart', ); expect(find.text('Script fooScript.dart'), findsOneWidget); expect(find.byType(VmScriptDisplay), findsOneWidget); }, ); }); group('test for library object:', () { late MockLibraryObject mockLibraryObject; setUp(() { mockLibraryObject = MockLibraryObject(); mockVmObject(mockLibraryObject); }); testWidgets('viewport shows library display', (WidgetTester tester) async { testObjectInspectorViewController.fakeObjectHistory .setCurrentObject(mockLibraryObject); await tester.pumpWidget( wrap(ObjectViewport(controller: testObjectInspectorViewController)), ); expect(ObjectViewport.viewportTitle(mockLibraryObject), 'Library fooLib'); expect(find.text('Library fooLib'), findsOneWidget); expect(find.byType(VmLibraryDisplay), findsOneWidget); }); }); group('test for instance object:', () { testWidgets( 'builds display for Instance Object', (WidgetTester tester) async { final testInstanceObject = TestInstanceObject(ref: testInstance, testInstance: testInstance); testObjectInspectorViewController.fakeObjectHistory .setCurrentObject(testInstanceObject); await tester.pumpWidget( wrap(ObjectViewport(controller: testObjectInspectorViewController)), ); expect( ObjectViewport.viewportTitle(testInstanceObject), 'Instance of fooSuperClass', ); expect(find.text('Instance of fooSuperClass'), findsOneWidget); expect(find.byType(VmInstanceDisplay), findsOneWidget); }, ); }); group('test ObjectHistory', () { late ObjectHistory history; late MockClassObject obj1; late MockClassObject obj2; late MockClassObject obj3; setUp(() { history = ObjectHistory(); obj1 = MockClassObject(); obj2 = MockClassObject(); obj3 = MockClassObject(); when(obj1.obj).thenReturn(Class(id: '1')); when(obj2.obj).thenReturn(Class(id: '2')); when(obj3.obj).thenReturn(Class(id: '3')); }); test('initial values', () { expect(history.hasNext, false); expect(history.hasPrevious, false); expect(history.current.value, isNull); }); test('push entries', () { history.pushEntry(obj1); expect(history.hasNext, false); expect(history.hasPrevious, false); expect(history.current.value, obj1); history.pushEntry(obj2); expect(history.hasNext, false); expect(history.hasPrevious, true); expect(history.current.value, obj2); }); test('push same as current', () { history.pushEntry(obj1); history.pushEntry(obj1); expect(history.hasNext, false); expect(history.hasPrevious, false); expect(history.current.value, obj1); history.pushEntry(obj2); history.pushEntry(obj2); expect(history.hasNext, false); expect(history.hasPrevious, true); expect(history.current.value, obj2); history.moveBack(); expect(history.hasNext, isTrue); expect(history.hasPrevious, false); expect(history.current.value, obj1); }); test('pushEntry removes next entries', () { history.pushEntry(obj1); history.pushEntry(obj2); expect(history.current.value, obj2); expect(history.hasNext, isFalse); history.moveBack(); expect(history.current.value, obj1); expect(history.hasNext, isTrue); history.pushEntry(obj3); expect(history.current.value, obj3); expect(history.hasNext, isFalse); history.moveBack(); expect(history.current.value, obj1); expect(history.hasNext, isTrue); }); }); }
devtools/packages/devtools_app/test/vm_developer/object_inspector/object_viewport_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/vm_developer/object_inspector/object_viewport_test.dart", "repo_id": "devtools", "token_count": 3564 }
122
{ "name": "devtools_app", "short_name": "devtools_app", "start_url": ".", "display": "minimal-ui", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "Web-based performance tooling for Dart and Flutter.", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" } ] }
devtools/packages/devtools_app/web/manifest.json/0
{ "file_path": "devtools/packages/devtools_app/web/manifest.json", "repo_id": "devtools", "token_count": 315 }
123
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:dtd/dtd.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; final _log = Logger('dtd_manager'); /// Manages a connection to the Dart Tooling Daemon. class DTDManager { ValueListenable<DTDConnection?> get connection => _connection; final ValueNotifier<DTDConnection?> _connection = ValueNotifier<DTDConnection?>(null); /// Whether the [DTDManager] is connected to a running instance of the DTD. bool get hasConnection => connection.value != null; /// The URI of the current DTD connection. Uri? get uri => _uri; Uri? _uri; /// Sets the Dart Tooling Daemon connection to point to [uri]. /// /// Before connecting to [uri], if a current connection exists, then /// [disconnect] is called to close it. Future<void> connect( Uri uri, { void Function(Object, StackTrace?)? onError, }) async { await disconnect(); try { _connection.value = await DartToolingDaemon.connect(uri); _uri = uri; _log.info('Successfully connected to DTD at: $uri'); } catch (e, st) { onError?.call(e, st); } } /// Closes and unsets the Dart Tooling Daemon connection, if one is set. Future<void> disconnect() async { if (_connection.value != null) { await _connection.value!.close(); } _connection.value = null; _uri = null; } }
devtools/packages/devtools_app_shared/lib/src/service/dtd_manager.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/service/dtd_manager.dart", "repo_id": "devtools", "token_count": 513 }
124
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. import 'package:flutter/widgets.dart'; import 'theme.dart'; export '_ide_theme_desktop.dart' if (dart.library.js_interop) '_ide_theme_web.dart'; /// IDE-supplied theming. final class IdeTheme { IdeTheme({ this.backgroundColor, this.foregroundColor, this.fontSize = unscaledDefaultFontSize, this.embed = false, this.isDarkMode = true, }); final Color? backgroundColor; final Color? foregroundColor; final double fontSize; final bool embed; final bool isDarkMode; double get fontSizeFactor => fontSize / unscaledDefaultFontSize; }
devtools/packages/devtools_app_shared/lib/src/ui/theme/ide_theme.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/ui/theme/ide_theme.dart", "repo_id": "devtools", "token_count": 240 }
125
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; // NOTE: these helpers are duplicated from `package:devtools_test`. We copied // them instead of importing `devtools_test`, because `devtools_test` is not // published on pub.dev, and package `devtools_app_shared` will be. /// Wraps [widget] with the build context it needs to load in a test. /// /// This includes a [MaterialApp] to provide context like [Theme.of], a /// [Material] to support elements like [TextField] that draw ink effects, and a /// [Directionality] to support [RenderFlex] widgets like [Row] and [Column]. Widget wrap(Widget widget) { return MaterialApp( theme: themeFor( isDarkTheme: false, ideTheme: IdeTheme(), theme: ThemeData( useMaterial3: true, colorScheme: lightColorScheme, ), ), home: Directionality( textDirection: TextDirection.ltr, child: widget, ), ); } /// Runs a test with the size of the app window under test to [windowSize]. void testWidgetsWithWindowSize( String name, Size windowSize, WidgetTesterCallback test, { bool skip = false, }) { testWidgets( name, (WidgetTester tester) async { await _setWindowSize(tester, windowSize); await test(tester); await _resetWindowSize(tester); }, skip: skip, ); } Future<void> _setWindowSize(WidgetTester tester, Size windowSize) async { final binding = TestWidgetsFlutterBinding.ensureInitialized(); await binding.setSurfaceSize(windowSize); tester.view.physicalSize = windowSize; tester.view.devicePixelRatio = 1.0; } Future<void> _resetWindowSize(WidgetTester tester) async { await _setWindowSize(tester, const Size(800.0, 600.0)); }
devtools/packages/devtools_app_shared/test/test_utils.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/test/test_utils.dart", "repo_id": "devtools", "token_count": 676 }
126
include: ../analysis_options.yaml analyzer: exclude: - example/**
devtools/packages/devtools_extensions/analysis_options.yaml/0
{ "file_path": "devtools/packages/devtools_extensions/analysis_options.yaml", "repo_id": "devtools", "token_count": 27 }
127
# package:foo This is an example package that has a DevTools extension shipped with it. See the `extension/devtools` directory. There you will find the two requirements for the parent package that is providing a DevTools extension: 1. A `config.yaml` file that contains metadata DevTools needs to load the extension. 2. The `build` directory, which contains the pre-compiled build output of the extension Flutter web app (see `foo/packages/foo_devtools_extension`).
devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo/README.md/0
{ "file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo/README.md", "repo_id": "devtools", "token_count": 119 }
128
// Copyright 2014 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. if (!_flutter) { var _flutter = {}; } _flutter.loader = null; (function () { "use strict"; const baseUri = ensureTrailingSlash(getBaseURI()); function getBaseURI() { const base = document.querySelector("base"); return (base && base.getAttribute("href")) || ""; } function ensureTrailingSlash(uri) { if (uri == "") { return uri; } return uri.endsWith("/") ? uri : `${uri}/`; } /** * Wraps `promise` in a timeout of the given `duration` in ms. * * Resolves/rejects with whatever the original `promises` does, or rejects * if `promise` takes longer to complete than `duration`. In that case, * `debugName` is used to compose a legible error message. * * If `duration` is < 0, the original `promise` is returned unchanged. * @param {Promise} promise * @param {number} duration * @param {string} debugName * @returns {Promise} a wrapped promise. */ async function timeout(promise, duration, debugName) { if (duration < 0) { return promise; } let timeoutId; const _clock = new Promise((_, reject) => { timeoutId = setTimeout(() => { reject( new Error( `${debugName} took more than ${duration}ms to resolve. Moving on.`, { cause: timeout, } ) ); }, duration); }); return Promise.race([promise, _clock]).finally(() => { clearTimeout(timeoutId); }); } /** * Handles the creation of a TrustedTypes `policy` that validates URLs based * on an (optional) incoming array of RegExes. */ class FlutterTrustedTypesPolicy { /** * Constructs the policy. * @param {[RegExp]} validPatterns the patterns to test URLs * @param {String} policyName the policy name (optional) */ constructor(validPatterns, policyName = "flutter-js") { const patterns = validPatterns || [ /\.js$/, ]; if (window.trustedTypes) { this.policy = trustedTypes.createPolicy(policyName, { createScriptURL: function(url) { const parsed = new URL(url, window.location); const file = parsed.pathname.split("/").pop(); const matches = patterns.some((pattern) => pattern.test(file)); if (matches) { return parsed.toString(); } console.error( "URL rejected by TrustedTypes policy", policyName, ":", url, "(download prevented)"); } }); } } } /** * Handles loading/reloading Flutter's service worker, if configured. * * @see: https://developers.google.com/web/fundamentals/primers/service-workers */ class FlutterServiceWorkerLoader { /** * Injects a TrustedTypesPolicy (or undefined if the feature is not supported). * @param {TrustedTypesPolicy | undefined} policy */ setTrustedTypesPolicy(policy) { this._ttPolicy = policy; } /** * Returns a Promise that resolves when the latest Flutter service worker, * configured by `settings` has been loaded and activated. * * Otherwise, the promise is rejected with an error message. * @param {*} settings Service worker settings * @returns {Promise} that resolves when the latest serviceWorker is ready. */ loadServiceWorker(settings) { if (settings == null) { // In the future, settings = null -> uninstall service worker? console.debug("Null serviceWorker configuration. Skipping."); return Promise.resolve(); } if (!("serviceWorker" in navigator)) { let errorMessage = "Service Worker API unavailable."; if (!window.isSecureContext) { errorMessage += "\nThe current context is NOT secure." errorMessage += "\nRead more: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"; } return Promise.reject( new Error(errorMessage) ); } const { serviceWorkerVersion, serviceWorkerUrl = `${baseUri}flutter_service_worker.js?v=${serviceWorkerVersion}`, timeoutMillis = 4000, } = settings; // Apply the TrustedTypes policy, if present. let url = serviceWorkerUrl; if (this._ttPolicy != null) { url = this._ttPolicy.createScriptURL(url); } const serviceWorkerActivation = navigator.serviceWorker .register(url) .then((serviceWorkerRegistration) => this._getNewServiceWorker(serviceWorkerRegistration, serviceWorkerVersion)) .then(this._waitForServiceWorkerActivation); // Timeout race promise return timeout( serviceWorkerActivation, timeoutMillis, "prepareServiceWorker" ); } /** * Returns the latest service worker for the given `serviceWorkerRegistration`. * * This might return the current service worker, if there's no new service worker * awaiting to be installed/updated. * * @param {ServiceWorkerRegistration} serviceWorkerRegistration * @param {String} serviceWorkerVersion * @returns {Promise<ServiceWorker>} */ async _getNewServiceWorker(serviceWorkerRegistration, serviceWorkerVersion) { if (!serviceWorkerRegistration.active && (serviceWorkerRegistration.installing || serviceWorkerRegistration.waiting)) { // No active web worker and we have installed or are installing // one for the first time. Simply wait for it to activate. console.debug("Installing/Activating first service worker."); return serviceWorkerRegistration.installing || serviceWorkerRegistration.waiting; } else if (!serviceWorkerRegistration.active.scriptURL.endsWith(serviceWorkerVersion)) { // When the app updates the serviceWorkerVersion changes, so we // need to ask the service worker to update. const newRegistration = await serviceWorkerRegistration.update(); console.debug("Updating service worker."); return newRegistration.installing || newRegistration.waiting || newRegistration.active; } else { console.debug("Loading from existing service worker."); return serviceWorkerRegistration.active; } } /** * Returns a Promise that resolves when the `serviceWorker` changes its * state to "activated". * * @param {ServiceWorker} serviceWorker * @returns {Promise<void>} */ async _waitForServiceWorkerActivation(serviceWorker) { if (!serviceWorker || serviceWorker.state == "activated") { if (!serviceWorker) { throw new Error("Cannot activate a null service worker!"); } else { console.debug("Service worker already active."); return; } } return new Promise((resolve, _) => { serviceWorker.addEventListener("statechange", () => { if (serviceWorker.state == "activated") { console.debug("Activated new service worker."); resolve(); } }); }); } } /** * Handles injecting the main Flutter web entrypoint (main.dart.js), and notifying * the user when Flutter is ready, through `didCreateEngineInitializer`. * * @see https://docs.flutter.dev/development/platform-integration/web/initialization */ class FlutterEntrypointLoader { /** * Creates a FlutterEntrypointLoader. */ constructor() { // Watchdog to prevent injecting the main entrypoint multiple times. this._scriptLoaded = false; } /** * Injects a TrustedTypesPolicy (or undefined if the feature is not supported). * @param {TrustedTypesPolicy | undefined} policy */ setTrustedTypesPolicy(policy) { this._ttPolicy = policy; } /** * Loads flutter main entrypoint, specified by `entrypointUrl`, and calls a * user-specified `onEntrypointLoaded` callback with an EngineInitializer * object when it's done. * * @param {*} options * @returns {Promise | undefined} that will eventually resolve with an * EngineInitializer, or will be rejected with the error caused by the loader. * Returns undefined when an `onEntrypointLoaded` callback is supplied in `options`. */ async loadEntrypoint(options) { const { entrypointUrl = `${baseUri}main.dart.js`, onEntrypointLoaded, nonce } = options || {}; return this._loadEntrypoint(entrypointUrl, onEntrypointLoaded, nonce); } /** * Resolves the promise created by loadEntrypoint, and calls the `onEntrypointLoaded` * function supplied by the user (if needed). * * Called by Flutter through `_flutter.loader.didCreateEngineInitializer` method, * which is bound to the correct instance of the FlutterEntrypointLoader by * the FlutterLoader object. * * @param {Function} engineInitializer @see https://github.com/flutter/engine/blob/main/lib/web_ui/lib/src/engine/js_interop/js_loader.dart#L42 */ didCreateEngineInitializer(engineInitializer) { if (typeof this._didCreateEngineInitializerResolve === "function") { this._didCreateEngineInitializerResolve(engineInitializer); // Remove the resolver after the first time, so Flutter Web can hot restart. this._didCreateEngineInitializerResolve = null; // Make the engine revert to "auto" initialization on hot restart. delete _flutter.loader.didCreateEngineInitializer; } if (typeof this._onEntrypointLoaded === "function") { this._onEntrypointLoaded(engineInitializer); } } /** * Injects a script tag into the DOM, and configures this loader to be able to * handle the "entrypoint loaded" notifications received from Flutter web. * * @param {string} entrypointUrl the URL of the script that will initialize * Flutter. * @param {Function} onEntrypointLoaded a callback that will be called when * Flutter web notifies this object that the entrypoint is * loaded. * @returns {Promise | undefined} a Promise that resolves when the entrypoint * is loaded, or undefined if `onEntrypointLoaded` * is a function. */ _loadEntrypoint(entrypointUrl, onEntrypointLoaded, nonce) { const useCallback = typeof onEntrypointLoaded === "function"; if (!this._scriptLoaded) { this._scriptLoaded = true; const scriptTag = this._createScriptTag(entrypointUrl, nonce); if (useCallback) { // Just inject the script tag, and return nothing; Flutter will call // `didCreateEngineInitializer` when it's done. console.debug("Injecting <script> tag. Using callback."); this._onEntrypointLoaded = onEntrypointLoaded; document.body.append(scriptTag); } else { // Inject the script tag and return a promise that will get resolved // with the EngineInitializer object from Flutter when it calls // `didCreateEngineInitializer` later. return new Promise((resolve, reject) => { console.debug( "Injecting <script> tag. Using Promises. Use the callback approach instead!" ); this._didCreateEngineInitializerResolve = resolve; scriptTag.addEventListener("error", reject); document.body.append(scriptTag); }); } } } /** * Creates a script tag for the given URL. * @param {string} url * @returns {HTMLScriptElement} */ _createScriptTag(url, nonce) { const scriptTag = document.createElement("script"); scriptTag.type = "application/javascript"; if (nonce) { scriptTag.nonce = nonce; } // Apply TrustedTypes validation, if available. let trustedUrl = url; if (this._ttPolicy != null) { trustedUrl = this._ttPolicy.createScriptURL(url); } scriptTag.src = trustedUrl; return scriptTag; } } /** * The public interface of _flutter.loader. Exposes two methods: * * loadEntrypoint (which coordinates the default Flutter web loading procedure) * * didCreateEngineInitializer (which is called by Flutter to notify that its * Engine is ready to be initialized) */ class FlutterLoader { /** * Initializes the Flutter web app. * @param {*} options * @returns {Promise?} a (Deprecated) Promise that will eventually resolve * with an EngineInitializer, or will be rejected with * any error caused by the loader. Or Null, if the user * supplies an `onEntrypointLoaded` Function as an option. */ async loadEntrypoint(options) { const { serviceWorker, ...entrypoint } = options || {}; // A Trusted Types policy that is going to be used by the loader. const flutterTT = new FlutterTrustedTypesPolicy(); // The FlutterServiceWorkerLoader instance could be injected as a dependency // (and dynamically imported from a module if not present). const serviceWorkerLoader = new FlutterServiceWorkerLoader(); serviceWorkerLoader.setTrustedTypesPolicy(flutterTT.policy); await serviceWorkerLoader.loadServiceWorker(serviceWorker).catch(e => { // Regardless of what happens with the injection of the SW, the show must go on console.warn("Exception while loading service worker:", e); }); // The FlutterEntrypointLoader instance could be injected as a dependency // (and dynamically imported from a module if not present). const entrypointLoader = new FlutterEntrypointLoader(); entrypointLoader.setTrustedTypesPolicy(flutterTT.policy); // Install the `didCreateEngineInitializer` listener where Flutter web expects it to be. this.didCreateEngineInitializer = entrypointLoader.didCreateEngineInitializer.bind(entrypointLoader); return entrypointLoader.loadEntrypoint(entrypoint); } } _flutter.loader = new FlutterLoader(); })();
devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo/extension/devtools/build/flutter.js/0
{ "file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo/extension/devtools/build/flutter.js", "repo_id": "devtools", "token_count": 5368 }
129
{ // 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": "foo_devtools_extension + simulated environment", "request": "launch", "type": "dart", "args": [ "--dart-define=use_simulated_environment=true" ], }, { "name": "foo_devtools_extension + simulated environment (profile mode)", "request": "launch", "type": "dart", "flutterMode": "profile", "args": [ "--dart-define=use_simulated_environment=true" ], }, { "name": "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/foo/packages/foo_devtools_extension/.vscode/launch.json/0
{ "file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo_devtools_extension/.vscode/launch.json", "repo_id": "devtools", "token_count": 562 }
130
The `config.yaml` file for a DevTools extension must follow the format below. ## Required fields - `name` : the package name that this DevTools extension belongs to. The value of this field will be used in the extension page title bar. This name should contain only lowercase letters and underscores (no spaces or special characters like `'` or `.`). - `issueTracker`: the url for the extension's issue tracker. When a user clicks the “Report an issue” link in the DevTools UI, they will be directed to this url. - `version`: the version of the DevTools extension. This version number should evolve over time as the extension is developed. The value of this field will be used in the extension page title bar. - `materialIconCodePoint`: corresponds to the codepoint value of an icon from [material/icons.dart](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/icons.dart). This icon will be used for the extension’s tab in the top-level DevTools tab bar. ## Example ```yaml name: foo_package issueTracker: <link_to_your_issue_tracker.com> version: 0.0.1 materialIconCodePoint: '0xe0b1' ```
devtools/packages/devtools_extensions/extension_config_spec.md/0
{ "file_path": "devtools/packages/devtools_extensions/extension_config_spec.md", "repo_id": "devtools", "token_count": 319 }
131
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'package:devtools_app_shared/web_utils.dart'; import 'package:web/web.dart'; import '../api.dart'; DevToolsExtensionEvent? tryParseExtensionEvent(Event e) { if (e.isMessageEvent) { final messageData = (e as MessageEvent).data.dartify()!; return DevToolsExtensionEvent.tryParse(messageData); } return null; }
devtools/packages/devtools_extensions/lib/src/utils.dart/0
{ "file_path": "devtools/packages/devtools_extensions/lib/src/utils.dart", "repo_id": "devtools", "token_count": 176 }
132
// 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. export 'src/devtools_api.dart'; export 'src/memory/adb_memory_info.dart'; export 'src/memory/class_heap_detail_stats.dart'; export 'src/memory/event_sample.dart'; export 'src/memory/heap_sample.dart'; export 'src/memory/heap_space.dart'; export 'src/memory/memory_json.dart'; export 'src/service_utils.dart'; export 'src/sse/sse_shim.dart'; export 'src/utils/compare.dart'; export 'src/utils/file_utils.dart'; export 'src/utils/semantic_version.dart';
devtools/packages/devtools_shared/lib/devtools_shared.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/devtools_shared.dart", "repo_id": "devtools", "token_count": 220 }
133
// 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. /// HeapSpace of Dart VM collected heap data. class HeapSpace { HeapSpace._fromJson(this.json) : avgCollectionPeriodMillis = json['avgCollectionPeriodMillis'], capacity = json['capacity'], collections = json['collections'], external = json['external'], name = json['name'], time = json['time'], used = json['used']; static HeapSpace? parse(Map<String, dynamic>? json) => json == null ? null : HeapSpace._fromJson(json); final Map<String, dynamic> json; final double? avgCollectionPeriodMillis; final int? capacity; final int? collections; final int? external; final String? name; final double? time; final int? used; Map<String, dynamic> toJson() { final json = <String, dynamic>{}; json['type'] = 'HeapSpace'; json.addAll({ 'avgCollectionPeriodMillis': avgCollectionPeriodMillis, 'capacity': capacity, 'collections': collections, 'external': external, 'name': name, 'time': time, 'used': used, }); return json; } @override String toString() => '[HeapSpace]'; }
devtools/packages/devtools_shared/lib/src/memory/heap_space.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/memory/heap_space.dart", "repo_id": "devtools", "token_count": 470 }
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. // ignore_for_file: avoid_print import 'dart:convert'; import 'dart:io'; import 'package:args/args.dart'; import 'package:meta/meta.dart'; import 'chrome_driver.dart'; import 'io_utils.dart'; const _testSuffix = '_test.dart'; class IntegrationTestRunner with IOMixin { static const _beginExceptionMarker = 'EXCEPTION CAUGHT'; static const _endExceptionMarker = '═════════════════════════'; static const _errorMarker = ': Error: '; static const _unhandledExceptionMarker = 'Unhandled exception:'; static const _allTestsPassed = 'All tests passed!'; static const _maxRetriesOnTimeout = 1; Future<void> run( String testTarget, { required String testDriver, bool headless = false, List<String> dartDefineArgs = const <String>[], bool debugLogging = false, }) async { void debugLog(String log) { if (debugLogging) print(log); } Future<void> runTest({required int attemptNumber}) async { debugLog('starting the flutter drive process'); final process = await Process.start( 'flutter', [ 'drive', // Debug outputs from the test will not show up in profile mode. Since // we rely on debug outputs for detecting errors and exceptions from the // test, we cannot run this these tests in profile mode until this issue // is resolved. See https://github.com/flutter/flutter/issues/69070. // '--profile', '--driver=$testDriver', '--target=$testTarget', '-d', headless ? 'web-server' : 'chrome', for (final arg in dartDefineArgs) '--dart-define=$arg', ], ); bool stdOutWriteInProgress = false; bool stdErrWriteInProgress = false; final exceptionBuffer = StringBuffer(); var testsPassed = false; listenToProcessOutput( process, printTag: 'FlutterDriveProcess', onStdout: (line) { if (line.endsWith(_allTestsPassed)) { testsPassed = true; } if (line.startsWith(_IntegrationTestResult.testResultPrefix)) { final testResultJson = line.substring(line.indexOf('{')); final testResultMap = jsonDecode(testResultJson) as Map<String, Object?>; final result = _IntegrationTestResult.parse(testResultMap); if (!result.result) { exceptionBuffer ..writeln('$result') ..writeln(); } } if (line.contains(_beginExceptionMarker)) { stdOutWriteInProgress = true; } if (stdOutWriteInProgress) { exceptionBuffer.writeln(line); // Marks the end of the exception caught by flutter. if (line.contains(_endExceptionMarker) && !line.contains(_beginExceptionMarker)) { stdOutWriteInProgress = false; exceptionBuffer.writeln(); } } }, onStderr: (line) { if (line.contains(_errorMarker) || line.contains(_unhandledExceptionMarker)) { stdErrWriteInProgress = true; } if (stdErrWriteInProgress) { exceptionBuffer.writeln(line); } }, ); bool testTimedOut = false; final timeout = Future.delayed(const Duration(minutes: 8)).then((_) { testTimedOut = true; }); await Future.any([ process.exitCode, timeout, ]); debugLog('attempting to kill the flutter drive process'); process.kill(); debugLog('flutter drive process has exited'); // Ignore exception handling and retries if the tests passed. This is to // avoid bugs with the test runner where the test can fail after the test // has passed. See https://github.com/flutter/flutter/issues/129041. if (!testsPassed) { if (testTimedOut) { if (attemptNumber >= _maxRetriesOnTimeout) { throw Exception( 'Integration test timed out on try #$attemptNumber: $testTarget', ); } else { debugLog( 'Integration test timed out on try #$attemptNumber. Retrying ' '$testTarget now.', ); await runTest(attemptNumber: ++attemptNumber); } } if (exceptionBuffer.isNotEmpty) { throw Exception(exceptionBuffer.toString()); } } } await runTest(attemptNumber: 0); } } class _IntegrationTestResult { _IntegrationTestResult._(this.result, this.methodName, this.details); factory _IntegrationTestResult.parse(Map<String, Object?> json) { final result = json[resultKey] == 'true'; final failureDetails = (json[failureDetailsKey] as List<Object?>).cast<String>().firstOrNull ?? '{}'; final failureDetailsMap = jsonDecode(failureDetails) as Map<String, Object?>; final methodName = failureDetailsMap[methodNameKey] as String?; final details = failureDetailsMap[detailsKey] as String?; return _IntegrationTestResult._(result, methodName, details); } static const testResultPrefix = 'result {"result":'; static const resultKey = 'result'; static const failureDetailsKey = 'failureDetails'; static const methodNameKey = 'methodName'; static const detailsKey = 'details'; final bool result; final String? methodName; final String? details; @override String toString() { if (result) { return 'Test passed'; } return 'Test \'$methodName\' failed: $details.'; } } class IntegrationTestRunnerArgs { IntegrationTestRunnerArgs( List<String> args, { bool verifyValidTarget = true, void Function(ArgParser)? addExtraArgs, }) { final argParser = buildArgParser(addExtraArgs: addExtraArgs); argResults = argParser.parse(args); rawArgs = args; if (verifyValidTarget) { final target = argResults[testTargetArg]; assert( target != null, 'Please specify a test target (e.g. ' '--$testTargetArg=path/to/test.dart', ); } } @protected late final ArgResults argResults; late final List<String> rawArgs; /// The path to the test target. String? get testTarget => argResults[testTargetArg]; /// Whether this integration test should be run on the 'web-server' device /// instead of 'chrome'. bool get headless => argResults[_headlessArg]; /// Sharding information for this test run. ({int shardNumber, int totalShards})? get shard { final shardValue = argResults[_shardArg]; if (shardValue is String) { final shardParts = shardValue.split('/'); if (shardParts.length == 2) { final shardNumber = int.tryParse(shardParts[0]); final totalShards = int.tryParse(shardParts[1]); if (shardNumber is int && totalShards is int) { return (shardNumber: shardNumber, totalShards: totalShards); } } } return null; } /// Whether the help flag `-h` was passed to the integration test command. bool get help => argResults[_helpArg]; void printHelp() { print('Run integration tests (one or many) for the Dart DevTools package.'); print(buildArgParser().usage); } static const _helpArg = 'help'; static const testTargetArg = 'target'; static const _headlessArg = 'headless'; static const _shardArg = 'shard'; /// Builds an arg parser for DevTools integration tests. static ArgParser buildArgParser({ void Function(ArgParser)? addExtraArgs, }) { final argParser = ArgParser() ..addFlag( _helpArg, abbr: 'h', help: 'Prints help output.', ) ..addOption( testTargetArg, abbr: 't', help: 'The integration test target (e.g. path/to/test.dart). If left empty,' ' all integration tests will be run.', ) ..addFlag( _headlessArg, negatable: false, help: 'Runs the integration test on the \'web-server\' device instead of ' 'the \'chrome\' device. For headless test runs, you will not be ' 'able to see the integration test run visually in a Chrome browser.', ) ..addOption( _shardArg, valueHelp: '1/3', help: 'The shard number for this run out of the total number of shards ' '(e.g. 1/3)', ); addExtraArgs?.call(argParser); return argParser; } } Future<void> runOneOrManyTests<T extends IntegrationTestRunnerArgs>({ required String testDirectoryPath, required T testRunnerArgs, required Future<void> Function(T) runTest, required T Function(List<String>) newArgsGenerator, bool Function(FileSystemEntity)? testIsSupported, bool debugLogging = false, }) async { if (testRunnerArgs.help) { testRunnerArgs.printHelp(); return; } final chromedriver = ChromeDriver(); try { // Start chrome driver before running the flutter integration test. await chromedriver.start(debugLogging: debugLogging); if (testRunnerArgs.testTarget != null) { // TODO(kenz): add support for specifying a directory as the target instead // of a single file. await runTest(testRunnerArgs); } else { // Run all supported tests since a specific target test was not provided. final testDirectory = Directory(testDirectoryPath); var testFiles = testDirectory .listSync(recursive: true) .where( (testFile) => testFile.path.endsWith(_testSuffix) && (testIsSupported?.call(testFile) ?? true), ) .toList(); final shard = testRunnerArgs.shard; if (shard != null) { final shardSize = testFiles.length ~/ shard.totalShards; // Subtract 1 since the [shard.shardNumber] index is 1-based. final shardStart = (shard.shardNumber - 1) * shardSize; final shardEnd = shard.shardNumber == shard.totalShards ? null : shardStart + shardSize; testFiles = testFiles.sublist(shardStart, shardEnd); } for (final testFile in testFiles) { final testTarget = testFile.path; final newArgsWithTarget = newArgsGenerator([ ...testRunnerArgs.rawArgs, '--${IntegrationTestRunnerArgs.testTargetArg}=$testTarget', ]); await runTest(newArgsWithTarget); } } } finally { await chromedriver.stop(debugLogging: debugLogging); } }
devtools/packages/devtools_shared/lib/src/test/integration_test_runner.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/test/integration_test_runner.dart", "repo_id": "devtools", "token_count": 4317 }
135
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:devtools_shared/devtools_server.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:devtools_shared/devtools_test_utils.dart'; import 'package:devtools_shared/src/extensions/extension_manager.dart'; import 'package:devtools_shared/src/server/server_api.dart' as server; import 'package:dtd/dtd.dart'; import 'package:shelf/shelf.dart'; import 'package:test/test.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../fakes.dart'; import '../helpers.dart'; void main() { group('General DevTools server API', () { group(apiNotifyForVmServiceConnection, () { Future<Response> sendNotifyRequest({ required DTDConnectionInfo dtd, Map<String, Object?>? queryParameters, }) async { final request = Request( 'get', Uri( scheme: 'https', host: 'localhost', path: apiNotifyForVmServiceConnection, queryParameters: queryParameters, ), ); return server.ServerApi.handle( request, extensionsManager: ExtensionsManager(buildDir: '/'), deeplinkManager: FakeDeeplinkManager(), dtd: dtd, analytics: const NoOpAnalytics(), ); } test( 'succeeds when DTD is not available', () async { final response = await sendNotifyRequest( dtd: (uri: null, secret: null), queryParameters: { apiParameterValueKey: 'fake_uri', apiParameterVmServiceConnected: 'true', }, ); expect(response.statusCode, HttpStatus.ok); expect(await response.readAsString(), isEmpty); }, ); test( 'returns badRequest for invalid VM service argument', () async { final response = await sendNotifyRequest( dtd: (uri: 'ws://dtd:uri', secret: 'fake_secret'), queryParameters: { apiParameterValueKey: 'fake_uri', apiParameterVmServiceConnected: 'true', }, ); expect(response.statusCode, HttpStatus.badRequest); expect( await response.readAsString(), contains('Cannot normalize VM service URI'), ); }, ); test( 'returns badRequest for invalid $apiParameterVmServiceConnected argument', () async { final response = await sendNotifyRequest( dtd: (uri: 'ws://dtd:uri', secret: 'fake_secret'), queryParameters: { apiParameterValueKey: 'ws://127.0.0.1:8181/LEpVqqD7E_Y=/ws', apiParameterVmServiceConnected: 'bad_arg', }, ); expect(response.statusCode, HttpStatus.badRequest); expect( await response.readAsString(), contains('Cannot parse $apiParameterVmServiceConnected parameter'), ); }, ); }); group('updateDtdWorkspaceRoots', () { TestDtdConnectionInfo? dtd; DTDConnection? testDtdConnection; setUp(() async { dtd = await startDtd(); expect(dtd!.uri, isNotNull, reason: 'Error starting DTD for test'); testDtdConnection = await DartToolingDaemon.connect(Uri.parse(dtd!.uri!)); }); tearDown(() async { await testDtdConnection?.close(); dtd?.dtdProcess?.kill(); await dtd?.dtdProcess?.exitCode; dtd = null; }); Future<void> updateWorkspaceRoots({ required Uri root, required bool connected, }) async { await server.Handler.updateDtdWorkspaceRoots( (uri: dtd!.uri, secret: dtd!.secret), rootFromVmService: root, connected: connected, api: ServerApi(), ); } Future<void> verifyWorkspaceRoots(Set<Uri> roots) async { final currentRoots = (await testDtdConnection!.getIDEWorkspaceRoots()).ideWorkspaceRoots; expect(currentRoots, hasLength(roots.length)); expect(currentRoots, containsAll(roots)); } test( 'adds and removes workspace roots', () async { await verifyWorkspaceRoots({}); final rootUri1 = Uri.parse('file:///Users/me/package_root_1'); final rootUri2 = Uri.parse('file:///Users/me/package_root_2'); await updateWorkspaceRoots(root: rootUri1, connected: true); await verifyWorkspaceRoots({rootUri1}); // Add a second root and verify the roots are unioned. await updateWorkspaceRoots(root: rootUri2, connected: true); await verifyWorkspaceRoots({rootUri1, rootUri2}); // Verify duplicates cannot be added. await updateWorkspaceRoots(root: rootUri2, connected: true); await verifyWorkspaceRoots({rootUri1, rootUri2}); // Verify roots are removed for disconnect events. await updateWorkspaceRoots(root: rootUri2, connected: false); await verifyWorkspaceRoots({rootUri1}); await updateWorkspaceRoots(root: rootUri1, connected: false); await verifyWorkspaceRoots({}); }, timeout: const Timeout.factor(4), ); }); group('detectRootPackageForVmService', () { TestDartApp? app; String? vmServiceUriString; setUp(() async { app = TestDartApp(); vmServiceUriString = await app!.start(); // Await a short delay to give the VM a chance to initialize. await delay(duration: const Duration(seconds: 1)); expect(vmServiceUriString, isNotEmpty); }); tearDown(() async { await app?.kill(); app = null; vmServiceUriString = null; }); test('succeeds for a connect event', () async { final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); expect(vmServiceUri, isNotNull); final response = await server.Handler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, vmServiceUri: vmServiceUri!, connected: true, api: ServerApi(), ); expect(response.success, true); expect(response.message, isNull); expect(response.uri, isNotNull); expect(response.uri!.toString(), endsWith(app!.directory.path)); }); test('succeeds for a disconnect event when cache is empty', () async { final response = await server.Handler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, vmServiceUri: Uri.parse('ws://127.0.0.1:63555/fake-uri=/ws'), connected: false, api: ServerApi(), ); expect(response, (success: true, message: null, uri: null)); }); test( 'succeeds for a disconnect event when cache contains entry for VM service', () async { final vmServiceUri = normalizeVmServiceUri(vmServiceUriString!); expect(vmServiceUri, isNotNull); final response = await server.Handler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, vmServiceUri: vmServiceUri!, connected: true, api: ServerApi(), ); expect(response.success, true); expect(response.message, isNull); expect(response.uri, isNotNull); expect(response.uri!.toString(), endsWith(app!.directory.path)); final disconnectResponse = await server.Handler.detectRootPackageForVmService( vmServiceUriAsString: vmServiceUriString!, vmServiceUri: vmServiceUri, connected: false, api: ServerApi(), ); expect(disconnectResponse.success, true); expect(disconnectResponse.message, isNull); expect(disconnectResponse.uri, isNotNull); expect( disconnectResponse.uri!.toString(), endsWith(app!.directory.path), ); }, ); }); }); }
devtools/packages/devtools_shared/test/server/general_api_test.dart/0
{ "file_path": "devtools/packages/devtools_shared/test/server/general_api_test.dart", "repo_id": "devtools", "token_count": 3669 }
136
// 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 'package:devtools_app/devtools_app.dart'; import '_cpu_profiler_data.dart'; import '_performance_data.dart'; import '_performance_data_large.dart'; // To create Dart test data files from JSON, use the `tool/json_to_map.dart` // script. const cpuProfilerFileName = 'cpu_profile_data.json'; const performanceFileName = 'performance_data.json'; const performanceLargeFileName = 'performance_large_data.json'; final sampleData = <DevToolsJsonFile>[ DevToolsJsonFile( name: performanceFileName, lastModifiedTime: DateTime.now(), data: jsonDecode(jsonEncode(samplePerformanceData)), ), DevToolsJsonFile( name: performanceLargeFileName, lastModifiedTime: DateTime.now(), data: jsonDecode(jsonEncode(samplePerformanceDataLarge)), ), DevToolsJsonFile( name: cpuProfilerFileName, lastModifiedTime: DateTime.now(), data: jsonDecode(jsonEncode(sampleCpuProfilerData)), ), ];
devtools/packages/devtools_test/lib/src/test_data/sample_data.dart/0
{ "file_path": "devtools/packages/devtools_test/lib/src/test_data/sample_data.dart", "repo_id": "devtools", "token_count": 368 }
137
name: codicon description: VS Code icons for Flutter. homepage: https://github.com/flutter/devtools/tree/master/third_party/packages/codicon version: 1.0.0 environment: sdk: ^3.0.0 dependencies: flutter: sdk: flutter dev_dependencies: flutter_lints: ^3.0.1 flutter: fonts: - family: Codicon fonts: - asset: lib/font/codicon.ttf
devtools/third_party/packages/codicon/pubspec.yaml/0
{ "file_path": "devtools/third_party/packages/codicon/pubspec.yaml", "repo_id": "devtools", "token_count": 152 }
138
include: package:lints/recommended.yaml analyzer: exclude: - flutter-sdk/ linter: rules: # - avoid_dynamic_calls - require_trailing_commas - unawaited_futures - depend_on_referenced_packages - directives_ordering - sort_pub_dependencies
devtools/tool/analysis_options.yaml/0
{ "file_path": "devtools/tool/analysis_options.yaml", "repo_id": "devtools", "token_count": 111 }
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 'dart:convert'; import 'dart:io'; // Note: this is a helper script for development. This is helpful for generating // test data from DevTools exports. /// Generates a dart file with a [Map] variable 'data' that contains the JSON /// data contained in the given json file (first argument). /// /// To use: /// /// `dart json_to_map.dart ~/path/to/my_file.json` /// /// This will generate a file with the same name but with a '.dart' extension /// instead of '.json' (e.g. ~/path/to/my_file.dart). This will be a valid dart /// file with a single [Map] variable [data]. void main(List<String> args) { if (args.isEmpty) { throw Exception('Please pass a file location for the json file.'); } final jsonFileLocation = args.first; final jsonFilePath = Uri.parse(jsonFileLocation).path; final jsonFile = File(jsonFilePath); if (!jsonFile.existsSync()) { throw FileSystemException('File not found at $jsonFileLocation'); } final jsonFileName = jsonFilePath.split('/').last; final fileNameWithoutExtension = (jsonFileName.split('.')..removeLast()).join('.'); final jsonFileDirectoryPath = Uri.parse((jsonFilePath.split('/')..removeLast()).join('/')); final Map<String, Object?> jsonAsMap = jsonDecode(jsonFile.readAsStringSync()); var jsonFormattedString = JsonEncoder.withIndent(' ').convert(jsonAsMap); // Escape any '$' characters so that Dart does not think we are trying to do // String interpolation. jsonFormattedString = jsonFormattedString.replaceAll('\$', '\\\$'); final dartFile = File('$jsonFileDirectoryPath/$fileNameWithoutExtension.dart') ..createSync() ..writeAsStringSync( ''' // 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: prefer_single_quotes // ignore_for_file: prefer-trailing-comma // ignore_for_file: require_trailing_commas final Map<String, dynamic> data = <String, dynamic>$jsonFormattedString; ''', ); print('Created ${dartFile.path}'); }
devtools/tool/json_to_map.dart/0
{ "file_path": "devtools/tool/json_to_map.dart", "repo_id": "devtools", "token_count": 709 }
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. import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:cli_util/cli_logging.dart'; import 'package:devtools_tool/model.dart'; import 'package:io/io.dart'; import '../utils.dart'; const _updateOnPath = 'update-on-path'; const _useCacheFlag = 'use-cache'; /// This command updates the the Flutter SDK contained in the 'tool/' directory /// to the latest Flutter candidate branch. /// /// When the '--from-path' flag is passed, the Flutter SDK that is on PATH (your /// local flutter/flutter git checkout) will be updated as well. /// /// This command will use the Flutter version from the 'flutter-candidate.txt' /// file in the repository root, unless the '--no-use-cache' flag is passed, /// in which case it will run the 'tool/latest_flutter_candidate.sh' script to /// fetch the latest version from upstream. /// /// The version from 'flutter-candidate.txt' should be identical most of the /// time since the GitHub workflow that updates this file runs twice per day. /// /// To run this script: /// `devtools_tool update-flutter-sdk [--from-path] [--no-use-cache]` class UpdateFlutterSdkCommand extends Command { UpdateFlutterSdkCommand() { argParser ..addFlag( _updateOnPath, negatable: false, help: 'Also update the Flutter SDK that is on PATH (your local ' 'flutter/flutter git checkout)', ) ..addFlag( _useCacheFlag, negatable: true, defaultsTo: true, help: 'Update the Flutter SDK(s) to the cached Flutter version stored ' 'in "flutter-candidate.txt" instead of the latest version at ' '"https://flutter.googlesource.com/mirrors/flutter/"', ); } @override String get name => 'update-flutter-sdk'; @override String get description => 'Updates the the Flutter SDK contained in the \'tool/\' directory to the ' 'latest Flutter candidate branch. Optionally, can also update the Flutter' 'SDK that is on PATH (your local flutter/flutter git checkout).'; @override Future run() async { final updateOnPath = argResults![_updateOnPath] as bool; final useCachedVersion = argResults![_useCacheFlag] as bool; final log = Logger.standard(); // TODO(kenz): we can remove this if we can rewrite the // 'latest_flutter_candidate.sh' script as a Dart script, or if we instead // duplicate it as a Windows script (we may need this to be a non-Dart // script for execution on the bots before we have a Dart SDK available). if (Platform.isWindows && !useCachedVersion) { log.stderr( 'On windows, you can only use the cached Flutter version from ' '"flutter-candidate.txt". Please remove the "--no-use-cache" flag and ' 'try again.', ); return 1; } final repo = DevToolsRepo.getInstance(); final processManager = ProcessManager(); late String flutterTag; if (useCachedVersion) { flutterTag = 'tags/${repo.readFile(Uri.parse('flutter-candidate.txt')).trim()}'; } else { flutterTag = (await processManager.runProcess( CliCommand('sh', ['latest_flutter_candidate.sh']), workingDirectory: repo.toolDirectoryPath, )) .stdout .replaceFirst('refs/', '') .trim(); } log.stdout( 'Updating to Flutter version ' '${useCachedVersion ? 'from cache' : 'from upstream'}: $flutterTag ', ); final flutterSdkDirName = repo.sdkDirectoryName; final toolSdkPath = repo.toolFlutterSdkPath; // If the flag was set, update the SDK on PATH in addition to the // tool/flutter-sdk copy. if (updateOnPath) { final pathSdk = FlutterSdk.findFromPathEnvironmentVariable(); log.stdout('Updating Flutter from PATH at ${pathSdk.sdkPath}'); // Verify we have an upstream remote to pull from. await findRemote( processManager, remoteId: 'flutter/flutter.git', workingDirectory: pathSdk.sdkPath, ); await processManager.runAll( commands: [ CliCommand.git(['stash']), CliCommand.git(['fetch', 'upstream']), CliCommand.git(['checkout', 'upstream/master']), CliCommand.git(['reset', '--hard', 'upstream/master']), CliCommand.git(['checkout', flutterTag, '-f']), CliCommand.flutter(['--version']), ], workingDirectory: pathSdk.sdkPath, ); log.stdout('Finished updating Flutter from PATH at ${pathSdk.sdkPath}'); } // Next, update (or clone) the tool/flutter-sdk copy. if (Directory(toolSdkPath).existsSync()) { log.stdout('Updating Flutter at $toolSdkPath'); await processManager.runAll( commands: [ CliCommand.git(['fetch']), CliCommand.git(['checkout', flutterTag, '-f']), CliCommand.flutter(['--version']), ], workingDirectory: toolSdkPath, ); } else { log.stdout('Cloning Flutter into $toolSdkPath'); await processManager.runProcess( CliCommand.git( ['clone', 'https://github.com/flutter/flutter', flutterSdkDirName], ), workingDirectory: repo.toolDirectoryPath, ); await processManager.runAll( commands: [ CliCommand.git(['checkout', flutterTag, '-f']), CliCommand.flutter(['--version']), ], workingDirectory: toolSdkPath, ); } log.stdout('Finished updating Flutter at $toolSdkPath.'); } }
devtools/tool/lib/commands/update_flutter_sdk.dart/0
{ "file_path": "devtools/tool/lib/commands/update_flutter_sdk.dart", "repo_id": "devtools", "token_count": 2211 }
141
[style] based_on_style = yapf # Defined in https://github.com/google/yapf/blob/20d0c8f1774cf3843f4032f3e9ab02338bf98c75/yapf/yapflib/style.py#L326 # Docs and full list of knobs: # https://github.com/google/yapf#knobs split_before_first_argument = true blank_line_before_module_docstring = true # dedent_closing_brackets is required by coalesce_brackets dedent_closing_brackets = true coalesce_brackets = true each_dict_entry_on_separate_line = false # Match the number in .pylintrc at # https://github.com/flutter/engine/blob/main/.pylintrc#L135 column_limit = 100
engine/.style.yapf/0
{ "file_path": "engine/.style.yapf", "repo_id": "engine", "token_count": 221 }
142
# 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. config("benchmark_config") { include_dirs = [ "//flutter/third_party/benchmark:benchmark_config" ] } source_set("benchmarking") { testonly = true sources = [ "benchmarking.cc", "benchmarking.h", ] public_deps = [ "//flutter/fml", "//flutter/third_party/benchmark", ] public_configs = [ "//flutter:config", ":benchmark_config", ] } config("benchmark_library_config") { if (is_ios) { ldflags = [ "-Wl,-exported_symbol,_RunBenchmarks" ] } } source_set("benchmarking_library") { testonly = true sources = [ "library.cc", "library.h", ] public_deps = [ "//flutter/third_party/benchmark" ] public_configs = [ "//flutter:config", ":benchmark_config", ":benchmark_library_config", ] }
engine/benchmarking/BUILD.gn/0
{ "file_path": "engine/benchmarking/BUILD.gn", "repo_id": "engine", "token_count": 364 }
143
# 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") template("esbuild") { assert(defined(invoker.entry_point)) assert(defined(invoker.output_bundle)) action(target_name) { forward_variables_from(invoker, [ "public_deps" ]) if (host_os == "win") { executable_subpath = "esbuild.exe" } else { executable_subpath = "bin/esbuild" } esbuild = "$host_prebuilts_path/esbuild/$executable_subpath" script = "//build/gn_run_binary.py" inputs = [ esbuild, invoker.entry_point, ] output_filename = get_path_info(invoker.entry_point, "file") output_path = "${invoker.output_bundle}/$output_filename" outputs = [ output_path ] absolute_output = rebase_path(invoker.output_bundle) args = [ rebase_path(esbuild, root_build_dir) ] if (defined(invoker.bundle) && invoker.bundle) { args += [ "--bundle" ] } if (defined(invoker.minify) && invoker.minify) { args += [ "--minify" ] } if (defined(invoker.sourcemap) && invoker.sourcemap) { args += [ "--sourcemap" ] outputs += [ output_path + ".map" ] } args += [ "--outdir=$absolute_output", rebase_path(invoker.entry_point), ] } }
engine/build/esbuild/esbuild.gni/0
{ "file_path": "engine/build/esbuild/esbuild.gni", "repo_id": "engine", "token_count": 553 }
144
# 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. ocmock_path = "//flutter/third_party/ocmock/Source" # OCMock headers use `#import <OCMock/Foo.h>`. config("ocmock_config") { include_dirs = [ "$ocmock_path" ] } # Target that compiles all sources to .o files but does not produce a static # library for use in macOS desktop tests. source_set("ocmock_src") { configs -= [ "//build/config/compiler:chromium_code", "//build/config/gcc:symbol_visibility_hidden", "//build/config:symbol_visibility_hidden", ] all_dependent_configs = [ ":ocmock_config" ] cflags = [ "-fvisibility=default", "-Wno-misleading-indentation", ] if (is_ios) { cflags += [ "-mios-simulator-version-min=$ios_testing_deployment_target" ] } sources = [ "$ocmock_path/OCMock/NSInvocation+OCMAdditions.h", "$ocmock_path/OCMock/NSInvocation+OCMAdditions.m", "$ocmock_path/OCMock/NSMethodSignature+OCMAdditions.h", "$ocmock_path/OCMock/NSMethodSignature+OCMAdditions.m", "$ocmock_path/OCMock/NSNotificationCenter+OCMAdditions.h", "$ocmock_path/OCMock/NSNotificationCenter+OCMAdditions.m", "$ocmock_path/OCMock/NSObject+OCMAdditions.h", "$ocmock_path/OCMock/NSObject+OCMAdditions.m", "$ocmock_path/OCMock/NSValue+OCMAdditions.h", "$ocmock_path/OCMock/NSValue+OCMAdditions.m", "$ocmock_path/OCMock/OCClassMockObject.h", "$ocmock_path/OCMock/OCClassMockObject.m", "$ocmock_path/OCMock/OCMArg.h", "$ocmock_path/OCMock/OCMArg.m", "$ocmock_path/OCMock/OCMArgAction.h", "$ocmock_path/OCMock/OCMArgAction.m", "$ocmock_path/OCMock/OCMBlockArgCaller.h", "$ocmock_path/OCMock/OCMBlockArgCaller.m", "$ocmock_path/OCMock/OCMBlockCaller.h", "$ocmock_path/OCMock/OCMBlockCaller.m", "$ocmock_path/OCMock/OCMBoxedReturnValueProvider.h", "$ocmock_path/OCMock/OCMBoxedReturnValueProvider.m", "$ocmock_path/OCMock/OCMConstraint.h", "$ocmock_path/OCMock/OCMConstraint.m", "$ocmock_path/OCMock/OCMExceptionReturnValueProvider.h", "$ocmock_path/OCMock/OCMExceptionReturnValueProvider.m", "$ocmock_path/OCMock/OCMExpectationRecorder.h", "$ocmock_path/OCMock/OCMExpectationRecorder.m", "$ocmock_path/OCMock/OCMFunctions.h", "$ocmock_path/OCMock/OCMFunctions.m", "$ocmock_path/OCMock/OCMFunctionsPrivate.h", "$ocmock_path/OCMock/OCMIndirectReturnValueProvider.h", "$ocmock_path/OCMock/OCMIndirectReturnValueProvider.m", "$ocmock_path/OCMock/OCMInvocationExpectation.h", "$ocmock_path/OCMock/OCMInvocationExpectation.m", "$ocmock_path/OCMock/OCMInvocationMatcher.h", "$ocmock_path/OCMock/OCMInvocationMatcher.m", "$ocmock_path/OCMock/OCMInvocationStub.h", "$ocmock_path/OCMock/OCMInvocationStub.m", "$ocmock_path/OCMock/OCMLocation.h", "$ocmock_path/OCMock/OCMLocation.m", "$ocmock_path/OCMock/OCMMacroState.h", "$ocmock_path/OCMock/OCMMacroState.m", "$ocmock_path/OCMock/OCMNonRetainingObjectReturnValueProvider.h", "$ocmock_path/OCMock/OCMNonRetainingObjectReturnValueProvider.m", "$ocmock_path/OCMock/OCMNotificationPoster.h", "$ocmock_path/OCMock/OCMNotificationPoster.m", "$ocmock_path/OCMock/OCMObjectReturnValueProvider.h", "$ocmock_path/OCMock/OCMObjectReturnValueProvider.m", "$ocmock_path/OCMock/OCMObserverRecorder.h", "$ocmock_path/OCMock/OCMObserverRecorder.m", "$ocmock_path/OCMock/OCMPassByRefSetter.h", "$ocmock_path/OCMock/OCMPassByRefSetter.m", "$ocmock_path/OCMock/OCMQuantifier.h", "$ocmock_path/OCMock/OCMQuantifier.m", "$ocmock_path/OCMock/OCMRealObjectForwarder.h", "$ocmock_path/OCMock/OCMRealObjectForwarder.m", "$ocmock_path/OCMock/OCMRecorder.h", "$ocmock_path/OCMock/OCMRecorder.m", "$ocmock_path/OCMock/OCMStubRecorder.h", "$ocmock_path/OCMock/OCMStubRecorder.m", "$ocmock_path/OCMock/OCMVerifier.h", "$ocmock_path/OCMock/OCMVerifier.m", "$ocmock_path/OCMock/OCMock.h", "$ocmock_path/OCMock/OCMockObject.h", "$ocmock_path/OCMock/OCMockObject.m", "$ocmock_path/OCMock/OCObserverMockObject.h", "$ocmock_path/OCMock/OCObserverMockObject.m", "$ocmock_path/OCMock/OCPartialMockObject.h", "$ocmock_path/OCMock/OCPartialMockObject.m", "$ocmock_path/OCMock/OCProtocolMockObject.h", "$ocmock_path/OCMock/OCProtocolMockObject.m", ] frameworks = [ "Foundation.framework" ] } shared_library("ocmock_shared") { deps = [ ":ocmock_src" ] cflags = [ "-fvisibility=default" ] ldflags = [ "-Wl,-install_name,@rpath/Frameworks/libocmock_shared.dylib" ] } # Generates a static library, used in iOS unit test targets static_library("ocmock") { # Force the static lib to include code from dependencies complete_static_lib = true if (is_ios) { cflags = [ "-mios-simulator-version-min=$ios_testing_deployment_target" ] } public_deps = [ ":ocmock_src" ] }
engine/build/secondary/flutter/third_party/ocmock/BUILD.gn/0
{ "file_path": "engine/build/secondary/flutter/third_party/ocmock/BUILD.gn", "repo_id": "engine", "token_count": 2237 }
145
# 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. shaderc_base = "//flutter/third_party/shaderc" config("shaderc_util_config") { include_dirs = [ "$shaderc_base/libshaderc_util/include/" ] } source_set("shaderc_util_flutter") { public_configs = [ ":shaderc_util_config" ] configs += [ "//flutter/third_party/vulkan-deps/spirv-tools/src:spvtools_public_config" ] public_deps = [ "//flutter/third_party/vulkan-deps/glslang/src:glslang_sources", "//flutter/third_party/vulkan-deps/spirv-tools/src:spvtools", ] defines = [ "ENABLE_HLSL=1" ] if (is_clang) { cflags_cc = [ "-Wno-deprecated-copy", "-Wno-unknown-warning-option", ] } sources = [ "$shaderc_base/libshaderc_util/include/libshaderc_util/counting_includer.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/exceptions.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/file_finder.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/format.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/io_shaderc.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/message.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/mutex.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/resources.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/spirv_tools_wrapper.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/string_piece.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/universal_unistd.h", "$shaderc_base/libshaderc_util/include/libshaderc_util/version_profile.h", "$shaderc_base/libshaderc_util/src/compiler.cc", "$shaderc_base/libshaderc_util/src/file_finder.cc", "$shaderc_base/libshaderc_util/src/io_shaderc.cc", "$shaderc_base/libshaderc_util/src/message.cc", "$shaderc_base/libshaderc_util/src/resources.cc", "$shaderc_base/libshaderc_util/src/shader_stage.cc", "$shaderc_base/libshaderc_util/src/spirv_tools_wrapper.cc", "$shaderc_base/libshaderc_util/src/version_profile.cc", ] } config("shaderc_config") { include_dirs = [ "$shaderc_base/libshaderc/include/" ] } source_set("shaderc_flutter") { defines = [ "SHADERC_IMPLEMENTATION" ] public_configs = [ ":shaderc_config" ] configs += [ "//flutter/third_party/vulkan-deps/spirv-tools/src:spvtools_public_config" ] deps = [ ":shaderc_util_flutter" ] public_deps = [ "//flutter/third_party/vulkan-deps/glslang/src:glslang_sources", "//flutter/third_party/vulkan-deps/spirv-tools/src:spvtools", ] sources = [ "$shaderc_base/libshaderc/include/shaderc/env.h", "$shaderc_base/libshaderc/include/shaderc/shaderc.h", "$shaderc_base/libshaderc/include/shaderc/shaderc.hpp", "$shaderc_base/libshaderc/include/shaderc/status.h", "$shaderc_base/libshaderc/include/shaderc/visibility.h", "$shaderc_base/libshaderc/src/shaderc.cc", "$shaderc_base/libshaderc/src/shaderc_private.h", ] }
engine/build/secondary/third_party/shaderc_flutter/BUILD.gn/0
{ "file_path": "engine/build/secondary/third_party/shaderc_flutter/BUILD.gn", "repo_id": "engine", "token_count": 1358 }
146
This directory includes scripts and tools for continuous integration tests.
engine/ci/README.md/0
{ "file_path": "engine/ci/README.md", "repo_id": "engine", "token_count": 12 }
147
{ "builds": [ { "archives": [ { "name": "host_debug", "base_path": "out/host_debug/zip_archives/", "type": "gcs", "include_paths": [ "out/host_debug/zip_archives/linux-x64/artifacts.zip", "out/host_debug/zip_archives/linux-x64/linux-x64-embedder.zip", "out/host_debug/zip_archives/linux-x64/font-subset.zip", "out/host_debug/zip_archives/flutter_patched_sdk.zip", "out/host_debug/zip_archives/dart-sdk-linux-x64.zip" ], "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Linux" ], "gclient_variables": { "download_android_deps": false, "use_rbe": true }, "gn": [ "--runtime-mode", "debug", "--prebuilt-dart-sdk", "--build-embedder-examples", "--rbe", "--no-goma" ], "name": "host_debug", "ninja": { "config": "host_debug", "targets": [ "flutter:unittests", "flutter/build/archives:artifacts", "flutter/build/archives:dart_sdk_archive", "flutter/build/archives:embedder", "flutter/build/archives:flutter_patched_sdk", "flutter/build/dart:copy_dart_sdk", "flutter/tools/font_subset" ] }, "tests": [ { "language": "python3", "name": "Host Tests for host_debug", "script": "flutter/testing/run_tests.py", "parameters": [ "--variant", "host_debug", "--type", "dart,dart-host", "--engine-capture-core-dump" ] } ] }, { "archives": [ { "name": "host_profile", "base_path": "out/host_profile/zip_archives/", "type": "gcs", "include_paths": [] } ], "drone_dimensions": [ "device_type=none", "os=Linux" ], "gclient_variables": { "download_android_deps": false, "use_rbe": true }, "gn": [ "--runtime-mode", "profile", "--no-lto", "--prebuilt-dart-sdk", "--build-embedder-examples", "--rbe", "--no-goma" ], "name": "host_profile", "ninja": { "config": "host_profile", "targets": [ "flutter/build/dart:copy_dart_sdk", "flutter/shell/testing", "flutter/tools/path_ops", "flutter:unittests" ] }, "tests": [ { "language": "python3", "name": "Host Tests for host_profile", "script": "flutter/testing/run_tests.py", "parameters": [ "--variant", "host_profile", "--type", "dart,dart-host,engine", "--engine-capture-core-dump" ] } ] }, { "archives": [ { "name": "host_release", "base_path": "out/host_release/zip_archives/", "type": "gcs", "include_paths": [ "out/host_release/zip_archives/flutter_patched_sdk_product.zip" ], "realm": "production" } ], "drone_dimensions": [ "device_type=none", "os=Linux" ], "dependencies": [ { "dependency": "goldctl", "version": "git_revision:720a542f6fe4f92922c3b8f0fdcc4d2ac6bb83cd" } ], "gclient_variables": { "download_android_deps": false, "use_rbe": true }, "gn": [ "--runtime-mode", "release", "--prebuilt-dart-sdk", "--build-embedder-examples", "--rbe", "--no-goma" ], "name": "host_release", "ninja": { "config": "host_release", "targets": [ "flutter/build/dart:copy_dart_sdk", "flutter/display_list:display_list_benchmarks", "flutter/display_list:display_list_builder_benchmarks", "flutter/display_list:display_list_region_benchmarks", "flutter/display_list:display_list_transform_benchmarks", "flutter/fml:fml_benchmarks", "flutter/impeller/geometry:geometry_benchmarks", "flutter/impeller/aiks:canvas_benchmarks", "flutter/lib/ui:ui_benchmarks", "flutter/shell/common:shell_benchmarks", "flutter/shell/testing", "flutter/third_party/txt:txt_benchmarks", "flutter/tools/path_ops", "flutter/build/archives:flutter_patched_sdk", "flutter:unittests" ] }, "tests": [ { "language": "python3", "name": "Host Tests for host_release", "script": "flutter/testing/run_tests.py", "parameters": [ "--variant", "host_release", "--type", "dart,dart-host,engine,benchmarks", "--engine-capture-core-dump" ] }, { "language": "bash", "name": "Generate metrics test", "script": "flutter/testing/benchmark/generate_metrics.sh" }, { "language": "bash", "name": "Upload metrics dry-run", "script": "flutter/testing/benchmark/upload_metrics.sh", "parameters": [ "--no-upload" ] } ] } ], "generators": { "tasks": [ { "name": "Verify-export-symbols-release-binaries", "parameters": [ "src/out" ], "script": "flutter/testing/symbols/verify_exported.dart", "language": "dart" }, { "name": "api-documentation", "parameters": [ "out/docs" ], "script": "flutter/tools/gen_docs.py" } ] }, "archives": [ { "source": "out/docs/ios-docs.zip", "destination": "ios-docs.zip", "realm": "production" }, { "source": "out/docs/macos-docs.zip", "destination": "macos-docs.zip", "realm": "production" }, { "source": "out/docs/linux-docs.zip", "destination": "linux-docs.zip", "realm": "production" }, { "source": "out/docs/windows-docs.zip", "destination": "windows-docs.zip", "realm": "production" }, { "source": "out/docs/impeller-docs.zip", "destination": "impeller-docs.zip", "realm": "production" } ] }
engine/ci/builders/linux_host_engine.json/0
{ "file_path": "engine/ci/builders/linux_host_engine.json", "repo_id": "engine", "token_count": 5575 }
148
#!/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. set -e # Needed because if it is set, cd may print the path it changed to. unset CDPATH # On Mac OS, readlink -f doesn't work, so follow_links traverses the path one # link at a time, and then cds into the link destination and find out where it # ends up. # # The function is enclosed in a subshell to avoid changing the working directory # of the caller. function follow_links() ( cd -P "$(dirname -- "$1")" file="$PWD/$(basename -- "$1")" while [[ -h "$file" ]]; do cd -P "$(dirname -- "$file")" file="$(readlink -- "$file")" cd -P "$(dirname -- "$file")" file="$PWD/$(basename -- "$file")" done echo "$file" ) function dart_bin() { dart_path="$1/flutter/third_party/dart/tools/sdks/dart-sdk/bin" if [[ ! -e "$dart_path" ]]; then dart_path="$1/third_party/dart/tools/sdks/dart-sdk/bin" fi echo "$dart_path" } SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")") SRC_DIR="$(cd "$SCRIPT_DIR/../.."; pwd -P)" FLUTTER_DIR="$(cd "$SCRIPT_DIR/.."; pwd -P)" DART_BIN=$(dart_bin "$SRC_DIR") DART="${DART_BIN}/dart" cd "$SCRIPT_DIR" "$DART" \ --disable-dart-dev \ "$SRC_DIR/flutter/tools/pkg/engine_build_configs/bin/check.dart" \ "$SRC_DIR"
engine/ci/check_build_configs.sh/0
{ "file_path": "engine/ci/check_build_configs.sh", "repo_id": "engine", "token_count": 549 }
149
// 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_COMMON_GRAPHICS_GL_CONTEXT_SWITCH_H_ #define FLUTTER_COMMON_GRAPHICS_GL_CONTEXT_SWITCH_H_ #include <functional> #include <memory> #include <vector> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" namespace flutter { // This interface represents a gl context that can be switched by // |GLContextSwitch|. // // The implementation should wrap a "Context" object inside this class. For // example, in iOS while using a GL rendering surface, the implementation should // wrap an |EAGLContext|. class SwitchableGLContext { public: SwitchableGLContext(); virtual ~SwitchableGLContext(); // Implement this to set the context wrapped by this |SwitchableGLContext| // object to the current context. virtual bool SetCurrent() = 0; // Implement this to remove the context wrapped by this |SwitchableGLContext| // object from current context; virtual bool RemoveCurrent() = 0; FML_DISALLOW_COPY_AND_ASSIGN(SwitchableGLContext); }; // Represents the result of setting a gl context. // // This class exists because context results are used in places applies to all // the platforms. On certain platforms(for example lower end iOS devices that // uses gl), a |GLContextSwitch| is required to protect flutter's gl contect // from being polluted by other programs(embedded platform views). A // |GLContextSwitch| is a subclass of |GLContextResult|, which can be returned // on platforms that requires context switching. A |GLContextDefaultResult| is // also a subclass of |GLContextResult|, which can be returned on platforms // that doesn't require context switching. class GLContextResult { public: GLContextResult(); virtual ~GLContextResult(); //---------------------------------------------------------------------------- // Returns true if the gl context is set successfully. bool GetResult(); protected: explicit GLContextResult(bool static_result); bool result_; FML_DISALLOW_COPY_AND_ASSIGN(GLContextResult); }; //------------------------------------------------------------------------------ /// The default implementation of |GLContextResult|. /// /// Use this class on platforms that doesn't require gl context switching. /// * See also |GLContextSwitch| if the platform requires gl context switching. class GLContextDefaultResult : public GLContextResult { public: //---------------------------------------------------------------------------- /// Constructs a |GLContextDefaultResult| with a static result. /// /// Used this on platforms that doesn't require gl context switching. (For /// example, metal on iOS) /// /// @param static_result a static value that will be returned from /// |GetResult| explicit GLContextDefaultResult(bool static_result); ~GLContextDefaultResult() override; FML_DISALLOW_COPY_AND_ASSIGN(GLContextDefaultResult); }; //------------------------------------------------------------------------------ /// Switches the gl context to the a context that is passed in the /// constructor. /// /// In destruction, it should restore the current context to what was /// before the construction of this switch. class GLContextSwitch final : public GLContextResult { public: //---------------------------------------------------------------------------- /// Constructs a |GLContextSwitch|. /// /// @param context The context that is going to be set as the current /// context. The |GLContextSwitch| should not outlive the owner of the gl /// context wrapped inside the `context`. explicit GLContextSwitch(std::unique_ptr<SwitchableGLContext> context); ~GLContextSwitch() override; private: std::unique_ptr<SwitchableGLContext> context_; FML_DISALLOW_COPY_AND_ASSIGN(GLContextSwitch); }; } // namespace flutter #endif // FLUTTER_COMMON_GRAPHICS_GL_CONTEXT_SWITCH_H_
engine/common/graphics/gl_context_switch.h/0
{ "file_path": "engine/common/graphics/gl_context_switch.h", "repo_id": "engine", "token_count": 1006 }
150
// 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/benchmarking/dl_complexity_gl.h" // The numbers and weightings used in this file stem from taking the // data from the DisplayListBenchmarks suite run on an Pixel 4 and // applying very rough analysis on them to identify the approximate // trends. // // See the comments in display_list_complexity_helper.h for details on the // process and rationale behind coming up with these numbers. namespace flutter { DisplayListGLComplexityCalculator* DisplayListGLComplexityCalculator::instance_ = nullptr; DisplayListGLComplexityCalculator* DisplayListGLComplexityCalculator::GetInstance() { if (instance_ == nullptr) { instance_ = new DisplayListGLComplexityCalculator(); } return instance_; } unsigned int DisplayListGLComplexityCalculator::GLHelper::BatchedComplexity() { // Calculate the impact of saveLayer. unsigned int save_layer_complexity; if (save_layer_count_ == 0) { save_layer_complexity = 0; } else { // m = 1/5 // c = 10 save_layer_complexity = (save_layer_count_ + 50) * 40000; } unsigned int draw_text_blob_complexity; if (draw_text_blob_count_ == 0) { draw_text_blob_complexity = 0; } else { // m = 1/240 // c = 0.25 draw_text_blob_complexity = (draw_text_blob_count_ + 60) * 2500 / 3; } return save_layer_complexity + draw_text_blob_complexity; } void DisplayListGLComplexityCalculator::GLHelper::saveLayer( const SkRect& bounds, const SaveLayerOptions options, const DlImageFilter* backdrop) { if (IsComplex()) { return; } if (backdrop) { // Flutter does not offer this operation so this value can only ever be // non-null for a frame-wide builder which is not currently evaluated for // complexity. AccumulateComplexity(Ceiling()); } save_layer_count_++; } void DisplayListGLComplexityCalculator::GLHelper::drawLine(const SkPoint& p0, const SkPoint& p1) { if (IsComplex()) { return; } // There is a relatively high fixed overhead cost for drawLine on OpenGL. // Further, there is a strange bump where the cost of drawing a line of // length ~500px is actually more costly than drawing a line of length // ~1000px. The calculations here will be for a linear graph that // approximate the overall trend. float non_hairline_penalty = 1.0f; unsigned int aa_penalty = 1; // The non-hairline penalty is insignificant when AA is on. if (!IsHairline() && !IsAntiAliased()) { non_hairline_penalty = 1.15f; } if (IsAntiAliased()) { aa_penalty = 2; } // Use an approximation for the distance to avoid floating point or // sqrt() calls. SkScalar distance = abs(p0.x() - p1.x()) + abs(p0.y() - p1.y()); // The baseline complexity is for a hairline stroke with no AA. // m = 1/40 // c = 13 unsigned int complexity = ((distance + 520) / 2) * non_hairline_penalty * aa_penalty; AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawRect(const SkRect& rect) { if (IsComplex()) { return; } unsigned int complexity; // If stroked, cost scales linearly with the rectangle width/height. // If filled, it scales with the area. // // Hairline stroke vs non hairline has no significant penalty. // // There is also a kStrokeAndFill_Style that Skia exposes, but we do not // currently use it anywhere in Flutter. if (DrawStyle() == DlDrawStyle::kFill) { // No real difference for AA with filled styles unsigned int area = rect.width() * rect.height(); // m = 1/3500 // c = 0 complexity = area * 2 / 175; } else { // Take the average of the width and height. unsigned int length = (rect.width() + rect.height()) / 2; if (IsAntiAliased()) { // m = 1/30 // c = 0 complexity = length * 4 / 3; } else { // If AA is disabled, the data shows that at larger sizes the overall // cost comes down, peaking at around 1000px. As we don't anticipate // rasterising rects with AA disabled to be all that frequent, just treat // it as a straight line that peaks at 1000px, beyond which it stays // constant. The rationale here is that it makes more sense to // overestimate than to start decreasing the cost as the length goes up. // // This should be a reasonable approximation as it doesn't decrease by // much from 1000px to 2000px. // // m = 1/20 // c = 0 complexity = std::min(length, 1000u) * 2; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawOval( const SkRect& bounds) { if (IsComplex()) { return; } // DrawOval scales very roughly linearly with the bounding box width/height // (not area) for stroked styles without AA. // // Filled styles and stroked styles with AA scale linearly with the bounding // box area. unsigned int area = bounds.width() * bounds.height(); unsigned int complexity; // There is also a kStrokeAndFill_Style that Skia exposes, but we do not // currently use it anywhere in Flutter. if (DrawStyle() == DlDrawStyle::kFill) { // With filled styles, there is no significant AA penalty. // m = 1/6000 // c = 0 complexity = area / 30; } else { if (IsAntiAliased()) { // m = 1/4000 // c = 0 complexity = area / 20; } else { // Take the average of the width and height. unsigned int length = (bounds.width() + bounds.height()) / 2; // m = 1/75 // c = 0 complexity = length * 8 / 3; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawCircle( const SkPoint& center, SkScalar radius) { if (IsComplex()) { return; } unsigned int complexity; // There is also a kStrokeAndFill_Style that Skia exposes, but we do not // currently use it anywhere in Flutter. if (DrawStyle() == DlDrawStyle::kFill) { // We can ignore pi here unsigned int area = radius * radius; // m = 1/525 // c = 50 complexity = (area + 26250) * 8 / 105; // Penalty of around 8% when AA is disabled. if (!IsAntiAliased()) { complexity *= 1.08f; } } else { // Hairline vs non-hairline has no significant performance difference. if (IsAntiAliased()) { // m = 1/3 // c = 10 complexity = (radius + 30) * 40 / 3; } else { // m = 1/10 // c = 20 complexity = (radius + 200) * 4; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawRRect( const SkRRect& rrect) { if (IsComplex()) { return; } // Drawing RRects is split into three performance tiers: // // 1) All stroked styles without AA *except* simple/symmetric RRects. // 2) All filled styles and symmetric stroked styles w/AA. // 3) Remaining stroked styles with AA. // // 1) and 3) scale linearly with length, 2) scales with area. unsigned int complexity; // These values were worked out by creating a straight line graph (y=mx+c) // approximately matching the measured data, normalising the data so that // 0.0005ms resulted in a score of 100 then simplifying down the formula. if (DrawStyle() == DlDrawStyle::kFill || ((rrect.getType() == SkRRect::Type::kSimple_Type) && IsAntiAliased())) { unsigned int area = rrect.width() * rrect.height(); // m = 1/3200 // c = 0.5 complexity = (area + 1600) / 80; } else { // Take the average of the width and height. unsigned int length = (rrect.width() + rrect.height()) / 2; // There is some difference between hairline and non-hairline performance // but the spread is relatively inconsistent and it's pretty much a wash. if (IsAntiAliased()) { // m = 1/25 // c = 1 complexity = (length + 25) * 8 / 5; } else { // m = 1/50 // c = 0.75 complexity = ((length * 2) + 75) * 2 / 5; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawDRRect( const SkRRect& outer, const SkRRect& inner) { if (IsComplex()) { return; } // There are roughly four classes here: // a) Filled style. // b) Complex RRect type with AA enabled and filled style. // c) Stroked style with AA enabled. // d) Stroked style with AA disabled. // // a) and b) scale linearly with the area, c) and d) scale linearly with // a single dimension (length). In all cases, the dimensions refer to // the outer RRect. unsigned int complexity; // These values were worked out by creating a straight line graph (y=mx+c) // approximately matching the measured data, normalising the data so that // 0.0005ms resulted in a score of 100 then simplifying down the formula. // // There is also a kStrokeAndFill_Style that Skia exposes, but we do not // currently use it anywhere in Flutter. if (DrawStyle() == DlDrawStyle::kFill) { unsigned int area = outer.width() * outer.height(); if (outer.getType() == SkRRect::Type::kComplex_Type) { // m = 1/500 // c = 0.5 complexity = (area + 250) / 5; } else { // m = 1/1600 // c = 2 complexity = (area + 3200) / 16; } } else { unsigned int length = (outer.width() + outer.height()) / 2; if (IsAntiAliased()) { // m = 1/15 // c = 1 complexity = (length + 15) * 20 / 3; } else { // m = 1/27 // c = 0.5 complexity = ((length * 2) + 27) * 50 / 27; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawPath(const SkPath& path) { if (IsComplex()) { return; } // There is negligible effect on the performance for hairline vs. non-hairline // stroke widths. // // The data for filled styles is currently suspicious, so for now we are going // to assign scores based on stroked styles. unsigned int line_verb_cost, quad_verb_cost, conic_verb_cost, cubic_verb_cost; unsigned int complexity; if (IsAntiAliased()) { // There seems to be a fixed cost of around 1ms for calling drawPath with // AA. complexity = 200000; line_verb_cost = 235; quad_verb_cost = 365; conic_verb_cost = 365; cubic_verb_cost = 725; } else { // There seems to be a fixed cost of around 0.25ms for calling drawPath. // without AA complexity = 50000; line_verb_cost = 135; quad_verb_cost = 150; conic_verb_cost = 200; cubic_verb_cost = 235; } complexity += CalculatePathComplexity(path, line_verb_cost, quad_verb_cost, conic_verb_cost, cubic_verb_cost); AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawArc( const SkRect& oval_bounds, SkScalar start_degrees, SkScalar sweep_degrees, bool use_center) { if (IsComplex()) { return; } // Hairline vs non-hairline makes no difference to the performance. // Stroked styles without AA scale linearly with the log of the diameter. // Stroked styles with AA scale linearly with the area. // Filled styles scale lienarly with the area. unsigned int area = oval_bounds.width() * oval_bounds.height(); unsigned int complexity; // These values were worked out by creating a straight line graph (y=mx+c) // approximately matching the measured data, normalising the data so that // 0.0005ms resulted in a score of 100 then simplifying down the formula. // // There is also a kStrokeAndFill_Style that Skia exposes, but we do not // currently use it anywhere in Flutter. if (DrawStyle() == DlDrawStyle::kStroke) { if (IsAntiAliased()) { // m = 1/3800 // c = 12 complexity = (area + 45600) / 171; } else { unsigned int diameter = (oval_bounds.width() + oval_bounds.height()) / 2; // m = 15 // c = -100 // This should never go negative though, so use std::max to ensure // c is never larger than 15*log_diameter. // // Pre-multiply by 15 here so we get a little bit more precision. unsigned int log_diameter = 15 * log(diameter); complexity = (log_diameter - std::max(log_diameter, 100u)) * 200 / 9; } } else { if (IsAntiAliased()) { // m = 1/1000 // c = 10 complexity = (area + 10000) / 45; } else { // m = 1/6500 // c = 12 complexity = (area + 52000) * 2 / 585; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawPoints( DlCanvas::PointMode mode, uint32_t count, const SkPoint points[]) { if (IsComplex()) { return; } unsigned int complexity; if (IsAntiAliased()) { if (mode == DlCanvas::PointMode::kPoints) { if (IsHairline()) { // This is a special case, it triggers an extremely fast path. // m = 1/4500 // c = 0 complexity = count * 400 / 9; } else { // m = 1/500 // c = 0 complexity = count * 400; } } else if (mode == DlCanvas::PointMode::kLines) { if (IsHairline()) { // m = 1/750 // c = 0 complexity = count * 800 / 3; } else { // m = 1/500 // c = 0 complexity = count * 400; } } else { if (IsHairline()) { // m = 1/350 // c = 0 complexity = count * 4000 / 7; } else { // m = 1/250 // c = 0 complexity = count * 800; } } } else { if (mode == DlCanvas::PointMode::kPoints) { // Hairline vs non hairline makes no difference for points without AA. // m = 1/18000 // c = 0.25 complexity = (count + 4500) * 100 / 9; } else if (mode == DlCanvas::PointMode::kLines) { if (IsHairline()) { // m = 1/8500 // c = 0.25 complexity = (count + 2125) * 400 / 17; } else { // m = 1/9000 // c = 0.25 complexity = (count + 2250) * 200 / 9; } } else { // Polygon only really diverges for hairline vs non hairline at large // point counts, and only by a few %. // m = 1/7500 // c = 0.25 complexity = (count + 1875) * 80 / 3; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawVertices( const DlVertices* vertices, DlBlendMode mode) { // There is currently no way for us to get the VertexMode from the SkVertices // object, but for future reference: // // TriangleStrip is roughly 25% more expensive than TriangleFan. // TriangleFan is roughly 5% more expensive than Triangles. // For the baseline, it's hard to identify the trend. It might be O(n^1/2) // For now, treat it as linear as an approximation. // // m = 1/1600 // c = 1 unsigned int complexity = (vertices->vertex_count() + 1600) * 250 / 2; AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawImage( const sk_sp<DlImage> image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { if (IsComplex()) { return; } // AA vs non-AA has a cost but it's dwarfed by the overall cost of the // drawImage call. // // The main difference is if the image is backed by a texture already or not // If we don't need to upload, then the cost scales linearly with the // length of the image. If it needs uploading, the cost scales linearly // with the square of the area (!!!). SkISize dimensions = image->dimensions(); unsigned int length = (dimensions.width() + dimensions.height()) / 2; unsigned int area = dimensions.width() * dimensions.height(); // m = 1/13 // c = 0 unsigned int complexity = length * 400 / 13; if (!image->isTextureBacked()) { // We can't square the area here as we'll overflow, so let's approximate // by taking the calculated complexity score and applying a multiplier to // it. // // (complexity * area / 60000) + 4000 gives a reasonable approximation with // AA (complexity * area / 19000) gives a reasonable approximation without // AA. float multiplier; if (IsAntiAliased()) { multiplier = area / 60000.0f; complexity = complexity * multiplier + 4000; } else { multiplier = area / 19000.0f; complexity = complexity * multiplier; } } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::ImageRect( const SkISize& size, bool texture_backed, bool render_with_attributes, bool enforce_src_edges) { if (IsComplex()) { return; } // Two main groups here - texture-backed and non-texture-backed images. // // Within each group, they all perform within a few % of each other *except* // when we have a strict constraint and anti-aliasing enabled. // These values were worked out by creating a straight line graph (y=mx+c) // approximately matching the measured data, normalising the data so that // 0.0005ms resulted in a score of 100 then simplifying down the formula. unsigned int complexity; if (!texture_backed || (texture_backed && render_with_attributes && enforce_src_edges && IsAntiAliased())) { unsigned int area = size.width() * size.height(); // m = 1/4000 // c = 5 complexity = (area + 20000) / 10; } else { unsigned int length = (size.width() + size.height()) / 2; // There's a little bit of spread here but the numbers are pretty large // anyway. // // m = 1/22 // c = 0 complexity = length * 200 / 11; } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawImageNine( const sk_sp<DlImage> image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) { if (IsComplex()) { return; } SkISize dimensions = image->dimensions(); unsigned int area = dimensions.width() * dimensions.height(); // m = 1/3600 // c = 3 unsigned int complexity = (area + 10800) / 9; // Uploading incurs about a 40% performance penalty. if (!image->isTextureBacked()) { complexity *= 1.4f; } AccumulateComplexity(complexity); } void DisplayListGLComplexityCalculator::GLHelper::drawDisplayList( const sk_sp<DisplayList> display_list, SkScalar opacity) { if (IsComplex()) { return; } GLHelper helper(Ceiling() - CurrentComplexityScore()); if (opacity < SK_Scalar1 && !display_list->can_apply_group_opacity()) { auto bounds = display_list->bounds(); helper.saveLayer(bounds, SaveLayerOptions::kWithAttributes, nullptr); } display_list->Dispatch(helper); AccumulateComplexity(helper.ComplexityScore()); } void DisplayListGLComplexityCalculator::GLHelper::drawTextBlob( const sk_sp<SkTextBlob> blob, SkScalar x, SkScalar y) { if (IsComplex()) { return; } // DrawTextBlob has a high fixed cost, but if we call it multiple times // per frame, that fixed cost is greatly reduced per subsequent call. This // is likely because there is batching being done in SkCanvas. // Increment draw_text_blob_count_ and calculate the cost at the end. draw_text_blob_count_++; } void DisplayListGLComplexityCalculator::GLHelper::drawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y) {} void DisplayListGLComplexityCalculator::GLHelper::drawShadow( const SkPath& path, const DlColor color, const SkScalar elevation, bool transparent_occluder, SkScalar dpr) { if (IsComplex()) { return; } // Elevation has no significant effect on the timings. Whether the shadow // is cast by a transparent occluder or not has a small impact of around 5%. // // The path verbs do have an effect but only if the verb type is cubic; line, // quad and conic all perform similarly. float occluder_penalty = 1.0f; if (transparent_occluder) { occluder_penalty = 1.20f; } // The benchmark uses a test path of around 10 path elements. This is likely // to be similar to what we see in real world usage, but we should benchmark // different path lengths to see how much impact there is from varying the // path length. // // For now, we will assume that there is no fixed overhead and that the time // spent rendering the shadow for a path is split evenly amongst all the verbs // enumerated. unsigned int line_verb_cost = 17000; // 0.085ms unsigned int quad_verb_cost = 20000; // 0.1ms unsigned int conic_verb_cost = 20000; // 0.1ms unsigned int cubic_verb_cost = 120000; // 0.6ms unsigned int complexity = CalculatePathComplexity( path, line_verb_cost, quad_verb_cost, conic_verb_cost, cubic_verb_cost); AccumulateComplexity(complexity * occluder_penalty); } } // namespace flutter
engine/display_list/benchmarking/dl_complexity_gl.cc/0
{ "file_path": "engine/display_list/benchmarking/dl_complexity_gl.cc", "repo_id": "engine", "token_count": 7597 }
151
// 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_canvas.h" #include "third_party/skia/include/core/SkPoint3.h" #include "third_party/skia/include/utils/SkShadowUtils.h" namespace flutter { SkRect DlCanvas::ComputeShadowBounds(const SkPath& path, float elevation, SkScalar dpr, const SkMatrix& ctm) { SkRect shadow_bounds(path.getBounds()); SkShadowUtils::GetLocalBounds( ctm, path, SkPoint3::Make(0, 0, dpr * elevation), SkPoint3::Make(0, -1, 1), kShadowLightRadius / kShadowLightHeight, SkShadowFlags::kDirectionalLight_ShadowFlag, &shadow_bounds); return shadow_bounds; } } // namespace flutter
engine/display_list/dl_canvas.cc/0
{ "file_path": "engine/display_list/dl_canvas.cc", "repo_id": "engine", "token_count": 387 }
152
// 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_DL_VERTICES_H_ #define FLUTTER_DISPLAY_LIST_DL_VERTICES_H_ #include <memory> #include "flutter/display_list/dl_color.h" #include "third_party/skia/include/core/SkRect.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief Defines the way in which the vertices of a DlVertices object /// are separated into triangles into which to render. /// enum class DlVertexMode { /// The vertices are taken 3 at a time to form a triangle. kTriangles, /// The vertices are taken in overlapping triplets to form triangles, with /// each triplet sharing 2 of its vertices with the preceding and following /// triplets. /// vertices [ABCDE] yield 3 triangles ABC,BCD,CDE kTriangleStrip, /// The vertices are taken in overlapping pairs and combined with the first /// vertex to form triangles that radiate outward from the initial point. /// vertices [ABCDE] yield 3 triangles ABC,ACD,ADE kTriangleFan, }; //------------------------------------------------------------------------------ /// @brief Holds all of the data (both required and optional) for a /// DisplayList drawVertices call. /// /// There are 4 main pices of data: /// - vertices(): /// the points on the rendering surface that define the pixels /// being rendered to in a series of triangles. These points /// can map to triangles in various ways depending on the /// supplied |DlVertexMode|. /// - texture_coordinates(): /// the points in the DlColorSource to map to the coordinates /// of the triangles in the vertices(). If missing, the /// vertex coordinates themselves will be used to map the /// source colors to the vertices. /// - colors(): /// colors to map to each triangle vertex. Note that each /// vertex is mapped to exactly 1 color even if the DlVertex /// - indices(): /// An indirection based on indices into the array of vertices /// (and by extension, their associated texture_coordinates and /// colors). Note that the DLVertexMode will still apply to the /// indices in the same way (and instead of the way) that it /// would normally be applied to the vertices themselves. The /// indices are useful, for example, to fill the vertices with /// a grid of points and then use the indices to define a /// triangular mesh that covers that grid without having to /// repeat the vertex (and texture coordinate and color) /// information for the times when a given grid coordinate /// gets reused in up to 4 mesh triangles. /// /// Note that each vertex is mapped to exactly 1 texture_coordinate and /// color even if the DlVertexMode or indices specify that it contributes /// to more than one output triangle. /// class DlVertices { public: /// @brief A utility class to build up a |DlVertices| object /// one set of data at a time. class Builder { public: /// @brief flags to indicate/promise which of the optional /// texture coordinates or colors will be supplied /// during the build phase. union Flags { struct { unsigned has_texture_coordinates : 1; unsigned has_colors : 1; }; uint32_t mask = 0; inline Flags operator|(const Flags& rhs) const { return {.mask = (mask | rhs.mask)}; } inline Flags& operator|=(const Flags& rhs) { mask = mask | rhs.mask; return *this; } }; static constexpr Flags kNone = {{false, false}}; static constexpr Flags kHasTextureCoordinates = {{true, false}}; static constexpr Flags kHasColors = {{false, true}}; //-------------------------------------------------------------------------- /// @brief Constructs a Builder and prepares room for the /// required and optional data. /// /// Vertices are always required. Optional texture coordinates /// and optional colors are reserved depending on the |Flags|. /// Optional indices will be reserved if the index_count is /// positive (>0). /// /// The caller must provide all data that is promised by the /// supplied |flags| and |index_count| parameters before /// calling the |build()| method. Builder(DlVertexMode mode, int vertex_count, Flags flags, int index_count); /// Returns true iff the underlying object was successfully allocated. bool is_valid() { return vertices_ != nullptr; } /// @brief Copies the indicated list of points as vertices. /// /// fails if vertices have already been supplied. void store_vertices(const SkPoint points[]); /// @brief Copies the indicated list of float pairs as vertices. /// /// fails if vertices have already been supplied. void store_vertices(const float coordinates[]); /// @brief Copies the indicated list of points as texture coordinates. /// /// fails if texture coordinates have already been supplied or if they /// were not promised by the flags.has_texture_coordinates. void store_texture_coordinates(const SkPoint points[]); /// @brief Copies the indicated list of float pairs as texture coordinates. /// /// fails if texture coordinates have already been supplied or if they /// were not promised by the flags.has_texture_coordinates. void store_texture_coordinates(const float coordinates[]); /// @brief Copies the indicated list of colors as vertex colors. /// /// fails if colors have already been supplied or if they were not /// promised by the flags.has_colors. void store_colors(const DlColor colors[]); /// @brief Copies the indicated list of unsigned ints as vertex colors /// in the 32-bit RGBA format. /// /// fails if colors have already been supplied or if they were not /// promised by the flags.has_colors. void store_colors(const uint32_t colors[]) { store_colors(reinterpret_cast<const DlColor*>(colors)); } /// @brief Copies the indicated list of 16-bit indices as vertex indices. /// /// fails if indices have already been supplied or if they were not /// promised by (index_count > 0). void store_indices(const uint16_t indices[]); /// @brief Finalizes and the constructed DlVertices object. /// /// fails if any of the optional data promised in the constructor is /// missing. std::shared_ptr<DlVertices> build(); private: std::shared_ptr<DlVertices> vertices_; bool needs_vertices_ = true; bool needs_texture_coords_; bool needs_colors_; bool needs_indices_; }; //-------------------------------------------------------------------------- /// @brief Constructs a DlVector with compact inline storage for all /// of its required and optional lists of data. /// /// Vertices are always required. Optional texture coordinates /// and optional colors are stored if the arguments are non-null. /// Optional indices will be stored iff the array argument is /// non-null and the index_count is positive (>0). static std::shared_ptr<DlVertices> Make(DlVertexMode mode, int vertex_count, const SkPoint vertices[], const SkPoint texture_coordinates[], const DlColor colors[], int index_count = 0, const uint16_t indices[] = nullptr); /// Returns the size of the object including all of the inlined data. size_t size() const; /// Returns the bounds of the vertices. SkRect bounds() const { return bounds_; } /// Returns the vertex mode that defines how the vertices (or the indices) /// are turned into triangles. DlVertexMode mode() const { return mode_; } /// Returns the number of vertices, which also applies to the number of /// texture coordinate and colors if they are provided. int vertex_count() const { return vertex_count_; } /// Returns a pointer to the vertex information. Should be non-null. const SkPoint* vertices() const { return static_cast<const SkPoint*>(pod(vertices_offset_)); } /// Returns a pointer to the vertex texture coordinate /// or null if none were provided. const SkPoint* texture_coordinates() const { return static_cast<const SkPoint*>(pod(texture_coordinates_offset_)); } /// Returns a pointer to the vertex colors /// or null if none were provided. const DlColor* colors() const { return static_cast<const DlColor*>(pod(colors_offset_)); } /// Returns a pointer to the count of vertex indices /// or 0 if none were provided. int index_count() const { return index_count_; } /// Returns a pointer to the vertex indices /// or null if none were provided. const uint16_t* indices() const { return static_cast<const uint16_t*>(pod(indices_offset_)); } bool operator==(DlVertices const& other) const; bool operator!=(DlVertices const& other) const { return !(*this == other); } private: // Constructors are designed to encapsulate arrays sequentially in memory // which means they can only be called by intantiations that use the // new (ptr) paradigm which precomputes and preallocates the memory for // the class body and all of its arrays, such as in Builder. DlVertices(DlVertexMode mode, int vertex_count, const SkPoint vertices[], const SkPoint texture_coordinates[], const DlColor colors[], int index_count, const uint16_t indices[], const SkRect* bounds = nullptr); // This constructor is specifically used by the DlVertices::Builder to // establish the object before the copying of data is requested. DlVertices(DlVertexMode mode, int vertex_count, Builder::Flags flags, int index_count); // The copy constructor has the same memory pre-allocation requirements // as this other constructors. This particular version is used by the // DisplaylistBuilder to copy the instance into pre-allocated pod memory // in the display list buffer. explicit DlVertices(const DlVertices* other); DlVertexMode mode_; int vertex_count_; size_t vertices_offset_; size_t texture_coordinates_offset_; size_t colors_offset_; int index_count_; size_t indices_offset_; SkRect bounds_; const void* pod(int offset) const { if (offset <= 0) { return nullptr; } const void* base = static_cast<const void*>(this); return static_cast<const char*>(base) + offset; } friend class DisplayListBuilder; }; } // namespace flutter #endif // FLUTTER_DISPLAY_LIST_DL_VERTICES_H_
engine/display_list/dl_vertices.h/0
{ "file_path": "engine/display_list/dl_vertices.h", "repo_id": "engine", "token_count": 3626 }
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. #include "flutter/display_list/effects/dl_path_effect.h" #include "flutter/display_list/testing/dl_test_equality.h" #include "flutter/display_list/utils/dl_comparable.h" #include "gtest/gtest.h" #include "third_party/skia/include/core/SkScalar.h" namespace flutter { namespace testing { TEST(DisplayListPathEffect, EffectShared) { const SkScalar TestDashes2[] = {1.0, 1.5}; auto effect = DlDashPathEffect::Make(TestDashes2, 2, 0.0); ASSERT_TRUE(Equals(effect->shared(), effect)); } TEST(DisplayListPathEffect, DashEffectAsDash) { const SkScalar TestDashes2[] = {1.0, 1.5}; auto effect = DlDashPathEffect::Make(TestDashes2, 2, 0.0); ASSERT_NE(effect->asDash(), nullptr); ASSERT_EQ(effect->asDash(), effect.get()); } TEST(DisplayListPathEffect, DashEffectEquals) { const SkScalar TestDashes2[] = {1.0, 1.5}; auto effect1 = DlDashPathEffect::Make(TestDashes2, 2, 0.0); auto effect2 = DlDashPathEffect::Make(TestDashes2, 2, 0.0); TestEquals(*effect1, *effect1); } TEST(DisplayListPathEffect, CheckEffectProperties) { const SkScalar test_dashes[] = {4.0, 2.0}; const SkScalar TestDashes2[] = {5.0, 2.0}; const SkScalar TestDashes3[] = {4.0, 3.0}; const SkScalar TestDashes4[] = {4.0, 2.0, 6.0}; auto effect1 = DlDashPathEffect::Make(test_dashes, 2, 0.0); auto effect2 = DlDashPathEffect::Make(TestDashes2, 2, 0.0); auto effect3 = DlDashPathEffect::Make(TestDashes3, 2, 0.0); auto effect4 = DlDashPathEffect::Make(TestDashes4, 3, 0.0); auto effect5 = DlDashPathEffect::Make(test_dashes, 2, 1.0); TestNotEquals(*effect1, *effect2, "Interval 1 differs"); TestNotEquals(*effect1, *effect3, "Interval 2 differs"); TestNotEquals(*effect1, *effect4, "Dash count differs"); TestNotEquals(*effect1, *effect5, "Dash phase differs"); } } // namespace testing } // namespace flutter
engine/display_list/effects/dl_path_effect_unittests.cc/0
{ "file_path": "engine/display_list/effects/dl_path_effect_unittests.cc", "repo_id": "engine", "token_count": 756 }
154
// 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_SKIA_DL_SK_CONVERSIONS_H_ #define FLUTTER_DISPLAY_LIST_SKIA_DL_SK_CONVERSIONS_H_ #include "flutter/display_list/dl_op_receiver.h" #include "flutter/display_list/skia/dl_sk_types.h" namespace flutter { SkPaint ToSk(const DlPaint& paint); SkPaint ToStrokedSk(const DlPaint& paint); SkPaint ToNonShaderSk(const DlPaint& paint); inline SkBlendMode ToSk(DlBlendMode mode) { return static_cast<SkBlendMode>(mode); } inline SkColor ToSk(DlColor color) { // This is safe because both SkColor and DlColor are backed by ARGB uint32_t. // See dl_sk_conversions_unittests.cc. return reinterpret_cast<SkColor&>(color); } inline SkPaint::Style ToSk(DlDrawStyle style) { return static_cast<SkPaint::Style>(style); } inline SkPaint::Cap ToSk(DlStrokeCap cap) { return static_cast<SkPaint::Cap>(cap); } inline SkPaint::Join ToSk(DlStrokeJoin join) { return static_cast<SkPaint::Join>(join); } inline SkTileMode ToSk(DlTileMode dl_mode) { return static_cast<SkTileMode>(dl_mode); } inline SkBlurStyle ToSk(const DlBlurStyle blur_style) { return static_cast<SkBlurStyle>(blur_style); } inline SkFilterMode ToSk(const DlFilterMode filter_mode) { return static_cast<SkFilterMode>(filter_mode); } inline SkVertices::VertexMode ToSk(DlVertexMode dl_mode) { return static_cast<SkVertices::VertexMode>(dl_mode); } inline SkSamplingOptions ToSk(DlImageSampling sampling) { switch (sampling) { case DlImageSampling::kCubic: return SkSamplingOptions(SkCubicResampler{1 / 3.0f, 1 / 3.0f}); case DlImageSampling::kLinear: return SkSamplingOptions(SkFilterMode::kLinear); case DlImageSampling::kMipmapLinear: return SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kLinear); case DlImageSampling::kNearestNeighbor: return SkSamplingOptions(SkFilterMode::kNearest); } } inline SkCanvas::SrcRectConstraint ToSk( DlCanvas::SrcRectConstraint constraint) { return static_cast<SkCanvas::SrcRectConstraint>(constraint); } inline SkClipOp ToSk(DlCanvas::ClipOp op) { return static_cast<SkClipOp>(op); } inline SkCanvas::PointMode ToSk(DlCanvas::PointMode mode) { return static_cast<SkCanvas::PointMode>(mode); } extern sk_sp<SkShader> ToSk(const DlColorSource* source); inline sk_sp<SkShader> ToSk( const std::shared_ptr<const DlColorSource>& source) { return ToSk(source.get()); } inline sk_sp<SkShader> ToSk(const DlColorSource& source) { return ToSk(&source); } extern sk_sp<SkImageFilter> ToSk(const DlImageFilter* filter); inline sk_sp<SkImageFilter> ToSk( const std::shared_ptr<const DlImageFilter>& filter) { return ToSk(filter.get()); } inline sk_sp<SkImageFilter> ToSk(const DlImageFilter& filter) { return ToSk(&filter); } extern sk_sp<SkColorFilter> ToSk(const DlColorFilter* filter); inline sk_sp<SkColorFilter> ToSk( const std::shared_ptr<const DlColorFilter>& filter) { return ToSk(filter.get()); } inline sk_sp<SkColorFilter> ToSk(const DlColorFilter& filter) { return ToSk(&filter); } extern sk_sp<SkMaskFilter> ToSk(const DlMaskFilter* filter); inline sk_sp<SkMaskFilter> ToSk( const std::shared_ptr<const DlMaskFilter>& filter) { return ToSk(filter.get()); } inline sk_sp<SkMaskFilter> ToSk(const DlMaskFilter& filter) { return ToSk(&filter); } extern sk_sp<SkPathEffect> ToSk(const DlPathEffect* effect); inline sk_sp<SkPathEffect> ToSk( const std::shared_ptr<const DlPathEffect>& effect) { return ToSk(effect.get()); } inline sk_sp<SkPathEffect> ToSk(const DlPathEffect& effect) { return ToSk(&effect); } extern sk_sp<SkVertices> ToSk(const DlVertices* vertices); inline sk_sp<SkVertices> ToSk( const std::shared_ptr<const DlVertices>& vertices) { return ToSk(vertices.get()); } inline sk_sp<SkVertices> ToSk(const DlVertices& vertices) { return ToSk(&vertices); } } // namespace flutter #endif // FLUTTER_DISPLAY_LIST_SKIA_DL_SK_CONVERSIONS_H_
engine/display_list/skia/dl_sk_conversions.h/0
{ "file_path": "engine/display_list/skia/dl_sk_conversions.h", "repo_id": "engine", "token_count": 1549 }
155
// 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_METAL_H_ #define FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_METAL_H_ #include "flutter/display_list/testing/dl_test_surface_provider.h" #include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" #include "flutter/impeller/golden_tests/metal_screenshotter.h" #include "flutter/testing/test_metal_surface.h" namespace flutter { namespace testing { using MetalScreenshotter = impeller::testing::MetalScreenshotter; class DlMetalSurfaceProvider : public DlSurfaceProvider { public: explicit DlMetalSurfaceProvider() : DlSurfaceProvider() {} virtual ~DlMetalSurfaceProvider() = default; bool InitializeSurface(size_t width, size_t height, PixelFormat format) override; std::shared_ptr<DlSurfaceInstance> GetPrimarySurface() const override; std::shared_ptr<DlSurfaceInstance> MakeOffscreenSurface( size_t width, size_t height, PixelFormat format) const override; const std::string backend_name() const override { return "Metal"; } BackendType backend_type() const override { return kMetalBackend; } bool supports(PixelFormat format) const override { return format == kN32PremulPixelFormat; } bool supports_impeller() const override { return true; } sk_sp<DlPixelData> ImpellerSnapshot(const sk_sp<DisplayList>& list, int width, int height) const override; virtual sk_sp<DlImage> MakeImpellerImage(const sk_sp<DisplayList>& list, int width, int height) const override; private: // This must be placed before any other members that may use the // autorelease pool. fml::ScopedNSAutoreleasePool autorelease_pool_; std::unique_ptr<TestMetalContext> metal_context_; std::shared_ptr<DlSurfaceInstance> metal_surface_; mutable std::unique_ptr<MetalScreenshotter> snapshotter_; mutable std::unique_ptr<impeller::AiksContext> aiks_context_; void InitScreenShotter() const; }; } // namespace testing } // namespace flutter #endif // FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_METAL_H_
engine/display_list/testing/dl_test_surface_metal.h/0
{ "file_path": "engine/display_list/testing/dl_test_surface_metal.h", "repo_id": "engine", "token_count": 930 }
156
// 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/embedded_views.h" namespace flutter { DisplayListEmbedderViewSlice::DisplayListEmbedderViewSlice(SkRect view_bounds) { builder_ = std::make_unique<DisplayListBuilder>( /*bounds=*/view_bounds, /*prepare_rtree=*/true); } DlCanvas* DisplayListEmbedderViewSlice::canvas() { return builder_ ? builder_.get() : nullptr; } void DisplayListEmbedderViewSlice::end_recording() { display_list_ = builder_->Build(); FML_DCHECK(display_list_->has_rtree()); builder_ = nullptr; } const DlRegion& DisplayListEmbedderViewSlice::getRegion() const { return display_list_->rtree()->region(); } void DisplayListEmbedderViewSlice::render_into(DlCanvas* canvas) { canvas->DrawDisplayList(display_list_); } void DisplayListEmbedderViewSlice::dispatch(DlOpReceiver& receiver) { display_list_->Dispatch(receiver); } bool DisplayListEmbedderViewSlice::is_empty() { return display_list_->bounds().isEmpty(); } bool DisplayListEmbedderViewSlice::recording_ended() { return builder_ == nullptr; } void ExternalViewEmbedder::SubmitFlutterView( GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> frame) { frame->Submit(); } bool ExternalViewEmbedder::SupportsDynamicThreadMerging() { return false; } void ExternalViewEmbedder::Teardown() {} void MutatorsStack::PushClipRect(const SkRect& rect) { std::shared_ptr<Mutator> element = std::make_shared<Mutator>(rect); vector_.push_back(element); } void MutatorsStack::PushClipRRect(const SkRRect& rrect) { std::shared_ptr<Mutator> element = std::make_shared<Mutator>(rrect); vector_.push_back(element); } void MutatorsStack::PushClipPath(const SkPath& path) { std::shared_ptr<Mutator> element = std::make_shared<Mutator>(path); vector_.push_back(element); } void MutatorsStack::PushTransform(const SkMatrix& matrix) { std::shared_ptr<Mutator> element = std::make_shared<Mutator>(matrix); vector_.push_back(element); } void MutatorsStack::PushOpacity(const int& alpha) { std::shared_ptr<Mutator> element = std::make_shared<Mutator>(alpha); vector_.push_back(element); } void MutatorsStack::PushBackdropFilter( const std::shared_ptr<const DlImageFilter>& filter, const SkRect& filter_rect) { std::shared_ptr<Mutator> element = std::make_shared<Mutator>(filter, filter_rect); vector_.push_back(element); } void MutatorsStack::Pop() { vector_.pop_back(); } void MutatorsStack::PopTo(size_t stack_count) { while (vector_.size() > stack_count) { Pop(); } } const std::vector<std::shared_ptr<Mutator>>::const_reverse_iterator MutatorsStack::Top() const { return vector_.rend(); } const std::vector<std::shared_ptr<Mutator>>::const_reverse_iterator MutatorsStack::Bottom() const { return vector_.rbegin(); } const std::vector<std::shared_ptr<Mutator>>::const_iterator MutatorsStack::Begin() const { return vector_.begin(); } const std::vector<std::shared_ptr<Mutator>>::const_iterator MutatorsStack::End() const { return vector_.end(); } } // namespace flutter
engine/flow/embedded_views.cc/0
{ "file_path": "engine/flow/embedded_views.cc", "repo_id": "engine", "token_count": 1123 }
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. #include "flutter/flow/layers/clip_path_layer.h" #include "flutter/flow/layers/clip_rect_layer.h" #include "flutter/flow/layers/clip_rrect_layer.h" #include "flutter/flow/testing/layer_test.h" #include "flutter/flow/testing/mock_layer.h" #include "flutter/fml/macros.h" #include "flutter/testing/mock_canvas.h" namespace flutter { namespace testing { using CheckerBoardLayerTest = LayerTest; using ClipOp = DlCanvas::ClipOp; #ifndef NDEBUG TEST_F(CheckerBoardLayerTest, ClipRectSaveLayerCheckBoard) { const SkMatrix initial_matrix = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeXYWH(1.0, 2.0, 2.0, 2.0); const SkRect layer_bounds = SkRect::MakeXYWH(0.5, 1.0, 5.0, 6.0); const SkPath child_path = SkPath().addRect(child_bounds); const DlPaint child_paint = DlPaint(DlColor::kYellow()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ClipRectLayer>(layer_bounds, Clip::kAntiAliasWithSaveLayer); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_matrix); layer->Preroll(preroll_context()); // Untouched EXPECT_EQ(preroll_context()->state_stack.device_cull_rect(), kGiantRect); EXPECT_TRUE(preroll_context()->state_stack.is_empty()); EXPECT_EQ(mock_layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->paint_bounds(), mock_layer->paint_bounds()); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_TRUE(mock_layer->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_cull_rect(), layer_bounds); EXPECT_EQ(mock_layer->parent_matrix(), initial_matrix); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(layer_bounds)})); layer->Paint(display_list_paint_context()); { DisplayListBuilder expected_builder; /* (ClipRect)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipRect(layer_bounds, DlCanvas::ClipOp::kIntersect, true); expected_builder.SaveLayer(&child_bounds); { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } } expected_builder.Restore(); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } reset_display_list(); layer->Paint(checkerboard_context()); { DisplayListBuilder expected_builder; /* (ClipRect)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipRect(layer_bounds, DlCanvas::ClipOp::kIntersect, true); expected_builder.SaveLayer(&child_bounds); { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } expected_builder.DrawRect(child_path.getBounds(), checkerboard_paint()); } expected_builder.Restore(); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } TEST_F(CheckerBoardLayerTest, ClipPathSaveLayerCheckBoard) { const SkMatrix initial_matrix = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeXYWH(1.0, 2.0, 2.0, 2.0); const SkRect layer_bounds = SkRect::MakeXYWH(0.5, 1.0, 5.0, 6.0); const SkPath child_path = SkPath().addRect(child_bounds); const SkPath layer_path = SkPath().addRect(layer_bounds).addRect(layer_bounds); const DlPaint child_paint = DlPaint(DlColor::kYellow()); const DlPaint clip_paint; auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ClipPathLayer>(layer_path, Clip::kAntiAliasWithSaveLayer); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_matrix); layer->Preroll(preroll_context()); // Untouched EXPECT_EQ(preroll_context()->state_stack.device_cull_rect(), kGiantRect); EXPECT_TRUE(preroll_context()->state_stack.is_empty()); EXPECT_EQ(mock_layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->paint_bounds(), mock_layer->paint_bounds()); EXPECT_TRUE(mock_layer->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_cull_rect(), layer_bounds); EXPECT_EQ(mock_layer->parent_matrix(), initial_matrix); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(layer_path)})); layer->Paint(display_list_paint_context()); { DisplayListBuilder expected_builder; /* (ClipRect)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipPath(layer_path, DlCanvas::ClipOp::kIntersect, true); expected_builder.SaveLayer(&child_bounds); { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } } expected_builder.Restore(); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } reset_display_list(); layer->Paint(checkerboard_context()); { DisplayListBuilder expected_builder; /* (ClipRect)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipPath(layer_path, DlCanvas::ClipOp::kIntersect, true); expected_builder.SaveLayer(&child_bounds); { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } expected_builder.DrawRect(child_path.getBounds(), checkerboard_paint()); } expected_builder.Restore(); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } TEST_F(CheckerBoardLayerTest, ClipRRectSaveLayerCheckBoard) { const SkMatrix initial_matrix = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeXYWH(1.0, 2.0, 2.0, 2.0); const SkRect layer_bounds = SkRect::MakeXYWH(0.5, 1.0, 5.0, 6.0); const SkPath child_path = SkPath().addRect(child_bounds); const SkRRect layer_rrect = SkRRect::MakeRectXY(layer_bounds, .1, .1); const DlPaint child_paint = DlPaint(DlColor::kYellow()); const DlPaint clip_paint; auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ClipRRectLayer>(layer_rrect, Clip::kAntiAliasWithSaveLayer); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_matrix); layer->Preroll(preroll_context()); // Untouched EXPECT_EQ(preroll_context()->state_stack.device_cull_rect(), kGiantRect); EXPECT_TRUE(preroll_context()->state_stack.is_empty()); EXPECT_EQ(mock_layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->paint_bounds(), mock_layer->paint_bounds()); EXPECT_TRUE(mock_layer->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_cull_rect(), layer_bounds); EXPECT_EQ(mock_layer->parent_matrix(), initial_matrix); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(layer_rrect)})); layer->Paint(display_list_paint_context()); { DisplayListBuilder expected_builder; /* (ClipRect)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipRRect(layer_rrect, DlCanvas::ClipOp::kIntersect, true); expected_builder.SaveLayer(&child_bounds); { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } } expected_builder.Restore(); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } reset_display_list(); layer->Paint(checkerboard_context()); { DisplayListBuilder expected_builder; /* (ClipRect)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipRRect(layer_rrect, DlCanvas::ClipOp::kIntersect, true); expected_builder.SaveLayer(&child_bounds); { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } expected_builder.DrawRect(child_path.getBounds(), checkerboard_paint()); } expected_builder.Restore(); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } #endif } // namespace testing } // namespace flutter
engine/flow/layers/checkerboard_layertree_unittests.cc/0
{ "file_path": "engine/flow/layers/checkerboard_layertree_unittests.cc", "repo_id": "engine", "token_count": 4078 }
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/flow/layers/container_layer.h" #include "flutter/flow/layers/layer.h" #include "flutter/flow/layers/layer_tree.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/fml/macros.h" #include "gtest/gtest.h" #include "include/core/SkMatrix.h" // TODO(zanderso): https://github.com/flutter/flutter/issues/127701 // NOLINTBEGIN(bugprone-unchecked-optional-access) namespace flutter { namespace testing { using ContainerLayerTest = LayerTest; #ifndef NDEBUG TEST_F(ContainerLayerTest, LayerWithParentHasPlatformView) { auto layer = std::make_shared<ContainerLayer>(); preroll_context()->has_platform_view = true; EXPECT_DEATH_IF_SUPPORTED(layer->Preroll(preroll_context()), "!context->has_platform_view"); } TEST_F(ContainerLayerTest, LayerWithParentHasTextureLayer) { auto layer = std::make_shared<ContainerLayer>(); preroll_context()->has_texture_layer = true; EXPECT_DEATH_IF_SUPPORTED(layer->Preroll(preroll_context()), "!context->has_texture_layer"); } TEST_F(ContainerLayerTest, PaintingEmptyLayerDies) { auto layer = std::make_shared<ContainerLayer>(); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), SkRect::MakeEmpty()); EXPECT_EQ(layer->child_paint_bounds(), SkRect::MakeEmpty()); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(ContainerLayerTest, PaintBeforePrerollDies) { SkPath child_path; child_path.addRect(5.0f, 6.0f, 20.5f, 21.5f); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<ContainerLayer>(); layer->Add(mock_layer); EXPECT_EQ(layer->paint_bounds(), SkRect::MakeEmpty()); EXPECT_EQ(layer->child_paint_bounds(), SkRect::MakeEmpty()); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } #endif TEST_F(ContainerLayerTest, LayerWithParentHasTextureLayerNeedsResetFlag) { SkPath child_path1; child_path1.addRect(5.0f, 6.0f, 20.5f, 21.5f); SkPath child_path2; child_path2.addRect(8.0f, 2.0f, 16.5f, 14.5f); DlPaint child_paint1 = DlPaint(DlColor::kMidGrey()); DlPaint child_paint2 = DlPaint(DlColor::kGreen()); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); mock_layer1->set_fake_has_texture_layer(true); auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2); auto root = std::make_shared<ContainerLayer>(); auto container_layer1 = std::make_shared<ContainerLayer>(); auto container_layer2 = std::make_shared<ContainerLayer>(); root->Add(container_layer1); root->Add(container_layer2); container_layer1->Add(mock_layer1); container_layer2->Add(mock_layer2); EXPECT_EQ(preroll_context()->has_texture_layer, false); root->Preroll(preroll_context()); EXPECT_EQ(preroll_context()->has_texture_layer, true); // The flag for holding texture layer from parent needs to be clear EXPECT_EQ(mock_layer2->parent_has_texture_layer(), false); } TEST_F(ContainerLayerTest, Simple) { SkPath child_path; child_path.addRect(5.0f, 6.0f, 20.5f, 21.5f); DlPaint child_paint = DlPaint(DlColor::kGreen()); SkMatrix initial_transform = SkMatrix::Translate(-0.5f, -0.5f); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ContainerLayer>(); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_FALSE(preroll_context()->has_platform_view); EXPECT_EQ(mock_layer->paint_bounds(), child_path.getBounds()); EXPECT_EQ(layer->paint_bounds(), child_path.getBounds()); EXPECT_EQ(layer->child_paint_bounds(), layer->paint_bounds()); EXPECT_TRUE(mock_layer->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer->parent_cull_rect(), kGiantRect); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (Container)layer::Paint */ { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ContainerLayerTest, Multiple) { SkPath child_path1; child_path1.addRect(5.0f, 6.0f, 20.5f, 21.5f); SkPath child_path2; child_path2.addRect(8.0f, 2.0f, 16.5f, 14.5f); DlPaint child_paint1 = DlPaint(DlColor::kMidGrey()); DlPaint child_paint2 = DlPaint(DlColor::kGreen()); SkMatrix initial_transform = SkMatrix::Translate(-0.5f, -0.5f); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); mock_layer1->set_fake_has_platform_view(true); auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2); auto layer = std::make_shared<ContainerLayer>(); layer->Add(mock_layer1); layer->Add(mock_layer2); SkRect expected_total_bounds = child_path1.getBounds(); expected_total_bounds.join(child_path2.getBounds()); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_TRUE(preroll_context()->has_platform_view); EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds()); EXPECT_EQ(layer->paint_bounds(), expected_total_bounds); EXPECT_EQ(layer->child_paint_bounds(), layer->paint_bounds()); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_TRUE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer1->parent_cull_rect(), kGiantRect); EXPECT_EQ(mock_layer2->parent_cull_rect(), kGiantRect); // Siblings are independent layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (Container)layer::Paint */ { /* mock_layer1::Paint */ { expected_builder.DrawPath(child_path1, child_paint1); } /* mock_layer2::Paint */ { expected_builder.DrawPath(child_path2, child_paint2); } } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ContainerLayerTest, MultipleWithEmpty) { SkPath child_path1; child_path1.addRect(5.0f, 6.0f, 20.5f, 21.5f); DlPaint child_paint1 = DlPaint(DlColor::kMidGrey()); DlPaint child_paint2 = DlPaint(DlColor::kGreen()); SkMatrix initial_transform = SkMatrix::Translate(-0.5f, -0.5f); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); auto mock_layer2 = std::make_shared<MockLayer>(SkPath(), child_paint2); auto layer = std::make_shared<ContainerLayer>(); layer->Add(mock_layer1); layer->Add(mock_layer2); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_FALSE(preroll_context()->has_platform_view); EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), SkPath().getBounds()); EXPECT_EQ(layer->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(layer->child_paint_bounds(), layer->paint_bounds()); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_FALSE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer1->parent_cull_rect(), kGiantRect); EXPECT_EQ(mock_layer2->parent_cull_rect(), kGiantRect); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (Container)layer::Paint */ { /* mock_layer1::Paint */ { expected_builder.DrawPath(child_path1, child_paint1); } // mock_layer2 not drawn due to needs_painting() returning false } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ContainerLayerTest, NeedsSystemComposite) { SkPath child_path1; child_path1.addRect(5.0f, 6.0f, 20.5f, 21.5f); SkPath child_path2; child_path2.addRect(8.0f, 2.0f, 16.5f, 14.5f); DlPaint child_paint1 = DlPaint(DlColor::kMidGrey()); DlPaint child_paint2 = DlPaint(DlColor::kGreen()); SkMatrix initial_transform = SkMatrix::Translate(-0.5f, -0.5f); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); mock_layer1->set_fake_has_platform_view(false); auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2); auto layer = std::make_shared<ContainerLayer>(); layer->Add(mock_layer1); layer->Add(mock_layer2); SkRect expected_total_bounds = child_path1.getBounds(); expected_total_bounds.join(child_path2.getBounds()); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_FALSE(preroll_context()->has_platform_view); EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds()); EXPECT_EQ(layer->paint_bounds(), expected_total_bounds); EXPECT_EQ(layer->child_paint_bounds(), layer->paint_bounds()); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_TRUE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer1->parent_cull_rect(), kGiantRect); EXPECT_EQ(mock_layer2->parent_cull_rect(), kGiantRect); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (Container)layer::Paint */ { /* mock_layer1::Paint */ { expected_builder.DrawPath(child_path1, child_paint1); } /* mock_layer2::Paint */ { expected_builder.DrawPath(child_path2, child_paint2); } } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ContainerLayerTest, RasterCacheTest) { // LTRB const SkPath child_path1 = SkPath().addRect(5.0f, 6.0f, 20.5f, 21.5f); const SkPath child_path2 = SkPath().addRect(21.0f, 6.0f, 25.5f, 21.5f); const SkPath child_path3 = SkPath().addRect(26.0f, 6.0f, 30.5f, 21.5f); const DlPaint child_paint1 = DlPaint(DlColor::kMidGrey()); const DlPaint child_paint2 = DlPaint(DlColor::kGreen()); const DlPaint paint; auto cacheable_container_layer1 = MockCacheableContainerLayer::CacheLayerOrChildren(); auto cacheable_container_layer2 = MockCacheableContainerLayer::CacheLayerOnly(); auto cacheable_container_layer11 = MockCacheableContainerLayer::CacheLayerOrChildren(); auto cacheable_layer111 = std::make_shared<MockCacheableLayer>(child_path3, paint); // if the frame had rendered 2 frames, we will cache the cacheable_layer21 // layer auto cacheable_layer21 = std::make_shared<MockCacheableLayer>(child_path1, paint, 2); // clang-format off // layer // | // ________________________________ ________________________________ // | | | // cacheable_container_layer1 mock_layer2 cacheable_container_layer2 // | | // cacheable_container_layer11 cacheable_layer21 // | // cacheable_layer111 // clang-format on auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); auto mock_layer2 = std::make_shared<MockLayer>(SkPath(), child_paint2); auto mock_layer3 = std::make_shared<MockLayer>(child_path2, paint); cacheable_container_layer1->Add(mock_layer1); cacheable_container_layer1->Add(mock_layer3); cacheable_container_layer1->Add(cacheable_container_layer11); cacheable_container_layer11->Add(cacheable_layer111); cacheable_container_layer2->Add(cacheable_layer21); auto layer = std::make_shared<ContainerLayer>(); layer->Add(cacheable_container_layer1); layer->Add(mock_layer2); layer->Add(cacheable_container_layer2); DisplayListBuilder cache_canvas; cache_canvas.TransformReset(); // Initial Preroll for check the layer paint bounds layer->Preroll(preroll_context()); EXPECT_EQ(mock_layer1->paint_bounds(), SkRect::MakeLTRB(5.f, 6.f, 20.5f, 21.5f)); EXPECT_EQ(mock_layer3->paint_bounds(), SkRect::MakeLTRB(21.0f, 6.0f, 25.5f, 21.5f)); EXPECT_EQ(cacheable_layer111->paint_bounds(), SkRect::MakeLTRB(26.0f, 6.0f, 30.5f, 21.5f)); EXPECT_EQ(cacheable_container_layer1->paint_bounds(), SkRect::MakeLTRB(5.f, 6.f, 30.5f, 21.5f)); // the preroll context's raster cache is nullptr EXPECT_EQ(preroll_context()->raster_cached_entries->size(), static_cast<unsigned long>(0)); { // frame1 use_mock_raster_cache(); preroll_context()->raster_cache->BeginFrame(); layer->Preroll(preroll_context()); preroll_context()->raster_cache->EvictUnusedCacheEntries(); // Cache the cacheable entries LayerTree::TryToRasterCache(*(preroll_context()->raster_cached_entries), &paint_context()); EXPECT_EQ(preroll_context()->raster_cached_entries->size(), static_cast<unsigned long>(5)); // cacheable_container_layer1 will cache his children EXPECT_EQ(cacheable_container_layer1->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_container_layer1->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_EQ(cacheable_container_layer11->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_container_layer11->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_FALSE(raster_cache()->Draw( cacheable_container_layer11->raster_cache_item()->GetId().value(), cache_canvas, &paint)); // The cacheable_layer111 should be cached when rended 3 frames EXPECT_EQ(cacheable_layer111->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kNone); // render count < 2 don't cache it EXPECT_EQ(cacheable_container_layer2->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kNone); preroll_context()->raster_cache->EndFrame(); } { // frame2 // new frame the layer tree will create new PrerollContext, so in here we // clear the cached_entries preroll_context()->raster_cached_entries->clear(); preroll_context()->raster_cache->BeginFrame(); layer->Preroll(preroll_context()); preroll_context()->raster_cache->EvictUnusedCacheEntries(); // Cache the cacheable entries LayerTree::TryToRasterCache(*(preroll_context()->raster_cached_entries), &paint_context()); EXPECT_EQ(preroll_context()->raster_cached_entries->size(), static_cast<unsigned long>(5)); EXPECT_EQ(cacheable_container_layer1->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_container_layer1->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_EQ(cacheable_container_layer11->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_container_layer11->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_FALSE(raster_cache()->Draw( cacheable_container_layer11->raster_cache_item()->GetId().value(), cache_canvas, &paint)); EXPECT_EQ(cacheable_container_layer2->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kNone); // render count == 2 cache it EXPECT_EQ(cacheable_layer21->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kCurrent); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_layer21->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_TRUE(raster_cache()->Draw( cacheable_layer21->raster_cache_item()->GetId().value(), cache_canvas, &paint)); preroll_context()->raster_cache->EndFrame(); } { // frame3 // new frame the layer tree will create new PrerollContext, so in here we // clear the cached_entries preroll_context()->raster_cache->BeginFrame(); preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); preroll_context()->raster_cache->EvictUnusedCacheEntries(); // Cache the cacheable entries LayerTree::TryToRasterCache(*(preroll_context()->raster_cached_entries), &paint_context()); EXPECT_EQ(preroll_context()->raster_cached_entries->size(), static_cast<unsigned long>(5)); EXPECT_EQ(cacheable_container_layer1->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kCurrent); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_container_layer1->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_container_layer11->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_FALSE(raster_cache()->Draw( cacheable_container_layer11->raster_cache_item()->GetId().value(), cache_canvas, &paint)); // The 3td frame, we will cache the cacheable_layer111, but his ancestor has // been cached, so cacheable_layer111 Draw is false EXPECT_TRUE(raster_cache()->HasEntry( cacheable_layer111->raster_cache_item()->GetId().value(), SkMatrix::I())); EXPECT_FALSE(raster_cache()->Draw( cacheable_layer111->raster_cache_item()->GetId().value(), cache_canvas, &paint)); // The third frame, we will cache the cacheable_container_layer2 EXPECT_EQ(cacheable_container_layer2->raster_cache_item()->cache_state(), RasterCacheItem::CacheState::kCurrent); EXPECT_TRUE(raster_cache()->HasEntry( cacheable_layer21->raster_cache_item()->GetId().value(), SkMatrix::I())); preroll_context()->raster_cache->EndFrame(); } { preroll_context()->raster_cache->BeginFrame(); // frame4 preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); preroll_context()->raster_cache->EvictUnusedCacheEntries(); LayerTree::TryToRasterCache(*(preroll_context()->raster_cached_entries), &paint_context()); preroll_context()->raster_cache->EndFrame(); // frame5 preroll_context()->raster_cache->BeginFrame(); preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(*(preroll_context()->raster_cached_entries), &paint_context()); preroll_context()->raster_cache->EndFrame(); // frame6 preroll_context()->raster_cache->BeginFrame(); preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(*(preroll_context()->raster_cached_entries), &paint_context()); preroll_context()->raster_cache->EndFrame(); } } TEST_F(ContainerLayerTest, OpacityInheritance) { auto path1 = SkPath().addRect({10, 10, 30, 30}); auto mock1 = MockLayer::MakeOpacityCompatible(path1); auto container1 = std::make_shared<ContainerLayer>(); container1->Add(mock1); // ContainerLayer will pass through compatibility PrerollContext* context = preroll_context(); container1->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); auto path2 = SkPath().addRect({40, 40, 50, 50}); auto mock2 = MockLayer::MakeOpacityCompatible(path2); container1->Add(mock2); // ContainerLayer will pass through compatibility from multiple // non-overlapping compatible children container1->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); auto path3 = SkPath().addRect({20, 20, 40, 40}); auto mock3 = MockLayer::MakeOpacityCompatible(path3); container1->Add(mock3); // ContainerLayer will not pass through compatibility from multiple // overlapping children even if they are individually compatible container1->Preroll(context); EXPECT_EQ(context->renderable_state_flags, 0); auto container2 = std::make_shared<ContainerLayer>(); container2->Add(mock1); container2->Add(mock2); // Double check first two children are compatible and non-overlapping container2->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); auto path4 = SkPath().addRect({60, 60, 70, 70}); auto mock4 = MockLayer::Make(path4); container2->Add(mock4); // The third child is non-overlapping, but not compatible so the // ContainerLayer should end up incompatible container2->Preroll(context); EXPECT_EQ(context->renderable_state_flags, 0); } TEST_F(ContainerLayerTest, CollectionCacheableLayer) { SkPath child_path; child_path.addRect(5.0f, 6.0f, 20.5f, 21.5f); DlPaint child_paint = DlPaint(DlColor::kGreen()); SkMatrix initial_transform = SkMatrix::Translate(-0.5f, -0.5f); auto mock_layer1 = std::make_shared<MockLayer>(SkPath(), child_paint); auto mock_cacheable_container_layer1 = std::make_shared<MockCacheableContainerLayer>(); auto mock_container_layer = std::make_shared<ContainerLayer>(); auto mock_cacheable_layer = std::make_shared<MockCacheableLayer>(child_path, child_paint); mock_cacheable_container_layer1->Add(mock_cacheable_layer); // ContainerLayer // |- MockLayer // |- MockCacheableContainerLayer // |- MockCacheableLayer auto layer = std::make_shared<ContainerLayer>(); layer->Add(mock_cacheable_container_layer1); layer->Add(mock_layer1); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); // raster cache is null, so no entry ASSERT_EQ(preroll_context()->raster_cached_entries->size(), static_cast<const unsigned long>(0)); use_mock_raster_cache(); // preroll_context()->raster_cache = raster_cache(); layer->Preroll(preroll_context()); ASSERT_EQ(preroll_context()->raster_cached_entries->size(), static_cast<const unsigned long>(2)); } using ContainerLayerDiffTest = DiffContextTest; // Insert PictureLayer amongst container layers TEST_F(ContainerLayerDiffTest, PictureLayerInsertion) { auto pic1 = CreateDisplayList(SkRect::MakeLTRB(0, 0, 50, 50)); auto pic2 = CreateDisplayList(SkRect::MakeLTRB(100, 0, 150, 50)); auto pic3 = CreateDisplayList(SkRect::MakeLTRB(200, 0, 250, 50)); MockLayerTree t1; auto t1_c1 = CreateContainerLayer(CreateDisplayListLayer(pic1)); t1.root()->Add(t1_c1); auto t1_c2 = CreateContainerLayer(CreateDisplayListLayer(pic2)); t1.root()->Add(t1_c2); auto damage = DiffLayerTree(t1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 150, 50)); // Add in the middle MockLayerTree t2; auto t2_c1 = CreateContainerLayer(CreateDisplayListLayer(pic1)); t2_c1->AssignOldLayer(t1_c1.get()); t2.root()->Add(t2_c1); t2.root()->Add(CreateDisplayListLayer(pic3)); auto t2_c2 = CreateContainerLayer(CreateDisplayListLayer(pic2)); t2_c2->AssignOldLayer(t1_c2.get()); t2.root()->Add(t2_c2); damage = DiffLayerTree(t2, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 50)); // Add in the beginning t2 = MockLayerTree(); t2.root()->Add(CreateDisplayListLayer(pic3)); t2.root()->Add(t2_c1); t2.root()->Add(t2_c2); damage = DiffLayerTree(t2, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 50)); // Add at the end t2 = MockLayerTree(); t2.root()->Add(t2_c1); t2.root()->Add(t2_c2); t2.root()->Add(CreateDisplayListLayer(pic3)); damage = DiffLayerTree(t2, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 50)); } // Insert picture layer amongst other picture layers TEST_F(ContainerLayerDiffTest, PictureInsertion) { auto pic1 = CreateDisplayList(SkRect::MakeLTRB(0, 0, 50, 50)); auto pic2 = CreateDisplayList(SkRect::MakeLTRB(100, 0, 150, 50)); auto pic3 = CreateDisplayList(SkRect::MakeLTRB(200, 0, 250, 50)); MockLayerTree t1; t1.root()->Add(CreateDisplayListLayer(pic1)); t1.root()->Add(CreateDisplayListLayer(pic2)); auto damage = DiffLayerTree(t1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 150, 50)); MockLayerTree t2; t2.root()->Add(CreateDisplayListLayer(pic3)); t2.root()->Add(CreateDisplayListLayer(pic1)); t2.root()->Add(CreateDisplayListLayer(pic2)); damage = DiffLayerTree(t2, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 50)); MockLayerTree t3; t3.root()->Add(CreateDisplayListLayer(pic1)); t3.root()->Add(CreateDisplayListLayer(pic3)); t3.root()->Add(CreateDisplayListLayer(pic2)); damage = DiffLayerTree(t3, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 50)); MockLayerTree t4; t4.root()->Add(CreateDisplayListLayer(pic1)); t4.root()->Add(CreateDisplayListLayer(pic2)); t4.root()->Add(CreateDisplayListLayer(pic3)); damage = DiffLayerTree(t4, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 50)); } TEST_F(ContainerLayerDiffTest, LayerDeletion) { auto path1 = SkPath().addRect(SkRect::MakeLTRB(0, 0, 50, 50)); auto path2 = SkPath().addRect(SkRect::MakeLTRB(100, 0, 150, 50)); auto path3 = SkPath().addRect(SkRect::MakeLTRB(200, 0, 250, 50)); auto c1 = CreateContainerLayer(std::make_shared<MockLayer>(path1)); auto c2 = CreateContainerLayer(std::make_shared<MockLayer>(path2)); auto c3 = CreateContainerLayer(std::make_shared<MockLayer>(path3)); MockLayerTree t1; t1.root()->Add(c1); t1.root()->Add(c2); t1.root()->Add(c3); auto damage = DiffLayerTree(t1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 250, 50)); MockLayerTree t2; t2.root()->Add(c2); t2.root()->Add(c3); damage = DiffLayerTree(t2, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 50, 50)); MockLayerTree t3; t3.root()->Add(c1); t3.root()->Add(c3); damage = DiffLayerTree(t3, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(100, 0, 150, 50)); MockLayerTree t4; t4.root()->Add(c1); t4.root()->Add(c2); damage = DiffLayerTree(t4, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 50)); MockLayerTree t5; t5.root()->Add(c1); damage = DiffLayerTree(t5, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(100, 0, 250, 50)); MockLayerTree t6; t6.root()->Add(c2); damage = DiffLayerTree(t6, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 250, 50)); MockLayerTree t7; t7.root()->Add(c3); damage = DiffLayerTree(t7, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 150, 50)); } TEST_F(ContainerLayerDiffTest, ReplaceLayer) { auto path1 = SkPath().addRect(SkRect::MakeLTRB(0, 0, 50, 50)); auto path2 = SkPath().addRect(SkRect::MakeLTRB(100, 0, 150, 50)); auto path3 = SkPath().addRect(SkRect::MakeLTRB(200, 0, 250, 50)); auto path1a = SkPath().addRect(SkRect::MakeLTRB(0, 100, 50, 150)); auto path2a = SkPath().addRect(SkRect::MakeLTRB(100, 100, 150, 150)); auto path3a = SkPath().addRect(SkRect::MakeLTRB(200, 100, 250, 150)); auto c1 = CreateContainerLayer(std::make_shared<MockLayer>(path1)); auto c2 = CreateContainerLayer(std::make_shared<MockLayer>(path2)); auto c3 = CreateContainerLayer(std::make_shared<MockLayer>(path3)); MockLayerTree t1; t1.root()->Add(c1); t1.root()->Add(c2); t1.root()->Add(c3); auto damage = DiffLayerTree(t1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 250, 50)); MockLayerTree t2; t2.root()->Add(c1); t2.root()->Add(c2); t2.root()->Add(c3); damage = DiffLayerTree(t2, t1); EXPECT_TRUE(damage.frame_damage.isEmpty()); MockLayerTree t3; t3.root()->Add(CreateContainerLayer({std::make_shared<MockLayer>(path1a)})); t3.root()->Add(c2); t3.root()->Add(c3); damage = DiffLayerTree(t3, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(0, 0, 50, 150)); MockLayerTree t4; t4.root()->Add(c1); t4.root()->Add(CreateContainerLayer(std::make_shared<MockLayer>(path2a))); t4.root()->Add(c3); damage = DiffLayerTree(t4, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(100, 0, 150, 150)); MockLayerTree t5; t5.root()->Add(c1); t5.root()->Add(c2); t5.root()->Add(CreateContainerLayer(std::make_shared<MockLayer>(path3a))); damage = DiffLayerTree(t5, t1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(200, 0, 250, 150)); } } // namespace testing } // namespace flutter // NOLINTEND(bugprone-unchecked-optional-access)
engine/flow/layers/container_layer_unittests.cc/0
{ "file_path": "engine/flow/layers/container_layer_unittests.cc", "repo_id": "engine", "token_count": 12046 }
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/flow/layers/layer_tree.h" #include "flutter/display_list/skia/dl_sk_canvas.h" #include "flutter/flow/embedded_views.h" #include "flutter/flow/frame_timings.h" #include "flutter/flow/layer_snapshot_store.h" #include "flutter/flow/layers/layer.h" #include "flutter/flow/paint_utils.h" #include "flutter/flow/raster_cache.h" #include "flutter/flow/raster_cache_item.h" #include "flutter/fml/time/time_point.h" #include "flutter/fml/trace_event.h" #include "include/core/SkColorSpace.h" namespace flutter { LayerTree::LayerTree(const Config& config, const SkISize& frame_size) : root_layer_(config.root_layer), frame_size_(frame_size), rasterizer_tracing_threshold_(config.rasterizer_tracing_threshold), checkerboard_raster_cache_images_( config.checkerboard_raster_cache_images), checkerboard_offscreen_layers_(config.checkerboard_offscreen_layers) {} inline SkColorSpace* GetColorSpace(DlCanvas* canvas) { return canvas ? canvas->GetImageInfo().colorSpace() : nullptr; } bool LayerTree::Preroll(CompositorContext::ScopedFrame& frame, bool ignore_raster_cache, SkRect cull_rect) { TRACE_EVENT0("flutter", "LayerTree::Preroll"); if (!root_layer_) { FML_LOG(ERROR) << "The scene did not specify any layers."; return false; } SkColorSpace* color_space = GetColorSpace(frame.canvas()); frame.context().raster_cache().SetCheckboardCacheImages( checkerboard_raster_cache_images_); LayerStateStack state_stack; state_stack.set_preroll_delegate(cull_rect, frame.root_surface_transformation()); RasterCache* cache = ignore_raster_cache ? nullptr : &frame.context().raster_cache(); raster_cache_items_.clear(); PrerollContext context = { // clang-format off .raster_cache = cache, .gr_context = frame.gr_context(), .view_embedder = frame.view_embedder(), .state_stack = state_stack, .dst_color_space = sk_ref_sp<SkColorSpace>(color_space), .surface_needs_readback = false, .raster_time = frame.context().raster_time(), .ui_time = frame.context().ui_time(), .texture_registry = frame.context().texture_registry(), .raster_cached_entries = &raster_cache_items_, // clang-format on }; root_layer_->Preroll(&context); return context.surface_needs_readback; } void LayerTree::TryToRasterCache( const std::vector<RasterCacheItem*>& raster_cached_items, const PaintContext* paint_context, bool ignore_raster_cache) { unsigned i = 0; const auto item_size = raster_cached_items.size(); while (i < item_size) { auto* item = raster_cached_items[i]; if (item->need_caching()) { // try to cache current layer // If parent failed to cache, just proceed to the next entry // cache current entry, this entry's parent must not cache if (item->TryToPrepareRasterCache(*paint_context, false)) { // if parent cached, then foreach child layer to touch them. for (unsigned j = 0; j < item->child_items(); j++) { auto* child_item = raster_cached_items[i + j + 1]; if (child_item->need_caching()) { child_item->TryToPrepareRasterCache(*paint_context, true); } } i += item->child_items() + 1; continue; } } i++; } } void LayerTree::Paint(CompositorContext::ScopedFrame& frame, bool ignore_raster_cache) const { TRACE_EVENT0("flutter", "LayerTree::Paint"); if (!root_layer_) { FML_LOG(ERROR) << "The scene did not specify any layers to paint."; return; } LayerStateStack state_stack; // DrawCheckerboard is not supported on Impeller. if (checkerboard_offscreen_layers_ && !frame.aiks_context()) { state_stack.set_checkerboard_func(DrawCheckerboard); } DlCanvas* canvas = frame.canvas(); state_stack.set_delegate(canvas); // clear the previous snapshots. LayerSnapshotStore* snapshot_store = nullptr; if (enable_leaf_layer_tracing_) { frame.context().snapshot_store().Clear(); snapshot_store = &frame.context().snapshot_store(); } SkColorSpace* color_space = GetColorSpace(frame.canvas()); RasterCache* cache = ignore_raster_cache ? nullptr : &frame.context().raster_cache(); PaintContext context = { // clang-format off .state_stack = state_stack, .canvas = canvas, .gr_context = frame.gr_context(), .dst_color_space = sk_ref_sp(color_space), .view_embedder = frame.view_embedder(), .raster_time = frame.context().raster_time(), .ui_time = frame.context().ui_time(), .texture_registry = frame.context().texture_registry(), .raster_cache = cache, .layer_snapshot_store = snapshot_store, .enable_leaf_layer_tracing = enable_leaf_layer_tracing_, .impeller_enabled = !!frame.aiks_context(), .aiks_context = frame.aiks_context(), // clang-format on }; if (cache) { cache->EvictUnusedCacheEntries(); TryToRasterCache(raster_cache_items_, &context, ignore_raster_cache); } if (root_layer_->needs_painting(context)) { root_layer_->Paint(context); } } sk_sp<DisplayList> LayerTree::Flatten( const SkRect& bounds, const std::shared_ptr<TextureRegistry>& texture_registry, GrDirectContext* gr_context) { TRACE_EVENT0("flutter", "LayerTree::Flatten"); DisplayListBuilder builder(bounds); const FixedRefreshRateStopwatch unused_stopwatch; LayerStateStack preroll_state_stack; // No root surface transformation. So assume identity. preroll_state_stack.set_preroll_delegate(bounds); PrerollContext preroll_context{ // clang-format off .raster_cache = nullptr, .gr_context = gr_context, .view_embedder = nullptr, .state_stack = preroll_state_stack, .dst_color_space = nullptr, .surface_needs_readback = false, .raster_time = unused_stopwatch, .ui_time = unused_stopwatch, .texture_registry = texture_registry, // clang-format on }; LayerStateStack paint_state_stack; paint_state_stack.set_delegate(&builder); PaintContext paint_context = { // clang-format off .state_stack = paint_state_stack, .canvas = &builder, .gr_context = gr_context, .dst_color_space = nullptr, .view_embedder = nullptr, .raster_time = unused_stopwatch, .ui_time = unused_stopwatch, .texture_registry = texture_registry, .raster_cache = nullptr, .layer_snapshot_store = nullptr, .enable_leaf_layer_tracing = false, // clang-format on }; // Even if we don't have a root layer, we still need to create an empty // picture. if (root_layer_) { root_layer_->Preroll(&preroll_context); // The needs painting flag may be set after the preroll. So check it after. if (root_layer_->needs_painting(paint_context)) { root_layer_->Paint(paint_context); } } return builder.Build(); } } // namespace flutter
engine/flow/layers/layer_tree.cc/0
{ "file_path": "engine/flow/layers/layer_tree.cc", "repo_id": "engine", "token_count": 3504 }
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. #ifndef FLUTTER_FLOW_LAYERS_SHADER_MASK_LAYER_H_ #define FLUTTER_FLOW_LAYERS_SHADER_MASK_LAYER_H_ #include "flutter/display_list/effects/dl_color_source.h" #include "flutter/flow/layers/cacheable_layer.h" namespace flutter { class ShaderMaskLayer : public CacheableContainerLayer { public: ShaderMaskLayer(std::shared_ptr<DlColorSource> color_source, const SkRect& mask_rect, DlBlendMode blend_mode); void Diff(DiffContext* context, const Layer* old_layer) override; void Preroll(PrerollContext* context) override; void Paint(PaintContext& context) const override; private: std::shared_ptr<DlColorSource> color_source_; SkRect mask_rect_; DlBlendMode blend_mode_; FML_DISALLOW_COPY_AND_ASSIGN(ShaderMaskLayer); }; } // namespace flutter #endif // FLUTTER_FLOW_LAYERS_SHADER_MASK_LAYER_H_
engine/flow/layers/shader_mask_layer.h/0
{ "file_path": "engine/flow/layers/shader_mask_layer.h", "repo_id": "engine", "token_count": 389 }
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. #include "flutter/flow/raster_cache_key.h" #include <optional> #include "flutter/flow/layers/container_layer.h" #include "flutter/flow/layers/display_list_layer.h" #include "flutter/flow/layers/layer.h" namespace flutter { // std::optional<std::vector<RasterCacheKeyID>> RasterCacheKeyID::LayerChildrenIds( const Layer* layer) { FML_DCHECK(layer->as_container_layer()); auto& children_layers = layer->as_container_layer()->layers(); auto children_count = children_layers.size(); if (children_count == 0) { return std::nullopt; } std::vector<RasterCacheKeyID> ids; std::transform( children_layers.begin(), children_layers.end(), std::back_inserter(ids), [](auto& layer) -> RasterCacheKeyID { return layer->caching_key_id(); }); return ids; } } // namespace flutter
engine/flow/raster_cache_key.cc/0
{ "file_path": "engine/flow/raster_cache_key.cc", "repo_id": "engine", "token_count": 337 }
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. #ifndef FLUTTER_FLOW_SURFACE_H_ #define FLUTTER_FLOW_SURFACE_H_ #include <memory> #include "flutter/common/graphics/gl_context_switch.h" #include "flutter/flow/embedded_views.h" #include "flutter/flow/surface_frame.h" #include "flutter/fml/macros.h" class GrDirectContext; namespace impeller { class AiksContext; } // namespace impeller namespace flutter { /// Abstract Base Class that represents where we will be rendering content. class Surface { public: /// A screenshot of the surface's raw data. struct SurfaceData { std::string pixel_format; sk_sp<SkData> data; }; Surface(); virtual ~Surface(); virtual bool IsValid() = 0; virtual std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) = 0; virtual SkMatrix GetRootTransformation() const = 0; virtual GrDirectContext* GetContext() = 0; virtual std::unique_ptr<GLContextResult> MakeRenderContextCurrent(); virtual bool ClearRenderContext(); virtual bool AllowsDrawingWhenGpuDisabled() const; virtual bool EnableRasterCache() const; virtual std::shared_ptr<impeller::AiksContext> GetAiksContext() const; /// Capture the `SurfaceData` currently present in the surface. /// /// Not guaranteed to work on all setups and not intended to be used in /// production. The data field will be null if it was unable to work. virtual SurfaceData GetSurfaceData() const; private: FML_DISALLOW_COPY_AND_ASSIGN(Surface); }; } // namespace flutter #endif // FLUTTER_FLOW_SURFACE_H_
engine/flow/surface.h/0
{ "file_path": "engine/flow/surface.h", "repo_id": "engine", "token_count": 521 }
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. #include "flutter/flow/testing/mock_texture.h" #include "flutter/flow/layers/layer.h" #include "flutter/testing/display_list_testing.h" namespace flutter { namespace testing { sk_sp<DlImage> MockTexture::MakeTestTexture(int w, int h, int checker_size) { sk_sp<SkSurface> surface = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(w, h)); SkCanvas* canvas = surface->getCanvas(); SkPaint p0, p1; p0.setStyle(SkPaint::kFill_Style); p0.setColor(SK_ColorGREEN); p1.setStyle(SkPaint::kFill_Style); p1.setColor(SK_ColorBLUE); p1.setAlpha(128); for (int y = 0; y < w; y += checker_size) { for (int x = 0; x < h; x += checker_size) { SkPaint& cellp = ((x + y) & 1) == 0 ? p0 : p1; canvas->drawRect(SkRect::MakeXYWH(x, y, checker_size, checker_size), cellp); } } return DlImage::Make(surface->makeImageSnapshot()); } MockTexture::MockTexture(int64_t textureId, const sk_sp<DlImage>& texture) : Texture(textureId), texture_(texture) {} void MockTexture::Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) { // MockTexture objects that are not painted are allowed to have a null // texture, but when we get to this method we must have a non-null texture. FML_DCHECK(texture_ != nullptr); SkRect src = SkRect::Make(texture_->bounds()); if (freeze) { FML_DCHECK(src.width() > 2.0f && src.height() > 2.0f); src = src.makeInset(1.0f, 1.0f); } context.canvas->DrawImageRect(texture_, src, bounds, sampling, context.paint); } } // namespace testing } // namespace flutter
engine/flow/testing/mock_texture.cc/0
{ "file_path": "engine/flow/testing/mock_texture.cc", "repo_id": "engine", "token_count": 747 }
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. // Provides a simple class, |CommandLine|, for dealing with command lines (and // flags and positional arguments). // // * Options (a.k.a. flags or switches) are all of the form "--name=<value>" (or // "--name", but this is indistinguishable from "--name="), where <value> is a // string. Not supported: "-name", "-n", "--name <value>", "-n <value>", etc. // * Option order is preserved. // * Option processing is stopped after the first positional argument[*]. Thus // in the command line "my_program --foo bar --baz", only "--foo" is an option // ("bar" and "--baz" are positional arguments). // * Options can be looked up by name. If the same option occurs multiple times, // convention is to use the last occurrence (and the provided look-up // functions behave this way). // * "--" may also be used to separate options from positional arguments. Thus // in the command line "my_program --foo -- --bar", "--bar" is a positional // argument. // * |CommandLine|s store |argv[0]| and distinguish between not having |argv[0]| // and |argv[0]| being empty. // * Apart from being copyable and movable, |CommandLine|s are immutable. // // There are factory functions to turn raw arguments into |CommandLine|s, in // accordance with the above rules. However, |CommandLine|s may be used more // generically (with the user transforming arguments using different rules, // e.g., accepting "-name" as an option), subject to certain limitations (e.g., // not being able to distinguish "no value" from "empty value"). // // [*] This is somewhat annoying for users, but: a. it's standard Unix behavior // for most command line parsers, b. it makes "my_program *" (etc.) safer (which // mostly explains a.), c. it makes parsing "subcommands", like "my_program // --flag_for_my_program subcommand --flag_for_subcommand" saner. #ifndef FLUTTER_FML_COMMAND_LINE_H_ #define FLUTTER_FML_COMMAND_LINE_H_ #include <cstddef> #include <initializer_list> #include <optional> #include <string> #include <string_view> #include <unordered_map> #include <vector> #include "flutter/fml/macros.h" namespace fml { // CommandLine ----------------------------------------------------------------- // Class that stores processed command lines ("argv[0]", options, and positional // arguments) and provides access to them. For more details, see the file-level // comment above. This class is thread-safe. class CommandLine final { private: class ConstructionHelper; public: struct Option { Option() {} explicit Option(const std::string& name); Option(const std::string& name, const std::string& value); bool operator==(const Option& other) const { return name == other.name && value == other.value; } bool operator!=(const Option& other) const { return !operator==(other); } std::string name; std::string value; }; // Default, copy, and move constructors (to be out-of-lined). CommandLine(); CommandLine(const CommandLine& from); CommandLine(CommandLine&& from); // Constructs a |CommandLine| from its "components". This is especially useful // for creating a new |CommandLine| based on an existing |CommandLine| (e.g., // adding options or arguments). explicit CommandLine(const std::string& argv0, const std::vector<Option>& options, const std::vector<std::string>& positional_args); ~CommandLine(); // Copy and move assignment (to be out-of-lined). CommandLine& operator=(const CommandLine& from); CommandLine& operator=(CommandLine&& from); bool has_argv0() const { return has_argv0_; } const std::string& argv0() const { return argv0_; } const std::vector<Option>& options() const { return options_; } const std::vector<std::string>& positional_args() const { return positional_args_; } bool operator==(const CommandLine& other) const { // No need to compare |option_index_|. return has_argv0_ == other.has_argv0_ && argv0_ == other.argv0_ && options_ == other.options_ && positional_args_ == other.positional_args_; } bool operator!=(const CommandLine& other) const { return !operator==(other); } // Returns true if this command line has the option |name| (and if |index| is // non-null, sets |*index| to the index of the *last* occurrence of the given // option in |options()|) and false if not. bool HasOption(std::string_view name, size_t* index = nullptr) const; // Gets the value of the option |name|. Returns true (and sets |*value|) on // success and false (leaving |*value| alone) on failure. bool GetOptionValue(std::string_view name, std::string* value) const; // Gets all values of the option |name|. Returns all values, which may be // empty if the option is not specified. std::vector<std::string_view> GetOptionValues(std::string_view name) const; // Gets the value of the option |name|, with a default if the option is not // specified. (Note: This doesn't return a const reference, since this would // make the |default_value| argument inconvenient/dangerous.) std::string GetOptionValueWithDefault(std::string_view name, std::string_view default_value) const; private: bool has_argv0_ = false; // The following should all be empty if |has_argv0_| is false. std::string argv0_; std::vector<Option> options_; std::vector<std::string> positional_args_; // Maps option names to position in |options_|. If a given name occurs // multiple times, the index will be to the *last* occurrence. std::unordered_map<std::string, size_t> option_index_; // Allow copy and assignment. }; // Factory functions (etc.) ---------------------------------------------------- namespace internal { // Helper class for building command lines (finding options, etc.) from raw // arguments. class CommandLineBuilder final { public: CommandLineBuilder(); ~CommandLineBuilder(); // Processes an additional argument in the command line. Returns true if |arg| // is the *first* positional argument. bool ProcessArg(const std::string& arg); // Builds a |CommandLine| from the arguments processed so far. CommandLine Build() const; private: bool has_argv0_ = false; std::string argv0_; std::vector<CommandLine::Option> options_; std::vector<std::string> positional_args_; // True if we've started processing positional arguments. bool started_positional_args_ = false; FML_DISALLOW_COPY_AND_ASSIGN(CommandLineBuilder); }; } // namespace internal // The following factory functions create |CommandLine|s from raw arguments in // accordance with the rules outlined at the top of this file. (Other ways of // transforming raw arguments into options and positional arguments are // possible.) // Like |CommandLineFromIterators()| (see below), but sets // |*first_positional_arg| to point to the first positional argument seen (or // |last| if none are seen). This is useful for processing "subcommands". template <typename InputIterator> inline CommandLine CommandLineFromIteratorsFindFirstPositionalArg( InputIterator first, InputIterator last, InputIterator* first_positional_arg) { if (first_positional_arg) { *first_positional_arg = last; } internal::CommandLineBuilder builder; for (auto it = first; it < last; ++it) { if (builder.ProcessArg(*it)) { if (first_positional_arg) { *first_positional_arg = it; } } } return builder.Build(); } // Builds a |CommandLine| from first/last iterators (where |last| is really // one-past-the-last, as usual) to |std::string|s or things that implicitly // convert to |std::string|. template <typename InputIterator> inline CommandLine CommandLineFromIterators(InputIterator first, InputIterator last) { return CommandLineFromIteratorsFindFirstPositionalArg<InputIterator>( first, last, nullptr); } // Builds a |CommandLine| from first/last iterators (where |last| is really // one-past-the-last, as usual) to |std::string|s or things that implicitly // convert to |std::string|, where argv[0] is provided separately. template <typename InputIterator> inline CommandLine CommandLineFromIteratorsWithArgv0(const std::string& argv0, InputIterator first, InputIterator last) { internal::CommandLineBuilder builder; builder.ProcessArg(argv0); for (auto it = first; it < last; ++it) { builder.ProcessArg(*it); } return builder.Build(); } // Builds a |CommandLine| by obtaining the arguments of the process using host // platform APIs. The resulting |CommandLine| will be encoded in UTF-8. // Returns an empty optional if this is not supported on the host platform. // // This can be useful on platforms where argv may not be provided as UTF-8. std::optional<CommandLine> CommandLineFromPlatform(); // Builds a |CommandLine| from the usual argc/argv. inline CommandLine CommandLineFromArgcArgv(int argc, const char* const* argv) { return CommandLineFromIterators(argv, argv + argc); } // Builds a |CommandLine| by first trying the platform specific implementation, // and then falling back to the argc/argv. // // If the platform provides a special way of getting arguments, this method may // discard the values passed in to argc/argv. inline CommandLine CommandLineFromPlatformOrArgcArgv(int argc, const char* const* argv) { auto command_line = CommandLineFromPlatform(); if (command_line.has_value()) { return *command_line; } return CommandLineFromArgcArgv(argc, argv); } // Builds a |CommandLine| from an initializer list of |std::string|s or things // that implicitly convert to |std::string|. template <typename StringType> inline CommandLine CommandLineFromInitializerList( std::initializer_list<StringType> argv) { return CommandLineFromIterators(argv.begin(), argv.end()); } // This is the "opposite" of the above factory functions, transforming a // |CommandLine| into a vector of argument strings according to the rules // outlined at the top of this file. std::vector<std::string> CommandLineToArgv(const CommandLine& command_line); } // namespace fml #endif // FLUTTER_FML_COMMAND_LINE_H_
engine/fml/command_line.h/0
{ "file_path": "engine/fml/command_line.h", "repo_id": "engine", "token_count": 3308 }
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. #include "flutter/fml/endianness.h" #include "flutter/testing/testing.h" namespace fml { namespace testing { TEST(EndiannessTest, ByteSwap) { ASSERT_EQ(ByteSwap<int16_t>(0x1122), 0x2211); ASSERT_EQ(ByteSwap<int32_t>(0x11223344), 0x44332211); ASSERT_EQ(ByteSwap<uint64_t>(0x1122334455667788), 0x8877665544332211); } TEST(EndiannessTest, BigEndianToArch) { #if FML_ARCH_CPU_LITTLE_ENDIAN uint32_t expected = 0x44332211; #else uint32_t expected = 0x11223344; #endif ASSERT_EQ(BigEndianToArch(0x11223344u), expected); } TEST(EndiannessTest, LittleEndianToArch) { #if FML_ARCH_CPU_LITTLE_ENDIAN uint32_t expected = 0x11223344; #else uint32_t expected = 0x44332211; #endif ASSERT_EQ(LittleEndianToArch(0x11223344u), expected); } } // namespace testing } // namespace fml
engine/fml/endianness_unittests.cc/0
{ "file_path": "engine/fml/endianness_unittests.cc", "repo_id": "engine", "token_count": 393 }
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_FML_LOGGING_H_ #define FLUTTER_FML_LOGGING_H_ #include <sstream> #include "flutter/fml/log_level.h" #include "flutter/fml/macros.h" namespace fml { namespace testing { struct LogCapture { LogCapture(); ~LogCapture(); std::string str() const; private: std::ostringstream stream_; }; } // namespace testing class LogMessageVoidify { public: void operator&(std::ostream&) {} }; class LogMessage { public: LogMessage(LogSeverity severity, const char* file, int line, const char* condition); ~LogMessage(); std::ostream& stream() { return stream_; } static void CaptureNextLog(std::ostringstream* stream); private: // This is a raw pointer so that we avoid having a non-trivially-destructible // static. It is only ever for use in unit tests. static thread_local std::ostringstream* capture_next_log_stream_; std::ostringstream stream_; const LogSeverity severity_; const char* file_; const int line_; FML_DISALLOW_COPY_AND_ASSIGN(LogMessage); }; // Gets the FML_VLOG default verbosity level. int GetVlogVerbosity(); // Returns true if |severity| is at or above the current minimum log level. // kLogFatal and above is always true. bool ShouldCreateLogMessage(LogSeverity severity); [[noreturn]] void KillProcess(); } // namespace fml #define FML_LOG_STREAM(severity) \ ::fml::LogMessage(::fml::LOG_##severity, __FILE__, __LINE__, nullptr).stream() #define FML_LAZY_STREAM(stream, condition) \ !(condition) ? (void)0 : ::fml::LogMessageVoidify() & (stream) #define FML_EAT_STREAM_PARAMETERS(ignored) \ true || (ignored) \ ? (void)0 \ : ::fml::LogMessageVoidify() & \ ::fml::LogMessage(::fml::kLogFatal, 0, 0, nullptr).stream() #define FML_LOG_IS_ON(severity) \ (::fml::ShouldCreateLogMessage(::fml::LOG_##severity)) #define FML_LOG(severity) \ FML_LAZY_STREAM(FML_LOG_STREAM(severity), FML_LOG_IS_ON(severity)) #define FML_CHECK(condition) \ FML_LAZY_STREAM( \ ::fml::LogMessage(::fml::kLogFatal, __FILE__, __LINE__, #condition) \ .stream(), \ !(condition)) #define FML_VLOG_IS_ON(verbose_level) \ ((verbose_level) <= ::fml::GetVlogVerbosity()) // The VLOG macros log with negative verbosities. #define FML_VLOG_STREAM(verbose_level) \ ::fml::LogMessage(-verbose_level, __FILE__, __LINE__, nullptr).stream() #define FML_VLOG(verbose_level) \ FML_LAZY_STREAM(FML_VLOG_STREAM(verbose_level), FML_VLOG_IS_ON(verbose_level)) #ifndef NDEBUG #define FML_DLOG(severity) FML_LOG(severity) #define FML_DCHECK(condition) FML_CHECK(condition) #else #define FML_DLOG(severity) FML_EAT_STREAM_PARAMETERS(true) #define FML_DCHECK(condition) FML_EAT_STREAM_PARAMETERS(condition) #endif #define FML_UNREACHABLE() \ { \ FML_LOG(ERROR) << "Reached unreachable code."; \ ::fml::KillProcess(); \ } #endif // FLUTTER_FML_LOGGING_H_
engine/fml/logging.h/0
{ "file_path": "engine/fml/logging.h", "repo_id": "engine", "token_count": 1475 }
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. #define FML_USED_ON_EMBEDDER #include "flutter/fml/memory/task_runner_checker.h" #include <thread> #include "flutter/fml/message_loop.h" #include "flutter/fml/raster_thread_merger.h" #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "gtest/gtest.h" namespace fml { namespace testing { TEST(TaskRunnerCheckerTests, RunsOnCurrentTaskRunner) { TaskRunnerChecker checker; EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true); } TEST(TaskRunnerCheckerTests, FailsTheCheckIfOnDifferentTaskRunner) { TaskRunnerChecker checker; EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true); fml::MessageLoop* loop = nullptr; fml::AutoResetWaitableEvent latch; std::thread another_thread([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop = &fml::MessageLoop::GetCurrent(); loop->GetTaskRunner()->PostTask([&]() { EXPECT_EQ(checker.RunsOnCreationTaskRunner(), false); latch.Signal(); }); loop->Run(); }); latch.Wait(); loop->Terminate(); another_thread.join(); EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true); } TEST(TaskRunnerCheckerTests, SameTaskRunnerRunsOnTheSameThread) { fml::MessageLoop::EnsureInitializedForCurrentThread(); fml::MessageLoop& loop1 = fml::MessageLoop::GetCurrent(); fml::MessageLoop& loop2 = fml::MessageLoop::GetCurrent(); TaskQueueId a = loop1.GetTaskRunner()->GetTaskQueueId(); TaskQueueId b = loop2.GetTaskRunner()->GetTaskQueueId(); EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(a, b), true); } TEST(TaskRunnerCheckerTests, RunsOnDifferentThreadsReturnsFalse) { fml::MessageLoop::EnsureInitializedForCurrentThread(); fml::MessageLoop& loop1 = fml::MessageLoop::GetCurrent(); TaskQueueId a = loop1.GetTaskRunner()->GetTaskQueueId(); fml::AutoResetWaitableEvent latch; std::thread another_thread([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); fml::MessageLoop& loop2 = fml::MessageLoop::GetCurrent(); TaskQueueId b = loop2.GetTaskRunner()->GetTaskQueueId(); EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(a, b), false); latch.Signal(); }); latch.Wait(); another_thread.join(); } TEST(TaskRunnerCheckerTests, MergedTaskRunnersRunsOnTheSameThread) { fml::MessageLoop* loop1 = nullptr; fml::AutoResetWaitableEvent latch1; fml::AutoResetWaitableEvent term1; std::thread thread1([&loop1, &latch1, &term1]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop1 = &fml::MessageLoop::GetCurrent(); latch1.Signal(); term1.Wait(); }); fml::MessageLoop* loop2 = nullptr; fml::AutoResetWaitableEvent latch2; fml::AutoResetWaitableEvent term2; std::thread thread2([&loop2, &latch2, &term2]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop2 = &fml::MessageLoop::GetCurrent(); latch2.Signal(); term2.Wait(); }); latch1.Wait(); latch2.Wait(); fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); const auto raster_thread_merger = fml::MakeRefCounted<fml::RasterThreadMerger>(qid1, qid2); const size_t kNumFramesMerged = 5; raster_thread_merger->MergeWithLease(kNumFramesMerged); // merged, running on the same thread EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(qid1, qid2), true); for (size_t i = 0; i < kNumFramesMerged; i++) { ASSERT_TRUE(raster_thread_merger->IsMerged()); raster_thread_merger->DecrementLease(); } ASSERT_FALSE(raster_thread_merger->IsMerged()); // un-merged, not running on the same thread EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(qid1, qid2), false); term1.Signal(); term2.Signal(); thread1.join(); thread2.join(); } TEST(TaskRunnerCheckerTests, PassesRunsOnCreationTaskRunnerIfOnDifferentTaskRunner) { fml::MessageLoop* loop1 = nullptr; fml::AutoResetWaitableEvent latch1; std::thread thread1([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop1 = &fml::MessageLoop::GetCurrent(); latch1.Signal(); loop1->Run(); }); fml::MessageLoop* loop2 = nullptr; fml::AutoResetWaitableEvent latch2; std::thread thread2([&]() { fml::MessageLoop::EnsureInitializedForCurrentThread(); loop2 = &fml::MessageLoop::GetCurrent(); latch2.Signal(); loop2->Run(); }); latch1.Wait(); latch2.Wait(); fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); fml::MessageLoopTaskQueues::GetInstance()->Merge(qid1, qid2); std::unique_ptr<TaskRunnerChecker> checker; fml::AutoResetWaitableEvent latch3; loop2->GetTaskRunner()->PostTask([&]() { checker = std::make_unique<TaskRunnerChecker>(); EXPECT_EQ(checker->RunsOnCreationTaskRunner(), true); latch3.Signal(); }); latch3.Wait(); fml::MessageLoopTaskQueues::GetInstance()->Unmerge(qid1, qid2); fml::AutoResetWaitableEvent latch4; loop2->GetTaskRunner()->PostTask([&]() { EXPECT_EQ(checker->RunsOnCreationTaskRunner(), true); latch4.Signal(); }); latch4.Wait(); loop1->Terminate(); loop2->Terminate(); thread1.join(); thread2.join(); } } // namespace testing } // namespace fml
engine/fml/memory/task_runner_checker_unittest.cc/0
{ "file_path": "engine/fml/memory/task_runner_checker_unittest.cc", "repo_id": "engine", "token_count": 2015 }
168