text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
#import "GeneratedPluginRegistrant.h"
devtools/case_study/code_size/optimized/code_size_package/ios/Runner/Runner-Bridging-Header.h/0
{ "file_path": "devtools/case_study/code_size/optimized/code_size_package/ios/Runner/Runner-Bridging-Header.h", "repo_id": "devtools", "token_count": 13 }
71
#include "Generated.xcconfig"
devtools/case_study/code_size/unoptimized/code_size_images/ios/Flutter/Debug.xcconfig/0
{ "file_path": "devtools/case_study/code_size/unoptimized/code_size_images/ios/Flutter/Debug.xcconfig", "repo_id": "devtools", "token_count": 12 }
72
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
devtools/case_study/memory_leaks/leaking_counter_1/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "devtools/case_study/memory_leaks/leaking_counter_1/macos/Runner/Configs/Debug.xcconfig", "repo_id": "devtools", "token_count": 32 }
73
@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
devtools/case_study/memory_leaks/memory_leak_app/android/gradlew.bat/0
{ "file_path": "devtools/case_study/memory_leaks/memory_leak_app/android/gradlew.bat", "repo_id": "devtools", "token_count": 833 }
74
#include "Generated.xcconfig"
devtools/case_study/platform_channel/ios/Flutter/Release.xcconfig/0
{ "file_path": "devtools/case_study/platform_channel/ios/Flutter/Release.xcconfig", "repo_id": "devtools", "token_count": 12 }
75
import 'dart:async'; import 'package:flutter/material.dart'; import 'channel_demo.dart'; void main() => runApp(MyApp()); const platformChannelTitle = 'Platform Channel Demo'; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: _HomePage(), ); } } class _HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(platformChannelTitle), ), body: Center( child: TextButton( style: TextButton.styleFrom(backgroundColor: Colors.green), onPressed: () { unawaited( Navigator.push( context, MaterialPageRoute(builder: (context) => ChannelDemo()), ), ); }, child: const Text( platformChannelTitle, style: TextStyle(color: Colors.white), ), ), ), ); } }
devtools/case_study/platform_channel/lib/main.dart/0
{ "file_path": "devtools/case_study/platform_channel/lib/main.dart", "repo_id": "devtools", "token_count": 511 }
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. // ignore_for_file: invalid_use_of_visible_for_testing_member, valid use for benchmark tests. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_test/helpers.dart'; import 'package:devtools_test/test_data.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class PerformanceScreenAutomator { const PerformanceScreenAutomator(this.controller); final WidgetController controller; Future<void> run() async { logStatus('Loading offline performance data and interacting'); await loadSampleData(controller, performanceLargeFileName); logStatus('Select frames with the Frame Analysis tab open'); final frames = find.byType(FlutterFramesChartItem); for (var i = 0; i < 5; i++) { await controller.tap(frames.at(i)); await controller.pump(shortPumpDuration); } logStatus('Open the Timeline Events tab'); await controller.tap(find.widgetWithText(InkWell, 'Timeline Events')); await controller.pump(safePumpDuration); logStatus('Select frames with the Timeline Events tab open'); for (var i = 5; i < 10; i++) { await controller.tap(frames.at(i)); await controller.pump(shortPumpDuration); } logStatus('Scroll through the frames chart'); await scrollToEnd<FramesChart>(controller); logStatus('End loading offline performance data and interacting'); } }
devtools/packages/devtools_app/benchmark/test_infra/automators/_performance_automator.dart/0
{ "file_path": "devtools/packages/devtools_app/benchmark/test_infra/automators/_performance_automator.dart", "repo_id": "devtools", "token_count": 486 }
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:flutter/material.dart'; import 'controller.dart'; class EmbeddedExtension extends StatelessWidget { const EmbeddedExtension({super.key, required this.controller}); final EmbeddedExtensionController controller; @override Widget build(BuildContext context) { // TODO(kenz): if web view support for desktop is ever added, use that here. return const Center( child: Text( 'Cannot display the DevTools extension.' ' IFrames are not supported on desktop platforms.', ), ); } }
devtools/packages/devtools_app/lib/src/extensions/embedded/_view_desktop.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/extensions/embedded/_view_desktop.dart", "repo_id": "devtools", "token_count": 217 }
78
// 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 'dart:convert'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:logging/logging.dart'; import '../../../devtools.dart' as devtools; import '../../shared/primitives/url_utils.dart'; import '../../shared/server/server.dart' as server; import '../../shared/side_panel.dart'; import '../../shared/utils.dart'; import '../../standalone_ui/standalone_screen.dart'; final _log = Logger('release_notes'); // This is not const because it is manipulated for testing as well as for // local development. bool debugTestReleaseNotes = false; // To load markdown from a staged flutter website, set this string to the url // from the flutter/website PR, which has a GitHub action that automatically // stages commits to firebase. Example: // https://flutter-docs-prod--pr8928-dt-notes-links-b0b33er1.web.app/tools/devtools/release-notes/release-notes-2.24.0-src.md. const String? _debugReleaseNotesUrl = null; const releaseNotesKey = Key('release_notes'); const _unsupportedPathSyntax = '{{site.url}}'; const _releaseNotesPath = '/f/devtools-releases.json'; final _flutterDocsSite = Uri.https('docs.flutter.dev'); class ReleaseNotesViewer extends SidePanelViewer { const ReleaseNotesViewer({ required super.controller, Widget? child, }) : super( key: releaseNotesKey, title: 'What\'s new in DevTools?', textIfMarkdownDataEmpty: 'Stay tuned for updates.', child: child, ); } class ReleaseNotesController extends SidePanelController { ReleaseNotesController() { _init(); } @visibleForTesting static Uri get releaseIndexUrl => _flutterDocsSite.replace(path: _releaseNotesPath); void _init() { if (debugTestReleaseNotes || _debugReleaseNotesUrl != null || server.isDevToolsServerAvailable) { _maybeShowReleaseNotes(); } } void _maybeShowReleaseNotes() async { final currentUrl = getWebUrl(); final currentPage = currentUrl != null ? extractCurrentPageFromUrl(currentUrl) : null; if (isEmbedded() && currentPage == StandaloneScreenType.vsCodeFlutterPanel.name) { // Do not show release notes in the Flutter sidebar. return; } SemanticVersion previousVersion = SemanticVersion(); if (server.isDevToolsServerAvailable) { final lastReleaseNotesShownVersion = await server.getLastShownReleaseNotesVersion(); if (lastReleaseNotesShownVersion.isNotEmpty) { previousVersion = SemanticVersion.parse(lastReleaseNotesShownVersion); } } await _fetchAndShowReleaseNotes( versionFloor: debugTestReleaseNotes ? null : previousVersion, ); } /// Fetches and shows the most recent release notes for the current DevTools /// version, decreasing the patch version by 1 each time until we find release /// notes or until we hit [versionFloor]. Future<void> _fetchAndShowReleaseNotes({ SemanticVersion? versionFloor, }) async { if (_debugReleaseNotesUrl case final debugUrl?) { // Specially handle the case where a debug release notes URL is specified. final debugUri = Uri.parse(debugUrl); final releaseNotesMarkdown = await http.read(debugUri); // Update image links to use debug/testing URL. markdown.value = releaseNotesMarkdown.replaceAll( _unsupportedPathSyntax, debugUri.replace(path: '').toString(), ); toggleVisibility(true); return; } versionFloor ??= SemanticVersion(); // Parse the current version instead of using [devtools.version] directly to // strip off any build metadata (any characters following a '+' character). // Release notes will be hosted on the Flutter website with a version number // that does not contain any build metadata. final parsedVersion = SemanticVersion.parse(devtools.version); final notesVersion = latestVersionToCheckForReleaseNotes(parsedVersion); if (notesVersion <= versionFloor) { // If the current version is equal to or below the version floor, // no need to show the release notes. _emptyAndClose(); return; } final releases = await retrieveReleasesFromIndex(); if (releases == null) { return; } // If the version floor has the same major and minor version, // don't check below its patch version. final int minimumPatch; if (versionFloor.major == notesVersion.major && versionFloor.minor == notesVersion.minor) { minimumPatch = versionFloor.patch; } else { minimumPatch = 0; } final majorMinor = '${notesVersion.major}.${notesVersion.minor}'; var patchToCheck = notesVersion.patch; // Try each patch version in this major.minor combination until we find // release notes (e.g. 2.11.4 -> 2.11.3 -> 2.11.2 -> ...). while (patchToCheck >= minimumPatch) { final releaseToCheck = '$majorMinor.$patchToCheck'; if (releases[releaseToCheck] case final String releaseNotePath) { final String releaseNotesMarkdown; try { releaseNotesMarkdown = await http.read( _flutterDocsSite.replace(path: releaseNotePath), ); } catch (_) { // This can very infrequently fail due to CDN or caching issues, // or if the upstream file has an incorrect link. _log.info('Failed to retrieve release notes for v$releaseToCheck, ' 'despite indication it is live at $releaseNotePath.'); // If we couldn't retrieve this page, keep going to // try with earlier patch versions. continue; } // Replace the {{site.url}} template syntax that the // Flutter docs website uses to specify site URLs. markdown.value = releaseNotesMarkdown.replaceAll( _unsupportedPathSyntax, _flutterDocsSite.toString(), ); toggleVisibility(true); if (server.isDevToolsServerAvailable) { // Only set the last release notes version // if we are not debugging. unawaited( server.setLastShownReleaseNotesVersion(releaseToCheck), ); } return; } patchToCheck -= 1; } _emptyAndClose( 'Could not find release notes for DevTools version $notesVersion.', ); return; } /// Retrieve and parse the release note index from the /// Flutter website at [_flutterDocsSite]/[_releaseNotesPath]. /// /// Calls [_emptyAndClose] and returns `null` if /// the retrieval or parsing fails. @visibleForTesting Future<Map<String, Object?>?> retrieveReleasesFromIndex() async { final Map<String, Object?> releaseIndex; try { final releaseIndexString = await http.read(releaseIndexUrl); releaseIndex = jsonDecode(releaseIndexString) as Map<String, Object?>; } catch (e) { // This can occur if the file can't be retrieved or if its not a JSON map. _emptyAndClose(e.toString()); return null; } final releases = releaseIndex['releases']; if (releases is! Map<String, Object?>) { _emptyAndClose( 'The DevTools release index file was incorrectly formatted.', ); return null; } return releaseIndex; } /// Set the release notes viewer as having no contents, hidden, /// and optionally log the specified [message]. void _emptyAndClose([String? message]) { markdown.value = null; toggleVisibility(false); if (message != null) { _log.warning('Warning: $message'); } } @visibleForTesting SemanticVersion latestVersionToCheckForReleaseNotes( SemanticVersion currentVersion, ) { // If the current version is a pre-release, downgrade the minor to find the // previous DevTools release, and start looking for release notes from this // value. Release notes will never be published for pre-release versions. if (currentVersion.isPreRelease) { // It is very unlikely the patch value of the DevTools version will ever // be above this number. This is a safe number to start looking for // release notes at. const safeStartPatch = 10; currentVersion = SemanticVersion( major: currentVersion.major, minor: currentVersion.minor - 1, patch: safeStartPatch, ); } return currentVersion; } Future<void> openLatestReleaseNotes() async { if (markdown.value == null) { await _fetchAndShowReleaseNotes(); } toggleVisibility(true); } }
devtools/packages/devtools_app/lib/src/framework/release_notes/release_notes.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/framework/release_notes/release_notes.dart", "repo_id": "devtools", "token_count": 3065 }
79
// 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:async/async.dart'; import 'package:collection/collection.dart' show IterableExtension; import 'package:dap/dap.dart' as dap; 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 '../../service/vm_service_wrapper.dart'; import '../../shared/analytics/analytics.dart' as ga; import '../../shared/analytics/constants.dart' as gac; import '../../shared/diagnostics/dap_object_node.dart'; import '../../shared/diagnostics/dart_object_node.dart'; import '../../shared/diagnostics/primitives/source_location.dart'; import '../../shared/diagnostics/tree_builder.dart'; import '../../shared/feature_flags.dart'; import '../../shared/globals.dart'; import '../../shared/primitives/message_bus.dart'; import '../../shared/primitives/utils.dart'; import '../../shared/routing.dart'; import 'codeview_controller.dart'; import 'debugger_model.dart'; // Make sure this a checked in with `mute: true`. final _debugTimingLog = DebugTimingLogger('debugger', mute: true); final _log = Logger('debugger_controller'); /// Responsible for managing the debug state of the app. class DebuggerController extends DisposableController with AutoDisposeControllerMixin { // `initialSwitchToIsolate` can be set to false for tests to skip the logic // in `switchToIsolate`. DebuggerController({ DevToolsRouterDelegate? routerDelegate, bool initialSwitchToIsolate = true, }) : _initialSwitchToIsolate = initialSwitchToIsolate { addAutoDisposeListener(serviceConnection.serviceManager.connectedState, () { if (serviceConnection.serviceManager.connectedState.value.connected) { _handleConnectionAvailable(serviceConnection.serviceManager.service!); } }); if (routerDelegate != null) { codeViewController.subscribeToRouterEvents(routerDelegate); } addAutoDisposeListener(_selectedStackFrame, _updateCurrentFrame); addAutoDisposeListener(_stackFramesWithLocation, _updateCurrentFrame); if (serviceConnection.serviceManager.connectedState.value.connected) { _initialize(); } } final codeViewController = CodeViewController(); bool _firstDebuggerScreenLoaded = false; void _updateCurrentFrame() { serviceConnection.appState.setCurrentFrame( _selectedStackFrame.value?.frame ?? _stackFramesWithLocation.value.safeFirst?.frame, ); } /// 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> onFirstDebuggerScreenLoad() async { if (!_firstDebuggerScreenLoaded) { await codeViewController.maybeSetupProgramExplorer(); } } /// Method to call after the vm service shuts down. void _onServiceShutdown() { _clearCaches(isServiceShutdown: true); _hasTruncatedFrames.value = false; unawaited(_getStackOperation?.cancel()); _getStackOperation = null; final appState = serviceConnection.appState; _resuming.value = false; _lastEvent = null; _stackFramesWithLocation.value = []; _selectedStackFrame.value = null; appState.setVariables([]); _selectedBreakpoint.value = null; _firstDebuggerScreenLoaded = false; } VmServiceWrapper? _lastService; void _handleConnectionAvailable(VmServiceWrapper service) { if (service == _lastService) return; _lastService = service; _onServiceShutdown(); _initialize(); } ValueListenable<IsolateRef?> get _isolate => serviceConnection.serviceManager.isolateManager.selectedIsolate; void _initialize() { if (_initialSwitchToIsolate) { assert(_isolate.value != null); _switchToIsolate(_isolate.value); } addAutoDisposeListener(_isolate, () { _switchToIsolate(_isolate.value); }); autoDisposeStreamSubscription( _service.onDebugEvent.listen(_handleDebugEvent), ); autoDisposeStreamSubscription( _service.onIsolateEvent.listen(_handleIsolateEvent), ); } final bool _initialSwitchToIsolate; VmServiceWrapper get _service { return serviceConnection.serviceManager.service!; } final _resuming = ValueNotifier<bool>(false); /// This indicates that we've requested a resume (or step) operation from the /// VM, but haven't yet received the 'resumed' isolate event. ValueListenable<bool> get resuming => _resuming; Event? _lastEvent; Event? get lastEvent => _lastEvent; final _stackFramesWithLocation = ValueNotifier<List<StackFrameAndSourcePosition>>([]); ValueListenable<List<StackFrameAndSourcePosition>> get stackFramesWithLocation => _stackFramesWithLocation; final _selectedStackFrame = ValueNotifier<StackFrameAndSourcePosition?>(null); ValueListenable<StackFrameAndSourcePosition?> get selectedStackFrame => _selectedStackFrame; final _selectedBreakpoint = ValueNotifier<BreakpointAndSourcePosition?>(null); ValueListenable<BreakpointAndSourcePosition?> get selectedBreakpoint => _selectedBreakpoint; final _exceptionPauseMode = ValueNotifier<String>(ExceptionPauseMode.kUnhandled); ValueListenable<String?> get exceptionPauseMode => _exceptionPauseMode; bool get isSystemIsolate => _isolate.value?.isSystemIsolate ?? false; String get _isolateRefId { final id = _isolate.value?.id; if (id == null) return ''; return id; } void _switchToIsolate(IsolateRef? ref) async { // TODO(polina-c and jacob314): move this logic to appState // and modify to detect if app is paused from the isolate // https://github.com/flutter/devtools/pull/4993#discussion_r1060845351 await _pause(false); _clearCaches(); codeViewController.clearScriptHistory(); if (ref == null) { await _getStackOperation?.cancel(); await _populateFrameInfo([], truncated: false); return; } final isolate = await _service.getIsolate(_isolateRefId); if (isolate.id != _isolateRefId) { // Current request is obsolete. return; } if (isolate.pauseEvent != null && isolate.pauseEvent!.kind != EventKind.kResume) { _lastEvent = isolate.pauseEvent; await _pause(true, pauseEvent: isolate.pauseEvent); } if (isolate.id != _isolateRefId) { // Current request is obsolete. return; } _exceptionPauseMode.value = isolate.exceptionPauseMode ?? ExceptionPauseMode.kUnhandled; if (isolate.id != _isolateRefId) { // Current request is obsolete. return; } await _populateScripts(isolate); } Future<Success> pause() => _service.pause(_isolateRefId); Future<Success> resume() { _debugTimingLog.log('resume()'); _resuming.value = true; return _service.resume(_isolateRefId); } Future<Success> stepOver() { _debugTimingLog.log('stepOver()'); _resuming.value = true; // Handle async suspensions; issue StepOption.kOverAsyncSuspension. final useAsyncStepping = _lastEvent?.atAsyncSuspension ?? false; return _service .resume( _isolateRefId, step: useAsyncStepping ? StepOption.kOverAsyncSuspension : StepOption.kOver, ) .whenComplete(() => _debugTimingLog.log('stepOver() completed')); } Future<Success> stepIn() { _resuming.value = true; return _service.resume(_isolateRefId, step: StepOption.kInto); } Future<Success> stepOut() { _resuming.value = true; return _service.resume(_isolateRefId, step: StepOption.kOut); } Future<void> setIsolatePauseMode(String mode) async { await _service.setIsolatePauseMode( _isolateRefId, exceptionPauseMode: mode, ); _exceptionPauseMode.value = mode; } /// Flutter starting with '--start-paused'. All subsequent isolates, after /// the first isolate, are in a pauseStart state too. If _resuming, then /// resume any future isolate created with pause start. Future<Success> _resumeIsolatePauseStart(Event event) { assert(event.kind == EventKind.kPauseStart); assert(_resuming.value); final id = event.isolate!.id!; _debugTimingLog.log('resume() $id'); return _service.resume(id); } void _handleDebugEvent(Event event) { _debugTimingLog.log('event: ${event.kind}'); // We're resuming and another isolate has started in a paused state, // resume any pauseState isolates. if (_resuming.value && event.isolate!.id != _isolateRefId && event.kind == EventKind.kPauseStart) { unawaited(_resumeIsolatePauseStart(event)); } if (event.isolate!.id != _isolateRefId) return; _lastEvent = event; switch (event.kind) { case EventKind.kResume: unawaited(_pause(false)); break; case EventKind.kPauseStart: case EventKind.kPauseExit: case EventKind.kPauseBreakpoint: case EventKind.kPauseInterrupted: case EventKind.kPauseException: case EventKind.kPausePostRequest: // Any event we receive here indicates that any resume/step request has been // processed. _resuming.value = false; unawaited(_pause(true, pauseEvent: event)); break; } } void _handleIsolateEvent(Event event) { final eventId = event.isolate?.id; if (eventId != _isolateRefId) return; switch (event.kind) { case EventKind.kIsolateReload: _updateAfterIsolateReload(event); break; } } void _updateAfterIsolateReload(Event reloadEvent) async { // Generally this has the value 'success'; we update our data in any case. // ignore: unused_local_variable final status = reloadEvent.status; final theIsolateRef = _isolate.value; if (theIsolateRef == null) return; // Refresh the list of scripts. final previousScriptRefs = scriptManager.sortedScripts.value; final currentScriptRefs = await scriptManager.retrieveAndSortScripts(theIsolateRef); final removedScripts = Set.of(previousScriptRefs).difference(Set.of(currentScriptRefs)); final addedScripts = Set.of(currentScriptRefs).difference(Set.of(previousScriptRefs)); // TODO(devoncarew): Show a message in the logging view. // Show a toast. final count = removedScripts.length + addedScripts.length; messageBus.addEvent( BusEvent( 'toast', data: '${nf.format(count)} ${pluralize('script', count)} updated.', ), ); // Redirect the current editor screen if necessary. if (removedScripts.contains(codeViewController.currentScriptRef.value)) { final uri = codeViewController.currentScriptRef.value!.uri; final newScriptRef = addedScripts.firstWhereOrNull((script) => script.uri == uri); if (newScriptRef != null) { // Display the script location. _populateScriptAndShowLocation(newScriptRef); } } } /// Jump to the given script. /// /// This method ensures that the source for the script is populated in our /// cache, in order to reduce flashing in the editor view. void _populateScriptAndShowLocation(ScriptRef scriptRef) { unawaited( scriptManager.getScript(scriptRef).then((script) { codeViewController.showScriptLocation(ScriptLocation(scriptRef)); }), ); } final _hasTruncatedFrames = ValueNotifier<bool>(false); CancelableOperation<_StackInfo>? _getStackOperation; Future<void> _pause(bool paused, {Event? pauseEvent}) async { // TODO(jacobr): unify pause support with // serviceManager.isolateManager.selectedIsolateState.isPaused.value; // listening for changes there instead of having separate logic. await _getStackOperation?.cancel(); _debugTimingLog.log('_pause(running: ${!paused})'); // Perform an early exit if we're not paused. if (!paused) { await _populateFrameInfo([], truncated: false); return; } // Collecting frames for Dart web applications can be slow. At the potential // cost of a flicker in the stack view, display only the top frame // initially. // TODO(elliette): Find a better solution for this. Currently, this means // we fetch all variable objects twice (once in _getFullStack and once in // in_createStackFrameWithLocation). if (await serviceConnection.serviceManager.connectedApp!.isDartWebApp) { final topFrame = pauseEvent?.topFrame; if (topFrame == null) { _log.warning( 'Pause event has no frame. This likely indicates a DWDS bug.', ); await _populateFrameInfo( [ await _createStackFrameWithLocation( Frame( code: CodeRef( name: 'No Dart frames found, likely paused in JS.', kind: CodeKind.kTag, id: DateTime.now().microsecondsSinceEpoch.toString(), ), ), ), ], truncated: true, ); ga.select(gac.debugger, gac.pausedWithNoFrames); return; } await _populateFrameInfo( [ await _createStackFrameWithLocation(topFrame), ], truncated: true, ); unawaited(_getFullStack()); return; } // We populate the first 12 frames; this ~roughly corresponds to the number // of visible stack frames. const initialFrameRequestCount = 12; _getStackOperation = CancelableOperation.fromFuture( _getStackInfo( limit: initialFrameRequestCount, ), ); final stackInfo = await _getStackOperation!.value; await _populateFrameInfo( stackInfo.frames, truncated: stackInfo.truncated, ); // In the background, populate the rest of the frames. if (stackInfo.truncated) { unawaited(_getFullStack()); } } Future<_StackInfo> _getStackInfo({int? limit}) async { _debugTimingLog.log('getStack() with limit: $limit'); final stack = await _service.getStack(_isolateRefId, limit: limit); _debugTimingLog .log('getStack() completed (frames: ${stack.frames!.length})'); final frames = _framesForCallStack( stack.frames ?? [], asyncCausalFrames: stack.asyncCausalFrames ?? [], reportedException: _lastEvent?.exception, ); return _StackInfo( await Future.wait(frames.map(_createStackFrameWithLocation)), stack.truncated ?? false, ); } Future<void> _populateFrameInfo( List<StackFrameAndSourcePosition> frames, { required final bool truncated, }) async { _debugTimingLog.log('populated frame info'); _stackFramesWithLocation.value = frames; _hasTruncatedFrames.value = truncated; if (frames.isEmpty) { await selectStackFrame(null); } else { await selectStackFrame(frames.first); } } Future<void> _getFullStack() async { await _getStackOperation?.cancel(); _getStackOperation = CancelableOperation.fromFuture(_getStackInfo()); final stackInfo = await _getStackOperation!.value; await _populateFrameInfo(stackInfo.frames, truncated: stackInfo.truncated); } void _clearCaches({bool isServiceShutdown = false}) { _lastEvent = null; breakpointManager.clearCache(isServiceShutdown: isServiceShutdown); } Future<void> _populateScripts(Isolate isolate) async { final theIsolateRef = _isolate.value; if (theIsolateRef == null) return; final scriptRefs = await scriptManager.retrieveAndSortScripts(theIsolateRef); // Update the selected script. final mainScriptRef = scriptRefs.firstWhereOrNull((ref) { return ref.uri == isolate.rootLib?.uri; }); // Display the script location. if (mainScriptRef != null) { _populateScriptAndShowLocation(mainScriptRef); } } Future<StackFrameAndSourcePosition> _createStackFrameWithLocation( Frame frame, ) async { final scriptInfo = frame.location?.script; final tokenPos = frame.location?.tokenPos ?? -1; if (scriptInfo == null || tokenPos < 0) { return StackFrameAndSourcePosition(frame); } final script = await scriptManager.getScript(scriptInfo); final position = SourcePosition.calculatePosition(script, tokenPos); return StackFrameAndSourcePosition(frame, position: position); } Future<void> selectBreakpoint(BreakpointAndSourcePosition bp) async { _selectedBreakpoint.value = bp; final scriptRef = bp.scriptRef; if (scriptRef == null) return; if (bp.sourcePosition == null) { await codeViewController.showScriptLocation(ScriptLocation(scriptRef)); } else { await codeViewController.showScriptLocation( ScriptLocation(scriptRef, location: bp.sourcePosition), ); } } Future<void> selectStackFrame(StackFrameAndSourcePosition? frame) async { // Load the new script location: final scriptRef = frame?.scriptRef; final position = frame?.position; if (scriptRef != null && position != null) { await codeViewController.showScriptLocation( ScriptLocation(scriptRef, location: position), ); } // Update the variables for the stack frame: if (FeatureFlags.dapDebugging) { serviceConnection.appState.setDapVariables( frame != null ? await _createDapVariablesForFrame(frame.frame) : [], ); } else { serviceConnection.appState.setVariables( frame != null ? _createVariablesForFrame(frame.frame) : [], ); } // Notify that the stack frame has been successfully selected: _selectedStackFrame.value = frame; } List<DartObjectNode> _createVariablesForFrame(Frame frame) { // vars can be null for async frames. if (frame.vars == null) { return []; } final variables = frame.vars! .map( (v) => DartObjectNode.create( v, _isolate.value, ), ) .toList(); // TODO(jacobr): would be nice to be able to remove this call to unawaited // but it would require a significant refactor. variables ..forEach((v) => unawaited(buildVariablesTree(v))) ..sort((a, b) => sortFieldsByName(a.name!, b.name!)); return variables; } Future<List<DapObjectNode>> _createDapVariablesForFrame(Frame frame) async { // TODO(https://github.com/flutter/devtools/issues/6056): Use DAP for all // frames instead of translating between the current VM service frame and // the corresponding DAP frame. final dapFrame = await _fetchDapFrame(frame); final frameId = dapFrame?.id; if (frameId == null) return []; final dapObjectNodes = <DapObjectNode>[]; final scopes = await _fetchDapScopes(frameId); for (final scope in scopes) { final variables = await _fetchDapVariables(scope.variablesReference); for (final variable in variables) { final node = DapObjectNode(variable: variable, service: _service); await node.fetchChildren(); dapObjectNodes.add(node); } } return dapObjectNodes; } Future<dap.StackFrame?> _fetchDapFrame(Frame vmFrame) async { final isolateNumber = serviceConnection .serviceManager.isolateManager.selectedIsolate.value?.number; final frameIndex = vmFrame.index; if (isolateNumber == null || frameIndex == null) return null; final stackTraceResponse = await _service.dapStackTraceRequest( dap.StackTraceArguments( // The DAP thread ID is equivalent to the VM isolate number. See: // https://github.com/dart-lang/sdk/commit/95e6f1e1107ac3f494ca3dc97ffd12cf261313a9 threadId: int.parse(isolateNumber), startFrame: frameIndex, levels: 1, // The number of frames to return. ), ); return stackTraceResponse?.stackFrames.first; } Future<List<dap.Scope>> _fetchDapScopes(int frameId) async { final scopesResponse = await _service.dapScopesRequest( dap.ScopesArguments( frameId: frameId, ), ); return scopesResponse?.scopes ?? []; } Future<List<dap.Variable>> _fetchDapVariables(int variablesReference) async { final variablesResponse = await _service.dapVariablesRequest( dap.VariablesArguments( variablesReference: variablesReference, ), ); return variablesResponse?.variables ?? []; } List<Frame> _framesForCallStack( List<Frame> stackFrames, { List<Frame>? asyncCausalFrames, InstanceRef? reportedException, }) { // Prefer asyncCausalFrames if they exist. List<Frame> frames = asyncCausalFrames != null && asyncCausalFrames.isNotEmpty ? asyncCausalFrames : stackFrames; // Include any reported exception as a variable in the first frame. if (reportedException != null && frames.isNotEmpty) { final frame = frames.first; final newFrame = Frame( index: frame.index, function: frame.function, code: frame.code, location: frame.location, kind: frame.kind, ); newFrame.vars = [ BoundVariable( name: '<exception>', value: reportedException, ), ...frame.vars ?? [], ]; frames = [newFrame, ...frames.sublist(1)]; } return frames; } } class _StackInfo { _StackInfo(this.frames, this.truncated); final List<StackFrameAndSourcePosition> frames; final bool truncated; }
devtools/packages/devtools_app/lib/src/screens/debugger/debugger_controller.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/debugger/debugger_controller.dart", "repo_id": "devtools", "token_count": 7894 }
80
// 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/analytics/analytics.dart' as ga; import '../../shared/analytics/constants.dart' as gac; import '../../shared/directory_picker.dart'; import '../../shared/server/server.dart' as server; import '../../shared/utils.dart'; import 'deep_links_controller.dart'; import 'deep_links_model.dart'; const _kLinearProgressIndicatorWidth = 280.0; /// A view for selecting a Flutter project. class SelectProjectView extends StatefulWidget { const SelectProjectView({super.key}); @override State<SelectProjectView> createState() => _SelectProjectViewState(); } class _SelectProjectViewState extends State<SelectProjectView> with ProvidedControllerMixin<DeepLinksController, SelectProjectView> { bool _retrievingFlutterProject = false; @override void didChangeDependencies() { super.didChangeDependencies(); if (!initController()) return; callWhenControllerReady((_) async { final packageDirectoryForMainIsolate = await controller.packageDirectoryForMainIsolate(); if (packageDirectoryForMainIsolate != null) { _handleDirectoryPicked(packageDirectoryForMainIsolate); } }); } void _handleDirectoryPicked(String directory) async { setState(() { _retrievingFlutterProject = true; }); ga.timeStart(gac.deeplink, gac.AnalyzeFlutterProject.loadVariants.name); final List<String> androidVariants = await server.requestAndroidBuildVariants(directory); if (!mounted) { ga.cancelTimingOperation( gac.deeplink, gac.AnalyzeFlutterProject.loadVariants.name, ); return; } if (androidVariants.isEmpty) { ga.cancelTimingOperation( gac.deeplink, gac.AnalyzeFlutterProject.loadVariants.name, ); await showDialog( context: context, builder: (_) { return const AlertDialog( title: Text('You selected a non Flutter project'), content: Text( 'Seems you selected a non Flutter project. If it is not intended, please reselect a Flutter project.', ), actions: [ DialogCloseButton(), ], ); }, ); } else { ga.timeEnd(gac.deeplink, gac.AnalyzeFlutterProject.loadVariants.name); ga.select( gac.deeplink, gac.AnalyzeFlutterProject.flutterProjectSelected.name, ); controller.selectedProject.value = FlutterProject(path: directory, androidVariants: androidVariants); } setState(() { _retrievingFlutterProject = false; }); } @override Widget build(BuildContext context) { final theme = Theme.of(context); if (_retrievingFlutterProject) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Project loading...', style: theme.regularTextStyle, ), Container( width: _kLinearProgressIndicatorWidth, padding: const EdgeInsets.symmetric(vertical: densePadding), child: const LinearProgressIndicator(), ), Text( 'The first load will take longer than usual', style: theme.subtleTextStyle, ), ], ), ); } return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(defaultSpacing), child: Text( 'Pick a local flutter project to check the status of all deep links.', textAlign: TextAlign.center, style: theme.textTheme.titleSmall, ), ), DirectoryPicker( onDirectoryPicked: _handleDirectoryPicked, enabled: !_retrievingFlutterProject, ), ], ); } }
devtools/packages/devtools_app/lib/src/screens/deep_link_validation/select_project_view.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/deep_link_validation/select_project_view.dart", "repo_id": "devtools", "token_count": 1755 }
81
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui; import 'package:flutter/rendering.dart'; import '../../inspector_data_models.dart'; /// CustomPainter for drawing [DebugOverflowIndicatorMixin]'s patterned background. /// Draws overflow pattern on the [OverflowSide] of the widget. /// /// [DebugOverflowIndicatorMixin] can not be reused here /// because it is a mixin on RenderObject and requires real overflows on the widget. /// /// If [side] is set to [OverflowSide.right], /// the pattern will occupy the whole height /// and the width will be the given [size]. /// /// If [side] is set to [OverflowSide.bottom], /// the pattern will occupy the whole width /// and the height will be the given [size]. /// /// See also: /// * [DebugOverflowIndicatorMixin] class OverflowIndicatorPainter extends CustomPainter { const OverflowIndicatorPainter(this.side, this.size); final OverflowSide side; final double size; /// These static variables are taken from [DebugOverflowIndicatorMixin] /// since all of them are private. static const Color black = Color(0xBF000000); static const Color yellow = Color(0xBFFFFF00); static final Paint indicatorPaint = Paint() ..shader = ui.Gradient.linear( const Offset(0.0, 0.0), const Offset(10.0, 10.0), <Color>[black, yellow, yellow, black], <double>[0.25, 0.25, 0.75, 0.75], TileMode.repeated, ); @override void paint(Canvas canvas, Size size) { final bottomOverflow = OverflowSide.bottom == side; final width = bottomOverflow ? size.width : this.size; final height = !bottomOverflow ? size.height : this.size; final left = bottomOverflow ? 0.0 : size.width - width; final top = side == OverflowSide.right ? 0.0 : size.height - height; final rect = Rect.fromLTWH(left, top, width, height); canvas.drawRect(rect, indicatorPaint); } @override bool shouldRepaint(CustomPainter oldDelegate) { return oldDelegate is OverflowIndicatorPainter && (side != oldDelegate.side || size != oldDelegate.size); } }
devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/overflow_indicator_painter.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/layout_explorer/ui/overflow_indicator_painter.dart", "repo_id": "devtools", "token_count": 711 }
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 'dart:async'; import 'dart:math' as math; import 'package:devtools_shared/devtools_shared.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart'; import '../../../../shared/globals.dart'; import '../../../../shared/utils.dart'; import '../../shared/primitives/memory_timeline.dart'; import 'memory_controller.dart'; final _log = Logger('memory_protocol'); class MemoryTracker { MemoryTracker(this.memoryController); final MemoryController memoryController; Timer? _pollingTimer; final isolateHeaps = <String, MemoryUsage>{}; /// Polled VM current RSS. int processRss = 0; /// Polled adb dumpsys meminfo values. AdbMemoryInfo? adbMemoryInfo; /// Polled engine's RasterCache estimates. RasterCache? rasterCache; Stream<void> get onChange => _changeController.stream; final _changeController = StreamController<void>.broadcast(); StreamSubscription<Event>? _gcStreamListener; Timer? _monitorContinues; void start() { _updateLiveDataPolling(); memoryController.paused.addListener(_updateLiveDataPolling); } void _updateLiveDataPolling() { if (serviceConnection.serviceManager.service == null) { // A service of null implies we're disconnected - signal paused. memoryController.pauseLiveFeed(); } _pollingTimer ??= Timer(MemoryTimeline.updateDelay, _pollMemory); _gcStreamListener ??= serviceConnection.serviceManager.service?.onGCEvent .listen(_handleGCEvent); } void stop() { _updateLiveDataPolling(); _cleanListenersAndTimers(); } void _cleanListenersAndTimers() { memoryController.paused.removeListener(_updateLiveDataPolling); _pollingTimer?.cancel(); unawaited(_gcStreamListener?.cancel()); _pollingTimer = null; _gcStreamListener = null; } void _handleGCEvent(Event event) { final HeapSpace newHeap = HeapSpace.parse(event.json!['new'])!; final HeapSpace oldHeap = HeapSpace.parse(event.json!['old'])!; final MemoryUsage memoryUsage = MemoryUsage( externalUsage: newHeap.external! + oldHeap.external!, heapCapacity: newHeap.capacity! + oldHeap.capacity!, heapUsage: newHeap.used! + oldHeap.used!, ); _updateGCEvent(event.isolate!.id!, memoryUsage); } void _pollMemory() async { _pollingTimer = null; if (!serviceConnection.serviceManager.hasConnection || memoryController.memoryTracker == null) { _log.info('VM service connection and/or MemoryTracker lost.'); return; } final isolateMemory = <IsolateRef, MemoryUsage>{}; for (IsolateRef isolateRef in serviceConnection.serviceManager.isolateManager.isolates.value) { if (await memoryController.isIsolateLive(isolateRef.id!)) { isolateMemory[isolateRef] = await serviceConnection .serviceManager.service! .getMemoryUsage(isolateRef.id!); } } // Polls for current Android meminfo using: // > adb shell dumpsys meminfo -d <package_name> adbMemoryInfo = serviceConnection.serviceManager.hasConnection && serviceConnection.serviceManager.vm!.operatingSystem == 'android' && memoryController.isAndroidChartVisibleNotifier.value ? await _fetchAdbInfo() : AdbMemoryInfo.empty(); // Query the engine's rasterCache estimate. rasterCache = await _fetchRasterCacheInfo(); // Polls for current RSS size. final vm = await serviceConnection.serviceManager.service!.getVM(); _update(vm, isolateMemory); // TODO(terry): Is there a better way to detect an integration test running? if (vm.json!.containsKey('_FAKE_VM')) return; _pollingTimer ??= Timer(MemoryTimeline.updateDelay, _pollMemory); } void _update(VM vm, Map<IsolateRef, MemoryUsage> isolateMemory) { processRss = vm.json!['_currentRSS']; isolateHeaps.clear(); for (IsolateRef isolateRef in isolateMemory.keys) { isolateHeaps[isolateRef.id!] = isolateMemory[isolateRef]!; } _recalculate(); } void _updateGCEvent(String isolateId, MemoryUsage memoryUsage) { isolateHeaps[isolateId] = memoryUsage; _recalculate(true); } /// Fetch the Fultter engine's Raster Cache metrics. /// /// Returns engine's rasterCache estimates or null. Future<RasterCache?> _fetchRasterCacheInfo() async { final response = await serviceConnection.rasterCacheMetrics; if (response == null) return null; final rasterCache = RasterCache.parse(response.json); return rasterCache; } /// Fetch ADB meminfo, ADB returns values in KB convert to total bytes. Future<AdbMemoryInfo> _fetchAdbInfo() async => AdbMemoryInfo.fromJsonInKB( (await serviceConnection.adbMemoryInfo).json!, ); /// Returns the MemoryUsage of a particular isolate. /// /// `id`: id for the isolate /// `usage`: usage associated with the passed in isolate's id. /// /// Returns the MemoryUsage of the isolate or null if isolate is a sentinel. Future<MemoryUsage?> _isolateMemoryUsage( String id, MemoryUsage? usage, ) async => await memoryController.isIsolateLive(id) ? usage : null; void _recalculate([bool fromGC = false]) async { int used = 0; int capacity = 0; int external = 0; final keysToRemove = <String>[]; final isolateCount = isolateHeaps.length; final keys = isolateHeaps.keys.toList(); for (var index = 0; index < isolateCount; index++) { final isolateId = keys[index]; var usage = isolateHeaps[isolateId]; // Check if the isolate is dead (sentinel), null implies sentinel. final checkIsolateUsage = await _isolateMemoryUsage(isolateId, usage); if (checkIsolateUsage == null && !keysToRemove.contains(isolateId)) { // Sentinel Isolate don't include in the heap computation. keysToRemove.add(isolateId); // Don't use this sential isolate for any heap computation. usage = null; } if (usage != null) { // Isolate is live (a null usage implies sentinel). used += usage.heapUsage!; capacity += usage.heapCapacity!; external += usage.externalUsage!; } } // Removes any isolate that is a sentinel. isolateHeaps.removeWhere((key, value) => keysToRemove.contains(key)); final memoryTimeline = memoryController.controllers.memoryTimeline; int time = DateTime.now().millisecondsSinceEpoch; if (memoryTimeline.data.isNotEmpty) { time = math.max(time, memoryTimeline.data.last.timestamp); } // Process any memory events? final eventSample = processEventSample(memoryTimeline, time); if (eventSample != null && eventSample.isEventAllocationAccumulator) { if (eventSample.allocationAccumulator!.isStart) { // Stop Continuous events being auto posted - a new start is beginning. memoryTimeline.monitorContinuesState = ContinuesState.stop; } } else if (memoryTimeline.monitorContinuesState == ContinuesState.next) { if (_monitorContinues != null) { _monitorContinues!.cancel(); _monitorContinues = null; } _monitorContinues ??= Timer( const Duration(milliseconds: 300), _recalculate, ); } final HeapSample sample = HeapSample( time, processRss, // Displaying capacity dashed line on top of stacked (used + external). capacity + external, used, external, fromGC, adbMemoryInfo, eventSample, rasterCache, ); memoryTimeline.addSample(sample); _changeController.add(null); // Signal continues events are to be emitted. These events are hidden // until a reset event then the continuous events between last monitor // start/reset and latest reset are made visible. if (eventSample != null && eventSample.isEventAllocationAccumulator && eventSample.allocationAccumulator!.isStart) { memoryTimeline.monitorContinuesState = ContinuesState.next; } } /// Many extension events could arrive between memory collection ticks, those /// events need to be associated with a particular memory tick (timestamp). /// /// This routine collects those new events received that are closest to a tick /// (time parameter)). /// /// Returns copy of events to associate with an existing HeapSample tick /// (contained in the EventSample). See [processEventSample] it computes the /// events to aggregate to an existing HeapSample or delay associating those /// events until the next HeapSample (tick) received see [_recalculate]. EventSample pullClone(MemoryTimeline memoryTimeline, int time) { final pulledEvent = memoryTimeline.pullEventSample(); final extensionEvents = memoryTimeline.extensionEvents; final eventSample = pulledEvent.clone( time, extensionEvents: extensionEvents, ); if (extensionEvents?.isNotEmpty == true) { debugLogger('ExtensionEvents Received'); } return eventSample; } EventSample? processEventSample(MemoryTimeline memoryTimeline, int time) { if (memoryTimeline.anyEvents) { final eventTime = memoryTimeline.peekEventTimestamp; final timeDuration = Duration(milliseconds: time); final eventDuration = Duration(milliseconds: eventTime); // If the event is +/- _updateDelay (500 ms) of the current time then // associate the EventSample with the current HeapSample. const delay = MemoryTimeline.updateDelay; final compared = timeDuration.compareTo(eventDuration); if (compared < 0) { if ((timeDuration + delay).compareTo(eventDuration) >= 0) { // Currently, events are all UI events so duration < _updateDelay return pullClone(memoryTimeline, time); } // Throw away event, missed attempt to attach to a HeapSample. final ignoreEvent = memoryTimeline.pullEventSample(); _log.info( 'Event duration is lagging ignore event' 'timestamp: ${MemoryTimeline.fineGrainTimestampFormat(time)} ' 'event: ${MemoryTimeline.fineGrainTimestampFormat(eventTime)}' '\n$ignoreEvent', ); return null; } if (compared > 0) { final msDiff = time - eventTime; if (msDiff > MemoryTimeline.delayMs) { // eventSample is in the future. if ((timeDuration - delay).compareTo(eventDuration) >= 0) { // Able to match event time to a heap sample. We will attach the // EventSample to this HeapSample. return pullClone(memoryTimeline, time); } // Keep the event, its time hasn't caught up to the HeapSample time yet. return null; } // The almost exact eventSample we have. return pullClone(memoryTimeline, time); } } if (memoryTimeline.anyPendingExtensionEvents) { final extensionEvents = memoryTimeline.extensionEvents; return EventSample.extensionEvent(time, extensionEvents); } return null; } void dispose() { _cleanListenersAndTimers(); } }
devtools/packages/devtools_app/lib/src/screens/memory/framework/connected/memory_protocol.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/framework/connected/memory_protocol.dart", "repo_id": "devtools", "token_count": 3956 }
83
// 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 '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/common_widgets.dart'; import '../../../../shared/globals.dart'; import '../../shared/primitives/simple_elements.dart'; class PrimaryControls extends StatelessWidget { const PrimaryControls({ Key? key, }) : super(key: key); @visibleForTesting static const memoryChartText = 'Memory chart'; @override Widget build(BuildContext context) { return VisibilityButton( show: preferences.memory.showChart, gaScreen: gac.memory, onPressed: (show) => preferences.memory.showChart.value = show, minScreenWidthForTextBeforeScaling: memoryControlsMinVerboseWidth, label: memoryChartText, tooltip: 'Toggle visibility of the Memory usage chart', ); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/control/primary_controls.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/control/primary_controls.dart", "repo_id": "devtools", "token_count": 326 }
84
// 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/memory/simple_items.dart'; import '../../../../../shared/primitives/byte_utils.dart'; import '../../../shared/primitives/simple_elements.dart'; import '../controller/diff_pane_controller.dart'; import '../controller/item_controller.dart'; class SnapshotControlPane extends StatelessWidget { const SnapshotControlPane({Key? key, required this.controller}) : super(key: key); final DiffPaneController controller; @override Widget build(BuildContext context) { final current = controller.core.selectedItem as SnapshotInstanceItem; final heapIsReady = current.heap != null; if (heapIsReady) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ _DiffDropdown( current: current, controller: controller, ), const SizedBox(width: defaultSpacing), DownloadButton( tooltip: 'Download data in CSV format', label: 'CSV', minScreenWidthForTextBeforeScaling: memoryControlsMinVerboseWidth, gaScreen: gac.memory, gaSelection: gac.MemoryEvent.diffSnapshotDownloadCsv, onPressed: controller.downloadCurrentItemToCsv, ), ], ), Expanded( child: _SnapshotSizeView( footprint: current.heap!.footprint, ), ), ], ); } return const SizedBox.shrink(); } } class _DiffDropdown extends StatelessWidget { _DiffDropdown({ Key? key, required this.current, required this.controller, }) : super(key: key) { final list = controller.core.snapshots.value; final diffWith = current.diffWith.value; // Check if diffWith was deleted from list. if (diffWith != null && !list.contains(diffWith)) { current.diffWith.value = null; } } final SnapshotInstanceItem current; final DiffPaneController controller; List<DropdownMenuItem<SnapshotInstanceItem>> items() => controller.core.snapshots.value .where((item) => item.hasData) .cast<SnapshotInstanceItem>() .map( (item) { return DropdownMenuItem<SnapshotInstanceItem>( value: item, child: Text(item == current ? '-' : item.name), ); }, ).toList(); @override Widget build(BuildContext context) { return ValueListenableBuilder<SnapshotInstanceItem?>( valueListenable: current.diffWith, builder: (_, diffWith, __) => Row( children: [ const Text('Diff with:'), const SizedBox(width: defaultSpacing), RoundedDropDownButton<SnapshotInstanceItem>( isDense: true, value: current.diffWith.value ?? current, onChanged: (SnapshotInstanceItem? value) { late SnapshotInstanceItem? newDiffWith; if ((value ?? current) == current) { ga.select( gac.memory, gac.MemoryEvent.diffSnapshotDiffOff, ); newDiffWith = null; } else { ga.select( gac.memory, gac.MemoryEvent.diffSnapshotDiffSelect, ); newDiffWith = value; } controller.setDiffing(current, newDiffWith); }, items: items(), ), ], ), ); } } class _SnapshotSizeView extends StatelessWidget { const _SnapshotSizeView({Key? key, required this.footprint}) : super(key: key); final MemoryFootprint footprint; @override Widget build(BuildContext context) { final items = <String, int>{ 'Dart Heap': footprint.dart, 'Reachable': footprint.reachable, }; return Text( items.entries .map<String>( (e) => '${e.key}: ' '${prettyPrintBytes(e.value, includeUnit: true, kbFractionDigits: 0)}', ) // TODO(polina-c): consider using vertical divider instead of text. .join(' | '), overflow: TextOverflow.ellipsis, textAlign: TextAlign.right, ); } }
devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/snapshot_control_pane.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/panes/diff/widgets/snapshot_control_pane.dart", "repo_id": "devtools", "token_count": 2131 }
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:file_selector/file_selector.dart'; import 'package:vm_service/vm_service.dart'; import '../../../../shared/analytics/analytics.dart' as ga; import '../../../../shared/analytics/constants.dart' as gac; import '../../../../shared/analytics/metrics.dart'; import '../../../../shared/memory/adapted_heap_data.dart'; import '../primitives/memory_timeline.dart'; import '../primitives/memory_utils.dart'; abstract class SnapshotTaker { Future<AdaptedHeapData?> take(); } /// This class is needed to make the snapshot taking operation mockable. class SnapshotTakerRuntime extends SnapshotTaker { SnapshotTakerRuntime(this._timeline); final MemoryTimeline? _timeline; @override Future<AdaptedHeapData?> take() async { final snapshot = await snapshotMemoryInSelectedIsolate(); _timeline?.addSnapshotEvent(); if (snapshot == null) return null; final result = await _adaptSnapshotGaWrapper(snapshot); return result; } } class SnapshotTakerFromFile implements SnapshotTaker { SnapshotTakerFromFile(this._file); final XFile _file; @override Future<AdaptedHeapData?> take() async { final bytes = await _file.readAsBytes(); return AdaptedHeapData.fromBytes(bytes); } } Future<AdaptedHeapData> _adaptSnapshotGaWrapper(HeapSnapshotGraph graph) async { late final AdaptedHeapData result; await ga.timeAsync( gac.memory, gac.MemoryTime.adaptSnapshot, asyncOperation: () async => result = await AdaptedHeapData.fromHeapSnapshot(graph), screenMetricsProvider: () => MemoryScreenMetrics( heapObjectsTotal: graph.objects.length, ), ); return result; }
devtools/packages/devtools_app/lib/src/screens/memory/shared/heap/model.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/memory/shared/heap/model.dart", "repo_id": "devtools", "token_count": 606 }
86
## Timeline Code Architecture <img src="timeline_architecture.png" width="800" /> ### View The view has no awareness of the timeline data directly. It has access to the timeline data (frames, selected event, selected frame, cpu profile, etc.) through the `TimelineController`. The view receives updates from the `TimelineController` via streams. ### Model `TimelineData` stores the current data for the DevTools timeline. Its main components include `frames`, `selectedFrame`, `selectedEvent`, `cpuProfileData`, and `traceEvents`. This data is maintained by `TimelineController`. ### Controller The controller manages `TimelineData` and communicates with the view to give and receive data updates. It manages data processing via protocols `TimelineProtocol` (protocol for processing trace events and composing them into `TimelineEvent`s and `TimelineFrame`s) and `CpuProfileProtocol` (protocol for processing `CpuProfileData` and composing it into a structured tree of `CpuStackFrame`s). The controller also communicates with `TimelineService`, which manages interactions between the Timeline and the VmService. `TimelineController` has no dependency on `dart:html`, making it easily testable.
devtools/packages/devtools_app/lib/src/screens/performance/README.md/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/README.md", "repo_id": "devtools", "token_count": 291 }
87
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../../../../shared/primitives/utils.dart'; class RasterStats { RasterStats._({ required this.layerSnapshots, required this.originalFrameSize, required this.totalRasterTime, required this.selectedSnapshot, }); factory RasterStats.parse(Map<String, Object?> json) { Size? originalFrameSize; final originalWidth = json[_frameWidthKey] as num?; final originalHeight = json[_frameHeightKey] as num?; if (originalHeight != null && originalWidth != null) { originalFrameSize = Size( originalWidth.toDouble(), originalHeight.toDouble(), ); } int? selectedId; LayerSnapshot? selected; if (json[_selectedIdKey] != null) { selectedId = json[_selectedIdKey] as int?; } final snapshotsFromJson = (json[_snapshotsJsonKey] as List).cast<Map<String, dynamic>>(); final snapshots = <LayerSnapshot>[]; var totalRasterTime = Duration.zero; for (final snapshotJson in snapshotsFromJson) { final layerSnapshot = LayerSnapshot.parse(snapshotJson); snapshots.add(layerSnapshot); totalRasterTime += layerSnapshot.duration; if (layerSnapshot.id == selectedId) { selected = layerSnapshot; } } for (final snapshot in snapshots) { snapshot.totalRenderingDuration = totalRasterTime; } // Sort by percent rendering time in descending order. snapshots.sort( (a, b) => b.percentRenderingTimeAsDouble .compareTo(a.percentRenderingTimeAsDouble), ); selected ??= snapshots.safeFirst; return RasterStats._( layerSnapshots: snapshots, selectedSnapshot: selected, originalFrameSize: originalFrameSize, totalRasterTime: totalRasterTime, ); } static const _snapshotsJsonKey = 'snapshots'; static const _selectedIdKey = 'selectedId'; static const _frameWidthKey = 'frame_width'; static const _frameHeightKey = 'frame_height'; final List<LayerSnapshot> layerSnapshots; final Size? originalFrameSize; final Duration totalRasterTime; /// The selected snapshot for this set of raster stats data. /// /// This field is mutable, and is managed by the [RasterStatsController]. It /// is included in [RasterStats] so that it can be encoded in and decoded from /// json. LayerSnapshot? selectedSnapshot; Map<String, dynamic> get json => { _frameWidthKey: originalFrameSize?.width.toDouble(), _frameHeightKey: originalFrameSize?.height.toDouble(), _snapshotsJsonKey: layerSnapshots .map((snapshot) => snapshot.json) .toList(growable: false), _selectedIdKey: selectedSnapshot?.id, }; } class LayerSnapshot { LayerSnapshot({ required this.id, required this.duration, required this.size, required this.offset, required this.bytes, }); factory LayerSnapshot.parse(Map<String, Object?> json) { final id = json[_layerIdKey] as int; final dur = Duration(microseconds: json[_durationKey] as int); final size = Size( (json[_widthKey] as num).toDouble(), (json[_heightKey] as num).toDouble(), ); final offset = Offset( (json[_leftKey] as num).toDouble(), (json[_topKey] as num).toDouble(), ); final imageBytes = Uint8List.fromList( (json[_snapshotJsonKey] as List<Object?>).cast<int>(), ); return LayerSnapshot( id: id, duration: dur, size: size, offset: offset, bytes: imageBytes, ); } static const _layerIdKey = 'layer_unique_id'; static const _durationKey = 'duration_micros'; static const _snapshotJsonKey = 'snapshot'; static const _widthKey = 'width'; static const _heightKey = 'height'; static const _leftKey = 'left'; static const _topKey = 'top'; final int id; final Duration duration; final Size size; final Offset offset; final Uint8List bytes; /// The total rendering time for the set of snapshots that this /// [LayerSnapshot] is a part of. /// /// This will be set after this [LayerSnapshot] is created, once all the /// [LayerSnapshot]s in a set have been processed. Duration? totalRenderingDuration; double get percentRenderingTimeAsDouble => duration.inMicroseconds / totalRenderingDuration!.inMicroseconds; String get percentRenderingTimeDisplay => percent(percentRenderingTimeAsDouble); String get displayName => 'Layer $id'; Map<String, Object?> get json => { _layerIdKey: id, _durationKey: duration.inMicroseconds, _widthKey: size.width, _heightKey: size.height, _leftKey: offset.dx, _topKey: offset.dy, _snapshotJsonKey: bytes, }; }
devtools/packages/devtools_app/lib/src/screens/performance/panes/raster_stats/raster_stats_model.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/panes/raster_stats/raster_stats_model.dart", "repo_id": "devtools", "token_count": 1767 }
88
// 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 '../../shared/globals.dart'; const preCompileShadersDocsUrl = 'https://docs.flutter.dev/perf/shader'; const impellerDocsUrl = 'https://docs.flutter.dev/perf/impeller'; void pushNoTimelineEventsAvailableWarning() { notificationService.push( 'No timeline events available for the selected frame. Timeline ' 'events occurred too long ago before DevTools could access them. ' 'To avoid this, open the DevTools Performance page earlier.', ); }
devtools/packages/devtools_app/lib/src/screens/performance/performance_utils.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/performance/performance_utils.dart", "repo_id": "devtools", "token_count": 186 }
89
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 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/profiler_utils.dart'; import '../../../../shared/table/table.dart'; import '../../../../shared/table/table_data.dart'; import 'method_table_controller.dart'; import 'method_table_model.dart'; final _methodColumnMinWidth = scaleByFontFactor(800.0); /// Widget that displays a method table for a CPU profile. class CpuMethodTable extends StatelessWidget { const CpuMethodTable({super.key, required this.methodTableController}); final MethodTableController methodTableController; @override Widget build(BuildContext context) { return ValueListenableBuilder<List<MethodTableGraphNode>>( valueListenable: methodTableController.methods, builder: (context, methods, _) { return SplitPane( axis: Axis.horizontal, initialFractions: const [0.5, 0.5], children: [ MethodTable(methodTableController, methods), _MethodGraph(methodTableController), ], ); }, ); } } // TODO(kenz): ensure that this table automatically scrolls to the selected // node from [MethodTableController]. /// A table of methods and their timing information for a CPU profile. @visibleForTesting class MethodTable extends StatelessWidget { const MethodTable(this._methodTableController, this._methods, {super.key}); static final methodColumn = _MethodColumn(); static final selfTimeColumn = _SelfTimeColumn(); static final totalTimeColumn = _TotalTimeColumn(); static final columns = List<ColumnData<MethodTableGraphNode>>.unmodifiable([ totalTimeColumn, selfTimeColumn, methodColumn, ]); final MethodTableController _methodTableController; final List<MethodTableGraphNode> _methods; @override Widget build(BuildContext context) { return OutlineDecoration.onlyRight( child: SearchableFlatTable<MethodTableGraphNode>( searchController: _methodTableController, keyFactory: (node) => ValueKey(node.id), data: _methods, dataKey: 'cpu-profile-methods', columns: columns, defaultSortColumn: totalTimeColumn, defaultSortDirection: SortDirection.descending, sortOriginalData: true, selectionNotifier: _methodTableController.selectedNode, sizeColumnsToFit: false, ), ); } } /// A graph for a single method that shows its predecessors (callers) and /// successors (callees) as well as timing information for each of those nodes. class _MethodGraph extends StatefulWidget { const _MethodGraph(this.methodTableController); final MethodTableController methodTableController; @override State<_MethodGraph> createState() => _MethodGraphState(); } class _MethodGraphState extends State<_MethodGraph> with AutoDisposeMixin { MethodTableGraphNode? _selectedGraphNode; List<MethodTableGraphNode> _callers = []; List<MethodTableGraphNode> _callees = []; @override void initState() { super.initState(); _initGraphNodes(); addAutoDisposeListener(widget.methodTableController.selectedNode, () { setState(() { _initGraphNodes(); }); }); } void _initGraphNodes() { _selectedGraphNode = widget.methodTableController.selectedNode.value; if (_selectedGraphNode == null) { _callers = <MethodTableGraphNode>[]; _callees = <MethodTableGraphNode>[]; } else { _callers = _selectedGraphNode!.predecessors .cast<MethodTableGraphNode>() .toList(); _callees = _selectedGraphNode!.successors.cast<MethodTableGraphNode>().toList(); } } @override Widget build(BuildContext context) { final selectedNode = _selectedGraphNode; if (selectedNode == null) { return OutlineDecoration.onlyLeft( child: const Center( child: Text('Select a method to view its call graph.'), ), ); } final selectedNodeDisplay = selectedNode.display; return OutlineDecoration.onlyLeft( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Flexible( child: OutlineDecoration.onlyBottom( child: _CallersTable( widget.methodTableController, _callers, ), ), ), DevToolsTooltip( message: selectedNodeDisplay, child: Padding( padding: const EdgeInsets.symmetric( horizontal: denseSpacing, vertical: densePadding, ), child: MethodAndSourceDisplay( methodName: selectedNode.name, packageUri: selectedNode.packageUri, sourceLine: selectedNode.sourceLine, displayInRow: false, ), ), ), Flexible( child: OutlineDecoration.onlyTop( child: _CalleesTable( widget.methodTableController, _callees, ), ), ), ], ), ); } } /// A table of predecessors (callers) for a single method in a method table. class _CallersTable extends StatelessWidget { _CallersTable(this._methodTableController, this._callers) { _callerTimeColumn = _CallerTimeColumn(methodTableController: _methodTableController); columns = List<ColumnData<MethodTableGraphNode>>.unmodifiable([ _callerTimeColumn, methodColumn, ]); } static final methodColumn = _MethodColumn(); final MethodTableController _methodTableController; final List<MethodTableGraphNode> _callers; late final List<ColumnData<MethodTableGraphNode>> columns; late final _CallerTimeColumn _callerTimeColumn; @override Widget build(BuildContext context) { return FlatTable<MethodTableGraphNode>( keyFactory: (node) => ValueKey('caller-${node.id}'), data: _callers, dataKey: 'cpu-profile-method-callers', columns: columns, defaultSortColumn: _callerTimeColumn, defaultSortDirection: SortDirection.descending, selectionNotifier: _methodTableController.selectedNode, sizeColumnsToFit: false, ); } } /// A table of successors (callees) for a single method in a method table. class _CalleesTable extends StatelessWidget { _CalleesTable(this._methodTableController, this._callees) { _calleeTimeColumn = _CalleeTimeColumn(methodTableController: _methodTableController); _columns = List<ColumnData<MethodTableGraphNode>>.unmodifiable([ _calleeTimeColumn, _methodColumn, ]); } static final _methodColumn = _MethodColumn(); final MethodTableController _methodTableController; final List<MethodTableGraphNode> _callees; late final List<ColumnData<MethodTableGraphNode>> _columns; late final _CalleeTimeColumn _calleeTimeColumn; @override Widget build(BuildContext context) { return FlatTable<MethodTableGraphNode>( keyFactory: (node) => ValueKey('callee-${node.id}'), data: _callees, dataKey: 'cpu-profile-method-callees', columns: _columns, defaultSortColumn: _calleeTimeColumn, defaultSortDirection: SortDirection.descending, selectionNotifier: _methodTableController.selectedNode, sizeColumnsToFit: false, ); } } class _MethodColumn extends ColumnData<MethodTableGraphNode> implements ColumnRenderer<MethodTableGraphNode> { _MethodColumn() : super.wide( 'Method', minWidthPx: _methodColumnMinWidth, ); @override bool get supportsSorting => true; @override String getValue(MethodTableGraphNode dataObject) => dataObject.name; @override String getDisplayValue(MethodTableGraphNode dataObject) => dataObject.display; @override String getTooltip(MethodTableGraphNode dataObject) => dataObject.display; @override Widget? build( BuildContext context, MethodTableGraphNode data, { bool isRowSelected = false, bool isRowHovered = false, VoidCallback? onPressed, }) { return MethodAndSourceDisplay( methodName: data.name, packageUri: data.packageUri, sourceLine: data.sourceLine, ); } } const _totalAndSelfColumnWidth = 60.0; const _callGraphColumnWidth = 70.0; class _SelfTimeColumn extends TimeAndPercentageColumn<MethodTableGraphNode> { _SelfTimeColumn({String? titleTooltip}) : super( title: 'Self %', titleTooltip: titleTooltip, percentageOnly: true, timeProvider: (node) => node.selfTime, percentAsDoubleProvider: (node) => node.selfTimeRatio, secondaryCompare: (node) => node.name, columnWidth: _totalAndSelfColumnWidth, ); } class _TotalTimeColumn extends TimeAndPercentageColumn<MethodTableGraphNode> { _TotalTimeColumn({String? titleTooltip}) : super( title: 'Total %', titleTooltip: titleTooltip, percentageOnly: true, timeProvider: (node) => node.totalTime, percentAsDoubleProvider: (node) => node.totalTimeRatio, secondaryCompare: (node) => node.name, columnWidth: _totalAndSelfColumnWidth, ); } class _CallerTimeColumn extends TimeAndPercentageColumn<MethodTableGraphNode> { _CallerTimeColumn({ required MethodTableController methodTableController, String? titleTooltip, }) : super( title: 'Caller %', titleTooltip: titleTooltip, percentageOnly: true, percentAsDoubleProvider: (node) => methodTableController.callerPercentageFor(node), secondaryCompare: (node) => node.name, columnWidth: _callGraphColumnWidth, ); } class _CalleeTimeColumn extends TimeAndPercentageColumn<MethodTableGraphNode> { _CalleeTimeColumn({ required MethodTableController methodTableController, String? titleTooltip, }) : super( title: 'Callee %', titleTooltip: titleTooltip, percentageOnly: true, percentAsDoubleProvider: (node) => methodTableController.calleePercentageFor(node), secondaryCompare: (node) => node.name, columnWidth: _callGraphColumnWidth, ); }
devtools/packages/devtools_app/lib/src/screens/profiler/panes/method_table/method_table.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/profiler/panes/method_table/method_table.dart", "repo_id": "devtools", "token_count": 3997 }
90
// 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/service.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:vm_service/vm_service.dart'; import 'instance_viewer/eval.dart'; @immutable class ProviderNode { const ProviderNode({ required this.id, required this.type, }); final String id; final String type; } final _providerListChanged = AutoDisposeStreamProvider<void>((ref) async* { final service = await ref.watch(serviceProvider.future); yield* service.onExtensionEvent.where((event) { return event.extensionKind == 'provider:provider_list_changed'; }); }); final _rawProviderIdsProvider = AutoDisposeFutureProvider<List<String>>( (ref) async { // recompute the list of providers on hot-restart ref.watch(hotRestartEventProvider); // cause the list of providers to be re-evaluated when notified of a change ref.watch(_providerListChanged); final isAlive = Disposable(); ref.onDispose(isAlive.dispose); final eval = await ref.watch(providerEvalProvider.future); final providerIdRefs = await eval.evalInstance( 'ProviderBinding.debugInstance.providerDetails.keys.toList()', isAlive: isAlive, ); final providerIdInstances = await Future.wait([ for (final idRef in providerIdRefs.elements!.cast<InstanceRef>()) eval.safeGetInstance(idRef, isAlive), ]); return [ for (final idInstance in providerIdInstances) idInstance.valueAsString!, ]; }, name: '_rawProviderIdsProvider', ); final _rawProviderNodeProvider = AutoDisposeFutureProviderFamily<ProviderNode, String>( (ref, id) async { // recompute the providers informations on hot-restart ref.watch(hotRestartEventProvider); final isAlive = Disposable(); ref.onDispose(isAlive.dispose); final eval = await ref.watch(providerEvalProvider.future); final providerNodeInstance = await eval.evalInstance( "ProviderBinding.debugInstance.providerDetails['$id']", isAlive: isAlive, ); Future<Instance> getFieldWithName(String name) { return eval.safeGetInstance( providerNodeInstance.fields! .firstWhere((e) => e.decl?.name == name) .value as InstanceRef, isAlive, ); } final type = await getFieldWithName('type'); return ProviderNode( id: id, type: type.valueAsString!, ); }, name: '_rawProviderNodeProvider', ); /// Combines [providerIdsProvider] with [providerNodeProvider] to obtain all /// the [ProviderNode]s at once, sorted alphabetically. final sortedProviderNodesProvider = AutoDisposeFutureProvider<List<ProviderNode>>((ref) async { final ids = await ref.watch(_rawProviderIdsProvider.future); final nodes = await Future.wait<ProviderNode>( ids.map((id) => ref.watch(_rawProviderNodeProvider(id).future)), ); return nodes.toList()..sort((a, b) => a.type.compareTo(b.type)); });
devtools/packages/devtools_app/lib/src/screens/provider/provider_nodes.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/provider/provider_nodes.dart", "repo_id": "devtools", "token_count": 1093 }
91
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:vm_service/vm_service.dart'; import '../vm_developer_common_widgets.dart'; import '../vm_service_private_extensions.dart'; import 'object_inspector_view_controller.dart'; import 'vm_object_model.dart'; /// A widget for the object inspector historyViewport, displaying information /// related to field objects in the Dart VM. class VmFieldDisplay extends StatelessWidget { const VmFieldDisplay({ super.key, required this.controller, required this.field, }); final ObjectInspectorViewController controller; final FieldObject field; @override Widget build(BuildContext context) { return ObjectInspectorCodeView( codeViewController: controller.codeViewController, script: field.scriptRef!, object: field.obj, child: VmObjectDisplayBasicLayout( controller: controller, object: field, generalDataRows: _fieldDataRows(field), ), ); } /// Generates a list of key-value pairs (map entries) containing the general /// information of the field object [field]. List<MapEntry<String, WidgetBuilder>> _fieldDataRows( FieldObject field, ) { final staticValue = field.obj.staticValue; return [ ...vmObjectGeneralDataRows( controller, field, ), selectableTextBuilderMapEntry( 'Observed types', _fieldObservedTypes(field), ), if (staticValue is InstanceRef) serviceObjectLinkBuilderMapEntry( controller: controller, key: 'Static Value', object: staticValue, ), ]; } /// Returns the observed types of a field object, including null. /// /// The observed types can be a single type (guardClassSingle), various types /// (guardClassDynamic), or a type that has not been observed yet /// (guardClassUnknown). String _fieldObservedTypes(FieldObject field) { String type; final kind = field.guardClassKind; switch (kind) { case GuardClassKind.single: type = field.guardClass!.name ?? '<Observed Type>'; break; case GuardClassKind.dynamic: type = GuardClassKind.dynamic.jsonValue(); break; case GuardClassKind.unknown: type = 'none'; break; default: type = 'Observed types not found'; } final nullable = field.guardNullable == null ? '' : _nullMessage(field.guardNullable!); return '$type$nullable'; } String _nullMessage(bool isNullable) => ' - null ${isNullable ? '' : 'not '}observed'; }
devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_field_display.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/object_inspector/vm_field_display.dart", "repo_id": "devtools", "token_count": 984 }
92
// 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: constant_identifier_names import 'package:flutter/widgets.dart'; import 'package:vm_service/vm_service.dart'; import '../../shared/globals.dart'; import '../../shared/primitives/utils.dart'; import '../memory/panes/profile/profile_view.dart'; /// NOTE: this file contains extensions to classes provided by /// `package:vm_service` in order to expose VM internal fields in a controlled /// fashion. Objects and extensions in this class should not be used in /// contexts where [PreferencesController.vmDeveloperModeEnabled] is not set to /// `true`. const _vmNameKey = '_vmName'; /// An extension on [VM] which allows for access to VM internal fields. extension VMPrivateViewExtension on VM { String get embedder => json!['_embedder']; String get profilerMode => json!['_profilerMode']; int get currentMemory => json!['_currentMemory']; int get currentRSS => json!['_currentRSS']; int get maxRSS => json!['_maxRSS']; int? get nativeZoneMemoryUsage => json!['_nativeZoneMemoryUsage']; } /// An extension on [Isolate] which allows for access to VM internal fields. extension IsolatePrivateViewExtension on Isolate { Map<String, dynamic>? get tagCounters => json!['_tagCounters']; int get dartHeapSize => newSpaceUsage + oldSpaceUsage; int get dartHeapCapacity => newSpaceCapacity + oldSpaceCapacity; int get newSpaceUsage => _newHeap['used'] as int; int get oldSpaceUsage => _oldHeap['used'] as int; int get newSpaceCapacity => _newHeap['capacity'] as int; int get oldSpaceCapacity => _oldHeap['capacity'] as int; Map<String, Object?> get _newHeap => (_heaps['new'] as Map).cast<String, Object?>(); Map<String, Object?> get _oldHeap => (_heaps['old'] as Map).cast<String, Object?>(); Map<String, Object?> get _heaps => (json!['_heaps'] as Map).cast<String, Object?>(); } /// An extension on [Class] which allows for access to VM internal fields. extension ClassPrivateViewExtension on Class { /// The internal name of the [Class]. String get vmName => json![_vmNameKey]; } /// An extension on [InboundReferences] which allows for access to /// VM internal fields. extension InboundReferenceExtension on InboundReferences { static const _referencesKey = 'references'; static const _parentWordOffsetKey = '_parentWordOffset'; int? parentWordOffset(int inboundReferenceIndex) { final references = (json![_referencesKey] as List?)?.cast<Object?>(); final inboundReference = (references?[inboundReferenceIndex] as Map?)?.cast<String, Object?>(); return inboundReference?[_parentWordOffsetKey] as int?; } } class HeapStats { const HeapStats({ required this.count, required this.size, required this.externalSize, }); const HeapStats.empty() : count = 0, size = 0, externalSize = 0; HeapStats.parse(List<int> stats) : count = stats[0], size = stats[1], externalSize = stats[2]; final int count; final int size; final int externalSize; } /// An extension on [ClassHeapStats] which allows for access to VM internal /// fields. extension ClassHeapStatsPrivateViewExtension on ClassHeapStats { static const _newSpaceKey = '_new'; static const _oldSpaceKey = '_old'; HeapStats get newSpace => json!.containsKey(_newSpaceKey) ? HeapStats.parse((json![_newSpaceKey] as List).cast<int>()) : const HeapStats.empty(); HeapStats get oldSpace => json!.containsKey(_oldSpaceKey) ? HeapStats.parse((json![_oldSpaceKey] as List).cast<int>()) : const HeapStats.empty(); } class GCStats { GCStats({ required this.heap, required this.usage, required this.capacity, required this.collections, required this.averageCollectionTime, }); factory GCStats.parse({ required String heap, required Map<String, dynamic> json, }) { final collections = json[collectionsKey] as int; return GCStats( heap: heap, usage: json[usedKey], capacity: json[capacityKey], collections: collections, averageCollectionTime: (json[timeKey] as num) * 1000 / collections, ); } static const usedKey = 'used'; static const capacityKey = 'capacity'; static const collectionsKey = 'collections'; static const timeKey = 'time'; final String heap; final int usage; final int capacity; final int collections; final double averageCollectionTime; } extension AllocationProfilePrivateViewExtension on AllocationProfile { static const heapsKey = '_heaps'; static const newSpaceKey = 'new'; static const oldSpaceKey = 'old'; GCStats get newSpaceGCStats => GCStats.parse( heap: HeapGeneration.newSpace.toString(), json: (_heaps[newSpaceKey] as Map).cast<String, Object?>(), ); GCStats get oldSpaceGCStats => GCStats.parse( heap: HeapGeneration.oldSpace.toString(), json: (_heaps[oldSpaceKey] as Map).cast<String, Object?>(), ); Map<String, Object?> get _heaps => (json![heapsKey] as Map).cast<String, Object?>(); GCStats get totalGCStats { final newSpace = newSpaceGCStats; final oldSpace = oldSpaceGCStats; final collections = newSpace.collections + oldSpace.collections; final averageCollectionTime = ((newSpace.collections * newSpace.averageCollectionTime) + (oldSpace.collections * oldSpace.averageCollectionTime)) / collections; return GCStats( heap: HeapGeneration.total.toString(), usage: newSpace.usage + oldSpace.usage, capacity: newSpace.capacity + oldSpace.capacity, collections: collections, averageCollectionTime: averageCollectionTime, ); } } /// An extension on [ObjRef] which allows for access to VM internal fields. extension ObjRefPrivateViewExtension on ObjRef { static const _icDataType = 'ICData'; static const _objectPoolType = 'ObjectPool'; static const _subtypeTestCache = 'SubtypeTestCache'; static const _weakArrayType = 'WeakArray'; /// The internal type of the object. /// /// The type of non-public service objects can be determined using this /// value. String? get vmType => json!['_vmType']; /// `true` if this object is an instance of [ICDataRef]. bool get isICData => vmType == _icDataType; /// Casts the current [ObjRef] into an instance of [ICDataRef]. ICDataRef get asICData => ICDataRef.parse(json!); /// `true` if this object is an instance of [ObjectPool]. bool get isObjectPool => vmType == _objectPoolType; /// Casts the current [ObjRef] into an instance of [ObjectPoolRef]. ObjectPoolRef get asObjectPool => ObjectPoolRef.parse(json!); /// `true` if this object is an instance of [SubtypeTestCacheRef]. bool get isSubtypeTestCache => vmType == _subtypeTestCache; /// Casts the current [ObjRef] into an instance of [SubtypeTestCacheRef]. SubtypeTestCacheRef get asSubtypeTestCache => SubtypeTestCacheRef.parse(json!); /// `true` if this object is an instance of [WeakArrayRef]. bool get isWeakArray => vmType == _weakArrayType; /// Casts the current [ObjRef] into an instance of [WeakArrayRef]. WeakArrayRef get asWeakArray => WeakArrayRef.parse(json!); } /// An extension on [Obj] which allows for access to VM internal fields. extension ObjPrivateViewExtension on Obj { /// Casts the current [Obj] into an instance of [ObjectPool]. ObjectPool get asObjectPool => ObjectPool.parse(json!); /// Casts the current [Obj] into an instance of [ICData]. ICData get asICData => ICData.parse(json!); /// Casts the current [Obj] into an instance of [SubtypeTestCache]. SubtypeTestCache get asSubtypeTestCache => SubtypeTestCache.parse(json!); /// Casts the current [Obj] into an instance of [WeakArray]. WeakArray get asWeakArray => WeakArray.parse(json!); } /// A reference to a [WeakArray], which is an array consisting of weak /// persistent handles. /// /// References to an object from a [WeakArray] are ignored by the GC and will /// not prevent referenced objects from being collected when all other /// references to the object disappear. class WeakArrayRef implements ObjRef { WeakArrayRef({ required this.id, required this.json, required this.length, }); factory WeakArrayRef.parse(Map<String, dynamic> json) => WeakArrayRef( id: json['id'], json: json, length: json['length'], ); @override bool? fixedId; @override String? id; @override Map<String, dynamic>? json; final int length; @override Map<String, dynamic> toJson() => json!; @override String get type => 'WeakArray'; } /// A populated representation of a [WeakArray], which is an array consisting /// of weak persistent handles. /// /// References to an object from a [WeakArray] are ignored by the GC and will /// not prevent referenced objects from being collected when all other /// references to the object disappear. class WeakArray extends WeakArrayRef implements Obj { WeakArray({ required super.id, required super.json, required super.length, required this.elements, required this.size, required this.classRef, }); factory WeakArray.parse(Map<String, dynamic> json) => WeakArray( id: json['id'], json: json, length: json['length'], size: json['size'], elements: (createServiceObject(json['elements'], []) as List) .cast<Response?>(), classRef: createServiceObject(json['class'], [])! as ClassRef, ); final List<Response?> elements; @override Map<String, dynamic> toJson() => json!; @override String get type => 'WeakArray'; @override ClassRef? classRef; @override int? size; } /// A partially-populated representation of the Dart VM's subtype test cache. class SubtypeTestCacheRef implements ObjRef { SubtypeTestCacheRef({ required this.id, required this.json, }); factory SubtypeTestCacheRef.parse(Map<String, dynamic> json) => SubtypeTestCacheRef( id: json['id'], json: json, ); @override bool? fixedId; @override String? id; @override Map<String, dynamic>? json; @override Map<String, dynamic> toJson() => json!; @override String get type => 'SubtypeTestCache'; } /// A fully-populated representation of the Dart VM's subtype test cache. class SubtypeTestCache extends SubtypeTestCacheRef implements Obj { SubtypeTestCache({ required super.id, required super.json, required this.size, required this.classRef, required this.cache, }); factory SubtypeTestCache.parse(Map<String, dynamic> json) => SubtypeTestCache( id: json['id'], size: json['size'], cache: createServiceObject(json['_cache'], [])! as InstanceRef, classRef: createServiceObject(json['class'], [])! as ClassRef, json: json, ); /// An array of objects which make up the cache. final InstanceRef cache; @override ClassRef? classRef; @override int? size; } /// A partially-populated representation of the Dart VM's Inline Cache (IC). /// /// For more information: /// - [Slava's Dart VM intro](https://mrale.ph/dartvm/) /// - [Dart VM implementation](https://github.com/dart-lang/sdk/blob/2d064faf748d6c7700f08d223fb76c84c4335c5f/runtime/vm/raw_object.h#L2103) class ICDataRef implements ObjRef { ICDataRef({ required this.id, required this.json, required this.owner, required this.selector, }); factory ICDataRef.parse(Map<String, dynamic> json) => ICDataRef( id: json['id'], owner: createServiceObject(json['_owner'], []) as ObjRef, selector: json['_selector'], json: json, ); final ObjRef owner; final String selector; @override bool? fixedId; @override String? id; @override Map<String, dynamic>? json; @override Map<String, dynamic> toJson() => json!; @override String get type => 'ICData'; } /// A fully-populated representation of the Dart VM's Inline Cache (IC). /// /// For more information: /// - [Slava's Dart VM intro](https://mrale.ph/dartvm/) /// - [Dart VM implementation](https://github.com/dart-lang/sdk/blob/2d064faf748d6c7700f08d223fb76c84c4335c5f/runtime/vm/raw_object.h#L2103) class ICData extends ICDataRef implements Obj { ICData({ required super.id, required super.json, required super.owner, required super.selector, required this.classRef, required this.size, required this.argumentsDescriptor, required this.entries, }) : super(); factory ICData.parse(Map<String, dynamic> json) => ICData( id: json['id'], owner: createServiceObject(json['_owner'], []) as ObjRef, selector: json['_selector'], classRef: createServiceObject(json['class'], []) as ClassRef, size: json['size'], argumentsDescriptor: createServiceObject(json['_argumentsDescriptor'], [])! as InstanceRef, entries: createServiceObject(json['_entries'], [])! as InstanceRef, json: json, ); @override ClassRef? classRef; @override int? size; final InstanceRef argumentsDescriptor; final InstanceRef entries; } /// A single assembly instruction from a [Func]'s generated code disassembly. class Instruction { Instruction.parse(List data) : address = data[0], unknown = data[1], instruction = data[2] { if (data[3] == null) { object = null; return; } final rawObject = data[3] as Map<String, dynamic>; object = (rawObject['type'] as List).contains('Instance') ? InstanceRef.parse(rawObject) : createServiceObject(data[3], const <String>[]) as Response?; } /// The instruction's address in memory. final String address; /// The instruction's address in memory with leading zeros removed. String get unpaddedAddress => address.substring(address.indexOf(RegExp(r'[^0]'))); /// TODO(bkonyi): figure out what this value is for. final String unknown; /// The [String] representation of the assembly instruction. final String instruction; /// The Dart object this instruction is acting upon directly. late final Response? object; List toJson() => [ address, unknown, instruction, object?.json, ]; } /// The full disassembly of generated [Code] for a function. class Disassembly { Disassembly.parse(List disassembly) { for (int i = 0; i < disassembly.length; i += 4) { instructions.add( Instruction.parse(disassembly.getRange(i, i + 4).toList()), ); } } /// The list of [Instructions] that make up the generated code. final instructions = <Instruction>[]; List toJson() => [ for (final i in instructions) ...i.toJson(), ]; } /// An extension on [Func] which allows for access to VM internal fields. extension FunctionPrivateViewExtension on Func { static const _unoptimizedCodeKey = '_unoptimizedCode'; static const _kindKey = '_kind'; static const _deoptimizationsKey = '_deoptimizations'; static const _optimizableKey = '_optimizable'; static const _inlinableKey = '_inlinable'; static const _intrinsicKey = '_intrinsic'; static const _recognizedKey = '_recognized'; static const _nativeKey = '_native'; static const _icDataArrayKey = '_icDataArray'; /// The unoptimized [CodeRef] associated with the [Func]. CodeRef? get unoptimizedCode => CodeRef.parse(json![_unoptimizedCodeKey]); set unoptimizedCode(CodeRef? code) => json![_unoptimizedCodeKey] = code?.json; String? get kind => json![_kindKey]; int? get deoptimizations => json![_deoptimizationsKey]; bool? get optimizable => json![_optimizableKey]; bool? get inlinable => json![_inlinableKey]; bool? get intrinsic => json![_intrinsicKey]; bool? get recognized => json![_recognizedKey]; bool? get native => json![_nativeKey]; String? get vmName => json!['_vmName']; Future<Instance?> get icDataArray async { final icDataArray = (json![_icDataArrayKey] as Map?)?.cast<String, Object?>(); final icDataArrayId = icDataArray?['id'] as String?; if (icDataArrayId != null) { final service = serviceConnection.serviceManager.service!; final isolate = serviceConnection.serviceManager.isolateManager.selectedIsolate.value; return await service.getObject(isolate!.id!, icDataArrayId) as Instance; } else { return null; } } } /// The function kinds recognized by the Dart VM. enum FunctionKind { RegularFunction, ClosureFunction, ImplicitClosureFunction, GetterFunction, SetterFunction, Constructor, ImplicitGetter, ImplicitSetter, ImplicitStaticGetter, FieldInitializer, IrregexpFunction, MethodExtractor, NoSuchMethodDispatcher, InvokeFieldDispatcher, Collected, Native, FfiTrampoline, Stub, Tag, DynamicInvocationForwarder; String kind() { return toString().split('.').last; } /// Returns the [kind] string converted from camel case to title case by /// adding a space whenever a lowercase letter is followed by an uppercase /// letter. /// /// For example, calling [kindDescription] on /// [FunctionKind.ImplicitClosureFunction] would return /// 'Implicit Closure Function'; String kindDescription() { final description = StringBuffer(); final camelCase = RegExp(r'(?<=[a-z])[A-Z]'); description.write( kind().replaceAllMapped( camelCase, (Match m) => ' ${m.group(0)!}', ), ); return description.toString(); } } extension CodeRefPrivateViewExtension on CodeRef { static const _functionKey = 'function'; /// Returns the function from which this code object was generated. FuncRef? get function { final functionJson = json![_functionKey] as Map<String, dynamic>?; return FuncRef.parse(functionJson); } } /// An extension on [Code] which allows for access to VM internal fields. extension CodePrivateViewExtension on Code { static const _disassemblyKey = '_disassembly'; static const _kindKey = 'kind'; static const _objectPoolKey = '_objectPool'; /// Returns the disassembly of the [Code], which is the generated assembly /// instructions for the code's function. Disassembly get disassembly => Disassembly.parse(json![_disassemblyKey]); set disassembly(Disassembly disassembly) => json![_disassemblyKey] = disassembly.toJson(); /// The kind of code object represented by this instance. /// /// Can be one of: /// - Dart /// - Stub String get kind => json![_kindKey]; ObjectPoolRef get objectPool => ObjectPoolRef.parse(json![_objectPoolKey]); bool get hasInliningData => json!.containsKey(InliningData.kInlinedFunctions); InliningData get inliningData => InliningData.parse(json!); } extension AddressExtension on num { String get asAddress => '0x${toInt().toRadixString(16).toUpperCase().padLeft(8, '0')}'; } class InliningData { const InliningData._({required this.entries}); factory InliningData.parse(Map<String, dynamic> json) { final startAddress = int.parse(json[kStartAddressKey], radix: 16); final intervals = (json[kInlinedIntervals] as List).cast<List>(); final functions = (json[kInlinedFunctions] as List) .cast<Map<String, dynamic>>() .map<FuncRef>((e) => FuncRef.parse(e)!) .toList(); final entries = <InliningEntry>[]; // Inlining data format: [startAddress, endAddress, 0, inline functions...] for (final interval in intervals) { assert(interval.length >= 2); final range = Range( startAddress + interval[0], startAddress + interval[1], ); // We start at i = 3 as `interval[2]` is always present and set to 0, // likely serving as a sentinel. `functions[0]` is not inlined for every // range, so we'll ignore this value. final inlinedFunctions = <FuncRef>[ for (int i = 3; i < interval.length; ++i) functions[interval[i]], ]; entries.add( InliningEntry( addressRange: range, functions: inlinedFunctions, ), ); } return InliningData._(entries: entries); } @visibleForTesting static const kInlinedIntervals = '_inlinedIntervals'; @visibleForTesting static const kInlinedFunctions = '_inlinedFunctions'; @visibleForTesting static const kStartAddressKey = '_startAddress'; final List<InliningEntry> entries; } class InliningEntry { const InliningEntry({ required this.addressRange, required this.functions, }); final Range addressRange; final List<FuncRef> functions; } class ObjectPoolRef extends ObjRef { ObjectPoolRef({ required Map<String, dynamic> json, required super.id, required this.length, }) { super.json = json; } static const _idKey = 'id'; static const _lengthKey = 'length'; static ObjectPoolRef parse(Map<String, dynamic> json) => ObjectPoolRef( id: json[_idKey], length: json[_lengthKey], json: json, ); final int length; } class ObjectPool extends ObjectPoolRef implements Obj { ObjectPool({ required super.json, required super.id, required this.entries, required super.length, }); static const _entriesKey = '_entries'; static ObjectPool parse(Map<String, dynamic> json) { return ObjectPool( json: json, id: json[ObjectPoolRef._idKey], entries: (json[_entriesKey] as List) .map((e) => ObjectPoolEntry.parse(e)) .toList(), length: json[ObjectPoolRef._lengthKey], ); } @override String get type => 'ObjectPool'; @override ClassRef? classRef; @override int? size; List<ObjectPoolEntry> entries; } enum ObjectPoolEntryKind { object, immediate, nativeFunction; static const _kObject = 'Object'; static const _kImm = 'Immediate'; static const _kNativeFunction = 'NativeFunction'; static ObjectPoolEntryKind fromString(String type) { switch (type) { case _kObject: return object; case _kImm: return immediate; case _kNativeFunction: return nativeFunction; default: throw UnsupportedError('Unsupported ObjectPoolType: $type'); } } @override String toString() { switch (this) { case object: return _kObject; case immediate: return _kImm; case nativeFunction: return 'Native Function'; } } } class ObjectPoolEntry { const ObjectPoolEntry({ required this.offset, required this.kind, required this.value, }); static const _offsetKey = 'offset'; static const _kindKey = 'kind'; static const _valueKey = 'value'; static ObjectPoolEntry parse(Map<String, dynamic> json) => ObjectPoolEntry( offset: json[_offsetKey], kind: ObjectPoolEntryKind.fromString(json[_kindKey]), value: createServiceObject(json[_valueKey], [])!, ); final int offset; final ObjectPoolEntryKind kind; final Object value; } /// An extension on [Field] which allows for access to VM internal fields. extension FieldPrivateViewExtension on Field { static const _guardClassKey = '_guardClass'; bool? get guardNullable => json!['_guardNullable']; Future<Class?> get guardClass async { if (_guardClassIsClass()) { final service = serviceConnection.serviceManager.service!; final isolate = serviceConnection.serviceManager.isolateManager.selectedIsolate.value; return await service.getObject( isolate!.id!, guardClassData['id'] as String, ) as Class; } return null; } GuardClassKind? guardClassKind() { if (_guardClassIsClass()) { return GuardClassKind.single; } else if (json![_guardClassKey] == GuardClassKind.dynamic.jsonValue()) { return GuardClassKind.dynamic; } else if (json![_guardClassKey] == GuardClassKind.unknown.jsonValue()) { return GuardClassKind.unknown; } return null; } bool _guardClassIsClass() { String? guardClassType; if (json![_guardClassKey] is Map) { guardClassType = guardClassData['type'] as String?; } return guardClassType == '@Class' || guardClassType == 'Class'; } Map<String, Object?> get guardClassData => (json![_guardClassKey] as Map).cast<String, Object?>(); } /// The kinds of Guard Class that determine whether a Field object has /// a unique observed type [single], various observed types [dynamic], /// or if the field type has not been observed yet [unknown]. enum GuardClassKind { single, dynamic, unknown; String jsonValue() { switch (this) { case GuardClassKind.dynamic: return 'various'; case GuardClassKind.single: case GuardClassKind.unknown: return toString().split('.').last; } } } /// An extension on [Script] which allows for access to VM internal fields. extension ScriptPrivateViewExtension on Script { static const _loadTimeKey = '_loadTime'; int get loadTime => json![_loadTimeKey]!; } /// An extension on [Library] which allows for access to VM internal fields. extension LibraryPrivateExtension on Library { String? get vmName => json![_vmNameKey]; } typedef ObjectStoreEntry = MapEntry<String, ObjRef>; /// A collection of VM objects stored in an isolate's object store. /// /// The object store is used to provide easy and cheap access to important /// VM objects within the VM. Examples of objects stored in the object store /// include: /// /// - Code stubs (e.g., allocation paths, async/await machinery) /// - References to core classes (e.g., `Null`, `Object`, `Never`) /// - Common type arguments (e.g., `<String, dynamic>`) /// - References to frequently accessed fields / functions (e.g., /// `_objectEquals()`, `_Enum._name`) /// - Cached, per-isolate data (e.g., library URI mappings) /// /// The object store is considered one of the GC roots by the VM's garbage /// collector, meaning that objects in the store will be considered live, even /// if they're not referenced anywhere else in the program. class ObjectStore { const ObjectStore({ required this.fields, }); static ObjectStore? parse(Map<String, dynamic>? json) { if (json?['type'] != '_ObjectStore') { return null; } final rawFields = json!['fields']! as Map<String, dynamic>; return ObjectStore( fields: rawFields.map((key, value) { return ObjectStoreEntry( key, createServiceObject(value, ['InstanceRef']) as ObjRef, ); }), ); } final Map<String, ObjRef> fields; } /// A `ProfileCode` contains profiling information about a Dart or native /// code object. /// /// See [CpuSamples]. class ProfileCode { ProfileCode({ this.kind, this.inclusiveTicks, this.exclusiveTicks, this.code, this.ticks, }); ProfileCode._fromJson(Map<String, dynamic> json) { kind = json['kind'] ?? ''; inclusiveTicks = json['inclusiveTicks'] ?? -1; exclusiveTicks = json['exclusiveTicks'] ?? -1; code = createServiceObject(json['code'], const ['@Code']) as CodeRef?; ticks = json['ticks']; } static ProfileCode? parse(Map<String, dynamic>? json) => json == null ? null : ProfileCode._fromJson(json); /// The kind of function this object represents. String? kind; /// The number of times function appeared on the stack during sampling events. int? inclusiveTicks; /// The number of times function appeared on the top of the stack during /// sampling events. int? exclusiveTicks; /// The function captured during profiling. CodeRef? code; List? ticks; Map<String, Object?> toJson() { final json = <String, Object?>{}; json.addAll({ 'kind': kind ?? '', 'inclusiveTicks': inclusiveTicks ?? -1, 'exclusiveTicks': exclusiveTicks ?? -1, 'code': code?.toJson(), 'ticks': ticks, }); return json; } @override String toString() => '[ProfileCode ' // 'kind: $kind, inclusiveTicks: $inclusiveTicks, exclusiveTicks: $exclusiveTicks, ' // 'code: $code]'; } extension CpuSamplePrivateView on CpuSample { static final _expando = Expando<List<int>>(); List<int> get codeStack => _expando[this] ?? []; void setCodeStack(List<int> stack) => _expando[this] = stack; } extension CpuSamplesPrivateView on CpuSamples { // Used to attach the codes list to a CpuSamples instance. static final _expando = Expando<List<ProfileCode>>(); static const _kCodesKey = '_codes'; bool get hasCodes { return _expando[this] != null || json!.containsKey(_kCodesKey); } List<ProfileCode> get codes { return _expando[this] ??= (json![_kCodesKey] as List) .cast<Map<String, dynamic>>() .map<ProfileCode>((e) => ProfileCode.parse(e)!) .toList(); } } extension ProfileDataRanges on SourceReport { ProfileReport asProfileReport(Script script) => ProfileReport._fromJson(script, json!); } /// Profiling information for a given line in a [Script]. class ProfileReportEntry { const ProfileReportEntry({ required this.sampleCount, required this.line, required this.inclusive, required this.exclusive, }); final int sampleCount; final int line; final int inclusive; final int exclusive; double get inclusivePercentage => inclusive * 100 / sampleCount; double get exclusivePercentage => exclusive * 100 / sampleCount; } /// Profiling information for a range of token positions in a [Script]. class ProfileReportRange { ProfileReportRange._fromJson(Script script, _ProfileReportRangeJson json) { final inclusiveTicks = json.inclusiveTicks; final exclusiveTicks = json.exclusiveTicks; final lines = json.positions .map<int>( // It's possible to get a synthetic token position which will either // be a negative value or a String (e.g., 'ParallelMove' or // 'NoSource'). We'll just use -1 as a placeholder since we won't // display anything for these tokens anyway. (e) => e is int ? script.getLineNumberFromTokenPos(e) ?? _kNoSourcePosition : _kNoSourcePosition, ) .toList(); for (int i = 0; i < lines.length; ++i) { final line = lines[i]; // In a `Map<int, ProfileReportEntry>`, we're mapping an `int` to a // `ProfileReportEntry`. No bug. // ignore: avoid-collection-methods-with-unrelated-types entries[line] = ProfileReportEntry( sampleCount: json.sampleCount, line: line, inclusive: inclusiveTicks[i], exclusive: exclusiveTicks[i], ); } } static const _kNoSourcePosition = -1; final entries = <int, ProfileReportEntry>{}; } /// An extension type for the unstructured data in the 'ranges' data of the /// profiling information used in [ProfileReport]. extension type _ProfileReportRangeJson(Map<String, dynamic> json) { Map<String, Object?> get _profile => json[_kProfileKey]; Map<String, Object?> get metadata => (_profile[_kMetadataKey] as Map).cast<String, Object?>(); int get sampleCount => metadata[_kSampleCountKey] as int; List<int> get inclusiveTicks => (_profile[_kInclusiveTicksKey] as List).cast<int>(); List<int> get exclusiveTicks => (_profile[_kExclusiveTicksKey] as List).cast<int>(); List<Object?> get positions => _profile[_kPositionsKey] as List; static const _kProfileKey = 'profile'; static const _kMetadataKey = 'metadata'; static const _kSampleCountKey = 'sampleCount'; static const _kInclusiveTicksKey = 'inclusiveTicks'; static const _kExclusiveTicksKey = 'exclusiveTicks'; static const _kPositionsKey = 'positions'; } /// A representation of the `_Profile` [SourceReport], which contains profiling /// information for a given [Script]. class ProfileReport { ProfileReport._fromJson(Script script, Map<String, dynamic> json) : _profileRanges = (json['ranges'] as List) .cast<Map<String, dynamic>>() .where((e) => e.containsKey('profile')) .map<ProfileReportRange>( (e) => ProfileReportRange._fromJson( script, _ProfileReportRangeJson(e), ), ) .toList(); List<ProfileReportRange> get profileRanges => _profileRanges; final List<ProfileReportRange> _profileRanges; }
devtools/packages/devtools_app/lib/src/screens/vm_developer/vm_service_private_extensions.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/screens/vm_developer/vm_service_private_extensions.dart", "repo_id": "devtools", "token_count": 11220 }
93
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: non_constant_identifier_names @JS() library; import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:js/js.dart'; import 'package:logging/logging.dart'; import 'package:web/web.dart'; import '../../../devtools.dart' as devtools show version; import '../globals.dart'; import '../server/server.dart' as server; import '../utils.dart'; import 'analytics_common.dart'; import 'constants.dart' as gac; import 'gtags.dart'; import 'metrics.dart'; // Dimensions1 AppType values: const String appTypeFlutter = 'flutter'; const String appTypeWeb = 'web'; const String appTypeFlutterWeb = 'flutter_web'; const String appTypeDartCLI = 'dart_cli'; // Dimensions2 BuildType values: const String buildTypeDebug = 'debug'; const String buildTypeProfile = 'profile'; // Start with Android_n.n.n const String devToolsPlatformTypeAndroid = 'Android_'; // Dimension5 devToolsChrome starts with const String devToolsChromeName = 'Chrome/'; // starts with and ends with n.n.n const String devToolsChromeIos = 'Crios/'; // starts with and ends with n.n.n const String devToolsChromeOS = 'CrOS'; // Chrome OS // Dimension6 devToolsVersion // Dimension7 ideLaunched const String ideLaunchedCLI = 'CLI'; // Command Line Interface final _log = Logger('_analytics_web'); @JS('initializeGA') external void initializeGA(); @JS() @anonymous class GtagEventDevTools extends GtagEvent { // TODO(kenz): try to make this accept a JSON map of extra parameters rather // than a fixed list of fields. See // https://github.com/flutter/devtools/pull/3281#discussion_r692376353. external factory GtagEventDevTools({ String? event_category, String? event_label, // Event e.g., gaScreenViewEvent, gaSelectEvent, etc. String? send_to, // UA ID of target GA property to receive event data. int value, bool non_interaction, // This code is going away so not worth cleaning up to be free of dynamic. // ignore: avoid-dynamic dynamic custom_map, // NOTE: Do not reorder any of these. Order here must match the order in the // Google Analytics console. String? user_app, // dimension1 (flutter or web) String? user_build, // dimension2 (debug or profile) String? user_platform, // dimension3 (android/ios/fuchsia/linux/mac/windows) String? devtools_platform, // dimension4 linux/android/mac/windows String? devtools_chrome, // dimension5 Chrome version # String? devtools_version, // dimension6 DevTools version # String? ide_launched, // dimension7 Devtools launched (CLI, VSCode, Android) String? flutter_client_id, // dimension8 Flutter tool client_id (~/.flutter). String? is_external_build, // dimension9 External build or google3 String? is_embedded, // dimension10 Whether devtools is embedded String? g3_username, // dimension11 g3 username (null for external users) // dimension12 IDE feature that launched Devtools // The following is a non-exhaustive list of possible values for this dimension: // "command" - VS Code command palette // "sidebarContent" - the content of the sidebar (e.g. the DevTools dropdown for a debug session) // "sidebarTitle" - the DevTools action in the sidebar title // "touchbar" - MacOS touchbar button // "launchConfiguration" - configured explicitly in launch configuration // "onDebugAutomatic" - configured to always run on debug session start // "onDebugPrompt" - user responded to prompt when running a debug session // "languageStatus" - launched from the language status popout String? ide_launched_feature, // Performance screen metrics. See [PerformanceScreenMetrics]. int? ui_duration_micros, // metric1 int? raster_duration_micros, // metric2 int? shader_compilation_duration_micros, // metric3 // Profiler screen metrics. See [ProfilerScreenMetrics]. int? cpu_sample_count, // metric4 int? cpu_stack_depth, // metric5 // Performance screen metric. See [PerformanceScreenMetrics]. int? trace_event_count, // metric6 // Memory screen metric. See [MemoryScreenMetrics]. int? heap_diff_objects_before, // metric7 int? heap_diff_objects_after, // metric8 int? heap_objects_total, // metric9 // Inspector screen metrics. See [InspectorScreenMetrics]. int? root_set_count, // metric10 int? row_count, // metric11 int? inspector_tree_controller_id, // metric12 }); @override external String? get event_category; @override external String? get event_label; @override external String? get send_to; @override external int get value; // Positive number. @override external bool get non_interaction; @override external Object get custom_map; // Custom dimensions: external String? get user_app; external String? get user_build; external String? get user_platform; external String? get devtools_platform; external String? get devtools_chrome; external String? get devtools_version; external String? get ide_launched; external String? get flutter_client_id; external String? get is_external_build; external String? get is_embedded; external String? get g3_username; external String? get ide_launched_feature; // Custom metrics: external int? get ui_duration_micros; external int? get raster_duration_micros; external int? get shader_compilation_duration_micros; external int? get cpu_sample_count; external int? get cpu_stack_depth; external int? get trace_event_count; external int? get heap_diff_objects_before; external int? get heap_diff_objects_after; external int? get heap_objects_total; external int? get root_set_count; external int? get row_count; external int? get inspector_tree_controller_id; } // This cannot be a factory constructor in the [GtagEventDevTools] class due to // https://github.com/dart-lang/sdk/issues/46967. GtagEventDevTools _gtagEvent({ String? event_category, String? event_label, String? send_to, bool non_interaction = false, int value = 0, ScreenAnalyticsMetrics? screenMetrics, }) { return GtagEventDevTools( event_category: event_category, event_label: event_label, send_to: send_to, non_interaction: non_interaction, value: value, user_app: userAppType, user_build: userBuildType, user_platform: userPlatformType, devtools_platform: devtoolsPlatformType, devtools_chrome: devtoolsChrome, devtools_version: devtoolsVersion, ide_launched: ideLaunched, flutter_client_id: flutterClientId, is_external_build: isExternalBuild.toString(), is_embedded: ideTheme.embed.toString(), g3_username: devToolsExtensionPoints.username(), ide_launched_feature: ideLaunchedFeature, // [PerformanceScreenMetrics] ui_duration_micros: screenMetrics is PerformanceScreenMetrics ? screenMetrics.uiDuration?.inMicroseconds : null, raster_duration_micros: screenMetrics is PerformanceScreenMetrics ? screenMetrics.rasterDuration?.inMicroseconds : null, shader_compilation_duration_micros: screenMetrics is PerformanceScreenMetrics ? screenMetrics.shaderCompilationDuration?.inMicroseconds : null, trace_event_count: screenMetrics is PerformanceScreenMetrics ? screenMetrics.traceEventCount : null, // [ProfilerScreenMetrics] cpu_sample_count: screenMetrics is ProfilerScreenMetrics ? screenMetrics.cpuSampleCount : null, cpu_stack_depth: screenMetrics is ProfilerScreenMetrics ? screenMetrics.cpuStackDepth : null, // [MemoryScreenMetrics] heap_diff_objects_before: screenMetrics is MemoryScreenMetrics ? screenMetrics.heapDiffObjectsBefore : null, heap_diff_objects_after: screenMetrics is MemoryScreenMetrics ? screenMetrics.heapDiffObjectsAfter : null, heap_objects_total: screenMetrics is MemoryScreenMetrics ? screenMetrics.heapObjectsTotal : null, // [InspectorScreenMetrics] root_set_count: screenMetrics is InspectorScreenMetrics ? screenMetrics.rootSetCount : null, row_count: screenMetrics is InspectorScreenMetrics ? screenMetrics.rowCount : null, inspector_tree_controller_id: screenMetrics is InspectorScreenMetrics ? screenMetrics.inspectorTreeControllerId : null, ); } // This cannot be a factory constructor in the [GtagExceptionDevTools] class due to // https://github.com/dart-lang/sdk/issues/46967. GtagExceptionDevTools _gtagException( String errorMessage, { bool fatal = false, ScreenAnalyticsMetrics? screenMetrics, }) { return GtagExceptionDevTools( description: errorMessage, fatal: fatal, user_app: userAppType, user_build: userBuildType, user_platform: userPlatformType, devtools_platform: devtoolsPlatformType, devtools_chrome: devtoolsChrome, devtools_version: devtoolsVersion, ide_launched: _ideLaunched, flutter_client_id: flutterClientId, is_external_build: isExternalBuild.toString(), is_embedded: ideTheme.embed.toString(), g3_username: devToolsExtensionPoints.username(), ide_launched_feature: ideLaunchedFeature, // [PerformanceScreenMetrics] ui_duration_micros: screenMetrics is PerformanceScreenMetrics ? screenMetrics.uiDuration?.inMicroseconds : null, raster_duration_micros: screenMetrics is PerformanceScreenMetrics ? screenMetrics.rasterDuration?.inMicroseconds : null, trace_event_count: screenMetrics is PerformanceScreenMetrics ? screenMetrics.traceEventCount : null, shader_compilation_duration_micros: screenMetrics is PerformanceScreenMetrics ? screenMetrics.shaderCompilationDuration?.inMicroseconds : null, // [ProfilerScreenMetrics] cpu_sample_count: screenMetrics is ProfilerScreenMetrics ? screenMetrics.cpuSampleCount : null, cpu_stack_depth: screenMetrics is ProfilerScreenMetrics ? screenMetrics.cpuStackDepth : null, // [MemoryScreenMetrics] heap_diff_objects_before: screenMetrics is MemoryScreenMetrics ? screenMetrics.heapDiffObjectsBefore : null, heap_diff_objects_after: screenMetrics is MemoryScreenMetrics ? screenMetrics.heapDiffObjectsAfter : null, heap_objects_total: screenMetrics is MemoryScreenMetrics ? screenMetrics.heapObjectsTotal : null, // [InspectorScreenMetrics] root_set_count: screenMetrics is InspectorScreenMetrics ? screenMetrics.rootSetCount : null, row_count: screenMetrics is InspectorScreenMetrics ? screenMetrics.rowCount : null, inspector_tree_controller_id: screenMetrics is InspectorScreenMetrics ? screenMetrics.inspectorTreeControllerId : null, ); } @JS() @anonymous class GtagExceptionDevTools extends GtagException { external factory GtagExceptionDevTools({ String? description, bool fatal, // NOTE: Do not reorder any of these. Order here must match the order in the // Google Analytics console. String? user_app, // dimension1 (flutter or web) String? user_build, // dimension2 (debug or profile) String? user_platform, // dimension3 (android or ios) String? devtools_platform, // dimension4 linux/android/mac/windows String? devtools_chrome, // dimension5 Chrome version # String? devtools_version, // dimension6 DevTools version # String? ide_launched, // dimension7 IDE launched DevTools String? flutter_client_id, // dimension8 Flutter tool clientId String? is_external_build, // dimension9 External build or google3 String? is_embedded, // dimension10 Whether devtools is embedded String? g3_username, // dimension11 g3 username (null for external users) // dimension12 IDE feature that launched Devtools // The following is a non-exhaustive list of possible values for this dimension: // "command" - VS Code command palette // "sidebarContent" - the content of the sidebar (e.g. the DevTools dropdown for a debug session) // "sidebarTitle" - the DevTools action in the sidebar title // "touchbar" - MacOS touchbar button // "launchConfiguration" - configured explicitly in launch configuration // "onDebugAutomatic" - configured to always run on debug session start // "onDebugPrompt" - user responded to prompt when running a debug session // "languageStatus" - launched from the language status popout String? ide_launched_feature, // Performance screen metrics. See [PerformanceScreenMetrics]. int? ui_duration_micros, // metric1 int? raster_duration_micros, // metric2 int? shader_compilation_duration_micros, // metric3 // Profiler screen metrics. See [ProfilerScreenMetrics]. int? cpu_sample_count, // metric4 int? cpu_stack_depth, // metric5 // Performance screen metric. See [PerformanceScreenMetrics]. int? trace_event_count, // metric6 // Memory screen metric. See [MemoryScreenMetrics]. int? heap_diff_objects_before, // metric7 int? heap_diff_objects_after, // metric8 int? heap_objects_total, // metric9 // Inspector screen metrics. See [InspectorScreenMetrics]. int? root_set_count, // metric10 int? row_count, // metric11 int? inspector_tree_controller_id, // metric12 }); @override external String? get description; // Description of the error. @override external bool get fatal; // Fatal error. // Custom dimensions: external String? get user_app; external String? get user_build; external String? get user_platform; external String? get devtools_platform; external String? get devtools_chrome; external String? get devtools_version; external String? get ide_launched; external String? get flutter_client_id; external String? get is_external_build; external String? get is_embedded; external String? get g3_username; external String? get ide_launched_feature; // Custom metrics: external int? get ui_duration_micros; external int? get raster_duration_micros; external int? get shader_compilation_duration_micros; external int? get cpu_sample_count; external int? get cpu_stack_depth; external int? get trace_event_count; external int? get heap_diff_objects_before; external int? get heap_diff_objects_after; external int? get heap_objects_total; external int? get root_set_count; external int? get row_count; external int? get inspector_tree_controller_id; } /// Request DevTools property value 'enabled' (GA enabled) stored in the file /// '~/.flutter-devtools/.devtools'. Future<bool> isAnalyticsEnabled() async { return await server.isAnalyticsEnabled(); } /// Set the DevTools property 'enabled' (GA enabled) stored in the file /// '~/flutter-devtools/.devtools'. Future<bool> setAnalyticsEnabled(bool value) async { return await server.setAnalyticsEnabled(value); } void screen( String screenName, [ int value = 0, ]) { _log.fine('Event: Screen(screenName:$screenName, value:$value)'); GTag.event( screenName, gaEventProvider: () => _gtagEvent( event_category: gac.screenViewEvent, value: value, send_to: gaDevToolsPropertyId(), ), ); } String _operationKey(String screenName, String timedOperation) { return '$screenName-$timedOperation'; } final _timedOperationsInProgress = <String, DateTime>{}; // Use this method coupled with `timeEnd` when an operation cannot be timed in // a callback, but rather needs to be timed instead at two disjoint start and // end marks. void timeStart(String screenName, String timedOperation) { final startTime = DateTime.now(); final operationKey = _operationKey( screenName, timedOperation, ); _timedOperationsInProgress[operationKey] = startTime; } // Use this method coupled with `timeStart` when an operation cannot be timed in // a callback, but rather needs to be timed instead at two disjoint start and // end marks. void timeEnd( String screenName, String timedOperation, { ScreenAnalyticsMetrics Function()? screenMetricsProvider, }) { final endTime = DateTime.now(); final operationKey = _operationKey( screenName, timedOperation, ); final startTime = _timedOperationsInProgress.remove(operationKey); assert(startTime != null); if (startTime == null) { _log.warning( 'Could not time operation "$timedOperation" because a) `timeEnd` was ' 'called before `timeStart` or b) the `screenName` and `timedOperation`' 'parameters for the `timeStart` and `timeEnd` calls do not match.', ); return; } final durationMicros = endTime.microsecondsSinceEpoch - startTime.microsecondsSinceEpoch; _timing( screenName, timedOperation, durationMicros: durationMicros, screenMetrics: screenMetricsProvider != null ? screenMetricsProvider() : null, ); } void cancelTimingOperation(String screenName, String timedOperation) { final operationKey = _operationKey( screenName, timedOperation, ); final operation = _timedOperationsInProgress.remove(operationKey); assert( operation != null, 'The operation cannot be cancelled because it does not exist.', ); } // Use this when a synchronous operation can be timed in a callback. void timeSync( String screenName, String timedOperation, { required void Function() syncOperation, ScreenAnalyticsMetrics Function()? screenMetricsProvider, }) { final startTime = DateTime.now(); try { syncOperation(); } catch (e, st) { // Do not send the timing analytic to GA if the operation failed. _log.warning( 'Could not time sync operation "$timedOperation" ' 'because an exception was thrown:\n$e\n$st', ); rethrow; } final endTime = DateTime.now(); final durationMicros = endTime.microsecondsSinceEpoch - startTime.microsecondsSinceEpoch; _timing( screenName, timedOperation, durationMicros: durationMicros, screenMetrics: screenMetricsProvider != null ? screenMetricsProvider() : null, ); } // Use this when an asynchronous operation can be timed in a callback. Future<void> timeAsync( String screenName, String timedOperation, { required Future<void> Function() asyncOperation, ScreenAnalyticsMetrics Function()? screenMetricsProvider, }) async { final startTime = DateTime.now(); try { await asyncOperation(); } catch (e, st) { // Do not send the timing analytic to GA if the operation failed. _log.warning( 'Could not time async operation "$timedOperation" ' 'because an exception was thrown:\n$e\n$st', ); rethrow; } final endTime = DateTime.now(); final durationMicros = endTime.microsecondsSinceEpoch - startTime.microsecondsSinceEpoch; _timing( screenName, timedOperation, durationMicros: durationMicros, screenMetrics: screenMetricsProvider != null ? screenMetricsProvider() : null, ); } void _timing( String screenName, String timedOperation, { required int durationMicros, ScreenAnalyticsMetrics? screenMetrics, }) { _log.fine( 'Event: _timing(' 'screenName:$screenName, ' 'timedOperation:$timedOperation, ' 'durationMicros:$durationMicros)', ); GTag.event( screenName, gaEventProvider: () => _gtagEvent( event_category: gac.timingEvent, event_label: timedOperation, value: durationMicros, send_to: gaDevToolsPropertyId(), screenMetrics: screenMetrics, ), ); } /// Sends an analytics event to signal that something in DevTools was selected. void select( String screenName, String selectedItem, { int value = 0, bool nonInteraction = false, ScreenAnalyticsMetrics Function()? screenMetricsProvider, }) { _log.fine( 'Event: select(' 'screenName:$screenName, ' 'selectedItem:$selectedItem, ' 'value:$value, ' 'nonInteraction:$nonInteraction)', ); GTag.event( screenName, gaEventProvider: () => _gtagEvent( event_category: gac.selectEvent, event_label: selectedItem, value: value, non_interaction: nonInteraction, send_to: gaDevToolsPropertyId(), screenMetrics: screenMetricsProvider != null ? screenMetricsProvider() : null, ), ); } /// Sends an analytics event to signal that something in DevTools was viewed. /// /// Impression events should not signal user interaction like [select]. void impression( String screenName, String item, { ScreenAnalyticsMetrics Function()? screenMetricsProvider, }) { _log.fine( 'Event: impression(' 'screenName:$screenName, ' 'item:$item)', ); GTag.event( screenName, gaEventProvider: () => _gtagEvent( event_category: gac.impressionEvent, event_label: item, non_interaction: true, send_to: gaDevToolsPropertyId(), screenMetrics: screenMetricsProvider != null ? screenMetricsProvider() : null, ), ); } String? _lastGaError; void reportError( String errorMessage, { bool fatal = false, ScreenAnalyticsMetrics Function()? screenMetricsProvider, }) { // Don't keep recording same last error. if (_lastGaError == errorMessage) return; _lastGaError = errorMessage; GTag.exception( gaExceptionProvider: () => _gtagException( errorMessage, fatal: fatal, screenMetrics: screenMetricsProvider != null ? screenMetricsProvider() : null, ), ); } //////////////////////////////////////////////////////////////////////////////// // Utilities to collect all platform and DevTools state for Analytics. //////////////////////////////////////////////////////////////////////////////// // GA dimensions: String _userAppType = ''; // dimension1 String _userBuildType = ''; // dimension2 String _userPlatformType = ''; // dimension3 String _devtoolsPlatformType = ''; // dimension4 MacIntel/Linux/Windows/Android_n String _devtoolsChrome = ''; // dimension5 Chrome/n.n.n or Crios/n.n.n const String devtoolsVersion = devtools.version; //dimension6 n.n.n String _ideLaunched = ''; // dimension7 IDE launched DevTools (VSCode, CLI, ...) // dimension12 IDE feature that launched DevTools String _ideLaunchedFeature = ''; String _flutterClientId = ''; // dimension8 Flutter tool clientId. String get userAppType => _userAppType; set userAppType(String newUserAppType) { _userAppType = newUserAppType; } String get userBuildType => _userBuildType; set userBuildType(String newUserBuildType) { _userBuildType = newUserBuildType; } String get userPlatformType => _userPlatformType; set userPlatformType(String newUserPlatformType) { _userPlatformType = newUserPlatformType; } String get devtoolsPlatformType => _devtoolsPlatformType; set devtoolsPlatformType(String newDevtoolsPlatformType) { _devtoolsPlatformType = newDevtoolsPlatformType; } String get devtoolsChrome => _devtoolsChrome; set devtoolsChrome(String newDevtoolsChrome) { _devtoolsChrome = newDevtoolsChrome; } /// The IDE that DevTools was launched from. /// /// Defaults to [ideLaunchedCLI] if DevTools was not launched from the IDE. String get ideLaunched => _ideLaunched; String get ideLaunchedFeature => _ideLaunchedFeature; set ideLaunchedFeature(String newIdeLaunchedFeature) { _ideLaunchedFeature = newIdeLaunchedFeature; } String get flutterClientId => _flutterClientId; set flutterClientId(String newFlutterClientId) { _flutterClientId = newFlutterClientId; } bool _computingDimensions = false; bool _analyticsComputed = false; bool _computingUserApplicationDimensions = false; bool _userApplicationDimensionsComputed = false; // Computes the running application. void _computeUserApplicationCustomGTagData() { if (_userApplicationDimensionsComputed) return; final connectedApp = serviceConnection.serviceManager.connectedApp!; assert(connectedApp.isFlutterAppNow != null); assert(connectedApp.isDartWebAppNow != null); assert(connectedApp.isProfileBuildNow != null); const unknownOS = 'unknown'; if (connectedApp.isFlutterAppNow!) { userPlatformType = serviceConnection.serviceManager.vm?.operatingSystem ?? unknownOS; } if (connectedApp.isFlutterWebAppNow) { userAppType = appTypeFlutterWeb; } else if (connectedApp.isFlutterAppNow!) { userAppType = appTypeFlutter; } else if (connectedApp.isDartWebAppNow!) { userAppType = appTypeWeb; } else { userAppType = appTypeDartCLI; } userBuildType = connectedApp.isProfileBuildNow! ? buildTypeProfile : buildTypeDebug; _analyticsComputed = true; } @JS('getDevToolsPropertyID') external String gaDevToolsPropertyId(); @JS('hookupListenerForGA') external void jsHookupListenerForGA(); Future<bool> enableAnalytics() async { return await setAnalyticsEnabled(true); } Future<bool> disableAnalytics() async { return await setAnalyticsEnabled(false); } /// Fetch the legal consent message for telemetry collection for /// package:unified_analyitcs from the server Future<String> fetchAnalyticsConsentMessage() async { return await server.fetchAnalyticsConsentMessage(); } /// Communicates with the server to confirm with package:unified_analyitcs /// that the consent message has successfully been shown and to allow events /// to be recorded if the user has decided to remain opted in. Future<void> markConsentMessageAsShown() async { return await server.markConsentMessageAsShown(); } /// Computes the DevTools application. Fills in the devtoolsPlatformType and /// devtoolsChrome. void computeDevToolsCustomGTagsData() { // Platform final String platform = window.navigator.platform; platform.replaceAll(' ', '_'); devtoolsPlatformType = platform; final String appVersion = window.navigator.appVersion; final List<String> splits = appVersion.split(' '); final len = splits.length; for (int index = 0; index < len; index++) { final String value = splits[index]; // Chrome or Chrome iOS if (value.startsWith(devToolsChromeName) || value.startsWith(devToolsChromeIos)) { devtoolsChrome = value; } else if (value.startsWith('Android')) { // appVersion for Android is 'Android n.n.n' devtoolsPlatformType = '$devToolsPlatformTypeAndroid${splits[index + 1]}'; } else if (value == devToolsChromeOS) { // Chrome OS will return a platform e.g., CrOS_Linux_x86_64 devtoolsPlatformType = '${devToolsChromeOS}_$platform'; } } } // Look at the query parameters '&ide=' and record in GA. void computeDevToolsQueryParams() { _ideLaunched = ideLaunchedCLI; // Default is Command Line launch. final ideValue = ideFromUrl(); if (ideValue != null) { _ideLaunched = ideValue; } final ideFeature = lookupFromQueryParams('ideFeature'); if (ideFeature != null) { ideLaunchedFeature = ideFeature; } } Future<void> computeFlutterClientId() async { flutterClientId = await server.flutterGAClientID(); } int _stillWaiting = 0; void waitForDimensionsComputed(String screenName) { Timer(const Duration(milliseconds: 100), () { if (_analyticsComputed) { screen(screenName); } else { if (_stillWaiting++ < 50) { waitForDimensionsComputed(screenName); } else { _log.warning('Cancel waiting for dimensions.'); } } }); } Future<void> setupDimensions() async { if (!_analyticsComputed && !_computingDimensions) { _computingDimensions = true; computeDevToolsCustomGTagsData(); computeDevToolsQueryParams(); await computeFlutterClientId(); _analyticsComputed = true; } } void setupUserApplicationDimensions() { if (serviceConnection.serviceManager.connectedApp != null && !_userApplicationDimensionsComputed && !_computingUserApplicationDimensions) { _computingUserApplicationDimensions = true; _computeUserApplicationCustomGTagData(); _userApplicationDimensionsComputed = true; } } Map<String, dynamic> generateSurveyQueryParameters() { const ideKey = 'IDE'; const versionKey = 'Version'; const internalKey = 'Internal'; return { ideKey: _ideLaunched, versionKey: devtoolsVersion, internalKey: (!isExternalBuild).toString(), }; }
devtools/packages/devtools_app/lib/src/shared/analytics/_analytics_web.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/analytics/_analytics_web.dart", "repo_id": "devtools", "token_count": 9303 }
94
## DevTools Charting ![GitHub contributors](https://img.shields.io/github/contributors/flutter/devtools.svg) We gladly accept contributions via GitHub pull requests! You must complete the [Contributor License Agreement](https://cla.developers.google.com/clas). You can do this online, and it only takes a minute. If you've never submitted code before, you must add your (or your organization's) name and contact info to the [AUTHORS](AUTHORS) file. See Development prep in [CONTRIBUTING](https://github.com/flutter/devtools/blob/master/CONTRIBUTING.md) ## Overview DevTools has used a number of existing charting packages with various issues e.g., * rich set of charts, more than DevTools would produce * complex abstraction to support rich set of charts * not extensible stuff * not flexible enough without hacky code to augment * not Dart or Flutter compliant This charting subsystem plots [timeseries data](https://en.wikipedia.org/wiki/Time_series). Two basic charts are supported: 1. line chart to display non-numeric values e.g., events 1. scatter chats with or without shading from 0 to their Y coordinate. ## The Data A chart consist of one or more traces. A trace is a collection of data to be plotted in the same chart on the same temporal X-axis (time). For example, a chart could have 4 traces: 1. current capacity of the heap (free/used) at every sample period (time) 1. amount of heap used at every sample period (time) 1. number of objects in the heap at every sample period (time) 1. when a GC (garbage collection) occurred. In all cases, the above 4 traces share the same X-Axis time scale. However, the first two traces have numeric data a real value in total bytes, the third is number of objects and the last is when a GC occurred. There are a few ways to display these seemly disparate pieces of data. ## Charts First, create a StatefulWidget to contain the chart e.g., ``` class MyChart extends StatefulWidget { MyChart({Key key}) : super(key: key); final controller = ChartController(); @override State<StatefulWidget> createState() => MyChartState(); } class MyChartState extends State<MyChart> { MyChartState(this.controller); ChartController get controller => widget.controller; } ``` Then, override the State's initState and build methods in MyChartState e.g., ``` @override void initState() { super.initState(); // If you're creating a line chart then fix the Y-range. For a scatter chart // don't create a fixed range, then the chart will autmatically compute the // min/max range and rescale the axis. controller.setFixedYRange(0.4, 2.4); // Line chart fixed. // Create the traces to hold each set of data points e.g., temperature // collected every hour as well as barametric pressure collected every hour. setupTraces(); } @override Widget build(BuildContext context) { final ballChart = Chart(controller, 'Balls Chart'); return Padding( padding: const EdgeInsets.all(0.0), child: ballChart, ); } ``` ## Create a Trace Create each trace, in this example we're creating a red circle and blue ball to appear at particular points in time. The Y coordinate of a datum (for a line chart) is not significant other than where to place the event in time. For a scatter chart, the datum's Y coordinate would be significant e.g., temperature. For both the line and scatter charts the X coordinate is the time. Important note a trace contains the specific plotting characteristers e.g., color, shape, connected line, etc. This implies that even though different datum could be contained in a single trace each datum would need to hold its rendering characteristics when a datum is rendered in the trace. Considering that a trace may contain many thousands (tens of thousands) of pieces of data that would create unnessary datum overhead as well as more complex painting inside the canvas code when rendering different datum in a trace. The internal chart rendering instead, blasts each trace's data with the same trace's monolithic rendering characterstics. ``` void setupTraces() { // Green Circle greenTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.green, strokeWidth: 4, diameter: 6, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'Green Circle', ); // Small Blue Ball blueTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.blue, symbol: ChartSymbol.disc, diameter: 4, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'Blue Ball', ); // Red Circle redTraceIndex = controller.createTrace( ChartType.symbol, PaintCharacteristics( color: Colors.red, strokeWidth: 4, diameter: 6, fixedMinY: 0.4, fixedMaxY: 2.4, ), name: 'Red Circle', ); } ``` ## Adding Data Create a datum (see Data class) and add the data to a trace (adddatum). In the below example, a datum is created first and added to the green trace (green circle), every second a datum is added to the blue trace (blue ball) then after 30 seconds the last datum is added to the red trace (red circle). ``` static const greenPosition = 0.4; // Starting symbol position static const bluePosition = 1.4; // Every second symbol position static const redPosition = 2.4; // Stoping symbol position var previousTime = DateTime.now(); final startDatum = Data(previousTime.millisecondsSinceEpoch, greenPosition); // Start the heartbeat. controller.addTimestamp(startDatum.timestamp); // Add the first real datum. controller.trace(greenTraceIndex).addDatum(startDatum); Timer.periodic( const Duration(seconds: 1), (Timer timer) { if (controller.trace(blueTraceIndex).data.length < 30) { final currentTime = DateTime.now(); final = currentTime.millisecondsSinceEpoch; // Once a second heartbeat. controller.addTimestamps(timestamp); // Add the blue ball. final datum = Data(timestamp, bluePosition); controller.trace(blueTraceIndex).addDatum(datum); previousTime = currentTime; } else { controller.addTimestamps(previousTime.millisecondsSinceEpoch); final stopDatum = Data( previousTime.millisecondsSinceEpoch, redPosition, ); // Last datum is the red circle. controller.trace(redTraceIndex).addDatum(stopDatum); timer.cancel(); } }, ); ``` Each call to addDatum will 1. notifies the chart that new data has arrived. 1. compute the Y-axis scale (if not fixed) 1. chart the data 1. update the X-axis. One important piece of information is adding a heartbeat. If a live chart is needed where the timeline (X axis) moves in a linear fashion requires adding a heart beat (at the granularity requested of the X axis) a tickstamp is added to the ChartController timestamps field on every tick e.g., ``` controller.addTimestamps(currentTime.millisecondsSinceEpoch) ``` The heartbeat allows the data to be replayed as if the data collection is live, at the same rate of experiencing the collecting of the live data.
devtools/packages/devtools_app/lib/src/shared/charts/README.md/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/charts/README.md", "repo_id": "devtools", "token_count": 2306 }
95
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '_file_desktop.dart' if (dart.library.js_interop) '_file_web.dart'; abstract class FileIO { factory FileIO() { return createFileSystem(); } String exportDirectoryName({bool isMemory = false}); /// Create file in a directory (default Downloads). // TODO(terry): Better directory for Flutter Desktop when API available. // TODO(terry): Flutter Web/HTML port code to create file in Download directory. void writeStringToFile( String filename, String contents, { bool isMemory = false, }); /// Returns content of filename or null if file is unknown or content empty. String? readStringFromFile(String filename, {bool isMemory = false}); /// List of files (basename only). List<String> list({required String prefix, bool isMemory = false}); /// Delete exported files created for testing only. bool deleteFile(String path, {bool isMemory = false}); }
devtools/packages/devtools_app/lib/src/shared/config_specific/file/file.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/file/file.dart", "repo_id": "devtools", "token_count": 298 }
96
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'package:web/web.dart'; import 'logger.dart'; void printToConsole(Object message, [LogLevel level = LogLevel.debug]) { final jsMessage = message.jsify(); switch (level) { case LogLevel.debug: console.log(jsMessage); break; case LogLevel.warning: console.warn(jsMessage); break; case LogLevel.error: console.error(jsMessage); } }
devtools/packages/devtools_app/lib/src/shared/config_specific/logger/_logger_web.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/config_specific/logger/_logger_web.dart", "repo_id": "devtools", "token_count": 205 }
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. /// Inspector specific tree rendering support. /// /// This library must not have direct dependencies on web-only libraries. /// /// This allows tests of the complicated logic in this class to run on the VM. library; import 'package:devtools_app_shared/ui.dart'; import 'package:flutter/foundation.dart'; import '../../diagnostics/diagnostics_node.dart'; import '../../ui/search.dart'; /// Split text into two groups, word characters at the start of a string and all /// other characters. final RegExp treeNodePrimaryDescriptionPattern = RegExp(r'^([\w ]+)(.*)$'); // TODO(jacobr): temporary workaround for missing structure from assertion thrown building // widget errors. final RegExp assertionThrownBuildingError = RegExp( r'^(The following assertion was thrown building [a-zA-Z]+)(\(.*\))(:)$', ); typedef TreeEventCallback = void Function(InspectorTreeNode node); const double iconPadding = 4.0; const double chartLineStrokeWidth = 1.0; double get inspectorColumnWidth => scaleByFontFactor(12.0); double get inspectorRowHeight => scaleByFontFactor(16.0); /// This class could be refactored out to be a reasonable generic collapsible /// tree ui node class but we choose to instead make it widget inspector /// specific as that is the only case we care about. // TODO(kenz): extend TreeNode class to share tree logic. class InspectorTreeNode { InspectorTreeNode({ InspectorTreeNode? parent, bool expandChildren = true, }) : _children = <InspectorTreeNode>[], _parent = parent, _isExpanded = expandChildren; bool get showLinesToChildren { return _children.length > 1 && !_children.last.isProperty; } bool get isDirty => _isDirty; bool _isDirty = true; set isDirty(bool dirty) { if (dirty) { _isDirty = true; _shouldShow = null; if (_childrenCount == null) { // Already dirty. return; } _childrenCount = null; if (parent != null) { parent!.isDirty = true; } } else { _isDirty = false; } } /// Returns whether the node is currently visible in the tree. void updateShouldShow(bool value) { if (value != _shouldShow) { _shouldShow = value; for (var child in children) { child.updateShouldShow(value); } } } bool get shouldShow { final parentLocal = parent; _shouldShow ??= parentLocal == null || parentLocal.isExpanded && parentLocal.shouldShow; return _shouldShow!; } bool? _shouldShow; bool selected = false; RemoteDiagnosticsNode? _diagnostic; final List<InspectorTreeNode> _children; Iterable<InspectorTreeNode> get children => _children; bool get isProperty { final diagnosticLocal = diagnostic; return diagnosticLocal == null || diagnosticLocal.isProperty; } bool get isExpanded => _isExpanded; bool _isExpanded; bool allowExpandCollapse = true; bool get showExpandCollapse { return (diagnostic?.hasChildren == true || children.isNotEmpty) && allowExpandCollapse; } set isExpanded(bool value) { if (value != _isExpanded) { _isExpanded = value; isDirty = true; if (_shouldShow ?? false) { for (var child in children) { child.updateShouldShow(value); } } } } InspectorTreeNode? get parent => _parent; InspectorTreeNode? _parent; set parent(InspectorTreeNode? value) { _parent = value; _parent?.isDirty = true; } RemoteDiagnosticsNode? get diagnostic => _diagnostic; set diagnostic(RemoteDiagnosticsNode? v) { final value = v!; _diagnostic = value; _isExpanded = value.childrenReady; isDirty = true; } int get childrenCount { if (!isExpanded) { _childrenCount = 0; } final childrenCountLocal = _childrenCount; if (childrenCountLocal != null) { return childrenCountLocal; } int count = 0; for (InspectorTreeNode child in _children) { count += child.subtreeSize; } return _childrenCount = count; } bool get hasPlaceholderChildren { return children.length == 1 && children.first.diagnostic == null; } int? _childrenCount; int get subtreeSize => childrenCount + 1; // TODO(jacobr): move getRowIndex to the InspectorTree class. int getRowIndex(InspectorTreeNode node) { int index = 0; while (true) { final InspectorTreeNode? parent = node.parent; if (parent == null) { break; } for (InspectorTreeNode sibling in parent._children) { if (sibling == node) { break; } index += sibling.subtreeSize; } index += 1; // For parent itself. node = parent; } return index; } // TODO(jacobr): move this method to the InspectorTree class. // TODO: optimize this method. /// Use [getCachedRow] wherever possible, as [getRow] is slow and can cause /// performance problems. InspectorTreeRow? getRow(int index) { if (subtreeSize <= index) { return null; } final List<int> ticks = <int>[]; InspectorTreeNode node = this; int current = 0; int depth = 0; // Iterate till getting the result to return. while (true) { final style = node.diagnostic?.style; final bool indented = style != DiagnosticsTreeStyle.flat && style != DiagnosticsTreeStyle.error; if (current == index) { return InspectorTreeRow( node: node, index: index, ticks: ticks, depth: depth, lineToParent: !node.isProperty && index != 0 && node.parent!.showLinesToChildren, ); } assert(index > current); current++; final List<InspectorTreeNode> children = node._children; int i; for (i = 0; i < children.length; ++i) { final child = children[i]; final subtreeSize = child.subtreeSize; if (current + subtreeSize > index) { node = child; if (children.length > 1 && i + 1 != children.length && !children.last.isProperty) { if (indented) { ticks.add(depth); } } break; } current += subtreeSize; } assert(i < children.length); if (indented) { depth++; } } } void removeChild(InspectorTreeNode child) { child.parent = null; final removed = _children.remove(child); assert(removed); isDirty = true; } void appendChild(InspectorTreeNode child) { _children.add(child); child.parent = this; isDirty = true; } void clearChildren() { _children.clear(); isDirty = true; } } /// A row in the tree with all information required to render it. class InspectorTreeRow with SearchableDataMixin { InspectorTreeRow({ required this.node, required this.index, required this.ticks, required this.depth, required this.lineToParent, }); final InspectorTreeNode node; /// Column indexes of ticks to draw lines from parents to children. final List<int> ticks; final int depth; final int index; final bool lineToParent; bool get isSelected => node.selected; } /// Callback issued every time a node is added to the tree. typedef NodeAddedCallback = void Function( InspectorTreeNode node, RemoteDiagnosticsNode diagnosticsNode, ); class InspectorTreeConfig { InspectorTreeConfig({ this.onNodeAdded, this.onClientActiveChange, this.onSelectionChange, this.onExpand, }); final NodeAddedCallback? onNodeAdded; final VoidCallback? onSelectionChange; final void Function(bool added)? onClientActiveChange; final TreeEventCallback? onExpand; } enum SearchTargetType { widget, // TODO(https://github.com/flutter/devtools/issues/3489) implement other search scopes: details, all etc }
devtools/packages/devtools_app/lib/src/shared/console/eval/inspector_tree.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/console/eval/inspector_tree.dart", "repo_id": "devtools", "token_count": 2939 }
98
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:vm_service/vm_service.dart'; import '../primitives/enum_utils.dart'; import '../primitives/utils.dart'; import '../ui/icons.dart'; import 'object_group_api.dart'; import 'primitives/instance_ref.dart'; import 'primitives/source_location.dart'; final diagnosticLevelUtils = EnumUtils<DiagnosticLevel>(DiagnosticLevel.values); final treeStyleUtils = EnumUtils<DiagnosticsTreeStyle>(DiagnosticsTreeStyle.values); /// Defines diagnostics data for a [value]. /// /// [RemoteDiagnosticsNode] provides a high quality multi-line string dump via /// [toStringDeep]. The core members are the [name], [toDescription], /// [getProperties], [value], and [getChildren]. All other members exist /// typically to provide hints for how [toStringDeep] and debugging tools should /// format output. /// /// See also: /// /// * DiagnosticsNode class defined at https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/foundation/diagnostics.dart /// The difference is the class hierarchy is collapsed here as in /// package:flutter the subclasses exist more to simplify creation /// of Diagnostics than because the class hierarchy of Diagnostics is /// important. If you need to determine the exact Diagnostic class on the /// Dart side you can use the value of type. The raw Dart object value is /// also available via the getValue() method. class RemoteDiagnosticsNode extends DiagnosticableTree { RemoteDiagnosticsNode( this.json, this.objectGroupApi, this.isProperty, this.parent, ); /// Stores the [TextStyle] that was used when building the description. /// /// When not set, then the description has not been built yet. /// This style is used when approximating the length of the /// [DiagnosticsNodeDescription], to ensure we are approximating the content /// area using the right style. TextStyle? descriptionTextStyleFromBuild; static final CustomIconMaker iconMaker = CustomIconMaker(); static BoxConstraints deserializeConstraints(Map<String, Object?> json) { return BoxConstraints( minWidth: double.parse(json['minWidth'] as String? ?? '0.0'), maxWidth: double.parse(json['maxWidth'] as String? ?? 'Infinity'), minHeight: double.parse(json['minHeight'] as String? ?? '0.0'), maxHeight: double.parse(json['maxHeight'] as String? ?? 'Infinity'), ); } static BoxParentData deserializeParentData(Map<String, Object?> json) { return BoxParentData() ..offset = Offset( double.parse(json['offsetX'] as String? ?? '0.0'), double.parse(json['offsetY'] as String? ?? '0.0'), ); } static Size deserializeSize(Map<String, Object> json) { return Size( double.parse(json['width'] as String), double.parse(json['height'] as String), ); } static FlexFit deserializeFlexFit(String? flexFit) { if (flexFit == 'tight') return FlexFit.tight; return FlexFit.loose; } /// This node's parent (if it's been set). RemoteDiagnosticsNode? parent; Future<String>? propertyDocFuture; List<RemoteDiagnosticsNode>? cachedProperties; /// Service used to retrieve more detailed information about the value of /// the property and its children and properties. final InspectorObjectGroupApi<RemoteDiagnosticsNode>? objectGroupApi; /// JSON describing the diagnostic node. final Map<String, Object?> json; Future<Map<String, InstanceRef>?>? _valueProperties; final bool isProperty; // TODO(albertusangga): Refactor to cleaner/more robust solution bool get isFlex => ['Row', 'Column', 'Flex'].contains(widgetRuntimeType); bool get isBox => json['isBox'] == true; int? get flexFactor => json['flexFactor'] as int?; FlexFit get flexFit => deserializeFlexFit(json['flexFit'] as String?); RemoteDiagnosticsNode? get renderObject { if (_renderObject != null) return _renderObject; final data = json['renderObject']; if (data == null) return null; _renderObject = RemoteDiagnosticsNode( data as Map<String, Object?>? ?? {}, objectGroupApi, false, null, ); return _renderObject; } RemoteDiagnosticsNode? _renderObject; RemoteDiagnosticsNode? get parentRenderElement { final data = json['parentRenderElement']; if (data == null) return null; _parentRenderElement = RemoteDiagnosticsNode( data as Map<String, Object?>? ?? {}, objectGroupApi, false, null, ); return _parentRenderElement; } RemoteDiagnosticsNode? _parentRenderElement; BoxConstraints get constraints => deserializeConstraints( json['constraints'] as Map<String, Object?>? ?? {}, ); BoxParentData get parentData => deserializeParentData(json['parentData'] as Map<String, Object?>? ?? {}); // [deserializeSize] expects a parameter of type Map<String, Object> (note the // non-nullable Object), so we need to first type check as a Map and then we // can cast to the expected type. Size get size => deserializeSize( (json['size'] as Map?)?.cast<String, Object>() ?? <String, Object>{}, ); bool get isLocalClass { final objectGroup = objectGroupApi; if (objectGroup != null) { return _isLocalClass ??= objectGroup.isLocalClass(this); } else { // TODO(jacobr): if objectGroup is a Future<ObjectGroup> we cannot compute // whether classes are local as for convenience we need this method to // return synchronously. return _isLocalClass = false; } } bool? _isLocalClass; @override bool operator ==(Object other) { if (other is! RemoteDiagnosticsNode) return false; return jsonEquality(json, other.json); } @override int get hashCode => jsonHashCode(json); @visibleForTesting static int jsonHashCode(Map<String, dynamic> json) { return const DeepCollectionEquality().hash(json); } @visibleForTesting static bool jsonEquality( Map<String, dynamic> json1, Map<String, dynamic> json2, ) { return const DeepCollectionEquality().equals(json1, json2); } /// Separator text to show between property names and values. String get separator => showSeparator ? ':' : ''; /// Label describing the [RemoteDiagnosticsNode], typically shown before a separator /// (see [showSeparator]). /// /// The name should be omitted if the [showName] property is false. String? get name => getStringMember('name'); /// Whether to show a separator between [name] and description. /// /// If false, name and description should be shown with no separation. /// `:` is typically used as a separator when displaying as text. bool get showSeparator => getBooleanMember('showSeparator', true); /// Returns a description with a short summary of the node itself not /// including children or properties. /// /// `parentConfiguration` specifies how the parent is rendered as text art. /// For example, if the parent does not line break between properties, the /// description of a property should also be a single line if possible. String? get description => getStringMember('description'); /// Priority level of the diagnostic used to control which diagnostics should /// be shown and filtered. /// /// Typically this only makes sense to set to a different value than /// [DiagnosticLevel.info] for diagnostics representing properties. Some /// subclasses have a `level` argument to their constructor which influences /// the value returned here but other factors also influence it. For example, /// whether an exception is thrown computing a property value /// [DiagnosticLevel.error] is returned. DiagnosticLevel get level => getLevelMember('level', DiagnosticLevel.info); /// Whether the name of the property should be shown when showing the default /// view of the tree. /// /// This could be set to false (hiding the name) if the value's description /// will make the name self-evident. bool get showName => getBooleanMember('showName', true); /// Description to show if the node has no displayed properties or children. String? getEmptyBodyDescription() => getStringMember('emptyBodyDescription'); late DiagnosticsTreeStyle style = getStyleMember('style', DiagnosticsTreeStyle.sparse); /// Dart class defining the diagnostic node. /// For example, DiagnosticProperty<Color>, IntProperty, StringProperty, etc. /// This should rarely be required except for cases where custom rendering is desired /// of a specific Dart diagnostic class. String? get type => getStringMember('type'); /// Whether the description is enclosed in double quotes. /// /// Only relevant for String properties. bool get isQuoted => getBooleanMember('quoted', false); bool get hasIsQuoted => json.containsKey('quoted'); /// Optional unit the [value] is measured in. /// /// Unit must be acceptable to display immediately after a number with no /// spaces. For example: 'physical pixels per logical pixel' should be a /// [tooltip] not a [unit]. /// /// Only specified for Number properties. String? get unit => getStringMember('unit'); bool get hasUnit => json.containsKey('unit'); /// String describing just the numeric [value] without a unit suffix. /// /// Only specified for Number properties. String? get numberToString => getStringMember('numberToString'); bool get hasNumberToString => json.containsKey('numberToString'); /// Description to use if the property [value] is true. /// /// If not specified and [value] equals true the property's priority [level] /// will be [DiagnosticLevel.hidden]. /// /// Only applies to Flag properties. String? get ifTrue => getStringMember('ifTrue'); bool get hasIfTrue => json.containsKey('ifTrue'); /// Description to use if the property value is false. /// /// If not specified and [value] equals false, the property's priority [level] /// will be [DiagnosticLevel.hidden]. /// /// Only applies to Flag properties. String? get ifFalse => getStringMember('ifFalse'); bool get hasIfFalse => json.containsKey('ifFalse'); /// Value as a List of strings. /// /// The raw value can always be extracted with the regular observatory protocol. /// /// Only applies to IterableProperty. List<String>? get values { final rawValues = json['values'] as List<Object?>?; if (rawValues == null) { return null; } return List<String>.from(rawValues); } /// Whether each of the values is itself a primitive value. /// /// For example, bool|num|string are primitive values. This is useful as for /// non-primitive values, the user may want to view the value with an /// interactive object debugger view to get more information on what the value /// is. List<bool>? get primitiveValues { final rawValues = json['primitiveValues'] as List<Object?>?; if (rawValues == null) { return null; } return List<bool>.from(rawValues); } bool get hasValues => json.containsKey('values'); /// Description to use if the property [value] is not null. /// /// If the property [value] is not null and [ifPresent] is null, the /// [level] for the property is [DiagnosticsLevel.hidden] and the description /// from superclass is used. /// /// Only specified for ObjectFlagProperty. String? get ifPresent => getStringMember('ifPresent'); bool get hasIfPresent => json.containsKey('ifPresent'); /// If the [value] of the property equals [defaultValue] the priority [level] /// of the property is downgraded to [DiagnosticLevel.fine] as the property /// value is uninteresting. /// /// This is the default value of the object represented as a String. /// The actual Dart object representing the defaultValue can also be accessed via /// the observatory protocol. We can add a convenience helper method to access it here /// if there is a use case. /// /// Typically you shouldn't need to worry about the default value as the underlying /// machinery will generate appropriate description and priority level based on the /// default value. String? get defaultValue => getStringMember('defaultValue'); /// Whether a property has a default value. bool get hasDefaultValue => json.containsKey('defaultValue'); /// Description if the property description would otherwise be empty. /// /// Consider showing the property value in gray in an IDE if the description matches /// ifEmpty. String? get ifEmpty => getStringMember('ifEmpty'); /// Description if the property [value] is null. String? get ifNull => getStringMember('ifNull'); bool get allowWrap => getBooleanMember('allowWrap', true); /// Optional tooltip typically describing the property. /// /// Example tooltip: 'physical pixels per logical pixel' /// /// If present, the tooltip is added in parenthesis after the raw value when /// generating the string description. String get tooltip => getStringMember('tooltip') ?? ''; bool get hasTooltip => json.containsKey('tooltip'); /// Whether a [value] of null causes the property to have [level] /// [DiagnosticLevel.warning] warning that the property is missing a [value]. bool get missingIfNull => getBooleanMember('missingIfNull', false); /// String representation of exception thrown if accessing the property /// [value] threw an exception. String? get exception => getStringMember('exception'); /// Whether accessing the property throws an exception. bool get hasException => json.containsKey('exception'); bool get hasCreationLocation { return _creationLocation != null || json.containsKey('creationLocation'); } /// Location id compatible with rebuild location tracking code. int get locationId => JsonUtils.getIntMember(json, 'locationId'); set creationLocation(InspectorSourceLocation? location) { _creationLocation = location; } InspectorSourceLocation? _creationLocation; InspectorSourceLocation? get creationLocation { if (_creationLocation != null) { return _creationLocation; } if (!hasCreationLocation) { return null; } _creationLocation = InspectorSourceLocation( json['creationLocation'] as Map<String, Object?>? ?? {}, null, ); return _creationLocation; } /// String representation of the type of the property [value]. /// /// This is determined from the type argument `T` used to instantiate the /// [DiagnosticsProperty] class. This means that the type is available even if /// [value] is null, but it also means that the [propertyType] is only as /// accurate as the type provided when invoking the constructor. /// /// Generally, this is only useful for diagnostic tools that should display /// null values in a manner consistent with the property type. For example, a /// tool might display a null [Color] value as an empty rectangle instead of /// the word "null". String? get propertyType => getStringMember('propertyType'); /// If the [value] of the property equals [defaultValue] the priority [level] /// of the property is downgraded to [DiagnosticLevel.fine] as the property /// value is uninteresting. /// /// [defaultValue] has type [T] or is [kNoDefaultValue]. DiagnosticLevel get defaultLevel { return getLevelMember('defaultLevel', DiagnosticLevel.info); } /// Whether the value of the property is a Diagnosticable value itself. /// Optionally, properties that are themselves Diagnosticable should be /// displayed as trees of Diagnosticable properties and children. /// /// TODO(jacobr): add helpers to get the properties and children of /// this Diagnosticable value even if getChildren and getProperties /// would return null. This will allow showing nested data for properties /// that don't show children by default in other debugging output but /// could. bool get isDiagnosticableValue { return getBooleanMember('isDiagnosticableValue', false); } String? getStringMember(String memberName) { return JsonUtils.getStringMember(json, memberName); } bool getBooleanMember(String memberName, bool defaultValue) { if (json[memberName] == null) { return defaultValue; } return json[memberName] as bool; } DiagnosticLevel getLevelMember( String memberName, DiagnosticLevel defaultValue, ) { final value = json[memberName] as String?; if (value == null) { return defaultValue; } return diagnosticLevelUtils.enumEntry(value)!; } DiagnosticsTreeStyle getStyleMember( String memberName, DiagnosticsTreeStyle defaultValue, ) { if (!json.containsKey(memberName)) { return defaultValue; } final value = json[memberName] as String?; if (value == null) { return defaultValue; } return treeStyleUtils.enumEntry(value)!; } /// Returns a reference to the value the DiagnosticsNode object is describing. InspectorInstanceRef get valueRef => InspectorInstanceRef(json['valueId'] as String?); bool isEnumProperty() { return type?.startsWith('EnumProperty<') ?? false; } /// Returns a list of raw Dart property values of the Dart value of this /// property that are useful for custom display of the property value. /// For example, get the red, green, and blue components of color. /// /// Unfortunately we cannot just use the list of fields from the Observatory /// Instance object for the Dart value because much of the relevant /// information to display good visualizations of Flutter values is stored /// in properties not in fields. Future<Map<String, InstanceRef>?> get valueProperties async { if (_valueProperties == null) { if (propertyType == null || valueRef.id == null) { return _valueProperties = Future.value(); } if (isEnumProperty()) { // Populate all the enum property values. return objectGroupApi?.getEnumPropertyValues(valueRef); } List<String> propertyNames; // Add more cases here as visual displays for additional Dart objects // are added. switch (propertyType) { case 'Color': propertyNames = ['red', 'green', 'blue', 'alpha']; break; case 'IconData': propertyNames = ['codePoint']; break; default: return _valueProperties = Future.value(); } _valueProperties = objectGroupApi?.getDartObjectProperties(valueRef, propertyNames); } return _valueProperties; } Map<String, Object?>? get valuePropertiesJson => json['valueProperties'] as Map<String, Object?>?; bool get hasChildren { // In the summary tree, json['hasChildren']==true when the node has details // tree children so we need to first check whether the list of children for // the node in the tree was specified. If there is an empty list of children // that indicates the node should have no children in the tree while if the // 'children' property is not specified it means we do not know whether // there is a list of children and need to query the server to find out. final children = json['children'] as List<Object?>?; if (children != null) { return children.isNotEmpty; } return getBooleanMember('hasChildren', false); } bool get isCreatedByLocalProject { return getBooleanMember('createdByLocalProject', false); } /// Whether this node is being displayed as a full tree or a filtered tree. bool get isSummaryTree => getBooleanMember('summaryTree', false); /// Whether this node is being displayed as a full tree or a filtered tree. bool get isStateful => getBooleanMember('stateful', false); String? get widgetRuntimeType => getStringMember('widgetRuntimeType'); /// Check whether children are already available. bool get childrenReady { return json.containsKey('children') || _children != null || !hasChildren; } Future<List<RemoteDiagnosticsNode>?> get children async { await _computeChildren(); if (_children != null) return _children; return await _childrenFuture; } List<RemoteDiagnosticsNode> get childrenNow { _maybePopulateChildren(); return _children ?? []; } Future<void> _computeChildren() async { _maybePopulateChildren(); if (!hasChildren || _children != null) { return; } if (_childrenFuture != null) { await _childrenFuture; return; } _childrenFuture = _getChildrenHelper(); try { _children = await _childrenFuture; } finally { _children ??= []; } } Future<List<RemoteDiagnosticsNode>> _getChildrenHelper() { return objectGroupApi!.getChildren( valueRef, isSummaryTree, this, ); } void _maybePopulateChildren() { if (!hasChildren || _children != null) { return; } final jsonArray = json['children'] as List<Object?>?; if (jsonArray?.isNotEmpty == true) { final nodes = <RemoteDiagnosticsNode>[]; for (var element in jsonArray!.cast<Map<String, Object?>>()) { final child = RemoteDiagnosticsNode(element, objectGroupApi, false, parent); child.parent = this; nodes.add(child); } _children = nodes; } } Future<List<RemoteDiagnosticsNode>>? _childrenFuture; List<RemoteDiagnosticsNode>? _children; /// Properties to show inline in the widget tree. List<RemoteDiagnosticsNode> get inlineProperties { if (cachedProperties == null) { cachedProperties = []; if (json.containsKey('properties')) { final jsonArray = json['properties'] as List<Object?>; for (var element in jsonArray.cast<Map<String, Object?>>()) { cachedProperties!.add( RemoteDiagnosticsNode(element, objectGroupApi, true, parent), ); } } } return cachedProperties!; } Future<List<RemoteDiagnosticsNode>> getProperties( InspectorObjectGroupApi<RemoteDiagnosticsNode> objectGroup, ) async { return await objectGroup.getProperties(valueRef); } Widget? get icon { if (isProperty) return null; return iconMaker.fromWidgetName(widgetRuntimeType); } /// Returns true if two diagnostic nodes are indistinguishable from /// the perspective of a user debugging. /// /// In practice this means that all fields but the objectId and valueId /// properties for the DiagnosticsNode objects are identical. The valueId /// field may change even for properties that have not changed because in /// some cases such as the 'created' property for an element, the property /// value is created dynamically each time 'getProperties' is called. bool identicalDisplay(RemoteDiagnosticsNode node) { final entries = json.entries; if (entries.length != node.json.entries.length) { return false; } for (var entry in entries) { final String key = entry.key; if (key == 'valueId') { continue; } if (entry.value == node.json[key]) { return false; } } return true; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); for (var property in inlineProperties) { properties.add(DiagnosticsProperty(property.name, property)); } } @override List<DiagnosticsNode> debugDescribeChildren() { final children = childrenNow; if (children.isEmpty) return const <DiagnosticsNode>[]; final regularChildren = <DiagnosticsNode>[]; for (var child in children) { regularChildren.add(child.toDiagnosticsNode()); } return regularChildren; } @override DiagnosticsNode toDiagnosticsNode({ String? name, DiagnosticsTreeStyle? style, }) { return super.toDiagnosticsNode( name: name ?? this.name, style: style ?? DiagnosticsTreeStyle.sparse, ); } @override String toStringShort() { return description ?? ''; } Future<void> setSelectionInspector(bool uiAlreadyUpdated) async { final objectGroup = objectGroupApi; if (objectGroup != null && objectGroup.canSetSelectionInspector) { await objectGroup.setSelectionInspector(valueRef, uiAlreadyUpdated); } } }
devtools/packages/devtools_app/lib/src/shared/diagnostics/diagnostics_node.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/diagnostics/diagnostics_node.dart", "repo_id": "devtools", "token_count": 7435 }
99
// 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 '../../screens/debugger/codeview.dart'; import '../common_widgets.dart'; import '../diagnostics/inspector_service.dart'; abstract class DevToolsEnvironmentParameters { List<ScriptPopupMenuOption> buildExtraDebuggerScriptPopupMenuOptions(); Link issueTrackerLink({String? additionalInfo, String? issueTitle}); String? username(); String loadingAppSizeDataMessage(); InspectorServiceBase? inspectorServiceProvider(); Link? enableSourceMapsLink(); String get perfettoIndexLocation; String? chrome115BreakpointBug(); }
devtools/packages/devtools_app/lib/src/shared/environment_parameters/environment_parameters_base.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/environment_parameters/environment_parameters_base.dart", "repo_id": "devtools", "token_count": 190 }
100
// 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:logging/logging.dart'; import 'primitives/utils.dart'; /// Class for storing a limited number string messages. class LogStorage { static const int maxLogEntries = 4000; final Queue<LogRecord> _logs = Queue<LogRecord>(); /// Adds [message] to the end of the log queue. /// /// If there are more than [maxLogEntries] messages in the logs, then the /// oldest message will be removed from the queue. void addLog(LogRecord record) { _logs.add(record); if (_logs.length > maxLogEntries) { _logs.removeFirst(); } } /// Clears the queue of logs. void clear() { _logs.clear(); } @override String toString() { return toJsonLog(); } String toJsonLog() { return _logs .map( (e) => jsonEncode({ 'level': e.level.name, 'message': e.message, 'timestamp': e.time.toUtc().toString(), 'loggerName': e.loggerName, if (e.error != null) 'error': e.error.toString(), if (e.stackTrace != null) 'stackTrace': e.stackTrace.toString(), }), ) .joinWithTrailing('\n'); } /// Static instance for storing the app's logs. static final LogStorage root = LogStorage(); }
devtools/packages/devtools_app/lib/src/shared/log_storage.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/log_storage.dart", "repo_id": "devtools", "token_count": 569 }
101
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import '../../service/vm_service_wrapper.dart'; import '../analytics/analytics.dart' as ga; import '../analytics/constants.dart' as gac; import '../config_specific/logger/logger_helpers.dart'; import '../constants.dart'; import '../diagnostics/inspector_service.dart'; import '../globals.dart'; import '../utils.dart'; part '_extension_preferences.dart'; part '_inspector_preferences.dart'; part '_memory_preferences.dart'; part '_performance_preferences.dart'; const _thirdPartyPathSegment = 'third_party'; /// A controller for global application preferences. class PreferencesController extends DisposableController with AutoDisposeControllerMixin { final darkModeTheme = ValueNotifier<bool>(true); final vmDeveloperModeEnabled = ValueNotifier<bool>(false); final verboseLoggingEnabled = ValueNotifier<bool>(Logger.root.level == verboseLoggingLevel); static const _verboseLoggingStorageId = 'verboseLogging'; InspectorPreferencesController get inspector => _inspector; final _inspector = InspectorPreferencesController(); MemoryPreferencesController get memory => _memory; final _memory = MemoryPreferencesController(); PerformancePreferencesController get performance => _performance; final _performance = PerformancePreferencesController(); ExtensionsPreferencesController get devToolsExtensions => _extensions; final _extensions = ExtensionsPreferencesController(); Future<void> init() async { // Get the current values and listen for and write back changes. final darkModeValue = await storage.getValue('ui.darkMode'); final useDarkMode = (darkModeValue == null && useDarkThemeAsDefault) || darkModeValue == 'true'; toggleDarkModeTheme(useDarkMode); addAutoDisposeListener(darkModeTheme, () { storage.setValue('ui.darkMode', '${darkModeTheme.value}'); }); final vmDeveloperModeValue = await boolValueFromStorage( 'ui.vmDeveloperMode', defaultsTo: false, ); toggleVmDeveloperMode(vmDeveloperModeValue); addAutoDisposeListener(vmDeveloperModeEnabled, () { storage.setValue('ui.vmDeveloperMode', '${vmDeveloperModeEnabled.value}'); }); await _initVerboseLogging(); await inspector.init(); await memory.init(); await performance.init(); await devToolsExtensions.init(); setGlobal(PreferencesController, this); } Future<void> _initVerboseLogging() async { final verboseLoggingEnabledValue = await boolValueFromStorage( _verboseLoggingStorageId, defaultsTo: false, ); toggleVerboseLogging(verboseLoggingEnabledValue); addAutoDisposeListener(verboseLoggingEnabled, () { storage.setValue( 'verboseLogging', verboseLoggingEnabled.value.toString(), ); }); } @override void dispose() { inspector.dispose(); memory.dispose(); performance.dispose(); devToolsExtensions.dispose(); super.dispose(); } /// Change the value for the dark mode setting. void toggleDarkModeTheme(bool? useDarkMode) { if (useDarkMode != null) { darkModeTheme.value = useDarkMode; } } /// Change the value for the VM developer mode setting. void toggleVmDeveloperMode(bool? enableVmDeveloperMode) { if (enableVmDeveloperMode != null) { vmDeveloperModeEnabled.value = enableVmDeveloperMode; VmServiceWrapper.enablePrivateRpcs = enableVmDeveloperMode; } } void toggleVerboseLogging(bool? enableVerboseLogging) { if (enableVerboseLogging != null) { verboseLoggingEnabled.value = enableVerboseLogging; if (enableVerboseLogging) { setDevToolsLoggingLevel(verboseLoggingLevel); } else { setDevToolsLoggingLevel(basicLoggingLevel); } } } } /// Retrieves a boolean value from the preferences stored in local storage. /// /// If the value is not present in the stored preferences, this will default to /// the value specified by [defaultsTo]. Future<bool> boolValueFromStorage( String storageKey, { required bool defaultsTo, }) async { final value = await storage.getValue(storageKey); return defaultsTo ? value != 'false' : value == 'true'; }
devtools/packages/devtools_app/lib/src/shared/preferences/preferences.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/preferences/preferences.dart", "repo_id": "devtools", "token_count": 1475 }
102
// 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. /// An abstract implementation of a key value store. /// /// We have concrete implementations for Flutter web, Flutter desktop, and /// Flutter web when launched from the DevTools server. abstract class Storage { /// Return the value associated with the given key. Future<String?> getValue(String key); /// Set a value for the given key. Future<void> setValue(String key, String value); }
devtools/packages/devtools_app/lib/src/shared/primitives/storage.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/primitives/storage.dart", "repo_id": "devtools", "token_count": 143 }
103
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. part of 'server.dart'; /// Set DevTools parameter value for the active survey (e.g. 'Q1-2020'). /// /// The value is stored in the file '~/.flutter-devtools/.devtools'. /// /// This method must be called before calling other survey related methods /// ([isSurveyActionTaken], [setSurveyActionTaken], [surveyShownCount], /// [incrementSurveyShownCount]). If the active survey is not set, warnings are /// logged. Future<bool> setActiveSurvey(String value) async { if (isDevToolsServerAvailable) { final resp = await request( '$apiSetActiveSurvey' '?$activeSurveyName=$value', ); if ((resp?.statusOk ?? false) && json.decode(resp!.body)) { return true; } else { logWarning(resp, apiSetActiveSurvey); } } return false; } /// Request DevTools property value 'surveyActionTaken' for the active survey. /// /// The value is stored in the file '~/.flutter-devtools/.devtools'. /// /// Requires [setActiveSurvey] to have been called prior to calling this method. Future<bool> surveyActionTaken() async { bool surveyActionTaken = false; if (isDevToolsServerAvailable) { final resp = await request(apiGetSurveyActionTaken); if (resp?.statusOk ?? false) { surveyActionTaken = json.decode(resp!.body); } else { logWarning(resp, apiGetSurveyActionTaken); } } return surveyActionTaken; } /// Set DevTools property value 'surveyActionTaken' for the active survey. /// /// The value is stored in the file '~/.flutter-devtools/.devtools'. /// /// Requires [setActiveSurvey] to have been called prior to calling this method. Future<void> setSurveyActionTaken() async { if (isDevToolsServerAvailable) { final resp = await request( '$apiSetSurveyActionTaken' '?$surveyActionTakenPropertyName=true', ); if (resp == null || !resp.statusOk || !(json.decode(resp.body) as bool)) { logWarning(resp, apiSetSurveyActionTaken); } } } /// Request DevTools property value 'surveyShownCount' for the active survey. /// /// The value is stored in the file '~/.flutter-devtools/.devtools'. /// /// Requires [setActiveSurvey] to have been called prior to calling this method. Future<int> surveyShownCount() async { int surveyShownCount = 0; if (isDevToolsServerAvailable) { final resp = await request(apiGetSurveyShownCount); if (resp?.statusOk ?? false) { surveyShownCount = json.decode(resp!.body); } else { logWarning(resp, apiGetSurveyShownCount); } } return surveyShownCount; } /// Increment DevTools property value 'surveyShownCount' for the active survey. /// /// The value is stored in the file '~/.flutter-devtools/.devtools'. /// /// Requires [setActiveSurvey] to have been called prior to calling this method. Future<int> incrementSurveyShownCount() async { // Any failure will still return 0. int surveyShownCount = 0; if (isDevToolsServerAvailable) { final resp = await request(apiIncrementSurveyShownCount); if (resp?.statusOk ?? false) { surveyShownCount = json.decode(resp!.body); } else { logWarning(resp, apiIncrementSurveyShownCount); } } return surveyShownCount; }
devtools/packages/devtools_app/lib/src/shared/server/_survey_api.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/server/_survey_api.dart", "repo_id": "devtools", "token_count": 1102 }
104
// 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 'utils.dart'; /// This file holds color constants that are used throughout DevTools. // TODO(kenz): move colors from other pages to this file for consistency. const mainUiColor = Color(0xFF88B1DE); const mainRasterColor = Color(0xFF2C5DAA); const mainUnknownColor = Color(0xFFCAB8E9); const mainAsyncColor = Color(0xFF80CBC4); final uiColorPalette = [ const ColorPair(background: mainUiColor, foreground: Colors.black), const ColorPair(background: Color(0xFF6793CD), foreground: Colors.black), ]; final rasterColorPalette = [ const ColorPair( background: mainRasterColor, foreground: Colors.white, ), const ColorPair( background: Color(0xFF386EB6), foreground: Colors.white, ), ]; // TODO(jacobr): merge this with other color scheme extensions. extension FlameChartColorScheme on ColorScheme { Color get selectedFrameBackgroundColor => isLight ? const Color(0xFFDBDDDD) : const Color(0xFF4E4F4F); Color get treeGuidelineColor => isLight ? Colors.black54 : const Color.fromARGB(255, 200, 200, 200); } // Teal 200, 400 - see https://material.io/design/color/#tools-for-picking-colors. const asyncColorPalette = [ ColorPair(background: mainAsyncColor, foreground: Colors.black), ColorPair(background: Color(0xFF26A69A), foreground: Colors.black), ]; // Slight variation on Deep purple 100, 300 - see https://material.io/design/color/#tools-for-picking-colors. const unknownColorPalette = [ ColorPair(background: mainUnknownColor, foreground: Colors.black), ColorPair(background: Color(0xFF9D84CA), foreground: Colors.black), ]; const uiJankColor = Color(0xFFF5846B); const rasterJankColor = Color(0xFFC3595A); const shaderCompilationColor = ColorPair( background: Color(0xFF77102F), foreground: Colors.white, ); const treemapIncreaseColor = Color(0xFF3FB549); const treemapDecreaseColor = Color(0xFF77102F); const tableIncreaseColor = Color(0xFF73BF43); const tableDecreaseColor = Color(0xFFEE284F); const treemapDeferredColor = Color(0xFFBDBDBD); const appCodeColor = ThemedColorPair( background: ThemedColor( light: Color(0xFFFA7B17), dark: Color(0xFFFCAD70), ), foreground: ThemedColor.fromSingle(Color(0xFF202124)), ); const nativeCodeColor = ThemedColorPair( background: ThemedColor( light: Color(0xFF007B83), dark: Color(0xFF72B6C6), ), foreground: ThemedColor( light: Color(0xFFF8F9FA), dark: Color(0xFF202124), ), ); const flutterCoreColor = ThemedColorPair( background: ThemedColor( light: Color(0xFF6864D3), dark: Color(0xFF928EF9), ), foreground: ThemedColor( light: Color(0xFFF8F9FA), dark: Color(0xFF202124), ), ); const dartCoreColor = ThemedColorPair( background: ThemedColor( light: Color(0xFF1D649C), dark: Color(0xFF6887F7), ), foreground: ThemedColor( light: Color(0xFFF8F9FA), dark: Color(0xFF202124), ), ); extension SyntaxHighlightingExtension on ColorScheme { Color get functionSyntaxColor => isLight ? const Color(0xFF795E26) : const Color(0xFFDCDCAA); Color get declarationsSyntaxColor => isLight ? const Color(0xFF267f99) : const Color(0xFF4EC9B0); Color get modifierSyntaxColor => isLight ? const Color(0xFF0000FF) : const Color(0xFF569CD6); Color get controlFlowSyntaxColor => isLight ? const Color(0xFFAF00DB) : const Color(0xFFC586C0); Color get variableSyntaxColor => isLight ? const Color(0xFF001080) : const Color(0xFF9CDCFE); Color get commentSyntaxColor => isLight ? const Color(0xFF008000) : const Color(0xFF6A9955); Color get stringSyntaxColor => isLight ? const Color(0xFFB20001) : const Color(0xFFD88E73); Color get numericConstantSyntaxColor => isLight ? const Color(0xFF098658) : const Color(0xFFB5CEA8); } // TODO(kenz): try to get rid of these colors and replace with something from // the light and dark DevTools color schemes. extension DevToolsColorExtension on ColorScheme { // TODO(jacobr): replace this with Theme.of(context).scaffoldBackgroundColor, but we use // this in places where we do not have access to the context. // remove. // TODO(kenz): get rid of this. Color get defaultBackgroundColor => isLight ? Colors.grey[50]! : const Color(0xFF1B1B1F); Color get grey => const Color.fromARGB(255, 128, 128, 128); Color get green => const Color.fromARGB(255, 156, 233, 195); Color get overlayShadowColor => const Color.fromRGBO(0, 0, 0, 0.5); Color get deeplinkUnavailableColor => const Color(0xFFFE7C04); Color get deeplinkTableHeaderColor => Colors.black; }
devtools/packages/devtools_app/lib/src/shared/ui/colors.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/shared/ui/colors.dart", "repo_id": "devtools", "token_count": 1724 }
105
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_shared/devtools_extensions.dart'; import 'package:flutter/material.dart'; import '../../extensions/extension_screen.dart'; import '../../extensions/extension_service.dart'; import '../../shared/analytics/analytics.dart' as ga; import '../../shared/analytics/constants.dart' as gac; import '../../shared/constants.dart'; import '../../shared/feature_flags.dart'; import '../../shared/screen.dart'; import '../api/vs_code_api.dart'; class DebugSessions extends StatelessWidget { const DebugSessions({ required this.api, required this.sessions, required this.deviceMap, super.key, }); final VsCodeApi api; final List<VsCodeDebugSession> sessions; final Map<String, VsCodeDevice> deviceMap; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Debug Sessions', style: Theme.of(context).textTheme.titleMedium, ), if (sessions.isEmpty) const Text('Begin a debug session to use DevTools.') else Table( columnWidths: const { 0: FlexColumnWidth(), }, defaultColumnWidth: FixedColumnWidth(actionsIconSize + denseSpacing), defaultVerticalAlignment: TableCellVerticalAlignment.middle, children: [ for (final session in sessions) _debugSessionRow(session, context), ], ), ], ); } TableRow _debugSessionRow(VsCodeDebugSession session, BuildContext context) { final mode = session.flutterMode; final isDebug = mode == 'debug'; final isProfile = mode == 'profile'; final isRelease = mode == 'release' || mode == 'jit_release'; final isFlutter = session.debuggerType?.contains('Flutter') ?? false; final isWeb = deviceMap[session.flutterDeviceId]?.platformType == 'web'; final label = session.flutterMode != null ? '${session.name} (${session.flutterMode})' : session.name; return TableRow( children: [ Text( label, style: Theme.of(context).regularTextStyle, ), IconButton( onPressed: api.capabilities.hotReload && (isDebug || !isFlutter) ? () { ga.select( gac.VsCodeFlutterSidebar.id, gac.hotReload, ); unawaited(api.hotReload(session.id)); } : null, tooltip: 'Hot Reload', icon: Icon(hotReloadIcon, size: actionsIconSize), ), IconButton( onPressed: api.capabilities.hotRestart && (isDebug || !isFlutter) ? () { ga.select( gac.VsCodeFlutterSidebar.id, gac.hotRestart, ); unawaited(api.hotRestart(session.id)); } : null, tooltip: 'Hot Restart', icon: Icon(hotRestartIcon, size: actionsIconSize), ), if (api.capabilities.openDevToolsPage) _DevToolsMenu( api: api, session: session, isFlutter: isFlutter, isDebug: isDebug, isProfile: isProfile, isRelease: isRelease, isWeb: isWeb, supportsOpenExternal: api.capabilities.openDevToolsExternally, ), ], ); } } class _DevToolsMenu extends StatefulWidget { const _DevToolsMenu({ required this.api, required this.session, required this.isFlutter, required this.isDebug, required this.isProfile, required this.isRelease, required this.isWeb, required this.supportsOpenExternal, }); final VsCodeApi api; final VsCodeDebugSession session; final bool isFlutter; final bool isDebug; final bool isProfile; final bool isRelease; final bool isWeb; final bool supportsOpenExternal; @override State<_DevToolsMenu> createState() => _DevToolsMenuState(); } class _DevToolsMenuState extends State<_DevToolsMenu> { ExtensionService? _extensionServiceForSession; @override void initState() { super.initState(); _initExtensions(); } void _initExtensions() { final sessionRootPath = widget.session.projectRootPath; if (sessionRootPath != null) { // This file path might be a Windows path but because this code runs in // the web, Uri.file() will not handle it correctly. // // Since all paths are absolute, assume that if the path contains `\` and // not `/` then it's Windows. final isWindows = sessionRootPath.contains(r'\') && !sessionRootPath.contains(r'/'); final fileUri = Uri.file(sessionRootPath, windows: isWindows); assert(fileUri.isScheme('file')); _extensionServiceForSession = ExtensionService(fixedAppRoot: fileUri); unawaited(_extensionServiceForSession!.initialize()); } } @override void didUpdateWidget(_DevToolsMenu oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.session != widget.session) { _extensionServiceForSession?.dispose(); _initExtensions(); } } @override void dispose() { _extensionServiceForSession?.dispose(); _extensionServiceForSession = null; super.dispose(); } @override Widget build(BuildContext context) { Widget devToolsButton(ScreenMetaData screen) { final title = screen.title ?? screen.id; String? disabledReason; if (widget.isRelease) { disabledReason = 'Not available in release mode'; } else if (screen.requiresFlutter && !widget.isFlutter) { disabledReason = 'Only available for Flutter applications'; } else if (screen.requiresDebugBuild && !widget.isDebug) { disabledReason = 'Only available in debug mode'; } else if (screen.requiresDartVm && widget.isWeb) { disabledReason = 'Not available when running on the web'; } return DevToolsScreenMenuItem( title: title, icon: screen.icon!, disabledReason: disabledReason, onPressed: () { ga.select( gac.VsCodeFlutterSidebar.id, gac.VsCodeFlutterSidebar.openDevToolsScreen(screen.id), ); unawaited( widget.api.openDevToolsPage( widget.session.id, page: screen.id, ), ); }, ); } return MenuAnchor( menuChildren: [ ...ScreenMetaData.values .where(_shouldIncludeScreen) .map(devToolsButton) .toList(), if (widget.supportsOpenExternal) DevToolsScreenMenuItem( title: 'Open in Browser', icon: Icons.open_in_browser, onPressed: () { ga.select( gac.VsCodeFlutterSidebar.id, gac.VsCodeFlutterSidebar.openDevToolsExternally.name, ); unawaited( widget.api.openDevToolsPage( widget.session.id, forceExternal: true, ), ); }, ), if (_extensionServiceForSession != null) ValueListenableBuilder( valueListenable: _extensionServiceForSession!.visibleExtensions, builder: (context, extensions, _) { return extensions.isEmpty ? const SizedBox.shrink() : ExtensionScreenMenuItem( extensions: extensions, onPressed: (e) { ga.select( gac.VsCodeFlutterSidebar.id, gac.VsCodeFlutterSidebar.openDevToolsScreen( gac.DevToolsExtensionEvents.extensionScreenName( e, ), ), ); unawaited( widget.api.openDevToolsPage( widget.session.id, page: e.screenId, ), ); }, ); }, ), ], builder: (context, controller, child) => IconButton( onPressed: widget.isRelease ? null : () { if (controller.isOpen) { controller.close(); } else { controller.open(); } }, tooltip: 'DevTools', icon: Icon( Icons.construction, size: actionsIconSize, ), ), ); } bool _shouldIncludeScreen(ScreenMetaData screen) { return switch (screen) { // Some screens shouldn't show up in the menu. ScreenMetaData.home => false, ScreenMetaData.debugger => false, ScreenMetaData.simple => false, // generic screen isn't a screen itself // TODO(dantup): Check preferences.vmDeveloperModeEnabled ScreenMetaData.vmTools => false, // DeepLink is currently behind a feature flag. ScreenMetaData.deepLinks => FeatureFlags.deepLinkValidation, // Anything else can be shown as long as it doesn't require a specific // library. _ => screen.requiresLibrary == null, }; } } /// A context menu item for an individual DevTools screen. class DevToolsScreenMenuItem extends StatelessWidget { const DevToolsScreenMenuItem({ super.key, required this.title, required this.icon, required this.onPressed, this.disabledReason, }); final String title; final IconData icon; final VoidCallback onPressed; final String? disabledReason; @override Widget build(BuildContext context) { Widget text = Text(title); if (disabledReason != null) { text = Tooltip( preferBelow: false, message: disabledReason, child: text, ); } return MenuItemButton( leadingIcon: Icon(icon, size: actionsIconSize), onPressed: disabledReason != null ? null : onPressed, child: text, ); } } /// A context menu submenu button that contains the list of available extension /// screens. class ExtensionScreenMenuItem extends StatelessWidget { const ExtensionScreenMenuItem({ super.key, required this.extensions, required this.onPressed, }); static const _submenuOffsetDy = 8.0; final List<DevToolsExtensionConfig> extensions; final void Function(DevToolsExtensionConfig) onPressed; @override Widget build(BuildContext context) { return SubmenuButton( alignmentOffset: const Offset(0.0, _submenuOffsetDy), menuChildren: extensions .map( (e) => DevToolsScreenMenuItem( title: e.name, icon: e.icon, onPressed: () => onPressed(e), ), ) .toList(), child: const Text('Extensions'), ); } }
devtools/packages/devtools_app/lib/src/standalone_ui/vs_code/debug_sessions.dart/0
{ "file_path": "devtools/packages/devtools_app/lib/src/standalone_ui/vs_code/debug_sessions.dart", "repo_id": "devtools", "token_count": 5130 }
106
name: devtools_app description: Web-based performance tooling for Dart and Flutter. publish_to: none # Note: this version should only be updated by running tools/update_version.dart # that updates all versions of devtools packages (devtools_app, devtools_test). version: 2.34.0-dev.12 repository: https://github.com/flutter/devtools/tree/master/packages/devtools_app environment: sdk: ">=3.3.0-91.0.dev <4.0.0" flutter: ">=3.17.0-0.0.pre" dependencies: ansi_up: ^1.0.0 # path: ../../third_party/packages/ansi_up # Pin ansicolor to version before pre-NNBD version 1.1.0, should be ^1.0.5 # See https://github.com/flutter/devtools/issues/2530 ansicolor: ^2.0.0 async: ^2.0.0 clock: ^1.1.1 codicon: ^1.0.0 collection: ^1.15.0 dap: ^1.1.0 dds_service_extensions: ^1.6.0 devtools_app_shared: ^0.1.0 devtools_extensions: ^0.0.10 devtools_shared: ^6.0.1 dtd: ^1.0.0 file: ">=6.0.0 <8.0.0" file_selector: ^1.0.0 fixnum: ^1.1.0 flutter: sdk: flutter flutter_markdown: ^0.6.8 # TODO: https://github.com/flutter/devtools/issues/4569 - unpin this version flutter_riverpod: 2.0.0-dev.9 flutter_web_plugins: sdk: flutter http: ^1.1.0 image: ^4.1.3 intl: ^0.18.0 js: ^0.6.1+1 json_rpc_2: ^3.0.2 logging: ^1.1.1 meta: ^1.9.1 mime: ^1.0.0 path: ^1.8.0 perfetto_ui_compiled: path: ../../third_party/packages/perfetto_ui_compiled pointer_interceptor: ^0.9.3+3 provider: ^6.0.2 # Only used for debug mode logic. shared_preferences: ^2.0.15 sse: ^4.1.2 stack_trace: ^1.10.0 stream_channel: ^2.1.1 string_scanner: ^1.1.0 unified_analytics: ^5.8.1 url_launcher: ^6.1.0 url_launcher_web: ^2.0.6 vm_service: ^14.1.0 vm_service_protos: ^1.0.0 # TODO https://github.com/dart-lang/sdk/issues/52853 - unpin this version vm_snapshot_analysis: 0.7.2 web: ^0.4.1 web_socket_channel: ^2.1.0 # widget_icons: ^0.0.1 dev_dependencies: args: ^2.4.2 build_runner: ^2.3.3 devtools_test: 2.34.0-dev.12 fake_async: ^1.3.1 flutter_driver: sdk: flutter flutter_lints: ^2.0.3 flutter_test: sdk: flutter integration_test: sdk: flutter mockito: ^5.4.1 stager: ^1.0.1 test: ^1.21.1 web_benchmarks: ^1.1.0 webkit_inspection_protocol: ">=0.5.0 <2.0.0" flutter: uses-material-design: true assets: - assets/ - assets/img/ - assets/img/layout_explorer/ - assets/img/layout_explorer/cross_axis_alignment/ - assets/img/layout_explorer/main_axis_alignment/ - assets/img/legend/ - icons/ - icons/actions/ - icons/custom/ - icons/general/ - icons/gutter/ - icons/inspector/ - icons/inspector/widget_icons/ - icons/memory/ - icons/perf/ # We have to explicitly list every asset under `packages/perfetto_ui_compiled/` # since directory support is not available for assets under `packages/`. # See (https://github.com/flutter/flutter/issues/112019). - packages/perfetto_ui_compiled/dist/index.html - packages/perfetto_ui_compiled/dist/service_worker.js - packages/perfetto_ui_compiled/dist/devtools/devtools_dark.css - packages/perfetto_ui_compiled/dist/devtools/devtools_light.css - packages/perfetto_ui_compiled/dist/devtools/devtools_shared.css - packages/perfetto_ui_compiled/dist/devtools/devtools_theme_handler.js # The version number for all the Perfetto asset paths below is updated by running # `devtools_tool update-perfetto`. - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/engine_bundle.js - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/frontend_bundle.js - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/manifest.json - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/perfetto.css - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/trace_processor.wasm - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/brand.png - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/favicon.png - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/logo-128.png - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/logo-3d.png - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/scheduling_latency.png - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/MaterialSymbolsOutlined.woff2 - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/Roboto-100.woff2 - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/Roboto-300.woff2 - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/Roboto-400.woff2 - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/Roboto-500.woff2 - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/RobotoCondensed-Light.woff2 - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/RobotoCondensed-Regular.woff2 - packages/perfetto_ui_compiled/dist/v33.0-1838a06af/assets/RobotoMono-Regular.woff2 fonts: - family: Roboto fonts: - asset: fonts/Roboto/Roboto-Thin.ttf weight: 100 - asset: fonts/Roboto/Roboto-Light.ttf weight: 300 - asset: fonts/Roboto/Roboto-Regular.ttf weight: 400 - asset: fonts/Roboto/Roboto-Medium.ttf weight: 500 - asset: fonts/Roboto/Roboto-Bold.ttf weight: 700 - asset: fonts/Roboto/Roboto-Black.ttf weight: 900 - family: RobotoMono fonts: - asset: fonts/Roboto_Mono/RobotoMono-Thin.ttf weight: 100 - asset: fonts/Roboto_Mono/RobotoMono-Light.ttf weight: 300 - asset: fonts/Roboto_Mono/RobotoMono-Regular.ttf weight: 400 - asset: fonts/Roboto_Mono/RobotoMono-Medium.ttf weight: 500 - asset: fonts/Roboto_Mono/RobotoMono-Bold.ttf weight: 700 - family: Octicons fonts: - asset: fonts/Octicons.ttf - family: Codicon fonts: - asset: packages/codicon/font/codicon.ttf dependency_overrides: devtools_shared: path: ../devtools_shared devtools_app_shared: path: ../devtools_app_shared devtools_test: path: ../devtools_test devtools_extensions: path: ../devtools_extensions
devtools/packages/devtools_app/pubspec.yaml/0
{ "file_path": "devtools/packages/devtools_app/pubspec.yaml", "repo_id": "devtools", "token_count": 2842 }
107
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/profiler/cpu_profiler.dart'; import 'package:devtools_app/src/screens/profiler/panes/controls/cpu_profiler_controls.dart'; import 'package:devtools_app/src/screens/profiler/profiler_status.dart'; import 'package:devtools_app/src/service/vm_flags.dart' as vm_flags; import 'package:devtools_app/src/shared/file_import.dart'; import 'package:devtools_app/src/shared/ui/vm_flag_widgets.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../test_infra/scenes/cpu_profiler/default.dart'; import '../test_infra/scenes/scene_test_extensions.dart'; import '../test_infra/utils/test_utils.dart'; void main() { late CpuProfilerDefaultScene scene; setUp(() async { setCharacterWidthForTables(); scene = CpuProfilerDefaultScene(); await scene.setUp(); }); const windowSize = Size(2000.0, 1000.0); group('ProfilerScreen', () { void verifyBaseState() { expect(find.byType(RecordButton), findsOneWidget); expect(find.byType(StopRecordingButton), findsOneWidget); expect(find.byType(ClearButton), findsOneWidget); expect(find.text('Load all CPU samples'), findsOneWidget); if (scene.fakeServiceConnection.serviceManager.connectedApp! .isFlutterNativeAppNow) { expect(find.text('Profile app start up'), findsOneWidget); } expect(find.byType(CpuSamplingRateDropdown), findsOneWidget); expect(find.byType(OpenSaveButtonGroup), findsOneWidget); expect( find.byType(ProfileRecordingInstructions), findsOneWidget, ); expect(find.byType(RecordingStatus), findsNothing); expect(find.byType(CircularProgressIndicator), findsNothing); expect(find.byType(CpuProfiler), findsNothing); expect(find.byType(ModeDropdown), findsNothing); } Future<void> pumpProfilerScreen(WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpScene(scene); // Delay to ensure the memory profiler has collected data. await tester.pump(const Duration(seconds: 1)); expect(find.byType(ProfilerScreenBody), findsOneWidget); }); } testWidgets('builds its tab', (WidgetTester tester) async { await tester.pumpWidget( wrapWithControllers( Builder(builder: scene.screen.buildTab), profiler: ProfilerScreenController(), ), ); expect(find.text('CPU Profiler'), findsOneWidget); }); testWidgetsWithWindowSize( 'builds base state for Dart CLI app', windowSize, (WidgetTester tester) async { await pumpProfilerScreen(tester); verifyBaseState(); }, ); testWidgetsWithWindowSize( 'builds base state for Flutter native app', windowSize, (WidgetTester tester) async { mockConnectedApp( scene.fakeServiceConnection.serviceManager.connectedApp!, isFlutterApp: true, isProfileBuild: true, isWebApp: false, ); await pumpProfilerScreen(tester); verifyBaseState(); }, ); testWidgetsWithWindowSize( 'builds proper content for recording state', windowSize, (WidgetTester tester) async { await pumpProfilerScreen(tester); verifyBaseState(); // Start recording. await tester.tap(find.byType(RecordButton)); await tester.pump(const Duration(seconds: 1)); expect( find.byType(ProfileRecordingInstructions), findsNothing, ); expect(find.byType(RecordingStatus), findsOneWidget); expect(find.byType(CircularProgressIndicator), findsOneWidget); expect(find.byType(CpuProfiler), findsNothing); // Stop recording. await tester.tap(find.byType(StopRecordingButton)); await tester.pumpAndSettle(const Duration(seconds: 2)); expect(find.byType(CircularProgressIndicator), findsNothing); expect(find.byType(CpuProfiler), findsOneWidget); // Clear the profile. await tester.tap(find.byType(ClearButton)); await tester.pump(); verifyBaseState(); }, ); testWidgetsWithWindowSize( 'builds for disabled profiler', windowSize, (WidgetTester tester) async { await tester.runAsync(() async { await scene.fakeServiceConnection.serviceManager.service!.setFlag( vm_flags.profiler, 'false', ); }); await pumpProfilerScreen(tester); expect(find.byType(CpuProfilerDisabled), findsOneWidget); expect( find.byType(ProfileRecordingInstructions), findsNothing, ); expect(find.byType(RecordButton), findsNothing); expect(find.byType(StopRecordingButton), findsNothing); expect(find.byType(ClearButton), findsNothing); expect(find.byType(CpuSamplingRateDropdown), findsNothing); expect(find.byType(OpenSaveButtonGroup), findsNothing); await tester.runAsync(() async { await tester.tap(find.text('Enable profiler')); // Delay to ensure the memory profiler has collected data. await tester.pump(const Duration(seconds: 1)); }); await tester.pumpAndSettle(); verifyBaseState(); }, ); }); }
devtools/packages/devtools_app/test/cpu_profiler/profiler_screen_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/cpu_profiler/profiler_screen_test.dart", "repo_id": "devtools", "token_count": 2265 }
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/src/shared/diagnostics/tree_builder.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 '../test_infra/utils/variable_utils.dart'; void main() { late FakeServiceConnectionManager fakeServiceConnection; late MockDebuggerController debuggerController; late MockScriptManager scriptManager; const windowSize = Size(4000, 4000); setUp(() { fakeServiceConnection = FakeServiceConnectionManager(); scriptManager = MockScriptManager(); mockConnectedApp( fakeServiceConnection.serviceManager.connectedApp!, isProfileBuild: false, isFlutterApp: true, isWebApp: false, ); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal(ScriptManager, scriptManager); setGlobal(NotificationService, NotificationService()); setGlobal(BreakpointManager, BreakpointManager()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); fakeServiceConnection.consoleService.ensureServiceInitialized(); when(fakeServiceConnection.errorBadgeManager.errorCountNotifier('debugger')) .thenReturn(ValueNotifier<int>(0)); debuggerController = createMockDebuggerControllerWithDefaults(); resetRef(); resetRoot(); }); Future<void> pumpDebuggerScreen( WidgetTester tester, DebuggerController controller, ) async { await tester.pumpWidget( wrapWithControllers( const DebuggerWindows(), debugger: controller, ), ); } Future<void> verifyGroupings( WidgetTester tester, { required Finder parentFinder, }) async { final group0To9999Finder = find.textContaining('[0 - 9999]'); final group10000To19999Finder = find.textContaining('[10000 - 19999]'); final group230000To239999Finder = find.textContaining('[230000 - 239999]'); final group240000To243620Finder = find.textContaining('[240000 - 243620]'); final group0To99Finder = find.textContaining('[0 - 99]'); final group100To199Finder = find.textContaining('[100 - 199]'); final group200To299Finder = find.textContaining('[200 - 299]'); // Initially the parent variable is not expanded. expect(parentFinder, findsOneWidget); expect(group0To9999Finder, findsNothing); expect(group10000To19999Finder, findsNothing); expect(group230000To239999Finder, findsNothing); expect(group240000To243620Finder, findsNothing); // Expand the parent variable. await tester.tap(parentFinder); await tester.pump(); expect(group0To9999Finder, findsOneWidget); expect(group10000To19999Finder, findsOneWidget); expect(group230000To239999Finder, findsOneWidget); expect(group240000To243620Finder, findsOneWidget); // Initially group [0 - 9999] is not expanded. expect(group0To99Finder, findsNothing); expect(group100To199Finder, findsNothing); expect(group200To299Finder, findsNothing); // Expand group [0 - 9999]. await tester.tap(group0To9999Finder); await tester.pump(); expect(group0To99Finder, findsOneWidget); expect(group100To199Finder, findsOneWidget); expect(group200To299Finder, findsOneWidget); } testWidgetsWithWindowSize( 'Variables shows items', windowSize, (WidgetTester tester) async { fakeServiceConnection.appState.setVariables( [ buildListVariable(), buildMapVariable(), buildStringVariable('test str'), buildBooleanVariable(true), buildSetVariable(), ], ); await pumpDebuggerScreen(tester, debuggerController); expect(find.text('Variables'), findsOneWidget); final listFinder = find.text('Root 1: List (2 items)'); expect(listFinder, findsOneWidget); final mapFinder = find.textContaining( 'Root 2: Map (2 items)', ); final mapElement1Finder = find.textContaining("['key1']: 1.0"); final mapElement2Finder = find.textContaining("['key2']: 2.0"); expect(listFinder, findsOneWidget); expect(mapFinder, findsOneWidget); expect( find.textContaining("Root 3: 'test str...'"), findsOneWidget, ); expect( find.textContaining('Root 4: true'), findsOneWidget, ); // Initially list is not expanded. expect(find.textContaining('0: 3'), findsNothing); expect(find.textContaining('1: 4'), findsNothing); // Expand list. await tester.tap(listFinder); await tester.pump(); expect(find.textContaining('0: 0'), findsOneWidget); expect(find.textContaining('1: 1'), findsOneWidget); // Initially map is not expanded. expect(mapElement1Finder, findsNothing); expect(mapElement2Finder, findsNothing); // Expand map. await tester.tap(mapFinder); await tester.pump(); expect(mapElement1Finder, findsOneWidget); expect(mapElement2Finder, findsOneWidget); // Expect a tooltip for the set instance. final setFinder = find.text('Root 5: Set (2 items)'); expect(setFinder, findsOneWidget); // Initially set is not expanded. expect(find.textContaining('set value 0'), findsNothing); expect(find.textContaining('set value 1'), findsNothing); // Expand set await tester.tap(setFinder); await tester.pump(); expect(find.textContaining('set value 0'), findsOneWidget); expect(find.textContaining('set value 1'), findsOneWidget); }, ); testWidgetsWithWindowSize( 'Children in large list variables are grouped', windowSize, (WidgetTester tester) async { final list = buildParentListVariable(length: 243621); await buildVariablesTree(list); final appState = serviceConnection.appState; appState.setVariables([list]); await pumpDebuggerScreen(tester, debuggerController); final listFinder = find.text('Root 1: List (243,621 items)'); await verifyGroupings(tester, parentFinder: listFinder); }, ); testWidgetsWithWindowSize( 'Children in large map variables are grouped', windowSize, (WidgetTester tester) async { final map = buildParentMapVariable(length: 243621); await buildVariablesTree(map); final appState = serviceConnection.appState; appState.setVariables([map]); await pumpDebuggerScreen(tester, debuggerController); final mapFinder = find.text('Root 1: Map (243,621 items)'); await verifyGroupings(tester, parentFinder: mapFinder); }, ); testWidgetsWithWindowSize( 'Children in large set variables are grouped', windowSize, (WidgetTester tester) async { final set = buildParentSetVariable(length: 243621); await buildVariablesTree(set); final appState = serviceConnection.appState; appState.setVariables([set]); await pumpDebuggerScreen(tester, debuggerController); final setFinder = find.text('Root 1: Set (243,621 items)'); await verifyGroupings(tester, parentFinder: setFinder); }, ); }
devtools/packages/devtools_app/test/debugger/debugger_screen_variables_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/debugger/debugger_screen_variables_test.dart", "repo_id": "devtools", "token_count": 2732 }
109
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../test_infra/flutter_test_driver.dart' show FlutterRunConfiguration; import '../test_infra/flutter_test_environment.dart'; import '../test_infra/matchers/matchers.dart'; // This is a bit conservative to ensure we do not get flakes due to // slow interactions with the VM Service. This delay could likely be // reduced to under 1 second without introducing flakes. const inspectorChangeSettleTime = Duration(seconds: 2); void main() { // We need to use real async in this test so we need to use this binding. initializeLiveTestWidgetsFlutterBindingWithAssets(); const windowSize = Size(2600.0, 1200.0); final FlutterTestEnvironment env = FlutterTestEnvironment( const FlutterRunConfiguration(withDebugger: true), ); env.afterEverySetup = () async { final service = serviceConnection.inspectorService; if (env.reuseTestEnvironment) { // Ensure the previous test did not set the selection on the device. // TODO(jacobr): add a proper method to WidgetInspectorService that does // this. setSelection currently ignores null selection requests which is // a misfeature. await service!.inspectorLibrary.eval( 'WidgetInspectorService.instance.selection.clear()', isAlive: null, ); } }; setUp(() async { await env.setupEnvironment(); }); tearDownAll(() async { await env.tearDownEnvironment(force: true); }); group('screenshot tests', () { testWidgetsWithWindowSize( 'navigation', windowSize, (WidgetTester tester) async { await env.setupEnvironment(); expect(serviceConnection.serviceManager.service, equals(env.service)); expect(serviceConnection.serviceManager.isolateManager, isNotNull); final screen = InspectorScreen(); await tester.pumpWidget( wrapWithInspectorControllers(Builder(builder: screen.build)), ); await tester.pump(const Duration(seconds: 1)); final InspectorScreenBodyState state = tester.state(find.byType(InspectorScreenBody)); final controller = state.controller; while (!controller.flutterAppFrameReady) { await controller.maybeLoadUI(); await tester.pumpAndSettle(); } // Give time for the initial animation to complete. await tester.pumpAndSettle(inspectorChangeSettleTime); await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_inspector_initial_load.png', ), ); // Click on the Center widget (row index #5) await tester.tap(find.richText('Center')); await tester.pumpAndSettle(inspectorChangeSettleTime); await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_inspector_select_center.png', ), ); // Select the details tree. await tester.tap(find.text('Widget Details Tree')); await tester.pumpAndSettle(inspectorChangeSettleTime); await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_inspector_select_center_details_tree.png', ), ); // Select the RichText row. await tester.tap(find.richText('RichText')); await tester.pumpAndSettle(inspectorChangeSettleTime); await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_inspector_richtext_selected.png', ), ); // Test hovering over the icon shown when a property has its default // value. // TODO(jacobr): support tooltips in the Flutter version of the inspector. // https://github.com/flutter/devtools/issues/2570. // For example, verify that the tooltip hovering over the default value // icons is "Default value". // Test selecting a widget. // Two 'Scaffold's: a breadcrumb and an actual tree item expect(find.richText('Scaffold'), findsNWidgets(2)); // select Scaffold widget in summary tree. await tester.tap(find.richText('Scaffold').last); await tester.pumpAndSettle(inspectorChangeSettleTime); // This tree is huge. If there is a change to package:flutter it may // change. If this happens don't panic and rebaseline the golden. await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_inspector_scaffold_selected.png', ), ); // The important thing about this is that the details tree should scroll // instead of re-rooting as the selected row is already visible in the // details tree. await tester.tap(find.richText('AnimatedPhysicalModel')); await tester.pumpAndSettle(inspectorChangeSettleTime); await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_animated_physical_model_selected.png', ), ); await env.tearDownEnvironment(); }, ); // TODO(jacobr): convert these tests to screenshot tests like the initial // state test. /* // Intentionally trigger multiple quick navigate action to ensure that // multiple quick navigation commands in a row do not trigger race // conditions getting out of order updates from the server. tree.navigateDown(); tree.navigateDown(); tree.navigateDown(); await detailsTree.nextUiFrame; expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center\n' ' │ [/icons/inspector/textArea.png]Text\n' ' └─▼[A]AppBar <-- selected\n' ' [/icons/inspector/textArea.png]Text\n', ), ); // Make sure we don't go off the bottom of the tree. tree.navigateDown(); tree.navigateDown(); tree.navigateDown(); tree.navigateDown(); tree.navigateDown(); expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center\n' ' │ [/icons/inspector/textArea.png]Text\n' ' └─▼[A]AppBar\n' ' [/icons/inspector/textArea.png]Text <-- selected\n', ), ); tree.navigateUp(); expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center\n' ' │ [/icons/inspector/textArea.png]Text\n' ' └─▼[A]AppBar <-- selected\n' ' [/icons/inspector/textArea.png]Text\n', ), ); tree.navigateLeft(); await detailsTree.nextUiFrame; expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center\n' ' │ [/icons/inspector/textArea.png]Text\n' ' └─▶[A]AppBar <-- selected\n', ), ); tree.navigateLeft(); // First navigate left goes to the parent. expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold <-- selected\n' ' ├───▼[C]Center\n' ' │ [/icons/inspector/textArea.png]Text\n' ' └─▶[A]AppBar\n', ), ); tree.navigateLeft(); // Next navigate left closes the parent. expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▶[S]Scaffold <-- selected\n', ), ); tree.navigateRight(); expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold <-- selected\n' ' ├───▼[C]Center\n' ' │ [/icons/inspector/textArea.png]Text\n' ' └─▶[A]AppBar\n', ), ); // Node is already expanded so this is equivalent to navigate down. tree.navigateRight(); expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center <-- selected\n' ' │ [/icons/inspector/textArea.png]Text\n' ' └─▶[A]AppBar\n', ), ); await detailsTree.nextUiFrame; // Make sure the details and main trees have not gotten out of sync. expect( detailsTree.toStringDeep(hidePropertyLines: true), equalsIgnoringHashCodes('▼[C]Center <-- selected\n' '└─▼[/icons/inspector/textArea.png]Text\n' ' └─▼[/icons/inspector/textArea.png]RichText\n'), ); await env.tearDownEnvironment(); }); */ // TODO(jacobr): uncomment hotReload test once the hot reload test is not // flaky. https://github.com/flutter/devtools/issues/642 /* test('hotReload', () async { if (flutterVersion == '1.2.1') { // This test can be flaky in Flutter 1.2.1 because of // https://github.com/dart-lang/sdk/issues/33838 // so we just skip it. This block of code can be removed after the next // stable flutter release. // TODO(dantup): Remove this. return; } await env.setupEnvironment(); await serviceManager.performHotReload(); // Ensure the inspector does not fall over and die after a hot reload. expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center\n' ' │ [/icons/inspector/textArea.png]Text <-- selected\n' ' └─▼[A]AppBar\n' ' [/icons/inspector/textArea.png]Text\n', ), ); // TODO(jacobr): would be nice to have some tests that trigger a hot // reload that actually changes app state in a meaningful way. await env.tearDownEnvironment(); }); */ // TODO(jacobr): uncomment out the hotRestart tests once // https://github.com/flutter/devtools/issues/337 is fixed. /* test('hotRestart', () async { await env.setupEnvironment(); // The important thing about this is that the details tree should scroll // instead of re-rooting as the selected row is already visible in the // details tree. simulateRowClick(tree, rowIndex: 4); expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R]root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center <-- selected\n' ' │ ▼[/icons/inspector/textArea.png]Text\n' ' └─▼[A]AppBar\n' ' ▼[/icons/inspector/textArea.png]Text\n', ), ); /// After the hot restart some existing calls to the vm service may /// timeout and that is ok. serviceManager.manager.service.doNotWaitForPendingFuturesBeforeExit(); await serviceManager.performHotRestart(); // The isolate starts out paused on a hot restart so we have to resume // it manually to make the test pass. await serviceManager.manager.service .resume(serviceManager.isolateManager.selectedIsolate.id); // First UI transition is to an empty tree. await detailsTree.nextUiFrame; expect(tree.toStringDeep(), equalsIgnoringHashCodes('<empty>\n')); // Notice that the selection has been lost due to the hot restart. await detailsTree.nextUiFrame; expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center\n' ' │ ▼[/icons/inspector/textArea.png]Text\n' ' └─▼[A]AppBar\n' ' ▼[/icons/inspector/textArea.png]Text\n', ), ); // Verify that the selection can actually be changed after a restart. simulateRowClick(tree, rowIndex: 4); expect( tree.toStringDeep(), equalsIgnoringHashCodes( '▼[R][root]\n' ' ▼[M]MyApp\n' ' ▼[M]MaterialApp\n' ' ▼[S]Scaffold\n' ' ├───▼[C]Center <-- selected\n' ' │ ▼[/icons/inspector/textArea.png]Text\n' ' └─▼[A]AppBar\n' ' ▼[/icons/inspector/textArea.png]Text\n', ), ); await env.tearDownEnvironment(); }); */ }); group('widget errors', () { testWidgetsWithWindowSize( 'show navigator and error labels', windowSize, (WidgetTester tester) async { await env.setupEnvironment( config: const FlutterRunConfiguration( withDebugger: true, entryScript: 'lib/overflow_errors.dart', ), ); expect(serviceConnection.serviceManager.service, equals(env.service)); expect(serviceConnection.serviceManager.isolateManager, isNotNull); final screen = InspectorScreen(); await tester.pumpWidget( wrapWithInspectorControllers(Builder(builder: screen.build)), ); await tester.pumpAndSettle(const Duration(seconds: 1)); final InspectorScreenBodyState state = tester.state(find.byType(InspectorScreenBody)); final controller = state.controller; while (!controller.flutterAppFrameReady) { await controller.maybeLoadUI(); await tester.pumpAndSettle(); } await env.flutter!.hotReload(); // Give time for the initial animation to complete. await tester.pumpAndSettle(inspectorChangeSettleTime); await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_inspector_errors_1_initial_load.png', ), ); // Navigate so one of the errors is selected. for (var i = 0; i < 2; i++) { await tester.tap(find.byIcon(Icons.keyboard_arrow_down)); await tester.pumpAndSettle(inspectorChangeSettleTime); } await expectLater( find.byType(InspectorScreenBody), matchesDevToolsGolden( '../test_infra/goldens/integration_inspector_errors_2_error_selected.png', ), ); await env.tearDownEnvironment(); }, ); }); }
devtools/packages/devtools_app/test/inspector/inspector_integration_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/inspector/inspector_integration_test.dart", "repo_id": "devtools", "token_count": 7501 }
110
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app/src/shared/diagnostics/diagnostics_node.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'layout_explorer_serialization_delegate.dart'; Future<RemoteDiagnosticsNode> widgetToLayoutExplorerRemoteDiagnosticsNode({ required Widget widget, required WidgetTester tester, int subtreeDepth = 1, }) async { await tester.pumpWidget(MaterialApp(home: Scaffold(body: widget))); final element = find.byWidget(widget).evaluate().first; final nodeJson = element.toDiagnosticsNode(style: DiagnosticsTreeStyle.dense).toJsonMap( LayoutExplorerSerializationDelegate( subtreeDepth: subtreeDepth, service: WidgetInspectorService.instance, ), ); return RemoteDiagnosticsNode(nodeJson, null, false, null); }
devtools/packages/devtools_app/test/inspector/layout_explorer/layout_explorer_test_utils.dart/0
{ "file_path": "devtools/packages/devtools_app/test/inspector/layout_explorer/layout_explorer_test_utils.dart", "repo_id": "devtools", "token_count": 368 }
111
// 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/src/screens/memory/panes/diff/controller/item_controller.dart'; import 'package:devtools_app/src/screens/memory/panes/diff/diff_pane.dart'; import 'package:devtools_app/src/screens/memory/shared/heap/class_filter.dart'; import 'package:devtools_app/src/screens/memory/shared/widgets/class_filter.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/diff_snapshot.dart'; import '../../../test_infra/scenes/scene_test_extensions.dart'; class _FilterTest { _FilterTest({required this.isDiff}); final bool isDiff; String get name => isDiff ? 'diff' : 'single'; String get sceneGolden => '../../../test_infra/goldens/memory_diff_snapshot_scene_$name.png'; String snapshotGolden(ClassFilterType? type) => '../../../test_infra/goldens/memory_diff_snapshot_${type?.name ?? 'custom'}_$name.png'; static String dialogGolden(ClassFilterType? type) => '../../../test_infra/goldens/memory_diff_filter_dialog_${type?.name ?? 'custom'}.png'; } final _tests = [ _FilterTest(isDiff: false), _FilterTest(isDiff: true), ]; final _customFilter = ClassFilter( filterType: ClassFilterType.only, except: '', only: '', ); void main() { group('Class Filter', () { late DiffSnapshotScene scene; setUp(() async { scene = DiffSnapshotScene(); await scene.setUp(); }); Future<DiffSnapshotScene> pumpScene( WidgetTester tester, _FilterTest test, ) async { scene.setClassFilterToShowAll(); expect( scene.diffController.core.snapshots.value .where((element) => element.hasData), hasLength(2), ); final diffWith = test.isDiff ? scene.diffController.core.snapshots.value[1] as SnapshotInstanceItem : null; scene.diffController.setDiffing( scene.diffController.derived.selectedItem.value as SnapshotInstanceItem, diffWith, ); await tester.pumpScene(scene); await tester.pumpAndSettle(); expect( scene.diffController.core.classFilter.value.filterType, ClassFilterType.showAll, ); await expectLater( find.byType(SnapshotInstanceItemPane), matchesDevToolsGolden(test.sceneGolden), ); return scene; } // Set a wide enough screen width that we do not run into overflow. const windowSize = Size(2225.0, 1000.0); for (final test in _tests) { testWidgetsWithWindowSize( '$ClassFilterDialog filters classes, ${test.name}', windowSize, (WidgetTester tester) async { final scene = await pumpScene(tester, test); await _switchFilter( scene, ClassFilterType.showAll, ClassFilterType.except, tester, test, ); await _switchFilter( scene, ClassFilterType.except, ClassFilterType.only, tester, test, ); await _switchFilter( scene, ClassFilterType.only, ClassFilterType.showAll, tester, test, ); }, ); } for (final test in _tests) { testWidgetsWithWindowSize( '$ClassFilterDialog customizes and resets to default, ${test.name}', windowSize, (WidgetTester tester) async { final scene = await pumpScene(tester, test); // Customize filter. scene.diffController.derived.applyFilter(_customFilter); await _checkDataGolden(scene, null, tester, test); // Open dialog. await tester.tap(find.byType(ClassFilterButton)); await _checkFilterGolden(null, tester); // Reset to default. await tester.tap(find.text('Reset to default')); await tester.pumpAndSettle(); await tester.tap(find.text('APPLY')); await tester.pumpAndSettle(); await tester.pumpAndSettle(); final actualFilter = scene.diffController.core.classFilter.value; expect(actualFilter.filterType, equals(ClassFilterType.except)); expect(actualFilter.except, equals(ClassFilter.defaultExceptString)); }, ); } }); } /// Verifies original and new state of filter and data. Future<void> _switchFilter( DiffSnapshotScene scene, ClassFilterType from, ClassFilterType to, WidgetTester tester, _FilterTest test, ) async { await _checkDataGolden(scene, from, tester, test); // Open dialog. await tester.tap(find.byType(ClassFilterButton)); await _checkFilterGolden(from, tester); // Select new filter. final radioButton = find.byKey(Key(to.toString())); await tester.tap(radioButton); await _checkFilterGolden(to, tester); // Close dialog. await tester.tap(find.text('APPLY')); await _checkDataGolden(scene, to, tester, test); } /// If type is null, filter is [_customFilter]. Future<void> _checkFilterGolden( ClassFilterType? type, WidgetTester tester, ) async { await tester.pumpAndSettle(); await expectLater( find.byType(ClassFilterDialog), matchesDevToolsGolden(_FilterTest.dialogGolden(type)), ); } /// If type is null, filter is [_customFilter]. Future<void> _checkDataGolden( DiffSnapshotScene scene, ClassFilterType? type, WidgetTester tester, _FilterTest test, ) async { await tester.pumpAndSettle(); final currentFilterType = scene.diffController.core.classFilter.value.filterType; expect(currentFilterType, type ?? _customFilter.filterType); await expectLater( find.byType(SnapshotInstanceItemPane), matchesDevToolsGolden(test.snapshotGolden(type)), ); }
devtools/packages/devtools_app/test/memory/diff/widgets/class_filter_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/memory/diff/widgets/class_filter_test.dart", "repo_id": "devtools", "token_count": 2400 }
112
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:devtools_app/devtools_app.dart'; import 'package:devtools_app/src/screens/network/network_request_inspector.dart'; import 'package:devtools_app/src/screens/network/network_request_inspector_views.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:vm_service/vm_service.dart'; import '../test_infra/test_data/network.dart'; import '../test_infra/utils/test_utils.dart'; void main() { group('NetworkRequestInspector', () { late NetworkController controller; late FakeServiceConnectionManager fakeServiceConnection; final HttpProfileRequest? httpRequest = HttpProfileRequest.parse(httpPostJson); String clipboardContents = ''; setUp(() { setGlobal(IdeTheme, IdeTheme()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); clipboardContents = ''; fakeServiceConnection = FakeServiceConnectionManager( service: FakeServiceManager.createFakeService( httpProfile: HttpProfile( requests: [ httpRequest!, ], timestamp: DateTime.fromMicrosecondsSinceEpoch(0), ), ), ); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(NotificationService, NotificationService()); controller = NetworkController(); setupClipboardCopyListener( clipboardContentsCallback: (contents) { clipboardContents = contents ?? ''; }, ); }); testWidgets('copy request body', (tester) async { final requestsNotifier = controller.requests; await controller.startRecording(); await tester.pumpWidget( wrapWithControllers( NetworkRequestInspector(controller), debugger: createMockDebuggerControllerWithDefaults(), ), ); // Load the network request. await controller.networkService.refreshNetworkData(); expect(requestsNotifier.value.length, equals(1)); // Select the request in the network request list. final networkRequest = requestsNotifier.value.first; controller.selectedRequest.value = networkRequest; await tester.pumpAndSettle(); await tester.tap(find.text('Request')); await tester.pumpAndSettle(); // Tap the requestBody copy button. expect(clipboardContents, isEmpty); await tester.tap(find.byType(CopyToClipboardControl)); final expectedResponseBody = jsonDecode(utf8.decode(httpRequest!.requestBody!.toList())); // Check that the contents were copied to clipboard. expect(clipboardContents, isNotEmpty); expect( jsonDecode(clipboardContents), equals(expectedResponseBody), ); controller.stopRecording(); // pumpAndSettle so residual http timers can clear. await tester.pumpAndSettle(const Duration(seconds: 1)); }); testWidgets('copy response body', (tester) async { final requestsNotifier = controller.requests; await controller.startRecording(); await tester.pumpWidget( wrapWithControllers( NetworkRequestInspector(controller), debugger: createMockDebuggerControllerWithDefaults(), ), ); // Load the network request. await controller.networkService.refreshNetworkData(); expect(requestsNotifier.value.length, equals(1)); // Select the request in the network request list. final networkRequest = requestsNotifier.value.first; controller.selectedRequest.value = networkRequest; await tester.pumpAndSettle(); await tester.tap(find.text('Response')); await tester.pumpAndSettle(); // Tap the responseBody copy button. expect(clipboardContents, isEmpty); await tester.tap(find.byType(CopyToClipboardControl)); final expectedResponseBody = jsonDecode(utf8.decode(httpRequest!.responseBody!.toList())); // Check that the contents were copied to clipboard. expect(clipboardContents, isNotEmpty); expect( jsonDecode(clipboardContents), equals(expectedResponseBody), ); controller.stopRecording(); // pumpAndSettle so residual http timers can clear. await tester.pumpAndSettle(const Duration(seconds: 1)); }); group('HttpResponseTrailingDropDown', () { testWidgets( 'drop down value should update when response view type changes', (tester) async { NetworkResponseViewType? getCurrentDropDownValue() { final RoundedDropDownButton<NetworkResponseViewType> dropDownWidget = find .byType(RoundedDropDownButton<NetworkResponseViewType>) .evaluate() .first .widget as RoundedDropDownButton<NetworkResponseViewType>; return dropDownWidget.value; } final currentResponseViewType = ValueNotifier<NetworkResponseViewType>( NetworkResponseViewType.auto, ); // Matches Drop Down value with currentResponseViewType void checkDropDownValue() { final currentDropDownValue = getCurrentDropDownValue(); expect(currentDropDownValue, equals(currentResponseViewType.value)); } await tester.pumpWidget( wrapWithControllers( HttpResponseTrailingDropDown( httpGet, currentResponseViewType: currentResponseViewType, onChanged: (value) { currentResponseViewType.value = value; }, ), debugger: createMockDebuggerControllerWithDefaults(), ), ); await tester.pumpAndSettle(); checkDropDownValue(); currentResponseViewType.value = NetworkResponseViewType.text; await tester.pumpAndSettle(); checkDropDownValue(); currentResponseViewType.value = NetworkResponseViewType.auto; await tester.pumpAndSettle(); checkDropDownValue(); // pumpAndSettle so residual http timers can clear. await tester.pumpAndSettle(const Duration(seconds: 1)); }, ); testWidgets( 'onChanged handler should trigger when changing drop down value', (tester) async { final currentResponseViewType = ValueNotifier<NetworkResponseViewType>( NetworkResponseViewType.auto, ); String initial = 'Not changed'; const String afterOnChanged = 'changed'; await tester.pumpWidget( wrapWithControllers( HttpResponseTrailingDropDown( httpGet, currentResponseViewType: currentResponseViewType, onChanged: (value) { initial = afterOnChanged; }, ), debugger: createMockDebuggerControllerWithDefaults(), ), ); final dropDownFinder = find.byType( RoundedDropDownButton<NetworkResponseViewType>, ); await tester.tap(dropDownFinder); await tester.pumpAndSettle(); // Select Json from drop down await tester.tap( find.text( NetworkResponseViewType.json.toString(), ), ); await tester.pumpAndSettle(); expect( initial, afterOnChanged, ); // pumpAndSettle so residual http timers can clear. await tester.pumpAndSettle(const Duration(seconds: 1)); }, ); }); testWidgets( 'should update response view display when drop down value changes', (tester) async { final currentResponseNotifier = ValueNotifier<NetworkResponseViewType>( NetworkResponseViewType.auto, ); const contentType = 'application/json'; final responseBody = httpGet.requestBody ?? '{}'; const textStyle = TextStyle(); await tester.pumpWidget( wrapWithControllers( Column( children: [ HttpTextResponseViewer( contentType: contentType, responseBody: responseBody, currentResponseNotifier: currentResponseNotifier, textStyle: textStyle, ), HttpResponseTrailingDropDown( httpGet, currentResponseViewType: currentResponseNotifier, onChanged: (value) {}, ), ], ), debugger: createMockDebuggerControllerWithDefaults(), ), ); await tester.pumpAndSettle(); currentResponseNotifier.value = NetworkResponseViewType.json; await tester.pumpAndSettle(); // Check that Json viewer is visible Finder jsonViewer = find.byType(JsonViewer); expect(jsonViewer, findsOneWidget); currentResponseNotifier.value = NetworkResponseViewType.text; await tester.pumpAndSettle(); // Check that Json viewer is not visible jsonViewer = find.byType(JsonViewer); expect(jsonViewer, findsNothing); // pumpAndSettle so residual http timers can clear. await tester.pumpAndSettle(const Duration(seconds: 1)); }, ); }); }
devtools/packages/devtools_app/test/network/network_request_inspector_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/network/network_request_inspector_test.dart", "repo_id": "devtools", "token_count": 4155 }
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/src/framework/scaffold.dart'; import 'package:devtools_app/src/service/service_manager.dart'; import 'package:devtools_app/src/shared/banner_messages.dart'; import 'package:devtools_app/src/shared/globals.dart'; import 'package:devtools_app/src/shared/notifications.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'; void main() { late FakeServiceConnectionManager fakeServiceConnection; setUp(() { fakeServiceConnection = FakeServiceConnectionManager(); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal(NotificationService, NotificationService()); setGlobal(BannerMessagesController, BannerMessagesController()); }); group('BannerMessages', () { /// Pumps a test frame so that we can ensure post frame callbacks are /// executed. Future<void> pumpTestFrame(WidgetTester tester) async { // Tap the raised Button in order to draw a frame. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); } Widget buildBannerMessages() { return wrap( Directionality( textDirection: TextDirection.ltr, child: BannerMessages( screen: SimpleScreen( Column( children: <Widget>[ // This is button is present so that we can tap it and // simulate a frame being drawn. ElevatedButton( onPressed: () => {}, child: const SizedBox(), ), ], ), ), ), ), ); } testWidgets('displays banner messages', (WidgetTester tester) async { await tester.pumpWidget(buildBannerMessages()); expect(find.byKey(k1), findsNothing); bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); expect(find.byKey(k2), findsNothing); bannerMessages.addMessage(testMessage2); await pumpTestFrame(tester); expect(find.byKey(k2), findsOneWidget); }); testWidgets('does not add duplicate messages', (WidgetTester tester) async { await tester.pumpWidget(buildBannerMessages()); expect(find.byKey(k1), findsNothing); bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); // Verify there is still only one message after adding the duplicate. bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); }); testWidgets('removes and dismisses messages', (WidgetTester tester) async { await tester.pumpWidget(buildBannerMessages()); expect(find.byKey(k1), findsNothing); bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); bannerMessages.removeMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsNothing); // Verify message can be re-added, since it was not removed with // `dismiss = true`. bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); // Remove message by key this time. bannerMessages.removeMessageByKey(k1, testMessage1ScreenId); await pumpTestFrame(tester); expect(find.byKey(k1), findsNothing); // Verify message can be re-added, since it was not removed with // `dismiss = true`. bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); bannerMessages.removeMessage(testMessage1, dismiss: true); await pumpTestFrame(tester); expect(find.byKey(k1), findsNothing); // Verify message cannot be re-added, since it was removed with // `dismiss = true`. bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsNothing); }); testWidgets('messages self dismiss', (WidgetTester tester) async { await tester.pumpWidget(buildBannerMessages()); expect(find.byKey(k1), findsNothing); bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); await tester.tap(find.byType(IconButton)); await pumpTestFrame(tester); expect(find.byKey(k1), findsNothing); // Verify message cannot be re-added, since it was removed with // `dismiss = true`. bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsNothing); }); testWidgets( 'dismissed messages can be re-added when ignoreIfAlreadyDismissed is false', (WidgetTester tester) async { await tester.pumpWidget(buildBannerMessages()); expect(find.byKey(k1), findsNothing); bannerMessages.addMessage(testMessage1); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); await tester.tap(find.byType(IconButton)); await pumpTestFrame(tester); expect(find.byKey(k1), findsNothing); // Verify message can be re-added with ignoreIfAlreadyDismissed = false. bannerMessages.addMessage( testMessage1, ignoreIfAlreadyDismissed: false, ); await pumpTestFrame(tester); expect(find.byKey(k1), findsOneWidget); }, ); }); } final testMessage1ScreenId = SimpleScreen.id; final testMessage2ScreenId = SimpleScreen.id; const k1 = Key('test message 1'); const k2 = Key('test message 2'); final testMessage1 = BannerMessage( key: k1, textSpans: const [TextSpan(text: 'Test Message 1')], screenId: testMessage1ScreenId, messageType: BannerMessageType.warning, ); final testMessage2 = BannerMessage( key: k2, textSpans: const [TextSpan(text: 'Test Message 2')], screenId: testMessage2ScreenId, messageType: BannerMessageType.warning, );
devtools/packages/devtools_app/test/shared/banner_messages_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/banner_messages_test.dart", "repo_id": "devtools", "token_count": 2522 }
114
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app/src/shared/future_work_tracker.dart'; import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('FutureWorkTracker', () { test('tracker returns future', () { final tracker = FutureWorkTracker(); final completer = Completer<Object?>(); // ignore: discarded_futures, by design expect(tracker.track(() => completer.future), equals(isA<Future>())); }); void advanceClock(FakeAsync async) { async.elapse(const Duration(milliseconds: 50)); } test('tracks work', () { _wrapAndRunAsync( (async) async { final tracker = FutureWorkTracker(); expect(tracker.active.value, isFalse); final completer1 = Completer<Object?>(); unawaited(tracker.track(() => completer1.future)); advanceClock(async); expect(tracker.active.value, isTrue); final completer2 = Completer<Object?>(); unawaited(tracker.track(() => completer2.future)); advanceClock(async); expect(tracker.active.value, isTrue); completer1.complete(null); unawaited(completer1.future); advanceClock(async); expect(tracker.active.value, isTrue); completer2.complete(null); unawaited(completer2.future); advanceClock(async); expect(tracker.active.value, isFalse); }, ); }); test('tracks work after clear', () { _wrapAndRunAsync( (async) async { final tracker = FutureWorkTracker(); expect(tracker.active.value, isFalse); final completer1 = Completer<Object?>(); unawaited(tracker.track(() => completer1.future)); advanceClock(async); expect(tracker.active.value, isTrue); tracker.clear(); expect(tracker.active.value, isFalse); final completer2 = Completer<Object?>(); unawaited(tracker.track(() => completer2.future)); advanceClock(async); expect(tracker.active.value, isTrue); completer2.complete(null); unawaited(completer2.future); advanceClock(async); expect(tracker.active.value, isFalse); }, ); }); test('tracks failed work', () { _wrapAndRunAsync((async) async { await runZonedGuarded( () async { final tracker = FutureWorkTracker(); expect(tracker.active.value, isFalse); final completer1 = Completer<Object?>(); unawaited(tracker.track(() => completer1.future)); advanceClock(async); expect(tracker.active.value, isTrue); final completer2 = Completer<Object?>(); unawaited(tracker.track(() => completer2.future)); advanceClock(async); expect(tracker.active.value, isTrue); completer1.completeError('bad'); try { unawaited(completer1.future); advanceClock(async); } catch (error) { expectSync(error, equals('bad')); } expect(tracker.active.value, isTrue); completer2.completeError('bad'); try { unawaited(completer2.future); advanceClock(async); } catch (error) { expectSync(error, equals('bad')); } expect(tracker.active.value, isFalse); }, (Object error, StackTrace stack) { expectSync(error, equals('bad')); }, ); }); }); }); } void _wrapAndRunAsync(Future<void> Function(FakeAsync) testCallback) { unawaited( fakeAsync((async) async { // If the test expectations are not wrapped in a future, the test will // not fail even if one of the expectations fails. Future<void> testFuture() => testCallback(async); unawaited(testFuture()); async.flushMicrotasks(); }), ); }
devtools/packages/devtools_app/test/shared/future_work_tracker_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/future_work_tracker_test.dart", "repo_id": "devtools", "token_count": 1898 }
115
// 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/src/shared/primitives/simple_items.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../test_infra/utils/test_utils.dart'; void main() { for (final link in DocLinks.values) { test('$link is not broken', () async { final content = await loadPageHtmlContent(link.value); final hash = link.hash; if (hash != null) { expect(content, contains('href="#$hash"')); } }); } }
devtools/packages/devtools_app/test/shared/primitives/simple_items_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/primitives/simple_items_test.dart", "repo_id": "devtools", "token_count": 222 }
116
// 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. @TestOn('vm') import 'dart:convert'; import 'dart:io'; import 'package:devtools_app/src/screens/debugger/span_parser.dart'; import 'package:devtools_app/src/screens/debugger/syntax_highlighter.dart'; import 'package:devtools_app/src/shared/routing.dart'; import 'package:devtools_app/src/shared/ui/colors.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; const modifierSpans = [ // Start multi-capture spans 'import "foo";', 'export "foo";', 'part of "baz";', 'part "foo";', 'export "foo";', // End multi-capture spans '@annotation', 'true', 'false', 'null', 'as', 'abstract', 'class', 'enum', 'extends', 'extension', 'external', 'factory', 'implements', 'get', 'mixin', 'native', 'operator', 'set', 'typedef', 'with', 'covariant', 'static', 'final', 'const', 'required', 'late', ]; const controlFlowSpans = [ 'try', 'on', 'catch', 'finally', 'throw', 'rethrow', 'break', 'case', 'continue', 'default', 'do', 'else', 'for', 'if', 'in', 'return', 'switch', 'while', 'sync', 'async', 'await', 'yield', 'assert', 'new', ]; const declarationSpans = [ 'this', 'super', 'bool', 'num', 'int', 'double', 'dynamic', '_PrivateDeclaration', 'PublicDeclaration', ]; const functionSpans = [ 'foo()', '_foo()', 'foo(bar)', ]; const numericSpans = [ '1', '1.1', '0xFF', '0xff', '1.3e5', '1.3E5', ]; const helloWorld = ''' Future<void> main() async { print('hello world!'); } '''; const multilineDoc = ''' /** * Multiline */ '''; const docCodeReference = ''' /// This is a code reference for [Foo] '''; const variableReferenceInString = ''' '\$i: \${foo[i] == bar[i]}' '''; void main() { late Grammar grammar; setUp(() async { final grammarFile = File('assets/dart_syntax.json'); expect(grammarFile.existsSync(), true); final grammarJson = json.decode(await grammarFile.readAsString()); grammar = Grammar.fromJson(grammarJson); setGlobal(IdeTheme, IdeTheme()); }); Color? defaultTextColor(_) => const TextStyle().color; Color commentSyntaxColor(ColorScheme scheme) => scheme.commentSyntaxColor; Color controlFlowSyntaxColor(ColorScheme scheme) => scheme.controlFlowSyntaxColor; Color declarationSyntaxColor(ColorScheme scheme) => scheme.declarationsSyntaxColor; Color functionSyntaxColor(ColorScheme scheme) => scheme.functionSyntaxColor; Color modifierSyntaxColor(ColorScheme scheme) => scheme.modifierSyntaxColor; Color numericConstantSyntaxColor(ColorScheme scheme) => scheme.numericConstantSyntaxColor; Color stringSyntaxColor(ColorScheme scheme) => scheme.stringSyntaxColor; Color variableSyntaxColor(ColorScheme scheme) => scheme.variableSyntaxColor; void spanTester( BuildContext context, TextSpan span, String expectedText, Color? Function(ColorScheme) expectedColor, ) { expect(span.text, expectedText); expect( span.style, TextStyle( color: expectedColor(Theme.of(context).colorScheme), ), ); } void runTestsWithTheme({required bool useDarkTheme}) { group( 'Syntax Highlighting (${useDarkTheme ? 'Dark' : 'Light'} Theme)', () { Widget buildSyntaxHighlightingTestContext( void Function(BuildContext) callback, ) { return MaterialApp.router( theme: themeFor( isDarkTheme: useDarkTheme, ideTheme: getIdeTheme(), theme: ThemeData( useMaterial3: true, colorScheme: useDarkTheme ? darkColorScheme : lightColorScheme, ), ), routerDelegate: DevToolsRouterDelegate( (a, b, c, d) => const CupertinoPage(child: SizedBox.shrink()), ), routeInformationParser: DevToolsRouteInformationParser(), builder: (context, _) { callback(context); return Container(); }, ); } testWidgetsWithContext( 'hello world smoke', (WidgetTester tester) async { final highlighter = SyntaxHighlighter.withGrammar( grammar: grammar, source: helloWorld, ); await tester.pumpWidget( buildSyntaxHighlightingTestContext( (context) { final highlighted = highlighter.highlight(context); final children = highlighted.children!; spanTester( context, children[0] as TextSpan, 'Future', declarationSyntaxColor, ); spanTester( context, children[1] as TextSpan, '<', defaultTextColor, ); spanTester( context, children[2] as TextSpan, 'void', modifierSyntaxColor, ); spanTester( context, children[3] as TextSpan, '>', defaultTextColor, ); spanTester( context, children[4] as TextSpan, ' ', defaultTextColor, ); spanTester( context, children[5] as TextSpan, 'main', functionSyntaxColor, ); spanTester( context, children[6] as TextSpan, '() ', defaultTextColor, ); spanTester( context, children[7] as TextSpan, 'async', controlFlowSyntaxColor, ); spanTester( context, children[8] as TextSpan, ' {', defaultTextColor, ); expect(children[9].toPlainText(), '\n'); spanTester( context, children[10] as TextSpan, ' ', defaultTextColor, ); spanTester( context, children[11] as TextSpan, 'print', functionSyntaxColor, ); spanTester( context, children[12] as TextSpan, '(', defaultTextColor, ); spanTester( context, children[13] as TextSpan, "'hello world!'", stringSyntaxColor, ); spanTester( context, children[14] as TextSpan, ')', defaultTextColor, ); spanTester( context, children[15] as TextSpan, ';', defaultTextColor, ); expect(children[16].toPlainText(), '\n'); spanTester( context, children[17] as TextSpan, '}', defaultTextColor, ); expect(children[18].toPlainText(), '\n'); }, ), ); }, ); testWidgetsWithContext( 'multiline documentation', (WidgetTester tester) async { final highlighter = SyntaxHighlighter.withGrammar( grammar: grammar, source: multilineDoc, ); await tester.pumpWidget( buildSyntaxHighlightingTestContext( (context) { final highlighted = highlighter.highlight(context); final children = highlighted.children!; spanTester( context, children[0] as TextSpan, '/**', commentSyntaxColor, ); expect(children[1].toPlainText(), '\n'); spanTester( context, children[2] as TextSpan, ' * Multiline', commentSyntaxColor, ); expect( children[3].toPlainText(), '\n', ); spanTester( context, children[4] as TextSpan, ' */', commentSyntaxColor, ); }, ), ); }, ); testWidgetsWithContext( 'documentation code reference', (WidgetTester tester) async { final highlighter = SyntaxHighlighter.withGrammar( grammar: grammar, source: docCodeReference, ); await tester.pumpWidget( buildSyntaxHighlightingTestContext( (context) { final highlighted = highlighter.highlight(context); final children = highlighted.children!; spanTester( context, children[0] as TextSpan, '/// This is a code reference for ', commentSyntaxColor, ); spanTester( context, children[1] as TextSpan, '[Foo]', variableSyntaxColor, ); expect(children[2].toPlainText(), '\n'); }, ), ); }, ); testWidgetsWithContext( 'variable reference in string', (WidgetTester tester) async { final highlighter = SyntaxHighlighter.withGrammar( grammar: grammar, source: variableReferenceInString, ); await tester.pumpWidget( buildSyntaxHighlightingTestContext( (context) { final highlighted = highlighter.highlight(context); final children = highlighted.children!; var i = 0; spanTester( context, children[i++] as TextSpan, "'", stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, '\$', stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, 'i', variableSyntaxColor, ); spanTester( context, children[i++] as TextSpan, ': ', stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, '\${', stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, 'foo', variableSyntaxColor, ); spanTester( context, children[i++] as TextSpan, '[', stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, 'i', variableSyntaxColor, ); spanTester( context, children[i++] as TextSpan, '] == ', stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, 'bar', variableSyntaxColor, ); spanTester( context, children[i++] as TextSpan, '[', stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, 'i', variableSyntaxColor, ); spanTester( context, children[i++] as TextSpan, ']}', stringSyntaxColor, ); spanTester( context, children[i++] as TextSpan, '\'', stringSyntaxColor, ); }, ), ); }, ); void testSingleSpan( String name, String spanText, Color Function(ColorScheme) colorCallback, ) { testWidgetsWithContext( "$name '$spanText'", (WidgetTester tester) async { final highlighter = SyntaxHighlighter.withGrammar( grammar: grammar, source: spanText, ); await tester.pumpWidget( buildSyntaxHighlightingTestContext( (context) { final highlighted = highlighter.highlight(context); expect( highlighted.children!.first.style, TextStyle( color: colorCallback(Theme.of(context).colorScheme), ), ); }, ), ); }, ); } group( 'single span highlighting:', () { for (final spanText in modifierSpans) { testSingleSpan( 'modifier', spanText, modifierSyntaxColor, ); } for (final spanText in controlFlowSpans) { testSingleSpan( 'control flow', spanText, controlFlowSyntaxColor, ); } for (final spanText in declarationSpans) { testSingleSpan( 'declaration', spanText, declarationSyntaxColor, ); } for (final spanText in functionSpans) { testSingleSpan( 'function', spanText, functionSyntaxColor, ); } for (final spanText in numericSpans) { testSingleSpan( 'numeric', spanText, numericConstantSyntaxColor, ); } }, ); }, ); } runTestsWithTheme(useDarkTheme: false); runTestsWithTheme(useDarkTheme: true); }
devtools/packages/devtools_app/test/shared/syntax_highlighter_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/shared/syntax_highlighter_test.dart", "repo_id": "devtools", "token_count": 9531 }
117
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'dart:async'; void main() { print('starting debugging app (async)'); void run() { Timer(const Duration(milliseconds: 100), () async { await performAction(); run(); }); } run(); } int actionCount = 0; Future performAction() async { inc(); // breakpoint print(actionCount); // step inc(); // step print(actionCount); // step await delay(); // step } void inc() { actionCount++; } Future delay() { return Future.delayed(const Duration(milliseconds: 100)); }
devtools/packages/devtools_app/test/test_infra/fixtures/debugging_app_async.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/fixtures/debugging_app_async.dart", "repo_id": "devtools", "token_count": 232 }
118
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/material.dart'; class MissingMaterialError extends StatelessWidget { const MissingMaterialError({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return const MaterialApp( title: 'Missing Material', home: ExampleWidget(), // The line below can resolve the error. // home: Scaffold(body: new ExampleWidget()), ); } } /// Opens an [AlertDialog] showing what the user typed. class ExampleWidget extends StatefulWidget { const ExampleWidget({Key? key}) : super(key: key); @override State<ExampleWidget> createState() => _ExampleWidgetState(); } /// State for [ExampleWidget] widgets. class _ExampleWidgetState extends State<ExampleWidget> { final TextEditingController _controller = TextEditingController(); @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( controller: _controller, decoration: const InputDecoration( hintText: 'Type something', ), ), ElevatedButton( onPressed: () { unawaited( showDialog( context: context, builder: (context) => AlertDialog( title: const Text('What you typed'), content: Text(_controller.text), ), ), ); }, child: const Text('DONE'), ), ], ); } }
devtools/packages/devtools_app/test/test_infra/fixtures/flutter_error_app/lib/missing_material_error.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/fixtures/flutter_error_app/lib/missing_material_error.dart", "repo_id": "devtools", "token_count": 690 }
119
To retake the snapshots: 1. Create counter app with `flutter create`. 2. Update button handler to take snapshot after increasing counter: ``` void _incrementCounter() { setState(() { _counter++; }); var fileName = 'counter_snapshot$_counter'; fileName = p.absolute(fileName); print('saving snapshot to $fileName'); NativeRuntime.writeHeapSnapshotToFile(fileName); } ``` 3. Run the counter and click the button four times. 4. Copy the collected files to this folder.
devtools/packages/devtools_app/test/test_infra/test_data/memory/heap/README.md/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/test_data/memory/heap/README.md", "repo_id": "devtools", "token_count": 161 }
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. void foo() { Object? a; if (1 == 2) {} if (1 != 2) {} if (1 < 2) {} if (1 <= 2) {} if (1 > 2) {} if (1 >= 2) {} var b = 1 < 2 ? 1 / 1 : 2 * 2; a ??= b; b += 1; b -= 1; b = b / 2; b = b ~/ 2; b = b % 2; b++; b--; ++b; --b; var c = 1 >> 2; c >>= 1; var d = 1 << 2; d <<= 2; var e = 1 >>> 2; e >>>= 3; var f = -b; var g = 1 & 2; var h = 1 ^ 2; var i = ~2; var j = 1 & 2; j &= 2; j ^= 2; j |= 2; var k = 1 ^ 2; var l = 1 | 2; var m = !(a == a && false || true); }
devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/operators.dart/0
{ "file_path": "devtools/packages/devtools_app/test/test_infra/test_data/syntax_highlighting/operators.dart", "repo_id": "devtools", "token_count": 333 }
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/inbound_references_tree.dart'; import 'package:devtools_app/src/screens/vm_developer/vm_developer_common_widgets.dart'; import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:devtools_test/devtools_test.dart'; import 'package:devtools_test/helpers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:vm_service/vm_service.dart'; import '../vm_developer_test_utils.dart'; void main() { const windowSize = Size(4000.0, 4000.0); late MockClassObject mockClassObject; late TestObjectInspectorViewController testObjectInspectorViewController; late FakeServiceConnectionManager fakeServiceConnection; late InstanceRef requestedSize; final fetchingSizeNotifier = ValueNotifier<bool>(false); final retainingPathNotifier = ValueNotifier<RetainingPath?>(null); final inboundRefsNotifier = ListValueNotifier<InboundReferencesTreeNode>([]); setUp(() { fakeServiceConnection = FakeServiceConnectionManager(); setUpMockScriptManager(); setGlobal(ServiceConnectionManager, fakeServiceConnection); setGlobal(IdeTheme, IdeTheme()); setGlobal( DevToolsEnvironmentParameters, ExternalDevToolsEnvironmentParameters(), ); setGlobal(PreferencesController, PreferencesController()); mockClassObject = MockClassObject(); testObjectInspectorViewController = TestObjectInspectorViewController(); final json = testInstance.toJson(); requestedSize = Instance.parse(json)!; when(mockClassObject.reachableSize).thenReturn(null); when(mockClassObject.retainedSize).thenReturn(null); // Intentionally unawaited. // ignore: discarded_futures when(mockClassObject.requestReachableSize()).thenAnswer((_) async { fetchingSizeNotifier.value = true; if (requestedSize.valueAsString == null) { requestedSize.valueAsString = '1024'; } else { int value = int.parse(requestedSize.valueAsString!); value += 512; requestedSize.valueAsString = value.toString(); } fetchingSizeNotifier.value = false; }); when(mockClassObject.retainingPath).thenReturn(retainingPathNotifier); // Intentionally unawaited. // ignore: discarded_futures when(mockClassObject.requestRetainingPath()).thenAnswer((_) async { retainingPathNotifier.value = testRetainingPath; }); when(mockClassObject.inboundReferencesTree).thenReturn(inboundRefsNotifier); // Intentionally unawaited. // ignore: discarded_futures when(mockClassObject.requestInboundsRefs()).thenAnswer((_) async { inboundRefsNotifier.clear(); inboundRefsNotifier.addAll( InboundReferencesTreeNode.buildTreeRoots(testInboundRefs), ); }); // Intentionally unawaited. // ignore: discarded_futures when(mockClassObject.expandInboundRef(any)).thenAnswer((_) async { for (final entry in inboundRefsNotifier.value) { entry.addAllChildren( InboundReferencesTreeNode.buildTreeRoots( TestInboundReferences( references: [ InboundReference(source: testFunction), ], ), ), ); } inboundRefsNotifier.notifyListeners(); }); }); testWidgets( 'test RequestableSizeWidget while fetching data', (WidgetTester tester) async { await tester.pumpWidget( wrap( RequestableSizeWidget( fetching: ValueNotifier(true), sizeProvider: () => mockClassObject.reachableSize, requestFunction: mockClassObject.requestReachableSize, ), ), ); await tester.pump(); expect(find.byType(CircularProgressIndicator), findsOneWidget); }, ); testWidgets('test RequestableSizeWidget', (WidgetTester tester) async { when(mockClassObject.reachableSize).thenReturn(requestedSize); await tester.pumpWidget( wrap( RequestableSizeWidget( fetching: fetchingSizeNotifier, sizeProvider: () => mockClassObject.reachableSize, requestFunction: mockClassObject.requestReachableSize, ), ), ); expect(find.byIcon(Icons.refresh), findsOneWidget); await tester.tap(find.byIcon(Icons.refresh)); await tester.pumpAndSettle(); expect(requestedSize.valueAsString, '1024'); expect(find.byType(Text), findsOneWidget); expect(find.text('1.0 KB'), findsOneWidget); expect(find.byType(ToolbarRefresh), findsOneWidget); await tester.tap(find.byType(ToolbarRefresh)); await tester.pumpAndSettle(); expect(requestedSize.valueAsString, '1536'); expect(find.byType(Text), findsOneWidget); expect(find.text('1.5 KB'), findsOneWidget); expect(find.byType(ToolbarRefresh), findsOneWidget); }); testWidgetsWithWindowSize( 'test RetainingPathWidget with null data', windowSize, (WidgetTester tester) async { await tester.pumpWidget( wrap( RetainingPathWidget( controller: testObjectInspectorViewController, retainingPath: mockClassObject.retainingPath, onExpanded: (bool _) {}, ), ), ); expect(find.byType(RetainingPathWidget), findsOneWidget); expect(find.text('Retaining Path'), findsOneWidget); await tester.tap(find.text('Retaining Path')); await tester.pump(); expect(find.byType(CenteredCircularProgressIndicator), findsOneWidget); }, ); testWidgetsWithWindowSize( 'test RetainingPathWidget with fetched data', windowSize, (WidgetTester tester) async { retainingPathNotifier.value = null; await tester.pumpWidget( wrap( RetainingPathWidget( controller: testObjectInspectorViewController, retainingPath: mockClassObject.retainingPath, onExpanded: (bool _) { mockClassObject.requestRetainingPath(); }, ), ), ); await tester.tap(find.text('Retaining Path')); await tester.pumpAndSettle(); expect(find.text('FooClass', findRichText: true), findsOneWidget); expect( find.text( 'Retained by element [1] of fooSuperClass', findRichText: true, ), findsOneWidget, ); expect( find.text('Retained by \$1 of Record', findRichText: true), findsOneWidget, ); expect( find.text('Retained by fooParentField of Record', findRichText: true), findsOneWidget, ); expect( find.text( 'Retained by element at [fooField] of fooSuperClass', findRichText: true, ), findsOneWidget, ); expect( find.text( 'Retained by fooParentField of FooClass fooField of fooLib', findRichText: true, ), findsOneWidget, ); expect( find.text( 'Retained by a GC root of type: class table', findRichText: true, ), findsOneWidget, ); }, ); testWidgetsWithWindowSize( 'test $InboundReferencesTree with null data', windowSize, (WidgetTester tester) async { inboundRefsNotifier.clear(); await tester.pumpWidget( wrap( InboundReferencesTree( controller: testObjectInspectorViewController, object: mockClassObject, onExpanded: (bool _) {}, ), ), ); expect(find.text('Inbound References'), findsOneWidget); await tester.tap(find.text('Inbound References')); await tester.pump(); expect( find.text('There are no inbound references for this object'), findsOneWidget, ); }, ); testWidgetsWithWindowSize( 'test $InboundReferencesTree with data', windowSize, (WidgetTester tester) async { await tester.pumpWidget( wrap( InboundReferencesTree( controller: testObjectInspectorViewController, object: mockClassObject, onExpanded: (bool _) => mockClassObject.requestInboundsRefs(), ), ), ); await tester.tap(find.text('Inbound References')); await tester.pumpAndSettle(); expect( find.text('Referenced by '), findsNWidgets(5), ); // Covers: // - Referenced by fooParentField in Record // - Referenced by element 1 of Record expect( find.text('fooParentField in ', findRichText: true), findsOneWidget, ); expect(find.text('element 1 of '), findsOneWidget); expect( find.text('Record', findRichText: true), findsNWidgets(2), ); // Covers: // - Referenced by fooField // - Referenced by fooSuperClass // - Referenced by fooFunction expect( find.text('fooField', findRichText: true), findsOneWidget, ); expect( find.text('fooSuperClass', findRichText: true), findsOneWidget, ); expect( find.text('fooFunction', findRichText: true), findsOneWidget, ); await tester.tap(find.byIcon(Icons.keyboard_arrow_down).first); await tester.pumpAndSettle(); expect( find.text('Referenced by '), findsNWidgets(6), ); expect( find.text('fooFunction', findRichText: true), findsNWidgets(2), ); }, ); }
devtools/packages/devtools_app/test/vm_developer/object_inspector/vm_developer_common_widgets_test.dart/0
{ "file_path": "devtools/packages/devtools_app/test/vm_developer/object_inspector/vm_developer_common_widgets_test.dart", "repo_id": "devtools", "token_count": 4046 }
122
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:core'; import 'package:collection/collection.dart' show IterableExtension; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:vm_service/vm_service.dart' hide Error; import '../utils/auto_dispose.dart'; import '../utils/list.dart'; import 'isolate_state.dart'; import 'service_extensions.dart' as extensions; final _log = Logger('isolate_manager'); @visibleForTesting base mixin TestIsolateManager implements IsolateManager {} final class IsolateManager with DisposerMixin { final _isolateStates = <IsolateRef, IsolateState>{}; /// Signifies whether the main isolate should be selected if it is started. /// /// This is used to make sure the the main isolate remains selected after /// a hot restart. bool _shouldReselectMainIsolate = false; VmService? _service; final StreamController<IsolateRef?> _isolateCreatedController = StreamController<IsolateRef?>.broadcast(); final StreamController<IsolateRef?> _isolateExitedController = StreamController<IsolateRef?>.broadcast(); ValueListenable<IsolateRef?> get selectedIsolate => _selectedIsolate; final _selectedIsolate = ValueNotifier<IsolateRef?>(null); int _lastIsolateIndex = 0; final Map<String?, int> _isolateIndexMap = {}; ValueListenable<List<IsolateRef>> get isolates => _isolates; final _isolates = ListValueNotifier(const <IsolateRef>[]); ValueListenable<IsolateRef?> get mainIsolate => _mainIsolate; final _mainIsolate = ValueNotifier<IsolateRef?>(null); final _isolateRunnableCompleters = <String?, Completer<void>>{}; // TODO(https://github.com/flutter/flutter/issues/134470): Track hot-restarts // triggered by other clients. bool hotRestartInProgress = false; Future<void> init(List<IsolateRef> isolates) async { await initIsolates(isolates); } IsolateState? get mainIsolateState { return _mainIsolate.value != null ? _isolateStates[_mainIsolate.value!] : null; } /// Return a unique, monotonically increasing number for this Isolate. int? isolateIndex(IsolateRef isolateRef) { if (!_isolateIndexMap.containsKey(isolateRef.id)) { _isolateIndexMap[isolateRef.id] = ++_lastIsolateIndex; } return _isolateIndexMap[isolateRef.id]; } void selectIsolate(IsolateRef? isolateRef) { _setSelectedIsolate(isolateRef); } @protected Future<void> initIsolates(List<IsolateRef> isolates) async { _clearIsolateStates(); await Future.wait([ for (final isolateRef in isolates) _registerIsolate(isolateRef), ]); // It is critical that the _serviceExtensionManager is already listening // for events indicating that new extension rpcs are registered before this // call otherwise there is a race condition where service extensions are not // described in the selectedIsolate or received as an event. It is ok if a // service extension is included in both places as duplicate extensions are // handled gracefully. await _initSelectedIsolate(); } Future<void> _registerIsolate(IsolateRef isolateRef) async { assert(!_isolateStates.containsKey(isolateRef)); _isolateStates[isolateRef] = IsolateState(isolateRef); _isolates.add(isolateRef); isolateIndex(isolateRef); await _loadIsolateState(isolateRef); } Future<void> _loadIsolateState(IsolateRef isolateRef) async { try { final service = _service; var isolate = await _service!.getIsolate(isolateRef.id!); if (isolate.runnable == false) { final isolateRunnableCompleter = _isolateRunnableCompleters.putIfAbsent( isolate.id, () => Completer<void>(), ); if (!isolateRunnableCompleter.isCompleted) { await isolateRunnableCompleter.future; isolate = await _service!.getIsolate(isolate.id!); } } if (service != _service) return; final state = _isolateStates[isolateRef]; if (state != null) { // Isolate might have already been closed. state.handleIsolateLoad(isolate); } } on SentinelException catch (_) { // Isolate doesn't exist anymore, nothing to do. _log.info( 'isolateRef($isolateRef) ceased to exist while loading isolate state', ); } } Future<void> _handleIsolateEvent(Event event) async { if (event.kind == EventKind.kIsolateRunnable) { final isolateRunnable = _isolateRunnableCompleters.putIfAbsent( event.isolate!.id, () => Completer<void>(), ); isolateRunnable.complete(); if (hotRestartInProgress) { hotRestartInProgress = false; } } else if (event.kind == EventKind.kIsolateStart && !event.isolate!.isSystemIsolate!) { await _registerIsolate(event.isolate!); _isolateCreatedController.add(event.isolate); // TODO(jacobr): we assume the first isolate started is the main isolate // but that may not always be a safe assumption. if (_mainIsolate.value == null) { _mainIsolate.value = event.isolate; if (_shouldReselectMainIsolate) { // Assume the main isolate has come back up after a hot restart, so // select it. _shouldReselectMainIsolate = false; _setSelectedIsolate(event.isolate); } } if (_selectedIsolate.value == null) { _setSelectedIsolate(event.isolate); } } else if (event.kind == EventKind.kServiceExtensionAdded) { // Check to see if there is a new isolate. if (_selectedIsolate.value == null && extensions.isFlutterExtension(event.extensionRPC!)) { _setSelectedIsolate(event.isolate); } } else if (event.kind == EventKind.kIsolateExit) { _isolateStates.remove(event.isolate)?.dispose(); if (event.isolate != null) _isolates.remove(event.isolate!); _isolateExitedController.add(event.isolate); if (_mainIsolate.value == event.isolate) { if (_selectedIsolate.value == _mainIsolate.value) { // If the main isolate was selected and exits, then assume that a hot // restart is happening. So reselect when the main isolate comes back. _shouldReselectMainIsolate = true; } _mainIsolate.value = null; } if (_selectedIsolate.value == event.isolate) { _selectedIsolate.value = _isolateStates.isEmpty ? null : _isolateStates.keys.first; } _isolateRunnableCompleters.remove(event.isolate!.id); } } Future<void> _initSelectedIsolate() async { if (_isolateStates.isEmpty) { return; } _mainIsolate.value = null; final service = _service; final mainIsolate = await _computeMainIsolate(); if (service != _service) return; _mainIsolate.value = mainIsolate; _setSelectedIsolate(_mainIsolate.value); } Future<IsolateRef?> _computeMainIsolate() async { if (_isolateStates.isEmpty) return null; final service = _service; for (var isolateState in _isolateStates.values) { if (_selectedIsolate.value == null) { final isolate = await isolateState.isolate; if (service != _service) return null; for (String extensionName in isolate?.extensionRPCs ?? []) { if (extensions.isFlutterExtension(extensionName)) { return isolateState.isolateRef; } } } } final IsolateRef? ref = _isolateStates.keys.firstWhereOrNull((IsolateRef ref) { // 'foo.dart:main()' return ref.name!.contains(':main('); }); return ref ?? _isolateStates.keys.first; } void _setSelectedIsolate(IsolateRef? ref) { _selectedIsolate.value = ref; } void handleVmServiceClosed() { cancelStreamSubscriptions(); _selectedIsolate.value = null; _service = null; _lastIsolateIndex = 0; _setSelectedIsolate(null); _isolateIndexMap.clear(); _clearIsolateStates(); _mainIsolate.value = null; _isolateRunnableCompleters.clear(); } void _clearIsolateStates() { for (var isolateState in _isolateStates.values) { isolateState.dispose(); } _isolateStates.clear(); _isolates.clear(); } void vmServiceOpened(VmService service) { _selectedIsolate.value = null; cancelStreamSubscriptions(); _service = service; autoDisposeStreamSubscription( service.onIsolateEvent.listen(_handleIsolateEvent), ); autoDisposeStreamSubscription( service.onDebugEvent.listen(_handleDebugEvent), ); // We don't know the main isolate yet. _mainIsolate.value = null; } IsolateState isolateState(IsolateRef isolateRef) { return _isolateStates.putIfAbsent( isolateRef, () => IsolateState(isolateRef), ); } void _handleDebugEvent(Event event) { final isolate = event.isolate; if (isolate == null) return; final isolateState = _isolateStates[isolate]; if (isolateState == null) { return; } isolateState.handleDebugEvent(event.kind); } }
devtools/packages/devtools_app_shared/lib/src/service/isolate_manager.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/service/isolate_manager.dart", "repo_id": "devtools", "token_count": 3434 }
123
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; /// Mixin to simplifying managing the lifetime of listeners used by a /// [StatefulWidget]. /// /// This mixin works by delegating to a [DisposerMixin]. It implements all of /// [DisposerMixin]'s interface. /// /// See also: /// * [AutoDisposeControllerMixin], which provides the same functionality for /// controller classes. mixin AutoDisposeMixin<T extends StatefulWidget> on State<T> implements DisposerMixin { final _delegate = Disposer(); @override @visibleForTesting List<Listenable> get listenables => _delegate.listenables; @override @visibleForTesting List<VoidCallback> get listeners => _delegate.listeners; @override void dispose() { cancelStreamSubscriptions(); cancelListeners(); cancelFocusNodes(); super.dispose(); } void _refresh() => setState(() {}); /// Add a listener to a Listenable object that is automatically removed on /// the object disposal or when cancel is called. /// /// If listener is not provided, setState will be invoked. @override void addAutoDisposeListener( Listenable? listenable, [ VoidCallback? listener, String? id, ]) { _delegate.addAutoDisposeListener(listenable, listener ?? _refresh, id); } @override // ignore: avoid_shadowing_type_parameters, false positive void callOnceWhenReady<T>({ required VoidCallback callback, required ValueListenable<T> trigger, required bool Function(T triggerValue) readyWhen, }) { _delegate.callOnceWhenReady( callback: callback, trigger: trigger, readyWhen: readyWhen, ); } @override void autoDisposeStreamSubscription(StreamSubscription subscription) { _delegate.autoDisposeStreamSubscription(subscription); } @override void autoDisposeFocusNode(FocusNode? node) { _delegate.autoDisposeFocusNode(node); } @override void cancelStreamSubscriptions() { _delegate.cancelStreamSubscriptions(); } @override void cancelListeners({List<String> excludeIds = const <String>[]}) { _delegate.cancelListeners(excludeIds: excludeIds); } @override void cancelListener(VoidCallback? listener) { _delegate.cancelListener(listener); } @override void cancelFocusNodes() { _delegate.cancelFocusNodes(); } } /// Provides functionality to simplify listening to streams and ValueNotifiers, /// and disposing FocusNodes. /// /// See also: /// * [AutoDisposeControllerMixin] which integrates this functionality /// with [DisposableController] objects. /// * [AutoDisposeMixin], which integrates this functionality with [State] /// objects. mixin DisposerMixin { final List<StreamSubscription> _subscriptions = []; final List<FocusNode> _focusNodes = []; @protected @visibleForTesting List<Listenable> get listenables => _listenables; /// Not using VoidCallback because of /// https://github.com/dart-lang/mockito/issues/579 @protected @visibleForTesting List<void Function()> get listeners => _listeners; final List<Listenable> _listenables = []; final List<VoidCallback> _listeners = []; /// An [Expando] that tracks listener ids when [addAutoDisposeListener] is /// called with a non-null [id] parameter. final _listenerIdExpando = Expando<String>(); /// Track a stream subscription to be automatically cancelled on dispose. void autoDisposeStreamSubscription(StreamSubscription subscription) { _subscriptions.add(subscription); } /// Track a focus node that will be automatically disposed on dispose. void autoDisposeFocusNode(FocusNode? node) { if (node == null) return; _focusNodes.add(node); } /// Add a listener to a Listenable object that is automatically removed when /// cancel is called. void addAutoDisposeListener( Listenable? listenable, [ VoidCallback? listener, String? id, ]) { if (listenable == null || listener == null) return; _listenables.add(listenable); _listeners.add(listener); listenable.addListener(listener); if (id != null) { _listenerIdExpando[listener] = id; } } /// Cancel all stream subscriptions added. /// /// It is fine to call this method and then add additional subscriptions. void cancelStreamSubscriptions() { for (StreamSubscription subscription in _subscriptions) { unawaited(subscription.cancel()); } _subscriptions.clear(); } /// Cancel all listeners added. /// /// It is fine to call this method and then add additional listeners. /// /// If [excludeIds] is non-empty, any listeners that have an associated id /// from [_listenersById] will not be cancelled. void cancelListeners({List<String> excludeIds = const <String>[]}) { assert(_listenables.length == _listeners.length); final skipCancelIndices = <int>[]; for (int i = 0; i < _listenables.length; ++i) { final listener = _listeners[i]; final listenerId = _listenerIdExpando[listener]; if (listenerId != null && excludeIds.contains(listenerId)) { skipCancelIndices.add(i); continue; } _listenables[i].removeListener(listener); } _listenables.removeAllExceptIndices(skipCancelIndices); _listeners.removeAllExceptIndices(skipCancelIndices); } /// Cancels a single listener, if present. void cancelListener(VoidCallback? listener) { if (listener == null) return; assert(_listenables.length == _listeners.length); final foundIndex = _listeners.indexWhere((currentListener) => currentListener == listener); if (foundIndex == -1) return; _listenables[foundIndex].removeListener(_listeners[foundIndex]); _listenables.removeAt(foundIndex); _listeners.removeAt(foundIndex); } /// Cancel all focus nodes added. /// /// It is fine to call this method and then add additional focus nodes. void cancelFocusNodes() { for (FocusNode focusNode in _focusNodes) { focusNode.dispose(); } _focusNodes.clear(); } /// Runs [callback] when [trigger]'s value satisfies the [readyWhen] function. /// /// When calling [callOnceWhenReady] : /// - If [trigger]'s value satisfies [readyWhen], then the [callback] will /// be immediately triggered. /// - Otherwise, the [callback] will be triggered when [trigger]'s value /// changes to equal [readyWhen]. /// /// Any listeners set by [callOnceWhenReady] will auto dispose, or be removed after the callback is run. void callOnceWhenReady<T>({ required VoidCallback callback, required ValueListenable<T> trigger, required bool Function(T triggerValue) readyWhen, }) { if (readyWhen(trigger.value)) { callback(); } else { VoidCallback? triggerListener; triggerListener = () { if (readyWhen(trigger.value)) { callback(); trigger.removeListener(triggerListener!); _listenables.remove(trigger); _listeners.remove(triggerListener); } }; addAutoDisposeListener(trigger, triggerListener); } } } /// Base class for controllers that need to manage their lifecycle. abstract class DisposableController { @mustCallSuper void dispose() {} } /// Mixin to simplifying managing the lifetime of listeners used by a /// [DisposableController]. /// /// This mixin works by delegating to a [DisposerMixin]. It implements all of /// [DisposerMixin]'s interface. /// /// See also: /// * [AutoDisposeMixin], which provides the same functionality for a /// [StatefulWidget]. mixin AutoDisposeControllerMixin on DisposableController implements DisposerMixin { final _delegate = Disposer(); @override @visibleForTesting List<Listenable> get listenables => _delegate.listenables; /// Not using VoidCallback because of /// https://github.com/dart-lang/mockito/issues/579 @override @visibleForTesting List<void Function()> get listeners => _delegate.listeners; @override void dispose() { cancelStreamSubscriptions(); cancelListeners(); cancelFocusNodes(); super.dispose(); } @override void addAutoDisposeListener( Listenable? listenable, [ VoidCallback? listener, String? id, ]) { _delegate.addAutoDisposeListener(listenable, listener, id); } @override void autoDisposeStreamSubscription(StreamSubscription subscription) { _delegate.autoDisposeStreamSubscription(subscription); } @override void autoDisposeFocusNode(FocusNode? node) { _delegate.autoDisposeFocusNode(node); } @override void cancelStreamSubscriptions() { _delegate.cancelStreamSubscriptions(); } @override void cancelListeners({List<String> excludeIds = const <String>[]}) { _delegate.cancelListeners(); } @override void cancelListener(VoidCallback? listener) { _delegate.cancelListener(listener); } @override void cancelFocusNodes() { _delegate.cancelFocusNodes(); } @override void callOnceWhenReady<T>({ required VoidCallback callback, required ValueListenable<T> trigger, required bool Function(T triggerValue) readyWhen, }) { _delegate.callOnceWhenReady( callback: callback, trigger: trigger, readyWhen: readyWhen, ); } } @visibleForTesting class Disposer with DisposerMixin {} extension _AutoDisposeListExtension<T> on List<T> { /// Reduces the list content to include only elements at [indices]. /// /// If any index in [indices] is out of range, an exception will be thrown. void removeAllExceptIndices(List<int> indices) { final tmp = [ for (int index in indices) this[index], ]; clear(); addAll(tmp); } }
devtools/packages/devtools_app_shared/lib/src/utils/auto_dispose.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/lib/src/utils/auto_dispose.dart", "repo_id": "devtools", "token_count": 3236 }
124
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_app_shared/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../test_utils.dart'; void main() { setUp(() { setGlobal(IdeTheme, IdeTheme()); }); // Note: tester by default has a window size of 800x600. group('Split', () { group('builds horizontal layout', () { testWidgets('with 25% space to first child', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, initialFractions: [0.25, 0.75], ); await tester.pumpWidget(wrap(split)); expect(find.byKey(_k1), findsOneWidget); expect(find.byKey(_k2), findsOneWidget); expect(find.byKey(split.dividerKey(0)), findsOneWidget); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(197.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(591.0, 600), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(12, 600), ); }); testWidgets('with 50% space to first child', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, initialFractions: [0.5, 0.5], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(394, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(394, 600), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(12, 600), ); }); testWidgets('with 75% space to first child', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, initialFractions: [0.75, 0.25], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(591.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(197.0, 600), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(12, 600), ); }); testWidgets('with 0% space to first child', (WidgetTester tester) async { final split = buildSplitPane(Axis.horizontal, initialFractions: [0.0, 1.0]); await tester.pumpWidget(wrap(split)); expect(find.byKey(_k1), findsOneWidget); expect(find.byKey(_k2), findsOneWidget); expect(find.byKey(split.dividerKey(0)), findsOneWidget); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(788, 600), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(12, 600), ); }); testWidgets( 'with 100% space to first child', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, initialFractions: [1.0, 0.0], ); await tester.pumpWidget(wrap(split)); expect(find.byKey(_k1), findsOneWidget); expect(find.byKey(_k2), findsOneWidget); expect(find.byKey(split.dividerKey(0)), findsOneWidget); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(788, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(12, 600), ); }, ); testWidgets('with n children', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(155.2, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(310.4, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(310.4, 600), ); }); testWidgets('with custom splitters', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], splitters: [_mediumSplitter, _largeSplitter], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(148, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(296, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(296, 600), ); }); testWidgets( 'with initialFraction rounding errors', (WidgetTester tester) async { const oneThird = 0.333333; final split = buildSplitPane( Axis.horizontal, children: [_w1, _w2, _w3], initialFractions: [oneThird, oneThird, oneThird], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(258.666416, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(258.666416, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(258.666416, 600), ); }, ); }); group('builds vertical layout', () { testWidgets('with 25% space to first child', (WidgetTester tester) async { final split = buildSplitPane(Axis.vertical, initialFractions: [0.25, 0.75]); await tester.pumpWidget(wrap(split)); expect(find.byKey(_k1), findsOneWidget); expect(find.byKey(_k2), findsOneWidget); expect(find.byKey(split.dividerKey(0)), findsOneWidget); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 147), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 441), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(800, 12), ); }); testWidgets('with 50% space to first child', (WidgetTester tester) async { final split = buildSplitPane(Axis.vertical, initialFractions: [0.5, 0.5]); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 294), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 294), ); }); testWidgets('with 75% space to first child', (WidgetTester tester) async { final split = buildSplitPane(Axis.vertical, initialFractions: [0.75, 0.25]); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 441.0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 147.0), ); }); testWidgets('with 0% space to first child', (WidgetTester tester) async { final split = buildSplitPane(Axis.vertical, initialFractions: [0.0, 1.0]); await tester.pumpWidget(wrap(split)); expect(find.byKey(_k1), findsOneWidget); expect(find.byKey(_k2), findsOneWidget); expect(find.byKey(split.dividerKey(0)), findsOneWidget); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 588), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(800, 12), ); }); testWidgets( 'with 100% space to first child', (WidgetTester tester) async { final split = buildSplitPane(Axis.vertical, initialFractions: [1.0, 0.0]); await tester.pumpWidget(wrap(split)); expect(find.byKey(_k1), findsOneWidget); expect(find.byKey(_k2), findsOneWidget); expect(find.byKey(split.dividerKey(0)), findsOneWidget); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 588), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 0), ); expectEqualSizes( tester.element(find.byKey(split.dividerKey(0))).size!, const Size(800, 12), ); }, ); testWidgets('with n children', (WidgetTester tester) async { final split = buildSplitPane( Axis.vertical, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 115.2), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 230.4), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(800, 230.4), ); }); testWidgets('with custom splitters', (WidgetTester tester) async { final split = buildSplitPane( Axis.vertical, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], splitters: [_mediumSplitter, _largeSplitter], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 108), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 216), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(800, 216), ); }); testWidgets( 'with initialFraction rounding errors', (WidgetTester tester) async { const oneThird = 0.333333; final split = buildSplitPane( Axis.vertical, children: [_w1, _w2, _w3], initialFractions: [oneThird, oneThird, oneThird], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 191.99981599999998), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 191.99981599999998), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(800, 191.99981599999998), ); }, ); }); group('drags properly', () { testWidgets('with horizontal layout', (WidgetTester tester) async { final split = buildSplitPane(Axis.horizontal, initialFractions: [0.5, 0.5]); await tester.pumpWidget(wrap(split)); // We start at 0.5 size. expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(394.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(394.0, 600), ); // Drag to 0.75 first child size. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(200, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(591.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(197.0, 600), ); // Drag to 0.25 first child size. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-400, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(197.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(591.0, 600), ); // Drag past the right end of the widget. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(600, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(788, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 600), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(200, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(788, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 600), ); // Drag back past the left end of the widget. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-800, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(788, 600), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-200, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(788, 600), ); }); testWidgets('with vertical layout', (WidgetTester tester) async { final split = buildSplitPane(Axis.vertical, initialFractions: [0.5, 0.5]); await tester.pumpWidget(wrap(split)); // We start at 0.5 size. expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 294.0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 294.0), ); // Drag to 0.75 first child size. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(0, 150), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 441.0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 147.0), ); // Drag to 0.25 first child size. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(0, -300), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 147.0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 441.0), ); // Drag past the right end of the widget. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(0, 450), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 588), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 0), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(0, 200), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 588), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 0), ); // Drag back past the left end of the widget. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(0, -600), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 588), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(0, -200), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(800, 0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(800, 588), ); }); testWidgets('with n children', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], ); await tester.pumpWidget(wrap(split)); // We start at initial size. expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(155.2, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(310.4, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(310.4, 600), ); // Drag first splitter to 0.1 first child size. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-80, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(77.6, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(388.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(310.4, 600), ); // Drag first splitter to the left end of the widget. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-80, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(465.6, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(310.4, 600), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-200, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(465.6, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(310.4, 600), ); // Drag first splitter to second splitter. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(480, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(465.6, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(310.4, 600), ); // Drag second splitter past first splitter. await tester.drag( find.byKey(split.dividerKey(1)), const Offset(-100, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(368.6, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(407.4, 600), ); // Drag second splitter to the right end of the widget. await tester.drag( find.byKey(split.dividerKey(1)), const Offset(420, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(368.6, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(407.4, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(0, 600), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(1)), const Offset(200, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(368.6, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(407.4, 600), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(0, 600), ); }); testWidgets('with minSizes', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, initialFractions: [0.5, 0.5], minSizes: [100.0, 100.0], ); await tester.pumpWidget(wrap(split)); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(394.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(394.0, 600), ); // Drag splitter to the left end of the widget. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-300, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(100, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(688.0, 600), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(-200, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(100, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(688.0, 600), ); // Drag splitter to the right end of the widget. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(597.5, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(688.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(100, 600), ); // Make sure we can't overdrag. await tester.drag( find.byKey(split.dividerKey(0)), const Offset(200, 0), ); await tester.pumpAndSettle(); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(688.0, 600), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(100, 600), ); }); }); group('resizes contents', () { testWidgets('in a horizontal layout', (WidgetTester tester) async { final split = buildSplitPane(Axis.horizontal, initialFractions: [0.0, 1.0]); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 300.0, height: 300.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(0, 300), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(288, 300), ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 200.0, height: 200.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(0, 200), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(188, 200), ); }); testWidgets( 'in a horizontal layout with n children', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 400.0, height: 400.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(75.2, 400), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(150.4, 400), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(150.4, 400), ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 200.0, height: 200.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(35.2, 200), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(70.4, 200), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(70.4, 200), ); }, ); testWidgets( 'with violated minsize constraints', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, children: [_w1, _w2, _w3], initialFractions: [0.1, 0.7, 0.2], minSizes: [100.0, 0, 100.0], ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 400.0, height: 400.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(100, 400), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(176.0, 400), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(100, 400), ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 230.0, height: 200.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(100.0, 200), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(6.0, 200), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(100.0, 200), ); // It would be nice if we restored the size of w2 in this case but the // logic is simpler if we don't as this way the layout calculation can // avoid tracking state about what the previous fractions were before // clipping which would add more complexity and shouldn't really matter. await tester.pumpWidget( wrap( Center( child: SizedBox(width: 400.0, height: 400.0, child: split), ), ), ); // TODO(dantup): These now fail, as the results are 100/176/100. It's not // clear why these expectations are different to the above when it's // in the same size box? expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(182.5242718446602, 400), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(10.951456310679607, 400), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(182.5242718446602, 400), ); }, ); testWidgets( 'with impossible minsize constraints', (WidgetTester tester) async { final split = buildSplitPane( Axis.horizontal, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], minSizes: [200.0, 0, 400.0], ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 400.0, height: 400.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(125.33333333333333, 400), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 400), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(250.66666666666666, 400), ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 200.0, height: 200.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(58.666666666666664, 200), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 200), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(117.33333333333333, 200), ); // Min size constraints still violated but not violated by as much. await tester.pumpWidget( wrap( Center( child: SizedBox(width: 400.0, height: 400.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(125.33333333333333, 400), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 400), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(250.66666666666666, 400), ); // Min size constraints are now satisfied. await tester.pumpWidget( wrap( Center( child: SizedBox(width: 800.0, height: 400.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(258.66666666666666, 400), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(0, 400), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(517.3333333333333, 400), ); }, ); testWidgets('in a vertical layout', (WidgetTester tester) async { final split = buildSplitPane(Axis.vertical, initialFractions: [0.0, 1.0]); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 300.0, height: 300.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(300, 0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(300, 288.0), ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 200.0, height: 200.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(200, 0), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(200, 188), ); }); testWidgets( 'in a vertical layout with n children', (WidgetTester tester) async { final split = buildSplitPane( Axis.vertical, children: [_w1, _w2, _w3], initialFractions: [0.2, 0.4, 0.4], ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 400.0, height: 400.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(400, 75.2), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(400, 150.4), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(400, 150.4), ); await tester.pumpWidget( wrap( Center( child: SizedBox(width: 200.0, height: 200.0, child: split), ), ), ); expectEqualSizes( tester.element(find.byKey(_k1)).size!, const Size(200, 35.2), ); expectEqualSizes( tester.element(find.byKey(_k2)).size!, const Size(200, 70.4), ); expectEqualSizes( tester.element(find.byKey(_k3)).size!, const Size(200, 70.4), ); }, ); }); group('axisFor', () { testWidgetsWithWindowSize( 'return Axis.horizontal', const Size(800, 800), (WidgetTester tester) async { await tester.pumpWidget( wrap( Builder( builder: (context) { expectLater(SplitPane.axisFor(context, 1.0), Axis.horizontal); return Container(); }, ), ), ); }, ); testWidgetsWithWindowSize( 'return Axis.vertical', const Size(500, 800), (WidgetTester tester) async { await tester.pumpWidget( wrap( Builder( builder: (context) { expectLater(SplitPane.axisFor(context, 1.0), Axis.vertical); return Container(); }, ), ), ); }, ); }); }); } const _k1 = Key('child 1'); const _k2 = Key('child 2'); const _k3 = Key('child 3'); const _w1 = Text('content1', key: _k1); const _w2 = Text('content2', key: _k2); const _w3 = Text('content3', key: _k3); const _mediumSplitter = PreferredSize( preferredSize: Size(20, 20), child: SizedBox(height: 20, width: 20), ); const _largeSplitter = PreferredSize( preferredSize: Size(40, 40), child: SizedBox(height: 40, width: 40), ); SplitPane buildSplitPane( Axis axis, { required List<double> initialFractions, List<Widget>? children, List<double>? minSizes, List<PreferredSizeWidget>? splitters, }) { children ??= const [_w1, _w2]; return SplitPane( axis: axis, initialFractions: initialFractions, minSizes: minSizes, splitters: splitters, children: children, ); } void expectEqualSizes(Size a, Size b) { expect( (a.width - b.width).abs() < defaultEpsilon, isTrue, reason: 'Widths unequal:\nExpected ${b.width}\nActual: ${a.width}', ); expect( (a.height - b.height).abs() < defaultEpsilon, isTrue, reason: 'Heights unequal:\nExpected ${b.height}\nActual: ${a.height}', ); }
devtools/packages/devtools_app_shared/test/ui/split_pane_test.dart/0
{ "file_path": "devtools/packages/devtools_app_shared/test/ui/split_pane_test.dart", "repo_id": "devtools", "token_count": 19941 }
125
// 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:args/command_runner.dart'; import 'package:io/io.dart'; import '_build_and_copy.dart'; import '_validate.dart'; void main(List<String> arguments) async { final command = BuildExtensionCommand(); final runner = CommandRunner('devtools_extensions', command.description) ..addCommand(BuildExtensionCommand()) ..addCommand(ValidateExtensionCommand()); await runner.run(arguments).whenComplete(sharedStdIn.terminate); }
devtools/packages/devtools_extensions/bin/devtools_extensions.dart/0
{ "file_path": "devtools/packages/devtools_extensions/bin/devtools_extensions.dart", "repo_id": "devtools", "token_count": 184 }
126
// 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:app_that_uses_foo/main.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:foo/foo.dart'; // This test can be run to verify that the `package:foo` DevTools extension // loads properly when debugging a test target with DevTools. // // To test this, run the following command and copy the VM service URI to // connect to DevTools: // // flutter run test/app_that_uses_foo_test.dart --start-paused -d flutter-tester void main() { testWidgets('Builds $MyAppThatUsesFoo', (tester) async { await tester.pumpWidget(const MyAppThatUsesFoo()); await tester.pumpAndSettle(); expect(find.byType(MyAppThatUsesFoo), findsOneWidget); expect(find.byType(FooWidget), findsOneWidget); }); }
devtools/packages/devtools_extensions/example/app_that_uses_foo/test/app_that_uses_foo_test.dart/0
{ "file_path": "devtools/packages/devtools_extensions/example/app_that_uses_foo/test/app_that_uses_foo_test.dart", "repo_id": "devtools", "token_count": 295 }
127
// Copyright 2023 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:devtools_app_shared/ui.dart'; import 'package:devtools_extensions/api.dart'; import 'package:devtools_extensions/devtools_extensions.dart'; import 'package:flutter/material.dart'; /// This widget shows an example of how you can register a custom event handler /// for any type of [DevToolsExtensionEventType]. /// /// When the DevTools extension receives an event from DevTools, the default /// handler for the [DevToolsExtensionEventType] will be called (this is /// managed automatically by package:devtools_extensions), and any custom /// event handlers will be called after the default handler. class ListeningForDevToolsEventExample extends StatefulWidget { const ListeningForDevToolsEventExample({super.key}); @override State<ListeningForDevToolsEventExample> createState() => _ListeningForDevToolsEventExampleState(); } class _ListeningForDevToolsEventExampleState extends State<ListeningForDevToolsEventExample> { String? message; @override void initState() { super.initState(); // Example of the devtools extension registering a custom handler for an // event coming from DevTools. extensionManager.registerEventHandler( DevToolsExtensionEventType.unknown, // This callback will be called when the DevTools extension receives an // event of type [DevToolsExtensionEventType.unknown] from DevTools. (event) { setState(() { message = event.data?.toString() ?? 'unknown event'; }); }, ); } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '3. Example of listening for a DevTools event', style: Theme.of(context).textTheme.titleMedium, ), const PaddedDivider.thin(), Text('Received an unknown event from DevTools: $message'), ], ); } }
devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo_devtools_extension/lib/src/devtools_event_example.dart/0
{ "file_path": "devtools/packages/devtools_extensions/example/packages_with_extensions/foo/packages/foo_devtools_extension/lib/src/devtools_event_example.dart", "repo_id": "devtools", "token_count": 687 }
128
// 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_extensions/api.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('$DevToolsExtensionEvent', () { test('parse', () { var event = DevToolsExtensionEvent.parse({ 'type': 'ping', 'data': {'foo': 'bar'}, }); expect(event.type, DevToolsExtensionEventType.ping); expect(event.data, {'foo': 'bar'}); event = DevToolsExtensionEvent.parse({ 'type': 'pong', 'data': {'baz': 'bob'}, }); expect(event.type, DevToolsExtensionEventType.pong); expect(event.data, {'baz': 'bob'}); event = DevToolsExtensionEvent.parse({ 'type': 'idk', }); expect(event.type, DevToolsExtensionEventType.unknown); expect(event.data, isNull); }); test('tryParse', () { var event = DevToolsExtensionEvent.tryParse({ 'type': 'ping', 'data': {'foo': 'bar'}, }); expect(event, isNotNull); event = DevToolsExtensionEvent.tryParse('bad input'); expect(event, isNull); event = DevToolsExtensionEvent.tryParse({'more', 'bad', 'input'}); expect(event, isNull); event = DevToolsExtensionEvent.tryParse({1: 'bad', 2: 'input'}); expect(event, isNull); }); test('toJson', () { var event = DevToolsExtensionEvent(DevToolsExtensionEventType.ping); expect(event.toJson(), {'type': 'ping'}); event = DevToolsExtensionEvent( DevToolsExtensionEventType.pong, data: {'foo': 'bar'}, ); expect(event.toJson(), { 'type': 'pong', 'data': {'foo': 'bar'}, }); event = DevToolsExtensionEvent( DevToolsExtensionEventType.unknown, data: {'foo': 'bar'}, ); expect(event.toJson(), { 'type': 'unknown', 'data': {'foo': 'bar'}, }); }); }); group('$DevToolsExtensionEventType', () { test('parses for expected values', () { expect( DevToolsExtensionEventType.from('ping'), DevToolsExtensionEventType.ping, ); expect( DevToolsExtensionEventType.from('pong'), DevToolsExtensionEventType.pong, ); expect( DevToolsExtensionEventType.from('forceReload'), DevToolsExtensionEventType.forceReload, ); expect( DevToolsExtensionEventType.from('showNotification'), DevToolsExtensionEventType.showNotification, ); expect( DevToolsExtensionEventType.from('showBannerMessage'), DevToolsExtensionEventType.showBannerMessage, ); expect( DevToolsExtensionEventType.from('vmServiceConnection'), DevToolsExtensionEventType.vmServiceConnection, ); expect( DevToolsExtensionEventType.from('themeUpdate'), DevToolsExtensionEventType.themeUpdate, ); }); test('parses for unexpected values', () { expect( DevToolsExtensionEventType.from('PING'), DevToolsExtensionEventType.unknown, ); expect( DevToolsExtensionEventType.from('pongg'), DevToolsExtensionEventType.unknown, ); }); test('supportedForDirection', () { verifyEventDirection( DevToolsExtensionEventType.ping, (bidirectional: false, toDevTools: false, toExtension: true), ); verifyEventDirection( DevToolsExtensionEventType.pong, (bidirectional: false, toDevTools: true, toExtension: false), ); verifyEventDirection( DevToolsExtensionEventType.forceReload, (bidirectional: false, toDevTools: false, toExtension: true), ); verifyEventDirection( DevToolsExtensionEventType.vmServiceConnection, (bidirectional: true, toDevTools: true, toExtension: true), ); verifyEventDirection( DevToolsExtensionEventType.themeUpdate, (bidirectional: false, toDevTools: false, toExtension: true), ); verifyEventDirection( DevToolsExtensionEventType.showNotification, (bidirectional: false, toDevTools: true, toExtension: false), ); verifyEventDirection( DevToolsExtensionEventType.showBannerMessage, (bidirectional: false, toDevTools: true, toExtension: false), ); verifyEventDirection( DevToolsExtensionEventType.unknown, (bidirectional: true, toDevTools: true, toExtension: true), ); }); }); group('$ShowNotificationExtensionEvent', () { test('constructs for expected values', () { final event = DevToolsExtensionEvent.parse({ 'type': 'showNotification', 'data': { 'message': 'foo message', }, }); final showNotificationEvent = ShowNotificationExtensionEvent.from(event); expect(showNotificationEvent.message, 'foo message'); }); test('throws for unexpected values', () { final event1 = DevToolsExtensionEvent.parse({ 'type': 'showNotification', 'data': { // Missing required fields. }, }); expect( () { ShowNotificationExtensionEvent.from(event1); }, throwsFormatException, ); final event2 = DevToolsExtensionEvent.parse({ 'type': 'showNotification', 'data': { // Bad key. 'msg': 'foo message', }, }); expect( () { ShowNotificationExtensionEvent.from(event2); }, throwsFormatException, ); final event3 = DevToolsExtensionEvent.parse({ 'type': 'showNotification', 'data': { // Bad value. 'message': false, }, }); expect( () { ShowNotificationExtensionEvent.from(event3); }, throwsFormatException, ); final event4 = DevToolsExtensionEvent.parse({ // Wrong type. 'type': 'showBannerMessage', 'data': { 'message': 'foo message', }, }); expect( () { ShowNotificationExtensionEvent.from(event4); }, throwsAssertionError, ); }); }); group('$ShowBannerMessageExtensionEvent', () { test('constructs for expected values', () { var event = DevToolsExtensionEvent.parse({ 'type': 'showBannerMessage', 'data': { 'id': 'fooMessageId', 'message': 'foo message', 'bannerMessageType': 'warning', 'extensionName': 'foo', }, }); var showBannerMessageEvent = ShowBannerMessageExtensionEvent.from(event); expect(showBannerMessageEvent.messageId, 'fooMessageId'); expect(showBannerMessageEvent.message, 'foo message'); expect(showBannerMessageEvent.bannerMessageType, 'warning'); expect(showBannerMessageEvent.extensionName, 'foo'); expect(showBannerMessageEvent.ignoreIfAlreadyDismissed, true); event = DevToolsExtensionEvent.parse({ 'type': 'showBannerMessage', 'data': { 'id': 'blah', 'message': 'blah message', 'bannerMessageType': 'error', 'extensionName': 'blah', 'ignoreIfAlreadyDismissed': false, }, }); showBannerMessageEvent = ShowBannerMessageExtensionEvent.from(event); expect(showBannerMessageEvent.messageId, 'blah'); expect(showBannerMessageEvent.message, 'blah message'); expect(showBannerMessageEvent.bannerMessageType, 'error'); expect(showBannerMessageEvent.extensionName, 'blah'); expect(showBannerMessageEvent.ignoreIfAlreadyDismissed, false); }); test('throws for unexpected values', () { final event1 = DevToolsExtensionEvent.parse({ 'type': 'showBannerMessage', 'data': { // Missing required fields. 'extensionName': 'foo', }, }); expect( () { ShowBannerMessageExtensionEvent.from(event1); }, throwsFormatException, ); final event2 = DevToolsExtensionEvent.parse({ 'type': 'showBannerMessage', 'data': { // Bad keys. 'bad_key': 'fooMessageId', 'messages': 'foo message', 'bannerMessageTypeee': 'warning', 'extension_name': 'foo', }, }); expect( () { ShowBannerMessageExtensionEvent.from(event2); }, throwsFormatException, ); final event3 = DevToolsExtensionEvent.parse({ 'type': 'showBannerMessage', 'data': { // Bad values. 'id': 1, 'message': 'foo message', 'bannerMessageType': 2.0, 'extensionName': 'foo', }, }); expect( () { ShowBannerMessageExtensionEvent.from(event3); }, throwsFormatException, ); final event4 = DevToolsExtensionEvent.parse({ // Wrong type. 'type': 'showNotification', 'data': { 'id': 'fooMessageId', 'message': 'foo message', 'bannerMessageType': 'warning', 'extensionName': 'foo', }, }); expect( () { ShowBannerMessageExtensionEvent.from(event4); }, throwsAssertionError, ); }); }); } void verifyEventDirection( DevToolsExtensionEventType type, ({bool bidirectional, bool toDevTools, bool toExtension}) expected, ) { expect( type.supportedForDirection(ExtensionEventDirection.bidirectional), expected.bidirectional, ); expect( type.supportedForDirection(ExtensionEventDirection.toDevTools), expected.toDevTools, ); expect( type.supportedForDirection(ExtensionEventDirection.toExtension), expected.toExtension, ); }
devtools/packages/devtools_extensions/test/api_test.dart/0
{ "file_path": "devtools/packages/devtools_extensions/test/api_test.dart", "repo_id": "devtools", "token_count": 4344 }
129
// 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. // This file handles json object. // ignore_for_file: avoid-dynamic import 'dart:convert'; /// The app link related settings of a Android build of a Flutter project. class AppLinkSettings { const AppLinkSettings._( this.applicationId, this.deeplinkingFlagEnabled, this.deeplinks, ); factory AppLinkSettings.fromJson(String json) { final jsonObject = jsonDecode(json) as Map; final { _kApplicationIdKey: String applicationId, _kDeeplinksKey: List<Object?> deepLinks, _kDeeplinkingFlagEnabledKey: bool deeplinkingFlagEnabled, } = jsonObject; return AppLinkSettings._( applicationId, deeplinkingFlagEnabled, deepLinks .cast<Map<String, dynamic>>() .map<AndroidDeeplink>(AndroidDeeplink._fromJsonObject) .toList(), ); } /// Used when the the server can't retrieve app link settings. static const empty = AppLinkSettings._('', false, <AndroidDeeplink>[]); static const _kApplicationIdKey = 'applicationId'; static const _kDeeplinkingFlagEnabledKey = 'deeplinkingFlagEnabled'; static const _kDeeplinksKey = 'deeplinks'; /// The application id of the Android build of this Flutter project. final String applicationId; /// The flag set by user in android manifest file to enable deep linking. final bool deeplinkingFlagEnabled; /// The supported deep link of the Android build of this Flutter project. /// /// This list also include deeplinks with custom scheme. final List<AndroidDeeplink> deeplinks; } /// A deep link in a Android build of a Flutter project. /// /// The deeplink is defined in intent filters of AndroidManifest.xml in the /// Android sub-project. class AndroidDeeplink { AndroidDeeplink._(this.scheme, this.host, this.path, this.intentFilterChecks); factory AndroidDeeplink._fromJsonObject(Map<String, dynamic> json) { return AndroidDeeplink._( json[_kSchemeKey] as String, json[_kHostKey] as String, json[_kPathKey] as String, IntentFilterChecks._fromJsonObject( json[_kIntentFilterChecksKey] as Map<String, dynamic>, ), ); } static const _kSchemeKey = 'scheme'; static const _kHostKey = 'host'; static const _kPathKey = 'path'; static const _kIntentFilterChecksKey = 'intentFilterCheck'; /// The scheme section of the deeplink. final String scheme; /// The host section of the deeplink. final String host; /// The path pattern section of the deeplink. final String path; /// The intent filter checks section of the deeplink. final IntentFilterChecks intentFilterChecks; } /// Intent filter checks for a deep link. /// /// The intent filters are from AndroidManifest.xml in the /// Android sub-project. class IntentFilterChecks { IntentFilterChecks._( this.hasAutoVerify, this.hasActionView, this.hasDefaultCategory, this.hasBrowsableCategory, ); factory IntentFilterChecks._fromJsonObject(Map<String, dynamic> json) { return IntentFilterChecks._( json[_kHasAutoVerifyKey] as bool, json[_kHasActionViewKey] as bool, json[_kHasDefaultCategoryKey] as bool, json[_kHasBrowsableCategoryKey] as bool, ); } static const _kHasAutoVerifyKey = 'hasAutoVerify'; static const _kHasActionViewKey = 'hasActionView'; static const _kHasDefaultCategoryKey = 'hasDefaultCategory'; static const _kHasBrowsableCategoryKey = 'hasBrowsableCategory'; final bool hasAutoVerify; final bool hasActionView; final bool hasDefaultCategory; final bool hasBrowsableCategory; }
devtools/packages/devtools_shared/lib/src/deeplink/app_link_settings.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/deeplink/app_link_settings.dart", "repo_id": "devtools", "token_count": 1234 }
130
// Copyright 2024 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_classes_with_only_static_members part of '../server_api.dart'; abstract class _DeeplinkApiHandler { static Future<shelf.Response> handleAndroidBuildVariants( ServerApi api, Map<String, String> queryParams, DeeplinkManager deeplinkManager, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( [DeeplinkApi.deeplinkRootPathPropertyName], queryParams: queryParams, api: api, requestName: DeeplinkApi.androidBuildVariants, ); if (missingRequiredParams != null) return missingRequiredParams; final rootPath = queryParams[DeeplinkApi.deeplinkRootPathPropertyName]!; final result = await deeplinkManager.getAndroidBuildVariants(rootPath: rootPath); return _resultOutputOrError(api, result); } static Future<shelf.Response> handleAndroidAppLinkSettings( ServerApi api, Map<String, String> queryParams, DeeplinkManager deeplinkManager, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( [ DeeplinkApi.deeplinkRootPathPropertyName, DeeplinkApi.androidBuildVariantPropertyName, ], queryParams: queryParams, api: api, requestName: DeeplinkApi.androidBuildVariants, ); if (missingRequiredParams != null) return missingRequiredParams; final rootPath = queryParams[DeeplinkApi.deeplinkRootPathPropertyName]!; final buildVariant = queryParams[DeeplinkApi.androidBuildVariantPropertyName]!; final result = await deeplinkManager.getAndroidAppLinkSettings( rootPath: rootPath, buildVariant: buildVariant, ); return _resultOutputOrError(api, result); } static Future<shelf.Response> handleIosBuildOptions( ServerApi api, Map<String, String> queryParams, DeeplinkManager deeplinkManager, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( [DeeplinkApi.deeplinkRootPathPropertyName], queryParams: queryParams, api: api, requestName: DeeplinkApi.iosBuildOptions, ); if (missingRequiredParams != null) return missingRequiredParams; final rootPath = queryParams[DeeplinkApi.deeplinkRootPathPropertyName]!; final result = await deeplinkManager.getIosBuildOptions(rootPath: rootPath); return _resultOutputOrError(api, result); } static Future<shelf.Response> handleIosUniversalLinkSettings( ServerApi api, Map<String, String> queryParams, DeeplinkManager deeplinkManager, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( [ DeeplinkApi.deeplinkRootPathPropertyName, DeeplinkApi.xcodeConfigurationPropertyName, DeeplinkApi.xcodeTargetPropertyName, ], queryParams: queryParams, api: api, requestName: DeeplinkApi.iosUniversalLinkSettings, ); if (missingRequiredParams != null) return missingRequiredParams; final result = await deeplinkManager.getIosUniversalLinkSettings( rootPath: queryParams[DeeplinkApi.deeplinkRootPathPropertyName]!, configuration: queryParams[DeeplinkApi.xcodeConfigurationPropertyName]!, target: queryParams[DeeplinkApi.xcodeTargetPropertyName]!, ); return _resultOutputOrError(api, result); } static shelf.Response _resultOutputOrError( ServerApi api, Map<String, Object?> result, ) { final error = result[DeeplinkManager.kErrorField] as String?; if (error != null) { return api.serverError(error); } return api.success( result[DeeplinkManager.kOutputJsonField]! as String, ); } }
devtools/packages/devtools_shared/lib/src/server/handlers/_deeplink.dart/0
{ "file_path": "devtools/packages/devtools_shared/lib/src/server/handlers/_deeplink.dart", "repo_id": "devtools", "token_count": 1397 }
131
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:devtools_app/devtools_app.dart'; import 'package:flutter/foundation.dart'; import 'package:vm_service/vm_service.dart'; class TestProgramExplorerController extends ProgramExplorerController { TestProgramExplorerController({ required this.initializer, }); @override ValueListenable<bool> get initialized => _initialized; final _initialized = ValueNotifier<bool>(false); final FutureOr<void> Function(TestProgramExplorerController) initializer; @override Future<void> initialize() async { if (_initialized.value) { return; } await initializer(this); _initialized.value = true; } @override Future<void> populateNode(VMServiceObjectNode node) async { // Since the data is hard coded and fully populated, we can completely // bypass all the service related code. However, we need to still build // the child nodes, which is done by calling // `VMServiceObjectNode.updateObject`. We need to "force" the update since // there are optimizations to avoid re-building the nodes if the root node // already contains a full VM service object (i.e., not a reference type). node.updateObject(node.object as Obj, forceUpdate: true); } }
devtools/packages/devtools_test/lib/src/mocks/fake_program_explorer_controller.dart/0
{ "file_path": "devtools/packages/devtools_test/lib/src/mocks/fake_program_explorer_controller.dart", "repo_id": "devtools", "token_count": 415 }
132
# This file exists to serve analysis_options.yaml name: devtools_root publish_to: none environment: sdk: '>=3.0.0 <4.0.0' dev_dependencies: flutter_lints: ^2.0.3
devtools/packages/pubspec.yaml/0
{ "file_path": "devtools/packages/pubspec.yaml", "repo_id": "devtools", "token_count": 72 }
133
## What is this? This directory stores pre-built assets of the [Perfetto UI](https://github.com/google/perfetto/tree/master/ui) web app, along with some additional files authored by the DevTools team, to support custom styling for the Perfetto UI. We embed this web app in an iFrame on the DevTools Performance page. This allows us to leverage the first-in-class trace viewer for viewing Dart and Flutter timeline traces. ## Why are we loading pre-compiled sources instead of the live Perfetto UI url? This build output is included with the DevTools app bundle so that we can load the Perfetto UI web app from source at runtime. We do this for the following reasons: * this allows us to include our custom theming .css and .js files in the build. These theming files enable a more dense interface that better fits our tooling, and they also enable a dark theme that we can switch to and from. * this allows us to load the Perfetto UI web app directly from assets, meaning we have zero latency and can support users with a slow or non-existent internet connection. ## How often is this build output updated? This build output should be updated as needed, for example, if the Perfetto team releases some new features or fixes we want to take advantage of. Outside of ad hoc updates, this output should be refreshed at least once per quarter. To update the Perfetto build output, run the `update_perfetto.sh` script located in `devtools/tools/`. Be sure that all DevTools-authored files under `assets/perfetto` are not deleted by mistake. ## How to update this build for local changes in the Perfetto codebase? If you are making changes to a local Perfetto branch and you want to test those changes in the DevTools embedding, follow these steps: 1. Make your changes in your local Perfetto branch. See Perfetto [build instructions](https://perfetto.dev/docs/contributing/build-instructions#standalone-builds) for instructions on how to get the code and build the app. 2. Run `ui/build` from your `perfetto` directory. You may need to run `tools/install-build-deps --ui` before you are able to build. See Perfetto's [UI development instructions](https://perfetto.dev/docs/contributing/build-instructions#ui-development) for more details. 3. Update the DevTools `perfetto_compiled` build to your local build: `update_perfetto.sh -b /Users/me/path/to/perfetto/out/ui/ui/dist` Then run DevTools on web, and you should see changes from your local Perfetto branch applied to the embedded Perfetto timeline view in DevTools.
devtools/third_party/packages/perfetto_ui_compiled/README.md/0
{ "file_path": "devtools/third_party/packages/perfetto_ui_compiled/README.md", "repo_id": "devtools", "token_count": 670 }
134
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:devtools_tool/devtools_command_runner.dart'; import 'package:io/io.dart'; void main(List<String> args) async { final runner = DevToolsCommandRunner(); try { final dynamic result = await runner.run(args).whenComplete(sharedStdIn.terminate); exit(result is int ? result : 0); } catch (e) { if (e is UsageException) { stderr.writeln('$e'); // Return an exit code representing a usage error. exit(64); } else { stderr.writeln('$e'); // Return a general failure exit code. exit(1); } } }
devtools/tool/bin/devtools_tool.dart/0
{ "file_path": "devtools/tool/bin/devtools_tool.dart", "repo_id": "devtools", "token_count": 291 }
135
// 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:devtools_tool/commands/shared.dart'; import 'package:devtools_tool/model.dart'; import 'package:io/io.dart'; import 'package:path/path.dart' as path; import '../utils.dart'; /// This command builds the DevTools Flutter web app. /// /// By default, this command builds DevTools in release mode, but this can be /// overridden by passing 'debug' or 'profile' as the /// [BuildCommandArgs.buildMode] argument. /// /// If the [BuildCommandArgs.useFlutterFromPath] argument is present, the /// Flutter SDK will not be updated to the latest Flutter candidate before /// building DevTools. Use this flag to save the cost of updating the Flutter /// SDK when you already have the proper SDK checked out. This is helpful when /// developing with the DevTools server. /// /// If the [BuildCommandArgs.updatePerfetto] argument is present, the /// precompiled bits for Perfetto will be updated from the /// `devtools_tool update-perfetto` command as part of the DevTools build /// process. /// /// If [BuildCommandArgs.pubGet] argument is negated (e.g. --no-pub-get), then /// `devtools_tool pub-get --only-main` command will not be run before building /// the DevTools web app. Use this flag to save the cost of updating pub /// packages if your pub cahce does not need to be updated. This is helpful when /// developing with the DevTools server. class BuildCommand extends Command { BuildCommand() { argParser ..addUpdateFlutterFlag() ..addUpdatePerfettoFlag() ..addPubGetFlag() ..addBulidModeOption(); } @override String get name => 'build'; @override String get description => 'Prepares a release build of DevTools.'; @override Future run() async { final repo = DevToolsRepo.getInstance(); final processManager = ProcessManager(); final updateFlutter = argResults![BuildCommandArgs.updateFlutter.flagName] as bool; final updatePerfetto = argResults![BuildCommandArgs.updatePerfetto.flagName] as bool; final runPubGet = argResults![BuildCommandArgs.pubGet.flagName] as bool; final buildMode = argResults![BuildCommandArgs.buildMode.flagName] as String; final webBuildDir = Directory(path.join(repo.devtoolsAppDirectoryPath, 'build', 'web')); if (updateFlutter) { logStatus('updating tool/flutter-sdk to the latest flutter candidate'); await processManager.runProcess(CliCommand.tool(['update-flutter-sdk'])); } if (updatePerfetto) { logStatus('updating the bundled Perfetto assets'); await processManager.runProcess(CliCommand.tool(['update-perfetto'])); } logStatus('cleaning project'); if (webBuildDir.existsSync()) { webBuildDir.deleteSync(recursive: true); } await processManager.runProcess( CliCommand.flutter(['clean']), workingDirectory: repo.devtoolsAppDirectoryPath, ); logStatus('building DevTools in release mode'); await processManager.runAll( commands: [ if (runPubGet) CliCommand.tool(['pub-get', '--only-main']), CliCommand.flutter( [ 'build', 'web', '--web-renderer', 'canvaskit', '--pwa-strategy=offline-first', // Enable default optimizations: https://dart.dev/tools/dart-compile#js '--dart2js-optimization=O1', if (buildMode != 'debug') '--$buildMode', '--no-tree-shake-icons', ], ), ], workingDirectory: repo.devtoolsAppDirectoryPath, ); // TODO(kenz): investigate if we need to perform a windows equivalent of // `chmod` or if we even need to perform `chmod` for linux / mac anymore. if (!Platform.isWindows) { final canvaskitDir = Directory(path.join(webBuildDir.path, 'canvaskit')); for (final file in canvaskitDir.listSync()) { if (RegExp(r'canvaskit\..*').hasMatch(file.path)) { await processManager .runProcess(CliCommand('chmod', ['0755', file.path])); } } } } }
devtools/tool/lib/commands/build.dart/0
{ "file_path": "devtools/tool/lib/commands/build.dart", "repo_id": "devtools", "token_count": 1543 }
136
// 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:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:devtools_tool/commands/build.dart'; import 'package:devtools_tool/commands/fix_goldens.dart'; import 'package:devtools_tool/commands/generate_code.dart'; import 'package:devtools_tool/commands/serve.dart'; import 'package:devtools_tool/commands/sync.dart'; import 'package:devtools_tool/commands/tag_version.dart'; import 'package:devtools_tool/commands/update_flutter_sdk.dart'; import 'package:devtools_tool/commands/update_perfetto.dart'; import 'package:devtools_tool/model.dart'; import 'commands/analyze.dart'; import 'commands/list.dart'; import 'commands/pub_get.dart'; import 'commands/release_helper.dart'; import 'commands/repo_check.dart'; import 'commands/rollback.dart'; import 'commands/update_dart_sdk_deps.dart'; import 'commands/update_version.dart'; const _flutterFromPathFlag = 'flutter-from-path'; class DevToolsCommandRunner extends CommandRunner { DevToolsCommandRunner() : super('devtools_tool', 'A repo management tool for DevTools.') { addCommand(AnalyzeCommand()); addCommand(BuildCommand()); addCommand(FixGoldensCommand()); addCommand(GenerateCodeCommand()); addCommand(ListCommand()); addCommand(PubGetCommand()); addCommand(ReleaseHelperCommand()); addCommand(RepoCheckCommand()); addCommand(RollbackCommand()); addCommand(ServeCommand()); addCommand(SyncCommand()); addCommand(TagVersionCommand()); addCommand(UpdateDartSdkDepsCommand()); addCommand(UpdateDevToolsVersionCommand()); addCommand(UpdateFlutterSdkCommand()); addCommand(UpdatePerfettoCommand()); argParser.addFlag( _flutterFromPathFlag, abbr: 'p', negatable: false, help: 'Use the Flutter SDK on PATH for any `flutter`, `dart` and ' '`devtools_tool` commands spawned by this process, instead of the ' 'Flutter SDK from tool/flutter-sdk which is used by default.', ); } @override Future<void> runCommand(ArgResults topLevelResults) { if (topLevelResults[_flutterFromPathFlag]) { FlutterSdk.useFromPathEnvironmentVariable(); } else { FlutterSdk.useFromCurrentVm(); } print('Using Flutter SDK from ${FlutterSdk.current.sdkPath}'); return super.runCommand(topLevelResults); } }
devtools/tool/lib/devtools_command_runner.dart/0
{ "file_path": "devtools/tool/lib/devtools_command_runner.dart", "repo_id": "devtools", "token_count": 870 }
137
# The following files define an Application Binary Interface (ABI) that must maintain # both forward and backward compatibility. Changes should be heavily # scrutinized as mistakes are irreversible. /shell/platform/embedder/embedder.h @cbracken @chinmaygarde /shell/platform/embedder/tests/embedder_frozen.h @cbracken @chinmaygarde @loic-sharma
engine/CODEOWNERS/0
{ "file_path": "engine/CODEOWNERS", "repo_id": "engine", "token_count": 95 }
138
#!/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. # Installs the dependencies necessary to build the Linux Flutter shell, beyond # those installed by install-build-deps.sh. set -e sudo apt -y install libfreetype6-dev \ libgl-dev \ libx11-dev \ libxcursor-dev \ libxinerama-dev \ libxrandr-dev \ libxxf86vm-dev
engine/build/install-build-deps-linux-desktop.sh/0
{ "file_path": "engine/build/install-build-deps-linux-desktop.sh", "repo_id": "engine", "token_count": 275 }
139
# Copyright 2014 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("//build/config/linux/pkg_config.gni") if (is_linux) { # This is a dependency on NSS with no libssl. On Linux we use a built-in SSL # library but the system NSS libraries. Non-Linux platforms using NSS use the # hermetic one in //third_party/nss. # # Generally you should depend on //crypto:platform instead of using this # config since that will properly pick up NSS or OpenSSL depending on # platform and build config. pkg_config("system_nss_no_ssl_config") { packages = [ "nss" ] extra_args = [ "-v", "-lssl3", ] } } else { include_nss_root_certs = is_ios include_nss_libpkix = is_ios config("nspr_config") { defines = [ "NO_NSPR_10_SUPPORT" ] include_dirs = [ "nspr/pr/include", "nspr/lib/ds", "nspr/lib/libc/include", ] if (component_mode != "shared_library") { defines += [ "NSPR_STATIC" ] } } component("nspr") { output_name = "crnspr" sources = [ "nspr/lib/ds/plarena.c", "nspr/lib/ds/plarena.h", "nspr/lib/ds/plarenas.h", "nspr/lib/ds/plhash.c", "nspr/lib/ds/plhash.h", "nspr/lib/libc/include/plbase64.h", "nspr/lib/libc/include/plerror.h", "nspr/lib/libc/include/plgetopt.h", "nspr/lib/libc/include/plstr.h", "nspr/lib/libc/src/base64.c", "nspr/lib/libc/src/plerror.c", "nspr/lib/libc/src/plgetopt.c", "nspr/lib/libc/src/strcase.c", "nspr/lib/libc/src/strcat.c", "nspr/lib/libc/src/strchr.c", "nspr/lib/libc/src/strcmp.c", "nspr/lib/libc/src/strcpy.c", "nspr/lib/libc/src/strdup.c", "nspr/lib/libc/src/strlen.c", "nspr/lib/libc/src/strpbrk.c", "nspr/lib/libc/src/strstr.c", "nspr/lib/libc/src/strtok.c", "nspr/pr/include/md/_darwin.cfg", "nspr/pr/include/md/_darwin.h", "nspr/pr/include/md/_pcos.h", "nspr/pr/include/md/_pth.h", "nspr/pr/include/md/_unix_errors.h", "nspr/pr/include/md/_unixos.h", "nspr/pr/include/md/_win32_errors.h", "nspr/pr/include/md/_win95.cfg", "nspr/pr/include/md/_win95.h", "nspr/pr/include/md/prosdep.h", "nspr/pr/include/nspr.h", "nspr/pr/include/obsolete/pralarm.h", "nspr/pr/include/obsolete/probslet.h", "nspr/pr/include/obsolete/protypes.h", "nspr/pr/include/obsolete/prsem.h", "nspr/pr/include/pratom.h", "nspr/pr/include/prbit.h", "nspr/pr/include/prclist.h", "nspr/pr/include/prcmon.h", "nspr/pr/include/prcountr.h", "nspr/pr/include/prcpucfg.h", "nspr/pr/include/prcvar.h", "nspr/pr/include/prdtoa.h", "nspr/pr/include/prenv.h", "nspr/pr/include/prerr.h", "nspr/pr/include/prerror.h", "nspr/pr/include/prinet.h", "nspr/pr/include/prinit.h", "nspr/pr/include/prinrval.h", "nspr/pr/include/prio.h", "nspr/pr/include/pripcsem.h", "nspr/pr/include/private/pprio.h", "nspr/pr/include/private/pprmwait.h", "nspr/pr/include/private/pprthred.h", "nspr/pr/include/private/primpl.h", "nspr/pr/include/private/prpriv.h", "nspr/pr/include/prlink.h", "nspr/pr/include/prlock.h", "nspr/pr/include/prlog.h", "nspr/pr/include/prlong.h", "nspr/pr/include/prmem.h", "nspr/pr/include/prmon.h", "nspr/pr/include/prmwait.h", "nspr/pr/include/prnetdb.h", "nspr/pr/include/prolock.h", "nspr/pr/include/prpdce.h", "nspr/pr/include/prprf.h", "nspr/pr/include/prproces.h", "nspr/pr/include/prrng.h", "nspr/pr/include/prrwlock.h", "nspr/pr/include/prshm.h", "nspr/pr/include/prshma.h", "nspr/pr/include/prsystem.h", "nspr/pr/include/prthread.h", "nspr/pr/include/prtime.h", "nspr/pr/include/prtpool.h", "nspr/pr/include/prtrace.h", "nspr/pr/include/prtypes.h", "nspr/pr/include/prvrsion.h", "nspr/pr/include/prwin16.h", "nspr/pr/src/io/prdir.c", "nspr/pr/src/io/prfdcach.c", "nspr/pr/src/io/prfile.c", "nspr/pr/src/io/prio.c", "nspr/pr/src/io/priometh.c", "nspr/pr/src/io/pripv6.c", "nspr/pr/src/io/prlayer.c", "nspr/pr/src/io/prlog.c", "nspr/pr/src/io/prmapopt.c", "nspr/pr/src/io/prmmap.c", "nspr/pr/src/io/prmwait.c", "nspr/pr/src/io/prpolevt.c", "nspr/pr/src/io/prprf.c", "nspr/pr/src/io/prscanf.c", "nspr/pr/src/io/prsocket.c", "nspr/pr/src/io/prstdio.c", "nspr/pr/src/linking/prlink.c", "nspr/pr/src/malloc/prmalloc.c", "nspr/pr/src/malloc/prmem.c", "nspr/pr/src/md/prosdep.c", "nspr/pr/src/md/unix/darwin.c", "nspr/pr/src/md/unix/os_Darwin.s", "nspr/pr/src/md/unix/unix.c", "nspr/pr/src/md/unix/unix_errors.c", "nspr/pr/src/md/unix/uxproces.c", "nspr/pr/src/md/unix/uxrng.c", "nspr/pr/src/md/unix/uxshm.c", "nspr/pr/src/md/unix/uxwrap.c", "nspr/pr/src/md/windows/ntgc.c", "nspr/pr/src/md/windows/ntinrval.c", "nspr/pr/src/md/windows/ntmisc.c", "nspr/pr/src/md/windows/ntsec.c", "nspr/pr/src/md/windows/ntsem.c", "nspr/pr/src/md/windows/w32ipcsem.c", "nspr/pr/src/md/windows/w32poll.c", "nspr/pr/src/md/windows/w32rng.c", "nspr/pr/src/md/windows/w32shm.c", "nspr/pr/src/md/windows/w95cv.c", "nspr/pr/src/md/windows/w95dllmain.c", "nspr/pr/src/md/windows/w95io.c", "nspr/pr/src/md/windows/w95sock.c", "nspr/pr/src/md/windows/w95thred.c", "nspr/pr/src/md/windows/win32_errors.c", "nspr/pr/src/memory/prseg.c", "nspr/pr/src/memory/prshm.c", "nspr/pr/src/memory/prshma.c", "nspr/pr/src/misc/pralarm.c", "nspr/pr/src/misc/pratom.c", "nspr/pr/src/misc/praton.c", "nspr/pr/src/misc/prcountr.c", "nspr/pr/src/misc/prdtoa.c", "nspr/pr/src/misc/prenv.c", "nspr/pr/src/misc/prerr.c", "nspr/pr/src/misc/prerror.c", "nspr/pr/src/misc/prerrortable.c", "nspr/pr/src/misc/prinit.c", "nspr/pr/src/misc/prinrval.c", "nspr/pr/src/misc/pripc.c", "nspr/pr/src/misc/pripcsem.c", "nspr/pr/src/misc/prlog2.c", "nspr/pr/src/misc/prlong.c", "nspr/pr/src/misc/prnetdb.c", "nspr/pr/src/misc/prolock.c", "nspr/pr/src/misc/prrng.c", "nspr/pr/src/misc/prsystem.c", "nspr/pr/src/misc/prthinfo.c", "nspr/pr/src/misc/prtime.c", "nspr/pr/src/misc/prtpool.c", "nspr/pr/src/misc/prtrace.c", "nspr/pr/src/pthreads/ptio.c", "nspr/pr/src/pthreads/ptmisc.c", "nspr/pr/src/pthreads/ptsynch.c", "nspr/pr/src/pthreads/ptthread.c", "nspr/pr/src/threads/combined/prucpu.c", "nspr/pr/src/threads/combined/prucv.c", "nspr/pr/src/threads/combined/prulock.c", "nspr/pr/src/threads/combined/prustack.c", "nspr/pr/src/threads/combined/pruthr.c", "nspr/pr/src/threads/prcmon.c", "nspr/pr/src/threads/prcthr.c", "nspr/pr/src/threads/prdump.c", "nspr/pr/src/threads/prmon.c", "nspr/pr/src/threads/prrwlock.c", "nspr/pr/src/threads/prsem.c", "nspr/pr/src/threads/prtpd.c", ] public_configs = [ ":nspr_config" ] configs -= [ "//build/config/compiler:chromium_code" ] if (is_win) { configs -= [ "//build/config/win:unicode", # Requires 8-bit mode. "//build/config/win:lean_and_mean", # Won"t compile with lean and mean. ] } configs += [ "//build/config/compiler:no_chromium_code", "//build/config/compiler:no_size_t_to_int_warning", ] cflags = [] defines = [ "_NSPR_BUILD_", "FORCE_PR_LOG", ] include_dirs = [ "nspr/pr/include/private" ] if (is_win) { cflags = [ "/wd4554" ] # Check precidence. defines += [ "XP_PC", "WIN32", "WIN95", "_PR_GLOBAL_THREADS_ONLY", "_CRT_SECURE_NO_WARNINGS", ] } else { sources -= [ "nspr/pr/src/md/windows/ntgc.c", "nspr/pr/src/md/windows/ntinrval.c", "nspr/pr/src/md/windows/ntmisc.c", "nspr/pr/src/md/windows/ntsec.c", "nspr/pr/src/md/windows/ntsem.c", "nspr/pr/src/md/windows/w32ipcsem.c", "nspr/pr/src/md/windows/w32poll.c", "nspr/pr/src/md/windows/w32rng.c", "nspr/pr/src/md/windows/w32shm.c", "nspr/pr/src/md/windows/w95cv.c", "nspr/pr/src/md/windows/w95dllmain.c", "nspr/pr/src/md/windows/w95io.c", "nspr/pr/src/md/windows/w95sock.c", "nspr/pr/src/md/windows/w95thred.c", "nspr/pr/src/md/windows/win32_errors.c", "nspr/pr/src/threads/combined/prucpu.c", "nspr/pr/src/threads/combined/prucv.c", "nspr/pr/src/threads/combined/prulock.c", "nspr/pr/src/threads/combined/prustack.c", "nspr/pr/src/threads/combined/pruthr.c", ] } if (!is_posix) { sources -= [ "nspr/pr/src/md/unix/darwin.c", "nspr/pr/src/md/unix/os_Darwin.s", "nspr/pr/src/md/unix/unix.c", "nspr/pr/src/md/unix/unix_errors.c", "nspr/pr/src/md/unix/uxproces.c", "nspr/pr/src/md/unix/uxrng.c", "nspr/pr/src/md/unix/uxshm.c", "nspr/pr/src/md/unix/uxwrap.c", "nspr/pr/src/pthreads/ptio.c", "nspr/pr/src/pthreads/ptmisc.c", "nspr/pr/src/pthreads/ptsynch.c", "nspr/pr/src/pthreads/ptthread.c", ] } if (current_cpu == "x86") { defines += [ "_X86_" ] } else if (current_cpu == "x64") { defines += [ "_AMD64_" ] } if (is_mac || is_ios) { sources -= [ "nspr/pr/src/io/prdir.c", "nspr/pr/src/io/prfile.c", "nspr/pr/src/io/prio.c", "nspr/pr/src/io/prsocket.c", "nspr/pr/src/misc/pripcsem.c", "nspr/pr/src/threads/prcthr.c", "nspr/pr/src/threads/prdump.c", "nspr/pr/src/threads/prmon.c", "nspr/pr/src/threads/prsem.c", ] defines += [ "XP_UNIX", "DARWIN", "XP_MACOSX", "_PR_PTHREADS", "HAVE_BSD_FLOCK", "HAVE_DLADDR", "HAVE_LCHOWN", "HAVE_SOCKLEN_T", "HAVE_STRERROR", ] } if (is_mac) { defines += [ "HAVE_CRT_EXTERNS_H" ] libs = [ "CoreFoundation.framework", "CoreServices.framework", ] } if (is_clang) { cflags += [ # nspr uses a bunch of deprecated functions (NSLinkModule etc) in # prlink.c on mac. "-Wno-deprecated-declarations", # nspr passes "const char*" through "void*". "-Wno-incompatible-pointer-types", # nspr passes "int*" through "unsigned int*". "-Wno-pointer-sign", ] # nspr uses assert(!"foo") instead of assert(false && "foo"). configs -= [ "//build/config/clang:extra_warnings" ] } } component("nss") { output_name = "crnss" sources = [ # Ensure at least one object file is produced, so that MSVC does not # warn when creating the static/shared library. See the note for # the "nssckbi" target for why the "nss" target was split as such. "nss/lib/nss/nssver.c", ] public_deps = [ ":nss_static" ] if (include_nss_root_certs) { public_deps += [ ":nssckbi" ] } if (component_mode == "shared_library") { if (is_mac) { ldflags = [ "-all_load" ] } else if (is_win) { # Pass the def file to the linker. ldflags = [ "/DEF:" + rebase_path("nss/exports_win.def", root_build_dir) ] } } } config("nssckbi_config") { include_dirs = [ "nss/lib/ckfw/builtins" ] } # This is really more of a pseudo-target to work around the fact that # a single static_library target cannot contain two object files of the # same name (hash.o / hash.obj). Logically, this is part of the # "nss_static" target. By separating it out, it creates a possible # circular dependency between "nss_static" and "nssckbi" when # "exclude_nss_root_certs" is not specified, as "nss_static" depends on # the "builtinsC_GetFunctionList" exported by this target. This is an # artifact of how NSS is being statically built, which is not an # officially supported configuration - normally, "nssckbi.dll/so" would # depend on libnss3.dll/so, and the higher layer caller would instruct # libnss3.dll to dynamically load nssckbi.dll, breaking the circle. # # TODO(rsleevi): http://crbug.com/128134 - Break the circular dependency # without requiring nssckbi to be built as a shared library. source_set("nssckbi") { visibility = [ ":nss" ] # This target is internal implementation detail. sources = [ "nss/lib/ckfw/builtins/anchor.c", "nss/lib/ckfw/builtins/bfind.c", "nss/lib/ckfw/builtins/binst.c", "nss/lib/ckfw/builtins/bobject.c", "nss/lib/ckfw/builtins/bsession.c", "nss/lib/ckfw/builtins/bslot.c", "nss/lib/ckfw/builtins/btoken.c", "nss/lib/ckfw/builtins/builtins.h", "nss/lib/ckfw/builtins/certdata.c", "nss/lib/ckfw/builtins/ckbiver.c", "nss/lib/ckfw/builtins/constants.c", "nss/lib/ckfw/builtins/nssckbi.h", "nss/lib/ckfw/ck.h", "nss/lib/ckfw/ckfw.h", "nss/lib/ckfw/ckfwm.h", "nss/lib/ckfw/ckfwtm.h", "nss/lib/ckfw/ckmd.h", "nss/lib/ckfw/ckt.h", "nss/lib/ckfw/crypto.c", "nss/lib/ckfw/find.c", "nss/lib/ckfw/hash.c", "nss/lib/ckfw/instance.c", "nss/lib/ckfw/mechanism.c", "nss/lib/ckfw/mutex.c", "nss/lib/ckfw/nssck.api", "nss/lib/ckfw/nssckepv.h", "nss/lib/ckfw/nssckft.h", "nss/lib/ckfw/nssckfw.h", "nss/lib/ckfw/nssckfwc.h", "nss/lib/ckfw/nssckfwt.h", "nss/lib/ckfw/nssckg.h", "nss/lib/ckfw/nssckmdt.h", "nss/lib/ckfw/nssckt.h", "nss/lib/ckfw/object.c", "nss/lib/ckfw/session.c", "nss/lib/ckfw/sessobj.c", "nss/lib/ckfw/slot.c", "nss/lib/ckfw/token.c", "nss/lib/ckfw/wrap.c", ] configs -= [ "//build/config/compiler:chromium_code" ] if (is_win) { configs -= [ "//build/config/win:unicode" ] # Requires 8-bit mode. } configs += [ "//build/config/compiler:no_chromium_code" ] include_dirs = [ "nss/lib/ckfw" ] public_configs = [ ":nssckbi_config" ] public_deps = [ ":nss_static" ] } config("nss_static_config") { defines = [ "NSS_STATIC", "NSS_USE_STATIC_LIBS", "USE_UTIL_DIRECTLY", ] if (is_win) { defines += [ "_WINDOWS" ] } include_dirs = [ "nspr/pr/include", "nspr/lib/ds", "nspr/lib/libc/include", "nss/lib/base", "nss/lib/certdb", "nss/lib/certhigh", "nss/lib/cryptohi", "nss/lib/dev", "nss/lib/freebl", "nss/lib/freebl/ecl", "nss/lib/nss", "nss/lib/pk11wrap", "nss/lib/pkcs7", "nss/lib/pki", "nss/lib/smime", "nss/lib/softoken", "nss/lib/util", ] } if (is_win && current_cpu == "x86") { source_set("nss_static_avx") { sources = [ "nss/lib/freebl/intel-gcm-wrap.c", "nss/lib/freebl/intel-gcm-x86-masm.asm", "nss/lib/freebl/intel-gcm.h", ] defines = [ "_WINDOWS", "_X86_", "INTEL_GCM", "MP_API_COMPATIBLE", "MP_ASSEMBLY_DIV_2DX1D", "MP_ASSEMBLY_MULTIPLY", "MP_ASSEMBLY_SQUARE", "MP_NO_MP_WORD", "MP_USE_UINT_DIGIT", "NSS_DISABLE_DBM", "NSS_STATIC", "NSS_USE_STATIC_LIBS", "NSS_X86", "NSS_X86_OR_X64", "RIJNDAEL_INCLUDE_TABLES", "SHLIB_PREFIX=\"\"", "SHLIB_SUFFIX=\"dll\"", "SHLIB_VERSION=\"3\"", "SOFTOKEN_LIB_NAME=\"softokn3.dll\"", "SOFTOKEN_SHLIB_VERSION=\"3\"", "USE_HW_AES", "USE_UTIL_DIRECTLY", "WIN32", "WIN95", "XP_PC", ] include_dirs = [ "nspr/pr/include", "nspr/lib/ds", "nspr/lib/libc/include", "nss/lib/freebl/ecl", "nss/lib/util", ] } } source_set("nss_static") { visibility = [ ":*" ] # Internal implementation detail. sources = [ "nss/lib/base/arena.c", "nss/lib/base/base.h", "nss/lib/base/baset.h", "nss/lib/base/error.c", "nss/lib/base/errorval.c", "nss/lib/base/hash.c", "nss/lib/base/hashops.c", "nss/lib/base/item.c", "nss/lib/base/libc.c", "nss/lib/base/list.c", "nss/lib/base/nssbase.h", "nss/lib/base/nssbaset.h", "nss/lib/base/nssutf8.c", "nss/lib/base/tracker.c", "nss/lib/certdb/alg1485.c", "nss/lib/certdb/cert.h", "nss/lib/certdb/certdb.c", "nss/lib/certdb/certdb.h", "nss/lib/certdb/certi.h", "nss/lib/certdb/certt.h", "nss/lib/certdb/certv3.c", "nss/lib/certdb/certxutl.c", "nss/lib/certdb/certxutl.h", "nss/lib/certdb/crl.c", "nss/lib/certdb/genname.c", "nss/lib/certdb/genname.h", "nss/lib/certdb/polcyxtn.c", "nss/lib/certdb/secname.c", "nss/lib/certdb/stanpcertdb.c", "nss/lib/certdb/xauthkid.c", "nss/lib/certdb/xbsconst.c", "nss/lib/certdb/xconst.c", "nss/lib/certdb/xconst.h", "nss/lib/certhigh/certhigh.c", "nss/lib/certhigh/certhtml.c", "nss/lib/certhigh/certreq.c", "nss/lib/certhigh/certvfy.c", "nss/lib/certhigh/crlv2.c", "nss/lib/certhigh/ocsp.c", "nss/lib/certhigh/ocsp.h", "nss/lib/certhigh/ocspi.h", "nss/lib/certhigh/ocspsig.c", "nss/lib/certhigh/ocspt.h", "nss/lib/certhigh/ocspti.h", "nss/lib/certhigh/xcrldist.c", "nss/lib/cryptohi/cryptohi.h", "nss/lib/cryptohi/cryptoht.h", "nss/lib/cryptohi/dsautil.c", "nss/lib/cryptohi/key.h", "nss/lib/cryptohi/keyhi.h", "nss/lib/cryptohi/keyi.h", "nss/lib/cryptohi/keyt.h", "nss/lib/cryptohi/keythi.h", "nss/lib/cryptohi/sechash.c", "nss/lib/cryptohi/sechash.h", "nss/lib/cryptohi/seckey.c", "nss/lib/cryptohi/secsign.c", "nss/lib/cryptohi/secvfy.c", "nss/lib/dev/ckhelper.c", "nss/lib/dev/ckhelper.h", "nss/lib/dev/dev.h", "nss/lib/dev/devm.h", "nss/lib/dev/devslot.c", "nss/lib/dev/devt.h", "nss/lib/dev/devtm.h", "nss/lib/dev/devtoken.c", "nss/lib/dev/devutil.c", "nss/lib/dev/nssdev.h", "nss/lib/dev/nssdevt.h", "nss/lib/freebl/aeskeywrap.c", "nss/lib/freebl/alg2268.c", "nss/lib/freebl/alghmac.c", "nss/lib/freebl/alghmac.h", "nss/lib/freebl/arcfive.c", "nss/lib/freebl/arcfour.c", "nss/lib/freebl/blapi.h", "nss/lib/freebl/blapii.h", "nss/lib/freebl/blapit.h", "nss/lib/freebl/camellia.c", "nss/lib/freebl/camellia.h", "nss/lib/freebl/chacha20/chacha20.c", "nss/lib/freebl/chacha20/chacha20.h", "nss/lib/freebl/chacha20/chacha20_vec.c", "nss/lib/freebl/chacha20poly1305.c", "nss/lib/freebl/chacha20poly1305.h", "nss/lib/freebl/ctr.c", "nss/lib/freebl/ctr.h", "nss/lib/freebl/cts.c", "nss/lib/freebl/cts.h", "nss/lib/freebl/des.c", "nss/lib/freebl/des.h", "nss/lib/freebl/desblapi.c", "nss/lib/freebl/dh.c", "nss/lib/freebl/drbg.c", "nss/lib/freebl/dsa.c", "nss/lib/freebl/ec.c", "nss/lib/freebl/ec.h", "nss/lib/freebl/ecdecode.c", "nss/lib/freebl/ecl/ec2.h", "nss/lib/freebl/ecl/ec_naf.c", "nss/lib/freebl/ecl/ecl-curve.h", "nss/lib/freebl/ecl/ecl-exp.h", "nss/lib/freebl/ecl/ecl-priv.h", "nss/lib/freebl/ecl/ecl.c", "nss/lib/freebl/ecl/ecl.h", "nss/lib/freebl/ecl/ecl_curve.c", "nss/lib/freebl/ecl/ecl_gf.c", "nss/lib/freebl/ecl/ecl_mult.c", "nss/lib/freebl/ecl/ecp.h", "nss/lib/freebl/ecl/ecp_256.c", "nss/lib/freebl/ecl/ecp_256_32.c", "nss/lib/freebl/ecl/ecp_384.c", "nss/lib/freebl/ecl/ecp_521.c", "nss/lib/freebl/ecl/ecp_aff.c", "nss/lib/freebl/ecl/ecp_jac.c", "nss/lib/freebl/ecl/ecp_jm.c", "nss/lib/freebl/ecl/ecp_mont.c", "nss/lib/freebl/gcm.c", "nss/lib/freebl/gcm.h", "nss/lib/freebl/hmacct.c", "nss/lib/freebl/hmacct.h", "nss/lib/freebl/intel-aes-x86-masm.asm", "nss/lib/freebl/intel-aes.h", "nss/lib/freebl/jpake.c", "nss/lib/freebl/md2.c", "nss/lib/freebl/md5.c", "nss/lib/freebl/mpi/logtab.h", "nss/lib/freebl/mpi/mp_gf2m-priv.h", "nss/lib/freebl/mpi/mp_gf2m.c", "nss/lib/freebl/mpi/mp_gf2m.h", "nss/lib/freebl/mpi/mpcpucache.c", "nss/lib/freebl/mpi/mpi-config.h", "nss/lib/freebl/mpi/mpi-priv.h", "nss/lib/freebl/mpi/mpi.c", "nss/lib/freebl/mpi/mpi.h", "nss/lib/freebl/mpi/mpi_amd64.c", "nss/lib/freebl/mpi/mpi_arm.c", "nss/lib/freebl/mpi/mpi_arm_mac.c", "nss/lib/freebl/mpi/mpi_x86_asm.c", "nss/lib/freebl/mpi/mplogic.c", "nss/lib/freebl/mpi/mplogic.h", "nss/lib/freebl/mpi/mpmontg.c", "nss/lib/freebl/mpi/mpprime.c", "nss/lib/freebl/mpi/mpprime.h", "nss/lib/freebl/mpi/primes.c", "nss/lib/freebl/nss_build_config_mac.h", "nss/lib/freebl/poly1305/poly1305-donna-x64-sse2-incremental-source.c", "nss/lib/freebl/poly1305/poly1305.c", "nss/lib/freebl/poly1305/poly1305.h", "nss/lib/freebl/pqg.c", "nss/lib/freebl/pqg.h", "nss/lib/freebl/rawhash.c", "nss/lib/freebl/rijndael.c", "nss/lib/freebl/rijndael.h", "nss/lib/freebl/rijndael32.tab", "nss/lib/freebl/rsa.c", "nss/lib/freebl/rsapkcs.c", "nss/lib/freebl/secmpi.h", "nss/lib/freebl/secrng.h", "nss/lib/freebl/seed.c", "nss/lib/freebl/seed.h", "nss/lib/freebl/sha256.h", "nss/lib/freebl/sha512.c", "nss/lib/freebl/sha_fast.c", "nss/lib/freebl/sha_fast.h", "nss/lib/freebl/shsign.h", "nss/lib/freebl/shvfy.c", "nss/lib/freebl/sysrand.c", "nss/lib/freebl/tlsprfalg.c", "nss/lib/freebl/unix_rand.c", "nss/lib/freebl/win_rand.c", "nss/lib/nss/nss.h", "nss/lib/nss/nssinit.c", "nss/lib/nss/nssrenam.h", "nss/lib/nss/utilwrap.c", "nss/lib/pk11wrap/debug_module.c", "nss/lib/pk11wrap/dev3hack.c", "nss/lib/pk11wrap/dev3hack.h", "nss/lib/pk11wrap/pk11akey.c", "nss/lib/pk11wrap/pk11auth.c", "nss/lib/pk11wrap/pk11cert.c", "nss/lib/pk11wrap/pk11cxt.c", "nss/lib/pk11wrap/pk11err.c", "nss/lib/pk11wrap/pk11func.h", "nss/lib/pk11wrap/pk11kea.c", "nss/lib/pk11wrap/pk11list.c", "nss/lib/pk11wrap/pk11load.c", "nss/lib/pk11wrap/pk11mech.c", "nss/lib/pk11wrap/pk11merge.c", "nss/lib/pk11wrap/pk11nobj.c", "nss/lib/pk11wrap/pk11obj.c", "nss/lib/pk11wrap/pk11pars.c", "nss/lib/pk11wrap/pk11pbe.c", "nss/lib/pk11wrap/pk11pk12.c", "nss/lib/pk11wrap/pk11pqg.c", "nss/lib/pk11wrap/pk11pqg.h", "nss/lib/pk11wrap/pk11priv.h", "nss/lib/pk11wrap/pk11pub.h", "nss/lib/pk11wrap/pk11sdr.c", "nss/lib/pk11wrap/pk11sdr.h", "nss/lib/pk11wrap/pk11skey.c", "nss/lib/pk11wrap/pk11slot.c", "nss/lib/pk11wrap/pk11util.c", "nss/lib/pk11wrap/secmod.h", "nss/lib/pk11wrap/secmodi.h", "nss/lib/pk11wrap/secmodt.h", "nss/lib/pk11wrap/secmodti.h", "nss/lib/pk11wrap/secpkcs5.h", "nss/lib/pkcs7/certread.c", "nss/lib/pkcs7/p7common.c", "nss/lib/pkcs7/p7create.c", "nss/lib/pkcs7/p7decode.c", "nss/lib/pkcs7/p7encode.c", "nss/lib/pkcs7/p7local.c", "nss/lib/pkcs7/p7local.h", "nss/lib/pkcs7/pkcs7t.h", "nss/lib/pkcs7/secmime.c", "nss/lib/pkcs7/secmime.h", "nss/lib/pkcs7/secpkcs7.h", "nss/lib/pki/asymmkey.c", "nss/lib/pki/certdecode.c", "nss/lib/pki/certificate.c", "nss/lib/pki/cryptocontext.c", "nss/lib/pki/nsspki.h", "nss/lib/pki/nsspkit.h", "nss/lib/pki/pki.h", "nss/lib/pki/pki3hack.c", "nss/lib/pki/pki3hack.h", "nss/lib/pki/pkibase.c", "nss/lib/pki/pkim.h", "nss/lib/pki/pkistore.c", "nss/lib/pki/pkistore.h", "nss/lib/pki/pkit.h", "nss/lib/pki/pkitm.h", "nss/lib/pki/symmkey.c", "nss/lib/pki/tdcache.c", "nss/lib/pki/trustdomain.c", "nss/lib/smime/cms.h", "nss/lib/smime/cmslocal.h", "nss/lib/smime/cmsreclist.h", "nss/lib/smime/cmst.h", "nss/lib/smime/smime.h", "nss/lib/softoken/fipsaudt.c", "nss/lib/softoken/fipstest.c", "nss/lib/softoken/fipstokn.c", "nss/lib/softoken/jpakesftk.c", "nss/lib/softoken/lgglue.c", "nss/lib/softoken/lgglue.h", "nss/lib/softoken/lowkey.c", "nss/lib/softoken/lowkeyi.h", "nss/lib/softoken/lowkeyti.h", "nss/lib/softoken/lowpbe.c", "nss/lib/softoken/lowpbe.h", "nss/lib/softoken/padbuf.c", "nss/lib/softoken/pkcs11.c", "nss/lib/softoken/pkcs11c.c", "nss/lib/softoken/pkcs11i.h", "nss/lib/softoken/pkcs11ni.h", "nss/lib/softoken/pkcs11u.c", "nss/lib/softoken/sdb.c", "nss/lib/softoken/sdb.h", "nss/lib/softoken/sftkdb.c", "nss/lib/softoken/sftkdb.h", "nss/lib/softoken/sftkdbt.h", "nss/lib/softoken/sftkdbti.h", "nss/lib/softoken/sftkhmac.c", "nss/lib/softoken/sftkpars.c", "nss/lib/softoken/sftkpars.h", "nss/lib/softoken/sftkpwd.c", "nss/lib/softoken/softkver.c", "nss/lib/softoken/softkver.h", "nss/lib/softoken/softoken.h", "nss/lib/softoken/softoknt.h", "nss/lib/softoken/tlsprf.c", "nss/lib/ssl/sslerr.h", "nss/lib/util/SECerrs.h", "nss/lib/util/base64.h", "nss/lib/util/ciferfam.h", "nss/lib/util/derdec.c", "nss/lib/util/derenc.c", "nss/lib/util/dersubr.c", "nss/lib/util/dertime.c", "nss/lib/util/errstrs.c", "nss/lib/util/hasht.h", "nss/lib/util/nssb64.h", "nss/lib/util/nssb64d.c", "nss/lib/util/nssb64e.c", "nss/lib/util/nssb64t.h", "nss/lib/util/nssilckt.h", "nss/lib/util/nssilock.c", "nss/lib/util/nssilock.h", "nss/lib/util/nsslocks.h", "nss/lib/util/nssrwlk.c", "nss/lib/util/nssrwlk.h", "nss/lib/util/nssrwlkt.h", "nss/lib/util/nssutil.h", "nss/lib/util/oidstring.c", "nss/lib/util/pkcs11.h", "nss/lib/util/pkcs11f.h", "nss/lib/util/pkcs11n.h", "nss/lib/util/pkcs11p.h", "nss/lib/util/pkcs11t.h", "nss/lib/util/pkcs11u.h", "nss/lib/util/pkcs1sig.c", "nss/lib/util/pkcs1sig.h", "nss/lib/util/portreg.c", "nss/lib/util/portreg.h", "nss/lib/util/quickder.c", "nss/lib/util/secalgid.c", "nss/lib/util/secasn1.h", "nss/lib/util/secasn1d.c", "nss/lib/util/secasn1e.c", "nss/lib/util/secasn1t.h", "nss/lib/util/secasn1u.c", "nss/lib/util/seccomon.h", "nss/lib/util/secder.h", "nss/lib/util/secdert.h", "nss/lib/util/secdig.c", "nss/lib/util/secdig.h", "nss/lib/util/secdigt.h", "nss/lib/util/secerr.h", "nss/lib/util/secitem.c", "nss/lib/util/secitem.h", "nss/lib/util/secoid.c", "nss/lib/util/secoid.h", "nss/lib/util/secoidt.h", "nss/lib/util/secport.c", "nss/lib/util/secport.h", "nss/lib/util/sectime.c", "nss/lib/util/templates.c", "nss/lib/util/utf8.c", "nss/lib/util/utilmod.c", "nss/lib/util/utilmodt.h", "nss/lib/util/utilpars.c", "nss/lib/util/utilpars.h", "nss/lib/util/utilparst.h", "nss/lib/util/utilrename.h", ] sources -= [ # mpi_arm.c is included by mpi_arm_mac.c. # NOTE: mpi_arm.c can be used directly on Linux. mpi_arm.c will need # to be excluded conditionally if we start to build NSS on Linux. "nss/lib/freebl/mpi/mpi_arm.c", # primes.c is included by mpprime.c. "nss/lib/freebl/mpi/primes.c", # unix_rand.c and win_rand.c are included by sysrand.c. "nss/lib/freebl/unix_rand.c", "nss/lib/freebl/win_rand.c", # debug_module.c is included by pk11load.c. "nss/lib/pk11wrap/debug_module.c", ] configs -= [ "//build/config/compiler:chromium_code" ] if (is_win) { configs -= [ "//build/config/win:unicode" ] # Requires 8-bit mode. } configs += [ "//build/config/compiler:no_chromium_code", "//build/config/compiler:no_size_t_to_int_warning", ] public_configs = [ ":nss_static_config" ] cflags = [] # Only need the defines and includes not in nss_static_config. defines = [ "MP_API_COMPATIBLE", "NSS_DISABLE_DBM", "RIJNDAEL_INCLUDE_TABLES", "SHLIB_VERSION=\"3\"", "SOFTOKEN_SHLIB_VERSION=\"3\"", ] include_dirs = [ "nss/lib/freebl/mpi", "nss/lib/ssl", ] if (is_win) { cflags += [ "/wd4101" ] # Unreferenced local variable. } if (include_nss_libpkix) { sources += [ "nss/lib/certhigh/certvfypkix.c", "nss/lib/certhigh/certvfypkixprint.c", "nss/lib/libpkix/include/pkix.h", "nss/lib/libpkix/include/pkix_certsel.h", "nss/lib/libpkix/include/pkix_certstore.h", "nss/lib/libpkix/include/pkix_checker.h", "nss/lib/libpkix/include/pkix_crlsel.h", "nss/lib/libpkix/include/pkix_errorstrings.h", "nss/lib/libpkix/include/pkix_params.h", "nss/lib/libpkix/include/pkix_pl_pki.h", "nss/lib/libpkix/include/pkix_pl_system.h", "nss/lib/libpkix/include/pkix_results.h", "nss/lib/libpkix/include/pkix_revchecker.h", "nss/lib/libpkix/include/pkix_sample_modules.h", "nss/lib/libpkix/include/pkix_util.h", "nss/lib/libpkix/include/pkixt.h", "nss/lib/libpkix/pkix/certsel/pkix_certselector.c", "nss/lib/libpkix/pkix/certsel/pkix_certselector.h", "nss/lib/libpkix/pkix/certsel/pkix_comcertselparams.c", "nss/lib/libpkix/pkix/certsel/pkix_comcertselparams.h", "nss/lib/libpkix/pkix/checker/pkix_basicconstraintschecker.c", "nss/lib/libpkix/pkix/checker/pkix_basicconstraintschecker.h", "nss/lib/libpkix/pkix/checker/pkix_certchainchecker.c", "nss/lib/libpkix/pkix/checker/pkix_certchainchecker.h", "nss/lib/libpkix/pkix/checker/pkix_crlchecker.c", "nss/lib/libpkix/pkix/checker/pkix_crlchecker.h", "nss/lib/libpkix/pkix/checker/pkix_ekuchecker.c", "nss/lib/libpkix/pkix/checker/pkix_ekuchecker.h", "nss/lib/libpkix/pkix/checker/pkix_expirationchecker.c", "nss/lib/libpkix/pkix/checker/pkix_expirationchecker.h", "nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.c", "nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.h", "nss/lib/libpkix/pkix/checker/pkix_nameconstraintschecker.c", "nss/lib/libpkix/pkix/checker/pkix_nameconstraintschecker.h", "nss/lib/libpkix/pkix/checker/pkix_ocspchecker.c", "nss/lib/libpkix/pkix/checker/pkix_ocspchecker.h", "nss/lib/libpkix/pkix/checker/pkix_policychecker.c", "nss/lib/libpkix/pkix/checker/pkix_policychecker.h", "nss/lib/libpkix/pkix/checker/pkix_revocationchecker.c", "nss/lib/libpkix/pkix/checker/pkix_revocationchecker.h", "nss/lib/libpkix/pkix/checker/pkix_revocationmethod.c", "nss/lib/libpkix/pkix/checker/pkix_revocationmethod.h", "nss/lib/libpkix/pkix/checker/pkix_signaturechecker.c", "nss/lib/libpkix/pkix/checker/pkix_signaturechecker.h", "nss/lib/libpkix/pkix/checker/pkix_targetcertchecker.c", "nss/lib/libpkix/pkix/checker/pkix_targetcertchecker.h", "nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.c", "nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.h", "nss/lib/libpkix/pkix/crlsel/pkix_crlselector.c", "nss/lib/libpkix/pkix/crlsel/pkix_crlselector.h", "nss/lib/libpkix/pkix/params/pkix_procparams.c", "nss/lib/libpkix/pkix/params/pkix_procparams.h", "nss/lib/libpkix/pkix/params/pkix_resourcelimits.c", "nss/lib/libpkix/pkix/params/pkix_resourcelimits.h", "nss/lib/libpkix/pkix/params/pkix_trustanchor.c", "nss/lib/libpkix/pkix/params/pkix_trustanchor.h", "nss/lib/libpkix/pkix/params/pkix_valparams.c", "nss/lib/libpkix/pkix/params/pkix_valparams.h", "nss/lib/libpkix/pkix/results/pkix_buildresult.c", "nss/lib/libpkix/pkix/results/pkix_buildresult.h", "nss/lib/libpkix/pkix/results/pkix_policynode.c", "nss/lib/libpkix/pkix/results/pkix_policynode.h", "nss/lib/libpkix/pkix/results/pkix_valresult.c", "nss/lib/libpkix/pkix/results/pkix_valresult.h", "nss/lib/libpkix/pkix/results/pkix_verifynode.c", "nss/lib/libpkix/pkix/results/pkix_verifynode.h", "nss/lib/libpkix/pkix/store/pkix_store.c", "nss/lib/libpkix/pkix/store/pkix_store.h", "nss/lib/libpkix/pkix/top/pkix_build.c", "nss/lib/libpkix/pkix/top/pkix_build.h", "nss/lib/libpkix/pkix/top/pkix_lifecycle.c", "nss/lib/libpkix/pkix/top/pkix_lifecycle.h", "nss/lib/libpkix/pkix/top/pkix_validate.c", "nss/lib/libpkix/pkix/top/pkix_validate.h", "nss/lib/libpkix/pkix/util/pkix_error.c", "nss/lib/libpkix/pkix/util/pkix_error.h", "nss/lib/libpkix/pkix/util/pkix_errpaths.c", "nss/lib/libpkix/pkix/util/pkix_list.c", "nss/lib/libpkix/pkix/util/pkix_list.h", "nss/lib/libpkix/pkix/util/pkix_logger.c", "nss/lib/libpkix/pkix/util/pkix_logger.h", "nss/lib/libpkix/pkix/util/pkix_tools.c", "nss/lib/libpkix/pkix/util/pkix_tools.h", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_aiamgr.c", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_aiamgr.h", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_colcertstore.c", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_colcertstore.h", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.c", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.h", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.h", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_nsscontext.c", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_nsscontext.h", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_pk11certstore.c", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_pk11certstore.h", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_socket.c", "nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_socket.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_basicconstraints.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_basicconstraints.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyinfo.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyinfo.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicymap.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicymap.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyqualifier.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_certpolicyqualifier.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crldp.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crldp.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crlentry.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crlentry.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_date.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_date.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_generalname.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_generalname.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_nameconstraints.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_nameconstraints.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspcertid.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspcertid.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocsprequest.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocsprequest.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspresponse.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspresponse.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_publickey.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_publickey.h", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_x500name.c", "nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_x500name.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bigint.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bigint.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bytearray.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bytearray.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_common.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_common.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_error.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_hashtable.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_hashtable.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_lifecycle.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_lifecycle.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mem.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mem.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_monitorlock.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_monitorlock.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_oid.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_oid.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_primhash.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_primhash.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_rwlock.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_rwlock.h", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_string.c", "nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_string.h", ] # Disable the LDAP code in libpkix. defines += [ "NSS_PKIX_NO_LDAP" ] include_dirs += [ "nss/lib/libpkix/include", "nss/lib/libpkix/pkix/certsel", "nss/lib/libpkix/pkix/checker", "nss/lib/libpkix/pkix/crlsel", "nss/lib/libpkix/pkix/params", "nss/lib/libpkix/pkix/results", "nss/lib/libpkix/pkix/store", "nss/lib/libpkix/pkix/top", "nss/lib/libpkix/pkix/util", "nss/lib/libpkix/pkix_pl_nss/module", "nss/lib/libpkix/pkix_pl_nss/pki", "nss/lib/libpkix/pkix_pl_nss/system", ] } else { defines += [ "NSS_DISABLE_LIBPKIX" ] } if (!include_nss_root_certs) { defines += [ "NSS_DISABLE_ROOT_CERTS" ] } if (current_cpu == "x64" && !is_win) { sources -= [ "nss/lib/freebl/chacha20/chacha20.c", "nss/lib/freebl/poly1305/poly1305.c", ] } else { sources -= [ "nss/lib/freebl/chacha20/chacha20_vec.c", "nss/lib/freebl/poly1305/poly1305-donna-x64-sse2-incremental-source.c", ] } if (is_mac || is_ios) { sources -= [ "nss/lib/freebl/mpi/mpi_amd64.c" ] cflags += [ "-include", rebase_path("//third_party/nss/nss/lib/freebl/nss_build_config_mac.h", root_build_dir), ] defines += [ "XP_UNIX", "DARWIN", "HAVE_STRERROR", "HAVE_BSD_FLOCK", "SHLIB_SUFFIX=\"dylib\"", "SHLIB_PREFIX=\"lib\"", "SOFTOKEN_LIB_NAME=\"libsoftokn3.dylib\"", ] configs -= [ "//build/config/gcc:symbol_visibility_hidden" ] } else { # Not Mac/iOS. sources -= [ "nss/lib/freebl/mpi/mpi_arm_mac.c" ] } if (is_win) { defines += [ "SHLIB_SUFFIX=\"dll\"", "SHLIB_PREFIX=\"\"", "SOFTOKEN_LIB_NAME=\"softokn3.dll\"", "XP_PC", "WIN32", "WIN95", ] if (current_cpu == "x86") { defines += [ "NSS_X86_OR_X64", "NSS_X86", "_X86_", "MP_ASSEMBLY_MULTIPLY", "MP_ASSEMBLY_SQUARE", "MP_ASSEMBLY_DIV_2DX1D", "MP_USE_UINT_DIGIT", "MP_NO_MP_WORD", "USE_HW_AES", "INTEL_GCM", ] sources -= [ "nss/lib/freebl/mpi/mpi_amd64.c" ] } else if (current_cpu == "x64") { sources -= [ "nss/lib/freebl/intel-aes-x86-masm.asm", "nss/lib/freebl/mpi/mpi_amd64.c", "nss/lib/freebl/mpi/mpi_x86_asm.c", ] defines += [ "NSS_USE_64", "NSS_X86_OR_X64", "NSS_X64", "_AMD64_", "MP_CHAR_STORE_SLOW", "MP_IS_LITTLE_ENDIAN", "WIN64", ] } } else { # Not Windows. sources -= [ # mpi_x86_asm.c contains MSVC inline assembly code. "nss/lib/freebl/mpi/mpi_x86_asm.c", ] } if (is_clang) { cflags += [ # nss doesn"t explicitly cast between different enum types. "-Wno-conversion", # nss passes "const char*" through "void*". "-Wno-incompatible-pointer-types", # nss prefers `a && b || c` over `(a && b) || c`. "-Wno-logical-op-parentheses", # nss doesn"t use exhaustive switches on enums "-Wno-switch", # nss has some `unsigned < 0` checks. "-Wno-tautological-compare", ] } public_deps = [ ":nspr" ] deps = [ ":nspr", "//third_party/sqlite", ] if (is_win && current_cpu == "x86") { deps += [ ":nss_static_avx" ] } } } # Windows/Mac/iOS.
engine/build/secondary/third_party/nss/BUILD.gn/0
{ "file_path": "engine/build/secondary/third_party/nss/BUILD.gn", "repo_id": "engine", "token_count": 25155 }
140
#!/usr/bin/env python3 # # 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 argparse import json import os import stat import sys import zipfile def _zip_dir(path, zip_file, prefix): path = path.rstrip('/\\') for root, directories, files in os.walk(path): for directory in directories: if os.path.islink(os.path.join(root, directory)): add_symlink( zip_file, os.path.join(root, directory), os.path.join(root.replace(path, prefix), directory), ) for file in files: if os.path.islink(os.path.join(root, file)): add_symlink( zip_file, os.path.join(root, file), os.path.join(root.replace(path, prefix), file) ) continue zip_file.write(os.path.join(root, file), os.path.join(root.replace(path, prefix), file)) def add_symlink(zip_file, source, target): """Adds a symlink to a zip file. Args: zip_file: The ZipFile obj where the symlink will be added. source: The full path to the symlink. target: The target path for the symlink within the zip file. """ zip_info = zipfile.ZipInfo(target) zip_info.create_system = 3 # Unix like system unix_st_mode = ( stat.S_IFLNK | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH ) zip_info.external_attr = unix_st_mode << 16 zip_file.writestr(zip_info, os.readlink(source)) def main(args): zip_file = zipfile.ZipFile(args.output, 'w', zipfile.ZIP_DEFLATED) if args.source_file: with open(args.source_file) as source_file: file_dict_list = json.load(source_file) for file_dict in file_dict_list: if os.path.islink(file_dict['source']): add_symlink(zip_file, file_dict['source'], file_dict['destination']) continue if os.path.isdir(file_dict['source']): _zip_dir(file_dict['source'], zip_file, file_dict['destination']) else: zip_file.write(file_dict['source'], file_dict['destination']) else: for path, archive_name in args.input_pairs: if os.path.islink(path): add_symlink(zip_file, path, archive_name) continue if os.path.isdir(path): _zip_dir(path, zip_file, archive_name) else: zip_file.write(path, archive_name) zip_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='This script creates zip files.') parser.add_argument('-o', dest='output', action='store', help='The name of the output zip file.') parser.add_argument( '-i', dest='input_pairs', nargs=2, action='append', help='The input file and its destination location in the zip archive.' ) parser.add_argument( '-f', dest='source_file', action='store', help='The path to the file list to zip.' ) sys.exit(main(parser.parse_args()))
engine/build/zip.py/0
{ "file_path": "engine/build/zip.py", "repo_id": "engine", "token_count": 1259 }
141
// 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. // Checks and fixes format on files with changes. // // Run with --help for usage. import 'dart:io'; import 'package:args/args.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'package:process/process.dart'; import 'package:process_runner/process_runner.dart'; class FormattingException implements Exception { FormattingException(this.message, [this.result]); final String message; final ProcessResult? result; @override String toString() { final StringBuffer output = StringBuffer(runtimeType.toString()); output.write(': $message'); final String? stderr = result?.stderr as String?; if (stderr?.isNotEmpty ?? false) { output.write(':\n$stderr'); } return output.toString(); } } enum MessageType { message, error, warning, } enum FormatCheck { gn, java, python, whitespace, header, // Run clang after the header check. clang, } FormatCheck nameToFormatCheck(String name) { switch (name) { case 'clang': return FormatCheck.clang; case 'gn': return FormatCheck.gn; case 'java': return FormatCheck.java; case 'python': return FormatCheck.python; case 'whitespace': return FormatCheck.whitespace; case 'header': return FormatCheck.header; default: throw FormattingException('Unknown FormatCheck type $name'); } } String formatCheckToName(FormatCheck check) { switch (check) { case FormatCheck.clang: return 'C++/ObjC/Shader'; case FormatCheck.gn: return 'GN'; case FormatCheck.java: return 'Java'; case FormatCheck.python: return 'Python'; case FormatCheck.whitespace: return 'Trailing whitespace'; case FormatCheck.header: return 'Header guards'; } } List<String> formatCheckNames() { return FormatCheck.values .map<String>((FormatCheck check) => check.toString().replaceFirst('$FormatCheck.', '')) .toList(); } Future<String> _runGit( List<String> args, ProcessRunner processRunner, { bool failOk = false, }) async { final ProcessRunnerResult result = await processRunner.runProcess( <String>['git', ...args], failOk: failOk, ); return result.stdout; } typedef MessageCallback = void Function(String? message, {MessageType type}); /// Base class for format checkers. /// /// Provides services that all format checkers need. abstract class FormatChecker { FormatChecker({ ProcessManager processManager = const LocalProcessManager(), required this.baseGitRef, required this.repoDir, this.allFiles = false, this.messageCallback, }) : _processRunner = ProcessRunner( defaultWorkingDirectory: repoDir, processManager: processManager, ); /// Factory method that creates subclass format checkers based on the type of check. factory FormatChecker.ofType( FormatCheck check, { ProcessManager processManager = const LocalProcessManager(), required String baseGitRef, required Directory repoDir, required Directory srcDir, bool allFiles = false, MessageCallback? messageCallback, }) { switch (check) { case FormatCheck.clang: return ClangFormatChecker( processManager: processManager, baseGitRef: baseGitRef, repoDir: repoDir, srcDir: srcDir, allFiles: allFiles, messageCallback: messageCallback, ); case FormatCheck.gn: return GnFormatChecker( processManager: processManager, baseGitRef: baseGitRef, repoDir: repoDir, allFiles: allFiles, messageCallback: messageCallback, ); case FormatCheck.java: return JavaFormatChecker( processManager: processManager, baseGitRef: baseGitRef, repoDir: repoDir, srcDir: srcDir, allFiles: allFiles, messageCallback: messageCallback, ); case FormatCheck.python: return PythonFormatChecker( processManager: processManager, baseGitRef: baseGitRef, repoDir: repoDir, allFiles: allFiles, messageCallback: messageCallback, ); case FormatCheck.whitespace: return WhitespaceFormatChecker( processManager: processManager, baseGitRef: baseGitRef, repoDir: repoDir, allFiles: allFiles, messageCallback: messageCallback, ); case FormatCheck.header: return HeaderFormatChecker( processManager: processManager, baseGitRef: baseGitRef, repoDir: repoDir, allFiles: allFiles, messageCallback: messageCallback, ); } } final ProcessRunner _processRunner; final Directory repoDir; final bool allFiles; MessageCallback? messageCallback; final String baseGitRef; /// Override to provide format checking for a specific type. Future<bool> checkFormatting(); /// Override to provide format fixing for a specific type. Future<bool> fixFormatting(); @protected void message(String? string) => messageCallback?.call(string, type: MessageType.message); @protected void error(String string) => messageCallback?.call(string, type: MessageType.error); @protected Future<String> runGit(List<String> args) async => _runGit(args, _processRunner); /// Converts a given raw string of code units to a stream that yields those /// code units. /// /// Uses to convert the stdout of a previous command into an input stream for /// the next command. @protected Stream<List<int>> codeUnitsAsStream(List<int>? input) async* { if (input != null) { yield input; } } @protected Future<bool> applyPatch(List<String> patches) async { final ProcessPool patchPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('patch'), ); final List<WorkerJob> jobs = patches.map<WorkerJob>((String patch) { return WorkerJob( <String>['git', 'apply', '--ignore-space-change'], stdinRaw: codeUnitsAsStream(patch.codeUnits), ); }).toList(); final List<WorkerJob> completedJobs = await patchPool.runToCompletion(jobs); if (patchPool.failedJobs != 0) { error('${patchPool.failedJobs} patch${patchPool.failedJobs > 1 ? 'es' : ''} ' 'failed to apply.'); completedJobs .where((WorkerJob job) => job.result.exitCode != 0) .map<String>((WorkerJob job) => job.result.output) .forEach(message); } return patchPool.failedJobs == 0; } /// Gets the list of files to operate on. /// /// If [allFiles] is true, then returns all git controlled files in the repo /// of the given types. /// /// If [allFiles] is false, then only return those files of the given types /// that have changed between the current working tree and the [baseGitRef]. @protected Future<List<String>> getFileList(List<String> types) async { String output; if (allFiles) { output = await runGit(<String>[ 'ls-files', '--', ...types, ]); } else { output = await runGit(<String>[ 'diff', '-U0', '--no-color', '--diff-filter=d', '--name-only', baseGitRef, '--', ...types, ]); } return output.split('\n').where( (String line) => line.isNotEmpty && !line.contains('third_party') ).toList(); } /// Generates a reporting function to supply to ProcessRunner to use instead /// of the default reporting function. @protected ProcessPoolProgressReporter namedReport(String name) { return (int total, int completed, int inProgress, int pending, int failed) { final String percent = total == 0 ? '100' : ((100 * completed) ~/ total).toString().padLeft(3); final String completedStr = completed.toString().padLeft(3); final String totalStr = total.toString().padRight(3); final String inProgressStr = inProgress.toString().padLeft(2); final String pendingStr = pending.toString().padLeft(3); final String failedStr = failed.toString().padLeft(3); stdout.write('$name Jobs: $percent% done, ' '$completedStr/$totalStr completed, ' '$inProgressStr in progress, ' '$pendingStr pending, ' '$failedStr failed.${' ' * 20}\r'); }; } /// Clears the last printed report line so garbage isn't left on the terminal. @protected void reportDone() { stdout.write('\r${' ' * 100}\r'); } } /// Checks and formats C++/ObjC/Shader files using clang-format. class ClangFormatChecker extends FormatChecker { ClangFormatChecker({ super.processManager, required super.baseGitRef, required super.repoDir, required Directory srcDir, super.allFiles, super.messageCallback, }) { /*late*/ String clangOs; if (Platform.isLinux) { clangOs = 'linux-x64'; } else if (Platform.isMacOS) { clangOs = 'mac-x64'; } else if (Platform.isWindows) { clangOs = 'windows-x64'; } else { throw FormattingException( "Unknown operating system: don't know how to run clang-format here."); } clangFormat = File( path.join( srcDir.absolute.path, 'buildtools', clangOs, 'clang', 'bin', 'clang-format', ), ); } late final File clangFormat; @override Future<bool> checkFormatting() async { final List<String> failures = await _getCFormatFailures(); failures.map(stdout.writeln); return failures.isEmpty; } @override Future<bool> fixFormatting() async { message('Fixing C++/ObjC/Shader formatting...'); final List<String> failures = await _getCFormatFailures(fixing: true); if (failures.isEmpty) { return true; } return applyPatch(failures); } Future<String> _getClangFormatVersion() async { final ProcessRunnerResult result = await _processRunner.runProcess(<String>[clangFormat.path, '--version']); return result.stdout.trim(); } Future<List<String>> _getCFormatFailures({bool fixing = false}) async { message('Checking C++/ObjC/Shader formatting...'); const List<String> clangFiletypes = <String>[ '*.c', '*.cc', '*.cxx', '*.cpp', '*.h', '*.m', '*.mm', '*.glsl', '*.hlsl', '*.comp', '*.tese', '*.tesc', '*.vert', '*.frag', ]; final List<String> files = await getFileList(clangFiletypes); if (files.isEmpty) { message('No C++/ObjC/Shader files with changes, skipping C++/ObjC/Shader format check.'); return <String>[]; } if (verbose) { message('Using ${await _getClangFormatVersion()}'); } final List<WorkerJob> clangJobs = <WorkerJob>[]; for (final String file in files) { if (file.trim().isEmpty) { continue; } clangJobs.add(WorkerJob(<String>[clangFormat.path, '--style=file', file.trim()])); } final ProcessPool clangPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('clang-format'), ); final Stream<WorkerJob> completedClangFormats = clangPool.startWorkers(clangJobs); final List<WorkerJob> diffJobs = <WorkerJob>[]; await for (final WorkerJob completedJob in completedClangFormats) { if (completedJob.result.exitCode == 0) { diffJobs.add( WorkerJob(<String>[ 'git', 'diff', '--no-index', '--no-color', '--ignore-cr-at-eol', '--', completedJob.command.last, '-', ], stdinRaw: codeUnitsAsStream(completedJob.result.stdoutRaw)), ); } else { final String formatterCommand = completedJob.command.join(' '); error("Formatter command '$formatterCommand' failed with exit code " '${completedJob.result.exitCode}. Command output follows:\n\n' '${completedJob.result.output}'); } } final ProcessPool diffPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('diff'), ); final List<WorkerJob> completedDiffs = await diffPool.runToCompletion(diffJobs); final Iterable<WorkerJob> failed = completedDiffs.where((WorkerJob job) { return job.result.exitCode != 0; }); reportDone(); if (failed.isNotEmpty) { final bool plural = failed.length > 1; if (fixing) { message('Fixing ${failed.length} C++/ObjC/Shader file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); } else { error('Found ${failed.length} C++/ObjC/Shader file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); stdout.writeln('To fix, run `et format` or:'); stdout.writeln(); stdout.writeln('git apply <<DONE'); for (final WorkerJob job in failed) { stdout.write(job.result.stdout .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}') .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}')); } stdout.writeln('DONE'); stdout.writeln(); } } else { message('Completed checking ${diffJobs.length} C++/ObjC/Shader files with no formatting problems.'); } return failed.map<String>((WorkerJob job) { return job.result.stdout .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}') .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}'); }).toList(); } } /// Checks the format of Java files uing the Google Java format checker. class JavaFormatChecker extends FormatChecker { JavaFormatChecker({ super.processManager, required super.baseGitRef, required super.repoDir, required Directory srcDir, super.allFiles, super.messageCallback, }) { googleJavaFormatJar = File( path.absolute( path.join( srcDir.absolute.path, 'third_party', 'android_tools', 'google-java-format', 'google-java-format-1.7-all-deps.jar', ), ), ); } late final File googleJavaFormatJar; Future<String> _getGoogleJavaFormatVersion() async { final ProcessRunnerResult result = await _processRunner .runProcess(<String>['java', '-jar', googleJavaFormatJar.path, '--version']); return result.stderr.trim(); } @override Future<bool> checkFormatting() async { final List<String> failures = await _getJavaFormatFailures(); failures.map(stdout.writeln); return failures.isEmpty; } @override Future<bool> fixFormatting() async { message('Fixing Java formatting...'); final List<String> failures = await _getJavaFormatFailures(fixing: true); if (failures.isEmpty) { return true; } return applyPatch(failures); } Future<String> _getJavaVersion() async { final ProcessRunnerResult result = await _processRunner.runProcess(<String>['java', '-version']); return result.stderr.trim().split('\n')[0]; } Future<List<String>> _getJavaFormatFailures({bool fixing = false}) async { message('Checking Java formatting...'); final List<WorkerJob> formatJobs = <WorkerJob>[]; final List<String> files = await getFileList(<String>['*.java']); if (files.isEmpty) { message('No Java files with changes, skipping Java format check.'); return <String>[]; } String javaVersion = '<unknown>'; String javaFormatVersion = '<unknown>'; try { javaVersion = await _getJavaVersion(); } on ProcessRunnerException { error('Cannot run Java, skipping Java file formatting!'); return const <String>[]; } try { javaFormatVersion = await _getGoogleJavaFormatVersion(); } on ProcessRunnerException { error('Cannot find google-java-format, skipping Java format check.'); return const <String>[]; } if (verbose) { message('Using $javaFormatVersion with Java $javaVersion'); } for (final String file in files) { if (file.trim().isEmpty) { continue; } formatJobs.add( WorkerJob( <String>['java', '-jar', googleJavaFormatJar.path, file.trim()], ), ); } final ProcessPool formatPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('Java format'), ); final Stream<WorkerJob> completedJavaFormats = formatPool.startWorkers(formatJobs); final List<WorkerJob> diffJobs = <WorkerJob>[]; await for (final WorkerJob completedJob in completedJavaFormats) { if (completedJob.result.exitCode == 0) { diffJobs.add( WorkerJob( <String>[ 'git', 'diff', '--no-index', '--no-color', '--ignore-cr-at-eol', '--', completedJob.command.last, '-', ], stdinRaw: codeUnitsAsStream(completedJob.result.stdoutRaw), ), ); } else { final String formatterCommand = completedJob.command.join(' '); error("Formatter command '$formatterCommand' failed with exit code " '${completedJob.result.exitCode}. Command output follows:\n\n' '${completedJob.result.output}'); } } final ProcessPool diffPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('diff'), ); final List<WorkerJob> completedDiffs = await diffPool.runToCompletion(diffJobs); final Iterable<WorkerJob> failed = completedDiffs.where((WorkerJob job) { return job.result.exitCode != 0; }); reportDone(); if (failed.isNotEmpty) { final bool plural = failed.length > 1; if (fixing) { error('Fixing ${failed.length} Java file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); } else { error('Found ${failed.length} Java file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); stdout.writeln('To fix, run `et format` or:'); stdout.writeln(); stdout.writeln('git apply <<DONE'); for (final WorkerJob job in failed) { stdout.write(job.result.stdout .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}') .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}')); } stdout.writeln('DONE'); stdout.writeln(); } } else { message('Completed checking ${diffJobs.length} Java files with no formatting problems.'); } return failed.map<String>((WorkerJob job) { return job.result.stdout .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}') .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}'); }).toList(); } } /// Checks the format of any BUILD.gn files using the "gn format" command. class GnFormatChecker extends FormatChecker { GnFormatChecker({ super.processManager, required super.baseGitRef, required Directory repoDir, super.allFiles, super.messageCallback, }) : super( repoDir: repoDir, ) { gnBinary = File( path.join( repoDir.absolute.path, 'third_party', 'gn', Platform.isWindows ? 'gn.exe' : 'gn', ), ); } late final File gnBinary; @override Future<bool> checkFormatting() async { message('Checking GN formatting...'); return (await _runGnCheck(fixing: false)) == 0; } @override Future<bool> fixFormatting() async { message('Fixing GN formatting...'); await _runGnCheck(fixing: true); // The GN script shouldn't fail when fixing errors. return true; } Future<int> _runGnCheck({required bool fixing}) async { final List<String> filesToCheck = await getFileList(<String>['*.gn', '*.gni']); final List<String> cmd = <String>[ gnBinary.path, 'format', if (!fixing) '--stdin', ]; final List<WorkerJob> jobs = <WorkerJob>[]; for (final String file in filesToCheck) { if (fixing) { jobs.add(WorkerJob( <String>[...cmd, file], name: <String>[...cmd, file].join(' '), )); } else { final WorkerJob job = WorkerJob( cmd, stdinRaw: codeUnitsAsStream( File(path.join(repoDir.absolute.path, file)).readAsBytesSync(), ), name: <String>[...cmd, file].join(' '), ); jobs.add(job); } } final ProcessPool gnPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('gn format'), ); final Stream<WorkerJob> completedJobs = gnPool.startWorkers(jobs); final List<WorkerJob> diffJobs = <WorkerJob>[]; await for (final WorkerJob completedJob in completedJobs) { if (completedJob.result.exitCode == 0) { diffJobs.add( WorkerJob( <String>[ 'git', 'diff', '--no-index', '--no-color', '--ignore-cr-at-eol', '--', completedJob.name.split(' ').last, '-' ], stdinRaw: codeUnitsAsStream(completedJob.result.stdoutRaw), ), ); } else { final String formatterCommand = completedJob.command.join(' '); error("Formatter command '$formatterCommand' failed with exit code " '${completedJob.result.exitCode}. Command output follows:\n\n' '${completedJob.result.output}'); } } final ProcessPool diffPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('diff'), ); final List<WorkerJob> completedDiffs = await diffPool.runToCompletion(diffJobs); final Iterable<WorkerJob> failed = completedDiffs.where((WorkerJob job) { return job.result.exitCode != 0; }); reportDone(); if (failed.isNotEmpty) { final bool plural = failed.length > 1; if (fixing) { message('Fixed ${failed.length} GN file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); } else { error('Found ${failed.length} GN file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); stdout.writeln('To fix, run `et format` or:'); stdout.writeln(); stdout.writeln('git apply <<DONE'); for (final WorkerJob job in failed) { stdout.write(job.result.stdout .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}') .replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}')); } stdout.writeln('DONE'); stdout.writeln(); } } else { message('Completed checking ${completedDiffs.length} GN files with no ' 'formatting problems.'); } return failed.length; } } /// Checks the format of any .py files using the "yapf" command. class PythonFormatChecker extends FormatChecker { PythonFormatChecker({ super.processManager, required super.baseGitRef, required Directory repoDir, super.allFiles, super.messageCallback, }) : super( repoDir: repoDir, ) { yapfBin = File(path.join( repoDir.absolute.path, 'tools', Platform.isWindows ? 'yapf.bat' : 'yapf.sh', )); _yapfStyle = File(path.join( repoDir.absolute.path, '.style.yapf', )); } late final File yapfBin; late final File _yapfStyle; @override Future<bool> checkFormatting() async { message('Checking Python formatting...'); return (await _runYapfCheck(fixing: false)) == 0; } @override Future<bool> fixFormatting() async { message('Fixing Python formatting...'); await _runYapfCheck(fixing: true); // The yapf script shouldn't fail when fixing errors. return true; } Future<int> _runYapfCheck({required bool fixing}) async { final List<String> filesToCheck = <String>[ ...await getFileList(<String>['*.py']), // Always include flutter/tools/gn. '${repoDir.path}/tools/gn', ]; final List<String> cmd = <String>[ yapfBin.path, '--style', _yapfStyle.path, if (!fixing) '--diff', if (fixing) '--in-place', ]; final List<WorkerJob> jobs = <WorkerJob>[]; for (final String file in filesToCheck) { jobs.add(WorkerJob(<String>[...cmd, file])); } final ProcessPool yapfPool = ProcessPool( processRunner: _processRunner, printReport: namedReport('python format'), ); final List<WorkerJob> completedJobs = await yapfPool.runToCompletion(jobs); reportDone(); final List<String> incorrect = <String>[]; for (final WorkerJob job in completedJobs) { if (job.result.exitCode == 1) { incorrect.add(' ${job.command.last}\n${job.result.output}'); } } if (incorrect.isNotEmpty) { final bool plural = incorrect.length > 1; if (fixing) { message('Fixed ${incorrect.length} python file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly.'); } else { error('Found ${incorrect.length} python file${plural ? 's' : ''}' ' which ${plural ? 'were' : 'was'} formatted incorrectly:'); stdout.writeln('To fix, run `et format` or:'); stdout.writeln(); stdout.writeln('git apply <<DONE'); incorrect.forEach(stdout.writeln); stdout.writeln('DONE'); stdout.writeln(); } } else { message('All python files formatted correctly.'); } return incorrect.length; } } @immutable class _GrepResult { const _GrepResult(this.file, [this.hits = const <String>[], this.lineNumbers = const <int>[]]); bool get isEmpty => hits.isEmpty && lineNumbers.isEmpty; final File file; final List<String> hits; final List<int> lineNumbers; } /// Checks for trailing whitspace in Dart files. class WhitespaceFormatChecker extends FormatChecker { WhitespaceFormatChecker({ super.processManager, required super.baseGitRef, required super.repoDir, super.allFiles, super.messageCallback, }); @override Future<bool> checkFormatting() async { final List<File> failures = await _getWhitespaceFailures(); return failures.isEmpty; } static final RegExp trailingWsRegEx = RegExp(r'[ \t]+$', multiLine: true); @override Future<bool> fixFormatting() async { final List<File> failures = await _getWhitespaceFailures(); if (failures.isNotEmpty) { for (final File file in failures) { stderr.writeln('Fixing $file'); String contents = file.readAsStringSync(); contents = contents.replaceAll(trailingWsRegEx, ''); file.writeAsStringSync(contents); } } return true; } static _GrepResult _hasTrailingWhitespace(File file) { final List<String> hits = <String>[]; final List<int> lineNumbers = <int>[]; int lineNumber = 0; for (final String line in file.readAsLinesSync()) { if (trailingWsRegEx.hasMatch(line)) { hits.add(line); lineNumbers.add(lineNumber); } lineNumber++; } if (hits.isEmpty) { return _GrepResult(file); } return _GrepResult(file, hits, lineNumbers); } Iterable<_GrepResult> _whereHasTrailingWhitespace(Iterable<File> files) { return files.map(_hasTrailingWhitespace); } Future<List<File>> _getWhitespaceFailures() async { final List<String> files = await getFileList(<String>[ '*.c', '*.cc', '*.cpp', '*.cxx', '*.dart', '*.gn', '*.gni', '*.gradle', '*.h', '*.java', '*.json', '*.m', '*.mm', '*.py', '*.sh', '*.yaml', ]); if (files.isEmpty) { message('No files that differ, skipping whitespace check.'); return <File>[]; } message('Checking for trailing whitespace on ${files.length} source ' 'file${files.length > 1 ? 's' : ''}...'); final ProcessPoolProgressReporter reporter = namedReport('whitespace'); final List<_GrepResult> found = <_GrepResult>[]; final int total = files.length; int completed = 0; int inProgress = Platform.numberOfProcessors; int pending = total; int failed = 0; for (final _GrepResult result in _whereHasTrailingWhitespace( files.map<File>( (String file) => File( path.join(repoDir.absolute.path, file), ), ), )) { if (result.isEmpty) { completed++; } else { failed++; found.add(result); } pending--; inProgress = pending < Platform.numberOfProcessors ? pending : Platform.numberOfProcessors; reporter(total, completed, inProgress, pending, failed); } reportDone(); if (found.isNotEmpty) { error('Whitespace check failed. The following files have trailing spaces:'); for (final _GrepResult result in found) { for (int i = 0; i < result.hits.length; ++i) { message(' ${result.file.path}:${result.lineNumbers[i]}:${result.hits[i]}'); } } } else { message('No trailing whitespace found.'); } return found.map<File>((_GrepResult result) => result.file).toList(); } } final class HeaderFormatChecker extends FormatChecker { HeaderFormatChecker({ required super.baseGitRef, required super.repoDir, super.processManager, super.allFiles, super.messageCallback, }); // $ENGINE/third_party/dart/tools/sdks/dart-sdk/bin/dart late final String _dartBin = path.join( repoDir.absolute.parent.path, 'third_party', 'dart', 'tools', 'sdks', 'dart-sdk', 'bin', 'dart', ); // $ENGINE/src/flutter/tools/bin/main.dart late final String _headerGuardCheckBin = path.join( repoDir.absolute.path, 'tools', 'header_guard_check', 'bin', 'main.dart', ); @override Future<bool> checkFormatting() async { final List<String> include = <String>[]; if (!allFiles) { include.addAll(await getFileList(<String>[ '*.h', ])); if (include.isEmpty) { message('No header files with changes, skipping header guard check.'); return true; } } final List<String> args = <String>[ _dartBin, '--disable-dart-dev', _headerGuardCheckBin, ...include.map((String f) => '--include=$f'), ]; // TIP: --exclude is encoded into the tool itself. // see tools/header_guard_check/lib/header_guard_check.dart final ProcessRunnerResult result = await _processRunner.runProcess(args); if (result.exitCode != 0) { error('Header check failed. The following files have incorrect header guards:'); message(result.stdout); return false; } return true; } @override Future<bool> fixFormatting() async { final List<String> include = <String>[]; if (!allFiles) { include.addAll(await getFileList(<String>[ '*.h', ])); if (include.isEmpty) { message('No header files with changes, skipping header guard fix.'); return true; } } final List<String> args = <String>[ _dartBin, '--disable-dart-dev', _headerGuardCheckBin, '--fix', ...include.map((String f) => '--include=$f'), ]; // TIP: --exclude is encoded into the tool itself. // see tools/header_guard_check/lib/header_guard_check.dart final ProcessRunnerResult result = await _processRunner.runProcess(args); if (result.exitCode != 0) { error('Header check fix failed:'); message(result.stdout); return false; } return true; } } Future<String> _getDiffBaseRevision(ProcessManager processManager, Directory repoDir) async { final ProcessRunner processRunner = ProcessRunner( defaultWorkingDirectory: repoDir, processManager: processManager, ); String upstream = 'upstream'; final String upstreamUrl = await _runGit( <String>['remote', 'get-url', upstream], processRunner, failOk: true, ); if (upstreamUrl.isEmpty) { upstream = 'origin'; } await _runGit(<String>['fetch', upstream, 'main'], processRunner); String result = ''; try { // This is the preferred command to use, but developer checkouts often do // not have a clear fork point, so we fall back to just the regular // merge-base in that case. result = await _runGit( <String>['merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'], processRunner, ); } on ProcessRunnerException { result = await _runGit(<String>['merge-base', 'FETCH_HEAD', 'HEAD'], processRunner); } return result.trim(); } void _usage(ArgParser parser, {int exitCode = 1}) { stderr.writeln('format.dart [--help] [--fix] [--all-files] ' '[--check <${formatCheckNames().join('|')}>]'); stderr.writeln(parser.usage); exit(exitCode); } bool verbose = false; Future<int> main(List<String> arguments) async { final ArgParser parser = ArgParser(); parser.addFlag('help', help: 'Print help.', abbr: 'h'); parser.addFlag('fix', abbr: 'f', help: 'Instead of just checking for formatting errors, fix them in place.'); parser.addFlag('all-files', abbr: 'a', help: 'Instead of just checking for formatting errors in changed files, ' 'check for them in all files.'); parser.addMultiOption('check', abbr: 'c', allowed: formatCheckNames(), defaultsTo: formatCheckNames(), help: 'Specifies which checks will be performed. Defaults to all checks. ' 'May be specified more than once to perform multiple types of checks. '); parser.addFlag('verbose', help: 'Print verbose output.', defaultsTo: verbose); late final ArgResults options; try { options = parser.parse(arguments); } on FormatException catch (e) { stderr.writeln('ERROR: $e'); _usage(parser, exitCode: 0); } verbose = options['verbose'] as bool; if (options['help'] as bool) { _usage(parser, exitCode: 0); } final File script = File.fromUri(Platform.script).absolute; final Directory repoDir = script.parent.parent.parent; final Directory srcDir = repoDir.parent; if (verbose) { stderr.writeln('Repo: $repoDir'); stderr.writeln('Src: $srcDir'); } void message(String? message, {MessageType type = MessageType.message}) { message ??= ''; switch (type) { case MessageType.message: stdout.writeln(message); case MessageType.error: stderr.writeln('ERROR: $message'); case MessageType.warning: stderr.writeln('WARNING: $message'); } } const ProcessManager processManager = LocalProcessManager(); final String baseGitRef = await _getDiffBaseRevision(processManager, repoDir); bool result = true; final List<String> checks = options['check'] as List<String>; try { for (final String checkName in checks) { final FormatCheck check = nameToFormatCheck(checkName); final String humanCheckName = formatCheckToName(check); final FormatChecker checker = FormatChecker.ofType(check, baseGitRef: baseGitRef, repoDir: repoDir, srcDir: srcDir, allFiles: options['all-files'] as bool, messageCallback: message); bool stepResult; if (options['fix'] as bool) { message('Fixing any $humanCheckName format problems'); stepResult = await checker.fixFormatting(); if (!stepResult) { message('Unable to apply $humanCheckName format fixes.'); } } else { stepResult = await checker.checkFormatting(); } result = result && stepResult; } } on FormattingException catch (e) { message('ERROR: $e', type: MessageType.error); } exit(result ? 0 : 1); }
engine/ci/bin/format.dart/0
{ "file_path": "engine/ci/bin/format.dart", "repo_id": "engine", "token_count": 14665 }
142
{ "builds": [ { "drone_dimensions": [ "os=Mac-13", "os=Linux" ], "gn": [ "--runtime-mode", "debug", "--android", "--android-cpu=arm64", "--no-stripped", "--no-lto" ], "name": "android_debug_arm64", "ninja": { "config": "android_debug_arm64", "targets": [] } }, { "drone_dimensions": [ "os=Mac-13", "os=Linux" ], "gn": [ "--runtime-mode", "debug", "--unoptimized", "--android", "--android-cpu=arm64", "--no-stripped", "--no-lto" ], "name": "android_debug_unopt_arm64", "ninja": { "config": "android_debug_unopt_arm64", "targets": [] } }, { "drone_dimensions": [ "os=Mac-13", "os=Linux" ], "gn": [ "--runtime-mode", "profile", "--android", "--android-cpu=arm64", "--no-stripped", "--no-lto" ], "name": "android_profile_arm64", "ninja": { "config": "android_profile_arm64", "targets": [] } }, { "drone_dimensions": [ "os=Mac-13", "os=Linux" ], "gn": [ "--runtime-mode", "release", "--android", "--android-cpu=arm64", "--no-stripped", "--no-lto" ], "name": "android_release_arm64", "ninja": { "config": "android_release_arm64", "targets": [] } }, { "drone_dimensions": [ "os=Mac-13", "os=Linux" ], "gn": [ "--runtime-mode", "debug", "--no-stripped", "--no-lto" ], "name": "host_debug", "ninja": { "config": "host_debug", "targets": [] } }, { "drone_dimensions": [ "os=Mac-13", "os=Linux" ], "gn": [ "--runtime-mode", "profile", "--no-stripped", "--no-lto" ], "name": "host_profile", "ninja": { "config": "host_profile", "targets": [] } }, { "drone_dimensions": [ "os=Mac-13", "os=Linux" ], "gn": [ "--runtime-mode", "release", "--no-stripped", "--no-lto" ], "name": "host_release", "ninja": { "config": "host_release", "targets": [] } } ] }
engine/ci/builders/local_engine.json/0
{ "file_path": "engine/ci/builders/local_engine.json", "repo_id": "engine", "token_count": 1525 }
143
#!/usr/bin/env python3 # # 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 argparse import glob import re import os import subprocess import sys from compatibility_helper import byte_str_decode if 'STORAGE_BUCKET' not in os.environ: print('The GCP storage bucket must be provided as an environment variable.') sys.exit(1) BUCKET = os.environ['STORAGE_BUCKET'] if 'GCP_PROJECT' not in os.environ: print('The GCP project must be provided as an environment variable.') sys.exit(1) PROJECT = os.environ['GCP_PROJECT'] # Exit codes returned by the FTL command that signal an infrastructure failure. FTL_INFRA_FAILURE_CODES = [1, 15, 20] # Maximum number of retries done if an infrastructure failure occurs. MAX_RETRY_ATTEMPTS = 2 script_dir = os.path.dirname(os.path.realpath(__file__)) buildroot_dir = os.path.abspath(os.path.join(script_dir, '..', '..')) out_dir = os.path.join(buildroot_dir, 'out') error_re = re.compile(r'[EF]/flutter.+') def run_firebase_test(apk, results_dir): # game-loop tests are meant for OpenGL apps. # This type of test will give the application a handle to a file, and # we'll write the timeline JSON to that file. # See https://firebase.google.com/docs/test-lab/android/game-loop # Pixel 5. As of this commit, this is a highly available device in FTL. process = subprocess.Popen( [ 'gcloud', '--project', PROJECT, 'firebase', 'test', 'android', 'run', '--type', 'game-loop', '--app', apk, '--timeout', '2m', '--results-bucket', BUCKET, '--results-dir', results_dir, '--device', 'model=shiba,version=34', ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, ) return process def check_logcat(results_dir): logcat = subprocess.check_output(['gsutil', 'cat', '%s/%s/*/logcat' % (BUCKET, results_dir)]) logcat = byte_str_decode(logcat) if not logcat: sys.exit(1) logcat_matches = error_re.findall(logcat) if logcat_matches: print('Errors in logcat:') print(logcat_matches) sys.exit(1) def check_timeline(results_dir): gsutil_du = subprocess.check_output([ 'gsutil', 'du', '%s/%s/*/game_loop_results/results_scenario_0.json' % (BUCKET, results_dir) ]) gsutil_du = byte_str_decode(gsutil_du) gsutil_du = gsutil_du.strip() if gsutil_du == '0': print('Failed to produce a timeline.') sys.exit(1) def main(): parser = argparse.ArgumentParser() parser.add_argument( '--variant', dest='variant', action='store', default='android_profile_arm64', help='The engine variant to run tests for.' ) parser.add_argument( '--build-id', default=os.environ.get('SWARMING_TASK_ID', 'local_test'), help='A unique build identifier for this test. Used to sort results in the GCS bucket.' ) args = parser.parse_args() apks_dir = os.path.join(out_dir, args.variant, 'firebase_apks') apks = set(glob.glob('%s/*.apk' % apks_dir)) if not apks: print('No APKs found at %s' % apks_dir) return 1 git_revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=script_dir) git_revision = byte_str_decode(git_revision) git_revision = git_revision.strip() for retry in range(MAX_RETRY_ATTEMPTS): if retry > 0: print('Retrying %s' % apks) results = [] for apk in sorted(apks): results_dir = '%s/%s/%s' % (os.path.basename(apk), git_revision, args.build_id) process = run_firebase_test(apk, results_dir) results.append((apk, results_dir, process)) for apk, results_dir, process in results: print('===== Test output for %s' % apk) for line in iter(process.stdout.readline, ''): print(line.strip()) return_code = process.wait() if return_code in FTL_INFRA_FAILURE_CODES: print('Firebase test %s failed with infrastructure error code: %s' % (apk, return_code)) continue if return_code != 0: print('Firebase test %s failed with code: %s' % (apk, return_code)) sys.exit(return_code) print('Checking logcat for %s' % results_dir) check_logcat(results_dir) # scenario_app produces a timeline, but the android image test does not. if 'scenario' in apk: print('Checking timeline for %s' % results_dir) check_timeline(results_dir) apks.remove(apk) if not apks: break return 0 if __name__ == '__main__': sys.exit(main())
engine/ci/firebase_testlab.py/0
{ "file_path": "engine/ci/firebase_testlab.py", "repo_id": "engine", "token_count": 1985 }
144
#!/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" ) SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")") SRC_DIR="$( cd "$SCRIPT_DIR/../../.." pwd -P )" FLUTTER_DIR="$SRC_DIR/flutter" # Creates a file named `GeneratedPluginRegistrant.java` in the project outside # of it's expected location in shell/platform/android/test/... (where the exact # name and location is required to get loaded). # # This file is typically generated by Flutter tooling and should not exist. echo "Creating file ./src/flutter/GeneratedPluginRegistrant.java" touch "$FLUTTER_DIR/GeneratedPluginRegistrant.java" # Create a trap that, on exit, removes the temp files. function cleanup() { rm -f "$SRC_DIR/third_party/GeneratedPluginRegistrant.java" rm -f "$FLUTTER_DIR/GeneratedPluginRegistrant.java" rm -f "$FLUTTER_DIR/third_party/GeneratedPluginRegistrant.java" } trap cleanup EXIT # Run the ban script, expecting it to fail. # Intercept the output, only check the exit code. "$FLUTTER_DIR/ci/ban_generated_plugin_registrant_java.sh" > /dev/null 2>&1 && { echo "FAIL: ban_generated_plugin_registrant_java did not fail as expected" exit 1 } echo "PASS: ban_generated_plugin_registrant_java failed as expected" # Create a file in SRC_DIR/third_party, that should be OK. echo "Creating file ./src/third_party/GeneratedPluginRegistrant.java" touch "$SRC_DIR/third_party/GeneratedPluginRegistrant.java" # Run the ban script, expecting it to succeed. "$FLUTTER_DIR/ci/ban_generated_plugin_registrant_java.sh" > /dev/null 2>&1 || { echo "PASS: ban_generated_plugin_registrant_java ignored third_party" } # Create a file in SRC_DIR/flutter/third_party, that should be OK too. echo "Creating file ./src/flutter/third_party/GeneratedPluginRegistrant.java" touch "$FLUTTER_DIR/third_party/GeneratedPluginRegistrant.java" # Run the ban script, expecting it to succeed. "$FLUTTER_DIR/ci/ban_generated_plugin_registrant_java.sh" > /dev/null 2>&1 || { echo "PASS: ban_generated_plugin_registrant_java ignored flutter/third_party" }
engine/ci/test/ban_generated_plugin_registrant_java_test.sh/0
{ "file_path": "engine/ci/test/ban_generated_plugin_registrant_java_test.sh", "repo_id": "engine", "token_count": 953 }
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. #ifndef FLUTTER_COMMON_GRAPHICS_PERSISTENT_CACHE_H_ #define FLUTTER_COMMON_GRAPHICS_PERSISTENT_CACHE_H_ #include <memory> #include <mutex> #include <set> #include "flutter/assets/asset_manager.h" #include "flutter/fml/macros.h" #include "flutter/fml/task_runner.h" #include "flutter/fml/unique_fd.h" #include "third_party/skia/include/gpu/GrContextOptions.h" class GrDirectContext; namespace flutter { namespace testing { class ShellTest; } /// A cache of SkData that gets stored to disk. /// /// This is mainly used for Shaders but is also written to by Dart. It is /// thread-safe for reading and writing from multiple threads. class PersistentCache : public GrContextOptions::PersistentCache { public: // Mutable static switch that can be set before GetCacheForProcess. If true, // we'll only read existing caches but not generate new ones. Some clients // (e.g., embedded devices) prefer generating persistent cache files for the // specific device beforehand, and ship them as readonly files in OTA // packages. static bool gIsReadOnly; static PersistentCache* GetCacheForProcess(); static void ResetCacheForProcess(); // This must be called before |GetCacheForProcess|. Otherwise, it won't // affect the cache directory returned by |GetCacheForProcess|. static void SetCacheDirectoryPath(std::string path); // Convert a binary SkData key into a Base32 encoded string. // // This is used to specify persistent cache filenames and service protocol // json keys. static std::string SkKeyToFilePath(const SkData& key); // Allocate a MallocMapping containing the given key and value in the file // format used by the cache. static std::unique_ptr<fml::MallocMapping> BuildCacheObject( const SkData& key, const SkData& data); // Header written into the files used to store cached Skia objects. struct CacheObjectHeader { // A prefix used to identify the cache object file format. static const uint32_t kSignature = 0xA869593F; static const uint32_t kVersion1 = 1; explicit CacheObjectHeader(uint32_t p_key_size) : key_size(p_key_size) {} uint32_t signature = kSignature; uint32_t version = kVersion1; uint32_t key_size; }; ~PersistentCache() override; void AddWorkerTaskRunner(const fml::RefPtr<fml::TaskRunner>& task_runner); void RemoveWorkerTaskRunner(const fml::RefPtr<fml::TaskRunner>& task_runner); // Whether Skia tries to store any shader into this persistent cache after // |ResetStoredNewShaders| is called. This flag is usually reset before each // frame so we can know if Skia tries to compile new shaders in that frame. bool StoredNewShaders() const { return stored_new_shaders_; } void ResetStoredNewShaders() { stored_new_shaders_ = false; } void DumpSkp(const SkData& data); bool IsDumpingSkp() const { return is_dumping_skp_; } void SetIsDumpingSkp(bool value) { is_dumping_skp_ = value; } // Remove all files inside the persistent cache directory. // Return whether the purge is successful. bool Purge(); // |GrContextOptions::PersistentCache| sk_sp<SkData> load(const SkData& key) override; struct SkSLCache { sk_sp<SkData> key; sk_sp<SkData> value; }; /// Load all the SkSL shader caches in the right directory. std::vector<SkSLCache> LoadSkSLs() const; //---------------------------------------------------------------------------- /// @brief Precompile SkSLs packaged with the application and gathered /// during previous runs in the given context. /// /// @warning The context must be the rendering context. This context may be /// destroyed during application suspension and subsequently /// recreated. The SkSLs must be precompiled again in the new /// context. /// /// @param context The rendering context to precompile shaders in. /// /// @return The number of SkSLs precompiled. /// size_t PrecompileKnownSkSLs(GrDirectContext* context) const; // Return mappings for all skp's accessible through the AssetManager std::vector<std::unique_ptr<fml::Mapping>> GetSkpsFromAssetManager() const; /// Set the asset manager from which PersistentCache can load SkLSs. A nullptr /// can be provided to clear the asset manager. static void SetAssetManager(std::shared_ptr<AssetManager> value); static std::shared_ptr<AssetManager> asset_manager() { return asset_manager_; } static bool cache_sksl() { return cache_sksl_; } static void SetCacheSkSL(bool value); static void MarkStrategySet() { strategy_set_ = true; } static constexpr char kSkSLSubdirName[] = "sksl"; static constexpr char kAssetFileName[] = "io.flutter.shaders.json"; private: static std::string cache_base_path_; static std::shared_ptr<AssetManager> asset_manager_; static std::mutex instance_mutex_; static std::unique_ptr<PersistentCache> gPersistentCache; // Mutable static switch that can be set before GetCacheForProcess is called // and GrContextOptions.fShaderCacheStrategy is set. If true, it means that // we'll set `GrContextOptions::fShaderCacheStrategy` to `kSkSL`, and all the // persistent cache should be stored and loaded from the "sksl" directory. static std::atomic<bool> cache_sksl_; // Guard flag to make sure that cache_sksl_ is not modified after // strategy_set_ becomes true. static std::atomic<bool> strategy_set_; const bool is_read_only_; const std::shared_ptr<fml::UniqueFD> cache_directory_; const std::shared_ptr<fml::UniqueFD> sksl_cache_directory_; mutable std::mutex worker_task_runners_mutex_; std::multiset<fml::RefPtr<fml::TaskRunner>> worker_task_runners_; bool stored_new_shaders_ = false; bool is_dumping_skp_ = false; static SkSLCache LoadFile(const fml::UniqueFD& dir, const std::string& file_name, bool need_key); bool IsValid() const; explicit PersistentCache(bool read_only = false); // |GrContextOptions::PersistentCache| void store(const SkData& key, const SkData& data) override; fml::RefPtr<fml::TaskRunner> GetWorkerTaskRunner() const; friend class testing::ShellTest; FML_DISALLOW_COPY_AND_ASSIGN(PersistentCache); }; } // namespace flutter #endif // FLUTTER_COMMON_GRAPHICS_PERSISTENT_CACHE_H_
engine/common/graphics/persistent_cache.h/0
{ "file_path": "engine/common/graphics/persistent_cache.h", "repo_id": "engine", "token_count": 2079 }
146
// 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_metal.h" // The numbers and weightings used in this file stem from taking the // data from the DisplayListBenchmarks suite run on an iPhone 12 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 { DisplayListMetalComplexityCalculator* DisplayListMetalComplexityCalculator::instance_ = nullptr; DisplayListMetalComplexityCalculator* DisplayListMetalComplexityCalculator::GetInstance() { if (instance_ == nullptr) { instance_ = new DisplayListMetalComplexityCalculator(); } return instance_; } unsigned int DisplayListMetalComplexityCalculator::MetalHelper::BatchedComplexity() { // Calculate the impact of saveLayer. unsigned int save_layer_complexity; if (save_layer_count_ == 0) { save_layer_complexity = 0; } else { // saveLayer seems to have two trends; if the count is < 200, // then the individual cost of a saveLayer is higher than if // the count is > 200. // // However, the trend is strange and we should gather more data to // get a better idea of how to represent the trend. That being said, it's // very unlikely we'll ever hit a DisplayList with 200+ saveLayer calls // in it, so we will calculate based on the more reasonably anticipated // range of less than 200, with the trend line more weighted towards the // lower end of that range (as the data itself doesn't present as a straight // line). Further, we will easily hit our cache thresholds with such a // large number of saveLayer calls. // // m = 1/2 // c = 1 save_layer_complexity = (save_layer_count_ + 2) * 100000; } unsigned int draw_text_blob_complexity; if (draw_text_blob_count_ == 0) { draw_text_blob_complexity = 0; } else { // m = 1/240 // c = 0.75 draw_text_blob_complexity = (draw_text_blob_count_ + 180) * 2500 / 3; } return save_layer_complexity + draw_text_blob_complexity; } void DisplayListMetalComplexityCalculator::MetalHelper::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 DisplayListMetalComplexityCalculator::MetalHelper::drawLine( const SkPoint& p0, const SkPoint& p1) { if (IsComplex()) { return; } // The curve here may be log-linear, although it doesn't really match up that // well. To avoid costly computations, try and do a best fit of the data onto // a linear graph as a very rough first order approximation. float non_hairline_penalty = 1.0f; float aa_penalty = 1.0f; if (!IsHairline()) { non_hairline_penalty = 1.15f; } if (IsAntiAliased()) { aa_penalty = 1.4f; } // 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/45 // c = 5 unsigned int complexity = ((distance + 225) * 4 / 9) * non_hairline_penalty * aa_penalty; AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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 real penalty at smaller lengths, // but it increases at larger lengths. There isn't enough data to get a good // idea of the penalty at lengths > 1000px. // // 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/9000 // c = 0 complexity = area / 225; } else { // Take the average of the width and height. unsigned int length = (rect.width() + rect.height()) / 2; // There is a penalty for AA being *disabled*. if (IsAntiAliased()) { // m = 1/65 // c = 0 complexity = length * 8 / 13; } else { // m = 1/35 // c = 0 complexity = length * 8 / 7; } } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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/16000 // c = 0 complexity = area / 80; } else { if (IsAntiAliased()) { // m = 1/7500 // c = 0 complexity = area * 2 / 75; } else { // Take the average of the width and height. unsigned int length = (bounds.width() + bounds.height()) / 2; // m = 1/80 // c = 0 complexity = length * 5 / 2; } } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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/1300 // c = 5 complexity = (area + 6500) * 2 / 65; // Penalty of around 5% when AA is disabled. if (!IsAntiAliased()) { complexity *= 1.05f; } } else { // Hairline vs non-hairline has no significant performance difference. if (IsAntiAliased()) { // m = 1/7 // c = 7 complexity = (radius + 49) * 40 / 7; } else { // m = 1/16 // c = 8 complexity = (radius + 128) * 5 / 2; } } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::drawRRect( const SkRRect& rrect) { if (IsComplex()) { return; } // RRects scale linearly with the area of the bounding rect. unsigned int area = rrect.width() * rrect.height(); // Drawing RRects is split into two performance tiers; an expensive // one and a less expensive one. Both scale linearly with area. // // Expensive: All filled style, symmetric w/AA. bool expensive = (DrawStyle() == DlDrawStyle::kFill) || ((rrect.getType() == SkRRect::Type::kSimple_Type) && IsAntiAliased()); 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 (expensive) { // m = 1/25000 // c = 2 // An area of 7000px^2 ~= baseline timing of 0.0005ms. complexity = (area + 10500) / 175; } else { // m = 1/7000 // c = 1.5 // An area of 16000px^2 ~= baseline timing of 0.0005ms. complexity = (area + 50000) / 625; } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::drawDRRect( const SkRRect& outer, const SkRRect& inner) { if (IsComplex()) { return; } // There are roughly four classes here: // a) Filled style with AA enabled. // b) Filled style with AA disabled. // c) Complex RRect type with AA enabled and filled style. // d) Everything else. // // a) and c) scale linearly with the area, b) and d) scale linearly with // a single dimension (length). In all cases, the dimensions refer to // the outer RRect. unsigned int length = (outer.width() + outer.height()) / 2; 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/1000 // c = 1 complexity = (area + 1000) / 10; } else { if (IsAntiAliased()) { // m = 1/3500 // c = 1.5 complexity = (area + 5250) / 35; } else { // m = 1/30 // c = 1 complexity = (300 + (10 * length)) / 3; } } } else { // m = 1/60 // c = 1.75 complexity = ((10 * length) + 1050) / 6; } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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; if (IsAntiAliased()) { line_verb_cost = 75; quad_verb_cost = 100; conic_verb_cost = 160; cubic_verb_cost = 210; } else { line_verb_cost = 67; quad_verb_cost = 80; conic_verb_cost = 140; cubic_verb_cost = 210; } // There seems to be a fixed cost of around 1ms for calling drawPath. unsigned int complexity = 200000 + CalculatePathComplexity(path, line_verb_cost, quad_verb_cost, conic_verb_cost, cubic_verb_cost); AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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 diameter. // Stroked styles with AA scale linearly with the area except for small // values. Filled styles scale linearly with the area. unsigned int diameter = (oval_bounds.width() + oval_bounds.height()) / 2; 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/8500 // c = 16 complexity = (area + 136000) * 2 / 765; } else { // m = 1/60 // c = 3 complexity = (diameter + 180) * 10 / 27; } } else { if (IsAntiAliased()) { // m = 1/20000 // c = 20 complexity = (area + 400000) / 900; } else { // m = 1/2100 // c = 8 complexity = (area + 16800) * 2 / 189; } } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::drawPoints( DlCanvas::PointMode mode, uint32_t count, const SkPoint points[]) { if (IsComplex()) { return; } unsigned int complexity; // If AA is off then they all behave similarly, and scale // linearly with the point count. if (!IsAntiAliased()) { // m = 1/16000 // c = 0.75 complexity = (count + 12000) * 25 / 2; } else { if (mode == DlCanvas::PointMode::kPolygon) { // m = 1/1250 // c = 1 complexity = (count + 1250) * 160; } else { if (IsHairline() && mode == DlCanvas::PointMode::kPoints) { // This is a special case, it triggers an extremely fast path. // m = 1/14500 // c = 0 complexity = count * 400 / 29; } else { // m = 1/2200 // c = 0.75 complexity = (count + 1650) * 1000 / 11; } } } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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/4000 // c = 1 unsigned int complexity = (vertices->vertex_count() + 4000) * 50; AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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 // area of the image. If it needs uploading, the cost scales linearly // with the square of the area (!!!). SkISize dimensions = image->dimensions(); unsigned int area = dimensions.width() * dimensions.height(); // m = 1/17000 // c = 3 unsigned int complexity = (area + 51000) * 4 / 170; 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 / 35000) + 1200 gives a reasonable approximation. float multiplier = area / 35000.0f; complexity = complexity * multiplier + 1200; } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::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. unsigned int area = size.width() * size.height(); // 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) { // Baseline for texture-backed SkImages. // m = 1/23000 // c = 2.3 complexity = (area + 52900) * 2 / 115; if (render_with_attributes && enforce_src_edges && IsAntiAliased()) { // There's about a 30% performance penalty from the baseline. complexity *= 1.3f; } } else { if (render_with_attributes && enforce_src_edges && IsAntiAliased()) { // m = 1/12200 // c = 2.75 complexity = (area + 33550) * 2 / 61; } else { // m = 1/14500 // c = 2.5 complexity = (area + 36250) * 4 / 145; } } AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::drawImageNine( const sk_sp<DlImage> image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) { if (IsComplex()) { return; } // Whether uploading or not, the performance is comparable across all // variations. SkISize dimensions = image->dimensions(); unsigned int area = dimensions.width() * dimensions.height(); // m = 1/8000 // c = 3 unsigned int complexity = (area + 24000) / 20; AccumulateComplexity(complexity); } void DisplayListMetalComplexityCalculator::MetalHelper::drawDisplayList( const sk_sp<DisplayList> display_list, SkScalar opacity) { if (IsComplex()) { return; } MetalHelper 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 DisplayListMetalComplexityCalculator::MetalHelper::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 DisplayListMetalComplexityCalculator::MetalHelper::drawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y) {} void DisplayListMetalComplexityCalculator::MetalHelper::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.05f; } // 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 = 20000; // 0.1ms unsigned int quad_verb_cost = 20000; // 0.1ms unsigned int conic_verb_cost = 20000; // 0.1ms unsigned int cubic_verb_cost = 80000; // 0.4ms unsigned int complexity = 0 + 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_metal.cc/0
{ "file_path": "engine/display_list/benchmarking/dl_complexity_metal.cc", "repo_id": "engine", "token_count": 6861 }
147
// 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_color.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkColor.h" namespace flutter { namespace testing { static void arraysEqual(const uint32_t* ints, const DlColor* colors, int count) { for (int i = 0; i < count; i++) { EXPECT_TRUE(ints[i] == colors[i].argb()); } } TEST(DisplayListColor, ArrayInterchangeableWithUint32) { uint32_t ints[5] = { 0xFF000000, // 0xFFFF0000, // 0xFF00FF00, // 0xFF0000FF, // 0xF1F2F3F4, }; DlColor colors[5] = { DlColor::kBlack(), // DlColor::kRed(), // DlColor::kGreen(), // DlColor::kBlue(), // DlColor(0xF1F2F3F4), }; arraysEqual(ints, colors, 5); arraysEqual(reinterpret_cast<const uint32_t*>(colors), reinterpret_cast<const DlColor*>(ints), 5); } TEST(DisplayListColor, DlColorDirectlyComparesToSkColor) { EXPECT_EQ(DlColor::kBlack(), SK_ColorBLACK); EXPECT_EQ(DlColor::kRed(), SK_ColorRED); EXPECT_EQ(DlColor::kGreen(), SK_ColorGREEN); EXPECT_EQ(DlColor::kBlue(), SK_ColorBLUE); } } // namespace testing } // namespace flutter
engine/display_list/dl_color_unittests.cc/0
{ "file_path": "engine/display_list/dl_color_unittests.cc", "repo_id": "engine", "token_count": 612 }
148
// 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_EFFECTS_DL_COLOR_FILTER_H_ #define FLUTTER_DISPLAY_LIST_EFFECTS_DL_COLOR_FILTER_H_ #include "flutter/display_list/dl_attributes.h" #include "flutter/display_list/dl_blend_mode.h" #include "flutter/display_list/dl_color.h" #include "flutter/fml/logging.h" namespace flutter { class DlBlendColorFilter; class DlMatrixColorFilter; // The DisplayList ColorFilter class. This class implements all of the // facilities and adheres to the design goals of the |DlAttribute| base // class. // An enumerated type for the supported ColorFilter operations. enum class DlColorFilterType { kBlend, kMatrix, kSrgbToLinearGamma, kLinearToSrgbGamma, }; class DlColorFilter : public DlAttribute<DlColorFilter, DlColorFilterType> { public: // Return a boolean indicating whether the color filtering operation will // modify transparent black. This is typically used to determine if applying // the ColorFilter to a temporary saveLayer buffer will turn the surrounding // pixels non-transparent and therefore expand the bounds. virtual bool modifies_transparent_black() const = 0; // Return a boolean indicating whether the color filtering operation can // be applied either before or after modulating the pixels with an opacity // value without changing the operation. virtual bool can_commute_with_opacity() const { return false; } // Return a DlBlendColorFilter pointer to this object iff it is a Blend // type of ColorFilter, otherwise return nullptr. virtual const DlBlendColorFilter* asBlend() const { return nullptr; } // Return a DlMatrixColorFilter pointer to this object iff it is a Matrix // type of ColorFilter, otherwise return nullptr. virtual const DlMatrixColorFilter* asMatrix() const { return nullptr; } // asSrgb<->Linear is not needed because it has no properties to query. // Its type fully specifies its operation. }; // The Blend type of ColorFilter which specifies modifying the // colors as if the color specified in the Blend filter is the // source color and the color drawn by the rendering operation // is the destination color. The mode parameter of the Blend // filter is then used to combine those colors. class DlBlendColorFilter final : public DlColorFilter { public: DlBlendColorFilter(DlColor color, DlBlendMode mode) : color_(color), mode_(mode) {} DlBlendColorFilter(const DlBlendColorFilter& filter) : DlBlendColorFilter(filter.color_, filter.mode_) {} explicit DlBlendColorFilter(const DlBlendColorFilter* filter) : DlBlendColorFilter(filter->color_, filter->mode_) {} static std::shared_ptr<DlColorFilter> Make(DlColor color, DlBlendMode mode); DlColorFilterType type() const override { return DlColorFilterType::kBlend; } size_t size() const override { return sizeof(*this); } bool modifies_transparent_black() const override; bool can_commute_with_opacity() const override; std::shared_ptr<DlColorFilter> shared() const override { return std::make_shared<DlBlendColorFilter>(this); } const DlBlendColorFilter* asBlend() const override { return this; } DlColor color() const { return color_; } DlBlendMode mode() const { return mode_; } protected: bool equals_(DlColorFilter const& other) const override { FML_DCHECK(other.type() == DlColorFilterType::kBlend); auto that = static_cast<DlBlendColorFilter const*>(&other); return color_ == that->color_ && mode_ == that->mode_; } private: DlColor color_; DlBlendMode mode_; }; // The Matrix type of ColorFilter which runs every pixel drawn by // the rendering operation [iR,iG,iB,iA] through a vector/matrix // multiplication, as in: // // [ oR ] [ m[ 0] m[ 1] m[ 2] m[ 3] m[ 4] ] [ iR ] // [ oG ] [ m[ 5] m[ 6] m[ 7] m[ 8] m[ 9] ] [ iG ] // [ oB ] = [ m[10] m[11] m[12] m[13] m[14] ] x [ iB ] // [ oA ] [ m[15] m[16] m[17] m[18] m[19] ] [ iA ] // [ 1 ] // // The resulting color [oR,oG,oB,oA] is then clamped to the range of // valid pixel components before storing in the output. // // The incoming and outgoing [iR,iG,iB,iA] and [oR,oG,oB,oA] are // considered to be non-premultiplied. When working on premultiplied // pixel data, the necessary pre<->non-pre conversions must be performed. class DlMatrixColorFilter final : public DlColorFilter { public: explicit DlMatrixColorFilter(const float matrix[20]) { memcpy(matrix_, matrix, sizeof(matrix_)); } DlMatrixColorFilter(const DlMatrixColorFilter& filter) : DlMatrixColorFilter(filter.matrix_) {} explicit DlMatrixColorFilter(const DlMatrixColorFilter* filter) : DlMatrixColorFilter(filter->matrix_) {} static std::shared_ptr<DlColorFilter> Make(const float matrix[20]); DlColorFilterType type() const override { return DlColorFilterType::kMatrix; } size_t size() const override { return sizeof(*this); } bool modifies_transparent_black() const override; bool can_commute_with_opacity() const override; std::shared_ptr<DlColorFilter> shared() const override { return std::make_shared<DlMatrixColorFilter>(this); } const DlMatrixColorFilter* asMatrix() const override { return this; } const float& operator[](int index) const { return matrix_[index]; } void get_matrix(float matrix[20]) const { memcpy(matrix, matrix_, sizeof(matrix_)); } protected: bool equals_(const DlColorFilter& other) const override { FML_DCHECK(other.type() == DlColorFilterType::kMatrix); auto that = static_cast<DlMatrixColorFilter const*>(&other); return memcmp(matrix_, that->matrix_, sizeof(matrix_)) == 0; } private: float matrix_[20]; }; // The SrgbToLinear type of ColorFilter that applies the inverse of the sRGB // gamma curve to the rendered pixels. class DlSrgbToLinearGammaColorFilter final : public DlColorFilter { public: static const std::shared_ptr<DlSrgbToLinearGammaColorFilter> kInstance; DlSrgbToLinearGammaColorFilter() {} DlSrgbToLinearGammaColorFilter(const DlSrgbToLinearGammaColorFilter& filter) : DlSrgbToLinearGammaColorFilter() {} explicit DlSrgbToLinearGammaColorFilter( const DlSrgbToLinearGammaColorFilter* filter) : DlSrgbToLinearGammaColorFilter() {} DlColorFilterType type() const override { return DlColorFilterType::kSrgbToLinearGamma; } size_t size() const override { return sizeof(*this); } bool modifies_transparent_black() const override { return false; } bool can_commute_with_opacity() const override { return true; } std::shared_ptr<DlColorFilter> shared() const override { return kInstance; } protected: bool equals_(const DlColorFilter& other) const override { FML_DCHECK(other.type() == DlColorFilterType::kSrgbToLinearGamma); return true; } private: friend class DlColorFilter; }; // The LinearToSrgb type of ColorFilter that applies the sRGB gamma curve // to the rendered pixels. class DlLinearToSrgbGammaColorFilter final : public DlColorFilter { public: static const std::shared_ptr<DlLinearToSrgbGammaColorFilter> kInstance; DlLinearToSrgbGammaColorFilter() {} DlLinearToSrgbGammaColorFilter(const DlLinearToSrgbGammaColorFilter& filter) : DlLinearToSrgbGammaColorFilter() {} explicit DlLinearToSrgbGammaColorFilter( const DlLinearToSrgbGammaColorFilter* filter) : DlLinearToSrgbGammaColorFilter() {} DlColorFilterType type() const override { return DlColorFilterType::kLinearToSrgbGamma; } size_t size() const override { return sizeof(*this); } bool modifies_transparent_black() const override { return false; } bool can_commute_with_opacity() const override { return true; } std::shared_ptr<DlColorFilter> shared() const override { return kInstance; } protected: bool equals_(const DlColorFilter& other) const override { FML_DCHECK(other.type() == DlColorFilterType::kLinearToSrgbGamma); return true; } private: friend class DlColorFilter; }; } // namespace flutter #endif // FLUTTER_DISPLAY_LIST_EFFECTS_DL_COLOR_FILTER_H_
engine/display_list/effects/dl_color_filter.h/0
{ "file_path": "engine/display_list/effects/dl_color_filter.h", "repo_id": "engine", "token_count": 2727 }
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. #include "flutter/display_list/geometry/dl_region.h" #include "flutter/fml/logging.h" namespace flutter { // Threshold for switching from linear search through span lines to binary // search. const int kBinarySearchThreshold = 10; DlRegion::SpanBuffer::SpanBuffer(DlRegion::SpanBuffer&& m) : capacity_(m.capacity_), size_(m.size_), spans_(m.spans_) { m.size_ = 0; m.capacity_ = 0; m.spans_ = nullptr; }; DlRegion::SpanBuffer::SpanBuffer(const DlRegion::SpanBuffer& m) : capacity_(m.capacity_), size_(m.size_) { if (m.spans_ == nullptr) { spans_ = nullptr; } else { spans_ = static_cast<Span*>(std::malloc(capacity_ * sizeof(Span))); memcpy(spans_, m.spans_, size_ * sizeof(Span)); } }; DlRegion::SpanBuffer& DlRegion::SpanBuffer::operator=( const DlRegion::SpanBuffer& buffer) { SpanBuffer copy(buffer); std::swap(*this, copy); return *this; } DlRegion::SpanBuffer& DlRegion::SpanBuffer::operator=( DlRegion::SpanBuffer&& buffer) { std::swap(capacity_, buffer.capacity_); std::swap(size_, buffer.size_); std::swap(spans_, buffer.spans_); return *this; } DlRegion::SpanBuffer::~SpanBuffer() { free(spans_); } void DlRegion::SpanBuffer::reserve(size_t capacity) { if (capacity_ < capacity) { spans_ = static_cast<Span*>(std::realloc(spans_, capacity * sizeof(Span))); capacity_ = capacity; } } DlRegion::SpanChunkHandle DlRegion::SpanBuffer::storeChunk(const Span* begin, const Span* end) { size_t chunk_size = end - begin; size_t min_capacity = size_ + chunk_size + 1; if (capacity_ < min_capacity) { size_t new_capacity = std::max(min_capacity, capacity_ * 2); new_capacity = std::max(new_capacity, size_t(512)); reserve(new_capacity); } SpanChunkHandle res = size_; size_ += chunk_size + 1; setChunkSize(res, chunk_size); auto* dst = spans_ + res + 1; memmove(dst, begin, chunk_size * sizeof(Span)); return res; } size_t DlRegion::SpanBuffer::getChunkSize(SpanChunkHandle handle) const { FML_DCHECK(handle < size_); return spans_[handle].left; } void DlRegion::SpanBuffer::setChunkSize(SpanChunkHandle handle, size_t size) { FML_DCHECK(handle < size_); FML_DCHECK(spans_ != nullptr); // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) spans_[handle].left = size; } void DlRegion::SpanBuffer::getSpans(SpanChunkHandle handle, const DlRegion::Span*& begin, const DlRegion::Span*& end) const { FML_DCHECK(handle < size_); begin = spans_ + handle + 1; end = begin + getChunkSize(handle); } DlRegion::DlRegion(const std::vector<SkIRect>& rects) { setRects(rects); } DlRegion::DlRegion(const SkIRect& rect) : bounds_(rect) { Span span{rect.left(), rect.right()}; lines_.push_back(makeLine(rect.top(), rect.bottom(), &span, &span + 1)); } bool DlRegion::spansEqual(SpanLine& line, const Span* begin, const Span* end) const { const Span *our_begin, *our_end; span_buffer_.getSpans(line.chunk_handle, our_begin, our_end); size_t our_size = our_end - our_begin; size_t their_size = end - begin; if (our_size != their_size) { return false; } return memcmp(our_begin, begin, our_size * sizeof(Span)) == 0; } DlRegion::SpanLine DlRegion::makeLine(int32_t top, int32_t bottom, const SpanVec& v) { return makeLine(top, bottom, v.data(), v.data() + v.size()); } DlRegion::SpanLine DlRegion::makeLine(int32_t top, int32_t bottom, const Span* begin, const Span* end) { auto handle = span_buffer_.storeChunk(begin, end); return {top, bottom, handle}; } // Returns number of valid spans in res. For performance reasons res is never // downsized. size_t DlRegion::unionLineSpans(std::vector<Span>& res, const SpanBuffer& a_buffer, SpanChunkHandle a_handle, const SpanBuffer& b_buffer, SpanChunkHandle b_handle) { class OrderedSpanAccumulator { public: explicit OrderedSpanAccumulator(std::vector<Span>& res) : res(res) {} void accumulate(const Span& span) { if (span.left > last_ || len == 0) { res[len++] = span; last_ = span.right; } else if (span.right > last_) { FML_DCHECK(len > 0); res[len - 1].right = span.right; last_ = span.right; } } size_t len = 0; std::vector<Span>& res; private: int32_t last_ = std::numeric_limits<int32_t>::min(); }; const Span *begin1, *end1; a_buffer.getSpans(a_handle, begin1, end1); const Span *begin2, *end2; b_buffer.getSpans(b_handle, begin2, end2); size_t min_size = (end1 - begin1) + (end2 - begin2); if (res.size() < min_size) { res.resize(min_size); } OrderedSpanAccumulator accumulator(res); while (true) { if (begin1->left < begin2->left) { accumulator.accumulate(*begin1++); if (begin1 == end1) { break; } } else { // Either 2 is first, or they are equal, in which case add 2 now // and we might combine 1 with it next time around accumulator.accumulate(*begin2++); if (begin2 == end2) { break; } } } FML_DCHECK(begin1 == end1 || begin2 == end2); while (begin1 < end1) { accumulator.accumulate(*begin1++); } while (begin2 < end2) { accumulator.accumulate(*begin2++); } FML_DCHECK(begin1 == end1 && begin2 == end2); return accumulator.len; } size_t DlRegion::intersectLineSpans(std::vector<Span>& res, const SpanBuffer& a_buffer, SpanChunkHandle a_handle, const SpanBuffer& b_buffer, SpanChunkHandle b_handle) { const Span *begin1, *end1; a_buffer.getSpans(a_handle, begin1, end1); const Span *begin2, *end2; b_buffer.getSpans(b_handle, begin2, end2); // Worst case scenario, interleaved overlapping spans // AAAA BBBB CCCC // XXX YYYY XXXX size_t min_size = (end1 - begin1) + (end2 - begin2) - 1; if (res.size() < min_size) { res.resize(min_size); } // Pointer to the next span to be written. Span* new_span = res.data(); while (begin1 != end1 && begin2 != end2) { if (begin1->right <= begin2->left) { ++begin1; } else if (begin2->right <= begin1->left) { ++begin2; } else { int32_t left = std::max(begin1->left, begin2->left); int32_t right = std::min(begin1->right, begin2->right); FML_DCHECK(left < right); FML_DCHECK(new_span < res.data() + res.size()); *new_span++ = {left, right}; if (begin1->right == right) { ++begin1; } if (begin2->right == right) { ++begin2; } } } return new_span - res.data(); } void DlRegion::setRects(const std::vector<SkIRect>& unsorted_rects) { // setRects can only be called on empty regions. FML_DCHECK(lines_.empty()); size_t count = unsorted_rects.size(); std::vector<const SkIRect*> rects(count); for (size_t i = 0; i < count; i++) { rects[i] = &unsorted_rects[i]; bounds_.join(unsorted_rects[i]); } std::sort(rects.begin(), rects.end(), [](const SkIRect* a, const SkIRect* b) { if (a->top() < b->top()) { return true; } if (a->top() > b->top()) { return false; } return a->left() < b->left(); }); size_t active_end = 0; size_t next_rect = 0; int32_t cur_y = std::numeric_limits<int32_t>::min(); SpanVec working_spans; #ifdef DlRegion_DO_STATS size_t active_rect_count = 0; size_t span_count = 0; int pass_count = 0; int line_count = 0; #endif while (next_rect < count || active_end > 0) { // First prune passed rects out of the active list size_t preserve_end = 0; for (size_t i = 0; i < active_end; i++) { const SkIRect* r = rects[i]; if (r->bottom() > cur_y) { rects[preserve_end++] = r; } } active_end = preserve_end; // If we have no active rects any more, jump to the top of the // next available input rect. if (active_end == 0) { if (next_rect >= count) { // No active rects and no more rects to bring in. We are done. break; } cur_y = rects[next_rect]->top(); } // Next, insert any new rects we've reached into the active list while (next_rect < count) { const SkIRect* r = rects[next_rect]; if (r->isEmpty()) { continue; } if (r->top() > cur_y) { break; } // We now know that we will be inserting this rect into active list next_rect++; size_t insert_at = active_end++; while (insert_at > 0) { const SkIRect* ir = rects[insert_at - 1]; if (ir->left() <= r->left()) { break; } rects[insert_at--] = ir; } rects[insert_at] = r; } // We either preserved some rects in the active list or added more from // the remaining input rects, or we would have exited the loop above. FML_DCHECK(active_end != 0); working_spans.clear(); FML_DCHECK(working_spans.empty()); #ifdef DlRegion_DO_STATS active_rect_count += active_end; pass_count++; #endif // [start_x, end_x) always represents a valid span to be inserted // [cur_y, end_y) is the intersecting range over which all spans are valid int32_t start_x = rects[0]->left(); int32_t end_x = rects[0]->right(); int32_t end_y = rects[0]->bottom(); for (size_t i = 1; i < active_end; i++) { const SkIRect* r = rects[i]; if (r->left() > end_x) { working_spans.emplace_back(start_x, end_x); start_x = r->left(); end_x = r->right(); } else if (end_x < r->right()) { end_x = r->right(); } if (end_y > r->bottom()) { end_y = r->bottom(); } } working_spans.emplace_back(start_x, end_x); // end_y must not pass by the top of the next input rect if (next_rect < count && end_y > rects[next_rect]->top()) { end_y = rects[next_rect]->top(); } // If all of the rules above work out, we should never collapse the // current range of Y coordinates to empty FML_DCHECK(end_y > cur_y); if (!lines_.empty() && lines_.back().bottom == cur_y && spansEqual(lines_.back(), working_spans.data(), working_spans.data() + working_spans.size())) { lines_.back().bottom = end_y; } else { #ifdef DlRegion_DO_STATS span_count += working_spans.size(); line_count++; #endif lines_.push_back(makeLine(cur_y, end_y, working_spans)); } cur_y = end_y; } #ifdef DlRegion_DO_STATS double span_avg = ((double)span_count) / line_count; double active_avg = ((double)active_rect_count) / pass_count; FML_LOG(ERROR) << lines_.size() << " lines for " << count << " input rects, avg " << span_avg << " spans per line and avg " << active_avg << " active rects per loop"; #endif } void DlRegion::appendLine(int32_t top, int32_t bottom, const Span* begin, const Span* end) { if (lines_.empty()) { lines_.push_back(makeLine(top, bottom, begin, end)); } else { if (lines_.back().bottom == top && spansEqual(lines_.back(), begin, end)) { lines_.back().bottom = bottom; } else { lines_.push_back(makeLine(top, bottom, begin, end)); } } } DlRegion DlRegion::MakeUnion(const DlRegion& a, const DlRegion& b) { if (a.isEmpty()) { return b; } else if (b.isEmpty()) { return a; } else if (a.isSimple() && a.bounds_.contains(b.bounds_)) { return a; } else if (b.isSimple() && b.bounds_.contains(a.bounds_)) { return b; } DlRegion res; res.bounds_ = a.bounds_; res.bounds_.join(b.bounds_); res.span_buffer_.reserve(a.span_buffer_.capacity() + b.span_buffer_.capacity()); auto& lines = res.lines_; lines.reserve(a.lines_.size() + b.lines_.size()); auto a_it = a.lines_.begin(); auto b_it = b.lines_.begin(); auto a_end = a.lines_.end(); auto b_end = b.lines_.end(); FML_DCHECK(a_it != a_end && b_it != b_end); auto& a_buffer = a.span_buffer_; auto& b_buffer = b.span_buffer_; std::vector<Span> tmp; int32_t cur_top = std::numeric_limits<int32_t>::min(); while (a_it != a_end && b_it != b_end) { auto a_top = std::max(cur_top, a_it->top); auto b_top = std::max(cur_top, b_it->top); if (a_it->bottom <= b_top) { res.appendLine(a_top, a_it->bottom, a_buffer, a_it->chunk_handle); ++a_it; } else if (b_it->bottom <= a_top) { res.appendLine(b_top, b_it->bottom, b_buffer, b_it->chunk_handle); ++b_it; } else { if (a_top < b_top) { res.appendLine(a_top, b_top, a_buffer, a_it->chunk_handle); cur_top = b_top; if (cur_top == a_it->bottom) { ++a_it; } } else if (b_top < a_top) { res.appendLine(b_top, a_top, b_buffer, b_it->chunk_handle); cur_top = a_top; if (cur_top == b_it->bottom) { ++b_it; } } else { auto new_bottom = std::min(a_it->bottom, b_it->bottom); FML_DCHECK(a_top == b_top); FML_DCHECK(new_bottom > a_top); FML_DCHECK(new_bottom > b_top); auto size = unionLineSpans(tmp, a_buffer, a_it->chunk_handle, b_buffer, b_it->chunk_handle); res.appendLine(a_top, new_bottom, tmp.data(), tmp.data() + size); cur_top = new_bottom; if (cur_top == a_it->bottom) { ++a_it; } if (cur_top == b_it->bottom) { ++b_it; } } } } FML_DCHECK(a_it == a_end || b_it == b_end); while (a_it != a_end) { auto a_top = std::max(cur_top, a_it->top); res.appendLine(a_top, a_it->bottom, a_buffer, a_it->chunk_handle); ++a_it; } while (b_it != b_end) { auto b_top = std::max(cur_top, b_it->top); res.appendLine(b_top, b_it->bottom, b_buffer, b_it->chunk_handle); ++b_it; } return res; } DlRegion DlRegion::MakeIntersection(const DlRegion& a, const DlRegion& b) { if (!SkIRect::Intersects(a.bounds_, b.bounds_)) { return DlRegion(); } else if (a.isSimple() && b.isSimple()) { SkIRect r(a.bounds_); auto res = r.intersect(b.bounds_); (void)res; // Suppress unused variable warning in release builds. FML_DCHECK(res); return DlRegion(r); } else if (a.isSimple() && a.bounds_.contains(b.bounds_)) { return b; } else if (b.isSimple() && b.bounds_.contains(a.bounds_)) { return a; } DlRegion res; res.span_buffer_.reserve( std::max(a.span_buffer_.capacity(), b.span_buffer_.capacity())); auto& lines = res.lines_; lines.reserve(std::min(a.lines_.size(), b.lines_.size())); std::vector<SpanLine>::const_iterator a_it, b_it; getIntersectionIterators(a.lines_, b.lines_, a_it, b_it); auto a_end = a.lines_.end(); auto b_end = b.lines_.end(); auto& a_buffer = a.span_buffer_; auto& b_buffer = b.span_buffer_; std::vector<Span> tmp; int32_t cur_top = std::numeric_limits<int32_t>::min(); while (a_it != a_end && b_it != b_end) { auto a_top = std::max(cur_top, a_it->top); auto b_top = std::max(cur_top, b_it->top); if (a_it->bottom <= b_top) { ++a_it; } else if (b_it->bottom <= a_top) { ++b_it; } else { auto top = std::max(a_top, b_top); auto bottom = std::min(a_it->bottom, b_it->bottom); FML_DCHECK(top < bottom); auto size = intersectLineSpans(tmp, a_buffer, a_it->chunk_handle, b_buffer, b_it->chunk_handle); if (size > 0) { res.appendLine(top, bottom, tmp.data(), tmp.data() + size); res.bounds_.join(SkIRect::MakeLTRB( tmp.data()->left, top, (tmp.data() + size - 1)->right, bottom)); } cur_top = bottom; if (cur_top == a_it->bottom) { ++a_it; } if (cur_top == b_it->bottom) { ++b_it; } } } FML_DCHECK(a_it == a_end || b_it == b_end); return res; } std::vector<SkIRect> DlRegion::getRects(bool deband) const { std::vector<SkIRect> rects; if (isEmpty()) { return rects; } else if (isSimple()) { rects.push_back(bounds_); return rects; } size_t rect_count = 0; size_t previous_span_end = 0; for (const auto& line : lines_) { rect_count += span_buffer_.getChunkSize(line.chunk_handle); } rects.reserve(rect_count); for (const auto& line : lines_) { const Span *span_begin, *span_end; span_buffer_.getSpans(line.chunk_handle, span_begin, span_end); for (const auto* span = span_begin; span < span_end; ++span) { SkIRect rect{span->left, line.top, span->right, line.bottom}; if (deband) { auto iter = rects.begin() + previous_span_end; // If there is rectangle previously in rects on which this one is a // vertical continuation, remove the previous rectangle and expand // this one vertically to cover the area. while (iter != rects.begin()) { --iter; if (iter->bottom() < rect.top()) { // Went all the way to previous span line. break; } else if (iter->left() == rect.left() && iter->right() == rect.right()) { FML_DCHECK(iter->bottom() == rect.top()); rect.fTop = iter->fTop; rects.erase(iter); --previous_span_end; break; } } } rects.push_back(rect); } previous_span_end = rects.size(); } return rects; } bool DlRegion::isComplex() const { return lines_.size() > 1 || (lines_.size() == 1 && span_buffer_.getChunkSize(lines_.front().chunk_handle) > 1); } bool DlRegion::intersects(const SkIRect& rect) const { if (isEmpty()) { return false; } auto bounds_intersect = SkIRect::Intersects(bounds_, rect); if (isSimple()) { return bounds_intersect; } if (!bounds_intersect) { return false; } auto it = lines_.begin(); auto end = lines_.end(); if (lines_.size() > kBinarySearchThreshold && it[kBinarySearchThreshold].bottom <= rect.fTop) { it = std::lower_bound( lines_.begin() + kBinarySearchThreshold + 1, lines_.end(), rect.fTop, [](const SpanLine& line, int32_t top) { return line.bottom <= top; }); } else { while (it != end && it->bottom <= rect.fTop) { ++it; continue; } } while (it != end && it->top < rect.fBottom) { FML_DCHECK(rect.fTop < it->bottom && it->top < rect.fBottom); const Span *begin, *end; span_buffer_.getSpans(it->chunk_handle, begin, end); while (begin != end && begin->left < rect.fRight) { if (begin->right > rect.fLeft) { return true; } ++begin; } ++it; } return false; } bool DlRegion::spansIntersect(const Span* begin1, const Span* end1, const Span* begin2, const Span* end2) { while (begin1 != end1 && begin2 != end2) { if (begin1->right <= begin2->left) { ++begin1; } else if (begin2->right <= begin1->left) { ++begin2; } else { return true; } } return false; } void DlRegion::getIntersectionIterators( const std::vector<SpanLine>& a_lines, const std::vector<SpanLine>& b_lines, std::vector<SpanLine>::const_iterator& a_it, std::vector<SpanLine>::const_iterator& b_it) { a_it = a_lines.begin(); auto a_end = a_lines.end(); b_it = b_lines.begin(); auto b_end = b_lines.end(); FML_DCHECK(a_it != a_end && b_it != b_end); auto a_len = a_end - a_it; auto b_len = b_end - b_it; if (a_len > kBinarySearchThreshold && a_it[kBinarySearchThreshold].bottom <= b_it->top) { a_it = std::lower_bound( a_lines.begin() + kBinarySearchThreshold + 1, a_lines.end(), b_it->top, [](const SpanLine& line, int32_t top) { return line.bottom <= top; }); } else if (b_len > kBinarySearchThreshold && b_it[kBinarySearchThreshold].bottom <= a_it->top) { b_it = std::lower_bound( b_lines.begin() + kBinarySearchThreshold + 1, b_lines.end(), a_it->top, [](const SpanLine& line, int32_t top) { return line.bottom <= top; }); } } bool DlRegion::intersects(const DlRegion& region) const { if (isEmpty() || region.isEmpty()) { return false; } auto our_complex = isComplex(); auto their_complex = region.isComplex(); auto bounds_intersect = SkIRect::Intersects(bounds_, region.bounds_); if (!our_complex && !their_complex) { return bounds_intersect; } if (!bounds_intersect) { return false; } if (!our_complex) { return region.intersects(bounds_); } if (!their_complex) { return intersects(region.bounds_); } std::vector<SpanLine>::const_iterator ours, theirs; getIntersectionIterators(lines_, region.lines_, ours, theirs); auto ours_end = lines_.end(); auto theirs_end = region.lines_.end(); while (ours != ours_end && theirs != theirs_end) { if (ours->bottom <= theirs->top) { ++ours; } else if (theirs->bottom <= ours->top) { ++theirs; } else { FML_DCHECK(ours->top < theirs->bottom && theirs->top < ours->bottom); const Span *ours_begin, *ours_end; span_buffer_.getSpans(ours->chunk_handle, ours_begin, ours_end); const Span *theirs_begin, *theirs_end; region.span_buffer_.getSpans(theirs->chunk_handle, theirs_begin, theirs_end); if (spansIntersect(ours_begin, ours_end, theirs_begin, theirs_end)) { return true; } if (ours->bottom < theirs->bottom) { ++ours; } else { ++theirs; } } } return false; } } // namespace flutter
engine/display_list/geometry/dl_region.cc/0
{ "file_path": "engine/display_list/geometry/dl_region.cc", "repo_id": "engine", "token_count": 10206 }
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. #ifndef FLUTTER_DISPLAY_LIST_SKIA_DL_SK_DISPATCHER_H_ #define FLUTTER_DISPLAY_LIST_SKIA_DL_SK_DISPATCHER_H_ #include "flutter/display_list/display_list.h" #include "flutter/display_list/dl_op_receiver.h" #include "flutter/display_list/skia/dl_sk_paint_dispatcher.h" #include "flutter/display_list/skia/dl_sk_types.h" #include "flutter/fml/macros.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief Backend implementation of |DlOpReceiver| for |SkCanvas|. /// /// @see DlOpReceiver class DlSkCanvasDispatcher : public virtual DlOpReceiver, public DlSkPaintDispatchHelper { public: explicit DlSkCanvasDispatcher(SkCanvas* canvas, SkScalar opacity = SK_Scalar1) : DlSkPaintDispatchHelper(opacity), canvas_(canvas), original_transform_(canvas->getLocalToDevice()) {} const SkPaint* safe_paint(bool use_attributes); void save() override; void restore() override; void saveLayer(const SkRect& bounds, const SaveLayerOptions options, const DlImageFilter* backdrop) override; void translate(SkScalar tx, SkScalar ty) override; void scale(SkScalar sx, SkScalar sy) override; void rotate(SkScalar degrees) override; void skew(SkScalar sx, SkScalar sy) override; // clang-format off // 2x3 2D affine subset of a 4x4 transform in row major order void transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myt) override; // full 4x4 transform in row major order void transformFullPerspective( SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override; // clang-format on void transformReset() override; void clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) override; void clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) override; void clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) override; void drawPaint() override; void drawColor(DlColor color, DlBlendMode mode) override; void drawLine(const SkPoint& p0, const SkPoint& p1) override; void drawRect(const SkRect& rect) override; void drawOval(const SkRect& bounds) override; void drawCircle(const SkPoint& center, SkScalar radius) override; void drawRRect(const SkRRect& rrect) override; void drawDRRect(const SkRRect& outer, const SkRRect& inner) override; void drawPath(const SkPath& path) override; void drawArc(const SkRect& bounds, SkScalar start, SkScalar sweep, bool useCenter) override; void drawPoints(PointMode mode, uint32_t count, const SkPoint pts[]) override; void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; void drawImage(const sk_sp<DlImage> image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override; void drawImageRect(const sk_sp<DlImage> image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint) override; void drawImageNine(const sk_sp<DlImage> image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override; void drawAtlas(const sk_sp<DlImage> atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const SkRect* cullRect, bool render_with_attributes) override; void drawDisplayList(const sk_sp<DisplayList> display_list, SkScalar opacity) override; void drawTextBlob(const sk_sp<SkTextBlob> blob, SkScalar x, SkScalar y) override; void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y) override; void drawShadow(const SkPath& path, const DlColor color, const SkScalar elevation, bool transparent_occluder, SkScalar dpr) override; static void DrawShadow(SkCanvas* canvas, const SkPath& path, DlColor color, float elevation, bool transparentOccluder, SkScalar dpr); private: SkCanvas* canvas_; const SkM44 original_transform_; SkPaint temp_paint_; }; } // namespace flutter #endif // FLUTTER_DISPLAY_LIST_SKIA_DL_SK_DISPATCHER_H_
engine/display_list/skia/dl_sk_dispatcher.h/0
{ "file_path": "engine/display_list/skia/dl_sk_dispatcher.h", "repo_id": "engine", "token_count": 2355 }
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/testing/dl_test_surface_software.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { namespace testing { using PixelFormat = DlSurfaceProvider::PixelFormat; bool DlSoftwareSurfaceProvider::InitializeSurface(size_t width, size_t height, PixelFormat format) { primary_ = MakeOffscreenSurface(width, height, format); return primary_ != nullptr; } std::shared_ptr<DlSurfaceInstance> DlSoftwareSurfaceProvider::MakeOffscreenSurface(size_t width, size_t height, PixelFormat format) const { auto surface = SkSurfaces::Raster(MakeInfo(format, width, height)); surface->getCanvas()->clear(SK_ColorTRANSPARENT); return std::make_shared<DlSurfaceInstanceBase>(surface); } } // namespace testing } // namespace flutter
engine/display_list/testing/dl_test_surface_software.cc/0
{ "file_path": "engine/display_list/testing/dl_test_surface_software.cc", "repo_id": "engine", "token_count": 508 }
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. #include <string> namespace flutter { static std::string gGoldenDir; static std::string gFontFile; const std::string& GetGoldenDir() { return gGoldenDir; } void SetGoldenDir(const std::string& dir) { gGoldenDir = dir; } const std::string& GetFontFile() { return gFontFile; } void SetFontFile(const std::string& file) { gFontFile = file; } } // namespace flutter
engine/flow/flow_test_utils.cc/0
{ "file_path": "engine/flow/flow_test_utils.cc", "repo_id": "engine", "token_count": 174 }
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/flow/layers/clip_path_layer.h" #include "flutter/flow/layers/layer_tree.h" #include "flutter/flow/layers/opacity_layer.h" #include "flutter/flow/layers/platform_view_layer.h" #include "flutter/flow/raster_cache_item.h" #include "flutter/flow/testing/layer_test.h" #include "flutter/flow/testing/mock_embedder.h" #include "flutter/flow/testing/mock_layer.h" #include "gtest/gtest.h" // TODO(zanderso): https://github.com/flutter/flutter/issues/127701 // NOLINTBEGIN(bugprone-unchecked-optional-access) namespace flutter { namespace testing { using ClipPathLayerTest = LayerTest; using ClipOp = DlCanvas::ClipOp; #ifndef NDEBUG TEST_F(ClipPathLayerTest, ClipNoneBehaviorDies) { EXPECT_DEATH_IF_SUPPORTED( auto clip = std::make_shared<ClipPathLayer>(SkPath(), Clip::kNone), "clip_behavior != Clip::kNone"); } TEST_F(ClipPathLayerTest, PaintingEmptyLayerDies) { auto layer = std::make_shared<ClipPathLayer>(SkPath(), Clip::kHardEdge); 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(layer->paint_bounds(), kEmptyRect); EXPECT_EQ(layer->child_paint_bounds(), kEmptyRect); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(ClipPathLayerTest, PaintBeforePrerollDies) { const SkRect layer_bounds = SkRect::MakeXYWH(0.5, 1.0, 5.0, 6.0); const SkPath layer_path = SkPath().addRect(layer_bounds); auto layer = std::make_shared<ClipPathLayer>(layer_path, Clip::kHardEdge); EXPECT_EQ(layer->paint_bounds(), kEmptyRect); EXPECT_EQ(layer->child_paint_bounds(), kEmptyRect); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(ClipPathLayerTest, PaintingCulledLayerDies) { 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 SkRect distant_bounds = SkRect::MakeXYWH(100.0, 100.0, 10.0, 10.0); const SkPath child_path = SkPath().addRect(child_bounds); const SkPath layer_path = SkPath().addRect(layer_bounds); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<ClipPathLayer>(layer_path, Clip::kHardEdge); layer->Add(mock_layer); // Cull these children preroll_context()->state_stack.set_preroll_delegate(distant_bounds, initial_matrix); layer->Preroll(preroll_context()); // Untouched EXPECT_EQ(preroll_context()->state_stack.device_cull_rect(), distant_bounds); EXPECT_TRUE(preroll_context()->state_stack.is_empty()); EXPECT_EQ(mock_layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->paint_bounds(), child_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(), kEmptyRect); EXPECT_EQ(mock_layer->parent_matrix(), initial_matrix); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(layer_path)})); auto mutator = paint_context().state_stack.save(); mutator.clipRect(distant_bounds, false); EXPECT_FALSE(mock_layer->needs_painting(paint_context())); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } #endif TEST_F(ClipPathLayerTest, ChildOutsideBounds) { const SkMatrix initial_matrix = SkMatrix::Translate(0.5f, 1.0f); const SkRect local_cull_bounds = SkRect::MakeXYWH(0.0, 0.0, 2.0, 4.0); const SkRect device_cull_bounds = initial_matrix.mapRect(local_cull_bounds); const SkRect child_bounds = SkRect::MakeXYWH(2.5, 5.0, 4.5, 4.0); const SkRect clip_bounds = SkRect::MakeXYWH(0.5, 1.0, 5.0, 6.0); const SkPath child_path = SkPath().addRect(child_bounds); const SkPath clip_path = SkPath().addRect(clip_bounds); const DlPaint child_paint = DlPaint(DlColor::kYellow()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ClipPathLayer>(clip_path, Clip::kHardEdge); layer->Add(mock_layer); SkRect clip_cull_rect = local_cull_bounds; ASSERT_TRUE(clip_cull_rect.intersect(clip_bounds)); SkRect clip_layer_bounds = child_bounds; ASSERT_TRUE(clip_layer_bounds.intersect(clip_bounds)); // Set up both contexts to cull clipped child preroll_context()->state_stack.set_preroll_delegate(device_cull_bounds, initial_matrix); paint_context().canvas->ClipRect(device_cull_bounds); paint_context().canvas->Transform(initial_matrix); layer->Preroll(preroll_context()); // Untouched EXPECT_EQ(preroll_context()->state_stack.device_cull_rect(), device_cull_bounds); EXPECT_EQ(preroll_context()->state_stack.local_cull_rect(), local_cull_bounds); EXPECT_TRUE(preroll_context()->state_stack.is_empty()); EXPECT_EQ(mock_layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->paint_bounds(), clip_layer_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_EQ(mock_layer->parent_cull_rect(), clip_cull_rect); EXPECT_EQ(mock_layer->parent_matrix(), initial_matrix); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(clip_path)})); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_FALSE(mock_layer->needs_painting(paint_context())); // Top level layer not visible so calling layer->Paint() // would trip an FML_DCHECK } TEST_F(ClipPathLayerTest, FullyContainedChild) { 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).addOval(child_bounds.makeInset(0.1, 0.1)); const SkPath layer_path = SkPath().addRect(layer_bounds).addOval(layer_bounds.makeInset(0.1, 0.1)); const DlPaint child_paint = DlPaint(DlColor::kYellow()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ClipPathLayer>(layer_path, Clip::kHardEdge); 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_path)})); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (ClipPath)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipPath(layer_path); /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } } expected_builder.Restore(); } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ClipPathLayerTest, PartiallyContainedChild) { const SkMatrix initial_matrix = SkMatrix::Translate(0.5f, 1.0f); const SkRect local_cull_bounds = SkRect::MakeXYWH(0.0, 0.0, 4.0, 5.5); const SkRect device_cull_bounds = initial_matrix.mapRect(local_cull_bounds); const SkRect child_bounds = SkRect::MakeXYWH(2.5, 5.0, 4.5, 4.0); const SkRect clip_bounds = SkRect::MakeXYWH(0.5, 1.0, 5.0, 6.0); const SkPath child_path = SkPath().addRect(child_bounds).addOval(child_bounds.makeInset(0.1, 0.1)); const SkPath clip_path = SkPath().addRect(clip_bounds).addOval(clip_bounds.makeInset(0.1, 0.1)); const DlPaint child_paint = DlPaint(DlColor::kYellow()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ClipPathLayer>(clip_path, Clip::kHardEdge); layer->Add(mock_layer); SkRect clip_cull_rect = local_cull_bounds; ASSERT_TRUE(clip_cull_rect.intersect(clip_bounds)); SkRect clip_layer_bounds = child_bounds; ASSERT_TRUE(clip_layer_bounds.intersect(clip_bounds)); // Cull child preroll_context()->state_stack.set_preroll_delegate(device_cull_bounds, initial_matrix); layer->Preroll(preroll_context()); // Untouched EXPECT_EQ(preroll_context()->state_stack.device_cull_rect(), device_cull_bounds); EXPECT_EQ(preroll_context()->state_stack.local_cull_rect(), local_cull_bounds); EXPECT_TRUE(preroll_context()->state_stack.is_empty()); EXPECT_EQ(mock_layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->paint_bounds(), clip_layer_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(), clip_cull_rect); EXPECT_EQ(mock_layer->parent_matrix(), initial_matrix); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(clip_path)})); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (ClipPath)layer::Paint */ { expected_builder.Save(); { expected_builder.ClipPath(clip_path); /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } } expected_builder.Restore(); } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } static bool ReadbackResult(PrerollContext* context, Clip clip_behavior, const std::shared_ptr<Layer>& child, bool before) { const SkRect layer_bounds = SkRect::MakeXYWH(0.5, 1.0, 5.0, 6.0); const SkPath layer_path = SkPath().addRect(layer_bounds); auto layer = std::make_shared<ClipPathLayer>(layer_path, clip_behavior); if (child != nullptr) { layer->Add(child); } context->surface_needs_readback = before; layer->Preroll(context); return context->surface_needs_readback; } TEST_F(ClipPathLayerTest, Readback) { PrerollContext* context = preroll_context(); SkPath path; DlPaint paint; const Clip hard = Clip::kHardEdge; const Clip soft = Clip::kAntiAlias; const Clip save_layer = Clip::kAntiAliasWithSaveLayer; std::shared_ptr<MockLayer> nochild; auto reader = std::make_shared<MockLayer>(path, paint); reader->set_fake_reads_surface(true); auto nonreader = std::make_shared<MockLayer>(path, paint); // No children, no prior readback -> no readback after EXPECT_FALSE(ReadbackResult(context, hard, nochild, false)); EXPECT_FALSE(ReadbackResult(context, soft, nochild, false)); EXPECT_FALSE(ReadbackResult(context, save_layer, nochild, false)); // No children, prior readback -> readback after EXPECT_TRUE(ReadbackResult(context, hard, nochild, true)); EXPECT_TRUE(ReadbackResult(context, soft, nochild, true)); EXPECT_TRUE(ReadbackResult(context, save_layer, nochild, true)); // Non readback child, no prior readback -> no readback after EXPECT_FALSE(ReadbackResult(context, hard, nonreader, false)); EXPECT_FALSE(ReadbackResult(context, soft, nonreader, false)); EXPECT_FALSE(ReadbackResult(context, save_layer, nonreader, false)); // Non readback child, prior readback -> readback after EXPECT_TRUE(ReadbackResult(context, hard, nonreader, true)); EXPECT_TRUE(ReadbackResult(context, soft, nonreader, true)); EXPECT_TRUE(ReadbackResult(context, save_layer, nonreader, true)); // Readback child, no prior readback -> readback after unless SaveLayer EXPECT_TRUE(ReadbackResult(context, hard, reader, false)); EXPECT_TRUE(ReadbackResult(context, soft, reader, false)); EXPECT_FALSE(ReadbackResult(context, save_layer, reader, false)); // Readback child, prior readback -> readback after EXPECT_TRUE(ReadbackResult(context, hard, reader, true)); EXPECT_TRUE(ReadbackResult(context, soft, reader, true)); EXPECT_TRUE(ReadbackResult(context, save_layer, reader, true)); } TEST_F(ClipPathLayerTest, OpacityInheritance) { auto path1 = SkPath().addRect({10, 10, 30, 30}); auto mock1 = MockLayer::MakeOpacityCompatible(path1); auto layer_clip = SkPath() .addRect(SkRect::MakeLTRB(5, 5, 25, 25)) .addOval(SkRect::MakeLTRB(20, 20, 40, 50)); auto clip_path_layer = std::make_shared<ClipPathLayer>(layer_clip, Clip::kHardEdge); clip_path_layer->Add(mock1); // ClipRectLayer will pass through compatibility from a compatible child PrerollContext* context = preroll_context(); clip_path_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); auto path2 = SkPath().addRect({40, 40, 50, 50}); auto mock2 = MockLayer::MakeOpacityCompatible(path2); clip_path_layer->Add(mock2); // ClipRectLayer will pass through compatibility from multiple // non-overlapping compatible children clip_path_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); auto path3 = SkPath().addRect({20, 20, 40, 40}); auto mock3 = MockLayer::MakeOpacityCompatible(path3); clip_path_layer->Add(mock3); // ClipRectLayer will not pass through compatibility from multiple // overlapping children even if they are individually compatible clip_path_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, 0); { // ClipRectLayer(aa with saveLayer) will always be compatible auto clip_path_savelayer = std::make_shared<ClipPathLayer>( layer_clip, Clip::kAntiAliasWithSaveLayer); clip_path_savelayer->Add(mock1); clip_path_savelayer->Add(mock2); // Double check first two children are compatible and non-overlapping clip_path_savelayer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, Layer::kSaveLayerRenderFlags); // Now add the overlapping child and test again, should still be compatible clip_path_savelayer->Add(mock3); clip_path_savelayer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, Layer::kSaveLayerRenderFlags); } // An incompatible, but non-overlapping child for the following tests auto path4 = SkPath().addRect({60, 60, 70, 70}); auto mock4 = MockLayer::Make(path4); { // ClipRectLayer with incompatible child will not be compatible auto clip_path_bad_child = std::make_shared<ClipPathLayer>(layer_clip, Clip::kHardEdge); clip_path_bad_child->Add(mock1); clip_path_bad_child->Add(mock2); // Double check first two children are compatible and non-overlapping clip_path_bad_child->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); clip_path_bad_child->Add(mock4); // The third child is non-overlapping, but not compatible so the // TransformLayer should end up incompatible clip_path_bad_child->Preroll(context); EXPECT_EQ(context->renderable_state_flags, 0); } { // ClipRectLayer(aa with saveLayer) will always be compatible auto clip_path_savelayer_bad_child = std::make_shared<ClipPathLayer>( layer_clip, Clip::kAntiAliasWithSaveLayer); clip_path_savelayer_bad_child->Add(mock1); clip_path_savelayer_bad_child->Add(mock2); // Double check first two children are compatible and non-overlapping clip_path_savelayer_bad_child->Preroll(context); EXPECT_EQ(context->renderable_state_flags, Layer::kSaveLayerRenderFlags); // Now add the incompatible child and test again, should still be compatible clip_path_savelayer_bad_child->Add(mock4); clip_path_savelayer_bad_child->Preroll(context); EXPECT_EQ(context->renderable_state_flags, Layer::kSaveLayerRenderFlags); } } TEST_F(ClipPathLayerTest, OpacityInheritancePainting) { auto path1 = SkPath().addRect({10, 10, 30, 30}); auto mock1 = MockLayer::MakeOpacityCompatible(path1); auto path2 = SkPath().addRect({40, 40, 50, 50}); auto mock2 = MockLayer::MakeOpacityCompatible(path2); auto layer_clip = SkPath() .addRect(SkRect::MakeLTRB(5, 5, 25, 25)) .addOval(SkRect::MakeLTRB(45, 45, 55, 55)); auto clip_path_layer = std::make_shared<ClipPathLayer>(layer_clip, Clip::kAntiAlias); clip_path_layer->Add(mock1); clip_path_layer->Add(mock2); // ClipRectLayer will pass through compatibility from multiple // non-overlapping compatible children PrerollContext* context = preroll_context(); clip_path_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); int opacity_alpha = 0x7F; SkPoint offset = SkPoint::Make(10, 10); auto opacity_layer = std::make_shared<OpacityLayer>(opacity_alpha, offset); opacity_layer->Add(clip_path_layer); opacity_layer->Preroll(context); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); DisplayListBuilder expected_builder; /* OpacityLayer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(offset.fX, offset.fY); /* ClipRectLayer::Paint() */ { expected_builder.Save(); expected_builder.ClipPath(layer_clip, ClipOp::kIntersect, true); /* child layer1 paint */ { expected_builder.DrawPath(path1, DlPaint().setAlpha(opacity_alpha)); } /* child layer2 paint */ { expected_builder.DrawPath(path2, DlPaint().setAlpha(opacity_alpha)); } expected_builder.Restore(); } } expected_builder.Restore(); } opacity_layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ClipPathLayerTest, OpacityInheritanceSaveLayerPainting) { auto path1 = SkPath().addRect({10, 10, 30, 30}); auto mock1 = MockLayer::MakeOpacityCompatible(path1); auto path2 = SkPath().addRect({20, 20, 40, 40}); auto mock2 = MockLayer::MakeOpacityCompatible(path2); auto children_bounds = path1.getBounds(); children_bounds.join(path2.getBounds()); auto layer_clip = SkPath() .addRect(SkRect::MakeLTRB(5, 5, 25, 25)) .addOval(SkRect::MakeLTRB(20, 20, 40, 50)); auto clip_path_layer = std::make_shared<ClipPathLayer>( layer_clip, Clip::kAntiAliasWithSaveLayer); clip_path_layer->Add(mock1); clip_path_layer->Add(mock2); // ClipRectLayer will pass through compatibility from multiple // non-overlapping compatible children PrerollContext* context = preroll_context(); clip_path_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, Layer::kSaveLayerRenderFlags); int opacity_alpha = 0x7F; SkPoint offset = SkPoint::Make(10, 10); auto opacity_layer = std::make_shared<OpacityLayer>(opacity_alpha, offset); opacity_layer->Add(clip_path_layer); opacity_layer->Preroll(context); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); DisplayListBuilder expected_builder; /* OpacityLayer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(offset.fX, offset.fY); /* ClipRectLayer::Paint() */ { expected_builder.Save(); expected_builder.ClipPath(layer_clip, ClipOp::kIntersect, true); expected_builder.SaveLayer(&children_bounds, &DlPaint().setAlpha(opacity_alpha)); /* child layer1 paint */ { expected_builder.DrawPath(path1, DlPaint()); } /* child layer2 paint */ { // expected_builder.DrawPath(path2, DlPaint()); } expected_builder.Restore(); } } expected_builder.Restore(); } opacity_layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(expected_builder.Build(), display_list())); } TEST_F(ClipPathLayerTest, LayerCached) { auto path1 = SkPath().addRect({10, 10, 30, 30}); auto mock1 = MockLayer::MakeOpacityCompatible(path1); auto layer_clip = SkPath() .addRect(SkRect::MakeLTRB(5, 5, 25, 25)) .addOval(SkRect::MakeLTRB(20, 20, 40, 50)); auto layer = std::make_shared<ClipPathLayer>(layer_clip, Clip::kAntiAliasWithSaveLayer); layer->Add(mock1); auto initial_transform = SkMatrix::Translate(50.0, 25.5); SkMatrix cache_ctm = initial_transform; DisplayListBuilder cache_canvas; cache_canvas.Transform(cache_ctm); use_mock_raster_cache(); preroll_context()->state_stack.set_preroll_delegate(initial_transform); const auto* clip_cache_item = layer->raster_cache_item(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_EQ(clip_cache_item->cache_state(), RasterCacheItem::CacheState::kNone); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_EQ(clip_cache_item->cache_state(), RasterCacheItem::CacheState::kNone); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1); EXPECT_EQ(clip_cache_item->cache_state(), RasterCacheItem::CacheState::kCurrent); DlPaint paint; EXPECT_TRUE(raster_cache()->Draw(clip_cache_item->GetId().value(), cache_canvas, &paint)); } TEST_F(ClipPathLayerTest, EmptyClipDoesNotCullPlatformView) { const SkPoint view_offset = SkPoint::Make(0.0f, 0.0f); const SkSize view_size = SkSize::Make(8.0f, 8.0f); const int64_t view_id = 42; auto platform_view = std::make_shared<PlatformViewLayer>(view_offset, view_size, view_id); auto layer_clip = SkPath().addRect(kEmptyRect); auto clip = std::make_shared<ClipPathLayer>(layer_clip, Clip::kAntiAliasWithSaveLayer); clip->Add(platform_view); auto embedder = MockViewEmbedder(); DisplayListBuilder fake_overlay_builder; embedder.AddCanvas(&fake_overlay_builder); preroll_context()->view_embedder = &embedder; paint_context().view_embedder = &embedder; clip->Preroll(preroll_context()); EXPECT_EQ(embedder.prerolled_views(), std::vector<int64_t>({view_id})); clip->Paint(paint_context()); EXPECT_EQ(embedder.painted_views(), std::vector<int64_t>({view_id})); } } // namespace testing } // namespace flutter // NOLINTEND(bugprone-unchecked-optional-access)
engine/flow/layers/clip_path_layer_unittests.cc/0
{ "file_path": "engine/flow/layers/clip_path_layer_unittests.cc", "repo_id": "engine", "token_count": 9256 }
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. #define FML_USED_ON_EMBEDDER #include "flutter/flow/layers/display_list_layer.h" #include "flutter/display_list/dl_builder.h" #include "flutter/flow/layers/layer_tree.h" #include "flutter/flow/testing/diff_context_test.h" #include "flutter/fml/macros.h" // TODO(zanderso): https://github.com/flutter/flutter/issues/127701 // NOLINTBEGIN(bugprone-unchecked-optional-access) namespace flutter { namespace testing { using DisplayListLayerTest = LayerTest; #ifndef NDEBUG TEST_F(DisplayListLayerTest, PaintBeforePrerollInvalidDisplayListDies) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); auto layer = std::make_shared<DisplayListLayer>( layer_offset, sk_sp<DisplayList>(), false, false); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "display_list_"); } TEST_F(DisplayListLayerTest, PaintBeforePrerollDies) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); const SkRect picture_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); DisplayListBuilder builder; builder.DrawRect(picture_bounds, DlPaint()); auto display_list = builder.Build(); auto layer = std::make_shared<DisplayListLayer>(layer_offset, display_list, false, false); EXPECT_EQ(layer->paint_bounds(), SkRect::MakeEmpty()); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(DisplayListLayerTest, PaintingEmptyLayerDies) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); const SkRect picture_bounds = SkRect::MakeEmpty(); DisplayListBuilder builder; builder.DrawRect(picture_bounds, DlPaint()); auto display_list = builder.Build(); auto layer = std::make_shared<DisplayListLayer>(layer_offset, display_list, false, false); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), SkRect::MakeEmpty()); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(DisplayListLayerTest, InvalidDisplayListDies) { const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f); auto layer = std::make_shared<DisplayListLayer>( layer_offset, sk_sp<DisplayList>(), false, false); // Crashes reading a nullptr. EXPECT_DEATH_IF_SUPPORTED(layer->Preroll(preroll_context()), ""); } #endif TEST_F(DisplayListLayerTest, SimpleDisplayList) { const SkPoint layer_offset = SkPoint::Make(1.5f, -0.5f); const SkRect picture_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); DisplayListBuilder builder; builder.DrawRect(picture_bounds, DlPaint()); auto display_list = builder.Build(); auto layer = std::make_shared<DisplayListLayer>(layer_offset, display_list, false, false); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), picture_bounds.makeOffset(layer_offset.fX, layer_offset.fY)); EXPECT_EQ(layer->display_list(), display_list.get()); EXPECT_TRUE(layer->needs_painting(paint_context())); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (DisplayList)layer::Paint */ { expected_builder.Save(); { expected_builder.Translate(layer_offset.fX, layer_offset.fY); expected_builder.DrawDisplayList(display_list); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(this->display_list(), expected_builder.Build())); } TEST_F(DisplayListLayerTest, CachingDoesNotChangeCullRect) { const SkPoint layer_offset = SkPoint::Make(10, 10); DisplayListBuilder builder; builder.DrawRect({10, 10, 20, 20}, DlPaint()); auto display_list = builder.Build(); auto layer = std::make_shared<DisplayListLayer>(layer_offset, display_list, true, false); SkRect original_cull_rect = preroll_context()->state_stack.device_cull_rect(); use_mock_raster_cache(); layer->Preroll(preroll_context()); ASSERT_EQ(preroll_context()->state_stack.device_cull_rect(), original_cull_rect); } TEST_F(DisplayListLayerTest, SimpleDisplayListOpacityInheritance) { const SkPoint layer_offset = SkPoint::Make(1.5f, -0.5f); const SkRect picture_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); DisplayListBuilder builder; builder.DrawRect(picture_bounds, DlPaint()); auto display_list = builder.Build(); auto display_list_layer = std::make_shared<DisplayListLayer>( layer_offset, display_list, false, false); EXPECT_TRUE(display_list->can_apply_group_opacity()); auto context = preroll_context(); display_list_layer->Preroll(preroll_context()); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); int opacity_alpha = 0x7F; SkScalar opacity = opacity_alpha / 255.0; SkPoint opacity_offset = SkPoint::Make(10, 10); auto opacity_layer = std::make_shared<OpacityLayer>(opacity_alpha, opacity_offset); opacity_layer->Add(display_list_layer); opacity_layer->Preroll(context); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); DisplayListBuilder child_builder; child_builder.DrawRect(picture_bounds, DlPaint()); auto child_display_list = child_builder.Build(); DisplayListBuilder expected_builder; /* opacity_layer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(opacity_offset.fX, opacity_offset.fY); /* display_list_layer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(layer_offset.fX, layer_offset.fY); expected_builder.DrawDisplayList(child_display_list, opacity); } expected_builder.Restore(); } } expected_builder.Restore(); } opacity_layer->Paint(display_list_paint_context()); EXPECT_TRUE( DisplayListsEQ_Verbose(this->display_list(), expected_builder.Build())); } TEST_F(DisplayListLayerTest, IncompatibleDisplayListOpacityInheritance) { const SkPoint layer_offset = SkPoint::Make(1.5f, -0.5f); const SkRect picture1_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); const SkRect picture2_bounds = SkRect::MakeLTRB(10.0f, 15.0f, 30.0f, 35.0f); DisplayListBuilder builder; builder.DrawRect(picture1_bounds, DlPaint()); builder.DrawRect(picture2_bounds, DlPaint()); auto display_list = builder.Build(); auto display_list_layer = std::make_shared<DisplayListLayer>( layer_offset, display_list, false, false); EXPECT_FALSE(display_list->can_apply_group_opacity()); auto context = preroll_context(); display_list_layer->Preroll(preroll_context()); EXPECT_EQ(context->renderable_state_flags, 0); int opacity_alpha = 0x7F; SkPoint opacity_offset = SkPoint::Make(10, 10); auto opacity_layer = std::make_shared<OpacityLayer>(opacity_alpha, opacity_offset); opacity_layer->Add(display_list_layer); opacity_layer->Preroll(context); EXPECT_FALSE(opacity_layer->children_can_accept_opacity()); DisplayListBuilder child_builder; child_builder.DrawRect(picture1_bounds, DlPaint()); child_builder.DrawRect(picture2_bounds, DlPaint()); auto child_display_list = child_builder.Build(); auto display_list_bounds = picture1_bounds; display_list_bounds.join(picture2_bounds); auto save_layer_bounds = display_list_bounds.makeOffset(layer_offset.fX, layer_offset.fY); DisplayListBuilder expected_builder; /* opacity_layer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(opacity_offset.fX, opacity_offset.fY); expected_builder.SaveLayer(&save_layer_bounds, &DlPaint().setAlpha(opacity_alpha)); { /* display_list_layer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(layer_offset.fX, layer_offset.fY); expected_builder.DrawDisplayList(child_display_list); } expected_builder.Restore(); } } expected_builder.Restore(); } expected_builder.Restore(); } opacity_layer->Paint(display_list_paint_context()); EXPECT_TRUE( DisplayListsEQ_Verbose(this->display_list(), expected_builder.Build())); } TEST_F(DisplayListLayerTest, CachedIncompatibleDisplayListOpacityInheritance) { const SkPoint layer_offset = SkPoint::Make(1.5f, -0.5f); const SkRect picture1_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); const SkRect picture2_bounds = SkRect::MakeLTRB(10.0f, 15.0f, 30.0f, 35.0f); DisplayListBuilder builder; builder.DrawRect(picture1_bounds, DlPaint()); builder.DrawRect(picture2_bounds, DlPaint()); auto display_list = builder.Build(); auto display_list_layer = std::make_shared<DisplayListLayer>( layer_offset, display_list, true, false); EXPECT_FALSE(display_list->can_apply_group_opacity()); use_skia_raster_cache(); auto context = preroll_context(); display_list_layer->Preroll(preroll_context()); EXPECT_EQ(context->renderable_state_flags, 0); // Pump the DisplayListLayer until it is ready to cache its DL display_list_layer->Preroll(preroll_context()); display_list_layer->Preroll(preroll_context()); display_list_layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(*preroll_context()->raster_cached_entries, &paint_context(), false); int opacity_alpha = 0x7F; SkPoint opacity_offset = SkPoint::Make(10.2, 10.2); auto opacity_layer = std::make_shared<OpacityLayer>(opacity_alpha, opacity_offset); opacity_layer->Add(display_list_layer); opacity_layer->Preroll(context); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); auto display_list_bounds = picture1_bounds; display_list_bounds.join(picture2_bounds); auto save_layer_bounds = display_list_bounds.makeOffset(layer_offset.fX, layer_offset.fY); save_layer_bounds.roundOut(&save_layer_bounds); auto opacity_integral_matrix = RasterCacheUtil::GetIntegralTransCTM(SkMatrix::Translate(opacity_offset)); SkMatrix layer_offset_matrix = opacity_integral_matrix; layer_offset_matrix.postTranslate(layer_offset.fX, layer_offset.fY); auto layer_offset_integral_matrix = RasterCacheUtil::GetIntegralTransCTM(layer_offset_matrix); DisplayListBuilder expected(SkRect::MakeWH(1000, 1000)); /* opacity_layer::Paint() */ { expected.Save(); { expected.Translate(opacity_offset.fX, opacity_offset.fY); expected.TransformReset(); expected.Transform(opacity_integral_matrix); /* display_list_layer::Paint() */ { expected.Save(); { expected.Translate(layer_offset.fX, layer_offset.fY); expected.TransformReset(); expected.Transform(layer_offset_integral_matrix); context->raster_cache->Draw(display_list_layer->caching_key_id(), expected, &DlPaint().setAlpha(opacity_alpha)); } expected.Restore(); } } expected.Restore(); } opacity_layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(expected.Build(), this->display_list())); } TEST_F(DisplayListLayerTest, RasterCachePreservesRTree) { const SkRect picture1_bounds = SkRect::MakeXYWH(10, 10, 10, 10); const SkRect picture2_bounds = SkRect::MakeXYWH(15, 15, 10, 10); DisplayListBuilder builder(true); builder.DrawRect(picture1_bounds, DlPaint()); builder.DrawRect(picture2_bounds, DlPaint()); auto display_list = builder.Build(); auto display_list_layer = std::make_shared<DisplayListLayer>( SkPoint::Make(3, 3), display_list, true, false); use_skia_raster_cache(); auto context = preroll_context(); { auto mutator = context->state_stack.save(); mutator.transform(SkMatrix::Scale(2.0, 2.0)); display_list_layer->Preroll(preroll_context()); EXPECT_EQ(context->renderable_state_flags, 0); // Pump the DisplayListLayer until it is ready to cache its DL display_list_layer->Preroll(preroll_context()); display_list_layer->Preroll(preroll_context()); display_list_layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(*preroll_context()->raster_cached_entries, &paint_context(), false); } DisplayListBuilder expected_root_canvas(true); expected_root_canvas.Scale(2.0, 2.0); ASSERT_TRUE(context->raster_cache->Draw(display_list_layer->caching_key_id(), expected_root_canvas, nullptr, false)); auto root_canvas_dl = expected_root_canvas.Build(); const auto root_canvas_rects = root_canvas_dl->rtree()->searchAndConsolidateRects(kGiantRect, true); std::list<SkRect> root_canvas_rects_expected = { SkRect::MakeLTRB(26, 26, 56, 56), }; EXPECT_EQ(root_canvas_rects_expected, root_canvas_rects); DisplayListBuilder expected_overlay_canvas(true); expected_overlay_canvas.Scale(2.0, 2.0); ASSERT_TRUE(context->raster_cache->Draw(display_list_layer->caching_key_id(), expected_overlay_canvas, nullptr, true)); auto overlay_canvas_dl = expected_overlay_canvas.Build(); const auto overlay_canvas_rects = overlay_canvas_dl->rtree()->searchAndConsolidateRects(kGiantRect, true); // Same bounds as root canvas, but preserves individual rects. std::list<SkRect> overlay_canvas_rects_expected = { SkRect::MakeLTRB(26, 26, 46, 36), SkRect::MakeLTRB(26, 36, 56, 46), SkRect::MakeLTRB(36, 46, 56, 56), }; EXPECT_EQ(overlay_canvas_rects_expected, overlay_canvas_rects); }; using DisplayListLayerDiffTest = DiffContextTest; TEST_F(DisplayListLayerDiffTest, SimpleDisplayList) { auto display_list = CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60)); MockLayerTree tree1; tree1.root()->Add(CreateDisplayListLayer(display_list)); auto damage = DiffLayerTree(tree1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(10, 10, 60, 60)); MockLayerTree tree2; tree2.root()->Add(CreateDisplayListLayer(display_list)); damage = DiffLayerTree(tree2, tree1); EXPECT_TRUE(damage.frame_damage.isEmpty()); MockLayerTree tree3; damage = DiffLayerTree(tree3, tree2); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(10, 10, 60, 60)); } TEST_F(DisplayListLayerDiffTest, FractionalTranslation) { auto display_list = CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60)); MockLayerTree tree1; tree1.root()->Add( CreateDisplayListLayer(display_list, SkPoint::Make(0.5, 0.5))); auto damage = DiffLayerTree(tree1, MockLayerTree(), SkIRect::MakeEmpty(), 0, 0, /*use_raster_cache=*/false); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(10, 10, 61, 61)); } TEST_F(DisplayListLayerDiffTest, FractionalTranslationWithRasterCache) { auto display_list = CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60)); MockLayerTree tree1; tree1.root()->Add( CreateDisplayListLayer(display_list, SkPoint::Make(0.5, 0.5))); auto damage = DiffLayerTree(tree1, MockLayerTree(), SkIRect::MakeEmpty(), 0, 0, /*use_raster_cache=*/true); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(11, 11, 61, 61)); } TEST_F(DisplayListLayerDiffTest, DisplayListCompare) { MockLayerTree tree1; auto display_list1 = CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60), DlColor::kGreen()); tree1.root()->Add(CreateDisplayListLayer(display_list1)); auto damage = DiffLayerTree(tree1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(10, 10, 60, 60)); MockLayerTree tree2; // same DL, same offset auto display_list2 = CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60), DlColor::kGreen()); tree2.root()->Add(CreateDisplayListLayer(display_list2)); damage = DiffLayerTree(tree2, tree1); EXPECT_EQ(damage.frame_damage, SkIRect::MakeEmpty()); MockLayerTree tree3; auto display_list3 = CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60), DlColor::kGreen()); // add offset tree3.root()->Add( CreateDisplayListLayer(display_list3, SkPoint::Make(10, 10))); damage = DiffLayerTree(tree3, tree2); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(10, 10, 70, 70)); MockLayerTree tree4; // different color auto display_list4 = CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60), DlColor::kRed()); tree4.root()->Add( CreateDisplayListLayer(display_list4, SkPoint::Make(10, 10))); damage = DiffLayerTree(tree4, tree3); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(20, 20, 70, 70)); } TEST_F(DisplayListLayerTest, LayerTreeSnapshotsWhenEnabled) { const SkPoint layer_offset = SkPoint::Make(1.5f, -0.5f); const SkRect picture_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); DisplayListBuilder builder; builder.DrawRect(picture_bounds, DlPaint()); auto display_list = builder.Build(); auto layer = std::make_shared<DisplayListLayer>(layer_offset, display_list, false, false); layer->Preroll(preroll_context()); enable_leaf_layer_tracing(); layer->Paint(paint_context()); disable_leaf_layer_tracing(); auto& snapshot_store = layer_snapshot_store(); EXPECT_EQ(1u, snapshot_store.Size()); } TEST_F(DisplayListLayerTest, NoLayerTreeSnapshotsWhenDisabledByDefault) { const SkPoint layer_offset = SkPoint::Make(1.5f, -0.5f); const SkRect picture_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); DisplayListBuilder builder; builder.DrawRect(picture_bounds, DlPaint()); auto display_list = builder.Build(); auto layer = std::make_shared<DisplayListLayer>(layer_offset, display_list, false, false); layer->Preroll(preroll_context()); layer->Paint(paint_context()); auto& snapshot_store = layer_snapshot_store(); EXPECT_EQ(0u, snapshot_store.Size()); } TEST_F(DisplayListLayerTest, DisplayListAccessCountDependsOnVisibility) { const SkPoint layer_offset = SkPoint::Make(1.5f, -0.5f); const SkRect picture_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); const SkRect missed_cull_rect = SkRect::MakeLTRB(100, 100, 200, 200); const SkRect hit_cull_rect = SkRect::MakeLTRB(0, 0, 200, 200); DisplayListBuilder builder; builder.DrawRect(picture_bounds, DlPaint()); auto display_list = builder.Build(); auto layer = std::make_shared<DisplayListLayer>(layer_offset, display_list, true, false); auto raster_cache_item = layer->raster_cache_item(); use_mock_raster_cache(); // First Preroll the DisplayListLayer a few times where it does not intersect // the cull rect. No caching progress should occur during this time, the // access_count should remain 0 because the DisplayList was never "visible". ASSERT_TRUE(preroll_context()->state_stack.is_empty()); preroll_context()->state_stack.set_preroll_delegate(missed_cull_rect); for (int i = 0; i < 10; i++) { preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); ASSERT_EQ(raster_cache_item->cache_state(), RasterCacheItem::kNone); ASSERT_TRUE(raster_cache_item->GetId().has_value()); ASSERT_EQ(preroll_context()->raster_cache->GetAccessCount( raster_cache_item->GetId().value(), SkMatrix::I()), 0); ASSERT_EQ(preroll_context()->raster_cached_entries->size(), size_t(1)); ASSERT_EQ(preroll_context()->raster_cache->EstimatePictureCacheByteSize(), size_t(0)); ASSERT_FALSE(raster_cache_item->TryToPrepareRasterCache(paint_context())); ASSERT_FALSE(raster_cache_item->Draw(paint_context(), nullptr)); } // Next Preroll the DisplayListLayer once where it does intersect // the cull rect. No caching progress should occur during this time // since this is the first frame in which it was visible, but the // count should start incrementing. ASSERT_TRUE(preroll_context()->state_stack.is_empty()); preroll_context()->state_stack.set_preroll_delegate(hit_cull_rect); preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); ASSERT_EQ(raster_cache_item->cache_state(), RasterCacheItem::kNone); ASSERT_TRUE(raster_cache_item->GetId().has_value()); ASSERT_EQ(preroll_context()->raster_cache->GetAccessCount( raster_cache_item->GetId().value(), SkMatrix::I()), 1); ASSERT_EQ(preroll_context()->raster_cached_entries->size(), size_t(1)); ASSERT_EQ(preroll_context()->raster_cache->EstimatePictureCacheByteSize(), size_t(0)); ASSERT_FALSE(raster_cache_item->TryToPrepareRasterCache(paint_context())); ASSERT_FALSE(raster_cache_item->Draw(paint_context(), nullptr)); // Now we can Preroll the DisplayListLayer again with a cull rect that // it does not intersect and it should continue to count these operations // even though it is not visible. No actual caching should occur yet, // even though we will surpass its threshold. ASSERT_TRUE(preroll_context()->state_stack.is_empty()); preroll_context()->state_stack.set_preroll_delegate(missed_cull_rect); for (int i = 0; i < 10; i++) { preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); ASSERT_EQ(raster_cache_item->cache_state(), RasterCacheItem::kNone); ASSERT_TRUE(raster_cache_item->GetId().has_value()); ASSERT_EQ(preroll_context()->raster_cache->GetAccessCount( raster_cache_item->GetId().value(), SkMatrix::I()), i + 2); ASSERT_EQ(preroll_context()->raster_cached_entries->size(), size_t(1)); ASSERT_EQ(preroll_context()->raster_cache->EstimatePictureCacheByteSize(), size_t(0)); ASSERT_FALSE(raster_cache_item->TryToPrepareRasterCache(paint_context())); ASSERT_FALSE(raster_cache_item->Draw(paint_context(), nullptr)); } // Finally Preroll the DisplayListLayer again where it does intersect // the cull rect. Since we should have exhausted our access count // threshold in the loop above, these operations should result in the // DisplayList being cached. ASSERT_TRUE(preroll_context()->state_stack.is_empty()); preroll_context()->state_stack.set_preroll_delegate(hit_cull_rect); preroll_context()->raster_cached_entries->clear(); layer->Preroll(preroll_context()); ASSERT_EQ(raster_cache_item->cache_state(), RasterCacheItem::kCurrent); ASSERT_TRUE(raster_cache_item->GetId().has_value()); ASSERT_EQ(preroll_context()->raster_cache->GetAccessCount( raster_cache_item->GetId().value(), SkMatrix::I()), 12); ASSERT_EQ(preroll_context()->raster_cached_entries->size(), size_t(1)); ASSERT_EQ(preroll_context()->raster_cache->EstimatePictureCacheByteSize(), size_t(0)); ASSERT_TRUE(raster_cache_item->TryToPrepareRasterCache(paint_context())); ASSERT_GT(preroll_context()->raster_cache->EstimatePictureCacheByteSize(), size_t(0)); ASSERT_TRUE(raster_cache_item->Draw(paint_context(), nullptr)); } TEST_F(DisplayListLayerTest, OverflowCachedDisplayListOpacityInheritance) { use_mock_raster_cache(); PrerollContext* context = preroll_context(); int per_frame = RasterCacheUtil::kDefaultPictureAndDisplayListCacheLimitPerFrame; int layer_count = per_frame + 1; SkPoint opacity_offset = {10, 10}; auto opacity_layer = std::make_shared<OpacityLayer>(0.5f, opacity_offset); std::vector<std::shared_ptr<DisplayListLayer>> layers; for (int i = 0; i < layer_count; i++) { DisplayListBuilder builder(false); builder.DrawRect({0, 0, 100, 100}, DlPaint()); builder.DrawRect({50, 50, 100, 100}, DlPaint()); auto display_list = builder.Build(); ASSERT_FALSE(display_list->can_apply_group_opacity()); SkPoint offset = {i * 200.0f, 0}; layers.push_back( std::make_shared<DisplayListLayer>(offset, display_list, true, false)); opacity_layer->Add(layers.back()); } for (size_t j = 0; j < context->raster_cache->access_threshold(); j++) { context->raster_cache->BeginFrame(); for (int i = 0; i < layer_count; i++) { context->renderable_state_flags = 0; layers[i]->Preroll(context); ASSERT_EQ(context->renderable_state_flags, 0) << "pass " << (j + 1); } } opacity_layer->Preroll(context); ASSERT_FALSE(opacity_layer->children_can_accept_opacity()); LayerTree::TryToRasterCache(*context->raster_cached_entries, &paint_context(), false); context->raster_cached_entries->clear(); context->raster_cache->BeginFrame(); for (int i = 0; i < per_frame; i++) { context->renderable_state_flags = 0; layers[i]->Preroll(context); ASSERT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity) << "layer " << (i + 1); } for (int i = per_frame; i < layer_count; i++) { context->renderable_state_flags = 0; layers[i]->Preroll(context); ASSERT_EQ(context->renderable_state_flags, 0) << "layer " << (i + 1); } opacity_layer->Preroll(context); ASSERT_FALSE(opacity_layer->children_can_accept_opacity()); LayerTree::TryToRasterCache(*context->raster_cached_entries, &paint_context(), false); context->raster_cached_entries->clear(); context->raster_cache->BeginFrame(); for (int i = 0; i < layer_count; i++) { context->renderable_state_flags = 0; layers[i]->Preroll(context); ASSERT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity) << "layer " << (i + 1); } opacity_layer->Preroll(context); ASSERT_TRUE(opacity_layer->children_can_accept_opacity()); } } // namespace testing } // namespace flutter // NOLINTEND(bugprone-unchecked-optional-access)
engine/flow/layers/display_list_layer_unittests.cc/0
{ "file_path": "engine/flow/layers/display_list_layer_unittests.cc", "repo_id": "engine", "token_count": 10296 }
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. #include "flutter/flow/layers/offscreen_surface.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkPixmap.h" #include "third_party/skia/include/encode/SkPngEncoder.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" namespace flutter { static sk_sp<SkSurface> CreateSnapshotSurface(GrDirectContext* surface_context, const SkISize& size) { const auto image_info = SkImageInfo::MakeN32Premul( size.width(), size.height(), SkColorSpace::MakeSRGB()); if (surface_context) { // There is a rendering surface that may contain textures that are going to // be referenced in the layer tree about to be drawn. return SkSurfaces::RenderTarget(surface_context, skgpu::Budgeted::kNo, image_info); } // There is no rendering surface, assume no GPU textures are present and // create a raster surface. return SkSurfaces::Raster(image_info); } /// Returns a buffer containing a snapshot of the surface. /// /// If compressed is true the data is encoded as PNG. static sk_sp<SkData> GetRasterData(const sk_sp<SkSurface>& offscreen_surface, bool compressed) { // Prepare an image from the surface, this image may potentially be on th GPU. auto potentially_gpu_snapshot = offscreen_surface->makeImageSnapshot(); if (!potentially_gpu_snapshot) { FML_LOG(ERROR) << "Screenshot: unable to make image screenshot"; return nullptr; } // Copy the GPU image snapshot into CPU memory. // TODO (https://github.com/flutter/flutter/issues/13498) auto cpu_snapshot = potentially_gpu_snapshot->makeRasterImage(); if (!cpu_snapshot) { FML_LOG(ERROR) << "Screenshot: unable to make raster image"; return nullptr; } // If the caller want the pixels to be compressed, there is a Skia utility to // compress to PNG. Use that. if (compressed) { return SkPngEncoder::Encode(nullptr, cpu_snapshot.get(), {}); } // Copy it into a bitmap and return the same. SkPixmap pixmap; if (!cpu_snapshot->peekPixels(&pixmap)) { FML_LOG(ERROR) << "Screenshot: unable to obtain bitmap pixels"; return nullptr; } return SkData::MakeWithCopy(pixmap.addr32(), pixmap.computeByteSize()); } OffscreenSurface::OffscreenSurface(GrDirectContext* surface_context, const SkISize& size) { offscreen_surface_ = CreateSnapshotSurface(surface_context, size); if (offscreen_surface_) { adapter_.set_canvas(offscreen_surface_->getCanvas()); } } sk_sp<SkData> OffscreenSurface::GetRasterData(bool compressed) const { return flutter::GetRasterData(offscreen_surface_, compressed); } DlCanvas* OffscreenSurface::GetCanvas() { return &adapter_; } bool OffscreenSurface::IsValid() const { return offscreen_surface_ != nullptr; } } // namespace flutter
engine/flow/layers/offscreen_surface.cc/0
{ "file_path": "engine/flow/layers/offscreen_surface.cc", "repo_id": "engine", "token_count": 1190 }
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. #ifndef FLUTTER_FLOW_LAYERS_TEXTURE_LAYER_H_ #define FLUTTER_FLOW_LAYERS_TEXTURE_LAYER_H_ #include "flutter/flow/layers/layer.h" #include "third_party/skia/include/core/SkPoint.h" #include "third_party/skia/include/core/SkSize.h" namespace flutter { class TextureLayer : public Layer { public: TextureLayer(const SkPoint& offset, const SkSize& size, int64_t texture_id, bool freeze, DlImageSampling sampling); bool IsReplacing(DiffContext* context, const Layer* layer) const override { return layer->as_texture_layer() != nullptr; } void Diff(DiffContext* context, const Layer* old_layer) override; const TextureLayer* as_texture_layer() const override { return this; } void Preroll(PrerollContext* context) override; void Paint(PaintContext& context) const override; private: SkPoint offset_; SkSize size_; int64_t texture_id_; bool freeze_; DlImageSampling sampling_; FML_DISALLOW_COPY_AND_ASSIGN(TextureLayer); }; } // namespace flutter #endif // FLUTTER_FLOW_LAYERS_TEXTURE_LAYER_H_
engine/flow/layers/texture_layer.h/0
{ "file_path": "engine/flow/layers/texture_layer.h", "repo_id": "engine", "token_count": 464 }
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/raster_cache_util.h" namespace flutter { bool RasterCacheUtil::ComputeIntegralTransCTM(const SkMatrix& in, SkMatrix* out) { // Avoid integral snapping if the matrix has complex transformation to avoid // the artifact observed in https://github.com/flutter/flutter/issues/41654. if (!in.isScaleTranslate()) { return false; } SkScalar in_tx = in.getTranslateX(); SkScalar in_ty = in.getTranslateY(); SkScalar out_tx = SkScalarRoundToScalar(in_tx); SkScalar out_ty = SkScalarRoundToScalar(in_ty); if (out_tx != in_tx || out_ty != in_ty) { // As a side effect of those tests we also know that neither translation // component was a NaN *out = in; (*out)[SkMatrix::kMTransX] = out_tx; (*out)[SkMatrix::kMTransY] = out_ty; return true; } return false; } bool RasterCacheUtil::ComputeIntegralTransCTM(const SkM44& in, SkM44* out) { // Avoid integral snapping if the matrix has complex transformation to avoid // the artifact observed in https://github.com/flutter/flutter/issues/41654. if (in.rc(0, 1) != 0 || in.rc(0, 2) != 0) { // X multiplied by either Y or Z return false; } if (in.rc(1, 0) != 0 || in.rc(1, 2) != 0) { // Y multiplied by either X or Z return false; } if (in.rc(3, 0) != 0 || in.rc(3, 1) != 0 || in.rc(3, 2) != 0 || in.rc(3, 3) != 1) { // W not identity row, therefore perspective is applied return false; } // We do not need to worry about the Z row unless the W row // has perspective entries, which we've just eliminated... SkScalar in_tx = in.rc(0, 3); SkScalar in_ty = in.rc(1, 3); SkScalar out_tx = SkScalarRoundToScalar(in_tx); SkScalar out_ty = SkScalarRoundToScalar(in_ty); if (out_tx != in_tx || out_ty != in_ty) { // As a side effect of those tests we also know that neither translation // component was a NaN *out = in; out->setRC(0, 3, out_tx); out->setRC(1, 3, out_ty); // No need to worry about Z translation because it has no effect // without perspective entries... return true; } return false; } } // namespace flutter
engine/flow/raster_cache_util.cc/0
{ "file_path": "engine/flow/raster_cache_util.cc", "repo_id": "engine", "token_count": 902 }
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. #define FML_USED_ON_EMBEDDER #include "flutter/flow/surface_frame.h" #include "flutter/testing/testing.h" namespace flutter { TEST(FlowTest, SurfaceFrameDoesNotSubmitInDtor) { SurfaceFrame::FramebufferInfo framebuffer_info; auto callback = [](const SurfaceFrame&, DlCanvas*) { EXPECT_FALSE(true); return true; }; auto surface_frame = std::make_unique<SurfaceFrame>( /*surface=*/nullptr, /*framebuffer_info=*/framebuffer_info, /*submit_callback=*/callback, /*frame_size=*/SkISize::Make(800, 600)); surface_frame.reset(); } TEST(FlowTest, SurfaceFrameDoesNotHaveEmptyCanvas) { SurfaceFrame::FramebufferInfo framebuffer_info; auto callback = [](const SurfaceFrame&, DlCanvas*) { return true; }; SurfaceFrame frame( /*surface=*/nullptr, /*framebuffer_info=*/framebuffer_info, /*submit_callback=*/callback, /*frame_size=*/SkISize::Make(800, 600), /*context_result=*/nullptr, /*display_list_fallback=*/true); EXPECT_FALSE(frame.Canvas()->GetLocalClipBounds().isEmpty()); EXPECT_FALSE(frame.Canvas()->QuickReject(SkRect::MakeLTRB(10, 10, 50, 50))); } TEST(FlowTest, SurfaceFrameDoesNotPrepareRtree) { SurfaceFrame::FramebufferInfo framebuffer_info; auto callback = [](const SurfaceFrame&, DlCanvas*) { return true; }; auto surface_frame = std::make_unique<SurfaceFrame>( /*surface=*/nullptr, /*framebuffer_info=*/framebuffer_info, /*submit_callback=*/callback, /*frame_size=*/SkISize::Make(800, 600), /*context_result=*/nullptr, /*display_list_fallback=*/true); surface_frame->Canvas()->DrawRect(SkRect::MakeWH(100, 100), DlPaint()); EXPECT_FALSE(surface_frame->BuildDisplayList()->has_rtree()); } } // namespace flutter
engine/flow/surface_frame_unittests.cc/0
{ "file_path": "engine/flow/surface_frame_unittests.cc", "repo_id": "engine", "token_count": 705 }
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/common/graphics/texture.h" #include <functional> #include "flutter/flow/testing/mock_texture.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { namespace { using int_closure = std::function<void(int)>; struct TestContextListener : public ContextListener { TestContextListener(uintptr_t p_id, int_closure p_create, int_closure p_destroy) : id(p_id), create(std::move(p_create)), destroy(std::move(p_destroy)) {} virtual ~TestContextListener() = default; const uintptr_t id; int_closure create; int_closure destroy; void OnGrContextCreated() override { create(id); } void OnGrContextDestroyed() override { destroy(id); } }; } // namespace TEST(TextureRegistryTest, UnregisterTextureCallbackTriggered) { TextureRegistry registry; auto mock_texture1 = std::make_shared<MockTexture>(0); auto mock_texture2 = std::make_shared<MockTexture>(1); registry.RegisterTexture(mock_texture1); registry.RegisterTexture(mock_texture2); ASSERT_EQ(registry.GetTexture(0), mock_texture1); ASSERT_EQ(registry.GetTexture(1), mock_texture2); ASSERT_FALSE(mock_texture1->unregistered()); ASSERT_FALSE(mock_texture2->unregistered()); registry.UnregisterTexture(0); ASSERT_EQ(registry.GetTexture(0), nullptr); ASSERT_TRUE(mock_texture1->unregistered()); ASSERT_FALSE(mock_texture2->unregistered()); registry.UnregisterTexture(1); ASSERT_EQ(registry.GetTexture(1), nullptr); ASSERT_TRUE(mock_texture1->unregistered()); ASSERT_TRUE(mock_texture2->unregistered()); } TEST(TextureRegistryTest, GrContextCallbackTriggered) { TextureRegistry registry; auto mock_texture1 = std::make_shared<MockTexture>(0); auto mock_texture2 = std::make_shared<MockTexture>(1); registry.RegisterTexture(mock_texture1); registry.RegisterTexture(mock_texture2); ASSERT_FALSE(mock_texture1->gr_context_created()); ASSERT_FALSE(mock_texture2->gr_context_created()); ASSERT_FALSE(mock_texture1->gr_context_destroyed()); ASSERT_FALSE(mock_texture2->gr_context_destroyed()); registry.OnGrContextCreated(); ASSERT_TRUE(mock_texture1->gr_context_created()); ASSERT_TRUE(mock_texture2->gr_context_created()); registry.UnregisterTexture(0); registry.OnGrContextDestroyed(); ASSERT_FALSE(mock_texture1->gr_context_destroyed()); ASSERT_TRUE(mock_texture2->gr_context_created()); } TEST(TextureRegistryTest, RegisterTextureTwice) { TextureRegistry registry; auto mock_texture1 = std::make_shared<MockTexture>(0); auto mock_texture2 = std::make_shared<MockTexture>(0); registry.RegisterTexture(mock_texture1); ASSERT_EQ(registry.GetTexture(0), mock_texture1); registry.RegisterTexture(mock_texture2); ASSERT_EQ(registry.GetTexture(0), mock_texture2); ASSERT_FALSE(mock_texture1->unregistered()); ASSERT_FALSE(mock_texture2->unregistered()); registry.UnregisterTexture(0); ASSERT_EQ(registry.GetTexture(0), nullptr); ASSERT_FALSE(mock_texture1->unregistered()); ASSERT_TRUE(mock_texture2->unregistered()); } TEST(TextureRegistryTest, ReuseSameTextureSlot) { TextureRegistry registry; auto mock_texture1 = std::make_shared<MockTexture>(0); auto mock_texture2 = std::make_shared<MockTexture>(0); registry.RegisterTexture(mock_texture1); ASSERT_EQ(registry.GetTexture(0), mock_texture1); registry.UnregisterTexture(0); ASSERT_EQ(registry.GetTexture(0), nullptr); ASSERT_TRUE(mock_texture1->unregistered()); ASSERT_FALSE(mock_texture2->unregistered()); registry.RegisterTexture(mock_texture2); ASSERT_EQ(registry.GetTexture(0), mock_texture2); registry.UnregisterTexture(0); ASSERT_EQ(registry.GetTexture(0), nullptr); ASSERT_TRUE(mock_texture1->unregistered()); ASSERT_TRUE(mock_texture2->unregistered()); } TEST(TextureRegistryTest, CallsOnGrContextCreatedInInsertionOrder) { TextureRegistry registry; std::vector<int> create_order; std::vector<int> destroy_order; auto create = [&](int id) { create_order.push_back(id); }; auto destroy = [&](int id) { destroy_order.push_back(id); }; auto a = std::make_shared<TestContextListener>(5, create, destroy); auto b = std::make_shared<TestContextListener>(4, create, destroy); auto c = std::make_shared<TestContextListener>(3, create, destroy); registry.RegisterContextListener(a->id, a); registry.RegisterContextListener(b->id, b); registry.RegisterContextListener(c->id, c); registry.OnGrContextDestroyed(); registry.OnGrContextCreated(); EXPECT_THAT(create_order, ::testing::ElementsAre(5, 4, 3)); EXPECT_THAT(destroy_order, ::testing::ElementsAre(5, 4, 3)); } } // namespace testing } // namespace flutter
engine/flow/texture_unittests.cc/0
{ "file_path": "engine/flow/texture_unittests.cc", "repo_id": "engine", "token_count": 1687 }
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_FML_ASCII_TRIE_H_ #define FLUTTER_FML_ASCII_TRIE_H_ #include <memory> #include <string> #include <vector> namespace fml { /// A trie for looking for ASCII prefixes. class AsciiTrie { public: struct TrieNode; typedef std::unique_ptr<TrieNode> TrieNodePtr; /// The max Ascii value. static const int kMaxAsciiValue = 128; /// Clear and insert all the entries into the trie. void Fill(const std::vector<std::string>& entries); /// Returns true if \p argument is prefixed by the contents of the trie. inline bool Query(const char* argument) { return !node_ || Query(node_.get(), argument); } struct TrieNode { TrieNodePtr children[kMaxAsciiValue]; }; private: static bool Query(TrieNode* trie, const char* query); TrieNodePtr node_; }; } // namespace fml #endif // FLUTTER_FML_ASCII_TRIE_H_
engine/fml/ascii_trie.h/0
{ "file_path": "engine/fml/ascii_trie.h", "repo_id": "engine", "token_count": 347 }
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/fml/concurrent_message_loop.h" #include <algorithm> #include "flutter/fml/thread.h" #include "flutter/fml/trace_event.h" namespace fml { ConcurrentMessageLoop::ConcurrentMessageLoop(size_t worker_count) : worker_count_(std::max<size_t>(worker_count, 1ul)) { for (size_t i = 0; i < worker_count_; ++i) { workers_.emplace_back([i, this]() { fml::Thread::SetCurrentThreadName(fml::Thread::ThreadConfig( std::string{"io.worker." + std::to_string(i + 1)})); WorkerMain(); }); } for (const auto& worker : workers_) { worker_thread_ids_.emplace_back(worker.get_id()); } } ConcurrentMessageLoop::~ConcurrentMessageLoop() { Terminate(); for (auto& worker : workers_) { FML_DCHECK(worker.joinable()); worker.join(); } } size_t ConcurrentMessageLoop::GetWorkerCount() const { return worker_count_; } std::shared_ptr<ConcurrentTaskRunner> ConcurrentMessageLoop::GetTaskRunner() { return std::make_shared<ConcurrentTaskRunner>(weak_from_this()); } void ConcurrentMessageLoop::PostTask(const fml::closure& task) { if (!task) { return; } std::unique_lock lock(tasks_mutex_); // Don't just drop tasks on the floor in case of shutdown. if (shutdown_) { FML_DLOG(WARNING) << "Tried to post a task to shutdown concurrent message " "loop. The task will be executed on the callers thread."; lock.unlock(); ExecuteTask(task); return; } tasks_.push(task); // Unlock the mutex before notifying the condition variable because that mutex // has to be acquired on the other thread anyway. Waiting in this scope till // it is acquired there is a pessimization. lock.unlock(); tasks_condition_.notify_one(); } void ConcurrentMessageLoop::WorkerMain() { while (true) { std::unique_lock lock(tasks_mutex_); tasks_condition_.wait(lock, [&]() { return !tasks_.empty() || shutdown_ || HasThreadTasksLocked(); }); // Shutdown cannot be read with the task mutex unlocked. bool shutdown_now = shutdown_; fml::closure task; std::vector<fml::closure> thread_tasks; if (!tasks_.empty()) { task = tasks_.front(); tasks_.pop(); } if (HasThreadTasksLocked()) { thread_tasks = GetThreadTasksLocked(); FML_DCHECK(!HasThreadTasksLocked()); } // Don't hold onto the mutex while tasks are being executed as they could // themselves try to post more tasks to the message loop. lock.unlock(); TRACE_EVENT0("flutter", "ConcurrentWorkerWake"); // Execute the primary task we woke up for. if (task) { ExecuteTask(task); } // Execute any thread tasks. for (const auto& thread_task : thread_tasks) { ExecuteTask(thread_task); } if (shutdown_now) { break; } } } void ConcurrentMessageLoop::ExecuteTask(const fml::closure& task) { task(); } void ConcurrentMessageLoop::Terminate() { std::scoped_lock lock(tasks_mutex_); shutdown_ = true; tasks_condition_.notify_all(); } void ConcurrentMessageLoop::PostTaskToAllWorkers(const fml::closure& task) { if (!task) { return; } std::scoped_lock lock(tasks_mutex_); for (const auto& worker_thread_id : worker_thread_ids_) { thread_tasks_[worker_thread_id].emplace_back(task); } tasks_condition_.notify_all(); } bool ConcurrentMessageLoop::HasThreadTasksLocked() const { return thread_tasks_.count(std::this_thread::get_id()) > 0; } std::vector<fml::closure> ConcurrentMessageLoop::GetThreadTasksLocked() { auto found = thread_tasks_.find(std::this_thread::get_id()); FML_DCHECK(found != thread_tasks_.end()); std::vector<fml::closure> pending_tasks; std::swap(pending_tasks, found->second); thread_tasks_.erase(found); return pending_tasks; } ConcurrentTaskRunner::ConcurrentTaskRunner( std::weak_ptr<ConcurrentMessageLoop> weak_loop) : weak_loop_(std::move(weak_loop)) {} ConcurrentTaskRunner::~ConcurrentTaskRunner() = default; void ConcurrentTaskRunner::PostTask(const fml::closure& task) { if (!task) { return; } if (auto loop = weak_loop_.lock()) { loop->PostTask(task); return; } FML_DLOG(WARNING) << "Tried to post to a concurrent message loop that has already died. " "Executing the task on the callers thread."; task(); } bool ConcurrentMessageLoop::RunsTasksOnCurrentThread() { std::scoped_lock lock(tasks_mutex_); for (const auto& worker_thread_id : worker_thread_ids_) { if (worker_thread_id == std::this_thread::get_id()) { return true; } } return false; } } // namespace fml
engine/fml/concurrent_message_loop.cc/0
{ "file_path": "engine/fml/concurrent_message_loop.cc", "repo_id": "engine", "token_count": 1738 }
162
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstring> #include <memory> #include <vector> #include "flutter/fml/build_config.h" #include "flutter/fml/file.h" #include "flutter/fml/mapping.h" #include "flutter/fml/paths.h" #include "flutter/fml/unique_fd.h" #include "gtest/gtest.h" static bool WriteStringToFile(const fml::UniqueFD& fd, const std::string& contents) { if (!fml::TruncateFile(fd, contents.size())) { return false; } fml::FileMapping mapping(fd, {fml::FileMapping::Protection::kWrite}); if (mapping.GetSize() != contents.size()) { return false; } if (mapping.GetMutableMapping() == nullptr) { return false; } ::memmove(mapping.GetMutableMapping(), contents.data(), contents.size()); return true; } static std::string ReadStringFromFile(const fml::UniqueFD& fd) { fml::FileMapping mapping(fd); if (mapping.GetMapping() == nullptr) { return nullptr; } return {reinterpret_cast<const char*>(mapping.GetMapping()), mapping.GetSize()}; } TEST(FileTest, CreateTemporaryAndUnlink) { auto dir_name = fml::CreateTemporaryDirectory(); ASSERT_NE(dir_name, ""); auto dir = fml::OpenDirectory(dir_name.c_str(), false, fml::FilePermission::kRead); ASSERT_TRUE(dir.is_valid()); dir.reset(); ASSERT_TRUE(fml::UnlinkDirectory(dir_name.c_str())); } TEST(FileTest, ScopedTempDirIsValid) { fml::ScopedTemporaryDirectory dir; ASSERT_TRUE(dir.fd().is_valid()); } TEST(FileTest, CanOpenFileForWriting) { fml::ScopedTemporaryDirectory dir; ASSERT_TRUE(dir.fd().is_valid()); auto fd = fml::OpenFile(dir.fd(), "some.txt", true, fml::FilePermission::kWrite); ASSERT_TRUE(fd.is_valid()); fd.reset(); ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "some.txt")); } TEST(FileTest, CanTruncateAndWrite) { fml::ScopedTemporaryDirectory dir; ASSERT_TRUE(dir.fd().is_valid()); std::string contents = "some contents here"; // On the first iteration, this tests writing and then reading a file that // didn't exist yet. On the second iteration it tests truncating, writing, // and reading a file that already existed. for (int i = 0; i < 2; i++) { { auto fd = fml::OpenFile(dir.fd(), "some.txt", true, fml::FilePermission::kReadWrite); ASSERT_TRUE(fd.is_valid()); ASSERT_TRUE(fml::TruncateFile(fd, contents.size())); fml::FileMapping mapping(fd, {fml::FileMapping::Protection::kWrite}); ASSERT_EQ(mapping.GetSize(), contents.size()); ASSERT_NE(mapping.GetMutableMapping(), nullptr); ::memcpy(mapping.GetMutableMapping(), contents.data(), contents.size()); } { auto fd = fml::OpenFile(dir.fd(), "some.txt", false, fml::FilePermission::kRead); ASSERT_TRUE(fd.is_valid()); fml::FileMapping mapping(fd); ASSERT_EQ(mapping.GetSize(), contents.size()); ASSERT_EQ( 0, ::memcmp(mapping.GetMapping(), contents.data(), contents.size())); } } fml::UnlinkFile(dir.fd(), "some.txt"); } TEST(FileTest, CreateDirectoryStructure) { fml::ScopedTemporaryDirectory dir; std::string contents = "These are my contents"; { auto sub = fml::CreateDirectory(dir.fd(), {"a", "b", "c"}, fml::FilePermission::kReadWrite); ASSERT_TRUE(sub.is_valid()); auto file = fml::OpenFile(sub, "my_contents", true, fml::FilePermission::kReadWrite); ASSERT_TRUE(file.is_valid()); ASSERT_TRUE(WriteStringToFile(file, contents)); } const char* file_path = "a/b/c/my_contents"; { auto contents_file = fml::OpenFile(dir.fd(), file_path, false, fml::FilePermission::kRead); ASSERT_EQ(ReadStringFromFile(contents_file), contents); } // Cleanup. ASSERT_TRUE(fml::UnlinkFile(dir.fd(), file_path)); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b/c")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a")); } TEST(FileTest, VisitFilesCanBeCalledTwice) { fml::ScopedTemporaryDirectory dir; { auto file = fml::OpenFile(dir.fd(), "my_contents", true, fml::FilePermission::kReadWrite); ASSERT_TRUE(file.is_valid()); } int count; fml::FileVisitor count_visitor = [&count](const fml::UniqueFD& directory, const std::string& filename) { count += 1; return true; }; count = 0; fml::VisitFiles(dir.fd(), count_visitor); ASSERT_EQ(count, 1); // Without `rewinddir` in `VisitFiles`, the following check would fail. count = 0; fml::VisitFiles(dir.fd(), count_visitor); ASSERT_EQ(count, 1); ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "my_contents")); } TEST(FileTest, CanListFilesRecursively) { fml::ScopedTemporaryDirectory dir; { auto c = fml::CreateDirectory(dir.fd(), {"a", "b", "c"}, fml::FilePermission::kReadWrite); ASSERT_TRUE(c.is_valid()); auto file1 = fml::OpenFile(c, "file1", true, fml::FilePermission::kReadWrite); auto file2 = fml::OpenFile(c, "file2", true, fml::FilePermission::kReadWrite); auto d = fml::CreateDirectory(c, {"d"}, fml::FilePermission::kReadWrite); ASSERT_TRUE(d.is_valid()); auto file3 = fml::OpenFile(d, "file3", true, fml::FilePermission::kReadWrite); ASSERT_TRUE(file1.is_valid()); ASSERT_TRUE(file2.is_valid()); ASSERT_TRUE(file3.is_valid()); } std::set<std::string> names; fml::FileVisitor visitor = [&names](const fml::UniqueFD& directory, const std::string& filename) { names.insert(filename); return true; }; fml::VisitFilesRecursively(dir.fd(), visitor); ASSERT_EQ(names, std::set<std::string>( {"a", "b", "c", "d", "file1", "file2", "file3"})); // Cleanup. ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "a/b/c/d/file3")); ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "a/b/c/file1")); ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "a/b/c/file2")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b/c/d")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b/c")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a")); } TEST(FileTest, CanStopVisitEarly) { fml::ScopedTemporaryDirectory dir; { auto d = fml::CreateDirectory(dir.fd(), {"a", "b", "c", "d"}, fml::FilePermission::kReadWrite); ASSERT_TRUE(d.is_valid()); } std::set<std::string> names; fml::FileVisitor visitor = [&names](const fml::UniqueFD& directory, const std::string& filename) { names.insert(filename); return filename == "c" ? false : true; // stop if c is found }; // Check the d is not visited as we stop at c. ASSERT_FALSE(fml::VisitFilesRecursively(dir.fd(), visitor)); ASSERT_EQ(names, std::set<std::string>({"a", "b", "c"})); // Cleanup. ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b/c/d")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b/c")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a/b")); ASSERT_TRUE(fml::UnlinkDirectory(dir.fd(), "a")); } TEST(FileTest, AtomicWriteTest) { fml::ScopedTemporaryDirectory dir; const std::string contents = "These are my contents."; auto data = std::make_unique<fml::DataMapping>( std::vector<uint8_t>{contents.begin(), contents.end()}); // Write. ASSERT_TRUE(fml::WriteAtomically(dir.fd(), "precious_data", *data)); // Read and verify. ASSERT_EQ(contents, ReadStringFromFile(fml::OpenFile(dir.fd(), "precious_data", false, fml::FilePermission::kRead))); // Cleanup. ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "precious_data")); } TEST(FileTest, IgnoreBaseDirWhenPathIsAbsolute) { fml::ScopedTemporaryDirectory dir; // Make an absolute path. std::string filename = "filename.txt"; std::string full_path = fml::paths::AbsolutePath(fml::paths::JoinPaths({dir.path(), filename})); const std::string contents = "These are my contents."; auto data = std::make_unique<fml::DataMapping>( std::vector<uint8_t>{contents.begin(), contents.end()}); // Write. ASSERT_TRUE(fml::WriteAtomically(dir.fd(), full_path.c_str(), *data)); // Test existence. ASSERT_TRUE(fml::FileExists(dir.fd(), full_path.c_str())); // Read and verify. ASSERT_EQ(contents, ReadStringFromFile(fml::OpenFile(dir.fd(), full_path.c_str(), false, fml::FilePermission::kRead))); // Cleanup. ASSERT_TRUE(fml::UnlinkFile(dir.fd(), full_path.c_str())); } TEST(FileTest, EmptyMappingTest) { fml::ScopedTemporaryDirectory dir; { auto file = fml::OpenFile(dir.fd(), "my_contents", true, fml::FilePermission::kReadWrite); fml::FileMapping mapping(file); ASSERT_TRUE(mapping.IsValid()); ASSERT_EQ(mapping.GetSize(), 0ul); ASSERT_EQ(mapping.GetMapping(), nullptr); } ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "my_contents")); } TEST(FileTest, MappingDontNeedSafeTest) { fml::ScopedTemporaryDirectory dir; { auto file = fml::OpenFile(dir.fd(), "my_contents", true, fml::FilePermission::kReadWrite); WriteStringToFile(file, "some content"); } { auto file = fml::OpenFile(dir.fd(), "my_contents", false, fml::FilePermission::kRead); fml::FileMapping mapping(file); ASSERT_TRUE(mapping.IsValid()); ASSERT_EQ(mapping.GetMutableMapping(), nullptr); ASSERT_TRUE(mapping.IsDontNeedSafe()); } { auto file = fml::OpenFile(dir.fd(), "my_contents", false, fml::FilePermission::kReadWrite); fml::FileMapping mapping(file, {fml::FileMapping::Protection::kRead, fml::FileMapping::Protection::kWrite}); ASSERT_TRUE(mapping.IsValid()); ASSERT_NE(mapping.GetMutableMapping(), nullptr); ASSERT_FALSE(mapping.IsDontNeedSafe()); } ASSERT_TRUE(fml::UnlinkFile(dir.fd(), "my_contents")); } TEST(FileTest, FileTestsWork) { fml::ScopedTemporaryDirectory dir; ASSERT_TRUE(dir.fd().is_valid()); const char* filename = "some.txt"; auto fd = fml::OpenFile(dir.fd(), filename, true, fml::FilePermission::kWrite); ASSERT_TRUE(fd.is_valid()); fd.reset(); ASSERT_TRUE(fml::FileExists(dir.fd(), filename)); ASSERT_TRUE( fml::IsFile(fml::paths::JoinPaths({dir.path(), filename}).c_str())); ASSERT_TRUE(fml::UnlinkFile(dir.fd(), filename)); } TEST(FileTest, FileTestsSupportsUnicode) { fml::ScopedTemporaryDirectory dir; ASSERT_TRUE(dir.fd().is_valid()); const char* filename = u8"äëïöüテスト☃"; auto fd = fml::OpenFile(dir.fd(), filename, true, fml::FilePermission::kWrite); ASSERT_TRUE(fd.is_valid()); fd.reset(); ASSERT_TRUE(fml::FileExists(dir.fd(), filename)); ASSERT_TRUE( fml::IsFile(fml::paths::JoinPaths({dir.path(), filename}).c_str())); ASSERT_TRUE(fml::UnlinkFile(dir.fd(), filename)); }
engine/fml/file_unittest.cc/0
{ "file_path": "engine/fml/file_unittest.cc", "repo_id": "engine", "token_count": 4878 }
163
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FML_MAKE_COPYABLE_H_ #define FLUTTER_FML_MAKE_COPYABLE_H_ #include <utility> #include "flutter/fml/memory/ref_counted.h" #include "flutter/fml/memory/ref_ptr.h" namespace fml { namespace internal { template <typename T> class CopyableLambda { public: explicit CopyableLambda(T func) : impl_(MakeRefCounted<Impl>(std::move(func))) {} template <typename... ArgType> auto operator()(ArgType&&... args) const { return impl_->func_(std::forward<ArgType>(args)...); } private: class Impl : public RefCountedThreadSafe<Impl> { public: explicit Impl(T func) : func_(std::move(func)) {} T func_; }; RefPtr<Impl> impl_; }; } // namespace internal // Provides a wrapper for a move-only lambda that is implictly convertable to an // std::function. // // std::function is copyable, but if a lambda captures an argument with a // move-only type, the lambda itself is not copyable. In order to use the lambda // in places that accept std::functions, we provide a copyable object that wraps // the lambda and is implicitly convertable to an std::function. // // EXAMPLE: // // std::unique_ptr<Foo> foo = ... // std::function<int()> func = // fml::MakeCopyable([bar = std::move(foo)]() { return bar->count(); }); // // Notice that the return type of MakeCopyable is rarely used directly. Instead, // callers typically erase the type by implicitly converting the return value // to an std::function. template <typename T> internal::CopyableLambda<T> MakeCopyable(T lambda) { return internal::CopyableLambda<T>(std::move(lambda)); } } // namespace fml #endif // FLUTTER_FML_MAKE_COPYABLE_H_
engine/fml/make_copyable.h/0
{ "file_path": "engine/fml/make_copyable.h", "repo_id": "engine", "token_count": 600 }
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. // This file provides weak pointers and weak pointer factories that work like // Chromium's |base::WeakPtr<T>| and |base::WeakPtrFactory<T>|. #ifndef FLUTTER_FML_MEMORY_WEAK_PTR_H_ #define FLUTTER_FML_MEMORY_WEAK_PTR_H_ #include <utility> #include "flutter/fml/logging.h" #include "flutter/fml/memory/ref_counted.h" #include "flutter/fml/memory/task_runner_checker.h" #include "flutter/fml/memory/thread_checker.h" #include "flutter/fml/memory/weak_ptr_internal.h" namespace fml { struct DebugThreadChecker { FML_DECLARE_THREAD_CHECKER(checker); }; struct DebugTaskRunnerChecker { FML_DECLARE_TASK_RUNNER_CHECKER(checker); }; // Forward declaration, so |WeakPtr<T>| can friend it. template <typename T> class WeakPtrFactory; // Class for "weak pointers" that can be invalidated. Valid weak pointers // can only originate from a |WeakPtrFactory| (see below), though weak // pointers are copyable and movable. // // Weak pointers are not in general thread-safe. They may only be *used* on // a single thread, namely the same thread as the "originating" // |WeakPtrFactory| (which can invalidate the weak pointers that it // generates). // // However, weak pointers may be passed to other threads, reset on other // threads, or destroyed on other threads. They may also be reassigned on // other threads (in which case they should then only be used on the thread // corresponding to the new "originating" |WeakPtrFactory|). template <typename T> class WeakPtr { public: WeakPtr() : ptr_(nullptr) {} // Copy constructor. // NOLINTNEXTLINE(google-explicit-constructor) WeakPtr(const WeakPtr<T>& r) = default; template <typename U> WeakPtr(const WeakPtr<U>& r) // NOLINT(google-explicit-constructor) : ptr_(static_cast<T*>(r.ptr_)), flag_(r.flag_), checker_(r.checker_) {} // Move constructor. WeakPtr(WeakPtr<T>&& r) = default; template <typename U> WeakPtr(WeakPtr<U>&& r) // NOLINT(google-explicit-constructor) : ptr_(static_cast<T*>(r.ptr_)), flag_(std::move(r.flag_)), checker_(r.checker_) {} // The following methods are thread-friendly, in the sense that they may be // called subject to additional synchronization. // Copy assignment. WeakPtr<T>& operator=(const WeakPtr<T>& r) = default; // Move assignment. WeakPtr<T>& operator=(WeakPtr<T>&& r) = default; void reset() { flag_ = nullptr; } // The following methods should only be called on the same thread as the // "originating" |WeakPtrFactory|. explicit operator bool() const { CheckThreadSafety(); return flag_ && flag_->is_valid(); } T* get() const { CheckThreadSafety(); return *this ? ptr_ : nullptr; } T& operator*() const { CheckThreadSafety(); FML_DCHECK(*this); return *get(); } T* operator->() const { CheckThreadSafety(); FML_DCHECK(*this); return get(); } protected: explicit WeakPtr(T* ptr, fml::RefPtr<fml::internal::WeakPtrFlag>&& flag) : ptr_(ptr), flag_(std::move(flag)) {} void CheckThreadSafety() const { FML_DCHECK_CREATION_THREAD_IS_CURRENT(checker_.checker); } private: template <typename U> friend class WeakPtr; friend class WeakPtrFactory<T>; explicit WeakPtr(T* ptr, fml::RefPtr<fml::internal::WeakPtrFlag>&& flag, const DebugThreadChecker& checker) : ptr_(ptr), flag_(std::move(flag)), checker_(checker) {} T* ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_; DebugThreadChecker checker_; // Copy/move construction/assignment supported. }; // Forward declaration, so |TaskRunnerAffineWeakPtr<T>| can friend it. template <typename T> class TaskRunnerAffineWeakPtrFactory; // A weak pointer that can be used in different threads as long as // the threads are belong to the same |TaskRunner|. // // It is still not in general thread safe as |WeakPtr|. template <typename T> class TaskRunnerAffineWeakPtr { public: TaskRunnerAffineWeakPtr() : ptr_(nullptr) {} TaskRunnerAffineWeakPtr(const TaskRunnerAffineWeakPtr<T>& r) = default; template <typename U> // NOLINTNEXTLINE(google-explicit-constructor) TaskRunnerAffineWeakPtr(const TaskRunnerAffineWeakPtr<U>& r) : ptr_(static_cast<T*>(r.ptr_)), flag_(r.flag_), checker_(r.checker_) {} TaskRunnerAffineWeakPtr(TaskRunnerAffineWeakPtr<T>&& r) = default; template <typename U> // NOLINTNEXTLINE(google-explicit-constructor) TaskRunnerAffineWeakPtr(TaskRunnerAffineWeakPtr<U>&& r) : ptr_(static_cast<T*>(r.ptr_)), flag_(std::move(r.flag_)), checker_(r.checker_) {} ~TaskRunnerAffineWeakPtr() = default; TaskRunnerAffineWeakPtr<T>& operator=(const TaskRunnerAffineWeakPtr<T>& r) = default; TaskRunnerAffineWeakPtr<T>& operator=(TaskRunnerAffineWeakPtr<T>&& r) = default; void reset() { flag_ = nullptr; } // The following methods should only be called on the same thread as the // "originating" |TaskRunnerAffineWeakPtrFactory|. explicit operator bool() const { CheckThreadSafety(); return flag_ && flag_->is_valid(); } T* get() const { CheckThreadSafety(); return *this ? ptr_ : nullptr; } T& operator*() const { CheckThreadSafety(); FML_DCHECK(*this); return *get(); } T* operator->() const { CheckThreadSafety(); FML_DCHECK(*this); return get(); } protected: void CheckThreadSafety() const { FML_DCHECK_TASK_RUNNER_IS_CURRENT(checker_.checker); } private: template <typename U> friend class TaskRunnerAffineWeakPtr; friend class TaskRunnerAffineWeakPtrFactory<T>; explicit TaskRunnerAffineWeakPtr( T* ptr, fml::RefPtr<fml::internal::WeakPtrFlag>&& flag, const DebugTaskRunnerChecker& checker) : ptr_(ptr), flag_(std::move(flag)), checker_(checker) {} T* ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_; DebugTaskRunnerChecker checker_; }; // Class that produces (valid) |WeakPtr<T>|s. Typically, this is used as a // member variable of |T| (preferably the last one -- see below), and |T|'s // methods control how weak pointers to it are vended. This class is not // thread-safe, and should only be created, destroyed and used on a single // thread. // // Example: // // class Controller { // public: // Controller() : ..., weak_factory_(this) {} // ... // // void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); } // void WorkComplete(const Result& result) { ... } // // private: // ... // // // Member variables should appear before the |WeakPtrFactory|, to ensure // // that any |WeakPtr|s to |Controller| are invalidated before its member // // variables' destructors are executed. // WeakPtrFactory<Controller> weak_factory_; // }; // // class Worker { // public: // static void StartNew(const WeakPtr<Controller>& controller) { // Worker* worker = new Worker(controller); // // Kick off asynchronous processing.... // } // // private: // Worker(const WeakPtr<Controller>& controller) : controller_(controller) {} // // void DidCompleteAsynchronousProcessing(const Result& result) { // if (controller_) // controller_->WorkComplete(result); // } // // WeakPtr<Controller> controller_; // }; template <typename T> class WeakPtrFactory { public: explicit WeakPtrFactory(T* ptr) : ptr_(ptr), flag_(fml::MakeRefCounted<fml::internal::WeakPtrFlag>()) { FML_DCHECK(ptr_); } ~WeakPtrFactory() { CheckThreadSafety(); flag_->Invalidate(); } // Gets a new weak pointer, which will be valid until this object is // destroyed. WeakPtr<T> GetWeakPtr() const { return WeakPtr<T>(ptr_, flag_.Clone(), checker_); } private: // Note: See weak_ptr_internal.h for an explanation of why we store the // pointer here, instead of in the "flag". T* const ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_; void CheckThreadSafety() const { FML_DCHECK_CREATION_THREAD_IS_CURRENT(checker_.checker); } DebugThreadChecker checker_; FML_DISALLOW_COPY_AND_ASSIGN(WeakPtrFactory); }; // A type of |WeakPtrFactory| that produces |TaskRunnerAffineWeakPtr| instead of // |WeakPtr|. template <typename T> class TaskRunnerAffineWeakPtrFactory { public: explicit TaskRunnerAffineWeakPtrFactory(T* ptr) : ptr_(ptr), flag_(fml::MakeRefCounted<fml::internal::WeakPtrFlag>()) { FML_DCHECK(ptr_); } ~TaskRunnerAffineWeakPtrFactory() { CheckThreadSafety(); flag_->Invalidate(); } // Gets a new weak pointer, which will be valid until this object is // destroyed. TaskRunnerAffineWeakPtr<T> GetWeakPtr() const { return TaskRunnerAffineWeakPtr<T>(ptr_, flag_.Clone(), checker_); } private: // Note: See weak_ptr_internal.h for an explanation of why we store the // pointer here, instead of in the "flag". T* const ptr_; fml::RefPtr<fml::internal::WeakPtrFlag> flag_; void CheckThreadSafety() const { FML_DCHECK_TASK_RUNNER_IS_CURRENT(checker_.checker); } DebugTaskRunnerChecker checker_; FML_DISALLOW_COPY_AND_ASSIGN(TaskRunnerAffineWeakPtrFactory); }; } // namespace fml #endif // FLUTTER_FML_MEMORY_WEAK_PTR_H_
engine/fml/memory/weak_ptr.h/0
{ "file_path": "engine/fml/memory/weak_ptr.h", "repo_id": "engine", "token_count": 3266 }
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. #ifndef FLUTTER_FML_PATHS_H_ #define FLUTTER_FML_PATHS_H_ #include <string> #include <utility> #include "flutter/fml/unique_fd.h" namespace fml { namespace paths { std::pair<bool, std::string> GetExecutablePath(); std::pair<bool, std::string> GetExecutableDirectoryPath(); // Get the directory to the application's caches directory. fml::UniqueFD GetCachesDirectory(); std::string JoinPaths(std::initializer_list<std::string> components); // Returns the absolute path of a possibly relative path. // It doesn't consult the filesystem or simplify the path. std::string AbsolutePath(const std::string& path); // Returns the directory name component of the given path. std::string GetDirectoryName(const std::string& path); // Decodes a URI encoded string. std::string SanitizeURIEscapedCharacters(const std::string& str); // Converts a file URI to a path. std::string FromURI(const std::string& uri); } // namespace paths } // namespace fml #endif // FLUTTER_FML_PATHS_H_
engine/fml/paths.h/0
{ "file_path": "engine/fml/paths.h", "repo_id": "engine", "token_count": 352 }
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. #include "flutter/fml/platform/darwin/cf_utils.h" #include "flutter/testing/testing.h" namespace fml { namespace testing { TEST(CFTest, CanCreateRefs) { CFRef<CFMutableStringRef> string(CFStringCreateMutable(kCFAllocatorDefault, 100u)); // Cast ASSERT_TRUE(static_cast<bool>(string)); ASSERT_TRUE(string); const auto ref_count = CFGetRetainCount(string); // Copy & Reset { CFRef<CFMutableStringRef> string2 = string; ASSERT_TRUE(string2); ASSERT_EQ(ref_count + 1u, CFGetRetainCount(string)); ASSERT_EQ(CFGetRetainCount(string2), CFGetRetainCount(string)); string2.Reset(); ASSERT_FALSE(string2); ASSERT_EQ(ref_count, CFGetRetainCount(string)); } // Release { auto string3 = string; ASSERT_TRUE(string3); ASSERT_EQ(ref_count + 1u, CFGetRetainCount(string)); auto raw_string3 = string3.Release(); ASSERT_FALSE(string3); ASSERT_EQ(ref_count + 1u, CFGetRetainCount(string)); CFRelease(raw_string3); ASSERT_EQ(ref_count, CFGetRetainCount(string)); } // Move { auto string_source = string; ASSERT_TRUE(string_source); auto string_move = std::move(string_source); ASSERT_FALSE(string_source); // NOLINT(bugprone-use-after-move) ASSERT_EQ(ref_count + 1u, CFGetRetainCount(string)); string_move.Reset(); ASSERT_EQ(ref_count, CFGetRetainCount(string)); } // Move assign. { auto string_move_assign = std::move(string); ASSERT_FALSE(string); // NOLINT(bugprone-use-after-move) ASSERT_EQ(ref_count, CFGetRetainCount(string_move_assign)); } } } // namespace testing } // namespace fml
engine/fml/platform/darwin/cf_utils_unittests.mm/0
{ "file_path": "engine/fml/platform/darwin/cf_utils_unittests.mm", "repo_id": "engine", "token_count": 702 }
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. #ifndef FLUTTER_FML_PLATFORM_DARWIN_SCOPED_TYPEREF_H_ #define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_TYPEREF_H_ #include "flutter/fml/compiler_specific.h" #include "flutter/fml/platform/darwin/scoped_policy.h" namespace fml { // ScopedTypeRef<> is patterned after std::unique_ptr<>, but maintains ownership // of a reference to any type that is maintained by Retain and Release methods. // // The Traits structure must provide the Retain and Release methods for type T. // A default ScopedTypeRefTraits is used but not defined, and should be defined // for each type to use this interface. For example, an appropriate definition // of ScopedTypeRefTraits for CGLContextObj would be: // // template<> // struct ScopedTypeRefTraits<CGLContextObj> { // static CGLContextObj InvalidValue() { return nullptr; } // static CGLContextObj Retain(CGLContextObj object) { // CGLContextRetain(object); // return object; // } // static void Release(CGLContextObj object) { CGLContextRelease(object); } // }; // // For the many types that have pass-by-pointer create functions, the function // InitializeInto() is provided to allow direct initialization and assumption // of ownership of the object. For example, continuing to use the above // CGLContextObj specialization: // // fml::ScopedTypeRef<CGLContextObj> context; // CGLCreateContext(pixel_format, share_group, context.InitializeInto()); // // For initialization with an existing object, the caller may specify whether // the ScopedTypeRef<> being initialized is assuming the caller's existing // ownership of the object (and should not call Retain in initialization) or if // it should not assume this ownership and must create its own (by calling // Retain in initialization). This behavior is based on the |policy| parameter, // with |kAssume| for the former and |kRetain| for the latter. The default // policy is to |kAssume|. template <typename T> struct ScopedTypeRefTraits; template <typename T, typename Traits = ScopedTypeRefTraits<T>> class ScopedTypeRef { public: typedef T element_type; explicit ScopedTypeRef( __unsafe_unretained T object = Traits::InvalidValue(), fml::scoped_policy::OwnershipPolicy policy = fml::scoped_policy::kAssume) : object_(object) { if (object_ && policy == fml::scoped_policy::kRetain) { object_ = Traits::Retain(object_); } } // NOLINTNEXTLINE(google-explicit-constructor) ScopedTypeRef(const ScopedTypeRef<T, Traits>& that) : object_(that.object_) { if (object_) { object_ = Traits::Retain(object_); } } // This allows passing an object to a function that takes its superclass. template <typename R, typename RTraits> explicit ScopedTypeRef(const ScopedTypeRef<R, RTraits>& that_as_subclass) : object_(that_as_subclass.get()) { if (object_) { object_ = Traits::Retain(object_); } } // NOLINTNEXTLINE(google-explicit-constructor) ScopedTypeRef(ScopedTypeRef<T, Traits>&& that) : object_(that.object_) { that.object_ = Traits::InvalidValue(); } ~ScopedTypeRef() { if (object_) { Traits::Release(object_); } } ScopedTypeRef& operator=(const ScopedTypeRef<T, Traits>& that) { reset(that.get(), fml::scoped_policy::kRetain); return *this; } // This is to be used only to take ownership of objects that are created // by pass-by-pointer create functions. To enforce this, require that the // object be reset to NULL before this may be used. [[nodiscard]] T* InitializeInto() { FML_DCHECK(!object_); return &object_; } void reset(__unsafe_unretained T object = Traits::InvalidValue(), fml::scoped_policy::OwnershipPolicy policy = fml::scoped_policy::kAssume) { if (object && policy == fml::scoped_policy::kRetain) { object = Traits::Retain(object); } if (object_) { Traits::Release(object_); } object_ = object; } bool operator==(__unsafe_unretained T that) const { return object_ == that; } bool operator!=(__unsafe_unretained T that) const { return object_ != that; } // NOLINTNEXTLINE(google-explicit-constructor) operator T() const __attribute((ns_returns_not_retained)) { return object_; } T get() const __attribute((ns_returns_not_retained)) { return object_; } void swap(ScopedTypeRef& that) { __unsafe_unretained T temp = that.object_; that.object_ = object_; object_ = temp; } protected: // ScopedTypeRef<>::release() is like std::unique_ptr<>::release. It is NOT // a wrapper for Release(). To force a ScopedTypeRef<> object to call // Release(), use ScopedTypeRef<>::reset(). [[nodiscard]] T release() __attribute((ns_returns_not_retained)) { __unsafe_unretained T temp = object_; object_ = Traits::InvalidValue(); return temp; } private: __unsafe_unretained T object_; }; } // namespace fml #endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_TYPEREF_H_
engine/fml/platform/darwin/scoped_typeref.h/0
{ "file_path": "engine/fml/platform/darwin/scoped_typeref.h", "repo_id": "engine", "token_count": 1774 }
168
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/platform/fuchsia/task_observers.h" #include <map> namespace fml { thread_local std::map<intptr_t, fit::closure> tTaskObservers; void ExecuteAfterTaskObservers() { for (const auto& callback : tTaskObservers) { callback.second(); } } void CurrentMessageLoopAddAfterTaskObserver(intptr_t key, fit::closure observer) { if (observer) { tTaskObservers[key] = std::move(observer); } } void CurrentMessageLoopRemoveAfterTaskObserver(intptr_t key) { tTaskObservers.erase(key); } } // namespace fml
engine/fml/platform/fuchsia/task_observers.cc/0
{ "file_path": "engine/fml/platform/fuchsia/task_observers.cc", "repo_id": "engine", "token_count": 287 }
169
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/command_line.h" #include <windows.h> #include <Shellapi.h> #include <memory> namespace fml { std::optional<CommandLine> CommandLineFromPlatform() { wchar_t* command_line = GetCommandLineW(); int unicode_argc; std::unique_ptr<wchar_t*[], decltype(::LocalFree)*> unicode_argv( CommandLineToArgvW(command_line, &unicode_argc), ::LocalFree); if (!unicode_argv) { return std::nullopt; } std::vector<std::string> utf8_argv; for (int i = 0; i < unicode_argc; ++i) { wchar_t* arg = unicode_argv[i]; int arg_len = WideCharToMultiByte(CP_UTF8, 0, arg, wcslen(arg), nullptr, 0, nullptr, nullptr); std::string utf8_arg(arg_len, 0); WideCharToMultiByte(CP_UTF8, 0, arg, -1, utf8_arg.data(), utf8_arg.size(), nullptr, nullptr); utf8_argv.push_back(std::move(utf8_arg)); } return CommandLineFromIterators(utf8_argv.begin(), utf8_argv.end()); } } // namespace fml
engine/fml/platform/win/command_line_win.cc/0
{ "file_path": "engine/fml/platform/win/command_line_win.cc", "repo_id": "engine", "token_count": 496 }
170