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. #include "tonic/dart_class_library.h" #include "tonic/common/macros.h" #include "tonic/dart_wrapper_info.h" namespace tonic { DartClassLibrary::DartClassLibrary() {} DartClassLibrary::~DartClassLibrary() { // Note that we don't need to delete these persistent handles because this // object lives as long as the isolate. The handles will get deleted when the // isolate dies. } Dart_PersistentHandle DartClassLibrary::GetClass(const DartWrapperInfo& info) { const auto& result = info_cache_.insert(std::make_pair(&info, nullptr)); if (!result.second) { // Already present, return value. return result.first->second; } return GetAndCacheClass(info.library_name, info.interface_name, &result.first->second); } Dart_PersistentHandle DartClassLibrary::GetClass( const std::string& library_name, const std::string& interface_name) { auto key = std::make_pair(library_name, interface_name); const auto& result = name_cache_.insert(std::make_pair(key, nullptr)); if (!result.second) { // Already present, return value. return result.first->second; } return GetAndCacheClass(library_name.c_str(), interface_name.c_str(), &result.first->second); } Dart_PersistentHandle DartClassLibrary::GetAndCacheClass( const char* library_name, const char* interface_name, Dart_PersistentHandle* cache_slot) { auto it = providers_.find(library_name); TONIC_DCHECK(it != providers_.end()); Dart_Handle class_handle = it->second->GetClassByName(interface_name); *cache_slot = Dart_NewPersistentHandle(class_handle); return *cache_slot; } } // namespace tonic
engine/third_party/tonic/dart_class_library.cc/0
{ "file_path": "engine/third_party/tonic/dart_class_library.cc", "repo_id": "engine", "token_count": 620 }
412
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tonic/dart_weak_persistent_value.h" #include "tonic/dart_state.h" #include "tonic/scopes/dart_isolate_scope.h" namespace tonic { DartWeakPersistentValue::DartWeakPersistentValue() : handle_(nullptr) {} DartWeakPersistentValue::~DartWeakPersistentValue() { Clear(); } void DartWeakPersistentValue::Set(DartState* dart_state, Dart_Handle object, void* peer, intptr_t external_allocation_size, Dart_HandleFinalizer callback) { TONIC_DCHECK(is_empty()); dart_state_ = dart_state->GetWeakPtr(); handle_ = Dart_NewWeakPersistentHandle(object, peer, external_allocation_size, callback); } void DartWeakPersistentValue::Clear() { if (!handle_) { return; } auto dart_state = dart_state_.lock(); if (!dart_state) { // The DartVM that the handle used to belong to has been shut down and that // handle has already been deleted. handle_ = nullptr; return; } // The DartVM frees the handles during shutdown and calls the finalizers. // Freeing handles during shutdown would fail. if (!dart_state->IsShuttingDown()) { if (Dart_CurrentIsolateGroup()) { Dart_DeleteWeakPersistentHandle(handle_); } else { // If we are not on the mutator thread, this will fail. The caller must // ensure to be on the mutator thread. DartIsolateScope scope(dart_state->isolate()); Dart_DeleteWeakPersistentHandle(handle_); } } // If it's shutting down, the handle will be deleted already. dart_state_.reset(); handle_ = nullptr; } Dart_Handle DartWeakPersistentValue::Get() { auto dart_state = dart_state_.lock(); TONIC_DCHECK(dart_state); TONIC_DCHECK(!dart_state->IsShuttingDown()); if (!handle_) { return nullptr; } return Dart_HandleFromWeakPersistent(handle_); } } // namespace tonic
engine/third_party/tonic/dart_weak_persistent_value.cc/0
{ "file_path": "engine/third_party/tonic/dart_weak_persistent_value.cc", "repo_id": "engine", "token_count": 840 }
413
// 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 FILESYSTEM_PATH_H_ #define FILESYSTEM_PATH_H_ #include <string> namespace filesystem { // Resolves ".." and "." components of the path syntactically without consulting // the file system. std::string SimplifyPath(std::string path); // Returns the absolute path of a possibly relative path. // It doesn't consult the filesystem or simplify the path. std::string AbsolutePath(const std::string& path); // Returns the directory name component of the given path. std::string GetDirectoryName(const std::string& path); // Returns the basename component of the given path by stripping everything up // to and including the last slash. std::string GetBaseName(const std::string& path); // Returns the real path for the given path by unwinding symbolic links and // directory traversals. std::string GetAbsoluteFilePath(const std::string& path); } // namespace filesystem #endif // FILESYSTEM_PATH_H_
engine/third_party/tonic/filesystem/filesystem/path.h/0
{ "file_path": "engine/third_party/tonic/filesystem/filesystem/path.h", "repo_id": "engine", "token_count": 290 }
414
// 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 LIB_TONIC_PARSERS_PACKAGES_MAP_H_ #define LIB_TONIC_PARSERS_PACKAGES_MAP_H_ #include <string> #include <unordered_map> namespace tonic { class PackagesMap { public: PackagesMap(); ~PackagesMap(); bool Parse(const std::string& source, std::string* error); std::string Resolve(const std::string& package_name); private: std::unordered_map<std::string, std::string> map_; }; } // namespace tonic #endif // LIB_TONIC_PARSERS_PACKAGES_MAP_H_
engine/third_party/tonic/parsers/packages_map.h/0
{ "file_path": "engine/third_party/tonic/parsers/packages_map.h", "repo_id": "engine", "token_count": 222 }
415
// 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 LIB_TONIC_TYPED_DATA_TYPED_LIST_H_ #define LIB_TONIC_TYPED_DATA_TYPED_LIST_H_ #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/converter/dart_converter.h" namespace tonic { // A simple wrapper around Dart TypedData objects. It uses // Dart_TypedDataAcquireData to obtain a raw pointer to the data, which is // released when this object is destroyed. // // This is designed to be used with DartConverter only. template <Dart_TypedData_Type kTypeName, typename ElemType> class TypedList { public: explicit TypedList(Dart_Handle list); TypedList(TypedList<kTypeName, ElemType>&& other); TypedList(); ~TypedList(); ElemType& at(intptr_t i) { TONIC_CHECK(0 <= i); TONIC_CHECK(i < num_elements_); return data_[i]; } const ElemType& at(intptr_t i) const { TONIC_CHECK(0 <= i); TONIC_CHECK(i < num_elements_); return data_[i]; } ElemType& operator[](intptr_t i) { return at(i); } const ElemType& operator[](intptr_t i) const { return at(i); } const ElemType* data() const { return data_; } intptr_t num_elements() const { return num_elements_; } Dart_Handle dart_handle() const { return dart_handle_; } void Release(); private: ElemType* data_; intptr_t num_elements_; Dart_Handle dart_handle_; }; template <Dart_TypedData_Type kTypeName, typename ElemType> struct DartConverter<TypedList<kTypeName, ElemType>> { using NativeType = TypedList<kTypeName, ElemType>; using FfiType = Dart_Handle; static constexpr const char* kFfiRepresentation = "Handle"; static constexpr const char* kDartRepresentation = "Object"; static constexpr bool kAllowedInLeafCall = false; static void SetReturnValue(Dart_NativeArguments args, NativeType val); static NativeType FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception); static Dart_Handle ToDart(const ElemType* buffer, unsigned int length); static NativeType FromFfi(FfiType val) { return NativeType(val); } static FfiType ToFfi(NativeType val) { Dart_Handle handle = val.dart_handle(); val.Release(); return handle; } static const char* GetFfiRepresentation() { return kFfiRepresentation; } static const char* GetDartRepresentation() { return kDartRepresentation; } static bool AllowedInLeafCall() { return kAllowedInLeafCall; } }; #define TONIC_TYPED_DATA_FOREACH(F) \ F(Int8, int8_t) \ F(Uint8, uint8_t) \ F(Int16, int16_t) \ F(Uint16, uint16_t) \ F(Int32, int32_t) \ F(Uint32, uint32_t) \ F(Int64, int64_t) \ F(Uint64, uint64_t) \ F(Float32, float) \ F(Float64, double) #define TONIC_TYPED_DATA_DECLARE(name, type) \ using name##List = TypedList<Dart_TypedData_k##name, type>; \ extern template class TypedList<Dart_TypedData_k##name, type>; \ extern template struct DartConverter<name##List>; TONIC_TYPED_DATA_FOREACH(TONIC_TYPED_DATA_DECLARE) #undef TONIC_TYPED_DATA_DECLARE } // namespace tonic #endif // LIB_TONIC_TYPED_DATA_TYPED_LIST_H_
engine/third_party/tonic/typed_data/typed_list.h/0
{ "file_path": "engine/third_party/tonic/typed_data/typed_list.h", "repo_id": "engine", "token_count": 1413 }
416
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TXT_FONT_ASSET_PROVIDER_H_ #define TXT_FONT_ASSET_PROVIDER_H_ #include <string> #include "third_party/skia/include/core/SkFontMgr.h" namespace txt { class FontAssetProvider { public: virtual ~FontAssetProvider() = default; virtual size_t GetFamilyCount() const = 0; virtual std::string GetFamilyName(int index) const = 0; virtual sk_sp<SkFontStyleSet> MatchFamily(const std::string& family_name) = 0; protected: static std::string CanonicalFamilyName(std::string family_name); }; } // namespace txt #endif // TXT_FONT_ASSET_PROVIDER_H_
engine/third_party/txt/src/txt/font_asset_provider.h/0
{ "file_path": "engine/third_party/txt/src/txt/font_asset_provider.h", "repo_id": "engine", "token_count": 358 }
417
// 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 TXT_PLATFORM_H_ #define TXT_PLATFORM_H_ #include <string> #include <vector> #include "flutter/fml/macros.h" #include "third_party/skia/include/core/SkFontMgr.h" namespace txt { std::vector<std::string> GetDefaultFontFamilies(); sk_sp<SkFontMgr> GetDefaultFontManager(uint32_t font_initialization_data = 0); } // namespace txt #endif // TXT_PLATFORM_H_
engine/third_party/txt/src/txt/platform.h/0
{ "file_path": "engine/third_party/txt/src/txt/platform.h", "repo_id": "engine", "token_count": 194 }
418
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIB_TXT_SRC_TEXT_STYLE_H_ #define LIB_TXT_SRC_TEXT_STYLE_H_ #include <optional> #include <string> #include <vector> #include "flutter/display_list/dl_paint.h" #include "font_features.h" #include "font_style.h" #include "font_weight.h" #include "text_baseline.h" #include "text_decoration.h" #include "text_shadow.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkPaint.h" namespace txt { class TextStyle { public: SkColor color = SK_ColorWHITE; int decoration = TextDecoration::kNone; // Does not make sense to draw a transparent object, so we use it as a default // value to indicate no decoration color was set. SkColor decoration_color = SK_ColorTRANSPARENT; TextDecorationStyle decoration_style = TextDecorationStyle::kSolid; // Thickness is applied as a multiplier to the default thickness of the font. double decoration_thickness_multiplier = 1.0; FontWeight font_weight = FontWeight::w400; FontStyle font_style = FontStyle::normal; TextBaseline text_baseline = TextBaseline::kAlphabetic; bool half_leading = false; // An ordered list of fonts in order of priority. The first font is more // highly preferred than the last font. std::vector<std::string> font_families; double font_size = 14.0; double letter_spacing = 0.0; double word_spacing = 0.0; double height = 1.0; bool has_height_override = false; std::string locale; std::optional<flutter::DlPaint> background; std::optional<flutter::DlPaint> foreground; // An ordered list of shadows where the first shadow will be drawn first (at // the bottom). std::vector<TextShadow> text_shadows; FontFeatures font_features; FontVariations font_variations; TextStyle(); bool equals(const TextStyle& other) const; }; } // namespace txt #endif // LIB_TXT_SRC_TEXT_STYLE_H_
engine/third_party/txt/src/txt/text_style.h/0
{ "file_path": "engine/third_party/txt/src/txt/text_style.h", "repo_id": "engine", "token_count": 776 }
419
package: flutter/android/embedding_bundle description: Dependencies used by the Android embedding. data: - dir: lib
engine/tools/cipd/android_embedding_bundle/cipd.yaml/0
{ "file_path": "engine/tools/cipd/android_embedding_bundle/cipd.yaml", "repo_id": "engine", "token_count": 34 }
420
// 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' show exitCode; import 'package:compare_goldens/compare_goldens.dart' as compare_goldens; void main(List<String> args) { exitCode = compare_goldens.run(args); }
engine/tools/compare_goldens/bin/compare_goldens.dart/0
{ "file_path": "engine/tools/compare_goldens/bin/compare_goldens.dart", "repo_id": "engine", "token_count": 108 }
421
// 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 'target.dart'; void main() { Targets.used1.hit(); Targets.used2.hit(); final Target nonConstUsed3 = helper(Target.new); nonConstUsed3.hit(); } Target helper(Target Function(String, int, Target?) tearOff) { return tearOff('from tear-off', 3, null); } @staticIconProvider class Targets { static const Target used1 = Target('used1', 1, null); static const Target used2 = Target('used2', 2, null); static const Target unused1 = Target('unused1', 1, null); // ignore: unreachable_from_main } // const_finder explicitly does not retain constants appearing within a class // with this annotation. class StaticIconProvider { const StaticIconProvider(); } const StaticIconProvider staticIconProvider = StaticIconProvider();
engine/tools/const_finder/test/fixtures/lib/static_icon_provider.dart/0
{ "file_path": "engine/tools/const_finder/test/fixtures/lib/static_icon_provider.dart", "repo_id": "engine", "token_count": 261 }
422
#!/bin/bash if [[ $1 == '' ]]; then echo 'Usage: engine_roll_pr_desc.sh <from git hash>..<to git hash>' exit 1 fi git log --oneline --no-merges --no-color $1 | sed 's/^/flutter\/engine@/g' | sed -e 's/(\(#[0-9]*)\)/\(flutter\/engine\1/g'
engine/tools/engine_roll_pr_desc.sh/0
{ "file_path": "engine/tools/engine_roll_pr_desc.sh", "repo_id": "engine", "token_count": 112 }
423
// 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:ffi' as ffi show Abi; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:platform/platform.dart'; import 'package:process_runner/process_runner.dart'; import 'logger.dart'; /// This class encapsulates information about the host system. /// /// Rather than being written directly against `dart:io`, implementations in the /// tool should only access the system by way of the abstractions in this class. /// This is so that unit tests can be hermetic by providing fake /// implementations. final class Environment { /// Constructs the environment. Environment({ required this.abi, required this.engine, required this.logger, required this.platform, required this.processRunner, }); /// The host OS and architecture that the tool is running on. final ffi.Abi abi; /// Information about paths in the engine repo. final Engine engine; /// Where log messages are written. final Logger logger; /// More detailed information about the host platform. final Platform platform; /// Facility for commands to run subprocesses. final ProcessRunner processRunner; }
engine/tools/engine_tool/lib/src/environment.dart/0
{ "file_path": "engine/tools/engine_tool/lib/src/environment.dart", "repo_id": "engine", "token_count": 353 }
424
// 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:ffi' as ffi show Abi; import 'dart:io' as io; import 'package:engine_build_configs/engine_build_configs.dart'; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:engine_tool/src/commands/command_runner.dart'; import 'package:engine_tool/src/environment.dart'; import 'package:engine_tool/src/logger.dart'; import 'package:engine_tool/src/run_utils.dart'; import 'package:litetest/litetest.dart'; import 'package:platform/platform.dart'; import 'package:process_fakes/process_fakes.dart'; import 'package:process_runner/process_runner.dart'; import 'fixtures.dart' as fixtures; void main() { final Engine engine; try { engine = Engine.findWithin(); } catch (e) { io.stderr.writeln(e); io.exitCode = 1; return; } final BuilderConfig linuxTestConfig = BuilderConfig.fromJson( path: 'ci/builders/linux_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Linux')) as Map<String, Object?>, ); final BuilderConfig macTestConfig = BuilderConfig.fromJson( path: 'ci/builders/mac_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Mac-12')) as Map<String, Object?>, ); final BuilderConfig winTestConfig = BuilderConfig.fromJson( path: 'ci/builders/win_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Windows-11')) as Map<String, Object?>, ); final Map<String, BuilderConfig> configs = <String, BuilderConfig>{ 'linux_test_config': linuxTestConfig, 'linux_test_config2': linuxTestConfig, 'mac_test_config': macTestConfig, 'win_test_config': winTestConfig, }; (Environment, List<List<String>>) linuxEnv(Logger logger) { final List<List<String>> runHistory = <List<String>>[]; return ( Environment( abi: ffi.Abi.linuxX64, engine: engine, platform: FakePlatform( operatingSystem: Platform.linux, resolvedExecutable: io.Platform.resolvedExecutable), processRunner: ProcessRunner( processManager: FakeProcessManager(onStart: (List<String> command) { runHistory.add(command); switch (command) { case ['flutter', 'devices', '--machine']: return FakeProcess(stdout: fixtures.attachedDevices()); default: return FakeProcess(); } }, onRun: (List<String> command) { // Should not be executed. assert(false); return io.ProcessResult(81, 1, '', ''); }), ), logger: logger, ), runHistory ); } test('run command invokes flutter run', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>['run', '--', '--weird_argument']); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(6)); expect(runHistory[5], containsStringsInOrder(<String>['flutter', 'run', '--weird_argument'])); }); test('parse devices list', () async { final Logger logger = Logger.test(); final (Environment env, _) = linuxEnv(logger); final List<RunTarget> targets = parseDevices(env, fixtures.attachedDevices()); expect(targets.length, equals(4)); final RunTarget android = targets[0]; expect(android.name, contains('gphone64')); expect(android.buildConfigFor('debug'), equals('android_debug_arm64')); }); test('default device', () async { final Logger logger = Logger.test(); final (Environment env, _) = linuxEnv(logger); final List<RunTarget> targets = parseDevices(env, fixtures.attachedDevices()); expect(targets.length, equals(4)); final RunTarget? defaultTarget = defaultDevice(env, targets); expect(defaultTarget, isNotNull); expect(defaultTarget!.name, contains('gphone64')); expect( defaultTarget.buildConfigFor('debug'), equals('android_debug_arm64')); }); test('device select', () async { final Logger logger = Logger.test(); final (Environment env, _) = linuxEnv(logger); RunTarget target = selectRunTarget(env, fixtures.attachedDevices())!; expect(target.name, contains('gphone64')); target = selectRunTarget(env, fixtures.attachedDevices(), 'mac')!; expect(target.name, contains('macOS')); }); test('flutter run device select', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = linuxEnv(logger); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); // Request that the emulator device is used. The emulator is an Android // ARM64 device. final int result = await runner.run(<String>['run', '--', '-d', 'emulator']); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(6)); // Observe that we selected android_debug_arm64 as the target. expect( runHistory[5], containsStringsInOrder(<String>[ 'flutter', 'run', '--local-engine', 'android_debug_arm64', '--local-engine-host', 'host_debug', '-d', 'emulator' ])); }); }
engine/tools/engine_tool/test/run_command_test.dart/0
{ "file_path": "engine/tools/engine_tool/test/run_command_test.dart", "repo_id": "engine", "token_count": 2177 }
425
#!/usr/bin/env python3 # # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ''' Tests for font-subset ''' import argparse import filecmp import os import subprocess import sys from zipfile import ZipFile SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, '..', '..', '..')) MATERIAL_TTF = os.path.join(SCRIPT_DIR, 'fixtures', 'MaterialIcons-Regular.ttf') VARIABLE_MATERIAL_TTF = os.path.join(SCRIPT_DIR, 'fixtures', 'MaterialSymbols-Variable.ttf') COMPARE_TESTS = ( (True, '1.ttf', MATERIAL_TTF, [r'57347']), (True, '1.ttf', MATERIAL_TTF, [r'0xE003']), (True, '1.ttf', MATERIAL_TTF, [r'\uE003']), (False, '1.ttf', MATERIAL_TTF, [r'57348']), # False because different codepoint (True, '2.ttf', MATERIAL_TTF, [r'0xE003', r'0xE004']), (True, '2.ttf', MATERIAL_TTF, [r'0xE003', r'optional:0xE004']), # Optional codepoint that is found (True, '2.ttf', MATERIAL_TTF, [ r'0xE003', r'0xE004', r'optional:0x12', ]), # Optional codepoint that is not found (True, '2.ttf', MATERIAL_TTF, [ r'0xE003', r'0xE004', r'57347', ]), # Duplicated codepoint (True, '3.ttf', MATERIAL_TTF, [ r'0xE003', r'0xE004', r'0xE021', ]), # repeat tests with variable input font and verified variable output goldens (True, '1variable.ttf', VARIABLE_MATERIAL_TTF, [r'57347']), (True, '1variable.ttf', VARIABLE_MATERIAL_TTF, [r'0xE003']), (True, '1variable.ttf', VARIABLE_MATERIAL_TTF, [r'\uE003']), (False, '1variable.ttf', VARIABLE_MATERIAL_TTF, [r'57348' ]), # False because different codepoint (True, '2variable.ttf', VARIABLE_MATERIAL_TTF, [r'0xE003', r'0xE004']), (True, '2variable.ttf', VARIABLE_MATERIAL_TTF, [ r'0xE003', r'0xE004', r'57347', ]), # Duplicated codepoint (True, '3variable.ttf', VARIABLE_MATERIAL_TTF, [ r'0xE003', r'0xE004', r'0xE021', ]), ) def fail_tests(font_subset): return [ ([font_subset, 'output.ttf', 'does-not-exist.ttf'], [ '1', ]), # non-existent input font ([font_subset, 'output.ttf', MATERIAL_TTF], [ '0xFFFFFFFF', ]), # Value too big. ([font_subset, 'output.ttf', MATERIAL_TTF], [ '-1', ]), # invalid value ([font_subset, 'output.ttf', MATERIAL_TTF], [ 'foo', ]), # no valid values ([font_subset, 'output.ttf', MATERIAL_TTF], [ '0xE003', '0x12', '0xE004', ]), # codepoint not in font ([font_subset, 'non-existent-dir/output.ttf', MATERIAL_TTF], [ '0xE003', ]), # dir doesn't exist ([font_subset, 'output.ttf', MATERIAL_TTF], [ ' ', ]), # empty input ([font_subset, 'output.ttf', MATERIAL_TTF], []), # empty input ([font_subset, 'output.ttf', MATERIAL_TTF], ['']), # empty input # repeat tests with variable input font ([font_subset, 'output.ttf', VARIABLE_MATERIAL_TTF], [ '0xFFFFFFFF', ]), # Value too big. ([font_subset, 'output.ttf', VARIABLE_MATERIAL_TTF], [ '-1', ]), # invalid value ([font_subset, 'output.ttf', VARIABLE_MATERIAL_TTF], [ 'foo', ]), # no valid values ([font_subset, 'output.ttf', VARIABLE_MATERIAL_TTF], [ '0xE003', '0x12', '0xE004', ]), # codepoint not in font ([font_subset, 'non-existent-dir/output.ttf', VARIABLE_MATERIAL_TTF], [ '0xE003', ]), # dir doesn't exist ([font_subset, 'output.ttf', VARIABLE_MATERIAL_TTF], [ ' ', ]), # empty input ([font_subset, 'output.ttf', VARIABLE_MATERIAL_TTF], []), # empty input ([font_subset, 'output.ttf', VARIABLE_MATERIAL_TTF], ['']), # empty input ] def run_cmd(cmd, codepoints, fail=False): print('Running command:') print(' %s' % ' '.join(cmd)) print('STDIN: "%s"' % ' '.join(codepoints)) p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, cwd=SRC_DIR ) stdout_data, stderr_data = p.communicate(input=' '.join(codepoints).encode()) if p.returncode != 0 and fail == False: print('FAILURE: %s' % p.returncode) print('STDOUT:') print(stdout_data) print('STDERR:') print(stderr_data) elif p.returncode == 0 and fail == True: print('FAILURE - test passed but should have failed.') print('STDOUT:') print(stdout_data) print('STDERR:') print(stderr_data) else: print('Success.') return p.returncode def test_zip(font_subset_zip, exe): with ZipFile(font_subset_zip, 'r') as zip: files = zip.namelist() if 'font-subset%s' % exe not in files: print('expected %s to contain font-subset%s' % (files, exe)) return 1 return 0 # Maps the platform name to the output directory of the font artifacts. def platform_to_path(os, cpu): d = { 'darwin': 'darwin-', 'linux': 'linux-', 'linux2': 'linux-', 'cygwin': 'windows-', 'win': 'windows-', 'win32': 'windows-', } return d[os] + cpu def main(): parser = argparse.ArgumentParser(description='Runs font-subset tests.') parser.add_argument('--variant', type=str, required=True) parser.add_argument('--target-cpu', type=str, default='x64') args = parser.parse_args() variant = args.variant is_windows = sys.platform.startswith(('cygwin', 'win')) exe = '.exe' if is_windows else '' font_subset = os.path.join(SRC_DIR, 'out', variant, 'font-subset' + exe) font_subset_zip = os.path.join( SRC_DIR, 'out', variant, 'zip_archives', platform_to_path(sys.platform, args.target_cpu), 'font-subset.zip' ) if not os.path.isfile(font_subset): raise Exception( 'Could not locate font-subset%s in host_debug or host_debug_unopt - build before running this script.' % exe ) print('Using font subset binary at %s (%s)' % (font_subset, font_subset_zip)) failures = 0 failures += test_zip(font_subset_zip, exe) for should_pass, golden_font, input_font, codepoints in COMPARE_TESTS: gen_ttf = os.path.join(SCRIPT_DIR, 'gen', golden_font) golden_ttf = os.path.join(SCRIPT_DIR, 'fixtures', golden_font) cmd = [font_subset, gen_ttf, input_font] run_cmd(cmd, codepoints) cmp = filecmp.cmp(gen_ttf, golden_ttf, shallow=False) if (should_pass and not cmp) or (not should_pass and cmp): print('Test case %s failed.' % cmd) failures += 1 with open(os.devnull, 'w') as devnull: for cmd, codepoints in fail_tests(font_subset): if run_cmd(cmd, codepoints, fail=True) == 0: failures += 1 if failures > 0: print('%s test(s) failed.' % failures) return 1 print('All tests passed') return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/font_subset/test.py/0
{ "file_path": "engine/tools/font_subset/test.py", "repo_id": "engine", "token_count": 3349 }
426
#!/usr/bin/env python3 # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import stat import string import sys def main(): parser = argparse.ArgumentParser(description='Generate a script that invokes a Dart application') parser.add_argument('--out', help='Path to the invocation file to generate', required=True) parser.add_argument('--dart', help='Path to the Dart binary', required=True) parser.add_argument('--snapshot', help='Path to the app snapshot', required=True) args = parser.parse_args() app_file = args.out app_path = os.path.dirname(app_file) if not os.path.exists(app_path): os.makedirs(app_path) script_template = string.Template('''#!/bin/sh $dart \\ $snapshot \\ "$$@" ''') with open(app_file, 'w') as file: file.write(script_template.substitute(args.__dict__)) permissions = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH ) os.chmod(app_file, permissions) if __name__ == '__main__': sys.exit(main())
engine/tools/fuchsia/dart/gen_app_invocation.py/0
{ "file_path": "engine/tools/fuchsia/dart/gen_app_invocation.py", "repo_id": "engine", "token_count": 419 }
427
#!/bin/bash # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ### Runs the Fuchsia unit tests in the debug configuration. ### ### Arguments: ### --package-filter: Only runs tests in packages that match the given `find` statement. ### --gtest-filter: In the packages, only runs tests that match the given filter. ### For example: --gtest-filter "*FlatlandConnection*" to run any tests ### that have the phrase FlatlandConnection in them. ### --unoptimized: Disables C++ compiler optimizations. ### --count: Number of times to run the test. By default runs 1 time. ### See `ffx test run --count`. ### --goma: Speeds up builds for Googlers. sorry. :( set -e # Fail on any error. source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/lib/vars.sh || exit $? ensure_fuchsia_dir ensure_engine_dir ensure_ninja # Parse arguments. runtime_mode="debug" compilation_mode="jit" fuchsia_cpu="x64" goma=0 goma_flags="" ninja_cmd="ninja" package_filter="*tests-0.far" test_filter_flags="" unoptimized_flags="" unoptimized_suffix="" count_flags="" while [[ $# -gt 0 ]]; do case $1 in --package_filter|--package-filter) shift # past argument package_filter="$1" shift # past value ;; --count) shift # past argument count_flags="--count $1" shift # past value ;; --goma) goma=1 goma_flags="--goma" ninja_cmd="autoninja" shift # past argument ;; --unopt|--unoptimized) unoptimized_flags="--unoptimized" unoptimized_suffix="_unopt" shift # past argument ;; --gtest_filter|--gtest-filter) shift # past argument test_filter_flags="-- --gtest_filter=$1" shift # past value ;; *) engine-error "Unknown argument: $1" exit 1 ;; esac done all_gn_args="--fuchsia --no-lto --fuchsia-cpu="${fuchsia_cpu}" --runtime-mode="${runtime_mode}" ${goma_flags} ${unoptimized_flags}" engine-info "GN args: ${all_gn_args}" "${ENGINE_DIR}"/flutter/tools/gn ${all_gn_args} fuchsia_out_dir_name=fuchsia_${runtime_mode}${unoptimized_suffix}_${fuchsia_cpu} fuchsia_out_dir="${ENGINE_DIR}"/out/"${fuchsia_out_dir_name}" engine-info "Building ${fuchsia_out_dir_name}..." ${ninja_cmd} -C "${fuchsia_out_dir}" fuchsia_tests engine-info "Registering debug symbols..." # .jiri_root/bin/ffx needs to run from $FUCHSIA_DIR. pushd $FUCHSIA_DIR "$FUCHSIA_DIR"/.jiri_root/bin/ffx debug symbol-index add "${fuchsia_out_dir}"/.build-id --build-dir "${fuchsia_out_dir}" popd # $FUCHSIA_DIR test_packages="$(find ${fuchsia_out_dir} -name "${package_filter}")" engine-info "Publishing test packages..." test_names=() for test_package in $test_packages do engine-info "... publishing ${test_package} ..." ${FUCHSIA_DIR}/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive "${test_package}" test_names+=("$(basename ${test_package} | sed -e "s/-0.far//")") done # .jiri_root/bin/ffx needs to run from $FUCHSIA_DIR. pushd $FUCHSIA_DIR # TODO(akbiggs): Match the behavior of this script more closely with test_suites.yaml. engine-info "Running tests... (if this fails because of Launch(InstanceCannotResolve), run fx serve and try again)" for test_name in "${test_names[@]}" do # ParagraphTest.* fails in txt_tests. if [[ "${test_name}" == "txt_tests" ]] then engine-warning "Skipping txt_tests because I don't know how to filter out ParagraphTests.*" continue fi # ${test_filter_flags} must come last below because it includes " -- " to start program arguments. test_cmd="${FUCHSIA_DIR}/.jiri_root/bin/ffx test run fuchsia-pkg://fuchsia.com/${test_name}#meta/${test_name}.cm ${count_flags} ${test_filter_flags}" engine-info "... $test_cmd ..." $test_cmd done popd # $FUCHSIA_DIR
engine/tools/fuchsia/devshell/run_unit_tests.sh/0
{ "file_path": "engine/tools/fuchsia/devshell/run_unit_tests.sh", "repo_id": "engine", "token_count": 1563 }
428
#!/usr/bin/env python3 # # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ''' Interpolates build environment information into a file. ''' from argparse import ArgumentParser from datetime import datetime from os import path import subprocess import sys import json def GetDartPath(buildroot): dart_path = path.join(buildroot, 'flutter', 'third_party', 'dart') if not path.exists(dart_path): dart_path = path.join(buildroot, 'third_party', 'dart') return dart_path def GetDartSdkGitRevision(buildroot): return subprocess.check_output(['git', '-C', GetDartPath(buildroot), 'rev-parse', 'HEAD']).strip() def GetDartSdkSemanticVersion(buildroot): project_root = path.join(buildroot, 'third_party', 'dart') return subprocess.check_output(['git', '-C', GetDartPath(buildroot), 'describe', '--abbrev=0']).strip() def GetFlutterEngineGitRevision(buildroot): project_root = path.join(buildroot, 'flutter') return subprocess.check_output(['git', '-C', project_root, 'rev-parse', 'HEAD']).strip() def GetFuchsiaSdkVersion(buildroot): with open(path.join(buildroot, 'fuchsia', 'sdk', 'linux' if sys.platform.startswith('linux') else 'mac', 'meta', 'manifest.json'), 'r') as fuchsia_sdk_manifest: return json.load(fuchsia_sdk_manifest)['id'] def main(): # Parse arguments. parser = ArgumentParser() parser.add_argument('--input', action='store', help='input file path', required=True) parser.add_argument('--output', action='store', help='output file path', required=True) parser.add_argument( '--buildroot', action='store', help='path to the flutter engine buildroot', required=True ) args = parser.parse_args() # Read, interpolate, write. with open(args.input, 'r') as i, open(args.output, 'w') as o: o.write( i.read().replace( '{{DART_SDK_GIT_REVISION}}', GetDartSdkGitRevision(args.buildroot).decode('utf-8') ).replace( '{{DART_SDK_SEMANTIC_VERSION}}', GetDartSdkSemanticVersion(args.buildroot).decode('utf-8') ).replace( '{{FLUTTER_ENGINE_GIT_REVISION}}', GetFlutterEngineGitRevision(args.buildroot).decode('utf-8') ).replace('{{FUCHSIA_SDK_VERSION}}', GetFuchsiaSdkVersion(args.buildroot)) ) if __name__ == '__main__': main()
engine/tools/fuchsia/make_build_info.py/0
{ "file_path": "engine/tools/fuchsia/make_build_info.py", "repo_id": "engine", "token_count": 992 }
429
//--------------------------------------------------------------------------------------------- // Copyright (c) 2022 Google LLC // Licensed under the MIT License. See License.txt in the project root for license information. //--------------------------------------------------------------------------------------------*/ // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // // This file is auto generated by flutter/engine:flutter/tools/gen_web_keyboard_keymap based on // https://github.com/microsoft/vscode/tree/@@@COMMIT_ID@@@/src/vs/workbench/services/keybinding/browser/keyboardLayouts // // Edit the following files instead: // // - Script: lib/main.dart // - Templates: data/*.tmpl // // See flutter/engine:flutter/tools/gen_web_keyboard_keymap/README.md for more information. import 'package:test/test.dart'; import 'package:web_locale_keymap/web_locale_keymap.dart'; import 'testing.dart'; void testWin(LocaleKeymap mapping) { @@@WIN_CASES@@@ } void testLinux(LocaleKeymap mapping) { @@@LINUX_CASES@@@ } void testDarwin(LocaleKeymap mapping) { @@@DARWIN_CASES@@@ }
engine/tools/gen_web_locale_keymap/data/test_cases.dart.tmpl/0
{ "file_path": "engine/tools/gen_web_locale_keymap/data/test_cases.dart.tmpl", "repo_id": "engine", "token_count": 323 }
430
// 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:collection'; import 'dart:convert'; import 'dart:io' as io; import 'package:archive/archive.dart' as a; import 'package:path/path.dart' as path; import 'cache.dart'; import 'limits.dart'; import 'patterns.dart'; enum FileType { binary, // won't have its own license block text, // might have its own UTF-8 license block latin1Text, // might have its own Windows-1252 license block zip, // should be parsed as an archive and drilled into tar, // should be parsed as an archive and drilled into gz, // should be parsed as a single compressed file and exposed bzip2, // should be parsed as a single compressed file and exposed notPartOfBuild, // can be skipped entirely (e.g. Mac OS X ._foo files, bash scripts) } typedef Reader = List<int> Function(); class BytesOf extends Key { BytesOf(super.value); } class UTF8Of extends Key { UTF8Of(super.value); } class Latin1Of extends Key { Latin1Of(super.value); } bool matchesSignature(List<int> bytes, List<int> signature) { if (bytes.length < signature.length) { return false; } for (int index = 0; index < signature.length; index += 1) { if (signature[index] != -1 && bytes[index] != signature[index]) { return false; } } return true; } bool hasSubsequence(List<int> bytes, List<int> signature, int limit) { if (bytes.length < limit) { limit = bytes.length; } for (int index = 0; index < limit; index += 1) { if (bytes.length - index < signature.length) { return false; } for (int offset = 0; offset < signature.length; offset += 1) { if (signature[offset] != -1 && bytes[index + offset] != signature[offset]) { break; } if (offset + 1 == signature.length) { return true; } } } return false; } const String kMultiLicenseFileHeader = 'Notices for files contained in'; bool isMultiLicenseNotice(Reader reader) { final List<int> bytes = reader(); return ascii.decode(bytes.take(kMultiLicenseFileHeader.length).toList(), allowInvalid: true) == kMultiLicenseFileHeader; } FileType identifyFile(String name, Reader reader) { List<int>? bytes; if ((path.split(name).reversed.take(6).toList().reversed.join('/') == 'third_party/icu/source/extra/uconv/README') || // This specific ICU README isn't in UTF-8. (path.split(name).reversed.take(6).toList().reversed.join('/') == 'third_party/icu/source/samples/uresb/sr.txt') || // This specific sample contains non-UTF-8 data (unlike other sr.txt files). (path.split(name).reversed.take(2).toList().reversed.join('/') == 'builds/detect.mk') || // This specific freetype sample contains non-UTF-8 data (unlike other .mk files). (path.split(name).reversed.take(3).toList().reversed.join('/') == 'third_party/cares/cares.rc')) { return FileType.latin1Text; } if (path.split(name).reversed.take(6).toList().reversed.join('/') == 'dart/runtime/tests/vm/dart/bad_snapshot') { // Not any particular format return FileType.binary; } if (path.split(name).reversed.take(9).toList().reversed.join('/') == 'fuchsia/sdk/linux/dart/zircon/lib/src/fakes/handle_disposition.dart' || // has bogus but benign "authors" reference, reported to jamesr@ path.split(name).reversed.take(6).toList().reversed.join('/') == 'third_party/angle/src/common/fuchsia_egl/fuchsia_egl.c' || // has bogus but benign "authors" reference, reported to author and legal team path.split(name).reversed.take(6).toList().reversed.join('/') == 'third_party/angle/src/common/fuchsia_egl/fuchsia_egl.h' || // has bogus but benign "authors" reference, reported to author and legal team path.split(name).reversed.take(6).toList().reversed.join('/') == 'third_party/angle/src/common/fuchsia_egl/fuchsia_egl_backend.h') { // has bogus but benign "authors" reference, reported to author and legal team return FileType.binary; } final String base = path.basename(name); if (base.startsWith('._')) { bytes ??= reader(); if (matchesSignature(bytes, <int>[0x00, 0x05, 0x16, 0x07, 0x00, 0x02, 0x00, 0x00, 0x4d, 0x61, 0x63, 0x20, 0x4f, 0x53, 0x20, 0x58])) { return FileType.notPartOfBuild; } // The ._* files in Mac OS X archives that gives icons and stuff } if (path.split(name).contains('cairo')) { bytes ??= reader(); // "Copyright <latin1 copyright symbol> " if (hasSubsequence(bytes, <int>[0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0xA9, 0x20], kMaxSize)) { return FileType.latin1Text; } } switch (base) { // Build files case 'DEPS': return FileType.text; case 'MANIFEST': return FileType.text; // Licenses case 'COPYING': return FileType.text; case 'LICENSE': return FileType.text; case 'NOTICE.txt': return isMultiLicenseNotice(reader) ? FileType.binary : FileType.text; case 'NOTICE': return FileType.text; // Documentation case 'Changes': return FileType.text; case 'change.log': return FileType.text; case 'ChangeLog': return FileType.text; case 'CHANGES.0': return FileType.latin1Text; case 'README': return FileType.text; case 'TODO': return FileType.text; case 'NEWS': return FileType.text; case 'README.chromium': return FileType.text; case 'README.flutter': return FileType.text; case 'README.tests': return FileType.text; case 'OWNERS': return FileType.text; case 'AUTHORS': return FileType.text; // Signatures (found in .jar files typically) case 'CERT.RSA': return FileType.binary; case 'ECLIPSE_.RSA': return FileType.binary; // Binary data files case 'tzdata': return FileType.binary; case 'compressed_atrace_data.txt': return FileType.binary; // Source files that don't use UTF-8 case 'Messages_de_DE.properties': // has a few non-ASCII characters they forgot to escape (from gnu-libstdc++) case 'mmx_blendtmp.h': // author name in comment contains latin1 (mesa) case 'calling_convention.txt': // contains a soft hyphen instead of a real hyphen for some reason (mesa) // Character encoding data files case 'danish-ISO-8859-1.txt': case 'eucJP.txt': case 'hangul-eucKR.txt': case 'hania-eucKR.txt': case 'ibm-37-test.txt': case 'iso8859-1.txt': case 'ISO-8859-2.txt': case 'ISO-8859-3.txt': case 'koi8r.txt': return FileType.latin1Text; // Giant data files case 'icudtl_dat.S': case 'icudtl.dat': case 'icudtl.dat.hash': return FileType.binary; } switch (path.extension(name)) { // C/C++ code case '.h': return FileType.text; case '.c': return FileType.text; case '.cc': return FileType.text; case '.cpp': return FileType.text; case '.inc': return FileType.text; // Go code case '.go': return FileType.text; // ObjectiveC code case '.m': return FileType.text; // Assembler case '.asm': return FileType.text; // Shell case '.sh': return FileType.notPartOfBuild; case '.bat': return FileType.notPartOfBuild; // Build files case '.ac': return FileType.notPartOfBuild; case '.am': return FileType.notPartOfBuild; case '.gn': return FileType.notPartOfBuild; case '.gni': return FileType.notPartOfBuild; case '.gyp': return FileType.notPartOfBuild; case '.gypi': return FileType.notPartOfBuild; // Java code case '.java': return FileType.text; case '.jar': return FileType.zip; // Java package case '.class': return FileType.binary; // compiled Java bytecode (usually found inside .jar archives) case '.dex': return FileType.binary; // Dalvik Executable (usually found inside .jar archives) // Dart code case '.dart': return FileType.text; case '.dill': return FileType.binary; // Compiled Dart code // LLVM bitcode case '.bc': return FileType.binary; // Python code case '.py': bytes ??= reader(); // # -*- coding: Latin-1 -*- if (matchesSignature(bytes, <int>[0x23, 0x20, 0x2d, 0x2a, 0x2d, 0x20, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x4c, 0x61, 0x74, 0x69, 0x6e, 0x2d, 0x31, 0x20, 0x2d, 0x2a, 0x2d])) { return FileType.latin1Text; } return FileType.text; case '.pyc': return FileType.binary; // compiled Python bytecode // Machine code case '.so': return FileType.binary; // ELF shared object case '.xpt': return FileType.binary; // XPCOM Type Library // Graphics code case '.glsl': return FileType.text; case '.spvasm': return FileType.text; // Documentation case '.md': return FileType.text; case '.txt': return FileType.text; case '.html': return FileType.text; // Fonts case '.ttf': return FileType.binary; // TrueType Font case '.ttcf': // (mac) case '.ttc': return FileType.binary; // TrueType Collection (windows) case '.woff': return FileType.binary; // Web Open Font Format case '.otf': return FileType.binary; // OpenType Font // Graphics formats case '.gif': return FileType.binary; // GIF case '.png': return FileType.binary; // PNG case '.tga': return FileType.binary; // Truevision TGA (TARGA) case '.dng': return FileType.binary; // Digial Negative (Adobe RAW format) case '.jpg': case '.jpeg': return FileType.binary; // JPEG case '.ico': return FileType.binary; // Windows icon format case '.icns': return FileType.binary; // macOS icon format case '.bmp': return FileType.binary; // Windows bitmap format case '.wbmp': return FileType.binary; // Wireless bitmap format case '.webp': return FileType.binary; // WEBP case '.pdf': return FileType.binary; // PDF case '.emf': return FileType.binary; // Windows enhanced metafile format case '.skp': return FileType.binary; // Skia picture format case '.mskp': return FileType.binary; // Skia picture format case '.spv': return FileType.binary; // SPIR-V // Videos case '.ogg': return FileType.binary; // Ogg media case '.mp4': return FileType.binary; // MPEG media case '.ts': return FileType.binary; // MPEG2 transport stream // Other binary files case '.raw': return FileType.binary; // raw audio or graphical data case '.bin': return FileType.binary; // some sort of binary data case '.rsc': return FileType.binary; // some sort of resource data case '.arsc': return FileType.binary; // Android compiled resources case '.apk': return FileType.zip; // Android Package case '.crx': return FileType.binary; // Chrome extension case '.keystore': return FileType.binary; case '.icc': return FileType.binary; // Color profile case '.swp': return FileType.binary; // Vim swap file case '.bfbs': return FileType.binary; // Flatbuffers Binary Schema // Archives case '.zip': return FileType.zip; // ZIP case '.tar': return FileType.tar; // Tar case '.gz': return FileType.gz; // GZip case '.bzip2': return FileType.bzip2; // BZip2 // Image file types from the Fuchsia SDK. case '.blk': case '.vboot': case '.snapshot': case '.zbi': return FileType.binary; // Special cases case '.patch': case '.diff': // Don't try to read the copyright out of patch files, since there'll be fragments. return FileType.binary; case '.plist': // These commonly include the word "copyright" but in a way that isn't necessarily a copyright statement that applies to the file. // Since there's so few of them, and none have their own copyright statement, we just treat them as binary files. return FileType.binary; } bytes ??= reader(); assert(bytes.isNotEmpty); if (matchesSignature(bytes, <int>[0x1F, 0x8B])) { return FileType.gz; } // GZip archive if (matchesSignature(bytes, <int>[0x42, 0x5A])) { return FileType.bzip2; } // BZip2 archive if (matchesSignature(bytes, <int>[0x42, 0x43])) { return FileType.binary; } // LLVM Bitcode if (matchesSignature(bytes, <int>[0xAC, 0xED])) { return FileType.binary; } // Java serialized object if (matchesSignature(bytes, <int>[0x4D, 0x5A])) { return FileType.binary; } // MZ executable (DOS, Windows PEs, etc) if (matchesSignature(bytes, <int>[0xFF, 0xD8, 0xFF])) { return FileType.binary; } // JPEG if (matchesSignature(bytes, <int>[-1, -1, 0xda, 0x27])) { return FileType.binary; } // ICU data files (.brk, .dict, etc) if (matchesSignature(bytes, <int>[0x03, 0x00, 0x08, 0x00])) { return FileType.binary; } // Android Binary XML if (matchesSignature(bytes, <int>[0x25, 0x50, 0x44, 0x46])) { return FileType.binary; } // PDF if (matchesSignature(bytes, <int>[0x43, 0x72, 0x32, 0x34])) { return FileType.binary; } // Chrome extension if (matchesSignature(bytes, <int>[0x4F, 0x67, 0x67, 0x53])) { return FileType.binary; } // Ogg media if (matchesSignature(bytes, <int>[0x50, 0x4B, 0x03, 0x04])) { return FileType.zip; } // ZIP archive if (matchesSignature(bytes, <int>[0x7F, 0x45, 0x4C, 0x46])) { return FileType.binary; } // ELF if (matchesSignature(bytes, <int>[0xCA, 0xFE, 0xBA, 0xBE])) { return FileType.binary; } // compiled Java bytecode (usually found inside .jar archives) if (matchesSignature(bytes, <int>[0xCE, 0xFA, 0xED, 0xFE])) { return FileType.binary; } // Mach-O binary, 32 bit, reverse byte ordering scheme if (matchesSignature(bytes, <int>[0xCF, 0xFA, 0xED, 0xFE])) { return FileType.binary; } // Mach-O binary, 64 bit, reverse byte ordering scheme if (matchesSignature(bytes, <int>[0xFE, 0xED, 0xFA, 0xCE])) { return FileType.binary; } // Mach-O binary, 32 bit if (matchesSignature(bytes, <int>[0xFE, 0xED, 0xFA, 0xCF])) { return FileType.binary; } // Mach-O binary, 64 bit if (matchesSignature(bytes, <int>[0x75, 0x73, 0x74, 0x61, 0x72])) { return FileType.bzip2; } // Tar if (matchesSignature(bytes, <int>[0x47, 0x49, 0x46, 0x38, 0x37, 0x61])) { return FileType.binary; } // GIF87a if (matchesSignature(bytes, <int>[0x47, 0x49, 0x46, 0x38, 0x39, 0x61])) { return FileType.binary; } // GIF89a if (matchesSignature(bytes, <int>[0x64, 0x65, 0x78, 0x0A, 0x30, 0x33, 0x35, 0x00])) { return FileType.binary; } // Dalvik Executable if (matchesSignature(bytes, <int>[0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A])) { // TODO(ianh): implement .ar parser, https://github.com/flutter/flutter/issues/25633 return FileType.binary; // Unix archiver (ar) } if (matchesSignature(bytes, <int>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0a])) { return FileType.binary; } // PNG if (matchesSignature(bytes, <int>[0x58, 0x50, 0x43, 0x4f, 0x4d, 0x0a, 0x54, 0x79, 0x70, 0x65, 0x4c, 0x69, 0x62, 0x0d, 0x0a, 0x1a])) { return FileType.binary; } // XPCOM Type Library if (matchesSignature(bytes, <int>[0x23, 0x21])) { // #! indicates a shell script, those are not part of the build return FileType.notPartOfBuild; } return FileType.text; } String _normalize(String fileContents) { fileContents = fileContents.replaceAll(newlinePattern, '\n'); fileContents = fileContents.replaceAll('\t', ' ' * 4); return fileContents; } // INTERFACE // base class abstract class IoNode { // Subclasses of IoNode are not mutually exclusive. // For example, a ZIP file is represented as a File that also implements Directory. String get name; String get fullName; @override String toString() => fullName; } // interface abstract class File extends IoNode { List<int>? readBytes(); } // interface abstract class TextFile extends File { String readString(); } mixin UTF8TextFile implements TextFile { @override String readString() { try { return cache(UTF8Of(this), () => _normalize(utf8.decode(readBytes()!))); } on FormatException { print(fullName); rethrow; } } } mixin Latin1TextFile implements TextFile { @override String readString() { return cache(Latin1Of(this), () { final List<int> bytes = readBytes()!; if (bytes.any((int byte) => byte == 0x00)) { throw '$fullName contains a U+0000 NULL and is probably not actually encoded as Win1252'; } bool isUTF8 = false; try { cache(UTF8Of(this), () => utf8.decode(readBytes()!)); isUTF8 = true; } on FormatException { // Exceptions are fine/expected for non-UTF8 text, which we test for // immediately below. } if (isUTF8) { throw '$fullName contains valid UTF-8 and is probably not actually encoded as Win1252'; } return _normalize(latin1.decode(bytes)); }); } } // interface abstract class Directory extends IoNode { // lists children (shallow walk, not deep walk) Iterable<IoNode> get walk; } // interface abstract class Link extends IoNode { } mixin ZipFile on File implements Directory { ArchiveDirectory? _root; @override Iterable<IoNode> get walk { try { _root ??= ArchiveDirectory.parseArchive(a.ZipDecoder().decodeBytes(readBytes()!), fullName); return _root!.walk; } catch (exception) { print('failed to parse archive:\n$fullName'); rethrow; } } } mixin TarFile on File implements Directory { ArchiveDirectory? _root; @override Iterable<IoNode> get walk { try { _root ??= ArchiveDirectory.parseArchive(a.TarDecoder().decodeBytes(readBytes()!), fullName); return _root!.walk; } catch (exception) { print('failed to parse archive:\n$fullName'); rethrow; } } } mixin GZipFile on File implements Directory { InMemoryFile? _data; @override Iterable<IoNode> get walk sync* { try { final String innerName = path.basenameWithoutExtension(fullName); _data ??= InMemoryFile.parse('$fullName!$innerName', a.GZipDecoder().decodeBytes(readBytes()!))!; if (_data != null) { yield _data!; } } catch (exception) { print('failed to parse archive:\n$fullName'); rethrow; } } } mixin BZip2File on File implements Directory { InMemoryFile? _data; @override Iterable<IoNode> get walk sync* { try { final String innerName = path.basenameWithoutExtension(fullName); _data ??= InMemoryFile.parse('$fullName!$innerName', a.BZip2Decoder().decodeBytes(readBytes()!))!; if (_data != null) { yield _data!; } } catch (exception) { print('failed to parse archive:\n$fullName'); rethrow; } } } // FILESYSTEM IMPLEMENTATIoN class FileSystemDirectory extends IoNode implements Directory { FileSystemDirectory(this._directory); factory FileSystemDirectory.fromPath(String name) { return FileSystemDirectory(io.Directory(name)); } final io.Directory _directory; @override String get name => path.basename(_directory.path); @override String get fullName => _directory.path; List<int> _readBytes(io.File file) { return cache(BytesOf(file), () => file.readAsBytesSync()); } @override Iterable<IoNode> get walk sync* { final List<io.FileSystemEntity> list = _directory.listSync().toList(); list.sort((io.FileSystemEntity a, io.FileSystemEntity b) => a.path.compareTo(b.path)); for (final io.FileSystemEntity entity in list) { if (entity is io.Directory) { yield FileSystemDirectory(entity); } else if (entity is io.Link) { yield FileSystemLink(entity); } else { assert(entity is io.File); final io.File fileEntity = entity as io.File; if (fileEntity.lengthSync() > 0) { switch (identifyFile(fileEntity.path, () => _readBytes(fileEntity))) { case FileType.binary: yield FileSystemFile(fileEntity); case FileType.zip: yield FileSystemZipFile(fileEntity); case FileType.tar: yield FileSystemTarFile(fileEntity); case FileType.gz: yield FileSystemGZipFile(fileEntity); case FileType.bzip2: yield FileSystemBZip2File(fileEntity); case FileType.text: yield FileSystemUTF8TextFile(fileEntity); case FileType.latin1Text: yield FileSystemLatin1TextFile(fileEntity); case FileType.notPartOfBuild: break; // ignore this file } } } } } } class FileSystemLink extends IoNode implements Link { FileSystemLink(this._link); final io.Link _link; @override String get name => path.basename(_link.path); @override String get fullName => _link.path; } class FileSystemFile extends IoNode implements File { FileSystemFile(this._file); final io.File _file; @override String get name => path.basename(_file.path); @override String get fullName => _file.path; @override List<int> readBytes() { return cache(BytesOf(_file), () => _file.readAsBytesSync()); } } class FileSystemUTF8TextFile extends FileSystemFile with UTF8TextFile { FileSystemUTF8TextFile(super.file); } class FileSystemLatin1TextFile extends FileSystemFile with Latin1TextFile { FileSystemLatin1TextFile(super.file); } class FileSystemZipFile extends FileSystemFile with ZipFile { FileSystemZipFile(super.file); } class FileSystemTarFile extends FileSystemFile with TarFile { FileSystemTarFile(super.file); } class FileSystemGZipFile extends FileSystemFile with GZipFile { FileSystemGZipFile(super.file); } class FileSystemBZip2File extends FileSystemFile with BZip2File { FileSystemBZip2File(super.file); } // ARCHIVES class ArchiveDirectory extends IoNode implements Directory { ArchiveDirectory(this.fullName, this.name); @override final String fullName; @override final String name; final Map<String, ArchiveDirectory> _subdirectories = SplayTreeMap<String, ArchiveDirectory>(); final List<ArchiveFile> _files = <ArchiveFile>[]; void _add(a.ArchiveFile entry, List<String> remainingPath) { if (remainingPath.length > 1) { final String subdirectoryName = remainingPath.removeAt(0); _subdirectories.putIfAbsent( subdirectoryName, () => ArchiveDirectory('$fullName/$subdirectoryName', subdirectoryName) )._add(entry, remainingPath); } else { if (entry.size > 0) { final String entryFullName = '$fullName/${path.basename(entry.name)}'; switch (identifyFile(entry.name, () => entry.content as List<int>)) { case FileType.binary: _files.add(ArchiveFile(entryFullName, entry)); case FileType.zip: _files.add(ArchiveZipFile(entryFullName, entry)); case FileType.tar: _files.add(ArchiveTarFile(entryFullName, entry)); case FileType.gz: _files.add(ArchiveGZipFile(entryFullName, entry)); case FileType.bzip2: _files.add(ArchiveBZip2File(entryFullName, entry)); case FileType.text: _files.add(ArchiveUTF8TextFile(entryFullName, entry)); case FileType.latin1Text: _files.add(ArchiveLatin1TextFile(entryFullName, entry)); case FileType.notPartOfBuild: break; // ignore this file } } } } static ArchiveDirectory parseArchive(a.Archive archive, String ownerPath) { final ArchiveDirectory root = ArchiveDirectory('$ownerPath!', ''); for (final a.ArchiveFile file in archive.files) { if (file.size > 0) { root._add(file, file.name.split('/')); } } return root; } @override Iterable<IoNode> get walk sync* { yield* _subdirectories.values; yield* _files; } } class ArchiveFile extends IoNode implements File { ArchiveFile(this.fullName, this._file); final a.ArchiveFile _file; @override String get name => path.basename(_file.name); @override final String fullName; @override List<int>? readBytes() { return _file.content as List<int>?; } } class ArchiveUTF8TextFile extends ArchiveFile with UTF8TextFile { ArchiveUTF8TextFile(super.fullName, super.file); } class ArchiveLatin1TextFile extends ArchiveFile with Latin1TextFile { ArchiveLatin1TextFile(super.fullName, super.file); } class ArchiveZipFile extends ArchiveFile with ZipFile { ArchiveZipFile(super.fullName, super.file); } class ArchiveTarFile extends ArchiveFile with TarFile { ArchiveTarFile(super.fullName, super.file); } class ArchiveGZipFile extends ArchiveFile with GZipFile { ArchiveGZipFile(super.fullName, super.file); } class ArchiveBZip2File extends ArchiveFile with BZip2File { ArchiveBZip2File(super.fullName, super.file); } // IN-MEMORY FILES (e.g. contents of GZipped files) class InMemoryFile extends IoNode implements File { InMemoryFile(this.fullName, this._bytes); static InMemoryFile? parse(String fullName, List<int> bytes) { if (bytes.isEmpty) { return null; } switch (identifyFile(fullName, () => bytes)) { case FileType.binary: return InMemoryFile(fullName, bytes); case FileType.zip: return InMemoryZipFile(fullName, bytes); case FileType.tar: return InMemoryTarFile(fullName, bytes); case FileType.gz: return InMemoryGZipFile(fullName, bytes); case FileType.bzip2: return InMemoryBZip2File(fullName, bytes); case FileType.text: return InMemoryUTF8TextFile(fullName, bytes); case FileType.latin1Text: return InMemoryLatin1TextFile(fullName, bytes); case FileType.notPartOfBuild: break; // ignore this file } assert(false); return null; } final List<int> _bytes; @override String get name => '<data>'; @override final String fullName; @override List<int> readBytes() => _bytes; } class InMemoryUTF8TextFile extends InMemoryFile with UTF8TextFile { InMemoryUTF8TextFile(super.fullName, super.file); } class InMemoryLatin1TextFile extends InMemoryFile with Latin1TextFile { InMemoryLatin1TextFile(super.fullName, super.file); } class InMemoryZipFile extends InMemoryFile with ZipFile { InMemoryZipFile(super.fullName, super.file); } class InMemoryTarFile extends InMemoryFile with TarFile { InMemoryTarFile(super.fullName, super.file); } class InMemoryGZipFile extends InMemoryFile with GZipFile { InMemoryGZipFile(super.fullName, super.file); } class InMemoryBZip2File extends InMemoryFile with BZip2File { InMemoryBZip2File(super.fullName, super.file); }
engine/tools/licenses/lib/filesystem.dart/0
{ "file_path": "engine/tools/licenses/lib/filesystem.dart", "repo_id": "engine", "token_count": 9849 }
431
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "path_ops.h" namespace flutter { SkPath* CreatePath(SkPathFillType fill_type) { auto* path = new SkPath(); path->setFillType(fill_type); return path; } void DestroyPath(SkPath* path) { delete path; } void MoveTo(SkPath* path, SkScalar x, SkScalar y) { path->moveTo(x, y); } void LineTo(SkPath* path, SkScalar x, SkScalar y) { path->lineTo(x, y); } void CubicTo(SkPath* path, SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2, SkScalar x3, SkScalar y3) { path->cubicTo(x1, y1, x2, y2, x3, y3); } void Close(SkPath* path) { path->close(); } void Reset(SkPath* path) { path->reset(); } void Op(SkPath* one, SkPath* two, SkPathOp op) { Op(*one, *two, op, one); } int GetFillType(SkPath* path) { return static_cast<int>(path->getFillType()); } struct PathData* Data(SkPath* path) { int point_count = path->countPoints(); int verb_count = path->countVerbs(); auto data = new PathData(); data->points = new float[point_count * 2]; data->point_count = point_count * 2; data->verbs = new uint8_t[verb_count]; data->verb_count = verb_count; path->getVerbs(data->verbs, verb_count); path->getPoints(reinterpret_cast<SkPoint*>(data->points), point_count); return data; } void DestroyData(PathData* data) { delete[] data->points; delete[] data->verbs; delete data; } } // namespace flutter
engine/tools/path_ops/path_ops.cc/0
{ "file_path": "engine/tools/path_ops/path_ops.cc", "repo_id": "engine", "token_count": 658 }
432
// 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. const String buildConfigJson = ''' { "builds": [ { "archives": [ { "name": "build_name", "base_path": "base/path", "type": "gcs", "include_paths": ["include/path"], "realm": "archive_realm" } ], "drone_dimensions": [ "os=Linux" ], "gclient_variables": { "variable": false }, "gn": ["--gn-arg", "--lto", "--goma", "--no-rbe"], "name": "build_name", "ninja": { "config": "build_name", "targets": ["ninja_target"] }, "tests": [ { "language": "python3", "name": "build_name tests", "parameters": ["--test-params"], "script": "test/script.py", "contexts": ["context"] } ], "generators": { "tasks": [ { "name": "generator_task", "language": "python", "parameters": ["--gen-param"], "scripts": ["gen/script.py"] } ] } } ], "generators": { "tasks": [ { "name": "global generator task", "parameters": ["--global-gen-param"], "script": "global/gen_script.dart", "language": "dart" } ] }, "tests": [ { "name": "global test", "recipe": "engine_v2/tester_engine", "drone_dimensions": [ "os=Linux" ], "gclient_variables": { "variable": false }, "dependencies": ["dependency"], "test_dependencies": [ { "dependency": "test_dependency", "version": "git_revision:3a77d0b12c697a840ca0c7705208e8622dc94603" } ], "tasks": [ { "name": "global test task", "parameters": ["--test-parameter"], "script": "global/test/script.py" } ] } ] } ''';
engine/tools/pkg/engine_build_configs/test/fixtures.dart/0
{ "file_path": "engine/tools/pkg/engine_build_configs/test/fixtures.dart", "repo_id": "engine", "token_count": 1091 }
433
@ECHO off REM Copyright 2013 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 `yapf.sh` script in the same directory to ensure that it continues to REM work across all platforms! REM REM -------------------------------------------------------------------------- SET yapf_path=%~dp0\..\..\flutter\third_party\yapf cmd /V /C "SET PYTHONPATH=%yapf_path%&& vpython3 %yapf_path%\yapf %*"
engine/tools/yapf.bat/0
{ "file_path": "engine/tools/yapf.bat", "repo_id": "engine", "token_count": 172 }
434
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "vulkan_command_buffer.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" namespace vulkan { VulkanCommandBuffer::VulkanCommandBuffer( const VulkanProcTable& p_vk, const VulkanHandle<VkDevice>& device, const VulkanHandle<VkCommandPool>& pool) : vk_(p_vk), device_(device), pool_(pool), valid_(false) { const VkCommandBufferAllocateInfo allocate_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .pNext = nullptr, .commandPool = pool_, .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = 1, }; VkCommandBuffer buffer = VK_NULL_HANDLE; if (VK_CALL_LOG_ERROR(vk_.AllocateCommandBuffers(device_, &allocate_info, &buffer)) != VK_SUCCESS) { FML_DLOG(INFO) << "Could not allocate command buffers."; return; } auto buffer_collect = [this](VkCommandBuffer buffer) { vk_.FreeCommandBuffers(device_, pool_, 1, &buffer); }; handle_ = VulkanHandle<VkCommandBuffer>{buffer, buffer_collect}; valid_ = true; } VulkanCommandBuffer::~VulkanCommandBuffer() = default; bool VulkanCommandBuffer::IsValid() const { return valid_; } VkCommandBuffer VulkanCommandBuffer::Handle() const { return handle_; } bool VulkanCommandBuffer::Begin() const { const VkCommandBufferBeginInfo info{ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .pNext = nullptr, .flags = 0, .pInheritanceInfo = nullptr, }; return VK_CALL_LOG_ERROR(vk_.BeginCommandBuffer(handle_, &info)) == VK_SUCCESS; } bool VulkanCommandBuffer::End() const { return VK_CALL_LOG_ERROR(vk_.EndCommandBuffer(handle_)) == VK_SUCCESS; } bool VulkanCommandBuffer::InsertPipelineBarrier( VkPipelineStageFlagBits src_stage_flags, VkPipelineStageFlagBits dest_stage_flags, uint32_t /* mask of VkDependencyFlagBits */ dependency_flags, uint32_t memory_barrier_count, const VkMemoryBarrier* memory_barriers, uint32_t buffer_memory_barrier_count, const VkBufferMemoryBarrier* buffer_memory_barriers, uint32_t image_memory_barrier_count, const VkImageMemoryBarrier* image_memory_barriers) const { vk_.CmdPipelineBarrier(handle_, src_stage_flags, dest_stage_flags, dependency_flags, memory_barrier_count, memory_barriers, buffer_memory_barrier_count, buffer_memory_barriers, image_memory_barrier_count, image_memory_barriers); return true; } } // namespace vulkan
engine/vulkan/vulkan_command_buffer.cc/0
{ "file_path": "engine/vulkan/vulkan_command_buffer.cc", "repo_id": "engine", "token_count": 1099 }
435
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "vulkan_surface.h" #include "vulkan_application.h" #include "vulkan_native_surface.h" namespace vulkan { VulkanSurface::VulkanSurface( VulkanProcTable& p_vk, // NOLINT VulkanApplication& application, // NOLINT std::unique_ptr<VulkanNativeSurface> native_surface) : vk(p_vk), application_(application), native_surface_(std::move(native_surface)), valid_(false) { if (native_surface_ == nullptr || !native_surface_->IsValid()) { FML_DLOG(INFO) << "Native surface was invalid."; return; } VkSurfaceKHR surface = native_surface_->CreateSurfaceHandle(vk, application.GetInstance()); if (surface == VK_NULL_HANDLE) { FML_DLOG(INFO) << "Could not create the surface handle."; return; } surface_ = VulkanHandle<VkSurfaceKHR>{ surface, [this](VkSurfaceKHR surface) { vk.DestroySurfaceKHR(application_.GetInstance(), surface, nullptr); }}; valid_ = true; } VulkanSurface::~VulkanSurface() = default; bool VulkanSurface::IsValid() const { return valid_; } const VulkanHandle<VkSurfaceKHR>& VulkanSurface::Handle() const { return surface_; } const VulkanNativeSurface& VulkanSurface::GetNativeSurface() const { return *native_surface_; } SkISize VulkanSurface::GetSize() const { return valid_ ? native_surface_->GetSize() : SkISize::Make(0, 0); } } // namespace vulkan
engine/vulkan/vulkan_surface.cc/0
{ "file_path": "engine/vulkan/vulkan_surface.cc", "repo_id": "engine", "token_count": 565 }
436
// 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. // ignore_for_file: avoid_print // Checks that JavaScript API is accessed properly. // // JavaScript access needs to be audited to make sure it follows security best // practices. To do that, all JavaScript access is consolidated into a small // number of libraries that change infrequently. These libraries are manually // audited on every change. All other code accesses JavaScript through these // libraries and does not require audit. import 'dart:io'; import 'package:test/test.dart'; // Libraries that allow making arbitrary calls to JavaScript. const List<String> _jsAccessLibraries = <String>[ 'dart:js_util', 'package:js', ]; // Libraries that are allowed to make direct calls to JavaScript. These // libraries must be reviewed carefully to make sure JavaScript APIs are used // safely. const List<String> _auditedLibraries = <String>[ 'lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart', 'lib/web_ui/lib/src/engine/safe_browser_api.dart', ]; Future<void> main(List<String> args) async { bool shouldThrow = true; assert(() { shouldThrow = false; return true; }()); if (shouldThrow) { throw ArgumentError( 'This test must run with --enable-asserts', ); } test('Self-test', () { // A library that doesn't directly access JavaScript API should pass. { final _CheckResult result = _checkFile( File('lib/web_ui/lib/src/engine/alarm_clock.dart'), ''' // A comment import 'dart:async'; import 'package:ui/ui.dart' as ui; export 'foo.dart'; ''', ); expect(result.passed, isTrue); expect(result.failed, isFalse); expect(result.violations, isEmpty); } // Multi-line imports should fail. { final _CheckResult result = _checkFile( File('lib/web_ui/lib/src/engine/alarm_clock.dart'), ''' import 'dart:async'; import 'package:ui/ui.dart' as ui; ''', ); expect(result.failed, isTrue); expect(result.violations, <String>[ "on line 2: import is broken up into multiple lines: import 'package:ui/ui.dart'", ]); } // A library that doesn't directly access JavaScript API should pass. expect( _checkFile( File('lib/web_ui/lib/src/engine/alarm_clock.dart'), ''' import 'dart:async'; import 'package:ui/ui.dart' as ui; ''', ).passed, isTrue, ); // A non-audited library that directly accesses JavaScript API should fail. for (final String jsAccessLibrary in _jsAccessLibraries) { final _CheckResult result = _checkFile( File('lib/web_ui/lib/src/engine/alarm_clock.dart'), ''' import 'dart:async'; import 'package:ui/ui.dart' as ui; import '$jsAccessLibrary'; ''', ); expect(result.passed, isFalse); expect(result.failed, isTrue); expect(result.violations, <String>[ 'on line 3: library accesses $jsAccessLibrary directly', ]); } // Audited libraries that directly accesses JavaScript API should pass. for (final String auditedLibrary in _auditedLibraries) { for (final String jsAccessLibrary in _jsAccessLibraries) { expect( _checkFile( File(auditedLibrary), ''' import 'dart:async'; import 'package:ui/ui.dart' as ui; import '$jsAccessLibrary'; ''', ).passed, isTrue, ); } } }); test('Check JavaScript access', () async { final Directory webUiLibDir = Directory('lib/web_ui/lib'); final List<File> dartFiles = webUiLibDir .listSync(recursive: true) .whereType<File>() .where((File file) => file.path.endsWith('.dart')) .toList(); expect(dartFiles, isNotEmpty); final List<_CheckResult> results = <_CheckResult>[]; for (final File dartFile in dartFiles) { results.add(_checkFile( dartFile, await dartFile.readAsString(), )); } if (results.any((_CheckResult result) => result.failed)) { // Sort to show failures last. results.sort((_CheckResult a, _CheckResult b) { final int aSortKey = a.passed ? 1 : 0; final int bSortKey = b.passed ? 1 : 0; return bSortKey - aSortKey; }); int passedCount = 0; int failedCount = 0; for (final _CheckResult result in results) { if (result.passed) { passedCount += 1; print('PASSED: ${result.file.path}'); } else { failedCount += 1; print('FAILED: ${result.file.path}'); for (final String violation in result.violations) { print(' $violation'); } } } expect(passedCount + failedCount, dartFiles.length); print('$passedCount files passed. $failedCount files contain violations.'); fail('Some file contain violations. See log messages above for details.'); } }); } _CheckResult _checkFile(File dartFile, String code) { final List<String> violations = <String>[]; final List<String> lines = code.split('\n'); for (int i = 0; i < lines.length; i += 1) { final int lineNumber = i + 1; final String line = lines[i].trim(); final bool isImport = line.startsWith('import'); if (!isImport) { continue; } final bool isProperlyFormattedImport = line.endsWith(';'); if (!isProperlyFormattedImport) { violations.add('on line $lineNumber: import is broken up into multiple lines: $line'); continue; } if (line.contains('"')) { violations.add('on line $lineNumber: import is using double quotes instead of single quotes: $line'); continue; } final bool isAuditedLibrary = _auditedLibraries.contains(dartFile.path); if (isAuditedLibrary) { // This library is allowed to access JavaScript API directly. continue; } for (final String jsAccessLibrary in _jsAccessLibraries) { if (line.contains("'$jsAccessLibrary'")) { violations.add('on line $lineNumber: library accesses $jsAccessLibrary directly'); continue; } } } if (violations.isEmpty) { return _CheckResult.passed(dartFile); } else { return _CheckResult.failed(dartFile, violations); } } class _CheckResult { _CheckResult.passed(this.file) : violations = const <String>[]; _CheckResult.failed(this.file, this.violations) : assert(violations.isNotEmpty); /// The Dart file that was checked. final File file; /// If the check failed, contains the descriptions of violations. /// /// If the check passed, this is empty. final List<String> violations; /// Whether the file passed the check. bool get passed => violations.isEmpty; /// Whether the file failed the check. bool get failed => !passed; }
engine/web_sdk/test/js_access_test.dart/0
{ "file_path": "engine/web_sdk/test/js_access_test.dart", "repo_id": "engine", "token_count": 2570 }
437
<component name="ProjectCodeStyleConfiguration"> <state> <option name="USE_PER_PROJECT_SETTINGS" value="true" /> </state> </component>
flutter-intellij/.idea/codeStyles/codeStyleConfig.xml/0
{ "file_path": "flutter-intellij/.idea/codeStyles/codeStyleConfig.xml", "repo_id": "flutter-intellij", "token_count": 47 }
438
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="flutter-intellij [test]" type="GradleRunConfiguration" factoryName="Gradle"> <ExternalSystemSettings> <option name="executionName" /> <option name="externalProjectPath" value="$PROJECT_DIR$" /> <option name="externalSystemIdString" value="GRADLE" /> <option name="scriptParameters" value="" /> <option name="taskDescriptions"> <list /> </option> <option name="taskNames"> <list> <option value="test" /> </list> </option> <option name="vmOptions" value="" /> </ExternalSystemSettings> <ExternalSystemDebugServerProcess>false</ExternalSystemDebugServerProcess> <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess> <DebugAllEnabled>false</DebugAllEnabled> <method v="2"> <option name="ToolBeforeRunTask" enabled="true" actionId="Tool_External Tools_Provision" /> </method> </configuration> </component>
flutter-intellij/.idea/runConfigurations/flutter_intellij__test_.xml/0
{ "file_path": "flutter-intellij/.idea/runConfigurations/flutter_intellij__test_.xml", "repo_id": "flutter-intellij", "token_count": 362 }
439
# Plugin Smoke Testing Manual tests to execute before plugin releases. ## Setup Pre-reqs: Run through the [flutter setup](https://flutter.dev/docs/get-started/install) and [flutter getting started](https://flutter.dev/docs/development/tools/ide) guides. * Run `flutter upgrade` in a terminal to get the latest version prior to starting testing. ## Testing matrix * Testers should generally test against IntelliJ CE and Android Studio. * We also support internal IntelliJ; we should have testers assigned to each (IntelliJ CE, internal IntelliJ, and Android Studio) for every roll. * We support Windows, Mac, and Linux. We need to ensure the test script is run on all platforms for both IntelliJ and Android Studio. ## Project Creation Validate basic project creation. Find your other.xml (~/Library/Application Support/Google/<IDE>/options/other.xml) and remove FLUTTER_SDK_KNOWN_PATHS and remove `flutter` from your PATH. This might require a reboot. Start from the Welcome screen at least once. * Create a **simple project** (`File > New > Project...`, pick `Flutter`; on Android Studio, `File > New > New Flutter Project...`). * (select an `Application` type project) * use a project name that contains a space -- project location must be lowercase_with_underscores * Confirm that: * Project contents are created. * Verify that a run configuration (`main.dart`) is enabled in the run/debug selector. * Navigation works. * Open `lib/main.dart` and navigate to `AppBar`, from line 69 or so. * Verify that the new editor includes a 'View hosted code sample' banner. * There are no analysis errors or warnings. * Pub operations work. * Open `pubspec.yaml` and click the "Packages get" and "Packages upgrade" links. * Flutter operations work. * From the `Tools` menu, select `Flutter` > `Flutter Doctor`. * Code completion works. * Change `primarySwatch: Colors` to some other color and validate that you get completions. * `File > Project Structure` works. * Create a **plugin project** (`File > New > Project...`, pick `Flutter`; on Android Studio, `File > New > New Flutter Project...`), specify "Plugin" as the project type and select "Swift" for the iOS language. * Confirm that: * Project contents are created. * Verify that `<project root>/ios/Classes/Swift<Project Name>Plugin.swift` exists. * Verify that a run configuration (`main.dart`) is enabled in the run/debug selector. * `Open Android module in Android Studio` does the right thing * Navigate to and select `<project root>/android/src/main` * Select `Flutter > Open Android module in Android Studio` from the project list menu * Verify that the new project window allows editing of `<project root>/example/android/app` * Create a **module project** (`File > New > Project...`, pick `Flutter`; on Android Studio, `File > New > New Flutter Project...`), specify "Module" as the project type. * Confirm that: * Project contents are created. * Verify that a run configuration (`main.dart`) is enabled in the run/debug selector. * Verify that directories `.ios` and `.android` exist. * Run the app and verify that it starts correctly. * Stop the app. * Navigate to and select `<project root>/.android` * Select `Flutter > Open Android module in Android Studio` from the project list menu * Opening in a new window is recommended. If necessary change your preference/setting to allow that. * Verify that Gradle sync completes normally * Verify that the new project window allows editing of `app/java` (using the Android view of the project) * The file icon should be blue to indicate it is a source folder. ## Project Open Validate that our example projects can be opened. * close any open projects in IDEA * from the Welcome screen choose `Open` (IntelliJ) or `Open an existing Android Studio project` (AS) * browse to and select `<flutter-root>/examples/hello_world` * ensure there are no analysis errors or warnings * test that code completion is working as expected * ensure that the `main.dart` launch configuration shows up and is selected Validate that a `flutter create` project can opened. * close any open projects in IDEA * run `flutter create` in a terminal to create a new project `testcreate` * choose `File > Open...` and browse to and select the 'testcreate' project * or, type `idea .` or `studio .` from the CLI if you have the CLI launcher installed * ensure there are no analysis errors or warnings * test that code completion is working as expected * ensure that the `main.dart` launch configuration shows up and is selected ## Device Detection Validate device selection. ### Any OS * Physical Android device * Plug in a physical Android device * Ensure that a menu item appears in the device pull down for the device. * Emulated Android device * Start an Android emulator * Ensure that a menu item appears in the device pull down for the device. ### macOS only * Verify that the simulator can be opened. * Quit any open iOS simulator. * From the device pull-down, select "Open iOS Simulator" and verify that the simulator opens. ## Run / Debug Validate basic application running and debugging. In the newly created app: * plug in an Android device (or open the iOS Simulator) * set a breakpoint on the `_counter++` line * hit the `'debug'` icon to start the app running * verify the app appears on the device * tap the `'+'` icon on the app * verify that the IDE pauses at the breakpoint, and that the `Variables` pane has the right value for `_counter` * open the inspector * change the display by clicking `Render Tree` and the refresh button * open the performance view * hit resume in the debugger ## Hot Reload Validate basic hot reload functionality. Assuming the app state from above (i.e., leave the Debug session running): * modify the text for the `'You have pushed the button this many times:'` line * change the `_counter++` line to `_counter--` * hit the hot reload button in the debugger UI * validate that 1. the state persisted (the same number of clicks in the UI), and 2. the text changed to end in an exclamation point 3. the + button decreases the value Keybindings: * verify that the hot reload keybinding works (on a mac: `cmd-\ `) * verify that the reload-on-save feature works (hitting cmd-s / ctrl-s triggers a reload) ## Hot Restart * change the text and counter line back * hit the `Flutter Hot Restart` button (or hit the Debug button again) * validate that the text and state resets, and the count increases ## Debugging Sessions Validate that a sequence of sessions works as expected. After testing the above, terminate your debugging session and start another. * validate that a breakpoint is hit * verify that the reload keybinding works as expected ## Project Open Verification Verify that projects without Flutter project metadata open properly and are given the Flutter module type. * create a new Flutter project and delete IntelliJ metadata: * `flutter create foo_bar` * `cd foo_bar` * `rm -rf .idea` (Windows: `rd /s /q .idea`) * `rm foo_bar.iml` (Windows: `del foo_bar.iml`) * open project ("File > Open") * verify that the project has the Flutter module type (the device pull-down displays, the Flutter Outline window is present, etc.) and analyzes cleanly ## Fresh Install Configuration Verify installation and configuration in a fresh IDEA installation. * Follow the instructions to [simulate a fresh installation](https://github.com/flutter/flutter-intellij/wiki/Development#simulating-a-fresh-install). * (If not running in a "runtime workbench", [install the plugins](https://flutter.dev/docs/development/packages-and-plugins/using-packages).) * Open "Languages & Frameworks>Flutter" in Preferences and verify that there is no Flutter SDK set. * Set the Flutter SDK path to a valid SDK location. * Verify that invalid locations are rejected (and cannot be applied). * Verify project creation, run/debug. ## Add-to-app module integration test Create and debug a Flutter module in an Android app. Do this twice, once using Java and again with Kotlin as the language choice for the Android app. The location of the Flutter module is important. Put it in the Android app directory once and put it outside the app another time. ### Create an Android app Start Android Studio and use the File > New > New Project menu to open the new project wizard. Choose the template that includes a Basic Activity. On the next page, use Kotlin and minimum API level 16. Let the system stabilize (Gradle sync). Switch the Project view to the Project Files mode. Collapse the Gradle window if it is open. ### Create a Flutter module Use the File > New > New Module menu to start the new module wizard. Choose the Flutter Module template. Fill out the wizard pages and click Finish, then wait a bit. Android Studio needs to do two successive Gradle sync's. The first one generates an error message, which is corrected by the second one. Ignore the error. Let the system stabilize again. ### Link the Flutter module to the Android app Go to the editor for MainActivity.kt. Change the onCreate method: ```kotlin override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar)) val engine = FlutterEngine(this.applicationContext) engine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view -> FlutterEngineCache.getInstance().put("1", engine) startActivity(FlutterActivity.withCachedEngine("1").build(this)) } } ``` If you opted to use Java, use this: ```java public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FlutterEngine engine = new FlutterEngine(getApplicationContext()); engine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()); findViewById(R.id.fab).setOnClickListener(view -> { FlutterEngineCache.getInstance().put("1", engine); startActivity(FlutterActivity.withCachedEngine("1").build(this)); }); } ``` You need to add some imports. Click on each red name then type `alt-return`. Accept the suggestion. "FlutterActivity" has two choices; use the one from the io.flutter.embedGradle library, io.flutter.embedding.android.FlutterActivity. Open an editor on the AndroidManifest.xml. Add this line to the <application> tag: ```xml <activity android:name="io.flutter.embedding.android.FlutterActivity" /> ``` At this point, click the "hammer" icon to build the application. ### Debug the app The run config should show the Flutter run config, which makes the Flutter Attach button active. Click the Flutter Attach button, or use the menu item Run > Flutter Attach. (Note: with the kotlin code above you need to start the attach process before starting the Android app.) Change the run config to "app" for the Android app. Click the Debug button. Wait for the app to launch. When the app is visible, click the mail icon at bottom right. The Flutter screen should become visible. At this point you can set breakpoints and do hot reload as for a stand-alone Flutter app.
flutter-intellij/docs/testing.md/0
{ "file_path": "flutter-intellij/docs/testing.md", "repo_id": "flutter-intellij", "token_count": 3209 }
440
/* * 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.fixtures import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.testGuiFramework.fixtures.IdeFrameFixture import com.intellij.testGuiFramework.fixtures.JBCheckBoxFixture import com.intellij.testGuiFramework.fixtures.JComponentFixture import com.intellij.testGuiFramework.fixtures.ToolWindowFixture import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.GuiTestUtilKt import com.intellij.testGuiFramework.matcher.ClassNameMatcher import com.intellij.testGuiFramework.util.step import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBLabel import io.flutter.inspector.HeapDisplay import io.flutter.view.PerfFPSTab import io.flutter.view.PerfMemoryTab import org.fest.swing.core.ComponentFinder import org.fest.swing.core.Robot import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause.pause import java.awt.Component import javax.swing.JPanel fun IdeFrameFixture.flutterPerfFixture(ideFrame: IdeFrameFixture): FlutterPerfFixture { return FlutterPerfFixture(project, robot(), ideFrame) } // A fixture for the Performance top-level view. class FlutterPerfFixture(project: Project, robot: Robot, private val ideFrame: IdeFrameFixture) : ToolWindowFixture("Flutter Performance", project, robot) { fun populate() { step("Populate perf view") { activate() selectedContent pause(object : Condition("Initialize perf") { override fun test(): Boolean { return contents[0].displayName != null } }, Timeouts.seconds30) GuiTestUtilKt.waitForBackgroundTasks(myRobot) } } fun memoryTabFixture(): MemoryTabFixture { showTab(1, contents) val base = perfPanel(classMatcher(PerfMemoryTab::class.java)) return MemoryTabFixture(base) } fun perfTabFixture(): PerfTabFixture { showTab(0, contents) val base = perfPanel(classMatcher(PerfFPSTab::class.java)) return PerfTabFixture(base) } private fun <T : Component> perfPanel(matcher: ClassNameMatcher<T>): T { val panelRef = Ref<T>() pause(object : Condition("Perf panel shows up") { override fun test(): Boolean { val panels = finder().findAll(contents[0].component, matcher) if (panels.isEmpty()) { return false } else { panelRef.set(panels.first()) return true } } }, Timeouts.seconds10) return panelRef.get()!! } private fun finder(): ComponentFinder { return ideFrame.robot().finder() } private fun <T : Component> classMatcher(base: Class<T>): ClassNameMatcher<T> { return ClassNameMatcher.forClass(base.name, base) } inner class MemoryTabFixture(val memoryTab: PerfMemoryTab) { fun heapDisplayLabels(): Collection<JBLabel> { return finder().findAll(memoryTab, classMatcher(JBLabel::class.java)) } fun heapDisplay(): HeapDisplayFixture { return HeapDisplayFixture(myRobot, finder().find(memoryTab, classMatcher(HeapDisplay::class.java))) } } inner class PerfTabFixture(val fpsTab: PerfFPSTab) { fun controlCheckboxes(): Collection<JBCheckBox> { return finder().findAll(fpsTab, classMatcher(JBCheckBox::class.java)) } fun performanceCheckbox(): JBCheckBoxFixture { return JBCheckBoxFixture.findByText("Show Performance Overlay", fpsTab, myRobot, true) } fun repaintCheckbox(): JBCheckBoxFixture { return JBCheckBoxFixture.findByText("Show Repaint Rainbow", fpsTab, myRobot, true) } fun frameRenderingPanel(): FrameRenderingPanelFixture { // FrameRenderingPanel is not public, but we only need JPanel protocol, like componentCount. return FrameRenderingPanelFixture(myRobot, finder().find(fpsTab, ClassNameMatcher.forClass("io.flutter.inspector.FrameRenderingPanel", JPanel::class.java))) } } inner class FrameRenderingPanelFixture(robot: Robot, target: JPanel) : JComponentFixture<FrameRenderingPanelFixture, JPanel>(FrameRenderingPanelFixture::class.java, robot, target) { fun componentCount(): Int { return GuiTestUtilKt.computeOnEdt { target().componentCount }!! } } inner class HeapDisplayFixture(robot: Robot, target: JPanel) : JComponentFixture<HeapDisplayFixture, JPanel>(HeapDisplayFixture::class.java, robot, target) }
flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/fixtures/FlutterPerfFixture.kt/0
{ "file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/fixtures/FlutterPerfFixture.kt", "repo_id": "flutter-intellij", "token_count": 1666 }
441
/* * 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.actions; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import io.flutter.FlutterBundle; import io.flutter.FlutterInitializer; import io.flutter.FlutterMessages; import io.flutter.FlutterUtils; import io.flutter.bazel.Workspace; import io.flutter.pub.PubRoot; import io.flutter.pub.PubRoots; import io.flutter.sdk.FlutterSdk; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * Base class for Flutter commands. */ public abstract class FlutterSdkAction extends DumbAwareAction { private static final Logger LOG = Logger.getInstance(FlutterSdkAction.class); @Override public void actionPerformed(@NotNull AnActionEvent event) { final Project project = DumbAwareAction.getEventProject(event); if (enableActionInBazelContext()) { // See if the Bazel workspace exists for this project. final Workspace workspace = FlutterModuleUtils.getFlutterBazelWorkspace(project); if (workspace != null) { FlutterInitializer.sendAnalyticsAction(this); FileDocumentManager.getInstance().saveAllDocuments(); startCommandInBazelContext(project, workspace, event); return; } } final FlutterSdk sdk = project != null ? FlutterSdk.getFlutterSdk(project) : null; if (sdk == null) { showMissingSdkDialog(project); return; } FlutterInitializer.sendAnalyticsAction(this); FileDocumentManager.getInstance().saveAllDocuments(); PubRoot root = PubRoot.forEventWithRefresh(event); @NotNull DataContext context = event.getDataContext(); if (root != null) { startCommand(project, sdk, root, context); } else { List<PubRoot> roots = PubRoots.forProject(project); for (PubRoot sub : roots) { startCommand(project, sdk, sub, context); } } } public abstract void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nullable PubRoot root, @NotNull DataContext context); /** * Implemented by actions which are used in the Bazel context ({@link #enableActionInBazelContext()} returns true), by default this method * throws an {@link Error}. */ public void startCommandInBazelContext(@NotNull Project project, @NotNull Workspace workspace, @NotNull AnActionEvent event) { throw new Error("This method should not be called directly, but should be overridden."); } /** * By default this method returns false. For actions which can be used in the Bazel context this method should return true. */ public boolean enableActionInBazelContext() { return false; } public static void showMissingSdkDialog(Project project) { final int response = FlutterMessages.showDialog(project, FlutterBundle.message("flutter.sdk.notAvailable.message"), FlutterBundle.message("flutter.sdk.notAvailable.title"), new String[]{"Yes, configure", "No, thanks"}, -1); if (response == 0) { FlutterUtils.openFlutterSettings(project); } } }
flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterSdkAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterSdkAction.java", "repo_id": "flutter-intellij", "token_count": 1353 }
442
/* * 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.actions; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.FlutterConstants; import io.flutter.FlutterInitializer; import io.flutter.FlutterMessages; import io.flutter.bazel.WorkspaceCache; import io.flutter.run.FlutterReloadManager; import io.flutter.run.daemon.FlutterApp; import io.flutter.settings.FlutterSettings; import org.jetbrains.annotations.NotNull; public class RestartFlutterApp extends FlutterAppAction { public static final String ID = "Flutter.RestartFlutterApp"; //NON-NLS public static final String TEXT = FlutterBundle.message("app.restart.action.text"); public static final String DESCRIPTION = FlutterBundle.message("app.restart.action.description"); public RestartFlutterApp(@NotNull FlutterApp app, @NotNull Computable<Boolean> isApplicable) { super(app, TEXT, DESCRIPTION, FlutterIcons.HotRestart, isApplicable, ID); // Shortcut is associated with toolbar action. copyShortcutFrom(ActionManager.getInstance().getAction("Flutter.Toolbar.RestartAction")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { final Project project = getEventProject(e); if (project == null) { return; } FlutterInitializer.sendAnalyticsAction(this); FlutterReloadManager.getInstance(project).saveAllAndRestart(getApp(), FlutterConstants.RELOAD_REASON_MANUAL); if (WorkspaceCache.getInstance(project).isBazel() && FlutterSettings.getInstance().isShowBazelHotRestartWarning() && !FlutterSettings.getInstance().isEnableBazelHotRestart()) { final Notification notification = new Notification( FlutterMessages.FLUTTER_NOTIFICATION_GROUP_ID, "Hot restart is not google3-specific", "Hot restart now disables google3-specific support by default. This makes hot restart faster and more robust, but hot " + "restart will not update generated files. To enable google3 hot restart, go to Settings > Flutter.", NotificationType.INFORMATION); Notifications.Bus.notify(notification, project); // We only want to show this notification once. FlutterSettings.getInstance().setShowBazelHotRestartWarning(false); } } }
flutter-intellij/flutter-idea/src/io/flutter/actions/RestartFlutterApp.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/RestartFlutterApp.java", "repo_id": "flutter-intellij", "token_count": 873 }
443
/* * 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.android; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.EnvironmentUtil; import io.flutter.sdk.FlutterSdk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; /** * An Android SDK and its home directory; this references an IntelliJ @{@link Sdk} instance. */ public class IntelliJAndroidSdk { private static final Logger LOG = Logger.getInstance(IntelliJAndroidSdk.class); @NotNull private final Sdk sdk; @NotNull private final VirtualFile home; private IntelliJAndroidSdk(@NotNull Sdk sdk, @NotNull VirtualFile home) { this.sdk = sdk; this.home = home; } /** * Returns android home directory for this SDK. */ @NotNull public VirtualFile getHome() { return home; } /** * Changes the project's Java SDK to this one. */ public void setCurrent(@NotNull Project project) { assert ApplicationManager.getApplication().isWriteAccessAllowed(); final ProjectRootManager roots = ProjectRootManager.getInstance(project); roots.setProjectSdk(sdk); } /** * Returns the Java SDK in the project's configuration, or null if not an Android SDK. */ @Nullable public static IntelliJAndroidSdk fromProject(@NotNull Project project) { final Sdk candidate = ProjectRootManager.getInstance(project).getProjectSdk(); return fromSdk(candidate); } /** * Returns the Android SDK that matches the ANDROID_HOME environment variable, provided it exists. */ @Nullable public static IntelliJAndroidSdk fromEnvironment() { final String path = EnvironmentUtil.getValue("ANDROID_HOME"); if (path == null) { return null; } // TODO(skybrian) refresh? final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); if (file == null) { return null; } return fromHome(file); } /** * Returns the Android SDK for the given home directory, or null if no SDK matches. */ @Nullable public static IntelliJAndroidSdk fromHome(VirtualFile file) { for (IntelliJAndroidSdk candidate : findAll()) { if (file.equals(candidate.getHome())) { return candidate; } } return null; // not found } /** * Returns the best value of the Android SDK location to use, including possibly querying flutter tools for it. */ public static String chooseAndroidHome(@Nullable Project project, boolean askFlutterTools) { if (project == null) { return EnvironmentUtil.getValue("ANDROID_HOME"); } final IntelliJAndroidSdk intelliJAndroidSdk = fromProject(project); if (intelliJAndroidSdk != null) { return intelliJAndroidSdk.getHome().getPath(); } // Ask flutter tools. if (askFlutterTools) { final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project); if (flutterSdk != null) { final String androidSdkLocation = flutterSdk.queryFlutterConfig("android-sdk", true); if (androidSdkLocation != null) { return androidSdkLocation; } } } return EnvironmentUtil.getValue("ANDROID_HOME"); } /** * Returns each SDK that's an Android SDK. */ @NotNull private static List<IntelliJAndroidSdk> findAll() { final List<IntelliJAndroidSdk> result = new ArrayList<>(); for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) { final IntelliJAndroidSdk candidate = IntelliJAndroidSdk.fromSdk(sdk); if (candidate != null) { result.add(candidate); } } return result; } @Nullable private static IntelliJAndroidSdk fromSdk(@Nullable Sdk candidate) { if (candidate == null) { return null; } if (!"Android SDK".equals(candidate.getSdkType().getName())) { return null; } final VirtualFile home = candidate.getHomeDirectory(); if (home == null) { return null; // Skip; misconfigured SDK? } return new IntelliJAndroidSdk(candidate, home); } }
flutter-intellij/flutter-idea/src/io/flutter/android/IntelliJAndroidSdk.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/android/IntelliJAndroidSdk.java", "repo_id": "flutter-intellij", "token_count": 1593 }
444
/* * Copyright 2023 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.devtools; /** * This identifies from what feature DevTools is started. See https://github.com/flutter/flutter-intellij/issues/7100 for details. */ public enum DevToolsIdeFeature { ON_DEBUG_AUTOMATIC("onDebugAutomatic"), RUN_CONSOLE("runConsole"), TOOL_WINDOW("toolWindow"), TOOL_WINDOW_RELOAD("toolWindowReload"); public final String value; DevToolsIdeFeature(String value) { this.value = value; } }
flutter-intellij/flutter-idea/src/io/flutter/devtools/DevToolsIdeFeature.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/devtools/DevToolsIdeFeature.java", "repo_id": "flutter-intellij", "token_count": 192 }
445
/* * 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.ui.Gray; import com.intellij.ui.JBColor; import java.awt.*; public class FlutterEditorColors { // These colors are by design identical for the light and dark theme. @SuppressWarnings("UseJBColor") public final static Color TOOLTIP_BACKGROUND_COLOR = new Color(60, 60, 60, 230); @SuppressWarnings("UseJBColor") public final static Color HIGHLIGHTED_RENDER_OBJECT_FILL_COLOR = new Color(128, 128, 255, 128); @SuppressWarnings("UseJBColor") public final static Color HIGHLIGHTED_RENDER_OBJECT_BORDER_COLOR = new Color(64, 64, 128, 128); public final static JBColor VERY_LIGHT_GRAY = new JBColor(Gray._224, Gray._80); public final static JBColor SHADOW_GRAY = new JBColor(Gray._192, Gray._100); public final static JBColor OUTLINE_LINE_COLOR = new JBColor(Gray._128, Gray._128); public final static JBColor OUTLINE_LINE_COLOR_PAST_BLOCK = new JBColor(new Color(128, 128, 128, 65), new Color(128, 128, 128, 65)); public final static JBColor BUILD_METHOD_STRIPE_COLOR = new JBColor(new Color(0xc0d8f0), new Color(0x8d7043)); }
flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterEditorColors.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterEditorColors.java", "repo_id": "flutter-intellij", "token_count": 430 }
446
/* * 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.Disposable; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.CustomHighlighterRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.util.Disposer; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Comparator; /** * Class that manages rendering screenshots of all build methods in a file * directly in the text editor. */ public class PreviewsForEditor implements CustomHighlighterRenderer { static final boolean showOverallPreview = false; private final EditorEx editor; private final Disposable parentDisposable; private final WidgetEditingContext data; private final InlinePreviewViewController overallPreview; private ArrayList<InlinePreviewViewController> previews; public PreviewsForEditor(WidgetEditingContext data, EditorMouseEventService editorEventService, EditorEx editor, Disposable parentDisposable) { this.data = data; this.editor = editor; this.parentDisposable = parentDisposable; previews = new ArrayList<>(); if (showOverallPreview) { overallPreview = new InlinePreviewViewController( new InlineWidgetViewModelData(null, editor, data), true, parentDisposable ); } else { overallPreview = null; } editorEventService.addListener( editor, new EditorMouseEventService.Listener() { @Override public void onMouseMoved(MouseEvent event) { for (PreviewViewControllerBase preview : getAllPreviews(false)) { if (event.isConsumed()) { preview.onMouseExited(event); } else { preview.onMouseMoved(event); } } } @Override public void onMousePressed(MouseEvent event) { for (PreviewViewControllerBase preview : getAllPreviews(false)) { preview.onMousePressed(event); if (event.isConsumed()) break; } } @Override public void onMouseReleased(MouseEvent event) { for (PreviewViewControllerBase preview : getAllPreviews(false)) { preview.onMouseReleased(event); if (event.isConsumed()) break; } } @Override public void onMouseEntered(MouseEvent event) { for (PreviewViewControllerBase preview : getAllPreviews(false)) { if (event.isConsumed()) { preview.onMouseExited(event); } else { preview.onMouseEntered(event); } } } @Override public void onMouseExited(MouseEvent event) { for (PreviewViewControllerBase preview : getAllPreviews(false)) { preview.onMouseExited(event); } } }, parentDisposable ); } public void outlinesChanged(Iterable<WidgetIndentGuideDescriptor> newDescriptors) { final ArrayList<InlinePreviewViewController> newPreviews = new ArrayList<>(); int i = 0; // TODO(jacobr): be smarter about reusing. for (WidgetIndentGuideDescriptor descriptor : newDescriptors) { if (descriptor.parent == null) { if (i >= previews.size() || !descriptor.equals(previews.get(i).getDescriptor())) { newPreviews.add(new InlinePreviewViewController(new InlineWidgetViewModelData(descriptor, editor, data), true, parentDisposable)); } else { newPreviews.add(previews.get(i)); i++; } } } while (i < previews.size()) { Disposer.dispose(previews.get(i)); i++; } previews = newPreviews; } protected Iterable<InlinePreviewViewController> getAllPreviews(boolean paintOrder) { final ArrayList<InlinePreviewViewController> all = new ArrayList<>(); if (overallPreview != null) { all.add(overallPreview); } all.addAll(previews); if (paintOrder) { all.sort(Comparator.comparingInt(InlinePreviewViewController::getPriority)); } else { all.sort((a, b) -> Integer.compare(b.getPriority(), a.getPriority())); } return all; } @Override public void paint(@NotNull Editor editor, @NotNull RangeHighlighter highlighter, @NotNull Graphics graphics) { for (InlinePreviewViewController preview : getAllPreviews(true)) { if (preview.visible) { preview.paint(editor, highlighter, graphics); } } } }
flutter-intellij/flutter-idea/src/io/flutter/editor/PreviewsForEditor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/PreviewsForEditor.java", "repo_id": "flutter-intellij", "token_count": 1981 }
447
/* * 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.inspections; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import com.jetbrains.lang.dart.DartFileType; import com.jetbrains.lang.dart.DartLanguage; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.FlutterUtils; import io.flutter.sdk.FlutterSdk; import io.flutter.settings.FlutterUIConfig; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; public class SdkConfigurationNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> implements DumbAware { private static final Key<EditorNotificationPanel> KEY = Key.create("FlutterWrongDartSdkNotification"); private static final Logger LOG = Logger.getInstance(SdkConfigurationNotificationProvider.class); @NotNull private final Project project; public SdkConfigurationNotificationProvider(@NotNull Project project) { this.project = project; } @SuppressWarnings("SameReturnValue") private static EditorNotificationPanel createNoFlutterSdkPanel(Project project) { final EditorNotificationPanel panel = new EditorNotificationPanel(); panel.icon(FlutterIcons.Flutter); panel.setText(FlutterBundle.message("flutter.no.sdk.warning")); panel.createActionLabel("Dismiss", () -> panel.setVisible(false)); panel.createActionLabel("Open Flutter settings", () -> FlutterUtils.openFlutterSettings(project)); return panel; } @NotNull @Override public Key<EditorNotificationPanel> getKey() { return KEY; } @Override public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor, @NotNull Project project) { // If this is a Bazel configured Flutter project, exit immediately, neither of the notifications should be shown for this project type. if (FlutterModuleUtils.isFlutterBazelProject(project)) return null; if (file.getFileType() != DartFileType.INSTANCE) return null; final PsiFile psiFile = PsiManager.getInstance(project).findFile(file); if (psiFile == null || psiFile.getLanguage() != DartLanguage.INSTANCE) return null; final Module module = ModuleUtilCore.findModuleForPsiElement(psiFile); if (!FlutterModuleUtils.isFlutterModule(module)) return null; final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project); if (flutterSdk == null) { return createNoFlutterSdkPanel(project); } else if (!flutterSdk.getVersion().isMinRecommendedSupported()) { return createOutOfDateFlutterSdkPanel(flutterSdk); } return null; } private EditorNotificationPanel createOutOfDateFlutterSdkPanel(@NotNull FlutterSdk sdk) { final FlutterUIConfig settings = FlutterUIConfig.getInstance(); if (settings.shouldIgnoreOutOfDateFlutterSdks()) return null; final EditorNotificationPanel panel = new EditorNotificationPanel(); panel.icon(FlutterIcons.Flutter); panel.setText(FlutterBundle.message("flutter.old.sdk.warning")); panel.createActionLabel("Dismiss", () -> { settings.setIgnoreOutOfDateFlutterSdks(); panel.setVisible(false); }); return panel; } }
flutter-intellij/flutter-idea/src/io/flutter/inspections/SdkConfigurationNotificationProvider.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspections/SdkConfigurationNotificationProvider.java", "repo_id": "flutter-intellij", "token_count": 1339 }
448
/* * 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.inspector; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.ui.treeStructure.Tree; import io.flutter.view.InspectorPanel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; public abstract class InspectorTreeActionBase extends AnAction { @Override public void actionPerformed(final AnActionEvent e) { final DefaultMutableTreeNode node = getSelectedNode(e.getDataContext()); if (node != null) { final Object diagnostic = node.getUserObject(); if (diagnostic instanceof DiagnosticsNode) { perform(node, (DiagnosticsNode)diagnostic, e); } } } protected abstract void perform(final DefaultMutableTreeNode node, DiagnosticsNode diagnosticsNode, final AnActionEvent e); @Override public void update(final AnActionEvent e) { final DefaultMutableTreeNode node = getSelectedNode(e.getDataContext()); e.getPresentation().setEnabled(node != null && isEnabled(node, e)); } protected boolean isEnabled(final DefaultMutableTreeNode node, AnActionEvent e) { return node.getUserObject() instanceof DiagnosticsNode && isSupported((DiagnosticsNode)node.getUserObject()); } protected boolean isSupported(DiagnosticsNode diagnosticsNode) { return true; } public static DefaultMutableTreeNode getSelectedNode(final DataContext dataContext) { final Tree tree = InspectorPanel.getTree(dataContext); if (tree == null) return null; final TreePath path = tree.getSelectionPath(); if (path == null) return null; return (DefaultMutableTreeNode)path.getLastPathComponent(); } public static DiagnosticsNode getSelectedValue(DataContext dataContext) { final DefaultMutableTreeNode node = getSelectedNode(dataContext); if (node == null) { return null; } final Object userObject = node.getUserObject(); return userObject instanceof DiagnosticsNode ? (DiagnosticsNode)userObject : null; } }
flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorTreeActionBase.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorTreeActionBase.java", "repo_id": "flutter-intellij", "token_count": 689 }
449
/* * 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.logging; import com.google.common.annotations.VisibleForTesting; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.icons.AllIcons; import com.intellij.ide.util.PropertiesComponent; import com.intellij.notification.*; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.ui.SimpleTextAttributes; import com.intellij.util.concurrency.QueueProcessor; import io.flutter.FlutterInitializer; import io.flutter.FlutterUtils; import io.flutter.devtools.DevToolsUtils; import io.flutter.inspector.DiagnosticLevel; import io.flutter.inspector.DiagnosticsNode; import io.flutter.inspector.DiagnosticsTreeStyle; import io.flutter.inspector.InspectorService; import io.flutter.jxbrowser.JxBrowserManager; import io.flutter.run.daemon.FlutterApp; import io.flutter.sdk.FlutterSdk; import io.flutter.settings.FlutterSettings; import io.flutter.utils.JsonUtils; import io.flutter.view.EmbeddedBrowser; import io.flutter.view.FlutterView; import io.flutter.vmService.VmServiceConsumers; import org.dartlang.vm.service.VmService; import org.dartlang.vm.service.consumer.GetObjectConsumer; import org.dartlang.vm.service.element.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Handle displaying dart:developer log messages and Flutter.Error messages in the Run and Debug * console. */ public class FlutterConsoleLogManager { private static final Logger LOG = Logger.getInstance(FlutterConsoleLogManager.class); private static final String consolePreferencesSetKey = "io.flutter.console.preferencesSet"; private static final String DEEP_LINK_GROUP_ID = "deeplink"; private static final ConsoleViewContentType TITLE_CONTENT_TYPE = new ConsoleViewContentType("title", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES.toTextAttributes()); private static final ConsoleViewContentType NORMAL_CONTENT_TYPE = ConsoleViewContentType.NORMAL_OUTPUT; private static final ConsoleViewContentType SUBTLE_CONTENT_TYPE = new ConsoleViewContentType("subtle", SimpleTextAttributes.GRAY_ATTRIBUTES.toTextAttributes()); private static final ConsoleViewContentType ERROR_CONTENT_TYPE = ConsoleViewContentType.ERROR_OUTPUT; private static QueueProcessor<Runnable> queue; private static final AtomicInteger queueLength = new AtomicInteger(); /** * Set our preferred settings for the run console. */ public static void initConsolePreferences() { final PropertiesComponent properties = PropertiesComponent.getInstance(); if (!properties.getBoolean(consolePreferencesSetKey)) { properties.setValue(consolePreferencesSetKey, true); // Set our preferred default settings for console text wrapping. final EditorSettingsExternalizable editorSettings = EditorSettingsExternalizable.getInstance(); editorSettings.setUseSoftWraps(true, SoftWrapAppliancePlaces.CONSOLE); } } @NotNull final ConsoleView console; @NotNull final FlutterApp app; private int frameErrorCount = 0; private CompletableFuture<InspectorService.ObjectGroup> objectGroup; public FlutterConsoleLogManager(@NotNull ConsoleView console, @NotNull FlutterApp app) { this.console = console; this.app = app; app.addStateListener(new FlutterApp.FlutterAppListener() { @Override public void notifyFrameRendered() { frameErrorCount = 0; } @Override public void stateChanged(FlutterApp.State newState) { frameErrorCount = 0; } @Override public void notifyAppReloaded() { frameErrorCount = 0; } @Override public void notifyAppRestarted() { frameErrorCount = 0; } }); if (queue == null) { queue = QueueProcessor.createRunnableQueueProcessor(); } } /** * This method is used to delay construction of the InspectorService ObjectGroup instance until its first used. * <p> * This ensures that the app's VMService field has been populated. */ @Nullable private CompletableFuture<InspectorService.ObjectGroup> getCreateInspectorGroup() { if (objectGroup == null) { if (app.getFlutterDebugProcess() == null || app.getVmService() == null) { return null; } // TODO(devoncarew): This creates a new InspectorService but may not dispose of it. objectGroup = InspectorService.createGroup(app, app.getFlutterDebugProcess(), app.getVmService(), "console-group"); objectGroup.whenCompleteAsync((group, error) -> { if (group != null) { Disposer.register(app, group.getInspectorService()); } }); } return objectGroup; } public void handleFlutterErrorEvent(@NotNull Event event) { final CompletableFuture<InspectorService.ObjectGroup> objectGroup = getCreateInspectorGroup(); if (objectGroup == null) { return; } try { final ExtensionData extensionData = event.getExtensionData(); final JsonObject jsonObject = extensionData.getJson().getAsJsonObject(); final DiagnosticsNode diagnosticsNode = new DiagnosticsNode(jsonObject, objectGroup, app, false, null); if (FlutterSettings.getInstance().isShowStructuredErrors()) { queueLength.incrementAndGet(); queue.add(() -> { try { processFlutterErrorEvent(diagnosticsNode); } catch (Throwable t) { LOG.warn(t); } finally { queueLength.decrementAndGet(); synchronized (queueLength) { queueLength.notifyAll(); } } }); } } catch (Throwable t) { LOG.warn(t); } } /** * Wait until all pending work has completed. */ public void flushFlutterErrorQueue() { // If the queue isn't empty, then wait until the all the items have been processed. if (queueLength.get() > 0) { try { while (queueLength.get() > 0) { synchronized (queueLength) { queueLength.wait(); } } } catch (InterruptedException e) { e.printStackTrace(); } } } private static final int errorSeparatorLength = 100; private static final String errorSeparatorChar = "="; private static final ArrayList<DiagnosticsNode> emptyList = new ArrayList<>(); /** * Pretty print the error using the available console syling attributes. */ private void processFlutterErrorEvent(@NotNull DiagnosticsNode diagnosticsNode) { final String description = " " + diagnosticsNode + " "; final boolean terseError = !isFirstErrorForFrame() && !FlutterSettings.getInstance().isIncludeAllStackTraces(); frameErrorCount++; final String prefix = "========"; final String suffix = "=="; console.print("\n" + prefix, TITLE_CONTENT_TYPE); console.print(description, NORMAL_CONTENT_TYPE); console.print( StringUtil.repeat(errorSeparatorChar, Math.max( errorSeparatorLength - prefix.length() - description.length() - suffix.length(), 0)), TITLE_CONTENT_TYPE); console.print(suffix + "\n", TITLE_CONTENT_TYPE); // TODO(devoncarew): Create a hyperlink to a widget - ala 'widget://inspector-1347'. if (terseError) { for (DiagnosticsNode property : diagnosticsNode.getInlineProperties()) { printTerseNodeProperty(console, "", property); } } else { DiagnosticLevel lastLevel = null; String errorSummary = null; for (DiagnosticsNode property : diagnosticsNode.getInlineProperties()) { // Add blank line between hint and non-hint properties. if (lastLevel != property.getLevel()) { if (lastLevel == DiagnosticLevel.hint || property.getLevel() == DiagnosticLevel.hint) { console.print("\n", NORMAL_CONTENT_TYPE); } } lastLevel = property.getLevel(); if (StringUtil.equals("ErrorSummary", property.getType())) { errorSummary = property.getDescription(); } else if (StringUtil.equals("DevToolsDeepLinkProperty", property.getType()) && FlutterUtils.embeddedBrowserAvailable(JxBrowserManager.getInstance().getStatus())) { showDeepLinkNotification(property, errorSummary); continue; } printDiagnosticsNodeProperty(console, "", property, null, false); } } console.print(StringUtil.repeat(errorSeparatorChar, errorSeparatorLength) + "\n", TITLE_CONTENT_TYPE); } private boolean isFirstErrorForFrame() { return frameErrorCount == 0; } private void printTerseNodeProperty(ConsoleView console, String indent, DiagnosticsNode property) { boolean skip = true; if (property.getLevel() == DiagnosticLevel.summary) { skip = false; } else if (property.hasChildren()) { final CompletableFuture<ArrayList<DiagnosticsNode>> future = property.getChildren(); final ArrayList<DiagnosticsNode> children = future.getNow(emptyList); if (children.stream().noneMatch(DiagnosticsNode::hasChildren)) { skip = false; } } if (skip) { return; } final ConsoleViewContentType contentType = getContentTypeFor(property.getLevel()); console.print(indent, contentType); if (property.getShowName()) { console.print(property.getName(), contentType); if (property.getShowSeparator()) { console.print(property.getSeparator() + " ", contentType); } } final String description = property.getDescription() == null ? "" : property.getDescription(); console.print(description + "\n", contentType); final String childIndent = getChildIndent(indent, property); if (property.hasInlineProperties()) { for (DiagnosticsNode childProperty : property.getInlineProperties()) { printDiagnosticsNodeProperty(console, childIndent, childProperty, contentType, false); } } if (property.hasChildren()) { final CompletableFuture<ArrayList<DiagnosticsNode>> future = property.getChildren(); final ArrayList<DiagnosticsNode> children = future.getNow(emptyList); for (DiagnosticsNode child : children) { printDiagnosticsNodeProperty(console, childIndent, child, contentType, false); } } } private void printDiagnosticsNodeProperty(ConsoleView console, String indent, DiagnosticsNode property, ConsoleViewContentType contentType, boolean isInChild) { // TODO(devoncarew): Change the error message display in the framework. if (property.getDescription() != null && property.getLevel() == DiagnosticLevel.info) { // Elide framework blank styling lines. if (StringUtil.equals("ErrorSpacer", property.getType())) { return; } } if (contentType == null) { contentType = getContentTypeFor(property.getLevel()); } console.print(indent, contentType); if (property.getShowName()) { final String name = property.getName(); console.print(name == null ? "" : name, contentType); if (property.getShowSeparator()) { console.print(property.getSeparator() + " ", contentType); } } final String description = property.getDescription() == null ? "" : property.getDescription(); console.print(description + "\n", contentType); if (property.hasInlineProperties()) { String childIndent = getChildIndent(indent, property); if (property.getStyle() == DiagnosticsTreeStyle.shallow && !indent.startsWith("...")) { // Render properties of shallow nodes as collapesed. childIndent = "... " + indent; } for (DiagnosticsNode childProperty : property.getInlineProperties()) { printDiagnosticsNodeProperty(console, childIndent, childProperty, contentType, isInChild); } } if (property.hasChildren()) { final CompletableFuture<ArrayList<DiagnosticsNode>> future = property.getChildren(); final ArrayList<DiagnosticsNode> children = future.getNow(emptyList); // Don't collapse children if it's just a flat list of children. if (!isInChild && children.stream().noneMatch(DiagnosticsNode::hasChildren)) { final String childIndent = getChildIndent(indent, property); for (DiagnosticsNode child : children) { printDiagnosticsNodeProperty(console, childIndent, child, contentType, false); } } else { if (property.getStyle() != DiagnosticsTreeStyle.shallow) { // For deep trees, we show the text as collapsed. final String childIndent = isInChild ? getChildIndent(indent, property) : "... " + indent; for (DiagnosticsNode child : children) { printDiagnosticsNodeProperty(console, childIndent, child, contentType, true); } } } } // Print an extra line after the summary. if (property.getLevel() == DiagnosticLevel.summary) { console.print("\n", contentType); } } private void showDeepLinkNotification(DiagnosticsNode property, @NotNull String errorSummary) { NotificationGroup group = NotificationGroupManager.getInstance().getNotificationGroup(DEEP_LINK_GROUP_ID); assert group != null; Notification notification = group.createNotification(errorSummary, NotificationType.INFORMATION); notification.setIcon(AllIcons.General.BalloonWarning); notification.addAction(new AnAction("Inspect Widget") { @Override public void actionPerformed(@NotNull AnActionEvent event) { // Show inspector window if it's not already visible. final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(app.getProject()); if (!(toolWindowManager instanceof ToolWindowManagerEx)) { return; } final ToolWindow toolWindow = toolWindowManager.getToolWindow(FlutterView.TOOL_WINDOW_ID); if (toolWindow != null && !toolWindow.isVisible()) { toolWindow.show(); } final String widgetId = DevToolsUtils.findWidgetId(property.getValue()); Project project = app.getProject(); if (!project.isDisposed()) { final EmbeddedBrowser browser = FlutterUtils.embeddedBrowser(project); if (browser != null) { browser.updatePanelToWidget(widgetId); } } notification.expire(); FlutterInitializer.getAnalytics().sendEvent( "deep-link-clicked", errorSummary.contains("RenderFlex overflowed") ? "overflow" : "unknown", FlutterSdk.getFlutterSdk(app.getProject()) ); } }); Notifications.Bus.notify(notification, app.getProject()); Executors.newSingleThreadScheduledExecutor().schedule(notification::expire, 25, TimeUnit.SECONDS); } private String getChildIndent(String indent, DiagnosticsNode property) { if (property.getStyle() == DiagnosticsTreeStyle.flat) { return indent; } else { return indent + " "; } } public void handleLoggingEvent(@NotNull Event event) { queue.add(() -> { try { processLoggingEvent(event); } catch (Throwable t) { LOG.warn(t); } }); } private ConsoleViewContentType getContentTypeFor(DiagnosticLevel level) { switch (level) { case error: case summary: return ERROR_CONTENT_TYPE; case hint: return NORMAL_CONTENT_TYPE; default: return SUBTLE_CONTENT_TYPE; } } @VisibleForTesting public void processLoggingEvent(@NotNull Event event) { final LogRecord logRecord = event.getLogRecord(); if (logRecord == null) return; final VmService service = app.getVmService(); if (service == null) { return; } final IsolateRef isolateRef = event.getIsolate(); final InstanceRef message = logRecord.getMessage(); @NotNull final InstanceRef loggerName = logRecord.getLoggerName(); final String name = loggerName.getValueAsString().isEmpty() ? "log" : loggerName.getValueAsString(); final String prefix = "[" + name + "] "; final String messageStr = getFullStringValue(service, isolateRef.getId(), message); console.print(prefix, SUBTLE_CONTENT_TYPE); console.print(messageStr + "\n", NORMAL_CONTENT_TYPE); @NotNull final InstanceRef error = logRecord.getError(); @NotNull final InstanceRef stackTrace = logRecord.getStackTrace(); if (!error.isNull()) { final String padding = StringUtil.repeat(" ", prefix.length()); if (error.getKind() == InstanceKind.String) { String string = getFullStringValue(service, isolateRef.getId(), error); // Handle json in the error payload. boolean isJson = false; try { final JsonElement json = JsonUtils.parseString(string); isJson = true; string = new GsonBuilder().setPrettyPrinting().create().toJson(json); string = string.replaceAll("\n", "\n" + padding); } catch (JsonSyntaxException ignored) { } console.print(padding + string + "\n", isJson ? ConsoleViewContentType.NORMAL_OUTPUT : ERROR_CONTENT_TYPE); } else { final CountDownLatch latch = new CountDownLatch(1); service.invoke( isolateRef.getId(), error.getId(), "toString", Collections.emptyList(), true, new VmServiceConsumers.InvokeConsumerWrapper() { @Override public void received(InstanceRef response) { console.print(padding + stringValueFromStringRef(response) + "\n", ERROR_CONTENT_TYPE); latch.countDown(); } @Override public void noGoodResult() { console.print(padding + error.getClassRef().getName() + " " + error.getId() + "\n", ERROR_CONTENT_TYPE); latch.countDown(); } }); try { latch.await(); } catch (InterruptedException ignored) { } } } if (!stackTrace.isNull()) { final String padding = StringUtil.repeat(" ", prefix.length()); final String out = stackTrace.getValueAsString() == null ? "" : stackTrace.getValueAsString().trim(); console.print( padding + out.replaceAll("\n", "\n" + padding) + "\n", ERROR_CONTENT_TYPE); } } private String stringValueFromStringRef(InstanceRef ref) { return ref.getValueAsStringIsTruncated() ? formatTruncatedString(ref) : ref.getValueAsString(); } private String stringValueFromStringRef(Instance instance) { return instance.getValueAsStringIsTruncated() ? instance.getValueAsString() + "..." : instance.getValueAsString(); } private String formatTruncatedString(InstanceRef ref) { return ref.getValueAsString() + "..."; } private String getFullStringValue(@NotNull VmService service, String isolateId, @Nullable InstanceRef ref) { if (ref == null) return null; if (!ref.getValueAsStringIsTruncated()) { return ref.getValueAsString(); } final CountDownLatch latch = new CountDownLatch(1); final String[] result = new String[1]; service.getObject(isolateId, ref.getId(), 0, ref.getLength(), new GetObjectConsumer() { @Override public void onError(RPCError error) { result[0] = formatTruncatedString(ref); latch.countDown(); } @Override public void received(Obj response) { if (response instanceof Instance && ((Instance)response).getKind() == InstanceKind.String) { result[0] = stringValueFromStringRef((Instance)response); } else { result[0] = formatTruncatedString(ref); } latch.countDown(); } @Override public void received(Sentinel response) { result[0] = formatTruncatedString(ref); latch.countDown(); } }); try { latch.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { return null; } return result[0]; } }
flutter-intellij/flutter-idea/src/io/flutter/logging/FlutterConsoleLogManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/logging/FlutterConsoleLogManager.java", "repo_id": "flutter-intellij", "token_count": 7802 }
450
/* * 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.module.settings; import com.intellij.ide.browsers.BrowserLauncher; import com.intellij.openapi.components.ServiceManager; import com.intellij.ui.components.labels.LinkLabel; import io.flutter.FlutterBundle; import io.flutter.FlutterConstants; import io.flutter.FlutterUtils; import io.flutter.module.FlutterProjectType; import java.awt.Cursor; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import org.jetbrains.annotations.NotNull; /** * The settings panel that lists help messages. */ public class SettingsHelpForm { private JPanel mainPanel; private JPanel helpPanel; private JLabel helpLabel; private JLabel projectTypeLabel; private JLabel projectTypeDescriptionForApp; private JLabel projectTypeDescriptionForModule; private JLabel projectTypeDescriptionForPlugin; private JLabel projectTypeDescriptionForPackage; @SuppressWarnings("rawtypes") private LinkLabel gettingStartedUrl; public static SettingsHelpForm getInstance() { return ServiceManager.getService(SettingsHelpForm.class); } public SettingsHelpForm() { projectTypeLabel.setText(FlutterBundle.message("flutter.module.create.settings.help.project_type.label")); projectTypeDescriptionForApp.setText(FlutterBundle.message("flutter.module.create.settings.help.project_type.description.app")); projectTypeDescriptionForModule.setText(FlutterBundle.message("flutter.module.create.settings.help.project_type.description.module")); projectTypeDescriptionForPlugin.setText(FlutterBundle.message("flutter.module.create.settings.help.project_type.description.plugin")); projectTypeDescriptionForPackage.setText(FlutterBundle.message("flutter.module.create.settings.help.project_type.description.package")); if (!FlutterUtils.isAndroidStudio()) { projectTypeDescriptionForModule.setVisible(false); } gettingStartedUrl.setText(FlutterBundle.message("flutter.module.create.settings.help.getting_started_link_text")); gettingStartedUrl.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); gettingStartedUrl.setIcon(null); //noinspection unchecked gettingStartedUrl .setListener((label, linkUrl) -> BrowserLauncher.getInstance().browse(FlutterConstants.URL_GETTING_STARTED, null), null); } public void showGettingStarted() { projectTypeLabel.setVisible(false); projectTypeDescriptionForApp.setVisible(false); projectTypeDescriptionForModule.setVisible(false); projectTypeDescriptionForPlugin.setVisible(false); projectTypeDescriptionForPackage.setVisible(false); mainPanel.setVisible(true); gettingStartedUrl.setVisible(true); } @NotNull public JComponent getComponent() { return mainPanel; } public void adjustContrast(FlutterProjectType type) { projectTypeDescriptionForApp.setEnabled(false); projectTypeDescriptionForModule.setEnabled(false); projectTypeDescriptionForPlugin.setEnabled(false); projectTypeDescriptionForPackage.setEnabled(false); switch (type) { case APP: projectTypeDescriptionForApp.setEnabled(true); break; case MODULE: projectTypeDescriptionForModule.setEnabled(true); break; case PACKAGE: projectTypeDescriptionForPackage.setEnabled(true); break; case PLUGIN: projectTypeDescriptionForPlugin.setEnabled(true); break; default: break; } } }
flutter-intellij/flutter-idea/src/io/flutter/module/settings/SettingsHelpForm.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/SettingsHelpForm.java", "repo_id": "flutter-intellij", "token_count": 1175 }
451
/* * 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 java.util.List; /** * A performance tip describing a suggestion to optimize a Flutter application. */ public class PerfTip { final PerfTipRule rule; final List<Location> locations; double confidence; PerfTip(PerfTipRule rule, List<Location> locations, double confidence) { this.rule = rule; this.locations = locations; this.confidence = confidence; } public PerfTipRule getRule() { return rule; } public String getMessage() { return rule.getMessage(); } /** * Locations within the application that called the tip to trigger. */ public List<Location> getLocations() { return locations; } /** * Confidence between zero and 1 that the rule should be applied. */ public double getConfidence() { return confidence; } public String getUrl() { return rule.getUrl(); } }
flutter-intellij/flutter-idea/src/io/flutter/perf/PerfTip.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/PerfTip.java", "repo_id": "flutter-intellij", "token_count": 322 }
452
/* * 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.performance; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBPanel; import com.intellij.ui.components.panels.VerticalLayout; import com.intellij.util.ui.JBUI; import io.flutter.perf.FlutterWidgetPerfManager; import io.flutter.perf.PerfMetric; import io.flutter.perf.PerfReportKind; import io.flutter.run.daemon.FlutterApp; import io.flutter.vmService.ServiceExtensions; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; public class PerfWidgetRebuildsPanel extends JBPanel<PerfWidgetRebuildsPanel> { private static final Logger LOG = Logger.getInstance(PerfWidgetRebuildsPanel.class); private static final String REBUILD_STATS_TAB_LABEL = "Widget rebuild stats"; /** * Tracking widget repaints may confuse users so we disable it by default currently. */ private static final boolean ENABLE_TRACK_REPAINTS = false; private @NotNull final FlutterApp app; private final WidgetPerfSummary perfSummary; private final JCheckBox trackRebuildsCheckbox; private JCheckBox trackRepaintsCheckbox; private final JPanel perfSummaryContainer; private final JPanel perfSummaryPlaceholder; private JComponent currentSummaryView; PerfWidgetRebuildsPanel(@NotNull FlutterApp app, @NotNull Disposable parentDisposable) { this.app = app; setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), REBUILD_STATS_TAB_LABEL)); setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE)); final JPanel rebuildStatsPanel = new JPanel(new BorderLayout(0, 5)); add(rebuildStatsPanel, BorderLayout.CENTER); // rebuild stats perfSummaryContainer = new JPanel(new BorderLayout(0, 5)); currentSummaryView = null; perfSummaryPlaceholder = new JPanel(new BorderLayout()); final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane( new JBLabel( "<html><body style='padding-left:15px; padding-right:15px;'>" + "Widget rebuild information tells you what widgets have been " + "recently rebuilt for your application's current screen." + "<br>" + "</body></html>"), ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); scrollPane.setBorder(JBUI.Borders.empty()); scrollPane.setViewportBorder(JBUI.Borders.empty()); perfSummaryPlaceholder.add(scrollPane); final JPanel perfViewSettings = new JPanel(new VerticalLayout(5, 4)); trackRebuildsCheckbox = new JCheckBox("Track widget rebuilds"); trackRebuildsCheckbox.setHorizontalAlignment(JLabel.RIGHT); final boolean isInProfileMode = app.getMode().isProfiling() || app.getLaunchMode().isProfiling(); if (isInProfileMode){ trackRebuildsCheckbox.setToolTipText( "<html><body><p><b>This profiler identifies widgets that are rebuilt when the UI changes.</b></p>" + "<br>" + "<p>To enable 'Track widget rebuilds', start the app in debug mode.</p>" + "</body></html>"); } else { trackRebuildsCheckbox.setToolTipText( "<html><body><p><b>This profiler identifies widgets that are rebuilt when the UI changes.</b></p>" + "<br>" + "<p>Look for the indicators on the left margin of the code editor<br>and a list of the top rebuilt widgets in this window.</p>" + "</body></html>"); } perfViewSettings.add(trackRebuildsCheckbox); if (ENABLE_TRACK_REPAINTS) { trackRepaintsCheckbox = new JCheckBox("Show widget repaint information"); trackRepaintsCheckbox.setHorizontalAlignment(JLabel.RIGHT); perfViewSettings.add(trackRepaintsCheckbox); } perfViewSettings.add(new JSeparator()); perfSummary = new WidgetPerfSummary(parentDisposable, app, PerfMetric.lastFrame, PerfReportKind.rebuild); perfSummaryContainer.add(perfViewSettings, BorderLayout.NORTH); updateShowPerfSummaryView(); rebuildStatsPanel.add(perfSummaryContainer, BorderLayout.CENTER); // perf tips final JPanel perfTipsPanel = perfSummary.getWidgetPerfTipsPanel(); rebuildStatsPanel.add(perfTipsPanel, BorderLayout.SOUTH); perfTipsPanel.setVisible(false); final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject()); trackRebuildsCheckbox.setSelected(widgetPerfManager.isTrackRebuildWidgets()); if (ENABLE_TRACK_REPAINTS) { trackRepaintsCheckbox.setSelected(widgetPerfManager.isTrackRepaintWidgets()); } app.hasServiceExtension(ServiceExtensions.trackRebuildWidgets.getExtension(), trackRebuildsCheckbox::setEnabled, parentDisposable); if (ENABLE_TRACK_REPAINTS) { app.hasServiceExtension(ServiceExtensions.trackRepaintWidgets.getExtension(), trackRepaintsCheckbox::setEnabled, parentDisposable); } trackRebuildsCheckbox.addChangeListener((l) -> { if (app.getProject().isDisposed()) return; setTrackRebuildWidgets(trackRebuildsCheckbox.isSelected()); updateShowPerfSummaryView(); }); if (ENABLE_TRACK_REPAINTS) { trackRepaintsCheckbox.addChangeListener((l) -> { if (app.getProject().isDisposed()) return; setTrackRepaintWidgets(trackRepaintsCheckbox.isSelected()); updateShowPerfSummaryView(); }); } } void updateShowPerfSummaryView() { final boolean show = getShowPerfTable(); final boolean firstRender = currentSummaryView == null; final JComponent summaryView = show ? perfSummary : perfSummaryPlaceholder; if (summaryView != currentSummaryView) { if (currentSummaryView != null) { perfSummaryContainer.remove(currentSummaryView); } currentSummaryView = summaryView; perfSummaryContainer.add(summaryView, BorderLayout.CENTER); perfSummaryContainer.revalidate(); perfSummaryContainer.repaint(); } if (!show) { perfSummary.clearPerformanceTips(); } } boolean getShowPerfTable() { final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject()); return widgetPerfManager.isTrackRebuildWidgets() || widgetPerfManager.isTrackRepaintWidgets(); } private void setTrackRebuildWidgets(boolean selected) { final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject()); widgetPerfManager.setTrackRebuildWidgets(selected); // Update default so next app launched will match the existing setting. FlutterWidgetPerfManager.trackRebuildWidgetsDefault = selected; } private void setTrackRepaintWidgets(boolean selected) { final FlutterWidgetPerfManager widgetPerfManager = FlutterWidgetPerfManager.getInstance(app.getProject()); widgetPerfManager.setTrackRepaintWidgets(selected); // Update default so next app launched will match the existing setting. FlutterWidgetPerfManager.trackRepaintWidgetsDefault = selected; } }
flutter-intellij/flutter-idea/src/io/flutter/performance/PerfWidgetRebuildsPanel.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/performance/PerfWidgetRebuildsPanel.java", "repo_id": "flutter-intellij", "token_count": 2477 }
453
/* * 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.pub; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.jetbrains.lang.dart.util.DotPackagesFileUtil; import io.flutter.FlutterUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; /** * A snapshot of the root directory of a pub package. * <p> * That is, a directory containing (at a minimum) a pubspec.yaml file. */ public class PubRoot { private static final Logger LOG = Logger.getInstance(PubRoot.class); @NotNull private final VirtualFile root; @NotNull private final VirtualFile pubspec; private PubRoot(@NotNull VirtualFile root, @NotNull VirtualFile pubspec) { this.root = root; this.pubspec = pubspec; } /** * Returns the first pub root containing the given file. */ @Nullable public static PubRoot forFile(@Nullable VirtualFile file) { if (file == null) { return null; } if (file.isDirectory()) { final PubRoot root = forDirectory(file.getParent()); if (root != null) return root; } return forFile(file.getParent()); } /** * Returns the appropriate pub root for an event. * <p> * Refreshes the returned pubroot's directory (not any others). */ @Nullable public static PubRoot forEventWithRefresh(@NotNull final AnActionEvent event) { final PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(event.getDataContext()); if (psiFile != null) { final PubRoot root = forPsiFile(psiFile); if (root != null) { return root.refresh(); } } final Module module = LangDataKeys.MODULE.getData(event.getDataContext()); if (module != null) { final List<PubRoot> roots = PubRoots.forModule(module); if (!roots.isEmpty()) { return roots.get(0); } } return null; } /** * Returns the pub root for a PsiFile, if any. * <p> * The file must be within a content root that has a pubspec.yaml file. * <p> * Based on the filesystem cache; doesn't refresh anything. */ @Nullable public static PubRoot forPsiFile(@NotNull PsiFile psiFile) { final VirtualFile file = psiFile.getVirtualFile(); if (file == null) { return null; } if (isPubspec(file)) { return forDirectory(file.getParent()); } else { return forDescendant(file, psiFile.getProject()); } } /** * Returns the pub root for the content root containing a file or directory. * <p> * Based on the filesystem cache; doesn't refresh anything. */ @Nullable public static PubRoot forDescendant(@NotNull VirtualFile fileOrDir, @NotNull Project project) { final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); return ApplicationManager.getApplication().runReadAction((Computable<PubRoot>)() -> { final VirtualFile root = index.getContentRootForFile(fileOrDir); return forDirectory(root); }); } /** * Returns the PubRoot for a directory, provided it contains a pubspec.yaml file. * <p> * Otherwise returns null. * <p> * (The existence check is based on the filesystem cache; doesn't refresh anything.) */ @Nullable public static PubRoot forDirectory(@Nullable VirtualFile dir) { if (dir == null || !dir.isDirectory() || dir.getPath().endsWith("/")) { return null; } final VirtualFile pubspec = dir.findChild("pubspec.yaml"); if (pubspec == null || !pubspec.exists() || pubspec.isDirectory()) { return null; } return new PubRoot(dir, pubspec); } /** * Returns the PubRoot for a directory, provided it contains a pubspec.yaml file. * <p> * Refreshes the directory and the lib directory (if present). Returns null if not found. */ @Nullable public static PubRoot forDirectoryWithRefresh(@NotNull VirtualFile dir) { // Ensure file existence and timestamps are up to date. dir.refresh(false, false); return forDirectory(dir); } /** * Returns the relative path to a file or directory within this PubRoot. * <p> * Returns null for the pub root directory, or it not within the pub root. */ @Nullable public String getRelativePath(@NotNull VirtualFile file) { final String root = this.root.getPath(); final String path = file.getPath(); if (!path.startsWith(root) || path.length() < root.length() + 2) { return null; } return path.substring(root.length() + 1); } private static final String /*@NotNull*/ [] TEST_DIRS = new String[] { // TODO 2022.1 "/test/", "/integration_test/", "/test_driver/", "/testing/" }; /** * Returns true if the given file is a directory that contains tests. */ public boolean hasTests(@NotNull VirtualFile dir) { if (!dir.isDirectory()) return false; // We can run tests in the pub root. (It will look in the test dir.) if (getRoot().equals(dir)) return true; String path = dir.getPath() + "/"; // Any directory in a test dir or below is also okay. for (String testDir : TEST_DIRS) { if (path.contains(testDir)) { return true; } } return false; } /** * Refreshes the pubroot and lib directories and returns an up-to-date snapshot. * <p> * Returns null if the directory or pubspec file is no longer there. */ @Nullable public PubRoot refresh() { return forDirectoryWithRefresh(root); } @NotNull public VirtualFile getRoot() { return root; } @NotNull public String getPath() { return root.getPath(); } @NotNull public VirtualFile getPubspec() { return pubspec; } private FlutterUtils.FlutterPubspecInfo cachedPubspecInfo; /** * Returns true if the pubspec declares a flutter dependency. */ public boolean declaresFlutter() { validateUpdateCachedPubspecInfo(); return cachedPubspecInfo.declaresFlutter(); } /** * Check if the cache needs to be updated. */ private void validateUpdateCachedPubspecInfo() { if (cachedPubspecInfo == null || cachedPubspecInfo.getModificationStamp() != pubspec.getModificationStamp()) { cachedPubspecInfo = FlutterUtils.getFlutterPubspecInfo(pubspec); } } /** * Returns true if the pubspec indicates that it is a Flutter plugin. */ public boolean isFlutterPlugin() { return FlutterUtils.isFlutterPlugin(pubspec); } /** * Returns true if the directory content looks like a Flutter module. */ public boolean isFlutterModule() { return root.findChild(".android") != null; } public boolean isNonEditableFlutterModule() { return isFlutterModule() && root.findChild("android") == null; } @Nullable public VirtualFile getPackageConfigFile() { final VirtualFile tools = root.findChild(".dart_tool"); if (tools == null || !tools.isDirectory()) { return null; } final VirtualFile config = tools.findChild("package_config.json"); if (config != null && !config.isDirectory()) { return config; } return null; } @Nullable public VirtualFile getPackagesFile() { // Obsolete by Flutter 2.0 final VirtualFile packages = root.findChild(".packages"); if (packages != null && !packages.isDirectory()) { return packages; } return null; } public @Nullable Map<String, String> getPackagesMap() { final var packageConfigFile = getPackageConfigFile(); if (packageConfigFile != null) { return DotPackagesFileUtil.getPackagesMapFromPackageConfigJsonFile(packageConfigFile); } final var packagesFile = getPackagesFile(); if (packagesFile != null) { return DotPackagesFileUtil.getPackagesMap(packagesFile); } return null; } /** * Returns true if the packages are up to date wrt pubspec.yaml. */ public boolean hasUpToDatePackages() { final VirtualFile configFile = getPackageConfigFile(); if (configFile != null) { return pubspec.getTimeStamp() < configFile.getTimeStamp(); } final VirtualFile packagesFile = getPackagesFile(); if (packagesFile == null) { return false; } return pubspec.getTimeStamp() < packagesFile.getTimeStamp(); } @Nullable public VirtualFile getLib() { final VirtualFile lib = root.findChild("lib"); if (lib != null && lib.isDirectory()) { return lib; } return null; } /** * Returns a file in lib if it exists. */ @Nullable public VirtualFile getFileToOpen() { final VirtualFile main = getLibMain(); if (main != null) { return main; } final VirtualFile lib = getLib(); if (lib != null) { final VirtualFile[] files = lib.getChildren(); if (files.length != 0) { return files[0]; } } return null; } /** * Returns lib/main.dart if it exists. */ @Nullable public VirtualFile getLibMain() { final VirtualFile lib = getLib(); return lib == null ? null : lib.findChild("main.dart"); } /** * Returns example/lib/main.dart if it exists. */ public VirtualFile getExampleLibMain() { final VirtualFile exampleDir = root.findChild("example"); if (exampleDir != null) { final VirtualFile libDir = exampleDir.findChild("lib"); if (libDir != null) { return libDir.findChild("main.dart"); } } return null; } @Nullable public VirtualFile getIntegrationTestDir() { return root.findChild("integration_test"); } @Nullable public VirtualFile getExampleDir() { return root.findChild("example"); } /** * Returns the android subdirectory if it exists. */ @Nullable public VirtualFile getAndroidDir() { VirtualFile dir = root.findChild("android"); if (dir == null) { dir = root.findChild(".android"); } return dir; } /** * Returns the ios subdirectory if it exists. */ @Nullable public VirtualFile getiOsDir() { VirtualFile dir = root.findChild("ios"); if (dir == null) { dir = root.findChild(".ios"); } return dir; } /** * Returns true if the project has a module for the "android" directory. */ public boolean hasAndroidModule(Project project) { final VirtualFile androidDir = getAndroidDir(); if (androidDir == null) { return false; } for (Module module : ModuleManager.getInstance(project).getModules()) { for (VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) { if (contentRoot.equals(androidDir)) { return true; } } } return false; } /** * Returns the module containing this pub root, if any. */ @Nullable public Module getModule(@NotNull Project project) { if (project.isDisposed()) { return null; } return ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(pubspec); } /** * Returns true if the PubRoot is an ancestor of the given file. */ public boolean contains(@NotNull VirtualFile file) { VirtualFile dir = file.getParent(); while (dir != null) { if (dir.equals(root)) { return true; } dir = dir.getParent(); } return false; } @Override public String toString() { return "PubRoot(" + root.getName() + ")"; } public static boolean isPubspec(@NotNull VirtualFile file) { return !file.isDirectory() && file.getName().equals("pubspec.yaml"); } }
flutter-intellij/flutter-idea/src/io/flutter/pub/PubRoot.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/pub/PubRoot.java", "repo_id": "flutter-intellij", "token_count": 4273 }
454
/* * 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; import com.intellij.ide.BrowserUtil; import com.intellij.ide.util.PropertiesComponent; import com.intellij.notification.*; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.FlutterMessages; import io.flutter.view.FlutterViewMessages; import org.jetbrains.annotations.NotNull; public class FlutterRunNotifications { private static final String RELOAD_ALREADY_RUN = "io.flutter.reload.alreadyRun"; public static void init(@NotNull Project project) { // Initialize the flutter run notification group. NotificationsConfiguration.getNotificationsConfiguration().register( FlutterMessages.FLUTTER_NOTIFICATION_GROUP_ID, NotificationDisplayType.BALLOON, false); NotificationsConfiguration.getNotificationsConfiguration().register( FlutterMessages.FLUTTER_LOGGING_NOTIFICATION_GROUP_ID, NotificationDisplayType.BALLOON, true); final FlutterRunNotifications notifications = new FlutterRunNotifications(project); //noinspection CodeBlock2Expr project.getMessageBus().connect().subscribe( FlutterViewMessages.FLUTTER_DEBUG_TOPIC, (event) -> { ApplicationManager.getApplication().invokeLater(notifications::checkForDisplayFirstReload); } ); } @NotNull final Project myProject; FlutterRunNotifications(@NotNull Project project) { this.myProject = project; } private void checkForDisplayFirstReload() { if (myProject.isDisposed()) { return; } final PropertiesComponent properties = PropertiesComponent.getInstance(myProject); final boolean alreadyRun = properties.getBoolean(RELOAD_ALREADY_RUN); if (!alreadyRun) { properties.setValue(RELOAD_ALREADY_RUN, true); final Notification notification = new Notification( FlutterMessages.FLUTTER_NOTIFICATION_GROUP_ID, FlutterBundle.message("flutter.reload.firstRun.title"), FlutterBundle.message("flutter.reload.firstRun.content"), NotificationType.INFORMATION); notification.setIcon(FlutterIcons.HotReload); notification.addAction(new AnAction("Learn more") { @Override public void actionPerformed(@NotNull AnActionEvent event) { BrowserUtil.browse(FlutterBundle.message("flutter.reload.firstRun.url")); notification.expire(); } }); Notifications.Bus.notify(notification, myProject); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/FlutterRunNotifications.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterRunNotifications.java", "repo_id": "flutter-intellij", "token_count": 961 }
455
/* * 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.bazel; import com.google.common.annotations.VisibleForTesting; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.configurations.RunConfigurationSingletonPolicy; import com.intellij.openapi.project.Project; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.jetbrains.lang.dart.DartFileType; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; public class FlutterBazelRunConfigurationType extends ConfigurationTypeBase { @VisibleForTesting final Factory factory = new Factory(this); public FlutterBazelRunConfigurationType() { super("FlutterBazelRunConfigurationType", FlutterBundle.message("runner.flutter.bazel.configuration.name"), FlutterBundle.message("runner.flutter.bazel.configuration.description"), FlutterIcons.BazelRun); addFactory(factory); } /** * Defined here for all Flutter Bazel run configurations. */ public static boolean doShowBazelRunConfigurationForProject(@NotNull Project project) { return FileTypeIndex.containsFileOfType(DartFileType.INSTANCE, GlobalSearchScope.projectScope(project)) && FlutterModuleUtils.isFlutterBazelProject(project); } @VisibleForTesting static class Factory extends ConfigurationFactory { public Factory(FlutterBazelRunConfigurationType type) { super(type); } @Override @NotNull public RunConfiguration createTemplateConfiguration(@NotNull Project project) { // This is always called first when loading a run config, even when it's a non-template config. // See RunManagerImpl.doCreateConfiguration return new BazelRunConfig(project, this, FlutterBundle.message("runner.flutter.bazel.configuration.name")); } @Override @NotNull public RunConfiguration createConfiguration(String name, @NotNull RunConfiguration template) { // Called in two cases: // - When creating a non-template config from a template. // - whenever the run configuration editor is open (for creating snapshots). // In the first case, we want to override the defaults from the template. // In the second case, don't change anything. if (isNewlyGeneratedName(name) && template instanceof BazelRunConfig) { // TODO(jwren) is this really a good name for a new run config? Not sure why we override this. // Note that if the user creates more than one run config, they will need to rename it manually. name = template.getProject().getName(); return ((BazelRunConfig)template).copyTemplateToNonTemplate(name); } else { return super.createConfiguration(name, template); } } private boolean isNewlyGeneratedName(String name) { // Try to determine if this we are creating a non-template configuration from a template. // This is a hack based on what the code does in RunConfigurable.createUniqueName(). // If it fails to match, the new run config still works, just without any defaults set. final String baseName = ExecutionBundle.message("run.configuration.unnamed.name.prefix"); return name.equals(baseName) || name.startsWith(baseName + " ("); } @Override public boolean isApplicable(@NotNull Project project) { return FlutterBazelRunConfigurationType.doShowBazelRunConfigurationForProject(project); } @Override @NotNull public String getId() { return FlutterBundle.message("runner.flutter.bazel.configuration.name"); } @NotNull @Override public RunConfigurationSingletonPolicy getSingletonPolicy() { return RunConfigurationSingletonPolicy.MULTIPLE_INSTANCE_ONLY; } } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazel/FlutterBazelRunConfigurationType.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazel/FlutterBazelRunConfigurationType.java", "repo_id": "flutter-intellij", "token_count": 1314 }
456
/* * 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.common; import com.intellij.execution.TestStateStorage; import com.intellij.execution.lineMarker.ExecutorAction; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.execution.testframework.TestIconMapper; import com.intellij.execution.testframework.sm.runner.states.TestStateInfo; import com.intellij.icons.AllIcons; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiInvalidElementAccessException; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.util.Function; import com.intellij.util.Time; import com.jetbrains.lang.dart.psi.DartCallExpression; import com.jetbrains.lang.dart.psi.DartFunctionDeclarationWithBodyOrNative; import com.jetbrains.lang.dart.psi.DartId; import java.util.Date; import java.util.Map; import javax.swing.Icon; import io.flutter.run.test.TestConfigUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Utility for creating {@link RunLineMarkerContributor}s for tests. */ public abstract class TestLineMarkerContributor extends RunLineMarkerContributor { private static final int SCANNED_TEST_RESULT_LIMIT = 1024; @NotNull private final CommonTestConfigUtils testConfigUtils; protected TestLineMarkerContributor(@NotNull CommonTestConfigUtils testConfigUtils) { this.testConfigUtils = testConfigUtils; } @Nullable @Override public Info getInfo(@NotNull PsiElement element) { // We look for leaf nodes of a PSI tree matching the pattern of a Dart unit test, and place // the line marker at that leaf node; see #4036 for some background. // // The pattern we're matching below is: // DartCallExpression // DartReferenceExpression // DartId // LeafPsiElement if (element instanceof LeafElement && element.getParent() instanceof DartId) { final DartId dartId = (DartId)element.getParent(); if (dartId.getParent() != null) { if (dartId.getParent().getParent() instanceof DartCallExpression) { final DartCallExpression dartCallExpression = (DartCallExpression)dartId.getParent().getParent(); final TestType testCall = testConfigUtils.asTestCall(dartCallExpression); if (testCall != null) { final Icon icon = getTestStateIcon(element, testCall.getIcon()); final Function<PsiElement, String> tooltipProvider = psiElement -> testCall.getTooltip(psiElement, testConfigUtils); return new RunLineMarkerContributor.Info(icon, tooltipProvider, ExecutorAction.getActions()); } } else if (dartId.getParent().getParent() instanceof DartFunctionDeclarationWithBodyOrNative) { if (testConfigUtils instanceof TestConfigUtils) { // TODO(messick) Find a better way to eliminate duplicate pop-up menu entries. // The issue is that there are two contributors, one for normal Flutter, one for Bazel, // and they should not both produce contributions at the same time. return null; } if ("main".equals(dartId.getText())) { // There seems to be an intermittent timing issue that causes the first test call to not get marked. // Priming the cache here solves it. testConfigUtils.refreshOutline(element); TestType testCall = TestType.MAIN; final Icon icon = getTestStateIcon(element, testCall.getIcon()); final Function<PsiElement, String> tooltipProvider = psiElement -> testCall.getTooltip(psiElement, testConfigUtils); return new RunLineMarkerContributor.Info(icon, tooltipProvider, ExecutorAction.getActions()); } } } } return null; } @NotNull private static Icon getTestStateIcon(@NotNull PsiElement element, @NotNull Icon defaultIcon) { // SMTTestProxy maps test run data to a URI derived from a location hint produced by `package:test`. // If we can find corresponding data, we can provide state-aware icons. If not, we default to // a standard Run state. PsiFile containingFile; try { containingFile = element.getContainingFile(); } catch (PsiInvalidElementAccessException e) { containingFile = null; } final Project project = element.getProject(); final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project); final Document document = containingFile == null ? null : psiDocumentManager.getDocument(containingFile); if (document != null) { final int textOffset = element.getTextOffset(); final int lineNumber = document.getLineNumber(textOffset); // e.g., dart_location:///Users/pq/IdeaProjects/untitled1298891289891/test/unit_test.dart,3,2,["my first unit test"] final String path = FileUtil.toSystemIndependentName(containingFile.getVirtualFile().getPath()); final String testLocationPrefix = "dart_location://" + path + "," + lineNumber; final TestStateStorage storage = TestStateStorage.getInstance(project); if (storage != null) { final Map<String, TestStateStorage.Record> tests = storage.getRecentTests(SCANNED_TEST_RESULT_LIMIT, getSinceDate()); if (tests != null) { // TODO(pq): investigate performance implications. for (Map.Entry<String, TestStateStorage.Record> entry : tests.entrySet()) { if (entry.getKey().startsWith(testLocationPrefix)) { final TestStateStorage.Record state = entry.getValue(); final TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude); if (magnitude != null) { switch (magnitude) { case IGNORED_INDEX: return AllIcons.RunConfigurations.TestState.Yellow2; case ERROR_INDEX: case FAILED_INDEX: return AllIcons.RunConfigurations.TestState.Red2; case PASSED_INDEX: case COMPLETE_INDEX: return AllIcons.RunConfigurations.TestState.Green2; default: } } } } } } } return defaultIcon; } private static Date getSinceDate() { return new Date(System.currentTimeMillis() - Time.DAY); } }
flutter-intellij/flutter-idea/src/io/flutter/run/common/TestLineMarkerContributor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/common/TestLineMarkerContributor.java", "repo_id": "flutter-intellij", "token_count": 2556 }
457
/* * 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.daemon; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.intellij.concurrency.JobScheduler; import com.intellij.execution.ExecutionException; import com.intellij.ide.ActivityTracker; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.util.Disposer; import io.flutter.FlutterMessages; import io.flutter.FlutterUtils; import io.flutter.bazel.WorkspaceCache; import io.flutter.run.FlutterDevice; import io.flutter.sdk.AndroidEmulatorManager; import io.flutter.sdk.FlutterSdkManager; import io.flutter.utils.Refreshable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * Provides the list of available devices (mobile phones or emulators) that appears in the dropdown menu. */ public class DeviceService { @NotNull private final Project project; /** * The process used to watch for device list changes (for the device menu). May be null if not running. */ private final Refreshable<DeviceDaemon> deviceDaemon = new Refreshable<>(DeviceDaemon::shutdown); private final AtomicReference<DeviceSelection> deviceSelection = new AtomicReference<>(DeviceSelection.EMPTY); private final AtomicReference<ImmutableSet<Runnable>> listeners = new AtomicReference<>(ImmutableSet.of()); private final AtomicLong lastRestartTime = new AtomicLong(0); private boolean refreshInProgress = false; @NotNull public static DeviceService getInstance(@NotNull final Project project) { return Objects.requireNonNull(project.getService(DeviceService.class)); } private DeviceService(@NotNull final Project project) { this.project = project; deviceDaemon.setDisposeParent(project); deviceDaemon.subscribe(this::refreshDeviceSelection); refreshDeviceDaemon(); // Watch for Flutter SDK changes. final FlutterSdkManager.Listener sdkListener = new FlutterSdkManager.Listener() { @Override public void flutterSdkAdded() { refreshDeviceDaemon(); } @Override public void flutterSdkRemoved() { refreshDeviceDaemon(); } }; FlutterSdkManager.getInstance(project).addListener(sdkListener); Disposer.register(project, () -> FlutterSdkManager.getInstance(project).removeListener(sdkListener)); // Watch for Bazel workspace changes. WorkspaceCache.getInstance(project).subscribe(this::refreshDeviceDaemon); // Watch for Java SDK changes. (Used to get the value of ANDROID_HOME.) ProjectRootManagerEx.getInstanceEx(project).addProjectJdkListener(this::refreshDeviceDaemon); } /** * Adds a callback for any changes to the status, device list, or selection. */ public void addListener(@NotNull Runnable callback) { listeners.updateAndGet((old) -> { final List<Runnable> changed = new ArrayList<>(old); changed.add(callback); return ImmutableSet.copyOf(changed); }); } public void removeListener(@NotNull Runnable callback) { listeners.updateAndGet((old) -> { final List<Runnable> changed = new ArrayList<>(old); changed.remove(callback); return ImmutableSet.copyOf(changed); }); } public boolean isRefreshInProgress() { return refreshInProgress; } /** * Returns whether the device list is inactive, loading, or ready. */ public State getStatus() { final DeviceDaemon daemon = deviceDaemon.getNow(); if (daemon != null && daemon.isRunning()) { return State.READY; } else if (deviceDaemon.getState() == Refreshable.State.BUSY) { return State.LOADING; } else { return State.INACTIVE; } } /** * Returns the currently connected devices, sorted by device name. */ public Collection<FlutterDevice> getConnectedDevices() { return deviceSelection.get().getDevices(); } /** * Returns the currently selected device. * <p> * <p>When there is no device list (perhaps because the daemon isn't running), this will be null. */ @Nullable public FlutterDevice getSelectedDevice() { return deviceSelection.get().getSelection(); } public void setSelectedDevice(@Nullable FlutterDevice device) { deviceSelection.updateAndGet((old) -> old.withSelection(device == null ? null : device.deviceId())); fireChangeEvent(); } private synchronized void refreshDeviceSelection() { deviceSelection.updateAndGet((old) -> { final DeviceDaemon daemon = deviceDaemon.getNow(); final List<FlutterDevice> newDevices = daemon == null ? ImmutableList.of() : daemon.getDevices(); return old.withDevices(newDevices); }); fireChangeEvent(); } private void fireChangeEvent() { SwingUtilities.invokeLater(() -> { if (project.isDisposed()) return; for (Runnable listener : listeners.get()) { try { listener.run(); } catch (Exception e) { FlutterUtils.warn(LOG, "DeviceDaemon listener threw an exception", e); } } }); } /** * Updates the device daemon to what it should be based on current configuration. * <p> * <p>This might mean starting it, stopping it, or restarting it. */ private void refreshDeviceDaemon() { ApplicationManager.getApplication().executeOnPooledThread(() -> { DumbService.getInstance(project).waitForSmartMode(); if (project.isDisposed()) return; deviceDaemon.refresh(this::chooseNextDaemon); refreshInProgress = false; ActivityTracker.getInstance().inc(); }); } private void daemonStopped(String details) { if (project.isDisposed()) return; final DeviceDaemon current = deviceDaemon.getNow(); if (current == null || current.isRunning()) { // The active daemon didn't die, so it must be some older process. Just log it. LOG.info("A Flutter device daemon stopped.\n" + details); return; } // If we haven't tried restarting recently, try again. final long now = System.currentTimeMillis(); final long millisSinceLastRestart = now - lastRestartTime.get(); if (millisSinceLastRestart > TimeUnit.SECONDS.toMillis(20)) { LOG.info("A Flutter device daemon stopped. Automatically restarting it.\n" + details); refreshDeviceDaemon(); lastRestartTime.set(now); return; } // Display as a notification to the user. final ApplicationInfo info = ApplicationInfo.getInstance(); FlutterMessages.showWarning( "Flutter daemon terminated", "Consider re-starting " + info.getVersionName() + ".", project); } /** * Returns the device daemon that should be running. * <p> * <p>Starts it if needed. If null is returned then the previous daemon will be shut down. */ private DeviceDaemon chooseNextDaemon(Refreshable.Request<DeviceDaemon> request) { final DeviceDaemon.Command nextCommand = DeviceDaemon.chooseCommand(project); if (nextCommand == null) { return null; // Unconfigured; shut down if running. } final DeviceDaemon previous = request.getPrevious(); if (previous != null && !previous.needRestart(nextCommand)) { return previous; // Don't do anything; current daemon is what we want. } // Wait a bit to see if we get cancelled. This is to try to avoid starting a process only to // immediately kill it. Also, delay a bit in case the flutter tool just upgraded the sdk; // we'll need a bit more time to start up. try { Thread.sleep(100); } catch (InterruptedException e) { return previous; } if (request.isCancelled()) { return previous; } // When starting the device daemon, also refresh the list of AndroidEmulators. final AndroidEmulatorManager emulatorManager = AndroidEmulatorManager.getInstance(project); emulatorManager.refresh(); try { return nextCommand.start(request::isCancelled, this::refreshDeviceSelection, this::daemonStopped); } catch (ExecutionException executionException) { LOG.info("Error starting up the Flutter device daemon", executionException); // Couldn't start a new instance; don't shut down down any previous instance. return previous; } } public void restart() { if (project.isDisposed()) return; refreshInProgress = true; JobScheduler.getScheduler().schedule(this::shutDown, 0, TimeUnit.SECONDS); JobScheduler.getScheduler().schedule(this::refreshDeviceDaemon, 4, TimeUnit.SECONDS); } private void shutDown() { deviceDaemon.refresh(this::shutDownDaemon); } @SuppressWarnings("SameReturnValue") private DeviceDaemon shutDownDaemon(Refreshable.Request<DeviceDaemon> request) { // Return null to indicate that a shutdown is requested. return null; } public enum State {INACTIVE, LOADING, READY} private static final Logger LOG = Logger.getInstance(DeviceService.class); }
flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DeviceService.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DeviceService.java", "repo_id": "flutter-intellij", "token_count": 3152 }
458
/* * 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.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.CommandLineState; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.execution.filters.UrlFilter; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil; import com.intellij.execution.testframework.ui.BaseTestsOutputConsoleView; import com.intellij.execution.ui.ConsoleView; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.jetbrains.lang.dart.ide.runner.DartConsoleFilter; import com.jetbrains.lang.dart.ide.runner.DartRelativePathsConsoleFilter; import com.jetbrains.lang.dart.util.DartUrlResolver; import io.flutter.FlutterBundle; import io.flutter.pub.PubRoot; import io.flutter.run.common.ConsoleProps; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.DaemonConsoleView; import io.flutter.sdk.FlutterCommandStartResult; import io.flutter.sdk.FlutterSdk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A launcher that starts a process to run flutter tests, created from a run configuration. */ class TestLaunchState extends CommandLineState { @NotNull private final TestConfig config; @NotNull private final TestFields fields; @NotNull private final VirtualFile testFileOrDir; @NotNull private final PubRoot pubRoot; private final boolean testConsoleEnabled; private ProcessHandler processHandler; private TestLaunchState(@NotNull ExecutionEnvironment env, @NotNull TestConfig config, @NotNull VirtualFile testFileOrDir, @NotNull PubRoot pubRoot, boolean testConsoleEnabled) { super(env); this.config = config; this.fields = config.getFields(); this.testFileOrDir = testFileOrDir; this.pubRoot = pubRoot; this.testConsoleEnabled = testConsoleEnabled; } static TestLaunchState create(@NotNull ExecutionEnvironment env, @NotNull TestConfig config) throws ExecutionException { final TestFields fields = config.getFields(); try { fields.checkRunnable(env.getProject()); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } FileDocumentManager.getInstance().saveAllDocuments(); final VirtualFile fileOrDir = fields.getFileOrDir(); assert (fileOrDir != null); final PubRoot pubRoot = fields.getPubRoot(env.getProject()); assert (pubRoot != null); final FlutterSdk sdk = FlutterSdk.getFlutterSdk(env.getProject()); assert (sdk != null); final boolean testConsoleEnabled = sdk.getVersion().flutterTestSupportsMachineMode(); final TestLaunchState launcher = new TestLaunchState(env, config, fileOrDir, pubRoot, testConsoleEnabled); DaemonConsoleView.install(launcher, env, pubRoot.getRoot()); return launcher; } @NotNull @Override protected ProcessHandler startProcess() throws ExecutionException { final RunMode mode = RunMode.fromEnv(getEnvironment()); final FlutterCommandStartResult result = fields.run(getEnvironment().getProject(), mode); switch (result.status) { case OK: assert result.processHandler != null; processHandler = result.processHandler; return result.processHandler; case EXCEPTION: assert result.exception != null; throw new ExecutionException(FlutterBundle.message("flutter.command.exception.message" + result.exception.getMessage())); default: throw new ExecutionException("Unexpected state"); } } @Nullable @Override protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException { if (!testConsoleEnabled) { return super.createConsole(executor); } // Create a console showing a test tree. final Project project = getEnvironment().getProject(); final DartUrlResolver resolver = DartUrlResolver.getInstance(project, testFileOrDir); final ConsoleProps props = ConsoleProps.forPub(config, executor, resolver); final BaseTestsOutputConsoleView console = SMTestRunnerConnectionUtil.createConsole(ConsoleProps.pubFrameworkName, props); final Module module = ModuleUtil.findModuleForFile(testFileOrDir, project); console.addMessageFilter(new DartConsoleFilter(project, getTestFileOrDir())); final String baseDir = getBaseDir(); if (baseDir != null) { console.addMessageFilter(new DartRelativePathsConsoleFilter(project, baseDir)); } console.addMessageFilter(new UrlFilter()); return console; } @Nullable private String getBaseDir() { final PubRoot root = config.getFields().getPubRoot(config.getProject()); if (root != null) { return root.getPath(); } final VirtualFile baseDir = config.getProject().getBaseDir(); return baseDir == null ? null : baseDir.getPath(); } @NotNull VirtualFile getTestFileOrDir() { return testFileOrDir; } @NotNull PubRoot getPubRoot() { return pubRoot; } public boolean isTerminated() { return processHandler != null && processHandler.isProcessTerminated(); } public void notifyTextAvailable(@NotNull String text, @NotNull Key<?> outputType) { if (processHandler != null) { processHandler.notifyTextAvailable(text, outputType); } } }
flutter-intellij/flutter-idea/src/io/flutter/run/test/TestLaunchState.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/TestLaunchState.java", "repo_id": "flutter-intellij", "token_count": 1876 }
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.sdk; import com.intellij.concurrency.JobScheduler; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.util.Disposer; import com.intellij.util.EventDispatcher; import org.jetbrains.annotations.NotNull; import java.util.EventListener; import java.util.Objects; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Monitors the application library table to notify clients when Flutter SDK configuration changes. */ public class FlutterSdkManager { private final EventDispatcher<Listener> myListenerDispatcher = EventDispatcher.create(Listener.class); private boolean isFlutterConfigured; private final @NotNull Project myProject; @NotNull public static FlutterSdkManager getInstance(@NotNull Project project) { return Objects.requireNonNull(project.getService(FlutterSdkManager.class)); } private FlutterSdkManager(@NotNull Project project) { myProject = project; final LibraryTableListener libraryTableListener = new LibraryTableListener(); final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project); libraryTable.addListener(libraryTableListener); // TODO(devoncarew): We should replace this polling solution with listeners to project structure changes. final ScheduledFuture timer = JobScheduler.getScheduler().scheduleWithFixedDelay( this::checkForFlutterSdkChange, 1, 1, TimeUnit.SECONDS); Disposer.register(project, () -> { LibraryTablesRegistrar.getInstance().getLibraryTable(project).removeListener(libraryTableListener); timer.cancel(false); }); ProjectManager.getInstance().addProjectManagerListener(myProject, new ProjectManagerListener() { //See https://plugins.jetbrains.com/docs/intellij/plugin-components.html#comintellijpoststartupactivity // for notice and documentation on the deprecation intentions of // Components from JetBrains. // // Migration forward has different directions before and after // 2023.1, if we can, it would be prudent to wait until we are // only supporting this major platform as a minimum version. // // https://github.com/flutter/flutter-intellij/issues/6953 @Override public void projectOpened(@NotNull Project project) { checkForFlutterSdkChange(); } @Override public void projectClosed(@NotNull Project project) { checkForFlutterSdkChange(); } }); // Cache initial state. isFlutterConfigured = isFlutterSdkSetAndNeeded(); } // Send events if Flutter SDK was configured or unconfigured. public void checkForFlutterSdkChange() { if (!isFlutterConfigured && isFlutterSdkSetAndNeeded()) { isFlutterConfigured = true; myListenerDispatcher.getMulticaster().flutterSdkAdded(); } else if (isFlutterConfigured && !isFlutterSdkSetAndNeeded()) { isFlutterConfigured = false; myListenerDispatcher.getMulticaster().flutterSdkRemoved(); } } public void addListener(@NotNull Listener listener) { myListenerDispatcher.addListener(listener); } public void removeListener(@NotNull Listener listener) { myListenerDispatcher.removeListener(listener); } private boolean isFlutterSdkSetAndNeeded() { return FlutterSdk.getFlutterSdk(myProject) != null && FlutterSdkUtil.hasFlutterModules(myProject); } /** * Listen for SDK configuration changes. */ public interface Listener extends EventListener { /** * Fired when the Flutter global library is set. */ default void flutterSdkAdded() { } /** * Fired when the Flutter global library is removed. */ default void flutterSdkRemoved() { } } // Listens for changes in Flutter Library configuration state in the Library table. private final class LibraryTableListener implements LibraryTable.Listener { @Override public void afterLibraryAdded(@NotNull Library newLibrary) { checkForFlutterSdkChange(); } @Override public void afterLibraryRenamed(@NotNull Library library) { // Since we key off name, test to be safe. checkForFlutterSdkChange(); } @Override public void beforeLibraryRemoved(@NotNull Library library) { // Test after. } @Override public void afterLibraryRemoved(@NotNull Library library) { checkForFlutterSdkChange(); } } }
flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSdkManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSdkManager.java", "repo_id": "flutter-intellij", "token_count": 1585 }
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.utils; import com.intellij.lang.java.JavaParserDefinition; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectType; import com.intellij.openapi.project.ProjectTypeService; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.JavaTokenType; import com.intellij.psi.tree.java.IKeywordElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; // based on: org.jetbrains.android.util.AndroidUtils @SuppressWarnings("LocalCanBeFinal") public class AndroidUtils { private static final Lexer JAVA_LEXER = JavaParserDefinition.createLexer(LanguageLevel.JDK_1_5); // Flutter internal implementation dependencies. public static final String FLUTTER_MODULE_NAME = "flutter"; /** * Validates a potential package name and returns null if the package name is valid, and otherwise * returns a description for why it is not valid. * <p> * Note that Android package names are more restrictive than general Java package names; * we require at least two segments, limit the character set to [a-zA-Z0-9_] (Java allows any * {@link Character#isLetter(char)} and require that each segment start with a letter (Java allows * underscores at the beginning). * <p> * For details, see core/java/android/content/pm/PackageParser.java#validateName * * @param name the package name * @return null if the package is valid as an Android package name, and otherwise a description for why not */ @Nullable public static String validateAndroidPackageName(@NotNull String name) { if (name.isEmpty()) { return "Package name is missing"; } String packageManagerCheck = validateName(name, true); if (packageManagerCheck != null) { return packageManagerCheck; } // In addition, we have to check that none of the segments are Java identifiers, since // that will lead to compilation errors, which the package manager doesn't need to worry about // (the code wouldn't have compiled) int index = 0; while (true) { int index1 = name.indexOf('.', index); if (index1 < 0) { index1 = name.length(); } String error = isReservedKeyword(name.substring(index, index1)); if (error != null) return error; if (index1 == name.length()) { break; } index = index1 + 1; } return null; } @Nullable public static String isReservedKeyword(@NotNull String string) { Lexer lexer = JAVA_LEXER; lexer.start(string); if (lexer.getTokenType() != JavaTokenType.IDENTIFIER) { if (lexer.getTokenType() instanceof IKeywordElementType) { return "Package names cannot contain Java keywords like '" + string + "'"; } if (string.isEmpty()) { return "Package segments must be of non-zero length"; } return string + " is not a valid identifier"; } return null; } // This method is a copy of android.content.pm.PackageParser#validateName with the // error messages tweaked @Nullable private static String validateName(String name, boolean requiresSeparator) { final int N = name.length(); boolean hasSep = false; boolean front = true; for (int i = 0; i < N; i++) { final char c = name.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { front = false; continue; } if ((c >= '0' && c <= '9') || c == '_') { if (!front) { continue; } else { if (c == '_') { return "The character '_' cannot be the first character in a package segment"; } else { return "A digit cannot be the first character in a package segment"; } } } if (c == '.') { hasSep = true; front = true; continue; } return "The character '" + c + "' is not allowed in Android application package names"; } return hasSep || !requiresSeparator ? null : "The package must have at least one '.' separator"; } public static boolean isAndroidProject(@Nullable Project project) { // Note: IntelliJ does not set the project type. When a Flutter module is added to an // IntelliJ-created Android project we need to set it. We need to allow an alternative // name. GradleResourceCompilerConfigurationGenerator depends on "Android". // TODO(messick) Recognize both native Android Studio and IntelliJ Android projects. ProjectType projectType = ProjectTypeService.getProjectType(project); return projectType != null && "Android".equals(projectType.getId()); } }
flutter-intellij/flutter-idea/src/io/flutter/utils/AndroidUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/AndroidUtils.java", "repo_id": "flutter-intellij", "token_count": 1697 }
461
/* * Copyright 2020 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.utils; import com.intellij.openapi.util.SystemInfo; import io.flutter.settings.FlutterSettings; import org.jetbrains.annotations.NotNull; // import com.intellij.util.system.CpuArch; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class JxBrowserUtils { private static final String JXBROWSER_FILE_PREFIX = "jxbrowser"; private static final String JXBROWSER_FILE_VERSION = "7.27"; private static final String JXBROWSER_FILE_SUFFIX = "jar"; public static final String LICENSE_PROPERTY_NAME = "jxbrowser.license.key"; public String getPlatformFileName() throws FileNotFoundException { String name = ""; if (SystemInfo.isMac) { if (SystemInfo.OS_ARCH.equals("aarch64")) { name = "mac-arm"; } else { name = "mac"; } } else if (SystemInfo.isWindows) { if (SystemInfo.is32Bit) { name = "win32"; } else if (SystemInfo.is64Bit) { name = "win64"; } } else if (SystemInfo.isLinux && SystemInfo.is64Bit) { name = "linux64"; } if (name.isEmpty()) { throw new FileNotFoundException("Unable to find matching JxBrowser platform file for: " + SystemInfo.getOsNameAndVersion()); } return String.format("%s-%s-%s.%s", JXBROWSER_FILE_PREFIX, name, JXBROWSER_FILE_VERSION, JXBROWSER_FILE_SUFFIX); } public String getApiFileName() { return String.format("%s-%s.%s", JXBROWSER_FILE_PREFIX, JXBROWSER_FILE_VERSION, JXBROWSER_FILE_SUFFIX); } public String getSwingFileName() { return String.format("%s-swing-%s.%s", JXBROWSER_FILE_PREFIX, JXBROWSER_FILE_VERSION, JXBROWSER_FILE_SUFFIX); } @NotNull public String getDistributionLink(@NotNull String fileName) { String envBaseUrl = java.lang.System.getenv("FLUTTER_STORAGE_BASE_URL"); String baseUrl = envBaseUrl == null ? "https://storage.googleapis.com" : envBaseUrl; return String.format("%s/flutter_infra_release/flutter/intellij/jxbrowser/%s", baseUrl, fileName); } @NotNull public String getJxBrowserKey() throws FileNotFoundException { if (JxBrowserUtils.class.getResource("/jxbrowser/jxbrowser.properties") == null) { throw new FileNotFoundException("jxbrowser.properties file does not exist"); } final Properties properties = new Properties(); try { properties.load(JxBrowserUtils.class.getResourceAsStream("/jxbrowser/jxbrowser.properties")); } catch (IOException ex) { throw new FileNotFoundException("Unable to load properties of JxBrowser key file"); } final String value = properties.getProperty(LICENSE_PROPERTY_NAME); if (value == null) { throw new FileNotFoundException("No value for JxBrowser key exists"); } return value; } public boolean licenseIsSet() { return System.getProperty(JxBrowserUtils.LICENSE_PROPERTY_NAME) != null; } public boolean skipInstallation() { return FlutterSettings.getInstance().isEnableJcefBrowser(); } }
flutter-intellij/flutter-idea/src/io/flutter/utils/JxBrowserUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/JxBrowserUtils.java", "repo_id": "flutter-intellij", "token_count": 1168 }
462
/* * 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.utils.animation; /** * A curve that is the reversed inversion of its given curve. * <p> * This curve evaluates the given curve in reverse (i.e., from 1.0 to 0.0 as t * increases from 0.0 to 1.0) and returns the inverse of the given curve's value * (i.e., 1.0 minus the given curve's value). * <p> * This is the class used to implement the getFlipped method on curves. */ public class FlippedCurve extends Curve { /** * Creates a flipped curve. */ public FlippedCurve(Curve curve) { assert (curve != null); this.curve = curve; } /** * The curve that is being flipped. */ public final Curve curve; @Override public double transform(double t) { return 1.0 - curve.transform(1.0 - t); } @Override public String toString() { return this.getClass() + "(" + curve + ")"; } }
flutter-intellij/flutter-idea/src/io/flutter/utils/animation/FlippedCurve.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/animation/FlippedCurve.java", "repo_id": "flutter-intellij", "token_count": 330 }
463
/* * 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.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.DumbAwareAction; import io.flutter.FlutterInitializer; import io.flutter.run.daemon.FlutterApp; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public abstract class FlutterViewAction extends DumbAwareAction { @NotNull public final FlutterApp app; FlutterViewAction(@NotNull FlutterApp app, @Nullable String text) { super(text); this.app = app; } FlutterViewAction(@NotNull FlutterApp app, @Nullable String text, @Nullable String description, @Nullable Icon icon) { super(text, description, icon); this.app = app; } @Override public void actionPerformed(@NotNull AnActionEvent e) { FlutterInitializer.sendAnalyticsAction(this); perform(e); } protected abstract void perform(@Nullable AnActionEvent event); @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(app.isSessionActive()); } public void handleAppStarted() { } public void handleAppRestarted() { } }
flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewAction.java", "repo_id": "flutter-intellij", "token_count": 419 }
464
/* * 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.view; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnActionEvent; import io.flutter.run.daemon.FlutterApp; import io.flutter.vmService.ServiceExtensions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; @SuppressWarnings("ComponentNotRegistered") public class TimeDilationAction extends FlutterViewToggleableAction<Double> { public TimeDilationAction(@NotNull FlutterApp app, boolean showIcon) { super(app, showIcon ? AllIcons.Vcs.History : null, ServiceExtensions.slowAnimations); } @Override protected void perform(@Nullable AnActionEvent event) { final Map<String, Object> params = new HashMap<>(); params.put( "timeDilation", isSelected() ? ServiceExtensions.slowAnimations.getEnabledValue() : ServiceExtensions.slowAnimations.getDisabledValue()); if (app.isSessionActive()) { app.callServiceExtension(ServiceExtensions.slowAnimations.getExtension(), params); } } }
flutter-intellij/flutter-idea/src/io/flutter/view/TimeDilationAction.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/TimeDilationAction.java", "repo_id": "flutter-intellij", "token_count": 405 }
465
package io.flutter.vmService; import org.dartlang.vm.service.consumer.*; import org.dartlang.vm.service.element.*; import java.util.List; public class VmServiceConsumers { public static final SuccessConsumer EMPTY_SUCCESS_CONSUMER = new SuccessConsumer() { @Override public void received(Success response) { } @Override public void onError(RPCError error) { } }; private static abstract class ConsumerWrapper implements Consumer { @Override public void onError(RPCError error) { } } public static abstract class SuccessConsumerWrapper extends ConsumerWrapper implements SuccessConsumer { } public static abstract class VmConsumerWrapper extends ConsumerWrapper implements VMConsumer { } public static abstract class GetIsolateConsumerWrapper extends ConsumerWrapper implements GetIsolateConsumer { @Override public void received(Sentinel response) { } } public static abstract class BreakpointsConsumer { abstract void received(List<Breakpoint> breakpointResponses, List<RPCError> errorResponses); abstract void sourcePositionNotApplicable(); } public static abstract class InvokeConsumerWrapper implements InvokeConsumer { @Override public final void received(ErrorRef response) { noGoodResult(); } @Override public final void received(Sentinel response) { noGoodResult(); } @Override public final void onError(RPCError error) { noGoodResult(); } abstract public void noGoodResult(); } public static abstract class EmptyResumeConsumer extends ConsumerWrapper implements ResumeConsumer { @Override public void received(Sentinel response) { } @Override public void received(Success response) { } } }
flutter-intellij/flutter-idea/src/io/flutter/vmService/VmServiceConsumers.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/VmServiceConsumers.java", "repo_id": "flutter-intellij", "token_count": 536 }
466
/* * Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file * for details. All rights reserved. Use of this source code is governed by a * BSD-style license that can be found in the LICENSE file. * * This file has been automatically generated. Please do not edit it manually. * To regenerate the file, use the script "pkg/analysis_server/tool/spec/generate_files". */ package org.dartlang.analysis.server.protocol; import com.google.common.collect.Lists; import com.google.dart.server.utilities.general.ObjectUtilities; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import static org.apache.commons.lang3.StringUtils.join; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * A property of a Flutter widget. * * @coverage dart.server.generated.types */ @SuppressWarnings("unused") public class FlutterWidgetProperty { public static final FlutterWidgetProperty[] EMPTY_ARRAY = new FlutterWidgetProperty[0]; public static final List<FlutterWidgetProperty> EMPTY_LIST = Lists.newArrayList(); /** * The documentation of the property to show to the user. Omitted if the server does not know the * documentation, e.g. because the corresponding field is not documented. */ private final String documentation; /** * If the value of this property is set, the Dart code of the expression of this property. */ private final String expression; /** * The unique identifier of the property, must be passed back to the server when updating the * property value. Identifiers become invalid on any source code change. */ private final int id; /** * True if the property is required, e.g. because it corresponds to a required parameter of a * constructor. */ private final boolean isRequired; /** * If the property expression is a concrete value (e.g. a literal, or an enum constant), then it is * safe to replace the expression with another concrete value. In this case this field is true. * Otherwise, for example when the expression is a reference to a field, so that its value is * provided from outside, this field is false. */ private final boolean isSafeToUpdate; /** * The name of the property to display to the user. */ private final String name; /** * The list of children properties, if any. For example any property of type EdgeInsets will have * four children properties of type double - left / top / right / bottom. */ private final List<FlutterWidgetProperty> children; /** * The editor that should be used by the client. This field is omitted if the server does not know * the editor for this property, for example because it does not have one of the supported types. */ private final FlutterWidgetPropertyEditor editor; /** * If the expression is set, and the server knows the value of the expression, this field is set. */ private final FlutterWidgetPropertyValue value; /** * Constructor for {@link FlutterWidgetProperty}. */ public FlutterWidgetProperty(String documentation, String expression, int id, boolean isRequired, boolean isSafeToUpdate, String name, List<FlutterWidgetProperty> children, FlutterWidgetPropertyEditor editor, FlutterWidgetPropertyValue value) { this.documentation = documentation; this.expression = expression; this.id = id; this.isRequired = isRequired; this.isSafeToUpdate = isSafeToUpdate; this.name = name; this.children = children; this.editor = editor; this.value = value; } @Override public boolean equals(Object obj) { if (obj instanceof FlutterWidgetProperty) { FlutterWidgetProperty other = (FlutterWidgetProperty)obj; return ObjectUtilities.equals(other.documentation, documentation) && ObjectUtilities.equals(other.expression, expression) && other.id == id && other.isRequired == isRequired && other.isSafeToUpdate == isSafeToUpdate && ObjectUtilities.equals(other.name, name) && ObjectUtilities.equals(other.children, children) && ObjectUtilities.equals(other.editor, editor) && ObjectUtilities.equals(other.value, value); } return false; } public static FlutterWidgetProperty fromJson(JsonObject jsonObject) { String documentation = jsonObject.get("documentation") == null ? null : jsonObject.get("documentation").getAsString(); String expression = jsonObject.get("expression") == null ? null : jsonObject.get("expression").getAsString(); int id = jsonObject.get("id").getAsInt(); boolean isRequired = jsonObject.get("isRequired").getAsBoolean(); boolean isSafeToUpdate = jsonObject.get("isSafeToUpdate").getAsBoolean(); String name = jsonObject.get("name").getAsString(); List<FlutterWidgetProperty> children = jsonObject.get("children") == null ? null : FlutterWidgetProperty.fromJsonArray(jsonObject.get("children").getAsJsonArray()); FlutterWidgetPropertyEditor editor = jsonObject.get("editor") == null ? null : FlutterWidgetPropertyEditor.fromJson(jsonObject.get("editor").getAsJsonObject()); FlutterWidgetPropertyValue value = jsonObject.get("value") == null ? null : FlutterWidgetPropertyValue.fromJson(jsonObject.get("value").getAsJsonObject()); return new FlutterWidgetProperty(documentation, expression, id, isRequired, isSafeToUpdate, name, children, editor, value); } public static List<FlutterWidgetProperty> fromJsonArray(JsonArray jsonArray) { if (jsonArray == null) { return EMPTY_LIST; } ArrayList<FlutterWidgetProperty> list = new ArrayList<FlutterWidgetProperty>(jsonArray.size()); Iterator<JsonElement> iterator = jsonArray.iterator(); while (iterator.hasNext()) { list.add(fromJson(iterator.next().getAsJsonObject())); } return list; } /** * The list of children properties, if any. For example any property of type EdgeInsets will have * four children properties of type double - left / top / right / bottom. */ public List<FlutterWidgetProperty> getChildren() { return children; } /** * The documentation of the property to show to the user. Omitted if the server does not know the * documentation, e.g. because the corresponding field is not documented. */ public String getDocumentation() { return documentation; } /** * The editor that should be used by the client. This field is omitted if the server does not know * the editor for this property, for example because it does not have one of the supported types. */ public FlutterWidgetPropertyEditor getEditor() { return editor; } /** * If the value of this property is set, the Dart code of the expression of this property. */ public String getExpression() { return expression; } /** * The unique identifier of the property, must be passed back to the server when updating the * property value. Identifiers become invalid on any source code change. */ public int getId() { return id; } /** * True if the property is required, e.g. because it corresponds to a required parameter of a * constructor. */ public boolean isRequired() { return isRequired; } /** * If the property expression is a concrete value (e.g. a literal, or an enum constant), then it is * safe to replace the expression with another concrete value. In this case this field is true. * Otherwise, for example when the expression is a reference to a field, so that its value is * provided from outside, this field is false. */ public boolean isSafeToUpdate() { return isSafeToUpdate; } /** * The name of the property to display to the user. */ public String getName() { return name; } /** * If the expression is set, and the server knows the value of the expression, this field is set. */ public FlutterWidgetPropertyValue getValue() { return value; } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); builder.append(documentation); builder.append(expression); builder.append(id); builder.append(isRequired); builder.append(isSafeToUpdate); builder.append(name); builder.append(children); builder.append(editor); builder.append(value); return builder.toHashCode(); } public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); if (documentation != null) { jsonObject.addProperty("documentation", documentation); } if (expression != null) { jsonObject.addProperty("expression", expression); } jsonObject.addProperty("id", id); jsonObject.addProperty("isRequired", isRequired); jsonObject.addProperty("isSafeToUpdate", isSafeToUpdate); jsonObject.addProperty("name", name); if (children != null) { JsonArray jsonArrayChildren = new JsonArray(); for (FlutterWidgetProperty elt : children) { jsonArrayChildren.add(elt.toJson()); } jsonObject.add("children", jsonArrayChildren); } if (editor != null) { jsonObject.add("editor", editor.toJson()); } if (value != null) { jsonObject.add("value", value.toJson()); } return jsonObject; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("["); builder.append("documentation="); builder.append(documentation).append(", "); builder.append("expression="); builder.append(expression).append(", "); builder.append("id="); builder.append(id).append(", "); builder.append("isRequired="); builder.append(isRequired).append(", "); builder.append("isSafeToUpdate="); builder.append(isSafeToUpdate).append(", "); builder.append("name="); builder.append(name).append(", "); builder.append("children="); builder.append(join(children, ", ")).append(", "); builder.append("editor="); builder.append(editor).append(", "); builder.append("value="); builder.append(value); builder.append("]"); return builder.toString(); } }
flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetProperty.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetProperty.java", "repo_id": "flutter-intellij", "token_count": 3395 }
467
/* * 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.bazel; import com.intellij.mock.MockVirtualFileSystem; import com.intellij.openapi.util.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FakeWorkspaceFactory { /** * Creates a {@code Workspace} for testing and a {@code MockVirtualFileSystem} with the expected Flutter script files. */ @NotNull public static Pair.NonNull<MockVirtualFileSystem, Workspace> createWorkspaceAndFilesystem( @Nullable String daemonScript, @Nullable String devToolsScript, @Nullable String doctorScript, @Nullable String testScript, @Nullable String runScript, @Nullable String syncScript, @Nullable String toolsScript, @Nullable String sdkHome, @Nullable String versionFile, @Nullable String requiredIJPluginID, @Nullable String requiredIJPluginMessage, @Nullable String configWarningMessage, @Nullable String updatedIosRunMessage ) { final MockVirtualFileSystem fs = new MockVirtualFileSystem(); fs.file("/workspace/WORKSPACE", ""); if (daemonScript != null) { fs.file("/workspace/" + daemonScript, ""); } if (devToolsScript != null) { fs.file("/workspace/" + devToolsScript, ""); } if (doctorScript != null) { fs.file("/workspace/" + doctorScript, ""); } if (testScript != null) { fs.file("/workspace/" + testScript, ""); } if (runScript != null) { fs.file("/workspace/" + runScript, ""); } if (syncScript != null) { fs.file("/workspace/" + syncScript, ""); } if (toolsScript != null) { fs.file("/workspace/" + toolsScript, ""); } if (sdkHome != null) { fs.file("/workspace/" + sdkHome, ""); } if (requiredIJPluginID != null) { fs.file("/workspace/" + requiredIJPluginID, ""); } if (requiredIJPluginMessage != null) { fs.file("/workspace/" + requiredIJPluginMessage, ""); } if (configWarningMessage != null) { fs.file("/workspace/" + configWarningMessage, ""); } return Pair.createNonNull( fs, Workspace.forTest( fs.findFileByPath("/workspace/"), PluginConfig.forTest( daemonScript, devToolsScript, doctorScript, testScript, runScript, syncScript, toolsScript, sdkHome, requiredIJPluginID, requiredIJPluginMessage, configWarningMessage, updatedIosRunMessage ) ) ); } /** * Creates a {@code Workspace} for testing and a {@code MockVirtualFileSystem} with the expected Flutter script files. * <p> * Uses default values for all fields. */ @NotNull public static Pair.NonNull<MockVirtualFileSystem, Workspace> createWorkspaceAndFilesystem() { return createWorkspaceAndFilesystem( "scripts/flutter-daemon.sh", "scripts/flutter-devtools.sh", "scripts/flutter-doctor.sh", "scripts/flutter-test.sh", "scripts/flutter-run.sh", "scripts/flutter-sync.sh", "scripts/flutter-tools.sh", "scripts/", "flutter-version", "some.ij.plugin.id", "Some IJ Plugin ID Message", "Config warning message", "Updated iOS run message" ); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/bazel/FakeWorkspaceFactory.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/bazel/FakeWorkspaceFactory.java", "repo_id": "flutter-intellij", "token_count": 1362 }
468
/* * Copyright 2020 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.jxbrowser; import com.intellij.openapi.project.Project; import io.flutter.analytics.Analytics; import io.flutter.utils.FileUtils; import io.flutter.utils.JxBrowserUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import static io.flutter.jxbrowser.JxBrowserManager.DOWNLOAD_PATH; import static org.mockito.Mockito.*; public class JxBrowserManagerTest { final Project mockProject = mock(Project.class); final Analytics mockAnalytics = mock(Analytics.class); final String PLATFORM_FILE_NAME = "test/platform/file/name"; final String API_FILE_NAME = "test/api/file/name"; final String SWING_FILE_NAME = "test/swing/file/name"; @Before public void setUp() { JxBrowserManager.resetForTest(); } @Test public void testSetUpIfKeyNotFound() throws FileNotFoundException { final JxBrowserUtils mockUtils = mock(JxBrowserUtils.class); when(mockUtils.getJxBrowserKey()).thenThrow(new FileNotFoundException("Key not found")); // If the directory for JxBrowser files cannot be created, the installation should fail. final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockAnalytics, mock(FileUtils.class)); manager.setUp(mockProject); Assert.assertEquals(JxBrowserStatus.INSTALLATION_FAILED, manager.getStatus()); } @Test public void testSetUpIfDirectoryFails() throws FileNotFoundException { final JxBrowserUtils mockUtils = mock(JxBrowserUtils.class); when(mockUtils.getJxBrowserKey()).thenReturn("KEY"); final FileUtils mockFileUtils = mock(FileUtils.class); when(mockFileUtils.makeDirectory(DOWNLOAD_PATH)).thenReturn(false); // If the directory for JxBrowser files cannot be created, the installation should fail. final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockAnalytics, mockFileUtils); manager.setUp(mockProject); Assert.assertEquals(JxBrowserStatus.INSTALLATION_FAILED, manager.getStatus()); } @Test public void testSetUpIfPlatformFileNotFound() throws FileNotFoundException { final JxBrowserUtils mockUtils = mock(JxBrowserUtils.class); when(mockUtils.getJxBrowserKey()).thenReturn("KEY"); when(mockUtils.getPlatformFileName()).thenThrow(new FileNotFoundException()); final FileUtils mockFileUtils = mock(FileUtils.class); when(mockFileUtils.makeDirectory(DOWNLOAD_PATH)).thenReturn(true); // If the system platform is not found among JxBrowser files, then the installation should fail. final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockAnalytics, mockFileUtils); manager.setUp(mockProject); Assert.assertEquals(JxBrowserStatus.INSTALLATION_FAILED, manager.getStatus()); } @Test public void testSetUpIfAllFilesExist() throws FileNotFoundException { final JxBrowserUtils mockUtils = mock(JxBrowserUtils.class); when(mockUtils.getJxBrowserKey()).thenReturn("KEY"); when(mockUtils.getPlatformFileName()).thenReturn(PLATFORM_FILE_NAME); when(mockUtils.getApiFileName()).thenReturn(API_FILE_NAME); when(mockUtils.getSwingFileName()).thenReturn(SWING_FILE_NAME); final FileUtils mockFileUtils = mock(FileUtils.class); when(mockFileUtils.makeDirectory(DOWNLOAD_PATH)).thenReturn(true); when(mockFileUtils.fileExists(anyString())).thenReturn(true); // If all of the files are already downloaded, we should load the existing files. final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockAnalytics, mockFileUtils); manager.setUp(mockProject); final String[] expectedFileNames = {PLATFORM_FILE_NAME, API_FILE_NAME, SWING_FILE_NAME}; Assert.assertEquals(JxBrowserStatus.INSTALLED, manager.getStatus()); } @Test public void testSetUpIfFilesMissing() throws FileNotFoundException { System.out.println("in testSetUpIfFilesMissing"); final JxBrowserUtils mockUtils = mock(JxBrowserUtils.class); when(mockUtils.getJxBrowserKey()).thenReturn("KEY"); when(mockUtils.getPlatformFileName()).thenReturn(PLATFORM_FILE_NAME); when(mockUtils.getApiFileName()).thenReturn(API_FILE_NAME); when(mockUtils.getSwingFileName()).thenReturn(SWING_FILE_NAME); final FileUtils mockFileUtils = mock(FileUtils.class); when(mockFileUtils.makeDirectory(DOWNLOAD_PATH)).thenReturn(true); when(mockFileUtils.fileExists(PLATFORM_FILE_NAME)).thenReturn(true); when(mockFileUtils.fileExists(API_FILE_NAME)).thenReturn(false); when(mockFileUtils.fileExists(SWING_FILE_NAME)).thenReturn(true); when(mockFileUtils.deleteFile(anyString())).thenReturn(true); // If any of our required files do not exist, we want to delete any existing files and start a download of all of the required files. final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockAnalytics, mockFileUtils); final JxBrowserManager spy = spy(manager); final String[] expectedFileNames = {PLATFORM_FILE_NAME, API_FILE_NAME, SWING_FILE_NAME}; doNothing().when(spy).downloadJxBrowser(mockProject, expectedFileNames); System.out.println("using spy"); spy.setUp(mockProject); verify(mockFileUtils, times(1)).deleteFile(DOWNLOAD_PATH + File.separatorChar + PLATFORM_FILE_NAME); verify(mockFileUtils, times(1)).deleteFile(DOWNLOAD_PATH + File.separatorChar + API_FILE_NAME); verify(mockFileUtils, times(1)).deleteFile(DOWNLOAD_PATH + File.separatorChar + SWING_FILE_NAME); verify(spy, times(1)).downloadJxBrowser(mockProject, expectedFileNames); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/jxbrowser/JxBrowserManagerTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/jxbrowser/JxBrowserManagerTest.java", "repo_id": "flutter-intellij", "token_count": 1936 }
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.run.bazel; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.mock.MockVirtualFileSystem; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import io.flutter.bazel.FakeWorkspaceFactory; import io.flutter.bazel.Workspace; import io.flutter.run.FlutterDevice; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.DevToolsInstance; import io.flutter.run.daemon.DevToolsService; import io.flutter.testing.ProjectFixture; import io.flutter.testing.Testing; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LaunchCommandsTest { @Rule public ProjectFixture projectFixture = Testing.makeCodeInsightModule(); DevToolsService mockService; @Before public void setUp() { final CompletableFuture<DevToolsInstance> future = new CompletableFuture<>(); future.complete(new DevToolsInstance("http://localhost", 1234)); mockService = mock(DevToolsService.class); when(mockService.getDevToolsInstance()).thenReturn(future); } @Test @Ignore public void producesCorrectCommandLineInReleaseMode() throws ExecutionException { final BazelFields fields = setupBazelFields( "bazel_target", null, null, true ); final FlutterDevice device = FlutterDevice.getTester(); GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--release"); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineString(), equalTo(String.join(" ", expectedCommandLine))); // When release mode is enabled, using different RunModes has no effect. launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.DEBUG); assertThat(launchCommand.getCommandLineString(), equalTo(String.join(" ", expectedCommandLine))); launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.PROFILE); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineInRunMode() throws ExecutionException { final BazelFields fields = setupBazelFields(); final FlutterDevice device = FlutterDevice.getTester(); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineWithBazelArgs() throws ExecutionException { final BazelFields fields = setupBazelFields( "bazel_target", "--define=bazel_args", null, false ); final FlutterDevice device = FlutterDevice.getTester(); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--bazel-options=--define=bazel_args"); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void overridesRunModeFromBazelArgs() throws ExecutionException { BazelFields fields = setupBazelFields( "bazel_target", "--define=flutter_build_mode=release", null, false ); final FlutterDevice device = FlutterDevice.getTester(); GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--bazel-options=--define=flutter_build_mode=release"); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); // With a space instead of an = fields = setupBazelFields( "bazel_target", "--define flutter_build_mode=profile", null, false ); launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--bazel-options=--define flutter_build_mode=profile"); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); // With multiple params fields = setupBazelFields( "bazel_target", "--define param1=2 --define=param2=2 --define=flutter_build_mode=profile", null, false ); launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--bazel-options=--define param1=2 --define=param2=2 --define=flutter_build_mode=profile"); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineWithAdditionalArgs() throws ExecutionException { final BazelFields fields = setupBazelFields( "bazel_target", null, "additional_args", false ); final FlutterDevice device = FlutterDevice.getTester(); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--machine"); expectedCommandLine.add("additional_args"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineWithBazelAndAdditionalArgs() throws ExecutionException { final BazelFields fields = setupBazelFields( "bazel_target", "--define=bazel_args0 --define bazel_args1=value", "--additional_args1 --additional_args2 value_of_arg2 --no-enable-google3-hot-reload", false ); final FlutterDevice device = FlutterDevice.getTester(); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--bazel-options=--define=bazel_args0 --define bazel_args1=value"); expectedCommandLine.add("--machine"); expectedCommandLine.add("--additional_args1"); expectedCommandLine.add("--additional_args2"); expectedCommandLine.add("value_of_arg2"); expectedCommandLine.add("--no-enable-google3-hot-reload"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineInDebugMode() throws ExecutionException { final BazelFields fields = setupBazelFields(); final FlutterDevice device = FlutterDevice.getTester(); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.DEBUG); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--machine"); expectedCommandLine.add("--start-paused"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineInProfileMode() throws ExecutionException { final BazelFields fields = setupBazelFields(); final FlutterDevice device = FlutterDevice.getTester(); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.PROFILE); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--profile"); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("flutter-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineWithAndroidDevice() throws ExecutionException { final BazelFields fields = setupBazelFields(); final FlutterDevice device = new FlutterDevice("android-tester", "android device", "android", false); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("android-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineWithAndroidEmulator() throws ExecutionException { final BazelFields fields = setupBazelFields(); final FlutterDevice device = new FlutterDevice("android-tester", "android device", "android", true); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("android-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineWithIosDevice() throws ExecutionException { final BazelFields fields = setupBazelFields(); final FlutterDevice device = new FlutterDevice("ios-tester", "ios device", "ios", false); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("ios-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } @Test @Ignore public void producesCorrectCommandLineWithIosSimulator() throws ExecutionException { final BazelFields fields = setupBazelFields(); final FlutterDevice device = new FlutterDevice("ios-tester", "ios device", "ios", true); final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), device, RunMode.RUN); final List<String> expectedCommandLine = new ArrayList<>(); expectedCommandLine.add(platformize("/workspace/scripts/flutter-run.sh")); expectedCommandLine.add("--machine"); expectedCommandLine.add("-d"); expectedCommandLine.add("ios-tester"); expectedCommandLine.add("--devtools-server-address=http://http://localhost:1234"); expectedCommandLine.add("bazel_target"); assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine)); } /** * Default configuration for the bazel test fields. */ private BazelFields setupBazelFields( @Nullable String bazelTarget, @Nullable String bazelArgs, @Nullable String additionalArgs, boolean enableReleaseMode) { return new FakeBazelFields(new BazelFields( bazelTarget, bazelArgs, additionalArgs, enableReleaseMode, mockService )); } private BazelFields setupBazelFields() { return setupBazelFields("bazel_target", null, null, false); } private String platformize(String s) { return SystemInfo.isWindows ? s.replaceAll("/", "\\\\") : s; } /** * Fake bazel fields that doesn't depend on the Dart SDK. */ private static class FakeBazelFields extends BazelFields { MockVirtualFileSystem fs; final Workspace fakeWorkspace; FakeBazelFields(@NotNull BazelFields template, @Nullable String daemonScript, @Nullable String devToolsScript, @Nullable String doctorScript, @Nullable String testScript, @Nullable String runScript, @Nullable String syncScript, @Nullable String toolsScript, @Nullable String sdkHome, @Nullable String versionFile, @Nullable String requiredIJPluginID, @Nullable String requiredIJPluginMessage, @Nullable String configWarningMessage, @Nullable String updatedIosRunMessage) { super(template); final Pair.NonNull<MockVirtualFileSystem, Workspace> pair = FakeWorkspaceFactory .createWorkspaceAndFilesystem(daemonScript, devToolsScript, doctorScript, testScript, runScript, syncScript, toolsScript, sdkHome, versionFile, requiredIJPluginID, requiredIJPluginMessage, configWarningMessage, updatedIosRunMessage); fs = pair.first; fakeWorkspace = pair.second; } FakeBazelFields(@NotNull BazelFields template) { super(template); final Pair.NonNull<MockVirtualFileSystem, Workspace> pair = FakeWorkspaceFactory .createWorkspaceAndFilesystem(); fs = pair.first; fakeWorkspace = pair.second; } @Override void checkRunnable(@NotNull Project project) { } @Nullable @Override protected Workspace getWorkspace(@NotNull Project project) { return fakeWorkspace; } } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazel/LaunchCommandsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazel/LaunchCommandsTest.java", "repo_id": "flutter-intellij", "token_count": 5808 }
470
/* * 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.testing; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; public class IdeaProjectFixture extends ProjectFixture<IdeaProjectTestFixture> { IdeaProjectFixture(Factory<IdeaProjectTestFixture> factory, boolean setupOnDispatchThread) { super(factory, setupOnDispatchThread); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/IdeaProjectFixture.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/IdeaProjectFixture.java", "repo_id": "flutter-intellij", "token_count": 142 }
471
/* * Copyright 2020 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.view; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.util.messages.MessageBusConnection; import io.flutter.ObservatoryConnector; import io.flutter.devtools.DevToolsIdeFeature; import io.flutter.inspector.InspectorGroupManagerService; import io.flutter.inspector.InspectorService; import io.flutter.jxbrowser.FailureType; import io.flutter.jxbrowser.InstallationFailedReason; import io.flutter.jxbrowser.JxBrowserManager; import io.flutter.jxbrowser.JxBrowserStatus; import io.flutter.run.daemon.FlutterApp; import io.flutter.utils.JxBrowserUtils; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mock; import java.util.concurrent.TimeoutException; import static io.flutter.view.FlutterView.*; import static org.mockito.Mockito.*; //@PrepareForTest({ThreadUtil.class, FlutterInitializer.class, JxBrowserUtils.class, // InspectorGroupManagerService.class, SwingUtilities.class}) public class FlutterViewTest { Project mockProject = mock(Project.class); @Mock FlutterApp mockApp; @Mock InspectorService mockInspectorService; @Mock ToolWindow mockToolWindow; @Mock ObservatoryConnector mockObservatoryConnector; JxBrowserUtils mockUtils = mock(JxBrowserUtils.class); JxBrowserManager mockJxBrowserManager = mock(JxBrowserManager.class); InspectorGroupManagerService mockInspectorGroupManagerService = mock(InspectorGroupManagerService.class); MessageBusConnection mockBusConnection = mock(MessageBusConnection.class); @Test public void testHandleJxBrowserInstalled() { // If JxBrowser has been installed, we should use the DevTools instance to open the embedded browser. final FlutterView partialMockFlutterView = mock(FlutterView.class); doCallRealMethod().when(partialMockFlutterView).handleJxBrowserInstalled(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); partialMockFlutterView.handleJxBrowserInstalled(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); verify(partialMockFlutterView, times(1)).openInspectorWithDevTools(mockApp, mockInspectorService, mockToolWindow, true, DevToolsIdeFeature.TOOL_WINDOW); verify(partialMockFlutterView, times(1)).setUpToolWindowListener(mockApp, mockInspectorService, mockToolWindow, true, DevToolsIdeFeature.TOOL_WINDOW); } @Test public void testHandleJxBrowserInstallationFailed() { final JxBrowserUtils mockJxBrowserUtils = mock(JxBrowserUtils.class); when(mockJxBrowserUtils.licenseIsSet()).thenReturn(true); when(mockJxBrowserManager.getLatestFailureReason()).thenReturn(new InstallationFailedReason(FailureType.FILE_DOWNLOAD_FAILED)); // If JxBrowser failed to install, we should show a failure message that allows the user to manually retry. final FlutterView flutterView = new FlutterView(mockProject, mockJxBrowserManager, mockJxBrowserUtils, mockInspectorGroupManagerService, mockBusConnection); final FlutterView spy = spy(flutterView); doNothing().when(spy).presentClickableLabel( eq(mockToolWindow), anyList() ); spy.handleJxBrowserInstallationFailed(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); verify(spy, times(1)).presentClickableLabel( eq(mockToolWindow), anyList() ); } @Test public void testHandleJxBrowserInstallationInProgressWithSuccessfulInstall() { when(mockJxBrowserManager.getStatus()).thenReturn(JxBrowserStatus.INSTALLED); // If the JxBrowser installation is initially in progress, we should show a message about the installation. // If the installation quickly finishes (on the first re-check), then we should call the function to handle successful installation. final FlutterView flutterView = new FlutterView(mockProject, mockJxBrowserManager, mockUtils, mockInspectorGroupManagerService, mockBusConnection); final FlutterView spy = spy(flutterView); doNothing().when(spy).presentOpenDevToolsOptionWithMessage(any(), any(), any(), any(), any()); doNothing().when(spy).handleJxBrowserInstalled(any(), any(), any(), any()); spy.handleJxBrowserInstallationInProgress(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); verify(spy, times(1)) .presentOpenDevToolsOptionWithMessage(mockApp, mockInspectorService, mockToolWindow, INSTALLATION_IN_PROGRESS_LABEL, DevToolsIdeFeature.TOOL_WINDOW); verify(spy, times(1)).handleJxBrowserInstalled(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); } @Test public void testHandleJxBrowserInstallationInProgressWaiting() { when(mockJxBrowserManager.getStatus()).thenReturn(JxBrowserStatus.INSTALLATION_IN_PROGRESS); // If the JxBrowser installation is in progress and is not finished on the first re-check, we should start a thread to wait for the // installation to finish. final FlutterView flutterView = new FlutterView(mockProject, mockJxBrowserManager, mockUtils, mockInspectorGroupManagerService, mockBusConnection); final FlutterView spy = spy(flutterView); doNothing().when(spy).presentOpenDevToolsOptionWithMessage(any(), any(), any(), any(), any()); doNothing().when(spy).startJxBrowserInstallationWaitingThread(any(), any(), any(), any()); spy.handleJxBrowserInstallationInProgress(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); verify(spy, times(1)) .presentOpenDevToolsOptionWithMessage(mockApp, mockInspectorService, mockToolWindow, INSTALLATION_IN_PROGRESS_LABEL, DevToolsIdeFeature.TOOL_WINDOW); verify(spy, times(1)).startJxBrowserInstallationWaitingThread(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); } @Test public void testWaitForJxBrowserInstallationWithoutTimeout() throws TimeoutException { when(mockJxBrowserManager.getStatus()).thenReturn(JxBrowserStatus.INSTALLATION_IN_PROGRESS); when(mockJxBrowserManager.waitForInstallation(INSTALLATION_WAIT_LIMIT_SECONDS)).thenReturn(JxBrowserStatus.INSTALLATION_FAILED); // If waiting for JxBrowser installation completes without timing out, then we should return to event thread. final FlutterView flutterView = new FlutterView(mockProject, mockJxBrowserManager, mockUtils, mockInspectorGroupManagerService, mockBusConnection); final FlutterView spy = spy(flutterView); doNothing().when(spy).handleUpdatedJxBrowserStatusOnEventThread(any(), any(), any(), any(), any()); spy.waitForJxBrowserInstallation(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); verify(spy, times(1)) .handleUpdatedJxBrowserStatusOnEventThread(mockApp, mockInspectorService, mockToolWindow, JxBrowserStatus.INSTALLATION_FAILED, DevToolsIdeFeature.TOOL_WINDOW); } @Ignore @Test public void testWaitForJxBrowserInstallationWithTimeout() throws TimeoutException { when(mockJxBrowserManager.getStatus()).thenReturn(JxBrowserStatus.INSTALLATION_IN_PROGRESS); when(mockJxBrowserManager.waitForInstallation(INSTALLATION_WAIT_LIMIT_SECONDS)).thenThrow(new TimeoutException()); // If the JxBrowser installation doesn't complete on time, we should show a timed out message. final FlutterView flutterView = new FlutterView(mockProject, mockJxBrowserManager, mockUtils, mockInspectorGroupManagerService, mockBusConnection); final FlutterView spy = spy(flutterView); doNothing().when(spy).presentOpenDevToolsOptionWithMessage(any(), any(), any(), any(), any()); spy.waitForJxBrowserInstallation(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); verify(spy, times(1)) .presentOpenDevToolsOptionWithMessage(mockApp, mockInspectorService, mockToolWindow, INSTALLATION_TIMED_OUT_LABEL, DevToolsIdeFeature.TOOL_WINDOW); } @Test public void testHandleUpdatedJxBrowserStatusWithFailure() { // If waiting for JxBrowser installation completes with failure, then we should redirect to the function that handles failure. final FlutterView partialMockFlutterView = mock(FlutterView.class); doCallRealMethod().when(partialMockFlutterView) .handleUpdatedJxBrowserStatus(mockApp, mockInspectorService, mockToolWindow, JxBrowserStatus.INSTALLATION_FAILED, DevToolsIdeFeature.TOOL_WINDOW); partialMockFlutterView.handleUpdatedJxBrowserStatus(mockApp, mockInspectorService, mockToolWindow, JxBrowserStatus.INSTALLATION_FAILED, DevToolsIdeFeature.TOOL_WINDOW); verify(partialMockFlutterView, times(1)).handleJxBrowserInstallationFailed(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); } @Test public void testHandleUpdatedJxBrowserStatusWithSuccess() { // If waiting for JxBrowser installation completes with failure, then we should redirect to the function that handles failure. final FlutterView partialMockFlutterView = mock(FlutterView.class); doCallRealMethod().when(partialMockFlutterView) .handleUpdatedJxBrowserStatus(mockApp, mockInspectorService, mockToolWindow, JxBrowserStatus.INSTALLED, DevToolsIdeFeature.TOOL_WINDOW); partialMockFlutterView.handleUpdatedJxBrowserStatus(mockApp, mockInspectorService, mockToolWindow, JxBrowserStatus.INSTALLED, DevToolsIdeFeature.TOOL_WINDOW); verify(partialMockFlutterView, times(1)).handleJxBrowserInstalled(mockApp, mockInspectorService, mockToolWindow, DevToolsIdeFeature.TOOL_WINDOW); } @Test public void testHandleUpdatedJxBrowserStatusWithOtherstatus() { // If waiting for JxBrowser installation completes with any other status, then we should recommend opening non-embedded DevTools. final FlutterView partialMockFlutterView = mock(FlutterView.class); doCallRealMethod().when(partialMockFlutterView) .handleUpdatedJxBrowserStatus(mockApp, mockInspectorService, mockToolWindow, JxBrowserStatus.NOT_INSTALLED, DevToolsIdeFeature.TOOL_WINDOW); partialMockFlutterView.handleUpdatedJxBrowserStatus(mockApp, mockInspectorService, mockToolWindow, JxBrowserStatus.NOT_INSTALLED, DevToolsIdeFeature.TOOL_WINDOW); verify(partialMockFlutterView, times(1)) .presentOpenDevToolsOptionWithMessage(mockApp, mockInspectorService, mockToolWindow, INSTALLATION_WAIT_FAILED, DevToolsIdeFeature.TOOL_WINDOW); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/view/FlutterViewTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/view/FlutterViewTest.java", "repo_id": "flutter-intellij", "token_count": 3277 }
472
/* * 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. /** * An {@link ExceptionPauseMode} indicates how the isolate pauses when an exception is thrown. */ @SuppressWarnings({"WeakerAccess", "unused"}) public enum ExceptionPauseMode { All, None, Unhandled, /** * Represents a value returned by the VM but unknown to this client. */ Unknown }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ExceptionPauseMode.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ExceptionPauseMode.java", "repo_id": "flutter-intellij", "token_count": 292 }
473
/* * 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.JsonElement; import com.google.gson.JsonObject; import java.util.List; /** * An {@link Isolate} object provides information about one isolate in the VM. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Isolate extends Response { public Isolate(JsonObject json) { super(json); } /** * A list of all breakpoints for this isolate. */ public ElementList<Breakpoint> getBreakpoints() { return new ElementList<Breakpoint>(json.get("breakpoints").getAsJsonArray()) { @Override protected Breakpoint basicGet(JsonArray array, int index) { return new Breakpoint(array.get(index).getAsJsonObject()); } }; } /** * The error that is causing this isolate to exit, if applicable. * * Can return <code>null</code>. */ public ErrorObj getError() { JsonObject obj = (JsonObject) json.get("error"); 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 ErrorObj(obj); } /** * The current pause on exception mode for this isolate. */ public ExceptionPauseMode getExceptionPauseMode() { final JsonElement value = json.get("exceptionPauseMode"); try { return value == null ? ExceptionPauseMode.Unknown : ExceptionPauseMode.valueOf(value.getAsString()); } catch (IllegalArgumentException e) { return ExceptionPauseMode.Unknown; } } /** * The list of service extension RPCs that are registered for this isolate, if any. * * Can return <code>null</code>. */ public List<String> getExtensionRPCs() { return json.get("extensionRPCs") == null ? null : getListString("extensionRPCs"); } /** * The id which is passed to the getIsolate RPC to reload this isolate. */ public String getId() { return getAsString("id"); } /** * Specifies whether the isolate was spawned by the VM or embedder for internal use. If `false`, * this isolate is likely running user code. */ public boolean getIsSystemIsolate() { return getAsBoolean("isSystemIsolate"); } /** * The list of isolate flags provided to this isolate. See Dart_IsolateFlags in dart_api.h for * the list of accepted isolate flags. */ public ElementList<IsolateFlag> getIsolateFlags() { return new ElementList<IsolateFlag>(json.get("isolateFlags").getAsJsonArray()) { @Override protected IsolateFlag basicGet(JsonArray array, int index) { return new IsolateFlag(array.get(index).getAsJsonObject()); } }; } /** * The id of the isolate group that this isolate belongs to. */ public String getIsolateGroupId() { return getAsString("isolateGroupId"); } /** * A list of all libraries for this isolate. * * Guaranteed to be initialized when the IsolateRunnable event fires. */ public ElementList<LibraryRef> getLibraries() { return new ElementList<LibraryRef>(json.get("libraries").getAsJsonArray()) { @Override protected LibraryRef basicGet(JsonArray array, int index) { return new LibraryRef(array.get(index).getAsJsonObject()); } }; } /** * The number of live ports for this isolate. */ public int getLivePorts() { return getAsInt("livePorts"); } /** * A name identifying this isolate. Not guaranteed to be unique. */ public String getName() { return getAsString("name"); } /** * A numeric id for this isolate, represented as a string. Unique. */ public String getNumber() { return getAsString("number"); } /** * The last pause event delivered to the isolate. If the isolate is running, this will be a * resume event. */ public Event getPauseEvent() { return new Event((JsonObject) json.get("pauseEvent")); } /** * Will this isolate pause when exiting? */ public boolean getPauseOnExit() { return getAsBoolean("pauseOnExit"); } /** * The root library for this isolate. * * Guaranteed to be initialized when the IsolateRunnable event fires. * * Can return <code>null</code>. */ public LibraryRef getRootLib() { JsonObject obj = (JsonObject) json.get("rootLib"); 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 LibraryRef(obj); } /** * Is the isolate in a runnable state? */ public boolean getRunnable() { return getAsBoolean("runnable"); } /** * The time that the VM started in milliseconds since the epoch. * * Suitable to pass to DateTime.fromMillisecondsSinceEpoch. */ public int getStartTime() { return getAsInt("startTime"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Isolate.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Isolate.java", "repo_id": "flutter-intellij", "token_count": 1905 }
474
/* * 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; /** * {@link ObjRef} is a reference to a {@link Obj}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class ObjRef extends Response { public ObjRef(JsonObject json) { super(json); } /** * Provided and set to true if the id of an Object is fixed. If true, the id of an Object is * guaranteed not to change or expire. The object may, however, still be _Collected_. * * Can return <code>null</code>. */ public boolean getFixedId() { return getAsBoolean("fixedId"); } /** * A unique identifier for an Object. Passed to the getObject RPC to load this Object. */ public String getId() { return getAsString("id"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ObjRef.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ObjRef.java", "repo_id": "flutter-intellij", "token_count": 436 }
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.android; import static com.google.wireless.android.sdk.stats.GradleSyncStats.Trigger.TRIGGER_PROJECT_MODIFIED; import com.android.tools.idea.gradle.project.sync.GradleSyncInvoker; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public class AndroidStudioGradleSyncProvider implements GradleSyncProvider { @Override public void scheduleSync(@NotNull Project project) { GradleSyncInvoker.getInstance().requestProjectSync( project, new GradleSyncInvoker.Request(TRIGGER_PROJECT_MODIFIED), null); } }
flutter-intellij/flutter-studio/src/io/flutter/android/AndroidStudioGradleSyncProvider.java/0
{ "file_path": "flutter-intellij/flutter-studio/src/io/flutter/android/AndroidStudioGradleSyncProvider.java", "repo_id": "flutter-intellij", "token_count": 234 }
476
/* * 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 com.android.tools.idea.tests.gui.framework.fixture; import com.android.tools.idea.tests.gui.framework.GuiTests; import com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard.NewFlutterProjectWizardFixture; import com.android.tools.idea.tests.gui.framework.fixture.sdk.SdkProblemDialogFixture; import com.android.tools.idea.tests.gui.framework.matcher.Matchers; import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame; import org.fest.swing.core.Robot; import org.jetbrains.annotations.NotNull; // Adapted from com.android.tools.idea.tests.gui.framework.fixture.WelcomeFrameFixture @SuppressWarnings("SameParameterValue") public class FlutterWelcomeFrameFixture extends ComponentFixture<FlutterWelcomeFrameFixture, FlatWelcomeFrame> { private static final String NEW_PROJECT_WELCOME_ID = "flutter.NewProject.welcome"; // See META-INF/studio-contribs.xml private FlutterWelcomeFrameFixture(@NotNull Robot robot, @NotNull FlatWelcomeFrame target) { super(FlutterWelcomeFrameFixture.class, robot, target); } @SuppressWarnings("WeakerAccess") @NotNull public static FlutterWelcomeFrameFixture find(@NotNull Robot robot) { return new FlutterWelcomeFrameFixture(robot, GuiTests.waitUntilShowing(robot, Matchers.byType(FlatWelcomeFrame.class))); } @NotNull public static FlutterWelcomeFrameFixture find(@NotNull IdeaFrameFixture ideFrameFixture) { return find(ideFrameFixture.robot()); } public SdkProblemDialogFixture createNewProjectWhenSdkIsInvalid() { findActionLinkByActionId(NEW_PROJECT_WELCOME_ID).click(); return SdkProblemDialogFixture.find(this); } @NotNull public NewFlutterProjectWizardFixture createNewProject() { findActionLinkByActionId(NEW_PROJECT_WELCOME_ID).click(); return NewFlutterProjectWizardFixture.find(robot()); } @NotNull private ActionLinkFixture findActionLinkByActionId(String actionId) { return ActionLinkFixture.findByActionId(actionId, robot(), target()); } }
flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/FlutterWelcomeFrameFixture.java/0
{ "file_path": "flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/FlutterWelcomeFrameFixture.java", "repo_id": "flutter-intellij", "token_count": 696 }
477
# Location of the bash script. build_file: "flutter-intellij-kokoro/kokoro/macos_external/kokoro_build.sh" before_action { fetch_keystore { keystore_resource { keystore_config_id: 74840 keyname: "flutter-intellij-plugin-jxbrowser-license-key" } } }
flutter-intellij/kokoro/macos_external/continuous.cfg/0
{ "file_path": "flutter-intellij/kokoro/macos_external/continuous.cfg", "repo_id": "flutter-intellij", "token_count": 114 }
478
<?xml version='1.0'?> <!-- ~ 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. --> <list> <!--<option name="TEMPLATE_CONFIG_NAME">--> <!--<value>--> <!--<option name="FOREGROUND" value="008000"/>--> <!--<option name="BACKGROUND" value="e3fcff"/>--> <!--<option name="FONT_TYPE" value="1"/>--> <!--</value>--> <!--</option>--> <option name="FLUTTER_LOG_NONE_OUTPUT"> <value> <option name="FOREGROUND" value="#000000"/> </value> </option> <option name="FLUTTER_LOG_FINEST_OUTPUT"> <value> <option name="FOREGROUND" value="#000000"/> </value> </option> <option name="FLUTTER_LOG_FINER_OUTPUT"> <value> <option name="FOREGROUND" value="#000000"/> </value> </option> <option name="FLUTTER_LOG_FINE_OUTPUT"> <value> <option name="FOREGROUND" value="#000000"/> </value> </option> <option name="FLUTTER_LOG_CONFIG_OUTPUT"> <value> <option name="FOREGROUND" value="#000000"/> </value> </option> <option name="FLUTTER_LOG_INFO_OUTPUT"> <value> <option name="FOREGROUND" value="#000000"/> </value> </option> <option name="FLUTTER_LOG_WARNING_OUTPUT"> <value> <option name="FOREGROUND" value="#00007F"/> </value> </option> <option name="FLUTTER_LOG_SEVERE_OUTPUT"> <value> <option name="FOREGROUND" value="#7F0000"/> </value> </option> <option name="FLUTTER_LOG_SHOUT_OUTPUT"> <value> <option name="FOREGROUND" value="#7F0000"/> </value> </option> </list>
flutter-intellij/resources/colorSchemes/FlutterLogColorSchemeDefault.xml/0
{ "file_path": "flutter-intellij/resources/colorSchemes/FlutterLogColorSchemeDefault.xml", "repo_id": "flutter-intellij", "token_count": 657 }
479
## How this works `flutter_miscellaneous.xml` contains the Flutter related live templates that this plugin supports. In order to make authoring the templates, and reviewing changes to them, easier, the actual text content of the templates are split out into separate files, one for each template. A build step (below) will copy the contents of the inidividual files in-line into the IntelliJ live template file. ## Adding a new template To add a new template, create a new entry in the flutter_miscellaneous.xml file. This should be a valid live template entry. You can provide any content you want for the `value` field. Next, create a `$name.txt` file. This will hold the actual content of the `value` field. The re-generate step will copy the contents from that txt file into the xml `value` field. ## Re-generating the template file To re-generate the flutter_miscellaneous.xml template file, run: ``` ./bin/plugin generate ```
flutter-intellij/resources/liveTemplates/readme.md/0
{ "file_path": "flutter-intellij/resources/liveTemplates/readme.md", "repo_id": "flutter-intellij", "token_count": 245 }
480
#!/bin/bash # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Fast fail the script on failures. set -e export JAVA_HOME=$JAVA_HOME_17_X64 # Clone and configure Flutter to the latest stable release git clone --depth 1 -b stable --single-branch https://github.com/flutter/flutter.git ../flutter export PATH="$PATH":`pwd`/../flutter/bin:`pwd`/../flutter/bin/cache/dart-sdk/bin flutter config --no-analytics flutter doctor export FLUTTER_SDK=`pwd`/../flutter if [ "$IDEA_VERSION" = "4.0" -o "$IDEA_VERSION" = "4.1" ] ; then # Install Java 8 if running on 4.0 or 4.1. wget -O- https://apt.corretto.aws/corretto.key | sudo apt-key add - sudo add-apt-repository 'deb https://apt.corretto.aws stable main' sudo apt-get update; sudo apt-get install -y java-1.8.0-amazon-corretto-jdk export PATH=/usr/lib/jvm/java-1.8.0-amazon-corretto/jre/bin:$PATH fi java -version # Get packages for the top-level grind script utilities. echo "pub get `pwd`" dart pub get # Get packages for the test data. (cd flutter-idea/testData/sample_tests; echo "dart pub get `pwd`"; dart pub get) # Set up the plugin tool. (cd tool/plugin; echo "dart pub get `pwd`"; dart pub get) if [ "DART_BOT" = "$BOT" ] ; then # Analyze the Dart code in the repo. echo "dart analyze" (cd flutter-idea/src; dart analyze) (cd tool/plugin; dart analyze) # Ensure that the edits have been applied to template files (and their target # files have been regenerated). ./bin/plugin generate # Show any changed files. git status --porcelain # Return a failure exit code if there are any diffs. git diff --exit-code # Run the tests for the plugin tool. (cd tool/plugin; dart test/plugin_test.dart) elif [ "CHECK_BOT" = "$BOT" ] ; then # Run some validations on the repo code. ./bin/plugin lint # Check plugin-referenced urls for liveness. dart tool/grind.dart check-urls elif [ "UNIT_TEST_BOT" = "$BOT" ] ; then # Run unit tests. ./bin/plugin test --no-setup else # Run the build. ./bin/plugin make --channel=stable --only-version=$IDEA_VERSION --no-setup fi
flutter-intellij/tool/github.sh/0
{ "file_path": "flutter-intellij/tool/github.sh", "repo_id": "flutter-intellij", "token_count": 781 }
481
// 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. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:git/git.dart'; import 'package:path/path.dart' as p; import 'build_spec.dart'; import 'edit.dart'; import 'globals.dart'; import 'lint.dart'; import 'runner.dart'; import 'util.dart'; Future<int> main(List<String> args) async { var runner = BuildCommandRunner(); runner.addCommand(LintCommand(runner)); runner.addCommand(AntBuildCommand(runner)); runner.addCommand(GradleBuildCommand(runner)); runner.addCommand(TestCommand(runner)); runner.addCommand(DeployCommand(runner)); runner.addCommand(GenerateCommand(runner)); try { return await runner.run(args) ?? 0; } on UsageException catch (e) { print('$e'); return 1; } } void addProductFlags(ArgParser argParser, String verb) { argParser.addFlag('ij', help: '$verb the IntelliJ plugin', defaultsTo: true); argParser.addFlag('as', help: '$verb the Android Studio plugin', defaultsTo: true); } void copyResources({required String from, required String to}) { log('copying resources from $from to $to'); _copyResources(Directory(from), Directory(to)); } List<BuildSpec> createBuildSpecs(ProductCommand command) { var specs = <BuildSpec>[]; var input = readProductMatrix(); for (var json in input) { specs.add(BuildSpec.fromJson(json, command.release)); } return specs; } List<File> findJars(String path) { final dir = Directory(path); return dir .listSync(recursive: true, followLinks: false) .where((e) => e is File && e.path.endsWith('.jar')) .toList() .cast<File>(); } List<String> findJavaFiles(String path) { final dir = Directory(path); return dir .listSync(recursive: true, followLinks: false) .where((e) => e.path.endsWith('.java')) .map((f) => f.path) .toList(); } Future<bool> genPluginFiles(BuildSpec spec, String destDir) async { await genPluginXml(spec, destDir, 'META-INF/plugin.xml'); await genPluginXml(spec, destDir, 'META-INF/studio-contribs.xml'); return true; } Future<File> genPluginXml(BuildSpec spec, String destDir, String path) async { var templatePath = '${path.substring(0, path.length - '.xml'.length)}_template.xml'; var file = await File(p.join(rootPath, destDir, path)).create(recursive: true); log('writing ${p.relative(file.path)}'); var dest = file.openWrite(); dest.writeln( "<!-- Do not edit; instead, modify ${p.basename(templatePath)}, and run './bin/plugin generate'. -->"); dest.writeln(); await utf8.decoder .bind(File(p.join(rootPath, 'resources', templatePath)).openRead()) .transform(LineSplitter()) .forEach((l) => dest.writeln(substituteTemplateVariables(l, spec))); await dest.close(); return await dest.done; } bool genPresubmitYaml(List<BuildSpec> specs) { // This assumes the file contains 'steps:', which seems reasonable. var file = File(p.join(rootPath, '.github', 'workflows', 'presubmit.yaml')); var versions = []; for (var spec in specs) { if (spec.channel == 'stable' && !spec.untilBuild.contains('SNAPSHOT')) { versions.add(spec.version); } } var templateFile = File(p.join(rootPath, '.github', 'workflows', 'presubmit.yaml.template')); var templateContents = templateFile.readAsStringSync(); // If we need to make many changes consider something like genPluginXml(). templateContents = templateContents.replaceFirst('@VERSIONS@', versions.join(', ')); var header = "# Do not edit; instead, modify ${p.basename(templateFile.path)}," " and run './bin/plugin generate'.\n\n"; var contents = header + templateContents; log('writing ${p.relative(file.path)}'); var templateIndex = contents.indexOf('steps:'); if (templateIndex < 0) { log('presubmit template cannot be generated'); return false; } var fileContents = file.readAsStringSync(); var fileIndex = fileContents.indexOf('steps:'); var newContent = contents.substring(0, templateIndex) + fileContents.substring(fileIndex); file.writeAsStringSync(newContent, flush: true); return true; } bool isTravisFileValid() { var travisPath = p.join(rootPath, '.github/workflows/presubmit.yaml'); var travisFile = File(travisPath); if (!travisFile.existsSync()) { return false; } var matrixPath = p.join(rootPath, 'product-matrix.json'); var matrixFile = File(matrixPath); if (!matrixFile.existsSync()) { throw 'product-matrix.json is missing'; } return isNewer(travisFile, matrixFile); } Future<int> jar(String directory, String outFile) async { var args = ['cf', p.absolute(outFile)]; args.addAll(Directory(directory) .listSync(followLinks: false) .map((f) => p.basename(f.path))); args.remove('.DS_Store'); return await exec('jar', args, cwd: directory); } Future<bool> performReleaseChecks(ProductCommand cmd) async { // git must have a release_NN branch where NN is the value of --release // git must have no uncommitted changes var isGitDir = await GitDir.isGitDir(rootPath); if (isGitDir) { if (cmd.isTestMode) { return true; } if (cmd.isDevChannel) { log('release mode is incompatible with the dev channel'); return false; } if (!cmd.isReleaseValid) { log('the release identifier ("${cmd.release}") must be of the form xx.x (major.minor)'); return false; } var gitDir = await GitDir.fromExisting(rootPath); var isClean = await gitDir.isWorkingTreeClean(); if (isClean) { var branch = await gitDir.currentBranch(); var name = branch.branchName; var expectedName = cmd.isDevChannel ? 'master' : "release_${cmd.releaseMajor}"; var result = name == expectedName; if (!result) { result = name.startsWith("release_${cmd.releaseMajor}") && name.lastIndexOf(RegExp(r"\.[0-9]")) == name.length - 2; } if (result) { if (isTravisFileValid()) { return result; } else { log('the presubmit.yaml file needs updating: plugin generate'); } } else { log('the current git branch must be named "$expectedName"'); } } else { log('the current git branch has uncommitted changes'); } } else { log('the current working directory is not managed by git: $rootPath'); } return false; } List readProductMatrix() { var contents = File(p.join(rootPath, 'product-matrix.json')).readAsStringSync(); var map = json.decode(contents); return map['list']; } String substituteTemplateVariables(String line, BuildSpec spec) { String valueOf(String name) { switch (name) { case 'PLUGINID': return spec.pluginId; case 'SINCE': return spec.sinceBuild; case 'UNTIL': return spec.untilBuild; case 'VERSION': var releaseNo = buildVersionNumber(spec); return '<version>$releaseNo</version>'; case 'CHANGELOG': return spec.changeLog; case 'DEPEND': // If found, this is the module that triggers loading the Android Studio // support. The public sources and the installable plugin use different ones. return spec.isSynthetic ? 'com.intellij.modules.androidstudio' : 'com.android.tools.apk'; default: throw 'unknown template variable: $name'; } } var start = line.indexOf('@'); while (start >= 0 && start < line.length) { var end = line.indexOf('@', start + 1); if (end > 0) { var name = line.substring(start + 1, end); line = line.replaceRange(start, end + 1, valueOf(name)); if (end < line.length - 1) { start = line.indexOf('@', end + 1); } } else { break; // Some commit message has a '@' in it. } } return line; } void _copyFile(File file, Directory to, {String filename = ''}) { if (!file.existsSync()) { throw "${file.path} does not exist"; } if (!to.existsSync()) { to.createSync(recursive: true); } if (filename == '') filename = p.basename(file.path); final target = File(p.join(to.path, filename)); target.writeAsBytesSync(file.readAsBytesSync()); } void _copyResources(Directory from, Directory to) { for (var entity in from.listSync(followLinks: false)) { final basename = p.basename(entity.path); if (basename.endsWith('.java') || basename.endsWith('.kt') || basename.endsWith('.form') || basename == 'plugin.xml.template') { continue; } if (entity is File) { _copyFile(entity, to); } else if (entity is Directory) { _copyResources(entity, Directory(p.join(to.path, basename))); } } } class AntBuildCommand extends BuildCommand { AntBuildCommand(BuildCommandRunner runner) : super(runner, 'build'); @override Future<int> doit() async { return GradleBuildCommand(runner).doit(); } @override Future<int> externalBuildCommand(BuildSpec spec) async { // Not used return 0; } @override Future<int> savePluginArtifact(BuildSpec spec) async { // Not used return 0; } } class GradleBuildCommand extends BuildCommand { GradleBuildCommand(BuildCommandRunner runner) : super(runner, 'make'); @override Future<int> externalBuildCommand(BuildSpec spec) async { var pluginFile = File('resources/META-INF/plugin.xml'); var studioFile = File('resources/META-INF/studio-contribs.xml'); var pluginSrc = pluginFile.readAsStringSync(); var studioSrc = studioFile.readAsStringSync(); try { await genPluginFiles(spec, 'resources'); return await runner.buildPlugin(spec, buildVersionNumber(spec)); } finally { pluginFile.writeAsStringSync(pluginSrc); studioFile.writeAsStringSync(studioSrc); } } @override Future<int> savePluginArtifact(BuildSpec spec) async { final file = File(releasesFilePath(spec)); final version = buildVersionNumber(spec); var source = File('build/distributions/flutter-intellij-$version.zip'); if (!source.existsSync()) { // Setting the plugin name in Gradle should eliminate the need for this, // but it does not. // TODO(messick) Find a way to make the Kokoro file name: flutter-intellij-DEV.zip source = File('build/distributions/flutter-intellij-kokoro-$version.zip'); } _copyFile( source, file.parent, filename: p.basename(file.path), ); await _stopDaemon(); return 0; } Future<int> _stopDaemon() async { if (Platform.isWindows) { return await exec('.\\third_party\\gradlew.bat', ['--stop']); } else { return await exec('./third_party/gradlew', ['--stop']); } } } /// Build deployable plugin files. If the --release argument is given /// then perform additional checks to verify that the release environment /// is in good order. abstract class BuildCommand extends ProductCommand { @override final BuildCommandRunner runner; BuildCommand(this.runner, String commandName) : super(commandName) { argParser.addOption('only-version', abbr: 'o', help: 'Only build the specified IntelliJ version; useful for sharding ' 'builds on CI systems.'); argParser.addFlag('unpack', abbr: 'u', help: 'Unpack the artifact files during provisioning, ' 'even if the cache appears fresh.\n' 'This flag is ignored if --release is given.', defaultsTo: false); argParser.addOption('minor', abbr: 'm', help: 'Set the minor version number.'); argParser.addFlag('setup', abbr: 's', defaultsTo: true); } @override String get description => 'Build a deployable version of the Flutter plugin, ' 'compiled against the specified artifacts.'; Future<int> externalBuildCommand(BuildSpec spec); Future<int> savePluginArtifact(BuildSpec spec); @override Future<int> doit() async { if (isReleaseMode) { if (argResults!['unpack']) { separator('Release mode (--release) implies --unpack'); } if (!await performReleaseChecks(this)) { return 1; } } // Check to see if we should only be building a specific version. String? onlyVersion = argResults!['only-version']; var buildSpecs = specs; if (onlyVersion != null && onlyVersion.isNotEmpty) { buildSpecs = specs.where((spec) => spec.version == onlyVersion).toList(); if (buildSpecs.isEmpty) { log("No spec found for version '$onlyVersion'"); return 1; } } String? minorNumber = argResults!['minor']; if (minorNumber != null) { pluginCount = int.parse(minorNumber) - 1; } var result = 0; for (var spec in buildSpecs) { if (spec.channel != channel) { continue; } if (!(isForIntelliJ && isForAndroidStudio)) { // This is a little more complicated than I'd like because the default // is to always do both. if (isForAndroidStudio && !spec.isAndroidStudio) continue; if (isForIntelliJ && spec.isAndroidStudio) continue; } pluginCount++; if (spec.isDevChannel && !isDevChannel) { spec.buildForMaster(); } separator('Building flutter-intellij.jar'); await removeAll('build'); log('spec.version: ${spec.version}'); result = await applyEdits(spec, () async { return await externalBuildCommand(spec); }); if (result != 0) { log('applyEdits() returned ${result.toString()}'); return result; } try { result = await savePluginArtifact(spec); if (result != 0) { return result; } } catch (ex) { log("$ex"); return 1; } separator('Built artifact'); log(releasesFilePath(spec)); } if (argResults!['only-version'] == null) { checkAndClearAppliedEditCommands(); } return 0; } } /// Either the --release or --channel options must be provided. /// The permanent token is read from the file specified by Kokoro. class DeployCommand extends ProductCommand { @override final BuildCommandRunner runner; DeployCommand(this.runner) : super('deploy'); @override String get description => 'Upload the Flutter plugin to the JetBrains site.'; @override Future<int> doit() async { if (isReleaseMode) { if (!await performReleaseChecks(this)) { return 1; } } else if (!isDevChannel) { log('Deploy must have a --release or --channel=dev argument'); return 1; } var token = readTokenFromKeystore('FLUTTER_KEYSTORE_NAME'); var value = 0; var originalDir = Directory.current; for (var spec in specs) { if (spec.channel != channel) continue; var filePath = releasesFilePath(spec); log("uploading $filePath"); var file = File(filePath); changeDirectory(file.parent); var pluginNumber = pluginRegistryIds[spec.pluginId]; value = await upload( p.basename(file.path), pluginNumber!, token, spec.channel); if (value != 0) { return value; } } changeDirectory(originalDir); return value; } void changeDirectory(Directory dir) { Directory.current = dir.path; } Future<int> upload(String filePath, String pluginNumber, String token, String channel) async { if (!File(filePath).existsSync()) { throw 'File not found: $filePath'; } // See https://plugins.jetbrains.com/docs/marketplace/plugin-upload.html#PluginUploadAPI-POST // Trying to run curl directly doesn't work; something odd happens to the quotes. var cmd = ''' curl -i --header "Authorization: Bearer $token" -F pluginId=$pluginNumber -F file=@$filePath -F channel=$channel https://plugins.jetbrains.com/plugin/uploadPlugin '''; var args = ['-c', cmd.split('\n').join(' ')]; final processResult = await Process.run('sh', args); if (processResult.exitCode != 0) { log('Upload failed: ${processResult.stderr} for file: $filePath'); } String out = processResult.stdout; var message = out.trim().split('\n').last.trim(); log(message); return processResult.exitCode; } } /// Generate the plugin.xml from the plugin.xml.template file. If the --release /// argument is given, create a git branch and commit the new file to it, /// assuming the release checks pass. /// /// Note: The product-matrix.json file includes a build spec for the EAP version /// at the end. When the EAP version is released that needs to be updated. class GenerateCommand extends ProductCommand { @override final BuildCommandRunner runner; GenerateCommand(this.runner) : super('generate'); @override String get description => 'Generate plugin.xml, .github/workflows/presubmit.yaml, ' 'and resources/liveTemplates/flutter_miscellaneous.xml files for the ' 'Flutter plugin.\nThe plugin.xml.template and product-matrix.json are ' 'used as input.'; @override Future<int> doit() async { var json = readProductMatrix(); var spec = SyntheticBuildSpec.fromJson(json.first, release, specs); await genPluginFiles(spec, 'resources'); if (!genPresubmitYaml(specs)) { return 1; } generateLiveTemplates(); if (isReleaseMode) { if (!await performReleaseChecks(this)) { return 1; } } return 0; } SyntheticBuildSpec makeSyntheticSpec(List specs) => SyntheticBuildSpec.fromJson(specs[0], release, specs[2]); void generateLiveTemplates() { // Find all the live templates. final templateFragments = Directory(p.join('resources', 'liveTemplates')) .listSync() .whereType<File>() .where((file) => p.extension(file.path) == '.txt') .cast<File>() .toList(); final templateFile = File(p.join('resources', 'liveTemplates', 'flutter_miscellaneous.xml')); var contents = templateFile.readAsStringSync(); log('writing ${p.relative(templateFile.path)}'); for (var file in templateFragments) { final name = p.basenameWithoutExtension(file.path); var replaceContents = file.readAsStringSync(); replaceContents = replaceContents .replaceAll('\n', '&#10;') .replaceAll('<', '&lt;') .replaceAll('>', '&gt;'); // look for '<template name="$name" value="..."' final regexp = RegExp('<template name="$name" value="([^"]+)"'); final match = regexp.firstMatch(contents); if (match == null) { throw 'No entry found for "$name" live template in ${templateFile.path}'; } // Replace the existing content in the xml live template file with the // content from the template $name.txt file. final matchString = match.group(1); final matchStart = contents.indexOf(matchString!); contents = contents.substring(0, matchStart) + replaceContents + contents.substring(matchStart + matchString.length); } templateFile.writeAsStringSync(contents); } } abstract class ProductCommand extends Command { @override final String name; late List<BuildSpec> specs; ProductCommand(this.name) { addProductFlags(argParser, name[0].toUpperCase() + name.substring(1)); argParser.addOption('channel', abbr: 'c', help: 'Select the channel to build: stable or dev', defaultsTo: 'stable'); } String get channel => argResults!['channel']; bool get isDevChannel => channel == 'dev'; /// Returns true when running in the context of a unit test. bool get isTesting => false; bool get isForAndroidStudio => argResults!['as']; bool get isForIntelliJ => argResults!['ij']; DateTime get releaseDate => lastReleaseDate; bool get isReleaseMode => release != null; bool get isReleaseValid { var rel = release; if (rel == null) { return false; } // Validate for '00.0' with optional '-dev.0' return rel == RegExp(r'^\d+\.\d(?:-dev.\d)?$').stringMatch(rel); } bool get isTestMode => globalResults!['cwd'] != null; String? get release { String? rel = globalResults!['release']; if (rel != null) { if (rel.startsWith('=')) { rel = rel.substring(1); } if (!rel.contains('.')) { rel = '$rel.0'; } } return rel; } String? get releaseMajor { var rel = release; if (rel != null) { var idx = rel.indexOf('.'); if (idx > 0) { rel = rel.substring(0, idx); } } return rel; } String releasesFilePath(BuildSpec spec) { var subDir = isReleaseMode ? 'release_$releaseMajor' : (spec.channel == "stable" ? 'release_master' : 'release_dev'); var filePath = p.join( rootPath, 'releases', subDir, spec.version, 'flutter-intellij.zip'); return filePath; } String testTargetPath(BuildSpec spec) { var subDir = 'release_master'; var filePath = p.join(rootPath, 'releases', subDir, 'test_target'); return filePath; } String ijVersionPath(BuildSpec spec) { var subDir = 'release_master'; var filePath = p.join(rootPath, 'releases', subDir, spec.ijVersion); return filePath; } Future<int> doit(); @override Future<int> run() async { await _initGlobals(); await _initSpecs(); _handleSymlinksOnWindows(); try { return await doit(); } catch (ex, stack) { log(ex.toString()); log(stack.toString()); return 1; } } Future<void> _initGlobals() async { // Initialization constraint: rootPath depends on arg parsing, and // lastReleaseName and lastReleaseDate depend on rootPath. rootPath = Directory.current.path; var rel = globalResults!['cwd']; if (rel != null) { rootPath = p.normalize(p.join(rootPath, rel)); } if (isDevChannel) { lastReleaseName = await lastRelease(); lastReleaseDate = await dateOfLastRelease(); } } Future<int> _initSpecs() async { specs = createBuildSpecs(this); for (var i = 0; i < specs.length; i++) { if (isDevChannel) { specs[i].buildForDev(); } await specs[i].initChangeLog(); } return specs.length; } void _handleSymlinksOnWindows() { if (!Platform.isWindows) { return; } const List<String> symlinks = [ r'flutter-idea\resources', r'flutter-studio\resources', ]; final currentPath = Directory.current.path; for (final entityPath in symlinks) { final path = '$currentPath\\$entityPath'; if (FileSystemEntity.isLinkSync(path)) { continue; } final content = File(path).readAsStringSync(); File(path).deleteSync(); Link(path).createSync(content); } } } /// A crude rename utility. The IntelliJ feature does not work on the case /// needed. This just substitutes package names and assumes all are FQN-form. /// It does not update forms; they use paths instead of packages. /// It would be easy to do forms but it isn't worth the trouble. Only one /// had to be edited. class RenamePackageCommand extends ProductCommand { @override final BuildCommandRunner runner; String baseDir = Directory.current.path; // Run from flutter-intellij dir. late String oldName; late String newName; RenamePackageCommand(this.runner) : super('rename') { argParser.addOption('package', defaultsTo: 'com.android.tools.idea.npw', help: 'Package to be renamed'); argParser.addOption('append', defaultsTo: 'Old', help: 'Suffix to be appended to package name'); argParser.addOption('new-name', help: 'Name of package after renaming'); argParser.addFlag('studio', negatable: true, help: 'The package is in the flutter-studio module'); } @override String get description => 'Rename a package in the plugin sources'; @override Future<int> doit() async { if (argResults!['studio']) baseDir = p.join(baseDir, 'flutter-studio/src'); oldName = argResults!['package']; newName = argResults!.wasParsed('new-name') ? argResults!['new-name'] : oldName + argResults!['append']; if (oldName == newName) { log('Nothing to do; new name is same as old name'); return 1; } // TODO(messick) If the package is not in flutter-studio then we need to edit it too moveFiles(); editReferences(); await deleteDir(); return 0; } void moveFiles() { final srcDir = Directory(p.join(baseDir, oldName.replaceAll('.', '/'))); final destDir = Directory(p.join(baseDir, newName.replaceAll('.', '/'))); _editAndMoveAll(srcDir, destDir); } void editReferences() { final srcDir = Directory(p.join(baseDir, oldName.replaceAll('.', '/'))); final destDir = Directory(p.join(baseDir, newName.replaceAll('.', '/'))); _editAll(Directory(baseDir), skipOld: srcDir, skipNew: destDir); } Future<int> deleteDir() async { final dir = Directory(p.join(baseDir, oldName.replaceAll('.', '/'))); await dir.delete(recursive: true); return 0; } void _editAndMoveFile(File file, Directory to) { if (!to.existsSync()) { to.createSync(recursive: true); } final filename = p.basename(file.path); if (filename.startsWith('.')) return; final target = File(p.join(to.path, filename)); var source = file.readAsStringSync(); source = source.replaceAll(oldName, newName); target.writeAsStringSync(source); if (to.path != file.parent.path) file.deleteSync(); } void _editAndMoveAll(Directory from, Directory to) { for (var entity in from.listSync(followLinks: false)) { final basename = p.basename(entity.path); if (entity is File) { _editAndMoveFile(entity, to); } else if (entity is Directory) { _editAndMoveAll(entity, Directory(p.join(to.path, basename))); } } } void _editAll(Directory src, {required Directory skipOld, required Directory skipNew}) { if (src.path == skipOld.path || src.path == skipNew.path) return; for (var entity in src.listSync(followLinks: false)) { if (entity is File) { _editAndMoveFile(entity, src); } else if (entity is Directory) { _editAll(entity, skipOld: skipOld, skipNew: skipNew); } } } } /// Build the tests if necessary then run them and return any failure code. class TestCommand extends ProductCommand { @override final BuildCommandRunner runner; TestCommand(this.runner) : super('test') { argParser.addFlag('unit', negatable: false, help: 'Run unit tests'); argParser.addFlag('integration', negatable: false, help: 'Run integration tests'); argParser.addFlag('skip', negatable: false, help: 'Do not run tests, just unpack artifaccts', abbr: 's'); argParser.addFlag('setup', abbr: 'p', defaultsTo: true); } @override String get description => 'Run the tests for the Flutter plugin.'; @override Future<int> doit() async { final javaHome = Platform.environment['JAVA_HOME']; if (javaHome == null) { log('JAVA_HOME environment variable not set - this is needed by gradle.'); return 1; } log('JAVA_HOME=$javaHome'); final spec = specs.firstWhere((s) => s.isUnitTestTarget); if (!argResults!['skip']) { if (argResults!['integration']) { return await _runIntegrationTests(); } else { return await _runUnitTests(spec); } } return 0; } Future<int> _runUnitTests(BuildSpec spec) async { // run './gradlew test' return await applyEdits(spec, () async { return await runner.runGradleCommand(['test'], spec, '1', 'true'); }); } Future<int> _runIntegrationTests() async { throw 'integration test execution not yet implemented'; } }
flutter-intellij/tool/plugin/lib/plugin.dart/0
{ "file_path": "flutter-intellij/tool/plugin/lib/plugin.dart", "repo_id": "flutter-intellij", "token_count": 10434 }
482
uINhDrQ3fkTE08_henrSmgKkDo6bisZh4acJCffrRiMC
flutter/bin/internal/fuchsia-linux.version/0
{ "file_path": "flutter/bin/internal/fuchsia-linux.version", "repo_id": "flutter", "token_count": 31 }
483
# This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: "b9c3f1f74c075a1766fd74418b5d79f528cf8c74" channel: "master" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 base_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 - platform: android create_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 base_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 - platform: ios create_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 base_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 - platform: linux create_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 base_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 - platform: macos create_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 base_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 - platform: web create_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 base_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 - platform: windows create_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 base_revision: b9c3f1f74c075a1766fd74418b5d79f528cf8c74 # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj'
flutter/dev/a11y_assessments/.metadata/0
{ "file_path": "flutter/dev/a11y_assessments/.metadata", "repo_id": "flutter", "token_count": 798 }
484
// 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/badge.dart'; import 'package:flutter_test/flutter_test.dart'; import 'test_utils.dart'; void main() { testWidgets('badge can run', (WidgetTester tester) async { await pumpsUseCase(tester, BadgeUseCase()); expect(find.semantics.byLabel('5 new messages'), findsOne); expect(find.semantics.byLabel('Messages'), findsOne); }); }
flutter/dev/a11y_assessments/test/badge_test.dart/0
{ "file_path": "flutter/dev/a11y_assessments/test/badge_test.dart", "repo_id": "flutter", "token_count": 183 }
485
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
flutter/dev/benchmarks/complex_layout/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "flutter/dev/benchmarks/complex_layout/macos/Runner/Configs/Release.xcconfig", "repo_id": "flutter", "token_count": 32 }
486
// 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'; class AnimationWithMicrotasks extends StatefulWidget { const AnimationWithMicrotasks({super.key}); @override State<AnimationWithMicrotasks> createState() => _AnimationWithMicrotasksState(); } class _AnimationWithMicrotasksState extends State<AnimationWithMicrotasks> { final _ChunkedWork work = _ChunkedWork(); @override void initState() { super.initState(); work.start(); } @override void dispose() { work.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return const Scaffold( backgroundColor: Colors.grey, body: Center( child: SizedBox( width: 200, height: 100, child: LinearProgressIndicator(), ), ), ); } } class _ChunkedWork { bool _canceled = false; Future<void> start() async { // Run 100 pieces of synchronous work. // Chunked up to allow frames to be drawn. for (int i = 0; i < 100; ++i) { _chunkedSynchronousWork(); } } void cancel() { _canceled = true; } Future<void> _chunkedSynchronousWork() async { while (!_canceled) { // Yield to the event loop to let engine draw frames. await Future<void>.delayed(Duration.zero); // Perform synchronous computation for 1 ms. _syncComputationFor(const Duration(milliseconds: 1)); } } void _syncComputationFor(Duration duration) { final Stopwatch sw = Stopwatch()..start(); while (!_canceled && sw.elapsed < duration) {} } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/animation_with_microtasks.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/animation_with_microtasks.dart", "repo_id": "flutter", "token_count": 626 }
487
// 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:typed_data'; import 'package:flutter/material.dart'; class LargeImagesPage extends StatelessWidget { const LargeImagesPage({super.key}); @override Widget build(BuildContext context) { final ImageCache imageCache = PaintingBinding.instance.imageCache; imageCache.maximumSize = 30; imageCache.maximumSizeBytes = 50 << 20; return GridView.builder( itemCount: 1000, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemBuilder: (BuildContext context, int index) => DummyImage(index), ).build(context); } } class DummyImage extends StatelessWidget { DummyImage(this.index) : super(key: ValueKey<int>(index)); @override Widget build(BuildContext context) { final Future<ByteData> pngData = _getPngData(context); return FutureBuilder<ByteData>( future: pngData, builder: (BuildContext context, AsyncSnapshot<ByteData> snapshot) { // Use Image.memory instead of Image.asset to make sure that we're // creating many copies of the image to trigger the memory issue. return snapshot.data == null ? Container() : Image.memory(snapshot.data!.buffer.asUint8List()); }, ); } final int index; Future<ByteData> _getPngData(BuildContext context) async { return DefaultAssetBundle.of(context).load('assets/999x1000.png'); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/large_images.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/large_images.dart", "repo_id": "flutter", "token_count": 532 }
488
// 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 'dart:typed_data'; import 'package:flutter/widgets.dart'; import 'recorder.dart'; const List<int> kTransparentImage = <int>[ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4B, 0x47, 0x44, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xA0, 0xBD, 0xA7, 0x93, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0B, 0x13, 0x00, 0x00, 0x0B, 0x13, 0x01, 0x00, 0x9A, 0x9C, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4D, 0x45, 0x07, 0xE6, 0x03, 0x10, 0x17, 0x07, 0x1D, 0x2E, 0x5E, 0x30, 0x9B, 0x00, 0x00, 0x00, 0x0B, 0x49, 0x44, 0x41, 0x54, 0x08, 0xD7, 0x63, 0x60, 0x00, 0x02, 0x00, 0x00, 0x05, 0x00, 0x01, 0xE2, 0x26, 0x05, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, ]; /// An animated GIF image with 3 1x1 pixel frames (a red, green, and blue /// frames). The GIF animates forever, and each frame has a 100ms delay. const List<int> kAnimatedGif = <int> [ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0xa1, 0x03, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0x21, 0xff, 0x0b, 0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30, 0x03, 0x01, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x00, 0x0a, 0x00, 0xff, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x4c, 0x01, 0x00, 0x21, 0xf9, 0x04, 0x00, 0x0a, 0x00, 0xff, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x54, 0x01, 0x00, 0x21, 0xf9, 0x04, 0x00, 0x0a, 0x00, 0xff, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b, ]; /// Measures expense of constructing Image widgets. class BenchBuildImage extends WidgetRecorder { BenchBuildImage() : super(name: benchmarkName); static const String benchmarkName = 'draw_image'; @override Widget createWidget() { return Directionality( textDirection: TextDirection.ltr, child: _RotatingWidget( child: Row(children: <Widget>[ Image.memory(Uint8List.fromList(kTransparentImage)), Image.memory(Uint8List.fromList(kAnimatedGif)), ]), ), ); } } class _RotatingWidget extends StatefulWidget { const _RotatingWidget({required this.child}); final Widget child; @override _RotatingWidgetState createState() => _RotatingWidgetState(); } class _RotatingWidgetState extends State<_RotatingWidget> with SingleTickerProviderStateMixin { late AnimationController controller; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 200), vsync: this, )..repeat(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: controller, builder: (BuildContext context, Widget? child) { return Transform( transform: Matrix4.identity()..rotateZ(2 * math.pi * controller.value), child: widget.child, ); }, ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_build_image.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_build_image.dart", "repo_id": "flutter", "token_count": 1716 }
489
// 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 'bench_paths_recording.dart' as recording; import 'recorder.dart'; /// Measure the performance of path construction. /// /// This benchmarks was generated by running flutter gallery and recording /// path calls. class BenchPathRecording extends RawRecorder { BenchPathRecording() : super(name: benchmarkName); static const String benchmarkName = 'bench_path_recording'; @override Future<void> setUpAll() async { } @override void body(Profile profile) { profile.record('recordPathConstruction', () { for (int i = 1; i <= 10; i++) { recording.createPaths(); } }, reported: true); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_paths.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_paths.dart", "repo_id": "flutter", "token_count": 243 }
490
// 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_driver/driver_extension.dart'; import 'package:macrobenchmarks/src/animated_image.dart'; /// This test is slightly different than most of the other tests in this /// application, in that it directly instantiates the page we care about and /// passes a callback. This way, we can make sure to consistently wait for a /// set number of image frames to render. Future<void> main() async { final Completer<void> waiter = Completer<void>(); enableFlutterDriverExtension(handler: (String? request) async { if (request != 'waitForAnimation') { throw UnsupportedError('Unrecognized request $request'); } await waiter.future; return 'done'; }); runApp(MaterialApp( home: AnimatedImagePage( onFrame: (int frameNumber) { if (frameNumber == 250) { waiter.complete(); } }, ), )); }
flutter/dev/benchmarks/macrobenchmarks/test_driver/animated_image.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/test_driver/animated_image.dart", "repo_id": "flutter", "token_count": 355 }
491
#include "Generated.xcconfig"
flutter/dev/benchmarks/microbenchmarks/ios/Flutter/Debug.xcconfig/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/ios/Flutter/Debug.xcconfig", "repo_id": "flutter", "token_count": 12 }
492
// 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/foundation.dart'; import '../common.dart'; const int _kNumIterations = 65536; const int _kNumWarmUp = 100; const int _kScale = 1000; void main() { assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'."); // In the following benchmarks, we won't remove the listeners when we don't // want to measure removeListener because we know that everything will be // GC'ed in the end. // Not removing listeners would cause memory leaks in a real application. final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); void runAddListenerBenchmark(int iteration, {bool addResult = true}) { const String name = 'add'; for (int listenerCount = 1; listenerCount <= 5; listenerCount += 1) { final List<_Notifier> notifiers = List<_Notifier>.generate( iteration, (_) => _Notifier(), growable: false, ); final Stopwatch watch = Stopwatch(); watch.start(); for (int i = 0; i < iteration; i += 1) { for (int l = 0; l < listenerCount; l += 1) { notifiers[i].addListener(() {}); } } watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); } } } void runNotifyListenerBenchmark(int iteration, {bool addResult = true}) { const String name = 'notify'; for (int listenerCount = 0; listenerCount <= 5; listenerCount += 1) { final _Notifier notifier = _Notifier(); for (int i = 1; i <= listenerCount; i += 1) { notifier.addListener(() {}); } final Stopwatch watch = Stopwatch(); watch.start(); for (int i = 0; i < iteration; i += 1) { notifier.notify(); } watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); } } } void runRemoveListenerBenchmark(int iteration, {bool addResult = true}) { const String name = 'remove'; final List<VoidCallback> listeners = <VoidCallback>[ () {}, () {}, () {}, () {}, () {}, ]; for (int listenerCount = 1; listenerCount <= 5; listenerCount += 1) { final List<_Notifier> notifiers = List<_Notifier>.generate( iteration, (_) { final _Notifier notifier = _Notifier(); for (int l = 0; l < listenerCount; l += 1) { notifier.addListener(listeners[l]); } return notifier; }, growable: false, ); final Stopwatch watch = Stopwatch(); watch.start(); for (int i = 0; i < iteration; i += 1) { for (int l = 0; l < listenerCount; l += 1) { notifiers[i].removeListener(listeners[l]); } } watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); } } } void runRemoveListenerWhileNotifyingBenchmark(int iteration, {bool addResult = true}) { const String name = 'removeWhileNotify'; final List<VoidCallback> listeners = <VoidCallback>[ () {}, () {}, () {}, () {}, () {}, ]; for (int listenerCount = 1; listenerCount <= 5; listenerCount += 1) { final List<_Notifier> notifiers = List<_Notifier>.generate( iteration, (_) { final _Notifier notifier = _Notifier(); notifier.addListener(() { // This listener will remove all other listeners. So that only this // one is called and measured. for (int l = 0; l < listenerCount; l += 1) { notifier.removeListener(listeners[l]); } }); for (int l = 0; l < listenerCount; l += 1) { notifier.addListener(listeners[l]); } return notifier; }, growable: false, ); final Stopwatch watch = Stopwatch(); watch.start(); for (int i = 0; i < iteration; i += 1) { notifiers[i].notify(); } watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); } } } runAddListenerBenchmark(_kNumWarmUp, addResult: false); runAddListenerBenchmark(_kNumIterations); runNotifyListenerBenchmark(_kNumWarmUp, addResult: false); runNotifyListenerBenchmark(_kNumIterations); runRemoveListenerBenchmark(_kNumWarmUp, addResult: false); runRemoveListenerBenchmark(_kNumIterations); runRemoveListenerWhileNotifyingBenchmark(_kNumWarmUp, addResult: false); runRemoveListenerWhileNotifyingBenchmark(_kNumIterations); printer.printToStdout(); } class _Notifier extends ChangeNotifier { void notify() => notifyListeners(); }
flutter/dev/benchmarks/microbenchmarks/lib/foundation/change_notifier_bench.dart/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/lib/foundation/change_notifier_bench.dart", "repo_id": "flutter", "token_count": 2402 }
493
// 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 '../common.dart'; const int _kNumIterations = 1000; const int _kNumWarmUp = 100; void main() { final List<String> words = 'Lorem Ipsum is simply dummy text of the printing and' " typesetting industry. Lorem Ipsum has been the industry's" ' standard dummy text ever since the 1500s, when an unknown' ' printer took a galley of type and scrambled it to make a' ' type specimen book'.split(' '); final List<InlineSpanSemanticsInformation> data = <InlineSpanSemanticsInformation>[]; for (int i = 0; i < words.length; i++) { if (i.isEven) { data.add( InlineSpanSemanticsInformation(words[i]), ); } else if (i.isEven) { data.add( InlineSpanSemanticsInformation(words[i], isPlaceholder: true), ); } } print(words); // Warm up lap for (int i = 0; i < _kNumWarmUp; i += 1) { combineSemanticsInfoSyncStar(data); combineSemanticsInfoList(data); } final Stopwatch watch = Stopwatch(); watch.start(); for (int i = 0; i < _kNumIterations; i += 1) { consumeSpan(combineSemanticsInfoSyncStar(data)); } final int combineSemanticsInfoSyncStarTime = watch.elapsedMicroseconds; watch ..reset() ..start(); for (int i = 0; i < _kNumIterations; i += 1) { consumeSpan(combineSemanticsInfoList(data)); } final int combineSemanticsInfoListTime = watch.elapsedMicroseconds; watch ..reset() ..start(); final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); const double scale = 1000.0 / _kNumIterations; printer.addResult( description: 'combineSemanticsInfoSyncStar', value: combineSemanticsInfoSyncStarTime * scale, unit: 'ns per iteration', name: 'combineSemanticsInfoSyncStar_iteration', ); printer.addResult( description: 'combineSemanticsInfoList', value: combineSemanticsInfoListTime * scale, unit: 'ns per iteration', name: 'combineSemanticsInfoList_iteration', ); printer.printToStdout(); } String consumeSpan(Iterable<InlineSpanSemanticsInformation> items) { String result = ''; for (final InlineSpanSemanticsInformation span in items) { result += span.text; } return result; } Iterable<InlineSpanSemanticsInformation> combineSemanticsInfoSyncStar(List<InlineSpanSemanticsInformation> inputs) sync* { String workingText = ''; String? workingLabel; for (final InlineSpanSemanticsInformation info in inputs) { if (info.requiresOwnNode) { yield InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText); workingText = ''; workingLabel = null; yield info; } else { workingText += info.text; workingLabel ??= ''; final String? infoSemanticsLabel = info.semanticsLabel; workingLabel += infoSemanticsLabel ?? info.text; } } assert(workingLabel != null); } Iterable<InlineSpanSemanticsInformation> combineSemanticsInfoList(List<InlineSpanSemanticsInformation> inputs) { String workingText = ''; String? workingLabel; final List<InlineSpanSemanticsInformation> result = <InlineSpanSemanticsInformation>[]; for (final InlineSpanSemanticsInformation info in inputs) { if (info.requiresOwnNode) { result.add(InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText)); workingText = ''; workingLabel = null; result.add(info); } else { workingText += info.text; workingLabel ??= ''; final String? infoSemanticsLabel = info.semanticsLabel; workingLabel += infoSemanticsLabel ?? info.text; } } assert(workingLabel != null); return result; }
flutter/dev/benchmarks/microbenchmarks/lib/language/sync_star_semantics_bench.dart/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/lib/language/sync_star_semantics_bench.dart", "repo_id": "flutter", "token_count": 1313 }
494
// 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. package com.example.platform_channels_benchmarks import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.BasicMessageChannel import io.flutter.plugin.common.BinaryCodec import io.flutter.plugin.common.StandardMessageCodec import java.nio.ByteBuffer class MainActivity : FlutterActivity() { // We allow for the caching of a response in the binary channel case since // the reply requires a direct buffer, but the input is not a direct buffer. // We can't directly send the input back to the reply currently. private var byteBufferCache: ByteBuffer? = null override fun configureFlutterEngine(flutterEngine: FlutterEngine) { val reset = BasicMessageChannel(flutterEngine.dartExecutor, "dev.flutter.echo.reset", StandardMessageCodec.INSTANCE) reset.setMessageHandler { message, reply -> run { byteBufferCache = null } } val basicStandard = BasicMessageChannel(flutterEngine.dartExecutor, "dev.flutter.echo.basic.standard", StandardMessageCodec.INSTANCE) basicStandard.setMessageHandler { message, reply -> reply.reply(message) } val basicBinary = BasicMessageChannel(flutterEngine.dartExecutor, "dev.flutter.echo.basic.binary", BinaryCodec.INSTANCE_DIRECT) basicBinary.setMessageHandler { message, reply -> run { if (byteBufferCache == null) { byteBufferCache = ByteBuffer.allocateDirect(message!!.capacity()) byteBufferCache!!.put(message) } reply.reply(byteBufferCache) } } val taskQueue = flutterEngine.dartExecutor.getBinaryMessenger().makeBackgroundTaskQueue() val backgroundStandard = BasicMessageChannel( flutterEngine.dartExecutor, "dev.flutter.echo.background.standard", StandardMessageCodec.INSTANCE, taskQueue, ) backgroundStandard.setMessageHandler { message, reply -> reply.reply(message) } super.configureFlutterEngine(flutterEngine) } }
flutter/dev/benchmarks/platform_channels_benchmarks/android/app/src/main/kotlin/com/example/platform_channels_benchmarks/MainActivity.kt/0
{ "file_path": "flutter/dev/benchmarks/platform_channels_benchmarks/android/app/src/main/kotlin/com/example/platform_channels_benchmarks/MainActivity.kt", "repo_id": "flutter", "token_count": 900 }
495
{ "title": "Stocks", "market": "MARKET", "portfolio": "PORTFOLIO" }
flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stocks_en_US.arb/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/i18n/stocks_en_US.arb", "repo_id": "flutter", "token_count": 35 }
496
// 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_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { group('scrolling performance test', () { late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() async { driver.close(); }); test('measure', () async { final Timeline timeline = await driver.traceAction(() async { // Find the scrollable stock list final SerializableFinder stockList = find.byValueKey('stock-list'); expect(stockList, isNotNull); // Scroll down for (int i = 0; i < 5; i++) { await driver.scroll(stockList, 0.0, -300.0, const Duration(milliseconds: 300)); await Future<void>.delayed(const Duration(milliseconds: 500)); } // Scroll up for (int i = 0; i < 5; i++) { await driver.scroll(stockList, 0.0, 300.0, const Duration(milliseconds: 300)); await Future<void>.delayed(const Duration(milliseconds: 500)); } }); final TimelineSummary summary = TimelineSummary.summarize(timeline); await summary.writeTimelineToFile('stocks_scroll_perf', pretty: true); }, timeout: Timeout.none); }); }
flutter/dev/benchmarks/test_apps/stocks/test_driver/scroll_perf_test.dart/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/test_driver/scroll_perf_test.dart", "repo_id": "flutter", "token_count": 544 }
497
#!/usr/bin/env bash # 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. set -e function script_location() { local script_location="${BASH_SOURCE[0]}" # Resolve symlinks while [[ -h "$script_location" ]]; do DIR="$(cd -P "$( dirname "$script_location")" >/dev/null && pwd)" script_location="$(readlink "$script_location")" [[ "$script_location" != /* ]] && script_location="$DIR/$script_location" done cd -P "$(dirname "$script_location")" >/dev/null && pwd } # So that users can run this script from anywhere and it will work as expected. SCRIPT_LOCATION="$(script_location)" # Sets the Flutter root to be "$(script_location)/../..": This script assumes # that it resides two directory levels down from the root, so if that changes, # then this line will need to as well. FLUTTER_ROOT="$(dirname "$(dirname "$SCRIPT_LOCATION")")" export FLUTTER_ROOT echo "$(date): Running docs.sh" if [[ ! -d "$FLUTTER_ROOT" || ! -f "$FLUTTER_ROOT/bin/flutter" ]]; then >&2 echo "Unable to locate the Flutter installation (using FLUTTER_ROOT: $FLUTTER_ROOT)" exit 1 fi FLUTTER_BIN="$FLUTTER_ROOT/bin" DART_BIN="$FLUTTER_ROOT/bin/cache/dart-sdk/bin" FLUTTER="$FLUTTER_BIN/flutter" DART="$DART_BIN/dart" PATH="$FLUTTER_BIN:$DART_BIN:$PATH" # Make sure dart is installed by invoking Flutter to download it if it is missing. # Also make sure the flutter command is ready to run before capturing output from # it: if it has to rebuild itself or something, it'll spoil our JSON output. "$FLUTTER" > /dev/null 2>&1 FLUTTER_VERSION="$("$FLUTTER" --version --machine)" export FLUTTER_VERSION # If the pub cache directory exists in the root, then use that. FLUTTER_PUB_CACHE="$FLUTTER_ROOT/.pub-cache" if [[ -d "$FLUTTER_PUB_CACHE" ]]; then # This has to be exported, because pub interprets setting it to the empty # string in the same way as setting it to ".". PUB_CACHE="${PUB_CACHE:-"$FLUTTER_PUB_CACHE"}" export PUB_CACHE fi function usage() { echo "Usage: $(basename "${BASH_SOURCE[0]}") [--keep-temp] [--output <output.zip>]" echo "" echo " --keep-staging Do not delete the staging directory created while generating" echo " docs. Normally the script deletes the staging directory after" echo " generating the output ZIP file." echo " --output <output.zip> specifies where the output ZIP file containing the documentation" echo " data will be written." echo " --staging-dir <directory> specifies where the temporary output files will be written while" echo " generating docs. This directory will be deleted after generation" echo " unless --keep-staging is also specified." echo "" } function parse_args() { local arg local args=() STAGING_DIR= KEEP_STAGING=0 DESTINATION="$FLUTTER_ROOT/dev/docs/api_docs.zip" while (( "$#" )); do case "$1" in --help) usage exit 0 ;; --staging-dir) STAGING_DIR="$2" shift ;; --keep-staging) KEEP_STAGING=1 ;; --output) DESTINATION="$2" shift ;; *) args=("${args[@]}" "$1") ;; esac shift done if [[ -z $STAGING_DIR ]]; then STAGING_DIR=$(mktemp -d /tmp/dartdoc.XXXXX) fi DOC_DIR="$STAGING_DIR/doc" if [[ ${#args[@]} != 0 ]]; then >&2 echo "ERROR: Unknown arguments: ${args[@]}" usage exit 1 fi } function generate_docs() { # Install and activate dartdoc. # When updating to a new dartdoc version, please also update # `dartdoc_options.yaml` to include newly introduced error and warning types. "$DART" pub global activate dartdoc 8.0.6 # Install and activate the snippets tool, which resides in the # assets-for-api-docs repo: # https://github.com/flutter/assets-for-api-docs/tree/main/packages/snippets "$DART" pub global activate snippets 0.4.3 # This script generates a unified doc set, and creates # a custom index.html, placing everything into DOC_DIR. # Make sure that create_api_docs.dart has all the dependencies it needs. (cd "$FLUTTER_ROOT/dev/tools" && "$FLUTTER" pub get) (cd "$FLUTTER_ROOT" && "$DART" --disable-dart-dev --enable-asserts "$FLUTTER_ROOT/dev/tools/create_api_docs.dart" --output-dir="$DOC_DIR") } function main() { echo "Writing docs build temporary output to $DOC_DIR" mkdir -p "$DOC_DIR" generate_docs # If the destination isn't an absolute path, make it into one. if ! [[ "$DESTINATION" =~ ^/ ]]; then DESTINATION="$PWD/$DESTINATION" fi # Make sure the destination has .zip as an extension, because zip will add it # anyhow, and we want to print the correct output location. DESTINATION=${DESTINATION%.zip}.zip # Zip up doc directory and write the output to the destination. (cd "$STAGING_DIR"; zip -r -9 -q "$DESTINATION" ./doc) if [[ $KEEP_STAGING -eq 1 ]]; then echo "Staging documentation output left in $STAGING_DIR" else echo "Removing staging documentation output from $STAGING_DIR" rm -rf "$STAGING_DIR" fi echo "Wrote docs ZIP file to $DESTINATION" } parse_args "$@" main
flutter/dev/bots/docs.sh/0
{ "file_path": "flutter/dev/bots/docs.sh", "repo_id": "flutter", "token_count": 2068 }
498
This directory is excluded from analysis because its whole point is to test the analysis (so it has issues). We have to have the actual test file system in a subdirectory (root) because otherwise the .dartignore file in that directory would cause the test itself to ignore the directory.
flutter/dev/bots/test/analyze-test-input/.dartignore/0
{ "file_path": "flutter/dev/bots/test/analyze-test-input/.dartignore", "repo_id": "flutter", "token_count": 63 }
499
// 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. // External Library that creates Stopwatches. This file will not be analyzed but // its symbols will be imported by tests. class MyStopwatch implements Stopwatch { MyStopwatch(); MyStopwatch.create(): this(); @override Duration get elapsed => throw UnimplementedError(); @override int get elapsedMicroseconds => throw UnimplementedError(); @override int get elapsedMilliseconds => throw UnimplementedError(); @override int get elapsedTicks => throw UnimplementedError(); @override int get frequency => throw UnimplementedError(); @override bool get isRunning => throw UnimplementedError(); @override void reset() { } @override void start() { } @override void stop() { } } final MyStopwatch stopwatch = MyStopwatch.create(); MyStopwatch createMyStopwatch() => MyStopwatch(); Stopwatch createStopwatch() => Stopwatch();
flutter/dev/bots/test/analyze-test-input/root/packages/foo/stopwatch_external_lib.dart/0
{ "file_path": "flutter/dev/bots/test/analyze-test-input/root/packages/foo/stopwatch_external_lib.dart", "repo_id": "flutter", "token_count": 290 }
500
## Flutter Conductor Protocol Buffers This directory contains [conductor_state.proto](./conductor_state.proto), which defines the persistent state file the conductor creates. After changes to this file, you must run the [compile_proto.sh](./compile_proto.sh) script in this directory, which will re-generate the rest of the Dart files in this directory, format them, and prepend the license comment from [license_header.txt](./license_header.txt).
flutter/dev/conductor/core/lib/src/proto/README.md/0
{ "file_path": "flutter/dev/conductor/core/lib/src/proto/README.md", "repo_id": "flutter", "token_count": 121 }
501
// 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:args/command_runner.dart'; import 'package:conductor_core/src/clean.dart'; import 'package:conductor_core/src/repository.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:platform/platform.dart'; import './common.dart'; void main() { group('clean command', () { const String flutterRoot = '/flutter'; const String checkoutsParentDirectory = '$flutterRoot/dev/tools/'; const String stateFilePath = '/state-file.json'; late MemoryFileSystem fileSystem; late FakePlatform platform; late TestStdio stdio; late FakeProcessManager processManager; late CommandRunner<void> runner; setUp(() { stdio = TestStdio(); fileSystem = MemoryFileSystem.test(); final String operatingSystem = const LocalPlatform().operatingSystem; final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/'; processManager = FakeProcessManager.empty(); platform = FakePlatform( environment: <String, String>{'HOME': '/path/to/user/home'}, pathSeparator: pathSeparator, ); final Checkouts checkouts = Checkouts( fileSystem: fileSystem, parentDirectory: fileSystem.directory(checkoutsParentDirectory), platform: platform, processManager: processManager, stdio: stdio, ); final CleanCommand command = CleanCommand( checkouts: checkouts, ); runner = CommandRunner<void>('clean-test', '')..addCommand(command); }); test('throws if no state file found', () async { await expectLater( () async => runner.run(<String>[ 'clean', '--$kStateOption', stateFilePath, '--$kYesFlag', ]), throwsExceptionWith( 'No persistent state file found at $stateFilePath', ), ); }); test('deletes an empty state file', () async { final File stateFile = fileSystem.file(stateFilePath); stateFile.writeAsStringSync(''); await runner.run(<String>[ 'clean', '--$kStateOption', stateFile.path, '--$kYesFlag', ]); expect(stateFile.existsSync(), false); }); test('deletes a state file with content', () async { final File stateFile = fileSystem.file(stateFilePath); stateFile.writeAsStringSync('{status: pending}'); await runner.run(<String>[ 'clean', '--$kStateOption', stateFile.path, '--$kYesFlag', ]); expect(stateFile.existsSync(), false); }); }, onPlatform: <String, dynamic>{ 'windows': const Skip('Flutter Conductor only supported on macos/linux'), }); }
flutter/dev/conductor/core/test/clean_test.dart/0
{ "file_path": "flutter/dev/conductor/core/test/clean_test.dart", "repo_id": "flutter", "token_count": 1102 }
502
// 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:customer_testing/customer_test.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'common.dart'; void main() { test('constructs expected model', () async { const String registryContent = ''' [email protected] fetch=git clone https://github.com/flutter/cocoon.git tests fetch=git -C tests checkout abc123 setup=flutter --version setup.windows=flutter doctor setup.posix=flutter -h setup.linux=flutter analyze -h setup.macos=flutter build -h update=. # Runs flutter analyze, flutter test, and builds web platform test.posix=./test_utilities/bin/flutter_test_runner.sh app_flutter test.posix=./test_utilities/bin/flutter_test_runner.sh repo_dashboard test.windows=.\test_utilities\bin\flutter_test_runner.bat repo_dashboard '''; final File registryFile = MemoryFileSystem().file('flutter_cocoon.test')..writeAsStringSync(registryContent); final CustomerTest test = CustomerTest(registryFile); expect(test.contacts, containsAll(<String>['[email protected]'])); expect( test.fetch, containsAllInOrder( <String>['git clone https://github.com/flutter/cocoon.git tests', 'git -C tests checkout abc123'])); expect(test.setup.first, 'flutter --version'); if (Platform.isLinux || Platform.isMacOS) { expect(test.setup.length, 3); expect(test.setup[1], 'flutter -h'); expect(test.setup[2], Platform.isLinux ? 'flutter analyze -h' : 'flutter build -h'); expect( test.tests, containsAllInOrder(<String>[ './test_utilities/bin/flutter_test_runner.sh app_flutter', './test_utilities/bin/flutter_test_runner.sh repo_dashboard', ]), ); } else if (Platform.isWindows) { expect(test.setup.length, 2); expect(test.setup[1], 'flutter doctor'); expect(test.tests, containsAllInOrder(<String>['.\test_utilities\bin\flutter_test_runner.bat repo_dashboard'])); } }); test('throws exception when unknown field is passed', () async { const String registryContent = ''' [email protected] update=. fetch=git clone https://github.com/flutter/cocoon.git tests fetch=git -C tests checkout abc123 test.posix=./test_utilities/bin/flutter_test_runner.sh app_flutter test.windows=.\test_utilities\bin\flutter_test_runner.bat repo_dashboard unknownfield=super not cool '''; final File registryFile = MemoryFileSystem().file('abc.test')..writeAsStringSync(registryContent); expect(() => CustomerTest(registryFile), throwsFormatException); }); test('throws exception when no tests given', () async { const String registryContent = ''' [email protected] update=. fetch=git clone https://github.com/flutter/cocoon.git tests '''; final File registryFile = MemoryFileSystem().file('abc.test')..writeAsStringSync(registryContent); expect(() => CustomerTest(registryFile), throwsFormatException); }); test('throws exception when only one fetch instruction given', () async { const String registryContent = ''' [email protected] update=. fetch=git clone https://github.com/flutter/cocoon.git tests test.posix=./test_utilities/bin/flutter_test_runner.sh app_flutter test.windows=.\test_utilities\bin\flutter_test_runner.bat repo_dashboard '''; final File registryFile = MemoryFileSystem().file('abc.test')..writeAsStringSync(registryContent); expect(() => CustomerTest(registryFile), throwsFormatException); }); test('throws exception when no contacts given', () async { const String registryContent = ''' update=. fetch=git clone https://github.com/flutter/cocoon.git tests test.posix=./test_utilities/bin/flutter_test_runner.sh app_flutter test.windows=.\test_utilities\bin\flutter_test_runner.bat repo_dashboard '''; final File registryFile = MemoryFileSystem().file('abc.test')..writeAsStringSync(registryContent); expect(() => CustomerTest(registryFile), throwsFormatException); }); }
flutter/dev/customer_testing/test/customer_test_test.dart/0
{ "file_path": "flutter/dev/customer_testing/test/customer_test_test.dart", "repo_id": "flutter", "token_count": 1432 }
503
// 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_devicelab/framework/apk_utils.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:path/path.dart' as path; Future<void> main() async { await task(() async { try { await runPluginProjectTest((FlutterPluginProject pluginProject) async { section('APK content for task assembleDebug with target platform = android-arm'); await inDirectory(pluginProject.exampleAndroidPath, () { return flutter( 'build', options: <String>[ 'apk', '--debug', '--target-platform=android-arm', ], ); }); Iterable<String> apkFiles = await getFilesInApk(pluginProject.debugApkPath); checkCollectionContains<String>(<String>[ ...flutterAssets, ...debugAssets, ...baseApkFiles, 'lib/armeabi-v7a/libflutter.so', // Debug mode intentionally includes `x86` and `x86_64`. 'lib/x86/libflutter.so', 'lib/x86_64/libflutter.so', ], apkFiles); checkCollectionDoesNotContain<String>(<String>[ 'lib/arm64-v8a/libapp.so', 'lib/armeabi-v7a/libapp.so', 'lib/x86/libapp.so', 'lib/x86_64/libapp.so', ], apkFiles); section('APK content for task assembleDebug with target platform = android-x86'); // This is used by `flutter run` await inDirectory(pluginProject.exampleAndroidPath, () { return flutter( 'build', options: <String>[ 'apk', '--debug', '--target-platform=android-x86', ], ); }); apkFiles = await getFilesInApk(pluginProject.debugApkPath); checkCollectionContains<String>(<String>[ ...flutterAssets, ...debugAssets, ...baseApkFiles, // Debug mode intentionally includes `x86` and `x86_64`. 'lib/x86/libflutter.so', 'lib/x86_64/libflutter.so', ], apkFiles); checkCollectionDoesNotContain<String>(<String>[ 'lib/armeabi-v7a/libapp.so', 'lib/x86/libapp.so', 'lib/x86_64/libapp.so', ], apkFiles); section('APK content for task assembleDebug with target platform = android-x64'); // This is used by `flutter run` await inDirectory(pluginProject.exampleAndroidPath, () { return flutter( 'build', options: <String>[ 'apk', '--debug', '--target-platform=android-x64', ], ); }); apkFiles = await getFilesInApk(pluginProject.debugApkPath); checkCollectionContains<String>(<String>[ ...flutterAssets, ...debugAssets, ...baseApkFiles, // Debug mode intentionally includes `x86` and `x86_64`. 'lib/x86/libflutter.so', 'lib/x86_64/libflutter.so', ], apkFiles); checkCollectionDoesNotContain<String>(<String>[ 'lib/armeabi-v7a/libapp.so', 'lib/x86/libapp.so', 'lib/x86_64/libapp.so', ], apkFiles); section('APK content for task assembleRelease with target platform = android-arm'); await inDirectory(pluginProject.exampleAndroidPath, () { return flutter( 'build', options: <String>[ 'apk', '--release', '--target-platform=android-arm', ], ); }); apkFiles = await getFilesInApk(pluginProject.releaseApkPath); checkCollectionContains<String>(<String>[ ...flutterAssets, ...baseApkFiles, 'lib/armeabi-v7a/libflutter.so', 'lib/armeabi-v7a/libapp.so', ], apkFiles); checkCollectionDoesNotContain<String>(<String>[ ...debugAssets, 'lib/arm64-v8a/libflutter.so', 'lib/arm64-v8a/libapp.so', ], apkFiles); section('APK content for task assembleRelease with target platform = android-arm64'); await inDirectory(pluginProject.exampleAndroidPath, () { return flutter( 'build', options: <String>[ 'apk', '--release', '--target-platform=android-arm64', ], ); }); apkFiles = await getFilesInApk(pluginProject.releaseApkPath); checkCollectionContains<String>(<String>[ ...flutterAssets, ...baseApkFiles, 'lib/arm64-v8a/libflutter.so', 'lib/arm64-v8a/libapp.so', ], apkFiles); checkCollectionDoesNotContain<String>(<String>[ ...debugAssets, 'lib/armeabi-v7a/libflutter.so', 'lib/armeabi-v7a/libapp.so', ], apkFiles); }); await runProjectTest((FlutterProject project) async { section('gradlew assembleDebug'); await inDirectory(project.rootPath, () { return flutter( 'build', options: <String>[ 'apk', '--debug', ], ); }); final String? errorMessage = validateSnapshotDependency(project, 'kernel_blob.bin'); if (errorMessage != null) { throw TaskResult.failure(errorMessage); } section('gradlew assembleProfile'); await inDirectory(project.rootPath, () { return flutter( 'build', options: <String>[ 'apk', '--profile', ], ); }); section('gradlew assembleLocal (custom debug build)'); await project.addCustomBuildType('local', initWith: 'debug'); await project.runGradleTask('assembleLocal'); }); await runProjectTest((FlutterProject project) async { section('gradlew assembleLocal with plugin (custom debug build)'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_plugin.'); final Directory pluginDir = Directory(path.join(tempDir.path, 'plugin_under_test')); section('Create plugin'); await inDirectory(tempDir, () async { await flutter( 'create', options: <String>[ '--org', 'io.flutter.devicelab.plugin', '--template=plugin', '--platforms=android,ios', pluginDir.path, ], ); }); section('Configure'); project.addPlugin('plugin_under_test', value: '$platformLineSep path: ${pluginDir.path}'); await project.addCustomBuildType('local', initWith: 'debug'); await project.getPackages(); section('Build APK'); await project.runGradleTask('assembleLocal'); }); await runProjectTest((FlutterProject project) async { section('gradlew assembleBeta (custom release build)'); await project.addCustomBuildType('beta', initWith: 'release'); await project.runGradleTask('assembleBeta'); }); await runProjectTest((FlutterProject project) async { section('gradlew assembleLocal (plugin with custom build type)'); await project.addCustomBuildType('local', initWith: 'debug'); section('Add plugin'); project.addPlugin('path_provider'); await project.getPackages(); await project.runGradleTask('assembleLocal'); }); await runProjectTest((FlutterProject project) async { section('gradlew assembleFreeDebug (product flavor)'); await project.addProductFlavors(<String>['free']); await project.runGradleTask('assembleFreeDebug'); }); await runProjectTest((FlutterProject project) async { section('gradlew on build script with error'); await project.introduceError(); ProcessResult result = await inDirectory(project.rootPath, () { return executeFlutter( 'build', options: <String>[ 'apk', '--release', ], canFail: true, ); }); if (result.exitCode == 0) { throw failure( 'Gradle did not exit with error as expected', result); } String output = '${result.stdout}\n${result.stderr}'; if (output.contains('GradleException') || output.contains('Failed to notify') || output.contains('at org.gradle')) { throw failure( 'Gradle output should not contain stacktrace', result); } if (!output.contains('Build failed')) { throw failure( 'Gradle output should contain a readable error message', result); } section('flutter build apk on build script with error'); await project.introduceError(); result = await inDirectory(project.rootPath, () { return executeFlutter( 'build', options: <String>[ 'apk', '--release', ], canFail: true, ); }); if (result.exitCode == 0) { throw failure( 'flutter build apk should fail when Gradle does', result); } output = '${result.stdout}\n${result.stderr}'; if (!output.contains('Build failed')) { throw failure( 'flutter build apk output should contain a readable Gradle error message', result); } if (hasMultipleOccurrences(output, 'Build failed')) { throw failure( 'flutter build apk should not invoke Gradle repeatedly on error', result); } }); await runProjectTest((FlutterProject project) async { section('gradlew assembleDebug forwards stderr'); await project.introducePubspecError(); final ProcessResult result = await inDirectory(project.rootPath, () { return executeFlutter( 'build', options: <String>[ 'apk', '--release', ], canFail: true, ); }); if (result.exitCode == 0) { throw failure( 'Gradle did not exit with error as expected', result); } final String output = '${result.stdout}\n${result.stderr}'; if (!output.contains('No file or variants found for asset: lib/gallery/example_code.dart.')) { throw failure(output, result); } }); return TaskResult.success(null); } on TaskResult catch (taskResult) { return taskResult; } catch (e) { return TaskResult.failure(e.toString()); } }); }
flutter/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart", "repo_id": "flutter", "token_count": 5221 }
504
// 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:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:archive/archive.dart'; import 'package:flutter_devicelab/framework/apk_utils.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:path/path.dart' as path; final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew'; final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew'; final String fileReadWriteMode = Platform.isWindows ? 'rw-rw-rw-' : 'rw-r--r--'; final String platformLineSep = Platform.isWindows ? '\r\n' : '\n'; /// Combines several TaskFunctions with trivial success value into one. TaskFunction combine(List<TaskFunction> tasks) { return () async { for (final TaskFunction task in tasks) { final TaskResult result = await task(); if (result.failed) { return result; } } return TaskResult.success(null); }; } /// Tests that the Flutter module project template works and supports /// adding Flutter to an existing Android app. class ModuleTest { ModuleTest( this.buildTarget, { this.gradleVersion = '7.6.3', }); final String buildTarget; final String gradleVersion; Future<TaskResult> call() async { section('Running: $buildTarget'); section('Find Java'); final String? javaHome = await findJavaHome(); if (javaHome == null) { return TaskResult.failure('Could not find Java'); } print('\nUsing JAVA_HOME=$javaHome'); section('Create Flutter module project'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.'); final Directory projectDir = Directory(path.join(tempDir.path, 'hello')); try { await inDirectory(tempDir, () async { await flutter( 'create', options: <String>['--org', 'io.flutter.devicelab', '--template=module', 'hello'], ); }); section('Create package with native assets'); await flutter( 'config', options: <String>['--enable-native-assets'], ); const String ffiPackageName = 'ffi_package'; await createFfiPackage(ffiPackageName, tempDir); section('Add FFI package'); final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml')); String content = await pubspec.readAsString(); content = content.replaceFirst( 'dependencies:$platformLineSep', 'dependencies:$platformLineSep $ffiPackageName:$platformLineSep path: ..${Platform.pathSeparator}$ffiPackageName$platformLineSep', ); await pubspec.writeAsString(content, flush: true); await inDirectory(projectDir, () async { await flutter( 'packages', options: <String>['get'], ); }); section('Add read-only asset'); final File readonlyTxtAssetFile = await File(path.join( projectDir.path, 'assets', 'read-only.txt' )) .create(recursive: true); if (!exists(readonlyTxtAssetFile)) { return TaskResult.failure('Failed to create read-only asset'); } if (!Platform.isWindows) { await exec('chmod', <String>[ '444', readonlyTxtAssetFile.path, ]); } content = content.replaceFirst( '$platformLineSep # assets:$platformLineSep', '$platformLineSep assets:$platformLineSep - assets/read-only.txt$platformLineSep', ); await pubspec.writeAsString(content, flush: true); section('Add plugins'); content = content.replaceFirst( '${platformLineSep}dependencies:$platformLineSep', '${platformLineSep}dependencies:$platformLineSep device_info: 2.0.3$platformLineSep package_info: 2.0.2$platformLineSep', ); await pubspec.writeAsString(content, flush: true); await inDirectory(projectDir, () async { await flutter( 'packages', options: <String>['get'], ); }); // TODO(dacoharkes): Implement Add2app. https://github.com/flutter/flutter/issues/129757 section('Build Flutter module library archive'); await inDirectory(Directory(path.join(projectDir.path, '.android')), () async { await exec( gradlewExecutable, <String>['flutter:assembleDebug'], environment: <String, String>{ 'JAVA_HOME': javaHome }, ); }); final bool aarBuilt = exists(File(path.join( projectDir.path, '.android', 'Flutter', 'build', 'outputs', 'aar', 'flutter-debug.aar', ))); if (!aarBuilt) { return TaskResult.failure('Failed to build .aar'); } section('Build ephemeral host app'); await inDirectory(projectDir, () async { await flutter( 'build', options: <String>['apk'], ); }); final bool ephemeralHostApkBuilt = exists(File(path.join( projectDir.path, 'build', 'host', 'outputs', 'apk', 'release', 'app-release.apk', ))); if (!ephemeralHostApkBuilt) { return TaskResult.failure('Failed to build ephemeral host .apk'); } section('Clean build'); await inDirectory(projectDir, () async { await flutter('clean'); }); section('Make Android host app editable'); await inDirectory(projectDir, () async { await flutter( 'make-host-app-editable', options: <String>['android'], ); }); section('Build editable host app'); await inDirectory(projectDir, () async { await flutter( 'build', options: <String>['apk'], ); }); final bool editableHostApkBuilt = exists(File(path.join( projectDir.path, 'build', 'host', 'outputs', 'apk', 'release', 'app-release.apk', ))); if (!editableHostApkBuilt) { return TaskResult.failure('Failed to build editable host .apk'); } section('Add to existing Android app'); final Directory hostApp = Directory(path.join(tempDir.path, 'hello_host_app')); mkdir(hostApp); recursiveCopy( Directory( path.join( flutterDirectory.path, 'dev', 'integration_tests', 'android_host_app_v2_embedding', ), ), hostApp, ); copy( File(path.join(projectDir.path, '.android', gradlew)), hostApp, ); copy( File(path.join(projectDir.path, '.android', 'gradle', 'wrapper', 'gradle-wrapper.jar')), Directory(path.join(hostApp.path, 'gradle', 'wrapper')), ); // Modify gradle version to passed in version. // This is somehow the wrong file. final File gradleWrapperProperties = File(path.join( hostApp.path, 'gradle', 'wrapper', 'gradle-wrapper.properties')); String propertyContent = await gradleWrapperProperties.readAsString(); propertyContent = propertyContent.replaceFirst( 'REPLACEME', gradleVersion, ); section(propertyContent); await gradleWrapperProperties.writeAsString(propertyContent, flush: true); final File analyticsOutputFile = File(path.join(tempDir.path, 'analytics.log')); section('Build debug host APK'); await inDirectory(hostApp, () async { if (!Platform.isWindows) { await exec('chmod', <String>['+x', 'gradlew']); } await exec(gradlewExecutable, <String>['app:assembleDebug'], environment: <String, String>{ 'JAVA_HOME': javaHome, 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, }, ); }); section('Check debug APK exists'); final String debugHostApk = path.join( hostApp.path, 'app', 'build', 'outputs', 'apk', 'debug', 'app-debug.apk', ); if (!exists(File(debugHostApk))) { return TaskResult.failure('Failed to build debug host APK'); } section('Check files in debug APK'); checkCollectionContains<String>(<String>[ ...flutterAssets, ...debugAssets, ...baseApkFiles, 'lib/arm64-v8a/lib$ffiPackageName.so', 'lib/armeabi-v7a/lib$ffiPackageName.so', ], await getFilesInApk(debugHostApk)); section('Check debug AndroidManifest.xml'); final String androidManifestDebug = await getAndroidManifest(debugHostApk); if (!androidManifestDebug.contains(''' <meta-data android:name="flutterProjectType" android:value="module" />''') ) { return TaskResult.failure("Debug host APK doesn't contain metadata: flutterProjectType = module "); } final String analyticsOutput = analyticsOutputFile.readAsStringSync(); if (!analyticsOutput.contains('cd24: android') || !analyticsOutput.contains('cd25: true') || !analyticsOutput.contains('viewName: assemble')) { return TaskResult.failure( 'Building outer app produced the following analytics: "$analyticsOutput" ' 'but not the expected strings: "cd24: android", "cd25: true" and ' '"viewName: assemble"' ); } section('Check file access modes for read-only asset from Flutter module'); final String readonlyDebugAssetFilePath = path.joinAll(<String>[ hostApp.path, 'app', 'build', 'intermediates', 'assets', 'debug', 'flutter_assets', 'assets', 'read-only.txt', ]); final File readonlyDebugAssetFile = File(readonlyDebugAssetFilePath); if (!exists(readonlyDebugAssetFile)) { return TaskResult.failure('Failed to copy read-only asset file'); } String modes = readonlyDebugAssetFile.statSync().modeString(); print('\nread-only.txt file access modes = $modes'); if (modes.compareTo(fileReadWriteMode) != 0) { return TaskResult.failure('Failed to make assets user-readable and writable'); } section('Build release host APK'); await inDirectory(hostApp, () async { await exec(gradlewExecutable, <String>['app:assembleRelease'], environment: <String, String>{ 'JAVA_HOME': javaHome, 'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path, }, ); }); final String releaseHostApk = path.join( hostApp.path, 'app', 'build', 'outputs', 'apk', 'release', 'app-release-unsigned.apk', ); if (!exists(File(releaseHostApk))) { return TaskResult.failure('Failed to build release host APK'); } section('Check files in release APK'); checkCollectionContains<String>(<String>[ ...flutterAssets, ...baseApkFiles, 'lib/arm64-v8a/lib$ffiPackageName.so', 'lib/arm64-v8a/libapp.so', 'lib/arm64-v8a/libflutter.so', 'lib/armeabi-v7a/lib$ffiPackageName.so', 'lib/armeabi-v7a/libapp.so', 'lib/armeabi-v7a/libflutter.so', ], await getFilesInApk(releaseHostApk)); section('Check the NOTICE file is correct'); await inDirectory(hostApp, () async { final File apkFile = File(releaseHostApk); final Archive apk = ZipDecoder().decodeBytes(apkFile.readAsBytesSync()); // Shouldn't be missing since we already checked it exists above. final ArchiveFile? noticesFile = apk.findFile('assets/flutter_assets/NOTICES.Z'); final Uint8List? licenseData = noticesFile?.content as Uint8List?; if (licenseData == null) { return TaskResult.failure('Invalid license file.'); } final String licenseString = utf8.decode(gzip.decode(licenseData)); if (!licenseString.contains('skia') || !licenseString.contains('Flutter Authors')) { return TaskResult.failure('License content missing.'); } }); section('Check release AndroidManifest.xml'); final String androidManifestRelease = await getAndroidManifest(debugHostApk); if (!androidManifestRelease.contains(''' <meta-data android:name="flutterProjectType" android:value="module" />''') ) { return TaskResult.failure("Release host APK doesn't contain metadata: flutterProjectType = module "); } section('Check file access modes for read-only asset from Flutter module'); final String readonlyReleaseAssetFilePath = path.joinAll(<String>[ hostApp.path, 'app', 'build', 'intermediates', 'assets', 'release', 'flutter_assets', 'assets', 'read-only.txt', ]); final File readonlyReleaseAssetFile = File(readonlyReleaseAssetFilePath); if (!exists(readonlyReleaseAssetFile)) { return TaskResult.failure('Failed to copy read-only asset file'); } modes = readonlyReleaseAssetFile.statSync().modeString(); print('\nread-only.txt file access modes = $modes'); if (modes.compareTo(fileReadWriteMode) != 0) { return TaskResult.failure('Failed to make assets user-readable and writable'); } return TaskResult.success(null); } on TaskResult catch (taskResult) { return taskResult; } catch (e) { return TaskResult.failure(e.toString()); } finally { rmTree(tempDir); } } } Future<void> main() async { await task(combine(<TaskFunction>[ // ignore: avoid_redundant_argument_values ModuleTest('module-gradle-7.6', gradleVersion: '7.6.3').call, ModuleTest('module-gradle-7.6', gradleVersion: '7.6-rc-2').call, ])); }
flutter/dev/devicelab/bin/tasks/module_test.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/module_test.dart", "repo_id": "flutter", "token_count": 5998 }
505
// 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:path/path.dart' as path; import 'task_result.dart'; import 'utils.dart'; final String platformLineSep = Platform.isWindows ? '\r\n' : '\n'; final List<String> flutterAssets = <String>[ 'assets/flutter_assets/AssetManifest.json', 'assets/flutter_assets/NOTICES.Z', 'assets/flutter_assets/fonts/MaterialIcons-Regular.otf', 'assets/flutter_assets/packages/cupertino_icons/assets/CupertinoIcons.ttf', ]; final List<String> debugAssets = <String>[ 'assets/flutter_assets/isolate_snapshot_data', 'assets/flutter_assets/kernel_blob.bin', 'assets/flutter_assets/vm_snapshot_data', ]; final List<String> baseApkFiles = <String> [ 'classes.dex', 'AndroidManifest.xml', ]; /// Runs the given [testFunction] on a freshly generated Flutter project. Future<void> runProjectTest(Future<void> Function(FlutterProject project) testFunction) async { final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.'); final FlutterProject project = await FlutterProject.create(tempDir, 'hello'); try { await testFunction(project); } finally { rmTree(tempDir); } } /// Runs the given [testFunction] on a freshly generated Flutter plugin project. Future<void> runPluginProjectTest(Future<void> Function(FlutterPluginProject pluginProject) testFunction) async { final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.'); final FlutterPluginProject pluginProject = await FlutterPluginProject.create(tempDir, 'aaa'); try { await testFunction(pluginProject); } finally { rmTree(tempDir); } } /// Runs the given [testFunction] on a freshly generated Flutter module project. Future<void> runModuleProjectTest(Future<void> Function(FlutterModuleProject moduleProject) testFunction) async { final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_module_test.'); final FlutterModuleProject moduleProject = await FlutterModuleProject.create(tempDir, 'hello_module'); try { await testFunction(moduleProject); } finally { rmTree(tempDir); } } /// Returns the list of files inside an Android Package Kit. Future<Iterable<String>> getFilesInApk(String apk) async { if (!File(apk).existsSync()) { throw TaskResult.failure( 'Gradle did not produce an output artifact file at: $apk'); } final String files = await _evalApkAnalyzer( <String>[ 'files', 'list', apk, ] ); return files.split('\n').map((String file) => file.substring(1).trim()); } /// Returns the list of files inside an Android App Bundle. Future<Iterable<String>> getFilesInAppBundle(String bundle) { return getFilesInApk(bundle); } /// Returns the list of files inside an Android Archive. Future<Iterable<String>> getFilesInAar(String aar) { return getFilesInApk(aar); } TaskResult failure(String message, ProcessResult result) { print('Unexpected process result:'); print('Exit code: ${result.exitCode}'); print('Std out :\n${result.stdout}'); print('Std err :\n${result.stderr}'); return TaskResult.failure(message); } bool hasMultipleOccurrences(String text, Pattern pattern) { return text.indexOf(pattern) != text.lastIndexOf(pattern); } /// The Android home directory. String get _androidHome { final String? androidHome = Platform.environment['ANDROID_HOME'] ?? Platform.environment['ANDROID_SDK_ROOT']; if (androidHome == null || androidHome.isEmpty) { throw Exception('Environment variable `ANDROID_HOME` is not set.'); } return androidHome; } /// Executes an APK analyzer subcommand. Future<String> _evalApkAnalyzer( List<String> args, { bool printStdout = false, String? workingDirectory, }) async { final String? javaHome = await findJavaHome(); if (javaHome == null || javaHome.isEmpty) { throw Exception('No JAVA_HOME set.'); } final String apkAnalyzer = path .join(_androidHome, 'cmdline-tools', 'latest', 'bin', Platform.isWindows ? 'apkanalyzer.bat' : 'apkanalyzer'); if (canRun(apkAnalyzer)) { return eval( apkAnalyzer, args, printStdout: printStdout, workingDirectory: workingDirectory, environment: <String, String>{ 'JAVA_HOME': javaHome, }, ); } final String javaBinary = path.join(javaHome, 'bin', 'java'); assert(canRun(javaBinary)); final String androidTools = path.join(_androidHome, 'tools'); final String libs = path.join(androidTools, 'lib'); assert(Directory(libs).existsSync()); final String classSeparator = Platform.isWindows ? ';' : ':'; return eval( javaBinary, <String>[ '-Dcom.android.sdklib.toolsdir=$androidTools', '-classpath', '.$classSeparator$libs${Platform.pathSeparator}*', 'com.android.tools.apk.analyzer.ApkAnalyzerCli', ...args, ], printStdout: printStdout, workingDirectory: workingDirectory, ); } /// Utility class to analyze the content inside an APK using the APK analyzer. class ApkExtractor { ApkExtractor(this.apkFile); /// The APK. final File apkFile; bool _extracted = false; Set<String> _classes = const <String>{}; Set<String> _methods = const <String>{}; Future<void> _extractDex() async { if (_extracted) { return; } final String packages = await _evalApkAnalyzer( <String>[ 'dex', 'packages', apkFile.path, ], ); final List<String> lines = packages.split('\n'); _classes = Set<String>.from( lines.where((String line) => line.startsWith('C')) .map<String>((String line) => line.split('\t').last), ); assert(_classes.isNotEmpty); _methods = Set<String>.from( lines.where((String line) => line.startsWith('M')) .map<String>((String line) => line.split('\t').last) ); assert(_methods.isNotEmpty); _extracted = true; } /// Returns true if the APK contains a given class. Future<bool> containsClass(String className) async { await _extractDex(); return _classes.contains(className); } /// Returns true if the APK contains a given method. /// For example: io.flutter.plugins.googlemaps.GoogleMapController void onFlutterViewAttached(android.view.View) Future<bool> containsMethod(String methodName) async { await _extractDex(); return _methods.contains(methodName); } } /// Gets the content of the `AndroidManifest.xml`. Future<String> getAndroidManifest(String apk) async { return _evalApkAnalyzer( <String>[ 'manifest', 'print', apk, ], workingDirectory: _androidHome, ); } /// Checks that the classes are contained in the APK, throws otherwise. Future<void> checkApkContainsClasses(File apk, List<String> classes) async { final ApkExtractor extractor = ApkExtractor(apk); for (final String className in classes) { if (!(await extractor.containsClass(className))) { throw Exception("APK doesn't contain class `$className`."); } } } /// Checks that the methods are defined in the APK, throws otherwise. Future<void> checkApkContainsMethods(File apk, List<String> methods) async { final ApkExtractor extractor = ApkExtractor(apk); for (final String method in methods) { if (!(await extractor.containsMethod(method))) { throw Exception("APK doesn't contain method `$method`."); } } } class FlutterProject { FlutterProject(this.parent, this.name); final Directory parent; final String name; static Future<FlutterProject> create(Directory directory, String name) async { await inDirectory(directory, () async { await flutter('create', options: <String>['--template=app', name]); }); return FlutterProject(directory, name); } String get rootPath => path.join(parent.path, name); String get androidPath => path.join(rootPath, 'android'); String get iosPath => path.join(rootPath, 'ios'); Future<void> addCustomBuildType(String name, {required String initWith}) async { final File buildScript = File( path.join(androidPath, 'app', 'build.gradle'), ); buildScript.openWrite(mode: FileMode.append).write(''' android { buildTypes { $name { initWith $initWith } } } '''); } /// Adds a plugin to the pubspec. /// In pubspec, each dependency is expressed as key, value pair joined by a colon `:`. /// such as `plugin_a`:`^0.0.1` or `plugin_a`:`\npath: /some/path`. void addPlugin(String plugin, { String value = '' }) { final File pubspec = File(path.join(rootPath, 'pubspec.yaml')); String content = pubspec.readAsStringSync(); content = content.replaceFirst( '${platformLineSep}dependencies:$platformLineSep', '${platformLineSep}dependencies:$platformLineSep $plugin: $value$platformLineSep', ); pubspec.writeAsStringSync(content, flush: true); } Future<void> setMinSdkVersion(int sdkVersion) async { final File buildScript = File( path.join(androidPath, 'app', 'build.gradle'), ); buildScript.openWrite(mode: FileMode.append).write(''' android { defaultConfig { minSdkVersion $sdkVersion } } '''); } Future<void> getPackages() async { await inDirectory(Directory(rootPath), () async { await flutter('pub', options: <String>['get']); }); } Future<void> addProductFlavors(Iterable<String> flavors) async { final File buildScript = File( path.join(androidPath, 'app', 'build.gradle'), ); final String flavorConfig = flavors.map((String name) { return ''' $name { applicationIdSuffix ".$name" versionNameSuffix "-$name" } '''; }).join('\n'); buildScript.openWrite(mode: FileMode.append).write(''' android { flavorDimensions "mode" productFlavors { $flavorConfig } } '''); } Future<void> introduceError() async { final File buildScript = File( path.join(androidPath, 'app', 'build.gradle'), ); await buildScript.writeAsString((await buildScript.readAsString()).replaceAll('buildTypes', 'builTypes')); } Future<void> introducePubspecError() async { final File pubspec = File( path.join(parent.path, 'hello', 'pubspec.yaml') ); final String contents = pubspec.readAsStringSync(); final String newContents = contents.replaceFirst('${platformLineSep}flutter:$platformLineSep', ''' flutter: assets: - lib/gallery/example_code.dart '''); pubspec.writeAsStringSync(newContents); } Future<void> runGradleTask(String task, {List<String>? options}) async { return _runGradleTask(workingDirectory: androidPath, task: task, options: options); } Future<ProcessResult> resultOfGradleTask(String task, {List<String>? options}) { return _resultOfGradleTask(workingDirectory: androidPath, task: task, options: options); } Future<ProcessResult> resultOfFlutterCommand(String command, List<String> options) { return Process.run( path.join(flutterDirectory.path, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter'), <String>[command, ...options], workingDirectory: rootPath, ); } } class FlutterPluginProject { FlutterPluginProject(this.parent, this.name); final Directory parent; final String name; static Future<FlutterPluginProject> create(Directory directory, String name) async { await inDirectory(directory, () async { await flutter('create', options: <String>['--template=plugin', '--platforms=ios,android', name]); }); return FlutterPluginProject(directory, name); } String get rootPath => path.join(parent.path, name); String get examplePath => path.join(rootPath, 'example'); String get exampleAndroidPath => path.join(examplePath, 'android'); String get debugApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-debug.apk'); String get releaseApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-release.apk'); String get releaseArmApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk','app-armeabi-v7a-release.apk'); String get releaseArm64ApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-arm64-v8a-release.apk'); String get releaseBundlePath => path.join(examplePath, 'build', 'app', 'outputs', 'bundle', 'release', 'app.aab'); } class FlutterModuleProject { FlutterModuleProject(this.parent, this.name); final Directory parent; final String name; static Future<FlutterModuleProject> create(Directory directory, String name) async { await inDirectory(directory, () async { await flutter('create', options: <String>['--template=module', name]); }); return FlutterModuleProject(directory, name); } String get rootPath => path.join(parent.path, name); } Future<void> _runGradleTask({ required String workingDirectory, required String task, List<String>? options, }) async { final ProcessResult result = await _resultOfGradleTask( workingDirectory: workingDirectory, task: task, options: options); if (result.exitCode != 0) { print('stdout:'); print(result.stdout); print('stderr:'); print(result.stderr); } if (result.exitCode != 0) { throw 'Gradle exited with error'; } } Future<ProcessResult> _resultOfGradleTask({ required String workingDirectory, required String task, List<String>? options, }) async { section('Find Java'); final String? javaHome = await findJavaHome(); if (javaHome == null) { throw TaskResult.failure('Could not find Java'); } print('\nUsing JAVA_HOME=$javaHome'); final List<String> args = <String>[ 'app:$task', ...?options, ]; final String gradle = path.join(workingDirectory, Platform.isWindows ? 'gradlew.bat' : './gradlew'); print('β”Œβ”€β”€ $gradle'); print(File(path.join(workingDirectory, gradle)).readAsLinesSync().map((String line) => '| $line').join('\n')); print('└─────────────────────────────────────────────────────────────────────────────────────'); print( 'Running Gradle:\n' ' Executable: $gradle\n' ' Arguments: ${args.join(' ')}\n' ' Working directory: $workingDirectory\n' ' JAVA_HOME: $javaHome\n' ); return Process.run( gradle, args, workingDirectory: workingDirectory, environment: <String, String>{ 'JAVA_HOME': javaHome }, ); } /// Returns [null] if target matches [expectedTarget], otherwise returns an error message. String? validateSnapshotDependency(FlutterProject project, String expectedTarget) { final File snapshotBlob = File( path.join(project.rootPath, 'build', 'app', 'intermediates', 'flutter', 'debug', 'flutter_build.d')); assert(snapshotBlob.existsSync()); final String contentSnapshot = snapshotBlob.readAsStringSync(); return contentSnapshot.contains('$expectedTarget ') ? null : 'Dependency file should have $expectedTarget as target. Instead found $contentSnapshot'; }
flutter/dev/devicelab/lib/framework/apk_utils.dart/0
{ "file_path": "flutter/dev/devicelab/lib/framework/apk_utils.dart", "repo_id": "flutter", "token_count": 5243 }
506
// 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 '../framework/devices.dart'; import '../framework/framework.dart'; import '../framework/task_result.dart'; import '../framework/utils.dart'; const String _kOrgName = 'com.example.activitydestroy'; final RegExp _lifecycleSentinelRegExp = RegExp(r'==== lifecycle\: (.+) ===='); /// Tests the following Android lifecycles: Activity#onStop(), Activity#onResume(), Activity#onPause(), /// and Activity#onDestroy() from Dart perspective in debug, profile, and release modes. TaskFunction androidLifecyclesTest({ Map<String, String>? environment, }) { final Directory tempDir = Directory.systemTemp .createTempSync('flutter_devicelab_activity_destroy.'); return () async { try { section('Create app'); await inDirectory(tempDir, () async { await flutter( 'create', options: <String>[ '--platforms', 'android', '--org', _kOrgName, 'app', ], environment: environment, ); }); final File mainDart = File(path.join( tempDir.absolute.path, 'app', 'lib', 'main.dart', )); if (!mainDart.existsSync()) { return TaskResult.failure('${mainDart.path} does not exist'); } section('Patch lib/main.dart'); await mainDart.writeAsString(r''' import 'package:flutter/widgets.dart'; class LifecycleObserver extends WidgetsBindingObserver { @override void didChangeAppLifecycleState(AppLifecycleState state) { print('==== lifecycle: $state ===='); } } void main() { WidgetsFlutterBinding.ensureInitialized(); WidgetsBinding.instance.addObserver(LifecycleObserver()); runApp(Container()); } ''', flush: true); Future<TaskResult> runTestFor(String mode) async { final AndroidDevice device = await devices.workingDevice as AndroidDevice; await device.unlock(); section('Flutter run on device running API level ${device.apiLevel} (mode: $mode)'); late Process run; await inDirectory(path.join(tempDir.path, 'app'), () async { run = await startFlutter( 'run', options: <String>['--$mode'], ); }); final StreamController<String> lifecycles = StreamController<String>(); final StreamIterator<String> lifecycleItr = StreamIterator<String>(lifecycles.stream); final StreamSubscription<void> stdout = run.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String log) { final RegExpMatch? match = _lifecycleSentinelRegExp.firstMatch(log); print('stdout: $log'); if (match == null) { return; } final String lifecycle = match[1]!; print('stdout: Found app lifecycle: $lifecycle'); lifecycles.add(lifecycle); }); final StreamSubscription<void> stderr = run.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String log) { print('stderr: $log'); }); Future<void> expectedLifecycle(String expected) async { section('Wait for lifecycle: $expected (mode: $mode)'); await lifecycleItr.moveNext(); final String got = lifecycleItr.current; if (expected != got) { throw TaskResult.failure('expected lifecycles: `$expected`, but got` $got`'); } } await expectedLifecycle('AppLifecycleState.resumed'); section('Toggling app switch (mode: $mode)'); await device.shellExec('input', <String>['keyevent', 'KEYCODE_APP_SWITCH']); await expectedLifecycle('AppLifecycleState.inactive'); if (device.apiLevel == 28) { // Device lab currently runs 28. await expectedLifecycle('AppLifecycleState.paused'); await expectedLifecycle('AppLifecycleState.detached'); } section('Bring activity to foreground (mode: $mode)'); await device.shellExec('am', <String>['start', '-n', '$_kOrgName.app/.MainActivity']); await expectedLifecycle('AppLifecycleState.resumed'); section('Launch Settings app (mode: $mode)'); await device.shellExec('am', <String>['start', '-a', 'android.settings.SETTINGS']); await expectedLifecycle('AppLifecycleState.inactive'); if (device.apiLevel == 28) { // Device lab currently runs 28. await expectedLifecycle('AppLifecycleState.paused'); await expectedLifecycle('AppLifecycleState.detached'); } section('Bring activity to foreground (mode: $mode)'); await device.shellExec('am', <String>['start', '-n', '$_kOrgName.app/.MainActivity']); await expectedLifecycle('AppLifecycleState.resumed'); run.kill(); section('Stop subscriptions (mode: $mode)'); await lifecycleItr.cancel(); await lifecycles.close(); await stdout.cancel(); await stderr.cancel(); return TaskResult.success(null); } final TaskResult debugResult = await runTestFor('debug'); if (debugResult.failed) { return debugResult; } final TaskResult profileResult = await runTestFor('profile'); if (profileResult.failed) { return profileResult; } final TaskResult releaseResult = await runTestFor('release'); if (releaseResult.failed) { return releaseResult; } return TaskResult.success(null); } on TaskResult catch (error) { return error; } finally { rmTree(tempDir); } }; }
flutter/dev/devicelab/lib/tasks/android_lifecycles_test.dart/0
{ "file_path": "flutter/dev/devicelab/lib/tasks/android_lifecycles_test.dart", "repo_id": "flutter", "token_count": 2436 }
507
// 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:ffi'; import 'dart:io'; import '../framework/devices.dart'; import '../framework/framework.dart'; import '../framework/task_result.dart'; import '../framework/utils.dart'; TaskFunction createAndroidRunDebugTest() { return AndroidRunOutputTest(release: false).call; } TaskFunction createAndroidRunReleaseTest() { return AndroidRunOutputTest(release: true).call; } TaskFunction createLinuxRunDebugTest() { return DesktopRunOutputTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/empty.dart', release: false, ).call; } TaskFunction createLinuxRunReleaseTest() { return DesktopRunOutputTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/empty.dart', release: true, ).call; } TaskFunction createMacOSRunDebugTest() { return DesktopRunOutputTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/main.dart', release: false, allowStderr: true, ).call; } TaskFunction createMacOSRunReleaseTest() { return DesktopRunOutputTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/main.dart', release: true, allowStderr: true, ).call; } TaskFunction createWindowsRunDebugTest() { return WindowsRunOutputTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/empty.dart', release: false, ).call; } TaskFunction createWindowsRunReleaseTest() { return WindowsRunOutputTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/empty.dart', release: true, ).call; } class AndroidRunOutputTest extends RunOutputTask { AndroidRunOutputTest({required super.release}) : super( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/main.dart', ); @override Future<void> prepare(String deviceId) async { // Uninstall if the app is already installed on the device to get to a clean state. final List<String> stderr = <String>[]; print('uninstalling...'); final Process uninstall = await startFlutter( 'install', options: <String>['--suppress-analytics', '--uninstall-only', '-d', deviceId], isBot: false, ); uninstall.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { print('uninstall:stdout: $line'); }); uninstall.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { print('uninstall:stderr: $line'); stderr.add(line); }); if (await uninstall.exitCode != 0) { throw 'flutter install --uninstall-only failed.'; } if (stderr.isNotEmpty) { throw 'flutter install --uninstall-only had output on standard error.'; } } @override bool isExpectedStderr(String line) { // TODO(egarciad): Remove once https://github.com/flutter/flutter/issues/95131 is fixed. return line.contains('Mapping new ns'); } @override TaskResult verify(List<String> stdout, List<String> stderr) { final String gradleTask = release ? 'assembleRelease' : 'assembleDebug'; final String apk = release ? 'app-release.apk' : 'app-debug.apk'; _findNextMatcherInList( stdout, (String line) => line.startsWith('Launching lib/main.dart on ') && line.endsWith(' in ${release ? 'release' : 'debug'} mode...'), 'Launching lib/main.dart on', ); _findNextMatcherInList( stdout, (String line) => line.startsWith("Running Gradle task '$gradleTask'..."), "Running Gradle task '$gradleTask'...", ); // Size information is only included in release builds. _findNextMatcherInList( stdout, (String line) => line.contains('Built build/app/outputs/flutter-apk/$apk') && (!release || line.contains('MB).')), 'Built build/app/outputs/flutter-apk/$apk', ); _findNextMatcherInList( stdout, (String line) => line.startsWith('Installing build/app/outputs/flutter-apk/$apk...'), 'Installing build/app/outputs/flutter-apk/$apk...', ); _findNextMatcherInList( stdout, (String line) => line.contains('Quit (terminate the application on the device).'), 'q Quit (terminate the application on the device)', ); _findNextMatcherInList( stdout, (String line) => line == 'Application finished.', 'Application finished.', ); return TaskResult.success(null); } } class WindowsRunOutputTest extends DesktopRunOutputTest { WindowsRunOutputTest( super.testDirectory, super.testTarget, { required super.release, super.allowStderr = false, } ); final String arch = Abi.current() == Abi.windowsX64 ? 'x64': 'arm64'; static final RegExp _buildOutput = RegExp( r'Building Windows application\.\.\.\s*\d+(\.\d+)?(ms|s)', multiLine: true, ); static final RegExp _builtOutput = RegExp( r'Built build\\windows\\(x64|arm64)\\runner\\(Debug|Release)\\\w+\.exe( \(\d+(\.\d+)?MB\))?\.', ); @override void verifyBuildOutput(List<String> stdout) { _findNextMatcherInList( stdout, _buildOutput.hasMatch, 'Building Windows application...', ); final String buildMode = release ? 'Release' : 'Debug'; _findNextMatcherInList( stdout, (String line) { if (!_builtOutput.hasMatch(line) || !line.contains(buildMode)) { return false; } // Size information is only included in release builds. final bool hasSize = line.contains('MB).'); if (release != hasSize) { return false; } return true; }, 'Built build\\windows\\$arch\\runner\\$buildMode\\app.exe', ); } } class DesktopRunOutputTest extends RunOutputTask { DesktopRunOutputTest( super.testDirectory, super.testTarget, { required super.release, this.allowStderr = false, } ); /// Whether `flutter run` is expected to produce output on stderr. final bool allowStderr; @override bool isExpectedStderr(String line) => allowStderr; @override TaskResult verify(List<String> stdout, List<String> stderr) { _findNextMatcherInList( stdout, (String line) => line.startsWith('Launching $testTarget on ') && line.endsWith(' in ${release ? 'release' : 'debug'} mode...'), 'Launching $testTarget on', ); verifyBuildOutput(stdout); _findNextMatcherInList( stdout, (String line) => line.contains('Quit (terminate the application on the device).'), 'q Quit (terminate the application on the device)', ); _findNextMatcherInList( stdout, (String line) => line == 'Application finished.', 'Application finished.', ); return TaskResult.success(null); } /// Verify the output from `flutter run`'s build step. void verifyBuildOutput(List<String> stdout) {} } /// Test that the output of `flutter run` is expected. abstract class RunOutputTask { RunOutputTask( this.testDirectory, this.testTarget, { required this.release, } ); static final RegExp _engineLogRegex = RegExp( r'\[(VERBOSE|INFO|WARNING|ERROR|FATAL):.+\(\d+\)\]', ); /// The directory where the app under test is defined. final String testDirectory; /// The main entry-point file of the application, as run on the device. final String testTarget; /// Whether to run the app in release mode. final bool release; Future<TaskResult> call() { return inDirectory<TaskResult>(testDirectory, () async { final Device device = await devices.workingDevice; await device.unlock(); final String deviceId = device.deviceId; final Completer<void> ready = Completer<void>(); final List<String> stdout = <String>[]; final List<String> stderr = <String>[]; await prepare(deviceId); final List<String> options = <String>[ testTarget, '-d', deviceId, if (release) '--release', ]; final Process run = await startFlutter( 'run', options: options, isBot: false, ); int? runExitCode; run.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { print('run:stdout: $line'); stdout.add(line); if (line.contains('Quit (terminate the application on the device).')) { ready.complete(); } }); final Stream<String> runStderr = run.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .asBroadcastStream(); runStderr.listen((String line) => print('run:stderr: $line')); runStderr .skipWhile(isExpectedStderr) .listen((String line) => stderr.add(line)); unawaited(run.exitCode.then<void>((int exitCode) { runExitCode = exitCode; })); await Future.any<dynamic>(<Future<dynamic>>[ ready.future, run.exitCode ]); if (runExitCode != null) { throw 'Failed to run test app; runner unexpected exited, with exit code $runExitCode.'; } run.stdin.write('q'); await run.exitCode; if (stderr.isNotEmpty) { throw 'flutter run ${release ? '--release' : ''} had unexpected output on standard error.'; } final List<String> engineLogs = List<String>.from( stdout.where(_engineLogRegex.hasMatch), ); if (engineLogs.isNotEmpty) { throw 'flutter run had unexpected Flutter engine logs $engineLogs'; } return verify(stdout, stderr); }); } /// Prepare the device for running the test app. Future<void> prepare(String deviceId) => Future<void>.value(); /// Returns true if this stderr output line is expected. bool isExpectedStderr(String line) => false; /// Verify the output of `flutter run`. TaskResult verify(List<String> stdout, List<String> stderr) => throw UnimplementedError('verify is not implemented'); /// Helper that verifies a line in [list] matches [matcher]. /// The [list] is updated to contain the lines remaining after the match. void _findNextMatcherInList( List<String> list, bool Function(String testLine) matcher, String errorMessageExpectedLine ) { final List<String> copyOfListForErrorMessage = List<String>.from(list); while (list.isNotEmpty) { final String nextLine = list.first; list.removeAt(0); if (matcher(nextLine)) { return; } } throw ''' Did not find expected line $errorMessageExpectedLine in flutter run ${release ? '--release' : ''} stdout $copyOfListForErrorMessage '''; } }
flutter/dev/devicelab/lib/tasks/run_tests.dart/0
{ "file_path": "flutter/dev/devicelab/lib/tasks/run_tests.dart", "repo_id": "flutter", "token_count": 4172 }
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_devicelab/framework/task_result.dart'; import 'common.dart'; void main() { group('TaskResult fromJson', () { test('succeeded', () { final Map<String, dynamic> expectedJson = <String, dynamic>{ 'success': true, 'data': <String, dynamic>{ 'i': 5, 'j': 10, 'not_a_metric': 'something', }, 'benchmarkScoreKeys': <String>['i', 'j'], 'detailFiles': <String>[], }; final TaskResult result = TaskResult.fromJson(expectedJson); expect(result.toJson(), expectedJson); }); test('succeeded with empty data', () { final TaskResult result = TaskResult.fromJson(<String, dynamic>{ 'success': true, }); final Map<String, dynamic> expectedJson = <String, dynamic>{ 'success': true, 'data': null, 'benchmarkScoreKeys': <String>[], 'detailFiles': <String>[], }; expect(result.toJson(), expectedJson); }); test('failed', () { final Map<String, dynamic> expectedJson = <String, dynamic>{ 'success': false, 'reason': 'failure message', }; final TaskResult result = TaskResult.fromJson(expectedJson); expect(result.toJson(), expectedJson); }); }); }
flutter/dev/devicelab/test/task_result_test.dart/0
{ "file_path": "flutter/dev/devicelab/test/task_result_test.dart", "repo_id": "flutter", "token_count": 601 }
509
{ "rules": "firebase_rules.json", "hosting": { "public": "doc", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "headers": [ { "source": "snippets/**.dart", "headers": [ { "key": "Access-Control-Allow-Origin", "value": "*" } ] } ] } }
flutter/dev/docs/firebase.json/0
{ "file_path": "flutter/dev/docs/firebase.json", "repo_id": "flutter", "token_count": 219 }
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. import 'dart:convert'; import 'dart:io'; import 'package:args/args.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as path; import 'package:vm_snapshot_analysis/program_info.dart'; import 'package:vm_snapshot_analysis/v8_profile.dart'; const FileSystem fs = LocalFileSystem(); Future<void> main(List<String> args) async { final Options options = Options.fromArgs(args); final String json = options.snapshot.readAsStringSync(); final Snapshot snapshot = Snapshot.fromJson(jsonDecode(json) as Map<String, dynamic>); final ProgramInfo programInfo = toProgramInfo(snapshot); final List<String> foundForbiddenTypes = <String>[]; bool fail = false; for (final String forbiddenType in options.forbiddenTypes) { final int slash = forbiddenType.indexOf('/'); final int doubleColons = forbiddenType.indexOf('::'); if (slash == -1 || doubleColons < 2) { print('Invalid forbidden type "$forbiddenType". The format must be <package_uri>::<type_name>, e.g. package:flutter/src/widgets/framework.dart::Widget'); fail = true; continue; } if (!await validateType(forbiddenType, options.packageConfig)) { foundForbiddenTypes.add('Forbidden type "$forbiddenType" does not seem to exist.'); continue; } final List<String> lookupPath = <String>[ forbiddenType.substring(0, slash), forbiddenType.substring(0, doubleColons), forbiddenType.substring(doubleColons + 2), ]; if (programInfo.lookup(lookupPath) != null) { foundForbiddenTypes.add(forbiddenType); } } if (fail) { print('Invalid forbidden type formats. Exiting.'); exit(-1); } if (foundForbiddenTypes.isNotEmpty) { print('The output contained the following forbidden types:'); print(foundForbiddenTypes.join('\n')); exit(-1); } print('No forbidden types found.'); } Future<bool> validateType(String forbiddenType, File packageConfigFile) async { if (!forbiddenType.startsWith('package:')) { print('Warning: Unable to validate $forbiddenType. Continuing.'); return true; } final Uri packageUri = Uri.parse(forbiddenType.substring(0, forbiddenType.indexOf('::'))); final String typeName = forbiddenType.substring(forbiddenType.indexOf('::') + 2); final PackageConfig packageConfig = PackageConfig.parseString( packageConfigFile.readAsStringSync(), packageConfigFile.uri, ); final Uri? packageFileUri = packageConfig.resolve(packageUri); final File packageFile = fs.file(packageFileUri); if (!packageFile.existsSync()) { print('File $packageFile does not exist - forbidden type has moved or been removed.'); return false; } // This logic is imperfect. It will not detect mixed in types the way that // the snapshot has them, e.g. TypeName&MixedIn&Whatever. It also assumes // there is at least one space before and after the type name, which is not // strictly required by the language. final List<String> contents = packageFile.readAsStringSync().split('\n'); for (final String line in contents) { // Ignore comments. // This will fail for multi- and intra-line comments (i.e. /* */). if (line.trim().startsWith('//')) { continue; } if (line.contains(' $typeName ')) { return true; } } return false; } class Options { const Options({ required this.snapshot, required this.packageConfig, required this.forbiddenTypes, }); factory Options.fromArgs(List<String> args) { final ArgParser argParser = ArgParser(); argParser.addOption( 'snapshot', help: 'The path V8 snapshot file.', valueHelp: '/tmp/snapshot.arm64-v8a.json', ); argParser.addOption( 'package-config', help: 'Dart package_config.json file generated by `pub get`.', valueHelp: path.join(r'$FLUTTER_ROOT', 'examples', 'hello_world', '.dart_tool', 'package_config.json'), defaultsTo: path.join(fs.currentDirectory.path, 'examples', 'hello_world', '.dart_tool', 'package_config.json'), ); argParser.addMultiOption( 'forbidden-type', help: 'Type name(s) to forbid from release compilation, e.g. "package:flutter/src/widgets/framework.dart::Widget".', valueHelp: '<package_uri>::<type_name>', ); argParser.addFlag('help', help: 'Prints usage.', negatable: false); final ArgResults argResults = argParser.parse(args); if (argResults['help'] == true) { print(argParser.usage); exit(0); } return Options( snapshot: _getFileArg(argResults, 'snapshot'), packageConfig: _getFileArg(argResults, 'package-config'), forbiddenTypes: Set<String>.from(argResults['forbidden-type'] as List<String>), ); } final File snapshot; final File packageConfig; final Set<String> forbiddenTypes; static File _getFileArg(ArgResults argResults, String argName) { final File result = fs.file(argResults[argName] as String); if (!result.existsSync()) { print('The $argName file at $result could not be found.'); exit(-1); } return result; } }
flutter/dev/forbidden_from_release_tests/bin/main.dart/0
{ "file_path": "flutter/dev/forbidden_from_release_tests/bin/main.dart", "repo_id": "flutter", "token_count": 1828 }
511