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/typed_data/dart_byte_data.h"
#include <cstring>
#include "tonic/logging/dart_error.h"
namespace tonic {
namespace {
void FreeFinalizer(void* isolate_callback_data, void* peer) {
free(peer);
}
} // anonymous namespace
// For large objects it is more efficient to use an external typed data object
// with a buffer allocated outside the Dart heap.
const size_t DartByteData::kExternalSizeThreshold = 1000;
Dart_Handle DartByteData::Create(const void* data, size_t length) {
if (length < kExternalSizeThreshold) {
auto handle = DartByteData{data, length}.dart_handle();
// The destructor should release the typed data.
return handle;
} else {
void* buf = ::malloc(length);
TONIC_DCHECK(buf);
::memcpy(buf, data, length);
return Dart_NewExternalTypedDataWithFinalizer(
Dart_TypedData_kByteData, buf, length, buf, length, FreeFinalizer);
}
}
DartByteData::DartByteData()
: data_(nullptr), length_in_bytes_(0), dart_handle_(nullptr) {}
DartByteData::DartByteData(const void* data, size_t length)
: data_(nullptr),
length_in_bytes_(0),
dart_handle_(Dart_NewTypedData(Dart_TypedData_kByteData, length)) {
if (!Dart_IsError(dart_handle_)) {
Dart_TypedData_Type type;
auto acquire_result = Dart_TypedDataAcquireData(dart_handle_, &type, &data_,
&length_in_bytes_);
if (!Dart_IsError(acquire_result)) {
::memcpy(data_, data, length_in_bytes_);
}
}
}
DartByteData::DartByteData(Dart_Handle list)
: data_(nullptr), length_in_bytes_(0), dart_handle_(list) {
if (Dart_IsNull(list))
return;
Dart_TypedData_Type type;
Dart_TypedDataAcquireData(list, &type, &data_, &length_in_bytes_);
TONIC_DCHECK(!CheckAndHandleError(list));
if (type != Dart_TypedData_kByteData)
Dart_ThrowException(ToDart("Non-genuine ByteData passed to engine."));
}
DartByteData::DartByteData(DartByteData&& other)
: data_(other.data_),
length_in_bytes_(other.length_in_bytes_),
dart_handle_(other.dart_handle_) {
other.data_ = nullptr;
other.dart_handle_ = nullptr;
}
DartByteData::~DartByteData() {
Release();
}
std::vector<char> DartByteData::Copy() const {
const char* ptr = static_cast<const char*>(data_);
return std::vector<char>(ptr, ptr + length_in_bytes_);
}
void DartByteData::Release() const {
if (data_) {
Dart_TypedDataReleaseData(dart_handle_);
data_ = nullptr;
}
}
DartByteData DartConverter<DartByteData>::FromArguments(
Dart_NativeArguments args,
int index,
Dart_Handle& exception) {
Dart_Handle data = Dart_GetNativeArgument(args, index);
TONIC_DCHECK(!CheckAndHandleError(data));
return DartByteData(data);
}
void DartConverter<DartByteData>::SetReturnValue(Dart_NativeArguments args,
DartByteData val) {
Dart_SetReturnValue(args, val.dart_handle());
}
} // namespace tonic
| engine/third_party/tonic/typed_data/dart_byte_data.cc/0 | {
"file_path": "engine/third_party/tonic/typed_data/dart_byte_data.cc",
"repo_id": "engine",
"token_count": 1231
} | 425 |
/*
* Copyright 2019 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_PARAGRAPH_BUILDER_SKIA_H_
#define LIB_TXT_SRC_PARAGRAPH_BUILDER_SKIA_H_
#include "txt/paragraph_builder.h"
#include "flutter/display_list/dl_paint.h"
#include "third_party/skia/modules/skparagraph/include/ParagraphBuilder.h"
namespace txt {
//------------------------------------------------------------------------------
/// @brief ParagraphBuilder implementation using Skia's text layout module.
///
/// @note Despite the suffix "Skia", this class is not specific to Skia
/// and is also used with the Impeller backend.
class ParagraphBuilderSkia : public ParagraphBuilder {
public:
ParagraphBuilderSkia(const ParagraphStyle& style,
std::shared_ptr<FontCollection> font_collection,
const bool impeller_enabled);
virtual ~ParagraphBuilderSkia();
virtual void PushStyle(const TextStyle& style) override;
virtual void Pop() override;
virtual const TextStyle& PeekStyle() override;
virtual void AddText(const std::u16string& text) override;
virtual void AddPlaceholder(PlaceholderRun& span) override;
virtual std::unique_ptr<Paragraph> Build() override;
private:
friend class SkiaParagraphBuilderTests_ParagraphStrutStyle_Test;
skia::textlayout::ParagraphPainter::PaintID CreatePaintID(
const flutter::DlPaint& dl_paint);
skia::textlayout::ParagraphStyle TxtToSkia(const ParagraphStyle& txt);
skia::textlayout::TextStyle TxtToSkia(const TextStyle& txt);
std::shared_ptr<skia::textlayout::ParagraphBuilder> builder_;
TextStyle base_style_;
/// @brief Whether Impeller is enabled in the runtime.
///
/// @note As of the time of this writing, this is used to draw text
/// decorations (i.e. dashed and dotted lines) directly using the
/// `drawLine` API, because Impeller's path rendering does not
/// support dashed and dotted lines (but Skia's does).
const bool impeller_enabled_;
std::stack<TextStyle> txt_style_stack_;
std::vector<flutter::DlPaint> dl_paints_;
};
} // namespace txt
#endif // LIB_TXT_SRC_PARAGRAPH_BUILDER_SKIA_H_
| engine/third_party/txt/src/skia/paragraph_builder_skia.h/0 | {
"file_path": "engine/third_party/txt/src/skia/paragraph_builder_skia.h",
"repo_id": "engine",
"token_count": 906
} | 426 |
/*
* 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_PARAGRAPH_BUILDER_H_
#define LIB_TXT_SRC_PARAGRAPH_BUILDER_H_
#include <memory>
#include <string>
#include "flutter/fml/macros.h"
#include "font_collection.h"
#include "paragraph.h"
#include "paragraph_style.h"
#include "placeholder_run.h"
#include "text_style.h"
namespace txt {
class ParagraphBuilder {
public:
static std::unique_ptr<ParagraphBuilder> CreateSkiaBuilder(
const ParagraphStyle& style,
std::shared_ptr<FontCollection> font_collection,
const bool impeller_enabled);
virtual ~ParagraphBuilder() = default;
// Push a style to the stack. The corresponding text added with AddText will
// use the top-most style.
virtual void PushStyle(const TextStyle& style) = 0;
// Remove a style from the stack. Useful to apply different styles to chunks
// of text such as bolding.
// Example:
// builder.PushStyle(normal_style);
// builder.AddText("Hello this is normal. ");
//
// builder.PushStyle(bold_style);
// builder.AddText("And this is BOLD. ");
//
// builder.Pop();
// builder.AddText(" Back to normal again.");
virtual void Pop() = 0;
// Returns the last TextStyle on the stack.
virtual const TextStyle& PeekStyle() = 0;
// Adds text to the builder. Forms the proper runs to use the upper-most style
// on the style_stack_;
virtual void AddText(const std::u16string& text) = 0;
// Pushes the information required to leave an open space, where Flutter may
// draw a custom placeholder into.
//
// Internally, this method adds a single object replacement character (0xFFFC)
// and emplaces a new PlaceholderRun instance to the vector of inline
// placeholders.
virtual void AddPlaceholder(PlaceholderRun& span) = 0;
// Constructs a Paragraph object that can be used to layout and paint the text
// to a SkCanvas.
virtual std::unique_ptr<Paragraph> Build() = 0;
protected:
ParagraphBuilder() = default;
private:
FML_DISALLOW_COPY_AND_ASSIGN(ParagraphBuilder);
};
} // namespace txt
#endif // LIB_TXT_SRC_PARAGRAPH_BUILDER_H_
| engine/third_party/txt/src/txt/paragraph_builder.h/0 | {
"file_path": "engine/third_party/txt/src/txt/paragraph_builder.h",
"repo_id": "engine",
"token_count": 829
} | 427 |
//---------------------------------------------------------------------------------------------
// Copyright (c) 2022 Google LLC
// Licensed under the MIT License. See License.txt in the project root for license information.
//--------------------------------------------------------------------------------------------*/
import 'package:test/test.dart';
import 'package:web_locale_keymap/web_locale_keymap.dart';
final int _kLowerA = 'a'.codeUnitAt(0);
final int _kUpperA = 'A'.codeUnitAt(0);
final int _kLowerZ = 'z'.codeUnitAt(0);
final int _kUpperZ = 'Z'.codeUnitAt(0);
bool _isLetter(String char) {
if (char.length != 1) {
return false;
}
final int charCode = char.codeUnitAt(0);
return (charCode >= _kLowerA && charCode <= _kLowerZ)
|| (charCode >= _kUpperA && charCode <= _kUpperZ);
}
String _fromCharCode(int? logicalKey) {
if (logicalKey == null) {
return '';
}
return String.fromCharCode(logicalKey);
}
void verifyEntry(LocaleKeymap mapping, String eventCode, List<String> eventKeys, String mappedResult) {
// If the first two entry of KeyboardEvent.key are letter keys such as "a" and
// "A", then KeyboardEvent.keyCode is the upper letter such as "A". Otherwise,
// this field must not be used (in reality this field may or may not be
// platform independent).
int? eventKeyCode;
{
if (_isLetter(eventKeys[0]) && _isLetter(eventKeys[1])) {
eventKeyCode = eventKeys[0].toLowerCase().codeUnitAt(0);
}
}
int index = 0;
for (final String eventKey in eventKeys) {
if (eventKey.isEmpty) {
continue;
}
test('$eventCode $index', () {
expect(
_fromCharCode(mapping.getLogicalKey(eventCode, eventKey, eventKeyCode ?? 0)),
mappedResult,
);
});
index += 1;
}
}
| engine/third_party/web_locale_keymap/test/testing.dart/0 | {
"file_path": "engine/third_party/web_locale_keymap/test/testing.dart",
"repo_id": "engine",
"token_count": 600
} | 428 |
// 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';
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
/// "Downloads" (i.e. decodes base64 encoded strings) goldens from buildbucket.
///
/// See ../README.md for motivation and usage.
final class BuildBucketGoldenScraper {
/// Creates a scraper with the given configuration.
BuildBucketGoldenScraper({
required this.pathOrUrl,
this.dryRun = false,
String? engineSrcPath,
StringSink? outSink,
}) :
engine = engineSrcPath != null ?
Engine.fromSrcPath(engineSrcPath) :
Engine.findWithin(p.dirname(p.fromUri(io.Platform.script))),
_outSink = outSink ?? io.stdout;
/// Creates a scraper from the command line arguments.
///
/// Throws [FormatException] if the arguments are invalid.
factory BuildBucketGoldenScraper.fromCommandLine(
List<String> args, {
StringSink? outSink,
StringSink? errSink,
}) {
outSink ??= io.stdout;
errSink ??= io.stderr;
final ArgResults argResults = _argParser.parse(args);
if (argResults['help'] as bool) {
_usage(args);
}
final String? pathOrUrl = argResults.rest.isEmpty ? null : argResults.rest.first;
if (pathOrUrl == null) {
_usage(args);
}
return BuildBucketGoldenScraper(
pathOrUrl: pathOrUrl,
dryRun: argResults['dry-run'] as bool,
outSink: outSink,
engineSrcPath: argResults['engine-src-path'] as String?,
);
}
static Never _usage(List<String> args) {
final StringBuffer output = StringBuffer();
output.writeln('Usage: build_bucket_golden_scraper [options] <path or URL>');
output.writeln();
output.writeln(_argParser.usage);
throw FormatException(output.toString(), args.join(' '));
}
static final ArgParser _argParser = ArgParser()
..addFlag(
'help',
abbr: 'h',
help: 'Print this help message.',
negatable: false,
)
..addFlag(
'dry-run',
help: "If true, don't write any files to disk (other than temporary files).",
negatable: false,
)
..addOption(
'engine-src-path',
help: 'The path to the engine source code.',
valueHelp: 'path/that/contains/src (defaults to the directory containing this script)',
);
/// A local path or a URL to a buildbucket log file.
final String pathOrUrl;
/// If true, don't write any files to disk (other than temporary files).
final bool dryRun;
/// The path to the engine source code.
final Engine engine;
/// How to print output, typically [io.stdout].
final StringSink _outSink;
/// Runs the scraper.
Future<int> run() async {
// If the path is a URL, download it and store it in a temporary file.
final Uri? maybeUri = Uri.tryParse(pathOrUrl);
if (maybeUri == null) {
throw FormatException('Invalid path or URL: $pathOrUrl');
}
final String contents;
if (maybeUri.hasScheme) {
contents = await _downloadFile(maybeUri);
} else {
final io.File readFile = io.File(pathOrUrl);
if (!readFile.existsSync()) {
throw FormatException('File does not exist: $pathOrUrl');
}
contents = readFile.readAsStringSync();
}
// Check that it is a buildbucket log file.
if (!contents.contains(_buildBucketMagicString)) {
throw FormatException('Not a buildbucket log file: $pathOrUrl');
}
// Check for occurences of a base64 encoded string.
//
// The format looks something like this:
// [LINE N+0]: See also the base64 encoded /b/s/w/ir/cache/builder/src/flutter/testing/resources/performance_overlay_gold_120fps_new.png:
// [LINE N+1]: {{BASE_64_ENCODED_IMAGE}}
//
// We want to extract the file name (relative to the engine root) and then
// decode the base64 encoded string (and write it to disk if we are not in
// dry-run mode).
final List<_Golden> goldens = <_Golden>[];
final List<String> lines = contents.split('\n');
for (int i = 0; i < lines.length; i++) {
final String line = lines[i];
if (line.startsWith(_base64MagicString)) {
final String relativePath = line.split(_buildBucketMagicString).last.split(':').first;
// Remove the _new suffix from the file name.
final String pathWithouNew = relativePath.replaceAll('_new', '');
final String base64EncodedString = lines[i + 1];
final List<int> bytes = base64Decode(base64EncodedString);
final io.File outFile = io.File(p.join(engine.srcDir.path, pathWithouNew));
goldens.add(_Golden(outFile, bytes));
}
}
if (goldens.isEmpty) {
_outSink.writeln('No goldens found.');
return 0;
}
// Sort and de-duplicate the goldens.
goldens.sort();
final Set<_Golden> uniqueGoldens = goldens.toSet();
// Write the goldens to disk (or pretend to in dry-run mode).
_outSink.writeln('${dryRun ? 'Found' : 'Wrote'} ${uniqueGoldens.length} golden file changes:');
for (final _Golden golden in uniqueGoldens) {
final String truncatedPathAfterFlutterDir = golden.outFile.path.split('flutter${p.separator}').last;
_outSink.writeln(' $truncatedPathAfterFlutterDir');
if (!dryRun) {
await golden.outFile.writeAsBytes(golden.bytes);
}
}
if (dryRun) {
_outSink.writeln('Run again without --dry-run to apply these changes.');
}
return 0;
}
static const String _buildBucketMagicString = '/b/s/w/ir/cache/builder/src/';
static const String _base64MagicString = 'See also the base64 encoded $_buildBucketMagicString';
static Future<String> _downloadFile(Uri uri) async {
final io.HttpClient client = io.HttpClient();
final io.HttpClientRequest request = await client.getUrl(uri);
final io.HttpClientResponse response = await request.close();
final StringBuffer contents = StringBuffer();
await response.transform(utf8.decoder).forEach(contents.write);
client.close();
return contents.toString();
}
}
@immutable
final class _Golden implements Comparable<_Golden> {
const _Golden(this.outFile, this.bytes);
/// Where to write the golden file.
final io.File outFile;
/// The bytes of the golden file to write.
final List<int> bytes;
@override
int get hashCode => outFile.path.hashCode;
@override
bool operator ==(Object other) {
return other is _Golden && other.outFile.path == outFile.path;
}
@override
int compareTo(_Golden other) {
return outFile.path.compareTo(other.outFile.path);
}
}
| engine/tools/build_bucket_golden_scraper/lib/build_bucket_golden_scraper.dart/0 | {
"file_path": "engine/tools/build_bucket_golden_scraper/lib/build_bucket_golden_scraper.dart",
"repo_id": "engine",
"token_count": 2478
} | 429 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io show Directory, File, Platform, stderr;
import 'package:args/args.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart' as path;
import 'lint_target.dart';
final Engine _engineRoot = Engine.findWithin(path.dirname(path.fromUri(io.Platform.script)));
/// Adds warnings as errors for only specific runs. This is helpful if migrating one platform at a time.
String? _platformSpecificWarningsAsErrors(ArgResults options) {
if (options['target-variant'] == 'host_debug' && io.Platform.isMacOS) {
return options['mac-host-warnings-as-errors'] as String?;
}
return null;
}
/// A class for organizing the options to the Engine linter, and the files
/// that it operates on.
class Options {
/// Builds an instance of [Options] from the arguments.
Options({
required this.buildCommandsPath,
this.help = false,
this.verbose = false,
this.checksArg = '',
this.lintTarget = const LintChanged(),
this.fix = false,
this.errorMessage,
this.warningsAsErrors,
this.shardId,
this.shardCommandsPaths = const <io.File>[],
this.enableCheckProfile = false,
StringSink? errSink,
this.clangTidyPath,
}) : checks = checksArg.isNotEmpty ? '--checks=$checksArg' : null,
_errSink = errSink ?? io.stderr;
factory Options._error(
String message, {
StringSink? errSink,
}) {
return Options(
errorMessage: message,
buildCommandsPath: io.File('none'),
errSink: errSink,
);
}
factory Options._help({
StringSink? errSink,
}) {
return Options(
help: true,
buildCommandsPath: io.File('none'),
errSink: errSink,
);
}
/// Builds an [Options] instance with an [ArgResults] instance.
factory Options._fromArgResults(
ArgResults options, {
required io.File buildCommandsPath,
StringSink? errSink,
required List<io.File> shardCommandsPaths,
int? shardId,
io.File? clangTidyPath,
}) {
final LintTarget lintTarget;
if (options.wasParsed('lint-all') || io.Platform.environment['FLUTTER_LINT_ALL'] != null) {
lintTarget = const LintAll();
} else if (options.wasParsed('lint-regex')) {
lintTarget = LintRegex(options['lint-regex'] as String? ?? '');
} else if (options.wasParsed('lint-head')) {
lintTarget = const LintHead();
} else {
lintTarget = const LintChanged();
}
return Options(
help: options['help'] as bool,
verbose: options['verbose'] as bool,
buildCommandsPath: buildCommandsPath,
checksArg: options.wasParsed('checks') ? options['checks'] as String : '',
lintTarget: lintTarget,
fix: options['fix'] as bool,
errSink: errSink,
warningsAsErrors: _platformSpecificWarningsAsErrors(options),
shardCommandsPaths: shardCommandsPaths,
shardId: shardId,
enableCheckProfile: options['enable-check-profile'] as bool,
clangTidyPath: clangTidyPath,
);
}
/// Builds an instance of [Options] from the given `arguments`.
factory Options.fromCommandLine(
List<String> arguments, {
StringSink? errSink,
Engine? engine,
}) {
// TODO(matanlurey): Refactor this further, ideally moving all of the engine
// resolution logic (i.e. --src-dir, --target-variant, --compile-commands)
// into a separate method, and perhaps also adding `engine.output(name)`
// to engine_repo_tools instead of path manipulation inlined below.
final ArgResults argResults = _argParser(defaultEngine: engine).parse(arguments);
String? buildCommandsPath = argResults['compile-commands'] as String?;
String variantToBuildCommandsFilePath(String variant) =>
path.join(
argResults['src-dir'] as String,
'out',
variant,
'compile_commands.json',
);
// path/to/engine/src/out/variant/compile_commands.json
buildCommandsPath ??= variantToBuildCommandsFilePath(argResults['target-variant'] as String);
final io.File buildCommands = io.File(buildCommandsPath);
final List<io.File> shardCommands =
(argResults['shard-variants'] as String? ?? '')
.split(',')
.where((String element) => element.isNotEmpty)
.map((String variant) =>
io.File(variantToBuildCommandsFilePath(variant)))
.toList();
final String? message = _checkArguments(argResults, buildCommands);
if (message != null) {
return Options._error(message, errSink: errSink);
}
if (argResults['help'] as bool) {
return Options._help(errSink: errSink);
}
final String? shardIdString = argResults['shard-id'] as String?;
final int? shardId = shardIdString == null ? null : int.parse(shardIdString);
if (shardId != null && (shardId > shardCommands.length || shardId < 0)) {
return Options._error('Invalid shard-id value: $shardId.', errSink: errSink);
}
final io.File? clangTidyPath = ((String? path) => path == null
? null
: io.File(path))(argResults['clang-tidy'] as String?);
return Options._fromArgResults(
argResults,
buildCommandsPath: buildCommands,
errSink: errSink,
shardCommandsPaths: shardCommands,
shardId: shardId,
clangTidyPath: clangTidyPath,
);
}
static ArgParser _argParser({required Engine? defaultEngine}) {
defaultEngine ??= _engineRoot;
final io.Directory? latestBuild = defaultEngine.latestOutput()?.path;
return ArgParser()
..addFlag(
'help',
abbr: 'h',
help: 'Print help.',
negatable: false,
)
..addOption(
'lint-regex',
help: 'Lint all files, regardless of FLUTTER_NOLINT. Provide a regex '
'to filter files. For example, `--lint-regex=".*impeller.*"` will '
'lint all files within a path that contains "impeller".',
valueHelp: 'regex',
)
..addFlag(
'lint-all',
help: 'Lint all files, regardless of FLUTTER_NOLINT.',
)
..addFlag(
'lint-head',
help: 'Lint files changed in the tip-of-tree commit.',
)
..addFlag(
'fix',
help: 'Apply suggested fixes.',
)
..addFlag(
'verbose',
help: 'Print verbose output.',
)
..addOption(
'shard-id',
help: 'When used with the shard-commands option this identifies which shard will execute.',
valueHelp: 'A number less than 1 + the number of shard-commands arguments.',
)
..addOption(
'shard-variants',
help: 'Comma separated list of other targets, this invocation '
'will only execute a subset of the intersection and the difference of the '
'compile commands. Use with `shard-id`.'
)
..addOption(
'compile-commands',
help: 'Use the given path as the source of compile_commands.json. This '
'file is created by running "tools/gn". Cannot be used with --target-variant '
'or --src-dir.',
)
..addOption(
'target-variant',
aliases: <String>['variant'],
help: 'The engine variant directory name containing compile_commands.json '
'created by running "tools/gn".\n\nIf not provided, the default is '
'the latest build in the engine defined by --src-dir (or the '
'default path, see --src-dir for details).\n\n'
'Cannot be used with --compile-commands.',
valueHelp: 'host_debug|android_debug_unopt|ios_debug|ios_debug_sim_unopt',
defaultsTo: latestBuild == null ? 'host_debug' : path.basename(latestBuild.path),
)
..addOption('mac-host-warnings-as-errors',
help:
'checks that will be treated as errors when running debug_host on mac.')
..addOption(
'src-dir',
help:
'Path to the engine src directory.\n\n'
'If not provided, the default is the engine root directory that '
'contains the `clang_tidy` tool.\n\n'
'Cannot be used with --compile-commands.',
valueHelp: 'path/to/engine/src',
defaultsTo: _engineRoot.srcDir.path,
)
..addOption(
'checks',
help: 'Perform the given checks on the code. Defaults to the empty '
'string, indicating all checks should be performed.',
defaultsTo: '',
)
..addOption('clang-tidy',
help:
'Path to the clang-tidy executable. Defaults to deriving the path\n'
'from compile_commands.json.')
..addFlag(
'enable-check-profile',
help: 'Enable per-check timing profiles and print a report to stderr.',
negatable: false,
);
}
/// Whether to print a help message and exit.
final bool help;
/// Whether to run with verbose output.
final bool verbose;
/// The location of the compile_commands.json file.
final io.File buildCommandsPath;
/// The location of shard compile_commands.json files.
final List<io.File> shardCommandsPaths;
/// The identifier of the shard.
final int? shardId;
/// The root of the flutter/engine repository.
final io.Directory repoPath = _engineRoot.flutterDir;
/// Argument sent as `warnings-as-errors` to clang-tidy.
final String? warningsAsErrors;
/// Checks argument as supplied to the command-line.
final String checksArg;
/// Check argument to be supplied to the clang-tidy subprocess.
final String? checks;
/// What files to lint.
final LintTarget lintTarget;
/// Whether checks should apply available fix-ups to the working copy.
final bool fix;
/// Whether to enable per-check timing profiles and print a report to stderr.
final bool enableCheckProfile;
/// If there was a problem with the command line arguments, this string
/// contains the error message.
final String? errorMessage;
final StringSink _errSink;
/// Override for which clang-tidy to use. If it is null it will be derived
/// instead.
final io.File? clangTidyPath;
/// Print command usage with an additional message.
void printUsage({String? message, required Engine? engine}) {
if (message != null) {
_errSink.writeln(message);
}
_errSink.writeln(
'Usage: bin/main.dart [--help] [--lint-all] [--lint-head] [--fix] [--verbose] '
'[--diff-branch] [--target-variant variant] [--src-dir path/to/engine/src]',
);
_errSink.writeln(_argParser(defaultEngine: engine).usage);
}
/// Command line argument validation.
static String? _checkArguments(ArgResults argResults, io.File buildCommandsPath) {
if (argResults.wasParsed('help')) {
return null;
}
final bool compileCommandsParsed = argResults.wasParsed('compile-commands');
if (compileCommandsParsed && argResults.wasParsed('target-variant')) {
return 'ERROR: --compile-commands option cannot be used with --target-variant.';
}
if (compileCommandsParsed && argResults.wasParsed('src-dir')) {
return 'ERROR: --compile-commands option cannot be used with --src-dir.';
}
if (const <String>['lint-all', 'lint-head', 'lint-regex'].where(argResults.wasParsed).length > 1) {
return 'ERROR: At most one of --lint-all, --lint-head, --lint-regex can be passed.';
}
if (!buildCommandsPath.existsSync()) {
return "ERROR: Build commands path ${buildCommandsPath.absolute.path} doesn't exist.";
}
if (argResults.wasParsed('shard-variants') && !argResults.wasParsed('shard-id')) {
return 'ERROR: a `shard-id` must be specified with `shard-variants`.';
}
return null;
}
}
| engine/tools/clang_tidy/lib/src/options.dart/0 | {
"file_path": "engine/tools/clang_tidy/lib/src/options.dart",
"repo_id": "engine",
"token_count": 4660
} | 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.
// ignore_for_file: avoid_dynamic_calls
import 'dart:convert';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:kernel/const_finder.dart';
import 'package:path/path.dart' as path;
void expect<T>(T value, T expected) {
if (value != expected) {
stderr.writeln('Expected: $expected');
stderr.writeln('Actual: $value');
exitCode = -1;
}
}
void expectInstances(dynamic value, dynamic expected, Compiler compiler) {
// To ensure we ignore insertion order into maps as well as lists we use
// DeepCollectionEquality as well as sort the lists.
int compareByStringValue(dynamic a, dynamic b) {
return a['stringValue'].compareTo(b['stringValue']) as int;
}
value['constantInstances'].sort(compareByStringValue);
expected['constantInstances'].sort(compareByStringValue);
final Equality<Object?> equality;
if (compiler == Compiler.dart2js) {
equality = const Dart2JSDeepCollectionEquality();
} else {
equality = const DeepCollectionEquality();
}
if (!equality.equals(value, expected)) {
stderr.writeln('Expected: ${jsonEncode(expected)}');
stderr.writeln('Actual: ${jsonEncode(value)}');
exitCode = -1;
}
}
// This test is assuming the `dart` used to invoke the tests is compatible
// with the version of package:kernel in //third-party/dart/pkg/kernel
final String dart = Platform.resolvedExecutable;
void _checkRecursion(String dillPath, Compiler compiler) {
stdout.writeln('Checking recursive calls.');
final ConstFinder finder = ConstFinder(
kernelFilePath: dillPath,
classLibraryUri: 'package:const_finder_fixtures/box.dart',
className: 'Box',
);
// Will timeout if we did things wrong.
jsonEncode(finder.findInstances());
}
void _checkConsts(String dillPath, Compiler compiler) {
stdout.writeln('Checking for expected constants.');
final ConstFinder finder = ConstFinder(
kernelFilePath: dillPath,
classLibraryUri: 'package:const_finder_fixtures/target.dart',
className: 'Target',
);
final Map<String, Object?> expectation = <String, dynamic>{
'constantInstances': <Map<String, dynamic>>[
<String, dynamic>{'stringValue': '100', 'intValue': 100, 'targetValue': null},
<String, dynamic>{'stringValue': '102', 'intValue': 102, 'targetValue': null},
<String, dynamic>{'stringValue': '101', 'intValue': 101},
<String, dynamic>{'stringValue': '103', 'intValue': 103, 'targetValue': null},
<String, dynamic>{'stringValue': '105', 'intValue': 105, 'targetValue': null},
<String, dynamic>{'stringValue': '104', 'intValue': 104},
<String, dynamic>{'stringValue': '106', 'intValue': 106, 'targetValue': null},
<String, dynamic>{'stringValue': '108', 'intValue': 108, 'targetValue': null},
<String, dynamic>{'stringValue': '107', 'intValue': 107},
<String, dynamic>{'stringValue': '1', 'intValue': 1, 'targetValue': null},
<String, dynamic>{'stringValue': '4', 'intValue': 4, 'targetValue': null},
<String, dynamic>{'stringValue': '2', 'intValue': 2},
<String, dynamic>{'stringValue': '6', 'intValue': 6, 'targetValue': null},
<String, dynamic>{'stringValue': '8', 'intValue': 8, 'targetValue': null},
<String, dynamic>{'stringValue': '10', 'intValue': 10, 'targetValue': null},
<String, dynamic>{'stringValue': '9', 'intValue': 9},
<String, dynamic>{'stringValue': '7', 'intValue': 7, 'targetValue': null},
<String, dynamic>{'stringValue': '11', 'intValue': 11, 'targetValue': null},
<String, dynamic>{'stringValue': '12', 'intValue': 12, 'targetValue': null},
<String, dynamic>{'stringValue': 'package', 'intValue':-1, 'targetValue': null},
],
'nonConstantLocations': <dynamic>[],
};
if (compiler == Compiler.aot) {
expectation['nonConstantLocations'] = <Object?>[];
} else {
final String fixturesUrl = Platform.isWindows
? '/$fixtures'.replaceAll(Platform.pathSeparator, '/')
: fixtures;
// Without true tree-shaking, there is a non-const reference in a
// never-invoked function that will be present in the dill.
expectation['nonConstantLocations'] = <Object?>[
<String, dynamic>{
'file': 'file://$fixturesUrl/pkg/package.dart',
'line': 14,
'column': 25,
},
];
}
expectInstances(
finder.findInstances(),
expectation,
compiler,
);
final ConstFinder finder2 = ConstFinder(
kernelFilePath: dillPath,
classLibraryUri: 'package:const_finder_fixtures/target.dart',
className: 'MixedInTarget',
);
expectInstances(
finder2.findInstances(),
<String, dynamic>{
'constantInstances': <Map<String, dynamic>>[
<String, dynamic>{'val': '13'},
],
'nonConstantLocations': <dynamic>[],
},
compiler,
);
}
void _checkAnnotation(String dillPath, Compiler compiler) {
stdout.writeln('Checking constant instances in a class annotated with instance of StaticIconProvider are ignored with $compiler');
final ConstFinder finder = ConstFinder(
kernelFilePath: dillPath,
classLibraryUri: 'package:const_finder_fixtures/target.dart',
className: 'Target',
annotationClassName: 'StaticIconProvider',
annotationClassLibraryUri: 'package:const_finder_fixtures/static_icon_provider.dart',
);
final Map<String, dynamic> instances = finder.findInstances();
expectInstances(
instances,
<String, dynamic>{
'constantInstances': <Map<String, Object?>>[
<String, Object?>{
'stringValue': 'used1',
'intValue': 1,
'targetValue': null,
},
<String, Object?>{
'stringValue': 'used2',
'intValue': 2,
'targetValue': null,
},
],
// TODO(fujino): This should have non-constant locations from the use of
// a tear-off, see https://github.com/flutter/flutter/issues/116797
'nonConstantLocations': <Object?>[],
},
compiler,
);
}
void _checkNonConstsFrontend(String dillPath, Compiler compiler) {
stdout.writeln('Checking for non-constant instances with $compiler');
final ConstFinder finder = ConstFinder(
kernelFilePath: dillPath,
classLibraryUri: 'package:const_finder_fixtures/target.dart',
className: 'Target',
);
final String fixturesUrl = Platform.isWindows
? '/$fixtures'.replaceAll(Platform.pathSeparator, '/')
: fixtures;
expectInstances(
finder.findInstances(),
<String, dynamic>{
'constantInstances': <dynamic>[
<String, dynamic>{'stringValue': '1', 'intValue': 1, 'targetValue': null},
<String, dynamic>{'stringValue': '4', 'intValue': 4, 'targetValue': null},
<String, dynamic>{'stringValue': '6', 'intValue': 6, 'targetValue': null},
<String, dynamic>{'stringValue': '8', 'intValue': 8, 'targetValue': null},
<String, dynamic>{'stringValue': '10', 'intValue': 10, 'targetValue': null},
<String, dynamic>{'stringValue': '9', 'intValue': 9},
<String, dynamic>{'stringValue': '7', 'intValue': 7, 'targetValue': null},
],
'nonConstantLocations': <dynamic>[
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 14,
'column': 26,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 16,
'column': 26,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 16,
'column': 41,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 17,
'column': 26,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/pkg/package.dart',
'line': 14,
'column': 25,
}
]
},
compiler,
);
}
// Note, since web dills don't have tree shaking, we aren't able to eliminate
// an additional const versus _checkNonConstFrontend.
void _checkNonConstsWeb(String dillPath, Compiler compiler) {
assert(compiler == Compiler.dart2js);
stdout.writeln('Checking for non-constant instances with $compiler');
final ConstFinder finder = ConstFinder(
kernelFilePath: dillPath,
classLibraryUri: 'package:const_finder_fixtures/target.dart',
className: 'Target',
);
final String fixturesUrl = Platform.isWindows
? '/$fixtures'.replaceAll(Platform.pathSeparator, '/')
: fixtures;
expectInstances(
finder.findInstances(),
<String, dynamic>{
'constantInstances': <dynamic>[
<String, dynamic>{'stringValue': '1', 'intValue': 1, 'targetValue': null},
<String, dynamic>{'stringValue': '4', 'intValue': 4, 'targetValue': null},
<String, dynamic>{'stringValue': '6', 'intValue': 6, 'targetValue': null},
<String, dynamic>{'stringValue': '8', 'intValue': 8, 'targetValue': null},
<String, dynamic>{'stringValue': '10', 'intValue': 10, 'targetValue': null},
<String, dynamic>{'stringValue': '9', 'intValue': 9},
<String, dynamic>{'stringValue': '7', 'intValue': 7, 'targetValue': null},
<String, dynamic>{'stringValue': 'package', 'intValue': -1, 'targetValue': null},
],
'nonConstantLocations': <dynamic>[
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 14,
'column': 26,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 16,
'column': 26,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 16,
'column': 41,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/lib/consts_and_non.dart',
'line': 17,
'column': 26,
},
<String, dynamic>{
'file': 'file://$fixturesUrl/pkg/package.dart',
'line': 14,
'column': 25,
}
],
},
compiler,
);
}
void checkProcessResult(ProcessResult result) {
if (result.exitCode != 0) {
stdout.writeln(result.stdout);
stderr.writeln(result.stderr);
}
expect(result.exitCode, 0);
}
final String basePath =
path.canonicalize(path.join(path.dirname(Platform.script.toFilePath()), '..'));
final String fixtures = path.join(basePath, 'test', 'fixtures');
final String packageConfig = path.join(fixtures, '.dart_tool', 'package_config.json');
Future<void> main(List<String> args) async {
if (args.length != 3) {
stderr.writeln('The first argument must be the path to the frontend server dill.');
stderr.writeln('The second argument must be the path to the flutter_patched_sdk');
stderr.writeln('The third argument must be the path to libraries.json');
exit(-1);
}
final String frontendServer = args[0];
final String sdkRoot = args[1];
final String librariesSpec = args[2];
final List<_Test> tests = <_Test>[
_Test(
name: 'box_frontend',
dartSource: path.join(fixtures, 'lib', 'box.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkRecursion,
compiler: Compiler.aot,
),
_Test(
name: 'box_web',
dartSource: path.join(fixtures, 'lib', 'box.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkRecursion,
compiler: Compiler.dart2js,
),
_Test(
name: 'consts_frontend',
dartSource: path.join(fixtures, 'lib', 'consts.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkConsts,
compiler: Compiler.aot,
),
_Test(
name: 'consts_web',
dartSource: path.join(fixtures, 'lib', 'consts.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkConsts,
compiler: Compiler.dart2js,
),
_Test(
name: 'consts_and_non_frontend',
dartSource: path.join(fixtures, 'lib', 'consts_and_non.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkNonConstsFrontend,
compiler: Compiler.aot,
),
_Test(
name: 'consts_and_non_web',
dartSource: path.join(fixtures, 'lib', 'consts_and_non.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkNonConstsWeb,
compiler: Compiler.dart2js,
),
_Test(
name: 'static_icon_provider_frontend',
dartSource: path.join(fixtures, 'lib', 'static_icon_provider.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkAnnotation,
compiler: Compiler.aot,
),
_Test(
name: 'static_icon_provider_web',
dartSource: path.join(fixtures, 'lib', 'static_icon_provider.dart'),
frontendServer: frontendServer,
sdkRoot: sdkRoot,
librariesSpec: librariesSpec,
verify: _checkAnnotation,
compiler: Compiler.dart2js,
),
];
try {
stdout.writeln('Generating kernel fixtures...');
for (final _Test test in tests) {
test.run();
}
} finally {
try {
for (final _Test test in tests) {
test.dispose();
}
} finally {
stdout.writeln('Tests ${exitCode == 0 ? 'succeeded' : 'failed'} - exit code: $exitCode');
}
}
}
enum Compiler {
// Uses TFA tree-shaking.
aot,
// Does not have TFA tree-shaking.
dart2js,
}
class _Test {
_Test({
required this.name,
required this.dartSource,
required this.sdkRoot,
required this.verify,
required this.frontendServer,
required this.librariesSpec,
required this.compiler,
}) : dillPath = path.join(fixtures, '$name.dill');
final String name;
final String dartSource;
final String sdkRoot;
final String frontendServer;
final String librariesSpec;
final String dillPath;
void Function(String, Compiler) verify;
final Compiler compiler;
final List<String> resourcesToDispose = <String>[];
void run() {
stdout.writeln('Compiling $dartSource to $dillPath with $compiler');
if (compiler == Compiler.aot) {
_compileAOTDill();
} else {
_compileWebDill();
}
stdout.writeln('Testing $dillPath');
verify(dillPath, compiler);
}
void dispose() {
for (final String resource in resourcesToDispose) {
stdout.writeln('Deleting $resource');
File(resource).deleteSync();
}
}
void _compileAOTDill() {
checkProcessResult(Process.runSync(dart, <String>[
frontendServer,
'--sdk-root=$sdkRoot',
'--target=flutter',
'--aot',
'--tfa',
'--packages=$packageConfig',
'--output-dill=$dillPath',
dartSource,
]));
resourcesToDispose.add(dillPath);
}
void _compileWebDill() {
final ProcessResult result = Process.runSync(dart, <String>[
'compile',
'js',
'--libraries-spec=$librariesSpec',
'-Ddart.vm.product=true',
'-o',
dillPath,
'--packages=$packageConfig',
'--cfe-only',
dartSource,
]);
checkProcessResult(result);
resourcesToDispose.add(dillPath);
}
}
/// Equality that casts all [num]'s to [double] before comparing.
class Dart2JSDeepCollectionEquality extends DeepCollectionEquality {
const Dart2JSDeepCollectionEquality();
@override
bool equals(Object? e1, Object? e2) {
if (e1 is num && e2 is num) {
return e1.toDouble() == e2.toDouble();
}
return super.equals(e1, e2);
}
}
| engine/tools/const_finder/test/const_finder_test.dart/0 | {
"file_path": "engine/tools/const_finder/test/const_finder_test.dart",
"repo_id": "engine",
"token_count": 6497
} | 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.
import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
import 'package:path/path.dart' as p;
import '../logger.dart';
import 'command.dart';
import 'flags.dart';
/// The 'format' command.
///
/// The format command implementation below works by spawning another Dart VM to
/// run the program under ci/bin/format.dart.
///
// TODO(team-engine): Part of https://github.com/flutter/flutter/issues/132807.
// Instead, format.dart should be moved under the engine_tool package and
// invoked by a function call. The file ci/bin/format.dart should be split up so
// that each of its `FormatCheckers` is in a separate file under src/formatters,
// and they should be unit-tested.
final class FormatCommand extends CommandBase {
// ignore: public_member_api_docs
FormatCommand({
required super.environment,
}) {
argParser
..addFlag(
allFlag,
abbr: 'a',
help: 'By default only dirty files are checked. This flag causes all '
'files to be checked. (Slow)',
negatable: false,
)
..addFlag(
dryRunFlag,
abbr: 'd',
help: 'Do not fix formatting in-place. Instead, print file diffs to '
'the logs.',
negatable: false,
)
..addFlag(
quietFlag,
abbr: 'q',
help: 'Silences all log messages except for errors and warnings',
negatable: false,
);
}
@override
String get name => 'format';
@override
String get description => 'Formats files using standard formatters and styles.';
@override
Future<int> run() async {
final bool all = argResults![allFlag]! as bool;
final bool dryRun = argResults![dryRunFlag]! as bool;
final bool quiet = argResults![quietFlag]! as bool;
final bool verbose = globalResults![verboseFlag] as bool;
final String formatPath = p.join(
environment.engine.flutterDir.path, 'ci', 'bin', 'format.dart',
);
final io.Process process = await environment.processRunner.processManager.start(
<String>[
environment.platform.resolvedExecutable,
formatPath,
if (all) '--all-files',
if (!dryRun) '--fix',
if (verbose) '--verbose',
],
workingDirectory: environment.engine.flutterDir.path,
);
final Completer<void> stdoutComplete = Completer<void>();
final Completer<void> stderrComplete = Completer<void>();
final _FormatStreamer streamer = _FormatStreamer(
environment.logger,
dryRun,
quiet,
);
process.stdout
.transform<String>(const Utf8Decoder())
.transform(const LineSplitter())
.listen(
streamer.nextStdout,
onDone: () async => stdoutComplete.complete(),
);
process.stderr
.transform<String>(const Utf8Decoder())
.transform(const LineSplitter())
.listen(
streamer.nextStderr,
onDone: () async => stderrComplete.complete(),
);
await Future.wait<void>(<Future<void>>[
stdoutComplete.future, stderrComplete.future,
]);
final int exitCode = await process.exitCode;
return exitCode;
}
}
class _FormatStreamer {
_FormatStreamer(this.logger, this.dryRun, this.quiet);
final Logger logger;
final bool dryRun;
final bool quiet;
bool inADiff = false;
bool inProgress = false;
void nextStdout(String line) {
if (quiet) {
return;
}
final String l = line.trim();
if (l == 'To fix, run `et format` or:') {
inADiff = true;
}
if (l.isNotEmpty && (!inADiff || dryRun)) {
if (_isProgressLine(l)) {
inProgress = true;
logger.clearLine();
logger.status('$l\r', newline: false);
} else {
if (inProgress) {
logger.clearLine();
inProgress = false;
}
logger.status(l);
}
}
if (l == 'DONE') {
inADiff = false;
}
}
void nextStderr(String line) {
final String l = line.trim();
if (l.isEmpty) {
return;
}
logger.error(l);
}
bool _isProgressLine(String l) {
final List<String> words = l.split(',');
return words.isNotEmpty && words[0].endsWith('% done');
}
}
| engine/tools/engine_tool/lib/src/commands/format_command.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/commands/format_command.dart",
"repo_id": "engine",
"token_count": 1731
} | 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.
String testConfig(String os) => '''
{
"builds": [
{
"archives": [
{
"name": "build_name",
"base_path": "base/path",
"type": "gcs",
"include_paths": ["include/path"],
"realm": "archive_realm"
}
],
"drone_dimensions": [
"os=$os"
],
"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"]
}
]
}
},
{},
{},
{
"drone_dimensions": [
"os=$os"
],
"gn": ["--gn-arg", "--lto", "--goma", "--no-rbe"],
"name": "host_debug",
"ninja": {
"config": "host_debug",
"targets": ["ninja_target"]
}
},
{
"drone_dimensions": [
"os=$os"
],
"gn": ["--gn-arg", "--lto", "--goma", "--no-rbe"],
"name": "android_debug_arm64",
"ninja": {
"config": "android_debug_arm64",
"targets": ["ninja_target"]
}
},
{
"drone_dimensions": [
"os=$os"
],
"gn": ["--gn-arg", "--lto", "--no-goma", "--rbe"],
"name": "android_debug_rbe_arm64",
"ninja": {
"config": "android_debug_rbe_arm64",
"targets": ["ninja_target"]
}
}
],
"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=$os"
],
"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"
}
]
}
]
}
''';
String attachedDevices() => '''
[
{
"name": "sdk gphone64 arm64",
"id": "emulator-5554",
"isSupported": true,
"targetPlatform": "android-arm64",
"emulator": true,
"sdk": "Android 14 (API 34)",
"capabilities": {
"hotReload": true,
"hotRestart": true,
"screenshot": true,
"fastStart": true,
"flutterExit": true,
"hardwareRendering": true,
"startPaused": true
}
},
{
"name": "macOS",
"id": "macos",
"isSupported": true,
"targetPlatform": "darwin",
"emulator": false,
"sdk": "macOS 14.3.1 23D60 darwin-arm64",
"capabilities": {
"hotReload": true,
"hotRestart": true,
"screenshot": false,
"fastStart": false,
"flutterExit": true,
"hardwareRendering": false,
"startPaused": true
}
},
{
"name": "Mac Designed for iPad",
"id": "mac-designed-for-ipad",
"isSupported": true,
"targetPlatform": "darwin",
"emulator": false,
"sdk": "macOS 14.3.1 23D60 darwin-arm64",
"capabilities": {
"hotReload": true,
"hotRestart": true,
"screenshot": false,
"fastStart": false,
"flutterExit": true,
"hardwareRendering": false,
"startPaused": true
}
},
{
"name": "Chrome",
"id": "chrome",
"isSupported": true,
"targetPlatform": "web-javascript",
"emulator": false,
"sdk": "Google Chrome 122.0.6261.94",
"capabilities": {
"hotReload": true,
"hotRestart": true,
"screenshot": false,
"fastStart": false,
"flutterExit": false,
"hardwareRendering": false,
"startPaused": true
}
}
]
''';
| engine/tools/engine_tool/test/fixtures.dart/0 | {
"file_path": "engine/tools/engine_tool/test/fixtures.dart",
"repo_id": "engine",
"token_count": 2329
} | 433 |
# 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.
# NOTE: Generally, the build rules in //flutter/tools/fuchsia/dart/,
# //flutter/tools/fuchsia/dart/kernel/, and similar SUBDIRECTORIES of
# //flutter/tools/fuchsia/ (such as //flutter/tools/fuchsia/flutter/)
# mirror the directory paths and much of the build rule content of fuchsia.git
# //build/...
#
# Most of the fuchsia-derived build rules were implemented after some similar
# build rules already existed in the directory //flutter/tools/fuchsia/
# and several existing build targets use these (legacy) build rules.
# Though some rules and targets in //flutter/tools/fuchsia/ have similar names
# to the fuchsia.git-derived rules, the rule structures and behavior can be
# different. Therefore both are maintained for now.
#
# In the case of this file--dart.gni--some existing definitions from the
# original dart.gni are relevant and useful to the new fuchsia.git-derived
# rules, so these definitions can simply be imported.
import("//flutter/tools/fuchsia/dart.gni")
| engine/tools/fuchsia/dart/dart.gni/0 | {
"file_path": "engine/tools/fuchsia/dart/dart.gni",
"repo_id": "engine",
"token_count": 324
} | 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.
import("//flutter/common/fuchsia_config.gni")
template("fuchsia_host_bundle") {
assert(defined(invoker.name), "'name' must be defined for $target_name.")
_dest_dir_base = "${root_out_dir}/host_bundle"
_dest_dir = "${_dest_dir_base}/${invoker.name}-${flutter_runtime_mode}-${host_os}-${host_cpu}"
copy(target_name) {
if (defined(invoker.deps)) {
deps = invoker.deps
}
sources = invoker.sources
outputs = [ "${_dest_dir}/{{source_file_part}}" ]
}
}
| engine/tools/fuchsia/fuchsia_host_bundle.gni/0 | {
"file_path": "engine/tools/fuchsia/fuchsia_host_bundle.gni",
"repo_id": "engine",
"token_count": 247
} | 435 |
#!/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.
# Generates API docs for Flutter embedders and libraries.
import os
import shutil
import tempfile
import zipfile
import sys
import subprocess
from collections import namedtuple
Section = namedtuple('Section', ['title', 'inputs'])
SECTIONS = {
'ios':
Section(
'iOS Embedder', [
'shell/platform/darwin/ios',
'shell/platform/darwin/common',
'shell/platform/common',
]
),
'macos':
Section(
'macOS Embedder', [
'shell/platform/darwin/macos',
'shell/platform/darwin/common',
'shell/platform/common',
]
),
'linux':
Section('Linux Embedder', [
'shell/platform/linux',
'shell/platform/common',
]),
'windows':
Section('Windows Embedder', [
'shell/platform/windows',
'shell/platform/common',
]),
'impeller':
Section('Impeller', [
'impeller',
]),
}
def generate_doxyfile(section, output_dir, log_file, doxy_file):
doxyfile = open('docs/Doxyfile.template', 'r').read()
doxyfile = doxyfile.replace('@@OUTPUT_DIRECTORY@@', output_dir)
doxyfile = doxyfile.replace('@@LOG_FILE@@', log_file)
doxyfile = doxyfile.replace('@@INPUT_DIRECTORIES@@', '"{}"'.format('" "'.join(section.inputs)))
doxyfile = doxyfile.replace('@@PROJECT_NAME@@', 'Flutter {}'.format(section.title))
doxyfile = doxyfile.replace(
'@@DOCSET_FEEDNAME@@', 'Flutter {} Documentation'.format(section.title)
)
with open(doxy_file, 'w') as f:
f.write(doxyfile)
def process_section(name, section, destination):
output_dir = tempfile.mkdtemp(prefix="doxygen")
log_file = os.path.join(destination, '{}-doxygen.log'.format(name))
zip_file = os.path.join(destination, '{}-docs.zip'.format(name))
doxy_file = os.path.join(output_dir, 'Doxyfile')
generate_doxyfile(section, output_dir, log_file, doxy_file)
# Update the Doxyfile format to the latest format.
subprocess.call(['doxygen', '-u'], cwd=output_dir)
subprocess.call(['doxygen', doxy_file])
html_dir = os.path.join(output_dir, 'html')
with zipfile.ZipFile(zip_file, 'w') as zip:
for root, _, files in os.walk(html_dir):
for file in files:
filename = os.path.join(root, file)
zip.write(filename, os.path.relpath(filename, html_dir))
print('Wrote ZIP file for {} to {}'.format(section, zip_file))
print('Preserving log file in {}'.format(log_file))
shutil.rmtree(output_dir, ignore_errors=True)
def generate_docs(argv):
if len(argv) != 2:
print(
'Error: Argument specifying output directory required. '
'Directory may be an absolute path, or a relative path from the "src" directory.'
)
exit(1)
destination = argv[1]
script_path = os.path.realpath(__file__)
src_path = os.path.dirname(os.path.dirname(os.path.dirname(script_path)))
# Run commands from the Flutter root dir.
os.chdir(os.path.join(src_path, 'flutter'))
# If the argument isn't an absolute path, assume that it is relative to the src dir.
if not os.path.isabs(destination):
destination = os.path.join(src_path, destination)
os.makedirs(destination, exist_ok=True)
for name, section in SECTIONS.items():
process_section(name, section, destination)
if __name__ == '__main__':
generate_docs(sys.argv)
| engine/tools/gen_docs.py/0 | {
"file_path": "engine/tools/gen_docs.py",
"repo_id": "engine",
"token_count": 1475
} | 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.
import 'dart:io' as io;
const String _redBoldUnderline = '\x1B[31;1;4m';
const String _reset = '\x1B[0m';
/// Prints a reminder to stdout to run `gclient sync -D`. Uses colors when
/// stdout supports ANSI escape codes.
void printGclientSyncReminder(String command) {
final String prefix = io.stdout.supportsAnsiEscapes ? _redBoldUnderline : '';
final String postfix = io.stdout.supportsAnsiEscapes ? _reset : '';
io.stderr.writeln('$command: The engine source tree has been updated.');
io.stderr.writeln(
'\n${prefix}You may need to run "gclient sync -D"$postfix\n',
);
}
| engine/tools/githooks/lib/src/messages.dart/0 | {
"file_path": "engine/tools/githooks/lib/src/messages.dart",
"repo_id": "engine",
"token_count": 255
} | 437 |
android
android.accessibilityservice
android.accounts
android.animation
android.annotation
android.app
android.app.admin
android.app.appsearch
android.app.appsearch.exceptions
android.app.assist
android.app.backup
android.app.blob
android.app.job
android.app.people
android.app.role
android.app.slice
android.app.usage
android.appwidget
android.bluetooth
android.bluetooth.le
android.companion
android.content
android.content.pm
android.content.pm.verify.domain
android.content.res
android.content.res.loader
android.database
android.database.sqlite
android.drm
android.gesture
android.graphics
android.graphics.drawable
android.graphics.drawable.shapes
android.graphics.fonts
android.graphics.pdf
android.graphics.text
android.hardware
android.hardware.biometrics
android.hardware.camera2
android.hardware.camera2.params
android.hardware.display
android.hardware.fingerprint
android.hardware.input
android.hardware.lights
android.hardware.usb
android.icu.lang
android.icu.math
android.icu.number
android.icu.text
android.icu.util
android.inputmethodservice
android.location
android.location.provider
android.media
android.media.audiofx
android.media.browse
android.media.effect
android.media.metrics
android.media.midi
android.media.projection
android.media.session
android.media.tv
android.mtp
android.net
android.net.eap
android.net.http
android.net.ipsec.ike
android.net.ipsec.ike.exceptions
android.net.nsd
android.net.rtp
android.net.sip
android.net.ssl
android.net.vcn
android.net.wifi
android.net.wifi.aware
android.net.wifi.hotspot2
android.net.wifi.hotspot2.omadm
android.net.wifi.hotspot2.pps
android.net.wifi.p2p
android.net.wifi.p2p.nsd
android.net.wifi.rtt
android.nfc
android.nfc.cardemulation
android.nfc.tech
android.opengl
android.os
android.os.health
android.os.storage
android.os.strictmode
android.preference
android.print
android.print.pdf
android.printservice
android.provider
android.renderscript
android.sax
android.se.omapi
android.security
android.security.identity
android.security.keystore
android.service.autofill
android.service.carrier
android.service.chooser
android.service.controls
android.service.controls.actions
android.service.controls.templates
android.service.dreams
android.service.media
android.service.notification
android.service.quickaccesswallet
android.service.quicksettings
android.service.restrictions
android.service.textservice
android.service.voice
android.service.vr
android.service.wallpaper
android.speech
android.speech.tts
android.system
android.telecom
android.telephony
android.telephony.cdma
android.telephony.data
android.telephony.emergency
android.telephony.euicc
android.telephony.gsm
android.telephony.ims
android.telephony.ims.feature
android.telephony.mbms
android.test
android.test.mock
android.test.suitebuilder
android.test.suitebuilder.annotation
android.text
android.text.format
android.text.method
android.text.style
android.text.util
android.transition
android.util
android.util.proto
android.view
android.view.accessibility
android.view.animation
android.view.autofill
android.view.contentcapture
android.view.displayhash
android.view.inputmethod
android.view.inspector
android.view.textclassifier
android.view.textservice
android.view.translation
android.webkit
android.widget
android.widget.inline
android.window
dalvik.annotation
dalvik.bytecode
dalvik.system
java.awt.font
java.beans
java.io
java.lang
java.lang.annotation
java.lang.invoke
java.lang.ref
java.lang.reflect
java.math
java.net
java.nio
java.nio.channels
java.nio.channels.spi
java.nio.charset
java.nio.charset.spi
java.nio.file
java.nio.file.attribute
java.nio.file.spi
java.security
java.security.acl
java.security.cert
java.security.interfaces
java.security.spec
java.sql
java.text
java.time
java.time.chrono
java.time.format
java.time.temporal
java.time.zone
java.util
java.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks
java.util.function
java.util.jar
java.util.logging
java.util.prefs
java.util.regex
java.util.stream
java.util.zip
javax.crypto
javax.crypto.interfaces
javax.crypto.spec
javax.microedition.khronos.egl
javax.microedition.khronos.opengles
javax.net
javax.net.ssl
javax.security.auth
javax.security.auth.callback
javax.security.auth.login
javax.security.auth.x500
javax.security.cert
javax.sql
javax.xml
javax.xml.datatype
javax.xml.namespace
javax.xml.parsers
javax.xml.transform
javax.xml.transform.dom
javax.xml.transform.sax
javax.xml.transform.stream
javax.xml.validation
javax.xml.xpath
junit.framework
junit.runner
org.apache.http.conn
org.apache.http.conn.scheme
org.apache.http.conn.ssl
org.apache.http.params
org.json
org.w3c.dom
org.w3c.dom.ls
org.xml.sax
org.xml.sax.ext
org.xml.sax.helpers
org.xmlpull.v1
org.xmlpull.v1.sax2
| engine/tools/javadoc/android_reference/package-list/0 | {
"file_path": "engine/tools/javadoc/android_reference/package-list",
"repo_id": "engine",
"token_count": 1667
} | 438 |
MOZILLA PUBLIC LICENSE
Version 1.1
---------------
1. Definitions.
1.0.1. "Commercial Use" means distribution or otherwise making the
Covered Code available to a third party.
1.1. "Contributor" means each entity that creates or contributes to
the creation of Modifications.
1.2. "Contributor Version" means the combination of the Original
Code, prior Modifications used by a Contributor, and the Modifications
made by that particular Contributor.
1.3. "Covered Code" means the Original Code or Modifications or the
combination of the Original Code and Modifications, in each case
including portions thereof.
1.4. "Electronic Distribution Mechanism" means a mechanism generally
accepted in the software development community for the electronic
transfer of data.
1.5. "Executable" means Covered Code in any form other than Source
Code.
1.6. "Initial Developer" means the individual or entity identified
as the Initial Developer in the Source Code notice required by Exhibit
A.
1.7. "Larger Work" means a work which combines Covered Code or
portions thereof with code not governed by the terms of this License.
1.8. "License" means this document.
1.8.1. "Licensable" means having the right to grant, to the maximum
extent possible, whether at the time of the initial grant or
subsequently acquired, any and all of the rights conveyed herein.
1.9. "Modifications" means any addition to or deletion from the
substance or structure of either the Original Code or any previous
Modifications. When Covered Code is released as a series of files, a
Modification is:
A. Any addition to or deletion from the contents of a file
containing Original Code or previous Modifications.
B. Any new file that contains any part of the Original Code or
previous Modifications.
1.10. "Original Code" means Source Code of computer software code
which is described in the Source Code notice required by Exhibit A as
Original Code, and which, at the time of its release under this
License is not already Covered Code governed by this License.
1.10.1. "Patent Claims" means any patent claim(s), now owned or
hereafter acquired, including without limitation, method, process,
and apparatus claims, in any patent Licensable by grantor.
1.11. "Source Code" means the preferred form of the Covered Code for
making modifications to it, including all modules it contains, plus
any associated interface definition files, scripts used to control
compilation and installation of an Executable, or source code
differential comparisons against either the Original Code or another
well known, available Covered Code of the Contributor's choice. The
Source Code can be in a compressed or archival form, provided the
appropriate decompression or de-archiving software is widely available
for no charge.
1.12. "You" (or "Your") means an individual or a legal entity
exercising rights under, and complying with all of the terms of, this
License or a future version of this License issued under Section 6.1.
For legal entities, "You" includes any entity which controls, is
controlled by, or is under common control with You. For purposes of
this definition, "control" means (a) the power, direct or indirect,
to cause the direction or management of such entity, whether by
contract or otherwise, or (b) ownership of more than fifty percent
(50%) of the outstanding shares or beneficial ownership of such
entity.
2. Source Code License.
2.1. The Initial Developer Grant.
The Initial Developer hereby grants You a world-wide, royalty-free,
non-exclusive license, subject to third party intellectual property
claims:
(a) under intellectual property rights (other than patent or
trademark) Licensable by Initial Developer to use, reproduce,
modify, display, perform, sublicense and distribute the Original
Code (or portions thereof) with or without Modifications, and/or
as part of a Larger Work; and
(b) under Patents Claims infringed by the making, using or
selling of Original Code, to make, have made, use, practice,
sell, and offer for sale, and/or otherwise dispose of the
Original Code (or portions thereof).
(c) the licenses granted in this Section 2.1(a) and (b) are
effective on the date Initial Developer first distributes
Original Code under the terms of this License.
(d) Notwithstanding Section 2.1(b) above, no patent license is
granted: 1) for code that You delete from the Original Code; 2)
separate from the Original Code; or 3) for infringements caused
by: i) the modification of the Original Code or ii) the
combination of the Original Code with other software or devices.
2.2. Contributor Grant.
Subject to third party intellectual property claims, each Contributor
hereby grants You a world-wide, royalty-free, non-exclusive license
(a) under intellectual property rights (other than patent or
trademark) Licensable by Contributor, to use, reproduce, modify,
display, perform, sublicense and distribute the Modifications
created by such Contributor (or portions thereof) either on an
unmodified basis, with other Modifications, as Covered Code
and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using, or
selling of Modifications made by that Contributor either alone
and/or in combination with its Contributor Version (or portions
of such combination), to make, use, sell, offer for sale, have
made, and/or otherwise dispose of: 1) Modifications made by that
Contributor (or portions thereof); and 2) the combination of
Modifications made by that Contributor with its Contributor
Version (or portions of such combination).
(c) the licenses granted in Sections 2.2(a) and 2.2(b) are
effective on the date Contributor first makes Commercial Use of
the Covered Code.
(d) Notwithstanding Section 2.2(b) above, no patent license is
granted: 1) for any code that Contributor has deleted from the
Contributor Version; 2) separate from the Contributor Version;
3) for infringements caused by: i) third party modifications of
Contributor Version or ii) the combination of Modifications made
by that Contributor with other software (except as part of the
Contributor Version) or other devices; or 4) under Patent Claims
infringed by Covered Code in the absence of Modifications made by
that Contributor.
3. Distribution Obligations.
3.1. Application of License.
The Modifications which You create or to which You contribute are
governed by the terms of this License, including without limitation
Section 2.2. The Source Code version of Covered Code may be
distributed only under the terms of this License or a future version
of this License released under Section 6.1, and You must include a
copy of this License with every copy of the Source Code You
distribute. You may not offer or impose any terms on any Source Code
version that alters or restricts the applicable version of this
License or the recipients' rights hereunder. However, You may include
an additional document offering the additional rights described in
Section 3.5.
3.2. Availability of Source Code.
Any Modification which You create or to which You contribute must be
made available in Source Code form under the terms of this License
either on the same media as an Executable version or via an accepted
Electronic Distribution Mechanism to anyone to whom you made an
Executable version available; and if made available via Electronic
Distribution Mechanism, must remain available for at least twelve (12)
months after the date it initially became available, or at least six
(6) months after a subsequent version of that particular Modification
has been made available to such recipients. You are responsible for
ensuring that the Source Code version remains available even if the
Electronic Distribution Mechanism is maintained by a third party.
3.3. Description of Modifications.
You must cause all Covered Code to which You contribute to contain a
file documenting the changes You made to create that Covered Code and
the date of any change. You must include a prominent statement that
the Modification is derived, directly or indirectly, from Original
Code provided by the Initial Developer and including the name of the
Initial Developer in (a) the Source Code, and (b) in any notice in an
Executable version or related documentation in which You describe the
origin or ownership of the Covered Code.
3.4. Intellectual Property Matters
(a) Third Party Claims.
If Contributor has knowledge that a license under a third party's
intellectual property rights is required to exercise the rights
granted by such Contributor under Sections 2.1 or 2.2,
Contributor must include a text file with the Source Code
distribution titled "LEGAL" which describes the claim and the
party making the claim in sufficient detail that a recipient will
know whom to contact. If Contributor obtains such knowledge after
the Modification is made available as described in Section 3.2,
Contributor shall promptly modify the LEGAL file in all copies
Contributor makes available thereafter and shall take other steps
(such as notifying appropriate mailing lists or newsgroups)
reasonably calculated to inform those who received the Covered
Code that new knowledge has been obtained.
(b) Contributor APIs.
If Contributor's Modifications include an application programming
interface and Contributor has knowledge of patent licenses which
are reasonably necessary to implement that API, Contributor must
also include this information in the LEGAL file.
(c) Representations.
Contributor represents that, except as disclosed pursuant to
Section 3.4(a) above, Contributor believes that Contributor's
Modifications are Contributor's original creation(s) and/or
Contributor has sufficient rights to grant the rights conveyed by
this License.
3.5. Required Notices.
You must duplicate the notice in Exhibit A in each file of the Source
Code. If it is not possible to put such notice in a particular Source
Code file due to its structure, then You must include such notice in a
location (such as a relevant directory) where a user would be likely
to look for such a notice. If You created one or more Modification(s)
You may add your name as a Contributor to the notice described in
Exhibit A. You must also duplicate this License in any documentation
for the Source Code where You describe recipients' rights or ownership
rights relating to Covered Code. You may choose to offer, and to
charge a fee for, warranty, support, indemnity or liability
obligations to one or more recipients of Covered Code. However, You
may do so only on Your own behalf, and not on behalf of the Initial
Developer or any Contributor. You must make it absolutely clear than
any such warranty, support, indemnity or liability obligation is
offered by You alone, and You hereby agree to indemnify the Initial
Developer and every Contributor for any liability incurred by the
Initial Developer or such Contributor as a result of warranty,
support, indemnity or liability terms You offer.
3.6. Distribution of Executable Versions.
You may distribute Covered Code in Executable form only if the
requirements of Section 3.1-3.5 have been met for that Covered Code,
and if You include a notice stating that the Source Code version of
the Covered Code is available under the terms of this License,
including a description of how and where You have fulfilled the
obligations of Section 3.2. The notice must be conspicuously included
in any notice in an Executable version, related documentation or
collateral in which You describe recipients' rights relating to the
Covered Code. You may distribute the Executable version of Covered
Code or ownership rights under a license of Your choice, which may
contain terms different from this License, provided that You are in
compliance with the terms of this License and that the license for the
Executable version does not attempt to limit or alter the recipient's
rights in the Source Code version from the rights set forth in this
License. If You distribute the Executable version under a different
license You must make it absolutely clear that any terms which differ
from this License are offered by You alone, not by the Initial
Developer or any Contributor. You hereby agree to indemnify the
Initial Developer and every Contributor for any liability incurred by
the Initial Developer or such Contributor as a result of any such
terms You offer.
3.7. Larger Works.
You may create a Larger Work by combining Covered Code with other code
not governed by the terms of this License and distribute the Larger
Work as a single product. In such a case, You must make sure the
requirements of this License are fulfilled for the Covered Code.
4. Inability to Comply Due to Statute or Regulation.
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Code due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description
must be included in the LEGAL file described in Section 3.4 and must
be included with all distributions of the Source Code. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Application of this License.
This License applies to code to which the Initial Developer has
attached the notice in Exhibit A and to related Covered Code.
6. Versions of the License.
6.1. New Versions.
Netscape Communications Corporation ("Netscape") may publish revised
and/or new versions of the License from time to time. Each version
will be given a distinguishing version number.
6.2. Effect of New Versions.
Once Covered Code has been published under a particular version of the
License, You may always continue to use it under the terms of that
version. You may also choose to use such Covered Code under the terms
of any subsequent version of the License published by Netscape. No one
other than Netscape has the right to modify the terms applicable to
Covered Code created under this License.
6.3. Derivative Works.
If You create or use a modified version of this License (which you may
only do in order to apply it to code which is not already Covered Code
governed by this License), You must (a) rename Your license so that
the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
"MPL", "NPL" or any confusingly similar phrase do not appear in your
license (except to note that your license differs from this License)
and (b) otherwise make it clear that Your version of the license
contains terms which differ from the Mozilla Public License and
Netscape Public License. (Filling in the name of the Initial
Developer, Original Code or Contributor in the notice described in
Exhibit A shall not of themselves be deemed to be modifications of
this License.)
7. DISCLAIMER OF WARRANTY.
COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
8. TERMINATION.
8.1. This License and the rights granted hereunder will terminate
automatically if You fail to comply with terms herein and fail to cure
such breach within 30 days of becoming aware of the breach. All
sublicenses to the Covered Code which are properly granted shall
survive any termination of this License. Provisions which, by their
nature, must remain in effect beyond the termination of this License
shall survive.
8.2. If You initiate litigation by asserting a patent infringement
claim (excluding declatory judgment actions) against Initial Developer
or a Contributor (the Initial Developer or Contributor against whom
You file such action is referred to as "Participant") alleging that:
(a) such Participant's Contributor Version directly or indirectly
infringes any patent, then any and all rights granted by such
Participant to You under Sections 2.1 and/or 2.2 of this License
shall, upon 60 days notice from Participant terminate prospectively,
unless if within 60 days after receipt of notice You either: (i)
agree in writing to pay Participant a mutually agreeable reasonable
royalty for Your past and future use of Modifications made by such
Participant, or (ii) withdraw Your litigation claim with respect to
the Contributor Version against such Participant. If within 60 days
of notice, a reasonable royalty and payment arrangement are not
mutually agreed upon in writing by the parties or the litigation claim
is not withdrawn, the rights granted by Participant to You under
Sections 2.1 and/or 2.2 automatically terminate at the expiration of
the 60 day notice period specified above.
(b) any software, hardware, or device, other than such Participant's
Contributor Version, directly or indirectly infringes any patent, then
any rights granted to You by such Participant under Sections 2.1(b)
and 2.2(b) are revoked effective as of the date You first made, used,
sold, distributed, or had made, Modifications made by that
Participant.
8.3. If You assert a patent infringement claim against Participant
alleging that such Participant's Contributor Version directly or
indirectly infringes any patent where such claim is resolved (such as
by license or settlement) prior to the initiation of patent
infringement litigation, then the reasonable value of the licenses
granted by such Participant under Sections 2.1 or 2.2 shall be taken
into account in determining the amount or value of any payment or
license.
8.4. In the event of termination under Sections 8.1 or 8.2 above,
all end user license agreements (excluding distributors and resellers)
which have been validly granted by You or any distributor hereunder
prior to termination shall survive termination.
9. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
(INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
10. U.S. GOVERNMENT END USERS.
The Covered Code is a "commercial item," as that term is defined in
48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
software" and "commercial computer software documentation," as such
terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
all U.S. Government End Users acquire Covered Code with only those
rights set forth herein.
11. MISCELLANEOUS.
This License represents the complete agreement concerning subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. This License shall be governed by
California law provisions (except to the extent applicable law, if
any, provides otherwise), excluding its conflict-of-law provisions.
With respect to disputes in which at least one party is a citizen of,
or an entity chartered or registered to do business in the United
States of America, any litigation relating to this License shall be
subject to the jurisdiction of the Federal Courts of the Northern
District of California, with venue lying in Santa Clara County,
California, with the losing party responsible for costs, including
without limitation, court costs and reasonable attorneys' fees and
expenses. The application of the United Nations Convention on
Contracts for the International Sale of Goods is expressly excluded.
Any law or regulation which provides that the language of a contract
shall be construed against the drafter shall not apply to this
License.
12. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer and the Contributors, each party is
responsible for claims and damages arising, directly or indirectly,
out of its utilization of rights under this License and You agree to
work with Initial Developer and Contributors to distribute such
responsibility on an equitable basis. Nothing herein is intended or
shall be deemed to constitute any admission of liability.
13. MULTIPLE-LICENSED CODE.
Initial Developer may designate portions of the Covered Code as
"Multiple-Licensed". "Multiple-Licensed" means that the Initial
Developer permits you to utilize portions of the Covered Code under
Your choice of the MPL or the alternative licenses, if any, specified
by the Initial Developer in the file described in Exhibit A.
EXHIBIT A -Mozilla Public License.
``The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
https://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
The Original Code is ______________________________________.
The Initial Developer of the Original Code is ________________________.
Portions created by ______________________ are Copyright (C) ______
_______________________. All Rights Reserved.
Contributor(s): ______________________________________.
Alternatively, the contents of this file may be used under the terms
of the _____ license (the "[___] License"), in which case the
provisions of [______] License are applicable instead of those
above. If you wish to allow use of your version of this file only
under the terms of the [____] License and not to allow others to use
your version of this file under the MPL, indicate your decision by
deleting the provisions above and replace them with the notice and
other provisions required by the [___] License. If you do not delete
the provisions above, a recipient may use your version of this file
under either the MPL or the [___] License."
[NOTE: The text of this Exhibit A may differ slightly from the text of
the notices in the Source Code files of the Original Code. You should
use the text of this Exhibit A rather than the text found in the
Original Code Source Code for Your Modifications.]
| engine/tools/licenses/data/mozilla-1.1/0 | {
"file_path": "engine/tools/licenses/data/mozilla-1.1",
"repo_id": "engine",
"token_count": 7418
} | 439 |
#!/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.
# A script for re-running prod builds on LUCI
#
# Usage:
# $ build.py --commit [Engine commit hash] --builder [builder name]
#
# NOTE: This script requires python3.7 or later.
#
import argparse
import os
import re
import subprocess
import sys
def GetAllBuilders():
curl_command = [
'curl',
'https://ci.chromium.org/p/flutter/g/engine/builders',
]
curl_result = subprocess.run(
curl_command,
universal_newlines=True,
capture_output=True,
)
if curl_result.returncode != 0:
print('Failed to fetch builder list: stderr:\n%s' % curl_result.stderr)
return []
sed_command = [
'sed',
'-En',
's:.*aria-label="builder buildbucket/luci\\.flutter\\.prod/([^/]+)".*:\\1:p',
]
sed_result = subprocess.run(
sed_command,
input=curl_result.stdout,
capture_output=True,
universal_newlines=True,
)
if sed_result.returncode != 0:
print('Failed to fetch builder list: stderr:\n%s' % sed_result.stderr)
return list(set(sed_result.stdout.splitlines()))
def Main():
parser = argparse.ArgumentParser(description='Reruns Engine LUCI prod builds')
parser.add_argument(
'--force-upload',
action='store_true',
default=False,
help='Force artifact upload, overwriting existing artifacts.'
)
parser.add_argument('--all', action='store_true', default=False, help='Re-run all builds.')
parser.add_argument('--builder', type=str, help='The builer to rerun.')
parser.add_argument('--commit', type=str, required=True, help='The commit to rerun.')
parser.add_argument(
'--dry-run', action='store_true', help='Print what would be done, but do nothing.'
)
args = parser.parse_args()
if 'help' in vars(args) and args.help:
parser.print_help()
return 0
if args.all:
builders = GetAllBuilders()
elif args.builder == None:
print('Either --builder or --all is required.')
return 1
else:
builders = [args.builder]
auth_command = [
'gcloud',
'auth',
'print-identity-token',
]
auth_result = subprocess.run(
auth_command,
universal_newlines=True,
capture_output=True,
)
if auth_result.returncode != 0:
print('Auth failed:\nstdout:\n%s\nstderr:\n%s' % (auth_result.stdout, auth_result.stderr))
return 1
auth_token = auth_result.stdout.rstrip()
for builder in builders:
if args.force_upload:
params = (
'{"Commit": "%s", "Builder": "%s", "Repo": "engine", "Properties": {"force_upload":true}}'
% (args.commit, builder)
)
else:
params = '{"Commit": "%s", "Builder": "%s", "Repo": "engine"}' % (args.commit, builder)
curl_command = [
'curl',
'http://flutter-dashboard.appspot.com/api/reset-prod-task',
"-d %s" % params,
'-H',
'X-Flutter-IdToken: %s' % auth_token,
]
if args.dry_run:
print('Running: %s' % ' '.join(curl_command))
else:
result = subprocess.run(curl_command)
if result.returncode != 0:
print('Trigger for %s failed. Aborting.' % builder)
return 1
return 0
if __name__ == '__main__':
sys.exit(Main())
| engine/tools/luci/build.py/0 | {
"file_path": "engine/tools/luci/build.py",
"repo_id": "engine",
"token_count": 1344
} | 440 |
// 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 'package:yaml/yaml.dart' as y;
// This file contains classes for parsing information about CI configuration
// from the .ci.yaml file at the root of the flutter/engine repository.
// The meanings of the sections and fields are documented at:
//
// https://github.com/flutter/cocoon/blob/main/CI_YAML.md
//
// The classes here don't parse every possible field, but rather only those that
// are useful for working locally in the engine repo.
const String _targetsField = 'targets';
const String _nameField = 'name';
const String _recipeField = 'recipe';
const String _propertiesField = 'properties';
const String _configNameField = 'config_name';
/// A class containing the information deserialized from the .ci.yaml file.
///
/// The file contains three sections. "enabled_branches", "platform_properties",
/// and "targets". The "enabled_branches" section is not meaningful when working
/// locally. The configurations listed in the "targets" section inherit
/// properties listed in the "platform_properties" section depending on their
/// names. The configurations listed in the "targets" section are the names,
/// recipes, build configs, etc. of the builders in CI.
class CiConfig {
/// Builds a [CiConfig] instance from parsed yaml data.
///
/// If the yaml was malformed, then `CiConfig.valid` will be false, and
/// `CiConfig.error` will be populated with an informative error message.
/// Otherwise, `CiConfig.ciTargets` will contain a mapping from target name
/// to [CiTarget] instance.
factory CiConfig.fromYaml(y.YamlNode yaml) {
if (yaml is! y.YamlMap) {
final String error = yaml.span.message('Expected a map');
return CiConfig._error(error);
}
final y.YamlMap ymap = yaml;
final y.YamlNode? targetsNode = ymap.nodes[_targetsField];
if (targetsNode == null) {
final String error = ymap.span.message('Expected a "$_targetsField" key');
return CiConfig._error(error);
}
if (targetsNode is! y.YamlList) {
final String error = targetsNode.span.message(
'Expected "$_targetsField" to be a list.',
);
return CiConfig._error(error);
}
final y.YamlList targetsList = targetsNode;
final Map<String, CiTarget> result = <String, CiTarget>{};
for (final y.YamlNode yamlTarget in targetsList.nodes) {
final CiTarget target = CiTarget.fromYaml(yamlTarget);
if (!target.valid) {
return CiConfig._error(target.error);
}
result[target.name] = target;
}
return CiConfig._(ciTargets: result);
}
CiConfig._({
required this.ciTargets,
}) : error = null;
CiConfig._error(
this.error,
) : ciTargets = <String, CiTarget>{};
/// Information about CI builder configurations, which .ci.yaml calls
/// "targets".
final Map<String, CiTarget> ciTargets;
/// An error message when this instance is invalid.
final String? error;
/// Whether this is a valid instance.
late final bool valid = error == null;
}
/// Information about the configuration of a builder on CI, which .ci.yaml
/// calls a "target".
class CiTarget {
/// Builds a [CiTarget] from parsed yaml data.
///
/// If the yaml was malformed then `CiTarget.valid` is false and
/// `CiTarget.error` contains a useful error message. Otherwise, the other
/// fields contain information about the target.
factory CiTarget.fromYaml(y.YamlNode yaml) {
if (yaml is! y.YamlMap) {
final String error = yaml.span.message('Expected a map.');
return CiTarget._error(error);
}
final y.YamlMap targetMap = yaml;
final String? name = _stringOfNode(targetMap.nodes[_nameField]);
if (name == null) {
final String error = targetMap.span.message(
'Expected map to contain a string value for key "$_nameField".',
);
return CiTarget._error(error);
}
final String? recipe = _stringOfNode(targetMap.nodes[_recipeField]);
if (recipe == null) {
final String error = targetMap.span.message(
'Expected map to contain a string value for key "$_recipeField".',
);
return CiTarget._error(error);
}
final y.YamlNode? propertiesNode = targetMap.nodes[_propertiesField];
if (propertiesNode == null) {
final String error = targetMap.span.message(
'Expected map to contain a string value for key "$_propertiesField".',
);
return CiTarget._error(error);
}
final CiTargetProperties properties = CiTargetProperties.fromYaml(
propertiesNode,
);
if (!properties.valid) {
return CiTarget._error(properties.error);
}
return CiTarget._(
name: name,
recipe: recipe,
properties: properties,
);
}
CiTarget._({
required this.name,
required this.recipe,
required this.properties,
}) : error = null;
CiTarget._error(
this.error,
) : name = '',
recipe = '',
properties = CiTargetProperties._error('Invalid');
/// The name of the builder in CI.
final String name;
/// The CI recipe used to run the build.
final String recipe;
/// The properties of the build or builder.
final CiTargetProperties properties;
/// An error message when this instance is invalid.
final String? error;
/// Whether this is a valid instance.
late final bool valid = error == null;
}
/// Various properties of a [CiTarget].
class CiTargetProperties {
/// Builds a [CiTargetProperties] instance from parsed yaml data.
///
/// If the yaml was malformed then `CiTargetProperties.valid` is false and
/// `CiTargetProperties.error` contains a useful error message. Otherwise, the
/// other fields contain information about the target properties.
factory CiTargetProperties.fromYaml(y.YamlNode yaml) {
if (yaml is! y.YamlMap) {
final String error = yaml.span.message(
'Expected "$_propertiesField" to be a map.',
);
return CiTargetProperties._error(error);
}
final y.YamlMap propertiesMap = yaml;
final String? configName = _stringOfNode(
propertiesMap.nodes[_configNameField],
);
return CiTargetProperties._(
configName: configName ?? '',
);
}
CiTargetProperties._({
required this.configName,
}) : error = null;
CiTargetProperties._error(
this.error,
) : configName = '';
/// The name of the build configuration. If the containing [CiTarget] instance
/// is using the engine_v2 recipes, then this name is the same as the name
/// of the build config json file under ci/builders.
final String configName;
/// An error message when this instance is invalid.
final String? error;
/// Whether this is a valid instance.
late final bool valid = error == null;
}
String? _stringOfNode(y.YamlNode? stringNode) {
if (stringNode == null) {
return null;
}
if (stringNode is! y.YamlScalar) {
return null;
}
final y.YamlScalar stringScalar = stringNode;
if (stringScalar.value is! String) {
return null;
}
return stringScalar.value as String;
}
| engine/tools/pkg/engine_build_configs/lib/src/ci_yaml.dart/0 | {
"file_path": "engine/tools/pkg/engine_build_configs/lib/src/ci_yaml.dart",
"repo_id": "engine",
"token_count": 2398
} | 441 |
// 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';
import 'dart:io' as io;
import 'package:process/process.dart';
/// A fake implementation of [ProcessManager] that allows control for testing.
final class FakeProcessManager implements ProcessManager {
/// Creates a fake process manager delegates to [onRun] and [onStart].
///
/// If either is not provided, it throws an [UnsupportedError] when called.
FakeProcessManager({
io.ProcessResult Function(List<String> command) onRun = unhandledRun,
io.Process Function(List<String> command) onStart = unhandledStart,
bool Function(Object?, {String? workingDirectory}) canRun = unhandledCanRun,
}) : _onRun = onRun, _onStart = onStart, _canRun = canRun;
/// A default implementation of [onRun] that throws an [UnsupportedError].
static io.ProcessResult unhandledRun(List<String> command) {
throw UnsupportedError('Unhandled run: ${command.join(' ')}');
}
/// A default implementation of [onStart] that throws an [UnsupportedError].
static io.Process unhandledStart(List<String> command) {
throw UnsupportedError('Unhandled start: ${command.join(' ')}');
}
/// A default implementation of [canRun] that returns `true`.
static bool unhandledCanRun(Object? executable, {String? workingDirectory}) {
return true;
}
final io.ProcessResult Function(List<String> command) _onRun;
final io.Process Function(List<String> command) _onStart;
final bool Function(Object?, {String? workingDirectory}) _canRun;
@override
bool canRun(Object? executable, {String? workingDirectory}) {
return _canRun(executable, workingDirectory: workingDirectory);
}
@override
bool killPid(int pid, [io.ProcessSignal signal = io.ProcessSignal.sigterm]) => true;
@override
Future<io.ProcessResult> run(
List<Object> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
Encoding stdoutEncoding = io.systemEncoding,
Encoding stderrEncoding = io.systemEncoding,
}) async {
return runSync(
command,
workingDirectory: workingDirectory,
environment: environment,
includeParentEnvironment: includeParentEnvironment,
runInShell: runInShell,
stdoutEncoding: stdoutEncoding,
stderrEncoding: stderrEncoding,
);
}
@override
io.ProcessResult runSync(
List<Object> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
Encoding stdoutEncoding = io.systemEncoding,
Encoding stderrEncoding = io.systemEncoding,
}) {
return _onRun(command.map((Object o) => '$o').toList());
}
@override
Future<io.Process> start(
List<Object> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
io.ProcessStartMode mode = io.ProcessStartMode.normal,
}) async {
return _onStart(command.map((Object o) => '$o').toList());
}
}
/// An incomplete fake of [io.Process] that allows control for testing.
final class FakeProcess implements io.Process {
/// Creates a fake process that returns the given [exitCode] and out/err.
FakeProcess({
int exitCode = 0,
String stdout = '',
String stderr = '',
}) : _exitCode = exitCode,
_stdout = stdout,
_stderr = stderr;
final int _exitCode;
final String _stdout;
final String _stderr;
@override
Future<int> get exitCode async => _exitCode;
@override
bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) => true;
@override
int get pid => 0;
@override
Stream<List<int>> get stderr {
return Stream<List<int>>.fromIterable(<List<int>>[io.systemEncoding.encoder.convert(_stderr)]);
}
@override
io.IOSink get stdin => throw UnimplementedError();
@override
Stream<List<int>> get stdout {
return Stream<List<int>>.fromIterable(<List<int>>[io.systemEncoding.encoder.convert(_stdout)]);
}
}
| engine/tools/pkg/process_fakes/lib/process_fakes.dart/0 | {
"file_path": "engine/tools/pkg/process_fakes/lib/process_fakes.dart",
"repo_id": "engine",
"token_count": 1382
} | 442 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_VULKAN_PROCS_VULKAN_PROC_TABLE_H_
#define FLUTTER_VULKAN_PROCS_VULKAN_PROC_TABLE_H_
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/fml/native_library.h"
#include "flutter/vulkan/procs/vulkan_handle.h"
#include "flutter/vulkan/procs/vulkan_interface.h"
namespace vulkan {
class VulkanProcTable : public fml::RefCountedThreadSafe<VulkanProcTable> {
FML_FRIEND_REF_COUNTED_THREAD_SAFE(VulkanProcTable);
FML_FRIEND_MAKE_REF_COUNTED(VulkanProcTable);
public:
template <class T>
class Proc {
public:
using Proto = T;
explicit Proc(T proc = nullptr) : proc_(proc) {}
~Proc() { proc_ = nullptr; }
Proc operator=(T proc) {
proc_ = proc;
return *this;
}
Proc operator=(PFN_vkVoidFunction proc) {
proc_ = reinterpret_cast<Proto>(proc);
return *this;
}
explicit operator bool() const { return proc_ != nullptr; }
operator T() const { return proc_; } // NOLINT(google-explicit-constructor)
private:
T proc_;
};
VulkanProcTable();
explicit VulkanProcTable(const char* so_path);
explicit VulkanProcTable(PFN_vkGetInstanceProcAddr get_instance_proc_addr);
~VulkanProcTable();
bool HasAcquiredMandatoryProcAddresses() const;
bool IsValid() const;
bool AreInstanceProcsSetup() const;
bool AreDeviceProcsSetup() const;
bool SetupInstanceProcAddresses(const VulkanHandle<VkInstance>& instance);
bool SetupDeviceProcAddresses(const VulkanHandle<VkDevice>& device);
PFN_vkGetInstanceProcAddr GetInstanceProcAddr = nullptr;
#define DEFINE_PROC(name) Proc<PFN_vk##name> name;
DEFINE_PROC(AcquireNextImageKHR);
DEFINE_PROC(AllocateCommandBuffers);
DEFINE_PROC(AllocateMemory);
DEFINE_PROC(BeginCommandBuffer);
DEFINE_PROC(BindImageMemory);
DEFINE_PROC(CmdPipelineBarrier);
DEFINE_PROC(CreateCommandPool);
DEFINE_PROC(CreateDebugReportCallbackEXT);
DEFINE_PROC(CreateDevice);
DEFINE_PROC(CreateFence);
DEFINE_PROC(CreateImage);
DEFINE_PROC(CreateInstance);
DEFINE_PROC(CreateSemaphore);
DEFINE_PROC(CreateSwapchainKHR);
DEFINE_PROC(DestroyCommandPool);
DEFINE_PROC(DestroyDebugReportCallbackEXT);
DEFINE_PROC(DestroyDevice);
DEFINE_PROC(DestroyFence);
DEFINE_PROC(DestroyImage);
DEFINE_PROC(DestroyInstance);
DEFINE_PROC(DestroySemaphore);
DEFINE_PROC(DestroySurfaceKHR);
DEFINE_PROC(DestroySwapchainKHR);
DEFINE_PROC(DeviceWaitIdle);
DEFINE_PROC(EndCommandBuffer);
DEFINE_PROC(EnumerateDeviceLayerProperties);
DEFINE_PROC(EnumerateInstanceExtensionProperties);
DEFINE_PROC(EnumerateInstanceLayerProperties);
DEFINE_PROC(EnumeratePhysicalDevices);
DEFINE_PROC(FreeCommandBuffers);
DEFINE_PROC(FreeMemory);
DEFINE_PROC(GetDeviceProcAddr);
DEFINE_PROC(GetDeviceQueue);
DEFINE_PROC(GetImageMemoryRequirements);
DEFINE_PROC(GetPhysicalDeviceFeatures);
DEFINE_PROC(GetPhysicalDeviceQueueFamilyProperties);
DEFINE_PROC(QueueSubmit);
DEFINE_PROC(QueueWaitIdle);
DEFINE_PROC(ResetCommandBuffer);
DEFINE_PROC(ResetFences);
DEFINE_PROC(WaitForFences);
DEFINE_PROC(GetPhysicalDeviceProperties);
DEFINE_PROC(GetPhysicalDeviceMemoryProperties);
DEFINE_PROC(MapMemory);
DEFINE_PROC(UnmapMemory);
DEFINE_PROC(FlushMappedMemoryRanges);
DEFINE_PROC(InvalidateMappedMemoryRanges);
DEFINE_PROC(BindBufferMemory);
DEFINE_PROC(GetBufferMemoryRequirements);
DEFINE_PROC(CreateBuffer);
DEFINE_PROC(DestroyBuffer);
DEFINE_PROC(CmdCopyBuffer);
DEFINE_PROC(GetPhysicalDeviceMemoryProperties2);
DEFINE_PROC(GetPhysicalDeviceMemoryProperties2KHR);
DEFINE_PROC(GetBufferMemoryRequirements2);
DEFINE_PROC(GetBufferMemoryRequirements2KHR);
DEFINE_PROC(GetImageMemoryRequirements2);
DEFINE_PROC(GetImageMemoryRequirements2KHR);
DEFINE_PROC(BindBufferMemory2);
DEFINE_PROC(BindBufferMemory2KHR);
DEFINE_PROC(BindImageMemory2);
DEFINE_PROC(BindImageMemory2KHR);
#ifndef TEST_VULKAN_PROCS
#if FML_OS_ANDROID
DEFINE_PROC(GetPhysicalDeviceSurfaceCapabilitiesKHR);
DEFINE_PROC(GetPhysicalDeviceSurfaceFormatsKHR);
DEFINE_PROC(GetPhysicalDeviceSurfacePresentModesKHR);
DEFINE_PROC(GetPhysicalDeviceSurfaceSupportKHR);
DEFINE_PROC(GetSwapchainImagesKHR);
DEFINE_PROC(QueuePresentKHR);
DEFINE_PROC(CreateAndroidSurfaceKHR);
#endif // FML_OS_ANDROID
#if OS_FUCHSIA
DEFINE_PROC(ImportSemaphoreZirconHandleFUCHSIA);
DEFINE_PROC(GetSemaphoreZirconHandleFUCHSIA);
DEFINE_PROC(GetMemoryZirconHandleFUCHSIA);
DEFINE_PROC(CreateBufferCollectionFUCHSIA);
DEFINE_PROC(DestroyBufferCollectionFUCHSIA);
DEFINE_PROC(SetBufferCollectionImageConstraintsFUCHSIA);
DEFINE_PROC(GetBufferCollectionPropertiesFUCHSIA);
#endif // OS_FUCHSIA
#endif // TEST_VULKAN_PROCS
#undef DEFINE_PROC
PFN_vkGetInstanceProcAddr NativeGetInstanceProcAddr() const;
PFN_vkVoidFunction AcquireProc(
const char* proc_name,
const VulkanHandle<VkInstance>& instance) const;
PFN_vkVoidFunction AcquireProc(const char* proc_name,
const VulkanHandle<VkDevice>& device) const;
private:
fml::RefPtr<fml::NativeLibrary> handle_;
bool acquired_mandatory_proc_addresses_;
VulkanHandle<VkInstance> instance_;
VulkanHandle<VkDevice> device_;
bool OpenLibraryHandle(const char* path);
bool SetupGetInstanceProcAddress();
bool SetupLoaderProcAddresses();
bool CloseLibraryHandle();
FML_DISALLOW_COPY_AND_ASSIGN(VulkanProcTable);
};
} // namespace vulkan
#endif // FLUTTER_VULKAN_PROCS_VULKAN_PROC_TABLE_H_
| engine/vulkan/procs/vulkan_proc_table.h/0 | {
"file_path": "engine/vulkan/procs/vulkan_proc_table.h",
"repo_id": "engine",
"token_count": 2152
} | 443 |
// 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_native_surface_android.h"
#include <android/native_window.h>
#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h"
namespace vulkan {
VulkanNativeSurfaceAndroid::VulkanNativeSurfaceAndroid(
ANativeWindow* native_window)
: native_window_(native_window) {
if (native_window_ == nullptr) {
return;
}
ANativeWindow_acquire(native_window_);
}
VulkanNativeSurfaceAndroid::~VulkanNativeSurfaceAndroid() {
if (native_window_ == nullptr) {
return;
}
ANativeWindow_release(native_window_);
}
const char* VulkanNativeSurfaceAndroid::GetExtensionName() const {
return VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
}
uint32_t VulkanNativeSurfaceAndroid::GetSkiaExtensionName() const {
return kKHR_android_surface_GrVkExtensionFlag;
}
VkSurfaceKHR VulkanNativeSurfaceAndroid::CreateSurfaceHandle(
VulkanProcTable& vk,
const VulkanHandle<VkInstance>& instance) const {
if (!vk.IsValid() || !instance) {
return VK_NULL_HANDLE;
}
const VkAndroidSurfaceCreateInfoKHR create_info = {
.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR,
.pNext = nullptr,
.flags = 0,
.window = native_window_,
};
VkSurfaceKHR surface = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vk.CreateAndroidSurfaceKHR(
instance, &create_info, nullptr, &surface)) != VK_SUCCESS) {
return VK_NULL_HANDLE;
}
return surface;
}
bool VulkanNativeSurfaceAndroid::IsValid() const {
return native_window_ != nullptr;
}
SkISize VulkanNativeSurfaceAndroid::GetSize() const {
return native_window_ == nullptr
? SkISize::Make(0, 0)
: SkISize::Make(ANativeWindow_getWidth(native_window_),
ANativeWindow_getHeight(native_window_));
}
} // namespace vulkan
| engine/vulkan/vulkan_native_surface_android.cc/0 | {
"file_path": "engine/vulkan/vulkan_native_surface_android.cc",
"repo_id": "engine",
"token_count": 748
} | 444 |
# Copyright 2019 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/build/zip_bundle.gni")
import("//flutter/common/config.gni")
import("//flutter/lib/web_ui/flutter_js/sources.gni")
import("//flutter/web_sdk/web_sdk.gni")
import("$dart_src/build/dart/dart_action.gni")
web_ui_sources = exec_script("$dart_src/tools/list_dart_files.py",
[
"absolute",
rebase_path("//flutter/lib/web_ui/lib"),
],
"list lines")
web_engine_libraries = [
":skwasm_impl_library",
":skwasm_stub_library",
":web_engine_library",
":web_ui_library",
":web_ui_ui_web",
":web_ui_library_sources",
":web_unicode_library",
":web_test_fonts_library",
":web_locale_keymap_library",
]
group("web_sdk") {
deps = [
":flutter_ddc_modules",
":flutter_platform_dills",
"//flutter/lib/web_ui/flutter_js",
]
}
sdk_rewriter("web_ui_library_sources") {
ui = true
input_dir = "//flutter/lib/web_ui/lib/"
output_dir = "$root_out_dir/flutter_web_sdk/lib/ui/"
# exclude everything in the engine directory, it will be a separate internal library
exclude_pattern = rebase_path("//flutter/lib/web_ui/lib/src")
}
web_ui_ui_web_with_output("web_ui_ui_web") {
output_dir = "$root_out_dir/flutter_web_sdk/lib/ui_web/"
}
sdk_rewriter("web_engine_library") {
library_name = "engine"
api_file = "//flutter/lib/web_ui/lib/src/engine.dart"
input_dir = "//flutter/lib/web_ui/lib/src/engine/"
output_dir = "$root_out_dir/flutter_web_sdk/lib/_engine/"
# exclude skwasm, it will be a separate internal library
exclude_pattern = rebase_path("//flutter/lib/web_ui/lib/src/engine/skwasm")
}
sdk_rewriter("skwasm_stub_library") {
library_name = "skwasm_stub"
api_file = "//flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_stub.dart"
input_dir = "//flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/"
output_dir = "$root_out_dir/flutter_web_sdk/lib/_skwasm_stub/"
}
sdk_rewriter("skwasm_impl_library") {
library_name = "skwasm_impl"
api_file = "//flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_impl.dart"
input_dir = "//flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/"
output_dir = "$root_out_dir/flutter_web_sdk/lib/_skwasm_impl/"
}
sdk_rewriter("web_unicode_library") {
library_name = "web_unicode"
api_file = "//flutter/third_party/web_unicode/lib/web_unicode.dart"
input_dir = "//flutter/third_party/web_unicode/lib/web_unicode/"
output_dir = "$root_out_dir/flutter_web_sdk/lib/_web_unicode/"
}
sdk_rewriter("web_test_fonts_library") {
library_name = "web_test_fonts"
api_file = "//flutter/third_party/web_test_fonts/lib/web_test_fonts.dart"
input_dir = "//flutter/third_party/web_test_fonts/lib/web_test_fonts/"
output_dir = "$root_out_dir/flutter_web_sdk/lib/_web_test_fonts/"
}
sdk_rewriter("web_locale_keymap_library") {
library_name = "web_locale_keymap"
api_file =
"//flutter/third_party/web_locale_keymap/lib/web_locale_keymap.dart"
input_dir = "//flutter/third_party/web_locale_keymap/lib/web_locale_keymap/"
output_dir = "$root_out_dir/flutter_web_sdk/lib/_web_locale_keymap/"
}
copy("web_ui_library") {
sources = [ "//flutter/web_sdk/libraries.json" ]
outputs = [ "$root_out_dir/flutter_web_sdk/{{source_file_part}}" ]
}
# Compiles a Dart program with dartdevc
#
# Parameters:
#
# inputs (required): The inputs to dartdevc
#
# outputs (required): The files generated by dartdevc
#
# args (required): The arguments to pass to dartdevc
template("_dartdevc") {
if (flutter_prebuilt_dart_sdk) {
action(target_name) {
not_needed(invoker, [ "packages" ])
deps = web_engine_libraries
script = "//build/gn_run_binary.py"
inputs = invoker.inputs
outputs = invoker.outputs
pool = "//flutter/build/dart:dart_pool"
ext = ""
if (is_win) {
ext = ".exe"
}
dart = rebase_path("$host_prebuilt_dart_sdk/bin/dart$ext", root_out_dir)
dartdevc = rebase_path(
"$host_prebuilt_dart_sdk/bin/snapshots/dartdevc.dart.snapshot")
args = [
dart,
dartdevc,
] + invoker.args
}
} else {
prebuilt_dart_action(target_name) {
forward_variables_from(invoker, "*")
deps = web_engine_libraries + [
"$dart_src:create_sdk",
"$dart_src/pkg:pkg_files_stamp",
"$dart_src/utils/ddc:ddc_files_stamp",
"$dart_src/utils/ddc:ddc_sdk_patch_stamp",
]
script = "$dart_src/pkg/dev_compiler/bin/dartdevc.dart"
pool = "//flutter/build/dart:dart_pool"
}
}
}
# Compiles a Dart SDK with the kernel_worker
#
# Parameters:
#
# inputs (required): The inputs to the kernel_worker
#
# outputs (required): The files generated by the kernel_worker
#
# args (required): The arguments to pass to the kernel_worker
template("_kernel_worker") {
if (flutter_prebuilt_dart_sdk) {
action(target_name) {
deps = web_engine_libraries
script = "//build/gn_run_binary.py"
inputs = invoker.inputs
outputs = invoker.outputs
pool = "//flutter/build/dart:dart_pool"
ext = ""
if (is_win) {
ext = ".exe"
}
dart = rebase_path("$host_prebuilt_dart_sdk/bin/dart$ext", root_out_dir)
kernel_worker = rebase_path(
"$host_prebuilt_dart_sdk/bin/snapshots/kernel_worker.dart.snapshot")
args = [
dart,
kernel_worker,
] + invoker.args
}
} else {
prebuilt_dart_action(target_name) {
forward_variables_from(invoker, "*")
deps = web_engine_libraries + [
"$dart_src:create_sdk",
"$dart_src/pkg:pkg_files_stamp",
"$dart_src/utils/ddc:ddc_files_stamp",
"$dart_src/utils/ddc:ddc_sdk_patch_stamp",
]
script = "$dart_src/utils/bazel/kernel_worker.dart"
pool = "//flutter/build/dart:dart_pool"
}
}
}
template("_compile_platform") {
assert(defined(invoker.sound_null_safety),
"sound_null_safety must be defined for $target_name")
assert(defined(invoker.kernel_target),
"kernel_target must be defined for $target_name")
assert(defined(invoker.summary_only),
"summary_only must be defined for $target_name")
assert(defined(invoker.output_dill),
"output_dill must be defined for $target_name")
_kernel_worker(target_name) {
inputs = [ "sdk_rewriter.dart" ] + web_ui_sources
outputs = [ invoker.output_dill ]
if (invoker.sound_null_safety) {
args = [ "--sound-null-safety" ]
} else {
args = [ "--no-sound-null-safety" ]
}
if (invoker.summary_only) {
args += [ "--summary-only" ]
} else {
args += [ "--no-summary-only" ]
}
if (defined(invoker.null_environment) && invoker.null_environment) {
args += [ "--null-environment" ]
}
skwasm_library = "dart:_skwasm_stub"
if (invoker.kernel_target == "dart2wasm") {
skwasm_library = "dart:_skwasm_impl"
}
args += [
"--target",
"${invoker.kernel_target}",
"--packages-file",
"file:///" + rebase_path(dart_sdk_package_config),
"--multi-root-scheme",
"org-dartlang-sdk",
"--multi-root",
"file:///" + rebase_path("$root_out_dir/flutter_web_sdk"),
"--libraries-file",
"org-dartlang-sdk:///libraries.json",
"--output",
rebase_path(invoker.output_dill),
"--source",
"dart:core",
# Additional Flutter web dart libraries
"--source",
"dart:ui",
"--source",
"dart:ui_web",
"--source",
"dart:_engine",
"--source",
skwasm_library,
"--source",
"dart:_web_unicode",
"--source",
"dart:_web_locale_keymap",
]
if (flutter_prebuilt_dart_sdk) {
args += [
"--multi-root",
"file:///" + rebase_path("$host_prebuilt_dart_sdk/.."),
]
} else {
args += [
"--multi-root",
"file:///" + rebase_path("$root_out_dir"),
]
}
}
}
# Compile the unsound DDC SDK's summary.
_compile_platform("flutter_dartdevc_kernel_sdk_outline_unsound") {
sound_null_safety = false
kernel_target = "ddc"
summary_only = true
output_dill = "$root_out_dir/flutter_web_sdk/kernel/ddc_outline.dill"
}
# Compile the sound DDC SDK's summary.
_compile_platform("flutter_dartdevc_kernel_sdk_outline_sound") {
sound_null_safety = true
kernel_target = "ddc"
summary_only = true
output_dill = "$root_out_dir/flutter_web_sdk/kernel/ddc_outline_sound.dill"
}
_compile_platform("flutter_dart2js_kernel_sdk_full_unsound") {
sound_null_safety = false
kernel_target = "dart2js"
summary_only = false
output_dill =
"$root_out_dir/flutter_web_sdk/kernel/dart2js_platform_unsound.dill"
null_environment = true
}
_compile_platform("flutter_dart2js_kernel_sdk_full_sound") {
sound_null_safety = true
kernel_target = "dart2js"
summary_only = false
output_dill = "$root_out_dir/flutter_web_sdk/kernel/dart2js_platform.dill"
null_environment = true
}
_compile_platform("flutter_dart2wasm_kernel_sdk_full_sound") {
sound_null_safety = true
kernel_target = "dart2wasm"
summary_only = false
output_dill = "$root_out_dir/flutter_web_sdk/kernel/dart2wasm_platform.dill"
null_environment = true
}
group("flutter_platform_dills") {
public_deps = [
":flutter_dart2js_kernel_sdk_full_sound",
":flutter_dart2js_kernel_sdk_full_unsound",
":flutter_dart2wasm_kernel_sdk_full_sound",
":flutter_dartdevc_kernel_sdk_outline_sound",
":flutter_dartdevc_kernel_sdk_outline_unsound",
# TODO(jacksongardner): remove these once they are no longer used by the flutter tool
# https://github.com/flutter/flutter/issues/113303
":flutter_dartdevc_kernel_sdk_outline_sound",
":flutter_dartdevc_kernel_sdk_outline_unsound",
]
}
template("_compile_ddc_modules") {
assert(defined(invoker.sound_null_safety),
"sound_null_safety must be defined for $target_name")
assert(defined(invoker.use_skia),
"use_skia must be defined for $target_name")
assert(defined(invoker.auto_detect),
"auto_detect must be defined for $target_name")
_dartdevc(target_name) {
inputs = [ "sdk_rewriter.dart" ] + web_ui_sources
packages = dart_sdk_package_config
name_suffix = ""
if (invoker.use_skia) {
name_suffix += "-canvaskit"
}
if (invoker.auto_detect) {
name_suffix += "-html"
}
if (invoker.sound_null_safety) {
name_suffix += "-sound"
}
amd_js_path =
"$root_out_dir/flutter_web_sdk/kernel/amd${name_suffix}/dart_sdk.js"
ddc_js_path =
"$root_out_dir/flutter_web_sdk/kernel/ddc${name_suffix}/dart_sdk.js"
outputs = [
amd_js_path,
amd_js_path + ".map",
ddc_js_path,
ddc_js_path + ".map",
]
if (invoker.sound_null_safety) {
args = [ "--sound-null-safety" ]
} else {
args = [ "--no-sound-null-safety" ]
}
args += [
"--compile-sdk",
"dart:core",
# Additional Flutter web dart libraries
"dart:ui",
"dart:ui_web",
"dart:_engine",
"dart:_skwasm_stub",
"dart:_web_unicode",
"dart:_web_locale_keymap",
"--no-summarize",
"--packages",
"file:///" + rebase_path(dart_sdk_package_config),
"--multi-root-scheme",
"org-dartlang-sdk",
"--multi-root",
"file:///" + rebase_path("$root_out_dir/flutter_web_sdk"),
"--multi-root-output-path",
rebase_path("$root_out_dir/"),
"--libraries-file",
"org-dartlang-sdk:///libraries.json",
"--inline-source-map",
"-DFLUTTER_WEB_USE_SKIA=${invoker.use_skia}",
"-DFLUTTER_WEB_AUTO_DETECT=${invoker.auto_detect}",
"--modules",
"amd",
"-o",
rebase_path(amd_js_path),
"--modules",
"ddc",
"-o",
rebase_path(ddc_js_path),
]
if (flutter_prebuilt_dart_sdk) {
args += [
"--multi-root",
"file:///" + rebase_path("$host_prebuilt_dart_sdk/.."),
]
} else {
args += [
"--multi-root",
"file:///" + rebase_path("$root_out_dir"),
]
}
}
}
# Compiles the unsound html only renderer.
_compile_ddc_modules("flutter_dartdevc_kernel_sdk") {
sound_null_safety = false
use_skia = false
auto_detect = false
}
# Compiles the unsound canvaskit only renderer.
_compile_ddc_modules("flutter_dartdevc_canvaskit_kernel_sdk") {
sound_null_safety = false
use_skia = true
auto_detect = false
}
# Compiles the unsound autodetect renderer.
_compile_ddc_modules("flutter_dartdevc_canvaskit_html_kernel_sdk") {
sound_null_safety = false
use_skia = true
auto_detect = true
}
# Compiles the sound html only renderer.
_compile_ddc_modules("flutter_dartdevc_kernel_sdk_sound") {
sound_null_safety = true
use_skia = false
auto_detect = false
}
# Compiles the sound canvaskit only renderer.
_compile_ddc_modules("flutter_dartdevc_canvaskit_kernel_sdk_sound") {
sound_null_safety = true
use_skia = true
auto_detect = false
}
# Compiles the sound autodetect renderer.
_compile_ddc_modules("flutter_dartdevc_canvaskit_html_kernel_sdk_sound") {
sound_null_safety = true
use_skia = true
auto_detect = true
}
group("flutter_ddc_modules") {
public_deps = [
":flutter_dartdevc_canvaskit_html_kernel_sdk",
":flutter_dartdevc_canvaskit_html_kernel_sdk_sound",
":flutter_dartdevc_canvaskit_kernel_sdk",
":flutter_dartdevc_canvaskit_kernel_sdk_sound",
":flutter_dartdevc_kernel_sdk",
":flutter_dartdevc_kernel_sdk_sound",
]
}
# Archives Flutter Web SDK
if (!is_fuchsia) {
zip_bundle_from_file("flutter_web_sdk_archive") {
output = "flutter-web-sdk.zip"
deps = [
":flutter_ddc_modules",
":flutter_platform_dills",
] + web_engine_libraries
if (is_wasm) {
deps += [
"//flutter/third_party/canvaskit:canvaskit_chromium_group",
"//flutter/third_party/canvaskit:canvaskit_group",
"//flutter/third_party/canvaskit:skwasm_group",
]
}
deps += [ "//flutter/lib/web_ui/flutter_js" ]
# flutter_ddc_modules
sources = get_target_outputs(":flutter_dartdevc_kernel_sdk")
sources += get_target_outputs(":flutter_dartdevc_canvaskit_kernel_sdk")
sources += get_target_outputs(":flutter_dartdevc_canvaskit_html_kernel_sdk")
sources += get_target_outputs(":flutter_dartdevc_kernel_sdk_sound")
sources +=
get_target_outputs(":flutter_dartdevc_canvaskit_kernel_sdk_sound")
sources +=
get_target_outputs(":flutter_dartdevc_canvaskit_html_kernel_sdk_sound")
# flutter_platform_dills
sources +=
get_target_outputs(":flutter_dartdevc_kernel_sdk_outline_unsound")
sources += get_target_outputs(":flutter_dartdevc_kernel_sdk_outline_sound")
sources += get_target_outputs(":flutter_dart2js_kernel_sdk_full_unsound")
sources += get_target_outputs(":flutter_dart2js_kernel_sdk_full_sound")
sources += get_target_outputs(":flutter_dart2wasm_kernel_sdk_full_sound")
if (is_wasm) {
sources += [
"$root_out_dir/flutter_web_sdk/canvaskit/canvaskit.js",
"$root_out_dir/flutter_web_sdk/canvaskit/canvaskit.js.symbols",
"$root_out_dir/flutter_web_sdk/canvaskit/canvaskit.wasm",
"$root_out_dir/flutter_web_sdk/canvaskit/chromium/canvaskit.js",
"$root_out_dir/flutter_web_sdk/canvaskit/chromium/canvaskit.js.symbols",
"$root_out_dir/flutter_web_sdk/canvaskit/chromium/canvaskit.wasm",
"$root_out_dir/flutter_web_sdk/canvaskit/skwasm.js",
"$root_out_dir/flutter_web_sdk/canvaskit/skwasm.js.symbols",
"$root_out_dir/flutter_web_sdk/canvaskit/skwasm.wasm",
"$root_out_dir/flutter_web_sdk/canvaskit/skwasm.worker.js",
]
}
# flutter.js full sources
foreach(source, flutter_js_source_list) {
sources += [ "$root_out_dir/flutter_web_sdk/flutter_js/$source" ]
}
# flutter.js bundled source and sourcemap
sources += [
"$root_out_dir/flutter_web_sdk/flutter_js/flutter.js",
"$root_out_dir/flutter_web_sdk/flutter_js/flutter.js.map",
]
foreach(web_engine_library, web_engine_libraries) {
sources += get_target_outputs(web_engine_library)
}
tmp_files = []
web_sdk_files =
filter_include(sources, [ "$root_build_dir/flutter_web_sdk/**" ])
foreach(source, web_sdk_files) {
tmp_files += [
{
source = rebase_path(source)
destination = rebase_path(source, "$root_build_dir/flutter_web_sdk")
},
]
}
files = tmp_files
}
}
| engine/web_sdk/BUILD.gn/0 | {
"file_path": "engine/web_sdk/BUILD.gn",
"repo_id": "engine",
"token_count": 7888
} | 445 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:path/path.dart' as pathlib;
/// Contains various environment variables, such as common file paths and command-line options.
Environment get environment {
return _environment ??= Environment();
}
Environment? _environment;
/// Contains various environment variables, such as common file paths and command-line options.
class Environment {
/// Creates an environment deduced from the path of the main Dart script.
factory Environment() {
final io.File script = io.File.fromUri(io.Platform.script);
io.Directory directory = script.parent;
bool foundEngineRepoRoot = false;
while (!foundEngineRepoRoot) {
foundEngineRepoRoot = directory
.listSync()
.whereType<io.File>()
.map((io.File file) => pathlib.basename(file.path))
.contains('DEPS');
final io.Directory parent = directory.parent;
if (parent.path == directory.path) {
throw Exception(
'Failed to locate the root of the engine repository starting from ${script.path}',
);
}
directory = parent;
}
return _prepareEnvironmentFromEngineDir(script, directory);
}
Environment._({
required this.self,
required this.webUiRootDir,
required this.engineSrcDir,
required this.engineToolsDir,
});
static Environment _prepareEnvironmentFromEngineDir(
io.File self, io.Directory engineSrcDir) {
final io.Directory engineToolsDir =
io.Directory(pathlib.join(engineSrcDir.path, 'flutter', 'tools'));
final io.Directory webUiRootDir = io.Directory(
pathlib.join(engineSrcDir.path, 'flutter', 'lib', 'web_ui'));
for (final io.Directory expectedDirectory in <io.Directory>[
engineSrcDir,
webUiRootDir
]) {
if (!expectedDirectory.existsSync()) {
throw Exception('$expectedDirectory does not exist.');
}
}
return Environment._(
self: self,
webUiRootDir: webUiRootDir,
engineSrcDir: engineSrcDir,
engineToolsDir: engineToolsDir,
);
}
/// The Dart script that's currently running.
final io.File self;
/// Path to the "web_ui" package sources.
final io.Directory webUiRootDir;
/// Path to the engine's "src" directory.
final io.Directory engineSrcDir;
/// Path to the engine's "tools" directory.
final io.Directory engineToolsDir;
/// Path to where github.com/flutter/engine is checked out inside the engine workspace.
io.Directory get flutterDirectory =>
io.Directory(pathlib.join(engineSrcDir.path, 'flutter'));
/// Path to the "web_sdk" directory in the engine source tree.
io.Directory get webSdkRootDir => io.Directory(pathlib.join(
flutterDirectory.path,
'web_sdk',
));
/// Path to the "web_engine_tester" package.
io.Directory get webEngineTesterRootDir => io.Directory(pathlib.join(
webSdkRootDir.path,
'web_engine_tester',
));
/// Path to the "build" directory, generated by "package:build_runner".
///
/// This is where compiled output goes.
io.Directory get webUiBuildDir => io.Directory(pathlib.join(
engineSrcDir.path,
'out',
'web_tests',
));
/// Path to the ".dart_tool" directory, generated by various Dart tools.
io.Directory get webUiDartToolDir => io.Directory(pathlib.join(
webUiRootDir.path,
'.dart_tool',
));
/// Path to the ".dart_tool" directory living under `engine/src/flutter`.
///
/// This is a designated area for tool downloads which can be used by
/// multiple platforms. For exampe: Flutter repo for e2e tests.
io.Directory get engineDartToolDir => io.Directory(pathlib.join(
engineSrcDir.path,
'flutter',
'.dart_tool',
));
/// Path to the "dev" directory containing engine developer tools and
/// configuration files.
io.Directory get webUiDevDir => io.Directory(pathlib.join(
webUiRootDir.path,
'dev',
));
/// Path to the "test" directory containing web engine tests.
io.Directory get webUiTestDir => io.Directory(pathlib.join(
webUiRootDir.path,
'test',
));
/// Path to the "lib" directory containing web engine code.
io.Directory get webUiLibDir => io.Directory(pathlib.join(
webUiRootDir.path,
'lib',
));
/// Path to the base directory to be used by Skia Gold.
io.Directory get webUiSkiaGoldDirectory => io.Directory(pathlib.join(
webUiDartToolDir.path,
'skia_gold',
));
/// Directory to add test results which would later be uploaded to a gcs
/// bucket by LUCI.
io.Directory get webUiTestResultsDirectory => io.Directory(pathlib.join(
webUiDartToolDir.path,
'test_results',
));
/// Path to the screenshots taken by iOS simulator.
io.Directory get webUiSimulatorScreenshotsDirectory =>
io.Directory(pathlib.join(
webUiDartToolDir.path,
'ios_screenshots',
));
}
| engine/web_sdk/web_test_utils/lib/environment.dart/0 | {
"file_path": "engine/web_sdk/web_test_utils/lib/environment.dart",
"repo_id": "engine",
"token_count": 1852
} | 446 |
<component name="libraryTable">
<library name="intellij-coverage-agent-1.0.579">
<CLASSES>
<root url="jar:///Applications/IntelliJ IDEA 2021.1.1 EAP.app/Contents/lib/intellij-coverage-agent-1.0.579.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component> | flutter-intellij/.idea/libraries/intellij_coverage_agent_1_0_579.xml/0 | {
"file_path": "flutter-intellij/.idea/libraries/intellij_coverage_agent_1_0_579.xml",
"repo_id": "flutter-intellij",
"token_count": 126
} | 447 |
# <img src="https://github.com/dart-lang/site-shared/blob/master/src/_assets/image/flutter/icon/64.png?raw=1" alt="Flutter" width="26" height="26"/> Flutter Plugin for IntelliJ
[](https://plugins.jetbrains.com/plugin/9212-flutter)
[](https://travis-ci.org/flutter/flutter-intellij)
An IntelliJ plugin for [Flutter](https://flutter.dev/) development. Flutter is a multi-platform
app SDK to help developers and designers build modern apps for iOS, Android and the web.
## Documentation
- [flutter.dev](https://flutter.dev)
- [Installing Flutter](https://flutter.dev/docs/get-started/install)
- [Getting Started with IntelliJ](https://flutter.dev/docs/development/tools/ide)
## Fast development
Flutter's <em>hot reload</em> helps you quickly and easily experiment, build UIs, add features,
and fix bugs faster. Experience sub-second reload times, without losing state, on emulators,
simulators, and hardware for iOS and Android.
<img src="https://user-images.githubusercontent.com/919717/28131204-0f8c3cda-66ee-11e7-9428-6a0513eac75d.gif" alt="Make a change in your code, and your app is changed instantly.">
## Quick-start
A brief summary of the [getting started guide](https://flutter.dev/docs/development/tools/ide):
- install the [Flutter SDK](https://flutter.dev/docs/get-started/install)
- run `flutter doctor` from the command line to verify your installation
- ensure you have a supported IntelliJ development environment; either:
- the latest stable version of [IntelliJ](https://www.jetbrains.com/idea/download), Community or Ultimate Edition (EAP versions are not always supported)
- the latest stable version of [Android Studio](https://developer.android.com/studio) (note: Android Studio Canary versions are generally _not_ supported)
- open the plugin preferences
- `Preferences > Plugins` on macOS, `File > Settings > Plugins` on Linux, select "Browse repositories…"
- search for and install the 'Flutter' plugin
- choose the option to restart IntelliJ
- configure the Flutter SDK setting
- `Preferences` on macOS, `File>Settings` on Linux, select `Languages & Frameworks > Flutter`, and set
the path to the root of your flutter repo
## Filing issues
Please use our [issue tracker](https://github.com/flutter/flutter-intellij/issues)
for Flutter IntelliJ issues.
- for more general Flutter issues, you should prefer to use the Flutter
[issue tracker](https://github.com/flutter/flutter/issues)
- for more Dart IntelliJ related issues, you can use JetBrains'
[YouTrack tracker](https://youtrack.jetbrains.com/issues?q=%23Dart%20%23Unresolved%20)
## Known issues
Please note the following known issues:
- [#601](https://github.com/flutter/flutter-intellij/issues/601): IntelliJ will
read the PATH variable just once on startup. Thus, if you change PATH later to
include the Flutter SDK path, this will not have an affect in IntelliJ until you
restart the IDE.
- If you require network access to go through proxy settings, you will need to set the
`https_proxy` variable in your environment as described in the
[pub docs](https://dart.dev/tools/pub/troubleshoot#pub-get-fails-from-behind-a-corporate-firewall).
(See also: [#2914](https://github.com/flutter/flutter-intellij/issues/2914).)
## Dev Channel
If you like getting new features as soon as they've been added to the code then you
might want to try out the dev channel. It is updated weekly with the latest contents
from the "master" branch. It has minimal testing. Set up instructions are in the wiki's
[dev channel page](https://github.com/flutter/flutter-intellij/wiki/Dev-Channel).
| flutter-intellij/README.md/0 | {
"file_path": "flutter-intellij/README.md",
"repo_id": "flutter-intellij",
"token_count": 1120
} | 448 |
/*
* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.tests.gui
import com.intellij.ide.fileTemplates.impl.UrlUtil
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.platform.templates.github.ZipUtil
import com.intellij.testGuiFramework.fixtures.IdeFrameFixture
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.impl.*
import com.intellij.testGuiFramework.util.step
import com.intellij.testGuiFramework.utils.TestUtilsClass
import com.intellij.testGuiFramework.utils.TestUtilsClassCompanion
import com.intellij.util.UriUtil
import com.intellij.util.io.URLUtil
import io.flutter.tests.gui.fixtures.FlutterMessagesToolWindowFixture
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.timing.Pause.pause
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.net.URL
val GuiTestCase.ProjectCreator by ProjectCreator
// Inspired by CommunityProjectCreator
class ProjectCreator(guiTestCase: GuiTestCase) : TestUtilsClass(guiTestCase) {
companion object : TestUtilsClassCompanion<ProjectCreator>({ ProjectCreator(it) })
private val defaultProjectName = "untitled"
private val sampleProjectName = "simple_app"
private val log = Logger.getInstance(this.javaClass)
var flutterMessagesFixture: FlutterMessagesToolWindowFixture.FlutterContentFixture? = null
fun importProject(projectName: String = sampleProjectName): File {
return step("Import project $projectName") {
val projectDirFile = extractProject(projectName)
val projectPath: File = guiTestCase.guiTestRule.importProject(projectDirFile)
with(guiTestCase) {
waitForFirstIndexing()
step("Get packages") {
openPubspecInProject()
ideFrame {
editor {
val note = notificationPanel()
if (note?.getLabelText() == "Flutter commands") {
note.clickLink("Packages get")
flutterMessagesFixture = flutterMessagesToolWindowFixture().getFlutterContent(projectName)
flutterMessagesFixture!!.findMessageContainingText("Process finished")
}
// TODO(messick) Close pubspec.yaml once editor tab fixtures are working.
//closeTab("pubspec.yaml")
}
}
}
openMainInProject(wait = true)
pause()
}
projectPath
}
}
private fun extractProject(projectName: String): File {
val projectDirUrl = this.javaClass.classLoader.getResource("flutter_projects/$projectName")
val children = UrlUtil.getChildrenRelativePaths(projectDirUrl)
val tempDir = java.nio.file.Files.createTempDirectory("test").toFile()
val projectDir = File(tempDir, projectName)
for (child in children) {
val url = childUrl(projectDirUrl, child)
val inputStream = URLUtil.openResourceStream(url)
val outputFile = File(projectDir, child)
File(outputFile.parent).mkdirs()
val outputStream = BufferedOutputStream(FileOutputStream(outputFile))
try {
StreamUtil.copyStreamContent(inputStream, outputStream)
}
finally {
inputStream.close()
outputStream.close()
}
}
val srcZip = File(projectDir, "src.zip")
if (srcZip.exists() && srcZip.isFile) {
run {
ZipUtil.unzip(null, projectDir, srcZip, null, null, true)
srcZip.delete()
}
}
return projectDir
}
private fun childUrl(parent: URL, child: String): URL {
return URL(UriUtil.trimTrailingSlashes(parent.toExternalForm()) + "/" + child)
}
fun createProject(projectName: String = defaultProjectName, needToOpenMain: Boolean = true) {
with(guiTestCase) {
step("Create project $projectName") {
welcomeFrame {
this.actionLink(name = "Create New Project").click()
dialog("New Project") {
jList("Flutter").clickItem("Flutter")
button("Next").click()
typeText(projectName)
button("Finish").click()
GuiTestUtilKt.waitProgressDialogUntilGone(
robot = robot(), progressTitle = "Creating Flutter Project", timeoutToAppear = Timeouts.seconds03)
}
}
waitForFirstIndexing()
}
if (needToOpenMain) openMainInProject(wait = true)
}
}
private fun GuiTestCase.waitForFirstIndexing() {
ideFrame {
val secondsToWait = 10
try {
waitForStartingIndexing(secondsToWait)
}
catch (timedOutError: WaitTimedOutError) {
log.warn("Wait for indexing exceeded $secondsToWait seconds")
}
waitForBackgroundTasksToFinish()
}
}
private fun GuiTestCase.openMainInProject(wait: Boolean = false) {
ideFrame {
projectView {
step("Open lib/main.dart") {
path(project.name, "lib", "main.dart").doubleClick()
if (wait) waitForBackgroundTasksToFinish()
}
}
}
}
private fun GuiTestCase.openPubspecInProject() {
ideFrame {
projectView {
step("Open pubspec.yaml") {
path(project.name, "pubspec.yaml").doubleClick()
}
}
}
}
fun IdeFrameFixture.flutterMessagesToolWindowFixture(): FlutterMessagesToolWindowFixture {
return FlutterMessagesToolWindowFixture(project, robot())
}
}
| flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/ProjectCreator.kt/0 | {
"file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/ProjectCreator.kt",
"repo_id": "flutter-intellij",
"token_count": 2155
} | 449 |
/*
* Copyright 2016 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ProjectTopics;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerCore;
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.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.ModuleListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService;
import io.flutter.analytics.Analytics;
import io.flutter.analytics.FlutterAnalysisServerListener;
import io.flutter.analytics.ToolWindowTracker;
import io.flutter.android.IntelliJAndroidSdk;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.editor.FlutterSaveActionsManager;
import io.flutter.logging.FlutterConsoleLogManager;
import io.flutter.module.FlutterModuleBuilder;
import io.flutter.perf.FlutterWidgetPerfManager;
import io.flutter.performance.FlutterPerformanceViewFactory;
import io.flutter.preview.PreviewViewFactory;
import io.flutter.pub.PubRoot;
import io.flutter.pub.PubRoots;
import io.flutter.run.FlutterReloadManager;
import io.flutter.run.FlutterRunNotifications;
import io.flutter.run.daemon.DevToolsService;
import io.flutter.run.daemon.DeviceService;
import io.flutter.sdk.FlutterPluginsLibraryManager;
import io.flutter.settings.FlutterSettings;
import io.flutter.survey.FlutterSurveyNotifications;
import io.flutter.utils.FlutterModuleUtils;
import io.flutter.view.FlutterViewFactory;
import org.jetbrains.annotations.NotNull;
import javax.swing.event.HyperlinkEvent;
import java.util.List;
import java.util.UUID;
/**
* Runs actions after the project has started up and the index is up to date.
*
* @see ProjectOpenActivity for actions that run earlier.
* @see io.flutter.project.FlutterProjectOpenProcessor for additional actions that
* may run when a project is being imported.
*/
public class FlutterInitializer implements StartupActivity {
private static final String analyticsClientIdKey = "io.flutter.analytics.clientId";
private static final String analyticsOptOutKey = "io.flutter.analytics.optOut";
private static final String analyticsToastShown = "io.flutter.analytics.toastShown";
private static Analytics analytics;
private boolean toolWindowsInitialized = false;
@Override
public void runActivity(@NotNull Project project) {
// Convert all modules of deprecated type FlutterModuleType.
if (FlutterModuleUtils.convertFromDeprecatedModuleType(project)) {
// If any modules were converted over, create a notification
FlutterMessages.showInfo(
FlutterBundle.message("flutter.initializer.module.converted.title"),
"Converted from '" + FlutterModuleUtils.DEPRECATED_FLUTTER_MODULE_TYPE_ID +
"' to '" + FlutterModuleUtils.getModuleTypeIDForFlutter() + "'.",
project);
}
// Disable the 'Migrate Project to Gradle' notification.
FlutterUtils.disableGradleProjectMigrationNotification(project);
// Start watching for devices.
DeviceService.getInstance(project);
// Start a DevTools server
DevToolsService.getInstance(project);
// If the project declares a Flutter dependency, do some extra initialization.
boolean hasFlutterModule = false;
for (Module module : ModuleManager.getInstance(project).getModules()) {
final boolean declaresFlutter = FlutterModuleUtils.declaresFlutter(module);
hasFlutterModule = hasFlutterModule || declaresFlutter;
if (!declaresFlutter) {
continue;
}
// Ensure SDKs are configured; needed for clean module import.
FlutterModuleUtils.enableDartSDK(module);
for (PubRoot root : PubRoots.forModule(module)) {
// Set Android SDK.
if (root.hasAndroidModule(project)) {
ensureAndroidSdk(project);
}
// Setup a default run configuration for 'main.dart' (if it's not there already and the file exists).
FlutterModuleUtils.autoCreateRunConfig(project, root);
// If there are no open editors, show main.
if (FileEditorManager.getInstance(project).getOpenFiles().length == 0) {
FlutterModuleUtils.autoShowMain(project, root);
}
}
}
if (hasFlutterModule || WorkspaceCache.getInstance(project).isBazel()) {
initializeToolWindows(project);
}
else {
project.getMessageBus().connect().subscribe(ProjectTopics.MODULES, new ModuleListener() {
@Override
public void moduleAdded(@NotNull Project project, @NotNull Module module) {
if (!toolWindowsInitialized && FlutterModuleUtils.isFlutterModule(module)) {
initializeToolWindows(project);
}
}
});
}
if (hasFlutterModule
&& PluginManagerCore.getPlugin(PluginId.getId("org.jetbrains.android")) != null
&& !FlutterModuleUtils.hasAndroidModule(project)) {
List<Module> modules = FlutterModuleUtils.findModulesWithFlutterContents(project);
for (Module module : modules) {
if (module.isDisposed() || !FlutterModuleUtils.isFlutterModule(module)) continue;
VirtualFile moduleFile = module.getModuleFile();
if (moduleFile == null) continue;
VirtualFile baseDir = moduleFile.getParent();
if (baseDir.getName().equals(".idea")) {
baseDir = baseDir.getParent();
}
boolean isModule = false;
try { // TODO(messick) Rewrite this loop to eliminate the need for this try-catch
FlutterModuleBuilder.addAndroidModule(project, null, baseDir.getPath(), module.getName(), isModule);
} catch (IllegalStateException ignored) {
}
}
// Ensure a run config is selected and ready to go.
FlutterModuleUtils.ensureRunConfigSelected(project);
}
if (hasFlutterModule) {
// Check to see if we're on a supported version of Android Studio; warn otherwise.
performAndroidStudioCanaryCheck(project);
}
FlutterRunNotifications.init(project);
// Start watching for survey triggers.
FlutterSurveyNotifications.init(project);
// Start the widget perf manager.
FlutterWidgetPerfManager.init(project);
// Watch save actions for reload on save.
FlutterReloadManager.init(project);
// Watch save actions for format on save.
FlutterSaveActionsManager.init(project);
// Start watching for project structure changes.
final FlutterPluginsLibraryManager libraryManager = new FlutterPluginsLibraryManager(project);
libraryManager.startWatching();
// Initialize the analytics notification group.
NotificationsConfiguration.getNotificationsConfiguration().register(
Analytics.GROUP_DISPLAY_ID,
NotificationDisplayType.STICKY_BALLOON,
false);
// Set our preferred settings for the run console.
FlutterConsoleLogManager.initConsolePreferences();
// Initialize analytics.
final PropertiesComponent properties = PropertiesComponent.getInstance();
if (!properties.getBoolean(analyticsToastShown)) {
properties.setValue(analyticsToastShown, true);
final Notification notification = new Notification(
Analytics.GROUP_DISPLAY_ID,
"Welcome to Flutter!",
FlutterBundle.message("flutter.analytics.notification.content"),
NotificationType.INFORMATION,
(notification1, event) -> {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if ("url".equals(event.getDescription())) {
BrowserUtil.browse("https://www.google.com/policies/privacy/");
}
}
});
boolean finalHasFlutterModule = hasFlutterModule;
//noinspection DialogTitleCapitalization
notification.addAction(new AnAction("Sounds good!") {
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
notification.expire();
// We only track for flutter projects.
if (finalHasFlutterModule) {
enableAnalytics(project);
}
}
});
//noinspection DialogTitleCapitalization
notification.addAction(new AnAction("No thanks") {
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
notification.expire();
setCanReportAnalytics(false);
}
});
Notifications.Bus.notify(notification, project);
}
else {
// We only track for flutter projects.
if (hasFlutterModule) {
enableAnalytics(project);
}
}
}
private static void enableAnalytics(@NotNull Project project) {
ToolWindowTracker.track(project, getAnalytics());
DartAnalysisServerService.getInstance(project).addAnalysisServerListener(FlutterAnalysisServerListener.getInstance(project));
}
private void initializeToolWindows(@NotNull Project project) {
// Start watching for Flutter debug active events.
FlutterViewFactory.init(project);
FlutterPerformanceViewFactory.init(project);
PreviewViewFactory.init(project);
toolWindowsInitialized = true;
}
/**
* Automatically set Android SDK based on ANDROID_HOME.
*/
private void ensureAndroidSdk(@NotNull Project project) {
if (ProjectRootManager.getInstance(project).getProjectSdk() != null) {
return; // Don't override user's settings.
}
final IntelliJAndroidSdk wanted = IntelliJAndroidSdk.fromEnvironment();
if (wanted == null) {
return; // ANDROID_HOME not set or Android SDK not created in IDEA; not clear what to do.
}
ApplicationManager.getApplication().runWriteAction(() -> wanted.setCurrent(project));
}
/**
* This method is only used for testing.
*/
@VisibleForTesting
public static void setAnalytics(Analytics inAnalytics) {
analytics = inAnalytics;
}
@NotNull
public static Analytics getAnalytics() {
if (analytics == null) {
final PropertiesComponent properties = PropertiesComponent.getInstance();
String clientId = properties.getValue(analyticsClientIdKey);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
properties.setValue(analyticsClientIdKey, clientId);
}
final IdeaPluginDescriptor descriptor = PluginManagerCore.getPlugin(FlutterUtils.getPluginId());
assert descriptor != null;
final ApplicationInfo info = ApplicationInfo.getInstance();
analytics = new Analytics(clientId, descriptor.getVersion(), info.getVersionName(), info.getFullVersion());
// Set up reporting prefs.
analytics.setCanSend(getCanReportAnalytics());
// Send initial loading hit.
analytics.sendScreenView("main");
FlutterSettings.getInstance().sendSettingsToAnalytics(analytics);
}
return analytics;
}
public static boolean getCanReportAnalytics() {
final PropertiesComponent properties = PropertiesComponent.getInstance();
return !properties.getBoolean(analyticsOptOutKey, false);
}
public static void setCanReportAnalytics(boolean canReportAnalytics) {
if (getCanReportAnalytics() != canReportAnalytics) {
final boolean wasReporting = getCanReportAnalytics();
final PropertiesComponent properties = PropertiesComponent.getInstance();
properties.setValue(analyticsOptOutKey, !canReportAnalytics);
if (analytics != null) {
analytics.setCanSend(getCanReportAnalytics());
}
if (!wasReporting && canReportAnalytics) {
getAnalytics().sendScreenView("main");
}
}
}
public static void sendAnalyticsAction(@NotNull AnAction action) {
sendAnalyticsAction(action.getClass().getSimpleName());
}
public static void sendAnalyticsAction(@NotNull String name) {
getAnalytics().sendEvent("intellij", name);
}
private static void performAndroidStudioCanaryCheck(Project project) {
if (!FlutterUtils.isAndroidStudio()) {
return;
}
final ApplicationInfo info = ApplicationInfo.getInstance();
if (info.getFullVersion().contains("Canary") && !info.getBuild().isSnapshot()) {
FlutterMessages.showWarning(
"Unsupported Android Studio version",
"Canary versions of Android Studio are not supported by the Flutter plugin.",
project);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/FlutterInitializer.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/FlutterInitializer.java",
"repo_id": "flutter-intellij",
"token_count": 4383
} | 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.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.FlutterUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterExternalIdeActionGroup extends DefaultActionGroup {
private static boolean isExternalIdeFile(AnActionEvent e) {
final VirtualFile file = e.getData(CommonDataKeys.VIRTUAL_FILE);
if (file == null || !file.exists()) {
return false;
}
final Project project = e.getProject();
assert (project != null);
return
isWithinAndroidDirectory(file, project) ||
isProjectDirectory(file, project) ||
isWithinIOsDirectory(file, project) ||
FlutterUtils.isXcodeProjectFileName(file.getName()) || OpenInAndroidStudioAction.isProjectFileName(file.getName());
}
public static boolean isAndroidDirectory(@NotNull VirtualFile file) {
return file.isDirectory() && (file.getName().equals("android") || file.getName().equals(".android"));
}
public static boolean isIOsDirectory(@NotNull VirtualFile file) {
return file.isDirectory() && (file.getName().equals("ios") || file.getName().equals(".ios"));
}
protected static boolean isWithinAndroidDirectory(@NotNull VirtualFile file, @NotNull Project project) {
final VirtualFile baseDir = project.getBaseDir();
if (baseDir == null) {
return false;
}
VirtualFile candidate = file;
while (candidate != null && !baseDir.equals(candidate)) {
if (isAndroidDirectory(candidate)) {
return true;
}
candidate = candidate.getParent();
}
return false;
}
protected static boolean isWithinIOsDirectory(@NotNull VirtualFile file, @NotNull Project project) {
final VirtualFile baseDir = project.getBaseDir();
if (baseDir == null) {
return false;
}
VirtualFile candidate = file;
while (candidate != null && !baseDir.equals(candidate)) {
if (isIOsDirectory(candidate)) {
return true;
}
candidate = candidate.getParent();
}
return false;
}
private static boolean isProjectDirectory(@NotNull VirtualFile file, @Nullable Project project) {
if (!file.isDirectory() || project == null) {
return false;
}
final VirtualFile baseDir = project.getBaseDir();
return baseDir != null && baseDir.getPath().equals(file.getPath());
}
@Override
public void update(AnActionEvent event) {
final Presentation presentation = event.getPresentation();
final boolean enabled = isExternalIdeFile(event);
presentation.setEnabled(enabled);
presentation.setVisible(enabled);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterExternalIdeActionGroup.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterExternalIdeActionGroup.java",
"repo_id": "flutter-intellij",
"token_count": 1007
} | 451 |
/*
* 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.actions;
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.run.FlutterReloadManager;
import io.flutter.run.daemon.FlutterApp;
import org.jetbrains.annotations.NotNull;
/**
* Action that reloads all running Flutter apps.
*/
@SuppressWarnings("ComponentNotRegistered")
public class ReloadAllFlutterApps extends FlutterAppAction {
public static final String ID = "Flutter.ReloadAllFlutterApps"; //NON-NLS
public static final String TEXT = FlutterBundle.message("app.reload.all.action.text");
public static final String DESCRIPTION = FlutterBundle.message("app.reload.all.action.description");
public ReloadAllFlutterApps(@NotNull FlutterApp app, @NotNull Computable<Boolean> isApplicable) {
super(app, TEXT, DESCRIPTION, FlutterIcons.HotReload, isApplicable, ID);
// Shortcut is associated with toolbar action.
copyShortcutFrom(ActionManager.getInstance().getAction("Flutter.Toolbar.ReloadAllAction"));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final Project project = getEventProject(e);
if (project == null) {
return;
}
FlutterInitializer.sendAnalyticsAction(this);
FlutterReloadManager.getInstance(project)
.saveAllAndReloadAll(FlutterApp.allFromProjectProcess(project), FlutterConstants.RELOAD_REASON_MANUAL);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/ReloadAllFlutterApps.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/ReloadAllFlutterApps.java",
"repo_id": "flutter-intellij",
"token_count": 571
} | 452 |
/*
* 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.analytics;
import com.google.common.annotations.VisibleForTesting;
/**
* A throttling algorithm.
* <p>
* This models the throttling after a bucket with water dripping into it at the rate of 1 drop per
* second. If the bucket has water when an operation is requested, 1 drop of water is removed and
* the operation is performed. If not the operation is skipped. This algorithm lets operations
* be performed in bursts without throttling, but holds the overall average rate of operations to 1
* per second.
*/
@VisibleForTesting
public class ThrottlingBucket {
private final int startingCount;
private int drops;
private long lastReplenish;
public ThrottlingBucket(final int startingCount) {
this.startingCount = startingCount;
this.drops = startingCount;
this.lastReplenish = System.currentTimeMillis();
}
public boolean removeDrop() {
checkReplenish();
if (drops <= 0) {
return false;
}
else {
drops--;
return true;
}
}
private void checkReplenish() {
final long now = System.currentTimeMillis();
if (now >= lastReplenish + 1000L) {
final int inc = ((int)(now - lastReplenish)) / 1000;
drops = Math.min(drops + inc, startingCount);
lastReplenish = now;
}
}
static class NonTrhottlingBucket extends ThrottlingBucket {
public NonTrhottlingBucket(int startingCount) {
super(startingCount);
}
public boolean removeDrop() {
return true;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/analytics/ThrottlingBucket.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/analytics/ThrottlingBucket.java",
"repo_id": "flutter-intellij",
"token_count": 533
} | 453 |
/*
* 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.dart;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Version;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService;
import com.jetbrains.lang.dart.ide.actions.DartPubActionBase;
import com.jetbrains.lang.dart.sdk.DartSdk;
import com.jetbrains.lang.dart.sdk.DartSdkLibUtil;
import com.jetbrains.lang.dart.sdk.DartSdkUpdateOption;
import com.jetbrains.lang.dart.sdk.DartSdkUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* Provides access to the Dart Plugin.
*/
public class DartPlugin {
/**
* Tracks the minimum required Dart Plugin version.
*/
private static final Version MINIMUM_VERSION = Version.parseVersion("171.3780.79");
private static final DartPlugin INSTANCE = new DartPlugin();
private Version myVersion;
public static DartPlugin getInstance() {
return INSTANCE;
}
@Nullable
public static DartSdk getDartSdk(@NotNull Project project) {
return DartSdk.getDartSdk(project);
}
public static boolean isDartSdkEnabled(@NotNull Module module) {
return DartSdkLibUtil.isDartSdkEnabled(module);
}
public static void enableDartSdk(@NotNull Module module) {
DartSdkLibUtil.enableDartSdk(module);
}
public static void ensureDartSdkConfigured(@NotNull Project project, @NotNull String sdkHomePath) {
DartSdkLibUtil.ensureDartSdkConfigured(project, sdkHomePath);
}
public static void disableDartSdk(@NotNull Collection<Module> modules) {
DartSdkLibUtil.disableDartSdk(modules);
}
public static boolean isDartSdkHome(@Nullable String path) {
return DartSdkUtil.isDartSdkHome(path);
}
public static boolean isPubActionInProgress() {
return DartPubActionBase.isInProgress();
}
public static void setPubActionInProgress(boolean inProgress) {
DartPubActionBase.setIsInProgress(inProgress);
}
public static boolean isDartRunConfiguration(ConfigurationType type) {
return type.getId().equals("DartCommandLineRunConfigurationType");
}
public static boolean isDartTestConfiguration(ConfigurationType type) {
return type.getId().equals("DartTestRunConfigurationType");
}
public static DartSdkUpdateOption doCheckForUpdates() {
return DartSdkUpdateOption.getDartSdkUpdateOption();
}
public static void setCheckForUpdates(DartSdkUpdateOption sdkUpdateOption) {
DartSdkUpdateOption.setDartSdkUpdateOption(sdkUpdateOption);
}
/**
* @return the minimum required version of the Dart Plugin
*/
public Version getMinimumVersion() {
return MINIMUM_VERSION;
}
/**
* @return the version of the currently installed Dart Plugin
*/
public Version getVersion() {
if (myVersion == null) {
final IdeaPluginDescriptor descriptor = PluginManagerCore.getPlugin(PluginId.getId("Dart"));
assert (descriptor != null);
myVersion = Version.parseVersion(descriptor.getVersion());
}
return myVersion;
}
/**
* Return the DartAnalysisServerService instance.
*/
@Nullable
public DartAnalysisServerService getAnalysisService(@NotNull final Project project) {
return project.getService(DartAnalysisServerService.class);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/dart/DartPlugin.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/dart/DartPlugin.java",
"repo_id": "flutter-intellij",
"token_count": 1185
} | 454 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* @author max
*/
package io.flutter.editor;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.codeInsight.highlighting.BraceMatcher;
import com.intellij.codeInsight.highlighting.BraceMatchingUtil;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageParserDefinitions;
import com.intellij.lang.ParserDefinition;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.editor.markup.CustomHighlighterRenderer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.paint.LinePainter2D;
import com.intellij.util.DocumentUtil;
import com.intellij.util.containers.IntStack;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.List;
import java.util.*;
import static java.lang.Math.min;
/**
* This is an FilteredIndentsHighlightingPass class forked from com.intellij.codeInsight.daemon.impl.FilteredIndentsHighlightingPass
* that supports filtering out indent guides that conflict with widget indent
* guides as determined by calling WidgetIndentsHighlightingPass.isIndentGuideHidden.
*/
@SuppressWarnings("ALL")
public class FilteredIndentsHighlightingPass extends TextEditorHighlightingPass implements DumbAware {
private static final Key<List<RangeHighlighter>> INDENT_HIGHLIGHTERS_IN_EDITOR_KEY = Key.create("INDENT_HIGHLIGHTERS_IN_EDITOR_KEY");
private static final Key<Long> LAST_TIME_INDENTS_BUILT = Key.create("LAST_TIME_INDENTS_BUILT");
private final EditorEx myEditor;
private final PsiFile myFile;
private volatile List<TextRange> myRanges = Collections.emptyList();
private volatile List<IndentGuideDescriptor> myDescriptors = Collections.emptyList();
private static final CustomHighlighterRenderer RENDERER = (editor, highlighter, g) -> {
int startOffset = highlighter.getStartOffset();
final Document doc = highlighter.getDocument();
final int textLength = doc.getTextLength();
if (startOffset >= textLength) return;
final int endOffset = min(highlighter.getEndOffset(), textLength);
final int endLine = doc.getLineNumber(endOffset);
int off;
int startLine = doc.getLineNumber(startOffset);
IndentGuideDescriptor descriptor = editor.getIndentsModel().getDescriptor(startLine, endLine);
final CharSequence chars = doc.getCharsSequence();
do {
int start = doc.getLineStartOffset(startLine);
int end = doc.getLineEndOffset(startLine);
off = CharArrayUtil.shiftForward(chars, start, end, " \t");
startLine--;
}
while (startLine > 1 && off < doc.getTextLength() && chars.charAt(off) == '\n');
final VisualPosition startPosition = editor.offsetToVisualPosition(off);
int indentColumn = startPosition.column;
// It's considered that indent guide can cross not only white space but comments, javadoc etc. Hence, there is a possible
// case that the first indent guide line is, say, single-line comment where comment symbols ('//') are located at the first
// visual column. We need to calculate correct indent guide column then.
int lineShift = 1;
if (indentColumn <= 0 && descriptor != null) {
indentColumn = descriptor.indentLevel;
lineShift = 0;
}
if (indentColumn <= 0) return;
final FoldingModel foldingModel = editor.getFoldingModel();
if (foldingModel.isOffsetCollapsed(off)) return;
final FoldRegion headerRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(doc.getLineNumber(off)));
final FoldRegion tailRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineStartOffset(doc.getLineNumber(endOffset)));
if (tailRegion != null && tailRegion == headerRegion) return;
final boolean selected;
final IndentGuideDescriptor guide = editor.getIndentsModel().getCaretIndentGuide();
if (guide != null) {
final CaretModel caretModel = editor.getCaretModel();
final int caretOffset = caretModel.getOffset();
selected =
caretOffset >= off && caretOffset < endOffset && caretModel.getLogicalPosition().column == indentColumn;
}
else {
selected = false;
}
Point start = editor.visualPositionToXY(new VisualPosition(startPosition.line + lineShift, indentColumn));
final VisualPosition endPosition = editor.offsetToVisualPosition(endOffset);
Point end = editor.visualPositionToXY(new VisualPosition(endPosition.line, endPosition.column));
int maxY = end.y;
if (endPosition.line == editor.offsetToVisualPosition(doc.getTextLength()).line) {
maxY += editor.getLineHeight();
}
Rectangle clip = g.getClipBounds();
if (clip != null) {
if (clip.y >= maxY || clip.y + clip.height <= start.y) {
return;
}
maxY = min(maxY, clip.y + clip.height);
}
if (WidgetIndentsHighlightingPass.isIndentGuideHidden(editor, new LineRange(startLine, endPosition.line))) {
// Avoid rendering this guide as it overlaps with the Widget indent guides.
return;
}
final EditorColorsScheme scheme = editor.getColorsScheme();
g.setColor(scheme.getColor(selected ? EditorColors.SELECTED_INDENT_GUIDE_COLOR : EditorColors.INDENT_GUIDE_COLOR));
// There is a possible case that indent line intersects soft wrap-introduced text. Example:
// this is a long line <soft-wrap>
// that| is soft-wrapped
// |
// | <- vertical indent
//
// Also it's possible that no additional intersections are added because of soft wrap:
// this is a long line <soft-wrap>
// | that is soft-wrapped
// |
// | <- vertical indent
// We want to use the following approach then:
// 1. Show only active indent if it crosses soft wrap-introduced text;
// 2. Show indent as is if it doesn't intersect with soft wrap-introduced text;
if (selected) {
LinePainter2D.paint((Graphics2D)g, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, start.y, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, maxY - 1);
}
else {
int y = start.y;
int newY = start.y;
SoftWrapModel softWrapModel = editor.getSoftWrapModel();
int lineHeight = editor.getLineHeight();
for (int i = Math.max(0, startLine + lineShift); i < endLine && newY < maxY; i++) {
List<? extends SoftWrap> softWraps = softWrapModel.getSoftWrapsForLine(i);
int logicalLineHeight = softWraps.size() * lineHeight;
if (i > startLine + lineShift) {
logicalLineHeight += lineHeight; // We assume that initial 'y' value points just below the target line.
}
if (!softWraps.isEmpty() && softWraps.get(0).getIndentInColumns() < indentColumn) {
if (y < newY || i > startLine + lineShift) { // There is a possible case that soft wrap is located on indent start line.
LinePainter2D.paint((Graphics2D)g, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, y, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, newY + lineHeight - 1);
}
newY += logicalLineHeight;
y = newY;
}
else {
newY += logicalLineHeight;
}
FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(i));
if (foldRegion != null && foldRegion.getEndOffset() < doc.getTextLength()) {
i = doc.getLineNumber(foldRegion.getEndOffset());
}
}
if (y < maxY) {
LinePainter2D.paint((Graphics2D)g, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, y, start.x + WidgetIndentsHighlightingPass.INDENT_GUIDE_DELTA, maxY - 1);
}
}
};
// TODO(jacobr): some of this logic to compute what portion of the guide to
// render is duplicated from RENDERER.
static io.flutter.editor.LineRange getGuideLineRange(Editor editor, RangeHighlighter highlighter) {
final int startOffset = highlighter.getStartOffset();
final Document doc = highlighter.getDocument();
final int textLength = doc.getTextLength();
if (startOffset >= textLength || !highlighter.isValid()) return null;
final int endOffset = min(highlighter.getEndOffset(), textLength);
final int endLine = doc.getLineNumber(endOffset);
int off;
int startLine = doc.getLineNumber(startOffset);
final IndentGuideDescriptor descriptor = editor.getIndentsModel().getDescriptor(startLine, endLine);
final CharSequence chars = doc.getCharsSequence();
do {
final int start = doc.getLineStartOffset(startLine);
final int end = doc.getLineEndOffset(startLine);
off = CharArrayUtil.shiftForward(chars, start, end, " \t");
startLine--;
}
while (startLine > 1 && off < textLength && chars.charAt(off) == '\n');
final VisualPosition startPosition = editor.offsetToVisualPosition(off);
int indentColumn = startPosition.column;
// It's considered that indent guide can cross not only white space but comments, javadoc etc. Hence, there is a possible
// case that the first indent guide line is, say, single-line comment where comment symbols ('//') are located at the first
// visual column. We need to calculate correct indent guide column then.
int lineShift = 1;
if (indentColumn <= 0 && descriptor != null) {
indentColumn = descriptor.indentLevel;
lineShift = 0;
}
if (indentColumn <= 0) return null;
final FoldingModel foldingModel = editor.getFoldingModel();
if (foldingModel.isOffsetCollapsed(off)) return null;
final FoldRegion headerRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(doc.getLineNumber(off)));
final FoldRegion tailRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineStartOffset(doc.getLineNumber(endOffset)));
if (tailRegion != null && tailRegion == headerRegion) return null;
final VisualPosition endPosition = editor.offsetToVisualPosition(endOffset);
return new io.flutter.editor.LineRange(startLine, endPosition.line);
}
FilteredIndentsHighlightingPass(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
super(project, editor.getDocument(), false);
myEditor = (EditorEx)editor;
myFile = file;
}
public static void onWidgetIndentsChanged(EditorEx editor, WidgetIndentHitTester oldHitTester, WidgetIndentHitTester newHitTester) {
final List<RangeHighlighter> highlighters = editor.getUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY);
if (highlighters != null) {
final Document doc = editor.getDocument();
final int textLength = doc.getTextLength();
for (RangeHighlighter highlighter : highlighters) {
if (!highlighter.isValid()) {
continue;
}
final LineRange range = getGuideLineRange(editor, highlighter);
if (range != null) {
final boolean before = WidgetIndentsHighlightingPass.isIndentGuideHidden(oldHitTester, range);
final boolean after = WidgetIndentsHighlightingPass.isIndentGuideHidden(newHitTester, range);
if (before != after) {
int safeStart = min(highlighter.getStartOffset(), textLength);
int safeEnd = min(highlighter.getEndOffset(), textLength);
if (safeEnd > safeStart) {
editor.repaint(safeStart, safeEnd);
}
}
}
}
}
}
@Override
public void doCollectInformation(@NotNull ProgressIndicator progress) {
assert myDocument != null;
final Long stamp = myEditor.getUserData(LAST_TIME_INDENTS_BUILT);
if (stamp != null && stamp.longValue() == nowStamp()) return;
myDescriptors = buildDescriptors();
final ArrayList<TextRange> ranges = new ArrayList<>();
for (IndentGuideDescriptor descriptor : myDescriptors) {
ProgressManager.checkCanceled();
final int endOffset =
descriptor.endLine < myDocument.getLineCount() ? myDocument.getLineStartOffset(descriptor.endLine) : myDocument.getTextLength();
ranges.add(new TextRange(myDocument.getLineStartOffset(descriptor.startLine), endOffset));
}
Collections.sort(ranges, Segment.BY_START_OFFSET_THEN_END_OFFSET);
myRanges = ranges;
}
private long nowStamp() {
// If regular indent guides are being shown then the user has disabled
// the custom WidgetIndentGuides and we should skip this pass in favor
// of the regular indent guides instead of our fork.
if (myEditor.getSettings().isIndentGuidesShown()) return -1;
assert myDocument != null;
return myDocument.getModificationStamp();
}
public static void cleanupHighlighters(Editor editor) {
final List<RangeHighlighter> highlighters = editor.getUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY);
if (highlighters == null) return;
for (RangeHighlighter highlighter : highlighters) {
highlighter.dispose();
}
editor.putUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY, null);
editor.putUserData(LAST_TIME_INDENTS_BUILT, null);
}
@Override
public void doApplyInformationToEditor() {
final Long stamp = myEditor.getUserData(LAST_TIME_INDENTS_BUILT);
if (stamp != null && stamp.longValue() == nowStamp()) return;
List<RangeHighlighter> oldHighlighters = myEditor.getUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY);
final List<RangeHighlighter> newHighlighters = new ArrayList<>();
final MarkupModel mm = myEditor.getMarkupModel();
int curRange = 0;
if (oldHighlighters != null) {
// after document change some range highlighters could have become invalid, or the order could have been broken
oldHighlighters.sort(Comparator.comparing((RangeHighlighter h) -> !h.isValid())
.thenComparing(Segment.BY_START_OFFSET_THEN_END_OFFSET));
int curHighlight = 0;
while (curRange < myRanges.size() && curHighlight < oldHighlighters.size()) {
TextRange range = myRanges.get(curRange);
RangeHighlighter highlighter = oldHighlighters.get(curHighlight);
if (!highlighter.isValid()) break;
int cmp = compare(range, highlighter);
if (cmp < 0) {
newHighlighters.add(createHighlighter(mm, range));
curRange++;
}
else if (cmp > 0) {
highlighter.dispose();
curHighlight++;
}
else {
newHighlighters.add(highlighter);
curHighlight++;
curRange++;
}
}
for (; curHighlight < oldHighlighters.size(); curHighlight++) {
RangeHighlighter highlighter = oldHighlighters.get(curHighlight);
if (!highlighter.isValid()) break;
highlighter.dispose();
}
}
final int startRangeIndex = curRange;
assert myDocument != null;
DocumentUtil.executeInBulk(myDocument, myRanges.size() > 10000, () -> {
for (int i = startRangeIndex; i < myRanges.size(); i++) {
newHighlighters.add(createHighlighter(mm, myRanges.get(i)));
}
});
myEditor.putUserData(INDENT_HIGHLIGHTERS_IN_EDITOR_KEY, newHighlighters);
myEditor.putUserData(LAST_TIME_INDENTS_BUILT, nowStamp());
myEditor.getIndentsModel().assumeIndents(myDescriptors);
}
private List<IndentGuideDescriptor> buildDescriptors() {
// If regular indent guides are being shown then the user has disabled
// the custom WidgetIndentGuides and we should skip this pass in favor
// of the regular indent guides instead of our fork.
if (myEditor.getSettings().isIndentGuidesShown()) return Collections.emptyList();
IndentsCalculator calculator = new IndentsCalculator();
calculator.calculate();
int[] lineIndents = calculator.lineIndents;
IntStack lines = new IntStack();
IntStack indents = new IntStack();
lines.push(0);
indents.push(0);
assert myDocument != null;
List<IndentGuideDescriptor> descriptors = new ArrayList<>();
for (int line = 1; line < lineIndents.length; line++) {
ProgressManager.checkCanceled();
int curIndent = Math.abs(lineIndents[line]);
while (!indents.empty() && curIndent <= indents.peek()) {
ProgressManager.checkCanceled();
final int level = indents.pop();
int startLine = lines.pop();
if (level > 0) {
for (int i = startLine; i < line; i++) {
if (level != Math.abs(lineIndents[i])) {
descriptors.add(createDescriptor(level, startLine, line, lineIndents));
break;
}
}
}
}
int prevLine = line - 1;
int prevIndent = Math.abs(lineIndents[prevLine]);
if (curIndent - prevIndent > 1) {
lines.push(prevLine);
indents.push(prevIndent);
}
}
while (!indents.empty()) {
ProgressManager.checkCanceled();
final int level = indents.pop();
int startLine = lines.pop();
if (level > 0) {
descriptors.add(createDescriptor(level, startLine, myDocument.getLineCount(), lineIndents));
}
}
return descriptors;
}
private IndentGuideDescriptor createDescriptor(int level, int startLine, int endLine, int[] lineIndents) {
while (startLine > 0 && lineIndents[startLine] < 0) startLine--;
int codeConstructStartLine = findCodeConstructStartLine(startLine);
return new IndentGuideDescriptor(level, codeConstructStartLine, startLine, endLine);
}
private int findCodeConstructStartLine(int startLine) {
DocumentEx document = myEditor.getDocument();
CharSequence text = document.getImmutableCharSequence();
int lineStartOffset = document.getLineStartOffset(startLine);
int firstNonWsOffset = CharArrayUtil.shiftForward(text, lineStartOffset, " \t");
FileType type = PsiUtilBase.getPsiFileAtOffset(myFile, firstNonWsOffset).getFileType();
Language language = PsiUtilCore.getLanguageAtOffset(myFile, firstNonWsOffset);
BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(type, language);
HighlighterIterator iterator = myEditor.getHighlighter().createIterator(firstNonWsOffset);
if (braceMatcher.isLBraceToken(iterator, text, type)) {
int codeConstructStart = braceMatcher.getCodeConstructStart(myFile, firstNonWsOffset);
return document.getLineNumber(codeConstructStart);
}
else {
return startLine;
}
}
@NotNull
private static RangeHighlighter createHighlighter(MarkupModel mm, TextRange range) {
final RangeHighlighter highlighter =
mm.addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), 0, null, HighlighterTargetArea.EXACT_RANGE);
highlighter.setCustomRenderer(RENDERER);
return highlighter;
}
private static int compare(@NotNull TextRange r, @NotNull RangeHighlighter h) {
int answer = r.getStartOffset() - h.getStartOffset();
return answer != 0 ? answer : r.getEndOffset() - h.getEndOffset();
}
private class IndentsCalculator {
@NotNull final Map<Language, TokenSet> myComments = new HashMap<>();
@NotNull final int[] lineIndents; // negative value means the line is empty (or contains a comment) and indent
// (denoted by absolute value) was deduced from enclosing non-empty lines
@NotNull final CharSequence myChars;
IndentsCalculator() {
assert myDocument != null;
lineIndents = new int[myDocument.getLineCount()];
myChars = myDocument.getCharsSequence();
}
/**
* Calculates line indents for the {@link #myDocument target document}.
*/
void calculate() {
assert myDocument != null;
final FileType fileType = myFile.getFileType();
int tabSize = EditorUtil.getTabSize(myEditor);
for (int line = 0; line < lineIndents.length; line++) {
ProgressManager.checkCanceled();
int lineStart = myDocument.getLineStartOffset(line);
int lineEnd = myDocument.getLineEndOffset(line);
int offset = lineStart;
int column = 0;
outer:
while (offset < lineEnd) {
switch (myChars.charAt(offset)) {
case ' ':
column++;
break;
case '\t':
column = (column / tabSize + 1) * tabSize;
break;
default:
break outer;
}
offset++;
}
// treating commented lines in the same way as empty lines
// Blank line marker
lineIndents[line] = offset == lineEnd || isComment(offset) ? -1 : column;
}
int topIndent = 0;
for (int line = 0; line < lineIndents.length; line++) {
ProgressManager.checkCanceled();
if (lineIndents[line] >= 0) {
topIndent = lineIndents[line];
}
else {
int startLine = line;
while (line < lineIndents.length && lineIndents[line] < 0) {
//noinspection AssignmentToForLoopParameter
line++;
}
int bottomIndent = line < lineIndents.length ? lineIndents[line] : topIndent;
int indent = min(topIndent, bottomIndent);
if (bottomIndent < topIndent) {
int lineStart = myDocument.getLineStartOffset(line);
int lineEnd = myDocument.getLineEndOffset(line);
int nonWhitespaceOffset = CharArrayUtil.shiftForward(myChars, lineStart, lineEnd, " \t");
HighlighterIterator iterator = myEditor.getHighlighter().createIterator(nonWhitespaceOffset);
if (BraceMatchingUtil.isRBraceToken(iterator, myChars, fileType)) {
indent = topIndent;
}
}
for (int blankLine = startLine; blankLine < line; blankLine++) {
assert lineIndents[blankLine] == -1;
lineIndents[blankLine] = -min(topIndent, indent);
}
//noinspection AssignmentToForLoopParameter
line--; // will be incremented back at the end of the loop;
}
}
}
private boolean isComment(int offset) {
final HighlighterIterator it = myEditor.getHighlighter().createIterator(offset);
IElementType tokenType = it.getTokenType();
Language language = tokenType.getLanguage();
TokenSet comments = myComments.get(language);
if (comments == null) {
ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
if (definition != null) {
comments = definition.getCommentTokens();
}
if (comments == null) {
return false;
}
else {
myComments.put(language, comments);
}
}
return comments.contains(tokenType);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/FilteredIndentsHighlightingPass.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FilteredIndentsHighlightingPass.java",
"repo_id": "flutter-intellij",
"token_count": 8759
} | 455 |
/*
* 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 javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import com.intellij.openapi.ui.popup.Balloon;
// Stub implementation of IntellijColorPickerProvider so that we don't throw
// exceptions when running on AndroidStudio. We cannot include the real
// implementation of IntellijColorPickerProvider when building for
// AndroidStudio as it will generate compile errors.
// see product-matrix.json which specifies that IntellijColorPickerProvider
// should be stubbed out under AndroidStudio.
public class IntellijColorPickerProvider implements ColorPickerProvider {
@Override
public void show(Color initialColor, JComponent component, Point offset, Balloon.Position position, ColorListener colorListener, Runnable onCancel, Runnable onOk) {
}
@Override
public void dispose() {
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/IntellijColorPickerProvider.java_stub/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/IntellijColorPickerProvider.java_stub",
"repo_id": "flutter-intellij",
"token_count": 284
} | 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.inspector;
import com.google.common.collect.Lists;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import io.flutter.run.FlutterAppManager;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.utils.AsyncUtils;
import io.flutter.utils.StreamSubscription;
import io.flutter.vmService.ServiceExtensions;
import org.dartlang.vm.service.VmService;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
/**
* Service that provides the current inspector state independent of a specific
* application run.
* <p>
* This class provides a {@link Listener} that notifies consumers when state
* has changed.
* <ul>
* <li>The inspector is available.</li>
* <li>The inspector selection when it changes</li>
* <li>When the UI displayed in the app has changed</li>
* </ul>
*/
public class InspectorGroupManagerService implements Disposable {
/**
* Convenience implementation of Listener that tracks the active
* InspectorService and manages the creation of an
* InspectorObjectGroupManager for easy inspector lifecycle management.
*/
public static class Client implements Listener {
private InspectorService service;
private InspectorObjectGroupManager groupManager;
public Client(Disposable parent) {
Disposer.register(parent, () -> {
if (groupManager != null) {
groupManager.clear(false);
}
});
}
public InspectorObjectGroupManager getGroupManager() {
if (groupManager == null && service != null) {
groupManager = new InspectorObjectGroupManager(service, "client");
}
return groupManager;
}
public FlutterApp getApp() {
if (service == null) return null;
return service.getApp();
}
public InspectorService getInspectorService() {
return service;
}
@Override
public void onInspectorAvailable(InspectorService service) {
if (this.service == service) return;
if (groupManager != null) {
groupManager.clear(service == null);
}
this.service = service;
groupManager = null;
onInspectorAvailabilityChanged();
}
/**
* Clients should override this method to be notified when the inspector
* availabilty changed.
*/
public void onInspectorAvailabilityChanged() {
}
public InspectorService.ObjectGroup getCurrentObjectGroup() {
groupManager = getGroupManager();
if (groupManager == null) return null;
return groupManager.getCurrent();
}
}
private interface InvokeListener {
void run(Listener listener);
}
public interface Listener {
void onInspectorAvailable(InspectorService service);
/**
* Called when something has changed and UI dependent on inspector state
* should re-render.
*
* @param force indicates that the old UI is likely completely obsolete.
*/
default void requestRepaint(boolean force) {
}
/**
* Called whenever Flutter renders a frame.
*/
default void onFlutterFrame() {
}
default void notifyAppReloaded() {
}
default void notifyAppRestarted() {
}
/**
* Called when the inspector selection has changed.
*/
default void onSelectionChanged(DiagnosticsNode selection) {
}
}
private final Set<Listener> listeners = new HashSet<>();
boolean started = false;
private CompletableFuture<InspectorService> inspectorServiceFuture;
private FlutterApp app;
private FlutterApp.FlutterAppListener appListener;
private DiagnosticsNode selection;
private InspectorService inspectorService;
private InspectorObjectGroupManager selectionGroups;
private StreamSubscription<Boolean> onStructuredErrorsStream;
public InspectorGroupManagerService(Project project) {
FlutterAppManager.getInstance(project).getActiveAppAsStream().listen(
this::updateActiveApp, true);
Disposer.register(project, this);
}
@NotNull
public static InspectorGroupManagerService getInstance(@NotNull final Project project) {
return Objects.requireNonNull(project.getService(InspectorGroupManagerService.class));
}
public InspectorService getInspectorService() {
return inspectorService;
}
public void addListener(@NotNull Listener listener, Disposable disposable) {
synchronized (listeners) {
listeners.add(listener);
}
// Update the listener with the current active state if any.
if (inspectorService != null) {
listener.onInspectorAvailable(inspectorService);
}
if (selection != null) {
listener.onSelectionChanged(selection);
}
Disposer.register(disposable, () -> removeListener(listener));
}
private void removeListener(@NotNull Listener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
private void loadSelection() {
selectionGroups.cancelNext();
final CompletableFuture<DiagnosticsNode> pendingSelectionFuture =
selectionGroups.getNext().getSelection(null, InspectorService.FlutterTreeType.widget, true);
selectionGroups.getNext().safeWhenComplete(pendingSelectionFuture, (selection, error) -> {
if (error != null) {
// TODO(jacobr): should we report an error here?
selectionGroups.cancelNext();
return;
}
selectionGroups.promoteNext();
invokeOnAllListeners((listener) -> listener.onSelectionChanged(selection));
});
}
private void requestRepaint(boolean force) {
invokeOnAllListeners((listener) -> listener.requestRepaint(force));
}
private void updateActiveApp(FlutterApp app) {
if (app == this.app) {
return;
}
selection = null;
if (this.app != null && appListener != null) {
this.app.removeStateListener(appListener);
appListener = null;
}
this.app = app;
if (app == null) {
return;
}
started = false;
// start listening for frames, reload and restart events
appListener = new FlutterApp.FlutterAppListener() {
@Override
public void stateChanged(FlutterApp.State newState) {
if (!started && app.isStarted()) {
started = true;
requestRepaint(false);
}
if (newState == FlutterApp.State.TERMINATING) {
inspectorService = null;
invokeOnAllListeners((listener) -> listener.onInspectorAvailable(inspectorService));
}
}
@Override
public void notifyAppReloaded() {
invokeOnAllListeners(Listener::notifyAppReloaded);
requestRepaint(true);
}
@Override
public void notifyAppRestarted() {
invokeOnAllListeners(Listener::notifyAppRestarted);
requestRepaint(true);
}
public void notifyVmServiceAvailable(VmService vmService) {
assert (app.getFlutterDebugProcess() != null);
inspectorServiceFuture = app.getFlutterDebugProcess().getInspectorService();
AsyncUtils.whenCompleteUiThread(inspectorServiceFuture, (service, error) -> {
invokeOnAllListeners((listener) -> listener.onInspectorAvailable(service));
if (inspectorServiceFuture == null || inspectorServiceFuture.getNow(null) != service) return;
inspectorService = service;
selection = null;
selectionGroups = new InspectorObjectGroupManager(inspectorService, "selection");
// TODO (helin24): The specific stream we're checking here doesn't matter; we need a frame to be available before running
// loadSelection and other tasks.
if (onStructuredErrorsStream != null) {
Disposer.dispose(onStructuredErrorsStream);
}
onStructuredErrorsStream =
app.getVMServiceManager().hasServiceExtension(ServiceExtensions.toggleShowStructuredErrors.getExtension(), (hasData) -> {
if (hasData) {
loadSelection();
if (app != InspectorGroupManagerService.this.app) return;
service.addClient(new InspectorService.InspectorServiceClient() {
@Override
public void onInspectorSelectionChanged(boolean uiAlreadyUpdated, boolean textEditorUpdated) {
loadSelection();
}
@Override
public void onFlutterFrame() {
invokeOnAllListeners(Listener::onFlutterFrame);
}
@Override
public CompletableFuture<?> onForceRefresh() {
requestRepaint(true);
// Return null instead of a CompletableFuture as the
// InspectorService should not wait for our client to be ready.
return null;
}
});
}
});
});
}
};
app.addStateListener(appListener);
if (app.getFlutterDebugProcess() != null) {
appListener.notifyVmServiceAvailable(null);
}
}
private void invokeOnAllListeners(InvokeListener callback) {
AsyncUtils.invokeLater(() -> {
final ArrayList<Listener> cachedListeners;
synchronized (listeners) {
cachedListeners = Lists.newArrayList(listeners);
}
for (Listener listener : cachedListeners) {
callback.run(listener);
}
});
}
@Override
public void dispose() {
synchronized (listeners) {
listeners.clear();
}
if (app != null) {
this.app.removeStateListener(appListener);
}
this.app = null;
appListener = null;
if (onStructuredErrorsStream != null) {
Disposer.dispose(onStructuredErrorsStream);
onStructuredErrorsStream = null;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorGroupManagerService.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorGroupManagerService.java",
"repo_id": "flutter-intellij",
"token_count": 3670
} | 457 |
/*
* 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.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.ui.content.ContentManager;
import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.browser.UnsupportedRenderingModeException;
import com.teamdev.jxbrowser.browser.callback.AlertCallback;
import com.teamdev.jxbrowser.browser.callback.ConfirmCallback;
import com.teamdev.jxbrowser.browser.callback.input.PressKeyCallback;
import com.teamdev.jxbrowser.browser.event.ConsoleMessageReceived;
import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.js.ConsoleMessage;
import com.teamdev.jxbrowser.ui.KeyCode;
import com.teamdev.jxbrowser.ui.event.KeyPressed;
import com.teamdev.jxbrowser.view.swing.BrowserView;
import com.teamdev.jxbrowser.view.swing.callback.DefaultAlertCallback;
import com.teamdev.jxbrowser.view.swing.callback.DefaultConfirmCallback;
import io.flutter.FlutterInitializer;
import io.flutter.settings.FlutterSettings;
import io.flutter.view.EmbeddedBrowser;
import io.flutter.view.EmbeddedTab;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.Objects;
class EmbeddedJxBrowserTab implements EmbeddedTab {
private final Engine engine;
private Browser browser;
private static final Logger LOG = Logger.getInstance(EmbeddedJxBrowserTab.class);
public EmbeddedJxBrowserTab(Engine engine) {
this.engine = engine;
try {
this.browser = engine.newBrowser();
this.browser.settings().enableTransparentBackground();
this.browser.on(ConsoleMessageReceived.class, event -> {
final ConsoleMessage consoleMessage = event.consoleMessage();
LOG.info("Browser message(" + consoleMessage.level().name() + "): " + consoleMessage.message());
});
}
catch (UnsupportedRenderingModeException ex) {
// Skip using a transparent background if an exception is thrown.
}
catch (Exception | Error ex) {
LOG.info(ex);
FlutterInitializer.getAnalytics().sendExpectedException("jxbrowser-setup", ex);
}
}
@Override
public void loadUrl(String url) {
this.browser.navigation().loadUrl(url);
}
@Override
public void close() {
this.browser.close();
}
@Override
public JComponent getTabComponent(ContentManager contentManager) {
// Creating Swing component for rendering web content
// loaded in the given Browser instance.
final BrowserView view = BrowserView.newInstance(browser);
view.setPreferredSize(new Dimension(contentManager.getComponent().getWidth(), contentManager.getComponent().getHeight()));
// DevTools may show a confirm dialog to use a fallback version.
browser.set(ConfirmCallback.class, new DefaultConfirmCallback(view));
browser.set(AlertCallback.class, new DefaultAlertCallback(view));
// This is for pulling up Chrome inspector for debugging purposes.
browser.set(PressKeyCallback.class, params -> {
KeyPressed keyEvent = params.event();
boolean keyCodeC = keyEvent.keyCode() == KeyCode.KEY_CODE_J;
boolean controlDown = keyEvent.keyModifiers().isControlDown();
if (controlDown && keyCodeC) {
browser.devTools().show();
}
return PressKeyCallback.Response.proceed();
});
return view;
}
}
public class EmbeddedJxBrowser extends EmbeddedBrowser {
private static final Logger LOG = Logger.getInstance(JxBrowserManager.class);
private final Engine engine;
@NotNull
public static EmbeddedJxBrowser getInstance(@NotNull Project project) {
return Objects.requireNonNull(project.getService(EmbeddedJxBrowser.class));
}
private EmbeddedJxBrowser(Project project) {
super(project);
System.setProperty("jxbrowser.force.dpi.awareness", "1.0");
System.setProperty("jxbrowser.logging.level", "DEBUG");
System.setProperty("jxbrowser.logging.file", PathManager.getLogPath() + File.separatorChar + "jxbrowser.log");
if (FlutterSettings.getInstance().isVerboseLogging()) {
System.setProperty("jxbrowser.logging.level", "ALL");
}
this.engine = EmbeddedBrowserEngine.getInstance().getEngine();
}
@Override
public Logger logger() {
return LOG;
}
@Override
public EmbeddedTab openEmbeddedTab() {
return new EmbeddedJxBrowserTab(engine);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/EmbeddedJxBrowser.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/EmbeddedJxBrowser.java",
"repo_id": "flutter-intellij",
"token_count": 1469
} | 458 |
/*
* 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.module.settings
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.layout.*
import io.flutter.FlutterBundle
import io.flutter.sdk.FlutterCreateAdditionalSettings
import io.flutter.sdk.FlutterSdk
import io.flutter.sdk.FlutterSdkChannel
import io.flutter.sdk.FlutterSdkChannel.ID
import java.util.function.Supplier
class PlatformsForm() {
var channel: FlutterSdkChannel? = null
var configAndroid: Boolean = true
var configIos: Boolean = true
var configLinux: Boolean = true
var configMacos: Boolean = true
var configWeb: Boolean = true
var configWindows: Boolean = true
var component: DialogPanel? = null
fun panel(settings: FlutterCreateAdditionalSettings) =
panel {
row {
cell(isVerticalFlow = false) {
makeCheckBox(this, FlutterBundle.message("npw_platform_android"), settings.platformAndroidProperty, configAndroid)
makeCheckBox(this, FlutterBundle.message("npw_platform_ios"), settings.platformIosProperty, configIos)
makeCheckBox(this, FlutterBundle.message("npw_platform_linux"), settings.platformLinuxProperty, configLinux)
makeCheckBox(this, FlutterBundle.message("npw_platform_macos"), settings.platformMacosProperty, configMacos)
makeCheckBox(this, FlutterBundle.message("npw_platform_web"), settings.platformWebProperty, configWeb)
makeCheckBox(this, FlutterBundle.message("npw_platform_windows"), settings.platformWindowsProperty, configWindows)
}
}
row {
label(FlutterBundle.message("npw_platform_selection_help"))
}
}.apply { component = this }
private fun makeCheckBox(context: Cell,
name: String,
property: InitializeOnceBoolValueProperty,
config: Boolean?) {
context.apply {
val wasSelected = config == true
property.initialize(wasSelected)
checkBox(name,
property.get(),
actionListener = { _, checkBox ->
property.set(checkBox.isSelected)
}).apply {
val names: List<String> = listOfNotNull(
FlutterBundle.message("npw_platform_android"),
FlutterBundle.message("npw_platform_ios"),
FlutterBundle.message("npw_platform_web"),
FlutterBundle.message("npw_platform_windows"),
FlutterBundle.message("npw_platform_linux"),
FlutterBundle.message("npw_platform_macos"),
)
enabled(names.contains(name) || wasSelected)
}
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/module/settings/PlatformsForm.kt/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/PlatformsForm.kt",
"repo_id": "flutter-intellij",
"token_count": 1071
} | 459 |
/*
* 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 icons.FlutterIcons;
import io.flutter.utils.AnimatedIcon;
import javax.swing.*;
import java.awt.*;
public class Icons {
static final AnimatedIcon RED_PROGRESS = new RedProgress();
static final AnimatedIcon YELLOW_PROGRESS = new YellowProgress();
static final AnimatedIcon NORMAL_PROGRESS = new AnimatedIcon.Grey();
private static final Icon EMPTY_ICON = new EmptyIcon(FlutterIcons.CustomInfo);
// Threshold for statistics to use red icons.
static final int HIGH_LOAD_THRESHOLD = 2;
public static Icon getIconForCount(int count, boolean showInactive) {
if (count == 0) {
return showInactive ? FlutterIcons.CustomInfo : EMPTY_ICON;
}
if (count >= HIGH_LOAD_THRESHOLD) {
return YELLOW_PROGRESS;
}
return NORMAL_PROGRESS;
}
private static class EmptyIcon implements Icon {
final Icon iconForSize;
EmptyIcon(Icon iconForSize) {
this.iconForSize = iconForSize;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
}
@Override
public int getIconWidth() {
return iconForSize.getIconWidth();
}
@Override
public int getIconHeight() {
return iconForSize.getIconHeight();
}
}
// Spinning red progress icon
//
// TODO(jacobr): it would be nice to tint the icons programatically so that
// we could have a wider range of icon colors representing various repaint
// rates.
static final class RedProgress extends AnimatedIcon {
public RedProgress() {
super(150,
FlutterIcons.State.RedProgr_1,
FlutterIcons.State.RedProgr_2,
FlutterIcons.State.RedProgr_3,
FlutterIcons.State.RedProgr_4,
FlutterIcons.State.RedProgr_5,
FlutterIcons.State.RedProgr_6,
FlutterIcons.State.RedProgr_7,
FlutterIcons.State.RedProgr_8);
}
}
static final class YellowProgress extends AnimatedIcon {
public YellowProgress() {
super(150,
FlutterIcons.State.YellowProgr_1,
FlutterIcons.State.YellowProgr_2,
FlutterIcons.State.YellowProgr_3,
FlutterIcons.State.YellowProgr_4,
FlutterIcons.State.YellowProgr_5,
FlutterIcons.State.YellowProgr_6,
FlutterIcons.State.YellowProgr_7,
FlutterIcons.State.YellowProgr_8);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/Icons.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/Icons.java",
"repo_id": "flutter-intellij",
"token_count": 1017
} | 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.perf;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.fileEditor.FileEditor;
import io.flutter.inspector.DiagnosticsNode;
import java.util.concurrent.CompletableFuture;
/**
* Interface defining what information about widget performance can be fetched
* from the running device.
* <p>
* See VMServiceWidgetPerfProvider for the non-test implementation of this class.
*/
public interface WidgetPerfProvider extends Disposable {
void setTarget(WidgetPerfListener widgetPerfListener);
boolean isStarted();
boolean isConnected();
boolean shouldDisplayPerfStats(FileEditor editor);
CompletableFuture<DiagnosticsNode> getWidgetTree();
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/WidgetPerfProvider.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/WidgetPerfProvider.java",
"repo_id": "flutter-intellij",
"token_count": 243
} | 461 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.preview;
import com.intellij.util.EventDispatcher;
import com.intellij.util.xmlb.annotations.Attribute;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* State for the Preview view.
*/
public class PreviewViewState {
private final EventDispatcher<ChangeListener> dispatcher = EventDispatcher.create(ChangeListener.class);
@Attribute(value = "splitter-proportion")
public float splitterProportion;
public PreviewViewState() {
}
public float getSplitterProportion() {
return splitterProportion <= 0.0f ? 0.7f : splitterProportion;
}
public void setSplitterProportion(float value) {
splitterProportion = value;
dispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
public void addListener(ChangeListener listener) {
dispatcher.addListener(listener);
}
public void removeListener(ChangeListener listener) {
dispatcher.removeListener(listener);
}
// This attribute exists only to silence the "com.intellij.util.xmlb.Binding - no accessors for class" warning.
@Attribute(value = "placeholder")
public String placeholder;
void copyFrom(PreviewViewState other) {
this.placeholder = other.placeholder;
splitterProportion = other.splitterProportion;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/preview/PreviewViewState.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/preview/PreviewViewState.java",
"repo_id": "flutter-intellij",
"token_count": 434
} | 462 |
/*
* 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.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;
/**
* The Flutter launch mode. This corresponds to the flutter run modes: --debug, --profile, and --release.
*/
public enum FlutterLaunchMode {
DEBUG("debug"),
PROFILE("profile"),
RELEASE("release");
private static final Key<FlutterLaunchMode> LAUNCH_MODE_KEY = Key.create("FlutterLaunchMode");
public static void addToEnvironment(ExecutionEnvironment env, FlutterLaunchMode mode) {
env.putUserData(FlutterLaunchMode.LAUNCH_MODE_KEY, mode);
}
@NotNull
public static FlutterLaunchMode fromEnv(@NotNull ExecutionEnvironment env) {
final FlutterLaunchMode launchMode = env.getUserData(FlutterLaunchMode.LAUNCH_MODE_KEY);
return launchMode == null ? DEBUG : launchMode;
}
final private String myCliCommand;
FlutterLaunchMode(String cliCommand) {
this.myCliCommand = cliCommand;
}
public String getCliCommand() {
return myCliCommand;
}
/**
* This mode supports a debug connection (but, doesn't necessarily support breakpoints and debugging).
*/
public boolean supportsDebugConnection() {
return this == DEBUG || this == PROFILE;
}
public boolean supportsReload() {
return this == DEBUG;
}
public boolean isProfiling() {
return this == PROFILE;
}
@Override
public String toString() {
return myCliCommand;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/FlutterLaunchMode.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterLaunchMode.java",
"repo_id": "flutter-intellij",
"token_count": 498
} | 463 |
/*
* Copyright 2022 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.bazel;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.project.Project;
import io.flutter.run.FlutterDevice;
import io.flutter.run.common.RunMode;
import org.jetbrains.annotations.NotNull;
public class BazelAttachConfig extends BazelRunConfig {
public BazelAttachConfig(@NotNull Project project,
@NotNull ConfigurationFactory factory,
@NotNull String name) {
super(project, factory, name);
}
public BazelAttachConfig(BazelRunConfig configuration) {
super(configuration.getProject(), configuration.getFactory(), configuration.getName());
setFields(configuration.fields);
}
@NotNull
@Override
public GeneralCommandLine getCommand(ExecutionEnvironment env, @NotNull FlutterDevice device) throws ExecutionException {
final BazelFields launchFields = fields.copy();
final RunMode mode = RunMode.fromEnv(env);
return launchFields.getLaunchCommand(env.getProject(), device, mode, true);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelAttachConfig.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelAttachConfig.java",
"repo_id": "flutter-intellij",
"token_count": 445
} | 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.run.bazelTest;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.ListCellRendererWrapper;
import com.jetbrains.lang.dart.ide.runner.server.ui.DartCommandLineConfigurationEditorForm;
import io.flutter.run.bazelTest.BazelTestFields.Scope;
import io.flutter.settings.FlutterSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.ActionEvent;
import static io.flutter.run.bazelTest.BazelTestFields.Scope.*;
public class FlutterBazelTestConfigurationEditorForm extends SettingsEditor<BazelTestConfig> {
private JPanel myMainPanel;
private JComboBox<Scope> scope;
private JLabel scopeLabel;
private JLabel scopeLabelHint;
private TextFieldWithBrowseButton myEntryFile;
private JLabel myEntryFileLabel;
private JLabel myEntryFileHintLabel;
private JTextField myBuildTarget;
private JLabel myBuildTargetLabel;
private JLabel myBuildTargetHintLabel;
private JTextField myTestName;
private JLabel myTestNameLabel;
private JLabel myTestNameHintLabel;
private JTextField myAdditionalArgs;
private JLabel myAdditionalArgsLabel;
private JLabel myAdditionalArgsLabelHint;
private Scope displayedScope;
public FlutterBazelTestConfigurationEditorForm(final Project project) {
FlutterSettings.getInstance().addListener(() -> {
final Scope next = getScope();
updateFields(next);
render(getScope());
});
scope.setModel(new DefaultComboBoxModel<>(new Scope[]{TARGET_PATTERN, FILE, NAME}));
scope.addActionListener((ActionEvent e) -> {
final Scope next = getScope();
updateFields(next);
render(next);
});
scope.setRenderer(new ListCellRendererWrapper<Scope>() {
@Override
public void customize(final JList list,
final Scope value,
final int index,
final boolean selected,
final boolean hasFocus) {
setText(value.getDisplayName());
}
});
scope.setEnabled(true);
final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileDescriptor();
DartCommandLineConfigurationEditorForm.initDartFileTextWithBrowse(project, myEntryFile);
}
@Override
protected void resetEditorFrom(@NotNull final BazelTestConfig configuration) {
final BazelTestFields fields = configuration.getFields();
myTestName.setText(fields.getTestName());
myEntryFile.setText(FileUtil.toSystemDependentName(StringUtil.notNullize(fields.getEntryFile())));
myBuildTarget.setText(StringUtil.notNullize(fields.getBazelTarget()));
myAdditionalArgs.setText(StringUtil.notNullize(fields.getAdditionalArgs()));
final Scope next = fields.getScope(configuration.getProject());
scope.setSelectedItem(next);
render(next);
}
@Override
protected void applyEditorTo(@NotNull final BazelTestConfig configuration) {
final String testName = getTextValue(myTestName);
final String entryFile = getFilePathFromTextValue(myEntryFile);
final String bazelTarget = getTextValue(myBuildTarget);
final String additionalArgs = getTextValue(myAdditionalArgs);
final BazelTestFields fields = new BazelTestFields(
testName,
entryFile,
bazelTarget,
additionalArgs
);
configuration.setFields(fields);
}
@NotNull
@Override
protected JComponent createEditor() {
return myMainPanel;
}
/**
* When switching between file and directory scope, update the next field to
* a suitable default.
*/
private void updateFields(Scope next) {
// TODO(devoncarew): This if path is empty - due to a refactoring?
if (next == Scope.TARGET_PATTERN && displayedScope != Scope.TARGET_PATTERN) {
}
else if (next != Scope.TARGET_PATTERN) {
if (getFilePathFromTextValue(myEntryFile) == null) {
myEntryFile.setText(myBuildTarget.getText().replace("//", ""));
}
}
}
@NotNull
private Scope getScope() {
final Object item = scope.getSelectedItem();
// Set in resetEditorForm.
assert (item != null);
return (Scope)item;
}
/**
* Show and hide fields as appropriate for the next scope.
*/
private void render(Scope next) {
scope.setVisible(true);
scopeLabel.setVisible(true);
scopeLabelHint.setVisible(true);
myAdditionalArgs.setVisible(true);
myAdditionalArgsLabel.setVisible(true);
myAdditionalArgsLabel.setVisible(true);
myTestName.setVisible(next == Scope.NAME);
myTestNameLabel.setVisible(next == Scope.NAME);
myTestNameHintLabel.setVisible(next == Scope.NAME);
myEntryFile.setVisible(next == Scope.FILE || next == Scope.NAME);
myEntryFileLabel.setVisible(next == Scope.FILE || next == Scope.NAME);
myEntryFileHintLabel.setVisible(next == Scope.FILE || next == Scope.NAME);
myBuildTarget.setVisible(next == Scope.TARGET_PATTERN);
myBuildTargetLabel.setVisible(next == Scope.TARGET_PATTERN);
myBuildTargetHintLabel.setVisible(next == Scope.TARGET_PATTERN);
// Because the scope of the underlying fields is calculated based on which parameters are assigned,
// we remove fields that aren't part of the selected scope.
if (next.equals(Scope.TARGET_PATTERN)) {
myTestName.setText("");
myEntryFile.setText("");
}
else if (next.equals(Scope.FILE)) {
myTestName.setText("");
}
displayedScope = next;
}
@Nullable
private String getTextValue(@NotNull String textFieldContents) {
return StringUtil.nullize(textFieldContents.trim(), true);
}
@Nullable
private String getTextValue(JTextField textField) {
return getTextValue(textField.getText());
}
@Nullable
private String getFilePathFromTextValue(TextFieldWithBrowseButton textField) {
return getTextValue(FileUtil.toSystemIndependentName(textField.getText()));
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestConfigurationEditorForm.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestConfigurationEditorForm.java",
"repo_id": "flutter-intellij",
"token_count": 2234
} | 465 |
/*
* 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.intellij.execution.configurations.CommandLineState;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderImpl;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.GlobalSearchScopes;
import com.jetbrains.lang.dart.ide.runner.DartRelativePathsConsoleFilter;
import io.flutter.FlutterInitializer;
import io.flutter.analytics.Analytics;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.settings.FlutterSettings;
import io.flutter.utils.FlutterModuleUtils;
import io.flutter.utils.StdoutJsonParser;
import org.jetbrains.annotations.NotNull;
/**
* A console view that filters out JSON messages sent in --machine mode.
*/
public class DaemonConsoleView extends ConsoleViewImpl {
private static final Logger LOG = Logger.getInstance(DaemonConsoleView.class);
private final Analytics analytics = FlutterInitializer.getAnalytics();
/**
* Sets up a launcher to use a DaemonConsoleView.
*/
public static void install(@NotNull CommandLineState launcher, @NotNull ExecutionEnvironment env, @NotNull VirtualFile workDir) {
// Create our own console builder.
//
// We need to filter input to this console without affecting other consoles, so we cannot use a consoleFilterInputProvider.
final GlobalSearchScope searchScope = GlobalSearchScopes.executionScope(env.getProject(), env.getRunProfile());
final TextConsoleBuilder builder = new TextConsoleBuilderImpl(env.getProject(), searchScope) {
@NotNull
@Override
protected ConsoleView createConsole() {
return new DaemonConsoleView(env.getProject(), searchScope);
}
};
// Set up basic console filters. (More may be added later.)
// TODO(devoncarew): Do we need this filter? What about DartConsoleFilter (for package: uris)?
builder.addFilter(new DartRelativePathsConsoleFilter(env.getProject(), workDir.getPath()));
launcher.setConsoleBuilder(builder);
}
private final StdoutJsonParser stdoutParser = new StdoutJsonParser();
private boolean hasPrintedText;
public DaemonConsoleView(@NotNull final Project project, @NotNull final GlobalSearchScope searchScope) {
super(project, searchScope, true, false);
}
@Override
public void print(@NotNull String text, @NotNull ConsoleViewContentType contentType) {
if (!FlutterModuleUtils.hasFlutterModule(getProject())) {
return;
}
if (FlutterSettings.getInstance().isVerboseLogging()) {
super.print(text, contentType);
return;
}
if (contentType != ConsoleViewContentType.NORMAL_OUTPUT) {
writeAvailableLines();
// TODO(helin24): We want to log only disconnection messages, but we aren't sure what those are yet.
// Until then, only log error messages for internal users.
if (WorkspaceCache.getInstance(getProject()).isBazel() && contentType.equals(ConsoleViewContentType.ERROR_OUTPUT) && !text.isEmpty()) {
analytics.sendEvent("potential-disconnect", text);
}
super.print(text, contentType);
}
else {
stdoutParser.appendOutput(text);
writeAvailableLines();
}
}
private void writeAvailableLines() {
for (String line : stdoutParser.getAvailableLines()) {
if (DaemonApi.parseAndValidateDaemonEvent(line.trim()) != null) {
if (FlutterSettings.getInstance().isVerboseLogging()) {
LOG.info(line.trim());
}
}
else {
// We're seeing a spurious newline before some launches; this removes any single newline that occurred
// before we've printed text.
if (!hasPrintedText && line.equals(("\n"))) {
continue;
}
hasPrintedText = true;
super.print(line, ConsoleViewContentType.NORMAL_OUTPUT);
}
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DaemonConsoleView.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DaemonConsoleView.java",
"repo_id": "flutter-intellij",
"token_count": 1454
} | 466 |
/*
* 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.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.testframework.TestConsoleProperties;
import com.intellij.execution.testframework.actions.ConsolePropertiesProvider;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import io.flutter.sdk.FlutterSdk;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A configuration for running Flutter tests.
*
* Inheriting from ConsolePropertiesProvider enables the auto-test-before-commit feature in the VCS tool window.
* Note that using that window causes additional analysis to occur, which creates a bunch of spurious errors.
* IntelliJ has its own rules for Android files, and Flutter doesn't follow some of them.
*/
public class TestConfig extends LocatableConfigurationBase<CommandLineState> implements ConsolePropertiesProvider {
@NotNull
private TestFields fields = TestFields.forFile("");
protected TestConfig(@NotNull Project project,
@NotNull ConfigurationFactory factory, String name) {
super(project, factory, name);
}
@NotNull
public TestFields getFields() {
return fields;
}
public void setFields(@NotNull TestFields fields) {
this.fields = fields;
}
@Override
public void writeExternal(@NotNull Element element) throws WriteExternalException {
super.writeExternal(element);
fields.writeTo(element);
}
@Override
public void readExternal(@NotNull Element element) throws InvalidDataException {
super.readExternal(element);
fields = TestFields.readFrom(element);
}
@Override
public RunConfiguration clone() {
final TestConfig result = (TestConfig)super.clone();
result.fields = fields;
return result;
}
@NotNull
@Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new TestForm(getProject());
}
@Nullable
@Override
public String suggestedName() {
return fields.getSuggestedName(getProject(), "Flutter Tests");
}
@Override
public void checkConfiguration() throws RuntimeConfigurationException {
fields.checkRunnable(getProject());
}
@Nullable
public FlutterSdk getSdk() {
return FlutterSdk.getFlutterSdk(getProject());
}
@NotNull
@Override
public CommandLineState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException {
return TestLaunchState.create(env, this);
}
@Nullable
@Override
public TestConsoleProperties createTestConsoleProperties(@NotNull Executor exec) {
return new FlutterTestConsoleProperties(this, exec);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/test/TestConfig.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/TestConfig.java",
"repo_id": "flutter-intellij",
"token_count": 926
} | 467 |
/*
* 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.sdk;
import com.intellij.openapi.util.text.StringUtil;
import io.flutter.module.FlutterProjectType;
import io.flutter.module.settings.InitializeOnceBoolValueProperty;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterCreateAdditionalSettings {
@Nullable
private Boolean includeDriverTest;
@Nullable
private FlutterProjectType type;
@Nullable
private String description;
@Nullable
private String org;
@Nullable
private Boolean swift;
@Nullable
private Boolean kotlin;
@Nullable
private Boolean offlineMode;
@Nullable
private String projectName;
// These objects get re-used each time the UI is rebuilt, including after the Finish button is clicked.
@NotNull final private InitializeOnceBoolValueProperty platformAndroid = new InitializeOnceBoolValueProperty();
@NotNull final private InitializeOnceBoolValueProperty platformIos = new InitializeOnceBoolValueProperty();
@NotNull final private InitializeOnceBoolValueProperty platformWeb = new InitializeOnceBoolValueProperty();
@NotNull final private InitializeOnceBoolValueProperty platformLinux = new InitializeOnceBoolValueProperty();
@NotNull final private InitializeOnceBoolValueProperty platformMacos = new InitializeOnceBoolValueProperty();
@NotNull final private InitializeOnceBoolValueProperty platformWindows = new InitializeOnceBoolValueProperty();
public FlutterCreateAdditionalSettings() {
type = FlutterProjectType.APP;
description = "";
org = "";
}
private FlutterCreateAdditionalSettings(@Nullable Boolean includeDriverTest,
@Nullable FlutterProjectType type,
@Nullable String description,
@Nullable String org,
@Nullable Boolean swift,
@Nullable Boolean kotlin,
@Nullable Boolean offlineMode,
@Nullable Boolean platformAndroid,
@Nullable Boolean platformIos,
@Nullable Boolean platformWeb,
@Nullable Boolean platformLinux,
@Nullable Boolean platformMacos,
@Nullable Boolean platformWindows) {
this.includeDriverTest = includeDriverTest;
this.type = type;
this.description = description;
this.org = org;
this.swift = swift;
this.kotlin = kotlin;
this.offlineMode = offlineMode;
this.platformAndroid.set(Boolean.TRUE.equals(platformAndroid));
this.platformIos.set(Boolean.TRUE.equals(platformIos));
this.platformWeb.set(Boolean.TRUE.equals(platformWeb));
this.platformLinux.set(Boolean.TRUE.equals(platformLinux));
this.platformMacos.set(Boolean.TRUE.equals(platformMacos));
this.platformWindows.set(Boolean.TRUE.equals(platformWindows));
}
@Nullable
public String getProjectName() {
return projectName;
}
public void setProjectName(@Nullable String projectName) {
this.projectName = projectName;
}
public void setType(@Nullable FlutterProjectType value) {
type = value;
}
@Nullable
public String getOrg() {
return org;
}
public void setOrg(@Nullable String value) {
org = value;
}
public void setSwift(boolean value) {
swift = value;
}
public void setKotlin(boolean value) {
kotlin = value;
}
@NonNls
public List<String> getArgs() {
final List<String> args = new ArrayList<>();
if (Boolean.TRUE.equals(offlineMode)) {
args.add("--offline");
}
if (Boolean.TRUE.equals(includeDriverTest)) {
args.add("--with-driver-test");
}
if (type != null) {
if (type != FlutterProjectType.EMPTY_PROJECT) {
args.add("--template");
}
args.add(type.arg);
}
if (!StringUtil.isEmptyOrSpaces(description)) {
args.add("--description");
args.add(description);
}
if (!StringUtil.isEmptyOrSpaces(org)) {
args.add("--org");
args.add(org);
}
if (swift == null || Boolean.FALSE.equals(swift)) {
args.add("--ios-language");
args.add("objc");
}
if (kotlin == null || Boolean.FALSE.equals(kotlin)) {
args.add("--android-language");
args.add("java");
}
StringBuilder platforms = new StringBuilder();
if (platformAndroid.get()) {
platforms.append("android,");
}
if (platformIos.get()) {
platforms.append("ios,");
}
if (platformWeb.get()) {
platforms.append("web,");
}
if (platformLinux.get()) {
platforms.append("linux,");
}
if (platformMacos.get()) {
platforms.append("macos,");
}
if (platformWindows.get()) {
platforms.append("windows,");
}
if (type.requiresPlatform && platforms.isEmpty()) {
platforms.append("android,ios,");
}
int lastComma = platforms.lastIndexOf(",");
if (lastComma > 0) {
platforms.deleteCharAt(lastComma);
String platformsArg = platforms.toString();
args.add("--platforms");
args.add(platformsArg);
}
return args;
}
@Nullable
public String getDescription() {
return description;
}
public void setDescription(@Nullable String value) {
description = value;
}
@Nullable
public Boolean getKotlin() {
return kotlin;
}
@Nullable
public Boolean getSwift() {
return swift;
}
@Nullable
public Boolean getPlatformAndroid() {
return platformAndroid.get();
}
@Nullable
public Boolean getPlatformIos() {
return platformIos.get();
}
@Nullable
public Boolean getPlatformWeb() {
return platformWeb.get();
}
@Nullable
public Boolean getPlatformLinux() {
return platformLinux.get();
}
@Nullable
public Boolean getPlatformMacos() {
return platformMacos.get();
}
@Nullable
public Boolean getPlatformWindows() {
return platformWindows.get();
}
@Nullable
public FlutterProjectType getType() {
return type;
}
public boolean isSomePlatformSelected() {
return platformAndroid.get() ||
platformIos.get() ||
platformLinux.get() ||
platformMacos.get() ||
platformWeb.get() ||
platformWindows.get();
}
public InitializeOnceBoolValueProperty getPlatformAndroidProperty() {
return platformAndroid;
}
public InitializeOnceBoolValueProperty getPlatformIosProperty() {
return platformIos;
}
public InitializeOnceBoolValueProperty getPlatformWebProperty() {
return platformWeb;
}
public InitializeOnceBoolValueProperty getPlatformLinuxProperty() {
return platformLinux;
}
public InitializeOnceBoolValueProperty getPlatformMacosProperty() {
return platformMacos;
}
public InitializeOnceBoolValueProperty getPlatformWindowsProperty() {
return platformWindows;
}
public static class Builder {
@Nullable
private Boolean includeDriverTest;
@NotNull
private FlutterProjectType type = FlutterProjectType.APP;
@Nullable
private String description;
@Nullable
private String org;
@Nullable
private Boolean swift;
@Nullable
private Boolean kotlin;
@Nullable
private Boolean offlineMode;
@Nullable
private Boolean platformAndroid;
@Nullable
private Boolean platformIos;
@Nullable
private Boolean platformWeb;
@Nullable
private Boolean platformLinux;
@Nullable
private Boolean platformMacos;
@Nullable
private Boolean platformWindows;
public Builder() {
}
public Builder setIncludeDriverTest(@Nullable Boolean includeDriverTest) {
this.includeDriverTest = includeDriverTest;
return this;
}
public Builder setType(@Nullable FlutterProjectType type) {
this.type = type;
return this;
}
public Builder setDescription(@Nullable String description) {
this.description = description;
return this;
}
public Builder setOrg(@Nullable String org) {
this.org = org;
return this;
}
public Builder setSwift(@Nullable Boolean swift) {
this.swift = swift;
return this;
}
public Builder setKotlin(@Nullable Boolean kotlin) {
this.kotlin = kotlin;
return this;
}
public Builder setPlatformAndroid(@Nullable Boolean platformAndroid) {
this.platformAndroid = platformAndroid;
return this;
}
public Builder setPlatformIos(@Nullable Boolean platformIos) {
this.platformIos = platformIos;
return this;
}
public Builder setPlatformWeb(@Nullable Boolean platformWeb) {
this.platformWeb = platformWeb;
return this;
}
public Builder setPlatformLinux(@Nullable Boolean platformLinux) {
this.platformLinux = platformLinux;
return this;
}
public Builder setPlatformMacos(@Nullable Boolean platformMacos) {
this.platformMacos = platformMacos;
return this;
}
public Builder setPlatformWindows(@Nullable Boolean platformWindows) {
this.platformWindows = platformWindows;
return this;
}
public Builder setOffline(@Nullable Boolean offlineMode) {
this.offlineMode = offlineMode;
return this;
}
public FlutterCreateAdditionalSettings build() {
return new FlutterCreateAdditionalSettings(
includeDriverTest, type, description, org, swift, kotlin, offlineMode,
platformAndroid, platformIos, platformWeb, platformLinux, platformMacos, platformWindows);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterCreateAdditionalSettings.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterCreateAdditionalSettings.java",
"repo_id": "flutter-intellij",
"token_count": 3755
} | 468 |
/*
* 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.survey;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.lang.dart.DartFileType;
import icons.FlutterIcons;
import io.flutter.FlutterInitializer;
import io.flutter.FlutterMessages;
import io.flutter.pub.PubRoot;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class FlutterSurveyNotifications {
private static final int NOTIFICATION_DELAY_IN_SECS = 3;
private static final String FLUTTER_LAST_SURVEY_PROMPT_KEY = "FLUTTER_LAST_SURVEY_PROMPT_KEY";
private static final long PROMPT_INTERVAL_IN_MS = TimeUnit.HOURS.toMillis(40);
private static final String SURVEY_ACTION_TEXT = "Take survey";
private static final String SURVEY_DISMISSAL_TEXT = "No thanks";
interface FlutterSurveyNotifier {
void prompt();
}
@NotNull final Project myProject;
FlutterSurveyNotifications(@NotNull Project project) {
this.myProject = project;
}
public static void init(@NotNull Project project) {
project.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
@Override
public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file) {
check(file);
}
@Override
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
final VirtualFile file = event.getNewFile();
if (file != null) {
check(file);
}
}
private void check(@NotNull VirtualFile file) {
if (PubRoot.isPubspec(file) || file.getFileType() == DartFileType.INSTANCE) {
new FlutterSurveyNotifications(project).checkForDisplaySurvey();
}
}
});
}
private void checkForDisplaySurvey() {
final FlutterSurvey survey = FlutterSurveyService.getLatestSurveyContent();
if (survey == null) return;
// Limit display to the survey window.
if (!survey.isSurveyOpen()) return;
final PropertiesComponent properties = PropertiesComponent.getInstance();
// Don't prompt more often than every 40 hours.
final long lastPromptedMillis = properties.getLong(FLUTTER_LAST_SURVEY_PROMPT_KEY, 0);
if (System.currentTimeMillis() - lastPromptedMillis < PROMPT_INTERVAL_IN_MS) return;
properties.setValue(FLUTTER_LAST_SURVEY_PROMPT_KEY, String.valueOf(System.currentTimeMillis()));
// Or, if the survey has already been taken.
if (properties.getBoolean(survey.uniqueId)) return;
final boolean reportAnalytics = FlutterInitializer.getCanReportAnalytics();
final Notification notification = new Notification(
FlutterMessages.FLUTTER_NOTIFICATION_GROUP_ID,
FlutterIcons.Flutter,
survey.title,
null,
null,
NotificationType.INFORMATION,
null
);
//noinspection DialogTitleCapitalization
notification.addAction(new AnAction(SURVEY_ACTION_TEXT) {
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
properties.setValue(survey.uniqueId, true);
notification.expire();
String url = survey.urlPrefix + "?Source=IntelliJ";
// Add a client ID if analytics have been opted into.
if (reportAnalytics) {
FlutterInitializer.getAnalytics().sendEvent("intellij", "SurveyPromptAccepted");
}
BrowserUtil.browse(url);
}
});
//noinspection DialogTitleCapitalization
notification.addAction(new AnAction(SURVEY_DISMISSAL_TEXT) {
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
if (reportAnalytics) {
FlutterInitializer.getAnalytics().sendEvent("intellij", "SurveyPromptDismissed");
}
properties.setValue(survey.uniqueId, true);
notification.expire();
}
});
// Display the prompt after a short delay.
final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.schedule(() -> {
if (!myProject.isDisposed()) {
if (reportAnalytics) {
FlutterInitializer.getAnalytics().sendEvent("intellij", "SurveyPromptShown");
}
Notifications.Bus.notify(notification, myProject);
}
}, NOTIFICATION_DELAY_IN_SECS, TimeUnit.SECONDS);
scheduler.shutdown();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/survey/FlutterSurveyNotifications.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/survey/FlutterSurveyNotifications.java",
"repo_id": "flutter-intellij",
"token_count": 1848
} | 469 |
/*
* 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.vfs.VirtualFile;
import com.intellij.util.lang.UrlClassLoader;
import com.jetbrains.lang.dart.DartFileType;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.util.List;
public class FileUtils {
private static FileUtils fileUtils;
public static FileUtils getInstance() {
if (fileUtils == null) {
fileUtils = new FileUtils();
}
return fileUtils;
}
/**
* Makes a directory at the provided path.
* @param path path of the directory to be created.
* @return true if the directory already existed, or if it was successfully created; false if the directory could not be created.
*/
public boolean makeDirectory(String path) {
final File directory = new File(path);
if (!directory.exists()) {
return directory.mkdirs();
}
return true;
}
public boolean fileExists(String path) {
final File file = new File(path);
return file.exists();
}
/**
* Deletes a file at the provided path.
* @param path path of the file to be deleted.
* @return true if the file does not exist, or if it was successfully deleted; false if the file could not be deleted.
*/
public boolean deleteFile(String path) {
final File file = new File(path);
if (file.exists()) {
return file.delete();
}
return true;
}
public void loadClass(ClassLoader classLoader, String path) throws Exception {
final UrlClassLoader urlClassLoader = (UrlClassLoader) classLoader;
final File file = new File(path);
if (!file.exists()) {
throw new Exception("File does not exist: " + file.getAbsolutePath());
}
final URL url = file.toURI().toURL();
urlClassLoader.addURL(url);
}
/**
* Loads a list of file paths with a class loader.
*
* This is only available for versions 211.4961.30 and later.
* @param classLoader classloader that can be used as a UrlClassLoader to load the files.
* @param paths list of file paths to load.
*/
public void loadPaths(ClassLoader classLoader, List<Path> paths) {
final UrlClassLoader urlClassLoader = (UrlClassLoader) classLoader;
urlClassLoader.addFiles(paths);
}
public static boolean isDartFile(@NotNull VirtualFile file) {
return file.getFileType().equals(DartFileType.INSTANCE);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/FileUtils.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/FileUtils.java",
"repo_id": "flutter-intellij",
"token_count": 836
} | 470 |
package io.flutter.utils;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlUtils {
public static String generateHtmlFragmentWithHrefTags(String input) {
StringBuilder builder = new StringBuilder();
for (String token : input.split(" ")) {
if (!builder.isEmpty()) {
builder.append(" ");
}
try {
URL url = new URL(token);
builder.append("<a href=\"").append(url).append("\">").append(url).append("</a>");
} catch(MalformedURLException e) {
builder.append(token);
}
}
return builder.toString();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/UrlUtils.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/UrlUtils.java",
"repo_id": "flutter-intellij",
"token_count": 322
} | 471 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.view;
import icons.FlutterIcons;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.vmService.ServiceExtensions;
import org.jetbrains.annotations.NotNull;
public class DebugPaintAction extends FlutterViewToggleableAction {
public DebugPaintAction(@NotNull FlutterApp app) {
super(app, FlutterIcons.DebugPaint, ServiceExtensions.debugPaint);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/view/DebugPaintAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/DebugPaintAction.java",
"repo_id": "flutter-intellij",
"token_count": 172
} | 472 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.view;
import com.google.common.base.Joiner;
import com.intellij.openapi.diagnostic.Logger;
import io.flutter.FlutterUtils;
import io.flutter.inspector.DiagnosticsNode;
import io.flutter.inspector.TreeUtils;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.concurrent.CompletableFuture;
/**
* Listener that handles mouse interaction for the Inspector tree.
* <p>
* Handles displaying tooltips, notifying the InspectorPanel of what node is
* being highlighted, and custom double click selection behavior.
*/
class InspectorTreeMouseListener extends MouseAdapter {
private InspectorPanel panel;
private final JTree tree;
private DefaultMutableTreeNode lastHover;
private static final Logger LOG = Logger.getInstance(InspectorTreeMouseListener.class);
InspectorTreeMouseListener(InspectorPanel panel, JTree tree) {
this.panel = panel;
this.tree = tree;
}
@Override
public void mouseExited(MouseEvent e) {
clearTooltip();
endShowNode();
}
@Override
public void mouseClicked(MouseEvent event) {
final DefaultMutableTreeNode node = getClosestTreeNode(event);
// TODO(jacobr): support clicking on a property.
// It would be reasonable for that to trigger selecting the parent of the
// property.
final DiagnosticsNode diagnostic = TreeUtils.maybeGetDiagnostic(node);
if (diagnostic != null && !diagnostic.isProperty()) {
// A double click triggers forcing changing the subtree root.
if (event.getClickCount() == 2) {
if (panel.isSummaryTree) {
panel.applyNewSelection(diagnostic, diagnostic, true, false);
}
else if (panel.parentTree != null) {
panel.parentTree.applyNewSelection(
panel.firstAncestorInParentTree(node), diagnostic, true, false);
}
}
}
event.consume();
}
private void clearTooltip() {
final DiagnosticsTreeCellRenderer r = (DiagnosticsTreeCellRenderer)tree.getCellRenderer();
r.setToolTipText(null);
lastHover = null;
}
@Override
public void mouseMoved(MouseEvent event) {
calculateTooltip(event);
final DefaultMutableTreeNode treeNode = getTreeNode(event);
final DiagnosticsNode node = TreeUtils.maybeGetDiagnostic(treeNode);
if (node != null && !node.isProperty()) {
if (panel.detailsSubtree && panel.isCreatedByLocalProject(node)) {
panel.parentTree.highlightShowNode(node.getValueRef());
}
else if (panel.subtreePanel != null) {
panel.subtreePanel.highlightShowNode(node.getValueRef());
}
panel.highlightShowNode(treeNode);
}
}
private void endShowNode() {
if (panel.detailsSubtree) {
panel.parentTree.endShowNode();
}
else if (panel.subtreePanel != null) {
panel.subtreePanel.endShowNode();
}
panel.endShowNode();
}
private void calculateTooltip(MouseEvent event) {
final Point p = event.getPoint();
final int row = tree.getClosestRowForLocation(p.x, p.y);
final TreeCellRenderer r = tree.getCellRenderer();
if (r == null) {
return;
}
if (row == -1) {
clearTooltip();
return;
}
final TreePath path = tree.getPathForRow(row);
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
lastHover = node;
final Component rComponent = r.getTreeCellRendererComponent(tree, node, tree.isRowSelected(row), tree.isExpanded(row),
tree.getModel().isLeaf(node), row, true);
final Rectangle pathBounds = tree.getPathBounds(path);
if (pathBounds == null) {
// Something went wrong and the path isn't really visible.
return;
}
p.translate(-pathBounds.x, -pathBounds.y);
if (rComponent == null) {
clearTooltip();
return;
}
String tooltip = null;
final DiagnosticsTreeCellRenderer renderer = (DiagnosticsTreeCellRenderer)rComponent;
final DiagnosticsNode diagnostic = TreeUtils.maybeGetDiagnostic(node);
if (diagnostic != null) {
if (diagnostic.hasTooltip()) {
tooltip = diagnostic.getTooltip();
}
final Icon icon = renderer.getIconAt(p.x);
if (icon != null) {
if (icon == panel.defaultIcon) {
tooltip = "default value";
}
}
else {
if (diagnostic.getShowName()) {
final int fragmentIndex = renderer.findFragmentAt(p.x);
if (fragmentIndex == 0) {
// The name fragment is being hovered over.
// Set property description in tooltip.
// TODO (pq):
// * consider tooltips for values
// * consider rich navigation hovers (w/ styling and navigable docs)
final CompletableFuture<String> propertyDoc = diagnostic.getPropertyDoc();
final String doc = propertyDoc.getNow(null);
if (doc != null) {
tooltip = doc;
}
else {
tooltip = "Loading dart docs...";
diagnostic.safeWhenComplete(propertyDoc, (String tip, Throwable th) -> {
if (th != null) {
FlutterUtils.warn(LOG, th);
}
if (lastHover == node) {
// We are still hovering of the same node so show the user the tooltip.
renderer.setToolTipText(tip);
}
});
}
}
else {
if (diagnostic.isEnumProperty()) {
// We can display a better tooltip as we have access to introspection
// via the observatory service.
diagnostic.safeWhenComplete(diagnostic.getValueProperties(), (properties, th) -> {
if (properties == null || lastHover != node) {
return;
}
renderer.setToolTipText("Allowed values:\n" + Joiner.on('\n').join(properties.keySet()));
});
}
else {
renderer.setToolTipText(diagnostic.getTooltip());
}
}
}
}
}
renderer.setToolTipText(tooltip);
}
/**
* Match IntelliJ's fuzzier standards for what it takes to select a node.
*/
private DefaultMutableTreeNode getClosestTreeNode(MouseEvent event) {
final Point p = event.getPoint();
final int row = tree.getClosestRowForLocation(p.x, p.y);
final TreeCellRenderer r = tree.getCellRenderer();
if (row == -1 || r == null) {
return null;
}
final TreePath path = tree.getPathForRow(row);
return (DefaultMutableTreeNode)path.getLastPathComponent();
}
/**
* Requires the mouse to actually be over a tree node.
*/
private DefaultMutableTreeNode getTreeNode(MouseEvent event) {
final Point p = event.getPoint();
final int row = tree.getRowForLocation(p.x, p.y);
final TreeCellRenderer r = tree.getCellRenderer();
if (row == -1 || r == null) {
return null;
}
final TreePath path = tree.getPathForRow(row);
return (DefaultMutableTreeNode)path.getLastPathComponent();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/view/InspectorTreeMouseListener.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/InspectorTreeMouseListener.java",
"repo_id": "flutter-intellij",
"token_count": 3001
} | 473 |
package io.flutter.vmService;
import gnu.trove.THashMap;
import org.dartlang.vm.service.element.Isolate;
import org.dartlang.vm.service.element.IsolateRef;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public class IsolatesInfo {
public static class IsolateInfo {
private final IsolateRef myIsolateRef;
private boolean breakpointsSet = false;
private boolean shouldInitialResume = false;
private CompletableFuture<Isolate> myCachedIsolate;
private IsolateInfo(@NotNull IsolateRef isolateRef) {
this.myIsolateRef = isolateRef;
}
void invalidateCache() {
myCachedIsolate = null;
}
CompletableFuture<Isolate> getCachedIsolate() {
return myCachedIsolate;
}
void setCachedIsolate(CompletableFuture<Isolate> cachedIsolate) {
myCachedIsolate = cachedIsolate;
}
public IsolateRef getIsolateRef() {
return myIsolateRef;
}
public String getIsolateId() {
return myIsolateRef.getId();
}
public String getIsolateName() {
return myIsolateRef.getName();
}
public String toString() {
return getIsolateId() + ": breakpointsSet=" + breakpointsSet + ", shouldInitialResume=" + shouldInitialResume;
}
}
private final Map<String, IsolateInfo> myIsolateIdToInfoMap = new THashMap<>();
public synchronized boolean addIsolate(@NotNull final IsolateRef isolateRef) {
if (myIsolateIdToInfoMap.containsKey(isolateRef.getId())) {
return false;
}
myIsolateIdToInfoMap.put(isolateRef.getId(), new IsolateInfo(isolateRef));
return true;
}
public synchronized void setBreakpointsSet(@NotNull final IsolateRef isolateRef) {
final IsolateInfo info = myIsolateIdToInfoMap.get(isolateRef.getId());
if (info != null) {
info.breakpointsSet = true;
}
}
public synchronized void setShouldInitialResume(@NotNull final IsolateRef isolateRef) {
final IsolateInfo info = myIsolateIdToInfoMap.get(isolateRef.getId());
if (info != null) {
info.shouldInitialResume = true;
}
}
public synchronized boolean getShouldInitialResume(@NotNull final IsolateRef isolateRef) {
final IsolateInfo info = myIsolateIdToInfoMap.get(isolateRef.getId());
if (info != null) {
return info.breakpointsSet && info.shouldInitialResume;
}
else {
return false;
}
}
public synchronized void deleteIsolate(@NotNull final IsolateRef isolateRef) {
myIsolateIdToInfoMap.remove(isolateRef.getId());
}
public synchronized void invalidateCache(String isolateId) {
final IsolateInfo info = myIsolateIdToInfoMap.get(isolateId);
if (info != null) {
info.invalidateCache();
}
}
public synchronized CompletableFuture<Isolate> getCachedIsolate(String isolateId, Supplier<CompletableFuture<Isolate>> isolateSupplier) {
final IsolateInfo info = myIsolateIdToInfoMap.get(isolateId);
if (info == null) {
return CompletableFuture.completedFuture(null);
}
CompletableFuture<Isolate> cachedIsolate = info.getCachedIsolate();
if (cachedIsolate != null) {
return cachedIsolate;
}
cachedIsolate = isolateSupplier.get();
info.setCachedIsolate(cachedIsolate);
return cachedIsolate;
}
public synchronized Collection<IsolateInfo> getIsolateInfos() {
return new ArrayList<>(myIsolateIdToInfoMap.values());
}
}
| flutter-intellij/flutter-idea/src/io/flutter/vmService/IsolatesInfo.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/IsolatesInfo.java",
"repo_id": "flutter-intellij",
"token_count": 1248
} | 474 |
/*
* 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.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @coverage dart.server.generated.types
*/
@SuppressWarnings("unused")
public class ExtractWidgetFeedback extends RefactoringFeedback {
public static final ExtractWidgetFeedback[] EMPTY_ARRAY = new ExtractWidgetFeedback[0];
public static final List<ExtractWidgetFeedback> EMPTY_LIST = Lists.newArrayList();
/**
* Constructor for {@link ExtractWidgetFeedback}.
*/
public ExtractWidgetFeedback() {
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ExtractWidgetFeedback) {
ExtractWidgetFeedback other = (ExtractWidgetFeedback)obj;
return
true;
}
return false;
}
public static ExtractWidgetFeedback fromJson(JsonObject jsonObject) {
return new ExtractWidgetFeedback();
}
public static List<ExtractWidgetFeedback> fromJsonArray(JsonArray jsonArray) {
if (jsonArray == null) {
return EMPTY_LIST;
}
ArrayList<ExtractWidgetFeedback> list = new ArrayList<ExtractWidgetFeedback>(jsonArray.size());
Iterator<JsonElement> iterator = jsonArray.iterator();
while (iterator.hasNext()) {
list.add(fromJson(iterator.next().getAsJsonObject()));
}
return list;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
return builder.toHashCode();
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
return jsonObject;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append("]");
return builder.toString();
}
}
| flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/ExtractWidgetFeedback.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/ExtractWidgetFeedback.java",
"repo_id": "flutter-intellij",
"token_count": 742
} | 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.
*/
import 'dart:convert';
import 'dart:io';
/// Pretty-prints the contents of json from the file in arg 0 to the file in
/// arg 1.
///
/// Usage:
/// $ dart bin/pretty_print.dart json_file_raw.txt json_file.txt
void main(List<String> args) {
final fileContents = File(args[0]).readAsStringSync();
final json = jsonDecode(fileContents);
File(args[1]).writeAsStringSync(
JsonEncoder.withIndent(' ').convert(json),
);
print('Contents of ${args[0]} pretty-printed to ${args[1]}');
}
| flutter-intellij/flutter-idea/testData/sample_tests/bin/pretty_print.dart/0 | {
"file_path": "flutter-intellij/flutter-idea/testData/sample_tests/bin/pretty_print.dart",
"repo_id": "flutter-intellij",
"token_count": 218
} | 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 io.flutter;
import com.intellij.psi.PsiElement;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import io.flutter.ide.DartTestUtils;
import io.flutter.testing.ProjectFixture;
import io.flutter.testing.Testing;
import org.jetbrains.annotations.NotNull;
import org.junit.Rule;
import java.util.Objects;
public class AbstractDartElementTest {
@Rule
public final ProjectFixture<CodeInsightTestFixture> fixture = Testing.makeCodeInsightModule();
protected void run(@NotNull Testing.RunnableThatThrows callback) throws Exception {
Testing.runOnDispatchThread(callback);
}
/**
* Creates the syntax tree for a Dart file at a specific path and returns the innermost element with the given text.
*/
@NotNull
protected <E extends PsiElement> E setUpDartElement(String filePath, String fileText, String elementText, Class<E> expectedClass) {
assert fileText != null && elementText != null && expectedClass != null && fixture.getProject() != null;
return DartTestUtils.setUpDartElement(filePath, fileText, elementText, expectedClass, Objects.requireNonNull(fixture.getProject()));
}
/**
* Creates the syntax tree for a Dart file and returns the innermost element with the given text.
*/
@NotNull
protected <E extends PsiElement> E setUpDartElement(String fileText, String elementText, Class<E> expectedClass) {
assert fileText != null && elementText != null && expectedClass != null && fixture.getProject() != null;
return DartTestUtils.setUpDartElement(null, fileText, elementText, expectedClass, Objects.requireNonNull(fixture.getProject()));
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/AbstractDartElementTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/AbstractDartElementTest.java",
"repo_id": "flutter-intellij",
"token_count": 530
} | 477 |
/*
* 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.editor;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class ExpressionParsingUtilsTest {
@Test
public void parseColorComponents() {
assertThat(
ExpressionParsingUtils.parseColorComponents("255, 255, 255, 255)", "", true), is(notNullValue()));
assertThat(
ExpressionParsingUtils.parseColorComponents("256, 255, 255, 255)", "", true), is(nullValue()));
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/editor/ExpressionParsingUtilsTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/editor/ExpressionParsingUtilsTest.java",
"repo_id": "flutter-intellij",
"token_count": 214
} | 478 |
/*
* 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.project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import io.flutter.testing.ProjectFixture;
import io.flutter.testing.Testing;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertNotEquals;
public class ProjectWatchTest {
@Rule
public final ProjectFixture<IdeaProjectTestFixture> fixture = Testing.makeEmptyModule();
@Test
@Ignore
public void shouldSendEventWhenProjectCloses() throws Exception {
Testing.runOnDispatchThread(() -> {
final AtomicInteger callCount = new AtomicInteger();
final ProjectWatch listen = ProjectWatch.subscribe(fixture.getProject(), callCount::incrementAndGet);
ProjectManager.getInstance().closeProject(fixture.getProject());
// The number of events fired is an implementation detail of the project manager. We just need at least one.
assertNotEquals(0, callCount.get());
});
}
@Test @Ignore
public void shouldSendEventWhenModuleRootsChange() throws Exception {
Testing.runOnDispatchThread(() -> {
final AtomicInteger callCount = new AtomicInteger();
final ProjectWatch listen = ProjectWatch.subscribe(fixture.getProject(), callCount::incrementAndGet);
VirtualFile[] contentRoots = ModuleRootManager.getInstance(fixture.getModule()).getContentRoots();
VirtualFile dir = contentRoots[0].createChildDirectory(this, "testDir");
ModuleRootModificationUtil.addContentRoot(fixture.getModule(), dir);
PlatformTestUtil.dispatchAllEventsInIdeEventQueue();
// The number of events fired is an implementation detail of the project manager. We just need at least one.
assertNotEquals(0, callCount.get());
});
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/project/ProjectWatchTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/project/ProjectWatchTest.java",
"repo_id": "flutter-intellij",
"token_count": 688
} | 479 |
/*
* 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.sdk;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import io.flutter.module.FlutterProjectType;
import java.util.List;
import org.junit.Test;
public class FlutterCreateAdditionalSettingsTest {
@Test
public void includeDriverPropertyTest() {
final FlutterCreateAdditionalSettings additionalSettings1 =
new FlutterCreateAdditionalSettings.Builder().setIncludeDriverTest(true).build();
final FlutterCreateAdditionalSettings additionalSettings2 =
new FlutterCreateAdditionalSettings.Builder().setIncludeDriverTest(false).build();
final FlutterCreateAdditionalSettings additionalSettings3 =
new FlutterCreateAdditionalSettings.Builder().setIncludeDriverTest(null).build();
final List<String> args1 = additionalSettings1.getArgs();
final List<String> args2 = additionalSettings2.getArgs();
final List<String> args3 = additionalSettings3.getArgs();
assertEquals("--with-driver-test", args1.get(0));
assertEquals(args2.size(), args3.size());
}
@Test
public void generatePluginPropertyTest() {
final FlutterCreateAdditionalSettings additionalSettings1 =
new FlutterCreateAdditionalSettings.Builder().setType(FlutterProjectType.APP).build();
final FlutterCreateAdditionalSettings additionalSettings2 =
new FlutterCreateAdditionalSettings.Builder().setType(FlutterProjectType.PLUGIN).build();
final FlutterCreateAdditionalSettings additionalSettings3 =
new FlutterCreateAdditionalSettings.Builder().setType(FlutterProjectType.PACKAGE).build();
final List<String> args1 = additionalSettings1.getArgs();
final List<String> args2 = additionalSettings2.getArgs();
final List<String> args3 = additionalSettings3.getArgs();
final int base = 6;
assertEquals(base + 2, args1.size());
assertEquals("app", args1.get(1));
assertEquals(base + 2, args2.size());
assertEquals("plugin", args2.get(1));
assertEquals(base, args3.size());
assertEquals("package", args3.get(1));
}
@Test
public void descriptionPropertyTest() {
final String d = "My description.";
final FlutterCreateAdditionalSettings additionalSettings1 = new FlutterCreateAdditionalSettings.Builder().setDescription(d).build();
final FlutterCreateAdditionalSettings additionalSettings2 = new FlutterCreateAdditionalSettings.Builder().setDescription(" ").build();
final FlutterCreateAdditionalSettings additionalSettings3 = new FlutterCreateAdditionalSettings.Builder().setDescription(null).build();
final List<String> args1 = additionalSettings1.getArgs();
final List<String> args2 = additionalSettings2.getArgs();
final List<String> args3 = additionalSettings3.getArgs();
assertEquals(args2.size() + 2, args1.size());
assertEquals("--template", args1.get(0));
assertEquals(d, args1.get(3));
assertEquals(args2.size(), args3.size());
}
@Test
public void orgPropertyTest() {
final String d = "tld.domain";
final FlutterCreateAdditionalSettings additionalSettings1 = new FlutterCreateAdditionalSettings.Builder().setOrg(d).build();
final FlutterCreateAdditionalSettings additionalSettings2 = new FlutterCreateAdditionalSettings.Builder().setOrg(" ").build();
final FlutterCreateAdditionalSettings additionalSettings3 = new FlutterCreateAdditionalSettings.Builder().setOrg(null).build();
final List<String> args1 = additionalSettings1.getArgs();
final List<String> args2 = additionalSettings2.getArgs();
final List<String> args3 = additionalSettings3.getArgs();
assertEquals(args2.size() + 2, args1.size());
assertEquals("--org", args1.get(2));
assertEquals(d, args1.get(3));
assertEquals(args2.size(), args3.size());
}
@Test
public void iosPropertyTest() {
final FlutterCreateAdditionalSettings additionalSettings1 = new FlutterCreateAdditionalSettings.Builder().setSwift(true).build();
final FlutterCreateAdditionalSettings additionalSettings2 = new FlutterCreateAdditionalSettings.Builder().setSwift(false).build();
final FlutterCreateAdditionalSettings additionalSettings3 = new FlutterCreateAdditionalSettings.Builder().setSwift(null).build();
final List<String> args1 = additionalSettings1.getArgs();
final List<String> args2 = additionalSettings2.getArgs();
final List<String> args3 = additionalSettings3.getArgs();
assertEquals(6, args1.size());
assertNotEquals("--ios-language", args1.get(2));
assertEquals(args2.size(), args3.size());
}
@Test
public void kotlinPropertyTest() {
final FlutterCreateAdditionalSettings additionalSettings1 = new FlutterCreateAdditionalSettings.Builder().setKotlin(true).build();
final FlutterCreateAdditionalSettings additionalSettings2 = new FlutterCreateAdditionalSettings.Builder().setKotlin(false).build();
final FlutterCreateAdditionalSettings additionalSettings3 = new FlutterCreateAdditionalSettings.Builder().setKotlin(null).build();
final List<String> args1 = additionalSettings1.getArgs();
final List<String> args2 = additionalSettings2.getArgs();
final List<String> args3 = additionalSettings3.getArgs();
assertEquals(args2.size() - 2, args1.size());
assertNotEquals("--android-language", args1.get(0));
assertEquals(args2.size(), args3.size());
}
@Test
public void testPlatforms() {
// None of the non-platform tests set these properties so they all implicitly test the case where all are null.
final FlutterCreateAdditionalSettings additionalSettings = new FlutterCreateAdditionalSettings.Builder()
.setPlatformAndroid(true)
.setPlatformIos(true)
.setPlatformLinux(true)
.setPlatformMacos(true)
.setPlatformWeb(true)
.setPlatformWindows(true)
.build();
final List<String> args = additionalSettings.getArgs();
assertEquals(8, args.size());
assertEquals("--platforms", args.get(6));
assertEquals("android,ios,web,linux,macos,windows", args.get(7));
}
@Test
public void testPartialPlatforms() {
final FlutterCreateAdditionalSettings additionalSettings = new FlutterCreateAdditionalSettings.Builder()
.setPlatformIos(true)
.setPlatformMacos(true)
.setPlatformWindows(true)
.build();
final List<String> args = additionalSettings.getArgs();
assertEquals(8, args.size());
assertEquals("--platforms", args.get(6));
assertEquals("ios,macos,windows", args.get(7));
}
@Test
public void testSinglePlatforms() {
final FlutterCreateAdditionalSettings additionalSettings = new FlutterCreateAdditionalSettings.Builder()
.setPlatformAndroid(true)
.build();
final List<String> args = additionalSettings.getArgs();
assertEquals(8, args.size());
assertEquals("--platforms", args.get(6));
assertEquals("android", args.get(7));
}
@Test
public void testNoPlatforms() {
final FlutterCreateAdditionalSettings additionalSettings = new FlutterCreateAdditionalSettings.Builder()
.setPlatformAndroid(false)
.build();
final List<String> args = additionalSettings.getArgs();
assertEquals(8, args.size());
}
@Test
public void testMultipleProperties() {
final FlutterCreateAdditionalSettings additionalSettings = new FlutterCreateAdditionalSettings.Builder()
.setOrg("tld.domain")
.setType(FlutterProjectType.PLUGIN)
.setDescription("a b c")
.setSwift(true)
.setKotlin(true)
.build();
final List<String> args = additionalSettings.getArgs();
final String line = String.join(" ", args);
assertEquals(8, args.size());
assertEquals("--template plugin --description a b c --org tld.domain --platforms android,ios", line);
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/sdk/FlutterCreateAdditionalSettingsTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/sdk/FlutterCreateAdditionalSettingsTest.java",
"repo_id": "flutter-intellij",
"token_count": 2435
} | 480 |
/*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.utils;
import com.google.common.collect.ImmutableList;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class RefreshableTest {
private Refreshable<String> value;
private final List<String> logEntries = new ArrayList<>();
private final Semaphore canUnpublish = new Semaphore(0);
private final Semaphore unpublished = new Semaphore(0);
private final Semaphore canFireCloseEvent = new Semaphore(0);
private final Semaphore closeEventReceived = new Semaphore(0);
@Before
public void setUp() {
value = new Refreshable<>((value) -> {
acquireOrLog(canUnpublish, "unpublish not expected here");
log("unpublished: " + value);
unpublished.release();
});
value.subscribe(() -> {
if (!SwingUtilities.isEventDispatchThread()) {
log("subscriber should be called on Swing thread");
return;
}
if (value.getState() == Refreshable.State.CLOSED) {
acquireOrLog(canFireCloseEvent, "close event not expected here");
}
log(value.getState() + ": " + value.getNow());
if (value.getState() == Refreshable.State.CLOSED) {
closeEventReceived.release();
}
});
}
@Test
public void valueShouldBeNullAtStart() {
assertNull(value.getNow());
checkLog();
}
@Test
public void refreshShouldPublishNewValue() {
value.refresh(() -> "hello");
assertEquals("hello", value.getWhenReady());
checkLog("BUSY: null",
"BUSY: hello",
"IDLE: hello");
value.close();
expectUnpublish();
expectCloseEvent();
checkLog(
"unpublished: hello",
"CLOSED: null");
}
@Test
public void refreshShouldProvideAndUnpublishPreviousValue() {
value.refresh((req) -> {
log("previous: " + req.getPrevious());
return "one";
});
assertEquals("one", value.getWhenReady());
checkLog("BUSY: null",
"previous: null",
"BUSY: one",
"IDLE: one");
value.refresh((req) -> {
log("previous: " + req.getPrevious());
return "two";
});
expectUnpublish();
assertEquals("two", value.getWhenReady());
checkLog(
"BUSY: one",
"previous: one",
"unpublished: one",
"BUSY: two",
"IDLE: two");
value.close();
expectUnpublish();
expectCloseEvent();
checkLog("unpublished: two",
"CLOSED: null");
}
@Test
public void refreshShouldNotPublishOrUnpublishDuplicateValue() {
value.refresh(() -> "hello");
assertEquals("hello", value.getWhenReady());
checkLog("BUSY: null",
"BUSY: hello",
"IDLE: hello");
value.refresh(() -> "hello");
assertEquals("hello", value.getWhenReady());
checkLog("BUSY: hello",
"IDLE: hello");
value.close();
expectUnpublish();
expectCloseEvent();
checkLog("unpublished: hello",
"CLOSED: null");
}
@Test
public void refreshShouldNotPublishWhenCallbackThrowsException() {
value.refresh(() -> "first");
assertEquals("first", value.getWhenReady());
checkLog("BUSY: null",
"BUSY: first",
"IDLE: first");
value.refresh(() -> {
throw new RuntimeException("expected failure in test");
});
assertEquals("first", value.getWhenReady());
checkLog("BUSY: first",
"IDLE: first");
value.refresh((req) -> {
log("previous: " + req.getPrevious());
return "second";
});
expectUnpublish();
assertEquals("second", value.getWhenReady());
checkLog("BUSY: first",
"previous: first",
"unpublished: first",
"BUSY: second",
"IDLE: second");
}
@Test
public void refreshShouldRecoverIfSubscriberThrows() {
value.subscribe(() -> {
throw new RuntimeException("expected failure in test");
});
value.subscribe(() -> log(value.getState() + ": " + value.getNow() + " (last subscriber)"));
value.refresh(() -> "hello");
assertEquals("hello", value.getWhenReady());
checkLog("BUSY: null",
"BUSY: null (last subscriber)",
"BUSY: hello",
"BUSY: hello (last subscriber)",
"IDLE: hello",
"IDLE: hello (last subscriber)");
}
@Test
public void refreshShouldCancelRunningTaskWhenNewTaskIsSubmitted() throws Exception {
// Create a task that will block until we say to finish.
final FutureTask<?> startedFirstTask = new FutureTask<>(() -> null);
final FutureTask<String> dependency = new FutureTask<>(() -> "first task");
final AtomicReference<Refreshable.Request> firstRequest = new AtomicReference<>();
final Refreshable.Callback<String> firstTask = (request) -> {
firstRequest.set(request);
startedFirstTask.run();
return dependency.get();
};
final Callable<String> secondTask = () -> "second task";
value.refresh(firstTask);
startedFirstTask.get(); // wait for first task to start running.
assertNull("should have blocked on the dependency", value.getNow());
checkLog("BUSY: null");
value.refresh(secondTask);
assertTrue("should have cancelled first task", firstRequest.get().isCancelled());
checkLog();
dependency.run(); // Make first task exit, allowing second to run.
expectUnpublish();
assertEquals("second task", value.getWhenReady());
checkLog("unpublished: first task",
"BUSY: second task",
"IDLE: second task");
}
@Test
public void refreshShouldYieldToQueuedEvents() throws Exception {
// Queue up some events.
SwingUtilities.invokeAndWait(() -> {
value.refresh(() -> {
log("shouldn't create first");
return "first";
});
value.refresh((req) -> {
log("shouldn't create second");
return "second";
});
SwingUtilities.invokeLater(() -> value.refresh((req) -> {
log("created third; previous: " + req.getPrevious());
return "third";
}));
});
assertEquals("third", value.getWhenReady());
checkLog("BUSY: null",
"created third; previous: null",
"BUSY: third",
"IDLE: third");
}
@Test
public void publishShouldYieldToQueuedEvents() throws Exception {
final Semaphore finish = startRefresh("first");
SwingUtilities.invokeAndWait(() -> {
finish.release();
// Make sure publishing values is blocked until we exit.
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
log("unexpected exception: " + e);
}
log("event handler done");
});
assertEquals("first", value.getWhenReady());
checkLog("BUSY: null",
"entered refresh",
"exited refresh: first",
"event handler done",
"BUSY: first",
"IDLE: first");
}
@Test
public void shouldNotPublishWhenClosedDuringRefreshCallback() throws Exception {
final Semaphore finish = startRefresh("first");
value.close();
expectCloseEvent();
finish.release();
expectUnpublish();
assertNull(value.getWhenReady());
checkLog(
"BUSY: null",
"entered refresh",
"CLOSED: null",
"exited refresh: first",
"unpublished: first");
}
@Test
public void shouldNotPublishWhenClosedBeforePublish() throws Exception {
final Semaphore finish = startRefresh("first");
SwingUtilities.invokeAndWait(() -> {
SwingUtilities.invokeLater(() -> {
// Need to lose race with background tasks's call to reschedule(),
// But win the race to publish().
// So, schedule Swing event now, but make it slower.
// (No suitable semaphore for this one.)
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
log("interrupted");
}
value.close();
log("called close()");
});
finish.release();
});
expectUnpublish();
expectCloseEvent();
assertNull(value.getWhenReady());
checkLog("BUSY: null",
"entered refresh",
"exited refresh: first",
"called close()",
"unpublished: first",
"CLOSED: null");
}
private void expectUnpublish() {
canUnpublish.release();
acquireOrLog(unpublished, "should have unpublished");
}
private void expectCloseEvent() {
canFireCloseEvent.release();
acquireOrLog(closeEventReceived, "should have gotten close event");
}
private void acquireOrLog(Semaphore s, String error) {
try {
if (!s.tryAcquire(1, TimeUnit.SECONDS)) {
log(error);
}
} catch (InterruptedException e) {
log(error + " (interrupted)");
}
}
/**
* Starts running a refresh, but block until the test tells it to finish.
*
* <p>The caller should invoke release on the returned semaphore to unblock
* the refresh callback.
*/
private @NotNull Semaphore startRefresh(String newValue) throws Exception {
final Semaphore start = new Semaphore(0);
final Semaphore finish = new Semaphore(0);
value.refresh(() -> {
log("entered refresh");
start.release();
finish.acquire();
log("exited refresh: " + newValue);
return newValue;
});
start.acquire();
return finish;
}
private synchronized boolean log(String message) {
return logEntries.add(message);
}
private synchronized List<String> getLogEntries() {
return ImmutableList.copyOf(logEntries);
}
private void checkLog(String... expectedEntries) {
assertThat("logEntries entries are different", getLogEntries(), is(ImmutableList.copyOf(expectedEntries)));
logEntries.clear();
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/RefreshableTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/RefreshableTest.java",
"repo_id": "flutter-intellij",
"token_count": 4021
} | 481 |
package org.dartlang.vm.service.element;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Iterator;
/**
* Simple wrapper around a {@link JsonArray} which lazily converts {@link JsonObject} elements to
* subclasses of {@link Element}. Subclasses need only implement {@link #basicGet(JsonArray, int)}
* to return an {@link Element} subclass for the {@link JsonObject} at a given index.
*/
public abstract class ElementList<T> implements Iterable<T> {
private final JsonArray array;
public ElementList(JsonArray array) {
this.array = array;
}
public T get(int index) {
return basicGet(array, index);
}
public boolean isEmpty() {
return size() == 0;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
int index = 0;
@Override
public boolean hasNext() {
return index < size();
}
@Override
public T next() {
return get(index++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public int size() {
return array.size();
}
protected abstract T basicGet(JsonArray array, int index);
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ElementList.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ElementList.java",
"repo_id": "flutter-intellij",
"token_count": 435
} | 482 |
/*
* Copyright (c) 2015, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.dartlang.vm.service.element;
// This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* See getInboundReferences.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class InboundReference extends Element {
public InboundReference(JsonObject json) {
super(json);
}
/**
* If `source` is a `List`, `parentField` is the index of the inbound reference. If `source` is a
* record, `parentField` is the field name of the inbound reference. If `source` is an instance
* of any other kind, `parentField` is the field containing the inbound reference.
*
* Note: In v5.0 of the spec, `@Field` will no longer be a part of this property's type, i.e. the
* type will become `string|int`.
*
* @return one of <code>FieldRef</code>, <code>String</code> or <code>int</code>
*
* Can return <code>null</code>.
*/
public Object getParentField() {
final JsonElement elem = json.get("parentField");
if (elem == null) return null;
if (elem.isJsonPrimitive()) {
final JsonPrimitive p = (JsonPrimitive) elem;
if (p.isString()) return p.getAsString();
if (p.isNumber()) return p.getAsInt();
}
if (elem.isJsonObject()) {
final JsonObject o = (JsonObject) elem;
if (o.get("type").getAsString().equals("@Field")) return new FieldRef(o);
}
return null;
}
/**
* If source is a List, parentListIndex is the index of the inbound reference (deprecated).
*
* Note: this property is deprecated and will be replaced by `parentField`.
*
* Can return <code>null</code>.
*/
public int getParentListIndex() {
return getAsInt("parentListIndex");
}
/**
* The object holding the inbound reference.
*/
public ObjRef getSource() {
return new ObjRef((JsonObject) json.get("source"));
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/InboundReference.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/InboundReference.java",
"repo_id": "flutter-intellij",
"token_count": 841
} | 483 |
/*
* 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;
/**
* A {@link MemoryUsage} object provides heap usage information for a specific isolate at a given
* point in time.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class MemoryUsage extends Response {
public MemoryUsage(JsonObject json) {
super(json);
}
/**
* The amount of non-Dart memory that is retained by Dart objects. For example, memory associated
* with Dart objects through APIs such as Dart_NewFinalizableHandle, Dart_NewWeakPersistentHandle
* and Dart_NewExternalTypedData. This usage is only as accurate as the values supplied to these
* APIs from the VM embedder. This external memory applies GC pressure, but is separate from
* heapUsage and heapCapacity.
*/
public int getExternalUsage() {
return getAsInt("externalUsage");
}
/**
* The total capacity of the heap in bytes. This is the amount of memory used by the Dart heap
* from the perspective of the operating system.
*/
public int getHeapCapacity() {
return getAsInt("heapCapacity");
}
/**
* The current heap memory usage in bytes. Heap usage is always less than or equal to the heap
* capacity.
*/
public int getHeapUsage() {
return getAsInt("heapUsage");
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/MemoryUsage.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/MemoryUsage.java",
"repo_id": "flutter-intellij",
"token_count": 568
} | 484 |
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.actions;
public class FlutterShowStructureSettingsAction {}
/*
import com.android.tools.idea.gradle.structure.actions.AndroidShowStructureSettingsAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import io.flutter.utils.FlutterModuleUtils;
// This restores the Project Structure editor but does not convert it to use the
// new version defined by Android Studio. That one needs a lot of work to function
// with Flutter projects.
public class FlutterShowStructureSettingsAction extends AndroidShowStructureSettingsAction {
@Override
public void update(AnActionEvent e) {
Project project = e.getProject();
if (project != null && FlutterModuleUtils.hasFlutterModule(project)) {
e.getPresentation().setEnabledAndVisible(true);
}
else {
super.update(e);
}
}
@Override
public void actionPerformed(AnActionEvent e) {
//Project project = e.getProject();
//if (project == null && IdeInfo.getInstance().isAndroidStudio()) {
// project = ProjectManager.getInstance().getDefaultProject();
// showAndroidProjectStructure(project);
// return;
//}
//
//if (project != null) {
// showAndroidProjectStructure(project);
// return;
//}
super.actionPerformed(e);
}
//private static void showAndroidProjectStructure(@NotNull Project project) {
// if (StudioFlags.NEW_PSD_ENABLED.get()) {
// ProjectStructureConfigurable projectStructure = ProjectStructureConfigurable.getInstance(project);
// AtomicBoolean needsSync = new AtomicBoolean();
// ProjectStructureConfigurable.ProjectStructureChangeListener changeListener = () -> needsSync.set(true);
// projectStructure.add(changeListener);
// projectStructure.showDialog();
// projectStructure.remove(changeListener);
// if (needsSync.get()) {
// GradleSyncInvoker.getInstance().requestProjectSyncAndSourceGeneration(project, TRIGGER_PROJECT_MODIFIED);
// }
// return;
// }
// AndroidProjectStructureConfigurable.getInstance(project).showDialog();
//}
}*/
| flutter-intellij/flutter-studio/src/io/flutter/actions/FlutterShowStructureSettingsAction.java/0 | {
"file_path": "flutter-intellij/flutter-studio/src/io/flutter/actions/FlutterShowStructureSettingsAction.java",
"repo_id": "flutter-intellij",
"token_count": 715
} | 485 |
package org.jetbrains.idea.maven.wizards;
// This class definition is required to prevent an exception during extension initialization.
public class MavenWizardBundle {
public static String message(String msg, Object... args) {
return "NO MESSAGE";
}
}
| flutter-intellij/flutter-studio/src/org/jetbrains/idea/maven/wizards/MavenWizardBundle.java/0 | {
"file_path": "flutter-intellij/flutter-studio/src/org/jetbrains/idea/maven/wizards/MavenWizardBundle.java",
"repo_id": "flutter-intellij",
"token_count": 75
} | 486 |
/*
* 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.util;
import static com.android.tools.idea.util.ToolWindows.activateProjectView;
import static com.intellij.ide.impl.ProjectUtil.focusProjectWindow;
import static com.intellij.openapi.fileChooser.impl.FileChooserUtil.setLastOpenedFile;
import static com.intellij.openapi.ui.Messages.showErrorDialog;
import static com.intellij.openapi.util.io.FileUtil.toCanonicalPath;
import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
import static com.intellij.util.ExceptionUtil.rethrowUnchecked;
import com.android.tools.idea.tests.gui.framework.GuiTests;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.platform.PlatformProjectOpenProcessor;
import com.intellij.platform.templates.github.ZipUtil;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.EnumSet;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.jetbrains.annotations.NotNull;
/**
* ProjectWrangler encapsulates the project operations required by GUI tests.
* The testData directory must be identified as a test resource in the Project
* Structure dialog.
* <p>
* Sample projects are found in $MODULE_NAME/testData/PROJECT_DIR
* During a test build everything in testData (but NOT testData itself) is
* copied to the working directory under out/test. When a sample project is
* opened or imported it is first copied to a temp directory, then opened.
* <p>
* Opening a project uses it as-is. Importing a project first deletes IntelliJ
* meta-data, like .idea and *.iml.
*/
@SuppressWarnings("deprecation")
public class ProjectWrangler {
// Name of the module that defines GUI tests
public static final String MODULE_NAME = "flutter-studio";
// Name of the directory under testData where test projects are hosted during testing
public static final String PROJECT_DIR = "flutter_projects";
private static final String SRC_ZIP_NAME = "src.zip";
@NotNull final private String myTestDirectory;
public ProjectWrangler(@NotNull String dirName) {
myTestDirectory = dirName;
}
public void openProject(@NotNull VirtualFile selectedFile) {
VirtualFile projectFolder = findProjectFolder(selectedFile);
try {
doOpenProject(projectFolder);
}
catch (Throwable e) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
rethrowUnchecked(e);
}
showErrorDialog(e.getMessage(), "Open Project");
getLogger().error(e);
}
}
@NotNull
private Logger getLogger() {
return Logger.getInstance(getClass());
}
public File setUpProject(@NotNull String projectDirName, boolean isImport) throws IOException {
File projectPath = copyProjectBeforeOpening(projectDirName);
if (isImport) {
cleanUpProjectForImport(projectPath);
}
return projectPath;
}
public File copyProjectBeforeOpening(@NotNull String projectDirName) throws IOException {
File masterProjectPath = getMasterProjectDirPath(projectDirName);
File projectPath = getTestProjectDirPath(projectDirName);
if (projectPath.isDirectory()) {
FileUtilRt.delete(projectPath);
}
// If masterProjectPath contains a src.zip file, unzip the file to projectPath.
// Otherwise, copy the whole directory to projectPath.
File srcZip = new File(masterProjectPath, SRC_ZIP_NAME);
if (srcZip.exists() && srcZip.isFile()) {
ZipUtil.unzip(null, projectPath, srcZip, null, null, true);
}
else {
FileUtil.copyDir(masterProjectPath, projectPath);
}
return projectPath;
}
@NotNull
private File getTestProjectDirPath(@NotNull String projectDirName) {
assert (myTestDirectory != null);
return new File(GuiTests.getProjectCreationDirPath(myTestDirectory), projectDirName);
}
public void cleanUpProjectForImport(@NotNull File projectPath) {
File dotIdeaFolderPath = new File(projectPath, Project.DIRECTORY_STORE_FOLDER);
if (dotIdeaFolderPath.isDirectory()) {
File modulesXmlFilePath = new File(dotIdeaFolderPath, "modules.xml");
if (modulesXmlFilePath.isFile()) {
SAXBuilder saxBuilder = new SAXBuilder();
try {
Document document = saxBuilder.build(modulesXmlFilePath);
XPath xpath = XPath.newInstance("//*[@fileurl]");
//noinspection unchecked
List<Element> modules = xpath.selectNodes(document);
int urlPrefixSize = "file://$PROJECT_DIR$/".length();
for (Element module : modules) {
String fileUrl = module.getAttributeValue("fileurl");
if (!StringUtil.isEmpty(fileUrl)) {
String relativePath = toSystemDependentName(fileUrl.substring(urlPrefixSize));
File imlFilePath = new File(projectPath, relativePath);
if (imlFilePath.isFile()) {
FileUtilRt.delete(imlFilePath);
}
// It is likely that each module has a "build" folder. Delete it as well.
File buildFilePath = new File(imlFilePath.getParentFile(), "build");
if (buildFilePath.isDirectory()) {
FileUtilRt.delete(buildFilePath);
}
}
}
}
catch (Throwable ignored) {
// if something goes wrong, just ignore. Most likely it won't affect project import in any way.
}
}
FileUtilRt.delete(dotIdeaFolderPath);
}
}
@NotNull
private static File getMasterProjectDirPath(@NotNull String projectDirName) {
return new File(ProjectWrangler.getTestProjectsRootDirPath(), projectDirName);
}
@NotNull
private static File getTestProjectsRootDirPath() {
// It is important that the testData directory be marked as a test resource so its content is copied to out/test dir
String testDataPath = PathManager.getHomePathFor(ProjectWrangler.class);
// "out/test" is defined by IntelliJ but we may want to change the module or root dir of the test projects.
testDataPath = Paths.get(testDataPath, "out", "test", MODULE_NAME).toString();
testDataPath = toCanonicalPath(toSystemDependentName(testDataPath));
return new File(testDataPath, PROJECT_DIR);
}
@NotNull
private static VirtualFile findProjectFolder(@NotNull VirtualFile selectedFile) {
return selectedFile.isDirectory() ? selectedFile : selectedFile.getParent();
}
private static void afterProjectOpened(@NotNull VirtualFile projectFolder, @NotNull Project project) {
TransactionGuard.getInstance().submitTransactionLater(project, () -> {
setLastOpenedFile(project, projectFolder);
focusProjectWindow(project, false);
activateProjectView(project);
});
}
private static void doOpenProject(VirtualFile baseDir) {
// Open the project window.
EnumSet<PlatformProjectOpenProcessor.Option> options = EnumSet.noneOf(PlatformProjectOpenProcessor.Option.class);
Project project = PlatformProjectOpenProcessor.doOpenProject(baseDir, null, -1, null, options);
afterProjectOpened(baseDir, project);
}
}
| flutter-intellij/flutter-studio/testSrc/io/flutter/tests/util/ProjectWrangler.java/0 | {
"file_path": "flutter-intellij/flutter-studio/testSrc/io/flutter/tests/util/ProjectWrangler.java",
"repo_id": "flutter-intellij",
"token_count": 2624
} | 487 |
<!-- Do not edit; instead, modify plugin_template.xml, and run './bin/plugin generate'. -->
<idea-plugin>
<id>io.flutter</id>
<name>Flutter</name>
<description>
<![CDATA[
<p>Support for developing Flutter applications. Flutter gives developers an easy and productive
way to build and deploy cross-platform, high-performance mobile apps for both Android and iOS.
Installing this plugin will also install the Dart plugin.</p>
<br>
<p>For some tools, this plugin uses Chromium through JxBrowser to display content from the web.
JxBrowser complies with LGPL and offers an option to replace Chromium with another component.
To do this:</p>
<li>Find the JxBrowser files stored in the <a href="https://www.jetbrains.com/help/idea/tuning-the-ide.html?_ga=2.242942337.2083770720.1598541288-1470153005.1588544220#plugins-directory">plugins directory</a>, under /flutter-intellij/jxbrowser.</li>
<li>The LGPL requirements are at <a href="https://teamdev.com/jxbrowser/lgpl-compliance/#source-code">from JxBrowser</a>, here you can also download the build script to relink with modified components.</li>
]]>
</description>
<!--suppress PluginXmlValidity -->
<vendor url="https://google.com">Google</vendor>
<category>Custom Languages</category>
<version>SNAPSHOT</version>
<idea-version since-build="233.13135.103" until-build="233.*"/>
<depends>com.intellij.modules.platform</depends>
<depends>com.intellij.modules.lang</depends>
<depends>com.intellij.modules.xdebugger</depends>
<depends>com.intellij.modules.coverage</depends>
<depends>org.jetbrains.plugins.yaml</depends>
<depends>org.jetbrains.android</depends>
<depends>Dart</depends>
<depends>Git4Idea</depends>
<!-- plugin compatibility -->
<!-- see: http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html -->
<!-- Contributes IDEA-specific features and implementations. -->
<depends optional="true" config-file="idea-contribs.xml">com.intellij.modules.java</depends>
<depends optional="true" config-file="flutter-coverage.xml">com.intellij.modules.coverage</depends>
<!-- Contributes Android Studio-specific features and implementations. -->
<!--suppress PluginXmlValidity -->
<depends optional="true" config-file="studio-contribs.xml">com.intellij.modules.androidstudio</depends>
<change-notes>
<![CDATA[
<h1>78.4</h1>
<ul>
<li>Use Dart plugin's DevTools instance with DTD (#7264)</li>
</ul>
<h1>78.2, 78.3</h1>
<ul>
<li>Fix debugger variable information (#7228)</li>
</ul>
<h1>78, 78.1</h1>
<ul>
<li>Fix DevTools Inspector for all Android Studio users (#7147)</li>
</ul>
<h1>77.2</h1>
<ul>
<li>Update the vendor information for the JetBrains plugin marketplace (#7193)</li>
</ul>
<h1>77, 77.1</h1>
<ul>
<li>Report IDE feature source when opening DevTools (#7108)</li>
<li>Remove listener for file path on project dispose (#7093)</li>
<li>Dispose SDK config correctly on app ending (#7064)</li>
<li>Remove deprecated notification group usage from deep link (#7061)</li>
<li>Update plugin for Android Studio 2023.3 (Iguana) and IntelliJ 2023.3 (#7113)</li>
</ul>
<h1>76.3</h1>
<ul>
<li>Unmigrate change to use the new ActionListener API from IntelliJ as it introduced an issue with FlutterReloadManager (#6996)</li>
<li>Remove JX Browser usages and references (#7059)</li>
<li>Log and show link to open DevTools in separate browser if JCEF fails (#7057)</li>
</ul>
<h1>76.2</h1>
<ul>
<li>Fix for IndexOutOfBounds on startup (#6942)</li>
</ul>
<h1>76.1</h1>
<ul>
<li>Fix for JXBrowser key not provided (#6992)</li>
</ul>
<h1>76</h1>
<ul>
<li>Widget inspector doesn't jump to source code (#6875)</li>
<li>Change to use <code>org.apache.commons.lang3.*</code>, from <code>org.apache.commons.lang.*</code> (#6933)</li>
</ul>
<h1>75</h1>
<ul>
<li>Use pooled thread to find location of Android Studio (#6849)</li>
<li>Update build script for AS canary and IJ stable (#6846)</li>
<li>Remove isEnableEmbeddedBrowsers setting (#6845)</li>
<li>Stop showing an error after running tests with coverage (#6843)</li>
<li>Add gradle to ignore list (#6839)</li>
<li>Update VM service protocol to 4.11 (#6838)</li>
<li>Make AS 2022.2 the oldest supported platform (#6837)</li>
<li>Clear browser tabs when window closes (#6835)</li>
<li>Use BGT to update UI during reload/restart (#6836)</li>
<li>Default to JCEF browser (#6834)</li>
<li>Debug with 2023.2 (#6826)</li>
<li>Update Java, Gradle, plugins, and clean up (#6825)</li>
<li>Use EAP to run unit tests (#6822)</li>
<li>FlutterSdkVersion.version needs to be nullable (#6821)</li>
<li>Update build for latest EAP (#6820)</li>
<li>Disable Java indexing in AS canary (#6815)</li>
<li>add Open in Xcode for macOS (#6791)</li>
<li>Remove deprecated strong-mode entry in analysis options (#6800)</li>
<li>Update EAP build (#6797)</li>
<li>Add JCEF browser (#6787)</li>
</ul>
<h1>74</h1>
<ul>
<li>Support multiple running instance for inspectors (#6772)</li>
<li>Add Short super.key (#6757)</li>
<li>Enable envars for run configs (#6765)</li>
<li>Save pub root for attach (#6764)</li>
<li>Build for 2023.2 EAP (#6763)</li>
<li>Use VM service URI instead of observatory URI for bazel test startup (#6742)</li>
<li>Reorg CONTRIBUTING.md (#6740)</li>
<li>Improve run configurations (#6739)</li>
<li>Allow making the plugin from multiple platforms (#6730)</li>
<li>Delete <code>flutter-idea/artifacts</code> link (#6729)</li>
<li>Remove use of legacy inspector (#6728)</li>
<li>Use BGT to update UI for restart/reload (#6727)</li>
<li>Update versions in build script (#6721)</li>
<li>Update Dart version for latest EAP build (#6720)</li>
<li>Fix generation of presubmit.yaml (#6708)</li>
<li>Add a readme for kokoro (#6707)</li>
<li>Fix typo in icon file name (#6705)</li>
<li>Fix presubmit template (#6706)</li>
</ul>
<h1>73.1</h1>
<ul>
<li>Build for Android Studio Hedgehog</li>
</ul>
<h1>73</h1>
<ul>
<li>Prevent NPE when process is stopped while record fields are displayed</li>
<li>Check lcov files for files with no test coverage (#6692)</li>
<li>Add FLUTTER_SDK to setup instructions (#6684)</li>
<li>Fix DevTools opening for bazel workspaces (#6682)</li>
<li>Eliminate the dependency on artifacts (#6681)</li>
<li>Update Refresh on BGT (#6679)</li>
<li>Run unit tests on linux bots (#6675)</li>
<li>Follow-up on #6500, don't use setExceptionPauseMode() if possible (#6674)</li>
<li>Run unit tests on Linux (#6669)</li>
<li>Add the run configuration to make the plugin (#6639)</li>
<li>Remove some obsolete code (#6667)</li>
<li>Update on BGT (#6664)</li>
<li>Update VM service protocol (#6653)</li>
<li>Use 2023.1 to build (#6651)</li>
<li>Use 2022.3 for building (#6496)</li>
<li>Use <code>Directory.delete</code> instead of <code>rm</code> (#6649)</li>
<li>Always use <code>Utf8Codec</code> for plugin logs (#6648)</li>
<li>Use <code>FLUTTER_STORAGE_BASE_URL</code> for <code>ArtifactManager</code> (#6647)</li>
<li>Always open Android module in new window (#6646)</li>
<li>View record fields in the debugger (#6638)</li>
<li>Update CONTRIBUTING.md (#6637)</li>
<li>Update VM service protocol to 4.2 (#6636)</li>
<li>Fix debugger and BoundField.getName() (#6630)</li>
<li>Use setIsolatePauseMode (#6629)</li>
<li>Update VM service protocol to spec version 4.1 (#6628)</li>
</ul>
<h1>72.1</h1>
<ul>
<li>Eliminate more potentially nested service creations (#6626)</li>
<li>Create only a single service at a time (#6618)</li>
<li>Use reflection to find EmulatorSettings in both IDEs (#6625)</li>
<li>Check version of SDK for forming DevTools URL (#6614)</li>
<li>Open chrome devtools from JxBrowser (#6615)</li>
<li>Attempt to fix error email (#6605)</li>
<li>Fix debugger display of Uint8List elements (#6603)</li>
</ul>
<h1>72.0</h1>
<ul>
<li>Build 2023.1 (#6593)</li>
<li>Update settings to emphasize global options (#6592)-</li>
<li>Run update() on BGT (#6556)</li>
<li>Build AS canary with 2022.3 (#6583)</li>
<li>Catch UnsatisfiedLinkError for inspector (#6585)</li>
<li>Stop logging to improve completion times (#6584)</li>
<li>Allow auto pre-commit test to run prior to git commit (#6557)</li>
<li>Ignore disposed project in FlutterAppManager (#6554)</li>
<li>Ignore empty files that the Dart plugin says have errors (#6553)</li>
<li>Fix creating package project (#6542)</li>
</ul>
<h1>71.3</h1>
<ul>
<li>Fix the "Empty menu item text" problem</li>
</ul>
<h1>71.2</h1>
<ul>
<li>Always show device selector in IntelliJ 2022.3 due to: https://youtrack.jetbrains.com/issue/IDEA-308897/IntelliJ-2022.3-causes-custom-toolbar-widget-to-flash?s=IntelliJ-2022.3-causes-custom-toolbar-widget-to-flash</li>
<li>Re-enable embedded DevTools</li>
</ul>
<h1>71.1</h1>
<ul>
<li>Tweak device selector code</li>
<li>Add new project types plugin_ffi and empty (#6433)</li>
<li>Update device selector in background (#6429)</li>
<li>Catch exception if default project was disposed (#6401)</li>
<li>Fix test coverage for monorepo projects (#6391)</li>
<li>Permit attach in bazel context (#6389)</li>
<li>Change Container to Placeholder in live templates (#6390)</li>
<li>Move tests to 2022.2 (#6386)</li>
<li>Remove some deprecated API uses (#6383)</li>
</ul>
<h1>71.0</h1>
<ul>
<li>Remove the process listener after emulator termination (#6377)</li>
<li>Remove obsolete code from NPW (#6374)</li>
<li>Check for disposed project (#6371)</li>
<li>Remove platform availability channel warning (#6356)</li>
<li>Show values of TypedDataList in debugger (#6369)</li>
</ul>
<h1>70.0</h1>
<ul>
<li>Respect embedded emulator settings (#6279)</li>
<li>Update to JX Browser 7.27 and change linux mode (#6283)</li>
<li>Guard against JSON file problems (#6273)</li>
<li>Add missing null check (#6268)</li>
<li>Check for disposed editor (#6265)</li>
<li>Log bazel mapping differences from analyzer (#6263)</li>
<li>Update icon version (#6262)</li>
<li>Use new flutter.json file location (#6261)</li>
<li>Delete FlutterBazelSettingsNotificationProvider (#6256)</li>
</ul>
<h1>69.0</h1>
<ul>
<li>Build for canary 221 (#6248)</li>
<li>Revert "Delete code duplicated from Dart (#6113)" (#6246)</li>
<li>Update .iml for 221 (#6241)</li>
<li>Disable reader mode for Flutter plugins (#6238)</li>
<li>Update the build for 2022.2 EAP (#6224)</li>
<li>Avoid using canonical path for bazel (#6227)</li>
<li>Reduce error logging for not-useful errors (#6221)</li>
<li>Ensure disconnect even if import cancelled (#6220)</li>
<li>Improve import for monorepo projects (#6217)</li>
<li>Update Flutter commands on Build and Tools menu to run for all Flutter modules (#6215)</li>
<li>Change how Open in Xcode determines what to open (#6211)</li>
<li>Update survey announcement (#6210)</li>
</ul>
<h1>68.0</h1>
<ul>
<li>Use distributed icons for current SDK (#6208)</li>
<li>Update icons (#6207)</li>
<li>Enable stable platforms (#6202)</li>
<li>Use correct code to shut down process (#6201)</li>
<li>Use canonical paths to map symlinks(#6203)</li>
<li>Enable Windows platform for Flutter 2.10+ (#6195)</li>
<li>Escape spaces for VM mapping (#6194)</li>
<li>Stop relying only on .packages for pub banner (#6188)</li>
<li>Update icon previews to handle new format (#6186)</li>
<li>Fix typo in actions (#6180)</li>
<li>Send timing data as a GA event (#6179)</li>
<li>Check for project disposal before download (#6173)</li>
<li>Add default token permissions values + pin dependencies (#6152)</li>
<li>Show meaningful device names (#6158)</li>
<li>Specify dart bin path (#6153)</li>
<li>Update CONTRIBUTING.md (#6146)</li>
</ul>
<h1>67.1</h1>
<ul>
<li>Specify dart bin path (#6153)</li>
</ul>
<h1>67.0</h1>
<ul>
<li>Disable new analytics for M67 (#6142)</li>
<li>Stop running setup on the bots (#6141)</li>
<li>Update Dart plugin version (#6139)</li>
<li>Change setting on EDT (#6137)</li>
<li>Stop using a deprecated method (#6132)</li>
<li>Refactor Transport for easier logging while debugging (#6129)</li>
<li>Fix child lines when folding code (#6128)</li>
<li>Fix analytics (#6119)</li>
<li>Fix disposer bug (#6120)</li>
<li>Remove the 30-char limit for project names (#6121)</li>
<li>Use devtools script to launch bazel devtools (#6115)</li>
<li>Report flutter SDK version on startup (#6114)</li>
<li>Add dart devtools for starting server (#6112)</li>
<li>Delete code duplicated from Dart (#6113)</li>
<li>Update web URI mapping version (#6110)</li>
<li>Work around Kokoro Dart plugin problem (#6109)</li>
<li>Plugin tool improvements (#6106)</li>
<li>Fix layout issue (#6105)</li>
<li>Clean up edit.dart (#6104)</li>
<li>Add more analytics (#5985)</li>
<li>Update build for 2022.1 (#6102)</li>
<li>Enable Dart with multiple modules (#6099)</li>
<li>Look for a single module by name (#6098)</li>
<li>Add links to 3P plugin docs (#6090)</li>
<li>Fix config to load into 2021.3 (#6088)</li>
<li>Move third-party binaries into third_party (#6087)</li>
<li>This will allow us to assess the security posture of this repository. (#6047)</li>
<li>Update CONTRIBUTING.md (#6074)</li>
</ul>
]]>
</change-notes>
<!-- Everything following should be SmallIDE-friendly.-->
<!-- See: http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html -->
<actions>
<group id="Flutter.InspectorActions">
<action id="Flutter.JumpToTypeSource" class="io.flutter.inspector.JumpToTypeSourceAction"
description="Jump to Type Source"
text="Jump to Type Source">
<keyboard-shortcut keymap="$default" first-keystroke="shift F4"/>
</action>
<action id="Flutter.JumpToSource" class="io.flutter.inspector.JumpToSourceAction"
text="Jump to Source">
<keyboard-shortcut keymap="$default" first-keystroke="control DOWN"/>
</action>
</group>
<group id="Flutter.MainToolbarActions">
<action id="Flutter.DeviceSelector" class="io.flutter.actions.DeviceSelectorAction"
description="Flutter Device Selection"
icon="FlutterIcons.Phone"/>
<action id="Flutter.DeviceSelectorRefresher" class="io.flutter.actions.DeviceSelectorRefresherAction"
text="Refresh Device List"
description="Refresh device list" />
<add-to-group group-id="MainToolbarRight" />
<add-to-group anchor="before" group-id="ToolbarRunGroup" relative-to-action="RunConfiguration"/>
</group>
<group id="FlutterToolsActionGroup" class="io.flutter.actions.FlutterToolsActionGroup" popup="true"
text="Flutter" description="Flutter Tools" icon="FlutterIcons.Flutter">
<add-to-group group-id="ToolsMenu" anchor="last"/>
<action id="flutter.gettingStarted" class="io.flutter.actions.FlutterGettingStartedAction"
text="Getting Started"
description="View the online getting started documentation"/>
<separator/>
<action id="flutter.upgrade" class="io.flutter.actions.FlutterUpgradeAction"
text="Flutter Upgrade"
description="Run 'flutter upgrade'"/>
<action id="flutter.doctor" class="io.flutter.actions.FlutterDoctorAction"
text="Flutter Doctor"
description="Run 'flutter doctor'"/>
<separator/>
<action id="flutter.pub.get" class="io.flutter.actions.FlutterPackagesGetAction"
text="Flutter Pub Get"
description="Run 'flutter pub get'"/>
<action id="flutter.pub.upgrade" class="io.flutter.actions.FlutterPackagesUpgradeAction"
text="Flutter Pub Upgrade"
description="Run 'flutter pub upgrade'"/>
<separator/>
<action id="flutter.clean" class="io.flutter.actions.FlutterCleanAction"
text="Flutter Clean"
description="Run 'flutter clean'"/>
<separator/>
<action id="flutter.devtools.open" class="io.flutter.run.OpenDevToolsAction"
text="Open Flutter DevTools"
description="Open Flutter DevTools"/>
<separator/>
<action id="flutter.androidstudio.open" class="io.flutter.actions.OpenInAndroidStudioAction"
text="Open Android module in Android Studio"
description="Launch Android Studio to edit the Android module as a top-level project"/>
<action id="flutter.xcode.open" class="io.flutter.actions.OpenInXcodeAction"
text="Open iOS/macOS module in Xcode"
description="Launch Xcode to edit the iOS module as a top-level project"/>
<action id="flutter.appcode.open" class="io.flutter.actions.OpenInAppCodeAction"
text="Open iOS module in AppCode"
description="Launch AppCode to edit the iOS module as a top-level project"/>
<separator/>
<action id="flutter.submitFeedback" class="io.flutter.actions.FlutterSubmitFeedback"
text="Submit Feedback..."
description="Provide feedback for the Flutter plugin"/>
</group>
<!-- project explorer actions -->
<group id="FlutterPackagesExplorerActionGroup" class="io.flutter.actions.FlutterPackagesExplorerActionGroup">
<separator/>
<group text="Flutter" description="Flutter Tools" icon="FlutterIcons.Flutter" popup="true">
<separator/>
<reference ref="flutter.pub.get"/>
<reference ref="flutter.pub.upgrade"/>
<separator/>
<reference ref="flutter.androidstudio.open"/>
<reference ref="flutter.xcode.open"/>
<reference ref="flutter.appcode.open"/>
<separator/>
<reference ref="flutter.upgrade"/>
<reference ref="flutter.doctor"/>
</group>
<separator/>
<add-to-group group-id="ProjectViewPopupMenu" relative-to-action="AddToFavorites" anchor="before"/>
</group>
<group id="FlutterExternalIdeActionGroup" class="io.flutter.actions.FlutterExternalIdeActionGroup">
<separator/>
<group text="Flutter" description="Flutter Tools" icon="FlutterIcons.Flutter" popup="true">
<reference ref="flutter.androidstudio.open"/>
<reference ref="flutter.xcode.open"/>
<reference ref="flutter.appcode.open"/>
</group>
<separator/>
<add-to-group group-id="ProjectViewPopupMenu" relative-to-action="AddToFavorites" anchor="before"/>
</group>
<group id="FlutterBuildActionGroup" class="io.flutter.actions.FlutterBuildActionGroup">
<separator/>
<group text="Flutter" popup="true">
<action id="flutter.build.aar" text="Build AAR" description="Building a Flutter module for Android add-to-app"
class="io.flutter.actions.FlutterBuildActionGroup$AAR"/>
<action id="flutter.build.apk" text="Build APK" description="Building a Flutter app for general distribution"
class="io.flutter.actions.FlutterBuildActionGroup$APK"/>
<!--suppress PluginXmlCapitalization -->
<action id="flutter.build.aab" text="Build App Bundle" description="Building a Flutter app for Google Play Store distribution"
class="io.flutter.actions.FlutterBuildActionGroup$AppBundle"/>
<!--suppress PluginXmlCapitalization -->
<action id="flutter.build.ios" text="Build iOS" description="Building a Flutter app for Apple App Store distribution"
class="io.flutter.actions.FlutterBuildActionGroup$Ios"/>
<action id="flutter.build.web" text="Build Web" description="Building a Flutter app for web"
class="io.flutter.actions.FlutterBuildActionGroup$Web"/>
</group>
<add-to-group group-id="BuildMenu" anchor="first"/>
</group>
<!-- main toolbar run actions -->
<action id="AttachDebuggerAction"
class="io.flutter.actions.AttachDebuggerAction"
text="Flutter Attach"
description="Attach debugger to a Flutter process embedded in an Android app"
icon="FlutterIcons.AttachDebugger">
<add-to-group group-id="ToolbarRunGroup" anchor="after" relative-to-action="RunnerActions"/>
</action>
<action id="Flutter.Toolbar.ReloadAction" class="io.flutter.actions.ReloadFlutterAppRetarget"
description="Reload"
icon="FlutterIcons.HotReload">
<add-to-group group-id="ToolbarRunGroup" anchor="after" relative-to-action="RunnerActions"/>
<keyboard-shortcut keymap="$default" first-keystroke="ctrl BACK_SLASH"/>
</action>
<!-- run menu actions -->
<group id="Flutter.MenuActions.Run">
<separator/>
<reference ref="Flutter.Toolbar.ReloadAction"/>
<action id="Flutter.Toolbar.RestartAction" class="io.flutter.actions.RestartFlutterAppRetarget"
description="Restart"
icon="FlutterIcons.HotRestart">
<keyboard-shortcut keymap="$default" first-keystroke="ctrl shift BACK_SLASH"/>
</action>
<action id="Flutter.Toolbar.ReloadAllAction" class="io.flutter.actions.ReloadAllFlutterAppsRetarget"
description="Reload All Devices"
icon="FlutterIcons.HotReload">
<keyboard-shortcut keymap="$default" first-keystroke="ctrl alt BACK_SLASH"/>
</action>
<action id="Flutter.Toolbar.RestartAllAction" class="io.flutter.actions.RestartAllFlutterAppsRetarget"
description="Restart All Devices"
icon="FlutterIcons.HotRestart">
<keyboard-shortcut keymap="$default" first-keystroke="ctrl alt shift BACK_SLASH"/>
</action>
<separator/>
<action id="Flutter.Menu.RunProfileAction" class="io.flutter.actions.RunProfileFlutterApp"
description="Flutter Run Profile Mode"
icon="AllIcons.Actions.Execute">
</action>
<action id="Flutter.Menu.RunReleaseAction" class="io.flutter.actions.RunReleaseFlutterApp"
description="Flutter Run Release Mode"
icon="AllIcons.Actions.Execute">
</action>
<reference ref="AttachDebuggerAction"/>
<separator/>
<add-to-group group-id="RunMenu" anchor="after" relative-to-action="Stop"/>
</group>
<!-- refactoring menu -->
<action class="io.flutter.actions.ExtractWidgetAction" id="Flutter.ExtractWidget" text="Extract Flutter Widget...">
<add-to-group group-id="IntroduceActionsGroup" anchor="after" relative-to-action="ExtractMethod"/>
<keyboard-shortcut keymap="$default" first-keystroke="ctrl alt W"/>
</action>
<!-- help menu -->
<action class="io.flutter.actions.FlutterGettingStartedAction" id="Flutter.FlutterHelp" text="Flutter Plugin Help">
<add-to-group group-id="HelpMenu" anchor="after" relative-to-action="HelpTopics"/>
</action>
<action id="io.flutter.RestartDaemon" class="io.flutter.actions.RestartFlutterDaemonAction"
text="Restart Flutter Daemon" description="Restart Flutter Daemon" icon="FlutterIcons.Flutter">
</action>
<action id="io.flutter.OpenDevToolsAction" class="io.flutter.run.OpenDevToolsAction"
text="Open Flutter DevTools" description="Open Flutter DevTools" icon="FlutterIcons.Dart_16">
</action>
<!-- action
id="DeveloperServices.FlutterNewsAssistant"
class="io.flutter.actions.OpenFlutterNewsSidePanelAction"
icon="/icons/flutter.png"
text="What's New in Flutter">
<add-to-group group-id="HelpMenu" />
</action -->
</actions>
<applicationListeners>
<listener class="io.flutter.font.ProjectOpenListener"
topic="com.intellij.openapi.project.ProjectManagerListener"/>
</applicationListeners>
<projectListeners>
<listener class="io.flutter.view.FlutterViewFactory$FlutterViewListener" topic="com.intellij.openapi.wm.ex.ToolWindowManagerListener"/>
<listener class="io.flutter.performance.FlutterPerformanceViewFactory$FlutterPerformanceViewListener"
topic="com.intellij.openapi.wm.ex.ToolWindowManagerListener"/>
<listener class="io.flutter.preview.PreviewViewFactory$PreviewViewListener"
topic="com.intellij.openapi.wm.ex.ToolWindowManagerListener"/>
</projectListeners>
<extensionPoints>
<extensionPoint name="gradleSyncProvider" interface="io.flutter.android.GradleSyncProvider"/>
<extensionPoint name="colorPickerProvider" interface="io.flutter.editor.ColorPickerProvider"/>
</extensionPoints>
<extensions defaultExtensionNs="io.flutter">
<gradleSyncProvider implementation="io.flutter.android.IntellijGradleSyncProvider" order="last"/>
<colorPickerProvider implementation="io.flutter.editor.IntellijColorPickerProvider" order="last"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<postStartupActivity implementation="io.flutter.ProjectOpenActivity"/>
<postStartupActivity implementation="io.flutter.FlutterInitializer"/>
<projectService serviceInterface="io.flutter.run.daemon.DeviceService"
serviceImplementation="io.flutter.run.daemon.DeviceService"/>
<projectService serviceInterface="io.flutter.run.daemon.DevToolsService"
serviceImplementation="io.flutter.run.daemon.DevToolsService"/>
<projectService serviceInterface="io.flutter.dart.FlutterDartAnalysisServer"
serviceImplementation="io.flutter.dart.FlutterDartAnalysisServer"/>
<projectService serviceInterface="io.flutter.bazel.WorkspaceCache"
serviceImplementation="io.flutter.bazel.WorkspaceCache"/>
<projectService serviceImplementation="io.flutter.pub.PubRootCache"/>
<projectService serviceImplementation="io.flutter.analytics.FlutterAnalysisServerListener"/>
<configurationType implementation="io.flutter.run.FlutterRunConfigurationType"/>
<runConfigurationProducer implementation="io.flutter.run.FlutterRunConfigurationProducer"/>
<programRunner implementation="io.flutter.run.FlutterRunner"/>
<configurationType implementation="io.flutter.run.test.FlutterTestConfigType"/>
<runConfigurationProducer implementation="io.flutter.run.test.FlutterTestConfigProducer"/>
<programRunner implementation="io.flutter.run.test.FlutterTestRunner"/>
<runLineMarkerContributor language="Dart" implementationClass="io.flutter.run.test.FlutterTestLineMarkerContributor"/>
<configurationType implementation="io.flutter.run.bazel.FlutterBazelRunConfigurationType"/>
<programRunner implementation="io.flutter.run.bazel.BazelRunner"/>
<configurationType implementation="io.flutter.run.bazelTest.FlutterBazelTestConfigurationType"/>
<runConfigurationProducer implementation="io.flutter.run.bazelTest.BazelTestConfigProducer"/>
<runConfigurationProducer implementation="io.flutter.run.bazelTest.BazelWatchTestConfigProducer"/>
<programRunner implementation="io.flutter.run.bazelTest.BazelTestRunner"/>
<runLineMarkerContributor language="Dart" implementationClass="io.flutter.run.bazelTest.FlutterBazelTestLineMarkerContributor"/>
<defaultLiveTemplatesProvider implementation="io.flutter.template.FlutterLiveTemplatesProvider"/>
<liveTemplateContext implementation="io.flutter.template.DartToplevelTemplateContextType"/>
<!-- IDEA only -->
<moduleBuilder builderClass="io.flutter.module.FlutterModuleBuilder"/>
<projectService serviceImplementation="io.flutter.sdk.FlutterSdkManager"/>
<projectService serviceImplementation="io.flutter.sdk.AndroidEmulatorManager"/>
<applicationService serviceInterface="io.flutter.settings.FlutterSettings"
serviceImplementation="io.flutter.settings.FlutterSettings"
overrides="false"/>
<applicationService serviceImplementation="io.flutter.jxbrowser.EmbeddedBrowserEngine" overrides="false" />
<applicationService serviceImplementation="io.flutter.font.FontPreviewProcessor"/>
<console.folding implementation="io.flutter.console.FlutterConsoleFolding" id="1"/>
<console.folding implementation="io.flutter.console.FlutterConsoleExceptionFolding" order="after 1"/>
<console.folding implementation="io.flutter.logging.FlutterConsoleLogFolding" order="last"/>
<projectConfigurable groupId="language" instance="io.flutter.sdk.FlutterSettingsConfigurable"
id="flutter.settings" key="flutter.title" bundle="io.flutter.FlutterBundle" nonDefaultProject="true"/>
<colorProvider implementation="io.flutter.editor.FlutterColorProvider"/>
<codeInsight.lineMarkerProvider language="Dart" implementationClass="io.flutter.editor.FlutterIconLineMarkerProvider"/>
<errorHandler implementation="io.flutter.FlutterErrorReportSubmitter"/>
<toolWindow id="Flutter Outline" anchor="right" icon="FlutterIcons.Flutter_13"
factoryClass="io.flutter.preview.PreviewViewFactory"/>
<projectService serviceImplementation="io.flutter.preview.PreviewView" overrides="false"/>
<toolWindow id="Flutter Inspector" anchor="right" icon="FlutterIcons.Flutter_13"
factoryClass="io.flutter.view.FlutterViewFactory"/>
<projectService serviceImplementation="io.flutter.view.FlutterView" overrides="false"/>
<toolWindow id="Flutter Performance" anchor="right" icon="FlutterIcons.Flutter_13"
factoryClass="io.flutter.performance.FlutterPerformanceViewFactory"/>
<projectService serviceImplementation="io.flutter.performance.FlutterPerformanceView" overrides="false"/>
<projectOpenProcessor id="flutter" implementation="io.flutter.project.FlutterProjectOpenProcessor" order="first"/>
<localInspection bundle="io.flutter.FlutterBundle" key="outdated.dependencies.inspection.name"
groupName="Flutter" enabledByDefault="true" level="WARNING" language="Dart"
implementationClass="io.flutter.inspections.FlutterDependencyInspection"/>
<editorNotificationProvider implementation="io.flutter.editor.FlutterPubspecNotificationProvider"/>
<editorNotificationProvider implementation="io.flutter.inspections.SdkConfigurationNotificationProvider"/>
<editorNotificationProvider implementation="io.flutter.editor.NativeEditorNotificationProvider"/>
<editorNotificationProvider implementation="io.flutter.samples.FlutterSampleNotificationProvider"/>
<projectService serviceInterface="io.flutter.run.FlutterReloadManager"
serviceImplementation="io.flutter.run.FlutterReloadManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.FlutterSaveActionsManager"
serviceImplementation="io.flutter.editor.FlutterSaveActionsManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.run.FlutterAppManager"
serviceImplementation="io.flutter.run.FlutterAppManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.perf.FlutterWidgetPerfManager"
serviceImplementation="io.flutter.perf.FlutterWidgetPerfManager"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.ActiveEditorsOutlineService"
serviceImplementation="io.flutter.editor.ActiveEditorsOutlineService"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.EditorMouseEventService"
serviceImplementation="io.flutter.editor.EditorMouseEventService"
overrides="false"/>
<projectService serviceInterface="io.flutter.editor.EditorPositionService"
serviceImplementation="io.flutter.editor.EditorPositionService"
overrides="false"/>
<projectService serviceInterface="io.flutter.inspector.InspectorGroupManagerService"
serviceImplementation="io.flutter.inspector.InspectorGroupManagerService"
overrides="false"/>
<iconProvider implementation="io.flutter.project.FlutterIconProvider" order="first"/>
<library.type implementation="io.flutter.sdk.FlutterPluginLibraryType"/>
<projectStructureDetector implementation="io.flutter.project.FlutterProjectStructureDetector"/>
<additionalTextAttributes scheme="Default" file="colorSchemes/FlutterLogColorSchemeDefault.xml"/>
<additionalTextAttributes scheme="Default" file="colorSchemes/FlutterCodeColorSchemeDefault.xml"/>
<search.optionContributor implementation="io.flutter.sdk.FlutterSearchableOptionContributor"/>
<readerModeMatcher implementation="io.flutter.editor.FlutterReaderModeMatcher"/>
<projectService serviceInterface="io.flutter.editor.WidgetIndentsHighlightingPassFactory"
serviceImplementation="io.flutter.editor.WidgetIndentsHighlightingPassFactory"
overrides="false"/>
<highlightingPassFactory implementation="io.flutter.editor.WidgetIndentsHighlightingPassFactoryRegistrar"/>
<projectService serviceInterface="io.flutter.jxbrowser.EmbeddedJxBrowser"
serviceImplementation="io.flutter.jxbrowser.EmbeddedJxBrowser"
overrides="false"/>
<projectService serviceInterface="io.flutter.view.EmbeddedJcefBrowser"
serviceImplementation="io.flutter.view.EmbeddedJcefBrowser"
overrides="false"/>
<notificationGroup displayType="STICKY_BALLOON" id="deeplink"/>
</extensions>
<!-- Dart Plugin extensions -->
<extensions defaultExtensionNs="Dart">
<completionExtension implementation="io.flutter.editor.FlutterCompletionContributor" order="last"/>
<completionTimerExtension implementation="io.flutter.analytics.DartCompletionTimerListener"/>
</extensions>
</idea-plugin>
| flutter-intellij/resources/META-INF/plugin.xml/0 | {
"file_path": "flutter-intellij/resources/META-INF/plugin.xml",
"repo_id": "flutter-intellij",
"token_count": 12241
} | 488 |
// 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:io';
import 'package:plugin_tool/plugin.dart' as plugin;
/// Run from IntelliJ with a run configuration that has the working directory
/// set to the project root directory.
void main(List<String> arguments) async {
exit(await plugin.main(arguments));
}
| flutter-intellij/tool/plugin/bin/main.dart/0 | {
"file_path": "flutter-intellij/tool/plugin/bin/main.dart",
"repo_id": "flutter-intellij",
"token_count": 119
} | 489 |
61aeJQ9laGfEFF_Vlc_u0MCkqB6xb2hAYHRBxKH-Uw4C
| flutter/bin/internal/canvaskit.version/0 | {
"file_path": "flutter/bin/internal/canvaskit.version",
"repo_id": "flutter",
"token_count": 35
} | 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.
# ---------------------------------- NOTE ---------------------------------- #
#
# Please keep the logic in this file consistent with the logic in the
# `update_dart_sdk.sh` script in the same directory to ensure that Flutter
# continues to work across all platforms!
#
# -------------------------------------------------------------------------- #
$ErrorActionPreference = "Stop"
$progName = Split-Path -parent $MyInvocation.MyCommand.Definition
$flutterRoot = (Get-Item $progName).parent.parent.FullName
$cachePath = "$flutterRoot\bin\cache"
$dartSdkPath = "$cachePath\dart-sdk"
$dartSdkLicense = "$cachePath\LICENSE.dart_sdk_archive.md"
$engineStamp = "$cachePath\engine-dart-sdk.stamp"
$engineVersion = (Get-Content "$flutterRoot\bin\internal\engine.version")
$engineRealm = (Get-Content "$flutterRoot\bin\internal\engine.realm")
$oldDartSdkPrefix = "dart-sdk.old"
# Make sure that PowerShell has expected version.
$psMajorVersionRequired = 5
$psMajorVersionLocal = $PSVersionTable.PSVersion.Major
if ($psMajorVersionLocal -lt $psMajorVersionRequired) {
Write-Host "Flutter requires PowerShell $psMajorVersionRequired.0 or newer."
Write-Host "See https://flutter.dev/docs/get-started/install/windows for more."
Write-Host "Current version is $psMajorVersionLocal."
# Use exit code 2 to signal that shared.bat should exit immediately instead of retrying.
exit 2
}
if ((Test-Path $engineStamp) -and ($engineVersion -eq (Get-Content $engineStamp))) {
return
}
$dartSdkBaseUrl = $Env:FLUTTER_STORAGE_BASE_URL
if (-not $dartSdkBaseUrl) {
$dartSdkBaseUrl = "https://storage.googleapis.com"
}
if ($engineRealm) {
$dartSdkBaseUrl = "$dartSdkBaseUrl/$engineRealm"
}
# It's important to use the native Dart SDK as the default target architecture
# for Flutter Windows builds depend on the Dart executable's architecture.
$dartZipNameX64 = "dart-sdk-windows-x64.zip"
$dartZipNameArm64 = "dart-sdk-windows-arm64.zip"
$dartZipName = $dartZipNameX64
if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64") {
$dartSdkArm64Url = "$dartSdkBaseUrl/flutter_infra_release/flutter/$engineVersion/$dartZipNameArm64"
Try {
Invoke-WebRequest -Uri $dartSdkArm64Url -UseBasicParsing -Method Head | Out-Null
$dartZipName = $dartZipNameArm64
}
Catch {
Write-Host "The current channel's Dart SDK does not support Windows Arm64, falling back to Windows x64..."
}
}
$dartSdkUrl = "$dartSdkBaseUrl/flutter_infra_release/flutter/$engineVersion/$dartZipName"
if ((Test-Path $dartSdkPath) -or (Test-Path $dartSdkLicense)) {
# Move old SDK to a new location instead of deleting it in case it is still in use (e.g. by IntelliJ).
$oldDartSdkSuffix = 1
while (Test-Path "$cachePath\$oldDartSdkPrefix$oldDartSdkSuffix") { $oldDartSdkSuffix++ }
if (Test-Path $dartSdkPath) {
Rename-Item $dartSdkPath "$oldDartSdkPrefix$oldDartSdkSuffix"
}
if (Test-Path $dartSdkLicense) {
Rename-Item $dartSdkLicense "$oldDartSdkPrefix$oldDartSdkSuffix.LICENSE.md"
}
}
New-Item $dartSdkPath -force -type directory | Out-Null
$dartSdkZip = "$cachePath\$dartZipName"
Try {
Import-Module BitsTransfer
$ProgressPreference = 'SilentlyContinue'
Start-BitsTransfer -Source $dartSdkUrl -Destination $dartSdkZip -ErrorAction Stop
}
Catch {
Write-Host "Downloading the Dart SDK using the BITS service failed, retrying with WebRequest..."
# Invoke-WebRequest is very slow when the progress bar is visible - a 28
# second download can become a 33 minute download. Disable it with
# $ProgressPreference and then restore the original value afterwards.
# https://github.com/flutter/flutter/issues/37789
$OriginalProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $dartSdkUrl -OutFile $dartSdkZip
$ProgressPreference = $OriginalProgressPreference
}
If (Get-Command 7z -errorAction SilentlyContinue) {
Write-Host "Expanding downloaded archive with 7z..."
# The built-in unzippers are painfully slow. Use 7-Zip, if available.
& 7z x $dartSdkZip "-o$cachePath" -bd | Out-Null
} ElseIf (Get-Command 7za -errorAction SilentlyContinue) {
Write-Host "Expanding downloaded archive with 7za..."
# Use 7-Zip's standalone version 7za.exe, if available.
& 7za x $dartSdkZip "-o$cachePath" -bd | Out-Null
} ElseIf (Get-Command Microsoft.PowerShell.Archive\Expand-Archive -errorAction SilentlyContinue) {
Write-Host "Expanding downloaded archive with PowerShell..."
# Use PowerShell's built-in unzipper, if available (requires PowerShell 5+).
$global:ProgressPreference='SilentlyContinue'
Microsoft.PowerShell.Archive\Expand-Archive $dartSdkZip -DestinationPath $cachePath
} Else {
Write-Host "Expanding downloaded archive with Windows..."
# As last resort: fall back to the Windows GUI.
$shell = New-Object -com shell.application
$zip = $shell.NameSpace($dartSdkZip)
foreach($item in $zip.items()) {
$shell.Namespace($cachePath).copyhere($item)
}
}
Remove-Item $dartSdkZip
$engineVersion | Out-File $engineStamp -Encoding ASCII
# Try to delete all old SDKs and license files.
Get-ChildItem -Path $cachePath | Where {$_.BaseName.StartsWith($oldDartSdkPrefix)} | Remove-Item -Recurse -ErrorAction SilentlyContinue
| flutter/bin/internal/update_dart_sdk.ps1/0 | {
"file_path": "flutter/bin/internal/update_dart_sdk.ps1",
"repo_id": "flutter",
"token_count": 1881
} | 491 |
#include "Generated.xcconfig"
| flutter/dev/a11y_assessments/ios/Flutter/Release.xcconfig/0 | {
"file_path": "flutter/dev/a11y_assessments/ios/Flutter/Release.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/material.dart';
import 'use_cases.dart';
class TextFieldPasswordUseCase extends UseCase {
@override
String get name => 'TextField password';
@override
String get route => '/text-field-password';
@override
Widget build(BuildContext context) => const _MainWidget();
}
class _MainWidget extends StatelessWidget {
const _MainWidget();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('TextField password'),
),
body: ListView(
children: const <Widget>[
TextField(
key: Key('enabled password'),
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
),
obscureText: true,
),
TextField(
key: Key('disabled password'),
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
),
enabled: false,
obscureText: true,
),
],
),
);
}
}
| flutter/dev/a11y_assessments/lib/use_cases/text_field_password.dart/0 | {
"file_path": "flutter/dev/a11y_assessments/lib/use_cases/text_field_password.dart",
"repo_id": "flutter",
"token_count": 572
} | 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:a11y_assessments/use_cases/text_field_password.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'test_utils.dart';
void main() {
testWidgets('text field password can run', (WidgetTester tester) async {
await pumpsUseCase(tester, TextFieldPasswordUseCase());
expect(find.byType(TextField), findsExactly(2));
// Test the enabled password
{
final Finder finder = find.byKey(const Key('enabled password'));
await tester.tap(finder);
await tester.pumpAndSettle();
await tester.enterText(finder, 'abc');
await tester.pumpAndSettle();
expect(find.text('abc'), findsOneWidget);
}
// Test the disabled password
{
final Finder finder = find.byKey(const Key('disabled password'));
final TextField passwordField = tester.widget<TextField>(finder);
expect(passwordField.enabled, isFalse);
}
});
}
| flutter/dev/a11y_assessments/test/text_field_password_test.dart/0 | {
"file_path": "flutter/dev/a11y_assessments/test/text_field_password_test.dart",
"repo_id": "flutter",
"token_count": 384
} | 494 |
This directory is used by //flutter/dev/bots/test.dart to verify that
`flutter test` actually correctly fails when a test fails.
| flutter/dev/automated_tests/test_smoke_test/README.md/0 | {
"file_path": "flutter/dev/automated_tests/test_smoke_test/README.md",
"repo_id": "flutter",
"token_count": 35
} | 495 |
// 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 _MultiplyPainter extends CustomPainter {
_MultiplyPainter(this._color);
final Color _color;
@override
void paint(Canvas canvas, Size size) {
const int xDenominator = 2;
const int yDenominator = 10;
final double width = size.width / xDenominator;
final double height = size.height / yDenominator;
for (int y = 0; y < yDenominator; y++) {
for (int x = 0; x < xDenominator; x++) {
final Rect rect = Offset(x * width, y * height) & Size(width, height);
final Paint basePaint = Paint()
..color = Color.fromARGB(
(((x + 1) * width) / size.width * 255.0).floor(),
(((y + 1) * height) / size.height * 255.0).floor(),
255,
127);
canvas.drawRect(rect, basePaint);
final Paint multiplyPaint = Paint()
..color = _color
..blendMode = BlendMode.multiply;
canvas.drawRect(rect, multiplyPaint);
}
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
class AnimatedAdvancedBlend extends StatefulWidget {
const AnimatedAdvancedBlend({super.key});
@override
State<AnimatedAdvancedBlend> createState() => _AnimatedAdvancedBlendState();
}
class _AnimatedAdvancedBlendState extends State<AnimatedAdvancedBlend> with SingleTickerProviderStateMixin {
late final AnimationController controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 5000));
late final Animation<double> animation = controller.drive(Tween<double>(begin: 0.0, end: 1.0));
Color _color = const Color.fromARGB(255, 255, 0, 255);
@override
void initState() {
super.initState();
controller.repeat();
animation.addListener(() {
setState(() {
_color = Color.fromARGB((animation.value * 255).floor(), 255, 0, 255);
});
});
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: CustomPaint(
painter: _MultiplyPainter(_color),
child: Container(),
),
));
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/animated_advanced_blend.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/animated_advanced_blend.dart",
"repo_id": "flutter",
"token_count": 902
} | 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:ui' as ui;
import 'package:flutter/material.dart';
Future<ui.Image> loadImage(String asset) async {
final ui.ImmutableBuffer buffer = await ui.ImmutableBuffer.fromAsset(asset);
final ui.Codec codec = await PaintingBinding.instance.instantiateImageCodecWithSize(buffer);
final ui.FrameInfo frameInfo = await codec.getNextFrame();
return frameInfo.image;
}
class DrawVerticesPage extends StatefulWidget {
const DrawVerticesPage({super.key});
@override
State<DrawVerticesPage> createState() => _DrawVerticesPageState();
}
class _DrawVerticesPageState extends State<DrawVerticesPage> with SingleTickerProviderStateMixin {
late final AnimationController controller;
double tick = 0.0;
ui.Image? image;
@override
void initState() {
super.initState();
loadImage('packages/flutter_gallery_assets/food/butternut_squash_soup.png').then((ui.Image pending) {
setState(() {
image = pending;
});
});
controller = AnimationController(vsync: this, duration: const Duration(hours: 1));
controller.addListener(() {
setState(() {
tick += 1;
});
});
controller.forward(from: 0);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (image == null) {
return const Placeholder();
}
return CustomPaint(
size: const Size(500, 500),
painter: VerticesPainter(tick, image!),
child: Container(),
);
}
}
class VerticesPainter extends CustomPainter {
VerticesPainter(this.tick, this.image);
final double tick;
final ui.Image image;
@override
void paint(Canvas canvas, Size size) {
canvas.translate(0, tick);
final ui.Vertices vertices = ui.Vertices(
VertexMode.triangles,
const <Offset>[
Offset.zero,
Offset(0, 250),
Offset(250, 0),
Offset(0, 250),
Offset(250, 0),
Offset(250, 250)
],
textureCoordinates: <Offset>[
Offset.zero,
Offset(0, image.height.toDouble()),
Offset(image.width.toDouble(), 0),
Offset(0, image.height.toDouble()),
Offset(image.width.toDouble(), 0),
Offset(image.width.toDouble(), image.height.toDouble())
],
colors: <Color>[
Colors.red,
Colors.blue,
Colors.green,
Colors.red,
Colors.blue,
Colors.green,
]
);
canvas.drawVertices(vertices, BlendMode.plus, Paint()..shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Matrix4.identity().storage));
canvas.translate(250, 0);
canvas.drawVertices(vertices, BlendMode.plus, Paint()..shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Matrix4.identity().storage));
canvas.translate(0, 250);
canvas.drawVertices(vertices, BlendMode.plus, Paint()..shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Matrix4.identity().storage));
canvas.translate(-250, 0);
canvas.drawVertices(vertices, BlendMode.plus, Paint()..shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Matrix4.identity().storage));
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/draw_vertices.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/draw_vertices.dart",
"repo_id": "flutter",
"token_count": 1310
} | 497 |
// 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 SimpleAnimationPage extends StatelessWidget {
const SimpleAnimationPage({super.key});
@override
Widget build(BuildContext context) {
return const Center(child: LinearProgressIndicator());
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/simple_animation.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/simple_animation.dart",
"repo_id": "flutter",
"token_count": 113
} | 498 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'material3.dart';
import 'recorder.dart';
/// Measures how expensive it is to construct the material 3 components screen.
class BenchMaterial3Components extends WidgetBuildRecorder {
BenchMaterial3Components() : super(name: benchmarkName);
static const String benchmarkName = 'bench_material3_components';
@override
Widget createWidget() {
return const TwoColumnMaterial3Components();
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_material_3.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_material_3.dart",
"repo_id": "flutter",
"token_count": 168
} | 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.
import 'dart:math' as math;
import 'dart:ui';
// Used to randomize data.
//
// Using constant seed for reproducibility.
final math.Random _random = math.Random(0);
/// Random words used by benchmarks that contain text.
final List<String> lipsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing '
'elit. Vivamus ut ligula a neque mattis posuere. Sed suscipit lobortis '
'sodales. Morbi sed neque molestie, hendrerit odio ac, aliquam velit. '
'Curabitur non quam sit amet nibh sollicitudin ultrices. Fusce '
'ullamcorper bibendum commodo. In et feugiat nisl. Aenean vulputate in '
'odio vestibulum ultricies. Nunc dolor libero, hendrerit eu urna sit '
'amet, pretium iaculis nulla. Ut porttitor nisl et leo iaculis, vel '
'fringilla odio pulvinar. Ut eget ligula id odio auctor egestas nec a '
'nisl. Aliquam luctus dolor et magna posuere mattis. '
'Suspendisse fringilla nisl et massa congue, eget '
'imperdiet lectus porta. Vestibulum sed dui sed dui porta imperdiet ut in risus. '
'Fusce diam purus, faucibus id accumsan sit amet, semper a sem. Sed aliquam '
'lacus eget libero ultricies, quis hendrerit tortor posuere. Pellentesque '
'sagittis eu est in maximus. Proin auctor fringilla dolor in hendrerit. Nam '
'pulvinar rhoncus tellus. Nullam vel mauris semper, volutpat tellus at, sagittis '
'lectus. Donec vitae nibh mauris. Morbi posuere sem id eros tristique tempus. '
'Vivamus lacinia sapien neque, eu semper purus gravida ut.'.split(' ');
/// Generates strings and builds pre-laid out paragraphs to be used by
/// benchmarks.
List<Paragraph> generateLaidOutParagraphs({
required int paragraphCount,
required int minWordCountPerParagraph,
required int maxWordCountPerParagraph,
required double widthConstraint,
required Color color,
}) {
final List<Paragraph> strings = <Paragraph>[];
int wordPointer = 0; // points to the next word in lipsum to extract
for (int i = 0; i < paragraphCount; i++) {
final int wordCount = minWordCountPerParagraph +
_random.nextInt(maxWordCountPerParagraph - minWordCountPerParagraph + 1);
final List<String> string = <String>[];
for (int j = 0; j < wordCount; j++) {
string.add(lipsum[wordPointer]);
wordPointer = (wordPointer + 1) % lipsum.length;
}
final ParagraphBuilder builder =
ParagraphBuilder(ParagraphStyle(fontFamily: 'sans-serif'))
..pushStyle(TextStyle(color: color, fontSize: 18.0))
..addText(string.join(' '))
..pop();
final Paragraph paragraph = builder.build();
// Fill half the screen.
paragraph.layout(ParagraphConstraints(width: widthConstraint));
strings.add(paragraph);
}
return strings;
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/test_data.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/test_data.dart",
"repo_id": "flutter",
"token_count": 1025
} | 500 |
// 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 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:macrobenchmarks/src/simple_scroll.dart';
void main() {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets(
'Frame Counter and Input Delay for benchmarkLive',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Scaffold(body: SimpleScroll())));
await tester.pumpAndSettle();
final Offset location = tester.getCenter(find.byType(ListView));
int frameCount = 0;
void frameCounter(Duration elapsed) {
frameCount += 1;
}
tester.binding.addPersistentFrameCallback(frameCounter);
const int timeInSecond = 1;
const Duration totalTime = Duration(seconds: timeInSecond);
const int moveEventNumber = timeInSecond * 120; // 120Hz
const Offset movePerRun = Offset(0.0, -200.0 / moveEventNumber);
final List<PointerEventRecord> records = <PointerEventRecord>[
PointerEventRecord(Duration.zero, <PointerEvent>[
PointerAddedEvent(
position: location,
),
PointerDownEvent(
position: location,
pointer: 1,
),
]),
...<PointerEventRecord>[
for (int t=0; t < moveEventNumber; t++)
PointerEventRecord(totalTime * (t / moveEventNumber), <PointerEvent>[
PointerMoveEvent(
timeStamp: totalTime * (t / moveEventNumber),
position: location + movePerRun * t.toDouble(),
pointer: 1,
delta: movePerRun,
),
]),
],
PointerEventRecord(totalTime, <PointerEvent>[
PointerUpEvent(
// Deviate a little from integer number of frames to reduce flakiness
timeStamp: totalTime - const Duration(milliseconds: 1),
position: location + movePerRun * moveEventNumber.toDouble(),
pointer: 1,
),
]),
];
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive;
List<Duration> delays = await tester.handlePointerEventRecord(records);
await tester.pumpAndSettle();
binding.reportData = <String, dynamic>{
'benchmarkLive': _summarizeResult(frameCount, delays),
};
await tester.idle();
await tester.binding.delayed(const Duration(milliseconds: 250));
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
frameCount = 0;
delays = await tester.handlePointerEventRecord(records);
await tester.pumpAndSettle();
binding.reportData!['fullyLive'] = _summarizeResult(frameCount, delays);
await tester.idle();
},
);
}
Map<String, dynamic> _summarizeResult(
final int frameCount,
final List<Duration> delays,
) {
assert(delays.length > 1);
final List<int> delayedInMicro = delays.map<int>(
(Duration delay) => delay.inMicroseconds,
).toList();
final List<int> delayedInMicroSorted = List<int>.from(delayedInMicro)..sort();
final int index90th = (delayedInMicroSorted.length * 0.90).round();
final int percentile90th = delayedInMicroSorted[index90th];
final int sum = delayedInMicroSorted.reduce((int a, int b) => a + b);
final double averageDelay = sum.toDouble() / delayedInMicroSorted.length;
return <String, dynamic>{
'frame_count': frameCount,
'average_delay_millis': averageDelay / 1E3,
'90th_percentile_delay_millis': percentile90th / 1E3,
if (kDebugMode)
'delaysInMicro': delayedInMicro,
};
}
| flutter/dev/benchmarks/macrobenchmarks/test/frame_policy.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/test/frame_policy.dart",
"repo_id": "flutter",
"token_count": 1543
} | 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:flutter/material.dart';
class ButtonMatrixApp extends StatefulWidget {
const ButtonMatrixApp({super.key});
@override
ButtonMatrixAppState createState() => ButtonMatrixAppState();
}
class ButtonMatrixAppState extends State<ButtonMatrixApp> {
int count = 1;
int increment = 1;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Count: $count'),
actions: <Widget>[
TextButton(
onPressed: () => setState(() { count += increment; }),
child: Text('Add $increment'),
),
],
),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.filled(
3,
Column(
children: List<Widget>.filled(
10,
TextButton(
child: const Text('Faster'),
onPressed: () => setState(() { increment += 1; }),
),
),
),
),
),
),
);
}
}
void main() {
runApp(const ButtonMatrixApp());
}
| flutter/dev/benchmarks/microbenchmarks/lib/gestures/apps/button_matrix_app.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/gestures/apps/button_matrix_app.dart",
"repo_id": "flutter",
"token_count": 616
} | 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.
enum StockMode { optimistic, pessimistic }
enum BackupMode { enabled, disabled }
class StockConfiguration {
StockConfiguration({
required this.stockMode,
required this.backupMode,
required this.debugShowGrid,
required this.debugShowSizes,
required this.debugShowBaselines,
required this.debugShowLayers,
required this.debugShowPointers,
required this.debugShowRainbow,
required this.showPerformanceOverlay,
required this.showSemanticsDebugger,
});
final StockMode stockMode;
final BackupMode backupMode;
final bool debugShowGrid;
final bool debugShowSizes;
final bool debugShowBaselines;
final bool debugShowLayers;
final bool debugShowPointers;
final bool debugShowRainbow;
final bool showPerformanceOverlay;
final bool showSemanticsDebugger;
StockConfiguration copyWith({
StockMode? stockMode,
BackupMode? backupMode,
bool? debugShowGrid,
bool? debugShowSizes,
bool? debugShowBaselines,
bool? debugShowLayers,
bool? debugShowPointers,
bool? debugShowRainbow,
bool? showPerformanceOverlay,
bool? showSemanticsDebugger,
}) {
return StockConfiguration(
stockMode: stockMode ?? this.stockMode,
backupMode: backupMode ?? this.backupMode,
debugShowGrid: debugShowGrid ?? this.debugShowGrid,
debugShowSizes: debugShowSizes ?? this.debugShowSizes,
debugShowBaselines: debugShowBaselines ?? this.debugShowBaselines,
debugShowLayers: debugShowLayers ?? this.debugShowLayers,
debugShowPointers: debugShowPointers ?? this.debugShowPointers,
debugShowRainbow: debugShowRainbow ?? this.debugShowRainbow,
showPerformanceOverlay: showPerformanceOverlay ?? this.showPerformanceOverlay,
showSemanticsDebugger: showSemanticsDebugger ?? this.showSemanticsDebugger,
);
}
}
| flutter/dev/benchmarks/test_apps/stocks/lib/stock_types.dart/0 | {
"file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/stock_types.dart",
"repo_id": "flutter",
"token_count": 635
} | 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.
// To run this, from the root of the Flutter repository:
// bin/cache/dart-sdk/bin/dart --enable-asserts dev/bots/check_code_sample_links.dart
import 'dart:io';
import 'package:args/args.dart';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:path/path.dart' as path;
import 'utils.dart';
final String _scriptLocation = path.fromUri(Platform.script);
final String _flutterRoot = path.dirname(path.dirname(path.dirname(_scriptLocation)));
final String _exampleDirectoryPath = path.join(_flutterRoot, 'examples', 'api');
final String _packageDirectoryPath = path.join(_flutterRoot, 'packages');
final String _dartUIDirectoryPath = path.join(_flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib');
final List<String> _knownUnlinkedExamples = <String>[
// These are template files that aren't expected to be linked.
'examples/api/lib/sample_templates/cupertino.0.dart',
'examples/api/lib/sample_templates/widgets.0.dart',
'examples/api/lib/sample_templates/material.0.dart',
];
void main(List<String> args) {
final ArgParser argParser = ArgParser();
argParser.addFlag(
'help',
negatable: false,
help: 'Print help for this command.',
);
argParser.addOption(
'examples',
valueHelp: 'path',
defaultsTo: _exampleDirectoryPath,
help: 'A location where the API doc examples are found.',
);
argParser.addOption(
'packages',
valueHelp: 'path',
defaultsTo: _packageDirectoryPath,
help: 'A location where the source code that should link the API doc examples is found.',
);
argParser.addOption(
'dart-ui',
valueHelp: 'path',
defaultsTo: _dartUIDirectoryPath,
help: 'A location where the source code that should link the API doc examples is found.',
);
argParser.addOption(
'flutter-root',
valueHelp: 'path',
defaultsTo: _flutterRoot,
help: 'The path to the root of the Flutter repo.',
);
final ArgResults parsedArgs;
void usage() {
print('dart --enable-asserts ${path.basename(_scriptLocation)} [options]');
print(argParser.usage);
}
try {
parsedArgs = argParser.parse(args);
} on FormatException catch (e) {
print(e.message);
usage();
exit(1);
}
if (parsedArgs['help'] as bool) {
usage();
exit(0);
}
const FileSystem filesystem = LocalFileSystem();
final Directory examples = filesystem.directory(parsedArgs['examples']! as String);
final Directory packages = filesystem.directory(parsedArgs['packages']! as String);
final Directory dartUIPath = filesystem.directory(parsedArgs['dart-ui']! as String);
final Directory flutterRoot = filesystem.directory(parsedArgs['flutter-root']! as String);
final SampleChecker checker = SampleChecker(
examples: examples,
packages: packages,
dartUIPath: dartUIPath,
flutterRoot: flutterRoot,
);
if (!checker.checkCodeSamples()) {
reportErrorsAndExit('Some errors were found in the API docs code samples.');
}
reportSuccessAndExit('All examples are linked and have tests.');
}
class LinkInfo {
const LinkInfo(this.link, this.file, this.line);
final String link;
final File file;
final int line;
@override
String toString() {
return '${file.path}:$line: $link';
}
}
class SampleChecker {
SampleChecker({
required this.examples,
required this.packages,
required this.dartUIPath,
required this.flutterRoot,
this.filesystem = const LocalFileSystem(),
});
final Directory examples;
final Directory packages;
final Directory dartUIPath;
final Directory flutterRoot;
final FileSystem filesystem;
bool checkCodeSamples() {
filesystem.currentDirectory = flutterRoot;
// Get a list of all the filenames in the source directory that end in "[0-9]+.dart".
final List<File> exampleFilenames = getExampleFilenames(examples);
// Get a list of all the example link paths that appear in the source files.
final (Set<String> exampleLinks, Set<LinkInfo> malformedLinks) = getExampleLinks(packages);
// Also add in any that might be found in the dart:ui directory.
final (Set<String> uiExampleLinks, Set<LinkInfo> uiMalformedLinks) = getExampleLinks(dartUIPath);
exampleLinks.addAll(uiExampleLinks);
malformedLinks.addAll(uiMalformedLinks);
// Get a list of the filenames that were not found in the source files.
final List<String> missingFilenames = checkForMissingLinks(exampleFilenames, exampleLinks);
// Get a list of any tests that are missing, as well as any that used to be
// missing, but have been implemented.
final (List<File> missingTests, List<File> noLongerMissing) = checkForMissingTests(exampleFilenames);
// Remove any that we know are exceptions (examples that aren't expected to be
// linked into any source files). These are typically template files used to
// generate new examples.
missingFilenames.removeWhere((String file) => _knownUnlinkedExamples.contains(file));
if (missingFilenames.isEmpty && missingTests.isEmpty && noLongerMissing.isEmpty && malformedLinks.isEmpty) {
return true;
}
if (noLongerMissing.isNotEmpty) {
final StringBuffer buffer = StringBuffer('The following tests have been implemented! Huzzah!:\n');
for (final File name in noLongerMissing) {
buffer.writeln(' ${getRelativePath(name)}');
}
buffer.writeln('However, they now need to be removed from the _knownMissingTests');
buffer.write('list in the script $_scriptLocation.');
foundError(buffer.toString().split('\n'));
}
if (missingTests.isNotEmpty) {
final StringBuffer buffer = StringBuffer('The following example test files are missing:\n');
for (final File name in missingTests) {
buffer.writeln(' ${getRelativePath(name)}');
}
foundError(buffer.toString().trimRight().split('\n'));
}
if (missingFilenames.isNotEmpty) {
final StringBuffer buffer =
StringBuffer('The following examples are not linked from any source file API doc comments:\n');
for (final String name in missingFilenames) {
buffer.writeln(' $name');
}
buffer.write('Either link them to a source file API doc comment, or remove them.');
foundError(buffer.toString().split('\n'));
}
if (malformedLinks.isNotEmpty) {
final StringBuffer buffer =
StringBuffer('The following malformed links were found in API doc comments:\n');
for (final LinkInfo link in malformedLinks) {
buffer.writeln(' $link');
}
buffer.write(
'Correct the formatting of these links so that they match the exact pattern:\n'
r" r'\*\* See code in (?<path>.+) \*\*'"
);
foundError(buffer.toString().split('\n'));
}
return false;
}
String getRelativePath(File file, [Directory? root]) {
root ??= flutterRoot;
return path.relative(file.absolute.path, from: root.absolute.path);
}
List<File> getFiles(Directory directory, [Pattern? filenamePattern]) {
final List<File> filenames = directory
.listSync(recursive: true)
.map((FileSystemEntity entity) {
if (entity is File) {
return entity;
} else {
return null;
}
})
.where((File? filename) =>
filename != null && (filenamePattern == null || filename.absolute.path.contains(filenamePattern)))
.map<File>((File? s) => s!)
.toList();
return filenames;
}
List<File> getExampleFilenames(Directory directory) {
return getFiles(
directory.childDirectory('lib'),
RegExp(r'\d+\.dart$'),
);
}
(Set<String>, Set<LinkInfo>) getExampleLinks(Directory searchDirectory) {
final List<File> files = getFiles(searchDirectory, RegExp(r'\.dart$'));
final Set<String> searchStrings = <String>{};
final Set<LinkInfo> malformedStrings = <LinkInfo>{};
final RegExp validExampleRe = RegExp(r'\*\* See code in (?<path>.+) \*\*');
// Looks for some common broken versions of example links. This looks for
// something that is at minimum "///*seecode<something>*" to indicate that it
// looks like an example link. It should be narrowed if we start getting false
// positives.
final RegExp malformedLinkRe = RegExp(r'^(?<malformed>\s*///\s*\*\*?\s*[sS][eE][eE]\s*[Cc][Oo][Dd][Ee].+\*\*?)');
for (final File file in files) {
final String contents = file.readAsStringSync();
final List<String> lines = contents.split('\n');
int count = 0;
for (final String line in lines) {
count += 1;
final RegExpMatch? validMatch = validExampleRe.firstMatch(line);
if (validMatch != null) {
searchStrings.add(validMatch.namedGroup('path')!);
}
final RegExpMatch? malformedMatch = malformedLinkRe.firstMatch(line);
// It's only malformed if it doesn't match the valid RegExp.
if (malformedMatch != null && validMatch == null) {
malformedStrings.add(LinkInfo(malformedMatch.namedGroup('malformed')!, file, count));
}
}
}
return (searchStrings, malformedStrings);
}
List<String> checkForMissingLinks(List<File> exampleFilenames, Set<String> searchStrings) {
final List<String> missingFilenames = <String>[];
for (final File example in exampleFilenames) {
final String relativePath = getRelativePath(example);
if (!searchStrings.contains(relativePath)) {
missingFilenames.add(relativePath);
}
}
return missingFilenames;
}
String getTestNameForExample(File example, Directory examples) {
final String testPath = path.dirname(
path.join(
examples.absolute.path,
'test',
getRelativePath(example, examples.childDirectory('lib')),
),
);
return '${path.join(testPath, path.basenameWithoutExtension(example.path))}_test.dart';
}
(List<File>, List<File>) checkForMissingTests(List<File> exampleFilenames) {
final List<File> missingTests = <File>[];
final List<File> noLongerMissingTests = <File>[];
for (final File example in exampleFilenames) {
final File testFile = filesystem.file(getTestNameForExample(example, examples));
final String name = path.relative(testFile.absolute.path, from: flutterRoot.absolute.path);
if (!testFile.existsSync()) {
missingTests.add(testFile);
} else if (_knownMissingTests.contains(name.replaceAll(r'\', '/'))) {
noLongerMissingTests.add(testFile);
}
}
// Skip any that we know are missing.
missingTests.removeWhere(
(File test) {
final String name = path.relative(test.absolute.path, from: flutterRoot.absolute.path).replaceAll(r'\', '/');
return _knownMissingTests.contains(name);
},
);
return (missingTests, noLongerMissingTests);
}
}
// These tests are known to be missing. They should all eventually be
// implemented, but until they are we allow them, so that we can catch any new
// examples that are added without tests.
//
// TODO(gspencergoog): implement the missing tests.
// See https://github.com/flutter/flutter/issues/130459
final Set<String> _knownMissingTests = <String>{
'examples/api/test/material/bottom_app_bar/bottom_app_bar.2_test.dart',
'examples/api/test/material/bottom_app_bar/bottom_app_bar.1_test.dart',
'examples/api/test/material/theme/theme_extension.1_test.dart',
'examples/api/test/material/material_state/material_state_border_side.0_test.dart',
'examples/api/test/material/material_state/material_state_mouse_cursor.0_test.dart',
'examples/api/test/material/material_state/material_state_outlined_border.0_test.dart',
'examples/api/test/material/material_state/material_state_property.0_test.dart',
'examples/api/test/material/selectable_region/selectable_region.0_test.dart',
'examples/api/test/material/text_field/text_field.2_test.dart',
'examples/api/test/material/text_field/text_field.1_test.dart',
'examples/api/test/material/button_style/button_style.0_test.dart',
'examples/api/test/material/range_slider/range_slider.0_test.dart',
'examples/api/test/material/selection_container/selection_container_disabled.0_test.dart',
'examples/api/test/material/selection_container/selection_container.0_test.dart',
'examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart',
'examples/api/test/material/platform_menu_bar/platform_menu_bar.0_test.dart',
'examples/api/test/material/menu_anchor/menu_anchor.2_test.dart',
'examples/api/test/material/stepper/stepper.controls_builder.0_test.dart',
'examples/api/test/material/flexible_space_bar/flexible_space_bar.0_test.dart',
'examples/api/test/material/floating_action_button_location/standard_fab_location.0_test.dart',
'examples/api/test/material/chip/deletable_chip_attributes.on_deleted.0_test.dart',
'examples/api/test/material/snack_bar/snack_bar.2_test.dart',
'examples/api/test/material/snack_bar/snack_bar.1_test.dart',
'examples/api/test/material/icon_button/icon_button.3_test.dart',
'examples/api/test/material/expansion_panel/expansion_panel_list.expansion_panel_list_radio.0_test.dart',
'examples/api/test/material/input_decorator/input_decoration.1_test.dart',
'examples/api/test/material/input_decorator/input_decoration.prefix_icon_constraints.0_test.dart',
'examples/api/test/material/input_decorator/input_decoration.material_state.0_test.dart',
'examples/api/test/material/input_decorator/input_decoration.2_test.dart',
'examples/api/test/material/input_decorator/input_decoration.0_test.dart',
'examples/api/test/material/input_decorator/input_decoration.label.0_test.dart',
'examples/api/test/material/input_decorator/input_decoration.suffix_icon_constraints.0_test.dart',
'examples/api/test/material/input_decorator/input_decoration.3_test.dart',
'examples/api/test/material/input_decorator/input_decoration.material_state.1_test.dart',
'examples/api/test/material/text_form_field/text_form_field.1_test.dart',
'examples/api/test/material/scrollbar/scrollbar.1_test.dart',
'examples/api/test/material/dropdown_menu/dropdown_menu.1_test.dart',
'examples/api/test/material/radio/radio.toggleable.0_test.dart',
'examples/api/test/material/search_anchor/search_anchor.0_test.dart',
'examples/api/test/material/search_anchor/search_anchor.1_test.dart',
'examples/api/test/material/search_anchor/search_anchor.2_test.dart',
'examples/api/test/material/about/about_list_tile.0_test.dart',
'examples/api/test/material/tab_controller/tab_controller.1_test.dart',
'examples/api/test/material/selection_area/selection_area.0_test.dart',
'examples/api/test/material/scaffold/scaffold.end_drawer.0_test.dart',
'examples/api/test/material/scaffold/scaffold.drawer.0_test.dart',
'examples/api/test/material/scaffold/scaffold.1_test.dart',
'examples/api/test/material/scaffold/scaffold.of.0_test.dart',
'examples/api/test/material/scaffold/scaffold_messenger.of.0_test.dart',
'examples/api/test/material/scaffold/scaffold_messenger.0_test.dart',
'examples/api/test/material/scaffold/scaffold.0_test.dart',
'examples/api/test/material/scaffold/scaffold_state.show_bottom_sheet.0_test.dart',
'examples/api/test/material/scaffold/scaffold.2_test.dart',
'examples/api/test/material/scaffold/scaffold_messenger_state.show_material_banner.0_test.dart',
'examples/api/test/material/scaffold/scaffold.of.1_test.dart',
'examples/api/test/material/scaffold/scaffold_messenger.of.1_test.dart',
'examples/api/test/material/scaffold/scaffold_messenger_state.show_snack_bar.0_test.dart',
'examples/api/test/material/segmented_button/segmented_button.0_test.dart',
'examples/api/test/material/app_bar/sliver_app_bar.2_test.dart',
'examples/api/test/material/app_bar/sliver_app_bar.3_test.dart',
'examples/api/test/material/banner/material_banner.1_test.dart',
'examples/api/test/material/banner/material_banner.0_test.dart',
'examples/api/test/material/navigation_rail/navigation_rail.extended_animation.0_test.dart',
'examples/api/test/rendering/growth_direction/growth_direction.0_test.dart',
'examples/api/test/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.0_test.dart',
'examples/api/test/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.1_test.dart',
'examples/api/test/rendering/scroll_direction/scroll_direction.0_test.dart',
'examples/api/test/painting/axis_direction/axis_direction.0_test.dart',
'examples/api/test/painting/linear_border/linear_border.0_test.dart',
'examples/api/test/painting/gradient/linear_gradient.0_test.dart',
'examples/api/test/painting/star_border/star_border.0_test.dart',
'examples/api/test/painting/borders/border_side.stroke_align.0_test.dart',
'examples/api/test/widgets/autocomplete/raw_autocomplete.focus_node.0_test.dart',
'examples/api/test/widgets/autocomplete/raw_autocomplete.2_test.dart',
'examples/api/test/widgets/autocomplete/raw_autocomplete.1_test.dart',
'examples/api/test/widgets/autocomplete/raw_autocomplete.0_test.dart',
'examples/api/test/widgets/navigator/navigator.restorable_push_and_remove_until.0_test.dart',
'examples/api/test/widgets/navigator/navigator.0_test.dart',
'examples/api/test/widgets/navigator/navigator.restorable_push.0_test.dart',
'examples/api/test/widgets/navigator/navigator_state.restorable_push_replacement.0_test.dart',
'examples/api/test/widgets/navigator/navigator_state.restorable_push_and_remove_until.0_test.dart',
'examples/api/test/widgets/navigator/navigator.restorable_push_replacement.0_test.dart',
'examples/api/test/widgets/navigator/restorable_route_future.0_test.dart',
'examples/api/test/widgets/navigator/navigator_state.restorable_push.0_test.dart',
'examples/api/test/widgets/focus_manager/focus_node.unfocus.0_test.dart',
'examples/api/test/widgets/focus_manager/focus_node.0_test.dart',
'examples/api/test/widgets/framework/build_owner.0_test.dart',
'examples/api/test/widgets/framework/error_widget.0_test.dart',
'examples/api/test/widgets/inherited_theme/inherited_theme.0_test.dart',
'examples/api/test/widgets/sliver/decorated_sliver.0_test.dart',
'examples/api/test/widgets/autofill/autofill_group.0_test.dart',
'examples/api/test/widgets/drag_target/draggable.0_test.dart',
'examples/api/test/widgets/shared_app_data/shared_app_data.1_test.dart',
'examples/api/test/widgets/shared_app_data/shared_app_data.0_test.dart',
'examples/api/test/widgets/nested_scroll_view/nested_scroll_view_state.0_test.dart',
'examples/api/test/widgets/nested_scroll_view/nested_scroll_view.2_test.dart',
'examples/api/test/widgets/nested_scroll_view/nested_scroll_view.1_test.dart',
'examples/api/test/widgets/nested_scroll_view/nested_scroll_view.0_test.dart',
'examples/api/test/widgets/scroll_position/scroll_metrics_notification.0_test.dart',
'examples/api/test/widgets/media_query/media_query_data.system_gesture_insets.0_test.dart',
'examples/api/test/widgets/async/stream_builder.0_test.dart',
'examples/api/test/widgets/async/future_builder.0_test.dart',
'examples/api/test/widgets/restoration_properties/restorable_value.0_test.dart',
'examples/api/test/widgets/animated_size/animated_size.0_test.dart',
'examples/api/test/widgets/table/table.0_test.dart',
'examples/api/test/widgets/animated_switcher/animated_switcher.0_test.dart',
'examples/api/test/widgets/transitions/relative_positioned_transition.0_test.dart',
'examples/api/test/widgets/transitions/positioned_transition.0_test.dart',
'examples/api/test/widgets/transitions/sliver_fade_transition.0_test.dart',
'examples/api/test/widgets/transitions/align_transition.0_test.dart',
'examples/api/test/widgets/transitions/fade_transition.0_test.dart',
'examples/api/test/widgets/transitions/animated_builder.0_test.dart',
'examples/api/test/widgets/transitions/rotation_transition.0_test.dart',
'examples/api/test/widgets/transitions/animated_widget.0_test.dart',
'examples/api/test/widgets/transitions/slide_transition.0_test.dart',
'examples/api/test/widgets/transitions/listenable_builder.2_test.dart',
'examples/api/test/widgets/transitions/scale_transition.0_test.dart',
'examples/api/test/widgets/transitions/default_text_style_transition.0_test.dart',
'examples/api/test/widgets/transitions/decorated_box_transition.0_test.dart',
'examples/api/test/widgets/transitions/size_transition.0_test.dart',
'examples/api/test/widgets/animated_list/animated_list.0_test.dart',
'examples/api/test/widgets/focus_traversal/focus_traversal_group.0_test.dart',
'examples/api/test/widgets/focus_traversal/ordered_traversal_policy.0_test.dart',
'examples/api/test/widgets/image/image.error_builder.0_test.dart',
'examples/api/test/widgets/image/image.frame_builder.0_test.dart',
'examples/api/test/widgets/image/image.loading_builder.0_test.dart',
'examples/api/test/widgets/shortcuts/logical_key_set.0_test.dart',
'examples/api/test/widgets/shortcuts/shortcuts.0_test.dart',
'examples/api/test/widgets/shortcuts/single_activator.single_activator.0_test.dart',
'examples/api/test/widgets/shortcuts/shortcuts.1_test.dart',
'examples/api/test/widgets/shortcuts/character_activator.0_test.dart',
'examples/api/test/widgets/shortcuts/callback_shortcuts.0_test.dart',
'examples/api/test/widgets/page_storage/page_storage.0_test.dart',
'examples/api/test/widgets/scrollbar/raw_scrollbar.1_test.dart',
'examples/api/test/widgets/scrollbar/raw_scrollbar.2_test.dart',
'examples/api/test/widgets/scrollbar/raw_scrollbar.desktop.0_test.dart',
'examples/api/test/widgets/scrollbar/raw_scrollbar.shape.0_test.dart',
'examples/api/test/widgets/scrollbar/raw_scrollbar.0_test.dart',
'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.2_test.dart',
'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.1_test.dart',
'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.3_test.dart',
'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.0_test.dart',
'examples/api/test/widgets/interactive_viewer/interactive_viewer.constrained.0_test.dart',
'examples/api/test/widgets/interactive_viewer/interactive_viewer.transformation_controller.0_test.dart',
'examples/api/test/widgets/interactive_viewer/interactive_viewer.0_test.dart',
'examples/api/test/widgets/notification_listener/notification.0_test.dart',
'examples/api/test/widgets/gesture_detector/gesture_detector.1_test.dart',
'examples/api/test/widgets/gesture_detector/gesture_detector.0_test.dart',
'examples/api/test/widgets/editable_text/text_editing_controller.0_test.dart',
'examples/api/test/widgets/editable_text/editable_text.on_changed.0_test.dart',
'examples/api/test/widgets/undo_history/undo_history_controller.0_test.dart',
'examples/api/test/widgets/overscroll_indicator/glowing_overscroll_indicator.1_test.dart',
'examples/api/test/widgets/overscroll_indicator/glowing_overscroll_indicator.0_test.dart',
'examples/api/test/widgets/tween_animation_builder/tween_animation_builder.0_test.dart',
'examples/api/test/widgets/single_child_scroll_view/single_child_scroll_view.1_test.dart',
'examples/api/test/widgets/single_child_scroll_view/single_child_scroll_view.0_test.dart',
'examples/api/test/widgets/overflow_bar/overflow_bar.0_test.dart',
'examples/api/test/widgets/restoration/restoration_mixin.0_test.dart',
'examples/api/test/widgets/actions/actions.0_test.dart',
'examples/api/test/widgets/actions/action_listener.0_test.dart',
'examples/api/test/widgets/actions/focusable_action_detector.0_test.dart',
'examples/api/test/widgets/color_filter/color_filtered.0_test.dart',
'examples/api/test/widgets/focus_scope/focus.2_test.dart',
'examples/api/test/widgets/focus_scope/focus.0_test.dart',
'examples/api/test/widgets/focus_scope/focus.1_test.dart',
'examples/api/test/widgets/focus_scope/focus_scope.0_test.dart',
'examples/api/test/widgets/implicit_animations/animated_fractionally_sized_box.0_test.dart',
'examples/api/test/widgets/implicit_animations/animated_align.0_test.dart',
'examples/api/test/widgets/implicit_animations/animated_positioned.0_test.dart',
'examples/api/test/widgets/implicit_animations/animated_padding.0_test.dart',
'examples/api/test/widgets/implicit_animations/sliver_animated_opacity.0_test.dart',
'examples/api/test/widgets/implicit_animations/animated_container.0_test.dart',
'examples/api/test/widgets/dismissible/dismissible.0_test.dart',
'examples/api/test/widgets/scroll_view/custom_scroll_view.1_test.dart',
'examples/api/test/widgets/preferred_size/preferred_size.0_test.dart',
'examples/api/test/widgets/inherited_notifier/inherited_notifier.0_test.dart',
'examples/api/test/animation/curves/curve2_d.0_test.dart',
'examples/api/test/gestures/pointer_signal_resolver/pointer_signal_resolver.0_test.dart',
};
| flutter/dev/bots/check_code_samples.dart/0 | {
"file_path": "flutter/dev/bots/check_code_samples.dart",
"repo_id": "flutter",
"token_count": 9489
} | 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:io' hide Platform;
import 'package:file/file.dart' as fs;
import 'package:file/memory.dart';
import 'package:path/path.dart' as path;
import 'package:process/process.dart';
import '../test.dart';
import 'common.dart';
/// Fails a test if the exit code of `result` is not the expected value. This
/// is favored over `expect(result.exitCode, expectedExitCode)` because this
/// will include the process result's stdio in the failure message.
void expectExitCode(ProcessResult result, int expectedExitCode) {
if (result.exitCode != expectedExitCode) {
fail(
'Process ${result.pid} exited with the wrong exit code.\n'
'\n'
'EXPECTED: exit code $expectedExitCode\n'
'ACTUAL: exit code ${result.exitCode}\n'
'\n'
'STDOUT:\n'
'${result.stdout}\n'
'STDERR:\n'
'${result.stderr}'
);
}
}
void main() {
group('verifyVersion()', () {
late MemoryFileSystem fileSystem;
setUp(() {
fileSystem = MemoryFileSystem.test();
});
test('passes for valid version strings', () async {
const List<String> valid_versions = <String>[
'1.2.3',
'12.34.56',
'1.2.3.pre.1',
'1.2.3-4.5.pre',
'1.2.3-5.0.pre.12',
];
for (final String version in valid_versions) {
final File file = fileSystem.file('version');
file.writeAsStringSync(version);
expect(
await verifyVersion(file),
isNull,
reason: '$version is valid but verifyVersionFile said it was bad',
);
}
});
test('fails for invalid version strings', () async {
const List<String> invalid_versions = <String>[
'1.2.3.4',
'1.2.3.',
'1.2.pre.1',
'1.2.3-pre.1',
'1.2.3-pre.1+hotfix.1',
' 1.2.3',
'1.2.3-hotfix.1',
];
for (final String version in invalid_versions) {
final File file = fileSystem.file('version');
file.writeAsStringSync(version);
expect(
await verifyVersion(file),
'The version logic generated an invalid version string: "$version".',
reason: '$version is invalid but verifyVersionFile said it was fine',
);
}
});
});
group('flutter/packages version', () {
final MemoryFileSystem memoryFileSystem = MemoryFileSystem();
final fs.File packagesVersionFile = memoryFileSystem.file(path.join('bin','internal','flutter_packages.version'));
const String kSampleHash = '592b5b27431689336fa4c721a099eedf787aeb56';
setUpAll(() {
packagesVersionFile.createSync(recursive: true);
});
test('commit hash', () async {
packagesVersionFile.writeAsStringSync(kSampleHash);
final String actualHash = await getFlutterPackagesVersion(fileSystem: memoryFileSystem, packagesVersionFile: packagesVersionFile.path);
expect(actualHash, kSampleHash);
});
test('commit hash with newlines', () async {
packagesVersionFile.writeAsStringSync('\n$kSampleHash\n');
final String actualHash = await getFlutterPackagesVersion(fileSystem: memoryFileSystem, packagesVersionFile: packagesVersionFile.path);
expect(actualHash, kSampleHash);
});
});
group('test.dart script', () {
const ProcessManager processManager = LocalProcessManager();
Future<ProcessResult> runScript([
Map<String, String>? environment,
List<String> otherArgs = const <String>[],
]) async {
final String dart = path.absolute(
path.join('..', '..', 'bin', 'cache', 'dart-sdk', 'bin', 'dart'),
);
final ProcessResult scriptProcess = processManager.runSync(<String>[
dart,
'test.dart',
...otherArgs,
], environment: environment);
return scriptProcess;
}
test('subshards tests correctly', () async {
// When updating this test, try to pick shard numbers that ensure we're checking
// that unequal test distributions don't miss tests.
ProcessResult result = await runScript(
<String, String>{'SHARD': kTestHarnessShardName, 'SUBSHARD': '1_3'},
);
expectExitCode(result, 0);
expect(result.stdout, contains('Selecting subshard 1 of 3 (tests 1-3 of 9)'));
result = await runScript(
<String, String>{'SHARD': kTestHarnessShardName, 'SUBSHARD': '3_3'},
);
expectExitCode(result, 0);
expect(result.stdout, contains('Selecting subshard 3 of 3 (tests 7-9 of 9)'));
});
test('exits with code 1 when SUBSHARD index greater than total', () async {
final ProcessResult result = await runScript(
<String, String>{'SHARD': kTestHarnessShardName, 'SUBSHARD': '100_99'},
);
expectExitCode(result, 1);
expect(result.stdout, contains('Invalid subshard name'));
});
test('exits with code 255 when invalid SUBSHARD name', () async {
final ProcessResult result = await runScript(
<String, String>{'SHARD': kTestHarnessShardName, 'SUBSHARD': 'invalid_name'},
);
expectExitCode(result, 255);
expect(result.stdout, contains('Invalid subshard name'));
});
});
}
| flutter/dev/bots/test/test_test.dart/0 | {
"file_path": "flutter/dev/bots/test/test_test.dart",
"repo_id": "flutter",
"token_count": 2080
} | 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 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:platform/platform.dart';
import './globals.dart';
import './repository.dart';
import './state.dart';
import './stdio.dart';
const String kYesFlag = 'yes';
const String kStateOption = 'state-file';
/// Command to clean up persistent state file.
///
/// If the release was not completed, this command will abort the release.
class CleanCommand extends Command<void> {
CleanCommand({
required this.checkouts,
}) : platform = checkouts.platform,
fileSystem = checkouts.fileSystem,
stdio = checkouts.stdio {
final String defaultPath = defaultStateFilePath(platform);
argParser.addFlag(
kYesFlag,
help: 'Override confirmation checks.',
);
argParser.addOption(
kStateOption,
defaultsTo: defaultPath,
help: 'Path to persistent state file. Defaults to $defaultPath',
);
}
final Checkouts checkouts;
final FileSystem fileSystem;
final Platform platform;
final Stdio stdio;
@override
String get name => 'clean';
@override
String get description => 'Cleanup persistent state file. '
'This will abort a work in progress release.';
@override
Future<void> run() {
final ArgResults argumentResults = argResults!;
final File stateFile = checkouts.fileSystem.file(argumentResults[kStateOption]);
if (!stateFile.existsSync()) {
throw ConductorException('No persistent state file found at ${stateFile.path}!');
}
if (!(argumentResults[kYesFlag] as bool)) {
stdio.printStatus(
'Are you sure you want to clean up the persistent state file at\n'
'${stateFile.path} (y/n)?',
);
final String response = stdio.readLineSync();
// Only proceed if the first character of stdin is 'y' or 'Y'
if (response.isEmpty || response[0].toLowerCase() != 'y') {
stdio.printStatus('Aborting clean operation.');
}
}
stdio.printStatus('Deleting persistent state file ${stateFile.path}...');
final CleanContext cleanContext = CleanContext(
stateFile: stateFile,
);
return cleanContext.run();
}
}
/// Context for cleaning up persistent state file.
///
/// This is a frontend-agnostic implementation.
class CleanContext {
CleanContext({
required this.stateFile,
});
final File stateFile;
Future<void> run() {
return stateFile.delete();
}
}
| flutter/dev/conductor/core/lib/src/clean.dart/0 | {
"file_path": "flutter/dev/conductor/core/lib/src/clean.dart",
"repo_id": "flutter",
"token_count": 881
} | 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:convert' show JsonEncoder, jsonDecode;
import 'package:file/file.dart' show File;
import 'package:platform/platform.dart';
import './globals.dart' as globals;
import './proto/conductor_state.pb.dart' as pb;
import './proto/conductor_state.pbenum.dart' show ReleasePhase;
const String kStateFileName = '.flutter_conductor_state.json';
const String betaPostReleaseMsg = """
'Ensure the following post release steps are complete:',
'\t 1. Post announcement to discord and press the publish button',
'\t\t Discord: ${globals.discordReleaseChannel}',
'\t 2. Post announcement flutter release hotline chat room',
'\t\t Chatroom: ${globals.flutterReleaseHotline}',
""";
const String stablePostReleaseMsg = """
'Ensure the following post release steps are complete:',
'\t 1. Update hotfix to stable wiki following documentation best practices',
'\t\t Wiki link: ${globals.hotfixToStableWiki}',
'\t\t Best practices: ${globals.hotfixDocumentationBestPractices}',
'\t 2. Post announcement to flutter-announce group',
'\t\t Flutter Announce: ${globals.flutterAnnounceGroup}',
'\t 3. Post announcement to discord and press the publish button',
'\t\t Discord: ${globals.discordReleaseChannel}',
'\t 4. Post announcement flutter release hotline chat room',
'\t\t Chatroom: ${globals.flutterReleaseHotline}',
""";
// The helper functions in `state.dart` wrap the code-generated dart files in
// `lib/src/proto/`. The most interesting of these functions is:
// * `pb.ConductorState readStateFromFile(File)` - uses the code generated
// `.mergeFromProto3Json()` method to deserialize the JSON content from the
// config file into a Dart instance of the `ConductorState` class.
// * `void writeStateFromFile(File, pb.ConductorState, List<String>)`
// - similarly calls the `.toProto3Json()` method to serialize a
// * `ConductorState` instance to a JSON string which is then written to disk.
// `String phaseInstructions(pb.ConductorState state)` - returns instructions
// for what the user is supposed to do next based on `state.currentPhase`.
// * `String presentState(pb.ConductorState state)` - pretty print the state file.
// This is a little easier to read than the raw JSON.
String luciConsoleLink(String channel, String groupName) {
assert(
globals.kReleaseChannels.contains(channel),
'channel "$channel" not recognized',
);
assert(
<String>['flutter', 'engine', 'packaging'].contains(groupName),
'group named $groupName not recognized',
);
final String consoleName =
channel == 'master' ? groupName : '${channel}_$groupName';
if (groupName == 'packaging') {
return 'https://luci-milo.appspot.com/p/dart-internal/g/flutter_packaging/console';
}
return 'https://ci.chromium.org/p/flutter/g/$consoleName/console';
}
String defaultStateFilePath(Platform platform) {
final String? home = platform.environment['HOME'];
if (home == null) {
throw globals.ConductorException(
r'Environment variable $HOME must be set!');
}
return <String>[
home,
kStateFileName,
].join(platform.pathSeparator);
}
String presentState(pb.ConductorState state) {
final StringBuffer buffer = StringBuffer();
buffer.writeln('Conductor version: ${state.conductorVersion}');
buffer.writeln('Release channel: ${state.releaseChannel}');
buffer.writeln('Release version: ${state.releaseVersion}');
buffer.writeln();
buffer.writeln(
'Release started at: ${DateTime.fromMillisecondsSinceEpoch(state.createdDate.toInt())}');
buffer.writeln(
'Last updated at: ${DateTime.fromMillisecondsSinceEpoch(state.lastUpdatedDate.toInt())}');
buffer.writeln();
buffer.writeln('Engine Repo');
buffer.writeln('\tCandidate branch: ${state.engine.candidateBranch}');
buffer.writeln('\tStarting git HEAD: ${state.engine.startingGitHead}');
buffer.writeln('\tCurrent git HEAD: ${state.engine.currentGitHead}');
buffer.writeln('\tPath to checkout: ${state.engine.checkoutPath}');
buffer.writeln(
'\tPost-submit LUCI dashboard: ${luciConsoleLink(state.releaseChannel, 'engine')}');
if (state.engine.cherrypicks.isNotEmpty) {
buffer.writeln('${state.engine.cherrypicks.length} Engine Cherrypicks:');
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) {
buffer.writeln('\t${cherrypick.trunkRevision} - ${cherrypick.state}');
}
} else {
buffer.writeln('0 Engine cherrypicks.');
}
if (state.engine.dartRevision.isNotEmpty) {
buffer.writeln('New Dart SDK revision: ${state.engine.dartRevision}');
}
buffer.writeln('Framework Repo');
buffer.writeln('\tCandidate branch: ${state.framework.candidateBranch}');
buffer.writeln('\tStarting git HEAD: ${state.framework.startingGitHead}');
buffer.writeln('\tCurrent git HEAD: ${state.framework.currentGitHead}');
buffer.writeln('\tPath to checkout: ${state.framework.checkoutPath}');
buffer.writeln(
'\tPost-submit LUCI dashboard: ${luciConsoleLink(state.releaseChannel, 'flutter')}');
if (state.framework.cherrypicks.isNotEmpty) {
buffer.writeln(
'${state.framework.cherrypicks.length} Framework Cherrypicks:');
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks) {
buffer.writeln('\t${cherrypick.trunkRevision} - ${cherrypick.state}');
}
} else {
buffer.writeln('0 Framework cherrypicks.');
}
buffer.writeln();
if (state.currentPhase == ReleasePhase.VERIFY_RELEASE) {
buffer.writeln(
'${state.releaseChannel} release ${state.releaseVersion} has been published and verified.\n',
);
return buffer.toString();
}
buffer.writeln('The current phase is:');
buffer.writeln(presentPhases(state.currentPhase));
buffer.writeln(phaseInstructions(state));
buffer.writeln();
buffer.writeln('Issue `conductor next` when you are ready to proceed.');
return buffer.toString();
}
String presentPhases(ReleasePhase currentPhase) {
final StringBuffer buffer = StringBuffer();
bool phaseCompleted = true;
for (final ReleasePhase phase in ReleasePhase.values) {
if (phase == currentPhase) {
// This phase will execute the next time `conductor next` is run.
buffer.writeln('> ${phase.name} (current)');
phaseCompleted = false;
} else if (phaseCompleted) {
// This phase was already completed.
buffer.writeln('✓ ${phase.name}');
} else {
// This phase has not been completed yet.
buffer.writeln(' ${phase.name}');
}
}
return buffer.toString();
}
String phaseInstructions(pb.ConductorState state) {
switch (state.currentPhase) {
case ReleasePhase.APPLY_ENGINE_CHERRYPICKS:
if (state.engine.cherrypicks.isEmpty) {
return <String>[
'There are no engine cherrypicks, so issue `conductor next` to continue',
'to the next step.',
'\n',
'******************************************************',
'* Create a new entry in http://go/release-eng-retros *',
'******************************************************',
].join('\n');
}
return <String>[
'You must now manually apply the following engine cherrypicks to the checkout',
'at ${state.engine.checkoutPath} in order:',
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks)
'\t${cherrypick.trunkRevision}',
'See ${globals.kReleaseDocumentationUrl} for more information.',
].join('\n');
case ReleasePhase.VERIFY_ENGINE_CI:
if (!requiresEnginePR(state)) {
return 'You must verify engine CI has passed: '
'${luciConsoleLink(state.releaseChannel, 'engine')}';
}
// User's working branch was pushed to their mirror, but a PR needs to be
// opened on GitHub.
final String newPrLink = globals.getNewPrLink(
userName: githubAccount(state.engine.mirror.url),
repoName: 'engine',
state: state,
);
return <String>[
'Your working branch ${state.engine.workingBranch} was pushed to your mirror.',
'You must now open a pull request at $newPrLink, verify pre-submit CI',
'builds on your engine pull request are successful, merge your pull request,',
'validate post-submit CI, and then codesign the binaries on the merge commit.',
].join('\n');
case ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS:
final List<pb.Cherrypick> outstandingCherrypicks =
state.framework.cherrypicks.where(
(pb.Cherrypick cp) {
return cp.state == pb.CherrypickState.PENDING ||
cp.state == pb.CherrypickState.PENDING_WITH_CONFLICT;
},
).toList();
if (outstandingCherrypicks.isNotEmpty) {
return <String>[
'You must now manually apply the following framework cherrypicks to the checkout',
'at ${state.framework.checkoutPath} in order:',
for (final pb.Cherrypick cherrypick in outstandingCherrypicks)
'\t${cherrypick.trunkRevision}',
].join('\n');
}
return <String>[
'Either all cherrypicks have been auto-applied or there were none.',
].join('\n');
case ReleasePhase.PUBLISH_VERSION:
if (!requiresFrameworkPR(state)) {
return 'Since there are no code changes in this release, no Framework '
'PR is necessary.';
}
final String newPrLink = globals.getNewPrLink(
userName: githubAccount(state.framework.mirror.url),
repoName: 'flutter',
state: state,
);
return <String>[
'Your working branch ${state.framework.workingBranch} was pushed to your mirror.',
'You must now open a pull request at $newPrLink',
'verify pre-submit CI builds on your pull request are successful, merge your ',
'pull request, validate post-submit CI.',
].join('\n');
case ReleasePhase.VERIFY_RELEASE:
return 'Release archive packages must be verified on cloud storage: ${luciConsoleLink(state.releaseChannel, 'packaging')}';
case ReleasePhase.RELEASE_COMPLETED:
if (state.releaseChannel == 'beta') {
return <String>[
betaPostReleaseMsg,
'-----------------------------------------------------------------------',
'This release has been completed.',
].join('\n');
}
return <String>[
stablePostReleaseMsg,
'-----------------------------------------------------------------------',
'This release has been completed.',
].join('\n');
}
// For analyzer
throw globals.ConductorException('Unimplemented phase ${state.currentPhase}');
}
/// Regex pattern for git remote host URLs.
///
/// First group = git host (currently must be github.com)
/// Second group = account name
/// Third group = repo name
final RegExp githubRemotePattern = RegExp(
r'^(git@github\.com:|https?:\/\/github\.com\/)([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_-]+)(\.git)?$');
/// Parses a Git remote URL and returns the account name.
///
/// Uses [githubRemotePattern].
String githubAccount(String remoteUrl) {
final String engineUrl = remoteUrl;
final RegExpMatch? match = githubRemotePattern.firstMatch(engineUrl);
if (match == null) {
throw globals.ConductorException(
'Cannot determine the GitHub account from $engineUrl',
);
}
final String? accountName = match.group(2);
if (accountName == null || accountName.isEmpty) {
throw globals.ConductorException(
'Cannot determine the GitHub account from $match',
);
}
return accountName;
}
/// Returns the next phase in the ReleasePhase enum.
///
/// Will throw a [ConductorException] if [ReleasePhase.RELEASE_COMPLETED] is
/// passed as an argument, as there is no next phase.
ReleasePhase getNextPhase(ReleasePhase currentPhase) {
switch (currentPhase) {
case ReleasePhase.PUBLISH_VERSION:
return ReleasePhase.VERIFY_RELEASE;
case ReleasePhase.APPLY_ENGINE_CHERRYPICKS:
case ReleasePhase.VERIFY_ENGINE_CI:
case ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS:
case ReleasePhase.VERIFY_RELEASE:
case ReleasePhase.RELEASE_COMPLETED:
final ReleasePhase? nextPhase = ReleasePhase.valueOf(currentPhase.value + 1);
if (nextPhase != null) {
return nextPhase;
}
}
throw globals.ConductorException('There is no next ReleasePhase!');
}
// Indent two spaces.
const JsonEncoder _encoder = JsonEncoder.withIndent(' ');
void writeStateToFile(File file, pb.ConductorState state, List<String> logs) {
state.logs.addAll(logs);
file.writeAsStringSync(
_encoder.convert(state.toProto3Json()),
flush: true,
);
}
pb.ConductorState readStateFromFile(File file) {
final pb.ConductorState state = pb.ConductorState();
final String stateAsString = file.readAsStringSync();
state.mergeFromProto3Json(
jsonDecode(stateAsString),
);
return state;
}
/// This release will require a new Engine PR.
///
/// The logic is if there are engine cherrypicks that have not been abandoned OR
/// there is a new Dart revision, then return true, else false.
bool requiresEnginePR(pb.ConductorState state) {
final bool hasRequiredCherrypicks = state.engine.cherrypicks.any(
(pb.Cherrypick cp) => cp.state != pb.CherrypickState.ABANDONED,
);
if (hasRequiredCherrypicks) {
return true;
}
return state.engine.dartRevision.isNotEmpty;
}
/// This release will require a new Framework PR.
///
/// The logic is if there was an Engine PR OR there are framework cherrypicks
/// that have not been abandoned.
bool requiresFrameworkPR(pb.ConductorState state) {
if (requiresEnginePR(state)) {
return true;
}
final bool hasRequiredCherrypicks = state.framework.cherrypicks
.any((pb.Cherrypick cp) => cp.state != pb.CherrypickState.ABANDONED);
if (hasRequiredCherrypicks) {
return true;
}
return false;
}
| flutter/dev/conductor/core/lib/src/state.dart/0 | {
"file_path": "flutter/dev/conductor/core/lib/src/state.dart",
"repo_id": "flutter",
"token_count": 4876
} | 507 |
#!/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.
# This should match the ci.bat file in this directory.
# This is called from .cirrus.yml and the LUCI recipes:
# https://flutter.googlesource.com/recipes/+/refs/heads/master/recipe_modules/adhoc_validation/resources/customer_testing.sh
set -ex
# This script does not assume that "flutter update-packages" has been
# run, to allow CIs to save time by skipping that steps since it's
# largely not needed to run the flutter/tests tests.
#
# However, we do need to update this directory and the tools directory.
dart pub get
(cd ../tools; dart pub get) # used for find_commit.dart below
# Next we need to update the flutter/tests checkout.
#
# We use find_commit.dart so that we pull the version of flutter/tests
# that was contemporary when the branch we are on was created. That
# way, we can still run the tests on long-lived branches without being
# affected by breaking changes on trunk causing changes to the tests
# that wouldn't work on the long-lived branch.
#
# (This also prevents trunk from suddenly failing when tests are
# revved on flutter/tests -- if you rerun a passing customer_tests
# shard, it should still pass, even if we rolled one of the tests.)
rm -rf ../../bin/cache/pkg/tests
git clone https://github.com/flutter/tests.git ../../bin/cache/pkg/tests
git -C ../../bin/cache/pkg/tests checkout `dart --enable-asserts ../tools/bin/find_commit.dart . master ../../bin/cache/pkg/tests main`
# Finally, run the tests.
dart --enable-asserts run_tests.dart --skip-on-fetch-failure --skip-template ../../bin/cache/pkg/tests/registry/*.test
| flutter/dev/customer_testing/ci.sh/0 | {
"file_path": "flutter/dev/customer_testing/ci.sh",
"repo_id": "flutter",
"token_count": 520
} | 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/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:flutter_devicelab/tasks/perf_tests.dart';
const String packageName = 'io.flutter.demo.gallery';
const String activityName = 'io.flutter.demo.gallery.MainActivity';
/// Measure application memory usage after pausing and resuming the app
/// with the Android back button.
class BackButtonMemoryTest extends MemoryTest {
BackButtonMemoryTest() : super('${flutterDirectory.path}/dev/integration_tests/flutter_gallery', 'test_memory/back_button.dart', packageName);
@override
AndroidDevice? get device => super.device as AndroidDevice?;
@override
int get iterationCount => 5;
/// Perform a series of back button suspend and resume cycles.
@override
Future<void> useMemory() async {
await launchApp();
await recordStart();
for (int iteration = 0; iteration < 8; iteration += 1) {
print('back/forward iteration $iteration');
// Push back button, wait for it to be seen by the Flutter app.
prepareForNextMessage('AppLifecycleState.paused');
await device!.shellExec('input', <String>['keyevent', 'KEYCODE_BACK']);
await receivedNextMessage;
// Give Android time to settle (e.g. run GCs) after closing the app.
await Future<void>.delayed(const Duration(milliseconds: 100));
// Relaunch the app, wait for it to launch.
prepareForNextMessage('READY');
final String output = await device!.shellEval('am', <String>['start', '-n', '$packageName/$activityName']);
print('adb shell am start: $output');
if (output.contains('Error')) {
fail('unable to launch activity');
}
await receivedNextMessage;
// Wait for the Flutter app to settle (e.g. run GCs).
await Future<void>.delayed(const Duration(milliseconds: 100));
}
await recordEnd();
}
}
Future<void> main() async {
deviceOperatingSystem = DeviceOperatingSystem.android;
await task(BackButtonMemoryTest().run);
}
| flutter/dev/devicelab/bin/tasks/flutter_gallery__back_button_memory.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/flutter_gallery__back_button_memory.dart",
"repo_id": "flutter",
"token_count": 732
} | 509 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:flutter_devicelab/tasks/perf_tests.dart' show WebCompileTest;
Future<void> main() async {
await task(const NewGalleryWebCompileTest().run);
}
/// Measures the time to compile the New Flutter Gallery to JavaScript
/// and the size of the compiled code.
class NewGalleryWebCompileTest {
const NewGalleryWebCompileTest();
String get metricKeyPrefix => 'new_gallery';
/// Runs the test.
Future<TaskResult> run() async {
final Map<String, Object> metrics = await inDirectory<Map<String, int>>(
'${flutterDirectory.path}/dev/integration_tests/new_gallery/',
() async {
await flutter('doctor');
await flutter('create', options: <String>[
'--platforms',
'web,android,ios',
'--no-overwrite',
'.'
]);
return WebCompileTest.runSingleBuildTest(
directory: '${flutterDirectory.path}/dev/integration_tests/new_gallery/',
metric: metricKeyPrefix,
measureBuildTime: true,
);
},
);
return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
}
}
| flutter/dev/devicelab/bin/tasks/flutter_gallery_v2_web_compile_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/flutter_gallery_v2_web_compile_test.dart",
"repo_id": "flutter",
"token_count": 536
} | 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 'package:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/tasks/hot_mode_tests.dart';
Future<void> main() async {
// TODO(vashworth): Remove once https://github.com/flutter/flutter/issues/142305 is fixed.
deviceOperatingSystem = DeviceOperatingSystem.ios;
await task(createHotModeTest(
additionalOptions: <String>['--no-dds'],
));
}
| flutter/dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios__benchmark_no_dds.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/hot_mode_dev_cycle_ios__benchmark_no_dds.dart",
"repo_id": "flutter",
"token_count": 195
} | 511 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:path/path.dart' as path;
import 'package:pub_semver/pub_semver.dart';
String adbPath() {
final String? androidHome = io.Platform.environment['ANDROID_HOME'] ?? io.Platform.environment['ANDROID_SDK_ROOT'];
if (androidHome == null) {
return 'adb';
} else {
return path.join(androidHome, 'platform-tools', 'adb');
}
}
Future<Version> getTalkbackVersion() async {
final io.ProcessResult result = await io.Process.run(adbPath(), const <String>[
'shell',
'dumpsys',
'package',
'com.google.android.marvin.talkback',
]);
if (result.exitCode != 0) {
throw Exception('Failed to get TalkBack version: ${result.stdout as String}\n${result.stderr as String}');
}
final List<String> lines = (result.stdout as String).split('\n');
String? version;
for (final String line in lines) {
if (line.contains('versionName')) {
version = line.replaceAll(RegExp(r'\s*versionName='), '');
break;
}
}
if (version == null) {
throw Exception('Unable to determine TalkBack version.');
}
// Android doesn't quite use semver, so convert the version string to semver form.
final RegExp startVersion = RegExp(r'(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(\.(?<build>\d+))?');
final RegExpMatch? match = startVersion.firstMatch(version);
if (match == null) {
return Version(0, 0, 0);
}
return Version(
int.parse(match.namedGroup('major')!),
int.parse(match.namedGroup('minor')!),
int.parse(match.namedGroup('patch')!),
build: match.namedGroup('build'),
);
}
Future<void> enableTalkBack() async {
final io.Process run = await io.Process.start(adbPath(), const <String>[
'shell',
'settings',
'put',
'secure',
'enabled_accessibility_services',
'com.google.android.marvin.talkback/com.google.android.marvin.talkback.TalkBackService',
]);
await run.exitCode;
print('TalkBack version is ${await getTalkbackVersion()}');
}
Future<void> disableTalkBack() async {
final io.Process run = await io.Process.start(adbPath(), const <String>[
'shell',
'settings',
'put',
'secure',
'enabled_accessibility_services',
'null',
]);
await run.exitCode;
}
| flutter/dev/devicelab/lib/framework/talkback.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/framework/talkback.dart",
"repo_id": "flutter",
"token_count": 863
} | 512 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart: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';
import '../microbenchmarks.dart';
/// Creates a device lab task that runs benchmarks in
/// `dev/benchmarks/microbenchmarks` reports results to the dashboard.
TaskFunction createMicrobenchmarkTask({
bool? enableImpeller,
Map<String, String> environment = const <String, String>{},
}) {
return () async {
final Device device = await devices.workingDevice;
await device.unlock();
await device.clearLogs();
Future<Map<String, double>> runMicrobench(String benchmarkPath) async {
Future<Map<String, double>> run() async {
print('Running $benchmarkPath');
final Directory appDir = dir(
path.join(flutterDirectory.path, 'dev/benchmarks/microbenchmarks'));
final Process flutterProcess = await inDirectory(appDir, () async {
final List<String> options = <String>[
'-v',
// --release doesn't work on iOS due to code signing issues
'--profile',
'--no-publish-port',
if (enableImpeller != null && enableImpeller) '--enable-impeller',
if (enableImpeller != null && !enableImpeller) '--no-enable-impeller',
'-d',
device.deviceId,
];
options.add(benchmarkPath);
return startFlutter(
'run',
options: options,
environment: environment,
);
});
return readJsonResults(flutterProcess);
}
return run();
}
final Map<String, double> allResults = <String, double>{
...await runMicrobench('lib/foundation/all_elements_bench.dart'),
...await runMicrobench('lib/foundation/change_notifier_bench.dart'),
...await runMicrobench('lib/foundation/clamp.dart'),
...await runMicrobench('lib/foundation/platform_asset_bundle.dart'),
...await runMicrobench('lib/foundation/standard_message_codec_bench.dart'),
...await runMicrobench('lib/foundation/standard_method_codec_bench.dart'),
...await runMicrobench('lib/foundation/timeline_bench.dart'),
...await runMicrobench('lib/foundation/decode_and_parse_asset_manifest.dart'),
...await runMicrobench('lib/geometry/matrix_utils_transform_bench.dart'),
...await runMicrobench('lib/geometry/rrect_contains_bench.dart'),
...await runMicrobench('lib/gestures/gesture_detector_bench.dart'),
...await runMicrobench('lib/gestures/velocity_tracker_bench.dart'),
...await runMicrobench('lib/language/compute_bench.dart'),
...await runMicrobench('lib/language/sync_star_bench.dart'),
...await runMicrobench('lib/language/sync_star_semantics_bench.dart'),
...await runMicrobench('lib/stocks/animation_bench.dart'),
...await runMicrobench('lib/stocks/build_bench_profiled.dart'),
...await runMicrobench('lib/stocks/build_bench.dart'),
...await runMicrobench('lib/stocks/layout_bench.dart'),
...await runMicrobench('lib/ui/image_bench.dart'),
...await runMicrobench('lib/layout/text_intrinsic_bench.dart'),
};
return TaskResult.success(allResults,
benchmarkScoreKeys: allResults.keys.toList());
};
}
| flutter/dev/devicelab/lib/tasks/microbenchmarks.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/tasks/microbenchmarks.dart",
"repo_id": "flutter",
"token_count": 1358
} | 513 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_devicelab/framework/host_agent.dart';
import 'package:platform/platform.dart';
import 'common.dart';
void main() {
late FileSystem fs;
setUp(() {
fs = MemoryFileSystem();
hostAgent.resetDumpDirectory();
});
tearDown(() {
hostAgent.resetDumpDirectory();
});
group('dump directory', () {
test('set by environment', () async {
final Directory environmentDir = fs.directory(fs.path.join('home', 'logs'));
final FakePlatform fakePlatform = FakePlatform(
environment: <String, String>{'FLUTTER_LOGS_DIR': environmentDir.path},
operatingSystem: 'windows',
);
final HostAgent agent = HostAgent(platform: fakePlatform, fileSystem: fs);
expect(agent.dumpDirectory!.existsSync(), isTrue);
expect(agent.dumpDirectory!.path, environmentDir.path);
});
test('not set by environment', () async {
final FakePlatform fakePlatform = FakePlatform(environment: <String, String>{}, operatingSystem: 'windows');
final HostAgent agent = HostAgent(platform: fakePlatform, fileSystem: fs);
expect(agent.dumpDirectory, null);
});
});
}
| flutter/dev/devicelab/test/host_agent_test.dart/0 | {
"file_path": "flutter/dev/devicelab/test/host_agent_test.dart",
"repo_id": "flutter",
"token_count": 455
} | 514 |
/* Overrides for dartdoc styles. */
/* Prefer Open Sans for paragraph and other text */
body {
font-family: "Open Sans", "Roboto", sans-serif;
}
/* Prefer Google Sans for headers */
h1, h2, h3, h4, h5, h6 .h1, .h2, .h3, .h4, .h5, .h6 {
font-family: "Google Sans", "Roboto", sans-serif;
}
.section-title, .breadcrumbs {
font-family: "Google Sans", "Roboto", sans-serif;
}
/* Make all the h2 headings slightly bigger. */
h2 {
font-size: 24px;
}
/* Specifically make all the Markdown h2 headings slightly
bigger, so the Markdown CSS doesn't override it. */
.markdown h2 {
font-size: 24px;
}
section.summary h2 {
color: inherit;
border-bottom: none;
}
section.summary .name {
font-size: 1.5em;
margin-right: 0.2em;
}
section.summary .returntype {
font-style:italic;
}
pre {
margin: 0 0 15px 0;
padding: 8px 12px;
border-radius: 4px;
}
code {
/* Inherit the background color, otherwise all inline code blocks have a
different color from the rest of the paragraph */
background-color: inherit;
font-size: 1em; /* browsers default to smaller font for code */
padding-left: 0; /* otherwise we get ragged left margins */
padding-right: 0;
}
/* Otherwise the description text is limited to a particular size instead of
filling up the center of the page. */
.markdown.desc {
max-width: inherit;
}
/* Make the search box bigger and easier to read */
#search-box {
height: 24px;
font-size: 15px;
padding-left: 40px;
}
/* Make the typeahead match the search box font size */
input.form-control.typeahead {
font-size: 15px;
}
/* Make description list terms not be so dim. */
dl.dl-horizontal dt {
color: inherit;
}
/* Line the material icons up with their labels
See https://api.flutter.dev/flutter/material/Icons-class.html
for where this matters.
*/
i.md-36 {
vertical-align: middle;
}
/* Address a style issue with the background of code sections. Without this, the
code inside a code block has a different background from the rest of the box. */
code.hljs {
background: inherit;
}
/* Make the footer smaller and less prominent. */
footer {
font-size: 13px;
padding: 8px;
}
/* Override the comment color for highlight.js to make it more
prominent. */
.hljs-comment {
color: #128c00;
font-style: italic;
font-weight: bold;
}
/* Make the summary headers contrast a bit with text. */
.summary h2 {
opacity: 0.8;
}
/* Constrain the image width to the container so that images resize instead of
causing the page to scroll horizontally */
img {
max-width: 100%
}
/* Light/Dark Theme adjustments */
.light-theme {
/* This is the same link color as the main Flutter site */
--main-hyperlinks-color: rgb(19, 137, 253);
--main-footer-background: #eee;
}
.dark-theme {
--main-hyperlinks-color: rgb(81, 167, 254);
}
.light-theme footer {
color: rgb(74, 74, 74);
}
.dark-theme footer {
color:rgb(220, 220, 220);
}
body.light-theme {
color:rgb(74, 74, 74);
}
body.dark-theme {
color:rgb(220, 220, 220);
}
.dark-theme .multi-line-signature .name {
color: rgb(163, 163, 163);
}
.dark-theme .parameter-name {
color: rgb(163, 163, 163);
}
.dark-theme .parameter {
color: rgb(163, 163, 163);
}
.light-theme pre {
border: 1px solid white;
color: #222;
background-color:#eee;
}
.dark-theme pre {
border: 1px solid #444;
color: white;
background-color:rgb(23, 32, 43);
}
.dark-theme .hljs-string {
color:rgb(255, 100, 100);
}
.dark-theme .hljs-title {
color:rgb(192, 184, 255);
}
| flutter/dev/docs/assets/overrides.css/0 | {
"file_path": "flutter/dev/docs/assets/overrides.css",
"repo_id": "flutter",
"token_count": 1259
} | 515 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.integration.platformviews;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import java.util.HashMap;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity implements MethodChannel.MethodCallHandler {
final static int STORAGE_PERMISSION_CODE = 1;
MethodChannel mMethodChannel;
// The method result to complete with the Android permission request result.
// This is null when not waiting for the Android permission request;
private MethodChannel.Result permissionResult;
private View getFlutterView() {
return findViewById(FLUTTER_VIEW_ID);
}
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
DartExecutor executor = flutterEngine.getDartExecutor();
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory("simple_view", new SimpleViewFactory(executor));
mMethodChannel = new MethodChannel(executor, "android_views_integration");
mMethodChannel.setMethodCallHandler(this);
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
switch (methodCall.method) {
case "pipeFlutterViewEvents":
result.success(null);
return;
case "stopFlutterViewEvents":
result.success(null);
return;
case "getStoragePermission":
if (permissionResult != null) {
result.error("error", "already waiting for permissions", null);
return;
}
permissionResult = result;
getExternalStoragePermissions();
return;
case "synthesizeEvent":
synthesizeEvent(methodCall, result);
return;
}
result.notImplemented();
}
@SuppressWarnings("unchecked")
public void synthesizeEvent(MethodCall methodCall, MethodChannel.Result result) {
MotionEvent event = MotionEventCodec.decode((HashMap<String, Object>) methodCall.arguments());
getFlutterView().dispatchTouchEvent(event);
// TODO(egarciad): Remove invokeMethod since it is not necessary.
mMethodChannel.invokeMethod("onTouch", MotionEventCodec.encode(event));
result.success(null);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode != STORAGE_PERMISSION_CODE || permissionResult == null)
return;
boolean permissionGranted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
sendPermissionResult(permissionGranted);
}
private void getExternalStoragePermissions() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return;
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
sendPermissionResult(true);
return;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
private void sendPermissionResult(boolean result) {
if (permissionResult == null)
return;
permissionResult.success(result);
permissionResult = null;
}
}
| flutter/dev/integration_tests/android_views/android/app/src/main/java/io/flutter/integration/androidviews/MainActivity.java/0 | {
"file_path": "flutter/dev/integration_tests/android_views/android/app/src/main/java/io/flutter/integration/androidviews/MainActivity.java",
"repo_id": "flutter",
"token_count": 1562
} | 516 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:isolate';
import 'package:flutter/services.dart';
import 'pair.dart';
import 'test_step.dart';
class ExtendedStandardMessageCodec extends StandardMessageCodec {
const ExtendedStandardMessageCodec();
static const int _dateTime = 128;
static const int _pair = 129;
@override
void writeValue(WriteBuffer buffer, dynamic value) {
if (value is DateTime) {
buffer.putUint8(_dateTime);
buffer.putInt64(value.millisecondsSinceEpoch);
} else if (value is Pair) {
buffer.putUint8(_pair);
writeValue(buffer, value.left);
writeValue(buffer, value.right);
} else {
super.writeValue(buffer, value);
}
}
@override
dynamic readValueOfType(int type, ReadBuffer buffer) {
return switch (type) {
_dateTime => DateTime.fromMillisecondsSinceEpoch(buffer.getInt64()),
_pair => Pair(readValue(buffer), readValue(buffer)),
_ => super.readValueOfType(type, buffer),
};
}
}
Future<TestStepResult> basicBinaryHandshake(ByteData? message) async {
const BasicMessageChannel<ByteData?> channel =
BasicMessageChannel<ByteData?>(
'binary-msg',
BinaryCodec(),
);
return _basicMessageHandshake<ByteData?>(
'Binary >${toString(message)}<', channel, message);
}
Future<TestStepResult> basicStringHandshake(String? message) async {
const BasicMessageChannel<String?> channel = BasicMessageChannel<String?>(
'string-msg',
StringCodec(),
);
return _basicMessageHandshake<String?>('String >$message<', channel, message);
}
Future<TestStepResult> basicJsonHandshake(dynamic message) async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
'json-msg',
JSONMessageCodec(),
);
return _basicMessageHandshake<dynamic>('JSON >$message<', channel, message);
}
Future<TestStepResult> basicStandardHandshake(dynamic message) async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
'std-msg',
ExtendedStandardMessageCodec(),
);
return _basicMessageHandshake<dynamic>(
'Standard >${toString(message)}<', channel, message);
}
Future<void> _basicBackgroundStandardEchoMain(List<Object> args) async {
final SendPort sendPort = args[2] as SendPort;
final Object message = args[1];
final String name = 'Background Echo >${toString(message)}<';
const String description =
'Uses a platform channel from a background isolate.';
try {
BackgroundIsolateBinaryMessenger.ensureInitialized(
args[0] as RootIsolateToken);
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'std-echo',
ExtendedStandardMessageCodec(),
);
final Object response = await channel.send(message) as Object;
final TestStatus testStatus = TestStepResult.deepEquals(message, response)
? TestStatus.ok
: TestStatus.failed;
sendPort.send(TestStepResult(name, description, testStatus));
} catch (ex) {
sendPort.send(TestStepResult(name, description, TestStatus.failed,
error: ex.toString()));
}
}
Future<TestStepResult> basicBackgroundStandardEcho(Object message) async {
final ReceivePort receivePort = ReceivePort();
Isolate.spawn(_basicBackgroundStandardEchoMain, <Object>[
ServicesBinding.rootIsolateToken!,
message,
receivePort.sendPort,
]);
return await receivePort.first as TestStepResult;
}
Future<TestStepResult> basicBinaryMessageToUnknownChannel() async {
const BasicMessageChannel<ByteData?> channel =
BasicMessageChannel<ByteData?>(
'binary-unknown',
BinaryCodec(),
);
return _basicMessageToUnknownChannel<ByteData>('Binary', channel);
}
Future<TestStepResult> basicStringMessageToUnknownChannel() async {
const BasicMessageChannel<String?> channel = BasicMessageChannel<String?>(
'string-unknown',
StringCodec(),
);
return _basicMessageToUnknownChannel<String>('String', channel);
}
Future<TestStepResult> basicJsonMessageToUnknownChannel() async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
'json-unknown',
JSONMessageCodec(),
);
return _basicMessageToUnknownChannel<dynamic>('JSON', channel);
}
Future<TestStepResult> basicStandardMessageToUnknownChannel() async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
'std-unknown',
ExtendedStandardMessageCodec(),
);
return _basicMessageToUnknownChannel<dynamic>('Standard', channel);
}
/// Sends the specified message to the platform, doing a
/// receive message/send reply/receive reply echo handshake initiated by the
/// platform, then expecting a reply echo to the original message.
///
/// Fails, if an error occurs, or if any message seen is not deeply equal to
/// the original message.
Future<TestStepResult> _basicMessageHandshake<T>(
String description,
BasicMessageChannel<T?> channel,
T message,
) async {
final List<dynamic> received = <dynamic>[];
channel.setMessageHandler((T? message) async {
received.add(message);
return message;
});
dynamic messageEcho = nothing;
dynamic error = nothing;
try {
messageEcho = await channel.send(message);
} catch (e) {
error = e;
}
return resultOfHandshake(
'Basic message handshake',
description,
message,
received,
messageEcho,
error,
);
}
/// Sends a message on a channel that no one listens on.
Future<TestStepResult> _basicMessageToUnknownChannel<T>(
String description,
BasicMessageChannel<T?> channel,
) async {
dynamic messageEcho = nothing;
dynamic error = nothing;
try {
messageEcho = await channel.send(null);
} catch (e) {
error = e;
}
return resultOfHandshake(
'Message on unknown channel',
description,
null,
<dynamic>[null, null],
messageEcho,
error,
);
}
String toString(dynamic message) {
if (message is ByteData) {
return message.buffer
.asUint8List(message.offsetInBytes, message.lengthInBytes)
.toString();
} else {
return '$message';
}
}
| flutter/dev/integration_tests/channels/lib/src/basic_messaging.dart/0 | {
"file_path": "flutter/dev/integration_tests/channels/lib/src/basic_messaging.dart",
"repo_id": "flutter",
"token_count": 2046
} | 517 |
<!-- Copyright 2014 The Flutter Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- ${applicationName} is used by the Flutter tool to select the Application
class to use. For most apps, this is the default Android application.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
Application and put your custom class here. -->
<application
android:name="io.flutter.embedding.android.FlutterPlayStoreSplitApplication"
android:label="deferred_components_test"
android:extractNativeLibs="false">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:exported="true"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<meta-data
android:name="io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping"
android:value="2:component1" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>
| flutter/dev/integration_tests/deferred_components_test/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "flutter/dev/integration_tests/deferred_components_test/android/app/src/main/AndroidManifest.xml",
"repo_id": "flutter",
"token_count": 1141
} | 518 |
// 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 LogoScreen extends StatelessWidget {
const LogoScreen({super.key});
static const String _testSentinel = 'Running deferred code';
@override
Widget build(BuildContext context) {
print(_testSentinel);
return Container(
padding: const EdgeInsets.all(25),
color: Colors.blue,
child: Column(
children: <Widget>[
const Text('DeferredWidget', key: Key('DeferredWidget')),
Image.asset('customassets/flutter_logo.png', key: const Key('DeferredImage')),
],
),
);
}
}
| flutter/dev/integration_tests/deferred_components_test/lib/component1.dart/0 | {
"file_path": "flutter/dev/integration_tests/deferred_components_test/lib/component1.dart",
"repo_id": "flutter",
"token_count": 263
} | 519 |
// 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;
final RegExp _calibrationRegExp = RegExp('Flutter frame rate is (.*)fps');
final RegExp _statsRegExp = RegExp('Produced: (.*)fps\nConsumed: (.*)fps\nWidget builds: (.*)');
const Duration _samplingTime = Duration(seconds: 8);
Future<void> main() async {
late final FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
});
tearDownAll(() async {
await driver.close();
});
// Verifies we consume texture frames at a rate close to the minimum of the
// rate at which they are produced and Flutter's frame rate. In addition,
// it verifies that widget builds are not triggered by external texture
// frames.
test('renders frames from the device at a rate similar to the frames produced', () async {
final SerializableFinder fab = find.byValueKey('fab');
final SerializableFinder summary = find.byValueKey('summary');
// Wait for calibration to complete and fab to appear.
await driver.waitFor(fab);
final String calibrationResult = await driver.getText(summary);
final Match? matchCalibration = _calibrationRegExp.matchAsPrefix(calibrationResult);
expect(matchCalibration, isNotNull);
final double flutterFrameRate = double.parse(matchCalibration?.group(1) ?? '0');
// Texture frame stats at 0.5x Flutter frame rate
await driver.tap(fab);
await Future<void>.delayed(_samplingTime);
await driver.tap(fab);
final String statsSlow = await driver.getText(summary);
final Match matchSlow = _statsRegExp.matchAsPrefix(statsSlow)!;
expect(matchSlow, isNotNull);
double framesProduced = double.parse(matchSlow.group(1)!);
expect(framesProduced, closeTo(flutterFrameRate / 2.0, 5.0));
double framesConsumed = double.parse(matchSlow.group(2)!);
expect(framesConsumed, closeTo(flutterFrameRate / 2.0, 5.0));
int widgetBuilds = int.parse(matchSlow.group(3)!);
expect(widgetBuilds, 1);
// Texture frame stats at 2.0x Flutter frame rate
await driver.tap(fab);
await Future<void>.delayed(_samplingTime);
await driver.tap(fab);
final String statsFast = await driver.getText(summary);
final Match matchFast = _statsRegExp.matchAsPrefix(statsFast)!;
expect(matchFast, isNotNull);
framesProduced = double.parse(matchFast.group(1)!);
expect(framesProduced, closeTo(flutterFrameRate * 2.0, 5.0));
framesConsumed = double.parse(matchFast.group(2)!);
expect(framesConsumed, closeTo(flutterFrameRate, 10.0));
widgetBuilds = int.parse(matchSlow.group(3)!);
expect(widgetBuilds, 1);
}, timeout: Timeout.none);
}
| flutter/dev/integration_tests/external_textures/test_driver/frame_rate_main_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/external_textures/test_driver/frame_rate_main_test.dart",
"repo_id": "flutter",
"token_count": 941
} | 520 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Cocoa
import FlutterMacOS
class MainFlutterWindow: NSWindow {
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
let windowFrame = self.frame
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
RegisterGeneratedPlugins(registry: flutterViewController)
RegisterMethodChannel(registry: flutterViewController)
super.awakeFromNib()
}
func RegisterMethodChannel(registry: FlutterPluginRegistry) {
let registrar = registry.registrar(forPlugin: "flavors")
let channel = FlutterMethodChannel(name: "flavor",
binaryMessenger: registrar.messenger)
channel.setMethodCallHandler({ (call, result) in
let bundleIdentifier = Bundle.main.infoDictionary?["CFBundleName"] as? String
let flavor = bundleIdentifier?.split(separator: " ").last?.lowercased();
result(flavor)
})
}
}
| flutter/dev/integration_tests/flavors/macos/Runner/MainFlutterWindow.swift/0 | {
"file_path": "flutter/dev/integration_tests/flavors/macos/Runner/MainFlutterWindow.swift",
"repo_id": "flutter",
"token_count": 380
} | 521 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import '../../gallery/demo.dart';
class CupertinoAlertDemo extends StatefulWidget {
const CupertinoAlertDemo({super.key});
static const String routeName = '/cupertino/alert';
@override
State<CupertinoAlertDemo> createState() => _CupertinoAlertDemoState();
}
class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
String? lastSelectedValue;
void showDemoDialog({required BuildContext context, Widget? child}) {
showCupertinoDialog<String>(
context: context,
builder: (BuildContext context) => child!,
).then((String? value) {
if (value != null) {
setState(() { lastSelectedValue = value; });
}
});
}
void showDemoActionSheet({required BuildContext context, Widget? child}) {
showCupertinoModalPopup<String>(
context: context,
builder: (BuildContext context) => child!,
).then((String? value) {
if (value != null) {
setState(() { lastSelectedValue = value; });
}
});
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Alerts'),
// We're specifying a back label here because the previous page is a
// Material page. CupertinoPageRoutes could auto-populate these back
// labels.
previousPageTitle: 'Cupertino',
trailing: CupertinoDemoDocumentationButton(CupertinoAlertDemo.routeName),
),
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: Builder(
builder: (BuildContext context) {
return Stack(
alignment: Alignment.center,
children: <Widget>[
CupertinoScrollbar(
child: ListView(
primary: true,
// Add more padding to the normal safe area.
padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0)
+ MediaQuery.of(context).padding,
children: <Widget>[
CupertinoButton.filled(
child: const Text('Alert'),
onPressed: () => _onAlertPress(context),
),
const Padding(padding: EdgeInsets.all(8.0)),
CupertinoButton.filled(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0),
child: const Text('Alert with Title'),
onPressed: () => _onAlertWithTitlePress(context),
),
const Padding(padding: EdgeInsets.all(8.0)),
CupertinoButton.filled(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0),
child: const Text('Alert with Buttons'),
onPressed: () => _onAlertWithButtonsPress(context),
),
const Padding(padding: EdgeInsets.all(8.0)),
CupertinoButton.filled(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0),
child: const Text('Alert Buttons Only'),
onPressed: () {
showDemoDialog(
context: context,
child: const CupertinoDessertDialog(),
);
},
),
const Padding(padding: EdgeInsets.all(8.0)),
CupertinoButton.filled(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0),
child: const Text('Action Sheet'),
onPressed: () => _onActionSheetPress(context),
),
],
),
),
if (lastSelectedValue != null)
Positioned(
bottom: 32.0,
child: Text('You selected: $lastSelectedValue'),
),
],
);
},
),
),
);
}
void _onAlertPress(BuildContext context) {
showDemoDialog(
context: context,
child: CupertinoAlertDialog(
title: const Text('Discard draft?'),
actions: <Widget>[
CupertinoDialogAction(
isDestructiveAction: true,
child: const Text('Discard'),
onPressed: () => Navigator.pop(context, 'Discard'),
),
CupertinoDialogAction(
isDefaultAction: true,
child: const Text('Cancel'),
onPressed: () => Navigator.pop(context, 'Cancel'),
),
],
),
);
}
void _onAlertWithTitlePress(BuildContext context) {
showDemoDialog(
context: context,
child: CupertinoAlertDialog(
title: const Text('Allow "Maps" to access your location while you are using the app?'),
content: const Text('Your current location will be displayed on the map and used '
'for directions, nearby search results, and estimated travel times.'),
actions: <Widget>[
CupertinoDialogAction(
child: const Text("Don't Allow"),
onPressed: () => Navigator.pop(context, 'Disallow'),
),
CupertinoDialogAction(
child: const Text('Allow'),
onPressed: () => Navigator.pop(context, 'Allow'),
),
],
),
);
}
void _onAlertWithButtonsPress(BuildContext context) {
showDemoDialog(
context: context,
child: const CupertinoDessertDialog(
title: Text('Select Favorite Dessert'),
content: Text('Please select your favorite type of dessert from the '
'list below. Your selection will be used to customize the suggested '
'list of eateries in your area.'),
),
);
}
void _onActionSheetPress(BuildContext context) {
showDemoActionSheet(
context: context,
child: CupertinoActionSheet(
title: const Text('Favorite Dessert'),
message: const Text('Please select the best dessert from the options below.'),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Profiteroles'),
onPressed: () => Navigator.pop(context, 'Profiteroles'),
),
CupertinoActionSheetAction(
child: const Text('Cannolis'),
onPressed: () => Navigator.pop(context, 'Cannolis'),
),
CupertinoActionSheetAction(
child: const Text('Trifle'),
onPressed: () => Navigator.pop(context, 'Trifle'),
),
],
cancelButton: CupertinoActionSheetAction(
isDefaultAction: true,
child: const Text('Cancel'),
onPressed: () => Navigator.pop(context, 'Cancel'),
),
),
);
}
}
class CupertinoDessertDialog extends StatelessWidget {
const CupertinoDessertDialog({super.key, this.title, this.content});
final Widget? title;
final Widget? content;
@override
Widget build(BuildContext context) {
return CupertinoAlertDialog(
title: title,
content: content,
actions: <Widget>[
CupertinoDialogAction(
child: const Text('Cheesecake'),
onPressed: () {
Navigator.pop(context, 'Cheesecake');
},
),
CupertinoDialogAction(
child: const Text('Tiramisu'),
onPressed: () {
Navigator.pop(context, 'Tiramisu');
},
),
CupertinoDialogAction(
child: const Text('Apple Pie'),
onPressed: () {
Navigator.pop(context, 'Apple Pie');
},
),
CupertinoDialogAction(
child: const Text("Devil's food cake"),
onPressed: () {
Navigator.pop(context, "Devil's food cake");
},
),
CupertinoDialogAction(
child: const Text('Banana Split'),
onPressed: () {
Navigator.pop(context, 'Banana Split');
},
),
CupertinoDialogAction(
child: const Text('Oatmeal Cookie'),
onPressed: () {
Navigator.pop(context, 'Oatmeal Cookies');
},
),
CupertinoDialogAction(
child: const Text('Chocolate Brownie'),
onPressed: () {
Navigator.pop(context, 'Chocolate Brownies');
},
),
CupertinoDialogAction(
isDestructiveAction: true,
child: const Text('Cancel'),
onPressed: () {
Navigator.pop(context, 'Cancel');
},
),
],
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart",
"repo_id": "flutter",
"token_count": 4370
} | 522 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const String _elevatedText =
'Elevated buttons add dimension to mostly flat layouts. They emphasize '
'functions on busy or wide spaces.';
const String _elevatedCode = 'buttons_elevated';
const String _textText = 'A text button displays an ink splash on press '
'but does not lift. Use text buttons on toolbars, in dialogs and '
'inline with padding';
const String _textCode = 'buttons_text';
const String _outlinedText =
'Outlined buttons become opaque and elevate when pressed. They are often '
'paired with elevated buttons to indicate an alternative, secondary action.';
const String _outlinedCode = 'buttons_outlined';
const String _dropdownText =
"A dropdown button displays a menu that's used to select a value from a "
'small set of values. The button displays the current value and a down '
'arrow.';
const String _dropdownCode = 'buttons_dropdown';
const String _iconText =
'IconButtons are appropriate for toggle buttons that allow a single choice '
"to be selected or deselected, such as adding or removing an item's star.";
const String _iconCode = 'buttons_icon';
const String _actionText =
'Floating action buttons are used for a promoted action. They are '
'distinguished by a circled icon floating above the UI and can have motion '
'behaviors that include morphing, launching, and a transferring anchor '
'point.';
const String _actionCode = 'buttons_action';
class ButtonsDemo extends StatefulWidget {
const ButtonsDemo({super.key});
static const String routeName = '/material/buttons';
@override
State<ButtonsDemo> createState() => _ButtonsDemoState();
}
class _ButtonsDemoState extends State<ButtonsDemo> {
OutlinedBorder? _buttonShape;
@override
Widget build(BuildContext context) {
final List<ComponentDemoTabData> demos = <ComponentDemoTabData>[
ComponentDemoTabData(
tabName: 'ELEVATED',
description: _elevatedText,
demoWidget: buildElevatedButton(_buttonShape),
exampleCodeTag: _elevatedCode,
documentationUrl: 'https://api.flutter.dev/flutter/material/ElevatedButton-class.html',
),
ComponentDemoTabData(
tabName: 'TEXT',
description: _textText,
demoWidget: buildTextButton(_buttonShape),
exampleCodeTag: _textCode,
documentationUrl: 'https://api.flutter.dev/flutter/material/TextButton-class.html',
),
ComponentDemoTabData(
tabName: 'OUTLINED',
description: _outlinedText,
demoWidget: buildOutlinedButton(_buttonShape),
exampleCodeTag: _outlinedCode,
documentationUrl: 'https://api.flutter.dev/flutter/material/OutlinedButton-class.html',
),
ComponentDemoTabData(
tabName: 'DROPDOWN',
description: _dropdownText,
demoWidget: buildDropdownButton(),
exampleCodeTag: _dropdownCode,
documentationUrl: 'https://api.flutter.dev/flutter/material/DropdownButton-class.html',
),
ComponentDemoTabData(
tabName: 'ICON',
description: _iconText,
demoWidget: buildIconButton(),
exampleCodeTag: _iconCode,
documentationUrl: 'https://api.flutter.dev/flutter/material/IconButton-class.html',
),
ComponentDemoTabData(
tabName: 'ACTION',
description: _actionText,
demoWidget: buildActionButton(),
exampleCodeTag: _actionCode,
documentationUrl: 'https://api.flutter.dev/flutter/material/FloatingActionButton-class.html',
),
];
return TabbedComponentDemoScaffold(
title: 'Buttons',
demos: demos,
actions: <Widget>[
IconButton(
icon: const Icon(Icons.sentiment_very_satisfied, semanticLabel: 'Update shape'),
onPressed: () {
setState(() {
_buttonShape = _buttonShape == null ? const StadiumBorder() : null;
});
},
),
],
);
}
Widget buildElevatedButton(OutlinedBorder? shape) {
final ButtonStyle style = ElevatedButton.styleFrom(shape: shape);
return Align(
alignment: const Alignment(0.0, -0.2),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(height: 2),
OverflowBar(
spacing: 8,
children: <Widget>[
ElevatedButton(
style: style,
child: const Text('ELEVATED BUTTON', semanticsLabel: 'ELEVATED BUTTON 1'),
onPressed: () {
// Perform some action
},
),
const ElevatedButton(
onPressed: null,
child: Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 1'),
),
],
),
const SizedBox(height: 16),
OverflowBar(
spacing: 8,
children: <Widget>[
ElevatedButton.icon(
style: style,
icon: const Icon(Icons.add, size: 18.0),
label: const Text('ELEVATED BUTTON', semanticsLabel: 'ELEVATED BUTTON 2'),
onPressed: () {
// Perform some action
},
),
ElevatedButton.icon(
style: style,
icon: const Icon(Icons.add, size: 18.0),
label: const Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 2'),
onPressed: () {},
),
],
),
],
),
);
}
Widget buildTextButton(OutlinedBorder? shape) {
final ButtonStyle style = ElevatedButton.styleFrom(shape: shape);
return Align(
alignment: const Alignment(0.0, -0.2),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(height: 2),
OverflowBar(
spacing: 8,
children: <Widget>[
TextButton(
style: style,
child: const Text('TEXT BUTTON', semanticsLabel: 'TEXT BUTTON 1'),
onPressed: () {
// Perform some action
},
),
const TextButton(
onPressed: null,
child: Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 3',),
),
],
),
OverflowBar(
spacing: 8,
children: <Widget>[
TextButton.icon(
style: style,
icon: const Icon(Icons.add_circle_outline, size: 18.0),
label: const Text('TEXT BUTTON', semanticsLabel: 'TEXT BUTTON 2'),
onPressed: () {
// Perform some action
},
),
TextButton.icon(
style: style,
icon: const Icon(Icons.add_circle_outline, size: 18.0),
label: const Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 4'),
onPressed: () {},
),
],
),
],
),
);
}
Widget buildOutlinedButton(OutlinedBorder? shape) {
final ButtonStyle style = ElevatedButton.styleFrom(shape: shape);
return Align(
alignment: const Alignment(0.0, -0.2),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const SizedBox(height: 2),
OverflowBar(
spacing: 8,
children: <Widget>[
OutlinedButton(
style: style,
child: const Text('OUTLINED BUTTON', semanticsLabel: 'OUTLINED BUTTON 1'),
onPressed: () {
// Perform some action
},
),
OutlinedButton(
style: style,
onPressed: null,
child: const Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 5'),
),
],
),
const SizedBox(height: 16),
OverflowBar(
spacing: 8,
children: <Widget>[
OutlinedButton.icon(
style: style,
icon: const Icon(Icons.add, size: 18.0),
label: const Text('OUTLINED BUTTON', semanticsLabel: 'OUTLINED BUTTON 2'),
onPressed: () {
// Perform some action
},
),
OutlinedButton.icon(
icon: const Icon(Icons.add, size: 18.0),
label: const Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 6'),
onPressed: null,
),
],
),
],
),
);
}
// https://en.wikipedia.org/wiki/Free_Four
String? dropdown1Value = 'Free';
String? dropdown2Value;
String? dropdown3Value = 'Four';
Widget buildDropdownButton() {
return Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
children: <Widget>[
ListTile(
title: const Text('Simple dropdown:'),
trailing: DropdownButton<String>(
value: dropdown1Value,
onChanged: (String? newValue) {
setState(() {
dropdown1Value = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
const SizedBox(
height: 24.0,
),
ListTile(
title: const Text('Dropdown with a hint:'),
trailing: DropdownButton<String>(
value: dropdown2Value,
hint: const Text('Choose'),
onChanged: (String? newValue) {
setState(() {
dropdown2Value = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
const SizedBox(
height: 24.0,
),
ListTile(
title: const Text('Scrollable dropdown:'),
trailing: DropdownButton<String>(
value: dropdown3Value,
onChanged: (String? newValue) {
setState(() {
dropdown3Value = newValue;
});
},
items: <String>[
'One', 'Two', 'Free', 'Four', 'Can', 'I', 'Have', 'A', 'Little',
'Bit', 'More', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten',
]
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
),
),
],
),
);
}
bool iconButtonToggle = false;
Widget buildIconButton() {
return Align(
alignment: const Alignment(0.0, -0.2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: const Icon(
Icons.thumb_up,
semanticLabel: 'Thumbs up',
),
onPressed: () {
setState(() => iconButtonToggle = !iconButtonToggle);
},
color: iconButtonToggle ? Theme.of(context).primaryColor : null,
),
const IconButton(
icon: Icon(
Icons.thumb_up,
semanticLabel: 'Thumbs not up',
),
onPressed: null,
),
]
.map<Widget>((Widget button) => SizedBox(width: 64.0, height: 64.0, child: button))
.toList(),
),
);
}
Widget buildActionButton() {
return Align(
alignment: const Alignment(0.0, -0.2),
child: FloatingActionButton(
tooltip: 'floating action button',
child: const Icon(Icons.add),
onPressed: () {
// Perform some action
},
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/buttons_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/buttons_demo.dart",
"repo_id": "flutter",
"token_count": 6225
} | 523 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
class MenuDemo extends StatefulWidget {
const MenuDemo({ super.key });
static const String routeName = '/material/menu';
@override
MenuDemoState createState() => MenuDemoState();
}
class MenuDemoState extends State<MenuDemo> {
final String _simpleValue1 = 'Menu item value one';
final String _simpleValue2 = 'Menu item value two';
final String _simpleValue3 = 'Menu item value three';
String? _simpleValue;
final String _checkedValue1 = 'One';
final String _checkedValue2 = 'Two';
final String _checkedValue3 = 'Free';
final String _checkedValue4 = 'Four';
late List<String> _checkedValues;
@override
void initState() {
super.initState();
_simpleValue = _simpleValue2;
_checkedValues = <String>[_checkedValue3];
}
void showInSnackBar(String value) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(value),
));
}
void showMenuSelection(String value) {
if (<String>[_simpleValue1, _simpleValue2, _simpleValue3].contains(value)) {
setState(() => _simpleValue = value);
}
showInSnackBar('You selected: $value');
}
void showCheckedMenuSelections(String value) {
if (_checkedValues.contains(value)) {
_checkedValues.remove(value);
} else {
_checkedValues.add(value);
}
showInSnackBar('Checked $_checkedValues');
}
bool isChecked(String value) => _checkedValues.contains(value);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Menus'),
actions: <Widget>[
MaterialDemoDocumentationButton(MenuDemo.routeName),
PopupMenuButton<String>(
onSelected: showMenuSelection,
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
const PopupMenuItem<String>(
value: 'Toolbar menu',
child: Text('Toolbar menu'),
),
const PopupMenuItem<String>(
value: 'Right here',
child: Text('Right here'),
),
const PopupMenuItem<String>(
value: 'Hooray!',
child: Text('Hooray!'),
),
],
),
],
),
body: ListTileTheme(
iconColor: Theme.of(context).brightness == Brightness.light
? Colors.grey[600]
: Colors.grey[500],
child: ListView(
padding: kMaterialListPadding,
children: <Widget>[
// Pressing the PopupMenuButton on the right of this item shows
// a simple menu with one disabled item. Typically the contents
// of this "contextual menu" would reflect the app's state.
ListTile(
title: const Text('An item with a context menu button'),
trailing: PopupMenuButton<String>(
padding: EdgeInsets.zero,
onSelected: showMenuSelection,
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: _simpleValue1,
child: const Text('Context menu item one'),
),
const PopupMenuItem<String>(
enabled: false,
child: Text('A disabled menu item'),
),
PopupMenuItem<String>(
value: _simpleValue3,
child: const Text('Context menu item three'),
),
],
),
),
// Pressing the PopupMenuButton on the right of this item shows
// a menu whose items have text labels and icons and a divider
// That separates the first three items from the last one.
ListTile(
title: const Text('An item with a sectioned menu'),
trailing: PopupMenuButton<String>(
padding: EdgeInsets.zero,
onSelected: showMenuSelection,
itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'Preview',
child: ListTile(
leading: Icon(Icons.visibility),
title: Text('Preview'),
),
),
const PopupMenuItem<String>(
value: 'Share',
child: ListTile(
leading: Icon(Icons.person_add),
title: Text('Share'),
),
),
const PopupMenuItem<String>(
value: 'Get Link',
child: ListTile(
leading: Icon(Icons.link),
title: Text('Get link'),
),
),
const PopupMenuDivider(),
const PopupMenuItem<String>(
value: 'Remove',
child: ListTile(
leading: Icon(Icons.delete),
title: Text('Remove'),
),
),
],
),
),
// This entire list item is a PopupMenuButton. Tapping anywhere shows
// a menu whose current value is highlighted and aligned over the
// list item's center line.
PopupMenuButton<String>(
padding: EdgeInsets.zero,
initialValue: _simpleValue,
onSelected: showMenuSelection,
child: ListTile(
title: const Text('An item with a simple menu'),
subtitle: Text(_simpleValue!),
),
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: _simpleValue1,
child: Text(_simpleValue1),
),
PopupMenuItem<String>(
value: _simpleValue2,
child: Text(_simpleValue2),
),
PopupMenuItem<String>(
value: _simpleValue3,
child: Text(_simpleValue3),
),
],
),
// Pressing the PopupMenuButton on the right of this item shows a menu
// whose items have checked icons that reflect this app's state.
ListTile(
title: const Text('An item with a checklist menu'),
trailing: PopupMenuButton<String>(
padding: EdgeInsets.zero,
onSelected: showCheckedMenuSelections,
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
CheckedPopupMenuItem<String>(
value: _checkedValue1,
checked: isChecked(_checkedValue1),
child: Text(_checkedValue1),
),
CheckedPopupMenuItem<String>(
value: _checkedValue2,
enabled: false,
checked: isChecked(_checkedValue2),
child: Text(_checkedValue2),
),
CheckedPopupMenuItem<String>(
value: _checkedValue3,
checked: isChecked(_checkedValue3),
child: Text(_checkedValue3),
),
CheckedPopupMenuItem<String>(
value: _checkedValue4,
checked: isChecked(_checkedValue4),
child: Text(_checkedValue4),
),
],
),
),
],
),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart",
"repo_id": "flutter",
"token_count": 4099
} | 524 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.