text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:header_guard_check/src/header_file.dart'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as p; import 'package:source_span/source_span.dart'; Future<int> main(List<String> args) async { void withTestFile(String path, String contents, void Function(io.File) fn) { // Create a temporary file and delete it when we're done. final io.Directory tempDir = io.Directory.systemTemp.createTempSync('header_guard_check_test'); final io.File file = io.File(p.join(tempDir.path, path)); file.writeAsStringSync(contents); try { fn(file); } finally { tempDir.deleteSync(recursive: true); } } group('HeaderGuardSpans', () { test('parses #ifndef', () { const String input = '#ifndef FOO_H_'; final HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: SourceSpanWithContext( SourceLocation(0), SourceLocation(input.length), input, input, ), defineSpan: null, endifSpan: null, ); expect(guard.ifndefValue, 'FOO_H_'); }); test('ignores #ifndef if omitted', () { const HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: null, defineSpan: null, endifSpan: null, ); expect(guard.ifndefValue, isNull); }); test('ignores #ifndef if invalid', () { const String input = '#oops FOO_H_'; final HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: SourceSpanWithContext( SourceLocation(0), SourceLocation(input.length), input, input, ), defineSpan: null, endifSpan: null, ); expect(guard.ifndefValue, isNull); }); test('parses #define', () { const String input = '#define FOO_H_'; final HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: null, defineSpan: SourceSpanWithContext( SourceLocation(0), SourceLocation(input.length), input, input, ), endifSpan: null, ); expect(guard.defineValue, 'FOO_H_'); }); test('ignores #define if omitted', () { const HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: null, defineSpan: null, endifSpan: null, ); expect(guard.defineValue, isNull); }); test('ignores #define if invalid', () { const String input = '#oops FOO_H_'; final HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: null, defineSpan: SourceSpanWithContext( SourceLocation(0), SourceLocation(input.length), input, input, ), endifSpan: null, ); expect(guard.defineValue, isNull); }); test('parses #endif', () { const String input = '#endif // FOO_H_'; final HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: null, defineSpan: null, endifSpan: SourceSpanWithContext( SourceLocation(0), SourceLocation(input.length), input, input, ), ); expect(guard.endifValue, 'FOO_H_'); }); test('ignores #endif if omitted', () { const HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: null, defineSpan: null, endifSpan: null, ); expect(guard.endifValue, isNull); }); test('ignores #endif if invalid', () { const String input = '#oops // FOO_H_'; final HeaderGuardSpans guard = HeaderGuardSpans( ifndefSpan: null, defineSpan: null, endifSpan: SourceSpanWithContext( SourceLocation(0), SourceLocation(input.length), input, input, ), ); expect(guard.endifValue, isNull); }); }); group('HeaderFile', () { test('produces a valid header guard name from various file names', () { // All of these should produce the name `FOO_BAR_BAZ_H_`. const List<String> inputs = <String>[ 'foo_bar_baz.h', 'foo-bar-baz.h', 'foo_bar-baz.h', 'foo-bar_baz.h', 'foo+bar+baz.h', ]; for (final String input in inputs) { final HeaderFile headerFile = HeaderFile.from( input, guard: null, pragmaOnce: null, ); expect(headerFile.computeExpectedName(engineRoot: ''), endsWith('FOO_BAR_BAZ_H_')); } }); test('parses a header file with a valid guard', () { final String input = <String>[ '#ifndef FOO_H_', '#define FOO_H_', '', '#endif // FOO_H_', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.guard!.ifndefValue, 'FOO_H_'); expect(headerFile.guard!.defineValue, 'FOO_H_'); expect(headerFile.guard!.endifValue, 'FOO_H_'); }); }); test('parses a header file with an invalid #endif', () { final String input = <String>[ '#ifndef FOO_H_', '#define FOO_H_', '', // No comment after the #endif. '#endif', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.guard!.ifndefValue, 'FOO_H_'); expect(headerFile.guard!.defineValue, 'FOO_H_'); expect(headerFile.guard!.endifValue, isNull); }); }); test('parses a header file with a missing #define', () { final String input = <String>[ '#ifndef FOO_H_', // No #define. '', '#endif // FOO_H_', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.guard!.ifndefValue, 'FOO_H_'); expect(headerFile.guard!.defineValue, isNull); expect(headerFile.guard!.endifValue, 'FOO_H_'); }); }); test('parses a header file with a missing #ifndef', () { final String input = <String>[ // No #ifndef. '#define FOO_H_', '', '#endif // FOO_H_', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.guard, isNull); }); }); test('parses a header file with a #pragma once', () { final String input = <String>[ '#pragma once', '', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.pragmaOnce, isNotNull); }); }); test('fixes a file that uses #pragma once', () { final String input = <String>[ '#pragma once', '', '// ...', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.fix(engineRoot: p.dirname(file.path)), isTrue); expect(file.readAsStringSync(), <String>[ '#ifndef FLUTTER_FOO_H_', '#define FLUTTER_FOO_H_', '', '// ...', '#endif // FLUTTER_FOO_H_', '', ].join('\n')); }); }); test('fixes a file with an incorrect header guard', () { final String input = <String>[ '#ifndef FOO_H_', '#define FOO_H_', '', '#endif // FOO_H_', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.fix(engineRoot: p.dirname(file.path)), isTrue); expect(file.readAsStringSync(), <String>[ '#ifndef FLUTTER_FOO_H_', '#define FLUTTER_FOO_H_', '', '#endif // FLUTTER_FOO_H_', '', ].join('\n')); }); }); test('fixes a file with no header guard', () { final String input = <String>[ '// 1.', '// 2.', '// 3.', '', "#import 'flutter/shell/platform/darwin/Flutter.h'", '', '@protocl Flutter', '', '@end', '', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.fix(engineRoot: p.dirname(file.path)), isTrue); expect(file.readAsStringSync(), <String>[ '// 1.', '// 2.', '// 3.', '', '#ifndef FLUTTER_FOO_H_', '#define FLUTTER_FOO_H_', '', "#import 'flutter/shell/platform/darwin/Flutter.h'", '', '@protocl Flutter', '', '@end', '', '#endif // FLUTTER_FOO_H_', '', ].join('\n')); }); }); test('does not touch a file with an existing guard and another #define', () { final String input = <String>[ '// 1.', '// 2.', '// 3.', '', '#define FML_USED_ON_EMBEDDER', '', '#ifndef FLUTTER_FOO_H_', '#define FLUTTER_FOO_H_', '', '#endif // FLUTTER_FOO_H_', '', ].join('\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.fix(engineRoot: p.dirname(file.path)), isFalse); }); }); test('is OK with windows-style CRLF file with a valid header guard', () { final String input = <String>[ '#ifndef FLUTTER_FOO_H_', '#define FLUTTER_FOO_H_', '', '// ...', '', '#endif // FLUTTER_FOO_H_', ].join('\r\n'); withTestFile('foo.h', input, (io.File file) { final HeaderFile headerFile = HeaderFile.parse(file.path); expect(headerFile.pragmaOnce, isNull); expect(headerFile.guard!.ifndefValue, 'FLUTTER_FOO_H_'); expect(headerFile.guard!.defineValue, 'FLUTTER_FOO_H_'); expect(headerFile.guard!.endifValue, 'FLUTTER_FOO_H_'); }); }); }); return 0; }
engine/tools/header_guard_check/test/header_file_test.dart/0
{ "file_path": "engine/tools/header_guard_check/test/header_file_test.dart", "repo_id": "engine", "token_count": 5002 }
450
# 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. name: licenses publish_to: none environment: sdk: '>=3.2.0-0 <4.0.0' # Do not add any dependencies that require more than what is provided # in //third_party.pkg, //third_party/dart/pkg, or # //third_party/dart/third_party/pkg. # In particular, package:test is not usable here. # If you do add packages here, make sure you can run `pub get # --offline`, and check the .packages and .package_config to make sure # all the paths are relative to this directory into //third_party/dart dependencies: archive: any args: any collection: any crypto: any meta: any path: any dev_dependencies: litetest: any dependency_overrides: archive: path: ../../third_party/pkg/archive args: path: ../../../third_party/dart/third_party/pkg/args async_helper: path: ../../../third_party/dart/pkg/async_helper collection: path: ../../../third_party/dart/third_party/pkg/collection crypto: path: ../../../third_party/dart/third_party/pkg/crypto expect: path: ../../../third_party/dart/pkg/expect litetest: path: ../../testing/litetest meta: path: ../../../third_party/dart/pkg/meta path: path: ../../../third_party/dart/third_party/pkg/path smith: path: ../../../third_party/dart/pkg/smith typed_data: path: ../../../third_party/dart/third_party/pkg/typed_data
engine/tools/licenses/pubspec.yaml/0
{ "file_path": "engine/tools/licenses/pubspec.yaml", "repo_id": "engine", "token_count": 548 }
451
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert' as convert; import 'dart:io' as io show Directory, File; import 'package:path/path.dart' as p; import 'build_config.dart'; /// This is a utility class for reading all of the build configurations from /// a subdirectory of the engine repo. After building an instance of this class, /// the build configurations can be accessed on the [configs] getter. class BuildConfigLoader { BuildConfigLoader({required this.buildConfigsDir}); /// Any errors encountered while parsing and loading the build config files /// are accumulated in this list as strings. It should be checked for errors /// after the first access to the [configs] getter. final List<String> errors = <String>[]; /// The directory where the engine's build config .json files exist. final io.Directory buildConfigsDir; /// Walks [buildConfigsDir] looking for .json files, which it attempts to /// parse as engine build configs. JSON parsing errors during this process /// are added as strings to the [errors] list. That last should be checked /// for errors after accessing this getter. /// /// The [BuilderConfig]s given by this getter should be further checked for /// validity by calling `BuildConfig.check()` on each one. See /// `bin/check.dart` for an example. late final Map<String, BuilderConfig> configs = () { return _parseAllBuildConfigs(buildConfigsDir); }(); Map<String, BuilderConfig> _parseAllBuildConfigs(io.Directory dir) { final Map<String, BuilderConfig> result = <String, BuilderConfig>{}; if (!dir.existsSync()) { errors.add('${buildConfigsDir.path} does not exist.'); return result; } final List<io.File> jsonFiles = dir .listSync(recursive: true) .whereType<io.File>() .where((io.File f) => f.path.endsWith('.json')) .toList(); for (final io.File jsonFile in jsonFiles) { final String basename = p.basename(jsonFile.path); final String name = basename.substring( 0, basename.length - 5, ); final String jsonData = jsonFile.readAsStringSync(); final dynamic maybeJson; try { maybeJson = convert.jsonDecode(jsonData); } on FormatException catch (e) { errors.add('While parsing ${jsonFile.path}:\n$e'); continue; } if (maybeJson is! Map<String, Object?>) { errors.add('${jsonFile.path} did not contain a json map.'); continue; } result[name] = BuilderConfig.fromJson(path: jsonFile.path, map: maybeJson); } return result; } }
engine/tools/pkg/engine_build_configs/lib/src/build_config_loader.dart/0
{ "file_path": "engine/tools/pkg/engine_build_configs/lib/src/build_config_loader.dart", "repo_id": "engine", "token_count": 921 }
452
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:git_repo_tools/git_repo_tools.dart'; import 'package:litetest/litetest.dart'; import 'package:process_fakes/process_fakes.dart'; void main() { const String fakeShaHash = 'fake-sha-hash'; test('returns non-deleted files which differ from merge-base with main', () async { final Fixture fixture = Fixture( processManager: FakeProcessManager( onStart: (List<String> command) { // Succeed calling "git merge-base --fork-point FETCH_HEAD HEAD". if (command.join(' ').startsWith('git merge-base --fork-point')) { return FakeProcess(stdout: fakeShaHash); } // Succeed calling "git fetch upstream main". if (command.join(' ') == 'git fetch upstream main') { return FakeProcess(); } // Succeed calling "git diff --name-only --diff-filter=ACMRT fake-sha-hash". if (command.join(' ') == 'git diff --name-only --diff-filter=ACMRT $fakeShaHash') { return FakeProcess(stdout: 'file1\nfile2'); } // Otherwise, fail. return FakeProcessManager.unhandledStart(command); }, ), ); try { final List<io.File> changedFiles = await fixture.gitRepo.changedFiles; expect(changedFiles, hasLength(2)); expect(changedFiles[0].path, endsWith('file1')); expect(changedFiles[1].path, endsWith('file2')); } finally { fixture.gitRepo.root.deleteSync(recursive: true); } }); test('returns non-deleted files which differ from default merge-base', () async { final Fixture fixture = Fixture( processManager: FakeProcessManager( onStart: (List<String> command) { if (command.join(' ').startsWith('git merge-base --fork-point')) { return FakeProcess(exitCode: 1); } if (command.join(' ').startsWith('git merge-base')) { return FakeProcess(stdout: fakeShaHash); } if (command.join(' ') == 'git fetch upstream main') { return FakeProcess(); } if (command.join(' ') == 'git diff --name-only --diff-filter=ACMRT $fakeShaHash') { return FakeProcess(stdout: 'file1\nfile2'); } // Otherwise, fail. return FakeProcessManager.unhandledStart(command); }, ), ); try { final List<io.File> changedFiles = await fixture.gitRepo.changedFiles; expect(changedFiles, hasLength(2)); expect(changedFiles[0].path, endsWith('file1')); expect(changedFiles[1].path, endsWith('file2')); } finally { fixture.gitRepo.root.deleteSync(recursive: true); } }); test('returns non-deleted files which differ from HEAD', () async { final Fixture fixture = Fixture( processManager: FakeProcessManager( onStart: (List<String> command) { if (command.join(' ') == 'git fetch upstream main') { return FakeProcess(); } if (command.join(' ') == 'git diff-tree --no-commit-id --name-only --diff-filter=ACMRT -r HEAD') { return FakeProcess(stdout: 'file1\nfile2'); } // Otherwise, fail. return FakeProcessManager.unhandledStart(command); }, ), ); try { final List<io.File> changedFiles = await fixture.gitRepo.changedFilesAtHead; expect(changedFiles, hasLength(2)); expect(changedFiles[0].path, endsWith('file1')); expect(changedFiles[1].path, endsWith('file2')); } finally { fixture.gitRepo.root.deleteSync(recursive: true); } }); test('returns non-deleted files which differ from HEAD when merge-base fails', () async { final Fixture fixture = Fixture( processManager: FakeProcessManager( onStart: (List<String> command) { if (command.join(' ') == 'git fetch upstream main') { return FakeProcess(); } if (command.join(' ') == 'git diff-tree --no-commit-id --name-only --diff-filter=ACMRT -r HEAD') { return FakeProcess(stdout: 'file1\nfile2'); } if (command.join(' ').startsWith('git merge-base --fork-point')) { return FakeProcess(exitCode: 1); } if (command.join(' ').startsWith('git merge-base')) { return FakeProcess(stdout: fakeShaHash); } // Otherwise, fail. return FakeProcessManager.unhandledStart(command); }, ), ); try { final List<io.File> changedFiles = await fixture.gitRepo.changedFilesAtHead; expect(changedFiles, hasLength(2)); expect(changedFiles[0].path, endsWith('file1')); expect(changedFiles[1].path, endsWith('file2')); } finally { fixture.gitRepo.root.deleteSync(recursive: true); } }); test('verbose output is captured', () async { final Fixture fixture = Fixture( processManager: FakeProcessManager( onStart: (List<String> command) { if (command.join(' ').startsWith('git merge-base --fork-point')) { return FakeProcess(exitCode: 1); } if (command.join(' ').startsWith('git merge-base')) { return FakeProcess(stdout: fakeShaHash); } if (command.join(' ') == 'git fetch upstream main') { return FakeProcess(); } if (command.join(' ') == 'git diff --name-only --diff-filter=ACMRT $fakeShaHash') { return FakeProcess(stdout: 'file1\nfile2'); } // Otherwise, fail. return FakeProcessManager.unhandledStart(command); }, ), verbose: true, ); try { await fixture.gitRepo.changedFiles; expect(fixture.logSink.toString(), contains('git merge-base --fork-point failed, using default merge-base')); expect(fixture.logSink.toString(), contains('git diff output:\nfile1\nfile2')); } finally { fixture.gitRepo.root.deleteSync(recursive: true); } }); } final class Fixture { factory Fixture({ FakeProcessManager? processManager, bool verbose = false, }) { final io.Directory root = io.Directory.systemTemp.createTempSync('git_repo_tools.test'); final StringBuffer logSink = StringBuffer(); processManager ??= FakeProcessManager(); return Fixture._( gitRepo: GitRepo.fromRoot(root, logSink: logSink, processManager: processManager, verbose: verbose, ), logSink: logSink, ); } const Fixture._({ required this.gitRepo, required this.logSink, }); final GitRepo gitRepo; final StringBuffer logSink; }
engine/tools/pkg/git_repo_tools/test/git_repo_tools_test.dart/0
{ "file_path": "engine/tools/pkg/git_repo_tools/test/git_repo_tools_test.dart", "repo_id": "engine", "token_count": 2861 }
453
// 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_VULKAN_PROCS_VULKAN_INTERFACE_H_ #define FLUTTER_VULKAN_PROCS_VULKAN_INTERFACE_H_ #include <string> #include "flutter/fml/build_config.h" #include "flutter/fml/logging.h" #if FML_OS_ANDROID #ifndef VK_USE_PLATFORM_ANDROID_KHR #define VK_USE_PLATFORM_ANDROID_KHR 1 #endif // VK_USE_PLATFORM_ANDROID_KHR #endif // FML_OS_ANDROID #if OS_FUCHSIA #ifndef VK_USE_PLATFORM_MAGMA_KHR #define VK_USE_PLATFORM_MAGMA_KHR 1 #endif // VK_USE_PLATFORM_MAGMA_KHR #ifndef VK_USE_PLATFORM_FUCHSIA #define VK_USE_PLATFORM_FUCHSIA 1 #endif // VK_USE_PLATFORM_FUCHSIA #endif // OS_FUCHSIA #include <vulkan/vulkan.h> #define VK_CALL_LOG_ERROR(expression) VK_CALL_LOG(expression, ERROR) #define VK_CALL_LOG_FATAL(expression) VK_CALL_LOG(expression, FATAL) #define VK_CALL_LOG(expression, severity) \ ({ \ __typeof__(expression) _rc = (expression); \ if (_rc != VK_SUCCESS) { \ FML_LOG(severity) << "Vulkan call '" << #expression \ << "' failed with error " \ << vulkan::VulkanResultToString(_rc); \ } \ _rc; \ }) namespace vulkan { std::string VulkanResultToString(VkResult result); } // namespace vulkan #endif // FLUTTER_VULKAN_PROCS_VULKAN_INTERFACE_H_
engine/vulkan/procs/vulkan_interface.h/0
{ "file_path": "engine/vulkan/procs/vulkan_interface.h", "repo_id": "engine", "token_count": 876 }
454
// 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_VULKAN_VULKAN_WINDOW_H_ #define FLUTTER_VULKAN_VULKAN_WINDOW_H_ #include <memory> #include <tuple> #include <utility> #include <vector> #include "flutter/fml/compiler_specific.h" #include "flutter/fml/macros.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/vk/GrVkBackendContext.h" namespace vulkan { class VulkanNativeSurface; class VulkanDevice; class VulkanSurface; class VulkanSwapchain; class VulkanImage; class VulkanApplication; class VulkanBackbuffer; class VulkanWindow { public: //------------------------------------------------------------------------------ /// @brief Construct a VulkanWindow. Let it implicitly create a /// GrDirectContext. /// VulkanWindow(fml::RefPtr<VulkanProcTable> proc_table, std::unique_ptr<VulkanNativeSurface> native_surface); //------------------------------------------------------------------------------ /// @brief Construct a VulkanWindow. Let reuse an existing /// GrDirectContext built by another VulkanWindow. /// VulkanWindow(const sk_sp<GrDirectContext>& context, fml::RefPtr<VulkanProcTable> proc_table, std::unique_ptr<VulkanNativeSurface> native_surface); ~VulkanWindow(); bool IsValid() const; GrDirectContext* GetSkiaGrContext(); sk_sp<SkSurface> AcquireSurface(); bool SwapBuffers(); private: bool valid_; fml::RefPtr<VulkanProcTable> vk_; std::unique_ptr<VulkanApplication> application_; std::unique_ptr<VulkanDevice> logical_device_; std::unique_ptr<VulkanSurface> surface_; std::unique_ptr<VulkanSwapchain> swapchain_; sk_sp<skgpu::VulkanMemoryAllocator> memory_allocator_; sk_sp<GrDirectContext> skia_gr_context_; bool CreateSkiaGrContext(); bool CreateSkiaBackendContext(GrVkBackendContext* context); [[nodiscard]] bool RecreateSwapchain(); FML_DISALLOW_COPY_AND_ASSIGN(VulkanWindow); }; } // namespace vulkan #endif // FLUTTER_VULKAN_VULKAN_WINDOW_H_
engine/vulkan/vulkan_window.h/0
{ "file_path": "engine/vulkan/vulkan_window.h", "repo_id": "engine", "token_count": 848 }
455
name: web_engine_tester # Keep the SDK version range in sync with lib/web_ui/pubspec.yaml environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: js: 0.6.4 stream_channel: 2.1.1 test: 1.24.8 webkit_inspection_protocol: 1.0.0 stack_trace: 1.10.0 ui: path: ../../lib/web_ui
engine/web_sdk/web_engine_tester/pubspec.yaml/0
{ "file_path": "engine/web_sdk/web_engine_tester/pubspec.yaml", "repo_id": "engine", "token_count": 136 }
456
<component name="libraryTable"> <library name="com.google.guava:guava:28.2-jre" type="repository"> <properties maven-id="com.google.guava:guava:28.2-jre" /> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/com/google/guava/guava/28.2-jre/guava-28.2-jre.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/com/google/guava/failureaccess/1.0.1/failureaccess-1.0.1.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/com/google/guava/listenablefuture/9999.0-empty-to-avoid-conflict-with-guava/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/org/checkerframework/checker-qual/2.10.0/checker-qual-2.10.0.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/com/google/errorprone/error_prone_annotations/2.3.4/error_prone_annotations-2.3.4.jar!/" /> <root url="jar://$MAVEN_REPOSITORY$/com/google/j2objc/j2objc-annotations/1.3/j2objc-annotations-1.3.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
flutter-intellij/.idea/libraries/com_google_guava_guava_28_2_jre.xml/0
{ "file_path": "flutter-intellij/.idea/libraries/com_google_guava_guava_28_2_jre.xml", "repo_id": "flutter-intellij", "token_count": 520 }
457
Thanks for the feedback! If your issue is related to the Flutter framework itself, please open an issue at [github.com/flutter/flutter](https://github.com/flutter/flutter/issues/new). ## Steps to Reproduce _Please tell us what you were doing and what went wrong_ ## Version info Please paste the output of running `flutter doctor -v` here (available from the command line or from `Tools > Flutter > Flutter Doctor`). It will provide the version of the Flutter framework as well as of the IntelliJ plugin.
flutter-intellij/ISSUE_TEMPLATE.md/0
{ "file_path": "flutter-intellij/ISSUE_TEMPLATE.md", "repo_id": "flutter-intellij", "token_count": 136 }
458
/* * 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. */ package io.flutter.tests.gui import com.intellij.openapi.util.SystemInfo.isMac import com.intellij.testGuiFramework.fixtures.ActionButtonFixture import com.intellij.testGuiFramework.framework.RunWithIde import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.GuiTestCase import com.intellij.testGuiFramework.launcher.ide.CommunityIde import com.intellij.testGuiFramework.util.step import io.flutter.tests.gui.fixtures.flutterInspectorFixture import org.fest.swing.fixture.JTreeRowFixture import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause.pause import org.junit.Test import java.awt.event.KeyEvent import kotlin.test.expect @RunWithIde(CommunityIde::class) class InspectorTest : GuiTestCase() { @Test fun widgetTree() { ProjectCreator.importProject() ideFrame { launchFlutterApp() val inspector = flutterInspectorFixture(this) inspector.populate() val widgetTree = inspector.widgetsFixture() val inspectorTree = widgetTree.inspectorTreeFixture() val detailsTree = widgetTree.inspectorTreeFixture(isDetails = true) expect(true) { detailsTree.selection() == null } step("Details selection synced with main tree") { inspectorTree.selectRow(2, reexpand = true) expect("[[root], MyApp, MaterialApp, MyHomePage]") { inspectorTree.selectionSync().toString() } expect("[MyHomePage]") { detailsTree.selectionSync().toString() } inspectorTree.selectRow(10, reexpand = true) expect("[[root], MyApp, MaterialApp, MyHomePage, Scaffold, FloatingActionButton]") { inspectorTree.selectionSync().toString() } val string = detailsTree.selectionSync().toString() expect(true) { string.startsWith("[FloatingActionButton]") } } // This is disabled due to an issue in the test framework. The #selectRow call causes // the widget tree to change its selection, which is absolutely not what we want. // step("Details selection leaves main tree unchanged") { // val string = detailsTree.selectionSync().toString() // detailsTree.selectRow(1, expand = false) // pause(object : Condition("Details tree changes") { // override fun test(): Boolean { // return string != detailsTree.selectionSync().toString() // } // }, Timeouts.seconds05) // expect("[[root], MyApp, MaterialApp, MyHomePage, Scaffold, FloatingActionButton]") { // inspectorTree.selectionSync().toString() // } // } runner().stop() } } @Test fun hotReload() { ProjectCreator.importProject() ideFrame { launchFlutterApp() val inspector = flutterInspectorFixture(this) inspector.populate() val widgets = inspector.widgetsFixture() val widgetsTree = widgets.inspectorTreeFixture(isDetails = false) widgetsTree.selectRow(0) val detailsTree = widgets.inspectorTreeFixture(isDetails = true) val initialDetails = detailsTree.selectionSync().toString() editor { // Wait until current file has appeared in current editor and set focus to editor. moveTo(0) val editorCode = getCurrentFileContents(false)!! val original = "pushed the button this" val index = editorCode.indexOf(original) + original.length moveTo(index) val key = if (isMac) KeyEvent.VK_BACK_SPACE else KeyEvent.VK_DELETE for (n in 1..4) typeKey(key) typeText("that") //typeKey(KeyEvent.VK_ESCAPE) // Dismiss completion popup -- not needed with "that" but is needed with "so" } step("Trigger Hot Reload and wait for it to finish") { val reload = findHotReloadButton() reload.click() editor.clickCenter() // Need to cycle the event loop to get button enabled on Mac. pause(object : Condition("Hot Reload finishes") { override fun test(): Boolean { return reload.isEnabled } }, Timeouts.seconds05) step("Work around #3370") { // https://github.com/flutter/flutter-intellij/issues/3370 inspector.renderTreeFixture().show() // The refresh button is broken so force tree update by switching views. inspector.populate() widgets.show() // And back to the one we want } widgetsTree.selectRow(6) // Text widget pause(object : Condition("Details tree changes") { override fun test(): Boolean { return initialDetails != detailsTree.selectionSync().toString() } }, Timeouts.seconds05) val row: JTreeRowFixture = detailsTree.treeFixture().node(1) val expected = "\"You have pushed the button that many times:\"" expect(expected) { row.value() } } runner().stop() } } private fun findHotReloadButton(): ActionButtonFixture { return findActionButtonByClassName("ReloadFlutterAppRetarget") } private fun findActionButtonByActionId(actionId: String): ActionButtonFixture { // This seems to be broken, but finding by simple class name works. var button: ActionButtonFixture? = null ideFrame { button = ActionButtonFixture.fixtureByActionId(target().parent, robot(), actionId) } return button!! } private fun findActionButtonByClassName(className: String): ActionButtonFixture { // This works when the button is enabled but fails if it is disabled (implementation detail). var button: ActionButtonFixture? = null ideFrame { button = ActionButtonFixture.fixtureByActionClassName(target(), robot(), className) } return button!! } }
flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/InspectorTest.kt/0
{ "file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/InspectorTest.kt", "repo_id": "flutter-intellij", "token_count": 2193 }
459
/* * Copyright 2016 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. */ package io.flutter; import java.util.Arrays; import java.util.List; public class FlutterConstants { // From: https://github.com/dart-lang/sdk/blob/master/pkg/front_end/lib/src/scanner/token.dart public static final List<String> DART_KEYWORDS = Arrays.asList( "abstract", "as", "assert", "async", "await", "break", "case", "catch", "class", "const", "continue", "covariant", "default", "deferred", "do", "dynamic", "else", "enum", "export", "extends", "external", "factory", "false", "final", "finally", "for", "function", "get", "hide", "if", "implements", "import", "in", "interface", "is", "library", "mixin", "native", "new", "null", "of", "on", "operator", "part", "patch", "rethrow", "return", "set", "show", "source", "static", "super", "switch", "sync", "this", "throw", "true", "try", "typedef", "var", "void", "while", "with", "yield" ); // From: https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/commands/create.dart public final static List<String> FLUTTER_PACKAGE_DEPENDENCIES = Arrays.asList( "analyzer", "args", "async", "collection", "convert", "crypto", "flutter", "flutter_test", "front_end", "html", "http", "intl", "io", "isolate", "kernel", "logging", "matcher", "meta", "mime", "path", "plugin", "pool", "test", "utf", "watcher", "yaml"); // Aligned w/ VSCode (https://github.com/flutter/flutter-intellij/issues/2682) public static String RELOAD_REASON_MANUAL = "manual"; public static String RELOAD_REASON_SAVE = "save"; public static String RELOAD_REASON_TOOL = "tool"; public static final String FLUTTER_SETTINGS_PAGE_ID = "flutter.settings"; public static final String INDEPENDENT_PATH_SEPARATOR = "/"; public static final String URL_GETTING_STARTED = FlutterBundle.message("flutter.io.gettingStarted.url"); public static final String URL_GETTING_STARTED_IDE = FlutterBundle.message("flutter.io.gettingStarted.IDE.url"); public static final String URL_RUN_AND_DEBUG = FlutterBundle.message("flutter.io.runAndDebug.url"); private FlutterConstants() { } }
flutter-intellij/flutter-idea/src/io/flutter/FlutterConstants.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/FlutterConstants.java", "repo_id": "flutter-intellij", "token_count": 1124 }
460
/* * 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. */ package io.flutter.actions; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.project.Project; import io.flutter.FlutterMessages; import io.flutter.pub.PubRoot; import io.flutter.sdk.FlutterSdk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlutterCleanAction extends FlutterSdkAction { @Override public void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nullable PubRoot root, @NotNull DataContext context) { if (root == null) { FlutterMessages.showError( "Cannot Find Pub Root", "Flutter clean can only be run within a directory with a pubspec.yaml file", project); return; } sdk.flutterClean(root).startInConsole(project); } }
flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterCleanAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterCleanAction.java", "repo_id": "flutter-intellij", "token_count": 326 }
461
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import io.flutter.sdk.XcodeUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class OpenSimulatorAction extends AnAction { final boolean enabled; public OpenSimulatorAction(boolean enabled) { super("Open iOS Simulator"); this.enabled = enabled; } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(enabled); } @Override public void actionPerformed(@NotNull AnActionEvent event) { @Nullable final Project project = event.getProject(); // Check to see if the simulator is already running. If it is, and we're here, that means there are // no running devices and we want to issue an extra call to start (w/ `-n`) to load a new simulator. // TODO(devoncarew): Determine if we need to support this code path. //if (XcodeUtils.isSimulatorRunning()) { // if (XcodeUtils.openSimulator("-n") != 0) { // // No point in trying if we errored. // return; // } //} XcodeUtils.openSimulator(project); } }
flutter-intellij/flutter-idea/src/io/flutter/actions/OpenSimulatorAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/OpenSimulatorAction.java", "repo_id": "flutter-intellij", "token_count": 463 }
462
package io.flutter.analytics; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.dart.server.AnalysisServerListener; import com.google.dart.server.RequestListener; import com.google.dart.server.ResponseListener; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.intellij.codeInsight.lookup.LookupEvent; import com.intellij.codeInsight.lookup.LookupListener; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.util.messages.MessageBusConnection; import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService; import com.jetbrains.lang.dart.fixes.DartQuickFix; import com.jetbrains.lang.dart.fixes.DartQuickFixListener; import io.flutter.FlutterInitializer; import io.flutter.utils.FileUtils; import org.dartlang.analysis.server.protocol.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import java.beans.PropertyChangeEvent; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; @SuppressWarnings("LocalCanBeFinal") public final class FlutterAnalysisServerListener implements Disposable, AnalysisServerListener { // statics static final String INITIAL_COMPUTE_ERRORS_TIME = "initialComputeErrorsTime"; static final String INITIAL_HIGHLIGHTS_TIME = "initialHighlightsTime"; static final String INITIAL_OUTLINE_TIME = "initialOutlineTime"; static final String ROUND_TRIP_TIME = "roundTripTime"; static final String QUICK_FIX = "quickFix"; static final String UNKNOWN_LOOKUP_STRING = "<unknown>"; static final String ANALYSIS_SERVER_LOG = "analysisServerLog"; static final String ACCEPTED_COMPLETION = "acceptedCompletion"; static final String REJECTED_COMPLETION = "rejectedCompletion"; static final String E2E_IJ_COMPLETION_TIME = "e2eIJCompletionTime"; static final String GET_SUGGESTIONS = "completion.getSuggestions"; static final String FIND_REFERENCES = "search.findElementReferences"; static final Set<String> MANUALLY_MANAGED_METHODS = Sets.newHashSet(GET_SUGGESTIONS, FIND_REFERENCES); static final String ERRORS = "errors"; static final String WARNINGS = "warnings"; static final String HINTS = "hints"; static final String LINTS = "lints"; static final String DURATION = "duration"; static final String FAILURE = "failure"; static final String SUCCESS = "success"; static final String ERROR_TYPE_REQUEST = "R"; static final String ERROR_TYPE_SERVER = "@"; static final String DAS_STATUS_EVENT_TYPE = "analysisServerStatus"; static final String[] ERROR_TYPES = new String[]{ AnalysisErrorType.CHECKED_MODE_COMPILE_TIME_ERROR, AnalysisErrorType.COMPILE_TIME_ERROR, AnalysisErrorType.HINT, AnalysisErrorType.LINT, AnalysisErrorType.STATIC_TYPE_WARNING, AnalysisErrorType.STATIC_WARNING, AnalysisErrorType.SYNTACTIC_ERROR }; static final String LOG_ENTRY_KIND = "kind"; static final String LOG_ENTRY_TIME = "time"; static final String LOG_ENTRY_DATA = "data"; static final String LOG_ENTRY_SDK_VERSION = "sdkVersion"; static final HashSet<String> REQUEST_ERRORS_TO_IGNORE = new HashSet<>(); static { REQUEST_ERRORS_TO_IGNORE.addAll(Arrays.asList("FORMAT_WITH_ERRORS", "ORGANIZE_DIRECTIVES_ERROR", "REFACTORING_REQUEST_CANCELLED")); } private static final long ERROR_REPORT_INTERVAL = 1000 * 60 * 60 * 2; // Two hours between cumulative error reports, in ms. private static final long GENERAL_REPORT_INTERVAL = 1000 * 60; // One minute between general analytic reports, in ms. private static final Logger LOG = Logger.getInstance(FlutterAnalysisServerListener.class); private static final boolean IS_TESTING = ApplicationManager.getApplication().isUnitTestMode(); @NotNull final FlutterRequestListener requestListener; @NotNull final FlutterResponseListener responseListener; @NotNull final DartQuickFixListener quickFixListener; // instance members @NotNull private final Project project; @NotNull private final Map<String, List<AnalysisError>> pathToErrors; @NotNull private final Map<String, Instant> pathToErrorTimestamps; @NotNull private final Map<String, Instant> pathToHighlightTimestamps; @NotNull private final Map<String, Instant> pathToOutlineTimestamps; @NotNull private final Map<String, RequestDetails> requestToDetails; @NotNull private final MessageBusConnection messageBusConnection; @NotNull private final FileEditorManagerListener fileEditorManagerListener; LookupSelectionHandler lookupSelectionHandler; @NotNull private Instant nextMemoryUsageLoggedInstant = Instant.EPOCH; private long errorsTimestamp; private long generalTimestamp; private int errorCount; private int warningCount; private int hintCount; private int lintCount; FlutterAnalysisServerListener(@NotNull Project project) { this.project = project; this.pathToErrors = new HashMap<>(); this.pathToErrorTimestamps = new HashMap<>(); this.pathToHighlightTimestamps = new HashMap<>(); this.pathToOutlineTimestamps = new HashMap<>(); this.requestToDetails = new HashMap<>(); this.messageBusConnection = project.getMessageBus().connect(); LookupManager.getInstance(project).addPropertyChangeListener(this::onPropertyChange); this.fileEditorManagerListener = new FileEditorManagerListener() { @Override public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file) { // Record the time that this file was opened so that we'll be able to log // relative timings for errors, highlights, outlines, etc. String filePath = file.getPath(); Instant nowInstant = Instant.now(); pathToErrorTimestamps.put(filePath, nowInstant); pathToHighlightTimestamps.put(filePath, nowInstant); pathToOutlineTimestamps.put(filePath, nowInstant); } @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { } @Override public void fileClosed(@NotNull final FileEditorManager source, @NotNull final VirtualFile file) { } }; messageBusConnection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, fileEditorManagerListener); messageBusConnection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { public void projectClosing(@NotNull Project project) { messageBusConnection.disconnect(); // Do this first to void memory leaks when switching pojects. errorsTimestamp = 0L; // Ensure we always report error counts on shutdown. maybeReportErrorCounts(); // The ShutdownTracker only allows three seconds, so this might not always complete. } }); this.quickFixListener = new QuickFixListener(); this.requestListener = new FlutterRequestListener(); this.responseListener = new FlutterResponseListener(); DartAnalysisServerService analysisServer = DartAnalysisServerService.getInstance(project); analysisServer.addQuickFixListener(this.quickFixListener); analysisServer.addRequestListener(this.requestListener); analysisServer.addResponseListener(this.responseListener); } @NotNull public static FlutterAnalysisServerListener getInstance(@NotNull final Project project) { return Objects.requireNonNull(project.getService(FlutterAnalysisServerListener.class)); } @NotNull private static String safelyGetString(JsonObject jsonObject, String memberName) { if (jsonObject != null && StringUtil.isNotEmpty(memberName)) { JsonElement jsonElement = jsonObject.get(memberName); if (jsonElement != null) { return Objects.requireNonNull(jsonElement.getAsString()); } } return ""; } @Override public void dispose() { // This is deprecated and marked for removal in 2021.3. If it is removed we will // have to do some funny stuff to support older versions of Android Studio. //noinspection UnstableApiUsage LookupManager.getInstance(project).removePropertyChangeListener(this::onPropertyChange); } @Override public void computedAnalyzedFiles(List<String> list) { // No start time is recorded. } @Override public void computedAvailableSuggestions(@NotNull List<AvailableSuggestionSet> list, int[] ints) { // No start time is recorded. } @Override public void computedCompletion(String completionId, int replacementOffset, int replacementLength, List<CompletionSuggestion> completionSuggestions, List<IncludedSuggestionSet> includedSuggestionSets, List<String> includedElementKinds, List<IncludedSuggestionRelevanceTag> includedSuggestionRelevanceTags, boolean isLast, String libraryFilePathSD) { long currentTimestamp = System.currentTimeMillis(); String id = getIdForMethod(GET_SUGGESTIONS); if (id == null) { return; } RequestDetails details = requestToDetails.remove(id); if (details == null) { return; } maybeReport(true, (analytics) -> { long startTime = details.startTime().toEpochMilli(); analytics.sendTiming(ROUND_TRIP_TIME, GET_SUGGESTIONS, currentTimestamp - startTime); // test: computedCompletion }); } @Nullable private String getIdForMethod(@NotNull String method) { Set<String> keys = requestToDetails.keySet(); for (String id : keys) { RequestDetails details = requestToDetails.get(id); assert details != null; if (GET_SUGGESTIONS.equals(details.method())) { return id; } } return null; } @Override public void computedErrors(String path, List<AnalysisError> list) { assert list != null; pathToErrors.put(path, list); assert path != null; maybeLogInitialAnalysisTime(INITIAL_COMPUTE_ERRORS_TIME, path, pathToErrorTimestamps); } @NotNull public List<AnalysisError> getAnalysisErrorsForFile(String path) { if (path == null) { return AnalysisError.EMPTY_LIST; } return Objects.requireNonNull(pathToErrors.getOrDefault(path, AnalysisError.EMPTY_LIST)); } /** * Iterate through all files in this {@link Project}, counting how many of each {@link * AnalysisErrorType} is in each file. The returned {@link HashMap} will contain the set of String * keys in ERROR_TYPES and values with the mentioned sums, converted to Strings. */ @NotNull private HashMap<String, Integer> getTotalAnalysisErrorCounts() { // Create a zero-filled array of length ERROR_TYPES.length. int[] errorCountsArray = new int[ERROR_TYPES.length]; // Iterate through each file in this project. for (String keyPath : pathToErrors.keySet()) { // Get the list of AnalysisErrors and remove any todos from the list, these are ignored in the // Dart Problems view, and can be ignored for any dashboard work. assert keyPath != null; List<AnalysisError> errors = getAnalysisErrorsForFile(keyPath); errors.removeIf(e -> { assert e != null; return Objects.equals(e.getType(), AnalysisErrorType.TODO); }); if (errors.isEmpty()) { continue; } // For this file, count how many of each ERROR_TYPES type we have and add this count to each // errorCountsArray[*] for (int i = 0; i < ERROR_TYPES.length; i++) { final int j = i; errorCountsArray[j] += (int) errors.stream().filter(e -> { assert e != null; return Objects.equals(e.getType(), ERROR_TYPES[j]); }).count(); } } // Finally, create and return the final HashMap. HashMap<String, Integer> errorCounts = new HashMap<>(); for (int i = 0; i < ERROR_TYPES.length; i++) { errorCounts.put(ERROR_TYPES[i], errorCountsArray[i]); } return errorCounts; } @Override public void computedHighlights(String path, List<HighlightRegion> list) { assert path != null; maybeLogInitialAnalysisTime(INITIAL_HIGHLIGHTS_TIME, path, pathToHighlightTimestamps); } @Override public void computedImplemented(String s, List<ImplementedClass> list, List<ImplementedMember> list1) { // No start time is recorded. } @Override public void computedLaunchData(String s, String s1, String[] strings) { } @Override public void computedNavigation(String s, List<NavigationRegion> list) { // No start time is recorded. } @Override public void computedOccurrences(String s, List<Occurrences> list) { // No start time is recorded. } @Override public void computedOutline(String path, Outline outline) { assert path != null; maybeLogInitialAnalysisTime(INITIAL_OUTLINE_TIME, path, pathToOutlineTimestamps); } @Override public void computedOverrides(String s, List<OverrideMember> list) { // No start time is recorded. } @Override public void computedClosingLabels(String s, List<ClosingLabel> list) { // No start time is recorded. } @Override public void computedSearchResults(String searchId, List<SearchResult> results, boolean isLast) { RequestDetails details = requestToDetails.remove(searchId); if (details == null) { return; } maybeReport(true, (analytics) -> { String method = details.method(); long duration = generalTimestamp - details.startTime().toEpochMilli(); LOG.debug(ROUND_TRIP_TIME + " " + method + " " + duration); analytics.sendTiming(ROUND_TRIP_TIME, method, duration); // test: computedSearchResults() }); } @Override public void flushedResults(List<String> list) { // Timing info not valid. } @Override public void requestError(RequestError requestError) { maybeReport(true, (analytics) -> { assert requestError != null; String code = requestError.getCode(); if (code == null) { code = requestError.getMessage(); // test: requestErrorNoCode() } if (REQUEST_ERRORS_TO_IGNORE.contains(code)) { return; } String stack = requestError.getStackTrace(); String exception = composeException(ERROR_TYPE_REQUEST, code, stack); LOG.debug(exception); analytics.sendException(exception, false); // test: requestError() }); } /** * Build an exception parameter containing type, code, and stack. Limit it to 150 chars. * * @param type "R" for request error, "S" for server error * @param code error code or message * @param stack stack trace * @return exception description, value of "exd" parameter in analytics */ private static String composeException(@NotNull String type, @Nullable String code, @Nullable String stack) { String exception = type + " "; if (code != null && !code.isEmpty()) { exception += code; if (stack != null && !stack.isEmpty()) { exception += "\n" + stack; } } else if (stack != null && !stack.isEmpty()) { exception += stack; } else { exception += "exception"; } if (exception.length() > 150) { exception = exception.substring(0, 149); } return exception; } @Override public void serverConnected(String s) { } @Override public void serverError(boolean isFatal, String message, String stackTraceString) { maybeReport(true, (analytics) -> { String exception = composeException(ERROR_TYPE_SERVER, message, stackTraceString); LOG.debug(exception + " fatal"); analytics.sendException(exception, isFatal); // test: serverError() }); } @Override public void serverIncompatibleVersion(String s) { } @Override public void serverStatus(AnalysisStatus analysisStatus, PubStatus pubStatus) { assert analysisStatus != null; if (!analysisStatus.isAnalyzing()) { @NotNull HashMap<String, Integer> errorCounts = getTotalAnalysisErrorCounts(); errorCount = 0; errorCount += extractCount(errorCounts, AnalysisErrorType.CHECKED_MODE_COMPILE_TIME_ERROR); errorCount += extractCount(errorCounts, AnalysisErrorType.COMPILE_TIME_ERROR); errorCount += extractCount(errorCounts, AnalysisErrorType.SYNTACTIC_ERROR); warningCount = 0; warningCount += extractCount(errorCounts, AnalysisErrorType.STATIC_TYPE_WARNING); warningCount += extractCount(errorCounts, AnalysisErrorType.STATIC_WARNING); hintCount = extractCount(errorCounts, AnalysisErrorType.HINT); lintCount = extractCount(errorCounts, AnalysisErrorType.LINT); if (IS_TESTING) { errorCount = warningCount = hintCount = lintCount = 1; } maybeReportErrorCounts(); } } private void maybeReport(boolean observeThrottling, @NotNull java.util.function.Consumer<@NotNull Analytics> func) { long currentTimestamp = System.currentTimeMillis(); if (observeThrottling && !IS_TESTING) { // Throttle to one report per interval. if (currentTimestamp - generalTimestamp < GENERAL_REPORT_INTERVAL) { return; } } generalTimestamp = currentTimestamp; func.accept(FlutterInitializer.getAnalytics()); } private void maybeReportErrorCounts() { long currentTimestamp = System.currentTimeMillis(); // Send accumulated error counts once every defined interval, plus when the project is closed. if (errorsTimestamp == 0L || currentTimestamp - errorsTimestamp > ERROR_REPORT_INTERVAL || IS_TESTING) { errorsTimestamp = currentTimestamp; Analytics analytics = FlutterInitializer.getAnalytics(); LOG.debug(DAS_STATUS_EVENT_TYPE + " " + errorCount + " " + warningCount + " " + hintCount + " " + lintCount); analytics.disableThrottling(() -> { if (errorCount > 0) { analytics.sendEventMetric(DAS_STATUS_EVENT_TYPE, ERRORS, errorCount); // test: serverStatus() } if (warningCount > 0) { analytics.sendEventMetric(DAS_STATUS_EVENT_TYPE, WARNINGS, warningCount); // test: serverStatus() } if (hintCount > 0) { analytics.sendEventMetric(DAS_STATUS_EVENT_TYPE, HINTS, hintCount); // test: serverStatus() } if (lintCount > 0) { analytics.sendEventMetric(DAS_STATUS_EVENT_TYPE, LINTS, lintCount); // test: serverStatus() } }); errorCount = warningCount = hintCount = lintCount = 0; } } private static int extractCount(@NotNull Map<String, Integer> errorCounts, String name) { //noinspection Java8MapApi,ConstantConditions return errorCounts.containsKey(name) ? errorCounts.get(name) : 0; } @Override public void computedExistingImports(String file, Map<String, Map<String, Set<String>>> existingImports) { // No start time is recorded. } private void logCompletion(@NotNull String selection, int prefixLength, @NotNull String eventType) { maybeReport(true, (analytics) -> { LOG.debug(eventType + " " + selection + " " + prefixLength); analytics.sendEventMetric(eventType, selection, prefixLength); // test: acceptedCompletion(), lookupCanceled() }); } void logE2ECompletionSuccessMS(long e2eCompletionMS) { maybeReport(true, (analytics) -> { LOG.debug(E2E_IJ_COMPLETION_TIME + " " + SUCCESS + " " + e2eCompletionMS); analytics.sendTiming(E2E_IJ_COMPLETION_TIME, SUCCESS, e2eCompletionMS); // test: logE2ECompletionSuccessMS() }); } void logE2ECompletionErrorMS(long e2eCompletionMS) { maybeReport(true, (analytics) -> { LOG.debug(E2E_IJ_COMPLETION_TIME + " " + FAILURE + " " + e2eCompletionMS); analytics.sendTiming(E2E_IJ_COMPLETION_TIME, FAILURE, e2eCompletionMS); // test: logE2ECompletionErrorMS() }); } private void maybeLogInitialAnalysisTime(@NotNull String eventType, @NotNull String path, @NotNull Map<String, Instant> pathToStartTime) { if (!pathToStartTime.containsKey(path)) { return; } logFileAnalysisTime(eventType, path, Objects.requireNonNull( Duration.between(Objects.requireNonNull(pathToStartTime.get(path)), Instant.now())).toMillis()); pathToStartTime.remove(path); } private void logFileAnalysisTime(@NotNull String kind, String path, long analysisTime) { maybeReport(false, (analytics) -> { LOG.debug(kind + " " + DURATION + " " + analysisTime); analytics.sendEvent(kind, DURATION, "", Long.toString(analysisTime)); // test: computedErrors() }); } /** * Observe when the active {@link LookupImpl} changes and register the {@link * LookupSelectionHandler} on any new instances. */ void onPropertyChange(@NotNull PropertyChangeEvent propertyChangeEvent) { Object newValue = propertyChangeEvent.getNewValue(); if (!(newValue instanceof LookupImpl)) { return; } setLookupSelectionHandler(); LookupImpl lookup = (LookupImpl)newValue; lookup.addLookupListener(lookupSelectionHandler); } @VisibleForTesting void setLookupSelectionHandler() { this.lookupSelectionHandler = new LookupSelectionHandler(); } class LookupSelectionHandler implements LookupListener { @Override public void lookupCanceled(@NotNull LookupEvent event) { if (event.isCanceledExplicitly() && isDartLookupEvent(event)) { logCompletion(UNKNOWN_LOOKUP_STRING, -1, REJECTED_COMPLETION); // test: lookupCanceled() } } @Override public void itemSelected(@NotNull LookupEvent event) { if (event.getItem() == null) { return; } String selection = event.getItem().getLookupString(); LookupImpl lookup = (LookupImpl)event.getLookup(); assert lookup != null; int prefixLength = lookup.getPrefixLength(event.getItem()); if (isDartLookupEvent(event)) { logCompletion(selection, prefixLength, ACCEPTED_COMPLETION); // test: acceptedCompletion() } } @Override public void currentItemChanged(@NotNull LookupEvent event) { } private boolean isDartLookupEvent(@NotNull LookupEvent event) { LookupImpl lookup = (LookupImpl)event.getLookup(); return lookup != null && lookup.getPsiFile() != null && lookup.getPsiFile().getVirtualFile() != null && FileUtils.isDartFile(Objects.requireNonNull(lookup.getPsiFile().getVirtualFile())); } } private class QuickFixListener implements DartQuickFixListener { @Override public void beforeQuickFixInvoked(@NotNull DartQuickFix intention, @NotNull Editor editor, @NotNull PsiFile file) { maybeReport(true, (analytics) -> { String path = Objects.requireNonNull(file.getVirtualFile()).getPath(); int lineNumber = editor.getCaretModel().getLogicalPosition().line + 1; @SuppressWarnings("ConstantConditions") List<String> errorsOnLine = pathToErrors.containsKey(path) ? pathToErrors.get(path).stream().filter(error -> error.getLocation().getStartLine() == lineNumber) .map(AnalysisError::getCode).collect(Collectors.toList()) : ImmutableList.of(); LOG.debug(QUICK_FIX + " " + intention.getText() + " " + errorsOnLine.size()); analytics.sendEventMetric(QUICK_FIX, intention.getText(), errorsOnLine.size()); // test: quickFix() }); } } class FlutterRequestListener implements RequestListener { @Override public void onRequest(String jsonString) { JsonObject request = new Gson().fromJson(jsonString, JsonObject.class); //noinspection ConstantConditions RequestDetails details = new RequestDetails(request.get("method").getAsString(), Instant.now()); String id = Objects.requireNonNull(request.get("id")).getAsString(); requestToDetails.put(id, details); } } @SuppressWarnings("LocalCanBeFinal") class FlutterResponseListener implements ResponseListener { final Map<String, Long> methodTimestamps = new HashMap<>(); @Override public void onResponse(String jsonString) { JsonObject response = new Gson().fromJson(jsonString, JsonObject.class); if (response == null) return; if (safelyGetString(response, "event").equals("server.log")) { JsonObject serverLogEntry = Objects.requireNonNull(response.getAsJsonObject("params")).getAsJsonObject("entry"); if (serverLogEntry != null) { maybeReport(true, (analytics) -> { String sdkVersionValue = safelyGetString(serverLogEntry, LOG_ENTRY_SDK_VERSION); ImmutableMap<String, String> map; @SuppressWarnings("ConstantConditions") String logEntry = String.format("%s|%s|%s|%s|%s|%s", LOG_ENTRY_TIME, serverLogEntry.get(LOG_ENTRY_TIME).getAsInt(), LOG_ENTRY_KIND, serverLogEntry.get(LOG_ENTRY_KIND).getAsString(), LOG_ENTRY_DATA, serverLogEntry.get(LOG_ENTRY_DATA).getAsString()); assert logEntry != null; LOG.debug(ANALYSIS_SERVER_LOG + " " + logEntry); // Log the "sdkVersion" only if it was provided in the event if (StringUtil.isEmpty(sdkVersionValue)) { analytics.sendEvent(ANALYSIS_SERVER_LOG, logEntry); // test: dasListenerLogging() } else { // test: dasListenerLoggingWithSdk() analytics.sendEventWithSdk(ANALYSIS_SERVER_LOG, logEntry, sdkVersionValue); } }); } } if (response.get("id") == null) { return; } //noinspection ConstantConditions String id = response.get("id").getAsString(); RequestDetails details = requestToDetails.get(id); if (details != null) { if (MANUALLY_MANAGED_METHODS.contains(details.method())) { return; } Long timestamp = methodTimestamps.get(details.method()); long currentTimestamp = System.currentTimeMillis(); // Throttle to one report per interval for each distinct details.method(). if (timestamp == null || currentTimestamp - timestamp > GENERAL_REPORT_INTERVAL) { methodTimestamps.put(details.method(), currentTimestamp); LOG.debug(ROUND_TRIP_TIME + " " + details.method() + " " + Duration.between(details.startTime(), Instant.now()).toMillis()); FlutterInitializer.getAnalytics() .sendTiming(ROUND_TRIP_TIME, details.method(), // test: dasListenerTiming() Objects.requireNonNull(Duration.between(details.startTime(), Instant.now())).toMillis()); } } requestToDetails.remove(id); } } }
flutter-intellij/flutter-idea/src/io/flutter/analytics/FlutterAnalysisServerListener.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/analytics/FlutterAnalysisServerListener.java", "repo_id": "flutter-intellij", "token_count": 9709 }
463
/* * Copyright 2016 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. */ package io.flutter.console; import com.intellij.execution.ConsoleFolding; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import io.flutter.FlutterConstants; import io.flutter.sdk.FlutterSdkUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * Fold lines like '/Users/.../projects/flutter/flutter/bin/flutter --no-color packages get'. */ public class FlutterConsoleFolding extends ConsoleFolding { private static final String flutterMarker = FlutterConstants.INDEPENDENT_PATH_SEPARATOR + FlutterSdkUtil.flutterScriptName() + " --no-color "; @Override public boolean shouldFoldLine(@NotNull Project project, @NotNull String line) { if (line.contains(flutterMarker)) { return line.indexOf(' ') > line.indexOf(flutterMarker); } return false; } @Override public boolean shouldBeAttachedToThePreviousLine() { // This ensures that we don't get appended to the previous (likely unrelated) line. return false; } @Nullable @Override public String getPlaceholderText(@NotNull Project project, @NotNull List<String> lines) { final String fullText = StringUtil.join(lines, "\n"); final int index = fullText.indexOf(flutterMarker); if (index != -1) { String results = "flutter " + fullText.substring(index + flutterMarker.length()); results = results.replace("--machine ", ""); results = results.replace("--start-paused ", ""); return results; } else { return fullText.trim(); } } }
flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsoleFolding.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/console/FlutterConsoleFolding.java", "repo_id": "flutter-intellij", "token_count": 596 }
464
/* * 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. */ package io.flutter.editor; /* * 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 com.intellij.openapi.Disposable; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.Objects; /** * Service that tracks the visible area and Carat selection of an editor. * <p> * This class provides a {@link EditorPositionService.Listener} that notifies consumers when * the editor changes position or carat selection. */ public class EditorPositionService extends EditorEventServiceBase<EditorPositionService.Listener> implements Disposable { public interface Listener { void updateVisibleArea(Rectangle newRectangle); void onVisibleChanged(); default void updateSelected(Caret carat) { } } private final VisibleAreaListener visibleAreaListener; private final EditorEventMulticaster eventMulticaster; public EditorPositionService(Project project) { super(project); eventMulticaster = EditorFactory.getInstance().getEventMulticaster(); visibleAreaListener = (VisibleAreaEvent event) -> { invokeAll(listener -> listener.updateVisibleArea(event.getNewRectangle()), event.getEditor()); }; eventMulticaster.addVisibleAreaListener(visibleAreaListener); eventMulticaster.addCaretListener(new CaretListener() { @Override public void caretPositionChanged(@NotNull CaretEvent e) { invokeAll(listener -> listener.updateSelected(e.getCaret()), e.getEditor()); } }, this); // TODO(jacobr): listen for when editors are disposed? } @NotNull public static EditorPositionService getInstance(@NotNull final Project project) { return Objects.requireNonNull(project.getService(EditorPositionService.class)); } public void addListener(@NotNull EditorEx editor, @NotNull Listener listener, Disposable disposable) { super.addListener(editor, listener, disposable); // Notify the listener of the current state. listener.updateVisibleArea(editor.getScrollingModel().getVisibleArea()); final Caret carat = editor.getCaretModel().getPrimaryCaret(); if (carat.isValid()) { listener.updateSelected(carat); } } @Override public void dispose() { eventMulticaster.removeVisibleAreaListener(visibleAreaListener); super.dispose(); } }
flutter-intellij/flutter-idea/src/io/flutter/editor/EditorPositionService.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/EditorPositionService.java", "repo_id": "flutter-intellij", "token_count": 853 }
465
/* * 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. */ package io.flutter.editor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.util.TextRange; public class InlineWidgetViewModelData extends WidgetViewModelData { public final WidgetIndentGuideDescriptor descriptor; public final Document document; public final EditorEx editor; public InlineWidgetViewModelData( WidgetIndentGuideDescriptor descriptor, EditorEx editor, WidgetEditingContext context ) { super(context); this.descriptor = descriptor; this.document = editor.getDocument(); this.editor = editor; } public TextRange getMarker() { if (descriptor != null) { return descriptor.getMarker(); } return null; } }
flutter-intellij/flutter-idea/src/io/flutter/editor/InlineWidgetViewModelData.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/InlineWidgetViewModelData.java", "repo_id": "flutter-intellij", "token_count": 295 }
466
/* * 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. */ package io.flutter.editor; import com.intellij.openapi.editor.markup.RangeHighlighter; import org.dartlang.analysis.server.protocol.FlutterOutline; import java.util.Collections; import java.util.List; /** * Data describing widget indents for an editor that is persisted across * multiple runs of the WidgetIndentsHighlightingPass. */ public class WidgetIndentsPassData { public PreviewsForEditor previewsForEditor; /** * Descriptors describing the data model to render the widget indents. * <p> * This data is computed from the FlutterOutline and contains additional * information to manage how the locations need to be updated to reflect * edits to the documents. */ java.util.List<WidgetIndentGuideDescriptor> myDescriptors = Collections.emptyList(); /** * Descriptors combined with their current locations in the possibly modified document. */ java.util.List<TextRangeDescriptorPair> myRangesWidgets = Collections.emptyList(); /** * Highlighters that perform the actual rendering of the widget indent * guides. */ List<RangeHighlighter> highlighters; /** * Source of truth for whether other UI overlaps with the widget indents. */ WidgetIndentHitTester hitTester; /** * Outline the widget indents are based on. */ FlutterOutline outline; }
flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentsPassData.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentsPassData.java", "repo_id": "flutter-intellij", "token_count": 433 }
467
/* * 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. */ package io.flutter.inspector; import io.flutter.vmService.HeapMonitor; import org.dartlang.vm.service.element.MemoryUsage; import java.text.DecimalFormat; import java.util.List; public class HeapState { private static final DecimalFormat df = new DecimalFormat(); static { df.setMaximumFractionDigits(1); } // Running count of the max heap (in bytes). private int heapMaxInBytes; private final HeapSamples samples; public HeapState(int maxSampleSizeMs) { samples = new HeapSamples(maxSampleSizeMs); } public int getMaxSampleSizeMs() { return samples.maxSampleSizeMs; } public List<HeapMonitor.HeapSample> getSamples() { return samples.samples; } // Allocated heap size. public int getCapacity() { int max = heapMaxInBytes; for (HeapMonitor.HeapSample sample : samples.samples) { max = Math.max(max, sample.getBytes()); } return max; } private static String printMb(int bytes) { return df.format(bytes / (1024 * 1024.0)) + "MB"; } public String getHeapSummary() { return printMb(samples.samples.getLast().getBytes()) + " of " + printMb(heapMaxInBytes); } void addSample(HeapMonitor.HeapSample sample) { samples.addSample(sample); } public void handleMemoryUsage(List<MemoryUsage> memoryUsages) { int current = 0; int total = 0; int external = 0; for (MemoryUsage usage : memoryUsages) { current += usage.getHeapUsage(); total += usage.getHeapCapacity(); external += usage.getExternalUsage(); } heapMaxInBytes = total; addSample(new HeapMonitor.HeapSample(current, external)); } }
flutter-intellij/flutter-idea/src/io/flutter/inspector/HeapState.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/HeapState.java", "repo_id": "flutter-intellij", "token_count": 622 }
468
/* * 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. */ package io.flutter.inspector; import com.google.common.collect.ArrayListMultimap; import com.intellij.ide.browsers.BrowserLauncher; import com.intellij.openapi.Disposable; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.components.labels.LinkListener; import com.intellij.ui.components.panels.VerticalLayout; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.JBUI; import io.flutter.FlutterInitializer; import io.flutter.perf.*; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.AsyncUtils; import org.jetbrains.annotations.NotNull; import javax.swing.Timer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.*; /** * Panel displaying performance tips for the currently visible files. */ public class WidgetPerfTipsPanel extends JPanel { static final int PERF_TIP_COMPUTE_DELAY = 1000; private final FlutterWidgetPerfManager perfManager; private long lastUpdateTime; private final JPanel perfTips; /** * Currently active file editor if it is a TextEditor. */ private TextEditor currentEditor; private ArrayList<TextEditor> currentTextEditors; final LinkListener<PerfTip> linkListener; final private List<PerfTip> currentTips = new ArrayList<>(); public WidgetPerfTipsPanel(Disposable parentDisposable, @NotNull FlutterApp app) { setLayout(new VerticalLayout(5)); add(new JSeparator()); perfManager = FlutterWidgetPerfManager.getInstance(app.getProject()); perfTips = new JPanel(); perfTips.setLayout(new VerticalLayout(0)); linkListener = (source, tip) -> handleTipSelection(tip); final Project project = app.getProject(); final MessageBusConnection bus = project.getMessageBus().connect(project); final FileEditorManagerListener listener = new FileEditorManagerListener() { @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { selectedEditorChanged(); } }; selectedEditorChanged(); bus.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, listener); // Computing performance tips is somewhat expensive so we don't want to // compute them too frequently. Performance tips are only computed when // new performance stats are available but performance stats are updated // at 60fps so to be conservative we delay computing perf tips. final Timer perfTipComputeDelayTimer = new Timer(PERF_TIP_COMPUTE_DELAY, this::onComputePerfTips); perfTipComputeDelayTimer.start(); Disposer.register(parentDisposable, perfTipComputeDelayTimer::stop); } private static void handleTipSelection(@NotNull PerfTip tip) { // Send analytics. FlutterInitializer.getAnalytics().sendEvent("perf", "perfTipSelected." + tip.getRule().getId()); BrowserLauncher.getInstance().browse(tip.getUrl(), null); } private void onComputePerfTips(ActionEvent event) { final FlutterWidgetPerf stats = perfManager.getCurrentStats(); if (stats != null) { final long latestPerfUpdate = stats.getLastLocalPerfEventTime(); // Only do work if new performance stats have been recorded. if (latestPerfUpdate != lastUpdateTime) { lastUpdateTime = latestPerfUpdate; updateTip(); } } } public void clearTips() { currentTips.clear(); remove(perfTips); setVisible(hasPerfTips()); } private void selectedEditorChanged() { lastUpdateTime = -1; updateTip(); } private void updateTip() { if (perfManager.getCurrentStats() == null) { return; } final Set<TextEditor> selectedEditors = new HashSet<>(perfManager.getSelectedEditors()); if (selectedEditors.isEmpty()) { clearTips(); return; } final WidgetPerfLinter linter = perfManager.getCurrentStats().getPerfLinter(); AsyncUtils.whenCompleteUiThread(linter.getTipsFor(selectedEditors), (tips, throwable) -> { if (tips == null || tips.isEmpty() || throwable != null) { clearTips(); return; } final Map<String, TextEditor> forPath = new HashMap<>(); for (TextEditor editor : selectedEditors) { final VirtualFile file = editor.getFile(); if (file != null) { forPath.put(InspectorService.toSourceLocationUri(file.getPath()), editor); } } final ArrayListMultimap<TextEditor, PerfTip> newTipsForFile = ArrayListMultimap.create(); for (PerfTip tip : tips) { for (Location location : tip.getLocations()) { if (forPath.containsKey(location.path)) { newTipsForFile.put(forPath.get(location.path), tip); } } } tipsPerFile = newTipsForFile; if (!PerfTipRule.equivalentPerfTips(currentTips, tips)) { showPerfTips(tips); } }); } ArrayListMultimap<TextEditor, PerfTip> tipsPerFile; private void showPerfTips(@NotNull ArrayList<PerfTip> tips) { perfTips.removeAll(); currentTips.clear(); currentTips.addAll(tips); for (PerfTip tip : tips) { final LinkLabel<PerfTip> label = new LinkLabel<>( "<html><body><a>" + tip.getMessage() + "</a><body></html>", tip.getRule().getIcon(), linkListener, tip ); label.setPaintUnderline(false); label.setBorder(JBUI.Borders.empty(0, 5, 5, 5)); perfTips.add(label); } add(perfTips); setVisible(hasPerfTips()); } private boolean hasPerfTips() { return !currentTips.isEmpty(); } }
flutter-intellij/flutter-idea/src/io/flutter/inspector/WidgetPerfTipsPanel.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/WidgetPerfTipsPanel.java", "repo_id": "flutter-intellij", "token_count": 2132 }
469
/* * 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. */ package io.flutter.module.settings; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; public class FlutterCreateParams { private JCheckBox createProjectOfflineCheckBox; private JPanel mainPanel; private JLabel infoLabel; public FlutterCreateParams setInitialValues() { final boolean autoSelectOffline = !isPubAvailable(); createProjectOfflineCheckBox.setSelected(autoSelectOffline); infoLabel.setVisible(autoSelectOffline); return this; } @NotNull public JComponent getComponent() { return mainPanel; } public boolean isOfflineSelected() { return createProjectOfflineCheckBox.isSelected(); } public JCheckBox getOfflineCheckbox() { return createProjectOfflineCheckBox; } private static boolean isPubAvailable() { // Check to see if the pub site is accessible to indicate whether we're online // and if we should expect pub commands to succeed. try { new Socket(InetAddress.getByName("pub.dartlang.org"), 80).close(); return true; } catch (IOException ex) { // Ignore. } return false; } }
flutter-intellij/flutter-idea/src/io/flutter/module/settings/FlutterCreateParams.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/FlutterCreateParams.java", "repo_id": "flutter-intellij", "token_count": 427 }
470
/* * 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. */ package io.flutter.perf; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.HashMultimap; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.intellij.concurrency.JobScheduler; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ui.EdtInvocationManager; import gnu.trove.TIntObjectHashMap; import io.flutter.utils.AsyncUtils; import org.jetbrains.annotations.NotNull; import javax.swing.Timer; import java.awt.event.ActionEvent; import java.util.*; import java.util.concurrent.TimeUnit; /** * This class provides the glue code between code fetching performance * statistics json from a running flutter application and the ui rendering the * performance statistics directly within the text editors. * <p> * This class is written to be amenable to unittesting unlike * FlutterWidgetPerfManager so try to put all complex logic in this class * so that issues can be caught by unittests. * <p> * See EditorPerfDecorations which performs all of the concrete ui rendering * and VmServiceWidgetPerfProvider which performs fetching of json from a * production application. */ public class FlutterWidgetPerf implements Disposable, WidgetPerfListener { private static final Logger LOG = Logger.getInstance(FlutterWidgetPerf.class); public static final long IDLE_DELAY_MILISECONDS = 400; static class StatsForReportKind { final TIntObjectHashMap<SlidingWindowStats> data = new TIntObjectHashMap<>(); private int lastStartTime = -1; private int lastNonEmptyReportTime = -1; } // Retry requests if we do not receive a response within this interval. private static final long REQUEST_TIMEOUT_INTERVAL = 2000; // Intentionally use a low FPS as the animations in EditorPerfDecorations // are quite CPU intensive due to animating content in TextEditor windows. private static final int UI_FPS = 8; private boolean isDirty = true; private boolean requestInProgress = false; private long lastRequestTime; private final Set<PerfModel> perfListeners = new HashSet<>(); /** * Note: any access of editorDecorations contents must happen on the UI thread. */ private final Map<TextEditor, EditorPerfModel> editorDecorations = new HashMap<>(); private final TIntObjectHashMap<Location> knownLocationIds = new TIntObjectHashMap<>(); private final SetMultimap<String, Location> locationsPerFile = HashMultimap.create(); private final Map<PerfReportKind, StatsForReportKind> stats = new HashMap<>(); final Set<TextEditor> currentEditors = new HashSet<>(); private boolean profilingEnabled; final Timer uiAnimationTimer; @NotNull private final WidgetPerfProvider perfProvider; private boolean isDisposed = false; private final FilePerfModelFactory perfModelFactory; private final FileLocationMapperFactory fileLocationMapperFactory; private volatile long lastLocalPerfEventTime; private final WidgetPerfLinter perfLinter; FlutterWidgetPerf(boolean profilingEnabled, @NotNull WidgetPerfProvider perfProvider, FilePerfModelFactory perfModelFactory, FileLocationMapperFactory fileLocationMapperFactory) { this.profilingEnabled = profilingEnabled; this.perfProvider = perfProvider; this.perfModelFactory = perfModelFactory; this.fileLocationMapperFactory = fileLocationMapperFactory; this.perfLinter = new WidgetPerfLinter(this, perfProvider); perfProvider.setTarget(this); uiAnimationTimer = new Timer(1000 / UI_FPS, event -> { AsyncUtils.invokeLater(() -> onFrame(event)); }); } // The logic for when requests are in progress is fragile. This helper // method exists to we have a single place to instrument to track when // request status changes to help debug issues,. private void setRequestInProgress(boolean value) { requestInProgress = value; } private void onFrame(ActionEvent event) { for (EditorPerfModel decorations : editorDecorations.values()) { decorations.onFrame(); } for (PerfModel model : perfListeners) { model.onFrame(); } } private boolean isConnected() { return perfProvider.isConnected(); } public long getLastLocalPerfEventTime() { return lastLocalPerfEventTime; } /** * Schedule a repaint of the widget perf information. * <p> * When.now schedules a repaint immediately. * <p> * When.soon will schedule a repaint shortly; that can get delayed by another request, with a maximum delay. */ @Override public void requestRepaint(When when) { if (!profilingEnabled) { isDirty = false; return; } isDirty = true; if (!isConnected() || (this.currentEditors.isEmpty() && this.perfListeners.isEmpty())) { return; } final long currentTime = System.currentTimeMillis(); if (requestInProgress && (currentTime - lastRequestTime) < REQUEST_TIMEOUT_INTERVAL) { return; } setRequestInProgress(true); lastRequestTime = currentTime; final TextEditor[] editors = this.currentEditors.toArray(new TextEditor[0]); AsyncUtils.invokeLater(() -> performRequest(editors)); } @Override public void onWidgetPerfEvent(PerfReportKind kind, JsonObject json) { // Read access to the Document objects on background thread is needed so // a ReadAction is required. Document objects are used to determine the // widget names at specific locations in documents. final Runnable action = () -> { synchronized (this) { final long startTimeMicros = json.get("startTime").getAsLong(); final int startTimeMilis = (int)(startTimeMicros / 1000); lastLocalPerfEventTime = System.currentTimeMillis(); final StatsForReportKind statsForReportKind = getStatsForKind(kind); if (statsForReportKind.lastStartTime > startTimeMilis) { // We went backwards in time. There must have been a hot restart so // clear all old stats. statsForReportKind.data.forEachValue((SlidingWindowStats entry) -> { entry.clear(); return true; }); } statsForReportKind.lastStartTime = startTimeMilis; // Prefer the new 'locations' format if it exists; else read from 'newLocations'. if (json.has("locations")) { final JsonObject fileLocationsMap = json.getAsJsonObject("locations"); for (Map.Entry<String, JsonElement> entry : fileLocationsMap.entrySet()) { final String path = entry.getKey(); final FileLocationMapper locationMapper = fileLocationMapperFactory.create(path); final JsonObject locations = entry.getValue().getAsJsonObject(); final JsonArray ids = locations.getAsJsonArray("ids"); final JsonArray lines = locations.getAsJsonArray("lines"); final JsonArray columns = locations.getAsJsonArray("columns"); final JsonArray names = locations.getAsJsonArray("names"); for (int i = 0; i < ids.size(); i++) { final int id = ids.get(i).getAsInt(); final int line = lines.get(i).getAsInt(); final int column = columns.get(i).getAsInt(); final TextRange textRange = locationMapper.getIdentifierRange(line, column); final Location location = new Location( locationMapper.getPath(), line, column, id, textRange, names.get(i).getAsString() ); final Location existingLocation = knownLocationIds.get(id); if (existingLocation == null) { addNewLocation(id, location); } else { if (!location.equals(existingLocation)) { // Cleanup all references to the old location as it is stale. // This occurs if there is a hot restart or reload that we weren't aware of. locationsPerFile.remove(existingLocation.path, existingLocation); for (StatsForReportKind statsForKind : stats.values()) { statsForKind.data.remove(id); } addNewLocation(id, location); } } } } } else if (json.has("newLocations")) { final JsonObject newLocations = json.getAsJsonObject("newLocations"); for (Map.Entry<String, JsonElement> entry : newLocations.entrySet()) { final String path = entry.getKey(); final FileLocationMapper locationMapper = fileLocationMapperFactory.create(path); final JsonArray entries = entry.getValue().getAsJsonArray(); assert (entries.size() % 3 == 0); for (int i = 0; i < entries.size(); i += 3) { final int id = entries.get(i).getAsInt(); final int line = entries.get(i + 1).getAsInt(); final int column = entries.get(i + 2).getAsInt(); final TextRange textRange = locationMapper.getIdentifierRange(line, column); String name = locationMapper.getText(textRange); if (name == null) { name = ""; } final Location location = new Location(locationMapper.getPath(), line, column, id, textRange, name); final Location existingLocation = knownLocationIds.get(id); if (existingLocation == null) { addNewLocation(id, location); } else { if (!location.equals(existingLocation)) { // Cleanup all references to the old location as it is stale. // This occurs if there is a hot restart or reload that we weren't aware of. locationsPerFile.remove(existingLocation.path, existingLocation); for (StatsForReportKind statsForKind : stats.values()) { statsForKind.data.remove(id); } addNewLocation(id, location); } } } } } final StatsForReportKind statsForKind = getStatsForKind(kind); final PerfSourceReport report = new PerfSourceReport(json.getAsJsonArray("events"), kind, startTimeMicros); if (!report.getEntries().isEmpty()) { statsForReportKind.lastNonEmptyReportTime = startTimeMilis; } for (PerfSourceReport.Entry entry : report.getEntries()) { final int locationId = entry.locationId; SlidingWindowStats statsForLocation = statsForKind.data.get(locationId); if (statsForLocation == null) { statsForLocation = new SlidingWindowStats(); statsForKind.data.put(locationId, statsForLocation); } statsForLocation.add(entry.total, startTimeMilis); } } }; final Application application = ApplicationManager.getApplication(); if (application != null) { application.runReadAction(action); } else { // Unittest case. action.run(); } } @Override public void onNavigation() { synchronized (this) { for (StatsForReportKind statsForKind : stats.values()) { statsForKind.data.forEachValue((SlidingWindowStats entry) -> { entry.onNavigation(); return true; }); } } } @Override public void addPerfListener(PerfModel listener) { perfListeners.add(listener); } @Override public void removePerfListener(PerfModel listener) { perfListeners.remove(listener); } private StatsForReportKind getStatsForKind(PerfReportKind kind) { StatsForReportKind report = stats.get(kind); if (report == null) { report = new StatsForReportKind(); stats.put(kind, report); } return report; } private void addNewLocation(int id, Location location) { knownLocationIds.put(id, location); locationsPerFile.put(location.path, location); } void setProfilingEnabled(boolean enabled) { profilingEnabled = enabled; } private void performRequest(TextEditor[] fileEditors) { assert EdtInvocationManager.getInstance().isEventDispatchThread(); if (!profilingEnabled) { setRequestInProgress(false); return; } final Multimap<String, TextEditor> editorForPath = LinkedListMultimap.create(); final List<String> uris = new ArrayList<>(); for (TextEditor editor : fileEditors) { final VirtualFile file = editor.getFile(); if (file == null) { continue; } final String uri = file.getPath(); editorForPath.put(uri, editor); uris.add(uri); } if (uris.isEmpty() && perfListeners.isEmpty()) { setRequestInProgress(false); return; } isDirty = false; showReports(editorForPath); } private void showReports(Multimap<String, TextEditor> editorForPath) { // True if any of the EditorPerfDecorations want to animate. boolean animate = false; synchronized (this) { for (String path : editorForPath.keySet()) { for (TextEditor fileEditor : editorForPath.get(path)) { if (!fileEditor.isValid()) return; final EditorPerfModel editorDecoration = editorDecorations.get(fileEditor); if (editorDecoration != null) { if (!perfProvider.shouldDisplayPerfStats(fileEditor)) { editorDecoration.clear(); continue; } final FilePerfInfo fileStats = buildSummaryStats(fileEditor); editorDecoration.setPerfInfo(fileStats); if (editorDecoration.isAnimationActive()) { animate = true; } } } } } if (!animate) { for (PerfModel listener : perfListeners) { if (listener.isAnimationActive()) { animate = true; break; } } } if (animate != uiAnimationTimer.isRunning()) { if (animate) { uiAnimationTimer.start(); } else { uiAnimationTimer.stop(); } } performRequestFinish(); } private FilePerfInfo buildSummaryStats(TextEditor fileEditor) { final FilePerfInfo fileStats = new FilePerfInfo(); if (fileEditor.getFile() == null) { return fileStats; } final String path = fileEditor.getFile().getPath(); for (PerfReportKind kind : PerfReportKind.values()) { final StatsForReportKind forKind = stats.get(kind); if (forKind == null) { continue; } final TIntObjectHashMap<SlidingWindowStats> data = forKind.data; for (Location location : locationsPerFile.get(path)) { final SlidingWindowStats entry = data.get(location.id); if (entry == null) { continue; } final TextRange range = location.textRange; if (range == null) { continue; } fileStats.add( range, new SummaryStats( kind, new SlidingWindowStatsSummary(entry, forKind.lastStartTime, location), location.name ) ); } } return fileStats; } private void performRequestFinish() { setRequestInProgress(false); JobScheduler.getScheduler().schedule(this::maybeNotifyIdle, IDLE_DELAY_MILISECONDS, TimeUnit.MILLISECONDS); if (isDirty) { requestRepaint(When.soon); } } private void maybeNotifyIdle() { if (isDisposed) { return; } if (System.currentTimeMillis() >= lastRequestTime + IDLE_DELAY_MILISECONDS) { AsyncUtils.invokeLater(() -> { for (EditorPerfModel decoration : editorDecorations.values()) { decoration.markAppIdle(); } for (PerfModel listener : perfListeners) { listener.markAppIdle(); } uiAnimationTimer.stop(); }); } } public void showFor(Set<TextEditor> editors) { AsyncUtils.invokeAndWait(() -> { currentEditors.clear(); currentEditors.addAll(editors); // Harvest old editors. harvestInvalidEditors(editors); for (TextEditor fileEditor : currentEditors) { // Create a new EditorPerfModel if necessary. if (!editorDecorations.containsKey(fileEditor)) { editorDecorations.put(fileEditor, perfModelFactory.create(fileEditor)); } } requestRepaint(When.now); }); } private void harvestInvalidEditors(Set<TextEditor> newEditors) { final Iterator<TextEditor> editors = editorDecorations.keySet().iterator(); while (editors.hasNext()) { final TextEditor editor = editors.next(); if (!editor.isValid() || (newEditors != null && !newEditors.contains(editor))) { final EditorPerfModel editorPerfDecorations = editorDecorations.get(editor); editors.remove(); Disposer.dispose(editorPerfDecorations); } } } public void setAlwaysShowLineMarkersOverride(boolean show) { for (EditorPerfModel model : editorDecorations.values()) { model.setAlwaysShowLineMarkersOverride(show); } } @Override public void dispose() { if (isDisposed) { return; } this.isDisposed = true; if (uiAnimationTimer.isRunning()) { uiAnimationTimer.stop(); } // TODO(jacobr): WidgetPerfProvider implements Disposer but its dispose method // needs to be called manually rather than using the Disposer API // because it is not registered for disposal using // Disposer.register perfProvider.dispose(); AsyncUtils.invokeLater(() -> { clearModels(); for (EditorPerfModel decorations : editorDecorations.values()) { // TODO(jacobr): EditorPerfModel implements Disposer but its dispose method // needs to be called manually rather than using the Disposer API // because it is not registered for disposal using // Disposer.register decorations.dispose(); } editorDecorations.clear(); perfListeners.clear(); }); } /** * Note: this must be called on the UI thread. */ @VisibleForTesting() public void clearModels() { for (EditorPerfModel decorations : editorDecorations.values()) { decorations.clear(); } for (PerfModel listener : perfListeners) { listener.clear(); } } protected void clear() { AsyncUtils.invokeLater(this::clearModels); } protected void onRestart() { AsyncUtils.invokeLater(() -> { // The app has restarted. Location ids may not be valid. knownLocationIds.clear(); stats.clear(); clearModels(); }); } public WidgetPerfLinter getPerfLinter() { return perfLinter; } public ArrayList<FilePerfInfo> buildAllSummaryStats(Set<TextEditor> textEditors) { final ArrayList<FilePerfInfo> stats = new ArrayList<>(); synchronized (this) { for (TextEditor textEditor : textEditors) { stats.add(buildSummaryStats(textEditor)); } } return stats; } public ArrayList<SlidingWindowStatsSummary> getStatsForMetric(ArrayList<PerfMetric> metrics, PerfReportKind kind) { final ArrayList<SlidingWindowStatsSummary> entries = new ArrayList<>(); synchronized (this) { final StatsForReportKind forKind = stats.get(kind); if (forKind != null) { final int time = forKind.lastNonEmptyReportTime; forKind.data.forEachEntry((int locationId, SlidingWindowStats stats) -> { for (PerfMetric metric : metrics) { if (stats.getValue(metric, time) > 0) { final Location location = knownLocationIds.get(locationId); // TODO(jacobr): consider changing this check for // location != null to an assert once the edge case leading to // occassional null locations has been fixed. I expect the edge // case occurs because we are sometimes including a few stats // from before a hot restart due to an incorrect ordering for // when the events occur. In any case, the extra != null check // is harmless and ensures the UI display is robust at the cost // of perhaps ommiting a little likely stale data. // See https://github.com/flutter/flutter-intellij/issues/2892 if (location != null) { entries.add(new SlidingWindowStatsSummary( stats, time, location )); } return true; } } return true; }); } } return entries; } }
flutter-intellij/flutter-idea/src/io/flutter/perf/FlutterWidgetPerf.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/FlutterWidgetPerf.java", "repo_id": "flutter-intellij", "token_count": 8324 }
471
/* * 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. */ package io.flutter.perf; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; import com.intellij.icons.AllIcons; import com.intellij.openapi.fileEditor.TextEditor; import io.flutter.FlutterBundle; import io.flutter.inspector.DiagnosticsNode; import java.util.*; import java.util.concurrent.CompletableFuture; import static io.flutter.perf.PerfTipRule.matchParent; /** * Linter that determines what performance tips to show. * <p> * Performance tips are generally derived from a FlutterWidgetPerf object to * provide rebuild counts for widgets in the app and the Widget tree expressed * as a tree of DiagnositcsNode to give information about the types of * ancestors of widgets in the tree. */ public class WidgetPerfLinter { private static List<PerfTipRule> tips; final FlutterWidgetPerf widgetPerf; private final WidgetPerfProvider perfProvider; private ArrayList<PerfTip> lastTips; private Set<Location> lastCandidateLocations; private Multimap<Integer, DiagnosticsNode> nodesForLocation; WidgetPerfLinter(FlutterWidgetPerf widgetPerf, WidgetPerfProvider perfProvider) { this.widgetPerf = widgetPerf; this.perfProvider = perfProvider; } static List<PerfTipRule> getAllTips() { if (tips != null) { return tips; } tips = new ArrayList<>(); tips.add(new PerfTipRule( PerfReportKind.rebuild, 3, "perf_diagnosis_demo/lib/clock_demo.dart", "Performance considerations of StatefulWidget", "statefulWidget", FlutterBundle.message("flutter.perf.linter.statefulWidget.url"), matchParent("StatefulWidget"), 4, // Only relevant if the build method is somewhat large. 50, 20, AllIcons.Actions.IntentionBulb )); tips.add(new PerfTipRule( PerfReportKind.rebuild, 1, "perf_diagnosis_demo/lib/list_demo.dart", "Using ListView to load items efficiently", "listViewLoad", FlutterBundle.message("flutter.perf.linter.listViewLoad.url"), matchParent("ListView"), 1, 40, -1, AllIcons.Actions.IntentionBulb )); tips.add(new PerfTipRule( PerfReportKind.rebuild, 1, "perf_diagnosis_demo/lib/spinning_box_demo.dart", "Performance optimizations when using AnimatedBuilder", "animatedBuilder", FlutterBundle.message("flutter.perf.linter.animatedBuilder.url"), matchParent("AnimatedBuilder"), 1, 50, 20, AllIcons.Actions.IntentionBulb )); tips.add(new PerfTipRule( PerfReportKind.rebuild, 2, "perf_diagnosis_demo/lib/scorecard_demo.dart", "Performance considerations of Opacity animations", "opacityAnimations", FlutterBundle.message("flutter.perf.linter.opacityAnimations.url"), matchParent("Opacity"), 1, 20, 8, AllIcons.Actions.IntentionBulb )); return tips; } public CompletableFuture<ArrayList<PerfTip>> getTipsFor(Set<TextEditor> textEditors) { final ArrayList<PerfTipRule> candidateRules = new ArrayList<>(); final Set<Location> candidateLocations = new HashSet<>(); final ArrayList<FilePerfInfo> allFileStats = widgetPerf.buildAllSummaryStats(textEditors); for (PerfTipRule rule : getAllTips()) { for (FilePerfInfo fileStats : allFileStats) { for (SummaryStats stats : fileStats.getStats()) { if (rule.maybeMatches(stats)) { candidateRules.add(rule); candidateLocations.add(stats.getLocation()); break; } } } } if (candidateRules.isEmpty()) { return CompletableFuture.completedFuture(new ArrayList<>()); } if (candidateLocations.equals(lastCandidateLocations)) { // No need to load the widget tree again if the list of locations matching rules has not changed. return CompletableFuture.completedFuture(computeMatches(candidateRules, allFileStats)); } lastCandidateLocations = candidateLocations; return perfProvider.getWidgetTree().thenApplyAsync((treeRoot) -> { if (treeRoot != null) { nodesForLocation = LinkedListMultimap.create(); addNodesToMap(treeRoot); return computeMatches(candidateRules, allFileStats); } else { return new ArrayList<>(); } }); } private ArrayList<PerfTip> computeMatches(ArrayList<PerfTipRule> candidateRules, ArrayList<FilePerfInfo> allFileStats) { final ArrayList<PerfTip> matches = new ArrayList<>(); final Map<PerfReportKind, Map<Integer, SummaryStats>> maps = new HashMap<>(); for (FilePerfInfo fileStats : allFileStats) { for (SummaryStats stats : fileStats.getStats()) { Map<Integer, SummaryStats> map = maps.get(stats.getKind()); //noinspection Java8MapApi if (map == null) { map = new HashMap<>(); maps.put(stats.getKind(), map); } map.put(stats.getLocation().id, stats); } } for (PerfTipRule rule : candidateRules) { final Map<Integer, SummaryStats> map = maps.get(rule.kind); if (map != null) { final ArrayList<Location> matchingLocations = new ArrayList<>(); for (FilePerfInfo fileStats : allFileStats) { for (SummaryStats stats : fileStats.getStats()) { if (nodesForLocation == null) { // TODO(jacobr): warn that we need a new widget tree. continue; } assert (stats.getLocation() != null); final Collection<DiagnosticsNode> nodes = nodesForLocation.get(stats.getLocation().id); if (nodes == null || nodes.isEmpty()) { // This indicates a mismatch between the current inspector tree and the stats we are using. continue; } if (rule.matches(stats, nodes, map)) { matchingLocations.add(stats.getLocation()); } } if (!matchingLocations.isEmpty()) { matches.add(new PerfTip(rule, matchingLocations, 1.0 / rule.priority)); } } } } matches.sort(Comparator.comparingDouble(a -> -a.getConfidence())); final Set<PerfTipRule> matchingRules = new HashSet<>(); final ArrayList<PerfTip> uniqueMatches = new ArrayList<>(); for (PerfTip match : matches) { if (matchingRules.add(match.rule)) { uniqueMatches.add(match); } } return uniqueMatches; } private void addNodesToMap(DiagnosticsNode node) { final int id = node.getLocationId(); if (id >= 0) { nodesForLocation.put(id, node); } final ArrayList<DiagnosticsNode> children = node.getChildren().getNow(null); if (children != null) { for (DiagnosticsNode child : children) { addNodesToMap(child); } } } }
flutter-intellij/flutter-idea/src/io/flutter/perf/WidgetPerfLinter.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/WidgetPerfLinter.java", "repo_id": "flutter-intellij", "token_count": 2792 }
472
/* * 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. */ package io.flutter.preview; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.openapi.wm.ToolWindowManager; import io.flutter.utils.ViewListener; import org.jetbrains.annotations.NotNull; public class PreviewViewFactory implements ToolWindowFactory, DumbAware { private static final String TOOL_WINDOW_VISIBLE_PROPERTY = "flutter.preview.tool.window.visible"; public static void init(@NotNull Project project) { final ToolWindow window = ToolWindowManager.getInstance(project).getToolWindow(PreviewView.TOOL_WINDOW_ID); if (window != null) { window.setAvailable(true); if (PropertiesComponent.getInstance(project).getBoolean(TOOL_WINDOW_VISIBLE_PROPERTY, false)) { window.activate(null, false); } } } @Override public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { //noinspection CodeBlock2Expr DumbService.getInstance(project).runWhenSmart(() -> { (project.getService(PreviewView.class)).initToolWindow(toolWindow); }); } @Override public boolean shouldBeAvailable(@NotNull Project project) { return false; } public static class PreviewViewListener extends ViewListener { public PreviewViewListener(@NotNull Project project) { super(project, PreviewView.TOOL_WINDOW_ID, TOOL_WINDOW_VISIBLE_PROPERTY); } } }
flutter-intellij/flutter-idea/src/io/flutter/preview/PreviewViewFactory.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/preview/PreviewViewFactory.java", "repo_id": "flutter-intellij", "token_count": 578 }
473
/* * Copyright 2016 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. */ package io.flutter.run; import com.intellij.execution.ExecutionResult; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.ui.RunnerLayoutUi; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Computable; import com.intellij.ui.content.Content; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerBundle; import com.jetbrains.lang.dart.util.DartUrlResolver; import io.flutter.FlutterUtils; import io.flutter.actions.ReloadAllFlutterApps; import io.flutter.actions.ReloadFlutterApp; import io.flutter.actions.RestartAllFlutterApps; import io.flutter.actions.RestartFlutterApp; import io.flutter.inspector.InspectorService; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.FlutterApp; import io.flutter.view.FlutterViewMessages; import io.flutter.vmService.DartVmServiceDebugProcess; import org.dartlang.vm.service.VmService; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; /** * A debug process that handles hot reloads for Flutter. * <p> * It's used for both the 'Run' and 'Debug' modes. (We apparently need a debug process even * when not debugging in order to support hot reload.) */ public class FlutterDebugProcess extends DartVmServiceDebugProcess { private static final Logger LOG = Logger.getInstance(FlutterDebugProcess.class); private final @NotNull FlutterApp app; public FlutterDebugProcess(@NotNull FlutterApp app, @NotNull ExecutionEnvironment executionEnvironment, @NotNull XDebugSession session, @NotNull ExecutionResult executionResult, @NotNull DartUrlResolver dartUrlResolver, @NotNull PositionMapper mapper) { super(executionEnvironment, session, executionResult, dartUrlResolver, app.getConnector(), mapper); this.app = app; } @NotNull public FlutterApp getApp() { return app; } CompletableFuture<InspectorService> inspectorService; public CompletableFuture<InspectorService> getInspectorService() { if (inspectorService == null && getVmConnected() && app.getVmService() != null) { inspectorService = InspectorService.create(app, this, app.getVmService()); } return inspectorService; } @Override protected void onVmConnected(@NotNull VmService vmService) { app.setFlutterDebugProcess(this); FlutterViewMessages.sendDebugActive(getSession().getProject(), app, vmService); } @Override public void registerAdditionalActions(@NotNull final DefaultActionGroup leftToolbar, @NotNull final DefaultActionGroup topToolbar, @NotNull final DefaultActionGroup settings) { if (app.getMode() != RunMode.DEBUG) { // Remove the debug-specific actions that aren't needed when we're not debugging. // Remove all but specified actions. final AnAction[] leftActions = leftToolbar.getChildActionsOrStubs(); // Not all on the classpath so we resort to Strings. final List<String> actionClassNames = Arrays .asList("com.intellij.execution.actions.StopAction", "com.intellij.ui.content.tabs.PinToolwindowTabAction", "com.intellij.execution.ui.actions.CloseAction", "com.intellij.ide.actions.ContextHelpAction"); for (AnAction a : leftActions) { if (!actionClassNames.contains(a.getClass().getName())) { leftToolbar.remove(a); } } // Remove all top actions. final AnAction[] topActions = topToolbar.getChildActionsOrStubs(); for (AnAction action : topActions) { topToolbar.remove(action); } // Remove all settings actions. final AnAction[] settingsActions = settings.getChildActionsOrStubs(); for (AnAction a : settingsActions) { settings.remove(a); } } // Add actions common to the run and debug windows. final Computable<Boolean> isSessionActive = () -> app.isStarted() && getVmConnected() && !getSession().isStopped(); final Computable<Boolean> canReload = () -> app.getLaunchMode().supportsReload() && isSessionActive.compute() && !app.isReloading(); final Computable<Boolean> debugUrlAvailable = () -> isSessionActive.compute() && app.getConnector().getBrowserUrl() != null; if (app.getMode() == RunMode.DEBUG) { topToolbar.addSeparator(); topToolbar.addAction(new FlutterPopFrameAction()); } topToolbar.addSeparator(); topToolbar.addAction(new ReloadFlutterApp(app, canReload)); topToolbar.addAction(new RestartFlutterApp(app, canReload)); topToolbar.addSeparator(); topToolbar.addAction(new OpenDevToolsAction(app, debugUrlAvailable)); settings.addAction(new ReloadAllFlutterApps(app, canReload)); settings.addAction(new RestartAllFlutterApps(app, canReload)); // Don't call super since we have our own observatory action. } @Override public void sessionInitialized() { if (app.getMode() != RunMode.DEBUG) { suppressDebugViews(getSession().getUI()); } } /** * Turn off debug-only views (variables and frames). */ private static void suppressDebugViews(@Nullable RunnerLayoutUi ui) { if (ui == null) { return; } final String name = XDebuggerBundle.message("debugger.session.tab.console.content.name"); for (Content c : ui.getContents()) { if (!Objects.equals(c.getTabName(), name)) { try { ApplicationManager.getApplication().invokeAndWait(() -> ui.removeContent(c, false /* dispose? */)); } catch (ProcessCanceledException e) { FlutterUtils.warn(LOG, e); } } } } }
flutter-intellij/flutter-idea/src/io/flutter/run/FlutterDebugProcess.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterDebugProcess.java", "repo_id": "flutter-intellij", "token_count": 2309 }
474
/* * Copyright 2016 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. */ package io.flutter.run; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.xmlb.annotations.OptionTag; import com.intellij.util.xmlb.annotations.XMap; import com.jetbrains.lang.dart.sdk.DartConfigurable; import com.jetbrains.lang.dart.sdk.DartSdk; import io.flutter.FlutterBundle; import io.flutter.FlutterInitializer; import io.flutter.dart.DartPlugin; import io.flutter.pub.PubRoot; import io.flutter.pub.PubRootCache; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.DevToolsInstance; import io.flutter.run.daemon.DevToolsService; import io.flutter.sdk.FlutterCommand; import io.flutter.sdk.FlutterSdk; import io.flutter.settings.FlutterSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; /** * Fields used when launching an app using the Flutter SDK (non-bazel). */ public class SdkFields { private static final Logger LOG = Logger.getInstance(SdkFields.class); private @Nullable String filePath; private @Nullable String buildFlavor; private @Nullable String additionalArgs; private @Nullable String attachArgs; private @NotNull Map<String, String> envs = new LinkedHashMap<>(); public SdkFields() { } /** * Creates SDK fields from a Dart file containing a main method. */ public SdkFields(VirtualFile launchFile) { filePath = launchFile.getPath(); } @Nullable public String getFilePath() { return filePath; } public void setFilePath(final @Nullable String path) { filePath = path; } @Nullable public String getBuildFlavor() { return buildFlavor; } public void setBuildFlavor(final @Nullable String buildFlavor) { this.buildFlavor = buildFlavor; } @Nullable public String getAdditionalArgs() { return additionalArgs; } public void setAdditionalArgs(final @Nullable String additionalArgs) { this.additionalArgs = additionalArgs; } public boolean hasAdditionalArgs() { return additionalArgs != null; } public String[] getAdditionalArgsParsed() { if (hasAdditionalArgs()) { assert additionalArgs != null; return ParametersListUtil.parse(additionalArgs, false, true, true).toArray(new String[0]); } return new String[0]; } @Nullable public String getAttachArgs() { return attachArgs; } public void setAttachArgs(@Nullable String attachArgs) { this.attachArgs = attachArgs; } public boolean hasAttachArgs() { return attachArgs != null; } public String[] getAttachArgsParsed() { if (hasAttachArgs()) { assert attachArgs != null; return ParametersListUtil.parse(attachArgs, false, true, true).toArray(new String[0]); } return new String[0]; } /** * Present only for deserializing old run configs. */ @SuppressWarnings("SameReturnValue") @Deprecated @Nullable public String getWorkingDirectory() { return null; } /** * Present only for deserializing old run configs. */ @SuppressWarnings("EmptyMethod") @Deprecated public void setWorkingDirectory(final @Nullable String dir) { } @NotNull @OptionTag @XMap public Map<String, String> getEnvs() { return envs; } public void setEnvs(final Map<String, String> envs) { if (envs != null) { // null comes from old projects or if storage corrupted this.envs = envs; } } /** * Reports any errors that the user should correct. * <p>This will be called while the user is typing; see RunConfiguration.checkConfiguration. * * @throws RuntimeConfigurationError for an error that that the user must correct before running. */ void checkRunnable(@NotNull Project project) throws RuntimeConfigurationError { // TODO(pq): consider validating additional args values checkSdk(project); final MainFile.Result main = MainFile.verify(filePath, project); if (!main.canLaunch()) { throw new RuntimeConfigurationError(main.getError()); } if (PubRootCache.getInstance(project).getRoot(main.get().getAppDir()) == null) { throw new RuntimeConfigurationError("Entrypoint isn't within a Flutter pub root"); } } /** * Create a command to run 'flutter run --machine'. */ public GeneralCommandLine createFlutterSdkRunCommand( @NotNull Project project, @NotNull RunMode runMode, @NotNull FlutterLaunchMode flutterLaunchMode, @NotNull FlutterDevice device, boolean firstRun) throws ExecutionException { final MainFile main = MainFile.verify(filePath, project).get(); final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project); if (flutterSdk == null) { throw new ExecutionException(FlutterBundle.message("flutter.sdk.is.not.configured")); } final PubRoot root = PubRoot.forDirectory(main.getAppDir()); if (root == null) { throw new ExecutionException("Entrypoint isn't within a Flutter pub root"); } final FlutterCommand command; String[] args = getAdditionalArgsParsed(); if (buildFlavor != null) { args = ArrayUtil.append(args, "--flavor=" + buildFlavor); } if (FlutterSettings.getInstance().isShowStructuredErrors() && flutterSdk.getVersion().isDartDefineSupported()) { args = ArrayUtil.append(args, "--dart-define=flutter.inspector.structuredErrors=true"); } if (flutterSdk.getVersion().flutterRunSupportsDevToolsUrl()) { try { final ProgressManager progress = ProgressManager.getInstance(); final CompletableFuture<DevToolsInstance> devToolsFuture = new CompletableFuture<>(); progress.runProcessWithProgressSynchronously(() -> { progress.getProgressIndicator().setIndeterminate(true); try { final CompletableFuture<DevToolsInstance> futureInstance = DevToolsService.getInstance(project).getDevToolsInstance(); if (firstRun) { devToolsFuture.complete(futureInstance.get(30, TimeUnit.SECONDS)); } else { // Skip waiting if this isn't the first time running this project. If DevTools isn't available by now, there's likely to be // something wrong that won't be fixed by restarting, so we don't want to keep delaying run. final DevToolsInstance instance = futureInstance.getNow(null); if (instance == null) { devToolsFuture.completeExceptionally(new Exception("DevTools instance not available after first run.")); } else { devToolsFuture.complete(instance); } } } catch (Exception e) { devToolsFuture.completeExceptionally(e); } }, "Starting DevTools", false, project); final DevToolsInstance instance = devToolsFuture.get(); args = ArrayUtil.append(args, "--devtools-server-address=http://" + instance.host + ":" + instance.port); if (firstRun) { FlutterInitializer.getAnalytics().sendEvent("devtools", "first-run-success"); } } catch (Exception e) { LOG.info(e); FlutterInitializer.getAnalytics().sendExpectedException("devtools", e); } } command = flutterSdk.flutterRun(root, main.getFile(), device, runMode, flutterLaunchMode, project, args); final GeneralCommandLine commandLine = command.createGeneralCommandLine(project); commandLine.getEnvironment().putAll(getEnvs()); commandLine.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE); return commandLine; } /** * Create a command to run 'flutter attach --machine'. */ public GeneralCommandLine createFlutterSdkAttachCommand(@NotNull Project project, @NotNull FlutterLaunchMode flutterLaunchMode, @Nullable FlutterDevice device) throws ExecutionException { final MainFile main = MainFile.verify(filePath, project).get(); final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project); if (flutterSdk == null) { throw new ExecutionException(FlutterBundle.message("flutter.sdk.is.not.configured")); } final PubRoot root = PubRoot.forDirectory(main.getAppDir()); if (root == null) { throw new ExecutionException("Entrypoint isn't within a Flutter pub root"); } final String[] args = getAttachArgsParsed(); final FlutterCommand command = flutterSdk.flutterAttach(root, main.getFile(), device, flutterLaunchMode, args); return command.createGeneralCommandLine(project); } SdkFields copy() { final SdkFields copy = new SdkFields(); copy.setFilePath(filePath); copy.setAdditionalArgs(additionalArgs); copy.setBuildFlavor(buildFlavor); copy.envs.putAll(envs); return copy; } private static void checkSdk(@NotNull Project project) throws RuntimeConfigurationError { // TODO(skybrian) shouldn't this be flutter SDK? final DartSdk sdk = DartPlugin.getDartSdk(project); if (sdk == null) { throw new RuntimeConfigurationError(FlutterBundle.message("dart.sdk.is.not.configured"), () -> DartConfigurable.openDartSettings(project)); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/SdkFields.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/SdkFields.java", "repo_id": "flutter-intellij", "token_count": 3553 }
475
/* * 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. */ package io.flutter.run.bazelTest; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; /** * Modifies a bazel test configuration to watch a test instead of one-off running it. */ public class BazelWatchTestConfigProducer extends BazelTestConfigProducer { BazelWatchTestConfigProducer() { super(FlutterBazelTestConfigurationType.getInstance().watchFactory); } @Override protected boolean setupConfigurationFromContext(@NotNull BazelTestConfig config, @NotNull ConfigurationContext context, @NotNull Ref<PsiElement> sourceElement) { if (!super.setupConfigurationFromContext(config, context, sourceElement)) return false; config.setName(config.getName().replaceFirst("Run", "Watch")); return true; } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelWatchTestConfigProducer.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelWatchTestConfigProducer.java", "repo_id": "flutter-intellij", "token_count": 397 }
476
/* * 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. */ package io.flutter.run.coverage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.rt.coverage.data.ClassData; import com.intellij.rt.coverage.data.LineData; import com.intellij.rt.coverage.data.ProjectData; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; public class LcovInfo { private static final Logger LOG = Logger.getInstance(LcovInfo.class.getName()); private static final String FILE_LABEL = "SF:"; private static final String DATA_LABEL = "DA:"; private static final String END_LABEL = "end_of_record"; private final Map<String, List<LineCount>> counts = new HashMap<>(); private Path currentFile = null; private List<LineCount> lineCounts = null; private final String base; private LcovInfo(String base) { this.base = base; } public static void readInto(@NotNull ProjectData data, @NotNull File file) throws IOException { final String filePath = file.getAbsolutePath(); final int index = filePath.indexOf("coverage"); if (index < 0) { // TODO Define at least one class in data return; } final LcovInfo lcov = new LcovInfo(filePath.substring(0, index)); try (final Stream<String> lines = Files.lines(file.toPath())) { lines.forEach(lcov::processLine); } for (String path : lcov.counts.keySet()) { final List<LineCount> list = lcov.counts.get(path); if (list == null || list.isEmpty()) { continue; } final ClassData classData = data.getOrCreateClassData(path); classData.setSource(fullPath(path)); final int max = list.get(list.size() - 1).lineNum + 1; final LineData[] lines = new LineData[max]; for (LineCount line : list) { final LineData lineData = new LineData(line.lineNum, null); lineData.setHits(line.execCount); lines[line.lineNum] = lineData; classData.registerMethodSignature(lineData); } classData.setLines(lines); } } void processLine(String line) { line = line.trim(); if (line.startsWith(DATA_LABEL)) { assert currentFile != null; assert lineCounts != null; addLineCount(line.substring(DATA_LABEL.length())); } else if (line.startsWith(FILE_LABEL)) { //currentFile = Paths.get(line.substring(FILE_LABEL.length())).normalize(); final File file = new File(base, line.substring(FILE_LABEL.length())); final URI normalize = file.toURI().normalize(); currentFile = Paths.get(normalize); lineCounts = new ArrayList<>(); } else if (line.equals(END_LABEL)) { storeLineCounts(); currentFile = null; lineCounts = null; } } private void addLineCount(String data) { final String[] parts = data.split(","); assert parts.length >= 2; final int lineNum = safelyParse(parts[0]); final int execCount = safelyParse(parts[1]); lineCounts.add(new LineCount(lineNum, execCount)); } private static int safelyParse(String val) { try { return Integer.parseInt(val); } catch (NumberFormatException ex) { return 0; } } private void storeLineCounts() { final String path = fullPath(currentFile.toString()); counts.put(path, lineCounts); } private static String fullPath(String path) { String absPath = new File(path).getAbsolutePath(); if (SystemInfo.isWindows) { absPath = absPath.replaceAll("\\\\", "/"); } return absPath; } private static class LineCount { int lineNum; int execCount; public LineCount(int num, int count) { lineNum = num; execCount = count; } } }
flutter-intellij/flutter-idea/src/io/flutter/run/coverage/LcovInfo.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/coverage/LcovInfo.java", "repo_id": "flutter-intellij", "token_count": 1529 }
477
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run.test; import com.intellij.execution.Location; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.jetbrains.lang.dart.psi.DartCallExpression; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlutterTestLocationProvider extends DartTestLocationProviderZ { public static final FlutterTestLocationProvider INSTANCE = new FlutterTestLocationProvider(); private static final String TEST_WIDGETS = "testWidgets"; private final TestConfigUtils testConfigUtils = TestConfigUtils.getInstance(); @Nullable @Override protected Location<PsiElement> getLocationByLineAndColumn(@NotNull PsiFile file, int line, int column) { try { return super.getLocationByLineAndColumn(file, line, column); } catch (IndexOutOfBoundsException e) { // Line and column info can be wrong, in which case we fall-back on test and group name for test discovery. } return null; } @Override protected boolean isTest(@NotNull DartCallExpression expression) { return super.isTest(expression) || testConfigUtils.asTestCall(expression) != null || // The previous check works if the outline has already been populated. // However, if it needs to be updated then that will fail, as updating is async. TEST_WIDGETS.equals(expression.getExpression().getText()); } }
flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestLocationProvider.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestLocationProvider.java", "repo_id": "flutter-intellij", "token_count": 508 }
478
/* * 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. */ package io.flutter.sdk; import com.intellij.execution.ExecutionException; import com.intellij.execution.process.ColoredProcessHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlutterCommandStartResult { @NotNull public final FlutterCommandStartResultStatus status; @Nullable public final ColoredProcessHandler processHandler; @Nullable public final ExecutionException exception; public FlutterCommandStartResult(@NotNull FlutterCommandStartResultStatus status) { this(status, null, null); } public FlutterCommandStartResult(@Nullable ColoredProcessHandler processHandler) { this(FlutterCommandStartResultStatus.OK, processHandler, null); } public FlutterCommandStartResult(@Nullable ExecutionException exception) { this(FlutterCommandStartResultStatus.EXCEPTION, null, exception); } public FlutterCommandStartResult(@NotNull FlutterCommandStartResultStatus status, @Nullable ColoredProcessHandler processHandler, @Nullable ExecutionException exception) { this.status = status; this.processHandler = processHandler; this.exception = exception; } }
flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterCommandStartResult.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterCommandStartResult.java", "repo_id": "flutter-intellij", "token_count": 439 }
479
/* * Copyright 2016 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. */ package io.flutter.settings; /** * Persists Flutter settings for a session. */ public class FlutterUIConfig { private static final FlutterUIConfig INSTANCE = new FlutterUIConfig(); private boolean ignoreOutOfDateFlutterSdks; private FlutterUIConfig() { } public static FlutterUIConfig getInstance() { return INSTANCE; } public boolean shouldIgnoreOutOfDateFlutterSdks() { return ignoreOutOfDateFlutterSdks; } public void setIgnoreOutOfDateFlutterSdks() { ignoreOutOfDateFlutterSdks = true; } }
flutter-intellij/flutter-idea/src/io/flutter/settings/FlutterUIConfig.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/settings/FlutterUIConfig.java", "repo_id": "flutter-intellij", "token_count": 228 }
480
/* * 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. */ package io.flutter.utils; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.util.ui.EdtInvocationManager; import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService; import com.jetbrains.lang.dart.sdk.DartSdk; import com.jetbrains.lang.dart.sdk.DartSdkLibUtil; import com.jetbrains.lang.dart.sdk.DartSdkUtil; import org.jetbrains.annotations.NotNull; // Adapted from private class com.jetbrains.lang.dart.ide.actions.DartEditorNotificationsProvider.EnableDartSupportForModule. class EnableDartSupportForModule implements Runnable { private final Module myModule; EnableDartSupportForModule(@NotNull final Module module) { this.myModule = module; } @Override public void run() { final Project project = myModule.getProject(); EdtInvocationManager.getInstance().invokeLater(() -> { ApplicationManager.getApplication().invokeLater(() -> { ApplicationManager.getApplication().runWriteAction(() -> { if (DartSdk.getDartSdk(project) == null || !DartSdkLibUtil.isDartSdkEnabled(myModule)) { final String sdkPath = DartSdkUtil.getFirstKnownDartSdkPath(); if (DartSdkUtil.isDartSdkHome(sdkPath)) { DartSdkLibUtil.ensureDartSdkConfigured(project, sdkPath); DartSdkLibUtil.enableDartSdk(myModule); } else { FlutterModuleUtils.enableDartSDK(myModule); } } }); ApplicationManager.getApplication().executeOnPooledThread(() -> { ApplicationManager.getApplication().runReadAction(() -> { DartAnalysisServerService.getInstance(project).serverReadyForRequest(); }); }); }); }); } }
flutter-intellij/flutter-idea/src/io/flutter/utils/EnableDartSupportForModule.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/EnableDartSupportForModule.java", "repo_id": "flutter-intellij", "token_count": 773 }
481
/* * 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. */ package io.flutter.utils; import java.nio.*; public abstract class TypedDataList { public abstract String getValue(int i); public abstract int size(); public static class Int8List extends TypedDataList { final ByteBuffer buffer; public Int8List(byte [] bytes) { buffer = ByteBuffer.wrap(bytes); } public String getValue(int i) { return Byte.toString(buffer.get(i)); } public int size() { return buffer.capacity(); } } public static class Uint8List extends Int8List { public Uint8List(byte [] bytes) { super(bytes); } public String getValue(int i) { return "0x" + Integer.toHexString(buffer.get(i) & 0xff); } } public static class Int16List extends TypedDataList { final ShortBuffer buffer; public Int16List(byte [] bytes) { // 95% of CPUs are running in little-endian mode now, and we're not going to get fancy here. // If this becomes a problem, see the Dart code Endian.host for a way to possibly fix it. //noinspection ConstantConditions buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer(); } public String getValue(int i) { return Short.toString(buffer.get(i)); } public int size() { return buffer.capacity(); } } public static class Uint16List extends Int16List { public Uint16List(byte [] bytes) { super(bytes); } public String getValue(int i) { return "0x" + Integer.toHexString(buffer.get(i) & 0xffff); } } public static class Int32List extends TypedDataList { final IntBuffer buffer; public Int32List(byte [] bytes) { //noinspection ConstantConditions buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); } public String getValue(int i) { return Integer.toString(buffer.get(i)); } public int size() { return buffer.capacity(); } } public static class Uint32List extends Int32List { public Uint32List(byte [] bytes) { super(bytes); } public String getValue(int i) { return "0x" + Integer.toHexString(buffer.get(i)); } } public static class Int64List extends TypedDataList { final LongBuffer buffer; public Int64List(byte [] bytes) { //noinspection ConstantConditions buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); } public String getValue(int i) { return Long.toString(buffer.get(i)); } public int size() { return buffer.capacity(); } } public static class Uint64List extends Int64List { public Uint64List(byte [] bytes) { super(bytes); } public String getValue(int i) { return "0x" + Long.toUnsignedString(buffer.get(i), 16); } } public static class Float32List extends TypedDataList { final FloatBuffer buffer; public Float32List(byte [] bytes) { //noinspection ConstantConditions buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer(); } public String getValue(int i) { return String.valueOf(buffer.get(i)); } public int size() { return buffer.capacity(); } } public static class Float64List extends TypedDataList { final DoubleBuffer buffer; public Float64List(byte [] bytes) { //noinspection ConstantConditions buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); } public String getValue(int i) { return String.valueOf(buffer.get(i)); } public int size() { return buffer.capacity(); } } }
flutter-intellij/flutter-idea/src/io/flutter/utils/TypedDataList.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/TypedDataList.java", "repo_id": "flutter-intellij", "token_count": 1450 }
482
/* * 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. */ package io.flutter.utils.math; /** * This code is ported from the Dart vector_math package. */ public class VectorUtil { public static double clamp(double x, double min, double max) { return Math.min(Math.max(x, min), max); } /** * 2D dot product. */ public static double dot2(Vector2 x, Vector2 y) { return x.dot(y); } /** * 3D dot product. */ public static double dot3(Vector3 x, Vector3 y) { return x.dot(y); } /** * 3D Cross product. */ public static void cross3(Vector3 x, Vector3 y, Vector3 out) { x.crossInto(y, out); } /** * 2D cross product. vec2 x vec2. */ public static double cross2(Vector2 x, Vector2 y) { return x.cross(y); } /** * 2D cross product. double x vec2. */ public static void cross2A(double x, Vector2 y, Vector2 out) { final double tempy = x * y.getX(); out.setX(-x * y.getY()); out.setY(tempy); } /** * 2D cross product. vec2 x double. */ public static void cross2B(Vector2 x, double y, Vector2 out) { final double tempy = -y * x.getX(); out.setX(y * x.getY()); out.setY(tempy); } }
flutter-intellij/flutter-idea/src/io/flutter/utils/math/VectorUtil.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/math/VectorUtil.java", "repo_id": "flutter-intellij", "token_count": 503 }
483
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.view; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.ui.*; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.dualView.TreeTableView; import com.intellij.ui.treeStructure.Tree; import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns; import com.intellij.util.ui.ColumnInfo; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.tree.TreeUtil; import io.flutter.FlutterBundle; import io.flutter.FlutterUtils; import io.flutter.editor.FlutterMaterialIcons; import io.flutter.inspector.*; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.*; import org.dartlang.vm.service.element.InstanceRef; import org.dartlang.vm.service.element.IsolateRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.*; import java.util.concurrent.CompletableFuture; public class InspectorPanel extends JPanel implements Disposable, InspectorService.InspectorServiceClient, InspectorTabPanel { /** * Maximum frame rate to refresh the inspector panel at to avoid taxing the * physical device with too many requests to recompute properties and trees. * <p> * A value up to around 30 frames per second could be reasonable for * debugging highly interactive cases particularly when the user is on a * simulator or high powered native device. The frame rate is set low * for now mainly to minimize the risk of unintended consequences. */ public static final double REFRESH_FRAMES_PER_SECOND = 5.0; // We have to define this because SimpleTextAttributes does not define a // value for warnings. private static final SimpleTextAttributes WARNING_ATTRIBUTES = new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBColor.ORANGE); private static final Logger LOG = Logger.getInstance(InspectorPanel.class); protected final boolean detailsSubtree; protected final boolean isSummaryTree; /** * Parent InspectorPanel if this is a details subtree */ @Nullable protected final InspectorPanel parentTree; protected final InspectorPanel subtreePanel; final CustomIconMaker iconMaker = new CustomIconMaker(); final Splitter treeSplitter; final Icon defaultIcon; final JBScrollPane treeScrollPane; private final InspectorTree myRootsTree; @Nullable private final PropertiesPanel myPropertiesPanel; private final Computable<Boolean> isApplicable; private final InspectorService.FlutterTreeType treeType; @NotNull private final FlutterApp flutterApp; @NotNull private final InspectorService inspectorService; private final StreamSubscription<IsolateRef> flutterIsolateSubscription; private final TreeScrollAnimator scrollAnimator; /** * Mode with a tree view and a property table instead of a details tree and * a summary tree. */ private final boolean legacyMode; @Nullable private AsyncRateLimiter refreshRateLimiter; /** * Groups used to manage and cancel requests to load data to display directly * in the tree. */ private final InspectorObjectGroupManager treeGroups; /** * Groups used to manage and cancel requests to determine what the current * selection is. * <p> * This group needs to be kept separate from treeGroups as the selection is * shared more with the details subtree. * TODO(jacobr): is there a way we can unify the selection and tree groups? */ private final InspectorObjectGroupManager selectionGroups; /** * Node being highlighted due to the current hover. */ protected DefaultMutableTreeNode currentShowNode; boolean flutterAppFrameReady = false; private boolean treeLoadStarted = false; private DiagnosticsNode subtreeRoot; private boolean programaticSelectionChangeInProgress = false; private boolean programaticExpansionInProgress = false; private DefaultMutableTreeNode selectedNode; private DefaultMutableTreeNode lastExpanded; private boolean isActive = false; private final Map<InspectorInstanceRef, DefaultMutableTreeNode> valueToTreeNode = new HashMap<>(); /** * When visibleToUser is false we should dispose all allocated objects and * not perform any actions. */ private boolean visibleToUser = false; private boolean highlightNodesShownInBothTrees = false; public InspectorPanel(FlutterView flutterView, @NotNull FlutterApp flutterApp, @NotNull InspectorService inspectorService, @NotNull Computable<Boolean> isApplicable, @NotNull InspectorService.FlutterTreeType treeType, boolean isSummaryTree, boolean legacyMode, @NotNull EventStream<Boolean> shouldAutoHorizontalScroll, @NotNull EventStream<Boolean> highlightNodesShownInBothTrees ) { this(flutterView, flutterApp, inspectorService, isApplicable, treeType, false, null, isSummaryTree, legacyMode, shouldAutoHorizontalScroll, highlightNodesShownInBothTrees); } private InspectorPanel(FlutterView flutterView, @NotNull FlutterApp flutterApp, @NotNull InspectorService inspectorService, @NotNull Computable<Boolean> isApplicable, @NotNull InspectorService.FlutterTreeType treeType, boolean detailsSubtree, @Nullable InspectorPanel parentTree, boolean isSummaryTree, boolean legacyMode, @NotNull EventStream<Boolean> shouldAutoHorizontalScroll, @NotNull EventStream<Boolean> highlightNodesShownInBothTrees) { super(new BorderLayout()); this.treeType = treeType; this.flutterApp = flutterApp; this.inspectorService = inspectorService; this.treeGroups = new InspectorObjectGroupManager(inspectorService, "tree"); this.selectionGroups = new InspectorObjectGroupManager(inspectorService, "selection"); this.isApplicable = isApplicable; this.detailsSubtree = detailsSubtree; this.isSummaryTree = isSummaryTree; this.parentTree = parentTree; this.legacyMode = legacyMode; this.defaultIcon = iconMaker.fromInfo("Default"); if (!Disposer.isDisposed(flutterApp)) { // Only process refresh requests if the app is still running. refreshRateLimiter = new AsyncRateLimiter(REFRESH_FRAMES_PER_SECOND, this::refresh, flutterApp); } final String parentTreeDisplayName = (parentTree != null) ? parentTree.treeType.displayName : null; myRootsTree = new InspectorTree( new DefaultMutableTreeNode(null), treeType.displayName, detailsSubtree, parentTreeDisplayName, treeType != InspectorService.FlutterTreeType.widget || (!isSummaryTree && !legacyMode), legacyMode, flutterApp ); // We want to reserve double clicking for navigation within the detail // tree and in the future for editing values in the tree. myRootsTree.setHorizontalAutoScrollingEnabled(false); myRootsTree.setAutoscrolls(false); myRootsTree.setToggleClickCount(0); myRootsTree.addTreeExpansionListener(new MyTreeExpansionListener()); final InspectorTreeMouseListener mouseListener = new InspectorTreeMouseListener(this, myRootsTree); myRootsTree.addMouseListener(mouseListener); myRootsTree.addMouseMotionListener(mouseListener); if (isSummaryTree && !legacyMode) { subtreePanel = new InspectorPanel( flutterView, flutterApp, inspectorService, isApplicable, treeType, true, this, false, legacyMode, shouldAutoHorizontalScroll, highlightNodesShownInBothTrees ); } else { subtreePanel = null; } initTree(myRootsTree); myRootsTree.getSelectionModel().addTreeSelectionListener(this::selectionChanged); treeScrollPane = (JBScrollPane)ScrollPaneFactory.createScrollPane(myRootsTree); treeScrollPane.setAutoscrolls(false); scrollAnimator = new TreeScrollAnimator(myRootsTree, treeScrollPane); shouldAutoHorizontalScroll.listen(scrollAnimator::setAutoHorizontalScroll, true); highlightNodesShownInBothTrees.listen(this::setHighlightNodesShownInBothTrees, true); myRootsTree.setScrollAnimator(scrollAnimator); if (!detailsSubtree) { treeSplitter = new Splitter(false); treeSplitter.setProportion(flutterView.getState().getSplitterProportion()); flutterView.getState().addListener(e -> { final float newProportion = flutterView.getState().getSplitterProportion(); if (treeSplitter.getProportion() != newProportion) { treeSplitter.setProportion(newProportion); } }); //noinspection Convert2Lambda treeSplitter.addPropertyChangeListener("proportion", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { flutterView.getState().setSplitterProportion(treeSplitter.getProportion()); } }); if (subtreePanel == null) { myPropertiesPanel = new PropertiesPanel(flutterApp, inspectorService); treeSplitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myPropertiesPanel)); } else { myPropertiesPanel = null; /// This InspectorPanel doesn't have its own property panel. treeSplitter.setSecondComponent(subtreePanel); } Disposer.register(this, treeSplitter::dispose); Disposer.register(this, scrollAnimator::dispose); treeSplitter.setFirstComponent(treeScrollPane); add(treeSplitter); } else { treeSplitter = null; myPropertiesPanel = null; add(treeScrollPane); } this.addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent e) { determineSplitterOrientation(); } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { determineSplitterOrientation(); } @Override public void componentHidden(ComponentEvent e) { } }); determineSplitterOrientation(); if (isDetailsSubtree()) { // Draw a separator line between the main inspector tree and the details tree. setBorder(JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0)); } flutterIsolateSubscription = inspectorService.getApp().getVMServiceManager().getCurrentFlutterIsolate((IsolateRef flutterIsolate) -> { if (flutterIsolate == null) { onIsolateStopped(); } }, true); } @VisibleForTesting public boolean isDetailsSubtree() { return detailsSubtree; } @VisibleForTesting public boolean isSummaryTree() { return isSummaryTree; } public boolean isHighlightNodesShownInBothTrees() { return highlightNodesShownInBothTrees; } private void setHighlightNodesShownInBothTrees(boolean value) { if (highlightNodesShownInBothTrees != value) { highlightNodesShownInBothTrees = value; myRootsTree.repaint(); } } static DiagnosticsNode getDiagnosticNode(TreeNode treeNode) { if (!(treeNode instanceof DefaultMutableTreeNode)) { return null; } final Object userData = ((DefaultMutableTreeNode)treeNode).getUserObject(); return userData instanceof DiagnosticsNode ? (DiagnosticsNode)userData : null; } private static void expandAll(JTree tree, TreePath parent, boolean expandProperties) { final TreeNode node = (TreeNode)parent.getLastPathComponent(); if (node.getChildCount() >= 0) { for (final Enumeration<? extends TreeNode> e = node.children(); e.hasMoreElements(); ) { final DefaultMutableTreeNode n = (DefaultMutableTreeNode)e.nextElement(); if (n.getUserObject() instanceof DiagnosticsNode) { final DiagnosticsNode diagonsticsNode = (DiagnosticsNode)n.getUserObject(); if (!diagonsticsNode.childrenReady() || (diagonsticsNode.isProperty() && !expandProperties)) { continue; } } expandAll(tree, parent.pathByAddingChild(n), expandProperties); } } tree.expandPath(parent); } protected static SimpleTextAttributes textAttributesForLevel(DiagnosticLevel level) { switch (level) { case hidden: return SimpleTextAttributes.GRAYED_ATTRIBUTES; case fine: //noinspection DuplicateBranchesInSwitch return SimpleTextAttributes.REGULAR_ATTRIBUTES; case warning: return WARNING_ATTRIBUTES; case error: return SimpleTextAttributes.ERROR_ATTRIBUTES; case debug: case info: default: return SimpleTextAttributes.REGULAR_ATTRIBUTES; } } @Nullable public static Tree getTree(final DataContext e) { return e.getData(InspectorTree.INSPECTOR_KEY); } @NotNull public FlutterApp getFlutterApp() { return flutterApp; } public InspectorService.FlutterTreeType getTreeType() { return treeType; } public void setVisibleToUser(boolean visible) { if (visibleToUser == visible) { return; } visibleToUser = visible; if (subtreePanel != null) { subtreePanel.setVisibleToUser(visible); } if (visibleToUser) { if (parentTree == null) { maybeLoadUI(); } } else { shutdownTree(false); } } private void determineSplitterOrientation() { if (treeSplitter == null) { return; } final double aspectRatio = (double)getWidth() / (double)getHeight(); final boolean vertical = aspectRatio < 1.4; if (vertical != treeSplitter.getOrientation()) { treeSplitter.setOrientation(vertical); } } protected boolean hasDiagnosticsValue(InspectorInstanceRef ref) { return valueToTreeNode.containsKey(ref); } protected DiagnosticsNode findDiagnosticsValue(InspectorInstanceRef ref) { return getDiagnosticNode(valueToTreeNode.get(ref)); } protected void endShowNode() { highlightShowNode((DefaultMutableTreeNode)null); } protected boolean highlightShowNode(InspectorInstanceRef ref) { return highlightShowNode(valueToTreeNode.get(ref)); } protected boolean highlightShowNode(DefaultMutableTreeNode node) { if (node == null && parentTree != null) { // If nothing is highlighted, highlight the node selected in the parent // tree so user has context of where the node selected in the parent is // in the details tree. node = findMatchingTreeNode(parentTree.getSelectedDiagnostic()); } getTreeModel().nodeChanged(currentShowNode); getTreeModel().nodeChanged(node); currentShowNode = node; return true; } private DefaultMutableTreeNode findMatchingTreeNode(DiagnosticsNode node) { if (node == null) { return null; } return valueToTreeNode.get(node.getValueRef()); } private DefaultTreeModel getTreeModel() { return (DefaultTreeModel)myRootsTree.getModel(); } private CompletableFuture<?> getPendingUpdateDone() { // Wait for the selection to be resolved followed by waiting for the tree to be computed. final CompletableFuture<?> ret = new CompletableFuture<>(); AsyncUtils.whenCompleteUiThread(selectionGroups.getPendingUpdateDone(), (value, error) -> { treeGroups.getPendingUpdateDone().whenCompleteAsync((value2, error2) -> { ret.complete(null); }); }); return ret; } private CompletableFuture<?> refresh() { if (!visibleToUser) { // We will refresh again once we are visible. // There is a risk a refresh got triggered before the view was visble. return CompletableFuture.completedFuture(null); } // TODO(jacobr): refresh the tree as well as just the properties. if (myPropertiesPanel != null) { myPropertiesPanel.refresh(); } if (myPropertiesPanel != null) { return CompletableFuture.allOf(getPendingUpdateDone(), myPropertiesPanel.getPendingUpdateDone()); } else if (subtreePanel != null) { return CompletableFuture.allOf(getPendingUpdateDone(), subtreePanel.getPendingUpdateDone()); } else { return getPendingUpdateDone(); } } public void shutdownTree(boolean isolateStopped) { // It is critical we clear all data that is kept alive by inspector object // references in this method as that stale data will trigger inspector // exceptions. programaticSelectionChangeInProgress = true; treeGroups.clear(isolateStopped); selectionGroups.clear(isolateStopped); currentShowNode = null; selectedNode = null; lastExpanded = null; subtreeRoot = null; getTreeModel().setRoot(new DefaultMutableTreeNode()); if (subtreePanel != null) { subtreePanel.shutdownTree(isolateStopped); } if (myPropertiesPanel != null) { myPropertiesPanel.shutdownTree(isolateStopped); } programaticSelectionChangeInProgress = false; valueToTreeNode.clear(); } public void onIsolateStopped() { flutterAppFrameReady = false; treeLoadStarted = false; shutdownTree(true); } @Override public CompletableFuture<?> onForceRefresh() { if (!visibleToUser) { return CompletableFuture.completedFuture(null); } if (!legacyMode) { // We can't efficiently refresh the full tree in legacy mode. recomputeTreeRoot(null, null, false, true); } if (myPropertiesPanel != null) { myPropertiesPanel.refresh(); } return getPendingUpdateDone(); } public void onAppChanged() { setActivate(isApplicable.compute()); } @NotNull private InspectorService getInspectorService() { return inspectorService; } void setActivate(boolean enabled) { if (!enabled) { onIsolateStopped(); isActive = false; return; } if (isActive) { // Already activated. return; } isActive = true; getInspectorService().addClient(this); maybeLoadUI(); } void maybeLoadUI() { if (!visibleToUser || !isActive) { return; } if (flutterAppFrameReady) { updateSelectionFromService(false); } else { AsyncUtils.whenCompleteUiThread(inspectorService.isWidgetTreeReady(), (Boolean ready, Throwable throwable) -> { if (throwable != null) { return; } flutterAppFrameReady = ready; if (isActive && ready) { maybeLoadUI(); } }); } } private DefaultMutableTreeNode getRootNode() { return (DefaultMutableTreeNode)getTreeModel().getRoot(); } private void recomputeTreeRoot(DiagnosticsNode newSelection, DiagnosticsNode detailsSelection, boolean setSubtreeRoot, boolean textEditorUpdated) { treeGroups.cancelNext(); treeGroups.getNext().safeWhenComplete(detailsSubtree ? treeGroups.getNext().getDetailsSubtree(subtreeRoot) : treeGroups.getNext().getRoot(treeType), (final DiagnosticsNode n, Throwable error) -> { if (error != null) { FlutterUtils.warn(LOG, error); treeGroups.cancelNext(); return; } // TODO(jacobr): as a performance optimization we should check if the // new tree is identical to the existing tree in which case we should // dispose the new tree and keep the old tree. treeGroups.promoteNext(); clearValueToTreeNodeMapping(); if (n != null) { final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(n); getTreeModel().setRoot(rootNode); setupTreeNode(rootNode, n, true); // Legacy case. We got the root node but no children are loaded yet. // When the root node is hidden, we will never show anything unless we // load the children. if (n.hasChildren() && !n.childrenReady()) { maybeLoadChildren(rootNode); } } else { getTreeModel().setRoot(null); } refreshSelection(newSelection, detailsSelection, setSubtreeRoot, textEditorUpdated); }); } private void clearValueToTreeNodeMapping() { if (parentTree != null) { for (InspectorInstanceRef v : valueToTreeNode.keySet()) { parentTree.maybeUpdateValueUI(v); } } valueToTreeNode.clear(); } /** * Show the details subtree starting with node subtreeRoot highlighting * node subtreeSelection. */ public void showDetailSubtrees(DiagnosticsNode subtreeRoot, DiagnosticsNode subtreeSelection) { // TODO(jacobr): handle render objects subtree panel and other subtree panels here. assert (!legacyMode); this.subtreeRoot = subtreeRoot; myRootsTree.setHighlightedRoot(getSubtreeRootNode()); if (subtreePanel != null) { subtreePanel.setSubtreeRoot(subtreeRoot, subtreeSelection); } } public InspectorInstanceRef getSubtreeRootValue() { return subtreeRoot != null ? subtreeRoot.getValueRef() : null; } public void setSubtreeRoot(DiagnosticsNode node, DiagnosticsNode selection) { assert (detailsSubtree); if (selection == null) { selection = node; } if (node != null && node.equals(subtreeRoot)) { // Select the new node in the existing subtree. applyNewSelection(selection, null, false, true); return; } subtreeRoot = node; if (node == null) { // Passing in a null node indicates we should clear the subtree and free any memory allocated. shutdownTree(false); return; } // Clear now to eliminate frame of highlighted nodes flicker. clearValueToTreeNodeMapping(); recomputeTreeRoot(selection, null, false, true); } DefaultMutableTreeNode getSubtreeRootNode() { if (subtreeRoot == null) { return null; } return valueToTreeNode.get(subtreeRoot.getValueRef()); } private void refreshSelection(DiagnosticsNode newSelection, DiagnosticsNode detailsSelection, boolean setSubtreeRoot, boolean textEditorUpdated) { if (newSelection == null) { newSelection = getSelectedDiagnostic(); } setSelectedNode(findMatchingTreeNode(newSelection)); syncSelectionHelper(setSubtreeRoot, detailsSelection, textEditorUpdated); if (subtreePanel != null) { if ((subtreeRoot != null && getSubtreeRootNode() == null)) { subtreeRoot = newSelection; subtreePanel.setSubtreeRoot(newSelection, detailsSelection); } } if (!legacyMode) { myRootsTree.setHighlightedRoot(getSubtreeRootNode()); } syncTreeSelection(); } private void syncTreeSelection() { programaticSelectionChangeInProgress = true; final TreePath path = selectedNode != null ? new TreePath(selectedNode.getPath()) : null; myRootsTree.setSelectionPath(path); programaticSelectionChangeInProgress = false; myRootsTree.expandPath(path); animateTo(selectedNode); } private void selectAndShowNode(DiagnosticsNode node) { if (node == null) { return; } selectAndShowNode(node.getValueRef()); } private void selectAndShowNode(InspectorInstanceRef ref) { final DefaultMutableTreeNode node = valueToTreeNode.get(ref); if (node == null) { return; } setSelectedNode(node); syncTreeSelection(); } private TreePath getTreePath(DiagnosticsNode node) { if (node == null) { return null; } final DefaultMutableTreeNode treeNode = valueToTreeNode.get(node.getValueRef()); if (treeNode == null) { return null; } return new TreePath(treeNode.getPath()); } protected void maybeUpdateValueUI(InspectorInstanceRef valueRef) { final DefaultMutableTreeNode node = valueToTreeNode.get(valueRef); if (node == null) { // The value isn't shown in the parent tree. Nothing to do. return; } getTreeModel().nodeChanged(node); } void setupTreeNode(DefaultMutableTreeNode node, DiagnosticsNode diagnosticsNode, boolean expandChildren) { node.setUserObject(diagnosticsNode); node.setAllowsChildren(diagnosticsNode.hasChildren()); final InspectorInstanceRef valueRef = diagnosticsNode.getValueRef(); // Properties do not have unique values so should not go in the valueToTreeNode map. if (valueRef.getId() != null && !diagnosticsNode.isProperty()) { valueToTreeNode.put(valueRef, node); } if (parentTree != null) { parentTree.maybeUpdateValueUI(valueRef); } if (diagnosticsNode.hasChildren() || !diagnosticsNode.getInlineProperties().isEmpty()) { if (diagnosticsNode.childrenReady() || !diagnosticsNode.hasChildren()) { final CompletableFuture<ArrayList<DiagnosticsNode>> childrenFuture = diagnosticsNode.getChildren(); assert (childrenFuture.isDone()); setupChildren(diagnosticsNode, node, childrenFuture.getNow(null), expandChildren); } else { node.removeAllChildren(); node.add(new DefaultMutableTreeNode("Loading...")); } } } void setupChildren(DiagnosticsNode parent, DefaultMutableTreeNode treeNode, ArrayList<DiagnosticsNode> children, boolean expandChildren) { final DefaultTreeModel model = getTreeModel(); if (treeNode.getChildCount() > 0) { // Only case supported is this is the loading node. assert (treeNode.getChildCount() == 1); model.removeNodeFromParent((DefaultMutableTreeNode)treeNode.getFirstChild()); } final ArrayList<DiagnosticsNode> inlineProperties = parent.getInlineProperties(); treeNode.setAllowsChildren(!children.isEmpty() || !inlineProperties.isEmpty()); if (inlineProperties != null) { for (DiagnosticsNode property : inlineProperties) { final DefaultMutableTreeNode childTreeNode = new DefaultMutableTreeNode(); setupTreeNode(childTreeNode, property, false); childTreeNode.setAllowsChildren(childTreeNode.getChildCount() > 0); model.insertNodeInto(childTreeNode, treeNode, treeNode.getChildCount()); } } for (DiagnosticsNode child : children) { final DefaultMutableTreeNode childTreeNode = new DefaultMutableTreeNode(); setupTreeNode(childTreeNode, child, false); model.insertNodeInto(childTreeNode, treeNode, treeNode.getChildCount()); } if (expandChildren) { programaticExpansionInProgress = true; expandAll(myRootsTree, new TreePath(treeNode.getPath()), false); programaticExpansionInProgress = false; } } void maybeLoadChildren(DefaultMutableTreeNode node) { if (!(node.getUserObject() instanceof DiagnosticsNode)) { return; } final DiagnosticsNode diagnosticsNode = (DiagnosticsNode)node.getUserObject(); if (diagnosticsNode.hasChildren() || !diagnosticsNode.getInlineProperties().isEmpty()) { if (hasPlaceholderChildren(node)) { diagnosticsNode.safeWhenComplete(diagnosticsNode.getChildren(), (ArrayList<DiagnosticsNode> children, Throwable throwable) -> { if (throwable != null) { // TODO(jacobr): Display that children failed to load. return; } if (node.getUserObject() != diagnosticsNode) { // Node changed, this data is stale. return; } setupChildren(diagnosticsNode, node, children, true); if (node == selectedNode || node == lastExpanded) { animateTo(node); } }); } } } public void onFlutterFrame() { flutterAppFrameReady = true; if (!visibleToUser) { return; } if (!treeLoadStarted) { treeLoadStarted = true; // This was the first frame. maybeLoadUI(); } if (refreshRateLimiter != null) { refreshRateLimiter.scheduleRequest(); } } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean identicalDiagnosticsNodes(DiagnosticsNode a, DiagnosticsNode b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return a.getDartDiagnosticRef().equals(b.getDartDiagnosticRef()); } public void onInspectorSelectionChanged(boolean uiAlreadyUpdated, boolean textEditorUpdated) { if (uiAlreadyUpdated) return; if (!visibleToUser) { // Don't do anything. We will update the view once it is visible again. return; } if (detailsSubtree) { // Wait for the master to update. return; } updateSelectionFromService(textEditorUpdated); } public void updateSelectionFromService(boolean textEditorUpdated) { treeLoadStarted = true; selectionGroups.cancelNext(); final CompletableFuture<DiagnosticsNode> pendingSelectionFuture = selectionGroups.getNext().getSelection(getSelectedDiagnostic(), treeType, isSummaryTree); CompletableFuture<?> allPending; final CompletableFuture<DiagnosticsNode> pendingDetailsFuture = isSummaryTree ? selectionGroups.getNext().getSelection(getSelectedDiagnostic(), treeType, false) : null; final CompletableFuture<?> selectionsReady = isSummaryTree ? CompletableFuture.allOf(pendingDetailsFuture, pendingSelectionFuture) : pendingSelectionFuture; selectionGroups.getNext().safeWhenComplete(selectionsReady, (ignored, error) -> { if (error != null) { FlutterUtils.warn(LOG, error); selectionGroups.cancelNext(); return; } selectionGroups.promoteNext(); final DiagnosticsNode newSelection = pendingSelectionFuture.getNow(null); if (!legacyMode) { DiagnosticsNode detailsSelection = null; if (pendingDetailsFuture != null) { detailsSelection = pendingDetailsFuture.getNow(null); } subtreeRoot = newSelection; applyNewSelection(newSelection, detailsSelection, true, textEditorUpdated); } else { // Legacy case. TODO(jacobr): deprecate and remove this code. // This case only exists for the RenderObject tree which we haven't updated yet to use the new UI style. // TODO(jacobr): delete it. if (newSelection == null) { recomputeTreeRoot(null, null, false, true); return; } // TODO(jacobr): switch to using current and next groups in this case // as well to avoid memory leaks. treeGroups.getCurrent() .safeWhenComplete(treeGroups.getCurrent().getParentChain(newSelection), (ArrayList<DiagnosticsPathNode> path, Throwable ex) -> { if (ex != null) { FlutterUtils.warn(LOG, ex); return; } DefaultMutableTreeNode treeNode = getRootNode(); final DefaultTreeModel model = getTreeModel(); final DefaultMutableTreeNode[] treePath = new DefaultMutableTreeNode[path.size()]; for (int i = 0; i < path.size(); ++i) { treePath[i] = treeNode; final DiagnosticsPathNode pathNode = path.get(i); final DiagnosticsNode pathDiagnosticNode = pathNode.getNode(); final ArrayList<DiagnosticsNode> newChildren = pathNode.getChildren(); final DiagnosticsNode existingNode = getDiagnosticNode(treeNode); if (!identicalDiagnosticsNodes(pathDiagnosticNode, existingNode)) { treeNode.setUserObject(pathDiagnosticNode); } treeNode.setAllowsChildren(!newChildren.isEmpty()); for (int j = 0; j < newChildren.size(); ++j) { final DiagnosticsNode newChild = newChildren.get(j); if (j >= treeNode.getChildCount() || !identicalDiagnosticsNodes(newChild, getDiagnosticNode(treeNode.getChildAt(j)))) { final DefaultMutableTreeNode child; if (j >= treeNode.getChildCount()) { child = new DefaultMutableTreeNode(); treeNode.add(child); } else { child = (DefaultMutableTreeNode)treeNode.getChildAt(j); } if (j != pathNode.getChildIndex()) { setupTreeNode(child, newChild, false); model.reload(child); } else { child.setUserObject(newChild); child.setAllowsChildren(newChild.hasChildren()); child.removeAllChildren(); } // TODO(jacobr): we are likely calling the wrong node structure changed APIs. // For example, we should be getting these change notifications for free if we // switched to call methods on the model object directly to manipulate the tree. model.nodeStructureChanged(child); model.nodeChanged(child); } model.reload(treeNode); } if (i != path.size() - 1) { treeNode = (DefaultMutableTreeNode)treeNode.getChildAt(pathNode.getChildIndex()); } } // TODO(jacobr): review and simplify this. final TreePath selectionPath = new TreePath(treePath); myRootsTree.setSelectionPath(selectionPath); animateTo(treePath[treePath.length - 1]); }); } }); } protected void applyNewSelection(DiagnosticsNode newSelection, DiagnosticsNode detailsSelection, boolean setSubtreeRoot, boolean textEditorUpdated) { final DefaultMutableTreeNode nodeInTree = findMatchingTreeNode(newSelection); if (nodeInTree == null) { // The tree has probably changed since we last updated. Do a full refresh // so that the tree includes the new node we care about. recomputeTreeRoot(newSelection, detailsSelection, setSubtreeRoot, textEditorUpdated); } refreshSelection(newSelection, detailsSelection, setSubtreeRoot, textEditorUpdated); } private DiagnosticsNode getSelectedDiagnostic() { return getDiagnosticNode(selectedNode); } private void animateTo(DefaultMutableTreeNode node) { if (node == null) { return; } final List<TreePath> targets = new ArrayList<>(); final TreePath target = new TreePath(node.getPath()); targets.add(target); // Backtrack to the the first non-property parent so that all properties // for the node are visible if one property is animated to. This is helpful // as typically users want to view the properties of a node as a chunk. for (int i = target.getPathCount() - 1; i >= 0; i--) { node = (DefaultMutableTreeNode)target.getPathComponent(i); final Object userObject = node.getUserObject(); if (userObject instanceof DiagnosticsNode && !((DiagnosticsNode)userObject).isProperty()) { break; } } // Make sure we scroll so that immediate un-expanded children // are also in view. There is no risk in including these children as // the amount of space they take up is bounded. This also ensures that if // a node is selected, its properties will also be selected as by // convention properties are the first children of a node and properties // typically do not have children and are never expanded by default. for (int i = 0; i < node.getChildCount(); ++i) { final DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i); final DiagnosticsNode diagnosticsNode = TreeUtils.maybeGetDiagnostic(child); final TreePath childPath = new TreePath(child.getPath()); targets.add(childPath); if (!child.isLeaf() && myRootsTree.isExpanded(childPath)) { // Stop if we get to expanded children as they might be too large // to try to scroll into view. break; } if (diagnosticsNode != null && !diagnosticsNode.isProperty()) { break; } } scrollAnimator.animateTo(targets); } private void maybePopulateChildren(DefaultMutableTreeNode treeNode) { final Object userObject = treeNode.getUserObject(); if (userObject instanceof DiagnosticsNode) { final DiagnosticsNode diagnostic = (DiagnosticsNode)userObject; if (diagnostic.hasChildren() && treeNode.getChildCount() == 0) { diagnostic.safeWhenComplete(diagnostic.getChildren(), (ArrayList<DiagnosticsNode> children, Throwable throwable) -> { if (throwable != null) { FlutterUtils.warn(LOG, throwable); return; } if (treeNode.getChildCount() == 0) { setupChildren(diagnostic, treeNode, children, true); } getTreeModel().nodeStructureChanged(treeNode); if (treeNode == selectedNode) { myRootsTree.expandPath(new TreePath(treeNode.getPath())); } }); } } } private void setSelectedNode(DefaultMutableTreeNode newSelection) { if (newSelection == selectedNode) { return; } if (selectedNode != null) { if (!detailsSubtree) { getTreeModel().nodeChanged(selectedNode.getParent()); } } selectedNode = newSelection; animateTo(selectedNode); lastExpanded = null; // New selected node takes prescidence. endShowNode(); if (subtreePanel != null) { subtreePanel.endShowNode(); } else if (parentTree != null) { parentTree.endShowNode(); } } private void selectionChanged(TreeSelectionEvent event) { if (!visibleToUser) { return; } final DefaultMutableTreeNode[] selectedNodes = myRootsTree.getSelectedNodes(DefaultMutableTreeNode.class, null); for (DefaultMutableTreeNode node : selectedNodes) { maybePopulateChildren(node); } if (programaticSelectionChangeInProgress) { return; } if (selectedNodes.length > 0) { assert (selectedNodes.length == 1); setSelectedNode(selectedNodes[0]); final DiagnosticsNode selectedDiagnostic = getSelectedDiagnostic(); // Don't reroot if the selected value is already visible in the details tree. final boolean maybeReroot = isSummaryTree && subtreePanel != null && selectedDiagnostic != null && !subtreePanel.hasDiagnosticsValue(selectedDiagnostic.getValueRef()); syncSelectionHelper(maybeReroot, null, false); if (!maybeReroot) { if (isSummaryTree && subtreePanel != null) { subtreePanel.selectAndShowNode(selectedDiagnostic); } else if (parentTree != null) { parentTree.selectAndShowNode(firstAncestorInParentTree(selectedNode)); } } } } DiagnosticsNode firstAncestorInParentTree(DefaultMutableTreeNode node) { if (parentTree == null) { return getDiagnosticNode(node); } while (node != null) { final DiagnosticsNode diagnostic = getDiagnosticNode(node); if (diagnostic != null && parentTree.hasDiagnosticsValue(diagnostic.getValueRef())) { return parentTree.findDiagnosticsValue(diagnostic.getValueRef()); } node = (DefaultMutableTreeNode)node.getParent(); } return null; } private void syncSelectionHelper(boolean maybeRerootSubtree, DiagnosticsNode detailsSelection, boolean textEditorUpdated) { if (!detailsSubtree && selectedNode != null) { getTreeModel().nodeChanged(selectedNode.getParent()); } final DiagnosticsNode diagnostic = getSelectedDiagnostic(); if (myPropertiesPanel != null) { myPropertiesPanel.showProperties(diagnostic); } if (detailsSubtree || subtreePanel == null) { if (diagnostic != null) { DiagnosticsNode toSelect = diagnostic; if (diagnostic.isProperty()) { // Set the selection to the parent of the property not the property as what we // should display on device is the selected widget not the selected property // of the widget. final TreePath path = new TreePath(selectedNode.getPath()); // TODO(jacobr): even though it isn't currently an issue, we should // search for the first non-diagnostic node parent instead of just // assuming the first parent is a regular node. toSelect = getDiagnosticNode((DefaultMutableTreeNode)path.getPathComponent(path.getPathCount() - 2)); } toSelect.setSelection(toSelect.getValueRef(), true); } } if (maybeRerootSubtree) { showDetailSubtrees(diagnostic, detailsSelection); } else if (diagnostic != null) { // We can't rely on the details tree to update the selection on the server in this case. final DiagnosticsNode selection = detailsSelection != null ? detailsSelection : diagnostic; selection.setSelection(selection.getValueRef(), true); } } private void initTree(final Tree tree) { tree.setCellRenderer(new DiagnosticsTreeCellRenderer(this)); tree.setShowsRootHandles(true); TreeUtil.installActions(tree); PopupHandler.installUnknownPopupHandler(tree, createTreePopupActions(), ActionManager.getInstance()); new TreeSpeedSearch(tree) { @Override protected String getElementText(Object element) { final TreePath path = (TreePath)element; final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); final Object object = node.getUserObject(); if (object instanceof DiagnosticsNode) { // TODO(pq): consider a specialized String for matching. return object.toString(); } return null; } }; } private ActionGroup createTreePopupActions() { final DefaultActionGroup group = new DefaultActionGroup(); final ActionManager actionManager = ActionManager.getInstance(); group.add(actionManager.getAction(InspectorActions.JUMP_TO_SOURCE)); group.add(actionManager.getAction(InspectorActions.JUMP_TO_TYPE_SOURCE)); return group; } @Override public void dispose() { flutterIsolateSubscription.dispose(); // TODO(jacobr): actually implement. final InspectorService service = getInspectorService(); shutdownTree(false); // TODO(jacobr): verify subpanels are disposed as well. } boolean isCreatedByLocalProject(DiagnosticsNode node) { return node.isCreatedByLocalProject(); } boolean hasPlaceholderChildren(DefaultMutableTreeNode node) { return node.getChildCount() == 0 || (node.getChildCount() == 1 && ((DefaultMutableTreeNode)node.getFirstChild()).getUserObject() instanceof String); } static class PropertyNameColumnInfo extends ColumnInfo<DefaultMutableTreeNode, DiagnosticsNode> { private final TableCellRenderer renderer = new PropertyNameRenderer(); public PropertyNameColumnInfo(String name) { super(name); } @Nullable @Override public DiagnosticsNode valueOf(DefaultMutableTreeNode node) { return (DiagnosticsNode)node.getUserObject(); } @Override public TableCellRenderer getRenderer(DefaultMutableTreeNode item) { return renderer; } } static class PropertyValueColumnInfo extends ColumnInfo<DefaultMutableTreeNode, DiagnosticsNode> { private final TableCellRenderer defaultRenderer; public PropertyValueColumnInfo(String name) { super(name); defaultRenderer = new SimplePropertyValueRenderer(); } @Nullable @Override public DiagnosticsNode valueOf(DefaultMutableTreeNode node) { return (DiagnosticsNode)node.getUserObject(); } @Override public TableCellRenderer getRenderer(DefaultMutableTreeNode item) { return defaultRenderer; } } private static class PropertyNameRenderer extends ColoredTableCellRenderer { @Override protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean hasFocus, int row, int column) { if (value == null) return; final DiagnosticsNode node = (DiagnosticsNode)value; // If we should not show a separator then we should show the property name // as part of the property value instead of in its own column. if (!node.getShowSeparator() || !node.getShowName()) { return; } // Present user defined properties in BOLD. final SimpleTextAttributes attributes = node.hasCreationLocation() ? SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES; append(node.getName(), attributes); // Set property description in tooltip. // TODO (pq): // * consider tooltips for values // * consider rich navigation hovers (w/ styling and navigable docs) final CompletableFuture<String> propertyDoc = node.getPropertyDoc(); final String doc = propertyDoc.getNow(null); if (doc != null) { setToolTipText(doc); } else { // Make sure we see nothing stale while we wait. setToolTipText(null); node.safeWhenComplete(propertyDoc, (String tooltip, Throwable th) -> { // TODO(jacobr): make sure we still care about seeing this tooltip. if (th != null) { FlutterUtils.warn(LOG, th); } setToolTipText(tooltip); }); } } } /** * Property value renderer that handles common cases where colored text * is sufficient to describe the property value. */ private static class SimplePropertyValueRenderer extends ColoredTableCellRenderer { final ColorIconMaker colorIconMaker = new ColorIconMaker(); private static int getIntProperty(Map<String, InstanceRef> properties, String propertyName) { if (properties == null || !properties.containsKey(propertyName)) { return 0; } return Integer.parseInt(properties.get(propertyName).getValueAsString()); } @Override protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean hasFocus, int row, int column) { setToolTipText(null); if (value == null) return; final DiagnosticsNode node = (DiagnosticsNode)value; final SimpleTextAttributes textAttributes = textAttributesForLevel(node.getLevel()); boolean appendDescription = true; if (node.getTooltip() != null) { setToolTipText(node.getTooltip()); } // TODO(jacobr): also provide custom UI display for padding, transform, // and alignment properties. final CompletableFuture<Map<String, InstanceRef>> propertiesFuture = node.getValueProperties(); if (propertiesFuture != null && propertiesFuture.isDone() && !propertiesFuture.isCompletedExceptionally()) { final Map<String, InstanceRef> properties = propertiesFuture.getNow(null); if (node.isEnumProperty() && properties != null) { // We can display a better tooltip as we have access to introspection // via the observatory service. setToolTipText("Allowed values:\n" + Joiner.on('\n').join(properties.keySet())); } final String propertyType = node.getPropertyType(); if (propertyType != null) { switch (propertyType) { case "Color": { final int alpha = getIntProperty(properties, "alpha"); final int red = getIntProperty(properties, "red"); final int green = getIntProperty(properties, "green"); final int blue = getIntProperty(properties, "blue"); //noinspection UseJBColor final Color color = new Color(red, green, blue, alpha); this.setIcon(colorIconMaker.getCustomIcon(color)); if (alpha == 255) { append(String.format("#%02x%02x%02x", red, green, blue), textAttributes); } else { append(String.format("#%02x%02x%02x%02x", alpha, red, green, blue), textAttributes); } appendDescription = false; break; } case "IconData": { // IconData(U+0E88F) final int codePoint = getIntProperty(properties, "codePoint"); if (codePoint > 0) { final Icon icon = FlutterMaterialIcons.getIconForHex(String.format("%1$04x", codePoint)); if (icon != null) { this.setIcon(icon); this.setIconOpaque(false); this.setTransparentIconBackground(true); } } break; } } } } if (appendDescription) { append(node.getDescription(), textAttributes); } } } private static class PropertiesPanel extends TreeTableView implements DataProvider { private final InspectorObjectGroupManager groups; private final FlutterApp flutterApp; /** * Diagnostic we are displaying properties for. */ private DiagnosticsNode diagnostic; /** * Current properties being displayed. */ private ArrayList<DiagnosticsNode> currentProperties; PropertiesPanel(FlutterApp flutterApp, InspectorService inspectorService) { super(new ListTreeTableModelOnColumns( new DefaultMutableTreeNode(), new ColumnInfo[]{ new PropertyNameColumnInfo("Property"), new PropertyValueColumnInfo("Value") } )); this.flutterApp = flutterApp; this.groups = new InspectorObjectGroupManager(inspectorService, "panel"); setRootVisible(false); setStriped(true); setRowHeight(getRowHeight() + JBUI.scale(4)); final JTableHeader tableHeader = getTableHeader(); tableHeader.setPreferredSize(new Dimension(0, getRowHeight())); getColumnModel().getColumn(0).setPreferredWidth(120); getColumnModel().getColumn(1).setPreferredWidth(200); } private ActionGroup createTreePopupActions() { final DefaultActionGroup group = new DefaultActionGroup(); final ActionManager actionManager = ActionManager.getInstance(); group.add(actionManager.getAction(InspectorActions.JUMP_TO_SOURCE)); // TODO(pq): implement //group.add(new JumpToPropertyDeclarationAction()); return group; } ListTreeTableModelOnColumns getTreeModel() { return (ListTreeTableModelOnColumns)getTableModel(); } public void showProperties(DiagnosticsNode diagnostic) { this.diagnostic = diagnostic; if (diagnostic == null || diagnostic.isDisposed()) { shutdownTree(false); return; } getEmptyText().setText(FlutterBundle.message("app.inspector.loading_properties")); groups.cancelNext(); groups.getNext() .safeWhenComplete(diagnostic.getProperties(groups.getNext()), (ArrayList<DiagnosticsNode> properties, Throwable throwable) -> { if (throwable != null) { getTreeModel().setRoot(new DefaultMutableTreeNode()); getEmptyText().setText(FlutterBundle.message("app.inspector.error_loading_properties")); FlutterUtils.warn(LOG, throwable); groups.cancelNext(); return; } showPropertiesHelper(properties); PopupHandler.installUnknownPopupHandler(this, createTreePopupActions(), ActionManager.getInstance()); }); } private void showPropertiesHelper(ArrayList<DiagnosticsNode> properties) { currentProperties = properties; if (properties.isEmpty()) { getTreeModel().setRoot(new DefaultMutableTreeNode()); getEmptyText().setText(FlutterBundle.message("app.inspector.no_properties")); groups.promoteNext(); return; } groups.getNext().safeWhenComplete(loadPropertyMetadata(properties), (Void ignored, Throwable errorGettingInstances) -> { if (errorGettingInstances != null) { // TODO(jacobr): show error message explaining properties could not be loaded. getTreeModel().setRoot(new DefaultMutableTreeNode()); FlutterUtils.warn(LOG, errorGettingInstances); getEmptyText().setText(FlutterBundle.message("app.inspector.error_loading_property_details")); groups.cancelNext(); return; } groups.promoteNext(); setModelFromProperties(properties); }); } private void setModelFromProperties(ArrayList<DiagnosticsNode> properties) { final ListTreeTableModelOnColumns model = getTreeModel(); final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); for (DiagnosticsNode property : properties) { if (property.getLevel() != DiagnosticLevel.hidden) { root.add(new DefaultMutableTreeNode(property)); } } getEmptyText().setText(FlutterBundle.message("app.inspector.all_properties_hidden")); model.setRoot(root); } private CompletableFuture<Void> loadPropertyMetadata(ArrayList<DiagnosticsNode> properties) { // Preload all information we need about each property before instantiating // the UI so that the property display UI does not have to deal with values // that are not yet available. As the number of properties is small this is // a reasonable tradeoff. final CompletableFuture[] futures = new CompletableFuture[properties.size()]; int i = 0; for (DiagnosticsNode property : properties) { futures[i] = property.getValueProperties(); ++i; } return CompletableFuture.allOf(futures); } private void refresh() { if (diagnostic == null) { return; } // We don't know whether we will switch to the new group or keep the current group // until we have tested whether the properties are identical. groups.cancelNext(); // Cancel any existing pending next state. if (diagnostic.isDisposed()) { // We are getting properties for a stale object. Wait until the next frame when we will have new properties. return; } groups.getNext() .safeWhenComplete(diagnostic.getProperties(groups.getNext()), (ArrayList<DiagnosticsNode> properties, Throwable throwable) -> { if (throwable != null || propertiesIdentical(properties, currentProperties)) { // Dispose the new group as it wasn't used. groups.cancelNext(); return; } showPropertiesHelper(properties); }); } private boolean propertiesIdentical(ArrayList<DiagnosticsNode> a, ArrayList<DiagnosticsNode> b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.size() != b.size()) { return false; } for (int i = 0; i < a.size(); ++i) { if (!a.get(i).identicalDisplay(b.get(i))) { return false; } } return true; } @Nullable @Override public Object getData(@NotNull String dataId) { return InspectorTree.INSPECTOR_KEY.is(dataId) ? getTree() : null; } public void shutdownTree(boolean isolateStopped) { diagnostic = null; getEmptyText().setText(FlutterBundle.message("app.inspector.nothing_to_show")); getTreeModel().setRoot(new DefaultMutableTreeNode()); groups.clear(isolateStopped); } public CompletableFuture<?> getPendingUpdateDone() { return groups.getPendingUpdateDone(); } } private class MyTreeExpansionListener implements TreeExpansionListener { @Override public void treeExpanded(TreeExpansionEvent event) { final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)event.getPath().getLastPathComponent(); maybeLoadChildren(treeNode); if (!programaticExpansionInProgress) { lastExpanded = treeNode; animateTo(treeNode); } } @Override public void treeCollapsed(TreeExpansionEvent event) { } } }
flutter-intellij/flutter-idea/src/io/flutter/view/InspectorPanel.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/InspectorPanel.java", "repo_id": "flutter-intellij", "token_count": 21390 }
484
/* * 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. */ package io.flutter.vmService; import com.google.gson.JsonObject; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.EventDispatcher; import io.flutter.utils.VmServiceListenerAdapter; import org.dartlang.vm.service.VmService; import org.dartlang.vm.service.element.Event; import org.dartlang.vm.service.element.ExtensionData; import org.jetbrains.annotations.NotNull; import java.util.EventListener; import java.util.LinkedList; import java.util.List; public class FlutterFramesMonitor { static final int maxFrames = 200; private final DisplayRefreshRateManager displayRefreshRateManager; private final EventDispatcher<Listener> eventDispatcher = EventDispatcher.create(Listener.class); private long lastEventFinished = 0; public interface Listener extends EventListener { void handleFrameEvent(FlutterFrameEvent event); } public class FlutterFrameEvent { public final int frameId; public final long startTimeMicros; public final long elapsedMicros; public final boolean frameSetStart; FlutterFrameEvent(ExtensionData data, long lastEventFinished) { final JsonObject json = data.getJson(); frameId = json.get("number").getAsInt(); startTimeMicros = json.get("startTime").getAsLong(); elapsedMicros = json.get("elapsed").getAsLong(); frameSetStart = (startTimeMicros - lastEventFinished) > (displayRefreshRateManager.getTargetMicrosPerFrame() * 2); } public long getFrameFinishedMicros() { return startTimeMicros + elapsedMicros; } public boolean isSlowFrame() { return elapsedMicros > displayRefreshRateManager.getTargetMicrosPerFrame(); } public int hashCode() { return frameId; } public boolean equals(Object other) { return other instanceof FlutterFrameEvent && ((FlutterFrameEvent)other).frameId == frameId; } public String toString() { return "#" + frameId + " " + elapsedMicros + "µs"; } } public List<FlutterFrameEvent> frames = new LinkedList<>(); public FlutterFramesMonitor(@NotNull DisplayRefreshRateManager displayRefreshRateManager, @NotNull VmService vmService) { this.displayRefreshRateManager = displayRefreshRateManager; vmService.addVmServiceListener(new VmServiceListenerAdapter() { @Override public void received(String streamId, Event event) { onVmServiceReceived(streamId, event); } @Override public void connectionClosed() { } }); } private void onVmServiceReceived(String streamId, Event event) { if (StringUtil.equals(streamId, VmService.EXTENSION_STREAM_ID)) { if (StringUtil.equals("Flutter.Frame", event.getExtensionKind())) { handleFlutterFrame(event); } } } public boolean hasFps() { return !frames.isEmpty(); } /** * Return the most recent FPS value. */ public double getFPS() { int frameCount = 0; long costCount = 0; synchronized (this) { for (FlutterFrameEvent frame : frames) { frameCount++; final int targetMicrosPerFrame = displayRefreshRateManager.getTargetMicrosPerFrame(); long thisCost = frame.elapsedMicros / targetMicrosPerFrame; if (frame.elapsedMicros > (thisCost * targetMicrosPerFrame)) { thisCost++; } costCount += thisCost; if (frame.frameSetStart) { break; } } } if (costCount == 0) { return 0.0; } final double targetDisplayRefreshRate = displayRefreshRateManager.getCurrentDisplayRefreshRateRaw(); return frameCount * targetDisplayRefreshRate / costCount; } public void addListener(Listener listener) { eventDispatcher.addListener(listener); } public void removeListener(Listener listener) { eventDispatcher.removeListener(listener); } private void handleFlutterFrame(Event event) { final FlutterFrameEvent frameEvent = new FlutterFrameEvent(event.getExtensionData(), lastEventFinished); lastEventFinished = frameEvent.getFrameFinishedMicros(); synchronized (this) { frames.add(0, frameEvent); if (frames.size() > maxFrames) { frames.remove(frames.size() - 1); } } eventDispatcher.getMulticaster().handleFrameEvent(frameEvent); } }
flutter-intellij/flutter-idea/src/io/flutter/vmService/FlutterFramesMonitor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/FlutterFramesMonitor.java", "repo_id": "flutter-intellij", "token_count": 1551 }
485
package io.flutter.vmService.frame; import com.intellij.xdebugger.frame.XExecutionStack; import com.intellij.xdebugger.frame.XSuspendContext; import io.flutter.vmService.DartVmServiceDebugProcess; import io.flutter.vmService.IsolatesInfo; import org.dartlang.vm.service.element.Frame; import org.dartlang.vm.service.element.InstanceRef; import org.dartlang.vm.service.element.IsolateRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class DartVmServiceSuspendContext extends XSuspendContext { @NotNull private final DartVmServiceDebugProcess myDebugProcess; @NotNull private final DartVmServiceExecutionStack myActiveExecutionStack; private List<XExecutionStack> myExecutionStacks; private final boolean myAtAsyncSuspension; public DartVmServiceSuspendContext(@NotNull final DartVmServiceDebugProcess debugProcess, @NotNull final IsolateRef isolateRef, @NotNull final Frame topFrame, @Nullable final InstanceRef exception, boolean atAsyncSuspension) { myDebugProcess = debugProcess; myActiveExecutionStack = new DartVmServiceExecutionStack(debugProcess, isolateRef.getId(), isolateRef.getName(), topFrame, exception); myAtAsyncSuspension = atAsyncSuspension; } @NotNull @Override public XExecutionStack getActiveExecutionStack() { return myActiveExecutionStack; } public boolean getAtAsyncSuspension() { return myAtAsyncSuspension; } @Override public void computeExecutionStacks(@NotNull final XExecutionStackContainer container) { if (myExecutionStacks == null) { final Collection<IsolatesInfo.IsolateInfo> isolateInfos = myDebugProcess.getIsolateInfos(); myExecutionStacks = new ArrayList<>(isolateInfos.size()); for (IsolatesInfo.IsolateInfo isolateInfo : isolateInfos) { if (isolateInfo.getIsolateId().equals(myActiveExecutionStack.getIsolateId())) { myExecutionStacks.add(myActiveExecutionStack); } else { myExecutionStacks .add(new DartVmServiceExecutionStack(myDebugProcess, isolateInfo.getIsolateId(), isolateInfo.getIsolateName(), null, null)); } } } container.addExecutionStack(myExecutionStacks, true); } }
flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceSuspendContext.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceSuspendContext.java", "repo_id": "flutter-intellij", "token_count": 923 }
486
The sdk.tar file is an archive of a previous directory named `sdk`. It apparently was not used. I causes a lot of compilation errors. If no problems arise from removing it then this file and sdk.tar can be removed.
flutter-intellij/flutter-idea/testData/README-sdk.md/0
{ "file_path": "flutter-intellij/flutter-idea/testData/README-sdk.md", "repo_id": "flutter-intellij", "token_count": 56 }
487
/* * 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. */ package io.flutter.utils.math; import org.junit.Test; import java.util.ArrayList; import static io.flutter.utils.math.TestUtils.*; import static org.junit.Assert.*; /** * This code is ported from the Dart vector_math package. */ @SuppressWarnings("ConstantConditions") public class Matrix4Test { @Test public void testMatrix4InstacingFromFloat32List() { final double[] float32List = new double[]{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0 }; final Matrix4 input = new Matrix4(float32List); final Matrix4 inputB = new Matrix4(float32List); assertEquals(input, inputB); assertEquals(input.getStorage()[0], 1.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[1], 2.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[2], 3.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[3], 4.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[4], 5.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[5], 6.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[6], 7.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[7], 8.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[8], 9.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[9], 10.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[10], 11.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[11], 12.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[12], 13.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[13], 14.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[14], 15.0, TestUtils.errorThreshold); assertEquals(input.getStorage()[15], 16.0, TestUtils.errorThreshold); } @Test public void testMatrix4Transpose() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Matrix4> expectedOutput = new ArrayList<>(); inputA.add(parseMatrix4( "0.337719409821377 0.780252068321138 0.096454525168389 0.575208595078466\n" + "0.900053846417662 0.389738836961253 0.131973292606335 0.059779542947156\n" + "0.369246781120215 0.241691285913833 0.942050590775485 0.234779913372406\n" + "0.111202755293787 0.403912145588115 0.956134540229802 0.353158571222071")); expectedOutput.add(inputA.get(0).transposed()); for (int i = 0; i < inputA.size(); i++) { inputA.get(i).transpose(); relativeTest(inputA.get(i), expectedOutput.get(i)); } } @Test public void testMatrix4VectorMultiplication() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Vector4> inputB = new ArrayList<>(); final ArrayList<Vector4> expectedOutput = new ArrayList<>(); inputA.add(parseMatrix4( "0.337719409821377 0.780252068321138 0.096454525168389 0.575208595078466\n" + "0.900053846417662 0.389738836961253 0.131973292606335 0.059779542947156\n" + "0.369246781120215 0.241691285913833 0.942050590775485 0.234779913372406\n" + "0.111202755293787 0.403912145588115 0.956134540229802 0.353158571222071")); inputB.add(new Vector4(0.821194040197959, 0.015403437651555, 0.043023801657808, 0.168990029462704)); expectedOutput.add(new Vector4(0.390706088480722, 0.760902311900085, 0.387152194918898, 0.198357495624973)); assert (inputA.size() == inputB.size()); assert (expectedOutput.size() == inputB.size()); for (int i = 0; i < inputA.size(); i++) { final Vector4 output = inputA.get(i).operatorMultiply(inputB.get(i)); relativeTest(output, expectedOutput.get(i)); } } @Test public void testMatrix4Multiplication() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Matrix4> inputB = new ArrayList<>(); final ArrayList<Matrix4> expectedOutput = new ArrayList<>(); inputA.add(parseMatrix4( "0.587044704531417 0.230488160211558 0.170708047147859 0.923379642103244\n" + "0.207742292733028 0.844308792695389 0.227664297816554 0.430207391329584\n" + "0.301246330279491 0.194764289567049 0.435698684103899 0.184816320124136\n" + "0.470923348517591 0.225921780972399 0.311102286650413 0.904880968679893")); inputB.add(parseMatrix4( "0.979748378356085 0.408719846112552 0.711215780433683 0.318778301925882\n" + "0.438869973126103 0.594896074008614 0.221746734017240 0.424166759713807\n" + "0.111119223440599 0.262211747780845 0.117417650855806 0.507858284661118\n" + "0.258064695912067 0.602843089382083 0.296675873218327 0.085515797090044")); expectedOutput.add(parseMatrix4( "0.933571062150012 0.978468014433530 0.762614053950618 0.450561572247979\n" + "0.710396171182635 0.906228190244263 0.489336274658484 0.576762187862375\n" + "0.476730868989407 0.464650419830879 0.363428748133464 0.415721232510293\n" + "0.828623949506267 0.953951612073692 0.690010785130483 0.481326146122225")); assert (inputA.size() == inputB.size()); assert (expectedOutput.size() == inputB.size()); for (int i = 0; i < inputA.size(); i++) { final Matrix4 output = inputA.get(i).operatorMultiply(inputB.get(i)); //print('${inputA[i].cols}x${inputA[i].rows} * ${inputB[i].cols}x${inputB[i].rows} = ${output.cols}x${output.rows}'); relativeTest(output, expectedOutput.get(i)); } } @Test public void testMatrix4Adjoint() { final ArrayList<Matrix4> input = new ArrayList<>(); final ArrayList<Matrix4> expectedOutput = new ArrayList<>(); input.add(parseMatrix4( "0.934010684229183 0.011902069501241 0.311215042044805 0.262971284540144\n" + "0.129906208473730 0.337122644398882 0.528533135506213 0.654079098476782\n" + "0.568823660872193 0.162182308193243 0.165648729499781 0.689214503140008\n" + "0.469390641058206 0.794284540683907 0.601981941401637 0.748151592823709")); expectedOutput.add(parseMatrix4( "0.104914550911225 -0.120218628213523 0.026180662741638 0.044107217835411\n" + "-0.081375770192194 -0.233925009984709 -0.022194776259965 0.253560794325371\n" + "0.155967414263983 0.300399085119975 -0.261648453454468 -0.076412061081351\n" + "-0.104925204524921 0.082065846290507 0.217666653572481 -0.077704028180558")); input.add(parseMatrix4("1 0 0 0\n" + "0 1 0 0\n" + "0 0 1 0\n" + "0 0 0 1")); expectedOutput.add(parseMatrix4("1 0 0 0\n" + "0 1 0 0\n" + "0 0 1 0\n" + "0 0 0 1")); input.add(parseMatrix4( "0.450541598502498 0.152378018969223 0.078175528753184 0.004634224134067\n" + "0.083821377996933 0.825816977489547 0.442678269775446 0.774910464711502\n" + "0.228976968716819 0.538342435260057 0.106652770180584 0.817303220653433\n" + "0.913337361501670 0.996134716626885 0.961898080855054 0.868694705363510")); expectedOutput.add(parseMatrix4( "-0.100386867815513 0.076681891597503 -0.049082198794982 -0.021689260610181\n" + "-0.279454715225440 -0.269081505356250 0.114433412778961 0.133858687769130\n" + "0.218879650360982 0.073892735462981 0.069073300555062 -0.132069899391626\n" + "0.183633794399577 0.146113141160308 -0.156100829983306 -0.064859465665816")); assert (input.size() == expectedOutput.size()); for (int i = 0; i < input.size(); i++) { final Matrix4 output = input.get(i).clone(); output.scaleAdjoint(1.0); relativeTest(output, expectedOutput.get(i)); } } @Test public void testMatrix4Determinant() { final ArrayList<Matrix4> input = new ArrayList<>(); final ArrayList<Double> expectedOutput = new ArrayList<>(); input.add(parseMatrix4( "0.046171390631154 0.317099480060861 0.381558457093008 0.489764395788231\n" + "0.097131781235848 0.950222048838355 0.765516788149002 0.445586200710899\n" + "0.823457828327293 0.034446080502909 0.795199901137063 0.646313010111265\n" + "0.694828622975817 0.438744359656398 0.186872604554379 0.709364830858073")); expectedOutput.add(-0.199908980087990); input.add(parseMatrix4( " -2.336158020850647 0.358791716162913 0.571930324052307 0.866477090273158\n" + "-1.190335868711951 1.132044609886021 -0.693048859451418 0.742195189800671\n" + "0.015919048685702 0.552417702663606 1.020805610524362 -1.288062497216858\n" + "3.020318574990609 -1.197139524685751 -0.400475005629390 0.441263145991252")); expectedOutput.add(-5.002276533849802); input.add(parseMatrix4( "0.934010684229183 0.011902069501241 0.311215042044805 0.262971284540144\n" + "0.129906208473730 0.337122644398882 0.528533135506213 0.654079098476782\n" + "0.568823660872193 0.162182308193243 0.165648729499781 0.689214503140008\n" + "0.469390641058206 0.794284540683907 0.601981941401637 0.748151592823709")); expectedOutput.add(0.117969860982876); assert (input.size() == expectedOutput.size()); for (int i = 0; i < input.size(); i++) { final double output = input.get(i).determinant(); //print('${input[i].cols}x${input[i].rows} = $output'); relativeTest(output, expectedOutput.get(i)); } } @Test public void testMatrix4SelfTransposeMultiply() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Matrix4> inputB = new ArrayList<>(); final ArrayList<Matrix4> expectedOutput = new ArrayList<>(); inputA.add(parseMatrix4( "0.450541598502498 0.152378018969223 0.078175528753184 0.004634224134067\n" + "0.083821377996933 0.825816977489547 0.442678269775446 0.774910464711502\n" + "0.228976968716819 0.538342435260057 0.106652770180584 0.817303220653433\n" + "0.913337361501670 0.996134716626885 0.961898080855054 0.868694705363510")); inputB.add(parseMatrix4( "0.450541598502498 0.152378018969223 0.078175528753184 0.004634224134067\n" + "0.083821377996933 0.825816977489547 0.442678269775446 0.774910464711502\n" + "0.228976968716819 0.538342435260057 0.106652770180584 0.817303220653433\n" + "0.913337361501670 0.996134716626885 0.961898080855054 0.868694705363510")); expectedOutput.add(parseMatrix4( "1.096629343508065 1.170948826011164 0.975285713492989 1.047596917860438\n" + "1.170948826011164 1.987289692246011 1.393079247172284 1.945966332001094\n" + "0.975285713492989 1.393079247172284 1.138698195167051 1.266161729169725\n" + "1.047596917860438 1.945966332001094 1.266161729169725 2.023122749969790")); assert (inputA.size() == inputB.size()); assert (inputB.size() == expectedOutput.size()); for (int i = 0; i < inputA.size(); i++) { final Matrix4 output = inputA.get(i).clone(); output.transposeMultiply(inputB.get(i)); relativeTest(output, expectedOutput.get(i)); } } @Test public void testMatrix4SelfMultiply() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Matrix4> inputB = new ArrayList<>(); final ArrayList<Matrix4> expectedOutput = new ArrayList<>(); inputA.add(parseMatrix4( "0.450541598502498 0.152378018969223 0.078175528753184 0.004634224134067\n" + "0.083821377996933 0.825816977489547 0.442678269775446 0.774910464711502\n" + "0.228976968716819 0.538342435260057 0.106652770180584 0.817303220653433\n" + "0.913337361501670 0.996134716626885 0.961898080855054 0.868694705363510")); inputB.add(parseMatrix4( "0.450541598502498 0.152378018969223 0.078175528753184 0.004634224134067\n" + "0.083821377996933 0.825816977489547 0.442678269775446 0.774910464711502\n" + "0.228976968716819 0.538342435260057 0.106652770180584 0.817303220653433\n" + "0.913337361501670 0.996134716626885 0.961898080855054 0.868694705363510")); expectedOutput.add(parseMatrix4( "0.237893273152584 0.241190507375353 0.115471053480014 0.188086069635435\n" + "0.916103942227480 1.704973929800637 1.164721763902784 1.675285658272358\n" + "0.919182849383279 1.351023203753565 1.053750106199745 1.215382950294249\n" + "1.508657696357159 2.344965008135463 1.450552688877760 2.316940716769603")); assert (inputA.size() == inputB.size()); assert (inputB.size() == expectedOutput.size()); for (int i = 0; i < inputA.size(); i++) { final Matrix4 output = inputA.get(i).clone(); output.multiply(inputB.get(i)); relativeTest(output, expectedOutput.get(i)); } } @Test public void testMatrix4SelfMultiplyTranspose() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Matrix4> inputB = new ArrayList<>(); final ArrayList<Matrix4> expectedOutput = new ArrayList<>(); inputA.add(parseMatrix4( "0.450541598502498 0.152378018969223 0.078175528753184 0.004634224134067\n" + "0.083821377996933 0.825816977489547 0.442678269775446 0.774910464711502\n" + "0.228976968716819 0.538342435260057 0.106652770180584 0.817303220653433\n" + "0.913337361501670 0.996134716626885 0.961898080855054 0.868694705363510")); inputB.add(parseMatrix4( "0.450541598502498 0.152378018969223 0.078175528753184 0.004634224134067\n" + "0.083821377996933 0.825816977489547 0.442678269775446 0.774910464711502\n" + "0.228976968716819 0.538342435260057 0.106652770180584 0.817303220653433\n" + "0.913337361501670 0.996134716626885 0.961898080855054 0.868694705363510")); expectedOutput.add(parseMatrix4( "0.232339681975335 0.201799089276976 0.197320406329789 0.642508126615338\n" + "0.201799089276976 1.485449982570056 1.144315170085286 1.998154153033270\n" + "0.197320406329789 1.144315170085286 1.021602397682138 1.557970885061235\n" + "0.642508126615338 1.998154153033270 1.557970885061235 3.506347918663387")); assert (inputA.size() == inputB.size()); assert (inputB.size() == expectedOutput.size()); for (int i = 0; i < inputA.size(); i++) { final Matrix4 output = inputA.get(i).clone(); output.multiplyTranspose(inputB.get(i)); relativeTest(output, expectedOutput.get(i)); } } @Test public void testMatrix4Translation() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Matrix4> inputB = new ArrayList<>(); final ArrayList<Matrix4> output1 = new ArrayList<>(); final ArrayList<Matrix4> output2 = new ArrayList<>(); inputA.add(Matrix4.identity()); inputB.add(Matrix4.translationValues(1.0, 3.0, 5.7)); output1.add(inputA.get(0).operatorMultiply(inputB.get(0))); final Matrix4 tmpMatrix = Matrix4.identity(); tmpMatrix.translate(1.0, 3.0, 5.7); output2.add(tmpMatrix); assert (inputA.size() == inputB.size()); assert (output1.size() == output2.size()); for (int i = 0; i < inputA.size(); i++) { relativeTest(output1.get(i), output2.get(i)); } } @Test public void testMatrix4Scale() { final ArrayList<Matrix4> inputA = new ArrayList<>(); final ArrayList<Matrix4> inputB = new ArrayList<>(); final ArrayList<Matrix4> output1 = new ArrayList<>(); final ArrayList<Matrix4> output2 = new ArrayList<>(); inputA.add(Matrix4.identity()); inputB.add(Matrix4.diagonal3Values(1.0, 3.0, 5.7)); output1.add(inputA.get(0).operatorMultiply(inputB.get(0))); final Matrix4 tmpMatrix = Matrix4.identity(); tmpMatrix.scale(1.0, 3.0, 5.7); output2.add(tmpMatrix); assert (inputA.size() == inputB.size()); assert (output1.size() == output2.size()); for (int i = 0; i < inputA.size(); i++) { relativeTest(output1.get(i), output2.get(i)); } } @Test public void testMatrix4Column() { final Matrix4 I = Matrix4.identity(); I.setZero(); assertEquals(I.get(0), 0.0, TestUtils.errorThreshold); final Vector4 c0 = new Vector4(1.0, 2.0, 3.0, 4.0); I.setColumn(0, c0); assertEquals(I.get(0), 1.0, TestUtils.errorThreshold); c0.setX(4.0); assertEquals(I.get(0), 1.0, TestUtils.errorThreshold); assertEquals(c0.getX(), 4.0, TestUtils.errorThreshold); } @Test public void testMatrix4Inversion() { final Matrix4 m = new Matrix4(1.0, 0.0, 2.0, 2.0, 0.0, 2.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 2.0, 1.0, 4.0); final Matrix4 result = Matrix4.identity(); result.setZero(); final double det = result.copyInverse(m); assertEquals(det, 2.0, TestUtils.errorThreshold); assertEquals(result.entry(0, 0), -2.0, TestUtils.errorThreshold); assertEquals(result.entry(1, 0), 1.0, TestUtils.errorThreshold); assertEquals(result.entry(2, 0), -8.0, TestUtils.errorThreshold); assertEquals(result.entry(3, 0), 3.0, TestUtils.errorThreshold); assertEquals(result.entry(0, 1), -0.5, TestUtils.errorThreshold); assertEquals(result.entry(1, 1), 0.5, TestUtils.errorThreshold); assertEquals(result.entry(2, 1), -1.0, TestUtils.errorThreshold); assertEquals(result.entry(3, 1), 0.5, TestUtils.errorThreshold); assertEquals(result.entry(0, 2), 1.0, TestUtils.errorThreshold); assertEquals(result.entry(1, 2), 0.0, TestUtils.errorThreshold); assertEquals(result.entry(2, 2), 2.0, TestUtils.errorThreshold); assertEquals(result.entry(3, 2), -1.0, TestUtils.errorThreshold); assertEquals(result.entry(0, 3), 0.5, TestUtils.errorThreshold); assertEquals(result.entry(1, 3), -0.5, TestUtils.errorThreshold); assertEquals(result.entry(2, 3), 2.0, TestUtils.errorThreshold); assertEquals(result.entry(3, 3), -0.5, TestUtils.errorThreshold); } @Test public void testMatrix4Dot() { final Matrix4 matrix = new Matrix4(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0); final Vector4 v = new Vector4(1.0, 2.0, 3.0, 4.0); assertEquals(matrix.dotRow(0, v), 90.0, TestUtils.errorThreshold); assertEquals(matrix.dotRow(1, v), 100.0, TestUtils.errorThreshold); assertEquals(matrix.dotRow(2, v), 110.0, TestUtils.errorThreshold); assertEquals(matrix.dotColumn(0, v), 30.0, TestUtils.errorThreshold); assertEquals(matrix.dotColumn(1, v), 70.0, TestUtils.errorThreshold); assertEquals(matrix.dotColumn(2, v), 110.0, TestUtils.errorThreshold); } @Test() public void testMatrix4Equals() { assertEquals(Matrix4.identity(), Matrix4.identity()); assertNotEquals(Matrix4.zero(), Matrix4.identity()); assertNotEquals(Matrix4.zero(), 5); assertEquals( Matrix4.identity().hashCode(), Matrix4.identity().hashCode()); } @Test() public void testMatrix4InvertConstructor() { boolean exception = false; try { Matrix4.inverted(Matrix4.zero()); fail(); // don't hit here. } catch (IllegalArgumentException e) { exception = true; } assertTrue(exception); assertEquals(Matrix4.inverted(Matrix4.identity()), Matrix4.identity()); } @Test() public void testMatrix4tryInvert() { assertNull(Matrix4.tryInvert(Matrix4.zero())); assertEquals(Matrix4.tryInvert(Matrix4.identity()), Matrix4.identity()); } @Test() public void testMatrix4SkewConstructor() { final Matrix4 m = Matrix4.skew(0.0, 1.57); final Matrix4 m2 = Matrix4.skewY(1.57); assertEquals(m.entry(0, 0), 1.0, errorThreshold); assertEquals(m.entry(1, 1), 1.0, errorThreshold); assertEquals(m.entry(2, 2), 1.0, errorThreshold); assertEquals(m.entry(3, 3), 1.0, errorThreshold); relativeTest(m.entry(1, 0), Math.tan(1.57)); assertEquals(m.entry(0, 1), 0.0, errorThreshold); assertEquals(m2, m); final Matrix4 n = Matrix4.skew(1.57, 0.0); final Matrix4 n2 = Matrix4.skewX(1.57); assertEquals(n.entry(0, 0), 1.0, errorThreshold); assertEquals(n.entry(1, 1), 1.0, errorThreshold); assertEquals(n.entry(2, 2), 1.0, errorThreshold); assertEquals(n.entry(3, 3), 1.0, errorThreshold); assertEquals(n.entry(1, 0), 0.0, errorThreshold); relativeTest(m.entry(1, 0), Math.tan(1.57)); assertEquals(n2, n); } @Test() public void testLeftTranslate() { // Our test point. final Vector3 p = new Vector3(0.5, 0.0, 0.0); // Scale 2x matrix. Matrix4 m = Matrix4.diagonal3Values(2.0, 2.0, 2.0); // After scaling, translate along the X axis. m.leftTranslate(1.0); // Apply the transformation to p. This will move (0.5, 0, 0) to (2.0, 0, 0). // Scale: 0.5 -> 1.0. // Translate: 1.0 -> 2.0 Vector3 result = m.transformed3(p); assertEquals(result.getX(), 2.0, errorThreshold); assertEquals(result.getY(), 0.0, errorThreshold); assertEquals(result.getZ(), 0.0, errorThreshold); // Scale 2x matrix. m = Matrix4.diagonal3Values(2.0, 2.0, 2.0); // Before scaling, translate along the X axis. m.translate(1.0); // Apply the transformation to p. This will move (0.5, 0, 0) to (3.0, 0, 0). // Translate: 0.5 -> 1.5. // Scale: 1.5 -> 3.0. result = m.transformed3(p); assertEquals(result.getX(), 3.0, errorThreshold); assertEquals(result.getY(), 0.0, errorThreshold); assertEquals(result.getZ(), 0.0, errorThreshold); } @Test() public void testMatrixClassifiers() { assertFalse(Matrix4.zero().isIdentity()); assertTrue(Matrix4.zero().isZero()); assertTrue(Matrix4.identity().isIdentity()); assertFalse(Matrix4.identity().isZero()); } }
flutter-intellij/flutter-idea/testSrc/integration/io/flutter/utils/math/Matrix4Test.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/integration/io/flutter/utils/math/Matrix4Test.java", "repo_id": "flutter-intellij", "token_count": 10728 }
488
/* * 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. */ package io.flutter.devtools; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class DevToolsUtilsTest { @Test public void testFindWidgetId() { String url = "http://127.0.0.1:9102/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A51805%2FP-f92tUS3r8%3D%2F&inspectorRef=inspector-238"; assertEquals( "inspector-238", DevToolsUtils.findWidgetId(url) ); String noIdUrl = "http://127.0.0.1:9102/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A51805%2FP-f92tUS3r8%3D%2F"; assertNull(DevToolsUtils.findWidgetId(noIdUrl)); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/devtools/DevToolsUtilsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/devtools/DevToolsUtilsTest.java", "repo_id": "flutter-intellij", "token_count": 348 }
489
/* * 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. */ package io.flutter.perf; import com.google.common.collect.Lists; import com.google.gson.JsonObject; import com.intellij.codeHighlighting.BackgroundEditorHighlighter; import com.intellij.mock.MockVirtualFileSystem; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorLocation; import com.intellij.openapi.fileEditor.FileEditorState; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import io.flutter.inspector.DiagnosticsNode; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.JsonUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Ignore; import org.junit.Test; import javax.swing.*; import java.beans.PropertyChangeListener; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static io.flutter.perf.FlutterWidgetPerf.IDLE_DELAY_MILISECONDS; import static org.junit.Assert.*; class MockWidgetPerfProvider implements WidgetPerfProvider { WidgetPerfListener widgetPerfListener; boolean isDisposed = false; boolean shouldDisplayStats = true; List<List<String>> requests = new ArrayList<>(); List<Iterable<Integer>> locationIdRequests = new ArrayList<>(); @Override public void setTarget(WidgetPerfListener widgetPerfListener) { this.widgetPerfListener = widgetPerfListener; } @Override public boolean isStarted() { return true; } @Override public boolean isConnected() { return true; } @Override public boolean shouldDisplayPerfStats(FileEditor editor) { return shouldDisplayStats; } @Override public CompletableFuture<DiagnosticsNode> getWidgetTree() { return CompletableFuture.completedFuture(null); } @Override public void dispose() { isDisposed = true; } public void simulateWidgetPerfEvent(PerfReportKind kind, String json) { widgetPerfListener.onWidgetPerfEvent(kind, (JsonObject)JsonUtils.parseString(json)); } public void repaint(When when) { widgetPerfListener.requestRepaint(when); } } class MockPerfModel implements PerfModel { volatile int idleCount = 0; volatile int clearCount = 0; volatile int frameCount = 0; @Override public void markAppIdle() { idleCount++; } @Override public void clear() { clearCount++; } @Override public void onFrame() { frameCount++; } @Override public boolean isAnimationActive() { return idleCount == 0; } } class MockEditorPerfModel extends MockPerfModel implements EditorPerfModel { public boolean isHoveredOverLineMarkerAreaOverride = false; boolean isDisposed; CompletableFuture<FilePerfInfo> statsFuture; private FlutterApp app; private FilePerfInfo stats; private final TextEditor textEditor; MockEditorPerfModel(TextEditor textEditor) { this.textEditor = textEditor; statsFuture = new CompletableFuture<>(); } @NotNull @Override public FilePerfInfo getStats() { return stats; } CompletableFuture<FilePerfInfo> getStatsFuture() { return statsFuture; } @NotNull @Override public TextEditor getTextEditor() { return textEditor; } @Override public FlutterApp getApp() { return app; } @Override public boolean getAlwaysShowLineMarkers() { return isHoveredOverLineMarkerAreaOverride; } @Override public void setAlwaysShowLineMarkersOverride(boolean show) { } @Override public void markAppIdle() { super.markAppIdle(); stats.markAppIdle(); } @Override public void clear() { super.clear(); stats.clear(); } @Override public void setPerfInfo(@NotNull FilePerfInfo stats) { this.stats = stats; if (statsFuture.isDone()) { statsFuture = new CompletableFuture<>(); } statsFuture.complete(stats); } @Override public boolean isAnimationActive() { return stats.getTotalValue(PerfMetric.peakRecent) > 0; } @Override public void dispose() { isDisposed = true; } } class FakeFileLocationMapper implements FileLocationMapper { private final String path; FakeFileLocationMapper(String path) { this.path = path; } Map<TextRange, String> mockText = new HashMap<>(); @Override public TextRange getIdentifierRange(int line, int column) { // Bogus but unique. final int offset = line * 1000 + column; // Dummy name so we can tell what the original line and column was in tests final String text = "Widget:" + line + ":" + column; final TextRange range = new TextRange(offset, offset + text.length()); mockText.put(range, text); return range; } @Override public String getText(TextRange textRange) { assert mockText.containsKey(textRange); return mockText.get(textRange); } @Override public String getPath() { return path; } } class MockTextEditor implements TextEditor { static MockVirtualFileSystem fileSystem = new MockVirtualFileSystem(); private final String name; private final VirtualFile file; private boolean modified; MockTextEditor(String name) { this.name = name; file = fileSystem.findFileByPath(name); } @NotNull @Override public Editor getEditor() { throw new Error("not supported"); } @Override public VirtualFile getFile() { return file; } @Override public boolean canNavigateTo(@NotNull Navigatable navigatable) { return false; } @Override public void navigateTo(@NotNull Navigatable navigatable) { } @NotNull @Override public JComponent getComponent() { throw new Error("not supported"); } @Nullable @Override public JComponent getPreferredFocusedComponent() { return null; } @NotNull @Override public String getName() { return name; } @Override public void setState(@NotNull FileEditorState state) { } @Override public boolean isModified() { return modified; } @Override public boolean isValid() { return true; } @Override public void selectNotify() { } @Override public void deselectNotify() { } @Override public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) { } @Override public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) { } @Nullable @Override public BackgroundEditorHighlighter getBackgroundHighlighter() { return null; } @Nullable @Override public FileEditorLocation getCurrentLocation() { return null; } @Override public void dispose() { } @Nullable @Override public <T> T getUserData(@NotNull Key<T> key) { return null; } @Override public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) { } } public class FlutterWidgetPerfTest { private TextRange getTextRange(String path, int line, int column) { return new FakeFileLocationMapper(path).getIdentifierRange(line, column); } @Test @Ignore("https://github.com/flutter/flutter-intellij/issues/4343") public void testFileStatsCalculation() throws InterruptedException, ExecutionException { final MockWidgetPerfProvider widgetPerfProvider = new MockWidgetPerfProvider(); final Map<String, MockEditorPerfModel> perfModels = new HashMap<>(); final FlutterWidgetPerf flutterWidgetPerf = new FlutterWidgetPerf( true, widgetPerfProvider, (TextEditor textEditor) -> { final MockEditorPerfModel model = new MockEditorPerfModel(textEditor); perfModels.put(textEditor.getName(), model); return model; }, FakeFileLocationMapper::new ); widgetPerfProvider.simulateWidgetPerfEvent( PerfReportKind.rebuild, "{\"startTime\":1000,\"events\":[1,1,2,1,3,1,4,1,6,1,10,4,11,4,12,4,13,1,14,1,95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1],\"newLocations\":{\"/sample/project/main.dart\":[1,11,14,2,18,16,3,23,17,4,40,16,6,46,16,10,69,9,11,70,9,12,71,18,13,41,19,14,42,20,95,51,58],\"/sample/project/clock.dart\":[96,33,12,97,52,12,100,53,16,102,54,14,104,55,17,105,34,15,106,35,16]}}" ); // Simulate 60fps for 2 seconds. for (int frame = 1; frame <= 120; frame++) { final long startTime = 1000 + frame * 1000 * 1000 / 60; widgetPerfProvider.simulateWidgetPerfEvent( PerfReportKind.rebuild, "{\"startTime\":" + startTime + ",\"events\":[95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1]}"); } final Set<TextEditor> textEditors = new HashSet<>(); final TextEditor clockTextEditor = new MockTextEditor("/sample/project/clock.dart"); textEditors.add(clockTextEditor); flutterWidgetPerf.showFor(textEditors); assertEquals(perfModels.size(), 1); MockEditorPerfModel clockModel = perfModels.get("/sample/project/clock.dart"); assertEquals(clockModel.getTextEditor(), clockTextEditor); FilePerfInfo stats = clockModel.getStatsFuture().get(); // Stats for the first response are rebuilds only assertEquals(1620, stats.getTotalValue(PerfMetric.pastSecond)); List<TextRange> locations = Lists.newArrayList(stats.getLocations()); assertEquals(7, locations.size()); final TextRange textRange = getTextRange("/sample/project/clock.dart", 52, 12); List<SummaryStats> rangeStats = Lists.newArrayList(stats.getRangeStats(textRange)); assertEquals(1, rangeStats.size()); assertEquals(PerfReportKind.rebuild, rangeStats.get(0).getKind()); assertEquals(360, rangeStats.get(0).getValue(PerfMetric.pastSecond)); assertEquals(726, rangeStats.get(0).getValue(PerfMetric.total)); assertEquals("Widget:52:12", rangeStats.get(0).getDescription()); rangeStats = Lists.newArrayList(stats.getRangeStats(getTextRange("/sample/project/clock.dart", 34, 15))); assertEquals(1, rangeStats.size()); assertEquals(PerfReportKind.rebuild, rangeStats.get(0).getKind()); assertEquals(60, rangeStats.get(0).getValue(PerfMetric.pastSecond)); assertEquals(121, rangeStats.get(0).getValue(PerfMetric.total)); assertEquals("Widget:34:15", rangeStats.get(0).getDescription()); clockModel.markAppIdle(); assertEquals(0, stats.getTotalValue(PerfMetric.pastSecond)); rangeStats = Lists.newArrayList(stats.getRangeStats(locations.get(4))); assertEquals(0, rangeStats.get(0).getValue(PerfMetric.pastSecond)); // Total is not impacted. assertEquals(121, rangeStats.get(0).getValue(PerfMetric.total)); rangeStats = Lists.newArrayList(stats.getRangeStats(textRange)); assertEquals(1, rangeStats.size()); assertEquals(PerfReportKind.rebuild, rangeStats.get(0).getKind()); assertEquals(0, rangeStats.get(0).getValue(PerfMetric.pastSecond)); assertEquals(726, rangeStats.get(0).getValue(PerfMetric.total)); assertEquals("Widget:52:12", rangeStats.get(0).getDescription()); final TextEditor mainTextEditor = new MockTextEditor("/sample/project/main.dart"); textEditors.add(mainTextEditor); flutterWidgetPerf.clearModels(); // Add events with both rebuilds and repaints. widgetPerfProvider.simulateWidgetPerfEvent(PerfReportKind.rebuild, "{\"startTime\":19687239,\"events\":[95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1]}"); widgetPerfProvider.simulateWidgetPerfEvent(PerfReportKind.repaint, "{\"startTime\":19687239,\"events\":[95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1]}"); flutterWidgetPerf.showFor(textEditors); assertEquals(2, perfModels.size()); clockModel = perfModels.get("/sample/project/clock.dart"); final MockEditorPerfModel mainModel = perfModels.get("/sample/project/main.dart"); assert mainModel != null; final FilePerfInfo mainStats = mainModel.getStatsFuture().get(); assert clockModel != null; stats = clockModel.getStatsFuture().get(); // We have new fake data for the files so the count in the past second is // back up from zero assertEquals(2, mainStats.getTotalValue(PerfMetric.pastSecond)); assertEquals(142, mainStats.getTotalValue(PerfMetric.total)); assertEquals(3321, stats.getTotalValue(PerfMetric.total)); locations = Lists.newArrayList(stats.getLocations()); assertEquals(7, locations.size()); rangeStats = Lists.newArrayList(stats.getRangeStats(getTextRange("/sample/project/clock.dart", 52, 12))); assertEquals(2, rangeStats.size()); assertEquals(PerfReportKind.repaint, rangeStats.get(0).getKind()); assertEquals(6, rangeStats.get(0).getValue(PerfMetric.pastSecond)); assertEquals(6, rangeStats.get(0).getValue(PerfMetric.total)); assertEquals("Widget:52:12", rangeStats.get(0).getDescription()); assertEquals(PerfReportKind.rebuild, rangeStats.get(1).getKind()); assertEquals(6, rangeStats.get(1).getValue(PerfMetric.pastSecond)); assertEquals(732, rangeStats.get(1).getValue(PerfMetric.total)); assertEquals("Widget:52:12", rangeStats.get(1).getDescription()); rangeStats = Lists.newArrayList(stats.getRangeStats(getTextRange("/sample/project/clock.dart", 33, 12))); assertEquals(2, rangeStats.size()); assertEquals(PerfReportKind.repaint, rangeStats.get(0).getKind()); assertEquals(1, rangeStats.get(0).getValue(PerfMetric.pastSecond)); assertEquals(1, rangeStats.get(0).getValue(PerfMetric.total)); assertEquals("Widget:33:12", rangeStats.get(0).getDescription()); assertEquals(PerfReportKind.rebuild, rangeStats.get(1).getKind()); assertEquals(1, rangeStats.get(1).getValue(PerfMetric.pastSecond)); assertEquals(122, rangeStats.get(1).getValue(PerfMetric.total)); assertEquals("Widget:33:12", rangeStats.get(1).getDescription()); assertFalse(clockModel.isDisposed); assertFalse(mainModel.isDisposed); flutterWidgetPerf.showFor(new HashSet<>()); assertTrue(clockModel.isDisposed); assertTrue(mainModel.isDisposed); flutterWidgetPerf.dispose(); } @Test public void testOverallStatsCalculation_oldFormat() throws InterruptedException { final MockWidgetPerfProvider widgetPerfProvider = new MockWidgetPerfProvider(); final FlutterWidgetPerf flutterWidgetPerf = new FlutterWidgetPerf( true, widgetPerfProvider, textEditor -> null, FakeFileLocationMapper::new ); final MockPerfModel perfModel = new MockPerfModel(); flutterWidgetPerf.addPerfListener(perfModel); widgetPerfProvider.simulateWidgetPerfEvent( PerfReportKind.rebuild, "{\"startTime\":1000,\"events\":[1,1,2,1,3,1,4,1,6,1,10,4,11,4,12,4,13,1,14,1,95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1],\"newLocations\":{\"/sample/project/main.dart\":[1,11,14,2,18,16,3,23,17,4,40,16,6,46,16,10,69,9,11,70,9,12,71,18,13,41,19,14,42,20,95,51,58],\"/sample/project/clock.dart\":[96,33,12,97,52,12,100,53,16,102,54,14,104,55,17,105,34,15,106,35,16]}}"); // Simulate 60fps for 2 seconds. for (int frame = 1; frame <= 120; frame++) { final long startTime = 1000 + frame * 1000 * 1000 / 60; widgetPerfProvider.simulateWidgetPerfEvent( PerfReportKind.rebuild, "{\"startTime\":" + startTime + ",\"events\":[95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1]}"); } final ArrayList<PerfMetric> lastFrameOnly = new ArrayList<>(); lastFrameOnly.add(PerfMetric.lastFrame); final ArrayList<PerfMetric> metrics = new ArrayList<>(); metrics.add(PerfMetric.lastFrame); metrics.add(PerfMetric.totalSinceEnteringCurrentScreen); ArrayList<SlidingWindowStatsSummary> stats = flutterWidgetPerf.getStatsForMetric(lastFrameOnly, PerfReportKind.repaint); // No repaint stats are provided. assertTrue(stats.isEmpty()); stats = flutterWidgetPerf.getStatsForMetric(lastFrameOnly, PerfReportKind.rebuild); assertEquals(8, stats.size()); for (SlidingWindowStatsSummary stat : stats) { assertTrue(stat.getValue(PerfMetric.lastFrame) > 0); } stats = flutterWidgetPerf.getStatsForMetric(metrics, PerfReportKind.rebuild); assertEquals(18, stats.size()); for (SlidingWindowStatsSummary stat : stats) { assertTrue(stat.getValue(PerfMetric.lastFrame) > 0 || stat.getValue(PerfMetric.totalSinceEnteringCurrentScreen) > 0); } /// Test that the perfModel gets notified correctly when there are // events to draw a frame of the ui. assertEquals(perfModel.frameCount, 0); SwingUtilities.invokeLater(() -> { flutterWidgetPerf.requestRepaint(When.now); }); while (perfModel.frameCount == 0) { try { //noinspection BusyWait Thread.sleep(1); } catch (InterruptedException e) { fail(e.toString()); } } assertEquals(1, perfModel.frameCount); assertEquals(0, perfModel.idleCount); // Verify that an idle event occurs once we wait the idle time delay. Thread.sleep(IDLE_DELAY_MILISECONDS); Thread.yield(); assertEquals(1, perfModel.idleCount); flutterWidgetPerf.removePerfListener(perfModel); flutterWidgetPerf.dispose(); } @Test public void testOverallStatsCalculation_newFormat() throws InterruptedException { final MockWidgetPerfProvider widgetPerfProvider = new MockWidgetPerfProvider(); final FlutterWidgetPerf flutterWidgetPerf = new FlutterWidgetPerf( true, widgetPerfProvider, textEditor -> null, FakeFileLocationMapper::new ); final MockPerfModel perfModel = new MockPerfModel(); flutterWidgetPerf.addPerfListener(perfModel); widgetPerfProvider.simulateWidgetPerfEvent( PerfReportKind.rebuild, "{\"startTime\":1000,\"events\":[1,1,2,1,3,1,4,1,6,1,10,4,11,4,12,4,13,1,14,1,95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1],\"locations\":{\"/sample/project/main.dart\":{\t\"ids\":[1, 2, 3, 4, 6, 10, 11, 12, 13, 14, 95],\"lines\":[11, 18, 23, 40, 46, 69, 70, 71, 41, 42, 51],\"columns\":[14, 16, 17, 16, 16, 9, 9, 18, 19, 20, 58],\"names\":[\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\"]},\"/sample/project/clock.dart\":{\"ids\":[96, 97, 100, 102, 104, 105, 106],\"lines\":[33, 52, 53, 54, 55, 34, 35],\"columns\":[12, 12, 16, 14, 17, 15, 16],\"names\":[\"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\"]}}}"); // Simulate 60fps for 2 seconds. for (int frame = 1; frame <= 120; frame++) { final long startTime = 1000 + frame * 1000 * 1000 / 60; widgetPerfProvider.simulateWidgetPerfEvent( PerfReportKind.rebuild, "{\"startTime\":" + startTime + ",\"events\":[95,1,96,1,97,6,100,6,102,6,104,6,105,1,106,1]}"); } final ArrayList<PerfMetric> lastFrameOnly = new ArrayList<>(); lastFrameOnly.add(PerfMetric.lastFrame); final ArrayList<PerfMetric> metrics = new ArrayList<>(); metrics.add(PerfMetric.lastFrame); metrics.add(PerfMetric.totalSinceEnteringCurrentScreen); ArrayList<SlidingWindowStatsSummary> stats = flutterWidgetPerf.getStatsForMetric(lastFrameOnly, PerfReportKind.repaint); // No repaint stats are provided. assertTrue(stats.isEmpty()); stats = flutterWidgetPerf.getStatsForMetric(lastFrameOnly, PerfReportKind.rebuild); assertEquals(8, stats.size()); for (SlidingWindowStatsSummary stat : stats) { assertTrue(stat.getValue(PerfMetric.lastFrame) > 0); } stats = flutterWidgetPerf.getStatsForMetric(metrics, PerfReportKind.rebuild); assertEquals(18, stats.size()); for (SlidingWindowStatsSummary stat : stats) { assertTrue(stat.getValue(PerfMetric.lastFrame) > 0 || stat.getValue(PerfMetric.totalSinceEnteringCurrentScreen) > 0); } /// Test that the perfModel gets notified correctly when there are // events to draw a frame of the ui. assertEquals(perfModel.frameCount, 0); SwingUtilities.invokeLater(() -> { flutterWidgetPerf.requestRepaint(When.now); }); while (perfModel.frameCount == 0) { try { //noinspection BusyWait Thread.sleep(1); } catch (InterruptedException e) { fail(e.toString()); } } assertEquals(1, perfModel.frameCount); assertEquals(0, perfModel.idleCount); // Verify that an idle event occurs once we wait the idle time delay. Thread.sleep(IDLE_DELAY_MILISECONDS); assertEquals(1, perfModel.idleCount); flutterWidgetPerf.removePerfListener(perfModel); flutterWidgetPerf.dispose(); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/perf/FlutterWidgetPerfTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/perf/FlutterWidgetPerfTest.java", "repo_id": "flutter-intellij", "token_count": 7827 }
490
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.run.test; import io.flutter.run.test.TestFields.Scope; import org.jdom.Element; import org.junit.Test; import static org.junit.Assert.*; /** * Verifies that we can read and write test configurations. */ public class TestFieldsTest { @Test public void shouldReadNameScopeFieldsFromXml() { final Element elt = new Element("test"); addOption(elt, "testName", "should work"); addOption(elt, "testFile", "hello_test.dart"); final TestFields after = TestFields.readFrom(elt); assertEquals(Scope.NAME, after.getScope()); assertEquals("should work", after.getTestName()); assertEquals("hello_test.dart", after.getTestFile()); assertNull(after.getTestDir()); } @Test public void shouldReadFileScopeFieldsFromXml() { final Element elt = new Element("test"); addOption(elt, "testFile", "hello_test.dart"); final TestFields after = TestFields.readFrom(elt); assertEquals(Scope.FILE, after.getScope()); assertEquals("hello_test.dart", after.getTestFile()); assertNull(after.getTestDir()); } @Test public void shouldReadDirectoryScopeFieldsFromXml() { final Element elt = new Element("test"); addOption(elt, "testDir", "test/dir"); final TestFields after = TestFields.readFrom(elt); assertEquals(Scope.DIRECTORY, after.getScope()); assertNull(after.getTestFile()); assertEquals("test/dir", after.getTestDir()); } @Test public void roundTripShouldPreserveNameScopeSettings() { final Element elt = new Element("test"); TestFields.forTestName("should work", "hello_test.dart").writeTo(elt); final TestFields after = TestFields.readFrom(elt); assertEquals(Scope.NAME, after.getScope()); assertEquals("should work", after.getTestName()); assertEquals("hello_test.dart", after.getTestFile()); assertNull(after.getTestDir()); } @Test public void roundTripShouldPreserveRegexpSettings() { final Element elt = new Element("test"); TestFields.forTestName("should *", "hello_test.dart").useRegexp(true).writeTo(elt); final TestFields after = TestFields.readFrom(elt); assertEquals(Scope.NAME, after.getScope()); assertEquals("should *", after.getTestName()); assertEquals("hello_test.dart", after.getTestFile()); assertTrue(after.getUseRegexp()); assertNull(after.getTestDir()); } @Test public void roundTripShouldPreserveFileScopeSettings() { final Element elt = new Element("test"); TestFields.forFile("hello_test.dart").writeTo(elt); final TestFields after = TestFields.readFrom(elt); assertEquals(Scope.FILE, after.getScope()); assertEquals("hello_test.dart", after.getTestFile()); assertNull(after.getTestDir()); } @Test public void roundTripShouldPreserveDirectoryScopeSettings() { final Element elt = new Element("test"); TestFields.forDir("test/dir").writeTo(elt); final TestFields after = TestFields.readFrom(elt); assertEquals(Scope.DIRECTORY, after.getScope()); assertNull(after.getTestFile()); assertEquals("test/dir", after.getTestDir()); } private void addOption(Element elt, String name, String value) { final Element child = new Element("option"); child.setAttribute("name", name); child.setAttribute("value", value); elt.addContent(child); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/test/TestFieldsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/test/TestFieldsTest.java", "repo_id": "flutter-intellij", "token_count": 1195 }
491
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.utils; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import io.flutter.testing.ProjectFixture; import io.flutter.testing.Testing; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.*; /** * Verifies the Flutter module detection utilities in {@link FlutterModuleUtils}. */ public class FlutterModuleUtilsTest { @Rule public final ProjectFixture<IdeaProjectTestFixture> fixture = Testing.makeEmptyModule(); @Test public void isDeprecatedFlutterModuleType_false_empty_module() { assertFalse(FlutterModuleUtils.isDeprecatedFlutterModuleType(fixture.getModule())); } @Test public void isFlutterModule_null() { assertFalse(FlutterModuleUtils.isFlutterModule(null)); } @Test public void isFlutterModule_emptyModule() { assertFalse(FlutterModuleUtils.isFlutterModule(fixture.getModule())); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/FlutterModuleUtilsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/FlutterModuleUtilsTest.java", "repo_id": "flutter-intellij", "token_count": 334 }
492
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * A {@link BoundVariable} represents a local variable bound to a particular value in a {@link * Frame}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class BoundVariable extends Response { public BoundVariable(JsonObject json) { super(json); } /** * The token position where this variable was declared. */ public int getDeclarationTokenPos() { return getAsInt("declarationTokenPos"); } public String getName() { return getAsString("name"); } /** * The last token position where this variable is visible to the scope. */ public int getScopeEndTokenPos() { return getAsInt("scopeEndTokenPos"); } /** * The first token position where this variable is visible to the scope. */ public int getScopeStartTokenPos() { return getAsInt("scopeStartTokenPos"); } /** * @return one of <code>InstanceRef</code>, <code>TypeArgumentsRef</code> or * <code>Sentinel</code> */ public Object getValue() { final JsonElement elem = json.get("value"); if (elem == null) return null; if (elem.isJsonObject()) { final JsonObject o = (JsonObject) elem; if (o.get("type").getAsString().equals("@Instance")) return new InstanceRef(o); if (o.get("type").getAsString().equals("@TypeArguments")) return new TypeArgumentsRef(o); if (o.get("type").getAsString().equals("Sentinel")) return new Sentinel(o); } return null; } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/BoundVariable.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/BoundVariable.java", "repo_id": "flutter-intellij", "token_count": 706 }
493
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * A {@link Func} represents a Dart language function. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Func extends Obj { public Func(JsonObject json) { super(json); } /** * The compiled code associated with this function. * * Can return <code>null</code>. */ public CodeRef getCode() { JsonObject obj = (JsonObject) json.get("code"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new CodeRef(obj); } /** * Is this function implicitly defined (e.g., implicit getter/setter)? */ public boolean getImplicit() { return getAsBoolean("implicit"); } /** * The location of this function in the source code. * * Note: this may not agree with the location of `owner` if this is a function from a mixin * application, expression evaluation, patched class, etc. * * Can return <code>null</code>. */ public SourceLocation getLocation() { JsonObject obj = (JsonObject) json.get("location"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new SourceLocation(obj); } /** * The name of this function. */ public String getName() { return getAsString("name"); } /** * The owner of this function, which can be a Library, Class, or a Function. * * Note: the location of `owner` may not agree with `location` if this is a function from a mixin * application, expression evaluation, patched class, etc. * * @return one of <code>LibraryRef</code>, <code>ClassRef</code> or <code>FuncRef</code> */ public Object getOwner() { final JsonElement elem = json.get("owner"); if (elem == null) return null; if (elem.isJsonObject()) { final JsonObject o = (JsonObject) elem; if (o.get("type").getAsString().equals("@Library")) return new LibraryRef(o); if (o.get("type").getAsString().equals("@Class")) return new ClassRef(o); if (o.get("type").getAsString().equals("@Func")) return new FuncRef(o); } return null; } /** * The signature of the function. */ public InstanceRef getSignature() { return new InstanceRef((JsonObject) json.get("signature")); } /** * Is this function an abstract method? */ public boolean isAbstract() { return getAsBoolean("abstract"); } /** * Is this function const? */ public boolean isConst() { return getAsBoolean("const"); } /** * Is this function static? */ public boolean isStatic() { return getAsBoolean("static"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Func.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Func.java", "repo_id": "flutter-intellij", "token_count": 1248 }
494
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonObject; @SuppressWarnings({"WeakerAccess", "unused"}) public class LogRecord extends Response { public LogRecord(JsonObject json) { super(json); } /** * An error object associated with this log event. */ public InstanceRef getError() { return new InstanceRef((JsonObject) json.get("error")); } /** * The severity level (a value between 0 and 2000). * * See the package:logging `Level` class for an overview of the possible values. */ public int getLevel() { return getAsInt("level"); } /** * The name of the source of the log message. */ public InstanceRef getLoggerName() { return new InstanceRef((JsonObject) json.get("loggerName")); } /** * The log message. */ public InstanceRef getMessage() { return new InstanceRef((JsonObject) json.get("message")); } /** * A monotonically increasing sequence number. */ public int getSequenceNumber() { return getAsInt("sequenceNumber"); } /** * A stack trace associated with this log event. */ public InstanceRef getStackTrace() { return new InstanceRef((JsonObject) json.get("stackTrace")); } /** * The timestamp. */ public int getTime() { return getAsInt("time"); } /** * The zone where the log was emitted. */ public InstanceRef getZone() { return new InstanceRef((JsonObject) json.get("zone")); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/LogRecord.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/LogRecord.java", "repo_id": "flutter-intellij", "token_count": 687 }
495
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.dartlang.vm.service.internal.VmServiceConst; /** * When an RPC encounters an error, it is provided in the _error_ property of the response object. * JSON-RPC errors always provide _code_, _message_, and _data_ properties. <br/> * Here is an example error response for our [streamListen](#streamlisten) request above. This error * would be generated if we were attempting to subscribe to the _GC_ stream multiple times from the * same client. * * <pre> * { * "jsonrpc": "2.0", * "error": { * "code": 103, * "message": "Stream already subscribed", * "data": { * "details": "The stream 'GC' is already subscribed" * } * } * "id": "2" * } * </pre> * <p> * In addition the [error codes](http://www.jsonrpc.org/specification#error_object) specified in * the JSON-RPC spec, we use the following application specific error codes: * * <pre> * code | message | meaning * ---- | ------- | ------- * 100 | Feature is disabled | The operation is unable to complete because a feature is disabled * 101 | VM must be paused | This operation is only valid when the VM is paused * 102 | Cannot add breakpoint | The VM is unable to add a breakpoint at the specified line or function * 103 | Stream already subscribed | The client is already subscribed to the specified _streamId_ * 104 | Stream not subscribed | The client is not subscribed to the specified _streamId_ * </pre> */ public class RPCError extends Element implements VmServiceConst { /** * The response code used by the client when it receives a response from the server that it did * not expect. For example, it requested a library element but received a list. */ public static final int UNEXPECTED_RESPONSE = 5; public static RPCError unexpected(String expectedType, Response response) { String errMsg = "Expected type " + expectedType + " but received " + response.getType(); if (response instanceof Sentinel) { errMsg += ": " + ((Sentinel) response).getKind(); } JsonObject json = new JsonObject(); json.addProperty("code", UNEXPECTED_RESPONSE); json.addProperty("message", errMsg); JsonObject data = new JsonObject(); data.addProperty("details", errMsg); data.add("response", response.getJson()); json.add("data", data); return new RPCError(json); } public RPCError(JsonObject json) { super(json); } public int getCode() { return json.get("code").getAsInt(); } public String getDetails() { JsonElement data = json.get("data"); if (data instanceof JsonObject) { JsonElement details = ((JsonObject) data).get("details"); if (details != null) { return details.getAsString(); } } return null; } public String getMessage() { return json.get("message").getAsString(); } public JsonObject getRequest() { JsonElement data = json.get("data"); if (data instanceof JsonObject) { JsonElement request = ((JsonObject) data).get("request"); if (request instanceof JsonObject) { return (JsonObject) request; } } return null; } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/RPCError.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/RPCError.java", "repo_id": "flutter-intellij", "token_count": 1202 }
496
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * The {@link Stack} class represents the various components of a Dart stack trace for a given * isolate. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Stack extends Response { public Stack(JsonObject json) { super(json); } /** * A list of frames representing the asynchronous path. Comparable to `awaiterFrames`, if * provided, although some frames may be different. * * Can return <code>null</code>. */ public ElementList<Frame> getAsyncCausalFrames() { if (json.get("asyncCausalFrames") == null) return null; return new ElementList<Frame>(json.get("asyncCausalFrames").getAsJsonArray()) { @Override protected Frame basicGet(JsonArray array, int index) { return new Frame(array.get(index).getAsJsonObject()); } }; } /** * A list of frames representing the asynchronous path. Comparable to `asyncCausalFrames`, if * provided, although some frames may be different. * * Can return <code>null</code>. */ public ElementList<Frame> getAwaiterFrames() { if (json.get("awaiterFrames") == null) return null; return new ElementList<Frame>(json.get("awaiterFrames").getAsJsonArray()) { @Override protected Frame basicGet(JsonArray array, int index) { return new Frame(array.get(index).getAsJsonObject()); } }; } /** * A list of frames that make up the synchronous stack, rooted at the message loop (i.e., the * frames since the last asynchronous gap or the isolate's entrypoint). */ public ElementList<Frame> getFrames() { return new ElementList<Frame>(json.get("frames").getAsJsonArray()) { @Override protected Frame basicGet(JsonArray array, int index) { return new Frame(array.get(index).getAsJsonObject()); } }; } /** * A list of messages in the isolate's message queue. */ public ElementList<Message> getMessages() { return new ElementList<Message>(json.get("messages").getAsJsonArray()) { @Override protected Message basicGet(JsonArray array, int index) { return new Message(array.get(index).getAsJsonObject()); } }; } /** * Specifies whether or not this stack is complete or has been artificially truncated. */ public boolean getTruncated() { return getAsBoolean("truncated"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Stack.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Stack.java", "repo_id": "flutter-intellij", "token_count": 1029 }
497
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.internal; import com.google.common.collect.Lists; import com.google.gson.JsonObject; import java.util.LinkedList; /** * A {@link RequestSink} that enqueues all requests and can be later converted into a "passthrough" * or an "error" {@link RequestSink}. */ public class BlockingRequestSink implements RequestSink { /** * The base {@link RequestSink} */ private final RequestSink base; /** * A queue of requests. */ private final LinkedList<JsonObject> queue = Lists.newLinkedList(); public BlockingRequestSink(RequestSink base) { this.base = base; } @Override public void add(JsonObject request) { synchronized (queue) { queue.add(request); } } @Override public void close() { base.close(); } /** * Responds with an error to all the currently queued requests and return a {@link RequestSink} to * do the same for all the future requests. * * @param errorResponseSink the sink to send error responses to, not {@code null} */ public RequestSink toErrorSink(ResponseSink errorResponseSink, String errorResponseCode, String errorResponseMessage) { ErrorRequestSink errorRequestSink = new ErrorRequestSink(errorResponseSink, errorResponseCode, errorResponseMessage); synchronized (queue) { for (JsonObject request : queue) { errorRequestSink.add(request); } } return errorRequestSink; } /** * Returns the passthrough {@link RequestSink}. */ public RequestSink toPassthroughSink() { synchronized (queue) { for (JsonObject request : queue) { base.add(request); } } return base; } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/BlockingRequestSink.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/BlockingRequestSink.java", "repo_id": "flutter-intellij", "token_count": 770 }
498
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.actions; import com.intellij.icons.AllIcons; import com.intellij.ide.impl.NewProjectUtil; import com.intellij.ide.projectWizard.NewProjectWizard; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.wm.impl.welcomeScreen.NewWelcomeScreen; import com.intellij.ui.LayeredIcon; import com.intellij.ui.OffsetIcon; import icons.FlutterIcons; import io.flutter.FlutterBundle; import javax.swing.Icon; import org.jetbrains.annotations.NotNull; public class FlutterNewProjectAction extends AnAction implements DumbAware { public FlutterNewProjectAction() { super(FlutterBundle.message("action.new.project.title")); } @Override public void update(@NotNull AnActionEvent e) { if (NewWelcomeScreen.isNewWelcomeScreen(e)) { //e.getPresentation().setIcon(getFlutterDecoratedIcon()); e.getPresentation().setText(FlutterBundle.message("welcome.new.project.compact")); } } @Override public void actionPerformed(@NotNull AnActionEvent e) { NewProjectWizard wizard = new NewProjectWizard(null, ModulesProvider.EMPTY_MODULES_PROVIDER, null); NewProjectUtil.createNewProject(wizard); } @NotNull Icon getFlutterDecoratedIcon() { Icon icon = AllIcons.Welcome.CreateNewProject; Icon badgeIcon = new OffsetIcon(0, FlutterIcons.Flutter_badge).scale(0.666f); LayeredIcon decorated = new LayeredIcon(2); decorated.setIcon(badgeIcon, 0, 7, 7); decorated.setIcon(icon, 1, 0, 0); return decorated; } }
flutter-intellij/flutter-studio/src/io/flutter/actions/FlutterNewProjectAction.java/0
{ "file_path": "flutter-intellij/flutter-studio/src/io/flutter/actions/FlutterNewProjectAction.java", "repo_id": "flutter-intellij", "token_count": 634 }
499
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package io.flutter.utils; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.gradle.util.GradleConstants; public class FlutterExternalSystemTaskNotificationListener extends ExternalSystemTaskNotificationListenerAdapter { public FlutterExternalSystemTaskNotificationListener() { } @Override public void onSuccess(@NotNull ExternalSystemTaskId id) { if (id.getType() == ExternalSystemTaskType.RESOLVE_PROJECT && id.getProjectSystemId() == GradleConstants.SYSTEM_ID) { final Project project = id.findProject(); if (project != null) { GradleUtils.checkDartSupport(project); } } } }
flutter-intellij/flutter-studio/src/io/flutter/utils/FlutterExternalSystemTaskNotificationListener.java/0
{ "file_path": "flutter-intellij/flutter-studio/src/io/flutter/utils/FlutterExternalSystemTaskNotificationListener.java", "repo_id": "flutter-intellij", "token_count": 336 }
500
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.tests.gui; import static com.google.common.truth.Truth.assertThat; import com.android.tools.idea.tests.gui.framework.FlutterGuiTestRule; import com.android.tools.idea.tests.gui.framework.GuiTests; import com.android.tools.idea.tests.gui.framework.fixture.EditorFixture; import com.android.tools.idea.tests.gui.framework.fixture.FlutterFrameFixture; import com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard.FlutterProjectStepFixture; import com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard.NewFlutterModuleWizardFixture; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.module.WorkingDirectoryProvider; import io.flutter.module.FlutterProjectType; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(NewModuleTest.GuiTestRemoteRunner.class) public class NewModuleTest { @Rule public final FlutterGuiTestRule myGuiTest = new FlutterGuiTestRule(); @Test public void createNewAppModule() throws IOException { System.out.println("TEST_DIR=" + GuiTests.getConfigDirPath().getParent()); FlutterFrameFixture ideFrame = myGuiTest.importSimpleApplication(); EditorFixture editor = ideFrame.getEditor(); editor.waitUntilErrorAnalysisFinishes(); NewFlutterModuleWizardFixture wizardFixture = ideFrame.openFromMenu(NewFlutterModuleWizardFixture::find, "File", "New", "New Module..."); wizardFixture.chooseModuleType("Flutter Package").clickNext(); NewFlutterModuleWizardFixture wizard = ideFrame.findNewModuleWizard(); FlutterProjectStepFixture projectStep = wizard.getFlutterProjectStep(FlutterProjectType.PACKAGE); assertThat(projectStep.isConfiguredForModules()).isTrue(); // Check error messages. assertThat(projectStep.getErrorMessage()).isNotNull(); projectStep.enterProjectName(""); assertThat(projectStep.getErrorMessage()).contains("Please enter"); projectStep.enterProjectName("A"); assertThat(projectStep.getErrorMessage()).contains("valid Dart package"); projectStep.enterProjectName("class"); assertThat(projectStep.getErrorMessage()).contains("Dart keyword"); projectStep.enterProjectName("utf"); assertThat(projectStep.getErrorMessage()).contains("Flutter package"); projectStep.enterProjectName("a_long_module_name_is_not_allowed"); assertThat(projectStep.getErrorMessage()).contains("less than"); projectStep.enterProjectName("module"); // TODO(messick) Fix SDK path tests //String path = projectStep.getSdkPath(); //projectStep.enterSdkPath(""); //// This does not work. The message comes back as " ". It does work in manual testing. ////assertThat(projectStep.getErrorMessage()).endsWith(("not given.")); //projectStep.enterSdkPath("x"); //assertThat(projectStep.getErrorMessage()).endsWith(("not exist.")); //projectStep.enterSdkPath("/tmp"); //assertThat(projectStep.getErrorMessage()).endsWith(("location.")); //projectStep.enterSdkPath(path); wizard.clickFinish(); myGuiTest.waitForBackgroundTasks(); myGuiTest.ideFrame().waitForProjectSyncToFinish(); } /** * This custom runner sets a custom path to the GUI tests. * This needs to be done by the test runner because the test framework * initializes the path before the test class is loaded. */ public static class GuiTestRemoteRunner extends com.intellij.testGuiFramework.framework.GuiTestRemoteRunner { private static final ExtensionPointName<WorkingDirectoryProvider> WORKING_DIRECTORY_PROVIDER_EP_NAME = ExtensionPointName .create("com.intellij.module.workingDirectoryProvider"); public GuiTestRemoteRunner(Class<?> suiteClass) { super(suiteClass); System.setProperty("gui.tests.root.dir.path", getDefaultWorkingDir()); //System.setProperty(GuiTestOptions.IS_RUNNING_ON_RELEASE, "true"); //System.setProperty(GuiTestOptions.REMOTE_IDE_PATH_KEY, "/Applications/Android Studio.app/Contents/MacOS/studio"); //System.setProperty(GuiTestOptions.REMOTE_IDE_VM_OPTIONS_PATH_KEY, "/Applications/Android Studio.app/Contents/bin/studio.vmoptions"); } protected static String getDefaultWorkingDir() { return System.getenv("GUI_TEST_SRC"); } } }
flutter-intellij/flutter-studio/testSrc/io/flutter/tests/gui/NewModuleTest.java/0
{ "file_path": "flutter-intellij/flutter-studio/testSrc/io/flutter/tests/gui/NewModuleTest.java", "repo_id": "flutter-intellij", "token_count": 1440 }
501
<idea-plugin> <extensions defaultExtensionNs="com.intellij"> <programRunner implementation="io.flutter.run.coverage.FlutterCoverageProgramRunner"/> <coverageEngine implementation="io.flutter.run.coverage.FlutterCoverageEngine"/> <coverageRunner implementation="io.flutter.run.coverage.FlutterCoverageRunner"/> <projectService serviceImplementation="io.flutter.run.coverage.FlutterCoverageAnnotator"/> </extensions> </idea-plugin>
flutter-intellij/resources/META-INF/flutter-coverage.xml/0
{ "file_path": "flutter-intellij/resources/META-INF/flutter-coverage.xml", "repo_id": "flutter-intellij", "token_count": 143 }
502
{ "amber.primary": "ffffc107", "amber[50]": "fffff8e1", "amber[100]": "ffffecb3", "amber[200]": "ffffe082", "amber[300]": "ffffd54f", "amber[400]": "ffffca28", "amber[500]": "ffffc107", "amber[600]": "ffffb300", "amber[700]": "ffffa000", "amber[800]": "ffff8f00", "amber[900]": "ffff6f00", "amberAccent.primary": "ffffd740", "amberAccent[100]": "ffffe57f", "amberAccent[200]": "ffffd740", "amberAccent[400]": "ffffc400", "amberAccent[700]": "ffffab00", "black": "ff000000", "black12": "1f000000", "black26": "42000000", "black38": "61000000", "black45": "73000000", "black54": "8a000000", "black87": "dd000000", "blue.primary": "ff2196f3", "blue[50]": "ffe3f2fd", "blue[100]": "ffbbdefb", "blue[200]": "ff90caf9", "blue[300]": "ff64b5f6", "blue[400]": "ff42a5f5", "blue[500]": "ff2196f3", "blue[600]": "ff1e88e5", "blue[700]": "ff1976d2", "blue[800]": "ff1565c0", "blue[900]": "ff0d47a1", "blueAccent.primary": "ff448aff", "blueAccent[100]": "ff82b1ff", "blueAccent[200]": "ff448aff", "blueAccent[400]": "ff2979ff", "blueAccent[700]": "ff2962ff", "blueGrey.primary": "ff607d8b", "blueGrey[50]": "ffeceff1", "blueGrey[100]": "ffcfd8dc", "blueGrey[200]": "ffb0bec5", "blueGrey[300]": "ff90a4ae", "blueGrey[400]": "ff78909c", "blueGrey[500]": "ff607d8b", "blueGrey[600]": "ff546e7a", "blueGrey[700]": "ff455a64", "blueGrey[800]": "ff37474f", "blueGrey[900]": "ff263238", "brown.primary": "ff795548", "brown[50]": "ffefebe9", "brown[100]": "ffd7ccc8", "brown[200]": "ffbcaaa4", "brown[300]": "ffa1887f", "brown[400]": "ff8d6e63", "brown[500]": "ff795548", "brown[600]": "ff6d4c41", "brown[700]": "ff5d4037", "brown[800]": "ff4e342e", "brown[900]": "ff3e2723", "cyan.primary": "ff00bcd4", "cyan[50]": "ffe0f7fa", "cyan[100]": "ffb2ebf2", "cyan[200]": "ff80deea", "cyan[300]": "ff4dd0e1", "cyan[400]": "ff26c6da", "cyan[500]": "ff00bcd4", "cyan[600]": "ff00acc1", "cyan[700]": "ff0097a7", "cyan[800]": "ff00838f", "cyan[900]": "ff006064", "cyanAccent.primary": "ff18ffff", "cyanAccent[100]": "ff84ffff", "cyanAccent[200]": "ff18ffff", "cyanAccent[400]": "ff00e5ff", "cyanAccent[700]": "ff00b8d4", "deepOrange.primary": "ffff5722", "deepOrange[50]": "fffbe9e7", "deepOrange[100]": "ffffccbc", "deepOrange[200]": "ffffab91", "deepOrange[300]": "ffff8a65", "deepOrange[400]": "ffff7043", "deepOrange[500]": "ffff5722", "deepOrange[600]": "fff4511e", "deepOrange[700]": "ffe64a19", "deepOrange[800]": "ffd84315", "deepOrange[900]": "ffbf360c", "deepOrangeAccent.primary": "ffff6e40", "deepOrangeAccent[100]": "ffff9e80", "deepOrangeAccent[200]": "ffff6e40", "deepOrangeAccent[400]": "ffff3d00", "deepOrangeAccent[700]": "ffdd2c00", "deepPurple.primary": "ff673ab7", "deepPurple[50]": "ffede7f6", "deepPurple[100]": "ffd1c4e9", "deepPurple[200]": "ffb39ddb", "deepPurple[300]": "ff9575cd", "deepPurple[400]": "ff7e57c2", "deepPurple[500]": "ff673ab7", "deepPurple[600]": "ff5e35b1", "deepPurple[700]": "ff512da8", "deepPurple[800]": "ff4527a0", "deepPurple[900]": "ff311b92", "deepPurpleAccent.primary": "ff7c4dff", "deepPurpleAccent[100]": "ffb388ff", "deepPurpleAccent[200]": "ff7c4dff", "deepPurpleAccent[400]": "ff651fff", "deepPurpleAccent[700]": "ff6200ea", "green.primary": "ff4caf50", "green[50]": "ffe8f5e9", "green[100]": "ffc8e6c9", "green[200]": "ffa5d6a7", "green[300]": "ff81c784", "green[400]": "ff66bb6a", "green[500]": "ff4caf50", "green[600]": "ff43a047", "green[700]": "ff388e3c", "green[800]": "ff2e7d32", "green[900]": "ff1b5e20", "greenAccent.primary": "ff69f0ae", "greenAccent[100]": "ffb9f6ca", "greenAccent[200]": "ff69f0ae", "greenAccent[400]": "ff00e676", "greenAccent[700]": "ff00c853", "grey.primary": "ff9e9e9e", "grey[50]": "fffafafa", "grey[100]": "fff5f5f5", "grey[200]": "ffeeeeee", "grey[300]": "ffe0e0e0", "grey[350]": "ffd6d6d6", "grey[400]": "ffbdbdbd", "grey[500]": "ff9e9e9e", "grey[600]": "ff757575", "grey[700]": "ff616161", "grey[800]": "ff424242", "grey[850]": "ff303030", "grey[900]": "ff212121", "indigo.primary": "ff3f51b5", "indigo[50]": "ffe8eaf6", "indigo[100]": "ffc5cae9", "indigo[200]": "ff9fa8da", "indigo[300]": "ff7986cb", "indigo[400]": "ff5c6bc0", "indigo[500]": "ff3f51b5", "indigo[600]": "ff3949ab", "indigo[700]": "ff303f9f", "indigo[800]": "ff283593", "indigo[900]": "ff1a237e", "indigoAccent.primary": "ff536dfe", "indigoAccent[100]": "ff8c9eff", "indigoAccent[200]": "ff536dfe", "indigoAccent[400]": "ff3d5afe", "indigoAccent[700]": "ff304ffe", "lightBlue.primary": "ff03a9f4", "lightBlue[50]": "ffe1f5fe", "lightBlue[100]": "ffb3e5fc", "lightBlue[200]": "ff81d4fa", "lightBlue[300]": "ff4fc3f7", "lightBlue[400]": "ff29b6f6", "lightBlue[500]": "ff03a9f4", "lightBlue[600]": "ff039be5", "lightBlue[700]": "ff0288d1", "lightBlue[800]": "ff0277bd", "lightBlue[900]": "ff01579b", "lightBlueAccent.primary": "ff40c4ff", "lightBlueAccent[100]": "ff80d8ff", "lightBlueAccent[200]": "ff40c4ff", "lightBlueAccent[400]": "ff00b0ff", "lightBlueAccent[700]": "ff0091ea", "lightGreen.primary": "ff8bc34a", "lightGreen[50]": "fff1f8e9", "lightGreen[100]": "ffdcedc8", "lightGreen[200]": "ffc5e1a5", "lightGreen[300]": "ffaed581", "lightGreen[400]": "ff9ccc65", "lightGreen[500]": "ff8bc34a", "lightGreen[600]": "ff7cb342", "lightGreen[700]": "ff689f38", "lightGreen[800]": "ff558b2f", "lightGreen[900]": "ff33691e", "lightGreenAccent.primary": "ffb2ff59", "lightGreenAccent[100]": "ffccff90", "lightGreenAccent[200]": "ffb2ff59", "lightGreenAccent[400]": "ff76ff03", "lightGreenAccent[700]": "ff64dd17", "lime.primary": "ffcddc39", "lime[50]": "fff9fbe7", "lime[100]": "fff0f4c3", "lime[200]": "ffe6ee9c", "lime[300]": "ffdce775", "lime[400]": "ffd4e157", "lime[500]": "ffcddc39", "lime[600]": "ffc0ca33", "lime[700]": "ffafb42b", "lime[800]": "ff9e9d24", "lime[900]": "ff827717", "limeAccent.primary": "ffeeff41", "limeAccent[100]": "fff4ff81", "limeAccent[200]": "ffeeff41", "limeAccent[400]": "ffc6ff00", "limeAccent[700]": "ffaeea00", "orange.primary": "ffff9800", "orange[50]": "fffff3e0", "orange[100]": "ffffe0b2", "orange[200]": "ffffcc80", "orange[300]": "ffffb74d", "orange[400]": "ffffa726", "orange[500]": "ffff9800", "orange[600]": "fffb8c00", "orange[700]": "fff57c00", "orange[800]": "ffef6c00", "orange[900]": "ffe65100", "orangeAccent.primary": "ffffab40", "orangeAccent[100]": "ffffd180", "orangeAccent[200]": "ffffab40", "orangeAccent[400]": "ffff9100", "orangeAccent[700]": "ffff6d00", "pink.primary": "ffe91e63", "pink[50]": "fffce4ec", "pink[100]": "fff8bbd0", "pink[200]": "fff48fb1", "pink[300]": "fff06292", "pink[400]": "ffec407a", "pink[500]": "ffe91e63", "pink[600]": "ffd81b60", "pink[700]": "ffc2185b", "pink[800]": "ffad1457", "pink[900]": "ff880e4f", "pinkAccent.primary": "ffff4081", "pinkAccent[100]": "ffff80ab", "pinkAccent[200]": "ffff4081", "pinkAccent[400]": "fff50057", "pinkAccent[700]": "ffc51162", "purple.primary": "ff9c27b0", "purple[50]": "fff3e5f5", "purple[100]": "ffe1bee7", "purple[200]": "ffce93d8", "purple[300]": "ffba68c8", "purple[400]": "ffab47bc", "purple[500]": "ff9c27b0", "purple[600]": "ff8e24aa", "purple[700]": "ff7b1fa2", "purple[800]": "ff6a1b9a", "purple[900]": "ff4a148c", "purpleAccent.primary": "ffe040fb", "purpleAccent[100]": "ffea80fc", "purpleAccent[200]": "ffe040fb", "purpleAccent[400]": "ffd500f9", "purpleAccent[700]": "ffaa00ff", "red.primary": "fff44336", "red[50]": "ffffebee", "red[100]": "ffffcdd2", "red[200]": "ffef9a9a", "red[300]": "ffe57373", "red[400]": "ffef5350", "red[500]": "fff44336", "red[600]": "ffe53935", "red[700]": "ffd32f2f", "red[800]": "ffc62828", "red[900]": "ffb71c1c", "redAccent.primary": "ffff5252", "redAccent[100]": "ffff8a80", "redAccent[200]": "ffff5252", "redAccent[400]": "ffff1744", "redAccent[700]": "ffd50000", "teal.primary": "ff009688", "teal[50]": "ffe0f2f1", "teal[100]": "ffb2dfdb", "teal[200]": "ff80cbc4", "teal[300]": "ff4db6ac", "teal[400]": "ff26a69a", "teal[500]": "ff009688", "teal[600]": "ff00897b", "teal[700]": "ff00796b", "teal[800]": "ff00695c", "teal[900]": "ff004d40", "tealAccent.primary": "ff64ffda", "tealAccent[100]": "ffa7ffeb", "tealAccent[200]": "ff64ffda", "tealAccent[400]": "ff1de9b6", "tealAccent[700]": "ff00bfa5", "transparent": "00000000", "white": "ffffffff", "white10": "1affffff", "white12": "1fffffff", "white24": "3dffffff", "white30": "4dffffff", "white38": "62ffffff", "white54": "8affffff", "white60": "99ffffff", "white70": "b3ffffff", "yellow.primary": "ffffeb3b", "yellow[50]": "fffffde7", "yellow[100]": "fffff9c4", "yellow[200]": "fffff59d", "yellow[300]": "fffff176", "yellow[400]": "ffffee58", "yellow[500]": "ffffeb3b", "yellow[600]": "fffdd835", "yellow[700]": "fffbc02d", "yellow[800]": "fff9a825", "yellow[900]": "fff57f17", "yellowAccent.primary": "ffffff00", "yellowAccent[100]": "ffffff8d", "yellowAccent[200]": "ffffff00", "yellowAccent[400]": "ffffea00", "yellowAccent[700]": "ffffd600" }
flutter-intellij/resources/flutter/colors/material.json/0
{ "file_path": "flutter-intellij/resources/flutter/colors/material.json", "repo_id": "flutter-intellij", "token_count": 4690 }
503
<!-- ~ Copyright 2017 The Chromium Authors. All rights reserved. ~ Use of this source code is governed by a BSD-style license that can be ~ found in the LICENSE file. --> <html> <body> Flutter package dependency check. <!-- tooltip end --> Checks whether a Flutter <code><a href="https://dart.dev/tools/pub/pubspec">pubspec.yaml</a></code> has been edited since the last <a href="https://flutter.dev/upgrading/">package update</a>. </body> </html>
flutter-intellij/resources/inspectionDescriptions/FlutterDependency.html/0
{ "file_path": "flutter-intellij/resources/inspectionDescriptions/FlutterDependency.html", "repo_id": "flutter-intellij", "token_count": 144 }
504
distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists
flutter-intellij/third_party/gradle/wrapper/gradle-wrapper.properties/0
{ "file_path": "flutter-intellij/third_party/gradle/wrapper/gradle-wrapper.properties", "repo_id": "flutter-intellij", "token_count": 73 }
505
# Flutter Plugin Maintenance Tool The previous builder for the Flutter plugin was written in Ant. An expert in Ant would probably have no trouble maintaining it, but we have no such expert available. In order to increase stability and productivity we transformed the builder into a Dart command line tool, inspired by the Flutter tool. The tool is named `plugin`, since it helps with plugin development. ## Functions The tool needs to perform several functions. Building is the basic one, but others are important too. Implementation note: these will be implemented as compound commands in the CLI tool (similar to `flutter doctor` or `flutter run` in the Flutter CLI tool). * `make` * `test` * `deploy` * `generate` * `lint` Each command has its own set of optional arguments. If the CLI tool is invoked without a command then it will print its help message. There are two global options. On the command line these are given prior to the command name. * `-r, --release=XX` Use "release mode." The `XX` value specifies the release identifier, like 18 or 19.1. It will be shown in the "version" field of the plugin manager's listing for the Flutter plugin. In this mode additional constraints must be satisfied. The current git branch must have no unsaved changes and must be named "release_XX". The `.github/workflows/presubmit.yaml` file must be newer than the `product-matrix.json` file (see the `generate` command). * `-d, --cwd=<working-directory>` Set the root directory to the `working-directory` value. This should not be used when running the tool from the command line. It is only intended to be used when running tests from IntelliJ run configurations that have no way to specify the working directory. ### Make Builds may be targeted for local development or distribution. * `-[no-]ij` Build for IntelliJ. Default is true; may be negated by including `no`. * `-[no-]as` Build for Android Studio. Default is true; may be negated by including `no`. * `-o, --only-version=ID` Only build the specified IntelliJ version. `ID` is one of the "version" strings in product-matrix.json. * `-u, --unpack` Normally the archive files are not unpacked if the corresponding directory exists. This flag forces the archive files to be unpacked. The make function must generate the correct `plugin.xml` for each platform and generate the correct artifacts for each. In release mode the archive files are always unpacked (--unpack is implied). The plugin files are saved in the `artifacts` directory. In release mode a subdirectory of `artifacts` is created which has the name of the release and they are put there. During a local dev/test run the subdirectory is not created and the created files are children of `artifacts`. Returns a success or failure code to play nice with shell commands. ### Test Both unit and integration tests need to run, and tests should work whether running locally or on Travis. * `-u, --[no-]unit `Run unit tests (or not). * `-i, --[no-]integration` Run GUI-based integration tests (or not). TBD: We may need some mechanism to automatically upload testing artifacts, since we can no longer attach zip files to email. This could also potentially be addressed by creating a 'dev' channel for the plugin on the JetBrains store, and publishing to it when we have release candidates. ### Deploy Automatically upload all required artifacts to the JetBrains site. This function will print instructions to retrieve the password from valentine then prompt for the password to log into the JetBrains site. It has no options. Returns a success or failure code to play nice with shell commands. (Used primarily by the dev channel Kokoro job. Not sure if it works for uploading to the stable channel.) ### Generate Generate a `plugin.xml` from `plugin.xml.template` to be used for launching a runtime workbench. This is different from the ones generated during building because it will have a version range that allows use in all targeted platforms. ### Lint Run the lint tool. It checks for bad imports and prints a report of the Dart plugin API usage. ## Examples Build the Flutter plugin for IntelliJ and Android Studio, in distribution mode. `plugin -r19.2 make` Build a local version of the IntelliJ version of the plugin, not for distribution. `plugin make --no-as` Run integration tests without doing a build, assuming an edit-build-test cycle during development. `plugin test --no-unit` Build everything then run all tests. The big question here is: Can we get integration tests to run using the newly-built plugin rather than sources? `plugin make && plugin test` ## Debugging It can be difficult to debug issues that only occur with a deployable plugin built by `plugin make`. Here's how to set up remote debugging with IntelliJ: In IntelliJ create a "Remote" type of run configuration. It shows you the command-line arg you need to add in the top text field of the run config. Copy that text. Now, (assuming you are on a Mac) find your IJ or AS app in the Finder. Right-click, 'Show Package Contents', open Contents, edit Info.plist. In the plist editor expand JVMOptions and then edit VMOptions. Append the copied text to the end. Save the plist editor and launch the AS or IJ app. Back in IntelliJ, select your new run config and click the debug icon to attach the debugger to the app. The copied text includes "suspend=n". If you want to set a breakpoint before execution begins change that 'n' to 'y'.
flutter-intellij/tool/plugin/README.md/0
{ "file_path": "flutter-intellij/tool/plugin/README.md", "repo_id": "flutter-intellij", "token_count": 1398 }
506
@ECHO off REM Copyright 2014 The Flutter Authors. All rights reserved. REM Use of this source code is governed by a BSD-style license that can be REM found in the LICENSE file. REM ---------------------------------- NOTE ---------------------------------- REM REM Please keep the logic in this file consistent with the logic in the REM `flutter` script in the same directory to ensure that Flutter & Dart continue to REM work across all platforms! REM REM -------------------------------------------------------------------------- SETLOCAL REM To debug the tool, you can uncomment the following line to enable debug mode: REM SET FLUTTER_TOOL_ARGS="--enable-asserts %FLUTTER_TOOL_ARGS%" FOR %%i IN ("%~dp0..") DO SET FLUTTER_ROOT=%%~fi REM If available, add location of bundled mingit to PATH SET mingit_path=%FLUTTER_ROOT%\bin\mingit\cmd IF EXIST "%mingit_path%" SET PATH=%PATH%;%mingit_path% REM We test if Git is available on the Host as we run git in shared.bat REM Test if the flutter directory is a git clone, otherwise git rev-parse HEAD would fail IF NOT EXIST "%flutter_root%\.git" ( ECHO Error: The Flutter directory is not a clone of the GitHub project. ECHO The flutter tool requires Git in order to operate properly; ECHO to set up Flutter, run the following command: ECHO git clone -b stable https://github.com/flutter/flutter.git EXIT 1 ) REM Include shared scripts in shared.bat SET shared_bin=%FLUTTER_ROOT%\bin\internal\shared.bat CALL "%shared_bin%" SET flutter_tools_dir=%FLUTTER_ROOT%\packages\flutter_tools SET cache_dir=%FLUTTER_ROOT%\bin\cache SET snapshot_path=%cache_dir%\flutter_tools.snapshot SET dart_sdk_path=%cache_dir%\dart-sdk SET dart=%dart_sdk_path%\bin\dart.exe SET exit_with_errorlevel=%FLUTTER_ROOT%/bin/internal/exit_with_errorlevel.bat REM Chaining the call to 'dart' and 'exit' with an ampersand ensures that REM Windows reads both commands into memory once before executing them. This REM avoids nasty errors that may otherwise occur when the dart command (e.g. as REM part of 'flutter upgrade') modifies this batch script while it is executing. REM REM Do not use the CALL command in the next line to execute Dart. CALL causes REM Windows to re-read the line from disk after the CALL command has finished REM regardless of the ampersand chain. "%dart%" --disable-dart-dev --packages="%flutter_tools_dir%\.dart_tool\package_config.json" %FLUTTER_TOOL_ARGS% "%snapshot_path%" %* & "%exit_with_errorlevel%"
flutter/bin/flutter.bat/0
{ "file_path": "flutter/bin/flutter.bat", "repo_id": "flutter", "token_count": 757 }
507
@ECHO off REM Copyright 2014 The Flutter Authors. All rights reserved. REM Use of this source code is governed by a BSD-style license that can be REM found in the LICENSE file. REM ---------------------------------- NOTE ---------------------------------- REM REM Please keep the logic in this file consistent with the logic in the REM `shared.sh` script in the same directory to ensure that Flutter & Dart continue to REM work across all platforms! REM REM -------------------------------------------------------------------------- SETLOCAL SET flutter_tools_dir=%FLUTTER_ROOT%\packages\flutter_tools SET cache_dir=%FLUTTER_ROOT%\bin\cache SET snapshot_path=%cache_dir%\flutter_tools.snapshot SET snapshot_path_old=%cache_dir%\flutter_tools.snapshot.old SET stamp_path=%cache_dir%\flutter_tools.stamp SET script_path=%flutter_tools_dir%\bin\flutter_tools.dart SET dart_sdk_path=%cache_dir%\dart-sdk SET engine_stamp=%cache_dir%\engine-dart-sdk.stamp SET engine_version_path=%FLUTTER_ROOT%\bin\internal\engine.version SET dart=%dart_sdk_path%\bin\dart.exe REM Ensure that bin/cache exists. IF NOT EXIST "%cache_dir%" MKDIR "%cache_dir%" REM If the cache still doesn't exist, fail with an error that we probably don't have permissions. IF NOT EXIST "%cache_dir%" ( ECHO Error: Unable to create cache directory at 1>&2 ECHO %cache_dir% 1>&2 ECHO. 1>&2 ECHO This may be because flutter doesn't have write permissions for 1>&2 ECHO this path. Try moving the flutter directory to a writable location, 1>&2 ECHO such as within your home directory. 1>&2 EXIT 1 ) :acquire_lock 2>NUL ( REM "3" is now stderr because of "2>NUL". CALL :subroutine %* 2>&3 9> "%cache_dir%\flutter.bat.lock" || GOTO acquire_lock ) GOTO :after_subroutine :subroutine REM If present, run the bootstrap script first SET bootstrap_path=%FLUTTER_ROOT%\bin\internal\bootstrap.bat IF EXIST "%bootstrap_path%" ( CALL "%bootstrap_path%" ) REM Check that git exists and get the revision SET git_exists=false 2>NUL ( PUSHD "%flutter_root%" FOR /f %%r IN ('git rev-parse HEAD') DO ( SET git_exists=true SET revision=%%r ) POPD ) REM If git didn't execute we don't have git. Exit without /B to avoid retrying. if %git_exists% == false echo Error: Unable to find git in your PATH. && EXIT 1 SET compilekey="%revision%:%FLUTTER_TOOL_ARGS%" REM Invalidate cache if: REM * SNAPSHOT_PATH is not a file, or REM * STAMP_PATH is not a file, or REM * STAMP_PATH is an empty file, or REM * Contents of STAMP_PATH is not what we are going to compile, or REM * pubspec.yaml last modified after pubspec.lock REM The following IF conditions are all linked with a logical OR. However, REM there is no OR operator in batch and a GOTO construct is used as replacement. IF NOT EXIST "%engine_stamp%" GOTO do_sdk_update_and_snapshot SET /P dart_required_version=<"%engine_version_path%" SET /P dart_installed_version=<"%engine_stamp%" IF %dart_required_version% NEQ %dart_installed_version% GOTO do_sdk_update_and_snapshot IF NOT EXIST "%snapshot_path%" GOTO do_snapshot IF NOT EXIST "%stamp_path%" GOTO do_snapshot SET /P stamp_value=<"%stamp_path%" IF %stamp_value% NEQ %compilekey% GOTO do_snapshot SET pubspec_yaml_path=%flutter_tools_dir%\pubspec.yaml SET pubspec_lock_path=%flutter_tools_dir%\pubspec.lock FOR /F %%i IN ('DIR /B /O:D "%pubspec_yaml_path%" "%pubspec_lock_path%"') DO SET newer_file=%%i FOR %%i IN (%pubspec_yaml_path%) DO SET pubspec_yaml_timestamp=%%~ti FOR %%i IN (%pubspec_lock_path%) DO SET pubspec_lock_timestamp=%%~ti IF "%pubspec_yaml_timestamp%" == "%pubspec_lock_timestamp%" SET newer_file="" IF "%newer_file%" EQU "pubspec.yaml" GOTO do_snapshot REM Everything is up-to-date - exit subroutine EXIT /B :do_sdk_update_and_snapshot REM Detect which PowerShell executable is available on the Host REM PowerShell version <= 5: PowerShell.exe REM PowerShell version >= 6: pwsh.exe WHERE /Q pwsh.exe && ( SET powershell_executable=pwsh.exe ) || WHERE /Q PowerShell.exe && ( SET powershell_executable=PowerShell.exe ) || ( ECHO Error: PowerShell executable not found. 1>&2 ECHO Either pwsh.exe or PowerShell.exe must be in your PATH. 1>&2 EXIT 1 ) ECHO Checking Dart SDK version... 1>&2 SET update_dart_bin=%FLUTTER_ROOT%\bin\internal\update_dart_sdk.ps1 REM Escape apostrophes from the executable path SET "update_dart_bin=%update_dart_bin:'=''%" REM PowerShell command must have exit code set in order to prevent all non-zero exit codes from being translated REM into 1. The exit code 2 is used to detect the case where the major version is incorrect and there should be REM no subsequent retries. ECHO Downloading Dart SDK from Flutter engine %dart_required_version%... 1>&2 %powershell_executable% -ExecutionPolicy Bypass -NoProfile -Command "Unblock-File -Path '%update_dart_bin%'; & '%update_dart_bin%'; exit $LASTEXITCODE;" IF "%ERRORLEVEL%" EQU "2" ( EXIT 1 ) IF "%ERRORLEVEL%" NEQ "0" ( ECHO Error: Unable to update Dart SDK. Retrying... 1>&2 timeout /t 5 /nobreak GOTO :do_sdk_update_and_snapshot ) :do_snapshot IF EXIST "%FLUTTER_ROOT%\version" DEL "%FLUTTER_ROOT%\version" IF EXIST "%FLUTTER_ROOT%\bin\cache\flutter.version.json" DEL "%FLUTTER_ROOT%\bin\cache\flutter.version.json" ECHO: > "%cache_dir%\.dartignore" ECHO Building flutter tool... 1>&2 PUSHD "%flutter_tools_dir%" REM Makes changes to PUB_ENVIRONMENT only visible to commands within SETLOCAL/ENDLOCAL SETLOCAL IF "%CI%" == "true" GOTO on_bot IF "%BOT%" == "true" GOTO on_bot IF "%CONTINUOUS_INTEGRATION%" == "true" GOTO on_bot IF "%CHROME_HEADLESS%" == "1" GOTO on_bot GOTO not_on_bot :on_bot SET PUB_ENVIRONMENT=%PUB_ENVIRONMENT%:flutter_bot :not_on_bot SET PUB_SUMMARY_ONLY=1 SET PUB_ENVIRONMENT=%PUB_ENVIRONMENT%:flutter_install IF "%PUB_CACHE%" == "" ( IF EXIST "%pub_cache_path%" SET PUB_CACHE=%pub_cache_path% ) SET /A total_tries=10 SET /A remaining_tries=%total_tries%-1 :retry_pub_upgrade ECHO Running pub upgrade... 1>&2 "%dart%" pub upgrade --suppress-analytics IF "%ERRORLEVEL%" EQU "0" goto :upgrade_succeeded ECHO Error (%ERRORLEVEL%): Unable to 'pub upgrade' flutter tool. Retrying in five seconds... (%remaining_tries% tries left) 1>&2 timeout /t 5 /nobreak 2>NUL SET /A remaining_tries-=1 IF "%remaining_tries%" EQU "0" GOTO upgrade_retries_exhausted GOTO :retry_pub_upgrade :upgrade_retries_exhausted SET exit_code=%ERRORLEVEL% ECHO Error: 'pub upgrade' still failing after %total_tries% tries. 1>&2 GOTO final_exit :upgrade_succeeded ENDLOCAL POPD REM Move the old snapshot - we can't just overwrite it as the VM might currently have it REM memory mapped (e.g. on flutter upgrade), and deleting it might not work if the file REM is in use. For downloading a new dart sdk the folder is moved, so we take the same REM approach of moving the file here. SET /A snapshot_path_suffix=1 :move_old_snapshot IF EXIST "%snapshot_path_old%%snapshot_path_suffix%" ( SET /A snapshot_path_suffix+=1 GOTO move_old_snapshot ) ELSE ( IF EXIST "%snapshot_path%" ( MOVE "%snapshot_path%" "%snapshot_path_old%%snapshot_path_suffix%" 2> NUL > NUL ) ) IF "%FLUTTER_TOOL_ARGS%" == "" ( "%dart%" --verbosity=error --snapshot="%snapshot_path%" --snapshot-kind="app-jit" --packages="%flutter_tools_dir%\.dart_tool\package_config.json" --no-enable-mirrors "%script_path%" > NUL ) else ( "%dart%" "%FLUTTER_TOOL_ARGS%" --verbosity=error --snapshot="%snapshot_path%" --snapshot-kind="app-jit" --packages="%flutter_tools_dir%\.dart_tool\package_config.json" "%script_path%" > NUL ) IF "%ERRORLEVEL%" NEQ "0" ( ECHO Error: Unable to create dart snapshot for flutter tool. 1>&2 SET exit_code=%ERRORLEVEL% GOTO :final_exit ) >"%stamp_path%" ECHO %compilekey% REM Try to delete any old snapshots now. Swallow any errors though. DEL "%snapshot_path%.old*" 2> NUL > NUL REM Exit Subroutine EXIT /B :after_subroutine :final_exit EXIT /B %exit_code%
flutter/bin/internal/shared.bat/0
{ "file_path": "flutter/bin/internal/shared.bat", "repo_id": "flutter", "token_count": 3513 }
508
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'use_cases.dart'; class TextButtonUseCase extends UseCase { @override String get name => 'TextButton'; @override String get route => '/text-button'; @override Widget build(BuildContext context) => const MainWidget(); } class MainWidget extends StatefulWidget { const MainWidget({super.key}); @override State<MainWidget> createState() => MainWidgetState(); } class MainWidgetState extends State<MainWidget> { double currentSliderValue = 20; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('TextButton'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( onPressed: () { }, child: const Text('Text button'), ), const TextButton( onPressed: null, child: Text('Text button disabled'), ), ], ), ), ); } }
flutter/dev/a11y_assessments/lib/use_cases/text_button.dart/0
{ "file_path": "flutter/dev/a11y_assessments/lib/use_cases/text_button.dart", "repo_id": "flutter", "token_count": 521 }
509
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:a11y_assessments/use_cases/use_cases.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; Future<void> pumpsUseCase(WidgetTester tester, UseCase useCase) async { await tester.pumpWidget(MaterialApp( home: Builder( builder: (BuildContext context) { return useCase.build(context); }, ), )); }
flutter/dev/a11y_assessments/test/test_utils.dart/0
{ "file_path": "flutter/dev/a11y_assessments/test/test_utils.dart", "repo_id": "flutter", "token_count": 188 }
510
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const String kCullOpacityRouteName = '/cull_opacity'; const String kCubicBezierRouteName = '/cubic_bezier'; const String kBackdropFilterRouteName = '/backdrop_filter'; const String kPostBackdropFilterRouteName = '/post_backdrop_filter'; const String kSimpleAnimationRouteName = '/simple_animation'; const String kPictureCacheRouteName = '/picture_cache'; const String kPictureCacheComplexityScoringRouteName = '/picture_cache_complexity_scoring'; const String kLargeImageChangerRouteName = '/large_image_changer'; const String kLargeImagesRouteName = '/large_images'; const String kPathTessellationRouteName = '/path_tessellation'; const String kTextRouteName = '/text'; const String kVeryLongPictureScrollingRouteName = '/very_long_picture_scrolling'; const String kFullscreenTextRouteName = '/fullscreen_text'; const String kAnimatedPlaceholderRouteName = '/animated_placeholder'; const String kClipperCacheRouteName = '/clipper_cache'; const String kColorFilterAndFadeRouteName = '/color_filter_and_fade'; const String kColorFilterCacheRouteName = '/color_filter_cache'; const String kColorFilterWithUnstableChildName = '/color_filter_with_unstable_child'; const String kFadingChildAnimationRouteName = '/fading_child_animation'; const String kImageFilteredTransformAnimationRouteName = '/imagefiltered_transform_animation'; const String kMultiWidgetConstructionRouteName = '/multi_widget_construction'; const String kHeavyGridViewRouteName = '/heavy_gridview'; const String kRasterCacheUseMemory = '/raster_cache_use_memory'; const String kShaderMaskCacheRouteName = '/shader_mask_cache'; const String kSimpleScrollRouteName = '/simple_scroll'; const String kStackSizeRouteName = '/stack_size'; const String kAnimationWithMicrotasksRouteName = '/animation_with_microtasks'; const String kAnimatedImageRouteName = '/animated_image'; const String kOpacityPeepholeRouteName = '/opacity_peephole'; const String kGradientPerfRouteName = '/gradient_perf'; const String kAnimatedComplexOpacityPerfRouteName = '/animated_complex_opacity'; const String kAnimatedComplexImageFilteredPerfRouteName = '/animated_complex_image_filtered'; const String kListTextLayoutRouteName = '/list_text_layout'; const String kAnimatedBlurBackdropFilter = '/animated_blur_backdrop_filter'; const String kSlidersRouteName = '/sliders'; const String kDrawPointsPageRougeName = '/draw_points'; const String kDrawVerticesPageRouteName = '/draw_vertices'; const String kDrawAtlasPageRouteName = '/draw_atlas'; const String kAnimatedAdvancedBlend = '/animated_advanced_blend'; const String kOpacityPeepholeOneRectRouteName = '$kOpacityPeepholeRouteName/one_big_rect'; const String kOpacityPeepholeColumnOfOpacityRouteName = '$kOpacityPeepholeRouteName/column_of_opacity'; const String kOpacityPeepholeOpacityOfCachedChildRouteName = '$kOpacityPeepholeRouteName/opacity_of_cached_child'; const String kOpacityPeepholeOpacityOfColumnRouteName = '$kOpacityPeepholeRouteName/opacity_of_column'; const String kOpacityPeepholeGridOfOpacityRouteName = '$kOpacityPeepholeRouteName/grid_of_opacity'; const String kOpacityPeepholeOpacityOfGridRouteName = '$kOpacityPeepholeRouteName/opacity_of_grid'; const String kOpacityPeepholeOpacityOfColOfRowsRouteName = '$kOpacityPeepholeRouteName/opacity_of_col_of_rows'; const String kOpacityPeepholeFadeTransitionTextRouteName = '$kOpacityPeepholeRouteName/fade_transition_text'; const String kOpacityPeepholeGridOfRectsWithAlphaRouteName = '$kOpacityPeepholeRouteName/grid_of_rects_with_alpha'; const String kOpacityPeepholeGridOfAlphaSaveLayerRectsRouteName = '$kOpacityPeepholeRouteName/grid_of_alpha_savelayer_rects'; const String kOpacityPeepholeColumnOfAlphaSaveLayerRowsOfRectsRouteName = '$kOpacityPeepholeRouteName/column_of_alpha_save_layer_rows_of_rects'; const String kGradientPerfRecreateDynamicRouteName = '$kGradientPerfRouteName/recreate_dynamic'; const String kGradientPerfRecreateConsistentRouteName = '$kGradientPerfRouteName/recreate_consistent'; const String kGradientPerfStaticConsistentRouteName = '$kGradientPerfRouteName/static_consistent'; const String kScrollableName = '/macrobenchmark_listview'; const String kOpacityScrollableName = '$kOpacityPeepholeRouteName/listview'; const String kGradientPerfScrollableName = '$kGradientPerfRouteName/listview'; const String kStackSizeKey = 'stack_size';
flutter/dev/benchmarks/macrobenchmarks/lib/common.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/common.dart", "repo_id": "flutter", "token_count": 1351 }
511
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui; import 'package:flutter/material.dart'; Future<ui.Image> loadImage(String asset) async { final ui.ImmutableBuffer buffer = await ui.ImmutableBuffer.fromAsset(asset); final ui.Codec codec = await PaintingBinding.instance.instantiateImageCodecWithSize(buffer); final ui.FrameInfo frameInfo = await codec.getNextFrame(); return frameInfo.image; } class DrawAtlasPage extends StatefulWidget { const DrawAtlasPage({super.key}); @override State<DrawAtlasPage> createState() => _DrawAtlasPageState(); } class _DrawAtlasPageState extends State<DrawAtlasPage> with SingleTickerProviderStateMixin { late final AnimationController controller; double tick = 0.0; ui.Image? image; @override void initState() { super.initState(); loadImage('packages/flutter_gallery_assets/food/butternut_squash_soup.png').then((ui.Image pending) { setState(() { image = pending; }); }); controller = AnimationController(vsync: this, duration: const Duration(hours: 1)); controller.addListener(() { setState(() { tick += 1; }); }); controller.forward(from: 0); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (image == null) { return const Placeholder(); } return CustomPaint( size: const Size(500, 500), painter: VerticesPainter(tick, image!), child: Container(), ); } } class VerticesPainter extends CustomPainter { VerticesPainter(this.tick, this.image); final double tick; final ui.Image image; @override void paint(Canvas canvas, Size size) { canvas.translate(0, tick); canvas.drawAtlas( image, <RSTransform>[RSTransform.fromComponents(rotation: 0, scale: 1, anchorX: 0, anchorY: 0, translateX: 0, translateY: 0)], <Rect>[Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble())], <Color>[Colors.red], BlendMode.plus, null, Paint() ); canvas.drawAtlas( image, <RSTransform>[RSTransform.fromComponents(rotation: 0, scale: 1, anchorX: 0, anchorY: 0, translateX: 250, translateY: 0)], <Rect>[Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble())], <Color>[Colors.green], BlendMode.plus, null, Paint() ); canvas.drawAtlas( image, <RSTransform>[RSTransform.fromComponents(rotation: 0, scale: 1, anchorX: 0, anchorY: 0, translateX: 0, translateY: 250)], <Rect>[Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble())], <Color>[Colors.blue], BlendMode.plus, null, Paint() ); canvas.drawAtlas( image, <RSTransform>[RSTransform.fromComponents(rotation: 0, scale: 1, anchorX: 0, anchorY: 0, translateX: 250, translateY: 250)], <Rect>[Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble())], <Color>[Colors.yellow], BlendMode.plus, null, Paint() ); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return true; } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/draw_atlas.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/draw_atlas.dart", "repo_id": "flutter", "token_count": 1293 }
512
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:ui'; import 'package:flutter/material.dart'; class RasterCacheUseMemory extends StatefulWidget { const RasterCacheUseMemory({super.key}); @override State<RasterCacheUseMemory> createState() => _RasterCacheUseMemoryState(); } class _RasterCacheUseMemoryState extends State<RasterCacheUseMemory> with TickerProviderStateMixin { final ScrollController _controller = ScrollController(); @override void initState() { super.initState(); _controller.addListener(() { if (_controller.offset < 5) { _controller.animateTo(20, duration: const Duration(milliseconds: 1000), curve: Curves.ease); } else if (_controller.offset >= 19) { _controller.animateTo(0, duration: const Duration(milliseconds: 1000), curve: Curves.ease); } }); Timer(const Duration(milliseconds: 1000), () { _controller.animateTo(150, duration: const Duration(milliseconds: 1000), curve: Curves.ease); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.lightBlue, body: ListView( controller: _controller, children: <Widget>[ RepaintBoundary( child: ImageFiltered( imageFilter: ImageFilter.blur( sigmaX: 4, sigmaY: 4, ), child: RepaintBoundary( child: Container( width: 50, height: 50, color: Colors.red, ), ), ), ), ShaderMask( shaderCallback: (Rect bounds) { return const RadialGradient( center: Alignment.topLeft, radius: 1.0, colors: <Color>[Colors.yellow, Colors.deepOrange], tileMode: TileMode.mirror, ).createShader(bounds); }, blendMode: BlendMode.srcATop, child: Opacity( opacity: 0.5, child: Column( children: <Widget>[ ImageFiltered( imageFilter: ImageFilter.blur( sigmaX: 4, sigmaY: 4, ), child: Row( children: <Widget>[ ImageFiltered( imageFilter: ImageFilter.blur( sigmaX: 4, sigmaY: 4, ), child: RepaintBoundary( child: Container( margin: const EdgeInsets.fromLTRB(10, 5, 10, 5), decoration: BoxDecoration( color: Colors.white70, boxShadow: const <BoxShadow>[ BoxShadow( blurRadius: 5.0, ), ], borderRadius: BorderRadius.circular(5.0), ), child: const FlutterLogo( size: 50, ), ), ), ) ], ), ) ], ), ), ), const RepaintBoundary( child: FlutterLogo( size: 50, ), ), Container( height: 800, ), ], ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/raster_cache_use_memory.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/raster_cache_use_memory.dart", "repo_id": "flutter", "token_count": 2329 }
513
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'recorder.dart'; class BenchWidgetRecorder extends WidgetRecorder { BenchWidgetRecorder() : super(name: benchmarkName); static const String benchmarkName = 'bench_widget_recorder'; @override Widget createWidget() { // This is intentionally using a simple widget. The benchmark is meant to // measure the overhead of the harness, so this method should induce as // little work as possible. return const SizedBox.expand(); } } class BenchWidgetBuildRecorder extends WidgetBuildRecorder { BenchWidgetBuildRecorder() : super(name: benchmarkName); static const String benchmarkName = 'bench_widget_build_recorder'; @override Widget createWidget() { // This is intentionally using a simple widget. The benchmark is meant to // measure the overhead of the harness, so this method should induce as // little work as possible. return const SizedBox.expand(); } } class BenchRawRecorder extends RawRecorder { BenchRawRecorder() : super(name: benchmarkName); static const String benchmarkName = 'bench_raw_recorder'; @override void body(Profile profile) { profile.record('profile.record', () { // This is intentionally empty. The benchmark only measures the overhead // of the harness. }, reported: true); } } class BenchSceneBuilderRecorder extends SceneBuilderRecorder { BenchSceneBuilderRecorder() : super(name: benchmarkName); static const String benchmarkName = 'bench_scene_builder_recorder'; @override void onDrawFrame(ui.SceneBuilder sceneBuilder) { // This is intentionally empty. The benchmark only measures the overhead // of the harness. } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_harness.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_harness.dart", "repo_id": "flutter", "token_count": 537 }
514
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
flutter/dev/benchmarks/macrobenchmarks/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/macos/Runner/Configs/Debug.xcconfig", "repo_id": "flutter", "token_count": 32 }
515
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:macrobenchmarks/common.dart'; import 'util.dart'; void main() { macroPerfTestE2E( 'picture_cache_perf', kPictureCacheRouteName, pageDelay: const Duration(seconds: 1), body: (WidgetController controller) async { final Finder nestedScroll = find.byKey(const ValueKey<String>('tabbar_view')); expect(nestedScroll, findsOneWidget); Future<void> scrollOnce(double offset) async { await controller.timedDrag( nestedScroll, Offset(offset, 0.0), const Duration(milliseconds: 300), ); await Future<void>.delayed(const Duration(milliseconds: 500)); } for (int i = 0; i < 3; i += 1) { await scrollOnce(-300.0); await scrollOnce(-300.0); await scrollOnce(300.0); await scrollOnce(300.0); } }, ); }
flutter/dev/benchmarks/macrobenchmarks/test/picture_cache_perf_e2e.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/test/picture_cache_perf_e2e.dart", "repo_id": "flutter", "token_count": 437 }
516
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_driver/flutter_driver.dart'; import 'package:macrobenchmarks/common.dart'; import 'util.dart'; void main() { macroPerfTest( 'post_backdrop_filter_perf', kPostBackdropFilterRouteName, pageDelay: const Duration(seconds: 2), duration: const Duration(seconds: 10), setupOps: (FlutterDriver driver) async { final SerializableFinder backdropFilterCheckbox = find.byValueKey('bdf-checkbox'); await driver.tap(backdropFilterCheckbox); await Future<void>.delayed(const Duration(milliseconds: 500)); // BackdropFilter on await driver.tap(backdropFilterCheckbox); await Future<void>.delayed(const Duration(milliseconds: 500)); // BackdropFilter off final SerializableFinder animateButton = find.byValueKey('bdf-animate'); await driver.tap(animateButton); await Future<void>.delayed(const Duration(milliseconds: 10000)); // Now animate }, ); }
flutter/dev/benchmarks/macrobenchmarks/test_driver/post_backdrop_filter_perf_test.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/test_driver/post_backdrop_filter_perf_test.dart", "repo_id": "flutter", "token_count": 360 }
517
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/rendering.dart'; import '../common.dart'; const int _kNumIterations = 10000000; const int _kNumWarmUp = 100000; void main() { assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'."); print('MatrixUtils.transformRect and .transformPoint benchmark...'); Matrix4 makePerspective(double radius, double angle, double perspective) { return MatrixUtils.createCylindricalProjectionTransform( radius: radius, angle: angle, perspective: perspective, ); } final List<Matrix4> affineTransforms = <Matrix4>[ Matrix4.identity()..scale(1.2, 1.3, 1.0)..rotateZ(0.1), Matrix4.identity()..translate(12.0, 13.0, 10.0), Matrix4.identity()..scale(1.2, 1.3, 1.0)..translate(12.0, 13.0, 10.0), ]; final List<Matrix4> perspectiveTransforms = <Matrix4>[ makePerspective(10.0, math.pi / 8.0, 0.3), makePerspective( 8.0, math.pi / 8.0, 0.2), makePerspective( 1.0, math.pi / 4.0, 0.1)..rotateX(0.1), ]; final List<Rect> rectangles = <Rect>[ const Rect.fromLTRB(1.1, 1.2, 1.5, 1.8), const Rect.fromLTRB(1.1, 1.2, 0.0, 1.0), const Rect.fromLTRB(1.1, 1.2, 1.3, 1.0), const Rect.fromLTRB(-1.1, -1.2, 0.0, 1.0), const Rect.fromLTRB(-1.1, -1.2, -1.5, -1.8), ]; final List<Offset> offsets = <Offset>[ const Offset(1.1, 1.2), const Offset(1.5, 1.8), Offset.zero, const Offset(-1.1, -1.2), const Offset(-1.5, -1.8), ]; final int nAffine = affineTransforms.length; final int nPerspective = perspectiveTransforms.length; final int nRectangles = rectangles.length; final int nOffsets = offsets.length; // Warm up lap for (int i = 0; i < _kNumWarmUp; i += 1) { final Matrix4 transform = perspectiveTransforms[i % nPerspective]; final Rect rect = rectangles[(i ~/ nPerspective) % nRectangles]; final Offset offset = offsets[(i ~/ nPerspective) % nOffsets]; MatrixUtils.transformRect(transform, rect); MatrixUtils.transformPoint(transform, offset); } for (int i = 0; i < _kNumWarmUp; i += 1) { final Matrix4 transform = affineTransforms[i % nAffine]; final Rect rect = rectangles[(i ~/ nAffine) % nRectangles]; final Offset offset = offsets[(i ~/ nAffine) % nOffsets]; MatrixUtils.transformRect(transform, rect); MatrixUtils.transformPoint(transform, offset); } final Stopwatch watch = Stopwatch(); watch.start(); for (int i = 0; i < _kNumIterations; i += 1) { final Matrix4 transform = perspectiveTransforms[i % nPerspective]; final Rect rect = rectangles[(i ~/ nPerspective) % nRectangles]; MatrixUtils.transformRect(transform, rect); } watch.stop(); final int rectMicrosecondsPerspective = watch.elapsedMicroseconds; watch.reset(); watch.start(); for (int i = 0; i < _kNumIterations; i += 1) { final Matrix4 transform = affineTransforms[i % nAffine]; final Rect rect = rectangles[(i ~/ nAffine) % nRectangles]; MatrixUtils.transformRect(transform, rect); } watch.stop(); final int rectMicrosecondsAffine = watch.elapsedMicroseconds; watch.reset(); watch.start(); for (int i = 0; i < _kNumIterations; i += 1) { final Matrix4 transform = perspectiveTransforms[i % nPerspective]; final Offset offset = offsets[(i ~/ nPerspective) % nOffsets]; MatrixUtils.transformPoint(transform, offset); } watch.stop(); final int pointMicrosecondsPerspective = watch.elapsedMicroseconds; watch.reset(); watch.start(); for (int i = 0; i < _kNumIterations; i += 1) { final Matrix4 transform = affineTransforms[i % nAffine]; final Offset offset = offsets[(i ~/ nAffine) % nOffsets]; MatrixUtils.transformPoint(transform, offset); } watch.stop(); final int pointMicrosecondsAffine = watch.elapsedMicroseconds; final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); const double scale = 1000.0 / _kNumIterations; printer.addResult( description: 'MatrixUtils.transformRectPerspective', value: rectMicrosecondsPerspective * scale, unit: 'ns per iteration', name: 'MatrixUtils_persp_transformRect_iteration', ); printer.addResult( description: 'MatrixUtils.transformRectAffine', value: rectMicrosecondsAffine * scale, unit: 'ns per iteration', name: 'MatrixUtils_affine_transformRect_iteration', ); printer.addResult( description: 'MatrixUtils.transformPointPerspective', value: pointMicrosecondsPerspective * scale, unit: 'ns per iteration', name: 'MatrixUtils_persp_transformPoint_iteration', ); printer.addResult( description: 'MatrixUtils.transformPointAffine', value: pointMicrosecondsAffine * scale, unit: 'ns per iteration', name: 'MatrixUtils_affine_transformPoint_iteration', ); printer.printToStdout(); }
flutter/dev/benchmarks/microbenchmarks/lib/geometry/matrix_utils_transform_bench.dart/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/lib/geometry/matrix_utils_transform_bench.dart", "repo_id": "flutter", "token_count": 1819 }
518
name: microbenchmarks description: Small benchmarks for very specific parts of the Flutter framework. environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: meta: 1.12.0 flutter: sdk: flutter flutter_test: sdk: flutter stocks: path: ../test_apps/stocks test: 1.25.2 flutter_gallery_assets: 1.0.2 _fe_analyzer_shared: 67.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" analyzer: 6.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" file: 7.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http: 0.13.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" intl: 0.19.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" isolate: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" js: 0.7.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker: 10.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker_flutter_testing: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" logging: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" mime: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" test_core: 0.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vm_service: 14.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" web: 0.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" web_socket_channel: 2.4.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" flutter: uses-material-design: true assets: - money_asset_manifest.json - packages/flutter_gallery_assets/people/ali_landscape.png - packages/flutter_gallery_assets/monochrome/red-square-1024x1024.png - packages/flutter_gallery_assets/logos/flutter_white/logo.png - packages/flutter_gallery_assets/logos/fortnightly/fortnightly_logo.png - packages/flutter_gallery_assets/videos/bee.mp4 - packages/flutter_gallery_assets/videos/butterfly.mp4 - packages/flutter_gallery_assets/animated_images/animated_flutter_lgtm.gif - packages/flutter_gallery_assets/animated_images/animated_flutter_stickers.webp - packages/flutter_gallery_assets/food/butternut_squash_soup.png - packages/flutter_gallery_assets/food/cherry_pie.png - packages/flutter_gallery_assets/food/chopped_beet_leaves.png - packages/flutter_gallery_assets/food/fruits.png - packages/flutter_gallery_assets/food/pesto_pasta.png - packages/flutter_gallery_assets/food/roasted_chicken.png - packages/flutter_gallery_assets/food/spanakopita.png - packages/flutter_gallery_assets/food/spinach_onion_salad.png - packages/flutter_gallery_assets/food/icons/fish.png - packages/flutter_gallery_assets/food/icons/healthy.png - packages/flutter_gallery_assets/food/icons/main.png - packages/flutter_gallery_assets/food/icons/meat.png - packages/flutter_gallery_assets/food/icons/quick.png - packages/flutter_gallery_assets/food/icons/spicy.png - packages/flutter_gallery_assets/food/icons/veggie.png - packages/flutter_gallery_assets/logos/pesto/logo_small.png - packages/flutter_gallery_assets/places/india_chennai_flower_market.png - packages/flutter_gallery_assets/places/india_thanjavur_market.png - packages/flutter_gallery_assets/places/india_tanjore_bronze_works.png - packages/flutter_gallery_assets/places/india_tanjore_market_merchant.png - packages/flutter_gallery_assets/places/india_tanjore_thanjavur_temple.png - packages/flutter_gallery_assets/places/india_pondicherry_salt_farm.png - packages/flutter_gallery_assets/places/india_chennai_highway.png - packages/flutter_gallery_assets/places/india_chettinad_silk_maker.png - packages/flutter_gallery_assets/places/india_tanjore_thanjavur_temple_carvings.png - packages/flutter_gallery_assets/places/india_chettinad_produce.png - packages/flutter_gallery_assets/places/india_tanjore_market_technology.png - packages/flutter_gallery_assets/places/india_pondicherry_beach.png - packages/flutter_gallery_assets/places/india_pondicherry_fisherman.png - packages/flutter_gallery_assets/products/backpack.png - packages/flutter_gallery_assets/products/belt.png - packages/flutter_gallery_assets/products/cup.png - packages/flutter_gallery_assets/products/deskset.png - packages/flutter_gallery_assets/products/dress.png - packages/flutter_gallery_assets/products/earrings.png - packages/flutter_gallery_assets/products/flatwear.png - packages/flutter_gallery_assets/products/hat.png - packages/flutter_gallery_assets/products/jacket.png - packages/flutter_gallery_assets/products/jumper.png - packages/flutter_gallery_assets/products/kitchen_quattro.png - packages/flutter_gallery_assets/products/napkins.png - packages/flutter_gallery_assets/products/planters.png - packages/flutter_gallery_assets/products/platter.png - packages/flutter_gallery_assets/products/scarf.png - packages/flutter_gallery_assets/products/shirt.png - packages/flutter_gallery_assets/products/sunnies.png - packages/flutter_gallery_assets/products/sweater.png - packages/flutter_gallery_assets/products/sweats.png - packages/flutter_gallery_assets/products/table.png - packages/flutter_gallery_assets/products/teaset.png - packages/flutter_gallery_assets/products/top.png - packages/flutter_gallery_assets/people/square/ali.png - packages/flutter_gallery_assets/people/square/peter.png - packages/flutter_gallery_assets/people/square/sandra.png - packages/flutter_gallery_assets/people/square/stella.png - packages/flutter_gallery_assets/people/square/trevor.png # PUBSPEC CHECKSUM: 4934
flutter/dev/benchmarks/microbenchmarks/pubspec.yaml/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/pubspec.yaml", "repo_id": "flutter", "token_count": 3661 }
519
#Tue Sep 27 5:06 AM PST 2022 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip
flutter/dev/benchmarks/multiple_flutters/android/gradle/wrapper/gradle-wrapper.properties/0
{ "file_path": "flutter/dev/benchmarks/multiple_flutters/android/gradle/wrapper/gradle-wrapper.properties", "repo_id": "flutter", "token_count": 84 }
520
<!-- Copyright 2014 The Flutter Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <uses-permission android:name="android.permission.INTERNET"/> <application android:name="${applicationName}" android:label="platform_view_layout"> <activity android:name=".DummyPlatformViewActivity" android:launchMode="singleTop" android:exported="true" android:theme="@android:style/Theme.Black.NoTitleBar" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <meta-data android:name="flutterEmbedding" android:value="2"/> <meta-data android:name="io.flutter.embedded_views_preview" android:value="true" /> </application> </manifest>
flutter/dev/benchmarks/platform_views_layout_hybrid_composition/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/android/app/src/main/AndroidManifest.xml", "repo_id": "flutter", "token_count": 539 }
521
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_driver/driver_extension.dart'; import 'android_platform_view.dart'; void main() { enableFlutterDriverExtension(); runApp( const PlatformViewApp() ); } class PlatformViewApp extends StatefulWidget { const PlatformViewApp({ super.key }); @override PlatformViewAppState createState() => PlatformViewAppState(); } class PlatformViewAppState extends State<PlatformViewApp> { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light(), title: 'Advanced Layout', home: const PlatformViewLayout(), ); } } class PlatformViewLayout extends StatelessWidget { const PlatformViewLayout({ super.key }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Platform View Scrolling Layout')), body: ListView.builder( key: const Key('platform-views-scroll'), // This key is used by the driver test. itemCount: 200, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(5.0), child: Material( elevation: (index % 5 + 1).toDouble(), color: Colors.white, child: const Stack( children: <Widget> [ DummyPlatformView(), RotationContainer(), ], ), ), ); }, ), ); } } class DummyPlatformView extends StatelessWidget { const DummyPlatformView({super.key}); @override Widget build(BuildContext context) { const String viewType = 'benchmarks/platform_views_layout_hybrid_composition/DummyPlatformView'; late Widget nativeView; if (Platform.isIOS) { nativeView = const UiKitView( viewType: viewType, ); } else if (Platform.isAndroid) { nativeView = const AndroidPlatformView( viewType: viewType, ); } else { assert(false, 'Invalid platform'); } return Container( color: Colors.purple, height: 200.0, width: 300.0, child: nativeView, ); } } class RotationContainer extends StatefulWidget { const RotationContainer({super.key}); @override State<RotationContainer> createState() => _RotationContainerState(); } class _RotationContainerState extends State<RotationContainer> with SingleTickerProviderStateMixin { late AnimationController _rotationController; @override void initState() { super.initState(); _rotationController = AnimationController( vsync: this, duration: const Duration(seconds: 1), value: 1, ); _rotationController.repeat(); } @override void dispose() { _rotationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return RotationTransition( turns: Tween<double>(begin: 0.0, end: 1.0).animate(_rotationController), child: Container( color: Colors.purple, width: 50.0, height: 50.0, ), ); } }
flutter/dev/benchmarks/platform_views_layout_hybrid_composition/lib/main.dart/0
{ "file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/lib/main.dart", "repo_id": "flutter", "token_count": 1283 }
522
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'stock_types.dart'; class StockSettings extends StatefulWidget { const StockSettings(this.configuration, this.updater, {super.key}); final StockConfiguration configuration; final ValueChanged<StockConfiguration> updater; @override StockSettingsState createState() => StockSettingsState(); } class StockSettingsState extends State<StockSettings> { void _handleOptimismChanged(bool? value) { value ??= false; sendUpdates(widget.configuration.copyWith(stockMode: value ? StockMode.optimistic : StockMode.pessimistic)); } void _handleBackupChanged(bool value) { sendUpdates(widget.configuration.copyWith(backupMode: value ? BackupMode.enabled : BackupMode.disabled)); } void _handleShowGridChanged(bool value) { sendUpdates(widget.configuration.copyWith(debugShowGrid: value)); } void _handleShowSizesChanged(bool value) { sendUpdates(widget.configuration.copyWith(debugShowSizes: value)); } void _handleShowBaselinesChanged(bool value) { sendUpdates(widget.configuration.copyWith(debugShowBaselines: value)); } void _handleShowLayersChanged(bool value) { sendUpdates(widget.configuration.copyWith(debugShowLayers: value)); } void _handleShowPointersChanged(bool value) { sendUpdates(widget.configuration.copyWith(debugShowPointers: value)); } void _handleShowRainbowChanged(bool value) { sendUpdates(widget.configuration.copyWith(debugShowRainbow: value)); } void _handleShowPerformanceOverlayChanged(bool value) { sendUpdates(widget.configuration.copyWith(showPerformanceOverlay: value)); } void _handleShowSemanticsDebuggerChanged(bool value) { sendUpdates(widget.configuration.copyWith(showSemanticsDebugger: value)); } void _confirmOptimismChange() { switch (widget.configuration.stockMode) { case StockMode.optimistic: _handleOptimismChanged(false); case StockMode.pessimistic: showDialog<bool>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Change mode?'), content: const Text('Optimistic mode means everything is awesome. Are you sure you can handle that?'), actions: <Widget>[ TextButton( child: const Text('NO THANKS'), onPressed: () { Navigator.pop(context, false); }, ), TextButton( child: const Text('AGREE'), onPressed: () { Navigator.pop(context, true); }, ), ], ); }, ).then<void>(_handleOptimismChanged); } } void sendUpdates(StockConfiguration value) { widget.updater(value); } AppBar buildAppBar(BuildContext context) { return AppBar( title: const Text('Settings'), ); } Widget buildSettingsPane(BuildContext context) { final List<Widget> rows = <Widget>[ ListTile( leading: const Icon(Icons.thumb_up), title: const Text('Everything is awesome'), onTap: _confirmOptimismChange, trailing: Checkbox( value: widget.configuration.stockMode == StockMode.optimistic, onChanged: (bool? value) => _confirmOptimismChange(), ), ), ListTile( leading: const Icon(Icons.backup), title: const Text('Back up stock list to the cloud'), onTap: () { _handleBackupChanged(!(widget.configuration.backupMode == BackupMode.enabled)); }, trailing: Switch( value: widget.configuration.backupMode == BackupMode.enabled, onChanged: _handleBackupChanged, ), ), ListTile( leading: const Icon(Icons.picture_in_picture), title: const Text('Show rendering performance overlay'), onTap: () { _handleShowPerformanceOverlayChanged(!widget.configuration.showPerformanceOverlay); }, trailing: Switch( value: widget.configuration.showPerformanceOverlay, onChanged: _handleShowPerformanceOverlayChanged, ), ), ListTile( leading: const Icon(Icons.accessibility), title: const Text('Show semantics overlay'), onTap: () { _handleShowSemanticsDebuggerChanged(!widget.configuration.showSemanticsDebugger); }, trailing: Switch( value: widget.configuration.showSemanticsDebugger, onChanged: _handleShowSemanticsDebuggerChanged, ), ), ]; assert(() { // material grid and size construction lines are only available in debug mode rows.addAll(<Widget>[ ListTile( leading: const Icon(Icons.border_clear), title: const Text('Show material grid (for debugging)'), onTap: () { _handleShowGridChanged(!widget.configuration.debugShowGrid); }, trailing: Switch( value: widget.configuration.debugShowGrid, onChanged: _handleShowGridChanged, ), ), ListTile( leading: const Icon(Icons.border_all), title: const Text('Show construction lines (for debugging)'), onTap: () { _handleShowSizesChanged(!widget.configuration.debugShowSizes); }, trailing: Switch( value: widget.configuration.debugShowSizes, onChanged: _handleShowSizesChanged, ), ), ListTile( leading: const Icon(Icons.format_color_text), title: const Text('Show baselines (for debugging)'), onTap: () { _handleShowBaselinesChanged(!widget.configuration.debugShowBaselines); }, trailing: Switch( value: widget.configuration.debugShowBaselines, onChanged: _handleShowBaselinesChanged, ), ), ListTile( leading: const Icon(Icons.filter_none), title: const Text('Show layer boundaries (for debugging)'), onTap: () { _handleShowLayersChanged(!widget.configuration.debugShowLayers); }, trailing: Switch( value: widget.configuration.debugShowLayers, onChanged: _handleShowLayersChanged, ), ), ListTile( leading: const Icon(Icons.mouse), title: const Text('Show pointer hit-testing (for debugging)'), onTap: () { _handleShowPointersChanged(!widget.configuration.debugShowPointers); }, trailing: Switch( value: widget.configuration.debugShowPointers, onChanged: _handleShowPointersChanged, ), ), ListTile( leading: const Icon(Icons.gradient), title: const Text('Show repaint rainbow (for debugging)'), onTap: () { _handleShowRainbowChanged(!widget.configuration.debugShowRainbow); }, trailing: Switch( value: widget.configuration.debugShowRainbow, onChanged: _handleShowRainbowChanged, ), ), ]); return true; }()); return ListView( padding: const EdgeInsets.symmetric(vertical: 20.0), children: rows, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: buildAppBar(context), body: buildSettingsPane(context), ); } }
flutter/dev/benchmarks/test_apps/stocks/lib/stock_settings.dart/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/stock_settings.dart", "repo_id": "flutter", "token_count": 3039 }
523
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // To run this, from the root of the Flutter repository: // bin/cache/dart-sdk/bin/dart --enable-asserts dev/bots/analyze_snippet_code.dart // In general, please prefer using full linked examples in API docs. // // For documentation on creating sample code, see ../../examples/api/README.md // See also our style guide's discussion on documentation and sample code: // https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#documentation-dartdocs-javadocs-etc // // This tool is used to analyze smaller snippets of code in the API docs. // Such snippets are wrapped in ```dart ... ``` blocks, which may themselves // be wrapped in {@tool snippet} ... {@end-tool} blocks to set them apart // in the rendered output. // // Such snippets: // // * If they start with `import` are treated as full application samples; avoid // doing this in general, it's better to use samples as described above. (One // exception might be in dart:ui where the sample code would end up in a // different repository which would be awkward.) // // * If they start with a comment that says `// continuing from previous example...`, // they automatically import the previous test's file. // // * If they start with a comment that says `// (e.g. in a stateful widget)`, // are analyzed after being inserted into a class that inherits from State. // // * If they start with what looks like a getter, function declaration, or // other top-level keyword (`class`, `typedef`, etc), or if they start with // the keyword `final`, they are analyzed directly. // // * If they end with a trailing semicolon or have a line starting with a // statement keyword like `while` or `try`, are analyzed after being inserted // into a function body. // // * If they start with the word `static`, are placed in a class body before // analysis. // // * Otherwise, are used as an initializer for a global variable for the // purposes of analysis; in this case, any leading label (`foo:`) // and any trailing comma are removed. // // In particular, these rules imply that starting an example with `const` means // it is an _expression_, not a top-level declaration. This is because mostly // `const` indicates a Widget. // // A line that contains just a comment with an ellipsis (`// ...`) adds an ignore // for the `non_abstract_class_inherits_abstract_member` error for the snippet. // This is useful when you're writing an example that extends an abstract class // with lots of members, but you only care to show one. // // At the top of a file you can say `// Examples can assume:` and then list some // commented-out declarations that will be included in the analysis for snippets // in that file. This section may also contain explicit import statements. // // For files without an `// Examples can assume:` section or if that section // contains no explicit imports, the snippets will implicitly import all the // main Flutter packages (including material and flutter_test), as well as most // core Dart packages with the usual prefixes. // // When invoked without an additional path argument, the script will analyze // the code snippets for all packages in the "packages" subdirectory that do // not specify "nodoc: true" in their pubspec.yaml (i.e. all packages for which // we publish docs will have their doc code snippets analyzed). import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:args/args.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'package:watcher/watcher.dart'; final String _flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))); final String _packageFlutter = path.join(_flutterRoot, 'packages', 'flutter', 'lib'); final String _defaultDartUiLocation = path.join(_flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'ui'); final String _flutter = path.join(_flutterRoot, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter'); Future<void> main(List<String> arguments) async { bool asserts = false; assert(() { asserts = true; return true; }()); if (!asserts) { print('You must run this script with asserts enabled.'); exit(1); } int width; try { width = stdout.terminalColumns; } on StdoutException { width = 80; } final ArgParser argParser = ArgParser(usageLineLength: width); argParser.addOption( 'temp', valueHelp: 'path', help: 'A location where temporary files may be written. Defaults to a ' 'directory in the system temp folder. If specified, will not be ' 'automatically removed at the end of execution.', ); argParser.addFlag( 'verbose', negatable: false, help: 'Print verbose output for the analysis process.', ); argParser.addOption( 'dart-ui-location', defaultsTo: _defaultDartUiLocation, valueHelp: 'path', help: 'A location where the dart:ui dart files are to be found. Defaults to ' 'the sky_engine directory installed in this flutter repo. This ' 'is typically the engine/src/flutter/lib/ui directory in an engine dev setup. ' 'Implies --include-dart-ui.', ); argParser.addFlag( 'include-dart-ui', defaultsTo: true, help: 'Includes the dart:ui code supplied by the engine in the analysis.', ); argParser.addFlag( 'help', negatable: false, help: 'Print help for this command.', ); argParser.addOption( 'interactive', abbr: 'i', valueHelp: 'file', help: 'Analyzes the snippet code in a specified file interactively.', ); final ArgResults parsedArguments; try { parsedArguments = argParser.parse(arguments); } on FormatException catch (e) { print(e.message); print('dart --enable-asserts analyze_snippet_code.dart [options]'); print(argParser.usage); exit(1); } if (parsedArguments['help'] as bool) { print('dart --enable-asserts analyze_snippet_code.dart [options]'); print(argParser.usage); exit(0); } final List<Directory> flutterPackages; if (parsedArguments.rest.length == 1) { // Used for testing. flutterPackages = <Directory>[Directory(parsedArguments.rest.single)]; } else { // By default analyze snippets in all packages in the packages subdirectory // that do not specify "nodoc: true" in their pubspec.yaml. flutterPackages = <Directory>[]; final String packagesRoot = path.join(_flutterRoot, 'packages'); for (final FileSystemEntity entity in Directory(packagesRoot).listSync()) { if (entity is! Directory) { continue; } final File pubspec = File(path.join(entity.path, 'pubspec.yaml')); if (!pubspec.existsSync()) { throw StateError("Unexpected package '${entity.path}' found in packages directory"); } if (!pubspec.readAsStringSync().contains('nodoc: true')) { flutterPackages.add(Directory(path.join(entity.path, 'lib'))); } } assert(flutterPackages.length >= 4); } final bool includeDartUi = parsedArguments.wasParsed('dart-ui-location') || parsedArguments['include-dart-ui'] as bool; late Directory dartUiLocation; if (((parsedArguments['dart-ui-location'] ?? '') as String).isNotEmpty) { dartUiLocation = Directory( path.absolute(parsedArguments['dart-ui-location'] as String)); } else { dartUiLocation = Directory(_defaultDartUiLocation); } if (!dartUiLocation.existsSync()) { stderr.writeln('Unable to find dart:ui directory ${dartUiLocation.path}'); exit(1); } if (parsedArguments['interactive'] != null) { await _runInteractive( flutterPackages: flutterPackages, tempDirectory: parsedArguments['temp'] as String?, filePath: parsedArguments['interactive'] as String, dartUiLocation: includeDartUi ? dartUiLocation : null, ); } else { if (await _SnippetChecker( flutterPackages, tempDirectory: parsedArguments['temp'] as String?, verbose: parsedArguments['verbose'] as bool, dartUiLocation: includeDartUi ? dartUiLocation : null, ).checkSnippets()) { stderr.writeln('See the documentation at the top of dev/bots/analyze_snippet_code.dart for details.'); exit(1); } } } /// A class to represent a line of input code. @immutable class _Line { const _Line({this.code = '', this.line = -1, this.indent = 0}) : generated = false; const _Line.generated({this.code = ''}) : line = -1, indent = 0, generated = true; final int line; final int indent; final String code; final bool generated; String asLocation(String filename, int column) { return '$filename:$line:${column + indent}'; } @override String toString() => code; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is _Line && other.line == line && other.indent == indent && other.code == code && other.generated == generated; } @override int get hashCode => Object.hash(line, indent, code, generated); } @immutable class _ErrorBase implements Comparable<Object> { const _ErrorBase({this.file, this.line, this.column}); final String? file; final int? line; final int? column; @override int compareTo(Object other) { if (other is _ErrorBase) { if (other.file != file) { if (other.file == null) { return -1; } if (file == null) { return 1; } return file!.compareTo(other.file!); } if (other.line != line) { if (other.line == null) { return -1; } if (line == null) { return 1; } return line!.compareTo(other.line!); } if (other.column != column) { if (other.column == null) { return -1; } if (column == null) { return 1; } return column!.compareTo(other.column!); } } return toString().compareTo(other.toString()); } } @immutable class _SnippetCheckerException extends _ErrorBase implements Exception { const _SnippetCheckerException(this.message, {super.file, super.line}); final String message; @override String toString() { if (file != null || line != null) { final String fileStr = file == null ? '' : '$file:'; final String lineStr = line == null ? '' : '$line:'; return '$fileStr$lineStr $message'; } else { return message; } } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is _SnippetCheckerException && other.message == message && other.file == file && other.line == line; } @override int get hashCode => Object.hash(message, file, line); } /// A class representing an analysis error along with the context of the error. /// /// Changes how it converts to a string based on the source of the error. @immutable class _AnalysisError extends _ErrorBase { const _AnalysisError( String file, int line, int column, this.message, this.errorCode, this.source, ) : super(file: file, line: line, column: column); final String message; final String errorCode; final _Line source; @override String toString() { return '${source.asLocation(file!, column!)}: $message ($errorCode)'; } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is _AnalysisError && other.file == file && other.line == line && other.column == column && other.message == message && other.errorCode == errorCode && other.source == source; } @override int get hashCode => Object.hash(file, line, column, message, errorCode, source); } /// Checks code snippets for analysis errors. /// /// Extracts dartdoc content from flutter package source code, identifies code /// sections, and writes them to a temporary directory, where 'flutter analyze' /// is used to analyze the sources for problems. If problems are found, the /// error output from the analyzer is parsed for details, and the problem /// locations are translated back to the source location. class _SnippetChecker { /// Creates a [_SnippetChecker]. /// /// The positional argument is the path to the package directory for the /// flutter package within the Flutter root dir. /// /// The optional `tempDirectory` argument supplies the location for the /// temporary files to be written and analyzed. If not supplied, it defaults /// to a system generated temp directory. /// /// The optional `verbose` argument indicates whether or not status output /// should be emitted while doing the check. /// /// The optional `dartUiLocation` argument indicates the location of the /// `dart:ui` code to be analyzed along with the framework code. If not /// supplied, the default location of the `dart:ui` code in the Flutter /// repository is used (i.e. "<flutter repo>/bin/cache/pkg/sky_engine/lib/ui"). _SnippetChecker( this._flutterPackages, { String? tempDirectory, this.verbose = false, Directory? dartUiLocation, }) : _tempDirectory = _createTempDirectory(tempDirectory), _keepTmp = tempDirectory != null, _dartUiLocation = dartUiLocation; /// The prefix of each comment line static const String _dartDocPrefix = '///'; /// The prefix of each comment line with a space appended. static const String _dartDocPrefixWithSpace = '$_dartDocPrefix '; /// A RegExp that matches the beginning of a dartdoc snippet. static final RegExp _dartDocSnippetBeginRegex = RegExp(r'{@tool ([^ }]+)(?:| ([^}]*))}'); /// A RegExp that matches the end of a dartdoc snippet. static final RegExp _dartDocSnippetEndRegex = RegExp(r'{@end-tool}'); /// A RegExp that matches the start of a code block within dartdoc. static final RegExp _codeBlockStartRegex = RegExp(r'^ */// *```dart$'); /// A RegExp that matches the start of a code block within a regular comment. /// Such blocks are not analyzed. They can be used to give sample code for /// internal (private) APIs where visibility would make analyzing the sample /// code problematic. static final RegExp _uncheckedCodeBlockStartRegex = RegExp(r'^ *// *```dart$'); /// A RegExp that matches the end of a code block within dartdoc. static final RegExp _codeBlockEndRegex = RegExp(r'^ */// *``` *$'); /// A RegExp that matches a line starting with a comment or annotation static final RegExp _nonCodeRegExp = RegExp(r'^ *(//|@)'); /// A RegExp that matches things that look like a function declaration. static final RegExp _maybeFunctionDeclarationRegExp = RegExp(r'^([A-Z][A-Za-z0-9_<>, ?]*|int|double|num|bool|void)\?? (_?[a-z][A-Za-z0-9_<>]*)\(.*'); /// A RegExp that matches things that look like a getter. static final RegExp _maybeGetterDeclarationRegExp = RegExp(r'^([A-Z][A-Za-z0-9_<>?]*|int|double|num|bool)\?? get (_?[a-z][A-Za-z0-9_<>]*) (?:=>|{).*'); /// A RegExp that matches an identifier followed by a colon, potentially with two spaces of indent. static final RegExp _namedArgumentRegExp = RegExp(r'^(?: )?([a-zA-Z0-9_]+): '); /// A RegExp that matches things that look unambiguously like top-level declarations. static final RegExp _topLevelDeclarationRegExp = RegExp(r'^(abstract|class|mixin|enum|typedef|final|extension) '); /// A RegExp that matches things that look unambiguously like statements. static final RegExp _statementRegExp = RegExp(r'^(if|while|for|try) '); /// A RegExp that matches things that look unambiguously like declarations that must be in a class. static final RegExp _classDeclarationRegExp = RegExp(r'^(static) '); /// A RegExp that matches a line that ends with a comma (and maybe a comment) static final RegExp _trailingCommaRegExp = RegExp(r'^(.*),(| *//.*)$'); /// A RegExp that matches a line that ends with a semicolon (and maybe a comment) static final RegExp _trailingSemicolonRegExp = RegExp(r'^(.*);(| *//.*)$'); /// A RegExp that matches a line that ends with a closing brace (and maybe a comment) static final RegExp _trailingCloseBraceRegExp = RegExp(r'^(.*)}(| *//.*)$'); /// A RegExp that matches a line that only contains a commented-out ellipsis /// (and maybe whitespace). Has three groups: before, ellipsis, after. static final RegExp _ellipsisRegExp = RegExp(r'^( *)(// \.\.\.)( *)$'); /// Whether or not to print verbose output. final bool verbose; /// Whether or not to keep the temp directory around after running. /// /// Defaults to false. final bool _keepTmp; /// The temporary directory where all output is written. This will be deleted /// automatically if there are no errors unless _keepTmp is true. final Directory _tempDirectory; /// The package directories within the flutter root dir that will be checked. final List<Directory> _flutterPackages; /// The directory for the dart:ui code to be analyzed with the flutter code. /// /// If this is null, then no dart:ui code is included in the analysis. It /// defaults to the location inside of the flutter bin/cache directory that /// contains the dart:ui code supplied by the engine. final Directory? _dartUiLocation; static List<File> _listDartFiles(Directory directory, {bool recursive = false}) { return directory.listSync(recursive: recursive, followLinks: false).whereType<File>().where((File file) => path.extension(file.path) == '.dart').toList(); } static const List<String> ignoresDirectives = <String>[ '// ignore_for_file: directives_ordering', '// ignore_for_file: duplicate_ignore', '// ignore_for_file: no_leading_underscores_for_local_identifiers', '// ignore_for_file: prefer_final_locals', '// ignore_for_file: unnecessary_import', '// ignore_for_file: unreachable_from_main', '// ignore_for_file: unused_element', '// ignore_for_file: unused_element_parameter', '// ignore_for_file: unused_local_variable', ]; /// Computes the headers needed for each snippet file. List<_Line> get headersWithoutImports { return _headersWithoutImports ??= ignoresDirectives.map<_Line>((String code) => _Line.generated(code: code)).toList(); } List<_Line>? _headersWithoutImports; /// Computes the headers needed for each snippet file. List<_Line> get headersWithImports { return _headersWithImports ??= <String>[ ...ignoresDirectives, '// ignore_for_file: unused_import', "import 'dart:async';", "import 'dart:convert';", "import 'dart:io';", "import 'dart:math' as math;", "import 'dart:typed_data';", "import 'dart:ui' as ui;", "import 'package:flutter_test/flutter_test.dart';", for (final File file in _listDartFiles(Directory(_packageFlutter))) "import 'package:flutter/${path.basename(file.path)}';", ].map<_Line>((String code) => _Line.generated(code: code)).toList(); } List<_Line>? _headersWithImports; /// Checks all the snippets in the Dart files in [_flutterPackage] for errors. /// Returns true if any errors are found, false otherwise. Future<bool> checkSnippets() async { final Map<String, _SnippetFile> snippets = <String, _SnippetFile>{}; if (_dartUiLocation != null && !_dartUiLocation.existsSync()) { stderr.writeln('Unable to analyze engine dart snippets at ${_dartUiLocation.path}.'); } final List<File> filesToAnalyze = <File>[ for (final Directory flutterPackage in _flutterPackages) ..._listDartFiles(flutterPackage, recursive: true), if (_dartUiLocation != null && _dartUiLocation.existsSync()) ..._listDartFiles(_dartUiLocation, recursive: true), ]; final Set<Object> errors = <Object>{}; errors.addAll(await _extractSnippets(filesToAnalyze, snippetMap: snippets)); errors.addAll(_analyze(snippets)); (errors.toList()..sort()).map(_stringify).forEach(stderr.writeln); stderr.writeln('Found ${errors.length} snippet code errors.'); cleanupTempDirectory(); return errors.isNotEmpty; } static Directory _createTempDirectory(String? tempArg) { if (tempArg != null) { final Directory tempDirectory = Directory(path.join(Directory.systemTemp.absolute.path, path.basename(tempArg))); if (path.basename(tempArg) != tempArg) { stderr.writeln('Supplied temporary directory name should be a name, not a path. Using ${tempDirectory.absolute.path} instead.'); } print('Leaving temporary output in ${tempDirectory.absolute.path}.'); // Make sure that any directory left around from a previous run is cleared out. if (tempDirectory.existsSync()) { tempDirectory.deleteSync(recursive: true); } tempDirectory.createSync(); return tempDirectory; } return Directory.systemTemp.createTempSync('flutter_analyze_snippet_code.'); } void recreateTempDirectory() { _tempDirectory.deleteSync(recursive: true); _tempDirectory.createSync(); } void cleanupTempDirectory() { if (_keepTmp) { print('Leaving temporary directory ${_tempDirectory.path} around for your perusal.'); } else { try { _tempDirectory.deleteSync(recursive: true); } on FileSystemException catch (e) { stderr.writeln('Failed to delete ${_tempDirectory.path}: $e'); } } } /// Creates a name for the snippets tool to use for the snippet ID from a /// filename and starting line number. String _createNameFromSource(String prefix, String filename, int start) { String snippetId = path.split(filename).join('.'); snippetId = path.basenameWithoutExtension(snippetId); snippetId = '$prefix.$snippetId.$start'; return snippetId; } /// Extracts the snippets from the Dart files in [files], writes them /// to disk, and adds them to the [snippetMap]. Future<List<Object>> _extractSnippets( List<File> files, { required Map<String, _SnippetFile> snippetMap, }) async { final List<Object> errors = <Object>[]; _SnippetFile? lastExample; for (final File file in files) { try { final String relativeFilePath = path.relative(file.path, from: _flutterRoot); final List<String> fileLines = file.readAsLinesSync(); final List<_Line> ignorePreambleLinesOnly = <_Line>[]; final List<_Line> preambleLines = <_Line>[]; final List<_Line> customImports = <_Line>[]; bool inExamplesCanAssumePreamble = false; // Whether or not we're in the file-wide preamble section ("Examples can assume"). bool inToolSection = false; // Whether or not we're in a code snippet bool inDartSection = false; // Whether or not we're in a '```dart' segment. bool inOtherBlock = false; // Whether we're in some other '```' segment. int lineNumber = 0; final List<String> block = <String>[]; late _Line startLine; for (final String line in fileLines) { lineNumber += 1; final String trimmedLine = line.trim(); if (inExamplesCanAssumePreamble) { if (line.isEmpty) { // end of preamble inExamplesCanAssumePreamble = false; } else if (!line.startsWith('// ')) { throw _SnippetCheckerException('Unexpected content in snippet code preamble.', file: relativeFilePath, line: lineNumber); } else { final _Line newLine = _Line(line: lineNumber, indent: 3, code: line.substring(3)); if (newLine.code.startsWith('import ')) { customImports.add(newLine); } else { preambleLines.add(newLine); } if (line.startsWith('// // ignore_for_file: ')) { ignorePreambleLinesOnly.add(newLine); } } } else if (trimmedLine.startsWith(_dartDocSnippetEndRegex)) { if (!inToolSection) { throw _SnippetCheckerException('{@tool-end} marker detected without matching {@tool}.', file: relativeFilePath, line: lineNumber); } if (inDartSection) { throw _SnippetCheckerException("Dart section didn't terminate before end of snippet", file: relativeFilePath, line: lineNumber); } inToolSection = false; } else if (inDartSection) { final RegExpMatch? snippetMatch = _dartDocSnippetBeginRegex.firstMatch(trimmedLine); if (snippetMatch != null) { throw _SnippetCheckerException('{@tool} found inside Dart section', file: relativeFilePath, line: lineNumber); } if (trimmedLine.startsWith(_codeBlockEndRegex)) { inDartSection = false; final _SnippetFile snippet = _processBlock(startLine, block, preambleLines, ignorePreambleLinesOnly, relativeFilePath, lastExample, customImports); final String path = _writeSnippetFile(snippet).path; assert(!snippetMap.containsKey(path)); snippetMap[path] = snippet; block.clear(); lastExample = snippet; } else if (trimmedLine == _dartDocPrefix) { block.add(''); } else { final int index = line.indexOf(_dartDocPrefixWithSpace); if (index < 0) { throw _SnippetCheckerException( 'Dart section inexplicably did not contain "$_dartDocPrefixWithSpace" prefix.', file: relativeFilePath, line: lineNumber, ); } block.add(line.substring(index + 4)); } } else if (trimmedLine.startsWith(_codeBlockStartRegex)) { if (inOtherBlock) { throw _SnippetCheckerException( 'Found "```dart" section in another "```" section.', file: relativeFilePath, line: lineNumber, ); } assert(block.isEmpty); startLine = _Line( line: lineNumber + 1, indent: line.indexOf(_dartDocPrefixWithSpace) + _dartDocPrefixWithSpace.length, ); inDartSection = true; } else if (line.contains('```')) { if (inOtherBlock) { inOtherBlock = false; } else if (line.contains('```yaml') || line.contains('```ascii') || line.contains('```java') || line.contains('```objectivec') || line.contains('```kotlin') || line.contains('```swift') || line.contains('```glsl') || line.contains('```json') || line.contains('```csv')) { inOtherBlock = true; } else if (line.startsWith(_uncheckedCodeBlockStartRegex)) { // this is an intentionally-unchecked block that doesn't appear in the API docs. inOtherBlock = true; } else { throw _SnippetCheckerException( 'Found "```" in code but it did not match $_codeBlockStartRegex so something is wrong. Line was: "$line"', file: relativeFilePath, line: lineNumber, ); } } else if (!inToolSection) { final RegExpMatch? snippetMatch = _dartDocSnippetBeginRegex.firstMatch(trimmedLine); if (snippetMatch != null) { inToolSection = true; } else if (line == '// Examples can assume:') { if (inToolSection || inDartSection) { throw _SnippetCheckerException( '"// Examples can assume:" sections must come before all sample code.', file: relativeFilePath, line: lineNumber, ); } inExamplesCanAssumePreamble = true; } } } } on _SnippetCheckerException catch (e) { errors.add(e); } } return errors; } /// Process one block of snippet code (the part inside of "```" markers). Uses /// a primitive heuristic to make snippet blocks into valid Dart code. /// /// `block` argument will get mutated, but is copied before this function returns. _SnippetFile _processBlock(_Line startingLine, List<String> block, List<_Line> assumptions, List<_Line> ignoreAssumptionsOnly, String filename, _SnippetFile? lastExample, List<_Line> customImports) { if (block.isEmpty) { throw _SnippetCheckerException('${startingLine.asLocation(filename, 0)}: Empty ```dart block in snippet code.'); } bool hasEllipsis = false; for (int index = 0; index < block.length; index += 1) { final Match? match = _ellipsisRegExp.matchAsPrefix(block[index]); if (match != null) { hasEllipsis = true; // in case the "..." is implying some overridden members, add an ignore to silence relevant warnings break; } } bool hasStatefulWidgetComment = false; bool importPreviousExample = false; int index = startingLine.line; for (final String line in block) { if (line == '// (e.g. in a stateful widget)') { if (hasStatefulWidgetComment) { throw _SnippetCheckerException('Example says it is in a stateful widget twice.', file: filename, line: index); } hasStatefulWidgetComment = true; } else if (line == '// continuing from previous example...') { if (importPreviousExample) { throw _SnippetCheckerException('Example says it continues from the previous example twice.', file: filename, line: index); } if (lastExample == null) { throw _SnippetCheckerException('Example says it continues from the previous example but it is the first example in the file.', file: filename, line: index); } importPreviousExample = true; } else { break; } index += 1; } final List<_Line> preamble; if (importPreviousExample) { preamble = <_Line>[ ...lastExample!.code, // includes assumptions if (hasEllipsis || hasStatefulWidgetComment) const _Line.generated(code: '// ignore_for_file: non_abstract_class_inherits_abstract_member'), ]; } else { preamble = <_Line>[ if (hasEllipsis || hasStatefulWidgetComment) const _Line.generated(code: '// ignore_for_file: non_abstract_class_inherits_abstract_member'), ...assumptions, ]; } final String firstCodeLine = block.firstWhere((String line) => !line.startsWith(_nonCodeRegExp)).trim(); final String lastCodeLine = block.lastWhere((String line) => !line.startsWith(_nonCodeRegExp)).trim(); if (firstCodeLine.startsWith('import ')) { // probably an entire program if (importPreviousExample) { throw _SnippetCheckerException('An example cannot both be self-contained (with its own imports) and say it wants to import the previous example.', file: filename, line: startingLine.line); } if (hasStatefulWidgetComment) { throw _SnippetCheckerException('An example cannot both be self-contained (with its own imports) and say it is in a stateful widget.', file: filename, line: startingLine.line); } return _SnippetFile.fromStrings( startingLine, block.toList(), headersWithoutImports, <_Line>[ ...ignoreAssumptionsOnly, if (hasEllipsis) const _Line.generated(code: '// ignore_for_file: non_abstract_class_inherits_abstract_member'), ], 'self-contained program', filename, ); } final List<_Line> headers = switch ((importPreviousExample, customImports.length)) { (true, _) => <_Line>[], (false, 0) => headersWithImports, (false, _) => <_Line>[ ...headersWithoutImports, const _Line.generated(code: '// ignore_for_file: unused_import'), ...customImports, ] }; if (hasStatefulWidgetComment) { return _SnippetFile.fromStrings( startingLine, prefix: 'class _State extends State<StatefulWidget> {', block.toList(), postfix: '}', headers, preamble, 'stateful widget', filename, ); } else if (firstCodeLine.startsWith(_maybeGetterDeclarationRegExp) || (firstCodeLine.startsWith(_maybeFunctionDeclarationRegExp) && lastCodeLine.startsWith(_trailingCloseBraceRegExp)) || block.any((String line) => line.startsWith(_topLevelDeclarationRegExp))) { // probably a top-level declaration return _SnippetFile.fromStrings( startingLine, block.toList(), headers, preamble, 'top-level declaration', filename, ); } else if (lastCodeLine.startsWith(_trailingSemicolonRegExp) || block.any((String line) => line.startsWith(_statementRegExp))) { // probably a statement return _SnippetFile.fromStrings( startingLine, prefix: 'Future<void> function() async {', block.toList(), postfix: '}', headers, preamble, 'statement', filename, ); } else if (firstCodeLine.startsWith(_classDeclarationRegExp)) { // probably a static method return _SnippetFile.fromStrings( startingLine, prefix: 'class Class {', block.toList(), postfix: '}', headers, <_Line>[ ...preamble, const _Line.generated(code: '// ignore_for_file: avoid_classes_with_only_static_members'), ], 'class declaration', filename, ); } else { // probably an expression if (firstCodeLine.startsWith(_namedArgumentRegExp)) { // This is for snippets like: // // ```dart // // bla bla // foo: 2, // ``` // // This section removes the label. for (int index = 0; index < block.length; index += 1) { final Match? prefix = _namedArgumentRegExp.matchAsPrefix(block[index]); if (prefix != null) { block[index] = block[index].substring(prefix.group(0)!.length); break; } } } // strip trailing comma, if any for (int index = block.length - 1; index >= 0; index -= 1) { if (!block[index].startsWith(_nonCodeRegExp)) { final Match? lastLine = _trailingCommaRegExp.matchAsPrefix(block[index]); if (lastLine != null) { block[index] = lastLine.group(1)! + lastLine.group(2)!; } break; } } return _SnippetFile.fromStrings( startingLine, prefix: 'dynamic expression = ', block.toList(), postfix: ';', headers, preamble, 'expression', filename, ); } } /// Creates the configuration files necessary for the analyzer to consider /// the temporary directory a package, and sets which lint rules to enforce. void _createConfigurationFiles() { final File targetPubSpec = File(path.join(_tempDirectory.path, 'pubspec.yaml')); if (!targetPubSpec.existsSync()) { // Copying pubspec.yaml from examples/api into temp directory. final File sourcePubSpec = File(path.join(_flutterRoot, 'examples', 'api', 'pubspec.yaml')); if (!sourcePubSpec.existsSync()) { throw 'Cannot find pubspec.yaml at ${sourcePubSpec.path}, which is also used to analyze code snippets.'; } sourcePubSpec.copySync(targetPubSpec.path); } final File targetAnalysisOptions = File(path.join(_tempDirectory.path, 'analysis_options.yaml')); if (!targetAnalysisOptions.existsSync()) { // Use the same analysis_options.yaml configuration that's used for examples/api. final File sourceAnalysisOptions = File(path.join(_flutterRoot, 'examples', 'api', 'analysis_options.yaml')); if (!sourceAnalysisOptions.existsSync()) { throw 'Cannot find analysis_options.yaml at ${sourceAnalysisOptions.path}, which is also used to analyze code snippets.'; } targetAnalysisOptions ..createSync(recursive: true) ..writeAsStringSync('include: ${sourceAnalysisOptions.absolute.path}'); } } /// Writes out a snippet section to the disk and returns the file. File _writeSnippetFile(_SnippetFile snippetFile) { final String snippetFileId = _createNameFromSource('snippet', snippetFile.filename, snippetFile.indexLine); final File outputFile = File(path.join(_tempDirectory.path, '$snippetFileId.dart'))..createSync(recursive: true); final String contents = snippetFile.code.map<String>((_Line line) => line.code).join('\n').trimRight(); outputFile.writeAsStringSync('$contents\n'); return outputFile; } /// Starts the analysis phase of checking the snippets by invoking the analyzer /// and parsing its output. Returns the errors, if any. List<Object> _analyze(Map<String, _SnippetFile> snippets) { final List<String> analyzerOutput = _runAnalyzer(); final List<Object> errors = <Object>[]; final String kBullet = Platform.isWindows ? ' - ' : ' • '; // RegExp to match an error output line of the analyzer. final RegExp errorPattern = RegExp( '^ *(?<type>[a-z]+)' '$kBullet(?<description>.+)' '$kBullet(?<file>.+):(?<line>[0-9]+):(?<column>[0-9]+)' '$kBullet(?<code>[-a-z_]+)\$', caseSensitive: false, ); for (final String error in analyzerOutput) { final RegExpMatch? match = errorPattern.firstMatch(error); if (match == null) { errors.add(_SnippetCheckerException('Could not parse analyzer output: $error')); continue; } final String message = match.namedGroup('description')!; final File file = File(path.join(_tempDirectory.path, match.namedGroup('file'))); final List<String> fileContents = file.readAsLinesSync(); final String lineString = match.namedGroup('line')!; final String columnString = match.namedGroup('column')!; final String errorCode = match.namedGroup('code')!; final int lineNumber = int.parse(lineString, radix: 10); final int columnNumber = int.parse(columnString, radix: 10); if (lineNumber < 1 || lineNumber > fileContents.length + 1) { errors.add(_AnalysisError( file.path, lineNumber, columnNumber, message, errorCode, _Line(line: lineNumber), )); errors.add(_SnippetCheckerException('Error message points to non-existent line number: $error', file: file.path, line: lineNumber)); continue; } final _SnippetFile? snippet = snippets[file.path]; if (snippet == null) { errors.add(_SnippetCheckerException( "Unknown section for ${file.path}. Maybe the temporary directory wasn't empty?", file: file.path, line: lineNumber, )); continue; } if (fileContents.length != snippet.code.length) { errors.add(_SnippetCheckerException( 'Unexpected file contents for ${file.path}. File has ${fileContents.length} lines but we generated ${snippet.code.length} lines:\n${snippet.code.join("\n")}', file: file.path, line: lineNumber, )); continue; } late final _Line actualSource; late final int actualLine; late final int actualColumn; late final String actualMessage; int delta = 0; while (true) { // find the nearest non-generated line to the error if ((lineNumber - delta > 0) && (lineNumber - delta <= snippet.code.length) && !snippet.code[lineNumber - delta - 1].generated) { actualSource = snippet.code[lineNumber - delta - 1]; actualLine = actualSource.line; actualColumn = delta == 0 ? columnNumber : actualSource.code.length + 1; actualMessage = delta == 0 ? message : '$message -- in later generated code'; break; } if ((lineNumber + delta < snippet.code.length) && (lineNumber + delta >= 0) && !snippet.code[lineNumber + delta].generated) { actualSource = snippet.code[lineNumber + delta]; actualLine = actualSource.line; actualColumn = 1; actualMessage = '$message -- in earlier generated code'; break; } delta += 1; assert((lineNumber - delta > 0) || (lineNumber + delta < snippet.code.length)); } errors.add(_AnalysisError( snippet.filename, actualLine, actualColumn, '$actualMessage (${snippet.generatorComment})', errorCode, actualSource, )); } return errors; } /// Invokes the analyzer on the given [directory] and returns the stdout (with some lines filtered). List<String> _runAnalyzer() { _createConfigurationFiles(); // Run pub get to avoid output from getting dependencies in the analyzer // output. Process.runSync( _flutter, <String>['pub', 'get'], workingDirectory: _tempDirectory.absolute.path, ); final ProcessResult result = Process.runSync( _flutter, <String>['--no-wrap', 'analyze', '--no-preamble', '--no-congratulate', '.'], workingDirectory: _tempDirectory.absolute.path, ); final List<String> stderr = result.stderr.toString().trim().split('\n'); final List<String> stdout = result.stdout.toString().trim().split('\n'); // Remove output from building the flutter tool. stderr.removeWhere((String line) { return line.startsWith('Building flutter tool...') || line.startsWith('Waiting for another flutter command to release the startup lock...') || line.startsWith('Flutter assets will be downloaded from '); }); // Check out the stderr to see if the analyzer had it's own issues. if (stderr.isNotEmpty && stderr.first.contains(RegExp(r' issues? found\. \(ran in '))) { stderr.removeAt(0); if (stderr.isNotEmpty && stderr.last.isEmpty) { stderr.removeLast(); } } if (stderr.isNotEmpty && stderr.any((String line) => line.isNotEmpty)) { throw _SnippetCheckerException('Cannot analyze dartdocs; unexpected error output:\n$stderr'); } if (stdout.isNotEmpty && stdout.first == 'Building flutter tool...') { stdout.removeAt(0); } if (stdout.isNotEmpty && stdout.first.isEmpty) { stdout.removeAt(0); } return stdout; } } /// A class to represent a section of snippet code, marked by "```dart ... ```", that ends up /// in a file we then analyze (each snippet is in its own file). class _SnippetFile { const _SnippetFile(this.code, this.generatorComment, this.filename, this.indexLine); factory _SnippetFile.fromLines( List<_Line> code, List<_Line> headers, List<_Line> preamble, String generatorComment, String filename, ) { while (code.isNotEmpty && code.last.code.isEmpty) { code.removeLast(); } assert(code.isNotEmpty); final _Line firstLine = code.firstWhere((_Line line) => !line.generated); return _SnippetFile( <_Line>[ ...headers, const _Line.generated(), // blank line if (preamble.isNotEmpty) ...preamble, if (preamble.isNotEmpty) const _Line.generated(), // blank line _Line.generated(code: '// From: $filename:${firstLine.line}'), ...code, ], generatorComment, filename, firstLine.line, ); } factory _SnippetFile.fromStrings( _Line firstLine, List<String> code, List<_Line> headers, List<_Line> preamble, String generatorComment, String filename, { String? prefix, String? postfix, }) { final List<_Line> codeLines = <_Line>[ if (prefix != null) _Line.generated(code: prefix), for (int i = 0; i < code.length; i += 1) _Line(code: code[i], line: firstLine.line + i, indent: firstLine.indent), if (postfix != null) _Line.generated(code: postfix), ]; return _SnippetFile.fromLines(codeLines, headers, preamble, generatorComment, filename); } final List<_Line> code; final String generatorComment; final String filename; final int indexLine; } Future<void> _runInteractive({ required String? tempDirectory, required List<Directory> flutterPackages, required String filePath, required Directory? dartUiLocation, }) async { filePath = path.isAbsolute(filePath) ? filePath : path.join(path.current, filePath); final File file = File(filePath); if (!file.existsSync()) { stderr.writeln('Specified file ${file.absolute.path} does not exist or is not a file.'); exit(1); } if (!path.isWithin(_flutterRoot, file.absolute.path) && (dartUiLocation == null || !path.isWithin(dartUiLocation.path, file.absolute.path))) { stderr.writeln( 'Specified file ${file.absolute.path} is not within the flutter root: ' "$_flutterRoot${dartUiLocation != null ? ' or the dart:ui location: $dartUiLocation' : ''}" ); exit(1); } print('Starting up in interactive mode on ${path.relative(filePath, from: _flutterRoot)} ...'); print('Type "q" to quit, or "r" to force a reload.'); final _SnippetChecker checker = _SnippetChecker(flutterPackages, tempDirectory: tempDirectory) .._createConfigurationFiles(); ProcessSignal.sigint.watch().listen((_) { checker.cleanupTempDirectory(); exit(0); }); bool busy = false; Future<void> rerun() async { assert(!busy); try { busy = true; print('\nAnalyzing...'); checker.recreateTempDirectory(); final Map<String, _SnippetFile> snippets = <String, _SnippetFile>{}; final Set<Object> errors = <Object>{}; errors.addAll(await checker._extractSnippets(<File>[file], snippetMap: snippets)); errors.addAll(checker._analyze(snippets)); stderr.writeln('\u001B[2J\u001B[H'); // Clears the old results from the terminal. if (errors.isNotEmpty) { (errors.toList()..sort()).map(_stringify).forEach(stderr.writeln); stderr.writeln('Found ${errors.length} errors.'); } else { stderr.writeln('No issues found.'); } } finally { busy = false; } } await rerun(); stdin.lineMode = false; stdin.echoMode = false; stdin.transform(utf8.decoder).listen((String input) async { switch (input.trim()) { case 'q': checker.cleanupTempDirectory(); exit(0); case 'r': if (!busy) { rerun(); } } }); Watcher(file.absolute.path).events.listen((_) => rerun()); } String _stringify(Object object) => object.toString();
flutter/dev/bots/analyze_snippet_code.dart/0
{ "file_path": "flutter/dev/bots/analyze_snippet_code.dart", "repo_id": "flutter", "token_count": 17947 }
524
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:core' hide print; import 'dart:io' as io; import 'package:path/path.dart' as path; import 'utils.dart'; /// Runs the `executable` and returns standard output as a stream of lines. /// /// The returned stream reaches its end immediately after the command exits. /// /// If `expectNonZeroExit` is false and the process exits with a non-zero exit /// code fails the test immediately by exiting the test process with exit code /// 1. Stream<String> runAndGetStdout(String executable, List<String> arguments, { String? workingDirectory, Map<String, String>? environment, bool expectNonZeroExit = false, }) async* { final StreamController<String> output = StreamController<String>(); final Future<CommandResult?> command = runCommand( executable, arguments, workingDirectory: workingDirectory, environment: environment, expectNonZeroExit: expectNonZeroExit, // Capture the output so it's not printed to the console by default. outputMode: OutputMode.capture, outputListener: (String line, io.Process process) { output.add(line); }, ); // Close the stream controller after the command is complete. Otherwise, // the yield* will never finish. command.whenComplete(output.close); yield* output.stream; } /// Represents a running process launched using [startCommand]. class Command { Command._(this.process, this._time, this._savedStdout, this._savedStderr); /// The raw process that was launched for this command. final io.Process process; final Stopwatch _time; final Future<String> _savedStdout; final Future<String> _savedStderr; } /// The result of running a command using [startCommand] and [runCommand]; class CommandResult { CommandResult._(this.exitCode, this.elapsedTime, this.flattenedStdout, this.flattenedStderr); /// The exit code of the process. final int exitCode; /// The amount of time it took the process to complete. final Duration elapsedTime; /// Standard output decoded as a string using UTF8 decoder. final String? flattenedStdout; /// Standard error output decoded as a string using UTF8 decoder. final String? flattenedStderr; } /// Starts the `executable` and returns a command object representing the /// running process. /// /// `outputListener` is called for every line of standard output from the /// process, and is given the [Process] object. This can be used to interrupt /// an indefinitely running process, for example, by waiting until the process /// emits certain output. /// /// `outputMode` controls where the standard output from the command process /// goes. See [OutputMode]. Future<Command> startCommand(String executable, List<String> arguments, { String? workingDirectory, Map<String, String>? environment, OutputMode outputMode = OutputMode.print, bool Function(String)? removeLine, void Function(String, io.Process)? outputListener, }) async { final String relativeWorkingDir = path.relative(workingDirectory ?? io.Directory.current.path); final String commandDescription = '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; print('RUNNING: cd $cyan$relativeWorkingDir$reset; $green$commandDescription$reset'); final Stopwatch time = Stopwatch()..start(); print('workingDirectory: $workingDirectory, executable: $executable, arguments: $arguments'); final io.Process process = await io.Process.start(executable, arguments, workingDirectory: workingDirectory, environment: environment, ); return Command._( process, time, process.stdout .transform<String>(const Utf8Decoder()) .transform(const LineSplitter()) .where((String line) => removeLine == null || !removeLine(line)) .map<String>((String line) { final String formattedLine = '$line\n'; if (outputListener != null) { outputListener(formattedLine, process); } switch (outputMode) { case OutputMode.print: print(line); case OutputMode.capture: break; } return line; }) .join('\n'), process.stderr .transform<String>(const Utf8Decoder()) .transform(const LineSplitter()) .map<String>((String line) { switch (outputMode) { case OutputMode.print: print(line); case OutputMode.capture: break; } return line; }) .join('\n'), ); } /// Runs the `executable` and waits until the process exits. /// /// If the process exits with a non-zero exit code and `expectNonZeroExit` is /// false, calls foundError (which does not terminate execution!). /// /// `outputListener` is called for every line of standard output from the /// process, and is given the [Process] object. This can be used to interrupt /// an indefinitely running process, for example, by waiting until the process /// emits certain output. /// /// Returns the result of the finished process. /// /// `outputMode` controls where the standard output from the command process /// goes. See [OutputMode]. Future<CommandResult> runCommand(String executable, List<String> arguments, { String? workingDirectory, Map<String, String>? environment, bool expectNonZeroExit = false, int? expectedExitCode, String? failureMessage, OutputMode outputMode = OutputMode.print, bool Function(String)? removeLine, void Function(String, io.Process)? outputListener, }) async { final String commandDescription = '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; final String relativeWorkingDir = workingDirectory ?? path.relative(io.Directory.current.path); final Command command = await startCommand(executable, arguments, workingDirectory: workingDirectory, environment: environment, outputMode: outputMode, removeLine: removeLine, outputListener: outputListener, ); final CommandResult result = CommandResult._( await command.process.exitCode, command._time.elapsed, await command._savedStdout, await command._savedStderr, ); if ((result.exitCode == 0) == expectNonZeroExit || (expectedExitCode != null && result.exitCode != expectedExitCode)) { // Print the output when we get unexpected results (unless output was // printed already). switch (outputMode) { case OutputMode.print: break; case OutputMode.capture: print(result.flattenedStdout); print(result.flattenedStderr); } final String allOutput = '${result.flattenedStdout}\n${result.flattenedStderr}'; foundError(<String>[ if (failureMessage != null) failureMessage, '${bold}Command: $green$commandDescription$reset', if (failureMessage == null) '$bold${red}Command exited with exit code ${result.exitCode} but expected ${expectNonZeroExit ? (expectedExitCode ?? 'non-zero') : 'zero'} exit code.$reset', '${bold}Working directory: $cyan${path.absolute(relativeWorkingDir)}$reset', if (allOutput.isNotEmpty && allOutput.length < 512) '${bold}stdout and stderr output:\n$allOutput', ]); } else { print('ELAPSED TIME: ${prettyPrintDuration(result.elapsedTime)} for $green$commandDescription$reset in $cyan$relativeWorkingDir$reset'); } return result; } /// Specifies what to do with the command output from [runCommand] and [startCommand]. enum OutputMode { /// Forwards standard output and standard error streams to the test process' /// standard output stream (i.e. stderr is redirected to stdout). /// /// Use this mode if all you want is print the output of the command to the /// console. The output is no longer available after the process exits. print, /// Saves standard output and standard error streams in memory. /// /// Captured output can be retrieved from the [CommandResult] object. /// /// Use this mode in tests that need to inspect the output of a command, or /// when the output should not be printed to console. capture, }
flutter/dev/bots/run_command.dart/0
{ "file_path": "flutter/dev/bots/run_command.dart", "repo_id": "flutter", "token_count": 2533 }
525
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Mack class definition for testing. /// Should not be tag-enforced, no analysis failures should be found. void matchesGoldenFile(Object key) { return; }
flutter/dev/bots/test/analyze-test-input/root/packages/foo/golden_class.dart/0
{ "file_path": "flutter/dev/bots/test/analyze-test-input/root/packages/foo/golden_class.dart", "repo_id": "flutter", "token_count": 83 }
526
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import '../run_command.dart'; import '../utils.dart'; import 'common.dart'; void main() { // These tests only run on Linux. They test platform-agnostic code that is // triggered by platform-sensitive code. To avoid having to complicate our // test harness by using a mockable process manager, the tests rely on one // platform's conventions (Linux having `sh`). The logic being tested is not // so critical that it matters that we're only testing it on one platform. test('short output on runCommand failure', () async { final List<Object?> log = <String>[]; final PrintCallback oldPrint = print; print = log.add; try { await runCommand('/usr/bin/sh', <String>['-c', 'echo test; false']); expect(log, <Object>[ startsWith('RUNNING:'), 'workingDirectory: null, executable: /usr/bin/sh, arguments: [-c, echo test; false]', 'test', '╔═╡ERROR #1╞════════════════════════════════════════════════════════════════════', startsWith('║ Command: '), '║ Command exited with exit code 1 but expected zero exit code.', startsWith('║ Working directory: '), '║ stdout and stderr output:', '║ test', '║ ', '╚═══════════════════════════════════════════════════════════════════════════════' ]); } finally { print = oldPrint; resetErrorStatus(); } }, skip: !io.Platform.isLinux); // [intended] See comments above. test('long output on runCommand failure', () async { final List<Object?> log = <String>[]; final PrintCallback oldPrint = print; print = log.add; try { await runCommand('/usr/bin/sh', <String>['-c', 'echo ${"meow" * 1024}; false']); expect(log, <Object>[ startsWith('RUNNING:'), 'workingDirectory: null, executable: /usr/bin/sh, arguments: [-c, echo ${"meow" * 1024}; false]', 'meow' * 1024, '╔═╡ERROR #1╞════════════════════════════════════════════════════════════════════', startsWith('║ Command: '), '║ Command exited with exit code 1 but expected zero exit code.', startsWith('║ Working directory: '), '╚═══════════════════════════════════════════════════════════════════════════════' ]); } finally { print = oldPrint; resetErrorStatus(); } }, skip: !io.Platform.isLinux); // [intended] See comments above. }
flutter/dev/bots/test/run_command_test.dart/0
{ "file_path": "flutter/dev/bots/test/run_command_test.dart", "repo_id": "flutter", "token_count": 1024 }
527
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io' as io; import 'package:file/file.dart'; import 'package:meta/meta.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; import './git.dart'; import './globals.dart'; import './stdio.dart'; import './version.dart'; /// Allowed git remote names. enum RemoteName { upstream, mirror, } class Remote { const Remote({required RemoteName name, required this.url}) : _name = name, assert(url != ''); const Remote.mirror(String url) : this(name: RemoteName.mirror, url: url); const Remote.upstream(String url) : this(name: RemoteName.upstream, url: url); final RemoteName _name; /// The name of the remote. String get name { return switch (_name) { RemoteName.upstream => 'upstream', RemoteName.mirror => 'mirror', }; } /// The URL of the remote. final String url; } /// A source code repository. /// /// This class is an abstraction over a git /// repository on the local disk. Ideally this abstraction would hide from /// the outside libraries what git calls were needed to either read or update /// data in the underlying repository. In practice, most of the bugs in the /// conductor codebase are related to the git calls made from this and its /// subclasses. /// /// Two factors that make this code more complicated than it would otherwise /// need to be are: /// 1. That any particular invocation of the conductor may or may not already /// have the git checkout present on disk, depending on what commands were /// previously run; and /// 2. The need to provide overrides for integration tests (in particular /// the ability to mark a [Repository] instance as a [localUpstream] made /// integration tests more hermetic, at the cost of complexity in the /// implementation). /// /// The only way to simplify the first factor would be to change the behavior of /// the conductor tool to be a long-lived dart process that keeps all of its /// state in memory and blocks on user input. This would add the constraint that /// the user would need to keep the process running for the duration of a /// release, which could potentially take multiple days and users could not /// manually change the state of the release process (via editing the JSON /// config file). However, these may be reasonable trade-offs to make the /// codebase simpler and easier to reason about. /// /// The way to simplify the second factor would be to not put any special /// handling in this library for integration tests. This would make integration /// tests more difficult/less hermetic, but the production code more reliable. /// This is probably the right trade-off to make, as the integration tests were /// still not hermetic or reliable, and the main integration test was ultimately /// deleted in #84354. abstract class Repository { Repository({ required this.name, required this.upstreamRemote, required this.processManager, required this.stdio, required this.platform, required this.fileSystem, required this.parentDirectory, required this.requiredLocalBranches, this.initialRef, this.localUpstream = false, this.previousCheckoutLocation, this.mirrorRemote, }) : git = Git(processManager), assert(upstreamRemote.url.isNotEmpty); final String name; final Remote upstreamRemote; /// Branches that must exist locally in this [Repository]. /// /// If this [Repository] is used as a local upstream for another, the /// downstream may try to fetch these branches, and git will fail if they do /// not exist. final List<String> requiredLocalBranches; /// Remote for user's mirror. /// /// This value can be null, in which case attempting to access it will lead to /// a [ConductorException]. final Remote? mirrorRemote; /// The initial ref (branch or commit name) to check out. final String? initialRef; final Git git; final ProcessManager processManager; final Stdio stdio; final Platform platform; final FileSystem fileSystem; final Directory parentDirectory; /// If the repository will be used as an upstream for a test repo. final bool localUpstream; Directory? _checkoutDirectory; String? previousCheckoutLocation; /// Directory for the repository checkout. /// /// Since cloning a repository takes a long time, we do not ensure it is /// cloned on the filesystem until this getter is accessed. Future<Directory> get checkoutDirectory async { if (_checkoutDirectory != null) { return _checkoutDirectory!; } if (previousCheckoutLocation != null) { _checkoutDirectory = fileSystem.directory(previousCheckoutLocation); if (!_checkoutDirectory!.existsSync()) { throw ConductorException( 'Provided previousCheckoutLocation $previousCheckoutLocation does not exist on disk!'); } if (initialRef != null) { assert(initialRef != ''); await git.run( <String>['fetch', upstreamRemote.name], 'Fetch ${upstreamRemote.name} to ensure we have latest refs', workingDirectory: _checkoutDirectory!.path, ); // If [initialRef] is a remote ref, the checkout will be left in a detached HEAD state. await git.run( <String>['checkout', initialRef!], 'Checking out initialRef $initialRef', workingDirectory: _checkoutDirectory!.path, ); } return _checkoutDirectory!; } _checkoutDirectory = parentDirectory.childDirectory(name); await lazilyInitialize(_checkoutDirectory!); return _checkoutDirectory!; } /// RegExp pattern to parse the output of git ls-remote. /// /// Git output looks like: /// /// 35185330c6af3a435f615ee8ac2fed8b8bb7d9d4 refs/heads/95159-squash /// 6f60a1e7b2f3d2c2460c9dc20fe54d0e9654b131 refs/heads/add-debug-trace /// c1436c42c0f3f98808ae767e390c3407787f1a67 refs/heads/add-recipe-field /// 4d44dca340603e25d4918c6ef070821181202e69 refs/heads/add-release-channel /// /// We are interested in capturing what comes after 'refs/heads/'. static final RegExp _lsRemotePattern = RegExp(r'.*\s+refs\/heads\/([^\s]+)$'); /// Parse git ls-remote --heads and return branch names. Future<List<String>> listRemoteBranches(String remote) async { final String output = await git.getOutput( <String>['ls-remote', '--heads', remote], 'get remote branches', workingDirectory: (await checkoutDirectory).path, ); final List<String> remoteBranches = <String>[]; for (final String line in output.split('\n')) { final RegExpMatch? match = _lsRemotePattern.firstMatch(line); if (match != null) { remoteBranches.add(match.group(1)!); } } return remoteBranches; } /// Ensure the repository is cloned to disk and initialized with proper state. Future<void> lazilyInitialize(Directory checkoutDirectory) async { if (checkoutDirectory.existsSync()) { stdio.printTrace('Deleting $name from ${checkoutDirectory.path}...'); checkoutDirectory.deleteSync(recursive: true); } stdio.printTrace( 'Cloning $name from ${upstreamRemote.url} to ${checkoutDirectory.path}...', ); await git.run( <String>[ 'clone', '--origin', upstreamRemote.name, '--', upstreamRemote.url, checkoutDirectory.path, ], 'Cloning $name repo', workingDirectory: parentDirectory.path, ); if (mirrorRemote != null) { await git.run( <String>['remote', 'add', mirrorRemote!.name, mirrorRemote!.url], 'Adding remote ${mirrorRemote!.url} as ${mirrorRemote!.name}', workingDirectory: checkoutDirectory.path, ); await git.run( <String>['fetch', mirrorRemote!.name], 'Fetching git remote ${mirrorRemote!.name}', workingDirectory: checkoutDirectory.path, ); } if (localUpstream) { // These branches must exist locally for the repo that depends on it // to fetch and push to. for (final String channel in requiredLocalBranches) { await git.run( <String>['checkout', channel, '--'], 'check out branch $channel locally', workingDirectory: checkoutDirectory.path, ); } } if (initialRef != null) { await git.run( <String>['checkout', initialRef!], 'Checking out initialRef $initialRef', workingDirectory: checkoutDirectory.path, ); } final String revision = await reverseParse('HEAD'); stdio.printTrace( 'Repository $name is checked out at revision "$revision".', ); } /// The URL of the remote named [remoteName]. Future<String> remoteUrl(String remoteName) async { return git.getOutput( <String>['remote', 'get-url', remoteName], 'verify the URL of the $remoteName remote', workingDirectory: (await checkoutDirectory).path, ); } /// Verify the repository's git checkout is clean. Future<bool> gitCheckoutClean() async { final String output = await git.getOutput( <String>['status', '--porcelain'], 'check that the git checkout is clean', workingDirectory: (await checkoutDirectory).path, ); return output == ''; } /// Return the revision for the branch point between two refs. Future<String> branchPoint(String firstRef, String secondRef) async { return (await git.getOutput( <String>['merge-base', firstRef, secondRef], 'determine the merge base between $firstRef and $secondRef', workingDirectory: (await checkoutDirectory).path, )).trim(); } /// Fetch all branches and associated commits and tags from [remoteName]. Future<void> fetch(String remoteName) async { await git.run( <String>['fetch', remoteName, '--tags'], 'fetch $remoteName --tags', workingDirectory: (await checkoutDirectory).path, ); } /// Create (and checkout) a new branch based on the current HEAD. /// /// Runs `git checkout -b $branchName`. Future<void> newBranch(String branchName) async { await git.run( <String>['checkout', '-b', branchName], 'create & checkout new branch $branchName', workingDirectory: (await checkoutDirectory).path, ); } /// Check out the given ref. Future<void> checkout(String ref) async { await git.run( <String>['checkout', ref], 'checkout ref', workingDirectory: (await checkoutDirectory).path, ); } /// Obtain the version tag at the tip of a release branch. Future<String> getFullTag( String remoteName, String branchName, { bool exact = true, }) async { // includes both stable (e.g. 1.2.3) and dev tags (e.g. 1.2.3-4.5.pre) const String glob = '*.*.*'; // describe the latest dev release final String ref = 'refs/remotes/$remoteName/$branchName'; return git.getOutput( <String>[ 'describe', '--match', glob, if (exact) '--exact-match', '--tags', ref, ], 'obtain last released version number', workingDirectory: (await checkoutDirectory).path, ); } /// Tag [commit] and push the tag to the remote. Future<void> tag(String commit, String tagName, String remote) async { assert(commit.isNotEmpty); assert(tagName.isNotEmpty); assert(remote.isNotEmpty); stdio.printStatus('About to tag commit $commit as $tagName...'); await git.run( <String>['tag', tagName, commit], 'tag the commit with the version label', workingDirectory: (await checkoutDirectory).path, ); stdio.printStatus('Tagging successful.'); stdio.printStatus('About to push $tagName to remote $remote...'); await git.run( <String>['push', remote, tagName], 'publish the tag to the repo', workingDirectory: (await checkoutDirectory).path, ); stdio.printStatus('Tag push successful.'); } /// List commits in reverse chronological order. Future<List<String>> revList(List<String> args) async { return (await git.getOutput(<String>['rev-list', ...args], 'rev-list with args ${args.join(' ')}', workingDirectory: (await checkoutDirectory).path)) .trim() .split('\n'); } /// Look up the commit for [ref]. Future<String> reverseParse(String ref) async { final String revisionHash = await git.getOutput( <String>['rev-parse', ref], 'look up the commit for the ref $ref', workingDirectory: (await checkoutDirectory).path, ); assert(revisionHash.isNotEmpty); return revisionHash; } /// Determines if one ref is an ancestor for another. Future<bool> isAncestor(String possibleAncestor, String possibleDescendant) async { final int exitcode = await git.run( <String>[ 'merge-base', '--is-ancestor', possibleDescendant, possibleAncestor, ], 'verify $possibleAncestor is a direct ancestor of $possibleDescendant.', allowNonZeroExitCode: true, workingDirectory: (await checkoutDirectory).path, ); return exitcode == 0; } /// Determines if a given commit has a tag. Future<bool> isCommitTagged(String commit) async { final int exitcode = await git.run( <String>['describe', '--exact-match', '--tags', commit], 'verify $commit is already tagged', allowNonZeroExitCode: true, workingDirectory: (await checkoutDirectory).path, ); return exitcode == 0; } /// Resets repository HEAD to [ref]. Future<void> reset(String ref) async { await git.run( <String>['reset', ref, '--hard'], 'reset to $ref', workingDirectory: (await checkoutDirectory).path, ); } /// Push [commit] to the release channel [branch]. Future<void> pushRef({ required String fromRef, required String remote, required String toRef, bool force = false, bool dryRun = false, }) async { final List<String> args = <String>[ 'push', if (force) '--force', remote, '$fromRef:$toRef', ]; final String command = <String>[ 'git', ...args, ].join(' '); if (dryRun) { stdio.printStatus('About to execute command: `$command`'); } else { await git.run( args, 'update the release branch with the commit', workingDirectory: (await checkoutDirectory).path, ); stdio.printStatus('Executed command: `$command`'); } } Future<String> commit( String message, { bool addFirst = false, String? author, }) async { final bool hasChanges = (await git.getOutput( <String>['status', '--porcelain'], 'check for uncommitted changes', workingDirectory: (await checkoutDirectory).path, )).trim().isNotEmpty; if (!hasChanges) { throw ConductorException( 'Tried to commit with message $message but no changes were present'); } if (addFirst) { await git.run( <String>['add', '--all'], 'add all changes to the index', workingDirectory: (await checkoutDirectory).path, ); } String? authorArg; if (author != null) { if (author.contains('"')) { throw FormatException( 'Commit author cannot contain character \'"\', received $author', ); } // verify [author] matches git author convention, e.g. "Jane Doe <[email protected]>" if (!RegExp(r'.+<.*>').hasMatch(author)) { throw FormatException( 'Commit author appears malformed: "$author"', ); } authorArg = '--author="$author"'; } await git.run( <String>[ 'commit', '--message', message, if (authorArg != null) authorArg, ], 'commit changes', workingDirectory: (await checkoutDirectory).path, ); return reverseParse('HEAD'); } /// Create an empty commit and return the revision. @visibleForTesting Future<String> authorEmptyCommit([String message = 'An empty commit']) async { await git.run( <String>[ '-c', 'user.name=Conductor', '-c', '[email protected]', 'commit', '--allow-empty', '-m', "'$message'", ], 'create an empty commit', workingDirectory: (await checkoutDirectory).path, ); return reverseParse('HEAD'); } /// Create a new clone of the current repository. /// /// The returned repository will inherit all properties from this one, except /// for the upstream, which will be the path to this repository on disk. /// /// This method is for testing purposes. @visibleForTesting Future<Repository> cloneRepository(String cloneName); } class FrameworkRepository extends Repository { FrameworkRepository( this.checkouts, { super.name = 'framework', super.upstreamRemote = const Remote( name: RemoteName.upstream, url: FrameworkRepository.defaultUpstream), super.localUpstream, super.previousCheckoutLocation, String super.initialRef = FrameworkRepository.defaultBranch, super.mirrorRemote, List<String>? additionalRequiredLocalBranches, }) : super( fileSystem: checkouts.fileSystem, parentDirectory: checkouts.directory, platform: checkouts.platform, processManager: checkouts.processManager, stdio: checkouts.stdio, requiredLocalBranches: <String>[ ...?additionalRequiredLocalBranches, ...kReleaseChannels, ], ); /// A [FrameworkRepository] with the host conductor's repo set as upstream. /// /// This is useful when testing a commit that has not been merged upstream /// yet. factory FrameworkRepository.localRepoAsUpstream( Checkouts checkouts, { String name = 'framework', String? previousCheckoutLocation, String initialRef = FrameworkRepository.defaultBranch, required String upstreamPath, }) { return FrameworkRepository( checkouts, name: name, upstreamRemote: Remote( name: RemoteName.upstream, url: 'file://$upstreamPath/', ), previousCheckoutLocation: previousCheckoutLocation, initialRef: initialRef, ); } final Checkouts checkouts; static const String defaultUpstream = '[email protected]:flutter/flutter.git'; static const String defaultBranch = 'master'; Future<String> get cacheDirectory async { return fileSystem.path.join( (await checkoutDirectory).path, 'bin', 'cache', ); } @override Future<FrameworkRepository> cloneRepository(String? cloneName) async { assert(localUpstream); cloneName ??= 'clone-of-$name'; return FrameworkRepository( checkouts, name: cloneName, upstreamRemote: Remote( name: RemoteName.upstream, url: 'file://${(await checkoutDirectory).path}/'), ); } Future<void> _ensureToolReady() async { final File toolsStamp = fileSystem .directory(await cacheDirectory) .childFile('flutter_tools.stamp'); if (toolsStamp.existsSync()) { final String toolsStampHash = toolsStamp.readAsStringSync().trim(); final String repoHeadHash = await reverseParse('HEAD'); if (toolsStampHash == repoHeadHash) { return; } } stdio.printTrace('Building tool...'); // Build tool await processManager.run(<String>[ fileSystem.path.join((await checkoutDirectory).path, 'bin', 'flutter'), 'help', ]); } Future<io.ProcessResult> runFlutter(List<String> args) async { await _ensureToolReady(); return processManager.run(<String>[ fileSystem.path.join((await checkoutDirectory).path, 'bin', 'flutter'), ...args, ]); } Future<io.Process> streamFlutter( List<String> args, { void Function(String)? stdoutCallback, void Function(String)? stderrCallback, }) async { await _ensureToolReady(); final io.Process process = await processManager.start(<String>[ fileSystem.path.join((await checkoutDirectory).path, 'bin', 'flutter'), ...args, ]); process .stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen(stdoutCallback ?? stdio.printTrace); process .stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen(stderrCallback ?? stdio.printError); return process; } @override Future<void> checkout(String ref) async { await super.checkout(ref); // The tool will overwrite old cached artifacts, but not delete unused // artifacts from a previous version. Thus, delete the entire cache and // re-populate. final Directory cache = fileSystem.directory(await cacheDirectory); if (cache.existsSync()) { stdio.printTrace('Deleting cache...'); cache.deleteSync(recursive: true); } await _ensureToolReady(); } Future<Version> flutterVersion() async { // Check version final io.ProcessResult result = await runFlutter(<String>['--version', '--machine']); final Map<String, dynamic> versionJson = jsonDecode( stdoutToString(result.stdout), ) as Map<String, dynamic>; return Version.fromString(versionJson['frameworkVersion'] as String); } /// Create a release candidate branch version file. /// /// This file allows for easily traversing what candidate branch was used /// from a release channel. /// /// Returns [true] if the version file was updated and a commit is needed. Future<bool> updateCandidateBranchVersion( String branch, { @visibleForTesting File? versionFile, }) async { assert(branch.isNotEmpty); versionFile ??= (await checkoutDirectory) .childDirectory('bin') .childDirectory('internal') .childFile('release-candidate-branch.version'); if (versionFile.existsSync()) { final String oldCandidateBranch = versionFile.readAsStringSync(); if (oldCandidateBranch.trim() == branch.trim()) { stdio.printTrace( 'Tried to update the candidate branch but version file is already up to date at: $branch', ); return false; } } stdio.printStatus('Create ${versionFile.path} containing $branch'); versionFile.writeAsStringSync( // Version files have trailing newlines '${branch.trim()}\n', flush: true, ); return true; } /// Update this framework's engine version file. /// /// Returns [true] if the version file was updated and a commit is needed. Future<bool> updateEngineRevision( String newEngine, { @visibleForTesting File? engineVersionFile, }) async { assert(newEngine.isNotEmpty); engineVersionFile ??= (await checkoutDirectory) .childDirectory('bin') .childDirectory('internal') .childFile('engine.version'); assert(engineVersionFile.existsSync()); final String oldEngine = engineVersionFile.readAsStringSync(); if (oldEngine.trim() == newEngine.trim()) { stdio.printTrace( 'Tried to update the engine revision but version file is already up to date at: $newEngine', ); return false; } stdio.printStatus('Updating engine revision from $oldEngine to $newEngine'); engineVersionFile.writeAsStringSync( // Version files have trailing newlines '${newEngine.trim()}\n', flush: true, ); return true; } } /// A wrapper around the host repository that is executing the conductor. /// /// [Repository] methods that mutate the underlying repository will throw a /// [ConductorException]. class HostFrameworkRepository extends FrameworkRepository { HostFrameworkRepository({ required Checkouts checkouts, String name = 'host-framework', required String upstreamPath, }) : super( checkouts, name: name, upstreamRemote: Remote( name: RemoteName.upstream, url: 'file://$upstreamPath/', ), localUpstream: false, ) { _checkoutDirectory = checkouts.fileSystem.directory(upstreamPath); } @override Future<Directory> get checkoutDirectory async => _checkoutDirectory!; @override Future<void> newBranch(String branchName) async { throw ConductorException( 'newBranch not implemented for the host repository'); } @override Future<void> checkout(String ref) async { throw ConductorException( 'checkout not implemented for the host repository'); } @override Future<String> reset(String ref) async { throw ConductorException('reset not implemented for the host repository'); } @override Future<void> tag(String commit, String tagName, String remote) async { throw ConductorException('tag not implemented for the host repository'); } void updateChannel( String commit, String remote, String branch, { bool force = false, bool dryRun = false, }) { throw ConductorException( 'updateChannel not implemented for the host repository'); } @override Future<String> authorEmptyCommit([String message = 'An empty commit']) async { throw ConductorException( 'authorEmptyCommit not implemented for the host repository', ); } } class EngineRepository extends Repository { EngineRepository( this.checkouts, { super.name = 'engine', String super.initialRef = EngineRepository.defaultBranch, super.upstreamRemote = const Remote( name: RemoteName.upstream, url: EngineRepository.defaultUpstream), super.localUpstream, super.previousCheckoutLocation, super.mirrorRemote, List<String>? additionalRequiredLocalBranches, }) : super( fileSystem: checkouts.fileSystem, parentDirectory: checkouts.directory, platform: checkouts.platform, processManager: checkouts.processManager, stdio: checkouts.stdio, requiredLocalBranches: additionalRequiredLocalBranches ?? const <String>[], ); final Checkouts checkouts; static const String defaultUpstream = '[email protected]:flutter/engine.git'; static const String defaultBranch = 'main'; /// Update the `dart_revision` entry in the DEPS file. Future<void> updateDartRevision( String newRevision, { @visibleForTesting File? depsFile, }) async { assert(newRevision.length == 40); depsFile ??= (await checkoutDirectory).childFile('DEPS'); final String fileContent = depsFile.readAsStringSync(); final RegExp dartPattern = RegExp("[ ]+'dart_revision': '([a-z0-9]{40})',"); final Iterable<RegExpMatch> allMatches = dartPattern.allMatches(fileContent); if (allMatches.length != 1) { throw ConductorException( 'Unexpected content in the DEPS file at ${depsFile.path}\n' 'Expected to find pattern ${dartPattern.pattern} 1 times, but got ' '${allMatches.length}.'); } final String updatedFileContent = fileContent.replaceFirst( dartPattern, " 'dart_revision': '$newRevision',", ); depsFile.writeAsStringSync(updatedFileContent, flush: true); } @override Future<Repository> cloneRepository(String? cloneName) async { assert(localUpstream); cloneName ??= 'clone-of-$name'; return EngineRepository( checkouts, name: cloneName, upstreamRemote: Remote( name: RemoteName.upstream, url: 'file://${(await checkoutDirectory).path}/'), ); } } /// An enum of all the repositories that the Conductor supports. enum RepositoryType { framework, engine, } class Checkouts { Checkouts({ required this.fileSystem, required this.platform, required this.processManager, required this.stdio, required Directory parentDirectory, String directoryName = 'flutter_conductor_checkouts', }) : directory = parentDirectory.childDirectory(directoryName) { if (!directory.existsSync()) { directory.createSync(recursive: true); } } final Directory directory; final FileSystem fileSystem; final Platform platform; final ProcessManager processManager; final Stdio stdio; }
flutter/dev/conductor/core/lib/src/repository.dart/0
{ "file_path": "flutter/dev/conductor/core/lib/src/repository.dart", "repo_id": "flutter", "token_count": 10090 }
528
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:conductor_core/src/proto/conductor_state.pbenum.dart'; import 'package:conductor_core/src/version.dart'; import 'common.dart'; void main() { group('Version.fromString()', () { test('parses commits past a tagged stable', () { const String versionString = '2.8.0-1-g2ef5ad67fe'; final Version version; try { version = Version.fromString(versionString); } on Exception catch (exception) { fail('Failed parsing "$versionString" with:\n$exception'); } expect(version.x, 2); expect(version.y, 8); expect(version.z, 0); expect(version.m, isNull); expect(version.n, isNull); expect(version.commits, 1); expect(version.type, VersionType.gitDescribe); }); }); group('Version.increment()', () { test('throws exception on nonsensical `level`', () { final List<String> levels = <String>['f', '0', 'xyz']; for (final String level in levels) { final Version version = Version.fromString('1.0.0-0.0.pre'); expect( () => Version.increment(version, level).toString(), throwsExceptionWith('Unknown increment level $level.'), ); } }); test('does not support incrementing x', () { const String level = 'x'; final Version version = Version.fromString('1.0.0-0.0.pre'); expect( () => Version.increment(version, level).toString(), throwsExceptionWith( 'Incrementing $level is not supported by this tool'), ); }); test('successfully increments y', () { const String level = 'y'; Version version = Version.fromString('1.0.0-0.0.pre'); expect(Version.increment(version, level).toString(), '1.1.0-0.0.pre'); version = Version.fromString('10.20.0-40.50.pre'); expect(Version.increment(version, level).toString(), '10.21.0-0.0.pre'); version = Version.fromString('1.18.0-3.0.pre'); expect(Version.increment(version, level).toString(), '1.19.0-0.0.pre'); }); test('successfully increments z', () { const String level = 'z'; Version version = Version.fromString('1.0.0'); expect(Version.increment(version, level).toString(), '1.0.1'); version = Version.fromString('10.20.0'); expect(Version.increment(version, level).toString(), '10.20.1'); version = Version.fromString('1.18.3'); expect(Version.increment(version, level).toString(), '1.18.4'); }); test('does not support incrementing m', () { const String level = 'm'; final Version version = Version.fromString('1.0.0-0.0.pre'); expect( () => Version.increment(version, level).toString(), throwsAssertionWith("Do not increment 'm' via Version.increment"), ); }); test('successfully increments n', () { const String level = 'n'; Version version = Version.fromString('1.0.0-0.0.pre'); expect(Version.increment(version, level).toString(), '1.0.0-0.1.pre'); version = Version.fromString('10.20.0-40.50.pre'); expect(Version.increment(version, level).toString(), '10.20.0-40.51.pre'); version = Version.fromString('1.18.0-3.0.pre'); expect(Version.increment(version, level).toString(), '1.18.0-3.1.pre'); }); }, onPlatform: <String, dynamic>{ 'windows': const Skip('Flutter Conductor only supported on macos/linux'), }); group('.ensureValid()', () { test('throws when x does not match', () { const String versionString = '1.2.3-4.5.pre'; const String candidateBranch = 'flutter-3.2-candidate.4'; final Version version = Version.fromString(versionString); expect( () => version.ensureValid(candidateBranch, ReleaseType.BETA_HOTFIX), throwsExceptionWith( 'Parsed version $versionString has a different x value than ' 'candidate branch $candidateBranch', ), ); }); test('throws when y does not match', () { const String versionString = '1.2.3'; const String candidateBranch = 'flutter-1.15-candidate.4'; final Version version = Version.fromString(versionString); expect( () => version.ensureValid(candidateBranch, ReleaseType.BETA_INITIAL), throwsExceptionWith( 'Parsed version $versionString has a different y value than ' 'candidate branch $candidateBranch', ), ); }); test('throws when m does not match', () { const String versionString = '1.2.3-4.5.pre'; const String candidateBranch = 'flutter-1.2-candidate.0'; final Version version = Version.fromString(versionString); expect( () => version.ensureValid(candidateBranch, ReleaseType.BETA_HOTFIX), throwsExceptionWith( 'Parsed version $versionString has a different m value than ' 'candidate branch $candidateBranch', ), ); }); test('does not validate m if version type is stable', () { const String versionString = '1.2.0'; const String candidateBranch = 'flutter-1.2-candidate.98'; final Version version = Version.fromString(versionString); expect( () => version.ensureValid(candidateBranch, ReleaseType.STABLE_HOTFIX), isNot(throwsException), ); }); test('throws on malformed candidate branch', () { const String versionString = '1.2.0'; const String candidateBranch = 'stable'; final Version version = Version.fromString(versionString); expect( () => version.ensureValid(candidateBranch, ReleaseType.STABLE_HOTFIX), throwsExceptionWith( 'Candidate branch $candidateBranch does not match the pattern', ), ); }); }); }
flutter/dev/conductor/core/test/version_test.dart/0
{ "file_path": "flutter/dev/conductor/core/test/version_test.dart", "repo_id": "flutter", "token_count": 2323 }
529
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'dart:typed_data'; import 'package:flutter_devicelab/framework/devices.dart'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:flutter_devicelab/tasks/integration_tests.dart'; import 'package:path/path.dart' as path; import 'package:standard_message_codec/standard_message_codec.dart'; Future<void> main() async { deviceOperatingSystem = DeviceOperatingSystem.macos; await task(() async { await createFlavorsTest().call(); await createIntegrationTestFlavorsTest().call(); final String projectDir = '${flutterDirectory.path}/dev/integration_tests/flavors'; final TaskResult installTestsResult = await inDirectory( projectDir, () async { await flutter( 'install', options: <String>['--flavor', 'paid', '-d', 'macos'], ); await flutter( 'install', options: <String>['--flavor', 'paid', '--uninstall-only', '-d', 'macos'], ); final StringBuffer stderr = StringBuffer(); await evalFlutter( 'build', canFail: true, stderr: stderr, options: <String>['macos', '--flavor', 'bogus'], ); final Uint8List assetManifestFileData = File( path.join( projectDir, 'build', 'macos', 'Build', 'Products', 'Debug-paid', 'Debug Paid.app', 'Contents', 'Frameworks', 'App.framework', 'Resources', 'flutter_assets', 'AssetManifest.bin' ), ).readAsBytesSync(); final Map<Object?, Object?> assetManifest = const StandardMessageCodec() .decodeMessage(ByteData.sublistView(assetManifestFileData)) as Map<Object?, Object?>; if (assetManifest.containsKey('assets/free/free.txt')) { return TaskResult.failure('Expected the asset "assets/free/free.txt", which ' ' was declared with a flavor of "free" to not be included in the asset bundle ' ' because the --flavor was set to "paid".'); } if (!assetManifest.containsKey('assets/paid/paid.txt')) { return TaskResult.failure('Expected the asset "assets/paid/paid.txt", which ' ' was declared with a flavor of "paid" to be included in the asset bundle ' ' because the --flavor was set to "paid".'); } final String stderrString = stderr.toString(); print(stderrString); if (!stderrString.contains('The Xcode project defines schemes:')) { print(stderrString); return TaskResult.failure('Should not succeed with bogus flavor'); } return TaskResult.success(null); }, ); return installTestsResult; }); }
flutter/dev/devicelab/bin/tasks/flavors_test_macos.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/flavors_test_macos.dart", "repo_id": "flutter", "token_count": 1327 }
530
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_devicelab/framework/framework.dart'; /// Smoke test of a task that fails with an exception. Future<void> main() async { await task(() async { throw 'failed'; }); }
flutter/dev/devicelab/bin/tasks/smoke_test_throws.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/smoke_test_throws.dart", "repo_id": "flutter", "token_count": 106 }
531
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:meta/meta.dart'; import 'package:vm_service/vm_service.dart'; import 'cocoon.dart'; import 'devices.dart'; import 'task_result.dart'; import 'utils.dart'; /// Run a list of tasks. /// /// For each task, an auto rerun will be triggered when task fails. /// /// If the task succeeds the first time, it will be recorded as successful. /// /// If the task fails first, but gets passed in the end, the /// test will be recorded as successful but with a flake flag. /// /// If the task fails all reruns, it will be recorded as failed. Future<void> runTasks( List<String> taskNames, { bool exitOnFirstTestFailure = false, // terminateStrayDartProcesses defaults to false so that tests don't have to specify it. // It is set based on the --terminate-stray-dart-processes command line argument in // normal execution, and that flag defaults to true. bool terminateStrayDartProcesses = false, bool silent = false, String? deviceId, String? gitBranch, String? localEngine, String? localEngineHost, String? localEngineSrcPath, String? luciBuilder, String? resultsPath, List<String>? taskArgs, bool useEmulator = false, @visibleForTesting Map<String, String>? isolateParams, @visibleForTesting void Function(String) print = print, @visibleForTesting List<String>? logs, }) async { for (final String taskName in taskNames) { TaskResult result = TaskResult.success(null); int failureCount = 0; while (failureCount <= Cocoon.retryNumber) { result = await rerunTask( taskName, deviceId: deviceId, localEngine: localEngine, localEngineHost: localEngineHost, localEngineSrcPath: localEngineSrcPath, terminateStrayDartProcesses: terminateStrayDartProcesses, silent: silent, taskArgs: taskArgs, resultsPath: resultsPath, gitBranch: gitBranch, luciBuilder: luciBuilder, isolateParams: isolateParams, useEmulator: useEmulator, ); if (!result.succeeded) { failureCount += 1; if (exitOnFirstTestFailure) { break; } } else { section('Flaky status for "$taskName"'); if (failureCount > 0) { print('Total ${failureCount+1} executions: $failureCount failures and 1 false positive.'); print('flaky: true'); // TODO(ianh): stop ignoring this failure. We should set exitCode=1, and quit // if exitOnFirstTestFailure is true. } else { print('Test passed on first attempt.'); print('flaky: false'); } break; } } if (!result.succeeded) { section('Flaky status for "$taskName"'); print('Consistently failed across all $failureCount executions.'); print('flaky: false'); exitCode = 1; if (exitOnFirstTestFailure) { return; } } } } /// A rerun wrapper for `runTask`. /// /// This separates reruns in separate sections. Future<TaskResult> rerunTask( String taskName, { String? deviceId, String? localEngine, String? localEngineHost, String? localEngineSrcPath, bool terminateStrayDartProcesses = false, bool silent = false, List<String>? taskArgs, String? resultsPath, String? gitBranch, String? luciBuilder, bool useEmulator = false, @visibleForTesting Map<String, String>? isolateParams, }) async { section('Running task "$taskName"'); final TaskResult result = await runTask( taskName, deviceId: deviceId, localEngine: localEngine, localEngineHost: localEngineHost, localEngineSrcPath: localEngineSrcPath, terminateStrayDartProcesses: terminateStrayDartProcesses, silent: silent, taskArgs: taskArgs, isolateParams: isolateParams, useEmulator: useEmulator, ); print('Task result:'); print(const JsonEncoder.withIndent(' ').convert(result)); section('Finished task "$taskName"'); if (resultsPath != null) { final Cocoon cocoon = Cocoon(); await cocoon.writeTaskResultToFile( builderName: luciBuilder, gitBranch: gitBranch, result: result, resultsPath: resultsPath, ); } return result; } /// Runs a task in a separate Dart VM and collects the result using the VM /// service protocol. /// /// [taskName] is the name of the task. The corresponding task executable is /// expected to be found under `bin/tasks`. /// /// Running the task in [silent] mode will suppress standard output from task /// processes and only print standard errors. /// /// [taskArgs] are passed to the task executable for additional configuration. Future<TaskResult> runTask( String taskName, { bool terminateStrayDartProcesses = false, bool silent = false, String? localEngine, String? localEngineHost, String? localWebSdk, String? localEngineSrcPath, String? deviceId, List<String>? taskArgs, bool useEmulator = false, @visibleForTesting Map<String, String>? isolateParams, }) async { final String taskExecutable = 'bin/tasks/$taskName.dart'; if (!file(taskExecutable).existsSync()) { print('Executable Dart file not found: $taskExecutable'); exit(1); } if (useEmulator) { taskArgs ??= <String>[]; taskArgs ..add('--android-emulator') ..add('--browser-name=android-chrome'); } stdout.writeln('Starting process for task: [$taskName]'); final Process runner = await startProcess( dartBin, <String>[ '--disable-dart-dev', '--enable-vm-service=0', // zero causes the system to choose a free port '--no-pause-isolates-on-exit', if (localEngine != null) '-DlocalEngine=$localEngine', if (localEngineHost != null) '-DlocalEngineHost=$localEngineHost', if (localWebSdk != null) '-DlocalWebSdk=$localWebSdk', if (localEngineSrcPath != null) '-DlocalEngineSrcPath=$localEngineSrcPath', taskExecutable, ...?taskArgs, ], environment: <String, String>{ if (deviceId != null) DeviceIdEnvName: deviceId, }, ); bool runnerFinished = false; unawaited(runner.exitCode.whenComplete(() { runnerFinished = true; })); final Completer<Uri> uri = Completer<Uri>(); final StreamSubscription<String> stdoutSub = runner.stdout .transform<String>(const Utf8Decoder()) .transform<String>(const LineSplitter()) .listen((String line) { if (!uri.isCompleted) { final Uri? serviceUri = parseServiceUri(line, prefix: RegExp('The Dart VM service is listening on ')); if (serviceUri != null) { uri.complete(serviceUri); } } if (!silent) { stdout.writeln('[${DateTime.now()}] [STDOUT] $line'); } }); final StreamSubscription<String> stderrSub = runner.stderr .transform<String>(const Utf8Decoder()) .transform<String>(const LineSplitter()) .listen((String line) { stderr.writeln('[${DateTime.now()}] [STDERR] $line'); }); try { final ConnectionResult result = await _connectToRunnerIsolate(await uri.future); print('[$taskName] Connected to VM server.'); isolateParams = isolateParams == null ? <String, String>{} : Map<String, String>.of(isolateParams); isolateParams['runProcessCleanup'] = terminateStrayDartProcesses.toString(); final Map<String, dynamic> taskResultJson = (await result.vmService.callServiceExtension( 'ext.cocoonRunTask', args: isolateParams, isolateId: result.isolate.id, )).json!; final TaskResult taskResult = TaskResult.fromJson(taskResultJson); final int exitCode = await runner.exitCode; print('[$taskName] Process terminated with exit code $exitCode.'); return taskResult; } catch (error, stack) { print('[$taskName] Task runner system failed with exception!\n$error\n$stack'); rethrow; } finally { if (!runnerFinished) { print('[$taskName] Terminating process...'); runner.kill(ProcessSignal.sigkill); } await stdoutSub.cancel(); await stderrSub.cancel(); } } Future<ConnectionResult> _connectToRunnerIsolate(Uri vmServiceUri) async { final List<String> pathSegments = <String>[ // Add authentication code. if (vmServiceUri.pathSegments.isNotEmpty) vmServiceUri.pathSegments[0], 'ws', ]; final String url = vmServiceUri.replace(scheme: 'ws', pathSegments: pathSegments).toString(); final Stopwatch stopwatch = Stopwatch()..start(); while (true) { try { // Make sure VM server is up by successfully opening and closing a socket. await (await WebSocket.connect(url)).close(); // Look up the isolate. final VmService client = await vmServiceConnectUri(url); VM vm = await client.getVM(); while (vm.isolates!.isEmpty) { await Future<void>.delayed(const Duration(seconds: 1)); vm = await client.getVM(); } final IsolateRef isolate = vm.isolates!.first; final Response response = await client.callServiceExtension('ext.cocoonRunnerReady', isolateId: isolate.id); if (response.json!['response'] != 'ready') { throw 'not ready yet'; } return ConnectionResult(client, isolate); } catch (error) { if (stopwatch.elapsed > const Duration(seconds: 10)) { print( 'VM service still not ready. It is possible the target has failed.\n' 'Latest connection error:\n' ' $error\n' 'Continuing to retry...\n', ); stopwatch.reset(); } await Future<void>.delayed(const Duration(milliseconds: 50)); } } } class ConnectionResult { ConnectionResult(this.vmService, this.isolate); final VmService vmService; final IsolateRef isolate; } /// The cocoon client sends an invalid VM service response, we need to intercept it. Future<VmService> vmServiceConnectUri(String wsUri, {Log? log}) async { final WebSocket socket = await WebSocket.connect(wsUri); final StreamController<dynamic> controller = StreamController<dynamic>(); final Completer<dynamic> streamClosedCompleter = Completer<dynamic>(); socket.listen( (dynamic data) { final Map<String, dynamic> rawData = json.decode(data as String) as Map<String, dynamic> ; if (rawData['result'] == 'ready') { rawData['result'] = <String, dynamic>{'response': 'ready'}; controller.add(json.encode(rawData)); } else { controller.add(data); } }, onError: (Object err, StackTrace stackTrace) => controller.addError(err, stackTrace), onDone: () => streamClosedCompleter.complete(), ); return VmService( controller.stream, (String message) => socket.add(message), log: log, disposeHandler: () => socket.close(), streamClosed: streamClosedCompleter.future, ); }
flutter/dev/devicelab/lib/framework/runner.dart/0
{ "file_path": "flutter/dev/devicelab/lib/framework/runner.dart", "repo_id": "flutter", "token_count": 3976 }
532
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as path; import 'package:process/process.dart'; import '../framework/devices.dart'; import '../framework/framework.dart'; import '../framework/running_processes.dart'; import '../framework/task_result.dart'; import '../framework/utils.dart'; final Directory _editedFlutterGalleryDir = dir(path.join(Directory.systemTemp.path, 'edited_flutter_gallery')); final Directory flutterGalleryDir = dir(path.join(flutterDirectory.path, 'dev/integration_tests/flutter_gallery')); const String kSourceLine = 'fontSize: (orientation == Orientation.portrait) ? 32.0 : 24.0'; const String kReplacementLine = 'fontSize: (orientation == Orientation.portrait) ? 34.0 : 24.0'; TaskFunction createHotModeTest({ String? deviceIdOverride, bool checkAppRunningOnLocalDevice = false, List<String>? additionalOptions, }) { // This file is modified during the test and needs to be restored at the end. final File flutterFrameworkSource = file(path.join( flutterDirectory.path, 'packages/flutter/lib/src/widgets/framework.dart', )); final String oldContents = flutterFrameworkSource.readAsStringSync(); return () async { if (deviceIdOverride == null) { final Device device = await devices.workingDevice; await device.unlock(); deviceIdOverride = device.deviceId; } final File benchmarkFile = file(path.join(_editedFlutterGalleryDir.path, 'hot_benchmark.json')); rm(benchmarkFile); final List<String> options = <String>[ '--hot', '-d', deviceIdOverride!, '--benchmark', '--resident', '--no-android-gradle-daemon', '--no-publish-port', '--verbose', '--uninstall-first', if (additionalOptions != null) ...additionalOptions, ]; int hotReloadCount = 0; late Map<String, dynamic> smallReloadData; late Map<String, dynamic> mediumReloadData; late Map<String, dynamic> largeReloadData; late Map<String, dynamic> freshRestartReloadsData; await inDirectory<void>(flutterDirectory, () async { rmTree(_editedFlutterGalleryDir); mkdirs(_editedFlutterGalleryDir); recursiveCopy(flutterGalleryDir, _editedFlutterGalleryDir); try { await inDirectory<void>(_editedFlutterGalleryDir, () async { smallReloadData = await captureReloadData( options: options, benchmarkFile: benchmarkFile, onLine: (String line, Process process) { if (!line.contains('Reloaded ')) { return; } if (hotReloadCount == 0) { // Update a file for 2 library invalidation. final File appDartSource = file(path.join( _editedFlutterGalleryDir.path, 'lib/gallery/app.dart', )); appDartSource.writeAsStringSync(appDartSource.readAsStringSync().replaceFirst( "'Flutter Gallery'", "'Updated Flutter Gallery'", )); process.stdin.writeln('r'); hotReloadCount += 1; } else { process.stdin.writeln('q'); } }, ); mediumReloadData = await captureReloadData( options: options, benchmarkFile: benchmarkFile, onLine: (String line, Process process) { if (!line.contains('Reloaded ')) { return; } if (hotReloadCount == 1) { // Update a file for ~50 library invalidation. final File appDartSource = file(path.join( _editedFlutterGalleryDir.path, 'lib/demo/calculator/home.dart', )); appDartSource.writeAsStringSync( appDartSource.readAsStringSync().replaceFirst(kSourceLine, kReplacementLine) ); process.stdin.writeln('r'); hotReloadCount += 1; } else { process.stdin.writeln('q'); } }, ); largeReloadData = await captureReloadData( options: options, benchmarkFile: benchmarkFile, onLine: (String line, Process process) async { if (!line.contains('Reloaded ')) { return; } if (hotReloadCount == 2) { // Trigger a framework invalidation (370 libraries) without modifying the source flutterFrameworkSource.writeAsStringSync( '${flutterFrameworkSource.readAsStringSync()}\n' ); process.stdin.writeln('r'); hotReloadCount += 1; } else { if (checkAppRunningOnLocalDevice) { await _checkAppRunning(true); } process.stdin.writeln('q'); } }, ); // Start `flutter run` again to make sure it loads from the previous // state. Frontend loads up from previously generated kernel files. { final Process process = await startFlutter( 'run', options: options, ); final Completer<void> stdoutDone = Completer<void>(); final Completer<void> stderrDone = Completer<void>(); process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { if (line.contains('Reloaded ')) { process.stdin.writeln('q'); } print('stdout: $line'); }, onDone: () { stdoutDone.complete(); }); process.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { print('stderr: $line'); }, onDone: () { stderrDone.complete(); }); await Future.wait<void>( <Future<void>>[stdoutDone.future, stderrDone.future]); await process.exitCode; freshRestartReloadsData = json.decode(benchmarkFile.readAsStringSync()) as Map<String, dynamic>; } }); if (checkAppRunningOnLocalDevice) { await _checkAppRunning(false); } } finally { flutterFrameworkSource.writeAsStringSync(oldContents); } }); return TaskResult.success( <String, dynamic> { // ignore: avoid_dynamic_calls 'hotReloadInitialDevFSSyncMilliseconds': smallReloadData['hotReloadInitialDevFSSyncMilliseconds'][0], // ignore: avoid_dynamic_calls 'hotRestartMillisecondsToFrame': smallReloadData['hotRestartMillisecondsToFrame'][0], // ignore: avoid_dynamic_calls 'hotReloadMillisecondsToFrame' : smallReloadData['hotReloadMillisecondsToFrame'][0], // ignore: avoid_dynamic_calls 'hotReloadDevFSSyncMilliseconds': smallReloadData['hotReloadDevFSSyncMilliseconds'][0], // ignore: avoid_dynamic_calls 'hotReloadFlutterReassembleMilliseconds': smallReloadData['hotReloadFlutterReassembleMilliseconds'][0], // ignore: avoid_dynamic_calls 'hotReloadVMReloadMilliseconds': smallReloadData['hotReloadVMReloadMilliseconds'][0], // ignore: avoid_dynamic_calls 'hotReloadMillisecondsToFrameAfterChange' : smallReloadData['hotReloadMillisecondsToFrame'][1], // ignore: avoid_dynamic_calls 'hotReloadDevFSSyncMillisecondsAfterChange': smallReloadData['hotReloadDevFSSyncMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadFlutterReassembleMillisecondsAfterChange': smallReloadData['hotReloadFlutterReassembleMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadVMReloadMillisecondsAfterChange': smallReloadData['hotReloadVMReloadMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadInitialDevFSSyncAfterRelaunchMilliseconds' : freshRestartReloadsData['hotReloadInitialDevFSSyncMilliseconds'][0], // ignore: avoid_dynamic_calls 'hotReloadMillisecondsToFrameAfterMediumChange' : mediumReloadData['hotReloadMillisecondsToFrame'][1], // ignore: avoid_dynamic_calls 'hotReloadDevFSSyncMillisecondsAfterMediumChange': mediumReloadData['hotReloadDevFSSyncMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadFlutterReassembleMillisecondsAfterMediumChange': mediumReloadData['hotReloadFlutterReassembleMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadVMReloadMillisecondsAfterMediumChange': mediumReloadData['hotReloadVMReloadMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadMillisecondsToFrameAfterLargeChange' : largeReloadData['hotReloadMillisecondsToFrame'][1], // ignore: avoid_dynamic_calls 'hotReloadDevFSSyncMillisecondsAfterLargeChange': largeReloadData['hotReloadDevFSSyncMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadFlutterReassembleMillisecondsAfterLargeChange': largeReloadData['hotReloadFlutterReassembleMilliseconds'][1], // ignore: avoid_dynamic_calls 'hotReloadVMReloadMillisecondsAfterLargeChange': largeReloadData['hotReloadVMReloadMilliseconds'][1], }, benchmarkScoreKeys: <String>[ 'hotReloadInitialDevFSSyncMilliseconds', 'hotRestartMillisecondsToFrame', 'hotReloadMillisecondsToFrame', 'hotReloadDevFSSyncMilliseconds', 'hotReloadFlutterReassembleMilliseconds', 'hotReloadVMReloadMilliseconds', 'hotReloadMillisecondsToFrameAfterChange', 'hotReloadDevFSSyncMillisecondsAfterChange', 'hotReloadFlutterReassembleMillisecondsAfterChange', 'hotReloadVMReloadMillisecondsAfterChange', 'hotReloadInitialDevFSSyncAfterRelaunchMilliseconds', 'hotReloadMillisecondsToFrameAfterMediumChange', 'hotReloadDevFSSyncMillisecondsAfterMediumChange', 'hotReloadFlutterReassembleMillisecondsAfterMediumChange', 'hotReloadVMReloadMillisecondsAfterMediumChange', 'hotReloadMillisecondsToFrameAfterLargeChange', 'hotReloadDevFSSyncMillisecondsAfterLargeChange', 'hotReloadFlutterReassembleMillisecondsAfterLargeChange', 'hotReloadVMReloadMillisecondsAfterLargeChange', ], ); }; } Future<Map<String, dynamic>> captureReloadData({ required List<String> options, required File benchmarkFile, required void Function(String, Process) onLine, }) async { final Process process = await startFlutter( 'run', options: options, ); final Completer<void> stdoutDone = Completer<void>(); final Completer<void> stderrDone = Completer<void>(); process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { onLine(line, process); print('stdout: $line'); }, onDone: stdoutDone.complete); process.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen( (String line) => print('stderr: $line'), onDone: stderrDone.complete, ); await Future.wait<void>(<Future<void>>[stdoutDone.future, stderrDone.future]); await process.exitCode; final Map<String, dynamic> result = json.decode(benchmarkFile.readAsStringSync()) as Map<String, dynamic>; benchmarkFile.deleteSync(); return result; } Future<void> _checkAppRunning(bool shouldBeRunning) async { late Set<RunningProcessInfo> galleryProcesses; for (int i = 0; i < 10; i++) { final String exe = Platform.isWindows ? '.exe' : ''; galleryProcesses = await getRunningProcesses( processName: 'Flutter Gallery$exe', processManager: const LocalProcessManager(), ); if (galleryProcesses.isNotEmpty == shouldBeRunning) { return; } // Give the app time to shut down. sleep(const Duration(seconds: 1)); } print(galleryProcesses.join('\n')); throw TaskResult.failure('Flutter Gallery app is ${shouldBeRunning ? 'not' : 'still'} running'); }
flutter/dev/devicelab/lib/tasks/hot_mode_tests.dart/0
{ "file_path": "flutter/dev/devicelab/lib/tasks/hot_mode_tests.dart", "repo_id": "flutter", "token_count": 5330 }
533
<!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f) })(window,document,'script','dataLayer','GTM-ND4LWWZ');</script> <!-- End Google Tag Manager -->
flutter/dev/docs/analytics-header.html/0
{ "file_path": "flutter/dev/docs/analytics-header.html", "repo_id": "flutter", "token_count": 184 }
534
org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true android.enableJetifier=true flutter.hostAppProjectName=SampleApp
flutter/dev/integration_tests/android_custom_host_app/gradle.properties/0
{ "file_path": "flutter/dev/integration_tests/android_custom_host_app/gradle.properties", "repo_id": "flutter", "token_count": 65 }
535
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'text_field_constants.dart'; export 'text_field_constants.dart'; /// A page with a normal text field and a password field. class TextFieldPage extends StatefulWidget { const TextFieldPage({super.key}); @override State<StatefulWidget> createState() => _TextFieldPageState(); } class _TextFieldPageState extends State<TextFieldPage> { final TextEditingController _normalController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); final Key backButtonKey = const ValueKey<String>(backButtonKeyValue); final Key normalTextFieldKey = const ValueKey<String>(normalTextFieldKeyValue); final Key passwordTextFieldKey = const ValueKey<String>(passwordTextFieldKeyValue); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(leading: BackButton(key: backButtonKey)), body: Material( child: Column(children: <Widget>[ TextField( key: normalTextFieldKey, controller: _normalController, ), const Spacer(), TextField( key: passwordTextFieldKey, controller: _passwordController, obscureText: true, ), ], ), )); } }
flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/text_field_page.dart/0
{ "file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/text_field_page.dart", "repo_id": "flutter", "token_count": 507 }
536
# ============================================================================== # The contents of this file are automatically generated and it is not # recommended to modify this file manually. # ============================================================================== # # In order to prevent unexpected splitting of deferred apps, this file records # the last generated set of loading units. It only possible to obtain the final # configuration of loading units after compilation is complete. This means # improperly setup deferred imports can only be detected after compilation. # # This file allows the build tool to detect any changes in the generated # loading units. During the next build attempt, loading units in this file are # compared against the newly generated loading units to check for any new or # removed loading units. In the case where loading units do not match, the build # will fail and ask the developer to verify that the `deferred-components` # configuration in `pubspec.yaml` is correct. Developers should make any # necessary changes to integrate new and changed loading units or remove no # longer existing loading units from the configuration. The build command should # then be re-run to continue the build process. # # Sometimes, changes to the generated loading units may be unintentional. If # the list of loading units in this file is not what is expected, the app's # deferred imports should be reviewed. Third party plugins and packages may # also introduce deferred imports that result in unexpected loading units. loading-units: - id: 2 libraries: - package:deferred_components_test/component1.dart
flutter/dev/integration_tests/deferred_components_test/deferred_components_loading_units.yaml/0
{ "file_path": "flutter/dev/integration_tests/deferred_components_test/deferred_components_loading_units.yaml", "repo_id": "flutter", "token_count": 340 }
537
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_driver/driver_extension.dart'; void main() { enableFlutterDriverExtension(); debugPrint('Application starting...'); runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => MyAppState(); } const MethodChannel channel = MethodChannel('texture'); enum FrameState { initial, slow, afterSlow, fast, afterFast } class MyAppState extends State<MyApp> with SingleTickerProviderStateMixin { int _widgetBuilds = 0; FrameState _state = FrameState.initial; String _summary = ''; IconData? _icon; double _flutterFrameRate = 0; Future<void> _summarizeStats() async { final double? framesProduced = await channel.invokeMethod('getProducedFrameRate'); final double? framesConsumed = await channel.invokeMethod('getConsumedFrameRate'); _summary = ''' Produced: ${framesProduced?.toStringAsFixed(1)}fps Consumed: ${framesConsumed?.toStringAsFixed(1)}fps Widget builds: $_widgetBuilds'''; } Future<void> _nextState() async { switch (_state) { case FrameState.initial: debugPrint('Starting .5x speed test...'); _widgetBuilds = 0; _summary = 'Producing texture frames at .5x speed...'; _state = FrameState.slow; _icon = Icons.stop; channel.invokeMethod<void>('start', _flutterFrameRate ~/ 2); case FrameState.slow: debugPrint('Stopping .5x speed test...'); await channel.invokeMethod<void>('stop'); await _summarizeStats(); _icon = Icons.fast_forward; _state = FrameState.afterSlow; case FrameState.afterSlow: debugPrint('Starting 2x speed test...'); _widgetBuilds = 0; _summary = 'Producing texture frames at 2x speed...'; _state = FrameState.fast; _icon = Icons.stop; channel.invokeMethod<void>('start', (_flutterFrameRate * 2).toInt()); case FrameState.fast: debugPrint('Stopping 2x speed test...'); await channel.invokeMethod<void>('stop'); await _summarizeStats(); _state = FrameState.afterFast; _icon = Icons.replay; case FrameState.afterFast: debugPrint('Test complete.'); _summary = 'Press play to start again'; _state = FrameState.initial; _icon = Icons.play_arrow; } setState(() {}); } @override void initState() { super.initState(); _calibrate(); } static const int calibrationTickCount = 600; /// Measures Flutter's frame rate. Future<void> _calibrate() async { debugPrint('Awaiting calm (3 second pause)...'); await Future<void>.delayed(const Duration(milliseconds: 3000)); debugPrint('Calibrating...'); late DateTime startTime; int tickCount = 0; Ticker? ticker; ticker = createTicker((Duration time) { tickCount += 1; if (tickCount == calibrationTickCount) { // about 10 seconds final Duration elapsed = DateTime.now().difference(startTime); ticker?.stop(); ticker?.dispose(); setState(() { _flutterFrameRate = tickCount * 1000 / elapsed.inMilliseconds; debugPrint('Calibrated: frame rate ${_flutterFrameRate.toStringAsFixed(1)}fps.'); _summary = ''' Flutter frame rate is ${_flutterFrameRate.toStringAsFixed(1)}fps. Press play to produce texture frames.'''; _icon = Icons.play_arrow; _state = FrameState.initial; }); } else { if ((tickCount % (calibrationTickCount ~/ 20)) == 0) { debugPrint('Calibrating... ${(100.0 * tickCount / calibrationTickCount).floor()}%'); } } }); ticker.start(); startTime = DateTime.now(); setState(() { _summary = 'Calibrating...'; _icon = null; }); } @override Widget build(BuildContext context) { _widgetBuilds += 1; return MaterialApp( home: Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const SizedBox( width: 300.0, height: 200.0, child: Texture(textureId: 0), ), Container( width: 300.0, height: 60.0, color: Colors.grey, child: Center( child: Text( _summary, key: const ValueKey<String>('summary'), ), ), ), ], ), ), floatingActionButton: _icon == null ? null : FloatingActionButton( key: const ValueKey<String>('fab'), onPressed: _nextState, child: Icon(_icon), ), ), ); } }
flutter/dev/integration_tests/external_textures/lib/frame_rate_main.dart/0
{ "file_path": "flutter/dev/integration_tests/external_textures/lib/frame_rate_main.dart", "repo_id": "flutter", "token_count": 2135 }
538
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. export 'cupertino_activity_indicator_demo.dart'; export 'cupertino_alert_demo.dart'; export 'cupertino_buttons_demo.dart'; export 'cupertino_navigation_demo.dart'; export 'cupertino_picker_demo.dart'; export 'cupertino_refresh_demo.dart'; export 'cupertino_segmented_control_demo.dart'; export 'cupertino_slider_demo.dart'; export 'cupertino_switch_demo.dart'; export 'cupertino_text_field_demo.dart';
flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino.dart", "repo_id": "flutter", "token_count": 206 }
539
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../gallery/demo.dart'; class BottomAppBarDemo extends StatefulWidget { const BottomAppBarDemo({super.key}); static const String routeName = '/material/bottom_app_bar'; @override State createState() => _BottomAppBarDemoState(); } // Flutter generally frowns upon abbreviation however this class uses two // abbreviations extensively: "fab" for floating action button, and "bab" // for bottom application bar. class _BottomAppBarDemoState extends State<BottomAppBarDemo> { static final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>(); // FAB shape static const _ChoiceValue<Widget> kNoFab = _ChoiceValue<Widget>( title: 'None', label: 'do not show a floating action button', ); static const _ChoiceValue<Widget> kCircularFab = _ChoiceValue<Widget>( title: 'Circular', label: 'circular floating action button', value: FloatingActionButton( onPressed: _showSnackbar, backgroundColor: Colors.orange, child: Icon(Icons.add, semanticLabel: 'Action'), ), ); static const _ChoiceValue<Widget> kDiamondFab = _ChoiceValue<Widget>( title: 'Diamond', label: 'diamond shape floating action button', value: _DiamondFab( onPressed: _showSnackbar, child: Icon(Icons.add, semanticLabel: 'Action'), ), ); // Notch static const _ChoiceValue<bool> kShowNotchTrue = _ChoiceValue<bool>( title: 'On', label: 'show bottom appbar notch', value: true, ); static const _ChoiceValue<bool> kShowNotchFalse = _ChoiceValue<bool>( title: 'Off', label: 'do not show bottom appbar notch', value: false, ); // FAB Position static const _ChoiceValue<FloatingActionButtonLocation> kFabEndDocked = _ChoiceValue<FloatingActionButtonLocation>( title: 'Attached - End', label: 'floating action button is docked at the end of the bottom app bar', value: FloatingActionButtonLocation.endDocked, ); static const _ChoiceValue<FloatingActionButtonLocation> kFabCenterDocked = _ChoiceValue<FloatingActionButtonLocation>( title: 'Attached - Center', label: 'floating action button is docked at the center of the bottom app bar', value: FloatingActionButtonLocation.centerDocked, ); static const _ChoiceValue<FloatingActionButtonLocation> kFabEndFloat= _ChoiceValue<FloatingActionButtonLocation>( title: 'Free - End', label: 'floating action button floats above the end of the bottom app bar', value: FloatingActionButtonLocation.endFloat, ); static const _ChoiceValue<FloatingActionButtonLocation> kFabCenterFloat = _ChoiceValue<FloatingActionButtonLocation>( title: 'Free - Center', label: 'floating action button is floats above the center of the bottom app bar', value: FloatingActionButtonLocation.centerFloat, ); static void _showSnackbar() { const String text = "When the Scaffold's floating action button location changes, " 'the floating action button animates to its new position. ' 'The BottomAppBar adapts its shape appropriately.'; _scaffoldMessengerKey.currentState!.showSnackBar( const SnackBar(content: Text(text)), ); } // App bar color static const List<_NamedColor> kBabColors = <_NamedColor>[ _NamedColor(null, 'Clear'), _NamedColor(Color(0xFFFFC100), 'Orange'), _NamedColor(Color(0xFF91FAFF), 'Light Blue'), _NamedColor(Color(0xFF00D1FF), 'Cyan'), _NamedColor(Color(0xFF00BCFF), 'Cerulean'), _NamedColor(Color(0xFF009BEE), 'Blue'), ]; _ChoiceValue<Widget> _fabShape = kCircularFab; _ChoiceValue<bool> _showNotch = kShowNotchTrue; _ChoiceValue<FloatingActionButtonLocation> _fabLocation = kFabEndDocked; Color? _babColor = kBabColors.first.color; void _onShowNotchChanged(_ChoiceValue<bool>? value) { setState(() { _showNotch = value!; }); } void _onFabShapeChanged(_ChoiceValue<Widget>? value) { setState(() { _fabShape = value!; }); } void _onFabLocationChanged(_ChoiceValue<FloatingActionButtonLocation>? value) { setState(() { _fabLocation = value!; }); } void _onBabColorChanged(Color? value) { setState(() { _babColor = value; }); } @override Widget build(BuildContext context) { return ScaffoldMessenger( key: _scaffoldMessengerKey, child: Builder( builder: (BuildContext context) => Scaffold( appBar: AppBar( title: const Text('Bottom app bar'), elevation: 0.0, actions: <Widget>[ MaterialDemoDocumentationButton(BottomAppBarDemo.routeName), IconButton( icon: const Icon(Icons.sentiment_very_satisfied, semanticLabel: 'Update shape'), onPressed: () { setState(() { _fabShape = _fabShape == kCircularFab ? kDiamondFab : kCircularFab; }); }, ), ], ), body: Scrollbar( child: ListView( primary: true, padding: const EdgeInsets.only(bottom: 88.0), children: <Widget>[ const _Heading('FAB Shape'), _RadioItem<Widget>(kCircularFab, _fabShape, _onFabShapeChanged), _RadioItem<Widget>(kDiamondFab, _fabShape, _onFabShapeChanged), _RadioItem<Widget>(kNoFab, _fabShape, _onFabShapeChanged), const Divider(), const _Heading('Notch'), _RadioItem<bool>(kShowNotchTrue, _showNotch, _onShowNotchChanged), _RadioItem<bool>(kShowNotchFalse, _showNotch, _onShowNotchChanged), const Divider(), const _Heading('FAB Position'), _RadioItem<FloatingActionButtonLocation>(kFabEndDocked, _fabLocation, _onFabLocationChanged), _RadioItem<FloatingActionButtonLocation>(kFabCenterDocked, _fabLocation, _onFabLocationChanged), _RadioItem<FloatingActionButtonLocation>(kFabEndFloat, _fabLocation, _onFabLocationChanged), _RadioItem<FloatingActionButtonLocation>(kFabCenterFloat, _fabLocation, _onFabLocationChanged), const Divider(), const _Heading('App bar color'), _ColorsItem(kBabColors, _babColor, _onBabColorChanged), ], ), ), floatingActionButton: _fabShape.value, floatingActionButtonLocation: _fabLocation.value, bottomNavigationBar: _DemoBottomAppBar( color: _babColor, fabLocation: _fabLocation.value, shape: _selectNotch(), ), ), ), ); } NotchedShape? _selectNotch() { if (!_showNotch.value!) { return null; } if (_fabShape == kCircularFab) { return const CircularNotchedRectangle(); } if (_fabShape == kDiamondFab) { return const _DiamondNotchedRectangle(); } return null; } } class _ChoiceValue<T> { const _ChoiceValue({ this.value, this.title, this.label }); final T? value; final String? title; final String? label; // For the Semantics widget that contains title @override String toString() => '$runtimeType("$title")'; } class _RadioItem<T> extends StatelessWidget { const _RadioItem(this.value, this.groupValue, this.onChanged); final _ChoiceValue<T> value; final _ChoiceValue<T> groupValue; final ValueChanged<_ChoiceValue<T>?> onChanged; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return Container( height: 56.0, padding: const EdgeInsetsDirectional.only(start: 16.0), alignment: AlignmentDirectional.centerStart, child: MergeSemantics( child: Row( children: <Widget>[ Radio<_ChoiceValue<T>>( value: value, groupValue: groupValue, onChanged: onChanged, ), Expanded( child: Semantics( container: true, button: true, label: value.label, child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { onChanged(value); }, child: Text( value.title!, style: theme.textTheme.titleMedium, ), ), ), ), ], ), ), ); } } class _NamedColor { const _NamedColor(this.color, this.name); final Color? color; final String name; } class _ColorsItem extends StatelessWidget { const _ColorsItem(this.colors, this.selectedColor, this.onChanged); final List<_NamedColor> colors; final Color? selectedColor; final ValueChanged<Color?> onChanged; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: colors.map<Widget>((_NamedColor namedColor) { return RawMaterialButton( onPressed: () { onChanged(namedColor.color); }, constraints: const BoxConstraints.tightFor( width: 32.0, height: 32.0, ), fillColor: namedColor.color, shape: CircleBorder( side: BorderSide( color: namedColor.color == selectedColor ? Colors.black : const Color(0xFFD5D7DA), width: 2.0, ), ), child: Semantics( value: namedColor.name, selected: namedColor.color == selectedColor, ), ); }).toList(), ); } } class _Heading extends StatelessWidget { const _Heading(this.text); final String text; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return Container( height: 48.0, padding: const EdgeInsetsDirectional.only(start: 56.0), alignment: AlignmentDirectional.centerStart, child: Text( text, style: theme.textTheme.bodyLarge, ), ); } } class _DemoBottomAppBar extends StatelessWidget { const _DemoBottomAppBar({ this.color, this.fabLocation, this.shape, }); final Color? color; final FloatingActionButtonLocation? fabLocation; final NotchedShape? shape; static final List<FloatingActionButtonLocation> kCenterLocations = <FloatingActionButtonLocation>[ FloatingActionButtonLocation.centerDocked, FloatingActionButtonLocation.centerFloat, ]; @override Widget build(BuildContext context) { return BottomAppBar( color: color, shape: shape, child: Row(children: <Widget>[ IconButton( icon: const Icon(Icons.menu, semanticLabel: 'Show bottom sheet'), onPressed: () { showModalBottomSheet<void>( context: context, builder: (BuildContext context) => const _DemoDrawer(), ); }, ), if (kCenterLocations.contains(fabLocation)) const Expanded(child: SizedBox()), IconButton( icon: const Icon(Icons.search, semanticLabel: 'show search action',), onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('This is a dummy search action.')), ); }, ), IconButton( icon: Icon( Theme.of(context).platform == TargetPlatform.iOS ? Icons.more_horiz : Icons.more_vert, semanticLabel: 'Show menu actions', ), onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('This is a dummy menu action.')), ); }, ), ]), ); } } // A drawer that pops up from the bottom of the screen. class _DemoDrawer extends StatelessWidget { const _DemoDrawer(); @override Widget build(BuildContext context) { return const Drawer( child: Column( children: <Widget>[ ListTile( leading: Icon(Icons.search), title: Text('Search'), ), ListTile( leading: Icon(Icons.threed_rotation), title: Text('3D'), ), ], ), ); } } // A diamond-shaped floating action button. class _DiamondFab extends StatelessWidget { const _DiamondFab({ this.child, this.onPressed, }); final Widget? child; final VoidCallback? onPressed; @override Widget build(BuildContext context) { return Material( shape: const _DiamondBorder(), color: Colors.orange, elevation: 6.0, child: InkWell( onTap: onPressed, child: SizedBox( width: 56.0, height: 56.0, child: IconTheme.merge( data: IconThemeData(color: Theme.of(context).colorScheme.secondary), child: child!, ), ), ), ); } } class _DiamondNotchedRectangle implements NotchedShape { const _DiamondNotchedRectangle(); @override Path getOuterPath(Rect host, Rect? guest) { if (!host.overlaps(guest!)) { return Path()..addRect(host); } assert(guest.width > 0.0); final Rect intersection = guest.intersect(host); // We are computing a "V" shaped notch, as in this diagram: // -----\**** /----- // \ / // \ / // \ / // // "-" marks the top edge of the bottom app bar. // "\" and "/" marks the notch outline // // notchToCenter is the horizontal distance between the guest's center and // the host's top edge where the notch starts (marked with "*"). // We compute notchToCenter by similar triangles: final double notchToCenter = intersection.height * (guest.height / 2.0) / (guest.width / 2.0); return Path() ..moveTo(host.left, host.top) ..lineTo(guest.center.dx - notchToCenter, host.top) ..lineTo(guest.left + guest.width / 2.0, guest.bottom) ..lineTo(guest.center.dx + notchToCenter, host.top) ..lineTo(host.right, host.top) ..lineTo(host.right, host.bottom) ..lineTo(host.left, host.bottom) ..close(); } } class _DiamondBorder extends ShapeBorder { const _DiamondBorder(); @override EdgeInsetsGeometry get dimensions { return EdgeInsets.zero; } @override Path getInnerPath(Rect rect, { TextDirection? textDirection }) { return getOuterPath(rect, textDirection: textDirection); } @override Path getOuterPath(Rect rect, { TextDirection? textDirection }) { return Path() ..moveTo(rect.left + rect.width / 2.0, rect.top) ..lineTo(rect.right, rect.top + rect.height / 2.0) ..lineTo(rect.left + rect.width / 2.0, rect.bottom) ..lineTo(rect.left, rect.top + rect.height / 2.0) ..close(); } @override void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { } // This border doesn't support scaling. @override ShapeBorder scale(double t) { return this; } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart", "repo_id": "flutter", "token_count": 6477 }
540
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../gallery/demo.dart'; enum _MaterialListType { /// A list tile that contains a single line of text. oneLine, /// A list tile that contains a [CircleAvatar] followed by a single line of text. oneLineWithAvatar, /// A list tile that contains two lines of text. twoLine, /// A list tile that contains three lines of text. threeLine, } class ListDemo extends StatefulWidget { const ListDemo({ super.key }); static const String routeName = '/material/list'; @override State<ListDemo> createState() => _ListDemoState(); } class _ListDemoState extends State<ListDemo> { static final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); PersistentBottomSheetController? _bottomSheet; _MaterialListType? _itemType = _MaterialListType.threeLine; bool? _dense = false; bool? _showAvatars = true; bool? _showIcons = false; bool? _showDividers = false; bool _reverseSort = false; List<String> items = <String>[ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', ]; void changeItemType(_MaterialListType? type) { setState(() { _itemType = type; }); _bottomSheet?.setState!(() { }); } void _showConfigurationSheet() { final PersistentBottomSheetController bottomSheet = scaffoldKey.currentState!.showBottomSheet((BuildContext bottomSheetContext) { return Container( decoration: const BoxDecoration( border: Border(top: BorderSide(color: Colors.black26)), ), child: ListView( shrinkWrap: true, primary: false, children: <Widget>[ MergeSemantics( child: ListTile( dense: true, title: const Text('One-line'), trailing: Radio<_MaterialListType>( value: _showAvatars! ? _MaterialListType.oneLineWithAvatar : _MaterialListType.oneLine, groupValue: _itemType, onChanged: changeItemType, ), ), ), MergeSemantics( child: ListTile( dense: true, title: const Text('Two-line'), trailing: Radio<_MaterialListType>( value: _MaterialListType.twoLine, groupValue: _itemType, onChanged: changeItemType, ), ), ), MergeSemantics( child: ListTile( dense: true, title: const Text('Three-line'), trailing: Radio<_MaterialListType>( value: _MaterialListType.threeLine, groupValue: _itemType, onChanged: changeItemType, ), ), ), MergeSemantics( child: ListTile( dense: true, title: const Text('Show avatar'), trailing: Checkbox( value: _showAvatars, onChanged: (bool? value) { setState(() { _showAvatars = value; }); final StateSetter? bottomSheetSetState = _bottomSheet?.setState; if (bottomSheetSetState != null) { bottomSheetSetState(() { }); } }, ), ), ), MergeSemantics( child: ListTile( dense: true, title: const Text('Show icon'), trailing: Checkbox( value: _showIcons, onChanged: (bool? value) { setState(() { _showIcons = value; }); final StateSetter? bottomSheetSetState = _bottomSheet?.setState; if (bottomSheetSetState != null) { bottomSheetSetState(() { }); } }, ), ), ), MergeSemantics( child: ListTile( dense: true, title: const Text('Show dividers'), trailing: Checkbox( value: _showDividers, onChanged: (bool? value) { setState(() { _showDividers = value; }); final StateSetter? bottomSheetSetState = _bottomSheet?.setState; if (bottomSheetSetState != null) { bottomSheetSetState(() { }); } }, ), ), ), MergeSemantics( child: ListTile( dense: true, title: const Text('Dense layout'), trailing: Checkbox( value: _dense, onChanged: (bool? value) { setState(() { _dense = value; }); final StateSetter? bottomSheetSetState = _bottomSheet?.setState; if (bottomSheetSetState != null) { bottomSheetSetState(() { }); } }, ), ), ), ], ), ); }); setState(() { _bottomSheet = bottomSheet; }); _bottomSheet?.closed.whenComplete(() { if (mounted) { setState(() { _bottomSheet = null; }); } }); } Widget buildListTile(BuildContext context, String item) { Widget? secondary; if (_itemType == _MaterialListType.twoLine) { secondary = const Text('Additional item information.'); } else if (_itemType == _MaterialListType.threeLine) { secondary = const Text( 'Even more additional list item information appears on line three.', ); } return MergeSemantics( child: ListTile( isThreeLine: _itemType == _MaterialListType.threeLine, dense: _dense, leading: _showAvatars != null ? ExcludeSemantics(child: CircleAvatar(child: Text(item))) : null, title: Text('This item represents $item.'), subtitle: secondary, trailing: _showIcons != null ? Icon(Icons.info, color: Theme.of(context).disabledColor) : null, ), ); } @override Widget build(BuildContext context) { final String layoutText = _dense != null ? ' \u2013 Dense' : ''; String? itemTypeText; switch (_itemType) { case _MaterialListType.oneLine: case _MaterialListType.oneLineWithAvatar: itemTypeText = 'Single-line'; case _MaterialListType.twoLine: itemTypeText = 'Two-line'; case _MaterialListType.threeLine: itemTypeText = 'Three-line'; case null: break; } Iterable<Widget> listTiles = items.map<Widget>((String item) => buildListTile(context, item)); if (_showDividers != null) { listTiles = ListTile.divideTiles(context: context, tiles: listTiles); } return Scaffold( key: scaffoldKey, appBar: AppBar( title: Text('Scrolling list\n$itemTypeText$layoutText'), actions: <Widget>[ MaterialDemoDocumentationButton(ListDemo.routeName), IconButton( icon: const Icon(Icons.sort_by_alpha), tooltip: 'Sort', onPressed: () { setState(() { _reverseSort = !_reverseSort; items.sort((String a, String b) => _reverseSort ? b.compareTo(a) : a.compareTo(b)); }); }, ), IconButton( icon: Icon( Theme.of(context).platform == TargetPlatform.iOS ? Icons.more_horiz : Icons.more_vert, ), tooltip: 'Show menu', onPressed: _bottomSheet == null ? _showConfigurationSheet : null, ), ], ), body: Scrollbar( child: ListView( primary: true, padding: EdgeInsets.symmetric(vertical: _dense != null ? 4.0 : 8.0), children: listTiles.toList(), ), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/list_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/list_demo.dart", "repo_id": "flutter", "token_count": 4332 }
541
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../gallery/demo.dart'; class TextFormFieldDemo extends StatefulWidget { const TextFormFieldDemo({ super.key }); static const String routeName = '/material/text-form-field'; @override TextFormFieldDemoState createState() => TextFormFieldDemoState(); } class PersonData { String? name = ''; String? phoneNumber = ''; String? email = ''; String password = ''; } class PasswordField extends StatefulWidget { const PasswordField({ super.key, this.fieldKey, this.hintText, this.labelText, this.helperText, this.onSaved, this.validator, this.onFieldSubmitted, }); final Key? fieldKey; final String? hintText; final String? labelText; final String? helperText; final FormFieldSetter<String>? onSaved; final FormFieldValidator<String>? validator; final ValueChanged<String>? onFieldSubmitted; @override State<PasswordField> createState() => _PasswordFieldState(); } class _PasswordFieldState extends State<PasswordField> { bool _obscureText = true; @override Widget build(BuildContext context) { return TextFormField( key: widget.fieldKey, obscureText: _obscureText, maxLength: 8, onSaved: widget.onSaved, validator: widget.validator, onFieldSubmitted: widget.onFieldSubmitted, decoration: InputDecoration( border: const UnderlineInputBorder(), filled: true, hintText: widget.hintText, labelText: widget.labelText, helperText: widget.helperText, suffixIcon: GestureDetector( dragStartBehavior: DragStartBehavior.down, onTap: () { setState(() { _obscureText = !_obscureText; }); }, child: Icon( _obscureText ? Icons.visibility : Icons.visibility_off, semanticLabel: _obscureText ? 'show password' : 'hide password', ), ), ), ); } } class TextFormFieldDemoState extends State<TextFormFieldDemo> { PersonData person = PersonData(); void showInSnackBar(String value) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text(value), )); } AutovalidateMode _autovalidateMode = AutovalidateMode.disabled; bool _formWasEdited = false; final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final GlobalKey<FormFieldState<String>> _passwordFieldKey = GlobalKey<FormFieldState<String>>(); final _UsNumberTextInputFormatter _phoneNumberFormatter = _UsNumberTextInputFormatter(); void _handleSubmitted() { final FormState form = _formKey.currentState!; if (!form.validate()) { _autovalidateMode = AutovalidateMode.always; // Start validating on every change. showInSnackBar('Please fix the errors in red before submitting.'); } else { form.save(); showInSnackBar("${person.name}'s phone number is ${person.phoneNumber}"); } } String? _validateName(String? value) { _formWasEdited = true; if (value!.isEmpty) { return 'Name is required.'; } final RegExp nameExp = RegExp(r'^[A-Za-z ]+$'); if (!nameExp.hasMatch(value)) { return 'Please enter only alphabetical characters.'; } return null; } String? _validatePhoneNumber(String? value) { _formWasEdited = true; final RegExp phoneExp = RegExp(r'^\(\d\d\d\) \d\d\d\-\d\d\d\d$'); if (!phoneExp.hasMatch(value!)) { return '(###) ###-#### - Enter a US phone number.'; } return null; } String? _validatePassword(String? value) { _formWasEdited = true; final FormFieldState<String> passwordField = _passwordFieldKey.currentState!; if (passwordField.value == null || passwordField.value!.isEmpty) { return 'Please enter a password.'; } if (passwordField.value != value) { return "The passwords don't match"; } return null; } Future<void> _handlePopInvoked(bool didPop) async { if (didPop) { return; } final bool? result = await showDialog<bool>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('This form has errors'), content: const Text('Really leave this form?'), actions: <Widget> [ TextButton( child: const Text('YES'), onPressed: () { Navigator.of(context).pop(true); }, ), TextButton( child: const Text('NO'), onPressed: () { Navigator.of(context).pop(false); }, ), ], ); }, ); if (result ?? false) { // Since this is the root route, quit the app where possible by invoking // the SystemNavigator. If this wasn't the root route, then // Navigator.maybePop could be used instead. // See https://github.com/flutter/flutter/issues/11490 SystemNavigator.pop(); } } @override Widget build(BuildContext context) { return Scaffold( drawerDragStartBehavior: DragStartBehavior.down, appBar: AppBar( title: const Text('Text fields'), actions: <Widget>[MaterialDemoDocumentationButton(TextFormFieldDemo.routeName)], ), body: SafeArea( top: false, bottom: false, child: Form( key: _formKey, autovalidateMode: _autovalidateMode, canPop: _formKey.currentState == null || !_formWasEdited || _formKey.currentState!.validate(), onPopInvoked: _handlePopInvoked, child: Scrollbar( child: SingleChildScrollView( primary: true, dragStartBehavior: DragStartBehavior.down, padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ const SizedBox(height: 24.0), TextFormField( textCapitalization: TextCapitalization.words, decoration: const InputDecoration( border: UnderlineInputBorder(), filled: true, icon: Icon(Icons.person), hintText: 'What do people call you?', labelText: 'Name *', ), onSaved: (String? value) { person.name = value; }, validator: _validateName, ), const SizedBox(height: 24.0), TextFormField( decoration: const InputDecoration( border: UnderlineInputBorder(), filled: true, icon: Icon(Icons.phone), hintText: 'Where can we reach you?', labelText: 'Phone Number *', prefixText: '+1', ), keyboardType: TextInputType.phone, onSaved: (String? value) { person.phoneNumber = value; }, validator: _validatePhoneNumber, // TextInputFormatters are applied in sequence. inputFormatters: <TextInputFormatter> [ FilteringTextInputFormatter.digitsOnly, // Fit the validating format. _phoneNumberFormatter, ], ), const SizedBox(height: 24.0), TextFormField( decoration: const InputDecoration( border: UnderlineInputBorder(), filled: true, icon: Icon(Icons.email), hintText: 'Your email address', labelText: 'E-mail', ), keyboardType: TextInputType.emailAddress, onSaved: (String? value) { person.email = value; }, ), const SizedBox(height: 24.0), TextFormField( decoration: const InputDecoration( border: OutlineInputBorder(), hintText: 'Tell us about yourself (e.g., write down what you do or what hobbies you have)', helperText: 'Keep it short, this is just a demo.', labelText: 'Life story', ), maxLines: 3, ), const SizedBox(height: 24.0), TextFormField( keyboardType: TextInputType.number, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Salary', prefixText: r'$', suffixText: 'USD', suffixStyle: TextStyle(color: Colors.green), ), ), const SizedBox(height: 24.0), PasswordField( fieldKey: _passwordFieldKey, helperText: 'No more than 8 characters.', labelText: 'Password *', onFieldSubmitted: (String value) { setState(() { person.password = value; }); }, ), const SizedBox(height: 24.0), TextFormField( enabled: person.password.isNotEmpty, decoration: const InputDecoration( border: UnderlineInputBorder(), filled: true, labelText: 'Re-type password', ), maxLength: 8, obscureText: true, validator: _validatePassword, ), const SizedBox(height: 24.0), Center( child: ElevatedButton( onPressed: _handleSubmitted, child: const Text('SUBMIT'), ), ), const SizedBox(height: 24.0), Text( '* indicates required field', style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 24.0), ], ), ), ), ), ), ); } } /// Format incoming numeric text to fit the format of (###) ###-#### ##... class _UsNumberTextInputFormatter extends TextInputFormatter { @override TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue, ) { final int newTextLength = newValue.text.length; int selectionIndex = newValue.selection.end; int usedSubstringIndex = 0; final StringBuffer newText = StringBuffer(); if (newTextLength >= 1) { newText.write('('); if (newValue.selection.end >= 1) { selectionIndex++; } } if (newTextLength >= 4) { final String value = newValue.text.substring(0, usedSubstringIndex = 3); newText.write('$value) '); if (newValue.selection.end >= 3) { selectionIndex += 2; } } if (newTextLength >= 7) { final String value = newValue.text.substring(3, usedSubstringIndex = 6); newText.write('$value-'); if (newValue.selection.end >= 6) { selectionIndex++; } } if (newTextLength >= 11) { final String value = newValue.text.substring(6, usedSubstringIndex = 10); newText.write('$value '); if (newValue.selection.end >= 10) { selectionIndex++; } } // Dump the rest. if (newTextLength >= usedSubstringIndex) { newText.write(newValue.text.substring(usedSubstringIndex)); } return TextEditingValue( text: newText.toString(), selection: TextSelection.collapsed(offset: selectionIndex), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart", "repo_id": "flutter", "token_count": 5910 }
542
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:scoped_model/scoped_model.dart'; import '../model/app_state_model.dart'; import '../model/product.dart'; class ProductCard extends StatelessWidget { const ProductCard({ super.key, this.imageAspectRatio = 33 / 49, this.product }) : assert(imageAspectRatio > 0); final double imageAspectRatio; final Product? product; static const double kTextBoxHeight = 65.0; @override Widget build(BuildContext context) { final NumberFormat formatter = NumberFormat.simpleCurrency( decimalDigits: 0, locale: Localizations.localeOf(context).toString(), ); final ThemeData theme = Theme.of(context); final Image imageWidget = Image.asset( product!.assetName, package: product!.assetPackage, fit: BoxFit.cover, ); // The fontSize to use for computing the heuristic UI scaling factor. const double defaultFontSize = 14.0; final double containerScalingFactor = MediaQuery.textScalerOf(context).scale(defaultFontSize) / defaultFontSize; return ScopedModelDescendant<AppStateModel>( builder: (BuildContext context, Widget? child, AppStateModel model) { return GestureDetector( onTap: () { model.addProductToCart(product!.id); }, child: child, ); }, child: Stack( children: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ AspectRatio( aspectRatio: imageAspectRatio, child: imageWidget, ), SizedBox( height: kTextBoxHeight * containerScalingFactor, width: 121.0, child: Column( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Text( product == null ? '' : product!.name, style: theme.textTheme.labelLarge, softWrap: false, overflow: TextOverflow.ellipsis, maxLines: 1, ), const SizedBox(height: 4.0), Text( product == null ? '' : formatter.format(product!.price), style: theme.textTheme.bodySmall, ), ], ), ), ], ), const Padding( padding: EdgeInsets.all(16.0), child: Icon(Icons.add_shopping_cart), ), ], ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_card.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_card.dart", "repo_id": "flutter", "token_count": 1351 }
543
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../demo/all.dart'; import 'icons.dart'; @immutable class GalleryDemoCategory { const GalleryDemoCategory._({ required this.name, required this.icon, }); final String name; final IconData icon; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is GalleryDemoCategory && other.name == name && other.icon == icon; } @override int get hashCode => Object.hash(name, icon); @override String toString() { return '$runtimeType($name)'; } } const GalleryDemoCategory _kDemos = GalleryDemoCategory._( name: 'Studies', icon: GalleryIcons.animation, ); const GalleryDemoCategory _kStyle = GalleryDemoCategory._( name: 'Style', icon: GalleryIcons.custom_typography, ); const GalleryDemoCategory _kMaterialComponents = GalleryDemoCategory._( name: 'Material', icon: GalleryIcons.category_mdc, ); const GalleryDemoCategory _kCupertinoComponents = GalleryDemoCategory._( name: 'Cupertino', icon: GalleryIcons.phone_iphone, ); const GalleryDemoCategory _kMedia = GalleryDemoCategory._( name: 'Media', icon: GalleryIcons.drive_video, ); class GalleryDemo { const GalleryDemo({ required this.title, required this.icon, this.subtitle, required this.category, required this.routeName, this.documentationUrl, required this.buildRoute, }); final String title; final IconData icon; final String? subtitle; final GalleryDemoCategory category; final String routeName; final WidgetBuilder buildRoute; final String? documentationUrl; @override String toString() { return '$runtimeType($title $routeName)'; } } List<GalleryDemo> _buildGalleryDemos() { final List<GalleryDemo> galleryDemos = <GalleryDemo>[ // Demos GalleryDemo( title: 'Shrine', subtitle: 'Basic shopping app', icon: GalleryIcons.shrine, category: _kDemos, routeName: ShrineDemo.routeName, buildRoute: (BuildContext context) => const ShrineDemo(), ), GalleryDemo( title: 'Fortnightly', subtitle: 'Newspaper typography app', icon: GalleryIcons.custom_typography, category: _kDemos, routeName: FortnightlyDemo.routeName, buildRoute: (BuildContext context) => const FortnightlyDemo(), ), GalleryDemo( title: 'Contact profile', subtitle: 'Address book entry with a flexible appbar', icon: GalleryIcons.account_box, category: _kDemos, routeName: ContactsDemo.routeName, buildRoute: (BuildContext context) => const ContactsDemo(), ), GalleryDemo( title: 'Animation', subtitle: 'Section organizer', icon: GalleryIcons.animation, category: _kDemos, routeName: AnimationDemo.routeName, buildRoute: (BuildContext context) => const AnimationDemo(), ), GalleryDemo( title: '2D Transformations', subtitle: 'Pan, Zoom, Rotate', icon: GalleryIcons.grid_on, category: _kDemos, routeName: TransformationsDemo.routeName, buildRoute: (BuildContext context) => const TransformationsDemo(), ), GalleryDemo( title: 'Pesto', subtitle: 'Simple recipe browser', icon: Icons.adjust, category: _kDemos, routeName: PestoDemo.routeName, buildRoute: (BuildContext context) => const PestoDemo(), ), // Style GalleryDemo( title: 'Colors', subtitle: 'All of the predefined colors', icon: GalleryIcons.colors, category: _kStyle, routeName: ColorsDemo.routeName, buildRoute: (BuildContext context) => const ColorsDemo(), ), GalleryDemo( title: 'Typography', subtitle: 'All of the predefined text styles', icon: GalleryIcons.custom_typography, category: _kStyle, routeName: TypographyDemo.routeName, buildRoute: (BuildContext context) => const TypographyDemo(), ), // Material Components GalleryDemo( title: 'Backdrop', subtitle: 'Select a front layer from back layer', icon: GalleryIcons.backdrop, category: _kMaterialComponents, routeName: BackdropDemo.routeName, buildRoute: (BuildContext context) => const BackdropDemo(), ), GalleryDemo( title: 'Banner', subtitle: 'Displaying a banner within a list', icon: GalleryIcons.lists_leave_behind, category: _kMaterialComponents, routeName: BannerDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/MaterialBanner-class.html', buildRoute: (BuildContext context) => const BannerDemo(), ), GalleryDemo( title: 'Bottom app bar', subtitle: 'Optional floating action button notch', icon: GalleryIcons.bottom_app_bar, category: _kMaterialComponents, routeName: BottomAppBarDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/BottomAppBar-class.html', buildRoute: (BuildContext context) => const BottomAppBarDemo(), ), GalleryDemo( title: 'Bottom navigation', subtitle: 'Bottom navigation with cross-fading views', icon: GalleryIcons.bottom_navigation, category: _kMaterialComponents, routeName: BottomNavigationDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html', buildRoute: (BuildContext context) => const BottomNavigationDemo(), ), GalleryDemo( title: 'Bottom sheet: Modal', subtitle: 'A dismissible bottom sheet', icon: GalleryIcons.bottom_sheets, category: _kMaterialComponents, routeName: ModalBottomSheetDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/showModalBottomSheet.html', buildRoute: (BuildContext context) => const ModalBottomSheetDemo(), ), GalleryDemo( title: 'Bottom sheet: Persistent', subtitle: 'A bottom sheet that sticks around', icon: GalleryIcons.bottom_sheet_persistent, category: _kMaterialComponents, routeName: PersistentBottomSheetDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/ScaffoldState/showBottomSheet.html', buildRoute: (BuildContext context) => const PersistentBottomSheetDemo(), ), GalleryDemo( title: 'Buttons', subtitle: 'Flat, raised, dropdown, and more', icon: GalleryIcons.generic_buttons, category: _kMaterialComponents, routeName: ButtonsDemo.routeName, buildRoute: (BuildContext context) => const ButtonsDemo(), ), GalleryDemo( title: 'Buttons: Floating Action Button', subtitle: 'FAB with transitions', icon: GalleryIcons.buttons, category: _kMaterialComponents, routeName: TabsFabDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/FloatingActionButton-class.html', buildRoute: (BuildContext context) => const TabsFabDemo(), ), GalleryDemo( title: 'Cards', subtitle: 'Baseline cards with rounded corners', icon: GalleryIcons.cards, category: _kMaterialComponents, routeName: CardsDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/Card-class.html', buildRoute: (BuildContext context) => const CardsDemo(), ), GalleryDemo( title: 'Chips', subtitle: 'Labeled with delete buttons and avatars', icon: GalleryIcons.chips, category: _kMaterialComponents, routeName: ChipDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/Chip-class.html', buildRoute: (BuildContext context) => const ChipDemo(), ), GalleryDemo( title: 'Data tables', subtitle: 'Rows and columns', icon: GalleryIcons.data_table, category: _kMaterialComponents, routeName: DataTableDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/PaginatedDataTable-class.html', buildRoute: (BuildContext context) => const DataTableDemo(), ), GalleryDemo( title: 'Dialogs', subtitle: 'Simple, alert, and fullscreen', icon: GalleryIcons.dialogs, category: _kMaterialComponents, routeName: DialogDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/showDialog.html', buildRoute: (BuildContext context) => const DialogDemo(), ), GalleryDemo( title: 'Elevations', subtitle: 'Shadow values on cards', // TODO(larche): Change to custom icon for elevations when one exists. icon: GalleryIcons.cupertino_progress, category: _kMaterialComponents, routeName: ElevationDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/Material/elevation.html', buildRoute: (BuildContext context) => const ElevationDemo(), ), GalleryDemo( title: 'Expand/collapse list control', subtitle: 'A list with one sub-list level', icon: GalleryIcons.expand_all, category: _kMaterialComponents, routeName: ExpansionTileListDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/ExpansionTile-class.html', buildRoute: (BuildContext context) => const ExpansionTileListDemo(), ), GalleryDemo( title: 'Expansion panels', subtitle: 'List of expanding panels', icon: GalleryIcons.expand_all, category: _kMaterialComponents, routeName: ExpansionPanelsDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/ExpansionPanel-class.html', buildRoute: (BuildContext context) => const ExpansionPanelsDemo(), ), GalleryDemo( title: 'Grid', subtitle: 'Row and column layout', icon: GalleryIcons.grid_on, category: _kMaterialComponents, routeName: GridListDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/widgets/GridView-class.html', buildRoute: (BuildContext context) => const GridListDemo(), ), GalleryDemo( title: 'Icons', subtitle: 'Enabled and disabled icons with opacity', icon: GalleryIcons.sentiment_very_satisfied, category: _kMaterialComponents, routeName: IconsDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/IconButton-class.html', buildRoute: (BuildContext context) => const IconsDemo(), ), GalleryDemo( title: 'Lists', subtitle: 'Scrolling list layouts', icon: GalleryIcons.list_alt, category: _kMaterialComponents, routeName: ListDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/ListTile-class.html', buildRoute: (BuildContext context) => const ListDemo(), ), GalleryDemo( title: 'Lists: leave-behind list items', subtitle: 'List items with hidden actions', icon: GalleryIcons.lists_leave_behind, category: _kMaterialComponents, routeName: LeaveBehindDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/widgets/Dismissible-class.html', buildRoute: (BuildContext context) => const LeaveBehindDemo(), ), GalleryDemo( title: 'Lists: reorderable', subtitle: 'Reorderable lists', icon: GalleryIcons.list_alt, category: _kMaterialComponents, routeName: ReorderableListDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/ReorderableListView-class.html', buildRoute: (BuildContext context) => const ReorderableListDemo(), ), GalleryDemo( title: 'Menus', subtitle: 'Menu buttons and simple menus', icon: GalleryIcons.more_vert, category: _kMaterialComponents, routeName: MenuDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/PopupMenuButton-class.html', buildRoute: (BuildContext context) => const MenuDemo(), ), GalleryDemo( title: 'Navigation drawer', subtitle: 'Navigation drawer with standard header', icon: GalleryIcons.menu, category: _kMaterialComponents, routeName: DrawerDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/Drawer-class.html', buildRoute: (BuildContext context) => const DrawerDemo(), ), GalleryDemo( title: 'Pagination', subtitle: 'PageView with indicator', icon: GalleryIcons.page_control, category: _kMaterialComponents, routeName: PageSelectorDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/TabBarView-class.html', buildRoute: (BuildContext context) => const PageSelectorDemo(), ), GalleryDemo( title: 'Pickers', subtitle: 'Date and time selection widgets', icon: GalleryIcons.event, category: _kMaterialComponents, routeName: DateAndTimePickerDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/showDatePicker.html', buildRoute: (BuildContext context) => const DateAndTimePickerDemo(), ), GalleryDemo( title: 'Progress indicators', subtitle: 'Linear, circular, indeterminate', icon: GalleryIcons.progress_activity, category: _kMaterialComponents, routeName: ProgressIndicatorDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/LinearProgressIndicator-class.html', buildRoute: (BuildContext context) => const ProgressIndicatorDemo(), ), GalleryDemo( title: 'Pull to refresh', subtitle: 'Refresh indicators', icon: GalleryIcons.refresh, category: _kMaterialComponents, routeName: OverscrollDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/RefreshIndicator-class.html', buildRoute: (BuildContext context) => const OverscrollDemo(), ), GalleryDemo( title: 'Search', subtitle: 'Expandable search', icon: Icons.search, category: _kMaterialComponents, routeName: SearchDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/showSearch.html', buildRoute: (BuildContext context) => const SearchDemo(), ), GalleryDemo( title: 'Selection controls', subtitle: 'Checkboxes, radio buttons, and switches', icon: GalleryIcons.check_box, category: _kMaterialComponents, routeName: SelectionControlsDemo.routeName, buildRoute: (BuildContext context) => const SelectionControlsDemo(), ), GalleryDemo( title: 'Sliders', subtitle: 'Widgets for selecting a value by swiping', icon: GalleryIcons.sliders, category: _kMaterialComponents, routeName: SliderDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/Slider-class.html', buildRoute: (BuildContext context) => const SliderDemo(), ), GalleryDemo( title: 'Snackbar', subtitle: 'Temporary messaging', icon: GalleryIcons.snackbar, category: _kMaterialComponents, routeName: SnackBarDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/ScaffoldState/showSnackBar.html', buildRoute: (BuildContext context) => const SnackBarDemo(), ), GalleryDemo( title: 'Tabs', subtitle: 'Tabs with independently scrollable views', icon: GalleryIcons.tabs, category: _kMaterialComponents, routeName: TabsDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/TabBarView-class.html', buildRoute: (BuildContext context) => const TabsDemo(), ), GalleryDemo( title: 'Tabs: Scrolling', subtitle: 'Tab bar that scrolls', category: _kMaterialComponents, icon: GalleryIcons.tabs, routeName: ScrollableTabsDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/TabBar-class.html', buildRoute: (BuildContext context) => const ScrollableTabsDemo(), ), GalleryDemo( title: 'Text fields', subtitle: 'Single line of editable text and numbers', icon: GalleryIcons.text_fields_alt, category: _kMaterialComponents, routeName: TextFormFieldDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/TextFormField-class.html', buildRoute: (BuildContext context) => const TextFormFieldDemo(), ), GalleryDemo( title: 'Tooltips', subtitle: 'Short message displayed on long-press', icon: GalleryIcons.tooltip, category: _kMaterialComponents, routeName: TooltipDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/material/Tooltip-class.html', buildRoute: (BuildContext context) => const TooltipDemo(), ), // Cupertino Components GalleryDemo( title: 'Activity Indicator', icon: GalleryIcons.cupertino_progress, category: _kCupertinoComponents, routeName: CupertinoProgressIndicatorDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoActivityIndicator-class.html', buildRoute: (BuildContext context) => const CupertinoProgressIndicatorDemo(), ), GalleryDemo( title: 'Alerts', icon: GalleryIcons.dialogs, category: _kCupertinoComponents, routeName: CupertinoAlertDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/showCupertinoDialog.html', buildRoute: (BuildContext context) => const CupertinoAlertDemo(), ), GalleryDemo( title: 'Buttons', icon: GalleryIcons.generic_buttons, category: _kCupertinoComponents, routeName: CupertinoButtonsDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoButton-class.html', buildRoute: (BuildContext context) => const CupertinoButtonsDemo(), ), GalleryDemo( title: 'Navigation', icon: GalleryIcons.bottom_navigation, category: _kCupertinoComponents, routeName: CupertinoNavigationDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoTabScaffold-class.html', buildRoute: (BuildContext context) => CupertinoNavigationDemo(), ), GalleryDemo( title: 'Pickers', icon: GalleryIcons.event, category: _kCupertinoComponents, routeName: CupertinoPickerDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoPicker-class.html', buildRoute: (BuildContext context) => const CupertinoPickerDemo(), ), GalleryDemo( title: 'Pull to refresh', icon: GalleryIcons.cupertino_pull_to_refresh, category: _kCupertinoComponents, routeName: CupertinoRefreshControlDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoSliverRefreshControl-class.html', buildRoute: (BuildContext context) => const CupertinoRefreshControlDemo(), ), GalleryDemo( title: 'Segmented Control', icon: GalleryIcons.tabs, category: _kCupertinoComponents, routeName: CupertinoSegmentedControlDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoSegmentedControl-class.html', buildRoute: (BuildContext context) => const CupertinoSegmentedControlDemo(), ), GalleryDemo( title: 'Sliders', icon: GalleryIcons.sliders, category: _kCupertinoComponents, routeName: CupertinoSliderDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoSlider-class.html', buildRoute: (BuildContext context) => const CupertinoSliderDemo(), ), GalleryDemo( title: 'Switches', icon: GalleryIcons.cupertino_switch, category: _kCupertinoComponents, routeName: CupertinoSwitchDemo.routeName, documentationUrl: 'https://api.flutter.dev/flutter/cupertino/CupertinoSwitch-class.html', buildRoute: (BuildContext context) => const CupertinoSwitchDemo(), ), GalleryDemo( title: 'Text Fields', icon: GalleryIcons.text_fields_alt, category: _kCupertinoComponents, routeName: CupertinoTextFieldDemo.routeName, buildRoute: (BuildContext context) => const CupertinoTextFieldDemo(), ), // Media GalleryDemo( title: 'Animated images', subtitle: 'GIF and WebP animations', icon: GalleryIcons.animation, category: _kMedia, routeName: ImagesDemo.routeName, buildRoute: (BuildContext context) => const ImagesDemo(), ), GalleryDemo( title: 'Video', subtitle: 'Video playback', icon: GalleryIcons.drive_video, category: _kMedia, routeName: VideoDemo.routeName, buildRoute: (BuildContext context) => const VideoDemo(), ), ]; return galleryDemos; } final List<GalleryDemo> kAllGalleryDemos = _buildGalleryDemos(); final Set<GalleryDemoCategory> kAllGalleryDemoCategories = kAllGalleryDemos.map<GalleryDemoCategory>((GalleryDemo demo) => demo.category).toSet(); final Map<GalleryDemoCategory, List<GalleryDemo>> kGalleryCategoryToDemos = Map<GalleryDemoCategory, List<GalleryDemo>>.fromIterable( kAllGalleryDemoCategories, value: (dynamic category) { return kAllGalleryDemos.where((GalleryDemo demo) => demo.category == category).toList(); }, ); final Map<String, String?> kDemoDocumentationUrl = <String, String?>{ for (final GalleryDemo demo in kAllGalleryDemos) if (demo.documentationUrl != null) demo.routeName: demo.documentationUrl, };
flutter/dev/integration_tests/flutter_gallery/lib/gallery/demos.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/demos.dart", "repo_id": "flutter", "token_count": 8189 }
544
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_gallery/demo/all.dart'; import 'package:flutter_gallery/gallery/app.dart'; import 'package:flutter_gallery/gallery/themes.dart'; import 'package:flutter_test/flutter_test.dart'; class TestMaterialApp extends StatelessWidget { const TestMaterialApp({ super.key, required this.home }); final Widget home; @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: home, ); } } void main() { group('All material demos meet recommended tap target sizes', () { testWidgets('backdrop_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: BackdropDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('bottom_app_bar_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: BottomAppBarDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('bottom_navigation_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: BottomNavigationDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('buttons_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ButtonsDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('cards_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: CardsDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('chip_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ChipDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }, skip: true); // https://github.com/flutter/flutter/issues/42455 testWidgets('data_table_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DataTableDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('date_and_time_picker_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DateAndTimePickerDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('dialog_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DialogDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('drawer_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DrawerDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('elevation_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ElevationDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('expansion_panels_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ExpansionPanelsDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('grid_list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: GridListDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('icons_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: IconsDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('leave_behind_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: LeaveBehindDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ListDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('menu_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: MenuDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('modal_bottom_sheet_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ModalBottomSheetDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('overscroll_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: OverscrollDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('page_selector_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: PageSelectorDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('persistent_bottom_sheet_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: PersistentBottomSheetDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('progress_indicator_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ProgressIndicatorDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('reorderable_list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ReorderableListDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('scrollable_tabs_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ScrollableTabsDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('search_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SearchDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('selection_controls_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SelectionControlsDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('slider_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SliderDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('snack_bar_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SnackBarDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('tabs_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TabsDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('tabs_fab_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TabsFabDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('text_form_field_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TextFormFieldDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('tooltip_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TooltipDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); testWidgets('expansion_tile_list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ExpansionTileListDemo())); await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); handle.dispose(); }); }); group('All material demos have labeled tap targets', () { testWidgets('backdrop_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: BackdropDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('bottom_app_bar_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: BottomAppBarDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('bottom_navigation_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: BottomNavigationDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('buttons_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ButtonsDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('cards_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: CardsDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('chip_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ChipDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('data_table_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DataTableDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }, skip: true); // DataTables are not accessible, https://github.com/flutter/flutter/issues/10830 testWidgets('date_and_time_picker_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DateAndTimePickerDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('dialog_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DialogDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('drawer_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: DrawerDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('elevation_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ElevationDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('expansion_panels_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ExpansionPanelsDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('grid_list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: GridListDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('icons_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: IconsDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('leave_behind_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: LeaveBehindDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ListDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('menu_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: MenuDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('modal_bottom_sheet_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ModalBottomSheetDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('overscroll_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: OverscrollDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('page_selector_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: PageSelectorDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('persistent_bottom_sheet_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: PersistentBottomSheetDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('progress_indicator_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ProgressIndicatorDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('reorderable_list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ReorderableListDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('scrollable_tabs_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ScrollableTabsDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('search_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SearchDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('selection_controls_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SelectionControlsDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('slider_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SliderDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('snack_bar_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: SnackBarDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('tabs_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TabsDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('tabs_fab_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TabsFabDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('text_form_field_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TextFormFieldDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('tooltip_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: TooltipDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); testWidgets('expansion_tile_list_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const TestMaterialApp(home: ExpansionTileListDemo())); await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); handle.dispose(); }); }); group('All material demos meet text contrast guidelines', () { final List<ThemeData> themes = <ThemeData>[ kLightGalleryTheme, kDarkGalleryTheme, ]; const List<String> themeNames = <String>[ 'kLightGalleryTheme', 'kDarkGalleryTheme', ]; for (int themeIndex = 0; themeIndex < themes.length; themeIndex += 1) { final ThemeData theme = themes[themeIndex]; final String themeName = themeNames[themeIndex]; testWidgets('backdrop_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const BackdropDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('bottom_app_bar_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const BottomAppBarDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('bottom_navigation_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const BottomNavigationDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('buttons_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ButtonsDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('cards_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const CardsDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('chip_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ChipDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('data_table_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const DataTableDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('date_and_time_picker_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const DateAndTimePickerDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('dialog_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const DialogDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('drawer_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const DrawerDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('elevation_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ElevationDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('expansion_panels_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ExpansionPanelsDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('grid_list_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const GridListDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('icons_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const IconsDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('leave_behind_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const LeaveBehindDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('list_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ListDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('menu_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const MenuDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('modal_bottom_sheet_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget( MaterialApp(theme: theme, home: const ModalBottomSheetDemo()) ); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('overscroll_demo', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const MaterialApp(home: OverscrollDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('page_selector_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const PageSelectorDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('persistent_bottom_sheet_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget( MaterialApp(theme: theme, home: const PersistentBottomSheetDemo()) ); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('progress_indicator_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ProgressIndicatorDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('reorderable_list_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ReorderableListDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('scrollable_tabs_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ScrollableTabsDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('search_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const SearchDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('selection_controls_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const SelectionControlsDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('slider_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const SliderDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('snack_bar_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget( MaterialApp(theme: theme, home: const SnackBarDemo()) ); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('tabs_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const TabsDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('tabs_fab_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const TabsFabDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('text_form_field_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const TextFormFieldDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('tooltip_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const TooltipDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); testWidgets('expansion_tile_list_demo $themeName', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MaterialApp(theme: theme, home: const ExpansionTileListDemo())); await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); }); } }); group('Gallery home page meets text contrast guidelines', () { testWidgets('options menu', (WidgetTester tester) async { await tester.pumpWidget(const GalleryApp(testMode: true)); await tester.tap(find.byTooltip('Toggle options page')); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); }); testWidgets('options menu - dark theme', (WidgetTester tester) async { await tester.pumpWidget(const GalleryApp(testMode: true)); await tester.tap(find.byTooltip('Toggle options page')); await tester.pumpAndSettle(); // Toggle dark mode. final Finder themeToggleContainer = find.ancestor( of: find.text('Theme'), matching: find.byType(Container), ); final Finder themeMenuButton = find.descendant( of: themeToggleContainer, matching: find.byIcon(Icons.arrow_drop_down), ); await tester.tap(themeMenuButton); await tester.pumpAndSettle(); await tester.tap(find.text('Dark')); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); }); }); }
flutter/dev/integration_tests/flutter_gallery/test/accessibility_test.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/accessibility_test.dart", "repo_id": "flutter", "token_count": 12879 }
545
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_gallery/gallery/app.dart' show GalleryApp; import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; } testWidgets('Flutter Gallery app simple smoke test', (WidgetTester tester) async { await tester.pumpWidget( const GalleryApp(testMode: true) // builds the app and schedules a frame but doesn't trigger one ); await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame final Finder showOptionsPageButton = find.byTooltip('Toggle options page'); // Show the options page await tester.tap(showOptionsPageButton); await tester.pumpAndSettle(); // Switch to the dark theme: the first switch control await tester.tap(find.byType(Switch).first); await tester.pumpAndSettle(); // Close the options page expect(showOptionsPageButton, findsOneWidget); await tester.tap(showOptionsPageButton); await tester.pumpAndSettle(); // Show the studies (aka "vignettes", aka "demos") await tester.tap(find.text('Studies')); await tester.pumpAndSettle(); // Show the Contact profile demo and scroll it upwards await tester.tap(find.text('Contact profile')); await tester.pumpAndSettle(); await tester.drag(find.text('(650) 555-1234'), const Offset(0.0, -50.0)); await tester.pump(const Duration(milliseconds: 200)); await tester.drag(find.text('(650) 555-1234'), const Offset(0.0, -50.0)); await tester.pump(const Duration(milliseconds: 200)); await tester.drag(find.text('(650) 555-1234'), const Offset(0.0, -50.0)); await tester.pump(const Duration(milliseconds: 200)); await tester.drag(find.text('(650) 555-1234'), const Offset(0.0, -50.0)); await tester.pump(const Duration(milliseconds: 200)); await tester.drag(find.text('(650) 555-1234'), const Offset(0.0, -50.0)); await tester.pump(const Duration(milliseconds: 200)); await tester.drag(find.text('(650) 555-1234'), const Offset(0.0, -50.0)); await tester.pump(const Duration(milliseconds: 200)); await tester.pump(const Duration(hours: 100)); // for testing }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.macOS })); }
flutter/dev/integration_tests/flutter_gallery/test/simple_smoke_test.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/simple_smoke_test.dart", "repo_id": "flutter", "token_count": 928 }
546
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; Future<void> main() async { late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() { driver.close(); }); // Each test below must return back to the home page after finishing. test('MotionEvent recomposition', () async { final SerializableFinder motionEventsListTile = find.byValueKey('MotionEventsListTile'); await driver.tap(motionEventsListTile); await driver.waitFor(find.byValueKey('PlatformView')); final String errorMessage = await driver.requestData('run test'); expect(errorMessage, ''); final SerializableFinder backButton = find.byValueKey('back'); await driver.tap(backButton); }, timeout: Timeout.none); group('Nested View Event', () { setUpAll(() async { final SerializableFinder wmListTile = find.byValueKey('NestedViewEventTile'); await driver.tap(wmListTile); }); tearDownAll(() async { await driver.waitFor(find.pageBack()); await driver.tap(find.pageBack()); }); test('AlertDialog from platform view context', () async { final SerializableFinder showAlertDialog = find.byValueKey('ShowAlertDialog'); await driver.waitFor(showAlertDialog); await driver.tap(showAlertDialog); final String status = await driver.getText(find.byValueKey('Status')); expect(status, 'Success'); }, timeout: Timeout.none); test('Child view can handle touches', () async { final SerializableFinder addChildView = find.byValueKey('AddChildView'); await driver.waitFor(addChildView); await driver.tap(addChildView); final SerializableFinder tapChildView = find.byValueKey('TapChildView'); await driver.tap(tapChildView); final String nestedViewClickCount = await driver.getText(find.byValueKey('NestedViewClickCount')); expect(nestedViewClickCount, 'Click count: 1'); }, timeout: Timeout.none); }); group('Flutter surface without hybrid composition', () { setUpAll(() async { await driver.tap(find.byValueKey('NestedViewEventTile')); }); tearDownAll(() async { await driver.waitFor(find.pageBack()); await driver.tap(find.pageBack()); }); test('Uses FlutterSurfaceView when Android view is on the screen', () async { await driver.waitFor(find.byValueKey('PlatformView')); expect( await driver.requestData('hierarchy'), '|-FlutterView\n' ' |-FlutterSurfaceView\n' // Flutter UI ' |-ViewGroup\n' // Platform View ' |-ViewGroup\n' ); // Hide platform view. final SerializableFinder togglePlatformView = find.byValueKey('TogglePlatformView'); await driver.tap(togglePlatformView); await driver.waitForAbsent(find.byValueKey('PlatformView')); expect( await driver.requestData('hierarchy'), '|-FlutterView\n' ' |-FlutterSurfaceView\n' // Just the Flutter UI ); // Show platform view again. await driver.tap(togglePlatformView); await driver.waitFor(find.byValueKey('PlatformView')); expect( await driver.requestData('hierarchy'), '|-FlutterView\n' ' |-FlutterSurfaceView\n' // Flutter UI ' |-ViewGroup\n' // Platform View ' |-ViewGroup\n' ); }, timeout: Timeout.none); }); group('Flutter surface with hybrid composition', () { setUpAll(() async { await driver.tap(find.byValueKey('NestedViewEventTile')); await driver.tap(find.byValueKey('ToggleHybridComposition')); await driver.tap(find.byValueKey('TogglePlatformView')); await driver.tap(find.byValueKey('TogglePlatformView')); }); tearDownAll(() async { await driver.waitFor(find.pageBack()); await driver.tap(find.pageBack()); }); test('Uses FlutterImageView when Android view is on the screen', () async { await driver.waitFor(find.byValueKey('PlatformView')); expect( await driver.requestData('hierarchy'), '|-FlutterView\n' ' |-FlutterSurfaceView\n' // Flutter UI (hidden) ' |-FlutterImageView\n' // Flutter UI (background surface) ' |-ViewGroup\n' // Platform View ' |-ViewGroup\n' ' |-FlutterImageView\n' // Flutter UI (overlay surface) ); // Hide platform view. final SerializableFinder togglePlatformView = find.byValueKey('TogglePlatformView'); await driver.tap(togglePlatformView); await driver.waitForAbsent(find.byValueKey('PlatformView')); expect( await driver.requestData('hierarchy'), '|-FlutterView\n' ' |-FlutterSurfaceView\n' // Just the Flutter UI ); // Show platform view again. await driver.tap(togglePlatformView); await driver.waitFor(find.byValueKey('PlatformView')); expect( await driver.requestData('hierarchy'), '|-FlutterView\n' ' |-FlutterSurfaceView\n' // Flutter UI (hidden) ' |-FlutterImageView\n' // Flutter UI (background surface) ' |-ViewGroup\n' // Platform View ' |-ViewGroup\n' ' |-FlutterImageView\n' // Flutter UI (overlay surface) ); }, timeout: Timeout.none); }); }
flutter/dev/integration_tests/hybrid_android_views/test_driver/main_test.dart/0
{ "file_path": "flutter/dev/integration_tests/hybrid_android_views/test_driver/main_test.dart", "repo_id": "flutter", "token_count": 2107 }
547
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "MainViewController.h" #import "AppDelegate.h" #import "DualFlutterViewController.h" #import "FullScreenViewController.h" #import "HybridViewController.h" #import "NativeViewController.h" @interface MainViewController () @property (weak, nonatomic) UIButton* flutterViewWarmButton; @end @implementation MainViewController { UIStackView *_stackView; } - (void)viewDidLoad { [super viewDidLoad]; [self.view setFrame:self.view.window.bounds]; self.title = @"Flutter iOS Demos Home"; self.view.backgroundColor = UIColor.whiteColor; _stackView = [[UIStackView alloc] initWithFrame:self.view.frame]; _stackView.axis = UILayoutConstraintAxisVertical; _stackView.distribution = UIStackViewDistributionEqualSpacing; _stackView.alignment = UIStackViewAlignmentCenter; _stackView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; _stackView.layoutMargins = UIEdgeInsetsMake(0, 0, 50, 0); _stackView.layoutMarginsRelativeArrangement = YES; [self.view addSubview:_stackView]; [self addButton:@"Native iOS View" action:@selector(showNative)]; [self addButton:@"Full Screen (Cold)" action:@selector(showFullScreenCold)]; [self addButton:@"Full Screen (Warm)" action:@selector(showFullScreenWarm)]; self.flutterViewWarmButton = [self addButton:@"Flutter View (Warm)" action:@selector(showFlutterViewWarm)]; [self addButton:@"Hybrid View (Warm)" action:@selector(showHybridView)]; [self addButton:@"Dual Flutter View (Cold)" action:@selector(showDualView)]; } - (FlutterEngine *)engine { return [(AppDelegate *)[[UIApplication sharedApplication] delegate] engine]; } - (FlutterBasicMessageChannel*)reloadMessageChannel { return [(AppDelegate *)[[UIApplication sharedApplication] delegate] reloadMessageChannel]; } - (void)showDualView { DualFlutterViewController *dualViewController = [[DualFlutterViewController alloc] init]; [self.navigationController pushViewController:dualViewController animated:YES]; } - (void)showHybridView { HybridViewController *hybridViewController = [[HybridViewController alloc] init]; [self.navigationController pushViewController:hybridViewController animated:YES]; } - (void)showNative { NativeViewController *nativeViewController = [[NativeViewController alloc] init]; [self.navigationController pushViewController:nativeViewController animated:YES]; } - (void)showFullScreenCold { FullScreenViewController *flutterViewController = [[FullScreenViewController alloc] init]; [flutterViewController setInitialRoute:@"full"]; [[self reloadMessageChannel] sendMessage:@"full"]; [self.navigationController pushViewController:flutterViewController animated:NO]; // Animating this is janky because of // transitions with header on the native side. // It's especially bad with a cold engine. } - (void)showFullScreenWarm { [[self engine].navigationChannel invokeMethod:@"setInitialRoute" arguments:@"full"]; [[self reloadMessageChannel] sendMessage:@"full"]; FullScreenViewController *flutterViewController = [[FullScreenViewController alloc] initWithEngine:[self engine] nibName:nil bundle:nil]; [self.navigationController pushViewController:flutterViewController animated:NO]; // Animating this is problematic. } - (void)showFlutterViewWarm { self.flutterViewWarmButton.backgroundColor = UIColor.redColor; FlutterEngine *engine = [self engine]; FlutterBasicMessageChannel* messageChannel = [self reloadMessageChannel]; NSAssert(engine != nil, @"Engine is not nil."); NSAssert(engine.navigationChannel != nil, @"Engine.navigationChannel is not nil."); NSAssert(messageChannel != nil, @"messageChannel is not nil."); [engine.navigationChannel invokeMethod:@"setInitialRoute" arguments:@"/"]; [messageChannel sendMessage:@"/"]; FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:[self engine] nibName:nil bundle:nil]; flutterViewController.view.accessibilityLabel = @"flutter view"; NSAssert(self.navigationController != nil, @"self.navigationController is not nil."); [self.navigationController pushViewController:flutterViewController animated:NO]; if (self.navigationController.topViewController != flutterViewController) { // For debugging: // Some unknown issue happened caused `flutterViewController` not being pushed. // We try to push an basic UIViewController to see if it would work. UIViewController *viewController = [[UIViewController alloc] init]; viewController.view.backgroundColor = UIColor.blueColor; [self.navigationController pushViewController:viewController animated:NO]; NSAssert(self.navigationController.topViewController == viewController, @"self.navigationController.topViewController should be the basic view controller"); } } - (UIButton *)addButton:(NSString *)title action:(SEL)action { UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setTitle:title forState:UIControlStateNormal]; [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside]; [_stackView addArrangedSubview:button]; return button; } @end
flutter/dev/integration_tests/ios_host_app/Host/MainViewController.m/0
{ "file_path": "flutter/dev/integration_tests/ios_host_app/Host/MainViewController.m", "repo_id": "flutter", "token_count": 2191 }
548
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import '../../gallery_localizations.dart'; // BEGIN cupertinoScrollbarDemo class CupertinoScrollbarDemo extends StatelessWidget { const CupertinoScrollbarDemo({super.key}); @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( automaticallyImplyLeading: false, middle: Text(localizations.demoCupertinoScrollbarTitle), ), child: CupertinoScrollbar( thickness: 6.0, thicknessWhileDragging: 10.0, radius: const Radius.circular(34.0), radiusWhileDragging: Radius.zero, child: ListView.builder( itemCount: 120, itemBuilder: (BuildContext context, int index) { return Center( child: Text('item $index', style: CupertinoTheme.of(context).textTheme.textStyle), ); }, ), ), ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_scrollbar_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_scrollbar_demo.dart", "repo_id": "flutter", "token_count": 484 }
549