text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// 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 '../base/context.dart';
import '../base/user_messages.dart';
import '../doctor_validator.dart';
import 'visual_studio.dart';
VisualStudioValidator? get visualStudioValidator => context.get<VisualStudioValidator>();
class VisualStudioValidator extends DoctorValidator {
const VisualStudioValidator({
required VisualStudio visualStudio,
required UserMessages userMessages,
}) : _visualStudio = visualStudio,
_userMessages = userMessages,
super('Visual Studio - develop Windows apps');
final VisualStudio _visualStudio;
final UserMessages _userMessages;
@override
Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType status = ValidationType.missing;
String? versionInfo;
if (_visualStudio.isInstalled) {
status = ValidationType.success;
messages.add(ValidationMessage(
_userMessages.visualStudioLocation(_visualStudio.installLocation ?? 'unknown')
));
messages.add(ValidationMessage(_userMessages.visualStudioVersion(
_visualStudio.displayName ?? 'unknown',
_visualStudio.fullVersion ?? 'unknown',
)));
if (_visualStudio.isPrerelease) {
messages.add(ValidationMessage(_userMessages.visualStudioIsPrerelease));
}
final String? windows10SdkVersion = _visualStudio.getWindows10SDKVersion();
if (windows10SdkVersion != null) {
messages.add(ValidationMessage(_userMessages.windows10SdkVersion(windows10SdkVersion)));
}
// Messages for faulty installations.
if (!_visualStudio.isAtLeastMinimumVersion) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(
_userMessages.visualStudioTooOld(
_visualStudio.minimumVersionDescription,
_visualStudio.workloadDescription,
),
));
} else if (_visualStudio.isRebootRequired) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(_userMessages.visualStudioRebootRequired));
} else if (!_visualStudio.isComplete) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(_userMessages.visualStudioIsIncomplete));
} else if (!_visualStudio.isLaunchable) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(_userMessages.visualStudioNotLaunchable));
} else if (!_visualStudio.hasNecessaryComponents) {
status = ValidationType.partial;
messages.add(ValidationMessage.error(
_userMessages.visualStudioMissingComponents(
_visualStudio.workloadDescription,
_visualStudio.necessaryComponentDescriptions(),
),
));
} else if (windows10SdkVersion == null) {
status = ValidationType.partial;
messages.add(ValidationMessage.hint(_userMessages.windows10SdkNotFound));
}
versionInfo = '${_visualStudio.displayName} ${_visualStudio.displayVersion}';
} else {
status = ValidationType.missing;
messages.add(ValidationMessage.error(
_userMessages.visualStudioMissing(
_visualStudio.workloadDescription,
),
));
}
return ValidationResult(status, messages, statusInfo: versionInfo);
}
}
| flutter/packages/flutter_tools/lib/src/windows/visual_studio_validator.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/windows/visual_studio_validator.dart",
"repo_id": "flutter",
"token_count": 1271
} | 812 |
<component name="libraryTable">
<library name="KotlinJavaRuntime">
<CLASSES>
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-stdlib.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-reflect.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-test.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-stdlib-sources.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-reflect-sources.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-test-sources.jar!/" />
</SOURCES>
</library>
</component>
| flutter/packages/flutter_tools/templates/app_shared/.idea/libraries/KotlinJavaRuntime.xml.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/app_shared/.idea/libraries/KotlinJavaRuntime.xml.tmpl",
"repo_id": "flutter",
"token_count": 296
} | 813 |
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android" name="Android">
<configuration>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="GEN_FOLDER_RELATIVE_PATH_APT" value="/gen" />
<option name="GEN_FOLDER_RELATIVE_PATH_AIDL" value="/gen" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
<option name="LIBS_FOLDER_RELATIVE_PATH" value="/src/main/libs" />
<option name="PROGUARD_LOGS_FOLDER_RELATIVE_PATH" value="/src/main/proguard_logs" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
</content>
<orderEntry type="jdk" jdkName="Android API {{androidSdkVersion}} Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Flutter for Android" level="project" />
</component>
</module>
| flutter/packages/flutter_tools/templates/plugin/android-java.tmpl/projectName_android.iml.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin/android-java.tmpl/projectName_android.iml.tmpl",
"repo_id": "flutter",
"token_count": 562
} | 814 |
#ifndef FLUTTER_PLUGIN_{{pluginClassCapitalSnakeCase}}_H_
#define FLUTTER_PLUGIN_{{pluginClassCapitalSnakeCase}}_H_
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <memory>
namespace {{projectName}} {
class {{pluginClass}} : public flutter::Plugin {
public:
static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar);
{{pluginClass}}();
virtual ~{{pluginClass}}();
// Disallow copy and assign.
{{pluginClass}}(const {{pluginClass}}&) = delete;
{{pluginClass}}& operator=(const {{pluginClass}}&) = delete;
// Called when a method is called on this plugin's channel from Dart.
void HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue> &method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
};
} // namespace {{projectName}}
#endif // FLUTTER_PLUGIN_{{pluginClassCapitalSnakeCase}}_H_
| flutter/packages/flutter_tools/templates/plugin/windows.tmpl/pluginClassSnakeCase.h.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin/windows.tmpl/pluginClassSnakeCase.h.tmpl",
"repo_id": "flutter",
"token_count": 306
} | 815 |
# The Flutter tooling requires that developers have a version of Visual Studio
# installed that includes CMake 3.14 or later. You should not increase this
# version, as doing so will cause the plugin to fail to compile for some
# customers of the plugin.
cmake_minimum_required(VERSION 3.14)
# Project-level configuration.
set(PROJECT_NAME "{{projectName}}")
project(${PROJECT_NAME} LANGUAGES CXX)
# Invoke the build for native code shared with the other target platforms.
# This can be changed to accommodate different builds.
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared")
# List of absolute paths to libraries that should be bundled with the plugin.
# This list could contain prebuilt libraries, or libraries created by an
# external build triggered from this build file.
set({{projectName}}_bundled_libraries
# Defined in ../src/CMakeLists.txt.
# This can be changed to accommodate different builds.
$<TARGET_FILE:{{projectName}}>
PARENT_SCOPE
)
| flutter/packages/flutter_tools/templates/plugin_ffi/windows.tmpl/CMakeLists.txt.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin_ffi/windows.tmpl/CMakeLists.txt.tmpl",
"repo_id": "flutter",
"token_count": 284
} | 816 |
# Template Xcode project with a custom application bundle
This template is an empty Xcode project with a settable application bundle path
within the `xcscheme`. It is used when debugging a project on a physical iOS 17+
device via Xcode 15+ when `--use-application-binary` is used. | flutter/packages/flutter_tools/templates/xcode/ios/custom_application_bundle/README.md/0 | {
"file_path": "flutter/packages/flutter_tools/templates/xcode/ios/custom_application_bundle/README.md",
"repo_id": "flutter",
"token_count": 67
} | 817 |
// 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:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/android/android_builder.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/terminal.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/analyze.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/project_validator.dart';
import 'package:test/fake.dart';
import '../../src/context.dart';
import '../../src/test_flutter_command_runner.dart';
void main() {
group('Android analyze command', () {
late FileSystem fileSystem;
late Platform platform;
late BufferLogger logger;
late FakeProcessManager processManager;
late Terminal terminal;
late AnalyzeCommand command;
late CommandRunner<void> runner;
late Directory tempDir;
late FakeAndroidBuilder builder;
setUpAll(() {
Cache.disableLocking();
});
setUp(() async {
fileSystem = MemoryFileSystem.test();
platform = FakePlatform();
logger = BufferLogger.test();
processManager = FakeProcessManager.empty();
terminal = Terminal.test();
command = AnalyzeCommand(
artifacts: Artifacts.test(),
fileSystem: fileSystem,
logger: logger,
platform: platform,
processManager: processManager,
terminal: terminal,
allProjectValidators: <ProjectValidator>[],
suppressAnalytics: true,
);
runner = createTestCommandRunner(command);
tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
tempDir.childDirectory('android').createSync();
// Setup repo roots
const String homePath = '/home/user/flutter';
Cache.flutterRoot = homePath;
for (final String dir in <String>['dev', 'examples', 'packages']) {
fileSystem.directory(homePath).childDirectory(dir).createSync(recursive: true);
}
builder = FakeAndroidBuilder();
});
testUsingContext('can list build variants', () async {
builder.variants = <String>['debug', 'release'];
await runner.run(<String>['analyze', '--android', '--list-build-variants', tempDir.path]);
expect(logger.statusText, contains('["debug","release"]'));
}, overrides: <Type, Generator>{
AndroidBuilder: () => builder,
});
testUsingContext('throw if provide multiple path', () async {
final Directory anotherTempDir = fileSystem.systemTempDirectory.createTempSync('another');
await expectLater(
runner.run(<String>['analyze', '--android', '--list-build-variants', tempDir.path, anotherTempDir.path]),
throwsA(
isA<Exception>().having(
(Exception e) => e.toString(),
'description',
contains('The Android analyze can process only one directory path'),
),
),
);
});
testUsingContext('can output app link settings', () async {
const String buildVariant = 'release';
await runner.run(<String>['analyze', '--android', '--output-app-link-settings', '--build-variant=$buildVariant', tempDir.path]);
expect(builder.outputVariant, buildVariant);
expect(logger.statusText, contains(builder.outputPath));
}, overrides: <Type, Generator>{
AndroidBuilder: () => builder,
});
testUsingContext('output app link settings throws if no build variant', () async {
await expectLater(
runner.run(<String>['analyze', '--android', '--output-app-link-settings', tempDir.path]),
throwsA(
isA<Exception>().having(
(Exception e) => e.toString(),
'description',
contains('"--build-variant" must be provided'),
),
),
);
});
});
}
class FakeAndroidBuilder extends Fake implements AndroidBuilder {
List<String> variants = const <String>[];
String? outputVariant;
final String outputPath = '/';
@override
Future<List<String>> getBuildVariants({required FlutterProject project}) async {
return variants;
}
@override
Future<String> outputsAppLinkSettings(String buildVariant, {required FlutterProject project}) async {
outputVariant = buildVariant;
return outputPath;
}
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/android_analyze_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/android_analyze_test.dart",
"repo_id": "flutter",
"token_count": 1653
} | 818 |
// 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' as io;
import 'dart:typed_data';
import 'package:fake_async/fake_async.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/android/android_device.dart';
import 'package:flutter_tools/src/android/android_workflow.dart';
import 'package:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/dds.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/utils.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/commands/daemon.dart';
import 'package:flutter_tools/src/daemon.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/fuchsia/fuchsia_workflow.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/ios/ios_workflow.dart';
import 'package:flutter_tools/src/preview_device.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:flutter_tools/src/windows/windows_workflow.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_devices.dart';
import '../../src/fakes.dart';
/// Runs a callback using FakeAsync.run while continually pumping the
/// microtask queue. This avoids a deadlock when tests `await` a Future
/// which queues a microtask that will not be processed unless the queue
/// is flushed.
Future<T> _runFakeAsync<T>(Future<T> Function(FakeAsync time) f) async {
return FakeAsync().run((FakeAsync time) async {
bool pump = true;
final Future<T> future = f(time).whenComplete(() => pump = false);
while (pump) {
time.flushMicrotasks();
}
return future;
});
}
class FakeDaemonStreams implements DaemonStreams {
final StreamController<DaemonMessage> inputs = StreamController<DaemonMessage>();
final StreamController<DaemonMessage> outputs = StreamController<DaemonMessage>();
@override
Stream<DaemonMessage> get inputStream {
return inputs.stream;
}
@override
void send(Map<String, Object?> message, [ List<int>? binary ]) {
outputs.add(DaemonMessage(message, binary != null ? Stream<List<int>>.value(binary) : null));
}
@override
Future<void> dispose() async {
await inputs.close();
// In some tests, outputs have no listeners. We don't wait for outputs to close.
unawaited(outputs.close());
}
}
void main() {
late Daemon daemon;
late NotifyingLogger notifyingLogger;
group('daemon', () {
late FakeDaemonStreams daemonStreams;
late DaemonConnection daemonConnection;
setUp(() {
BufferLogger bufferLogger;
bufferLogger = BufferLogger.test();
notifyingLogger = NotifyingLogger(verbose: false, parent: bufferLogger);
daemonStreams = FakeDaemonStreams();
daemonConnection = DaemonConnection(
daemonStreams: daemonStreams,
logger: bufferLogger,
);
});
tearDown(() async {
await daemon.shutdown();
notifyingLogger.dispose();
await daemonConnection.dispose();
});
testUsingContext('daemon.version command should succeed', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'daemon.version'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['result'], isNotEmpty);
expect(response.data['result'], isA<String>());
});
testUsingContext('daemon.getSupportedPlatforms command should succeed', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
// Use the flutter_gallery project which has a known set of supported platforms.
final String projectPath = globals.fs.path.join(getFlutterRoot(), 'dev', 'integration_tests', 'flutter_gallery');
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'daemon.getSupportedPlatforms',
'params': <String, Object>{'projectRoot': projectPath},
}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['result'], isNotEmpty);
expect(
response.data['result']! as Map<String, Object?>,
const <String, Object>{
'platforms': <String>['macos', 'windows', 'windowsPreview'],
'platformTypes': <String, Map<String, Object>>{
'web': <String, Object>{
'isSupported': false,
'reasons': <Map<String, String>>[
<String, String>{
'reasonText': 'the Web feature is not enabled',
'fixText': 'Run "flutter config --enable-web"',
'fixCode': 'config',
},
],
},
'android': <String, Object>{
'isSupported': false,
'reasons': <Map<String, String>>[
<String, String>{
'reasonText': 'the Android feature is not enabled',
'fixText': 'Run "flutter config --enable-android"',
'fixCode': 'config',
},
],
},
'ios': <String, Object>{
'isSupported': false,
'reasons': <Map<String, String>>[
<String, String>{
'reasonText': 'the iOS feature is not enabled',
'fixText': 'Run "flutter config --enable-ios"',
'fixCode': 'config',
},
],
},
'linux': <String, Object>{
'isSupported': false,
'reasons': <Map<String, String>>[
<String, String>{
'reasonText': 'the Linux feature is not enabled',
'fixText': 'Run "flutter config --enable-linux-desktop"',
'fixCode': 'config',
},
],
},
'macos': <String, bool>{'isSupported': true},
'windows': <String, bool>{'isSupported': true},
'fuchsia': <String, Object>{
'isSupported': false,
'reasons': <Map<String, String>>[
<String, String>{
'reasonText': 'the Fuchsia feature is not enabled',
'fixText': 'Run "flutter config --enable-fuchsia"',
'fixCode': 'config',
},
<String, String>{
'reasonText': 'the Fuchsia platform is not enabled for this project',
'fixText': 'Run "flutter create --platforms=fuchsia ." in your application directory',
'fixCode': 'create',
},
],
},
'custom': <String, Object>{
'isSupported': false,
'reasons': <Map<String, String>>[
<String, String>{
'reasonText': 'the custom devices feature is not enabled',
'fixText': 'Run "flutter config --enable-custom-devices"',
'fixCode': 'config',
},
],
},
'windowsPreview': <String, bool>{'isSupported': true},
},
},
);
}, overrides: <Type, Generator>{
// Disable Android/iOS and enable macOS to make sure result is consistent and defaults are tested off.
FeatureFlags: () => TestFeatureFlags(
isAndroidEnabled: false,
isIOSEnabled: false,
isMacOSEnabled: true,
isPreviewDeviceEnabled: true,
isWindowsEnabled: true,
),
});
testUsingContext('printError should send daemon.logMessage event', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
globals.printError('daemon.logMessage test');
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere((DaemonMessage message) {
return message.data['event'] == 'daemon.logMessage' && (message.data['params']! as Map<String, Object?>)['level'] == 'error';
});
expect(response.data['id'], isNull);
expect(response.data['event'], 'daemon.logMessage');
final Map<String, String> logMessage = castStringKeyedMap(response.data['params'])!.cast<String, String>();
expect(logMessage['level'], 'error');
expect(logMessage['message'], 'daemon.logMessage test');
}, overrides: <Type, Generator>{
Logger: () => notifyingLogger,
});
testUsingContext('printWarning should send daemon.logMessage event', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
globals.printWarning('daemon.logMessage test');
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere((DaemonMessage message) {
return message.data['event'] == 'daemon.logMessage' && (message.data['params']! as Map<String, Object?>)['level'] == 'warning';
});
expect(response.data['id'], isNull);
expect(response.data['event'], 'daemon.logMessage');
final Map<String, String> logMessage = castStringKeyedMap(response.data['params'])!.cast<String, String>();
expect(logMessage['level'], 'warning');
expect(logMessage['message'], 'daemon.logMessage test');
}, overrides: <Type, Generator>{
Logger: () => notifyingLogger,
});
testUsingContext('printStatus should log to stdout when logToStdout is enabled', () async {
final StringBuffer buffer = await capturedConsolePrint(() {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
logToStdout: true,
);
globals.printStatus('daemon.logMessage test');
return Future<void>.value();
});
expect(buffer.toString().trim(), 'daemon.logMessage test');
}, overrides: <Type, Generator>{
Logger: () => notifyingLogger,
});
testUsingContext('printBox should log to stdout when logToStdout is enabled', () async {
final StringBuffer buffer = await capturedConsolePrint(() {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
logToStdout: true,
);
globals.printBox('This is the box message', title: 'Sample title');
return Future<void>.value();
});
expect(buffer.toString().trim(), contains('Sample title: This is the box message'));
}, overrides: <Type, Generator>{
Logger: () => notifyingLogger,
});
testUsingContext('printTrace should send daemon.logMessage event when notifyVerbose is enabled', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
notifyingLogger.notifyVerbose = false;
globals.printTrace('daemon.logMessage test 1');
notifyingLogger.notifyVerbose = true;
globals.printTrace('daemon.logMessage test 2');
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere((DaemonMessage message) {
return message.data['event'] == 'daemon.logMessage' && (message.data['params']! as Map<String, Object?>)['level'] == 'trace';
});
expect(response.data['id'], isNull);
expect(response.data['event'], 'daemon.logMessage');
final Map<String, String> logMessage = castStringKeyedMap(response.data['params'])!.cast<String, String>();
expect(logMessage['level'], 'trace');
expect(logMessage['message'], 'daemon.logMessage test 2');
}, overrides: <Type, Generator>{
Logger: () => notifyingLogger,
});
testUsingContext('daemon.setNotifyVerbose command should update the notify verbose status to true', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
expect(notifyingLogger.notifyVerbose, false);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'daemon.setNotifyVerbose',
'params': <String, Object?>{
'verbose': true,
},
}));
await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(notifyingLogger.notifyVerbose, true);
});
testUsingContext('daemon.setNotifyVerbose command should update the notify verbose status to false', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
notifyingLogger.notifyVerbose = false;
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'daemon.setNotifyVerbose',
'params': <String, Object?>{
'verbose': false,
},
}));
await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(notifyingLogger.notifyVerbose, false);
});
testUsingContext('daemon.shutdown command should stop daemon', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'daemon.shutdown'}));
return daemon.onExit.then<void>((int code) async {
await daemonStreams.inputs.close();
expect(code, 0);
});
});
testUsingContext('app.restart without an appId should report an error', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'app.restart'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['error'], contains('appId is required'));
});
testUsingContext('ext.flutter.debugPaint via service extension without an appId should report an error', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'app.callServiceExtension',
'params': <String, String>{
'methodName': 'ext.flutter.debugPaint',
},
}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['error'], contains('appId is required'));
});
testUsingContext('app.stop without appId should report an error', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'app.stop'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['error'], contains('appId is required'));
});
testUsingContext('device.getDevices should respond with list', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'device.getDevices'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['result'], isList);
});
testUsingContext('device.getDevices reports available devices', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
daemon.deviceDomain.addDeviceDiscoverer(discoverer);
discoverer.addDevice(FakeAndroidDevice());
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'device.getDevices'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
final Object? result = response.data['result'];
expect(result, isList);
expect(result, isNotEmpty);
});
testUsingContext('should send device.added event when device is discovered', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
daemon.deviceDomain.addDeviceDiscoverer(discoverer);
discoverer.addDevice(FakeAndroidDevice());
final MemoryFileSystem fs = MemoryFileSystem.test();
discoverer.addDevice(PreviewDevice(
processManager: FakeProcessManager.empty(),
logger: BufferLogger.test(),
fileSystem: fs,
previewBinary: fs.file(r'preview_device.exe'),
artifacts: Artifacts.test(fileSystem: fs),
builderFactory: () => throw UnimplementedError('TODO implement builder factory'),
));
final List<Map<String, Object?>> names = <Map<String, Object?>>[];
await daemonStreams.outputs.stream.skipWhile(_isConnectedEvent).take(2).forEach((DaemonMessage response) async {
expect(response.data['event'], 'device.added');
expect(response.data['params'], isMap);
final Map<String, Object?> params = castStringKeyedMap(response.data['params'])!;
names.add(params);
});
await daemonStreams.outputs.close();
expect(
names,
containsAll(const <Map<String, Object?>>[
<String, Object?>{
'id': 'device',
'name': 'android device',
'platform': 'android-arm',
'emulator': false,
'category': 'mobile',
'platformType': 'android',
'ephemeral': false,
'emulatorId': 'device',
'sdk': 'Android 12',
'isConnected': true,
'connectionInterface': 'attached',
'capabilities': <String, Object?>{
'hotReload': true,
'hotRestart': true,
'screenshot': true,
'fastStart': true,
'flutterExit': true,
'hardwareRendering': true,
'startPaused': true,
},
},
<String, Object?>{
'id': 'preview',
'name': 'Preview',
'platform': 'windows-x64',
'emulator': false,
'category': 'desktop',
'platformType': 'windowsPreview',
'ephemeral': false,
'emulatorId': null,
'sdk': 'preview',
'isConnected': true,
'connectionInterface': 'attached',
'capabilities': <String, Object?>{
'hotReload': true,
'hotRestart': true,
'screenshot': false,
'fastStart': false,
'flutterExit': true,
'hardwareRendering': true,
'startPaused': true,
},
},
]),
);
}, overrides: <Type, Generator>{
AndroidWorkflow: () => FakeAndroidWorkflow(),
IOSWorkflow: () => FakeIOSWorkflow(),
FuchsiaWorkflow: () => FakeFuchsiaWorkflow(),
WindowsWorkflow: () => FakeWindowsWorkflow(),
});
testUsingContext('device.discoverDevices should respond with list', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'device.discoverDevices'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['result'], isList);
});
testUsingContext('device.discoverDevices reports available devices', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
daemon.deviceDomain.addDeviceDiscoverer(discoverer);
discoverer.addDevice(FakeAndroidDevice());
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'device.discoverDevices'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
final Object? result = response.data['result'];
expect(result, isList);
expect(result, isNotEmpty);
expect(discoverer.discoverDevicesCalled, true);
});
testUsingContext('device.supportsRuntimeMode returns correct value', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
daemon.deviceDomain.addDeviceDiscoverer(discoverer);
final FakeAndroidDevice device = FakeAndroidDevice();
discoverer.addDevice(device);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'device.supportsRuntimeMode',
'params': <String, Object?>{
'deviceId': 'device',
'buildMode': 'profile',
},
}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
final Object? result = response.data['result'];
expect(result, true);
expect(device.supportsRuntimeModeCalledBuildMode, BuildMode.profile);
});
testUsingContext('device.logReader.start and .stop starts and stops log reader', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
daemon.deviceDomain.addDeviceDiscoverer(discoverer);
final FakeAndroidDevice device = FakeAndroidDevice();
discoverer.addDevice(device);
final FakeDeviceLogReader logReader = FakeDeviceLogReader();
device.logReader = logReader;
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'device.logReader.start',
'params': <String, Object?>{
'deviceId': 'device',
},
}));
final Stream<DaemonMessage> broadcastOutput = daemonStreams.outputs.stream.asBroadcastStream();
final DaemonMessage firstResponse = await broadcastOutput.firstWhere(_notEvent);
expect(firstResponse.data['id'], 0);
final String? logReaderId = firstResponse.data['result'] as String?;
expect(logReaderId, isNotNull);
// Try sending logs.
logReader.logLinesController.add('Sample log line');
final DaemonMessage logEvent = await broadcastOutput.firstWhere(
(DaemonMessage message) => message.data['event'] != null && message.data['event'] != 'device.added',
);
expect(logEvent.data['params'], 'Sample log line');
// Now try to stop the log reader.
expect(logReader.disposeCalled, false);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 1,
'method': 'device.logReader.stop',
'params': <String, Object?>{
'id': logReaderId,
},
}));
final DaemonMessage stopResponse = await broadcastOutput.firstWhere(_notEvent);
expect(stopResponse.data['id'], 1);
expect(logReader.disposeCalled, true);
});
group('device.startApp and .stopApp', () {
late FakeApplicationPackageFactory applicationPackageFactory;
setUp(() {
applicationPackageFactory = FakeApplicationPackageFactory();
});
testUsingContext('device.startApp and .stopApp starts and stops an app', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
daemon.deviceDomain.addDeviceDiscoverer(discoverer);
final FakeAndroidDevice device = FakeAndroidDevice();
discoverer.addDevice(device);
final Stream<DaemonMessage> broadcastOutput = daemonStreams.outputs.stream.asBroadcastStream();
// First upload the application package.
final FakeApplicationPackage applicationPackage = FakeApplicationPackage();
applicationPackageFactory.applicationPackage = applicationPackage;
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'device.uploadApplicationPackage',
'params': <String, Object?>{
'targetPlatform': 'android',
'applicationBinary': 'test_file',
},
}));
final DaemonMessage applicationPackageIdResponse = await broadcastOutput.firstWhere(_notEvent);
expect(applicationPackageIdResponse.data['id'], 0);
expect(applicationPackageFactory.applicationBinaryRequested!.basename, 'test_file');
expect(applicationPackageFactory.platformRequested, TargetPlatform.android);
final String? applicationPackageId = applicationPackageIdResponse.data['result'] as String?;
// Try starting the app.
final Uri vmServiceUri = Uri.parse('http://127.0.0.1:12345/vmService');
device.launchResult = LaunchResult.succeeded(vmServiceUri: vmServiceUri);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 1,
'method': 'device.startApp',
'params': <String, Object?>{
'deviceId': 'device',
'applicationPackageId': applicationPackageId,
'debuggingOptions': DebuggingOptions.enabled(BuildInfo.debug).toJson(),
},
}));
final DaemonMessage startAppResponse = await broadcastOutput.firstWhere(_notEvent);
expect(startAppResponse.data['id'], 1);
expect(device.startAppPackage, applicationPackage);
final Map<String, Object?> startAppResult = startAppResponse.data['result']! as Map<String, Object?>;
expect(startAppResult['started'], true);
expect(startAppResult['vmServiceUri'], vmServiceUri.toString());
// Try stopping the app.
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 2,
'method': 'device.stopApp',
'params': <String, Object?>{
'deviceId': 'device',
'applicationPackageId': applicationPackageId,
},
}));
final DaemonMessage stopAppResponse = await broadcastOutput.firstWhere(_notEvent);
expect(stopAppResponse.data['id'], 2);
expect(device.stopAppPackage, applicationPackage);
final bool? stopAppResult = stopAppResponse.data['result'] as bool?;
expect(stopAppResult, true);
}, overrides: <Type, Generator>{
ApplicationPackageFactory: () => applicationPackageFactory,
});
});
testUsingContext('device.startDartDevelopmentService and .shutdownDartDevelopmentService starts and stops DDS', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
daemon.deviceDomain.addDeviceDiscoverer(discoverer);
final FakeAndroidDevice device = FakeAndroidDevice();
discoverer.addDevice(device);
final Completer<void> ddsDoneCompleter = Completer<void>();
device.dds.done = ddsDoneCompleter.future;
final Uri fakeDdsUri = Uri.parse('http://fake_dds_uri');
device.dds.uri = fakeDdsUri;
// Try starting DDS.
expect(device.dds.startCalled, false);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'device.startDartDevelopmentService',
'params': <String, Object?>{
'deviceId': 'device',
'disableServiceAuthCodes': false,
'vmServiceUri': 'http://fake_uri/auth_code',
},
}));
final Stream<DaemonMessage> broadcastOutput = daemonStreams.outputs.stream.asBroadcastStream();
final DaemonMessage startResponse = await broadcastOutput.firstWhere(_notEvent);
expect(startResponse.data['id'], 0);
expect(startResponse.data['error'], isNull);
final String? ddsUri = startResponse.data['result'] as String?;
expect(ddsUri, fakeDdsUri.toString());
expect(device.dds.startCalled, true);
expect(device.dds.startDisableServiceAuthCodes, false);
expect(device.dds.startVMServiceUri, Uri.parse('http://fake_uri/auth_code'));
// dds.done event should be sent to the client.
ddsDoneCompleter.complete();
final DaemonMessage startEvent = await broadcastOutput.firstWhere(
(DaemonMessage message) => message.data['event'] != null && message.data['event'] == 'device.dds.done.device',
);
expect(startEvent, isNotNull);
// Try stopping DDS.
expect(device.dds.shutdownCalled, false);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 1,
'method': 'device.shutdownDartDevelopmentService',
'params': <String, Object?>{
'deviceId': 'device',
},
}));
final DaemonMessage stopResponse = await broadcastOutput.firstWhere(_notEvent);
expect(stopResponse.data['id'], 1);
expect(stopResponse.data['error'], isNull);
expect(device.dds.shutdownCalled, true);
});
testUsingContext('device.getDiagnostics returns correct value', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final FakePollingDeviceDiscovery discoverer1 = FakePollingDeviceDiscovery();
discoverer1.diagnostics = <String>['fake diagnostic 1', 'fake diagnostic 2'];
final FakePollingDeviceDiscovery discoverer2 = FakePollingDeviceDiscovery();
discoverer2.diagnostics = <String>['fake diagnostic 3', 'fake diagnostic 4'];
daemon.deviceDomain.addDeviceDiscoverer(discoverer1);
daemon.deviceDomain.addDeviceDiscoverer(discoverer2);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{
'id': 0,
'method': 'device.getDiagnostics',
}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['result'], <String>[
'fake diagnostic 1',
'fake diagnostic 2',
'fake diagnostic 3',
'fake diagnostic 4',
]);
});
testUsingContext('emulator.launch without an emulatorId should report an error', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'emulator.launch'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['error'], contains('emulatorId is required'));
});
testUsingContext('emulator.launch coldboot parameter must be boolean', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
final Map<String, Object?> params = <String, Object?>{'emulatorId': 'device', 'coldBoot': 1};
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'emulator.launch', 'params': params}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['error'], contains('coldBoot is not a bool'));
});
testUsingContext('emulator.getEmulators should respond with list', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'emulator.getEmulators'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere(_notEvent);
expect(response.data['id'], 0);
expect(response.data['result'], isList);
});
testUsingContext('daemon can send exposeUrl requests to the client', () async {
const String originalUrl = 'http://localhost:1234/';
const String mappedUrl = 'https://publichost:4321/';
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
// Respond to any requests from the daemon to expose a URL.
unawaited(daemonStreams.outputs.stream
.firstWhere((DaemonMessage request) => request.data['method'] == 'app.exposeUrl')
.then((DaemonMessage request) {
expect((request.data['params']! as Map<String, Object?>)['url'], equals(originalUrl));
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': request.data['id'], 'result': <String, Object?>{'url': mappedUrl}}));
})
);
final String exposedUrl = await daemon.daemonDomain.exposeUrl(originalUrl);
expect(exposedUrl, equals(mappedUrl));
});
testUsingContext('devtools.serve command should return host and port on success', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'devtools.serve'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere((DaemonMessage response) => response.data['id'] == 0);
final Map<String, Object?> result = response.data['result']! as Map<String, Object?>;
expect(result, isNotEmpty);
expect(result['host'], '127.0.0.1');
expect(result['port'], 1234);
}, overrides: <Type, Generator>{
DevtoolsLauncher: () => FakeDevtoolsLauncher(DevToolsServerAddress('127.0.0.1', 1234)),
});
testUsingContext('devtools.serve command should return null fields if null returned', () async {
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'devtools.serve'}));
final DaemonMessage response = await daemonStreams.outputs.stream.firstWhere((DaemonMessage response) => response.data['id'] == 0);
final Map<String, Object?> result = response.data['result']! as Map<String, Object?>;
expect(result, isNotEmpty);
expect(result['host'], null);
expect(result['port'], null);
}, overrides: <Type, Generator>{
DevtoolsLauncher: () => FakeDevtoolsLauncher(null),
});
testUsingContext('proxy.connect tries to connect to an ipv4 address and proxies the connection correctly', () async {
final TestIOOverrides ioOverrides = TestIOOverrides();
await io.IOOverrides.runWithIOOverrides(() async {
final FakeSocket socket = FakeSocket();
bool connectCalled = false;
int? connectPort;
ioOverrides.connectCallback = (Object? host, int port) async {
connectCalled = true;
connectPort = port;
if (host == io.InternetAddress.loopbackIPv4) {
return socket;
}
throw const io.SocketException('fail');
};
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'proxy.connect', 'params': <String, Object?>{'port': 123}}));
final Stream<DaemonMessage> broadcastOutput = daemonStreams.outputs.stream.asBroadcastStream();
final DaemonMessage firstResponse = await broadcastOutput.firstWhere(_notEvent);
expect(firstResponse.data['id'], 0);
expect(firstResponse.data['result'], isNotNull);
expect(connectCalled, true);
expect(connectPort, 123);
final Object? id = firstResponse.data['result'];
// Can send received data as event.
socket.controller.add(Uint8List.fromList(<int>[10, 11, 12]));
final DaemonMessage dataEvent = await broadcastOutput.firstWhere(
(DaemonMessage message) => message.data['event'] != null && message.data['event'] == 'proxy.data.$id',
);
expect(dataEvent.binary, isNotNull);
final List<List<int>> data = await dataEvent.binary!.toList();
expect(data[0], <int>[10, 11, 12]);
// Can proxy data to the socket.
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'proxy.write', 'params': <String, Object?>{'id': id}}, Stream<List<int>>.value(<int>[21, 22, 23])));
await pumpEventQueue();
expect(socket.addedData[0], <int>[21, 22, 23]);
// Closes the connection when disconnect request received.
expect(socket.closeCalled, false);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'proxy.disconnect', 'params': <String, Object?>{'id': id}}));
await pumpEventQueue();
expect(socket.closeCalled, true);
// Sends disconnected event when socket.done completer finishes.
socket.doneCompleter.complete(true);
final DaemonMessage disconnectEvent = await broadcastOutput.firstWhere(
(DaemonMessage message) => message.data['event'] != null && message.data['event'] == 'proxy.disconnected.$id',
);
expect(disconnectEvent.data, isNotNull);
}, ioOverrides);
});
testUsingContext('proxy.connect connects to ipv6 if ipv4 failed', () async {
final TestIOOverrides ioOverrides = TestIOOverrides();
await io.IOOverrides.runWithIOOverrides(() async {
final FakeSocket socket = FakeSocket();
bool connectIpv4Called = false;
int? connectPort;
ioOverrides.connectCallback = (Object? host, int port) async {
connectPort = port;
if (host == io.InternetAddress.loopbackIPv4) {
connectIpv4Called = true;
} else if (host == io.InternetAddress.loopbackIPv6) {
return socket;
}
throw const io.SocketException('fail');
};
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'proxy.connect', 'params': <String, Object?>{'port': 123}}));
final Stream<DaemonMessage> broadcastOutput = daemonStreams.outputs.stream.asBroadcastStream();
final DaemonMessage firstResponse = await broadcastOutput.firstWhere(_notEvent);
expect(firstResponse.data['id'], 0);
expect(firstResponse.data['result'], isNotNull);
expect(connectIpv4Called, true);
expect(connectPort, 123);
}, ioOverrides);
});
testUsingContext('proxy.connect fails if both ipv6 and ipv4 failed', () async {
final TestIOOverrides ioOverrides = TestIOOverrides();
await io.IOOverrides.runWithIOOverrides(() async {
ioOverrides.connectCallback = (Object? host, int port) => throw const io.SocketException('fail');
daemon = Daemon(
daemonConnection,
notifyingLogger: notifyingLogger,
);
daemonStreams.inputs.add(DaemonMessage(<String, Object?>{'id': 0, 'method': 'proxy.connect', 'params': <String, Object?>{'port': 123}}));
final Stream<DaemonMessage> broadcastOutput = daemonStreams.outputs.stream.asBroadcastStream();
final DaemonMessage firstResponse = await broadcastOutput.firstWhere(_notEvent);
expect(firstResponse.data['id'], 0);
expect(firstResponse.data['result'], isNull);
expect(firstResponse.data['error'], isNotNull);
}, ioOverrides);
});
});
group('notifyingLogger', () {
late BufferLogger bufferLogger;
setUp(() {
bufferLogger = BufferLogger.test();
});
tearDown(() {
bufferLogger.clear();
});
testUsingContext('outputs trace messages in verbose mode', () async {
final NotifyingLogger logger = NotifyingLogger(verbose: true, parent: bufferLogger);
logger.printTrace('test');
expect(bufferLogger.errorText, contains('test'));
});
testUsingContext('ignores trace messages in non-verbose mode', () async {
final NotifyingLogger logger = NotifyingLogger(verbose: false, parent: bufferLogger);
final Future<LogMessage> messageResult = logger.onMessage.first;
logger.printTrace('test');
logger.printStatus('hello');
final LogMessage message = await messageResult;
expect(message.level, 'status');
expect(message.message, 'hello');
expect(bufferLogger.errorText, isEmpty);
});
testUsingContext('sends trace messages in notify verbose mode', () async {
final NotifyingLogger logger = NotifyingLogger(verbose: false, parent: bufferLogger, notifyVerbose: true);
final Future<LogMessage> messageResult = logger.onMessage.first;
logger.printTrace('hello');
final LogMessage message = await messageResult;
expect(message.level, 'trace');
expect(message.message, 'hello');
expect(bufferLogger.errorText, isEmpty);
});
testUsingContext('buffers messages sent before a subscription', () async {
final NotifyingLogger logger = NotifyingLogger(verbose: false, parent: bufferLogger);
logger.printStatus('hello');
final LogMessage message = await logger.onMessage.first;
expect(message.level, 'status');
expect(message.message, 'hello');
});
testWithoutContext('responds to .supportsColor', () async {
final NotifyingLogger logger = NotifyingLogger(verbose: false, parent: bufferLogger);
expect(logger.supportsColor, isFalse);
});
});
group('daemon queue', () {
late DebounceOperationQueue<int, String> queue;
const Duration debounceDuration = Duration(seconds: 1);
setUp(() {
queue = DebounceOperationQueue<int, String>();
});
testWithoutContext(
'debounces/merges same operation type and returns same result',
() async {
await _runFakeAsync((FakeAsync time) async {
final List<Future<int>> operations = <Future<int>>[
queue.queueAndDebounce('OP1', debounceDuration, () async => 1),
queue.queueAndDebounce('OP1', debounceDuration, () async => 2),
];
time.elapse(debounceDuration * 5);
final List<int> results = await Future.wait(operations);
expect(results, orderedEquals(<int>[1, 1]));
});
});
testWithoutContext('does not merge results outside of the debounce duration',
() async {
await _runFakeAsync((FakeAsync time) async {
final List<Future<int>> operations = <Future<int>>[
queue.queueAndDebounce('OP1', debounceDuration, () async => 1),
Future<void>.delayed(debounceDuration * 2).then((_) =>
queue.queueAndDebounce('OP1', debounceDuration, () async => 2)),
];
time.elapse(debounceDuration * 5);
final List<int> results = await Future.wait(operations);
expect(results, orderedEquals(<int>[1, 2]));
});
});
testWithoutContext('does not merge results of different operations',
() async {
await _runFakeAsync((FakeAsync time) async {
final List<Future<int>> operations = <Future<int>>[
queue.queueAndDebounce('OP1', debounceDuration, () async => 1),
queue.queueAndDebounce('OP2', debounceDuration, () async => 2),
];
time.elapse(debounceDuration * 5);
final List<int> results = await Future.wait(operations);
expect(results, orderedEquals(<int>[1, 2]));
});
});
testWithoutContext('does not run any operations concurrently', () async {
// Crete a function that's slow, but throws if another instance of the
// function is running.
bool isRunning = false;
Future<int> f(int ret) async {
if (isRunning) {
throw Exception('Functions ran concurrently!');
}
isRunning = true;
await Future<void>.delayed(debounceDuration * 2);
isRunning = false;
return ret;
}
await _runFakeAsync((FakeAsync time) async {
final List<Future<int>> operations = <Future<int>>[
queue.queueAndDebounce('OP1', debounceDuration, () => f(1)),
queue.queueAndDebounce('OP2', debounceDuration, () => f(2)),
];
time.elapse(debounceDuration * 5);
final List<int> results = await Future.wait(operations);
expect(results, orderedEquals(<int>[1, 2]));
});
});
});
}
bool _notEvent(DaemonMessage message) => message.data['event'] == null;
bool _isConnectedEvent(DaemonMessage message) => message.data['event'] == 'daemon.connected';
class FakeWindowsWorkflow extends Fake implements WindowsWorkflow {
FakeWindowsWorkflow({ this.canListDevices = true });
@override
final bool canListDevices;
}
class FakeFuchsiaWorkflow extends Fake implements FuchsiaWorkflow {
FakeFuchsiaWorkflow({ this.canListDevices = true });
@override
final bool canListDevices;
}
class FakeAndroidWorkflow extends Fake implements AndroidWorkflow {
FakeAndroidWorkflow({ this.canListDevices = true });
@override
final bool canListDevices;
}
class FakeIOSWorkflow extends Fake implements IOSWorkflow {
FakeIOSWorkflow({ this.canListDevices = true });
@override
final bool canListDevices;
}
class FakeAndroidDevice extends Fake implements AndroidDevice {
@override
final String id = 'device';
@override
final String name = 'android device';
@override
Future<String> get emulatorId async => 'device';
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.android_arm;
@override
Future<bool> get isLocalEmulator async => false;
@override
final Category category = Category.mobile;
@override
final PlatformType platformType = PlatformType.android;
@override
final bool ephemeral = false;
@override
final bool isConnected = true;
@override
final DeviceConnectionInterface connectionInterface = DeviceConnectionInterface.attached;
@override
Future<String> get sdkNameAndVersion async => 'Android 12';
@override
bool get supportsHotReload => true;
@override
bool get supportsHotRestart => true;
@override
bool get supportsScreenshot => true;
@override
bool get supportsFastStart => true;
@override
bool get supportsFlutterExit => true;
@override
Future<bool> get supportsHardwareRendering async => true;
@override
bool get supportsStartPaused => true;
@override
final FakeDartDevelopmentService dds = FakeDartDevelopmentService();
BuildMode? supportsRuntimeModeCalledBuildMode;
@override
Future<bool> supportsRuntimeMode(BuildMode buildMode) async {
supportsRuntimeModeCalledBuildMode = buildMode;
return true;
}
late DeviceLogReader logReader;
@override
FutureOr<DeviceLogReader> getLogReader({
ApplicationPackage? app,
bool includePastLogs = false,
}) => logReader;
ApplicationPackage? startAppPackage;
late LaunchResult launchResult;
@override
Future<LaunchResult> startApp(
ApplicationPackage? package, {
String? mainPath,
String? route,
DebuggingOptions? debuggingOptions,
Map<String, Object?> platformArgs = const <String, Object>{},
bool prebuiltApplication = false,
bool ipv6 = false,
String? userIdentifier,
}) async {
startAppPackage = package;
return launchResult;
}
ApplicationPackage? stopAppPackage;
@override
Future<bool> stopApp(
ApplicationPackage? app, {
String? userIdentifier,
}) async {
stopAppPackage = app;
return true;
}
}
class FakeDartDevelopmentService extends Fake implements DartDevelopmentService {
bool startCalled = false;
late Uri startVMServiceUri;
bool? startDisableServiceAuthCodes;
bool shutdownCalled = false;
@override
late Future<void> done;
@override
Uri? uri;
@override
Future<void> startDartDevelopmentService(
Uri vmServiceUri, {
required Logger logger,
int? hostPort,
bool? ipv6,
bool? disableServiceAuthCodes,
bool cacheStartupProfile = false,
}) async {
startCalled = true;
startVMServiceUri = vmServiceUri;
startDisableServiceAuthCodes = disableServiceAuthCodes;
}
@override
Future<void> shutdown() async {
shutdownCalled = true;
}
}
class FakeDeviceLogReader implements DeviceLogReader {
final StreamController<String> logLinesController = StreamController<String>();
bool disposeCalled = false;
@override
int? appPid;
@override
FlutterVmService? connectedVMService;
@override
void dispose() {
disposeCalled = true;
}
@override
Stream<String> get logLines => logLinesController.stream;
@override
String get name => 'device';
}
class FakeDevtoolsLauncher extends Fake implements DevtoolsLauncher {
FakeDevtoolsLauncher(this._serverAddress);
final DevToolsServerAddress? _serverAddress;
@override
Future<DevToolsServerAddress?> serve() async => _serverAddress;
@override
Future<void> close() async {}
}
class FakeApplicationPackageFactory implements ApplicationPackageFactory {
TargetPlatform? platformRequested;
File? applicationBinaryRequested;
ApplicationPackage? applicationPackage;
@override
Future<ApplicationPackage?> getPackageForPlatform(TargetPlatform platform, {BuildInfo? buildInfo, File? applicationBinary}) async {
platformRequested = platform;
applicationBinaryRequested = applicationBinary;
return applicationPackage;
}
}
class FakeApplicationPackage extends Fake implements ApplicationPackage {}
class TestIOOverrides extends io.IOOverrides {
late Future<io.Socket> Function(Object? host, int port) connectCallback;
@override
Future<io.Socket> socketConnect(Object? host, int port,
{Object? sourceAddress, int sourcePort = 0, Duration? timeout}) {
return connectCallback(host, port);
}
}
class FakeSocket extends Fake implements io.Socket {
bool closeCalled = false;
final StreamController<Uint8List> controller = StreamController<Uint8List>();
final List<List<int>> addedData = <List<int>>[];
final Completer<bool> doneCompleter = Completer<bool>();
@override
StreamSubscription<Uint8List> listen(
void Function(Uint8List event)? onData, {
Function? onError,
void Function()? onDone,
bool? cancelOnError,
}) {
return controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
@override
void add(List<int> data) {
addedData.add(data);
}
@override
Future<void> close() async {
closeCalled = true;
}
@override
Future<bool> get done => doneCompleter.future;
@override
void destroy() {}
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart",
"repo_id": "flutter",
"token_count": 19772
} | 819 |
// 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:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/terminal.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/daemon.dart';
import 'package:flutter_tools/src/commands/run.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/ios/devices.dart';
import 'package:flutter_tools/src/macos/macos_ipad_device.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/run_hot.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:test/fake.dart';
import 'package:unified_analytics/unified_analytics.dart' as analytics;
import 'package:vm_service/vm_service.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_devices.dart';
import '../../src/fakes.dart';
import '../../src/test_flutter_command_runner.dart';
void main() {
setUpAll(() {
Cache.disableLocking();
});
group('run', () {
late BufferLogger logger;
late TestDeviceManager testDeviceManager;
late FileSystem fileSystem;
setUp(() {
logger = BufferLogger.test();
testDeviceManager = TestDeviceManager(logger: logger);
fileSystem = MemoryFileSystem.test();
});
testUsingContext('fails when target not found', () async {
final RunCommand command = RunCommand();
expect(
() => createTestCommandRunner(command).run(<String>['run', '-t', 'abc123', '--no-pub']),
throwsA(isA<ToolExit>().having((ToolExit error) => error.exitCode, 'exitCode', anyOf(isNull, 1))),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
});
testUsingContext('does not support --no-sound-null-safety by default', () async {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final TestRunCommandThatOnlyValidates command = TestRunCommandThatOnlyValidates();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--use-application-binary=app/bar/faz',
'--no-sound-null-safety',
]),
throwsA(isException.having(
(Exception exception) => exception.toString(),
'toString',
contains('Could not find an option named "no-sound-null-safety"'),
)),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
});
testUsingContext('supports --no-sound-null-safety with an overridden NonNullSafeBuilds', () async {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final FakeDevice device = FakeDevice(isLocalEmulator: true, platformType: PlatformType.android);
testDeviceManager.devices = <Device>[device];
final TestRunCommandThatOnlyValidates command = TestRunCommandThatOnlyValidates();
await createTestCommandRunner(command).run(const <String>[
'run',
'--use-application-binary=app/bar/faz',
'--no-sound-null-safety',
]);
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
FileSystem: () => fileSystem,
Logger: () => logger,
NonNullSafeBuilds: () => NonNullSafeBuilds.allowed,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('does not support "--use-application-binary" and "--fast-start"', () async {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--use-application-binary=app/bar/faz',
'--fast-start',
'--no-pub',
'--show-test-device',
]),
throwsA(isException.having(
(Exception exception) => exception.toString(),
'toString',
isNot(contains('--fast-start is not supported with --use-application-binary')),
)),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
});
testUsingContext('Walks upward looking for a pubspec.yaml and succeeds if found', () async {
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages')
.writeAsStringSync('\n');
fileSystem.file('lib/main.dart')
.createSync(recursive: true);
fileSystem.currentDirectory = fileSystem.directory('a/b/c')
..createSync(recursive: true);
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
]),
throwsToolExit(),
);
final BufferLogger bufferLogger = globals.logger as BufferLogger;
expect(
bufferLogger.statusText,
containsIgnoringWhitespace('Changing current working directory to:'),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
});
testUsingContext('Walks upward looking for a pubspec.yaml and exits if missing', () async {
fileSystem.currentDirectory = fileSystem.directory('a/b/c')
..createSync(recursive: true);
fileSystem.file('lib/main.dart')
.createSync(recursive: true);
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
]),
throwsToolExit(message: 'No pubspec.yaml file found'),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
});
group('run app', () {
late MemoryFileSystem fs;
late Artifacts artifacts;
late TestUsage usage;
late FakeAnsiTerminal fakeTerminal;
late analytics.FakeAnalytics fakeAnalytics;
setUpAll(() {
Cache.disableLocking();
});
setUp(() {
fakeTerminal = FakeAnsiTerminal();
artifacts = Artifacts.test();
usage = TestUsage();
fs = MemoryFileSystem.test();
fs.currentDirectory.childFile('pubspec.yaml')
.writeAsStringSync('name: flutter_app');
fs.currentDirectory.childFile('.packages')
.writeAsStringSync('# Generated by pub on 2019-11-25 12:38:01.801784.');
final Directory libDir = fs.currentDirectory.childDirectory('lib');
libDir.createSync();
final File mainFile = libDir.childFile('main.dart');
mainFile.writeAsStringSync('void main() {}');
fakeAnalytics = getInitializedFakeAnalyticsInstance(
fs: fs,
fakeFlutterVersion: FakeFlutterVersion(),
);
});
testUsingContext('exits with a user message when no supported devices attached', () async {
final RunCommand command = RunCommand();
testDeviceManager.devices = <Device>[];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
]),
throwsA(isA<ToolExit>().having((ToolExit error) => error.message, 'message', isNull)),
);
expect(
testLogger.statusText,
containsIgnoringWhitespace('No supported devices connected.'),
);
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('Using flutter run -d with MacOSDesignedForIPadDevices throws an error', () async {
final RunCommand command = RunCommand();
testDeviceManager.devices = <Device>[FakeMacDesignedForIpadDevice()];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'-d',
'mac-designed-for-ipad',
]), throwsToolExit(message: 'Mac Designed for iPad is currently not supported for flutter run -d'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
DeviceManager: () => testDeviceManager,
Stdio: () => FakeStdio(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('Using flutter run -d all with a single MacOSDesignedForIPadDevices throws a tool error', () async {
final RunCommand command = RunCommand();
testDeviceManager.devices = <Device>[FakeMacDesignedForIpadDevice()];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'-d',
'all',
]), throwsToolExit(message: 'Mac Designed for iPad is currently not supported for flutter run -d'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
DeviceManager: () => testDeviceManager,
Stdio: () => FakeStdio(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('Using flutter run -d all with MacOSDesignedForIPadDevices removes from device list, and attempts to launch', () async {
final RunCommand command = TestRunCommandThatOnlyValidates();
testDeviceManager.devices = <Device>[FakeMacDesignedForIpadDevice(), FakeDevice()];
await createTestCommandRunner(command).run(<String>[
'run',
'-d',
'all',
]);
expect(command.devices?.length, 1);
expect(command.devices?.single.id, 'fake_device');
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
DeviceManager: () => testDeviceManager,
Stdio: () => FakeStdio(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('exits and lists available devices when specified device not found', () async {
final RunCommand command = RunCommand();
final FakeDevice device = FakeDevice(isLocalEmulator: true);
testDeviceManager
..devices = <Device>[device]
..specifiedDeviceId = 'invalid-device-id';
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'-d',
'invalid-device-id',
'--no-pub',
'--no-hot',
]),
throwsToolExit(),
);
expect(testLogger.statusText, contains("No supported devices found with name or id matching 'invalid-device-id'"));
expect(testLogger.statusText, contains('The following devices were found:'));
expect(testLogger.statusText, contains('FakeDevice (mobile) • fake_device • ios • (simulator)'));
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('fails when targeted device is not Android with --device-user', () async {
final FakeDevice device = FakeDevice(isLocalEmulator: true);
testDeviceManager.devices = <Device>[device];
final TestRunCommandThatOnlyValidates command = TestRunCommandThatOnlyValidates();
await expectLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--device-user',
'10',
]), throwsToolExit(message: '--device-user is only supported for Android. At least one Android device is required.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
DeviceManager: () => testDeviceManager,
Stdio: () => FakeStdio(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('succeeds when targeted device is an Android device with --device-user', () async {
final FakeDevice device = FakeDevice(isLocalEmulator: true, platformType: PlatformType.android);
testDeviceManager.devices = <Device>[device];
final TestRunCommandThatOnlyValidates command = TestRunCommandThatOnlyValidates();
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--device-user',
'10',
]);
// Finishes normally without error.
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
DeviceManager: () => testDeviceManager,
Stdio: () => FakeStdio(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('shows unsupported devices when no supported devices are found', () async {
final RunCommand command = RunCommand();
final FakeDevice mockDevice = FakeDevice(
targetPlatform: TargetPlatform.android_arm,
isLocalEmulator: true,
sdkNameAndVersion: 'api-14',
isSupported: false,
);
testDeviceManager.devices = <Device>[mockDevice];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
]),
throwsA(isA<ToolExit>().having((ToolExit error) => error.message, 'message', isNull)),
);
expect(
testLogger.statusText,
containsIgnoringWhitespace('No supported devices connected.'),
);
expect(
testLogger.statusText,
containsIgnoringWhitespace('The following devices were found, but are not supported by this project:'),
);
expect(
testLogger.statusText,
containsIgnoringWhitespace(
globals.userMessages.flutterMissPlatformProjects(
Device.devicesPlatformTypes(<Device>[mockDevice]),
),
),
);
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('prints warning when --flavor is used with an unsupported target platform', () async {
const List<String> runCommand = <String>[
'run',
'--no-pub',
'--no-hot',
'--flavor=vanilla',
'-d',
'all',
];
// Useful for test readability.
// ignore: avoid_redundant_argument_values
final FakeDevice deviceWithoutFlavorSupport = FakeDevice(supportsFlavors: false);
final FakeDevice deviceWithFlavorSupport = FakeDevice(supportsFlavors: true);
testDeviceManager.devices = <Device>[deviceWithoutFlavorSupport, deviceWithFlavorSupport];
await createTestCommandRunner(TestRunCommandThatOnlyValidates()).run(runCommand);
expect(logger.warningText, contains(
'--flavor is only supported for Android, macOS, and iOS devices. '
'Flavor-related features may not function properly and could '
'behave differently in a future release.'
));
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
Logger: () => logger,
});
testUsingContext('forwards --uninstall-only to DebuggingOptions', () async {
final RunCommand command = RunCommand();
final FakeDevice mockDevice = FakeDevice(
sdkNameAndVersion: 'iOS 13',
)..startAppSuccess = false;
testDeviceManager.devices = <Device>[mockDevice];
// Causes swift to be detected in the analytics.
fs.currentDirectory.childDirectory('ios').childFile('AppDelegate.swift').createSync(recursive: true);
await expectToolExitLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'--uninstall-first',
]), isNull);
final DebuggingOptions options = await command.createDebuggingOptions(false);
expect(options.uninstallFirst, isTrue);
}, overrides: <Type, Generator>{
Artifacts: () => artifacts,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Usage: () => usage,
});
testUsingContext('passes device target platform to usage', () async {
final RunCommand command = RunCommand();
final FakeDevice mockDevice = FakeDevice(sdkNameAndVersion: 'iOS 13')
..startAppSuccess = false;
testDeviceManager.devices = <Device>[mockDevice];
// Causes swift to be detected in the analytics.
fs.currentDirectory.childDirectory('ios').childFile('AppDelegate.swift').createSync(recursive: true);
await expectToolExitLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
]), isNull);
expect(usage.commands, contains(
TestUsageCommand('run', parameters: CustomDimensions.fromMap(<String, String>{
'cd3': 'false', 'cd4': 'ios', 'cd22': 'iOS 13',
'cd23': 'debug', 'cd18': 'false', 'cd15': 'swift', 'cd31': 'true',
'cd57': 'usb',
'cd58': 'false',
})
)));
expect(
fakeAnalytics.sentEvents,
contains(
analytics.Event.commandUsageValues(
workflow: 'run',
commandHasTerminal: globals.stdio.hasTerminal,
runIsEmulator: false,
runTargetName: 'ios',
runTargetOsVersion: 'iOS 13',
runModeName: 'debug',
runProjectModule: false,
runProjectHostLanguage: 'swift',
runIOSInterfaceType: 'usb',
runIsTest: false,
),
),
);
}, overrides: <Type, Generator>{
AnsiTerminal: () => fakeTerminal,
Artifacts: () => artifacts,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Stdio: () => FakeStdio(),
Usage: () => usage,
analytics.Analytics: () => fakeAnalytics,
});
testUsingContext('correctly reports tests to usage', () async {
fs.currentDirectory.childDirectory('test').childFile('widget_test.dart').createSync(recursive: true);
fs.currentDirectory.childDirectory('ios').childFile('AppDelegate.swift').createSync(recursive: true);
final RunCommand command = RunCommand();
final FakeDevice mockDevice = FakeDevice(sdkNameAndVersion: 'iOS 13')
..startAppSuccess = false;
testDeviceManager.devices = <Device>[mockDevice];
await expectToolExitLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'test/widget_test.dart',
]), isNull);
expect(usage.commands, contains(
TestUsageCommand('run', parameters: CustomDimensions.fromMap(<String, String>{
'cd3': 'false', 'cd4': 'ios', 'cd22': 'iOS 13',
'cd23': 'debug', 'cd18': 'false', 'cd15': 'swift', 'cd31': 'true',
'cd57': 'usb',
'cd58': 'true',
})),
));
expect(
fakeAnalytics.sentEvents,
contains(
analytics.Event.commandUsageValues(
workflow: 'run',
commandHasTerminal: globals.stdio.hasTerminal,
runIsEmulator: false,
runTargetName: 'ios',
runTargetOsVersion: 'iOS 13',
runModeName: 'debug',
runProjectModule: false,
runProjectHostLanguage: 'swift',
runIOSInterfaceType: 'usb',
runIsTest: true,
),
),
);
}, overrides: <Type, Generator>{
AnsiTerminal: () => fakeTerminal,
Artifacts: () => artifacts,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Stdio: () => FakeStdio(),
Usage: () => usage,
analytics.Analytics: () => fakeAnalytics,
});
group('--machine', () {
testUsingContext('can pass --device-user', () async {
final DaemonCapturingRunCommand command = DaemonCapturingRunCommand();
final FakeDevice device = FakeDevice(platformType: PlatformType.android);
testDeviceManager.devices = <Device>[device];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--machine',
'--device-user',
'10',
'-d',
device.id,
]),
throwsToolExit(),
);
expect(command.appDomain.userIdentifier, '10');
}, overrides: <Type, Generator>{
Artifacts: () => artifacts,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Usage: () => usage,
Stdio: () => FakeStdio(),
Logger: () => AppRunLogger(parent: logger),
});
testUsingContext('can disable devtools with --no-devtools', () async {
final DaemonCapturingRunCommand command = DaemonCapturingRunCommand();
final FakeDevice device = FakeDevice();
testDeviceManager.devices = <Device>[device];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-devtools',
'--machine',
'-d',
device.id,
]),
throwsToolExit(),
);
expect(command.appDomain.enableDevTools, isFalse);
}, overrides: <Type, Generator>{
Artifacts: () => artifacts,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Usage: () => usage,
Stdio: () => FakeStdio(),
Logger: () => AppRunLogger(parent: logger),
});
});
});
group('Fatal Logs', () {
late TestRunCommandWithFakeResidentRunner command;
late MemoryFileSystem fs;
setUp(() {
command = TestRunCommandWithFakeResidentRunner()
..fakeResidentRunner = FakeResidentRunner();
fs = MemoryFileSystem.test();
});
testUsingContext("doesn't fail if --fatal-warnings specified and no warnings occur", () async {
try {
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'--${FlutterOptions.kFatalWarnings}',
]);
} on Exception {
fail('Unexpected exception thrown');
}
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext("doesn't fail if --fatal-warnings not specified", () async {
testLogger.printWarning('Warning: Mild annoyance Will Robinson!');
try {
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
]);
} on Exception {
fail('Unexpected exception thrown');
}
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails if --fatal-warnings specified and warnings emitted', () async {
testLogger.printWarning('Warning: Mild annoyance Will Robinson!');
await expectLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received warning output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails if --fatal-warnings specified and errors emitted', () async {
testLogger.printError('Error: Danger Will Robinson!');
await expectLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received error output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
});
testUsingContext('should only request artifacts corresponding to connected devices', () async {
testDeviceManager.devices = <Device>[FakeDevice(targetPlatform: TargetPlatform.android_arm)];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
DevelopmentArtifact.androidGenSnapshot,
}));
testDeviceManager.devices = <Device>[FakeDevice()];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
DevelopmentArtifact.iOS,
}));
testDeviceManager.devices = <Device>[
FakeDevice(),
FakeDevice(targetPlatform: TargetPlatform.android_arm),
];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
DevelopmentArtifact.iOS,
DevelopmentArtifact.androidGenSnapshot,
}));
testDeviceManager.devices = <Device>[
FakeDevice(targetPlatform: TargetPlatform.web_javascript),
];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
DevelopmentArtifact.web,
}));
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
group('usageValues', () {
testUsingContext('with only non-iOS usb device', () async {
final List<Device> devices = <Device>[
FakeDevice(targetPlatform: TargetPlatform.android_arm, platformType: PlatformType.android),
];
final TestRunCommandForUsageValues command = TestRunCommandForUsageValues(devices: devices);
final CommandRunner<void> runner = createTestCommandRunner(command);
try {
// run the command so that CLI args are parsed
await runner.run(<String>['run']);
} on ToolExit catch (error) {
// we can ignore the ToolExit, as we are only interested in
// command.usageValues.
expect(
error,
isA<ToolExit>().having(
(ToolExit exception) => exception.message,
'message',
contains('No pubspec.yaml file found'),
),
);
}
final CustomDimensions dimensions = await command.usageValues;
expect(dimensions, const CustomDimensions(
commandRunIsEmulator: false,
commandRunTargetName: 'android-arm',
commandRunTargetOsVersion: '',
commandRunModeName: 'debug',
commandRunProjectModule: false,
commandRunProjectHostLanguage: '',
commandRunIsTest: false,
));
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('with only iOS usb device', () async {
final List<Device> devices = <Device>[
FakeIOSDevice(sdkNameAndVersion: 'iOS 16.2'),
];
final TestRunCommandForUsageValues command = TestRunCommandForUsageValues(devices: devices);
final CommandRunner<void> runner = createTestCommandRunner(command);
try {
// run the command so that CLI args are parsed
await runner.run(<String>['run']);
} on ToolExit catch (error) {
// we can ignore the ToolExit, as we are only interested in
// command.usageValues.
expect(
error,
isA<ToolExit>().having(
(ToolExit exception) => exception.message,
'message',
contains('No pubspec.yaml file found'),
),
);
}
final CustomDimensions dimensions = await command.usageValues;
expect(dimensions, const CustomDimensions(
commandRunIsEmulator: false,
commandRunTargetName: 'ios',
commandRunTargetOsVersion: 'iOS 16.2',
commandRunModeName: 'debug',
commandRunProjectModule: false,
commandRunProjectHostLanguage: '',
commandRunIOSInterfaceType: 'usb',
commandRunIsTest: false,
));
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('with only iOS wireless device', () async {
final List<Device> devices = <Device>[
FakeIOSDevice(
connectionInterface: DeviceConnectionInterface.wireless,
sdkNameAndVersion: 'iOS 16.2',
),
];
final TestRunCommandForUsageValues command = TestRunCommandForUsageValues(devices: devices);
final CommandRunner<void> runner = createTestCommandRunner(command);
try {
// run the command so that CLI args are parsed
await runner.run(<String>['run']);
} on ToolExit catch (error) {
// we can ignore the ToolExit, as we are only interested in
// command.usageValues.
expect(
error,
isA<ToolExit>().having(
(ToolExit exception) => exception.message,
'message',
contains('No pubspec.yaml file found'),
),
);
}
final CustomDimensions dimensions = await command.usageValues;
expect(dimensions, const CustomDimensions(
commandRunIsEmulator: false,
commandRunTargetName: 'ios',
commandRunTargetOsVersion: 'iOS 16.2',
commandRunModeName: 'debug',
commandRunProjectModule: false,
commandRunProjectHostLanguage: '',
commandRunIOSInterfaceType: 'wireless',
commandRunIsTest: false,
));
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('with both iOS usb and wireless devices', () async {
final List<Device> devices = <Device>[
FakeIOSDevice(
connectionInterface: DeviceConnectionInterface.wireless,
sdkNameAndVersion: 'iOS 16.2',
),
FakeIOSDevice(sdkNameAndVersion: 'iOS 16.2'),
];
final TestRunCommandForUsageValues command = TestRunCommandForUsageValues(devices: devices);
final CommandRunner<void> runner = createTestCommandRunner(command);
try {
// run the command so that CLI args are parsed
await runner.run(<String>['run']);
} on ToolExit catch (error) {
// we can ignore the ToolExit, as we are only interested in
// command.usageValues.
expect(
error,
isA<ToolExit>().having(
(ToolExit exception) => exception.message,
'message',
contains('No pubspec.yaml file found'),
),
);
}
final CustomDimensions dimensions = await command.usageValues;
expect(dimensions, const CustomDimensions(
commandRunIsEmulator: false,
commandRunTargetName: 'multiple',
commandRunTargetOsVersion: 'multiple',
commandRunModeName: 'debug',
commandRunProjectModule: false,
commandRunProjectHostLanguage: '',
commandRunIOSInterfaceType: 'wireless',
commandRunIsTest: false,
));
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
});
group('--web-header', () {
setUp(() {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final FakeDevice device = FakeDevice(isLocalEmulator: true, platformType: PlatformType.android);
testDeviceManager.devices = <Device>[device];
});
testUsingContext('can accept simple, valid values', () async {
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub', '--no-hot',
'--web-header', 'foo = bar',
]), throwsToolExit());
final DebuggingOptions options = await command.createDebuggingOptions(true);
expect(options.webHeaders, <String, String>{'foo': 'bar'});
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
DeviceManager: () => testDeviceManager,
});
testUsingContext('throws a ToolExit when no value is provided', () async {
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub', '--no-hot',
'--web-header',
'foo',
]), throwsToolExit(message: 'Invalid web headers: foo'));
await expectLater(
() => command.createDebuggingOptions(true),
throwsToolExit(),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
DeviceManager: () => testDeviceManager,
});
testUsingContext('throws a ToolExit when value includes delimiter characters', () async {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub', '--no-hot',
'--web-header', 'hurray/headers=flutter',
]), throwsToolExit());
await expectLater(
() => command.createDebuggingOptions(true),
throwsToolExit(message: 'Invalid web headers: hurray/headers=flutter'),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
DeviceManager: () => testDeviceManager,
});
testUsingContext('accepts headers with commas in them', () async {
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub', '--no-hot',
'--web-header', 'hurray=flutter,flutter=hurray',
]), throwsToolExit());
final DebuggingOptions options = await command.createDebuggingOptions(true);
expect(options.webHeaders, <String, String>{
'hurray': 'flutter,flutter=hurray'
});
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
DeviceManager: () => testDeviceManager,
});
});
});
group('terminal', () {
late FakeAnsiTerminal fakeTerminal;
setUp(() {
fakeTerminal = FakeAnsiTerminal();
});
testUsingContext('Flutter run sets terminal singleCharMode to false on exit', () async {
final FakeResidentRunner residentRunner = FakeResidentRunner();
final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner();
command.fakeResidentRunner = residentRunner;
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
]);
// The sync completer where we initially set `terminal.singleCharMode` to
// `true` does not execute in unit tests, so explicitly check the
// `setSingleCharModeHistory` that the finally block ran, setting this
// back to `false`.
expect(fakeTerminal.setSingleCharModeHistory, contains(false));
}, overrides: <Type, Generator>{
AnsiTerminal: () => fakeTerminal,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Flutter run catches StdinException while setting terminal singleCharMode to false', () async {
fakeTerminal.hasStdin = false;
final FakeResidentRunner residentRunner = FakeResidentRunner();
final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner();
command.fakeResidentRunner = residentRunner;
try {
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
]);
} catch (err) { // ignore: avoid_catches_without_on_clauses
fail('Expected no error, got $err');
}
expect(fakeTerminal.setSingleCharModeHistory, isEmpty);
}, overrides: <Type, Generator>{
AnsiTerminal: () => fakeTerminal,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
});
testUsingContext('Flutter run catches service has disappear errors and throws a tool exit', () async {
final FakeResidentRunner residentRunner = FakeResidentRunner();
residentRunner.rpcError = RPCError('flutter._listViews', RPCErrorCodes.kServiceDisappeared, '');
final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner();
command.fakeResidentRunner = residentRunner;
await expectToolExitLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
]), contains('Lost connection to device.'));
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Flutter run does not catch other RPC errors', () async {
final FakeResidentRunner residentRunner = FakeResidentRunner();
residentRunner.rpcError = RPCError('flutter._listViews', RPCErrorCodes.kInvalidParams, '');
final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner();
command.fakeResidentRunner = residentRunner;
await expectLater(() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
]), throwsA(isA<RPCError>()));
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Passes sksl bundle info the build options', () async {
final TestRunCommandWithFakeResidentRunner command = TestRunCommandWithFakeResidentRunner();
await expectLater(() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--bundle-sksl-path=foo.json',
]), throwsToolExit(message: 'No SkSL shader bundle found at foo.json'));
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Configures web connection options to use web sockets by default', () async {
final RunCommand command = RunCommand();
await expectLater(() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
]), throwsToolExit());
final DebuggingOptions options = await command.createDebuggingOptions(true);
expect(options.webUseSseForDebugBackend, false);
expect(options.webUseSseForDebugProxy, false);
expect(options.webUseSseForInjectedClient, false);
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('flags propagate to debugging options', () async {
final RunCommand command = RunCommand();
await expectLater(() => createTestCommandRunner(command).run(<String>[
'run',
'--start-paused',
'--disable-service-auth-codes',
'--use-test-fonts',
'--trace-skia',
'--trace-systrace',
'--trace-to-file=path/to/trace.binpb',
'--verbose-system-logs',
'--null-assertions',
'--native-null-assertions',
'--enable-impeller',
'--enable-vulkan-validation',
'--trace-systrace',
'--enable-software-rendering',
'--skia-deterministic-rendering',
'--enable-embedder-api',
'--ci',
'--debug-logs-dir=path/to/logs'
]), throwsToolExit());
final DebuggingOptions options = await command.createDebuggingOptions(false);
expect(options.startPaused, true);
expect(options.disableServiceAuthCodes, true);
expect(options.useTestFonts, true);
expect(options.traceSkia, true);
expect(options.traceSystrace, true);
expect(options.traceToFile, 'path/to/trace.binpb');
expect(options.verboseSystemLogs, true);
expect(options.nullAssertions, true);
expect(options.nativeNullAssertions, true);
expect(options.traceSystrace, true);
expect(options.enableImpeller, ImpellerStatus.enabled);
expect(options.enableVulkanValidation, true);
expect(options.enableSoftwareRendering, true);
expect(options.skiaDeterministicRendering, true);
expect(options.usingCISystem, true);
expect(options.debugLogsDirectoryPath, 'path/to/logs');
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails when "--web-launch-url" is not supported', () async {
final RunCommand command = RunCommand();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--web-launch-url=http://flutter.dev',
]),
throwsA(isException.having(
(Exception exception) => exception.toString(),
'toString',
isNot(contains('web-launch-url')),
)),
);
final DebuggingOptions options = await command.createDebuggingOptions(true);
expect(options.webLaunchUrl, 'http://flutter.dev');
final RegExp pattern = RegExp(r'^((http)?:\/\/)[^\s]+');
expect(pattern.hasMatch(options.webLaunchUrl!), true);
}, overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.any(),
Logger: () => BufferLogger.test(),
});
}
class TestDeviceManager extends DeviceManager {
TestDeviceManager({required super.logger});
List<Device> devices = <Device>[];
@override
List<DeviceDiscovery> get deviceDiscoverers {
final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
devices.forEach(discoverer.addDevice);
return <DeviceDiscovery>[discoverer];
}
}
class FakeDevice extends Fake implements Device {
FakeDevice({
bool isLocalEmulator = false,
TargetPlatform targetPlatform = TargetPlatform.ios,
String sdkNameAndVersion = '',
PlatformType platformType = PlatformType.ios,
bool isSupported = true,
bool supportsFlavors = false,
}): _isLocalEmulator = isLocalEmulator,
_targetPlatform = targetPlatform,
_sdkNameAndVersion = sdkNameAndVersion,
_platformType = platformType,
_isSupported = isSupported,
_supportsFlavors = supportsFlavors;
static const int kSuccess = 1;
static const int kFailure = -1;
final TargetPlatform _targetPlatform;
final bool _isLocalEmulator;
final String _sdkNameAndVersion;
final PlatformType _platformType;
final bool _isSupported;
final bool _supportsFlavors;
@override
Category get category => Category.mobile;
@override
String get id => 'fake_device';
Never _throwToolExit(int code) => throwToolExit('FakeDevice tool exit', exitCode: code);
@override
Future<bool> get isLocalEmulator => Future<bool>.value(_isLocalEmulator);
@override
bool supportsRuntimeMode(BuildMode mode) => true;
@override
Future<bool> get supportsHardwareRendering async => true;
@override
bool supportsHotReload = false;
@override
bool get supportsHotRestart => true;
@override
bool get supportsFastStart => false;
@override
bool get supportsFlavors => _supportsFlavors;
@override
bool get ephemeral => true;
@override
bool get isConnected => true;
@override
DeviceConnectionInterface get connectionInterface =>
DeviceConnectionInterface.attached;
bool supported = true;
@override
bool isSupportedForProject(FlutterProject flutterProject) => _isSupported;
@override
bool isSupported() => supported;
@override
Future<String> get sdkNameAndVersion => Future<String>.value(_sdkNameAndVersion);
@override
Future<String> get targetPlatformDisplayName async =>
getNameForTargetPlatform(await targetPlatform);
@override
DeviceLogReader getLogReader({
ApplicationPackage? app,
bool includePastLogs = false,
}) {
return FakeDeviceLogReader();
}
@override
String get name => 'FakeDevice';
@override
Future<TargetPlatform> get targetPlatform async => _targetPlatform;
@override
PlatformType get platformType => _platformType;
late bool startAppSuccess;
@override
DevFSWriter? createDevFSWriter(
ApplicationPackage? app,
String? userIdentifier,
) {
return null;
}
@override
Future<LaunchResult> startApp(
ApplicationPackage? package, {
String? mainPath,
String? route,
required DebuggingOptions debuggingOptions,
Map<String, Object?> platformArgs = const <String, Object?>{},
bool prebuiltApplication = false,
bool usesTerminalUi = true,
bool ipv6 = false,
String? userIdentifier,
}) async {
if (!startAppSuccess) {
return LaunchResult.failed();
}
if (startAppSuccess) {
return LaunchResult.succeeded();
}
final String dartFlags = debuggingOptions.dartFlags;
// In release mode, --dart-flags should be set to the empty string and
// provided flags should be dropped. In debug and profile modes,
// --dart-flags should not be empty.
if (debuggingOptions.buildInfo.isRelease) {
if (dartFlags.isNotEmpty) {
_throwToolExit(kFailure);
}
_throwToolExit(kSuccess);
} else {
if (dartFlags.isEmpty) {
_throwToolExit(kFailure);
}
_throwToolExit(kSuccess);
}
}
}
class FakeMacDesignedForIpadDevice extends Fake implements MacOSDesignedForIPadDevice {
@override
String get id => 'mac-designed-for-ipad';
@override
bool get isConnected => true;
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.darwin;
@override
DeviceConnectionInterface connectionInterface = DeviceConnectionInterface.attached;
@override
bool isSupported() => true;
@override
bool isSupportedForProject(FlutterProject project) => true;
}
class FakeIOSDevice extends Fake implements IOSDevice {
FakeIOSDevice({
this.connectionInterface = DeviceConnectionInterface.attached,
bool isLocalEmulator = false,
String sdkNameAndVersion = '',
}): _isLocalEmulator = isLocalEmulator,
_sdkNameAndVersion = sdkNameAndVersion;
final bool _isLocalEmulator;
final String _sdkNameAndVersion;
@override
Future<bool> get isLocalEmulator => Future<bool>.value(_isLocalEmulator);
@override
Future<String> get sdkNameAndVersion => Future<String>.value(_sdkNameAndVersion);
@override
final DeviceConnectionInterface connectionInterface;
@override
bool get isWirelesslyConnected =>
connectionInterface == DeviceConnectionInterface.wireless;
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios;
}
class TestRunCommandForUsageValues extends RunCommand {
TestRunCommandForUsageValues({
List<Device>? devices,
}) {
this.devices = devices;
}
@override
Future<BuildInfo> getBuildInfo({ BuildMode? forcedBuildMode, File? forcedTargetFile }) async {
return const BuildInfo(BuildMode.debug, null, treeShakeIcons: false);
}
}
class TestRunCommandWithFakeResidentRunner extends RunCommand {
late FakeResidentRunner fakeResidentRunner;
@override
Future<ResidentRunner> createRunner({
required bool hotMode,
required List<FlutterDevice> flutterDevices,
required String? applicationBinaryPath,
required FlutterProject flutterProject,
}) async {
return fakeResidentRunner;
}
@override
// ignore: must_call_super
Future<void> validateCommand() async {
devices = <Device>[FakeDevice()..supportsHotReload = true];
}
}
class TestRunCommandThatOnlyValidates extends RunCommand {
@override
Future<FlutterCommandResult> runCommand() async {
return FlutterCommandResult.success();
}
@override
bool get shouldRunPub => false;
}
class FakeResidentRunner extends Fake implements ResidentRunner {
RPCError? rpcError;
@override
Future<int> run({
Completer<DebugConnectionInfo>? connectionInfoCompleter,
Completer<void>? appStartedCompleter,
bool enableDevTools = false,
String? route,
}) async {
await null;
if (rpcError != null) {
throw rpcError!;
}
return 0;
}
}
class DaemonCapturingRunCommand extends RunCommand {
late Daemon daemon;
late CapturingAppDomain appDomain;
@override
Daemon createMachineDaemon() {
daemon = super.createMachineDaemon();
appDomain = daemon.appDomain = CapturingAppDomain(daemon);
daemon.registerDomain(appDomain);
return daemon;
}
}
class CapturingAppDomain extends AppDomain {
CapturingAppDomain(super.daemon);
String? userIdentifier;
bool? enableDevTools;
@override
Future<AppInstance> startApp(
Device device,
String projectDirectory,
String target,
String? route,
DebuggingOptions options,
bool enableHotReload, {
File? applicationBinary,
required bool trackWidgetCreation,
String? projectRootPath,
String? packagesFilePath,
String? dillOutputPath,
bool ipv6 = false,
String? isolateFilter,
bool machine = true,
String? userIdentifier,
bool enableDevTools = true,
String? flavor,
HotRunnerNativeAssetsBuilder? nativeAssetsBuilder,
}) async {
this.userIdentifier = userIdentifier;
this.enableDevTools = enableDevTools;
throwToolExit('');
}
}
class FakeAnsiTerminal extends Fake implements AnsiTerminal {
/// Setting to false will cause operations to Stdin to throw a [StdinException].
bool hasStdin = true;
@override
bool usesTerminalUi = false;
/// A list of all the calls to the [singleCharMode] setter.
List<bool> setSingleCharModeHistory = <bool>[];
@override
set singleCharMode(bool value) {
if (!hasStdin) {
throw const StdinException('Error setting terminal line mode', OSError('The handle is invalid', 6));
}
setSingleCharModeHistory.add(value);
}
@override
bool get singleCharMode => setSingleCharModeHistory.last;
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/run_test.dart",
"repo_id": "flutter",
"token_count": 21540
} | 820 |
// 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/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/upgrade.dart';
import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/persistent_tool_state.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/version.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart';
import '../../src/test_flutter_command_runner.dart';
void main() {
group('UpgradeCommandRunner', () {
late FakeUpgradeCommandRunner fakeCommandRunner;
late UpgradeCommandRunner realCommandRunner;
late FakeProcessManager processManager;
late FakePlatform fakePlatform;
const GitTagVersion gitTagVersion = GitTagVersion(
x: 1,
y: 2,
z: 3,
hotfix: 4,
commits: 5,
hash: 'asd',
);
setUp(() {
fakeCommandRunner = FakeUpgradeCommandRunner();
realCommandRunner = UpgradeCommandRunner()
..workingDirectory = getFlutterRoot();
processManager = FakeProcessManager.empty();
fakeCommandRunner.willHaveUncommittedChanges = false;
fakePlatform = FakePlatform()..environment = Map<String, String>.unmodifiable(<String, String>{
'ENV1': 'irrelevant',
'ENV2': 'irrelevant',
});
});
testUsingContext('throws on unknown tag, official branch, noforce', () async {
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: 'beta');
const String upstreamRevision = '';
final FakeFlutterVersion latestVersion = FakeFlutterVersion(frameworkRevision: upstreamRevision);
fakeCommandRunner.remoteVersion = latestVersion;
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: false,
continueFlow: false,
testFlow: false,
gitTagVersion: const GitTagVersion.unknown(),
flutterVersion: flutterVersion,
verifyOnly: false,
);
expect(result, throwsToolExit());
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
});
testUsingContext('throws tool exit with uncommitted changes', () async {
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: 'beta');
const String upstreamRevision = '';
final FakeFlutterVersion latestVersion = FakeFlutterVersion(frameworkRevision: upstreamRevision);
fakeCommandRunner.remoteVersion = latestVersion;
fakeCommandRunner.willHaveUncommittedChanges = true;
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: false,
continueFlow: false,
testFlow: false,
gitTagVersion: gitTagVersion,
flutterVersion: flutterVersion,
verifyOnly: false,
);
expect(result, throwsToolExit());
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
});
testUsingContext("Doesn't continue on known tag, beta branch, no force, already up-to-date", () async {
const String revision = 'abc123';
final FakeFlutterVersion latestVersion = FakeFlutterVersion(frameworkRevision: revision);
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: 'beta', frameworkRevision: revision);
fakeCommandRunner.alreadyUpToDate = true;
fakeCommandRunner.remoteVersion = latestVersion;
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: false,
continueFlow: false,
testFlow: false,
gitTagVersion: gitTagVersion,
flutterVersion: flutterVersion,
verifyOnly: false,
);
expect(await result, FlutterCommandResult.success());
expect(testLogger.statusText, contains('Flutter is already up to date'));
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('correctly provides upgrade version on verify only', () async {
const String revision = 'abc123';
const String upstreamRevision = 'def456';
const String version = '1.2.3';
const String upstreamVersion = '4.5.6';
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(
branch: 'beta',
frameworkRevision: revision,
frameworkRevisionShort: revision,
frameworkVersion: version,
);
final FakeFlutterVersion latestVersion = FakeFlutterVersion(
frameworkRevision: upstreamRevision,
frameworkRevisionShort: upstreamRevision,
frameworkVersion: upstreamVersion,
);
fakeCommandRunner.alreadyUpToDate = false;
fakeCommandRunner.remoteVersion = latestVersion;
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: false,
continueFlow: false,
testFlow: false,
gitTagVersion: gitTagVersion,
flutterVersion: flutterVersion,
verifyOnly: true,
);
expect(await result, FlutterCommandResult.success());
expect(testLogger.statusText, contains('A new version of Flutter is available'));
expect(testLogger.statusText, contains('The latest version: 4.5.6 (revision def456)'));
expect(testLogger.statusText, contains('Your current version: 1.2.3 (revision abc123)'));
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('fetchLatestVersion returns version if git succeeds', () async {
const String revision = 'abc123';
const String version = '1.2.3';
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git', 'fetch', '--tags',
]),
const FakeCommand(command: <String>[
'git', 'rev-parse', '--verify', '@{upstream}',
],
stdout: revision),
const FakeCommand(command: <String>[
'git', 'tag', '--points-at', revision,
]),
const FakeCommand(command: <String>[
'git', 'describe', '--match', '*.*.*', '--long', '--tags', revision,
],
stdout: version),
]);
final FlutterVersion updateVersion = await realCommandRunner.fetchLatestVersion(localVersion: FakeFlutterVersion());
expect(updateVersion.frameworkVersion, version);
expect(updateVersion.frameworkRevision, revision);
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('fetchLatestVersion throws toolExit if HEAD is detached', () async {
processManager.addCommands(const <FakeCommand>[
FakeCommand(command: <String>[
'git', 'fetch', '--tags',
]),
FakeCommand(
command: <String>['git', 'rev-parse', '--verify', '@{upstream}'],
exception: ProcessException(
'git',
<String>['rev-parse', '--verify', '@{upstream}'],
'fatal: HEAD does not point to a branch',
),
),
]);
await expectLater(
() async => realCommandRunner.fetchLatestVersion(localVersion: FakeFlutterVersion()),
throwsToolExit(message: 'Unable to upgrade Flutter: Your Flutter checkout '
'is currently not on a release branch.\n'
'Use "flutter channel" to switch to an official channel, and retry. '
'Alternatively, re-install Flutter by going to https://flutter.dev/docs/get-started/install.'
),
);
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('fetchLatestVersion throws toolExit if no upstream configured', () async {
processManager.addCommands(const <FakeCommand>[
FakeCommand(command: <String>[
'git', 'fetch', '--tags',
]),
FakeCommand(
command: <String>['git', 'rev-parse', '--verify', '@{upstream}'],
exception: ProcessException(
'git',
<String>['rev-parse', '--verify', '@{upstream}'],
'fatal: no upstream configured for branch',
),
),
]);
await expectLater(
() async => realCommandRunner.fetchLatestVersion(localVersion: FakeFlutterVersion()),
throwsToolExit(message: 'Unable to upgrade Flutter: The current Flutter '
'branch/channel is not tracking any remote repository.\n'
'Re-install Flutter by going to https://flutter.dev/docs/get-started/install.'
),
);
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('git exception during attemptReset throwsToolExit', () async {
const String revision = 'abc123';
const String errorMessage = 'fatal: Could not parse object ´$revision´';
processManager.addCommand(
const FakeCommand(
command: <String>['git', 'reset', '--hard', revision],
exception: ProcessException(
'git',
<String>['reset', '--hard', revision],
errorMessage,
),
),
);
await expectLater(
() async => realCommandRunner.attemptReset(revision),
throwsToolExit(message: errorMessage),
);
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('flutterUpgradeContinue passes env variables to child process', () async {
processManager.addCommand(
FakeCommand(
command: <String>[
globals.fs.path.join('bin', 'flutter'),
'upgrade',
'--continue',
'--no-version-check',
],
environment: <String, String>{'FLUTTER_ALREADY_LOCKED': 'true', ...fakePlatform.environment}
),
);
await realCommandRunner.flutterUpgradeContinue();
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('Show current version to the upgrade message.', () async {
const String revision = 'abc123';
const String upstreamRevision = 'def456';
const String version = '1.2.3';
const String upstreamVersion = '4.5.6';
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(
branch: 'beta',
frameworkRevision: revision,
frameworkVersion: version,
);
final FakeFlutterVersion latestVersion = FakeFlutterVersion(
frameworkRevision: upstreamRevision,
frameworkVersion: upstreamVersion,
);
fakeCommandRunner.alreadyUpToDate = false;
fakeCommandRunner.remoteVersion = latestVersion;
fakeCommandRunner.workingDirectory = 'workingDirectory/aaa/bbb';
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: true,
continueFlow: false,
testFlow: true,
gitTagVersion: gitTagVersion,
flutterVersion: flutterVersion,
verifyOnly: false,
);
expect(await result, FlutterCommandResult.success());
expect(testLogger.statusText, contains('Upgrading Flutter to 4.5.6 from 1.2.3 in workingDirectory/aaa/bbb...'));
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('precacheArtifacts passes env variables to child process', () async {
processManager.addCommand(
FakeCommand(
command: <String>[
globals.fs.path.join('bin', 'flutter'),
'--no-color',
'--no-version-check',
'precache',
],
environment: <String, String>{'FLUTTER_ALREADY_LOCKED': 'true', ...fakePlatform.environment}
),
);
await precacheArtifacts();
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
group('runs upgrade', () {
setUp(() {
processManager.addCommand(
FakeCommand(command: <String>[
globals.fs.path.join('bin', 'flutter'),
'upgrade',
'--continue',
'--no-version-check',
]),
);
});
testUsingContext('does not throw on unknown tag, official branch, force', () async {
fakeCommandRunner.remoteVersion = FakeFlutterVersion(frameworkRevision: '1234');
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: 'beta');
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: true,
continueFlow: false,
testFlow: false,
gitTagVersion: const GitTagVersion.unknown(),
flutterVersion: flutterVersion,
verifyOnly: false,
);
expect(await result, FlutterCommandResult.success());
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext('does not throw tool exit with uncommitted changes and force', () async {
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: 'beta');
fakeCommandRunner.remoteVersion = FakeFlutterVersion(frameworkRevision: '1234');
fakeCommandRunner.willHaveUncommittedChanges = true;
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: true,
continueFlow: false,
testFlow: false,
gitTagVersion: gitTagVersion,
flutterVersion: flutterVersion,
verifyOnly: false,
);
expect(await result, FlutterCommandResult.success());
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
testUsingContext("Doesn't throw on known tag, beta branch, no force", () async {
final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: 'beta');
fakeCommandRunner.remoteVersion = FakeFlutterVersion(frameworkRevision: '1234');
final Future<FlutterCommandResult> result = fakeCommandRunner.runCommand(
force: false,
continueFlow: false,
testFlow: false,
gitTagVersion: gitTagVersion,
flutterVersion: flutterVersion,
verifyOnly: false,
);
expect(await result, FlutterCommandResult.success());
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => processManager,
Platform: () => fakePlatform,
});
group('full command', () {
late FakeProcessManager fakeProcessManager;
late Directory tempDir;
late File flutterToolState;
late FileSystem fs;
setUp(() {
Cache.disableLocking();
fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>[
'git', 'tag', '--points-at', 'HEAD',
],
),
const FakeCommand(
command: <String>[
'git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD',
],
stdout: 'v1.12.16-19-gb45b676af',
),
]);
fs = MemoryFileSystem.test();
tempDir = fs.systemTempDirectory.createTempSync('flutter_upgrade_test.');
flutterToolState = tempDir.childFile('.flutter_tool_state');
});
tearDown(() {
Cache.enableLocking();
tryToDelete(tempDir);
});
testUsingContext('upgrade continue prints welcome message', () async {
fakeProcessManager = FakeProcessManager.any();
final UpgradeCommand upgradeCommand = UpgradeCommand(
verboseHelp: false,
commandRunner: fakeCommandRunner,
);
await createTestCommandRunner(upgradeCommand).run(
<String>[
'upgrade',
'--continue',
],
);
expect(
json.decode(flutterToolState.readAsStringSync()),
containsPair('redisplay-welcome-message', true),
);
}, overrides: <Type, Generator>{
FileSystem: () => fs,
FlutterVersion: () => FakeFlutterVersion(),
ProcessManager: () => fakeProcessManager,
PersistentToolState: () => PersistentToolState.test(
directory: tempDir,
logger: testLogger,
),
});
});
});
});
}
class FakeUpgradeCommandRunner extends UpgradeCommandRunner {
bool willHaveUncommittedChanges = false;
bool alreadyUpToDate = false;
late FlutterVersion remoteVersion;
@override
Future<FlutterVersion> fetchLatestVersion({FlutterVersion? localVersion}) async => remoteVersion;
@override
Future<bool> hasUncommittedChanges() async => willHaveUncommittedChanges;
@override
Future<void> attemptReset(String newRevision) async {}
@override
Future<void> updatePackages(FlutterVersion flutterVersion) async {}
@override
Future<void> runDoctor() async {}
}
| flutter/packages/flutter_tools/test/commands.shard/permeable/upgrade_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/permeable/upgrade_test.dart",
"repo_id": "flutter",
"token_count": 7165
} | 821 |
// 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/memory.dart';
import 'package:flutter_tools/src/android/android_studio.dart';
import 'package:flutter_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/config.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/version.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/ios/plist_parser.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_process_manager.dart';
void main() {
group('installation detection on MacOS', () {
const String homeMac = '/Users/me';
const Map<String, Object> macStudioInfoPlist3_3 = <String, Object>{
'CFBundleGetInfoString': 'Android Studio 3.3, build AI-182.5107.16.33.5199772. Copyright JetBrains s.r.o., (c) 2000-2018',
'CFBundleShortVersionString': '3.3',
'CFBundleVersion': 'AI-182.5107.16.33.5199772',
'JVMOptions': <String, Object>{
'Properties': <String, Object>{
'idea.paths.selector': 'AndroidStudio3.3',
'idea.platform.prefix': 'AndroidStudio',
},
},
};
const Map<String, Object> macStudioInfoPlist4_1 = <String, Object>{
'CFBundleGetInfoString': 'Android Studio 4.1, build AI-201.8743.12.41.6858069. Copyright JetBrains s.r.o., (c) 2000-2020',
'CFBundleShortVersionString': '4.1',
'CFBundleVersion': 'AI-201.8743.12.41.6858069',
'JVMOptions': <String, Object>{
'Properties': <String, Object>{
'idea.vendor.name' : 'Google',
'idea.paths.selector': 'AndroidStudio4.1',
'idea.platform.prefix': 'AndroidStudio',
},
},
};
const Map<String, Object> macStudioInfoPlist2020_3 = <String, Object>{
'CFBundleGetInfoString': 'Android Studio 2020.3, build AI-203.7717.56.2031.7583922. Copyright JetBrains s.r.o., (c) 2000-2021',
'CFBundleShortVersionString': '2020.3',
'CFBundleVersion': 'AI-203.7717.56.2031.7583922',
'JVMOptions': <String, Object>{
'Properties': <String, Object>{
'idea.vendor.name' : 'Google',
'idea.paths.selector': 'AndroidStudio2020.3',
'idea.platform.prefix': 'AndroidStudio',
},
},
};
const Map<String, Object> macStudioInfoPlist2022_1 = <String, Object>{
'CFBundleGetInfoString': 'Android Studio 2022.1, build AI-221.6008.13.2211.9477386. Copyright JetBrains s.r.o., (c) 2000-2023',
'CFBundleShortVersionString': '2022.1',
'CFBundleVersion': 'AI-221.6008.13.2211.9477386',
'JVMOptions': <String, Object>{
'Properties': <String, Object>{
'idea.vendor.name' : 'Google',
'idea.paths.selector': 'AndroidStudio2022.1',
'idea.platform.prefix': 'AndroidStudio',
},
},
};
const Map<String, Object> macStudioInfoPlistEap_2022_3_1_11 = <String, Object>{
'CFBundleGetInfoString': 'Android Studio EAP AI-223.8836.35.2231.9848316, build AI-223.8836.35.2231.9848316. Copyright JetBrains s.r.o., (c) 2000-2023',
'CFBundleShortVersionString': 'EAP AI-223.8836.35.2231.9848316',
'CFBundleVersion': 'AI-223.8836.35.2231.9848316',
'JVMOptions': <String, Object>{
'Properties': <String, Object>{
'idea.vendor.name' : 'Google',
'idea.paths.selector': 'AndroidStudioPreview2022.3',
'idea.platform.prefix': 'AndroidStudio',
},
},
};
late Config config;
late FileSystem fileSystem;
late FileSystemUtils fsUtils;
late Platform platform;
late FakePlistUtils plistUtils;
late FakeProcessManager processManager;
setUp(() {
config = Config.test();
fileSystem = MemoryFileSystem.test();
plistUtils = FakePlistUtils();
platform = FakePlatform(
operatingSystem: 'macos',
environment: <String, String>{'HOME': homeMac},
);
fsUtils = FileSystemUtils(
fileSystem: fileSystem,
platform: platform,
);
processManager = FakeProcessManager.empty();
});
testUsingContext('discovers Android Studio >=4.1 location', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist4_1;
processManager.addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'jdk', 'Contents', 'Home', 'bin', 'java'),
'-version',
],
stderr: '123',
)
);
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio, isNotNull);
expect(studio.pluginsPath, equals(fileSystem.path.join(
homeMac,
'Library',
'Application Support',
'Google',
'AndroidStudio4.1',
)));
expect(studio.validationMessages, <String>['Java version 123']);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('discovers Android Studio >=2020.3 location', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2020_3;
processManager.addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'Contents', 'Home', 'bin', 'java'),
'-version',
],
stderr: '123',
)
);
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio, isNotNull);
expect(studio.pluginsPath, equals(fileSystem.path.join(
homeMac,
'Library',
'Application Support',
'Google',
'AndroidStudio2020.3',
)));
expect(studio.validationMessages, <String>['Java version 123']);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('discovers Android Studio <4.1 location', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist3_3;
processManager.addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'jdk', 'Contents', 'Home', 'bin', 'java'),
'-version',
],
stderr: '123',
)
);
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio, isNotNull);
expect(studio.pluginsPath, equals(fileSystem.path.join(
homeMac,
'Library',
'Application Support',
'AndroidStudio3.3',
)));
expect(studio.validationMessages, <String>['Java version 123']);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('discovers Android Studio EAP location', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio with suffix.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlistEap_2022_3_1_11;
processManager.addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home', 'bin', 'java'),
'-version',
],
stderr: '123',
)
);
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio, isNotNull);
expect(studio.pluginsPath, equals(fileSystem.path.join(
homeMac,
'Library',
'Application Support',
'AndroidStudioPreview2022.3',
)));
expect(studio.validationMessages, <String>['Java version 123']);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('does not discover Android Studio with JetBrainsToolboxApp wrapper', () {
final String applicationPlistFolder = fileSystem.path.join(
'/',
'Applications',
'Android Studio.app',
'Contents',
);
fileSystem.directory(applicationPlistFolder).createSync(recursive: true);
final String applicationsPlistFilePath = fileSystem.path.join(applicationPlistFolder, 'Info.plist');
const Map<String, Object> jetbrainsInfoPlist = <String, Object>{
'JetBrainsToolboxApp': 'ignored',
};
plistUtils.fileContents[applicationsPlistFilePath] = jetbrainsInfoPlist;
final String homeDirectoryPlistFolder = fileSystem.path.join(
fsUtils.homeDirPath!,
'Applications',
'Android Studio.app',
'Contents',
);
fileSystem.directory(homeDirectoryPlistFolder).createSync(recursive: true);
final String homeDirectoryPlistFilePath = fileSystem.path.join(homeDirectoryPlistFolder, 'Info.plist');
plistUtils.fileContents[homeDirectoryPlistFilePath] = macStudioInfoPlist2020_3;
expect(AndroidStudio.allInstalled().length, 1);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => FakeProcessManager.any(),
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('discovers installation from Spotlight query', () {
// One in expected location.
final String studioInApplication = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
);
final String studioInApplicationPlistFolder = fileSystem.path.join(
studioInApplication,
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist4_1;
// Two in random location only Spotlight knows about.
final String randomLocation1 = fileSystem.path.join(
'/',
'random',
'Android Studio Preview.app',
);
final String randomLocation1PlistFolder = fileSystem.path.join(
randomLocation1,
'Contents',
);
fileSystem.directory(randomLocation1PlistFolder).createSync(recursive: true);
final String randomLocation1PlistPath = fileSystem.path.join(randomLocation1PlistFolder, 'Info.plist');
plistUtils.fileContents[randomLocation1PlistPath] = macStudioInfoPlist4_1;
final String randomLocation2 = fileSystem.path.join(
'/',
'random',
'Android Studio with Blaze.app',
);
final String randomLocation2PlistFolder = fileSystem.path.join(
randomLocation2,
'Contents',
);
fileSystem.directory(randomLocation2PlistFolder).createSync(recursive: true);
final String randomLocation2PlistPath = fileSystem.path.join(randomLocation2PlistFolder, 'Info.plist');
plistUtils.fileContents[randomLocation2PlistPath] = macStudioInfoPlist4_1;
final String javaBin = fileSystem.path.join('jre', 'jdk', 'Contents', 'Home', 'bin', 'java');
// Spotlight finds the one known and two random installations.
processManager.addCommands(<FakeCommand>[
FakeCommand(
command: const <String>[
'mdfind',
'kMDItemCFBundleIdentifier="com.google.android.studio*"',
],
stdout: '$randomLocation1\n$randomLocation2\n$studioInApplication',
),
FakeCommand(
command: <String>[
fileSystem.path.join(randomLocation1, 'Contents', javaBin),
'-version',
],
),
FakeCommand(
command: <String>[
fileSystem.path.join(randomLocation2, 'Contents', javaBin),
'-version',
],
),
FakeCommand(
command: <String>[
fileSystem.path.join(studioInApplicationPlistFolder, javaBin),
'-version',
],
),
]);
// Results are de-duplicated, only 3 installed.
expect(AndroidStudio.allInstalled().length, 3);
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('finds latest valid install', () {
final String applicationPlistFolder = fileSystem.path.join(
'/',
'Applications',
'Android Studio.app',
'Contents',
);
fileSystem.directory(applicationPlistFolder).createSync(recursive: true);
final String applicationsPlistFilePath = fileSystem.path.join(applicationPlistFolder, 'Info.plist');
plistUtils.fileContents[applicationsPlistFilePath] = macStudioInfoPlist3_3;
final String homeDirectoryPlistFolder = fileSystem.path.join(
fsUtils.homeDirPath!,
'Applications',
'Android Studio.app',
'Contents',
);
fileSystem.directory(homeDirectoryPlistFolder).createSync(recursive: true);
final String homeDirectoryPlistFilePath = fileSystem.path.join(homeDirectoryPlistFolder, 'Info.plist');
plistUtils.fileContents[homeDirectoryPlistFilePath] = macStudioInfoPlist4_1;
expect(AndroidStudio.allInstalled().length, 2);
expect(AndroidStudio.latestValid()!.version, Version(4, 1, 0));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => FakeProcessManager.any(),
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('extracts custom paths for directly downloaded Android Studio', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist3_3;
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio, isNotNull);
expect(studio.pluginsPath, equals(fileSystem.path.join(
homeMac,
'Library',
'Application Support',
'AndroidStudio3.3',
)));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => FakeProcessManager.any(),
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('finds Android Studio 2020.3 bundled Java version', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2020_3;
processManager.addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'Contents', 'Home', 'bin', 'java'),
'-version',
],
stderr: '123',
)
);
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio.javaPath, equals(fileSystem.path.join(
studioInApplicationPlistFolder,
'jre',
'Contents',
'Home',
)));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('finds Android Studio 2022.1 bundled Java version', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2022_1;
processManager.addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home', 'bin', 'java'),
'-version',
],
stderr: '123',
)
);
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio.javaPath, equals(fileSystem.path.join(
studioInApplicationPlistFolder,
'jbr',
'Contents',
'Home',
)));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('finds bundled Java version when Android Studio version is unknown by assuming the latest version', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
final Map<String, Object> plistWithoutVersion = Map<String, Object>.from(macStudioInfoPlist2022_1);
plistWithoutVersion['CFBundleShortVersionString'] = '';
plistUtils.fileContents[plistFilePath] = plistWithoutVersion;
final String jdkPath = fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home');
processManager.addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(jdkPath, 'bin', 'java'),
'-version',
],
stderr: '123',
)
);
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio.version, null);
expect(studio.javaPath, jdkPath);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('when given an Android Studio newer than any known version, finds Java version by assuming latest known Android Studio version', () {
final String studioInApplicationPlistFolder = fileSystem.path.join(
'/',
'Application',
'Android Studio.app',
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
final Map<String, Object> plistWithoutVersion = Map<String, Object>.from(macStudioInfoPlist2022_1);
plistWithoutVersion['CFBundleShortVersionString'] = '99999.99.99';
plistUtils.fileContents[plistFilePath] = plistWithoutVersion;
final String jdkPathFor2022 = fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home');
final AndroidStudio studio = AndroidStudio.fromMacOSBundle(
fileSystem.directory(studioInApplicationPlistFolder).parent.path,
)!;
expect(studio.version, equals(Version(99999, 99, 99)));
expect(studio.javaPath, jdkPathFor2022);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => FakeProcessManager.any(),
Platform: () => platform,
PlistParser: () => plistUtils,
});
testUsingContext('discovers explicitly configured Android Studio', () {
final String extractedDownloadZip = fileSystem.path.join(
'/',
'Users',
'Dash',
'Desktop',
'android-studio'
);
config.setValue('android-studio-dir', extractedDownloadZip);
final String studioInApplicationPlistFolder = fileSystem.path.join(
extractedDownloadZip,
'Contents',
);
fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist');
plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2022_1;
final String studioInApplicationJavaBinary = fileSystem.path.join(
extractedDownloadZip,
'Contents', 'jbr', 'Contents', 'Home', 'bin', 'java',
);
processManager.addCommands(<FakeCommand>[
FakeCommand(
command: const <String>[
'mdfind',
'kMDItemCFBundleIdentifier="com.google.android.studio*"',
],
stdout: extractedDownloadZip,
),
FakeCommand(
command: <String>[
studioInApplicationJavaBinary,
'-version',
],
),
]);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.configuredPath, extractedDownloadZip);
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
Config:() => config,
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
ProcessManager: () => processManager,
Platform: () => platform,
PlistParser: () => plistUtils,
});
});
group('installation detection on Windows', () {
late Config config;
late Platform platform;
late FileSystem fileSystem;
setUp(() {
config = Config.test();
platform = FakePlatform(
operatingSystem: 'windows',
environment: <String, String>{
'LOCALAPPDATA': r'C:\Users\Dash\AppData\Local',
}
);
fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows);
});
testUsingContext('discovers Android Studio 4.1 location', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.1\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 1, 0));
expect(studio.studioAppName, 'Android Studio');
}, overrides: <Type, Generator>{
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('discovers Android Studio 4.2 location', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.2\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 2, 0));
expect(studio.studioAppName, 'Android Studio');
}, overrides: <Type, Generator>{
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('discovers Android Studio 2020.3 location', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2020.3\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(2020, 3, 0));
expect(studio.studioAppName, 'Android Studio');
}, overrides: <Type, Generator>{
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('does not discover Android Studio 4.1 location if LOCALAPPDATA is null', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.1\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
expect(AndroidStudio.allInstalled(), isEmpty);
}, overrides: <Type, Generator>{
Platform: () => FakePlatform(
operatingSystem: 'windows',
environment: <String, String>{}, // Does not include LOCALAPPDATA
),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('does not discover Android Studio 4.2 location if LOCALAPPDATA is null', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.2\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
expect(AndroidStudio.allInstalled(), isEmpty);
}, overrides: <Type, Generator>{
Platform: () => FakePlatform(
operatingSystem: 'windows',
environment: <String, String>{}, // Does not include LOCALAPPDATA
),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('does not discover Android Studio 2020.3 location if LOCALAPPDATA is null', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2020.3\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
expect(AndroidStudio.allInstalled(), isEmpty);
}, overrides: <Type, Generator>{
Platform: () => FakePlatform(
operatingSystem: 'windows',
environment: <String, String>{}, // Does not include LOCALAPPDATA
),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('finds Android Studio 2020.3 bundled Java version', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2020.3\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals(r'C:\Program Files\AndroidStudio\jre'));
}, overrides: <Type, Generator>{
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('finds Android Studio 2022.1 bundled Java version', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2022.1\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals(r'C:\Program Files\AndroidStudio\jbr'));
}, overrides: <Type, Generator>{
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('finds bundled Java version when Android Studio version is unknown by assuming the latest version', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
fileSystem.file(r'C:\Program Files\AndroidStudio\jbr\bin\java').createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, null);
expect(studio.javaPath, equals(r'C:\Program Files\AndroidStudio\jbr'));
}, overrides: <Type, Generator>{
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('when given an Android Studio newer than any known version, finds Java version by assuming latest known Android Studio version', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio99999.99.99\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio');
fileSystem.directory(r'C:\Program Files\AndroidStudio')
.createSync(recursive: true);
fileSystem.file(r'C:\Program Files\AndroidStudio\jbr\bin\java').createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
const String expectedJdkLocationFor2022 = r'C:\Program Files\AndroidStudio\jbr';
expect(studio.version, equals(Version(99999, 99, 99)));
expect(studio.javaPath, equals(expectedJdkLocationFor2022));
}, overrides: <Type, Generator>{
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('discovers explicitly configured Android Studio', () {
const String androidStudioDir = r'C:\Users\Dash\Desktop\android-studio';
config.setValue('android-studio-dir', androidStudioDir);
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2022.1\.home')
..createSync(recursive: true)
..writeAsStringSync(androidStudioDir);
fileSystem.directory(androidStudioDir)
.createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, equals(Version(2022, 1, null)));
expect(studio.configuredPath, androidStudioDir);
expect(studio.javaPath, fileSystem.path.join(androidStudioDir, 'jbr'));
}, overrides: <Type, Generator>{
Config: () => config,
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
group('installation detection on Linux', () {
const String homeLinux = '/home/me';
late Config config;
late FileSystem fileSystem;
late FileSystemUtils fsUtils;
late Platform platform;
setUp(() {
config = Config.test();
platform = FakePlatform(
environment: <String, String>{'HOME': homeLinux},
);
fileSystem = MemoryFileSystem.test();
fsUtils = FileSystemUtils(
fileSystem: fileSystem,
platform: platform,
);
});
testUsingContext('discovers Android Studio <4.1', () {
const String studioHomeFilePath =
'$homeLinux/.AndroidStudio4.0/system/.home';
const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath)
..createSync(recursive: true)
..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 0, 0));
expect(studio.studioAppName, 'AndroidStudio');
expect(
studio.pluginsPath,
'/home/me/.AndroidStudio4.0/config/plugins',
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('discovers Android Studio >=4.1', () {
const String studioHomeFilePath =
'$homeLinux/.cache/Google/AndroidStudio4.1/.home';
const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath)
..createSync(recursive: true)
..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 1, 0));
expect(studio.studioAppName, 'AndroidStudio');
expect(
studio.pluginsPath,
'/home/me/.local/share/Google/AndroidStudio4.1',
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('discovers when installed with Toolbox', () {
const String studioHomeFilePath =
'$homeLinux/.cache/Google/AndroidStudio4.1/.home';
const String studioInstallPath =
'$homeLinux/.local/share/JetBrains/Toolbox/apps/AndroidStudio/ch-0/201.7042882';
const String pluginsInstallPath = '$studioInstallPath.plugins';
fileSystem.file(studioHomeFilePath)
..createSync(recursive: true)
..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync(recursive: true);
fileSystem.directory(pluginsInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 1, 0));
expect(studio.studioAppName, 'AndroidStudio');
expect(
studio.pluginsPath,
pluginsInstallPath,
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('finds Android Studio 2020.3 bundled Java version', () {
const String studioHomeFilePath = '$homeLinux/.cache/Google/AndroidStudio2020.3/.home';
const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath)
..createSync(recursive: true)
..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals('$studioInstallPath/jre'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('finds Android Studio 2022.1 bundled Java version', () {
const String studioHomeFilePath =
'$homeLinux/.cache/Google/AndroidStudio2022.1/.home';
const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath)
..createSync(recursive: true)
..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals('$studioInstallPath/jbr'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('finds bundled Java version when Android Studio version is unknown by assuming the latest version', () {
const String configuredStudioInstallPath = '$homeLinux/AndroidStudio';
config.setValue('android-studio-dir', configuredStudioInstallPath);
fileSystem.directory(configuredStudioInstallPath).createSync(recursive: true);
fileSystem.directory(configuredStudioInstallPath).createSync();
fileSystem.file(fileSystem.path.join(configuredStudioInstallPath, 'jbr', 'bin', 'java')).createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, null);
expect(studio.javaPath, equals('$configuredStudioInstallPath/jbr'));
}, overrides: <Type, Generator>{
Config: () => config,
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('when given an Android Studio newer than any known version, finds Java version by assuming latest known Android Studio version', () {
const String studioHomeFilePath =
'$homeLinux/.cache/Google/AndroidStudio99999.99.99/.home';
const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath)
..createSync(recursive: true)
..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final String expectedJdkLocationFor2022 = fileSystem.path.join(studioInstallPath, 'jbr', 'bin', 'java');
fileSystem.file(expectedJdkLocationFor2022).createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, equals(Version(99999, 99, 99)));
expect(studio.javaPath, equals('$studioInstallPath/jbr'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
FileSystemUtils: () => fsUtils,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('pluginsPath extracts custom paths from home dir', () {
const String installPath = '/opt/android-studio-with-cheese-5.0';
const String studioHome = '$homeLinux/.AndroidStudioWithCheese5.0';
const String homeFile = '$studioHome/system/.home';
fileSystem.directory(installPath).createSync(recursive: true);
fileSystem.file(homeFile).createSync(recursive: true);
fileSystem.file(homeFile).writeAsStringSync(installPath);
final AndroidStudio studio =
AndroidStudio.fromHomeDot(fileSystem.directory(studioHome))!;
expect(studio, isNotNull);
expect(studio.pluginsPath,
equals('/home/me/.AndroidStudioWithCheese5.0/config/plugins'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
// Custom home paths are not supported on macOS nor Windows yet,
// so we force the platform to fake Linux here.
Platform: () => platform,
FileSystemUtils: () => FileSystemUtils(
fileSystem: fileSystem,
platform: platform,
),
});
testUsingContext('discovers explicitly configured Android Studio', () {
const String androidStudioDir = '/Users/Dash/Desktop/android-studio';
config.setValue('android-studio-dir', androidStudioDir);
const String studioHome = '$homeLinux/.cache/Google/AndroidStudio2022.3/.home';
fileSystem.file(studioHome)
..createSync(recursive: true)
..writeAsStringSync(androidStudioDir);
fileSystem.directory(androidStudioDir)
.createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, equals(Version(2022, 3, null)));
expect(studio.configuredPath, androidStudioDir);
expect(studio.javaPath, fileSystem.path.join(androidStudioDir, 'jbr'));
}, overrides: <Type, Generator>{
Config: () => config,
Platform: () => platform,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
group('latestValid', () {
late Config config;
late Platform platform;
late FileSystem fileSystem;
setUp(() {
config = Config.test();
platform = FakePlatform(
operatingSystem: 'windows',
environment: <String, String>{
'LOCALAPPDATA': r'C:\Users\Dash\AppData\Local',
}
);
fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows);
});
testUsingContext('chooses the install with the latest version', () {
const List<String> versions = <String> [
'4.0',
'2022.0',
'3.1',
];
for (final String version in versions) {
fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home')
..createSync(recursive: true)
..writeAsStringSync('C:\\Program Files\\AndroidStudio$version');
fileSystem.directory('C:\\Program Files\\AndroidStudio$version')
.createSync(recursive: true);
}
expect(AndroidStudio.allInstalled().length, 3);
expect(AndroidStudio.latestValid()!.version, Version(2022, 0, 0));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('prefers installs with known versions over installs with unknown versions', () {
const List<String> versions = <String> [
'3.0',
'unknown',
];
for (final String version in versions) {
fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home')
..createSync(recursive: true)
..writeAsStringSync('C:\\Program Files\\AndroidStudio$version');
fileSystem.directory('C:\\Program Files\\AndroidStudio$version')
.createSync(recursive: true);
}
expect(AndroidStudio.allInstalled().length, 2);
expect(AndroidStudio.latestValid()!.version, Version(3, 0, 0));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('chooses install with lexicographically greatest directory if no installs have known versions', () {
const List<String> versions = <String> [
'Apple',
'Zucchini',
'Banana',
];
for (final String version in versions) {
fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home')
..createSync(recursive: true)
..writeAsStringSync('C:\\Program Files\\AndroidStudio$version');
fileSystem.directory('C:\\Program Files\\AndroidStudio$version')
.createSync(recursive: true);
}
expect(AndroidStudio.allInstalled().length, 3);
expect(AndroidStudio.latestValid()!.directory, r'C:\Program Files\AndroidStudioZucchini');
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('chooses install with lexicographically greatest directory if all installs have the same version', () {
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudioPreview4.0\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudioPreview4.0');
fileSystem.directory(r'C:\Program Files\AndroidStudioPreview4.0')
.createSync(recursive: true);
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.0\.home')
..createSync(recursive: true)
..writeAsStringSync(r'C:\Program Files\AndroidStudio4.0');
fileSystem.directory(r'C:\Program Files\AndroidStudio4.0')
.createSync(recursive: true);
expect(AndroidStudio.allInstalled().length, 2);
expect(AndroidStudio.latestValid()!.directory, contains('Preview'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('always chooses the install configured by --android-studio-dir, even if the install is invalid', () {
const String configuredAndroidStudioDir = r'C:\Users\Dash\Desktop\android-studio';
config.setValue('android-studio-dir', configuredAndroidStudioDir);
// The directory exists, but nothing is inside.
fileSystem.directory(configuredAndroidStudioDir).createSync(recursive: true);
(globals.processManager as FakeProcessManager).excludedExecutables.add(
fileSystem.path.join(configuredAndroidStudioDir, 'jbr', 'bin', 'java'),
);
const List<String> validVersions = <String> [
'4.0',
'2.0',
'3.1',
];
for (final String version in validVersions) {
fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home')
..createSync(recursive: true)
..writeAsStringSync('C:\\Program Files\\AndroidStudio$version');
fileSystem.directory('C:\\Program Files\\AndroidStudio$version')
.createSync(recursive: true);
}
const List<String> validJavaPaths = <String>[
r'C:\Program Files\AndroidStudio4.0\jre\bin\java',
r'C:\Program Files\AndroidStudio2.0\jre\bin\java',
r'C:\Program Files\AndroidStudio3.1\jre\bin\java',
];
for (final String javaPath in validJavaPaths) {
(globals.processManager as FakeProcessManager).addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(javaPath),
'-version',
],
));
}
expect(AndroidStudio.allInstalled().length, 4);
for (final String javaPath in validJavaPaths) {
(globals.processManager as FakeProcessManager).addCommand(FakeCommand(
command: <String>[
fileSystem.path.join(javaPath),
'-version',
],
));
}
final AndroidStudio chosenInstall = AndroidStudio.latestValid()!;
expect(chosenInstall.directory, configuredAndroidStudioDir);
expect(chosenInstall.isValid, false);
}, overrides: <Type, Generator>{
Config: () => config,
FileSystem: () => fileSystem,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.empty(),
});
testUsingContext('throws a ToolExit if --android-studio-dir is configured but the directory does not exist', () async {
const String configuredAndroidStudioDir = r'C:\Users\Dash\Desktop\android-studio';
config.setValue('android-studio-dir', configuredAndroidStudioDir);
expect(fileSystem.directory(configuredAndroidStudioDir).existsSync(), false);
expect(() => AndroidStudio.latestValid(), throwsA(
(dynamic e) => e is ToolExit &&
e.message!.startsWith('Could not find the Android Studio installation at the manually configured path')
)
);
}, overrides: <Type, Generator>{
Config: () => config,
FileSystem: () => fileSystem,
Platform: () => platform,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('handles file system exception when checking for explicitly configured Android Studio install', () {
const String androidStudioDir = '/Users/Dash/Desktop/android-studio';
config.setValue('android-studio-dir', androidStudioDir);
expect(() => AndroidStudio.latestValid(),
throwsToolExit(message: RegExp(r'[.\s\S]*Could not find[.\s\S]*FileSystemException[.\s\S]*')));
}, overrides: <Type, Generator>{
Config: () => config,
Platform: () => platform,
FileSystem: () => _FakeFileSystem(),
FileSystemUtils: () => _FakeFsUtils(),
ProcessManager: () => FakeProcessManager.any(),
});
});
}
class FakePlistUtils extends Fake implements PlistParser {
final Map<String, Map<String, Object>> fileContents = <String, Map<String, Object>>{};
@override
Map<String, Object> parseFile(String plistFilePath) {
return fileContents[plistFilePath]!;
}
}
class _FakeFileSystem extends Fake implements FileSystem {
@override
Directory directory(dynamic path) {
return _NonExistentDirectory();
}
@override
Context get path {
return MemoryFileSystem.test().path;
}
}
class _NonExistentDirectory extends Fake implements Directory {
@override
bool existsSync() {
throw const FileSystemException('OS Error: Filename, directory name, or volume label syntax is incorrect.');
}
@override
String get path => '';
@override
Directory get parent => _NonExistentDirectory();
}
class _FakeFsUtils extends Fake implements FileSystemUtils {
@override
String get homeDirPath => '/home/';
}
| flutter/packages/flutter_tools/test/general.shard/android/android_studio_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/android/android_studio_test.dart",
"repo_id": "flutter",
"token_count": 19873
} | 822 |
// 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/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/cache.dart';
import '../src/common.dart';
import '../src/context.dart';
import '../src/fakes.dart';
void main() {
group('CachedArtifacts', () {
late CachedArtifacts artifacts;
late Cache cache;
late FileSystem fileSystem;
late Platform platform;
setUp(() {
fileSystem = MemoryFileSystem.test();
final Directory cacheRoot = fileSystem.directory('root')
..createSync();
platform = FakePlatform();
cache = Cache(
rootOverride: cacheRoot,
fileSystem: fileSystem,
platform: platform,
logger: BufferLogger.test(),
osUtils: FakeOperatingSystemUtils(),
artifacts: <ArtifactSet>[],
);
artifacts = CachedArtifacts(
fileSystem: fileSystem,
cache: cache,
platform: platform,
operatingSystemUtils: FakeOperatingSystemUtils(),
);
});
testWithoutContext('getArtifactPath', () {
final String xcframeworkPath = artifacts.getArtifactPath(
Artifact.flutterXcframework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
);
expect(
xcframeworkPath,
fileSystem.path.join(
'root',
'bin',
'cache',
'artifacts',
'engine',
'ios-release',
'Flutter.xcframework',
),
);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.simulator,
),
throwsToolExit(
message:
'No xcframework found at $xcframeworkPath.'),
);
fileSystem.directory(xcframeworkPath).createSync(recursive: true);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.simulator,
),
throwsToolExit(message: 'No iOS frameworks found in $xcframeworkPath'),
);
fileSystem
.directory(xcframeworkPath)
.childDirectory('ios-arm64_x86_64-simulator')
.childDirectory('Flutter.framework')
.createSync(recursive: true);
fileSystem
.directory(xcframeworkPath)
.childDirectory('ios-arm64')
.childDirectory('Flutter.framework')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.simulator),
fileSystem.path
.join(xcframeworkPath, 'ios-arm64_x86_64-simulator', 'Flutter.framework'),
);
final String actualReleaseFrameworkArtifact = artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.physical,
);
final String expectedArm64ReleaseFrameworkArtifact = fileSystem.path.join(
xcframeworkPath,
'ios-arm64',
'Flutter.framework',
);
expect(
actualReleaseFrameworkArtifact,
expectedArm64ReleaseFrameworkArtifact,
);
expect(
artifacts.getArtifactPath(Artifact.flutterXcframework, platform: TargetPlatform.ios, mode: BuildMode.release),
fileSystem.path.join('root', 'bin', 'cache', 'artifacts', 'engine', 'ios-release', 'Flutter.xcframework'),
);
expect(
artifacts.getArtifactPath(Artifact.flutterTester),
fileSystem.path.join('root', 'bin', 'cache', 'artifacts', 'engine', 'linux-x64', 'flutter_tester'),
);
expect(
artifacts.getArtifactPath(Artifact.flutterTester, platform: TargetPlatform.linux_arm64),
fileSystem.path.join('root', 'bin', 'cache', 'artifacts', 'engine', 'linux-arm64', 'flutter_tester'),
);
expect(
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
fileSystem.path.join('root', 'bin', 'cache', 'dart-sdk', 'bin',
'snapshots', 'frontend_server_aot.dart.snapshot')
);
});
testWithoutContext('getArtifactPath for FlutterMacOS.framework and FlutterMacOS.xcframework', () {
final String xcframeworkPath = fileSystem.path.join(
'root',
'bin',
'cache',
'artifacts',
'engine',
'darwin-x64-release',
'FlutterMacOS.xcframework',
);
final String xcframeworkPathWithUnsetPlatform = fileSystem.path.join(
'root',
'bin',
'cache',
'artifacts',
'engine',
'linux-x64-release',
'FlutterMacOS.xcframework',
);
expect(
artifacts.getArtifactPath(
Artifact.flutterMacOSXcframework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
xcframeworkPath,
);
expect(
artifacts.getArtifactPath(
Artifact.flutterMacOSXcframework,
mode: BuildMode.release,
),
xcframeworkPathWithUnsetPlatform,
);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
throwsToolExit(
message:
'No xcframework found at $xcframeworkPath.'),
);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
mode: BuildMode.release,
),
throwsToolExit(
message:
'No xcframework found at $xcframeworkPathWithUnsetPlatform.'),
);
fileSystem.directory(xcframeworkPath).createSync(recursive: true);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
throwsToolExit(message: 'No macOS frameworks found in $xcframeworkPath'),
);
fileSystem
.directory(xcframeworkPath)
.childDirectory('macos-arm64_x86_64')
.childDirectory('FlutterMacOS.framework')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
fileSystem.path.join(
xcframeworkPath,
'macos-arm64_x86_64',
'FlutterMacOS.framework',
),
);
});
testWithoutContext('Precompiled web AMD module system artifact paths are correct', () {
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/amd/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/amd/dart_sdk.js.map',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdCanvaskitSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/amd-canvaskit/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdCanvaskitSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/amd-canvaskit/dart_sdk.js.map',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdSoundSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/amd-sound/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdSoundSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/amd-sound/dart_sdk.js.map',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdCanvaskitSoundSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/amd-canvaskit-sound/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledAmdCanvaskitSoundSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/amd-canvaskit-sound/dart_sdk.js.map',
);
});
testWithoutContext('Precompiled web DDC module system artifact paths are correct', () {
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc/dart_sdk.js.map',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcCanvaskitSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc-canvaskit/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcCanvaskitSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc-canvaskit/dart_sdk.js.map',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcSoundSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc-sound/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcSoundSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc-sound/dart_sdk.js.map',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcCanvaskitSoundSdk).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc-canvaskit-sound/dart_sdk.js',
);
expect(
artifacts.getHostArtifact(HostArtifact.webPrecompiledDdcCanvaskitSoundSdkSourcemaps).path,
'root/bin/cache/flutter_web_sdk/kernel/ddc-canvaskit-sound/dart_sdk.js.map',
);
});
testWithoutContext('getEngineType', () {
expect(
artifacts.getEngineType(TargetPlatform.android_arm, BuildMode.debug),
'android-arm',
);
expect(
artifacts.getEngineType(TargetPlatform.ios, BuildMode.release),
'ios-release',
);
expect(
artifacts.getEngineType(TargetPlatform.darwin),
'darwin-x64',
);
});
});
group('LocalEngineArtifacts', () {
late Artifacts artifacts;
late Cache cache;
late FileSystem fileSystem;
late Platform platform;
setUp(() {
fileSystem = MemoryFileSystem.test();
final Directory cacheRoot = fileSystem.directory('root')
..createSync();
platform = FakePlatform();
cache = Cache(
rootOverride: cacheRoot,
fileSystem: fileSystem,
platform: platform,
logger: BufferLogger.test(),
osUtils: FakeOperatingSystemUtils(),
artifacts: <ArtifactSet>[],
);
artifacts = CachedLocalWebSdkArtifacts(
parent: CachedLocalEngineArtifacts(
fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'host_debug_unopt'),
engineOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'android_debug_unopt'),
cache: cache,
fileSystem: fileSystem,
platform: platform,
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
),
webSdkPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'wasm_release'),
fileSystem: fileSystem,
platform: platform,
operatingSystemUtils: FakeOperatingSystemUtils());
});
testWithoutContext('getArtifactPath for FlutterMacOS.framework and FlutterMacOS.xcframework', () {
final String xcframeworkPath = fileSystem.path.join(
'/out',
'android_debug_unopt',
'FlutterMacOS.xcframework',
);
expect(
artifacts.getArtifactPath(
Artifact.flutterMacOSXcframework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
xcframeworkPath,
);
expect(
artifacts.getArtifactPath(
Artifact.flutterMacOSXcframework,
mode: BuildMode.release,
),
xcframeworkPath,
);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
throwsToolExit(
message:
'No xcframework found at /out/android_debug_unopt/FlutterMacOS.xcframework'),
);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
mode: BuildMode.release,
),
throwsToolExit(
message:
'No xcframework found at /out/android_debug_unopt/FlutterMacOS.xcframework'),
);
fileSystem.directory(xcframeworkPath).createSync(recursive: true);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
throwsToolExit(
message:
'No macOS frameworks found in /out/android_debug_unopt/FlutterMacOS.xcframework'),
);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
mode: BuildMode.release,
),
throwsToolExit(
message:
'No macOS frameworks found in /out/android_debug_unopt/FlutterMacOS.xcframework'),
);
fileSystem
.directory(xcframeworkPath)
.childDirectory('macos-arm64_x86_64')
.childDirectory('FlutterMacOS.framework')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
platform: TargetPlatform.darwin,
mode: BuildMode.release,
),
fileSystem.path
.join(xcframeworkPath, 'macos-arm64_x86_64', 'FlutterMacOS.framework'),
);
expect(
artifacts.getArtifactPath(
Artifact.flutterMacOSFramework,
mode: BuildMode.release,
),
fileSystem.path
.join(xcframeworkPath, 'macos-arm64_x86_64', 'FlutterMacOS.framework'),
);
});
testWithoutContext('getArtifactPath', () {
final String xcframeworkPath = artifacts.getArtifactPath(
Artifact.flutterXcframework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
);
expect(
xcframeworkPath,
fileSystem.path
.join('/out', 'android_debug_unopt', 'Flutter.xcframework'),
);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.simulator,
),
throwsToolExit(
message:
'No xcframework found at /out/android_debug_unopt/Flutter.xcframework'),
);
fileSystem.directory(xcframeworkPath).createSync(recursive: true);
expect(
() => artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.simulator,
),
throwsToolExit(
message:
'No iOS frameworks found in /out/android_debug_unopt/Flutter.xcframework'),
);
fileSystem
.directory(xcframeworkPath)
.childDirectory('ios-arm64_x86_64-simulator')
.childDirectory('Flutter.framework')
.createSync(recursive: true);
fileSystem
.directory(xcframeworkPath)
.childDirectory('ios-arm64')
.childDirectory('Flutter.framework')
.createSync(recursive: true);
fileSystem
.directory('out')
.childDirectory('host_debug_unopt')
.childDirectory('dart-sdk')
.childDirectory('bin')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.simulator,
),
fileSystem.path
.join(xcframeworkPath, 'ios-arm64_x86_64-simulator', 'Flutter.framework'),
);
expect(
artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
environmentType: EnvironmentType.physical,
),
fileSystem.path
.join(xcframeworkPath, 'ios-arm64', 'Flutter.framework'),
);
expect(
artifacts.getArtifactPath(
Artifact.flutterXcframework,
platform: TargetPlatform.ios,
mode: BuildMode.release,
),
fileSystem.path
.join('/out', 'android_debug_unopt', 'Flutter.xcframework'),
);
expect(
artifacts.getArtifactPath(Artifact.flutterTester),
fileSystem.path.join('/out', 'android_debug_unopt', 'flutter_tester'),
);
expect(
artifacts.getArtifactPath(Artifact.engineDartSdkPath),
fileSystem.path.join('/out', 'host_debug_unopt', 'dart-sdk'),
);
expect(
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
fileSystem.path.join('/out', 'host_debug_unopt', 'dart-sdk', 'bin',
'snapshots', 'frontend_server_aot.dart.snapshot')
);
expect(
artifacts.getArtifactPath(
Artifact.flutterPreviewDevice,
platform: TargetPlatform.windows_x64,
),
fileSystem.path.join('root', 'bin', 'cache', 'artifacts',
'flutter_preview', 'flutter_preview.exe'),
);
fileSystem.file(fileSystem.path.join('/out', 'host_debug_unopt', 'impellerc'))
.createSync(recursive: true);
fileSystem.file(fileSystem.path.join('/out', 'host_debug_unopt', 'libtessellator.so'))
.createSync(recursive: true);
expect(
artifacts.getHostArtifact(HostArtifact.impellerc).path,
fileSystem.path.join('/out', 'host_debug_unopt', 'impellerc'),
);
expect(
artifacts.getHostArtifact(HostArtifact.libtessellator).path,
fileSystem.path.join('/out', 'host_debug_unopt', 'libtessellator.so'),
);
});
testWithoutContext('falls back to bundled impeller artifacts if the files do not exist in the local engine', () {
expect(
artifacts.getHostArtifact(HostArtifact.impellerc).path,
fileSystem.path.join('root', 'bin', 'cache', 'artifacts', 'engine', 'linux-x64', 'impellerc'),
);
expect(
artifacts.getHostArtifact(HostArtifact.libtessellator).path,
fileSystem.path.join('root', 'bin', 'cache', 'artifacts', 'engine', 'linux-x64', 'libtessellator.so'),
);
});
testWithoutContext('uses prebuilt dart sdk for web platform', () {
final String failureMessage = 'Unable to find a prebuilt dart sdk at:'
' "${fileSystem.path.join('/flutter', 'prebuilts', 'linux-x64', 'dart-sdk')}"';
expect(
() => artifacts.getArtifactPath(
Artifact.frontendServerSnapshotForEngineDartSdk,
platform: TargetPlatform.web_javascript),
throwsToolExit(message: failureMessage),
);
expect(
() => artifacts.getArtifactPath(
Artifact.engineDartSdkPath,
platform: TargetPlatform.web_javascript),
throwsToolExit(message: failureMessage),
);
expect(
() => artifacts.getArtifactPath(
Artifact.engineDartBinary,
platform: TargetPlatform.web_javascript),
throwsToolExit(message: failureMessage),
);
expect(
() => artifacts.getArtifactPath(
Artifact.dart2jsSnapshot,
platform: TargetPlatform.web_javascript),
throwsToolExit(message: failureMessage),
);
fileSystem
.directory('flutter')
.childDirectory('prebuilts')
.childDirectory('linux-x64')
.childDirectory('dart-sdk')
.childDirectory('bin')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(
Artifact.frontendServerSnapshotForEngineDartSdk,
platform: TargetPlatform.web_javascript),
fileSystem.path.join('/flutter', 'prebuilts', 'linux-x64', 'dart-sdk', 'bin',
'snapshots', 'frontend_server_aot.dart.snapshot'),
);
expect(
artifacts.getArtifactPath(
Artifact.engineDartSdkPath,
platform: TargetPlatform.web_javascript),
fileSystem.path.join('/flutter', 'prebuilts', 'linux-x64', 'dart-sdk'),
);
expect(
artifacts.getArtifactPath(
Artifact.engineDartBinary,
platform: TargetPlatform.web_javascript),
fileSystem.path.join('/flutter', 'prebuilts', 'linux-x64', 'dart-sdk', 'bin', 'dart'),
);
expect(
artifacts.getArtifactPath(
Artifact.dart2jsSnapshot,
platform: TargetPlatform.web_javascript),
fileSystem.path.join('/flutter', 'prebuilts', 'linux-x64', 'dart-sdk',
'bin', 'snapshots', 'dart2js.dart.snapshot'),
);
});
testWithoutContext('getEngineType', () {
expect(
artifacts.getEngineType(TargetPlatform.android_arm, BuildMode.debug),
'android_debug_unopt',
);
expect(
artifacts.getEngineType(TargetPlatform.ios, BuildMode.release),
'android_debug_unopt',
);
expect(
artifacts.getEngineType(TargetPlatform.darwin),
'android_debug_unopt',
);
});
testWithoutContext('Looks up dart.exe on windows platforms', () async {
artifacts = CachedLocalWebSdkArtifacts(
parent: CachedLocalEngineArtifacts(
fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'host_debug_unopt'),
engineOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'android_debug_unopt'),
cache: cache,
fileSystem: fileSystem,
platform: FakePlatform(operatingSystem: 'windows'),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
),
webSdkPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'wasm_release'),
fileSystem: fileSystem,
platform: FakePlatform(operatingSystem: 'windows'),
operatingSystemUtils: FakeOperatingSystemUtils());
fileSystem
.directory('out')
.childDirectory('host_debug_unopt')
.childDirectory('dart-sdk')
.childDirectory('bin')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(Artifact.engineDartBinary),
fileSystem.path.join('/out', 'host_debug_unopt', 'dart-sdk', 'bin', 'dart.exe'),
);
});
testWithoutContext('Looks up dart on linux platforms', () async {
fileSystem
.directory('/out')
.childDirectory('host_debug_unopt')
.childDirectory('dart-sdk')
.childDirectory('bin')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(Artifact.engineDartBinary),
fileSystem.path.join('/out', 'host_debug_unopt', 'dart-sdk', 'bin', 'dart'),
);
});
testWithoutContext('Finds dart-sdk in windows prebuilts for web platform', () async {
artifacts = CachedLocalWebSdkArtifacts(
parent: CachedLocalEngineArtifacts(
fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'host_debug_unopt'),
engineOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'android_debug_unopt'),
cache: cache,
fileSystem: fileSystem,
platform: FakePlatform(operatingSystem: 'windows'),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
),
webSdkPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'wasm_release'),
fileSystem: fileSystem,
platform: FakePlatform(operatingSystem: 'windows'),
operatingSystemUtils: FakeOperatingSystemUtils());
fileSystem
.directory('/flutter')
.childDirectory('prebuilts')
.childDirectory('windows-x64')
.childDirectory('dart-sdk')
.childDirectory('bin')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(Artifact.engineDartBinary, platform: TargetPlatform.web_javascript),
fileSystem.path.join('/flutter', 'prebuilts', 'windows-x64', 'dart-sdk', 'bin', 'dart.exe'),
);
});
testWithoutContext('Finds dart-sdk in macos prebuilts for web platform', () async {
artifacts = CachedLocalWebSdkArtifacts(
parent: CachedLocalEngineArtifacts(
fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'host_debug_unopt'),
engineOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'android_debug_unopt'),
cache: cache,
fileSystem: fileSystem,
platform: FakePlatform(operatingSystem: 'macos'),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
),
webSdkPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'wasm_release'),
fileSystem: fileSystem,
platform: FakePlatform(operatingSystem: 'macos'),
operatingSystemUtils: FakeOperatingSystemUtils());
fileSystem
.directory('/flutter')
.childDirectory('prebuilts')
.childDirectory('macos-x64')
.childDirectory('dart-sdk')
.childDirectory('bin')
.createSync(recursive: true);
expect(
artifacts.getArtifactPath(Artifact.engineDartBinary, platform: TargetPlatform.web_javascript),
fileSystem.path.join('/flutter', 'prebuilts', 'macos-x64', 'dart-sdk', 'bin', 'dart'),
);
});
});
group('LocalEngineInfo', () {
late FileSystem fileSystem;
late LocalEngineInfo localEngineInfo;
setUp(() {
fileSystem = MemoryFileSystem.test();
});
testUsingContext('determines the target device name from the path', () {
localEngineInfo = LocalEngineInfo(
targetOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'android_debug_unopt'),
hostOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'host_debug_unopt'),
);
expect(localEngineInfo.localTargetName, 'android_debug_unopt');
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('determines the target device name from the path when using a custom engine path', () {
localEngineInfo = LocalEngineInfo(
targetOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'android_debug_unopt'),
hostOutPath: fileSystem.path.join(fileSystem.currentDirectory.path, 'out', 'host_debug_unopt'),
);
expect(localEngineInfo.localHostName, 'host_debug_unopt');
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
}
| flutter/packages/flutter_tools/test/general.shard/artifacts_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/artifacts_test.dart",
"repo_id": "flutter",
"token_count": 12282
} | 823 |
// 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' as io;
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/signals.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
class LocalFileSystemFake extends LocalFileSystem {
LocalFileSystemFake.test({required super.signals}) : super.test();
@override
Directory get superSystemTempDirectory => directory('/does_not_exist');
}
void main() {
group('fsUtils', () {
late MemoryFileSystem fs;
late FileSystemUtils fsUtils;
setUp(() {
fs = MemoryFileSystem.test();
fsUtils = FileSystemUtils(
fileSystem: fs,
platform: FakePlatform(),
);
});
testWithoutContext('getUniqueFile creates a unique file name', () async {
final File fileA = fsUtils.getUniqueFile(fs.currentDirectory, 'foo', 'json')
..createSync();
final File fileB = fsUtils.getUniqueFile(fs.currentDirectory, 'foo', 'json');
expect(fileA.path, '/foo_01.json');
expect(fileB.path, '/foo_02.json');
});
testWithoutContext('getUniqueDirectory creates a unique directory name', () async {
final Directory directoryA = fsUtils.getUniqueDirectory(fs.currentDirectory, 'foo')
..createSync();
final Directory directoryB = fsUtils.getUniqueDirectory(fs.currentDirectory, 'foo');
expect(directoryA.path, '/foo_01');
expect(directoryB.path, '/foo_02');
});
});
group('copyDirectorySync', () {
/// Test file_systems.copyDirectorySync() using MemoryFileSystem.
/// Copies between 2 instances of file systems which is also supported by copyDirectorySync().
testWithoutContext('test directory copy', () async {
final MemoryFileSystem sourceMemoryFs = MemoryFileSystem.test();
const String sourcePath = '/some/origin';
final Directory sourceDirectory = await sourceMemoryFs.directory(sourcePath).create(recursive: true);
sourceMemoryFs.currentDirectory = sourcePath;
final File sourceFile1 = sourceMemoryFs.file('some_file.txt')..writeAsStringSync('bleh');
final DateTime writeTime = sourceFile1.lastModifiedSync();
sourceMemoryFs.file('sub_dir/another_file.txt').createSync(recursive: true);
sourceMemoryFs.directory('empty_directory').createSync();
// Copy to another memory file system instance.
final MemoryFileSystem targetMemoryFs = MemoryFileSystem.test();
const String targetPath = '/some/non-existent/target';
final Directory targetDirectory = targetMemoryFs.directory(targetPath);
copyDirectory(sourceDirectory, targetDirectory);
expect(targetDirectory.existsSync(), true);
targetMemoryFs.currentDirectory = targetPath;
expect(targetMemoryFs.directory('empty_directory').existsSync(), true);
expect(targetMemoryFs.file('sub_dir/another_file.txt').existsSync(), true);
expect(targetMemoryFs.file('some_file.txt').readAsStringSync(), 'bleh');
// Assert that the copy operation hasn't modified the original file in some way.
expect(sourceMemoryFs.file('some_file.txt').lastModifiedSync(), writeTime);
// There's still 3 things in the original directory as there were initially.
expect(sourceMemoryFs.directory(sourcePath).listSync().length, 3);
});
testWithoutContext('test directory copy with followLinks: true', () async {
final Signals signals = Signals.test();
final LocalFileSystem fileSystem = LocalFileSystem.test(
signals: signals,
);
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_copy_directory.');
try {
final String sourcePath = io.Platform.isWindows ? r'some\origin' : 'some/origin';
final Directory sourceDirectory = tempDir.childDirectory(sourcePath)..createSync(recursive: true);
final File sourceFile1 = sourceDirectory.childFile('some_file.txt')..writeAsStringSync('file 1');
sourceDirectory.childLink('absolute_linked.txt').createSync(sourceFile1.absolute.path);
final DateTime writeTime = sourceFile1.lastModifiedSync();
final Directory sourceSubDirectory = sourceDirectory.childDirectory('dir1').childDirectory('dir2')..createSync(recursive: true);
sourceSubDirectory.childFile('another_file.txt').writeAsStringSync('file 2');
final String subdirectorySourcePath = io.Platform.isWindows ? r'dir1\dir2' : 'dir1/dir2';
sourceDirectory.childLink('relative_linked_sub_dir').createSync(subdirectorySourcePath);
sourceDirectory.childDirectory('empty_directory').createSync(recursive: true);
final String targetPath = io.Platform.isWindows ? r'some\non-existent\target' : 'some/non-existent/target';
final Directory targetDirectory = tempDir.childDirectory(targetPath);
copyDirectory(sourceDirectory, targetDirectory);
expect(targetDirectory.existsSync(), true);
expect(targetDirectory.childFile('some_file.txt').existsSync(), true);
expect(targetDirectory.childFile('some_file.txt').readAsStringSync(), 'file 1');
expect(targetDirectory.childFile('absolute_linked.txt').readAsStringSync(), 'file 1');
expect(targetDirectory.childLink('absolute_linked.txt').existsSync(), false);
expect(targetDirectory.childDirectory('dir1').childDirectory('dir2').existsSync(), true);
expect(targetDirectory.childDirectory('dir1').childDirectory('dir2').childFile('another_file.txt').existsSync(), true);
expect(targetDirectory.childDirectory('dir1').childDirectory('dir2').childFile('another_file.txt').readAsStringSync(), 'file 2');
expect(targetDirectory.childDirectory('relative_linked_sub_dir').existsSync(), true);
expect(targetDirectory.childLink('relative_linked_sub_dir').existsSync(), false);
expect(targetDirectory.childDirectory('relative_linked_sub_dir').childFile('another_file.txt').existsSync(), true);
expect(targetDirectory.childDirectory('relative_linked_sub_dir').childFile('another_file.txt').readAsStringSync(), 'file 2');
expect(targetDirectory.childDirectory('empty_directory').existsSync(), true);
// Assert that the copy operation hasn't modified the original file in some way.
expect(sourceDirectory.childFile('some_file.txt').lastModifiedSync(), writeTime);
// There's still 5 things in the original directory as there were initially.
expect(sourceDirectory.listSync().length, 5);
} finally {
tryToDelete(tempDir);
}
});
testWithoutContext('test directory copy with followLinks: false', () async {
final Signals signals = Signals.test();
final LocalFileSystem fileSystem = LocalFileSystem.test(
signals: signals,
);
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_copy_directory.');
try {
final String sourcePath = io.Platform.isWindows ? r'some\origin' : 'some/origin';
final Directory sourceDirectory = tempDir.childDirectory(sourcePath)..createSync(recursive: true);
final File sourceFile1 = sourceDirectory.childFile('some_file.txt')..writeAsStringSync('file 1');
sourceDirectory.childLink('absolute_linked.txt').createSync(sourceFile1.absolute.path);
final DateTime writeTime = sourceFile1.lastModifiedSync();
final Directory sourceSubDirectory = sourceDirectory.childDirectory('dir1').childDirectory('dir2')..createSync(recursive: true);
sourceSubDirectory.childFile('another_file.txt').writeAsStringSync('file 2');
final String subdirectorySourcePath = io.Platform.isWindows ? r'dir1\dir2' : 'dir1/dir2';
sourceDirectory.childLink('relative_linked_sub_dir').createSync(subdirectorySourcePath);
sourceDirectory.childDirectory('empty_directory').createSync(recursive: true);
final String targetPath = io.Platform.isWindows ? r'some\non-existent\target' : 'some/non-existent/target';
final Directory targetDirectory = tempDir.childDirectory(targetPath);
copyDirectory(sourceDirectory, targetDirectory, followLinks: false);
expect(targetDirectory.existsSync(), true);
expect(targetDirectory.childFile('some_file.txt').existsSync(), true);
expect(targetDirectory.childFile('some_file.txt').readAsStringSync(), 'file 1');
expect(targetDirectory.childFile('absolute_linked.txt').readAsStringSync(), 'file 1');
expect(targetDirectory.childLink('absolute_linked.txt').existsSync(), true);
expect(
targetDirectory.childLink('absolute_linked.txt').targetSync(),
sourceFile1.absolute.path,
);
expect(targetDirectory.childDirectory('dir1').childDirectory('dir2').existsSync(), true);
expect(targetDirectory.childDirectory('dir1').childDirectory('dir2').childFile('another_file.txt').existsSync(), true);
expect(targetDirectory.childDirectory('dir1').childDirectory('dir2').childFile('another_file.txt').readAsStringSync(), 'file 2');
expect(targetDirectory.childDirectory('relative_linked_sub_dir').existsSync(), true);
expect(targetDirectory.childLink('relative_linked_sub_dir').existsSync(), true);
expect(
targetDirectory.childLink('relative_linked_sub_dir').targetSync(),
subdirectorySourcePath,
);
expect(targetDirectory.childDirectory('relative_linked_sub_dir').childFile('another_file.txt').existsSync(), true);
expect(targetDirectory.childDirectory('relative_linked_sub_dir').childFile('another_file.txt').readAsStringSync(), 'file 2');
expect(targetDirectory.childDirectory('empty_directory').existsSync(), true);
// Assert that the copy operation hasn't modified the original file in some way.
expect(sourceDirectory.childFile('some_file.txt').lastModifiedSync(), writeTime);
// There's still 5 things in the original directory as there were initially.
expect(sourceDirectory.listSync().length, 5);
} finally {
tryToDelete(tempDir);
}
});
testWithoutContext('Skip files if shouldCopyFile returns false', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final Directory origin = fileSystem.directory('/origin');
origin.createSync();
fileSystem.file(fileSystem.path.join('origin', 'a.txt')).writeAsStringSync('irrelevant');
fileSystem.directory('/origin/nested').createSync();
fileSystem.file(fileSystem.path.join('origin', 'nested', 'a.txt')).writeAsStringSync('irrelevant');
fileSystem.file(fileSystem.path.join('origin', 'nested', 'b.txt')).writeAsStringSync('irrelevant');
final Directory destination = fileSystem.directory('/destination');
copyDirectory(origin, destination, shouldCopyFile: (File origin, File dest) {
return origin.basename == 'b.txt';
});
expect(destination.existsSync(), isTrue);
expect(destination.childDirectory('nested').existsSync(), isTrue);
expect(destination.childDirectory('nested').childFile('b.txt').existsSync(), isTrue);
expect(destination.childFile('a.txt').existsSync(), isFalse);
expect(destination.childDirectory('nested').childFile('a.txt').existsSync(), isFalse);
});
testWithoutContext('Skip directories if shouldCopyDirectory returns false', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final Directory origin = fileSystem.directory('/origin');
origin.createSync();
fileSystem.file(fileSystem.path.join('origin', 'a.txt')).writeAsStringSync('irrelevant');
fileSystem.directory('/origin/nested').createSync();
fileSystem.file(fileSystem.path.join('origin', 'nested', 'a.txt')).writeAsStringSync('irrelevant');
fileSystem.file(fileSystem.path.join('origin', 'nested', 'b.txt')).writeAsStringSync('irrelevant');
final Directory destination = fileSystem.directory('/destination');
copyDirectory(origin, destination, shouldCopyDirectory: (Directory directory) {
return !directory.path.endsWith('nested');
});
expect(destination, exists);
expect(destination.childDirectory('nested'), isNot(exists));
expect(destination.childDirectory('nested').childFile('b.txt'),isNot(exists));
});
});
group('escapePath', () {
testWithoutContext('on Windows', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FileSystemUtils fsUtils = FileSystemUtils(
fileSystem: fileSystem,
platform: FakePlatform(operatingSystem: 'windows'),
);
expect(fsUtils.escapePath(r'C:\foo\bar\cool.dart'), r'C:\\foo\\bar\\cool.dart');
expect(fsUtils.escapePath(r'foo\bar\cool.dart'), r'foo\\bar\\cool.dart');
expect(fsUtils.escapePath('C:/foo/bar/cool.dart'), 'C:/foo/bar/cool.dart');
});
testWithoutContext('on Linux', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FileSystemUtils fsUtils = FileSystemUtils(
fileSystem: fileSystem,
platform: FakePlatform(),
);
expect(fsUtils.escapePath('/foo/bar/cool.dart'), '/foo/bar/cool.dart');
expect(fsUtils.escapePath('foo/bar/cool.dart'), 'foo/bar/cool.dart');
expect(fsUtils.escapePath(r'foo\cool.dart'), r'foo\cool.dart');
});
});
group('LocalFileSystem', () {
late FakeProcessSignal fakeSignal;
late ProcessSignal signalUnderTest;
setUp(() {
fakeSignal = FakeProcessSignal();
signalUnderTest = ProcessSignal(fakeSignal);
});
testWithoutContext('runs shutdown hooks', () async {
final Signals signals = Signals.test();
final LocalFileSystem localFileSystem = LocalFileSystem.test(
signals: signals,
);
final Directory temp = localFileSystem.systemTempDirectory;
expect(temp.existsSync(), isTrue);
expect(localFileSystem.shutdownHooks.registeredHooks, hasLength(1));
final BufferLogger logger = BufferLogger.test();
await localFileSystem.shutdownHooks.runShutdownHooks(logger);
expect(temp.existsSync(), isFalse);
expect(logger.traceText, contains('Running 1 shutdown hook'));
});
testWithoutContext('deletes system temp entry on a fatal signal', () async {
final Completer<void> completer = Completer<void>();
final Signals signals = Signals.test();
final LocalFileSystem localFileSystem = LocalFileSystem.test(
signals: signals,
fatalSignals: <ProcessSignal>[signalUnderTest],
);
final Directory temp = localFileSystem.systemTempDirectory;
signals.addHandler(signalUnderTest, (ProcessSignal s) {
completer.complete();
});
expect(temp.existsSync(), isTrue);
fakeSignal.controller.add(fakeSignal);
await completer.future;
expect(temp.existsSync(), isFalse);
});
testWithoutContext('throwToolExit when temp not found', () async {
final Signals signals = Signals.test();
final LocalFileSystemFake localFileSystem = LocalFileSystemFake.test(
signals: signals,
);
try {
localFileSystem.systemTempDirectory;
fail('expected tool exit');
} on ToolExit catch (e) {
expect(e.message, 'Your system temp directory (/does_not_exist) does not exist. '
'Did you set an invalid override in your environment? '
'See issue https://github.com/flutter/flutter/issues/74042 for more context.'
);
}
});
});
}
class FakeProcessSignal extends Fake implements io.ProcessSignal {
final StreamController<io.ProcessSignal> controller = StreamController<io.ProcessSignal>();
@override
Stream<io.ProcessSignal> watch() => controller.stream;
}
| flutter/packages/flutter_tools/test/general.shard/base/file_system_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/base/file_system_test.dart",
"repo_id": "flutter",
"token_count": 5490
} | 824 |
// 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:file/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/utils.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/exceptions.dart';
import 'package:flutter_tools/src/convert.dart';
import '../../src/common.dart';
import '../../src/fake_process_manager.dart';
void main() {
late FileSystem fileSystem;
late Environment environment;
late TestTarget fooTarget;
late TestTarget barTarget;
late TestTarget fizzTarget;
late TestTarget sharedTarget;
late int fooInvocations;
late int barInvocations;
late int shared;
setUp(() {
fileSystem = MemoryFileSystem.test();
fooInvocations = 0;
barInvocations = 0;
shared = 0;
/// Create various test targets.
fooTarget = TestTarget((Environment environment) async {
environment
.buildDir
.childFile('out')
..createSync(recursive: true)
..writeAsStringSync('hey');
fooInvocations++;
})
..name = 'foo'
..inputs = const <Source>[
Source.pattern('{PROJECT_DIR}/foo.dart'),
]
..outputs = const <Source>[
Source.pattern('{BUILD_DIR}/out'),
]
..dependencies = <Target>[];
barTarget = TestTarget((Environment environment) async {
environment.buildDir
.childFile('bar')
..createSync(recursive: true)
..writeAsStringSync('there');
barInvocations++;
})
..name = 'bar'
..inputs = const <Source>[
Source.pattern('{BUILD_DIR}/out'),
]
..outputs = const <Source>[
Source.pattern('{BUILD_DIR}/bar'),
]
..dependencies = <Target>[];
fizzTarget = TestTarget((Environment environment) async {
throw Exception('something bad happens');
})
..name = 'fizz'
..inputs = const <Source>[
Source.pattern('{BUILD_DIR}/out'),
]
..outputs = const <Source>[
Source.pattern('{BUILD_DIR}/fizz'),
]
..dependencies = <Target>[fooTarget];
sharedTarget = TestTarget((Environment environment) async {
shared += 1;
})
..name = 'shared'
..inputs = const <Source>[
Source.pattern('{PROJECT_DIR}/foo.dart'),
];
final Artifacts artifacts = Artifacts.test();
environment = Environment.test(
fileSystem.currentDirectory,
artifacts: artifacts,
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
fileSystem.file('foo.dart')
..createSync(recursive: true)
..writeAsStringSync('');
fileSystem.file('pubspec.yaml').createSync();
});
testWithoutContext('Does not throw exception if asked to build with missing inputs', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
// Delete required input file.
fileSystem.file('foo.dart').deleteSync();
final BuildResult buildResult = await buildSystem.build(fooTarget, environment);
expect(buildResult.hasException, false);
});
testWithoutContext('Does not throw exception if it does not produce a specified output', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
// This target is document as producing foo.dart but does not actually
// output this value.
final Target badTarget = TestTarget((Environment environment) async {})
..inputs = const <Source>[
Source.pattern('{PROJECT_DIR}/foo.dart'),
]
..outputs = const <Source>[
Source.pattern('{BUILD_DIR}/out'),
];
final BuildResult result = await buildSystem.build(badTarget, environment);
expect(result.hasException, false);
});
testWithoutContext('Saves a stamp file with inputs and outputs', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
final File stampFile = fileSystem.file(
'${environment.buildDir.path}/foo.stamp');
expect(stampFile, exists);
final Map<String, Object?>? stampContents = castStringKeyedMap(
json.decode(stampFile.readAsStringSync()));
expect(stampContents, containsPair('inputs', <Object>['/foo.dart']));
expect(stampContents!.containsKey('buildKey'), false);
});
testWithoutContext('Saves a stamp file with inputs, outputs and build key', () async {
fooTarget.buildKey = 'fooBuildKey';
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
final File stampFile = fileSystem.file(
'${environment.buildDir.path}/foo.stamp');
expect(stampFile, exists);
final Map<String, Object?>? stampContents = castStringKeyedMap(
json.decode(stampFile.readAsStringSync()));
expect(stampContents, containsPair('inputs', <Object>['/foo.dart']));
expect(stampContents, containsPair('buildKey', 'fooBuildKey'));
});
testWithoutContext('Creates a BuildResult with inputs and outputs', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
final BuildResult result = await buildSystem.build(fooTarget, environment);
expect(result.inputFiles.single.path, '/foo.dart');
expect(result.outputFiles.single.path, '${environment.buildDir.path}/out');
});
testWithoutContext('Does not re-invoke build if stamp is valid', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
await buildSystem.build(fooTarget, environment);
expect(fooInvocations, 1);
});
testWithoutContext('Re-invoke build if input is modified', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
fileSystem.file('foo.dart').writeAsStringSync('new contents');
await buildSystem.build(fooTarget, environment);
expect(fooInvocations, 2);
});
testWithoutContext('Re-invoke build if build key is modified', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
fooTarget.buildKey = 'old';
await buildSystem.build(fooTarget, environment);
fooTarget.buildKey = 'new';
await buildSystem.build(fooTarget, environment);
expect(fooInvocations, 2);
});
testWithoutContext('does not re-invoke build if input timestamp changes', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
// The file was previously empty so this does not modify it.
fileSystem.file('foo.dart').writeAsStringSync('');
await buildSystem.build(fooTarget, environment);
expect(fooInvocations, 1);
});
testWithoutContext('does not re-invoke build if output timestamp changes', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
// This is the same content that the output file previously
// contained.
environment.buildDir.childFile('out').writeAsStringSync('hey');
await buildSystem.build(fooTarget, environment);
expect(fooInvocations, 1);
});
testWithoutContext('Re-invoke build if output is modified', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
await buildSystem.build(fooTarget, environment);
environment.buildDir.childFile('out').writeAsStringSync('Something different');
await buildSystem.build(fooTarget, environment);
expect(fooInvocations, 2);
});
testWithoutContext('Runs dependencies of targets', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
barTarget.dependencies.add(fooTarget);
await buildSystem.build(barTarget, environment);
expect(fileSystem.file('${environment.buildDir.path}/bar'), exists);
expect(fooInvocations, 1);
expect(barInvocations, 1);
});
testWithoutContext('Only invokes shared dependencies once', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
fooTarget.dependencies.add(sharedTarget);
barTarget.dependencies.add(sharedTarget);
barTarget.dependencies.add(fooTarget);
await buildSystem.build(barTarget, environment);
expect(shared, 1);
});
testWithoutContext('Automatically cleans old outputs when build graph changes', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
final TestTarget testTarget = TestTarget((Environment environment) async {
environment.buildDir.childFile('foo.out').createSync();
})
..inputs = const <Source>[Source.pattern('{PROJECT_DIR}/foo.dart')]
..outputs = const <Source>[Source.pattern('{BUILD_DIR}/foo.out')];
fileSystem.file('foo.dart').createSync();
await buildSystem.build(testTarget, environment);
expect(environment.buildDir.childFile('foo.out'), exists);
final TestTarget testTarget2 = TestTarget((Environment environment) async {
environment.buildDir.childFile('bar.out').createSync();
})
..inputs = const <Source>[Source.pattern('{PROJECT_DIR}/foo.dart')]
..outputs = const <Source>[Source.pattern('{BUILD_DIR}/bar.out')];
await buildSystem.build(testTarget2, environment);
expect(environment.buildDir.childFile('bar.out'), exists);
expect(environment.buildDir.childFile('foo.out'), isNot(exists));
});
testWithoutContext('Does not crash when filesystem and cache are out of sync', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
final TestTarget testWithoutContextTarget = TestTarget((Environment environment) async {
environment.buildDir.childFile('foo.out').createSync();
})
..inputs = const <Source>[Source.pattern('{PROJECT_DIR}/foo.dart')]
..outputs = const <Source>[Source.pattern('{BUILD_DIR}/foo.out')];
fileSystem.file('foo.dart').createSync();
await buildSystem.build(testWithoutContextTarget, environment);
expect(environment.buildDir.childFile('foo.out'), exists);
environment.buildDir.childFile('foo.out').deleteSync();
final TestTarget testWithoutContextTarget2 = TestTarget((Environment environment) async {
environment.buildDir.childFile('bar.out').createSync();
})
..inputs = const <Source>[Source.pattern('{PROJECT_DIR}/foo.dart')]
..outputs = const <Source>[Source.pattern('{BUILD_DIR}/bar.out')];
await buildSystem.build(testWithoutContextTarget2, environment);
expect(environment.buildDir.childFile('bar.out'), exists);
expect(environment.buildDir.childFile('foo.out'), isNot(exists));
});
testWithoutContext('Reruns build if stamp is corrupted', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
final TestTarget testWithoutContextTarget = TestTarget((Environment environment) async {
environment.buildDir.childFile('foo.out').createSync();
})
..inputs = const <Source>[Source.pattern('{PROJECT_DIR}/foo.dart')]
..outputs = const <Source>[Source.pattern('{BUILD_DIR}/foo.out')];
fileSystem.file('foo.dart').createSync();
await buildSystem.build(testWithoutContextTarget, environment);
// invalid JSON
environment.buildDir.childFile('testWithoutContext.stamp').writeAsStringSync('{X');
await buildSystem.build(testWithoutContextTarget, environment);
// empty file
environment.buildDir.childFile('testWithoutContext.stamp').writeAsStringSync('');
await buildSystem.build(testWithoutContextTarget, environment);
// invalid format
environment.buildDir.childFile('testWithoutContext.stamp').writeAsStringSync('{"inputs": 2, "outputs": 3}');
await buildSystem.build(testWithoutContextTarget, environment);
});
testWithoutContext('handles a throwing build action without crashing', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
final BuildResult result = await buildSystem.build(fizzTarget, environment);
expect(result.hasException, true);
});
testWithoutContext('Can describe itself with JSON output', () {
environment.buildDir.createSync(recursive: true);
expect(fooTarget.toJson(environment), <String, Object?>{
'inputs': <Object>[
'/foo.dart',
],
'outputs': <Object>[
fileSystem.path.join(environment.buildDir.path, 'out'),
],
'dependencies': <Object>[],
'name': 'foo',
'stamp': fileSystem.path.join(environment.buildDir.path, 'foo.stamp'),
});
});
testWithoutContext('Can find dependency cycles', () {
final Target barTarget = TestTarget()..name = 'bar';
final Target fooTarget = TestTarget()..name = 'foo';
barTarget.dependencies.add(fooTarget);
fooTarget.dependencies.add(barTarget);
expect(() => checkCycles(barTarget), throwsA(isA<CycleException>()));
});
testWithoutContext('Target with depfile dependency will not run twice without invalidation', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
int called = 0;
final TestTarget target = TestTarget((Environment environment) async {
environment.buildDir
.childFile('example.d')
.writeAsStringSync('a.txt: b.txt');
fileSystem.file('a.txt').writeAsStringSync('a');
called += 1;
})
..depfiles = <String>['example.d'];
fileSystem.file('b.txt').writeAsStringSync('b');
await buildSystem.build(target, environment);
expect(fileSystem.file('a.txt'), exists);
expect(called, 1);
// Second build is up to date due to depfile parse.
await buildSystem.build(target, environment);
expect(called, 1);
});
testWithoutContext('Target with depfile dependency will not run twice without '
'invalidation in incremental builds', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
int called = 0;
final TestTarget target = TestTarget((Environment environment) async {
environment.buildDir
.childFile('example.d')
.writeAsStringSync('a.txt: b.txt');
fileSystem.file('a.txt').writeAsStringSync('a');
called += 1;
})
..depfiles = <String>['example.d'];
fileSystem.file('b.txt').writeAsStringSync('b');
final BuildResult result = await buildSystem
.buildIncremental(target, environment, null);
expect(fileSystem.file('a.txt'), exists);
expect(called, 1);
// Second build is up to date due to depfile parse.
await buildSystem.buildIncremental(target, environment, result);
expect(called, 1);
});
testWithoutContext('output directory is an input to the build', () async {
final Environment environmentA = Environment.test(
fileSystem.currentDirectory,
outputDir: fileSystem.directory('a'),
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
final Environment environmentB = Environment.test(
fileSystem.currentDirectory,
outputDir: fileSystem.directory('b'),
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
expect(environmentA.buildDir.path, isNot(environmentB.buildDir.path));
});
testWithoutContext('Additional inputs do not change the build configuration', () async {
final Environment environmentA = Environment.test(
fileSystem.currentDirectory,
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
inputs: <String, String>{
'C': 'D',
}
);
final Environment environmentB = Environment.test(
fileSystem.currentDirectory,
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
inputs: <String, String>{
'A': 'B',
}
);
expect(environmentA.buildDir.path, equals(environmentB.buildDir.path));
});
testWithoutContext('A target with depfile dependencies can delete stale outputs on the first run', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
int called = 0;
final TestTarget target = TestTarget((Environment environment) async {
if (called == 0) {
environment.buildDir.childFile('example.d')
.writeAsStringSync('a.txt c.txt: b.txt');
fileSystem.file('a.txt').writeAsStringSync('a');
fileSystem.file('c.txt').writeAsStringSync('a');
} else {
// On second run, we no longer claim c.txt as an output.
environment.buildDir.childFile('example.d')
.writeAsStringSync('a.txt: b.txt');
fileSystem.file('a.txt').writeAsStringSync('a');
}
called += 1;
})
..depfiles = const <String>['example.d'];
fileSystem.file('b.txt').writeAsStringSync('b');
await buildSystem.build(target, environment);
expect(fileSystem.file('a.txt'), exists);
expect(fileSystem.file('c.txt'), exists);
expect(called, 1);
// rewrite an input to force a rerun, expect that the old c.txt is deleted.
fileSystem.file('b.txt').writeAsStringSync('ba');
await buildSystem.build(target, environment);
expect(fileSystem.file('a.txt'), exists);
expect(fileSystem.file('c.txt'), isNot(exists));
expect(called, 2);
});
testWithoutContext('trackSharedBuildDirectory handles a missing .last_build_id', () {
FlutterBuildSystem(
fileSystem: fileSystem,
logger: BufferLogger.test(),
platform: FakePlatform(),
).trackSharedBuildDirectory(environment, fileSystem, <String, File>{});
expect(environment.outputDir.childFile('.last_build_id'), exists);
expect(environment.outputDir.childFile('.last_build_id').readAsStringSync(),
'6666cd76f96956469e7be39d750cc7d9');
});
testWithoutContext('trackSharedBuildDirectory handles a missing output dir', () {
final Environment environment = Environment.test(
fileSystem.currentDirectory,
outputDir: fileSystem.directory('a/b/c/d'),
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
FlutterBuildSystem(
fileSystem: fileSystem,
logger: BufferLogger.test(),
platform: FakePlatform(),
).trackSharedBuildDirectory(environment, fileSystem, <String, File>{});
expect(environment.outputDir.childFile('.last_build_id'), exists);
expect(environment.outputDir.childFile('.last_build_id').readAsStringSync(),
'5954e2278dd01e1c4e747578776eeb94');
});
testWithoutContext('trackSharedBuildDirectory does not modify .last_build_id when config is identical', () {
environment.outputDir.childFile('.last_build_id')
..writeAsStringSync('6666cd76f96956469e7be39d750cc7d9')
..setLastModifiedSync(DateTime(1991, 8, 23));
FlutterBuildSystem(
fileSystem: fileSystem,
logger: BufferLogger.test(),
platform: FakePlatform(),
).trackSharedBuildDirectory(environment, fileSystem, <String, File>{});
expect(environment.outputDir.childFile('.last_build_id').lastModifiedSync(),
DateTime(1991, 8, 23));
});
testWithoutContext('trackSharedBuildDirectory does not delete files when outputs.json is missing', () {
environment.outputDir
.childFile('.last_build_id')
.writeAsStringSync('foo');
environment.buildDir.parent
.childDirectory('foo')
.createSync(recursive: true);
environment.outputDir
.childFile('stale')
.createSync();
FlutterBuildSystem(
fileSystem: fileSystem,
logger: BufferLogger.test(),
platform: FakePlatform(),
).trackSharedBuildDirectory(environment, fileSystem, <String, File>{});
expect(environment.outputDir.childFile('.last_build_id').readAsStringSync(),
'6666cd76f96956469e7be39d750cc7d9');
expect(environment.outputDir.childFile('stale'), exists);
});
testWithoutContext('trackSharedBuildDirectory deletes files in outputs.json but not in current outputs', () {
environment.outputDir
.childFile('.last_build_id')
.writeAsStringSync('foo');
final Directory otherBuildDir = environment.buildDir.parent
.childDirectory('foo')
..createSync(recursive: true);
final File staleFile = environment.outputDir
.childFile('stale')
..createSync();
otherBuildDir.childFile('outputs.json')
.writeAsStringSync(json.encode(<String>[staleFile.absolute.path]));
FlutterBuildSystem(
fileSystem: fileSystem,
logger: BufferLogger.test(),
platform: FakePlatform(),
).trackSharedBuildDirectory(environment, fileSystem, <String, File>{});
expect(environment.outputDir.childFile('.last_build_id').readAsStringSync(),
'6666cd76f96956469e7be39d750cc7d9');
expect(environment.outputDir.childFile('stale'), isNot(exists));
});
testWithoutContext('multiple builds to the same output directory do no leave stale artifacts', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
final Environment testEnvironmentDebug = Environment.test(
fileSystem.currentDirectory,
outputDir: fileSystem.directory('output'),
defines: <String, String>{
'config': 'debug',
},
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
logger: BufferLogger.test(),
fileSystem: fileSystem,
);
final Environment testEnvironmentProfile = Environment.test(
fileSystem.currentDirectory,
outputDir: fileSystem.directory('output'),
defines: <String, String>{
'config': 'profile',
},
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
logger: BufferLogger.test(),
fileSystem: fileSystem,
);
final TestTarget debugTarget = TestTarget((Environment environment) async {
environment.outputDir.childFile('debug').createSync();
})..outputs = const <Source>[Source.pattern('{OUTPUT_DIR}/debug')];
final TestTarget releaseTarget = TestTarget((Environment environment) async {
environment.outputDir.childFile('release').createSync();
})..outputs = const <Source>[Source.pattern('{OUTPUT_DIR}/release')];
await buildSystem.build(debugTarget, testEnvironmentDebug);
// Verify debug output was created
expect(fileSystem.file('output/debug'), exists);
await buildSystem.build(releaseTarget, testEnvironmentProfile);
// Last build config is updated properly
expect(testEnvironmentProfile.outputDir.childFile('.last_build_id'), exists);
expect(testEnvironmentProfile.outputDir.childFile('.last_build_id').readAsStringSync(),
'c20b3747fb2aa148cc4fd39bfbbd894f');
// Verify debug output removed
expect(fileSystem.file('output/debug'), isNot(exists));
expect(fileSystem.file('output/release'), exists);
});
testWithoutContext('A target using canSkip can create a conditional output', () async {
final BuildSystem buildSystem = setUpBuildSystem(fileSystem);
final File bar = environment.buildDir.childFile('bar');
final File foo = environment.buildDir.childFile('foo');
// The target will write a file `foo`, but only if `bar` already exists.
final TestTarget target = TestTarget(
(Environment environment) async {
foo.writeAsStringSync(bar.readAsStringSync());
environment.buildDir
.childFile('example.d')
.writeAsStringSync('${foo.path}: ${bar.path}');
},
(Environment environment) {
return !environment.buildDir.childFile('bar').existsSync();
}
)
..depfiles = const <String>['example.d'];
// bar does not exist, there should be no inputs/outputs.
final BuildResult firstResult = await buildSystem.build(target, environment);
expect(foo, isNot(exists));
expect(firstResult.inputFiles, isEmpty);
expect(firstResult.outputFiles, isEmpty);
// bar is created, the target should be able to run.
bar.writeAsStringSync('content-1');
final BuildResult secondResult = await buildSystem.build(target, environment);
expect(foo, exists);
expect(secondResult.inputFiles.map((File file) => file.path), <String>[bar.path]);
expect(secondResult.outputFiles.map((File file) => file.path), <String>[foo.path]);
// bar is destroyed, foo is also deleted.
bar.deleteSync();
final BuildResult thirdResult = await buildSystem.build(target, environment);
expect(foo, isNot(exists));
expect(thirdResult.inputFiles, isEmpty);
expect(thirdResult.outputFiles, isEmpty);
});
testWithoutContext('Build completes all dependencies before failing', () async {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final BuildSystem buildSystem = setUpBuildSystem(fileSystem, FakePlatform(
numberOfProcessors: 10, // Ensure the tool will process tasks concurrently.
));
final Completer<void> startB = Completer<void>();
final Completer<void> startC = Completer<void>();
final Completer<void> finishB = Completer<void>();
final TestTarget a = TestTarget((Environment environment) {
throw StateError('Should not run');
})..name = 'A';
final TestTarget b = TestTarget((Environment environment) async {
startB.complete();
await finishB.future;
throw Exception('1');
})..name = 'B';
final TestTarget c = TestTarget((Environment environment) {
startC.complete();
throw Exception('2');
})..name = 'C';
a.dependencies.addAll(<Target>[b, c]);
final Future<BuildResult> pendingResult = buildSystem.build(a, environment);
await startB.future;
await startC.future;
finishB.complete();
final BuildResult result = await pendingResult;
expect(result.success, false);
expect(result.exceptions.keys, containsAll(<String>['B', 'C']));
});
}
BuildSystem setUpBuildSystem(FileSystem fileSystem, [FakePlatform? platform]) {
return FlutterBuildSystem(
fileSystem: fileSystem,
logger: BufferLogger.test(),
platform: platform ?? FakePlatform(),
);
}
class TestTarget extends Target {
TestTarget([Future<void> Function(Environment environment)? build, this._canSkip])
: _build = build ?? ((Environment environment) async {});
final Future<void> Function(Environment environment) _build;
final bool Function(Environment environment)? _canSkip;
@override
bool canSkip(Environment environment) {
if (_canSkip != null) {
return _canSkip(environment);
}
return super.canSkip(environment);
}
@override
Future<void> build(Environment environment) => _build(environment);
@override
List<Target> dependencies = <Target>[];
@override
List<Source> inputs = <Source>[];
@override
List<String> depfiles = <String>[];
@override
String name = 'test';
@override
List<Source> outputs = <Source>[];
@override
String? buildKey;
}
| flutter/packages/flutter_tools/test/general.shard/build_system/build_system_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/build_system/build_system_test.dart",
"repo_id": "flutter",
"token_count": 9223
} | 825 |
// 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/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/targets/common.dart';
import 'package:flutter_tools/src/build_system/targets/linux.dart';
import 'package:flutter_tools/src/convert.dart';
import '../../../src/common.dart';
import '../../../src/context.dart';
void main() {
testWithoutContext('Copies files to correct cache directory, excluding unrelated code on a x64 host', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
final Artifacts artifacts = Artifacts.test();
setUpCacheDirectory(fileSystem, artifacts);
final Environment testEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: 'debug',
},
artifacts: artifacts,
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
testEnvironment.buildDir.createSync(recursive: true);
await const UnpackLinux(TargetPlatform.linux_x64).build(testEnvironment);
expect(fileSystem.file('linux/flutter/ephemeral/libflutter_linux_gtk.so'), exists);
expect(fileSystem.file('linux/flutter/ephemeral/unrelated-stuff'), isNot(exists));
// Check if the target files are copied correctly.
final String headersPathForX64 = artifacts.getArtifactPath(Artifact.linuxHeaders, platform: TargetPlatform.linux_x64, mode: BuildMode.debug);
final String headersPathForArm64 = artifacts.getArtifactPath(Artifact.linuxHeaders, platform: TargetPlatform.linux_arm64, mode: BuildMode.debug);
expect(fileSystem.file('linux/flutter/ephemeral/$headersPathForX64/foo.h'), exists);
expect(fileSystem.file('linux/flutter/ephemeral/$headersPathForArm64/foo.h'), isNot(exists));
final String icuDataPathForX64 = artifacts.getArtifactPath(Artifact.icuData, platform: TargetPlatform.linux_x64);
final String icuDataPathForArm64 = artifacts.getArtifactPath(Artifact.icuData, platform: TargetPlatform.linux_arm64);
expect(fileSystem.file('linux/flutter/ephemeral/$icuDataPathForX64'), exists);
expect(fileSystem.file('linux/flutter/ephemeral/$icuDataPathForArm64'), isNot(exists));
});
// This test is basically the same logic as the above test.
// The difference is the target CPU architecture.
testWithoutContext('Copies files to correct cache directory, excluding unrelated code on a arm64 host', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
final Artifacts artifacts = Artifacts.test();
setUpCacheDirectory(fileSystem, artifacts);
final Environment testEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: 'debug',
},
artifacts: artifacts,
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
testEnvironment.buildDir.createSync(recursive: true);
await const UnpackLinux(TargetPlatform.linux_arm64).build(testEnvironment);
expect(fileSystem.file('linux/flutter/ephemeral/libflutter_linux_gtk.so'), exists);
expect(fileSystem.file('linux/flutter/ephemeral/unrelated-stuff'), isNot(exists));
// Check if the target files are copied correctly.
final String headersPathForX64 = artifacts.getArtifactPath(Artifact.linuxHeaders, platform: TargetPlatform.linux_x64, mode: BuildMode.debug);
final String headersPathForArm64 = artifacts.getArtifactPath(Artifact.linuxHeaders, platform: TargetPlatform.linux_arm64, mode: BuildMode.debug);
expect(fileSystem.file('linux/flutter/ephemeral/$headersPathForX64/foo.h'), isNot(exists));
expect(fileSystem.file('linux/flutter/ephemeral/$headersPathForArm64/foo.h'), exists);
final String icuDataPathForX64 = artifacts.getArtifactPath(Artifact.icuData, platform: TargetPlatform.linux_x64);
final String icuDataPathForArm64 = artifacts.getArtifactPath(Artifact.icuData, platform: TargetPlatform.linux_arm64);
expect(fileSystem.file('linux/flutter/ephemeral/$icuDataPathForX64'), isNot(exists));
expect(fileSystem.file('linux/flutter/ephemeral/$icuDataPathForArm64'), exists);
});
// Only required for the test below that still depends on the context.
late FileSystem fileSystem;
setUp(() {
fileSystem = MemoryFileSystem.test();
});
testUsingContext('DebugBundleLinuxAssets copies artifacts to out directory', () async {
final Environment testEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: 'debug',
kBuildName: '2.0.0',
kBuildNumber: '22',
},
inputs: <String, String>{
kBundleSkSLPath: 'bundle.sksl',
},
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
engineVersion: '2',
);
testEnvironment.buildDir.createSync(recursive: true);
// Create input files.
testEnvironment.buildDir.childFile('app.dill').createSync();
fileSystem.file('bundle.sksl').writeAsStringSync(json.encode(
<String, Object>{
'engineRevision': '2',
'platform': 'ios',
'data': <String, Object>{
'A': 'B',
},
},
));
await const DebugBundleLinuxAssets(TargetPlatform.linux_x64).build(testEnvironment);
final Directory output = testEnvironment.outputDir
.childDirectory('flutter_assets');
expect(output.childFile('kernel_blob.bin'), exists);
expect(output.childFile('AssetManifest.json'), exists);
expect(output.childFile('version.json'), exists);
final String versionFile = output.childFile('version.json').readAsStringSync();
expect(versionFile, contains('"version":"2.0.0"'));
expect(versionFile, contains('"build_number":"22"'));
// SkSL
expect(output.childFile('io.flutter.shaders.json'), exists);
expect(output.childFile('io.flutter.shaders.json').readAsStringSync(), '{"data":{"A":"B"}}');
// No bundled fonts
expect(output.childFile('FontManifest.json'), isNot(exists));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testWithoutContext("DebugBundleLinuxAssets' name depends on target platforms", () async {
expect(const DebugBundleLinuxAssets(TargetPlatform.linux_x64).name, 'debug_bundle_linux-x64_assets');
expect(const DebugBundleLinuxAssets(TargetPlatform.linux_arm64).name, 'debug_bundle_linux-arm64_assets');
});
testUsingContext('ProfileBundleLinuxAssets copies artifacts to out directory', () async {
final Environment testEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: 'profile',
},
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
testEnvironment.buildDir.createSync(recursive: true);
// Create input files.
testEnvironment.buildDir.childFile('app.so').createSync();
await const LinuxAotBundle(AotElfProfile(TargetPlatform.linux_x64)).build(testEnvironment);
await const ProfileBundleLinuxAssets(TargetPlatform.linux_x64).build(testEnvironment);
final Directory libDir = testEnvironment.outputDir
.childDirectory('lib');
final Directory assetsDir = testEnvironment.outputDir
.childDirectory('flutter_assets');
expect(libDir.childFile('libapp.so'), exists);
expect(assetsDir.childFile('AssetManifest.json'), exists);
expect(assetsDir.childFile('version.json'), exists);
// No bundled fonts
expect(assetsDir.childFile('FontManifest.json'), isNot(exists));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testWithoutContext("ProfileBundleLinuxAssets' name depends on target platforms", () async {
expect(const ProfileBundleLinuxAssets(TargetPlatform.linux_x64).name, 'profile_bundle_linux-x64_assets');
expect(const ProfileBundleLinuxAssets(TargetPlatform.linux_arm64).name, 'profile_bundle_linux-arm64_assets');
});
testUsingContext('ReleaseBundleLinuxAssets copies artifacts to out directory', () async {
final Environment testEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: 'release',
},
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
testEnvironment.buildDir.createSync(recursive: true);
// Create input files.
testEnvironment.buildDir.childFile('app.so').createSync();
await const LinuxAotBundle(AotElfRelease(TargetPlatform.linux_x64)).build(testEnvironment);
await const ReleaseBundleLinuxAssets(TargetPlatform.linux_x64).build(testEnvironment);
final Directory libDir = testEnvironment.outputDir
.childDirectory('lib');
final Directory assetsDir = testEnvironment.outputDir
.childDirectory('flutter_assets');
expect(libDir.childFile('libapp.so'), exists);
expect(assetsDir.childFile('AssetManifest.json'), exists);
expect(assetsDir.childFile('version.json'), exists);
// No bundled fonts
expect(assetsDir.childFile('FontManifest.json'), isNot(exists));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testWithoutContext("ReleaseBundleLinuxAssets' name depends on target platforms", () async {
expect(const ReleaseBundleLinuxAssets(TargetPlatform.linux_x64).name, 'release_bundle_linux-x64_assets');
expect(const ReleaseBundleLinuxAssets(TargetPlatform.linux_arm64).name, 'release_bundle_linux-arm64_assets');
});
}
void setUpCacheDirectory(FileSystem fileSystem, Artifacts artifacts) {
final String desktopPathForX64 = artifacts.getArtifactPath(Artifact.linuxDesktopPath, platform: TargetPlatform.linux_x64, mode: BuildMode.debug);
final String desktopPathForArm64 = artifacts.getArtifactPath(Artifact.linuxDesktopPath, platform: TargetPlatform.linux_arm64, mode: BuildMode.debug);
fileSystem.file('$desktopPathForX64/unrelated-stuff').createSync(recursive: true);
fileSystem.file('$desktopPathForX64/libflutter_linux_gtk.so').createSync(recursive: true);
fileSystem.file('$desktopPathForArm64/unrelated-stuff').createSync(recursive: true);
fileSystem.file('$desktopPathForArm64/libflutter_linux_gtk.so').createSync(recursive: true);
final String headersPathForX64 = artifacts.getArtifactPath(Artifact.linuxHeaders, platform: TargetPlatform.linux_x64, mode: BuildMode.debug);
final String headersPathForArm64 = artifacts.getArtifactPath(Artifact.linuxHeaders, platform: TargetPlatform.linux_arm64, mode: BuildMode.debug);
fileSystem.file('$headersPathForX64/foo.h').createSync(recursive: true);
fileSystem.file('$headersPathForArm64/foo.h').createSync(recursive: true);
fileSystem.file(artifacts.getArtifactPath(Artifact.icuData, platform: TargetPlatform.linux_x64)).createSync();
fileSystem.file(artifacts.getArtifactPath(Artifact.icuData, platform: TargetPlatform.linux_arm64)).createSync();
fileSystem.file('packages/flutter_tools/lib/src/build_system/targets/linux.dart').createSync(recursive: true);
}
| flutter/packages/flutter_tools/test/general.shard/build_system/targets/linux_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/build_system/targets/linux_test.dart",
"repo_id": "flutter",
"token_count": 3887
} | 826 |
// 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 '../src/common.dart';
void main() {
group('containsIgnoreWhitespace Matcher', () {
group('on item to be contained', () {
test('matches simple case.', () {
expect('Give me any text!', containsIgnoringWhitespace('any text!'));
});
test("shouldn't match when it's only because of removing whitespaces", () {
expect('Give me anytext!', isNot(containsIgnoringWhitespace('any text!')));
});
test('ignores trailing spaces.', () {
expect('Give me any text!', containsIgnoringWhitespace('any text! '));
});
test('ignores leading spaces.', () {
expect('Give me any text!', containsIgnoringWhitespace(' any text!'));
});
test('ignores linebreaks.', () {
expect('Give me any text!', containsIgnoringWhitespace('any\n text!'));
});
test('ignores tabs.', () {
expect('Give me any text!', containsIgnoringWhitespace('any\t text!'));
});
test('is case sensitive.', () {
expect('Give me Any text!', isNot(containsIgnoringWhitespace('any text!')));
});
});
group('on value to match against', () {
test('ignores trailing spaces.', () {
expect('Give me any value to include! ',
containsIgnoringWhitespace('any value to include!'));
});
test('ignores leading spaces.', () {
expect(' Give me any value to include!',
containsIgnoringWhitespace('any value to include!'));
});
test('ignores linebreaks.', () {
expect('Give me \n any \n value \n to \n include!',
containsIgnoringWhitespace('any value to include!'));
});
test('ignores tabs.', () {
expect('\tGive\t me any\t value \t to \t include!',
containsIgnoringWhitespace('any value to include!'));
});
});
});
}
| flutter/packages/flutter_tools/test/general.shard/common_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/common_test.dart",
"repo_id": "flutter",
"token_count": 786
} | 827 |
// 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:collection/collection.dart';
import 'package:dds/dap.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/debug_adapters/flutter_adapter.dart';
import 'package:flutter_tools/src/debug_adapters/flutter_test_adapter.dart';
/// A [FlutterDebugAdapter] that captures what process/args will be launched.
class MockFlutterDebugAdapter extends FlutterDebugAdapter {
factory MockFlutterDebugAdapter({
required FileSystem fileSystem,
required Platform platform,
bool simulateAppStarted = true,
bool supportsRestart = true,
FutureOr<void> Function(MockFlutterDebugAdapter adapter)? preAppStart,
}) {
final StreamController<List<int>> stdinController = StreamController<List<int>>();
final StreamController<List<int>> stdoutController = StreamController<List<int>>();
final ByteStreamServerChannel channel = ByteStreamServerChannel(stdinController.stream, stdoutController.sink, null);
final ByteStreamServerChannel clientChannel = ByteStreamServerChannel(stdoutController.stream, stdinController.sink, null);
return MockFlutterDebugAdapter._(
channel,
clientChannel: clientChannel,
fileSystem: fileSystem,
platform: platform,
simulateAppStarted: simulateAppStarted,
supportsRestart: supportsRestart,
preAppStart: preAppStart,
);
}
MockFlutterDebugAdapter._(
super.channel, {
required this.clientChannel,
required super.fileSystem,
required super.platform,
this.simulateAppStarted = true,
this.supportsRestart = true,
this.preAppStart,
}) {
clientChannel.listen((ProtocolMessage message) {
_handleDapToClientMessage(message);
});
}
int _seq = 1;
final ByteStreamServerChannel clientChannel;
final bool simulateAppStarted;
final bool supportsRestart;
final FutureOr<void> Function(MockFlutterDebugAdapter adapter)? preAppStart;
late String executable;
late List<String> processArgs;
late Map<String, String>? env;
/// Overrides base implementation of [sendLogsToClient] which requires valid
/// `args` to have been set which may not be the case for mocks.
@override
bool get sendLogsToClient => false;
final StreamController<Map<String, Object?>> _dapToClientMessagesController = StreamController<Map<String, Object?>>.broadcast();
/// A stream of all messages sent from the adapter back to the client.
Stream<Map<String, Object?>> get dapToClientMessages => _dapToClientMessagesController.stream;
/// A stream of all progress events sent from the adapter back to the client.
Stream<Map<String, Object?>> get dapToClientProgressEvents {
const List<String> progressEventTypes = <String>['progressStart', 'progressUpdate', 'progressEnd'];
return dapToClientMessages
.where((Map<String, Object?> message) => progressEventTypes.contains(message['event'] as String?));
}
/// A list of all messages sent from the adapter to the `flutter run` processes `stdin`.
final List<Map<String, Object?>> dapToFlutterMessages = <Map<String, Object?>>[];
/// The `method`s of all messages sent to the `flutter run` processes `stdin`
/// by the debug adapter.
List<String> get dapToFlutterRequests => dapToFlutterMessages
.map((Map<String, Object?> message) => message['method'] as String?)
.whereNotNull()
.toList();
/// A handler for the 'app.exposeUrl' reverse-request.
String Function(String)? exposeUrlHandler;
@override
Future<void> launchAsProcess({
required String executable,
required List<String> processArgs,
required Map<String, String>? env,
}) async {
this.executable = executable;
this.processArgs = processArgs;
this.env = env;
await preAppStart?.call(this);
void sendLaunchProgress({required bool finished, String? message}) {
assert(finished == (message == null));
simulateStdoutMessage(<String, Object?>{
'event': 'app.progress',
'params': <String, Object?>{
'id': 'launch',
'message': message,
'finished': finished,
}
});
}
// Simulate the app starting by triggering handling of events that Flutter
// would usually write to stdout.
if (simulateAppStarted) {
sendLaunchProgress(message: 'Step 1…', finished: false);
simulateStdoutMessage(<String, Object?>{
'event': 'app.start',
'params': <String, Object?>{
'appId': 'TEST',
'supportsRestart': supportsRestart,
'deviceId': 'flutter-tester',
'mode': 'debug',
}
});
sendLaunchProgress(message: 'Step 2…', finished: false);
sendLaunchProgress(finished: true);
simulateStdoutMessage(<String, Object?>{
'event': 'app.started',
});
}
}
/// Handles messages sent from the debug adapter back to the client.
void _handleDapToClientMessage(ProtocolMessage message) {
_dapToClientMessagesController.add(message.toJson());
// Pretend to be the client, delegating any reverse-requests to the relevant
// handler that is provided by the test.
if (message is Event && message.event == 'flutter.forwardedRequest') {
final Map<String, Object?> body = message.body! as Map<String, Object?>;
final String method = body['method']! as String;
final Map<String, Object?>? params = body['params'] as Map<String, Object?>?;
final Object? result = _handleReverseRequest(method, params);
// Send the result back in the same way the client would.
clientChannel.sendRequest(Request(
seq: _seq++,
command: 'flutter.sendForwardedRequestResponse',
arguments: <String, Object?>{
'id': body['id'],
'result': result,
},
));
}
}
Object? _handleReverseRequest(String method, Map<String, Object?>? params) {
switch (method) {
case 'app.exposeUrl':
final String url = params!['url']! as String;
return exposeUrlHandler!(url);
default:
throw ArgumentError('Reverse-request $method is unknown');
}
}
/// Simulates a message emitted by the `flutter run` process by directly
/// calling the debug adapters [handleStdout] method.
///
/// Use [simulateRawStdout] to simulate non-daemon text output.
void simulateStdoutMessage(Map<String, Object?> message) {
// Messages are wrapped in a list because Flutter only processes messages
// wrapped in brackets.
handleStdout(jsonEncode(<Object?>[message]));
}
/// Simulates a string emitted by the `flutter run` process by directly
/// calling the debug adapters [handleStdout] method.
///
/// Use [simulateStdoutMessage] to simulate a daemon JSON message.
void simulateRawStdout(String output) {
handleStdout(output);
}
@override
void sendFlutterMessage(Map<String, Object?> message) {
dapToFlutterMessages.add(message);
// Don't call super because it will try to write to the process that we
// didn't actually spawn.
}
@override
Future<void> get debuggerInitialized {
// If we were mocking debug mode, then simulate the debugger initializing.
return enableDebugger
? Future<void>.value()
: throw StateError('Invalid attempt to wait for debuggerInitialized when not debugging');
}
}
/// A [FlutterTestDebugAdapter] that captures what process/args will be launched.
class MockFlutterTestDebugAdapter extends FlutterTestDebugAdapter {
factory MockFlutterTestDebugAdapter({
required FileSystem fileSystem,
required Platform platform,
}) {
final StreamController<List<int>> stdinController = StreamController<List<int>>();
final StreamController<List<int>> stdoutController = StreamController<List<int>>();
final ByteStreamServerChannel channel = ByteStreamServerChannel(stdinController.stream, stdoutController.sink, null);
return MockFlutterTestDebugAdapter._(
stdinController.sink,
stdoutController.stream,
channel,
fileSystem: fileSystem,
platform: platform,
);
}
MockFlutterTestDebugAdapter._(
this.stdin,
this.stdout,
ByteStreamServerChannel channel, {
required FileSystem fileSystem,
required Platform platform,
}) : super(channel, fileSystem: fileSystem, platform: platform);
final StreamSink<List<int>> stdin;
final Stream<List<int>> stdout;
late String executable;
late List<String> processArgs;
late Map<String, String>? env;
@override
Future<void> launchAsProcess({
required String executable,
required List<String> processArgs,
required Map<String, String>? env,
}) async {
this.executable = executable;
this.processArgs = processArgs;
this.env = env;
}
@override
Future<void> get debuggerInitialized {
// If we were mocking debug mode, then simulate the debugger initializing.
return enableDebugger
? Future<void>.value()
: throw StateError('Invalid attempt to wait for debuggerInitialized when not debugging');
}
}
class MockRequest extends Request {
MockRequest()
: super.fromMap(<String, Object?>{
'command': 'mock_command',
'type': 'mock_type',
'seq': _requestId++,
});
static int _requestId = 1;
}
| flutter/packages/flutter_tools/test/general.shard/dap/mocks.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/dap/mocks.dart",
"repo_id": "flutter",
"token_count": 3193
} | 828 |
// 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_tools/src/base/logger.dart';
import 'package:flutter_tools/src/flutter_manifest.dart';
import '../src/common.dart';
void main() {
group('parsing of assets section in flutter manifests with asset transformers', () {
testWithoutContext('parses an asset with a simple transformation', () async {
final BufferLogger logger = BufferLogger.test();
const String manifest = '''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- path: asset/hello.txt
transformers:
- package: my_package
''';
final FlutterManifest? parsedManifest = FlutterManifest.createFromString(manifest, logger: logger);
expect(parsedManifest!.assets, <AssetsEntry>[
AssetsEntry(
uri: Uri.parse('asset/hello.txt'),
transformers: const <AssetTransformerEntry>[
AssetTransformerEntry(package: 'my_package', args: <String>[])
],
),
]);
expect(logger.errorText, isEmpty);
});
testWithoutContext('parses an asset with a transformation that has args', () async {
final BufferLogger logger = BufferLogger.test();
const String manifest = '''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- path: asset/hello.txt
transformers:
- package: my_package
args: ["-e", "--color", "purple"]
''';
final FlutterManifest? parsedManifest = FlutterManifest.createFromString(manifest, logger: logger);
expect(parsedManifest!.assets, <AssetsEntry>[
AssetsEntry(
uri: Uri.parse('asset/hello.txt'),
transformers: const <AssetTransformerEntry>[
AssetTransformerEntry(
package: 'my_package',
args: <String>['-e', '--color', 'purple'],
)
],
),
]);
expect(logger.errorText, isEmpty);
});
testWithoutContext('fails when a transformers section is not a list', () async {
final BufferLogger logger = BufferLogger.test();
const String manifest = '''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- path: asset/hello.txt
transformers:
- my_transformer
''';
FlutterManifest.createFromString(manifest, logger: logger);
expect(
logger.errorText,
'Unable to parse assets section.\n'
'In transformers section of asset "asset/hello.txt": Expected '
'transformers list to be a list of Map, but element at index 0 was a String.\n',
);
});
testWithoutContext('fails when a transformers section package is not a string', () async {
final BufferLogger logger = BufferLogger.test();
const String manifest = '''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- path: asset/hello.txt
transformers:
- package:
i am a key: i am a value
''';
FlutterManifest.createFromString(manifest, logger: logger);
expect(
logger.errorText,
'Unable to parse assets section.\n'
'In transformers section of asset "asset/hello.txt": '
'Expected "package" to be a String. Found YamlMap instead.\n',
);
});
testWithoutContext('fails when a transformer is missing the package field', () async {
final BufferLogger logger = BufferLogger.test();
const String manifest = '''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- path: asset/hello.txt
transformers:
- args: ["-e"]
''';
FlutterManifest.createFromString(manifest, logger: logger);
expect(
logger.errorText,
'Unable to parse assets section.\n'
'In transformers section of asset "asset/hello.txt": Expected "package" to be a '
'String. Found Null instead.\n',
);
});
testWithoutContext('fails when a transformer has args field that is not a list of strings', () async {
final BufferLogger logger = BufferLogger.test();
const String manifest = '''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
uses-material-design: true
assets:
- path: asset/hello.txt
transformers:
- package: my_transformer
args: hello
''';
FlutterManifest.createFromString(manifest, logger: logger);
expect(
logger.errorText,
'Unable to parse assets section.\n'
'In transformers section of asset "asset/hello.txt": In args section '
'of transformer using package "my_transformer": Expected args to be a '
'list of String, but got hello (String).\n',
);
});
});
}
| flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_transformers_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_transformers_test.dart",
"repo_id": "flutter",
"token_count": 1933
} | 829 |
// 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:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/base/io.dart' as io;
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/test/integration_test_device.dart';
import 'package:flutter_tools/src/test/test_device.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:stream_channel/stream_channel.dart';
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
import '../src/context.dart';
import '../src/fake_devices.dart';
import '../src/fake_vm_services.dart';
final vm_service.Isolate isolate = vm_service.Isolate(
id: '1',
pauseEvent: vm_service.Event(
kind: vm_service.EventKind.kResume,
timestamp: 0
),
breakpoints: <vm_service.Breakpoint>[],
libraries: <vm_service.LibraryRef>[
vm_service.LibraryRef(
id: '1',
uri: 'file:///hello_world/main.dart',
name: '',
),
],
livePorts: 0,
name: 'test',
number: '1',
pauseOnExit: false,
runnable: true,
startTime: 0,
isSystemIsolate: false,
isolateFlags: <vm_service.IsolateFlag>[],
extensionRPCs: <String>[kIntegrationTestMethod],
);
final FlutterView fakeFlutterView = FlutterView(
id: 'a',
uiIsolate: isolate,
);
final FakeVmServiceRequest listViewsRequest = FakeVmServiceRequest(
method: kListViewsMethod,
jsonResponse: <String, Object>{
'views': <Object>[
fakeFlutterView.toJson(),
],
},
);
final Uri vmServiceUri = Uri.parse('http://localhost:1234');
void main() {
late FakeVmServiceHost fakeVmServiceHost;
late TestDevice testDevice;
setUp(() {
testDevice = IntegrationTestTestDevice(
id: 1,
device: FakeDevice(
'ephemeral',
'ephemeral',
type: PlatformType.android,
launchResult: LaunchResult.succeeded(vmServiceUri: vmServiceUri),
),
debuggingOptions: DebuggingOptions.enabled(
BuildInfo.debug,
),
userIdentifier: '',
compileExpression: null,
);
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
const FakeVmServiceRequest(
method: 'streamListen',
args: <String, Object>{
'streamId': 'Isolate',
},
),
listViewsRequest,
FakeVmServiceRequest(
method: 'getIsolate',
jsonResponse: isolate.toJson(),
args: <String, Object>{
'isolateId': '1',
},
),
const FakeVmServiceRequest(
method: 'streamCancel',
args: <String, Object>{
'streamId': 'Isolate',
},
),
const FakeVmServiceRequest(
method: 'streamListen',
args: <String, Object>{
'streamId': 'Extension',
},
),
]);
});
testUsingContext('will not start when package missing', () async {
await expectLater(
testDevice.start('entrypointPath'),
throwsA(
isA<TestDeviceException>().having(
(Exception e) => e.toString(),
'description',
contains('No application found for TargetPlatform.android_arm'),
),
),
);
});
testUsingContext('Can start the entrypoint', () async {
await testDevice.start('entrypointPath');
expect(await testDevice.vmServiceUri, vmServiceUri);
expect(testDevice.finished, doesNotComplete);
}, overrides: <Type, Generator>{
ApplicationPackageFactory: () => FakeApplicationPackageFactory(),
VMServiceConnector: () => (Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions? compression,
Device? device,
Logger? logger,
}) async => fakeVmServiceHost.vmService,
});
testUsingContext('Can kill the started device', () async {
await testDevice.start('entrypointPath');
await testDevice.kill();
expect(testDevice.finished, completes);
}, overrides: <Type, Generator>{
ApplicationPackageFactory: () => FakeApplicationPackageFactory(),
VMServiceConnector: () => (Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions? compression,
Device? device,
Logger? logger,
}) async => fakeVmServiceHost.vmService,
});
testUsingContext('when the device starts without providing an vmService URI', () async {
final TestDevice testDevice = IntegrationTestTestDevice(
id: 1,
device: FakeDevice(
'ephemeral',
'ephemeral',
type: PlatformType.android,
launchResult: LaunchResult.succeeded(),
),
debuggingOptions: DebuggingOptions.enabled(
BuildInfo.debug,
),
userIdentifier: '',
compileExpression: null,
);
expect(() => testDevice.start('entrypointPath'), throwsA(isA<TestDeviceException>()));
}, overrides: <Type, Generator>{
VMServiceConnector: () => (Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions? compression,
Device? device,
}) async => fakeVmServiceHost.vmService,
});
testUsingContext('when the device fails to start', () async {
final TestDevice testDevice = IntegrationTestTestDevice(
id: 1,
device: FakeDevice(
'ephemeral',
'ephemeral',
type: PlatformType.android,
launchResult: LaunchResult.failed(),
),
debuggingOptions: DebuggingOptions.enabled(
BuildInfo.debug,
),
userIdentifier: '',
compileExpression: null,
);
expect(() => testDevice.start('entrypointPath'), throwsA(isA<TestDeviceException>()));
}, overrides: <Type, Generator>{
VMServiceConnector: () => (Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions? compression,
Device? device,
}) async => fakeVmServiceHost.vmService,
});
testUsingContext('Can handle closing of the VM service', () async {
final StreamChannel<String> channel = await testDevice.start('entrypointPath');
await fakeVmServiceHost.vmService.dispose();
expect(await channel.stream.isEmpty, true);
}, overrides: <Type, Generator>{
ApplicationPackageFactory: () => FakeApplicationPackageFactory(),
VMServiceConnector: () => (Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions? compression,
Device? device,
Logger? logger,
}) async => fakeVmServiceHost.vmService,
});
}
class FakeApplicationPackageFactory extends Fake implements ApplicationPackageFactory {
@override
Future<ApplicationPackage> getPackageForPlatform(
TargetPlatform platform, {
BuildInfo? buildInfo,
File? applicationBinary,
}) async => FakeApplicationPackage();
}
class FakeApplicationPackage extends Fake implements ApplicationPackage { }
| flutter/packages/flutter_tools/test/general.shard/integration_test_device_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/integration_test_device_test.dart",
"repo_id": "flutter",
"token_count": 3014
} | 830 |
// 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/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/base/version.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/device_port_forwarder.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/ios/application_package.dart';
import 'package:flutter_tools/src/ios/plist_parser.dart';
import 'package:flutter_tools/src/ios/simulators.dart';
import 'package:flutter_tools/src/macos/xcode.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart';
final Platform macosPlatform = FakePlatform(
operatingSystem: 'macos',
environment: <String, String>{
'HOME': '/',
},
);
void main() {
late FakePlatform osx;
late FileSystemUtils fsUtils;
late MemoryFileSystem fileSystem;
setUp(() {
osx = FakePlatform(
environment: <String, String>{},
operatingSystem: 'macos',
);
fileSystem = MemoryFileSystem.test();
fsUtils = FileSystemUtils(fileSystem: fileSystem, platform: osx);
});
group('_IOSSimulatorDevicePortForwarder', () {
late FakeSimControl simControl;
late Xcode xcode;
setUp(() {
simControl = FakeSimControl();
xcode = Xcode.test(processManager: FakeProcessManager.any());
});
testUsingContext('dispose() does not throw an exception', () async {
final IOSSimulator simulator = IOSSimulator(
'123',
name: 'iPhone 11',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
);
final DevicePortForwarder portForwarder = simulator.portForwarder;
await portForwarder.forward(123);
await portForwarder.forward(124);
expect(portForwarder.forwardedPorts.length, 2);
try {
await portForwarder.dispose();
} on Exception catch (e) {
fail('Encountered exception: $e');
}
expect(portForwarder.forwardedPorts.length, 0);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Xcode: () => xcode,
}, testOn: 'posix');
});
testUsingContext('simulators only support debug mode', () async {
final IOSSimulator simulator = IOSSimulator(
'123',
name: 'iPhone 11',
simControl: FakeSimControl(),
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
);
expect(simulator.supportsRuntimeMode(BuildMode.debug), true);
expect(simulator.supportsRuntimeMode(BuildMode.profile), false);
expect(simulator.supportsRuntimeMode(BuildMode.release), false);
expect(simulator.supportsRuntimeMode(BuildMode.jitRelease), false);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
group('logFilePath', () {
late FakeSimControl simControl;
setUp(() {
simControl = FakeSimControl();
});
testUsingContext('defaults to rooted from HOME', () {
osx.environment['HOME'] = '/foo/bar';
final IOSSimulator simulator = IOSSimulator(
'123',
name: 'iPhone 11',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
);
expect(simulator.logFilePath, '/foo/bar/Library/Logs/CoreSimulator/123/system.log');
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystemUtils: () => fsUtils,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
}, testOn: 'posix');
testUsingContext('respects IOS_SIMULATOR_LOG_FILE_PATH', () {
osx.environment['HOME'] = '/foo/bar';
osx.environment['IOS_SIMULATOR_LOG_FILE_PATH'] = '/baz/qux/%{id}/system.log';
final IOSSimulator simulator = IOSSimulator(
'456',
name: 'iPhone 11',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
);
expect(simulator.logFilePath, '/baz/qux/456/system.log');
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystemUtils: () => fsUtils,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
group('compareIosVersions', () {
testWithoutContext('compares correctly', () {
// This list must be sorted in ascending preference order
final List<String> testList = <String>[
'8', '8.0', '8.1', '8.2',
'9', '9.0', '9.1', '9.2',
'10', '10.0', '10.1',
];
for (int i = 0; i < testList.length; i++) {
expect(compareIosVersions(testList[i], testList[i]), 0);
}
for (int i = 0; i < testList.length - 1; i++) {
for (int j = i + 1; j < testList.length; j++) {
expect(compareIosVersions(testList[i], testList[j]), lessThan(0));
expect(compareIosVersions(testList[j], testList[i]), greaterThan(0));
}
}
});
});
group('sdkMajorVersion', () {
late FakeSimControl simControl;
setUp(() {
simControl = FakeSimControl();
});
// This new version string appears in SimulatorApp-850 CoreSimulator-518.16 beta.
testWithoutContext('can be parsed from iOS-11-3', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
simControl: simControl,
);
expect(await device.sdkMajorVersion, 11);
});
testWithoutContext('can be parsed from iOS 11.2', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.2',
simControl: simControl,
);
expect(await device.sdkMajorVersion, 11);
});
testWithoutContext('Has a simulator category', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.2',
simControl: simControl,
);
expect(device.category, Category.mobile);
});
});
group('IOSSimulator.isSupported', () {
late FakeSimControl simControl;
setUp(() {
simControl = FakeSimControl();
});
testUsingContext('Apple TV is unsupported', () {
final IOSSimulator simulator = IOSSimulator(
'x',
name: 'Apple TV',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.tvOS-14-5',
);
expect(simulator.isSupported(), false);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Apple Watch is unsupported', () {
expect(IOSSimulator(
'x',
name: 'Apple Watch',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.watchOS-8-0',
).isSupported(), false);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('iPad 2 is supported', () {
expect(IOSSimulator(
'x',
name: 'iPad 2',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
).isSupported(), true);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('iPad Retina is supported', () {
expect(IOSSimulator(
'x',
name: 'iPad Retina',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
).isSupported(), true);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('iPhone 5 is supported', () {
expect(IOSSimulator(
'x',
name: 'iPhone 5',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
).isSupported(), true);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('iPhone 5s is supported', () {
expect(IOSSimulator(
'x',
name: 'iPhone 5s',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
).isSupported(), true);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('iPhone SE is supported', () {
expect(IOSSimulator(
'x',
name: 'iPhone SE',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
).isSupported(), true);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('iPhone 7 Plus is supported', () {
expect(IOSSimulator(
'x',
name: 'iPhone 7 Plus',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
).isSupported(), true);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('iPhone X is supported', () {
expect(IOSSimulator(
'x',
name: 'iPhone X',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
).isSupported(), true);
}, overrides: <Type, Generator>{
Platform: () => osx,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
group('Simulator screenshot', () {
testWithoutContext('supports screenshots', () async {
final Xcode xcode = Xcode.test(processManager: FakeProcessManager.any());
final Logger logger = BufferLogger.test();
final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'io',
'x',
'screenshot',
'screenshot.png',
],
),
]);
// Test a real one. Screenshot doesn't require instance states.
final SimControl simControl = SimControl(
processManager: fakeProcessManager,
logger: logger,
xcode: xcode,
);
// Doesn't matter what the device is.
final IOSSimulator deviceUnderTest = IOSSimulator(
'x',
name: 'iPhone SE',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
);
final File screenshot = MemoryFileSystem.test().file('screenshot.png');
await deviceUnderTest.takeScreenshot(screenshot);
expect(fakeProcessManager, hasNoRemainingExpectations);
});
});
group('device log tool', () {
late FakeProcessManager fakeProcessManager;
late FakeSimControl simControl;
setUp(() {
fakeProcessManager = FakeProcessManager.empty();
simControl = FakeSimControl();
});
testUsingContext('syslog uses tail', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 9.3',
simControl: simControl,
);
fakeProcessManager.addCommand(const FakeCommand(command: <String>[
'tail',
'-n',
'0',
'-F',
'/Library/Logs/CoreSimulator/x/system.log',
]));
await launchDeviceSystemLogTool(device);
expect(fakeProcessManager, hasNoRemainingExpectations);
},
overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
Platform: () => macosPlatform,
FileSystemUtils: () => FileSystemUtils(
fileSystem: fileSystem,
platform: macosPlatform,
),
});
testUsingContext('unified logging with app name', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.0',
simControl: simControl,
);
const String expectedPredicate = 'eventType = logEvent AND '
'processImagePath ENDSWITH "My Super Awesome App" AND '
'(senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" OR processImageUUID == senderImageUUID) AND '
'NOT(eventMessage CONTAINS ": could not find icon for representation -> com.apple.") AND '
'NOT(eventMessage BEGINSWITH "assertion failed: ") AND '
'NOT(eventMessage CONTAINS " libxpc.dylib ")';
fakeProcessManager.addCommand(const FakeCommand(command: <String>[
'xcrun',
'simctl',
'spawn',
'x',
'log',
'stream',
'--style',
'json',
'--predicate',
expectedPredicate,
]));
await launchDeviceUnifiedLogging(device, 'My Super Awesome App');
expect(fakeProcessManager, hasNoRemainingExpectations);
},
overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
});
testUsingContext('unified logging without app name', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.0',
simControl: simControl,
);
const String expectedPredicate = 'eventType = logEvent AND '
'(senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" OR processImageUUID == senderImageUUID) AND '
'NOT(eventMessage CONTAINS ": could not find icon for representation -> com.apple.") AND '
'NOT(eventMessage BEGINSWITH "assertion failed: ") AND '
'NOT(eventMessage CONTAINS " libxpc.dylib ")';
fakeProcessManager.addCommand(const FakeCommand(command: <String>[
'xcrun',
'simctl',
'spawn',
'x',
'log',
'stream',
'--style',
'json',
'--predicate',
expectedPredicate,
]));
await launchDeviceUnifiedLogging(device, null);
expect(fakeProcessManager, hasNoRemainingExpectations);
},
overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
});
});
group('log reader', () {
late FakeProcessManager fakeProcessManager;
late FakeIosProject mockIosProject;
late FakeSimControl simControl;
late Xcode xcode;
setUp(() {
fakeProcessManager = FakeProcessManager.empty();
mockIosProject = FakeIosProject();
simControl = FakeSimControl();
xcode = Xcode.test(processManager: FakeProcessManager.any());
});
group('syslog', () {
setUp(() {
final File syslog = fileSystem.file('system.log')..createSync();
osx.environment['IOS_SIMULATOR_LOG_FILE_PATH'] = syslog.path;
});
testUsingContext('simulator can parse Xcode 8/iOS 10-style logs', () async {
fakeProcessManager
..addCommand(const FakeCommand(
command: <String>['tail', '-n', '0', '-F', 'system.log'],
stdout: '''
Dec 20 17:04:32 md32-11-vm1 My Super Awesome App[88374]: flutter: The Dart VM service is listening on http://127.0.0.1:64213/1Uoeu523990=/
Dec 20 17:04:32 md32-11-vm1 Another App[88374]: Ignore this text'''
))
..addCommand(const FakeCommand(
command: <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
));
final IOSSimulator device = IOSSimulator(
'123456',
name: 'iPhone 11',
simulatorCategory: 'iOS 10.0',
simControl: simControl,
);
final DeviceLogReader logReader = device.getLogReader(
app: await BuildableIOSApp.fromProject(mockIosProject, null),
);
final List<String> lines = await logReader.logLines.toList();
expect(lines, <String>[
'flutter: The Dart VM service is listening on http://127.0.0.1:64213/1Uoeu523990=/',
]);
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
Platform: () => osx,
Xcode: () => xcode,
});
testUsingContext('simulator can output `)`', () async {
fakeProcessManager
..addCommand(const FakeCommand(
command: <String>['tail', '-n', '0', '-F', 'system.log'],
stdout: '''
2017-09-13 15:26:57.228948-0700 localhost My Super Awesome App[37195]: (Flutter) The Dart VM service is listening on http://127.0.0.1:57701/
2017-09-13 15:26:57.228948-0700 localhost My Super Awesome App[37195]: (Flutter) ))))))))))
2017-09-13 15:26:57.228948-0700 localhost My Super Awesome App[37195]: (Flutter) #0 Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)'''
))
..addCommand(const FakeCommand(
command: <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
));
final IOSSimulator device = IOSSimulator(
'123456',
name: 'iPhone 11',
simulatorCategory: 'iOS 10.3',
simControl: simControl,
);
final DeviceLogReader logReader = device.getLogReader(
app: await BuildableIOSApp.fromProject(mockIosProject, null),
);
final List<String> lines = await logReader.logLines.toList();
expect(lines, <String>[
'The Dart VM service is listening on http://127.0.0.1:57701/',
'))))))))))',
'#0 Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)',
]);
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
Platform: () => osx,
Xcode: () => xcode,
});
testUsingContext('multiline messages', () async {
fakeProcessManager
..addCommand(const FakeCommand(
command: <String>['tail', '-n', '0', '-F', 'system.log'],
stdout: '''
2017-09-13 15:26:57.228948-0700 localhost My Super Awesome App[37195]: (Flutter) Single line message
2017-09-13 15:26:57.228948-0700 localhost My Super Awesome App[37195]: (Flutter) Multi line message
continues...
continues...
2020-03-11 15:58:28.207175-0700 localhost My Super Awesome App[72166]: (libnetwork.dylib) [com.apple.network:] [28 www.googleapis.com:443 stream, pid: 72166, tls] cancelled
[28.1 64A98447-EABF-4983-A387-7DB9D0C1785F 10.0.1.200.57912<->172.217.6.74:443]
Connected Path: satisfied (Path is satisfied), interface: en18
Duration: 0.271s, DNS @0.000s took 0.001s, TCP @0.002s took 0.019s, TLS took 0.046s
bytes in/out: 4468/1933, packets in/out: 11/10, rtt: 0.016s, retransmitted packets: 0, out-of-order packets: 0
2017-09-13 15:36:57.228948-0700 localhost My Super Awesome App[37195]: (Flutter) Multi line message again
and it goes...
and goes...
2017-09-13 15:36:57.228948-0700 localhost My Super Awesome App[37195]: (Flutter) Single line message, not the part of the above
'''
))
..addCommand(const FakeCommand(
command: <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
));
final IOSSimulator device = IOSSimulator(
'123456',
name: 'iPhone 11',
simulatorCategory: 'iOS 10.3',
simControl: simControl,
);
final DeviceLogReader logReader = device.getLogReader(
app: await BuildableIOSApp.fromProject(mockIosProject, null),
);
final List<String> lines = await logReader.logLines.toList();
expect(lines, <String>[
'Single line message',
'Multi line message',
' continues...',
' continues...',
'Multi line message again',
' and it goes...',
' and goes...',
'Single line message, not the part of the above',
]);
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
Platform: () => osx,
Xcode: () => xcode,
});
});
group('unified logging', () {
late BufferLogger logger;
setUp(() {
logger = BufferLogger.test();
});
testUsingContext('log reader handles escaped multiline messages', () async {
const String logPredicate = 'eventType = logEvent AND processImagePath ENDSWITH "My Super Awesome App" '
'AND (senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" '
'OR processImageUUID == senderImageUUID) AND NOT(eventMessage CONTAINS ": could not find icon '
'for representation -> com.apple.") AND NOT(eventMessage BEGINSWITH "assertion failed: ") '
'AND NOT(eventMessage CONTAINS " libxpc.dylib ")';
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'spawn',
'123456',
'log',
'stream',
'--style',
'json',
'--predicate',
logPredicate,
],
stdout: r'''
},{
"traceID" : 37579774151491588,
"eventMessage" : "Single line message",
"eventType" : "logEvent"
},{
"traceID" : 37579774151491588,
"eventMessage" : "Multi line message\n continues...\n continues..."
},{
"traceID" : 37579774151491588,
"eventMessage" : "Single line message, not the part of the above",
"eventType" : "logEvent"
},{
'''
));
final IOSSimulator device = IOSSimulator(
'123456',
name: 'iPhone 11',
simulatorCategory: 'iOS 11.0',
simControl: simControl,
);
final DeviceLogReader logReader = device.getLogReader(
app: await BuildableIOSApp.fromProject(mockIosProject, null),
);
final List<String> lines = await logReader.logLines.toList();
expect(lines, <String>[
'Single line message', 'Multi line message\n continues...\n continues...',
'Single line message, not the part of the above',
]);
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
});
testUsingContext('log reader handles bad output', () async {
const String logPredicate = 'eventType = logEvent AND processImagePath ENDSWITH "My Super Awesome App" '
'AND (senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" '
'OR processImageUUID == senderImageUUID) AND NOT(eventMessage CONTAINS ": could not find icon '
'for representation -> com.apple.") AND NOT(eventMessage BEGINSWITH "assertion failed: ") '
'AND NOT(eventMessage CONTAINS " libxpc.dylib ")';
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'spawn',
'123456',
'log',
'stream',
'--style',
'json',
'--predicate',
logPredicate,
],
stdout: '"eventMessage" : "message with incorrect escaping""',
));
final IOSSimulator device = IOSSimulator(
'123456',
name: 'iPhone 11',
simulatorCategory: 'iOS 11.0',
simControl: simControl,
);
final DeviceLogReader logReader = device.getLogReader(
app: await BuildableIOSApp.fromProject(mockIosProject, null),
);
final List<String> lines = await logReader.logLines.toList();
expect(lines, isEmpty);
expect(logger.errorText, contains('Logger returned non-JSON response'));
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
ProcessManager: () => fakeProcessManager,
FileSystem: () => fileSystem,
Logger: () => logger,
});
});
});
group('SimControl', () {
const String validSimControlOutput = '''
{
"devices" : {
"com.apple.CoreSimulator.SimRuntime.iOS-14-0" : [
{
"dataPathSize" : 1734569984,
"udid" : "iPhone 11-UDID",
"isAvailable" : true,
"logPathSize" : 9506816,
"deviceTypeIdentifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-11",
"state" : "Booted",
"name" : "iPhone 11"
}
],
"com.apple.CoreSimulator.SimRuntime.iOS-13-0" : [
],
"com.apple.CoreSimulator.SimRuntime.iOS-12-4" : [
],
"com.apple.CoreSimulator.SimRuntime.tvOS-16-0" : [
],
"com.apple.CoreSimulator.SimRuntime.watchOS-9-0" : [
],
"com.apple.CoreSimulator.SimRuntime.iOS-16-0" : [
{
"dataPathSize" : 552366080,
"udid" : "Phone w Watch-UDID",
"isAvailable" : true,
"logPathSize" : 90112,
"deviceTypeIdentifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-11",
"state" : "Booted",
"name" : "Phone w Watch"
},
{
"dataPathSize" : 2186457088,
"udid" : "iPhone 13-UDID",
"isAvailable" : true,
"logPathSize" : 151552,
"deviceTypeIdentifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-13",
"state" : "Booted",
"name" : "iPhone 13"
}
]
}
}
''';
late FakeProcessManager fakeProcessManager;
Xcode xcode;
late SimControl simControl;
late BufferLogger logger;
const String deviceId = 'smart-phone';
const String appId = 'flutterApp';
setUp(() {
fakeProcessManager = FakeProcessManager.empty();
xcode = Xcode.test(processManager: FakeProcessManager.any());
logger = BufferLogger.test();
simControl = SimControl(
logger: logger,
processManager: fakeProcessManager,
xcode: xcode,
);
});
testWithoutContext('getConnectedDevices succeeds', () async {
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'list',
'devices',
'booted',
'iOS',
'--json',
],
stdout: validSimControlOutput,
));
final List<BootedSimDevice> devices = await simControl.getConnectedDevices();
final BootedSimDevice phone1 = devices[0];
expect(phone1.category, 'com.apple.CoreSimulator.SimRuntime.iOS-14-0');
expect(phone1.name, 'iPhone 11');
expect(phone1.udid, 'iPhone 11-UDID');
final BootedSimDevice phone2 = devices[1];
expect(phone2.category, 'com.apple.CoreSimulator.SimRuntime.iOS-16-0');
expect(phone2.name, 'Phone w Watch');
expect(phone2.udid, 'Phone w Watch-UDID');
final BootedSimDevice phone3 = devices[2];
expect(phone3.category, 'com.apple.CoreSimulator.SimRuntime.iOS-16-0');
expect(phone3.name, 'iPhone 13');
expect(phone3.udid, 'iPhone 13-UDID');
expect(fakeProcessManager, hasNoRemainingExpectations);
});
testWithoutContext('getConnectedDevices handles bad simctl output', () async {
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'list',
'devices',
'booted',
'iOS',
'--json',
],
stdout: 'Install Started',
));
final List<BootedSimDevice> devices = await simControl.getConnectedDevices();
expect(devices, isEmpty);
expect(fakeProcessManager, hasNoRemainingExpectations);
});
testWithoutContext('sdkMajorVersion defaults to 11 when sdkNameAndVersion is junk', () async {
final IOSSimulator iosSimulatorA = IOSSimulator(
'x',
name: 'Testo',
simulatorCategory: 'NaN',
simControl: simControl,
);
expect(await iosSimulatorA.sdkMajorVersion, 11);
});
testWithoutContext('.install() handles exceptions', () async {
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'install',
deviceId,
appId,
],
exception: ProcessException('xcrun', <String>[]),
));
expect(
() async => simControl.install(deviceId, appId),
throwsToolExit(message: r'Unable to install'),
);
});
testWithoutContext('.uninstall() handles exceptions', () async {
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'uninstall',
deviceId,
appId,
],
exception: ProcessException('xcrun', <String>[]),
));
expect(
() async => simControl.uninstall(deviceId, appId),
throwsToolExit(message: r'Unable to uninstall'),
);
});
testWithoutContext('.launch() handles exceptions', () async {
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'launch',
deviceId,
appId,
],
exception: ProcessException('xcrun', <String>[]),
));
expect(
() async => simControl.launch(deviceId, appId),
throwsToolExit(message: r'Unable to launch'),
);
});
testWithoutContext('.stopApp() handles exceptions', () async {
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'terminate',
deviceId,
appId,
],
exception: ProcessException('xcrun', <String>[]),
));
expect(
() async => simControl.stopApp(deviceId, appId),
throwsToolExit(message: 'Unable to terminate'),
);
expect(fakeProcessManager, hasNoRemainingExpectations);
});
testWithoutContext('simulator stopApp handles null app package', () async {
final IOSSimulator iosSimulator = IOSSimulator(
'x',
name: 'Testo',
simulatorCategory: 'NaN',
simControl: simControl,
);
expect(await iosSimulator.stopApp(null), isFalse);
});
testWithoutContext('listAvailableIOSRuntimes succeeds', () async {
const String validRuntimesOutput = '''
{
"runtimes" : [
{
"bundlePath" : "/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 15.4.simruntime",
"buildversion" : "19E240",
"platform" : "iOS",
"runtimeRoot" : "/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 15.4.simruntime/Contents/Resources/RuntimeRoot",
"identifier" : "com.apple.CoreSimulator.SimRuntime.iOS-15-4",
"version" : "15.4",
"isInternal" : false,
"isAvailable" : true,
"name" : "iOS 15.4",
"supportedDeviceTypes" : [
{
"bundlePath" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/DeviceTypes/iPhone 6s.simdevicetype",
"name" : "iPhone 6s",
"identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-6s",
"productFamily" : "iPhone"
},
{
"bundlePath" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/DeviceTypes/iPhone 6s Plus.simdevicetype",
"name" : "iPhone 6s Plus",
"identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-6s-Plus",
"productFamily" : "iPhone"
}
]
},
{
"bundlePath" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime",
"buildversion" : "20E247",
"platform" : "iOS",
"runtimeRoot" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot",
"identifier" : "com.apple.CoreSimulator.SimRuntime.iOS-16-4",
"version" : "16.4",
"isInternal" : false,
"isAvailable" : true,
"name" : "iOS 16.4",
"supportedDeviceTypes" : [
{
"bundlePath" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/DeviceTypes/iPhone 8.simdevicetype",
"name" : "iPhone 8",
"identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-8",
"productFamily" : "iPhone"
},
{
"bundlePath" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/DeviceTypes/iPhone 8 Plus.simdevicetype",
"name" : "iPhone 8 Plus",
"identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-8-Plus",
"productFamily" : "iPhone"
}
]
},
{
"bundlePath" : "/Library/Developer/CoreSimulator/Volumes/iOS_21A5268h/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 17.0.simruntime",
"buildversion" : "21A5268h",
"platform" : "iOS",
"runtimeRoot" : "/Library/Developer/CoreSimulator/Volumes/iOS_21A5268h/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 17.0.simruntime/Contents/Resources/RuntimeRoot",
"identifier" : "com.apple.CoreSimulator.SimRuntime.iOS-17-0",
"version" : "17.0",
"isInternal" : false,
"isAvailable" : true,
"name" : "iOS 17.0",
"supportedDeviceTypes" : [
{
"bundlePath" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/DeviceTypes/iPhone 8.simdevicetype",
"name" : "iPhone 8",
"identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-8",
"productFamily" : "iPhone"
},
{
"bundlePath" : "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/DeviceTypes/iPhone 8 Plus.simdevicetype",
"name" : "iPhone 8 Plus",
"identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-8-Plus",
"productFamily" : "iPhone"
}
]
}
]
}
''';
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'list',
'runtimes',
'available',
'iOS',
'--json',
],
stdout: validRuntimesOutput,
));
final List<IOSSimulatorRuntime> runtimes = await simControl.listAvailableIOSRuntimes();
final IOSSimulatorRuntime runtime1 = runtimes[0];
expect(runtime1.bundlePath, '/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 15.4.simruntime');
expect(runtime1.buildVersion, '19E240');
expect(runtime1.platform, 'iOS');
expect(runtime1.runtimeRoot, '/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 15.4.simruntime/Contents/Resources/RuntimeRoot');
expect(runtime1.identifier, 'com.apple.CoreSimulator.SimRuntime.iOS-15-4');
expect(runtime1.version, Version(15, 4, null));
expect(runtime1.isInternal, false);
expect(runtime1.isAvailable, true);
expect(runtime1.name, 'iOS 15.4');
final IOSSimulatorRuntime runtime2 = runtimes[1];
expect(runtime2.bundlePath, '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime');
expect(runtime2.buildVersion, '20E247');
expect(runtime2.platform, 'iOS');
expect(runtime2.runtimeRoot, '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot');
expect(runtime2.identifier, 'com.apple.CoreSimulator.SimRuntime.iOS-16-4');
expect(runtime2.version, Version(16, 4, null));
expect(runtime2.isInternal, false);
expect(runtime2.isAvailable, true);
expect(runtime2.name, 'iOS 16.4');
final IOSSimulatorRuntime runtime3 = runtimes[2];
expect(runtime3.bundlePath, '/Library/Developer/CoreSimulator/Volumes/iOS_21A5268h/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 17.0.simruntime');
expect(runtime3.buildVersion, '21A5268h');
expect(runtime3.platform, 'iOS');
expect(runtime3.runtimeRoot, '/Library/Developer/CoreSimulator/Volumes/iOS_21A5268h/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 17.0.simruntime/Contents/Resources/RuntimeRoot');
expect(runtime3.identifier, 'com.apple.CoreSimulator.SimRuntime.iOS-17-0');
expect(runtime3.version, Version(17, 0, null));
expect(runtime3.isInternal, false);
expect(runtime3.isAvailable, true);
expect(runtime3.name, 'iOS 17.0');
});
testWithoutContext('listAvailableIOSRuntimes handles bad simctl output', () async {
fakeProcessManager.addCommand(const FakeCommand(
command: <String>[
'xcrun',
'simctl',
'list',
'runtimes',
'available',
'iOS',
'--json',
],
stdout: 'Install Started',
));
final List<IOSSimulatorRuntime> runtimes = await simControl.listAvailableIOSRuntimes();
expect(runtimes, isEmpty);
expect(logger.errorText, contains('simctl returned non-JSON response:'));
expect(fakeProcessManager, hasNoRemainingExpectations);
});
});
group('startApp', () {
late FakePlistParser testPlistParser;
late FakeSimControl simControl;
late Xcode xcode;
late BufferLogger logger;
setUp(() {
simControl = FakeSimControl();
xcode = Xcode.test(processManager: FakeProcessManager.any());
testPlistParser = FakePlistParser();
logger = BufferLogger.test();
});
testUsingContext("startApp uses compiled app's Info.plist to find CFBundleIdentifier", () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.2',
simControl: simControl,
);
testPlistParser.setProperty('CFBundleIdentifier', 'correct');
final Directory mockDir = globals.fs.currentDirectory;
final IOSApp package = PrebuiltIOSApp(
projectBundleId: 'incorrect',
bundleName: 'name',
uncompressedBundle: mockDir,
applicationPackage: mockDir,
);
const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
final DebuggingOptions mockOptions = DebuggingOptions.disabled(mockInfo);
await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions);
expect(simControl.requests.single.appIdentifier, 'correct');
}, overrides: <Type, Generator>{
PlistParser: () => testPlistParser,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Xcode: () => xcode,
});
testUsingContext('startApp fails when cannot find CFBundleIdentifier', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.2',
simControl: simControl,
);
final Directory mockDir = globals.fs.currentDirectory;
final IOSApp package = PrebuiltIOSApp(
projectBundleId: 'incorrect',
bundleName: 'name',
uncompressedBundle: mockDir,
applicationPackage: mockDir,
);
const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
final DebuggingOptions mockOptions = DebuggingOptions.disabled(mockInfo);
final LaunchResult result = await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions);
expect(result.started, isFalse);
expect(simControl.requests, isEmpty);
expect(logger.errorText, contains('Invalid prebuilt iOS app. Info.plist does not contain bundle identifier'));
}, overrides: <Type, Generator>{
PlistParser: () => testPlistParser,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => logger,
Xcode: () => xcode,
});
testUsingContext('startApp forwards all supported debugging options', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.2',
simControl: simControl,
);
testPlistParser.setProperty('CFBundleIdentifier', 'correct');
final Directory mockDir = globals.fs.currentDirectory;
final IOSApp package = PrebuiltIOSApp(
projectBundleId: 'correct',
bundleName: 'name',
uncompressedBundle: mockDir,
applicationPackage: mockDir,
);
const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
final DebuggingOptions mockOptions = DebuggingOptions.enabled(
mockInfo,
enableSoftwareRendering: true,
traceSystrace: true,
traceToFile: 'path/to/trace.binpb',
startPaused: true,
disableServiceAuthCodes: true,
skiaDeterministicRendering: true,
useTestFonts: true,
traceSkia: true,
traceAllowlist: 'foo,bar',
traceSkiaAllowlist: 'skia.a,skia.b',
endlessTraceBuffer: true,
dumpSkpOnShaderCompilation: true,
verboseSystemLogs: true,
cacheSkSL: true,
purgePersistentCache: true,
dartFlags: '--baz',
enableImpeller: ImpellerStatus.disabled,
nullAssertions: true,
hostVmServicePort: 0,
);
await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions);
expect(simControl.requests.single.launchArgs, unorderedEquals(<String>[
'--enable-dart-profiling',
'--enable-checked-mode',
'--verify-entry-points',
'--enable-software-rendering',
'--trace-systrace',
'--trace-to-file="path/to/trace.binpb"',
'--start-paused',
'--disable-service-auth-codes',
'--skia-deterministic-rendering',
'--use-test-fonts',
'--trace-skia',
'--trace-allowlist="foo,bar"',
'--trace-skia-allowlist="skia.a,skia.b"',
'--endless-trace-buffer',
'--dump-skp-on-shader-compilation',
'--verbose-logging',
'--cache-sksl',
'--purge-persistent-cache',
'--enable-impeller=false',
'--dart-flags=--baz,--null_assertions',
'--vm-service-port=0',
]));
}, overrides: <Type, Generator>{
PlistParser: () => testPlistParser,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Xcode: () => xcode,
});
testUsingContext('startApp using route', () async {
final IOSSimulator device = IOSSimulator(
'x',
name: 'iPhone SE',
simulatorCategory: 'iOS 11.2',
simControl: simControl,
);
testPlistParser.setProperty('CFBundleIdentifier', 'correct');
final Directory mockDir = globals.fs.currentDirectory;
final IOSApp package = PrebuiltIOSApp(
projectBundleId: 'correct',
bundleName: 'name',
uncompressedBundle: mockDir,
applicationPackage: mockDir,
);
const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
final DebuggingOptions mockOptions = DebuggingOptions.enabled(mockInfo, enableSoftwareRendering: true);
await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions, route: '/animation');
expect(simControl.requests.single.launchArgs, contains('--route=/animation'));
}, overrides: <Type, Generator>{
PlistParser: () => testPlistParser,
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Xcode: () => xcode,
});
});
group('IOSDevice.isSupportedForProject', () {
late FakeSimControl simControl;
late Xcode xcode;
setUp(() {
simControl = FakeSimControl();
xcode = Xcode.test(processManager: FakeProcessManager.any());
});
testUsingContext('is true on module project', () async {
globals.fs.file('pubspec.yaml')
..createSync()
..writeAsStringSync(r'''
name: example
flutter:
module: {}
''');
globals.fs.file('.packages').createSync();
final FlutterProject flutterProject = FlutterProject.fromDirectoryTest(globals.fs.currentDirectory);
final IOSSimulator simulator = IOSSimulator(
'test',
name: 'iPhone 11',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
);
expect(simulator.isSupportedForProject(flutterProject), true);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Xcode: () => xcode,
});
testUsingContext('is true with editable host app', () async {
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
globals.fs.directory('ios').createSync();
final FlutterProject flutterProject = FlutterProject.fromDirectoryTest(globals.fs.currentDirectory);
final IOSSimulator simulator = IOSSimulator(
'test',
name: 'iPhone 11',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
);
expect(simulator.isSupportedForProject(flutterProject), true);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Xcode: () => xcode,
});
testUsingContext('is false with no host app and no module', () async {
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final FlutterProject flutterProject = FlutterProject.fromDirectoryTest(globals.fs.currentDirectory);
final IOSSimulator simulator = IOSSimulator(
'test',
name: 'iPhone 11',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
);
expect(simulator.isSupportedForProject(flutterProject), false);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Xcode: () => xcode,
});
testUsingContext('createDevFSWriter returns a LocalDevFSWriter', () {
final IOSSimulator simulator = IOSSimulator(
'test',
name: 'iPhone 11',
simControl: simControl,
simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
);
expect(simulator.createDevFSWriter(null, ''), isA<LocalDevFSWriter>());
});
});
}
class FakeIosProject extends Fake implements IosProject {
@override
Future<String> productBundleIdentifier(BuildInfo? buildInfo) async => 'com.example.test';
@override
Future<String> hostAppBundleName(BuildInfo? buildInfo) async => 'My Super Awesome App.app';
}
class FakeSimControl extends Fake implements SimControl {
final List<LaunchRequest> requests = <LaunchRequest>[];
@override
Future<RunResult> launch(String deviceId, String appIdentifier, [ List<String>? launchArgs ]) async {
requests.add(LaunchRequest(appIdentifier, launchArgs));
return RunResult(ProcessResult(0, 0, '', ''), <String>['test']);
}
@override
Future<RunResult> install(String deviceId, String appPath) async {
return RunResult(ProcessResult(0, 0, '', ''), <String>['test']);
}
}
class LaunchRequest {
const LaunchRequest(this.appIdentifier, this.launchArgs);
final String appIdentifier;
final List<String>? launchArgs;
}
| flutter/packages/flutter_tools/test/general.shard/ios/simulators_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/ios/simulators_test.dart",
"repo_id": "flutter",
"token_count": 20370
} | 831 |
// 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/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/os.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/linux/application_package.dart';
import 'package:flutter_tools/src/linux/linux_device.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart';
final FakePlatform linux = FakePlatform();
final FakePlatform windows = FakePlatform(
operatingSystem: 'windows',
);
void main() {
testWithoutContext('LinuxDevice defaults', () async {
final LinuxDevice device = LinuxDevice(
processManager: FakeProcessManager.any(),
logger: BufferLogger.test(),
fileSystem: MemoryFileSystem.test(),
operatingSystemUtils: FakeOperatingSystemUtils(),
);
final PrebuiltLinuxApp linuxApp = PrebuiltLinuxApp(executable: 'foo');
expect(await device.targetPlatform, TargetPlatform.linux_x64);
expect(device.name, 'Linux');
expect(await device.installApp(linuxApp), true);
expect(await device.uninstallApp(linuxApp), true);
expect(await device.isLatestBuildInstalled(linuxApp), true);
expect(await device.isAppInstalled(linuxApp), true);
expect(await device.stopApp(linuxApp), true);
expect(device.category, Category.desktop);
expect(device.supportsRuntimeMode(BuildMode.debug), true);
expect(device.supportsRuntimeMode(BuildMode.profile), true);
expect(device.supportsRuntimeMode(BuildMode.release), true);
expect(device.supportsRuntimeMode(BuildMode.jitRelease), false);
});
testWithoutContext('LinuxDevice on arm64 hosts is arm64', () async {
final LinuxDevice deviceArm64Host = LinuxDevice(
processManager: FakeProcessManager.any(),
logger: BufferLogger.test(),
fileSystem: MemoryFileSystem.test(),
operatingSystemUtils: FakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
);
expect(await deviceArm64Host.targetPlatform, TargetPlatform.linux_arm64);
});
testWithoutContext('LinuxDevice: no devices listed if platform unsupported', () async {
expect(await LinuxDevices(
fileSystem: MemoryFileSystem.test(),
platform: windows,
featureFlags: TestFeatureFlags(isLinuxEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
).devices(), <Device>[]);
});
testWithoutContext('LinuxDevice: no devices listed if Linux feature flag disabled', () async {
expect(await LinuxDevices(
fileSystem: MemoryFileSystem.test(),
platform: linux,
featureFlags: TestFeatureFlags(),
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
).devices(), <Device>[]);
});
testWithoutContext('LinuxDevice: devices', () async {
expect(await LinuxDevices(
fileSystem: MemoryFileSystem.test(),
platform: linux,
featureFlags: TestFeatureFlags(isLinuxEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
).devices(), hasLength(1));
});
testWithoutContext('LinuxDevice has well known id "linux"', () async {
expect(LinuxDevices(
fileSystem: MemoryFileSystem.test(),
platform: linux,
featureFlags: TestFeatureFlags(isLinuxEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
).wellKnownIds, <String>['linux']);
});
testWithoutContext('LinuxDevice: discoverDevices', () async {
// Timeout ignored.
final List<Device> devices = await LinuxDevices(
fileSystem: MemoryFileSystem.test(),
platform: linux,
featureFlags: TestFeatureFlags(isLinuxEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
operatingSystemUtils: FakeOperatingSystemUtils(),
).discoverDevices(timeout: const Duration(seconds: 10));
expect(devices, hasLength(1));
});
testWithoutContext('LinuxDevice.isSupportedForProject is true with editable host app', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
fileSystem.directory('linux').createSync();
final FlutterProject flutterProject = setUpFlutterProject(fileSystem.currentDirectory);
expect(LinuxDevice(
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
operatingSystemUtils: FakeOperatingSystemUtils(),
).isSupportedForProject(flutterProject), true);
});
testWithoutContext('LinuxDevice.isSupportedForProject is false with no host app', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final FlutterProject flutterProject = setUpFlutterProject(fileSystem.currentDirectory);
expect(LinuxDevice(
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
fileSystem: fileSystem,
operatingSystemUtils: FakeOperatingSystemUtils(),
).isSupportedForProject(flutterProject), false);
});
testWithoutContext('LinuxDevice.executablePathForDevice uses the correct package executable', () async {
final FakeLinuxApp mockApp = FakeLinuxApp();
final LinuxDevice device = LinuxDevice(
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
fileSystem: MemoryFileSystem.test(),
operatingSystemUtils: FakeOperatingSystemUtils(),
);
expect(device.executablePathForDevice(mockApp, BuildInfo.debug), 'debug/executable');
expect(device.executablePathForDevice(mockApp, BuildInfo.profile), 'profile/executable');
expect(device.executablePathForDevice(mockApp, BuildInfo.release), 'release/executable');
});
}
FlutterProject setUpFlutterProject(Directory directory) {
final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(
fileSystem: directory.fileSystem,
logger: BufferLogger.test(),
);
return flutterProjectFactory.fromDirectory(directory);
}
class FakeLinuxApp extends Fake implements LinuxApp {
@override
String executable(BuildMode buildMode) => switch (buildMode) {
BuildMode.debug => 'debug/executable',
BuildMode.profile => 'profile/executable',
BuildMode.release => 'release/executable',
_ => throw StateError('Invalid mode: $buildMode'),
};
}
class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils {
FakeOperatingSystemUtils({
HostPlatform hostPlatform = HostPlatform.linux_x64
}) : _hostPlatform = hostPlatform;
final HostPlatform _hostPlatform;
@override
String get name => 'Linux';
@override
HostPlatform get hostPlatform => _hostPlatform;
}
| flutter/packages/flutter_tools/test/general.shard/linux/linux_device_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/linux/linux_device_test.dart",
"repo_id": "flutter",
"token_count": 2388
} | 832 |
// 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/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/platform_plugins.dart';
import 'package:flutter_tools/src/plugins.dart';
import 'package:yaml/yaml.dart';
import '../src/common.dart';
const String _kTestPluginName = 'test_plugin_name';
const String _kTestPluginPath = 'test_plugin_path';
void main() {
testWithoutContext('Plugin creation from the legacy format', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw = 'androidPackage: com.flutter.dev\n'
'iosPrefix: FLT\n'
'pluginClass: SamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin;
final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin;
expect(iosPlugin.pluginClass, 'SamplePlugin');
expect(iosPlugin.classPrefix, 'FLT');
expect(iosPlugin.sharedDarwinSource, isFalse);
expect(androidPlugin.pluginClass, 'SamplePlugin');
expect(androidPlugin.package, 'com.flutter.dev');
});
testWithoutContext('Plugin creation from the multi-platform format', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw = 'platforms:\n'
' android:\n'
' package: com.flutter.dev\n'
' pluginClass: ASamplePlugin\n'
' ios:\n'
' pluginClass: ISamplePlugin\n'
' sharedDarwinSource: true\n'
' linux:\n'
' pluginClass: LSamplePlugin\n'
' macos:\n'
' pluginClass: MSamplePlugin\n'
' sharedDarwinSource: true\n'
' web:\n'
' pluginClass: WebSamplePlugin\n'
' fileName: web_plugin.dart\n'
' windows:\n'
' pluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin;
final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin;
final LinuxPlugin linuxPlugin = plugin.platforms[LinuxPlugin.kConfigKey]! as LinuxPlugin;
final MacOSPlugin macOSPlugin = plugin.platforms[MacOSPlugin.kConfigKey]! as MacOSPlugin;
final WebPlugin webPlugin = plugin.platforms[WebPlugin.kConfigKey]! as WebPlugin;
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(iosPlugin.pluginClass, 'ISamplePlugin');
expect(iosPlugin.classPrefix, '');
expect(iosPlugin.sharedDarwinSource, isTrue);
expect(androidPlugin.pluginClass, 'ASamplePlugin');
expect(androidPlugin.package, 'com.flutter.dev');
expect(linuxPlugin.pluginClass, 'LSamplePlugin');
expect(macOSPlugin.pluginClass, 'MSamplePlugin');
expect(macOSPlugin.sharedDarwinSource, isTrue);
expect(webPlugin.pluginClass, 'WebSamplePlugin');
expect(webPlugin.fileName, 'web_plugin.dart');
expect(windowsPlugin.pluginClass, 'WinSamplePlugin');
});
testWithoutContext('Plugin parsing of unknown fields are allowed (allows some future compatibility)', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw = 'implements: same_plugin\n' // this should be ignored by the tool
'platforms:\n'
' android:\n'
' package: com.flutter.dev\n'
' pluginClass: ASamplePlugin\n'
' anUnknownField: ASamplePlugin\n' // this should be ignored by the tool
' ios:\n'
' pluginClass: ISamplePlugin\n'
' linux:\n'
' pluginClass: LSamplePlugin\n'
' macos:\n'
' pluginClass: MSamplePlugin\n'
' web:\n'
' pluginClass: WebSamplePlugin\n'
' fileName: web_plugin.dart\n'
' windows:\n'
' pluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin;
final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin;
final LinuxPlugin linuxPlugin = plugin.platforms[LinuxPlugin.kConfigKey]! as LinuxPlugin;
final MacOSPlugin macOSPlugin = plugin.platforms[MacOSPlugin.kConfigKey]! as MacOSPlugin;
final WebPlugin webPlugin = plugin.platforms[WebPlugin.kConfigKey]! as WebPlugin;
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(iosPlugin.pluginClass, 'ISamplePlugin');
expect(iosPlugin.classPrefix, '');
expect(iosPlugin.sharedDarwinSource, isFalse);
expect(androidPlugin.pluginClass, 'ASamplePlugin');
expect(androidPlugin.package, 'com.flutter.dev');
expect(linuxPlugin.pluginClass, 'LSamplePlugin');
expect(macOSPlugin.pluginClass, 'MSamplePlugin');
expect(macOSPlugin.sharedDarwinSource, isFalse);
expect(webPlugin.pluginClass, 'WebSamplePlugin');
expect(webPlugin.fileName, 'web_plugin.dart');
expect(windowsPlugin.pluginClass, 'WinSamplePlugin');
});
testWithoutContext('Plugin parsing allows for Dart-only plugins without a pluginClass', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw = 'implements: same_plugin\n' // this should be ignored by the tool
'platforms:\n'
' android:\n'
' dartPluginClass: ASamplePlugin\n'
' ios:\n'
' dartPluginClass: ISamplePlugin\n'
' linux:\n'
' dartPluginClass: LSamplePlugin\n'
' macos:\n'
' dartPluginClass: MSamplePlugin\n'
' windows:\n'
' dartPluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin;
final IOSPlugin iOSPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin;
final LinuxPlugin linuxPlugin = plugin.platforms[LinuxPlugin.kConfigKey]! as LinuxPlugin;
final MacOSPlugin macOSPlugin = plugin.platforms[MacOSPlugin.kConfigKey]! as MacOSPlugin;
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(androidPlugin.pluginClass, isNull);
expect(iOSPlugin.pluginClass, isNull);
expect(linuxPlugin.pluginClass, isNull);
expect(macOSPlugin.pluginClass, isNull);
expect(windowsPlugin.pluginClass, isNull);
expect(androidPlugin.dartPluginClass, 'ASamplePlugin');
expect(iOSPlugin.dartPluginClass, 'ISamplePlugin');
expect(linuxPlugin.dartPluginClass, 'LSamplePlugin');
expect(macOSPlugin.dartPluginClass, 'MSamplePlugin');
expect(windowsPlugin.dartPluginClass, 'WinSamplePlugin');
});
testWithoutContext('Plugin parsing of legacy format and multi-platform format together is not allowed '
'and fatal error message contains plugin name', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw = 'androidPackage: com.flutter.dev\n'
'platforms:\n'
' android:\n'
' package: com.flutter.dev\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
expect(
() => Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
),
throwsToolExit(message: _kTestPluginName),
);
});
testWithoutContext('Plugin parsing allows a default_package field', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw =
'platforms:\n'
' android:\n'
' default_package: sample_package_android\n'
' ios:\n'
' default_package: sample_package_ios\n'
' linux:\n'
' default_package: sample_package_linux\n'
' macos:\n'
' default_package: sample_package_macos\n'
' web:\n'
' default_package: sample_package_web\n'
' windows:\n'
' default_package: sample_package_windows\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
expect(plugin.platforms, <String, PluginPlatform>{});
expect(plugin.defaultPackagePlatforms, <String, String>{
'android': 'sample_package_android',
'ios': 'sample_package_ios',
'linux': 'sample_package_linux',
'macos': 'sample_package_macos',
'windows': 'sample_package_windows',
});
expect(plugin.pluginDartClassPlatforms, <String, String>{});
});
testWithoutContext('Desktop plugin parsing allows a dartPluginClass field', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw =
'platforms:\n'
' linux:\n'
' dartPluginClass: LinuxClass\n'
' macos:\n'
' dartPluginClass: MacOSClass\n'
' windows:\n'
' dartPluginClass: WindowsClass\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
expect(plugin.pluginDartClassPlatforms, <String, String>{
'linux': 'LinuxClass',
'macos': 'MacOSClass',
'windows': 'WindowsClass',
});
});
testWithoutContext('Windows allows supported mode lists', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw =
'platforms:\n'
' windows:\n'
' pluginClass: WinSamplePlugin\n'
' supportedVariants:\n'
' - win32\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(windowsPlugin.supportedVariants, <PluginPlatformVariant>[
PluginPlatformVariant.win32,
]);
});
testWithoutContext('Web plugin tool exits if fileName field missing', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw =
'platforms:\n'
' web:\n'
' pluginClass: WebSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
expect(
() => Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
),
throwsToolExit(
message: 'The plugin `$_kTestPluginName` is missing the required field `fileName` in pubspec.yaml',
),
);
});
testWithoutContext('Windows assumes win32 when no variants are given', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw =
'platforms:\n'
' windows:\n'
' pluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(windowsPlugin.supportedVariants, <PluginPlatformVariant>[
PluginPlatformVariant.win32,
]);
});
testWithoutContext('Windows ignores unknown variants', () {
final FileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw =
'platforms:\n'
' windows:\n'
' pluginClass: WinSamplePlugin\n'
' supportedVariants:\n'
' - not_yet_invented_variant\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
final Plugin plugin = Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
);
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(windowsPlugin.supportedVariants, <PluginPlatformVariant>{});
});
testWithoutContext('Plugin parsing throws a fatal error on an empty plugin', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final YamlMap? pluginYaml = loadYaml('') as YamlMap?;
expect(
() => Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
),
throwsToolExit(message: 'Invalid "plugin" specification.'),
);
});
testWithoutContext('Plugin parsing throws a fatal error on empty platforms', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw = 'platforms:\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
expect(
() => Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
),
throwsToolExit(message: 'Invalid "platforms" specification.'),
);
});
test('Plugin parsing throws a fatal error on an empty platform key', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
const String pluginYamlRaw =
'platforms:\n'
' android:\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
expect(
() => Plugin.fromYaml(
_kTestPluginName,
_kTestPluginPath,
pluginYaml,
null,
const <String>[],
fileSystem: fileSystem,
),
throwsToolExit(message: 'Invalid "android" plugin specification.'),
);
});
}
| flutter/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart",
"repo_id": "flutter",
"token_count": 5576
} | 833 |
// 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:file/memory.dart';
import 'package:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/time.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/isolated/devfs_web.dart';
import 'package:flutter_tools/src/isolated/resident_web_runner.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:test/fake.dart';
import '../src/common.dart';
import '../src/context.dart';
import '../src/fakes.dart';
import '../src/test_build_system.dart';
void main() {
late FakeFlutterDevice mockFlutterDevice;
late FakeWebDevFS mockWebDevFS;
late FileSystem fileSystem;
setUp(() {
fileSystem = MemoryFileSystem.test();
mockWebDevFS = FakeWebDevFS();
final FakeWebDevice mockWebDevice = FakeWebDevice();
mockFlutterDevice = FakeFlutterDevice(mockWebDevice);
mockFlutterDevice._devFS = mockWebDevFS;
fileSystem.file('.packages').writeAsStringSync('\n');
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true);
fileSystem.file(fileSystem.path.join('web', 'index.html')).createSync(recursive: true);
});
testUsingContext('Can successfully run and connect without vmservice', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final ResidentWebRunner residentWebRunner = ResidentWebRunner(
mockFlutterDevice,
flutterProject: project,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
ipv6: true,
fileSystem: fileSystem,
logger: BufferLogger.test(),
systemClock: SystemClock.fixed(DateTime(0, 0, 0)),
usage: TestUsage(),
analytics: getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
),
);
final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
unawaited(residentWebRunner.run(
connectionInfoCompleter: connectionInfoCompleter,
));
final DebugConnectionInfo debugConnectionInfo = await connectionInfoCompleter.future;
expect(debugConnectionInfo.wsUri, null);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
// Regression test for https://github.com/flutter/flutter/issues/60613
testUsingContext('ResidentWebRunner calls appFailedToStart if initial compilation fails', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final ResidentWebRunner residentWebRunner = ResidentWebRunner(
mockFlutterDevice,
flutterProject: project,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
ipv6: true,
fileSystem: fileSystem,
logger: BufferLogger.test(),
systemClock: SystemClock.fixed(DateTime(0, 0, 0)),
usage: TestUsage(),
analytics: getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
),
);
expect(() => residentWebRunner.run(), throwsToolExit());
expect(await residentWebRunner.waitForAppToFinish(), 1);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: false)),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
// Regression test for https://github.com/flutter/flutter/issues/60613
testUsingContext('ResidentWebRunner calls appFailedToStart if error is thrown during startup', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final ResidentWebRunner residentWebRunner = ResidentWebRunner(
mockFlutterDevice,
flutterProject: project,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
ipv6: true,
fileSystem: fileSystem,
logger: BufferLogger.test(),
systemClock: SystemClock.fixed(DateTime(0, 0, 0)),
usage: TestUsage(),
analytics: getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
),
);
expect(() async => residentWebRunner.run(), throwsException);
expect(await residentWebRunner.waitForAppToFinish(), 1);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.error(Exception('foo')),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Can full restart after attaching', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final ResidentWebRunner residentWebRunner = ResidentWebRunner(
mockFlutterDevice,
flutterProject: project,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
ipv6: true,
fileSystem: fileSystem,
logger: BufferLogger.test(),
systemClock: SystemClock.fixed(DateTime(0, 0, 0)),
usage: TestUsage(),
analytics: getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
),
);
final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
unawaited(residentWebRunner.run(
connectionInfoCompleter: connectionInfoCompleter,
));
await connectionInfoCompleter.future;
final OperationResult result = await residentWebRunner.restart(fullRestart: true);
expect(result.code, 0);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Fails on compilation errors in hot restart', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final ResidentWebRunner residentWebRunner = ResidentWebRunner(
mockFlutterDevice,
flutterProject: project,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
ipv6: true,
fileSystem: fileSystem,
logger: BufferLogger.test(),
systemClock: SystemClock.fixed(DateTime(0, 0, 0)),
usage: TestUsage(),
analytics: getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
),
);
final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
unawaited(residentWebRunner.run(
connectionInfoCompleter: connectionInfoCompleter,
));
await connectionInfoCompleter.future;
final OperationResult result = await residentWebRunner.restart(fullRestart: true);
expect(result.code, 1);
expect(result.message, contains('Failed to recompile application.'));
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.list(<BuildResult>[
BuildResult(success: true),
BuildResult(success: false),
]),
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
}
class FakeWebDevFS extends Fake implements WebDevFS {
@override
List<Uri> get sources => <Uri>[];
@override
Future<Uri> create() async {
return Uri.base;
}
}
class FakeWebDevice extends Fake implements Device {
@override
String get name => 'web';
@override
Future<bool> stopApp(
ApplicationPackage? app, {
String? userIdentifier,
}) async {
return true;
}
@override
Future<LaunchResult> startApp(
ApplicationPackage? package, {
String? mainPath,
String? route,
DebuggingOptions? debuggingOptions,
Map<String, dynamic>? platformArgs,
bool prebuiltApplication = false,
bool ipv6 = false,
String? userIdentifier,
}) async {
return LaunchResult.succeeded();
}
}
class FakeFlutterDevice extends Fake implements FlutterDevice {
FakeFlutterDevice(this.device);
@override
final FakeWebDevice device;
DevFS? _devFS;
@override
DevFS? get devFS => _devFS;
@override
set devFS(DevFS? value) { }
@override
FlutterVmService? vmService;
}
| flutter/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart",
"repo_id": "flutter",
"token_count": 2980
} | 834 |
// 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:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/tester/flutter_tester.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart';
import '../../src/test_build_system.dart';
void main() {
late MemoryFileSystem fileSystem;
setUp(() {
fileSystem = MemoryFileSystem.test();
});
testWithoutContext('FlutterTesterApp can be created from the current directory', () async {
const String projectPath = '/home/my/projects/my_project';
await fileSystem.directory(projectPath).create(recursive: true);
fileSystem.currentDirectory = projectPath;
final FlutterTesterApp app = FlutterTesterApp.fromCurrentDirectory(fileSystem);
expect(app.name, 'my_project');
});
group('FlutterTesterDevices', () {
tearDown(() {
FlutterTesterDevices.showFlutterTesterDevice = false;
});
testWithoutContext('no device', () async {
final FlutterTesterDevices discoverer = setUpFlutterTesterDevices();
final List<Device> devices = await discoverer.devices();
expect(devices, isEmpty);
});
testWithoutContext('has device', () async {
FlutterTesterDevices.showFlutterTesterDevice = true;
final FlutterTesterDevices discoverer = setUpFlutterTesterDevices();
final List<Device> devices = await discoverer.devices();
expect(devices, hasLength(1));
final Device device = devices.single;
expect(device, isA<FlutterTesterDevice>());
expect(device.id, 'flutter-tester');
});
testWithoutContext('discoverDevices', () async {
FlutterTesterDevices.showFlutterTesterDevice = true;
final FlutterTesterDevices discoverer = setUpFlutterTesterDevices();
// Timeout ignored.
final List<Device> devices = await discoverer.discoverDevices(timeout: const Duration(seconds: 10));
expect(devices, hasLength(1));
});
});
group('startApp', () {
late FlutterTesterDevice device;
late List<String> logLines;
String? mainPath;
late FakeProcessManager fakeProcessManager;
late TestBuildSystem buildSystem;
final Map<Type, Generator> startOverrides = <Type, Generator>{
Platform: () => FakePlatform(),
FileSystem: () => fileSystem,
ProcessManager: () => fakeProcessManager,
Artifacts: () => Artifacts.test(),
BuildSystem: () => buildSystem,
};
setUp(() {
buildSystem = TestBuildSystem.all(BuildResult(success: true));
fakeProcessManager = FakeProcessManager.empty();
device = FlutterTesterDevice('flutter-tester',
fileSystem: fileSystem,
processManager: fakeProcessManager,
artifacts: Artifacts.test(),
logger: BufferLogger.test(),
flutterVersion: FakeFlutterVersion(),
);
logLines = <String>[];
device.getLogReader().logLines.listen(logLines.add);
});
testWithoutContext('default settings', () async {
expect(device.id, 'flutter-tester');
expect(await device.isLocalEmulator, isFalse);
expect(device.name, 'Flutter test device');
expect(device.portForwarder, isNot(isNull));
expect(await device.targetPlatform, TargetPlatform.tester);
expect(await device.installApp(FakeApplicationPackage()), isTrue);
expect(await device.isAppInstalled(FakeApplicationPackage()), isFalse);
expect(await device.isLatestBuildInstalled(FakeApplicationPackage()), isFalse);
expect(await device.uninstallApp(FakeApplicationPackage()), isTrue);
expect(device.isSupported(), isTrue);
});
testWithoutContext('does not accept profile, release, or jit-release builds', () async {
final LaunchResult releaseResult = await device.startApp(FakeApplicationPackage(),
mainPath: mainPath,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
);
final LaunchResult profileResult = await device.startApp(FakeApplicationPackage(),
mainPath: mainPath,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.profile),
);
final LaunchResult jitReleaseResult = await device.startApp(FakeApplicationPackage(),
mainPath: mainPath,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.jitRelease),
);
expect(releaseResult.started, isFalse);
expect(profileResult.started, isFalse);
expect(jitReleaseResult.started, isFalse);
});
testUsingContext('performs a build and starts in debug mode', () async {
final FlutterTesterApp app = FlutterTesterApp.fromCurrentDirectory(fileSystem);
final Uri vmServiceUri = Uri.parse('http://127.0.0.1:6666/');
final Completer<void> completer = Completer<void>();
fakeProcessManager.addCommand(FakeCommand(
command: const <String>[
'Artifact.flutterTester',
'--run-forever',
'--non-interactive',
'--enable-dart-profiling',
'--packages=.dart_tool/package_config.json',
'--flutter-assets-dir=/.tmp_rand0/flutter_tester.rand0',
'/.tmp_rand0/flutter_tester.rand0/flutter-tester-app.dill',
],
completer: completer,
stdout:
'''
The Dart VM service is listening on $vmServiceUri
Hello!
''',
));
final LaunchResult result = await device.startApp(app,
mainPath: mainPath,
debuggingOptions: DebuggingOptions.enabled(const BuildInfo(BuildMode.debug, null, treeShakeIcons: false)),
);
expect(result.started, isTrue);
expect(result.vmServiceUri, vmServiceUri);
expect(logLines.last, 'Hello!');
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: startOverrides);
testUsingContext('performs a build and starts in debug mode with track-widget-creation', () async {
final FlutterTesterApp app = FlutterTesterApp.fromCurrentDirectory(fileSystem);
final Uri vmServiceUri = Uri.parse('http://127.0.0.1:6666/');
final Completer<void> completer = Completer<void>();
fakeProcessManager.addCommand(FakeCommand(
command: const <String>[
'Artifact.flutterTester',
'--run-forever',
'--non-interactive',
'--enable-dart-profiling',
'--packages=.dart_tool/package_config.json',
'--flutter-assets-dir=/.tmp_rand0/flutter_tester.rand0',
'/.tmp_rand0/flutter_tester.rand0/flutter-tester-app.dill.track.dill',
],
completer: completer,
stdout:
'''
The Dart VM service is listening on $vmServiceUri
Hello!
''',
));
final LaunchResult result = await device.startApp(app,
mainPath: mainPath,
debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
);
expect(result.started, isTrue);
expect(result.vmServiceUri, vmServiceUri);
expect(logLines.last, 'Hello!');
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: startOverrides);
});
}
FlutterTesterDevices setUpFlutterTesterDevices() {
return FlutterTesterDevices(
logger: BufferLogger.test(),
artifacts: Artifacts.test(),
processManager: FakeProcessManager.any(),
fileSystem: MemoryFileSystem.test(),
flutterVersion: FakeFlutterVersion(),
);
}
class FakeApplicationPackage extends Fake implements ApplicationPackage {}
| flutter/packages/flutter_tools/test/general.shard/tester/flutter_tester_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/tester/flutter_tester_test.dart",
"repo_id": "flutter",
"token_count": 2927
} | 835 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/test/flutter_web_goldens.dart';
import 'package:flutter_tools/src/test/test_compiler.dart';
import 'package:flutter_tools/src/web/compile.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
final Uri goldenKey = Uri.parse('file://golden_key');
final Uri goldenKey2 = Uri.parse('file://second_golden_key');
final Uri testUri = Uri.parse('file://test_uri');
final Uri testUri2 = Uri.parse('file://second_test_uri');
final Uint8List imageBytes = Uint8List.fromList(<int>[1, 2, 3, 4, 5]);
void main() {
group('Test that TestGoldenComparator', () {
late FakeProcessManager processManager;
setUp(() {
processManager = FakeProcessManager.empty();
});
testWithoutContext('succeed when golden comparison succeed', () async {
final Map<String, dynamic> expectedResponse = <String, dynamic>{
'success': true,
'message': 'some message',
};
processManager.addCommand(FakeCommand(
command: const <String>[
'shell',
'--disable-vm-service',
'--non-interactive',
'--packages=.dart_tool/package_config.json',
'compiler_output',
],
stdout: '${jsonEncode(expectedResponse)}\n',
environment: const <String, String>{
'FLUTTER_TEST_BROWSER': 'chrome',
'FLUTTER_WEB_RENDERER': 'html',
},
));
final TestGoldenComparator comparator = TestGoldenComparator(
'shell',
() => FakeTestCompiler(),
processManager: processManager,
fileSystem: MemoryFileSystem.test(),
logger: BufferLogger.test(),
webRenderer: WebRendererMode.html,
);
final String? result = await comparator.compareGoldens(testUri, imageBytes, goldenKey, false);
expect(result, null);
});
testWithoutContext('fail with error message when golden comparison failed', () async {
final Map<String, dynamic> expectedResponse = <String, dynamic>{
'success': false,
'message': 'some message',
};
processManager.addCommand(FakeCommand(
command: const <String>[
'shell',
'--disable-vm-service',
'--non-interactive',
'--packages=.dart_tool/package_config.json',
'compiler_output',
], stdout: '${jsonEncode(expectedResponse)}\n',
));
final TestGoldenComparator comparator = TestGoldenComparator(
'shell',
() => FakeTestCompiler(),
processManager: processManager,
fileSystem: MemoryFileSystem.test(),
logger: BufferLogger.test(),
webRenderer: WebRendererMode.canvaskit,
);
final String? result = await comparator.compareGoldens(testUri, imageBytes, goldenKey, false);
expect(result, 'some message');
});
testWithoutContext('reuse the process for the same test file', () async {
final Map<String, dynamic> expectedResponse1 = <String, dynamic>{
'success': false,
'message': 'some message',
};
final Map<String, dynamic> expectedResponse2 = <String, dynamic>{
'success': false,
'message': 'some other message',
};
processManager.addCommand(FakeCommand(
command: const <String>[
'shell',
'--disable-vm-service',
'--non-interactive',
'--packages=.dart_tool/package_config.json',
'compiler_output',
], stdout: '${jsonEncode(expectedResponse1)}\n${jsonEncode(expectedResponse2)}\n',
));
final TestGoldenComparator comparator = TestGoldenComparator(
'shell',
() => FakeTestCompiler(),
processManager: processManager,
fileSystem: MemoryFileSystem.test(),
logger: BufferLogger.test(),
webRenderer: WebRendererMode.html,
);
final String? result1 = await comparator.compareGoldens(testUri, imageBytes, goldenKey, false);
expect(result1, 'some message');
final String? result2 = await comparator.compareGoldens(testUri, imageBytes, goldenKey2, false);
expect(result2, 'some other message');
});
testWithoutContext('does not reuse the process for different test file', () async {
final Map<String, dynamic> expectedResponse1 = <String, dynamic>{
'success': false,
'message': 'some message',
};
final Map<String, dynamic> expectedResponse2 = <String, dynamic>{
'success': false,
'message': 'some other message',
};
processManager.addCommand(FakeCommand(
command: const <String>[
'shell',
'--disable-vm-service',
'--non-interactive',
'--packages=.dart_tool/package_config.json',
'compiler_output',
], stdout: '${jsonEncode(expectedResponse1)}\n',
));
processManager.addCommand(FakeCommand(
command: const <String>[
'shell',
'--disable-vm-service',
'--non-interactive',
'--packages=.dart_tool/package_config.json',
'compiler_output',
], stdout: '${jsonEncode(expectedResponse2)}\n',
));
final TestGoldenComparator comparator = TestGoldenComparator(
'shell',
() => FakeTestCompiler(),
processManager: processManager,
fileSystem: MemoryFileSystem.test(),
logger: BufferLogger.test(),
webRenderer: WebRendererMode.canvaskit,
);
final String? result1 = await comparator.compareGoldens(testUri, imageBytes, goldenKey, false);
expect(result1, 'some message');
final String? result2 = await comparator.compareGoldens(testUri2, imageBytes, goldenKey2, false);
expect(result2, 'some other message');
});
testWithoutContext('removes all temporary files when closed', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
final Map<String, dynamic> expectedResponse = <String, dynamic>{
'success': true,
'message': 'some message',
};
final StreamController<List<int>> controller = StreamController<List<int>>();
final IOSink stdin = IOSink(controller.sink);
processManager.addCommand(FakeCommand(
command: const <String>[
'shell',
'--disable-vm-service',
'--non-interactive',
'--packages=.dart_tool/package_config.json',
'compiler_output',
], stdout: '${jsonEncode(expectedResponse)}\n',
stdin: stdin,
));
final TestGoldenComparator comparator = TestGoldenComparator(
'shell',
() => FakeTestCompiler(),
processManager: processManager,
fileSystem: fileSystem,
logger: BufferLogger.test(),
webRenderer: WebRendererMode.html,
);
final String? result = await comparator.compareGoldens(testUri, imageBytes, goldenKey, false);
expect(result, null);
await comparator.close();
expect(fileSystem.systemTempDirectory.listSync(recursive: true), isEmpty);
});
});
}
class FakeTestCompiler extends Fake implements TestCompiler {
@override
Future<String> compile(Uri mainDart) {
return Future<String>.value('compiler_output');
}
@override
Future<void> dispose() async { }
}
| flutter/packages/flutter_tools/test/general.shard/web/golden_comparator_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/web/golden_comparator_test.dart",
"repo_id": "flutter",
"token_count": 3049
} | 836 |
// 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_tools/src/base/platform.dart';
import 'package:flutter_tools/src/windows/windows_workflow.dart';
import '../../src/common.dart';
import '../../src/fakes.dart';
void main() {
final FakePlatform windows = FakePlatform(operatingSystem: 'windows');
final FakePlatform notWindows = FakePlatform();
testWithoutContext('Windows workflow configuration when feature is enabled on Windows host machine', () {
final WindowsWorkflow windowsWorkflow = WindowsWorkflow(
platform: windows,
featureFlags: TestFeatureFlags(isWindowsEnabled: true),
);
expect(windowsWorkflow.appliesToHostPlatform, true);
expect(windowsWorkflow.canListDevices, true);
expect(windowsWorkflow.canLaunchDevices, true);
expect(windowsWorkflow.canListEmulators, false);
});
testWithoutContext('Windows workflow configuration when feature is disabled on Windows host machine', () {
final WindowsWorkflow windowsWorkflow = WindowsWorkflow(
platform: windows,
featureFlags: TestFeatureFlags(),
);
expect(windowsWorkflow.appliesToHostPlatform, false);
expect(windowsWorkflow.canListDevices, false);
expect(windowsWorkflow.canLaunchDevices, false);
expect(windowsWorkflow.canListEmulators, false);
});
testWithoutContext('Windows workflow configuration when feature is enabled on non-Windows host machine', () {
final WindowsWorkflow windowsWorkflow = WindowsWorkflow(
platform: notWindows,
featureFlags: TestFeatureFlags(isWindowsEnabled: true),
);
expect(windowsWorkflow.appliesToHostPlatform, false);
expect(windowsWorkflow.canListDevices, false);
expect(windowsWorkflow.canLaunchDevices, false);
expect(windowsWorkflow.canListEmulators, false);
});
testWithoutContext('Windows workflow configuration when feature is disabled on non-Windows host machine', () {
final WindowsWorkflow windowsWorkflow = WindowsWorkflow(
platform: notWindows,
featureFlags: TestFeatureFlags(),
);
expect(windowsWorkflow.appliesToHostPlatform, false);
expect(windowsWorkflow.canListDevices, false);
expect(windowsWorkflow.canLaunchDevices, false);
expect(windowsWorkflow.canListEmulators, false);
});
}
| flutter/packages/flutter_tools/test/general.shard/windows/windows_workflow_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/windows/windows_workflow_test.dart",
"repo_id": "flutter",
"token_count": 707
} | 837 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io' as io;
import 'package:file/file.dart';
import 'package:flutter_tools/src/android/gradle_utils.dart'
show getGradlewFileName;
import 'package:flutter_tools/src/base/io.dart';
import 'package:xml/xml.dart';
import '../src/common.dart';
import 'test_utils.dart';
final XmlElement deeplinkFlagMetaData = XmlElement(
XmlName('meta-data'),
<XmlAttribute>[
XmlAttribute(XmlName('name', 'android'), 'flutter_deeplinking_enabled'),
XmlAttribute(XmlName('value', 'android'), 'true'),
],
);
final XmlElement pureHttpIntentFilter = XmlElement(
XmlName('intent-filter'),
<XmlAttribute>[XmlAttribute(XmlName('autoVerify', 'android'), 'true')],
<XmlElement>[
XmlElement(
XmlName('action'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'http'),
XmlAttribute(XmlName('host', 'android'), 'pure-http.com'),
],
),
],
);
final XmlElement nonHttpIntentFilter = XmlElement(
XmlName('intent-filter'),
<XmlAttribute>[XmlAttribute(XmlName('autoVerify', 'android'), 'true')],
<XmlElement>[
XmlElement(
XmlName('action'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'custom'),
XmlAttribute(XmlName('host', 'android'), 'custom.com'),
],
),
],
);
final XmlElement hybridIntentFilter = XmlElement(
XmlName('intent-filter'),
<XmlAttribute>[XmlAttribute(XmlName('autoVerify', 'android'), 'true')],
<XmlElement>[
XmlElement(
XmlName('action'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'custom'),
XmlAttribute(XmlName('host', 'android'), 'hybrid.com'),
],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'http'),
],
),
],
);
final XmlElement nonAutoVerifyIntentFilter = XmlElement(
XmlName('intent-filter'),
<XmlAttribute>[],
<XmlElement>[
XmlElement(
XmlName('action'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'http'),
XmlAttribute(XmlName('host', 'android'), 'non-auto-verify.com'),
],
),
],
);
final XmlElement nonActionIntentFilter = XmlElement(
XmlName('intent-filter'),
<XmlAttribute>[XmlAttribute(XmlName('autoVerify', 'android'), 'true')],
<XmlElement>[
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'http'),
XmlAttribute(XmlName('host', 'android'), 'non-action.com'),
],
),
],
);
final XmlElement nonDefaultCategoryIntentFilter = XmlElement(
XmlName('intent-filter'),
<XmlAttribute>[XmlAttribute(XmlName('autoVerify', 'android'), 'true')],
<XmlElement>[
XmlElement(
XmlName('action'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'http'),
XmlAttribute(XmlName('host', 'android'), 'non-default-category.com'),
],
),
],
);
final XmlElement nonBrowsableCategoryIntentFilter = XmlElement(
XmlName('intent-filter'),
<XmlAttribute>[XmlAttribute(XmlName('autoVerify', 'android'), 'true')],
<XmlElement>[
XmlElement(
XmlName('action'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')],
),
XmlElement(
XmlName('category'),
<XmlAttribute>[XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')],
),
XmlElement(
XmlName('data'),
<XmlAttribute>[
XmlAttribute(XmlName('scheme', 'android'), 'http'),
XmlAttribute(XmlName('host', 'android'), 'non-browsable-category.com'),
],
),
],
);
void main() {
late Directory tempDir;
setUp(() async {
tempDir = createResolvedTempDirectorySync('run_test.');
});
tearDown(() async {
tryToDelete(tempDir);
});
void testDeeplink(
dynamic deeplink,
String scheme,
String host,
String path, {
required bool hasAutoVerify,
required bool hasActionView,
required bool hasDefaultCategory,
required bool hasBrowsableCategory,
}) {
deeplink as Map<String, dynamic>;
expect(deeplink['scheme'], scheme);
expect(deeplink['host'], host);
expect(deeplink['path'], path);
final Map<String, dynamic> intentFilterCheck = deeplink['intentFilterCheck'] as Map<String, dynamic>;
expect(intentFilterCheck['hasAutoVerify'], hasAutoVerify);
expect(intentFilterCheck['hasActionView'], hasActionView);
expect(intentFilterCheck['hasDefaultCategory'], hasDefaultCategory);
expect(intentFilterCheck['hasBrowsableCategory'], hasBrowsableCategory);
}
testWithoutContext(
'gradle task outputs<mode>AppLinkSettings works when a project has app links', () async {
// Create a new flutter project.
final String flutterBin =
fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
ProcessResult result = await processManager.run(<String>[
flutterBin,
'create',
tempDir.path,
'--project-name=testapp',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher());
// Adds intent filters for app links
final String androidManifestPath = fileSystem.path.join(tempDir.path, 'android', 'app', 'src', 'main', 'AndroidManifest.xml');
final io.File androidManifestFile = io.File(androidManifestPath);
final XmlDocument androidManifest = XmlDocument.parse(androidManifestFile.readAsStringSync());
final XmlElement activity = androidManifest.findAllElements('activity').first;
activity.children.add(deeplinkFlagMetaData);
activity.children.add(pureHttpIntentFilter);
activity.children.add(nonHttpIntentFilter);
activity.children.add(hybridIntentFilter);
activity.children.add(nonAutoVerifyIntentFilter);
activity.children.add(nonActionIntentFilter);
activity.children.add(nonDefaultCategoryIntentFilter);
activity.children.add(nonBrowsableCategoryIntentFilter);
androidManifestFile.writeAsStringSync(androidManifest.toString(), flush: true);
// Ensure that gradle files exists from templates.
result = await processManager.run(<String>[
flutterBin,
'build',
'apk',
'--config-only',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher());
final Directory androidApp = tempDir.childDirectory('android');
final io.File fileDump = tempDir.childDirectory('build').childDirectory('app').childFile('app-link-settings-debug.json');
result = await processManager.run(<String>[
'.${platform.pathSeparator}${getGradlewFileName(platform)}',
...getLocalEngineArguments(),
'-q', // quiet output.
'-PoutputPath=${fileDump.path}',
'outputDebugAppLinkSettings',
], workingDirectory: androidApp.path);
expect(result, const ProcessResultMatcher());
expect(fileDump.existsSync(), true);
final Map<String, dynamic> json = jsonDecode(fileDump.readAsStringSync()) as Map<String, dynamic>;
expect(json['applicationId'], 'com.example.testapp');
expect(json['deeplinkingFlagEnabled'], true);
final List<dynamic> deeplinks = json['deeplinks']! as List<dynamic>;
expect(deeplinks.length, 8);
testDeeplink(deeplinks[0], 'http', 'pure-http.com', '.*', hasAutoVerify:true, hasActionView: true, hasDefaultCategory:true, hasBrowsableCategory: true);
testDeeplink(deeplinks[1], 'custom', 'custom.com', '.*', hasAutoVerify:true, hasActionView: true, hasDefaultCategory:true, hasBrowsableCategory: true);
testDeeplink(deeplinks[2], 'custom', 'hybrid.com', '.*', hasAutoVerify:true, hasActionView: true, hasDefaultCategory:true, hasBrowsableCategory: true);
testDeeplink(deeplinks[3], 'http', 'hybrid.com', '.*', hasAutoVerify:true, hasActionView: true, hasDefaultCategory:true, hasBrowsableCategory: true);
testDeeplink(deeplinks[4], 'http', 'non-auto-verify.com', '.*', hasAutoVerify:false, hasActionView: true, hasDefaultCategory:true, hasBrowsableCategory: true);
testDeeplink(deeplinks[5], 'http', 'non-action.com', '.*', hasAutoVerify:true, hasActionView: false, hasDefaultCategory:true, hasBrowsableCategory: true);
testDeeplink(deeplinks[6], 'http', 'non-default-category.com', '.*', hasAutoVerify:true, hasActionView: true, hasDefaultCategory:false, hasBrowsableCategory: true);
testDeeplink(deeplinks[7], 'http', 'non-browsable-category.com', '.*', hasAutoVerify:true, hasActionView: true, hasDefaultCategory:true, hasBrowsableCategory: false);
});
testWithoutContext(
'gradle task outputs<mode>AppLinkSettings works when a project does not have app link and the flutter_deeplinking_enabled flag', () async {
// Create a new flutter project.
final String flutterBin =
fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
ProcessResult result = await processManager.run(<String>[
flutterBin,
'create',
tempDir.path,
'--project-name=testapp',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher());
// Ensure that gradle files exists from templates.
result = await processManager.run(<String>[
flutterBin,
'build',
'apk',
'--config-only',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher());
final Directory androidApp = tempDir.childDirectory('android');
final io.File fileDump = tempDir.childDirectory('build').childDirectory('app').childFile('app-link-settings-debug.json');
result = await processManager.run(<String>[
'.${platform.pathSeparator}${getGradlewFileName(platform)}',
...getLocalEngineArguments(),
'-q', // quiet output.
'-PoutputPath=${fileDump.path}',
'outputDebugAppLinkSettings',
], workingDirectory: androidApp.path);
expect(result, const ProcessResultMatcher());
expect(fileDump.existsSync(), true);
final Map<String, dynamic> json = jsonDecode(fileDump.readAsStringSync()) as Map<String, dynamic>;
expect(json['applicationId'], 'com.example.testapp');
expect(json['deeplinkingFlagEnabled'], false);
final List<dynamic> deeplinks = json['deeplinks']! as List<dynamic>;
expect(deeplinks.length, 0);
});
}
| flutter/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart",
"repo_id": "flutter",
"token_count": 4787
} | 838 |
// 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_testing/file_testing.dart';
import '../src/common.dart';
import 'test_data/test_project.dart';
import 'test_driver.dart';
import 'test_utils.dart';
void main() {
late Directory tempDir;
setUp(() async {
tempDir = createResolvedTempDirectorySync('flutter_coverage_collection_test.');
});
tearDown(() async {
tryToDelete(tempDir);
});
testWithoutContext('Can collect coverage in machine mode', () async {
final TestProject project = TestProject();
await project.setUpIn(tempDir);
final FlutterTestTestDriver flutter = FlutterTestTestDriver(tempDir);
await flutter.test(coverage: true);
await flutter.done;
final File lcovFile = tempDir.childDirectory('coverage').childFile('lcov.info');
expect(lcovFile, exists);
expect(lcovFile.readAsStringSync(), contains('main.dart')); // either 'SF:lib/main.dart or SF:lib\\main.dart
});
}
| flutter/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart",
"repo_id": "flutter",
"token_count": 365
} | 839 |
// 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_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import '../src/common.dart';
import 'test_utils.dart';
// Test that verbosity it propagated to Gradle tasks correctly.
void main() {
late Directory tempDir;
late String flutterBin;
late Directory exampleAppDir;
setUp(() async {
tempDir = createResolvedTempDirectorySync('flutter_build_test.');
flutterBin = fileSystem.path.join(
getFlutterRoot(),
'bin',
'flutter',
);
exampleAppDir = tempDir.childDirectory('aaa').childDirectory('example');
processManager.runSync(<String>[
flutterBin,
...getLocalEngineArguments(),
'create',
'--template=plugin',
'--platforms=android',
'aaa',
], workingDirectory: tempDir.path);
});
tearDown(() async {
tryToDelete(tempDir);
});
test(
'flutter build apk -v output should contain gen_snapshot command',
() async {
final ProcessResult result = processManager.runSync(<String>[
flutterBin,
...getLocalEngineArguments(),
'build',
'apk',
'--target-platform=android-arm',
'-v',
], workingDirectory: exampleAppDir.path);
expect(
result.stdout, contains(RegExp(r'executing:\s+.+gen_snapshot\s+')));
},
);
}
| flutter/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart",
"repo_id": "flutter",
"token_count": 574
} | 840 |
// 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_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/convert.dart';
import '../src/common.dart';
import 'test_data/basic_project.dart';
import 'test_utils.dart';
Future<int> getFreePort() async {
int port = 0;
final ServerSocket serverSocket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
port = serverSocket.port;
await serverSocket.close();
return port;
}
Future<void> waitForVmServiceMessage(Process process, int port) async {
final Completer<void> completer = Completer<void>();
process.stdout
.transform(utf8.decoder)
.listen((String line) {
printOnFailure(line);
if (line.contains('A Dart VM Service on Flutter test device is available at')) {
if (line.contains('http://127.0.0.1:$port')) {
completer.complete();
} else {
completer.completeError(Exception('Did not forward to provided port $port, instead found $line'));
}
}
});
process.stderr
.transform(utf8.decoder)
.listen(printOnFailure);
return completer.future;
}
void main() {
late Directory tempDir;
final BasicProject project = BasicProject();
setUp(() async {
tempDir = createResolvedTempDirectorySync('run_test.');
await project.setUpIn(tempDir);
});
tearDown(() async {
tryToDelete(tempDir);
});
testWithoutContext('flutter run --vm-service-port', () async {
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
final int port = await getFreePort();
// If only --vm-service-port is provided, --vm-service-port will be used by DDS
// and the VM service will bind to a random port.
final Process process = await processManager.start(<String>[
flutterBin,
'run',
'--show-test-device',
'--vm-service-port=$port',
'-d',
'flutter-tester',
], workingDirectory: tempDir.path);
await waitForVmServiceMessage(process, port);
process.kill();
await process.exitCode;
});
testWithoutContext('flutter run --dds-port --vm-service-port', () async {
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
final int vmServicePort = await getFreePort();
int ddsPort = await getFreePort();
while (ddsPort == vmServicePort) {
ddsPort = await getFreePort();
}
// If both --dds-port and --vm-service-port are provided, --dds-port will be used by
// DDS and --vm-service-port will be used by the VM service.
final Process process = await processManager.start(<String>[
flutterBin,
'run',
'--show-test-device',
'--vm-service-port=$vmServicePort',
'--dds-port=$ddsPort',
'-d',
'flutter-tester',
], workingDirectory: tempDir.path);
await waitForVmServiceMessage(process, ddsPort);
process.kill();
await process.exitCode;
});
testWithoutContext('flutter run --dds-port', () async {
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
final int ddsPort = await getFreePort();
// If only --dds-port is provided, --dds-port will be used by DDS and the VM service
// will bind to a random port.
final Process process = await processManager.start(<String>[
flutterBin,
'run',
'--show-test-device',
'--dds-port=$ddsPort',
'-d',
'flutter-tester',
], workingDirectory: tempDir.path);
await waitForVmServiceMessage(process, ddsPort);
process.kill();
await process.exitCode;
});
}
| flutter/packages/flutter_tools/test/integration.shard/observatory_port_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/integration.shard/observatory_port_test.dart",
"repo_id": "flutter",
"token_count": 1384
} | 841 |
// 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:flutter_tools/src/base/file_system.dart';
import '../test_utils.dart';
import 'project.dart';
import 'tests_project.dart';
class IntegrationTestsProject extends Project implements TestsProject {
@override
final String pubspec = '''
name: test
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
flutter:
sdk: flutter
dev_dependencies:
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
''';
@override
String get main => '// Unused';
@override
final String testContent = r'''
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
group('Flutter tests', () {
testWidgets('can pass', (WidgetTester tester) async {
expect(true, isTrue); // BREAKPOINT
});
testWidgets('can fail', (WidgetTester tester) async {
expect(true, isFalse);
});
});
}
''';
@override
Future<void> setUpIn(Directory dir) {
this.dir = dir;
writeFile(testFilePath, testContent);
return super.setUpIn(dir);
}
@override
String get testFilePath => fileSystem.path.join(dir.path, 'integration_test', 'app_test.dart');
@override
Uri get breakpointUri => Uri.file(testFilePath);
@override
Uri get breakpointAppUri => throw UnimplementedError();
@override
int get breakpointLine => lineContaining(testContent, '// BREAKPOINT');
}
| flutter/packages/flutter_tools/test/integration.shard/test_data/integration_tests_project.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/integration.shard/test_data/integration_tests_project.dart",
"repo_id": "flutter",
"token_count": 601
} | 842 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import '../src/common.dart';
import 'test_utils.dart' show fileSystem;
const ProcessManager processManager = LocalProcessManager();
final String flutterRoot = getFlutterRoot();
final String flutterBin = fileSystem.path.join(flutterRoot, 'bin', 'flutter');
void debugPrint(String message) {
// This is called to intentionally print debugging output when a test is
// either taking too long or has failed.
// ignore: avoid_print
print(message);
}
typedef LineHandler = String? Function(String line);
abstract class Transition {
const Transition({this.handler, this.logging});
/// Callback that is invoked when the transition matches.
///
/// This should not throw, even if the test is failing. (For example, don't use "expect"
/// in these callbacks.) Throwing here would prevent the [runFlutter] function from running
/// to completion, which would leave zombie `flutter` processes around.
final LineHandler? handler;
/// Whether to enable or disable logging when this transition is matched.
///
/// The default value, null, leaves the logging state unaffected.
final bool? logging;
bool matches(String line);
@protected
bool lineMatchesPattern(String line, Pattern pattern) {
if (pattern is String) {
return line == pattern;
}
return line.contains(pattern);
}
@protected
String describe(Pattern pattern) {
if (pattern is String) {
return '"$pattern"';
}
if (pattern is RegExp) {
return '/${pattern.pattern}/';
}
return '$pattern';
}
}
class Barrier extends Transition {
const Barrier(this.pattern, {super.handler, super.logging});
final Pattern pattern;
@override
bool matches(String line) => lineMatchesPattern(line, pattern);
@override
String toString() => describe(pattern);
}
class Multiple extends Transition {
Multiple(
List<Pattern> patterns, {
super.handler,
super.logging,
}) : _originalPatterns = patterns,
patterns = patterns.toList();
final List<Pattern> _originalPatterns;
final List<Pattern> patterns;
@override
bool matches(String line) {
for (int index = 0; index < patterns.length; index += 1) {
if (lineMatchesPattern(line, patterns[index])) {
patterns.removeAt(index);
break;
}
}
return patterns.isEmpty;
}
@override
String toString() {
if (patterns.isEmpty) {
return '${_originalPatterns.map(describe).join(', ')} (all matched)';
}
return '${_originalPatterns.map(describe).join(', ')} (matched ${_originalPatterns.length - patterns.length} so far)';
}
}
class LogLine {
const LogLine(this.channel, this.stamp, this.message);
final String channel;
final String stamp;
final String message;
bool get couldBeCrash =>
message.contains('Oops; flutter has exited unexpectedly:');
@override
String toString() => '$stamp $channel: $message';
void printClearly() {
debugPrint('$stamp $channel: ${clarify(message)}');
}
static String clarify(String line) {
return line.runes.map<String>((int rune) {
if (rune >= 0x20 && rune <= 0x7F) {
return String.fromCharCode(rune);
}
switch (rune) {
case 0x00:
return '<NUL>';
case 0x07:
return '<BEL>';
case 0x08:
return '<TAB>';
case 0x09:
return '<BS>';
case 0x0A:
return '<LF>';
case 0x0D:
return '<CR>';
}
return '<${rune.toRadixString(16).padLeft(rune <= 0xFF ? 2 : rune <= 0xFFFF ? 4 : 5, '0')}>';
}).join();
}
}
class ProcessTestResult {
const ProcessTestResult(this.exitCode, this.logs);
final int exitCode;
final List<LogLine> logs;
List<String> get stdout {
return logs
.where((LogLine log) => log.channel == 'stdout')
.map<String>((LogLine log) => log.message)
.toList();
}
List<String> get stderr {
return logs
.where((LogLine log) => log.channel == 'stderr')
.map<String>((LogLine log) => log.message)
.toList();
}
@override
String toString() => 'exit code $exitCode\nlogs:\n ${logs.join('\n ')}\n';
}
Future<ProcessTestResult> runFlutter(
List<String> arguments,
String workingDirectory,
List<Transition> transitions, {
bool debug = false,
bool logging = true,
Duration expectedMaxDuration = const Duration(
minutes: 10,
), // must be less than test timeout of 15 minutes! See ../../dart_test.yaml.
}) async {
const LocalPlatform platform = LocalPlatform();
final Stopwatch clock = Stopwatch()..start();
final Process process = await processManager.start(
<String>[
// In a container with no X display, use the virtual framebuffer.
if (platform.isLinux && (platform.environment['DISPLAY'] ?? '').isEmpty) '/usr/bin/xvfb-run',
flutterBin,
...arguments,
],
workingDirectory: workingDirectory,
);
final List<LogLine> logs = <LogLine>[];
int nextTransition = 0;
void describeStatus() {
if (transitions.isNotEmpty) {
debugPrint('Expected state transitions:');
for (int index = 0; index < transitions.length; index += 1) {
debugPrint('${index.toString().padLeft(5)} '
'${index < nextTransition ? 'ALREADY MATCHED ' : index == nextTransition ? 'NOW WAITING FOR>' : ' '} ${transitions[index]}');
}
}
if (logs.isEmpty) {
debugPrint(
'So far nothing has been logged${debug ? "" : "; use debug:true to print all output"}.');
} else {
debugPrint(
'Log${debug ? "" : " (only contains logged lines; use debug:true to print all output)"}:');
for (final LogLine log in logs) {
log.printClearly();
}
}
}
bool streamingLogs = false;
Timer? timeout;
void processTimeout() {
if (!streamingLogs) {
streamingLogs = true;
if (!debug) {
debugPrint(
'Test is taking a long time (${clock.elapsed.inSeconds} seconds so far).');
}
describeStatus();
debugPrint('(streaming all logs from this point on...)');
} else {
debugPrint('(taking a long time...)');
}
}
String stamp() =>
'[${(clock.elapsed.inMilliseconds / 1000.0).toStringAsFixed(1).padLeft(5)}s]';
void processStdout(String line) {
final LogLine log = LogLine('stdout', stamp(), line);
if (logging) {
logs.add(log);
}
if (streamingLogs) {
log.printClearly();
}
if (nextTransition < transitions.length &&
transitions[nextTransition].matches(line)) {
if (streamingLogs) {
debugPrint('(matched ${transitions[nextTransition]})');
}
if (transitions[nextTransition].logging != null) {
if (!logging && transitions[nextTransition].logging!) {
logs.add(log);
}
logging = transitions[nextTransition].logging!;
if (streamingLogs) {
if (logging) {
debugPrint('(enabled logging)');
} else {
debugPrint('(disabled logging)');
}
}
}
if (transitions[nextTransition].handler != null) {
final String? command = transitions[nextTransition].handler!(line);
if (command != null) {
final LogLine inLog = LogLine('stdin', stamp(), command);
logs.add(inLog);
if (streamingLogs) {
inLog.printClearly();
}
process.stdin.write(command);
}
}
nextTransition += 1;
timeout?.cancel();
timeout = Timer(expectedMaxDuration ~/ 5,
processTimeout); // This is not a failure timeout, just when to start logging verbosely to help debugging.
}
}
void processStderr(String line) {
final LogLine log = LogLine('stdout', stamp(), line);
logs.add(log);
if (streamingLogs) {
log.printClearly();
}
}
if (debug) {
processTimeout();
} else {
timeout = Timer(expectedMaxDuration ~/ 2,
processTimeout); // This is not a failure timeout, just when to start logging verbosely to help debugging.
}
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(processStdout);
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(processStderr);
unawaited(process.exitCode.timeout(expectedMaxDuration, onTimeout: () {
// This is a failure timeout, must not be short.
debugPrint(
'${stamp()} (process is not quitting, trying to send a "q" just in case that helps)');
debugPrint('(a functional test should never reach this point)');
final LogLine inLog = LogLine('stdin', stamp(), 'q');
logs.add(inLog);
if (streamingLogs) {
inLog.printClearly();
}
process.stdin.write('q');
return -1; // discarded
}).then(
(int i) => i,
onError: (Object error) {
// ignore errors here, they will be reported on the next line
return -1; // discarded
},
));
final int exitCode = await process.exitCode;
if (streamingLogs) {
debugPrint('${stamp()} (process terminated with exit code $exitCode)');
}
timeout?.cancel();
if (nextTransition < transitions.length) {
debugPrint(
'The subprocess terminated before all the expected transitions had been matched.');
if (logs.any((LogLine line) => line.couldBeCrash)) {
debugPrint(
'The subprocess may in fact have crashed. Check the stderr logs below.');
}
debugPrint(
'The transition that we were hoping to see next but that we never saw was:');
debugPrint(
'${nextTransition.toString().padLeft(5)} NOW WAITING FOR> ${transitions[nextTransition]}');
if (!streamingLogs) {
describeStatus();
debugPrint('(process terminated with exit code $exitCode)');
}
throw TestFailure('Missed some expected transitions.');
}
if (streamingLogs) {
debugPrint('${stamp()} (completed execution successfully!)');
}
return ProcessTestResult(exitCode, logs);
}
const int progressMessageWidth = 64;
| flutter/packages/flutter_tools/test/integration.shard/transition_test_utils.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/integration.shard/transition_test_utils.dart",
"repo_id": "flutter",
"token_count": 3919
} | 843 |
// 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 show Directory, File, IOOverrides, Link;
import 'package:flutter_tools/src/base/file_system.dart';
/// An [IOOverrides] that can delegate to [FileSystem] implementation if provided.
///
/// Does not override any of the socket facilities.
///
/// Do not provide a [LocalFileSystem] as a delegate. Since internally this calls
/// out to `dart:io` classes, it will result in a stack overflow error as the
/// IOOverrides and LocalFileSystem call each other endlessly.
///
/// The only safe delegate types are those that do not call out to `dart:io`,
/// like the [MemoryFileSystem].
class FlutterIOOverrides extends io.IOOverrides {
FlutterIOOverrides({ FileSystem? fileSystem })
: _fileSystemDelegate = fileSystem;
final FileSystem? _fileSystemDelegate;
@override
io.Directory createDirectory(String path) {
return _fileSystemDelegate?.directory(path) ?? super.createDirectory(path);
}
@override
io.File createFile(String path) {
return _fileSystemDelegate?.file(path) ?? super.createFile(path);
}
@override
io.Link createLink(String path) {
return _fileSystemDelegate?.link(path) ?? super.createLink(path);
}
@override
Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) {
return _fileSystemDelegate?.file(path).watch(events: events, recursive: recursive)
?? super.fsWatch(path, events, recursive);
}
@override
bool fsWatchIsSupported() {
return _fileSystemDelegate?.isWatchSupported ?? super.fsWatchIsSupported();
}
@override
Future<FileSystemEntityType> fseGetType(String path, bool followLinks) {
return _fileSystemDelegate?.type(path, followLinks: followLinks)
?? super.fseGetType(path, followLinks);
}
@override
FileSystemEntityType fseGetTypeSync(String path, bool followLinks) {
return _fileSystemDelegate?.typeSync(path, followLinks: followLinks)
?? super.fseGetTypeSync(path, followLinks);
}
@override
Future<bool> fseIdentical(String path1, String path2) {
return _fileSystemDelegate?.identical(path1, path2) ?? super.fseIdentical(path1, path2);
}
@override
bool fseIdenticalSync(String path1, String path2) {
return _fileSystemDelegate?.identicalSync(path1, path2) ?? super.fseIdenticalSync(path1, path2);
}
@override
io.Directory getCurrentDirectory() {
return _fileSystemDelegate?.currentDirectory ?? super.getCurrentDirectory();
}
@override
io.Directory getSystemTempDirectory() {
return _fileSystemDelegate?.systemTempDirectory ?? super.getSystemTempDirectory();
}
@override
void setCurrentDirectory(String path) {
if (_fileSystemDelegate == null) {
return super.setCurrentDirectory(path);
}
_fileSystemDelegate.currentDirectory = path;
}
@override
Future<FileStat> stat(String path) {
return _fileSystemDelegate?.stat(path) ?? super.stat(path);
}
@override
FileStat statSync(String path) {
return _fileSystemDelegate?.statSync(path) ?? super.statSync(path);
}
}
| flutter/packages/flutter_tools/test/src/io.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/src/io.dart",
"repo_id": "flutter",
"token_count": 1020
} | 844 |
// 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_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/drive/web_driver_service.dart';
import 'package:package_config/package_config_types.dart';
import '../src/common.dart';
import '../src/fake_process_manager.dart';
void main() {
testWithoutContext('WebDriverService catches SocketExceptions cleanly and includes link to documentation', () async {
final BufferLogger logger = BufferLogger.test();
final WebDriverService service = WebDriverService(
logger: logger,
processUtils: ProcessUtils(
logger: logger,
processManager: FakeProcessManager.empty(),
),
dartSdkPath: 'dart',
);
const String link = 'https://flutter.dev/docs/testing/integration-tests#running-in-a-browser';
try {
await service.startTest(
'foo.test',
<String>[],
<String, String>{},
PackageConfig(<Package>[Package('test', Uri.base)]),
driverPort: 1,
headless: true,
browserName: 'chrome',
);
fail('WebDriverService did not throw as expected.');
} on ToolExit catch (error) {
expect(error.message, isNot(contains('SocketException')));
expect(error.message, contains(link));
}
});
}
| flutter/packages/flutter_tools/test/web.shard/web_driver_service_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/web.shard/web_driver_service_test.dart",
"repo_id": "flutter",
"token_count": 549
} | 845 |
// 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.
@TestOn('!chrome')
library;
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'common.dart';
void main() {
group('Non-web UrlStrategy', () {
late TestPlatformLocation location;
setUp(() {
location = TestPlatformLocation();
});
test('Can create and set a $HashUrlStrategy', () {
expect(() {
final HashUrlStrategy strategy = HashUrlStrategy(location);
setUrlStrategy(strategy);
}, returnsNormally);
});
test('Can create and set a $PathUrlStrategy', () {
expect(() {
final PathUrlStrategy strategy = PathUrlStrategy(location);
setUrlStrategy(strategy);
}, returnsNormally);
});
test('Can usePathUrlStrategy', () {
expect(() {
usePathUrlStrategy();
}, returnsNormally);
});
});
}
| flutter/packages/flutter_web_plugins/test/navigation/non_web_url_strategy_test.dart/0 | {
"file_path": "flutter/packages/flutter_web_plugins/test/navigation/non_web_url_strategy_test.dart",
"repo_id": "flutter",
"token_count": 380
} | 846 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io' show ProcessResult, systemEncoding;
import 'package:fuchsia_remote_debug_protocol/src/runners/ssh_command_runner.dart';
import 'package:process/process.dart';
import 'package:test/fake.dart';
import 'package:test/test.dart';
void main() {
group('SshCommandRunner.constructors', () {
test('throws exception with invalid address', () async {
SshCommandRunner newCommandRunner() {
return SshCommandRunner(address: 'sillyaddress.what');
}
expect(newCommandRunner, throwsArgumentError);
});
test('throws exception from injection constructor with invalid addr', () async {
SshCommandRunner newCommandRunner() {
return SshCommandRunner.withProcessManager(
const LocalProcessManager(),
address: '192.168.1.1.1');
}
expect(newCommandRunner, throwsArgumentError);
});
});
group('SshCommandRunner.run', () {
late FakeProcessManager fakeProcessManager;
SshCommandRunner runner;
setUp(() {
fakeProcessManager = FakeProcessManager();
});
test('verify interface is appended to ipv6 address', () async {
const String ipV6Addr = 'fe80::8eae:4cff:fef4:9247';
const String interface = 'eno1';
runner = SshCommandRunner.withProcessManager(
fakeProcessManager,
address: ipV6Addr,
interface: interface,
sshConfigPath: '/whatever',
);
fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null);
await runner.run('ls /whatever');
expect(fakeProcessManager.runCommands.single, contains('$ipV6Addr%$interface'));
});
test('verify no percentage symbol is added when no ipv6 interface', () async {
const String ipV6Addr = 'fe80::8eae:4cff:fef4:9247';
runner = SshCommandRunner.withProcessManager(
fakeProcessManager,
address: ipV6Addr,
);
fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null);
await runner.run('ls /whatever');
expect(fakeProcessManager.runCommands.single, contains(ipV6Addr));
});
test('verify commands are split into multiple lines', () async {
const String addr = '192.168.1.1';
runner = SshCommandRunner.withProcessManager(fakeProcessManager,
address: addr);
fakeProcessManager.fakeResult = ProcessResult(
23,
0,
'''
this
has
four
lines''',
null);
final List<String> result = await runner.run('oihaw');
expect(result, hasLength(4));
});
test('verify exception on nonzero process result exit code', () async {
const String addr = '192.168.1.1';
runner = SshCommandRunner.withProcessManager(fakeProcessManager,
address: addr);
fakeProcessManager.fakeResult = ProcessResult(23, 1, 'whatever', null);
Future<void> failingFunction() async {
await runner.run('oihaw');
}
expect(failingFunction, throwsA(isA<SshCommandError>()));
});
test('verify correct args with config', () async {
const String addr = 'fe80::8eae:4cff:fef4:9247';
const String config = '/this/that/this/and/uh';
runner = SshCommandRunner.withProcessManager(
fakeProcessManager,
address: addr,
sshConfigPath: config,
);
fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null);
await runner.run('ls /whatever');
final List<String?> passedCommand = fakeProcessManager.runCommands.single as List<String?>;
expect(passedCommand, contains('-F'));
final int indexOfFlag = passedCommand.indexOf('-F');
final String? passedConfig = passedCommand[indexOfFlag + 1];
expect(passedConfig, config);
});
test('verify config is excluded correctly', () async {
const String addr = 'fe80::8eae:4cff:fef4:9247';
runner = SshCommandRunner.withProcessManager(
fakeProcessManager,
address: addr,
);
fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null);
await runner.run('ls /whatever');
final List<String?> passedCommand = fakeProcessManager.runCommands.single as List<String?>;
final int indexOfFlag = passedCommand.indexOf('-F');
expect(indexOfFlag, equals(-1));
});
});
}
class FakeProcessManager extends Fake implements ProcessManager {
ProcessResult? fakeResult;
List<List<dynamic>> runCommands = <List<dynamic>>[];
@override
Future<ProcessResult> run(List<dynamic> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
Encoding? stdoutEncoding = systemEncoding,
Encoding? stderrEncoding = systemEncoding,
}) async {
runCommands.add(command);
return fakeResult!;
}
}
| flutter/packages/fuchsia_remote_debug_protocol/test/src/runners/ssh_command_runner_test.dart/0 | {
"file_path": "flutter/packages/fuchsia_remote_debug_protocol/test/src/runners/ssh_command_runner_test.dart",
"repo_id": "flutter",
"token_count": 1898
} | 847 |
## 0.0.2
* Renames package to integration_test_macos.
## 0.0.1+1
* Remove Android folder from `e2e_macos`.
## 0.0.1
* Initial release
| flutter/packages/integration_test/integration_test_macos/CHANGELOG.md/0 | {
"file_path": "flutter/packages/integration_test/integration_test_macos/CHANGELOG.md",
"repo_id": "flutter",
"token_count": 59
} | 848 |
## Directory contents
The `.yaml` files in these directories are used to
define the [`dart fix` framework](https://dart.dev/tools/dart-fix) refactorings
used by `integration_test`.
The number of fix rules defined in a file should not exceed 50 for better
maintainability. Searching for `title:` in a given `.yaml` file will account
for the number of fixes. Splitting out fix rules should be done by class.
When adding a new `.yaml` file, make a copy of `template.yaml`. Each file should
be for a single class and named `fix_<class>.yaml`. To make sure each file is
grouped with related classes, a `fix_<filename>` folder will contain all of the
fix files for the individual classes.
See the flutter/packages/integration_test/test_fixes directory for the tests
that validate these fix rules.
To run these tests locally, execute this command in the
flutter/packages/integration_test/test_fixes directory.
```sh
dart fix --compare-to-golden
```
For more documentation about Data Driven Fixes, see
https://dart.dev/go/data-driven-fixes#test-folder.
To learn more about how fixes are authored in package:integration_test, see
https://github.com/flutter/flutter/wiki/Data-driven-Fixes
## When making structural changes to this directory
The tests in this directory are also invoked from external
repositories. Specifically, the CI system for the dart-lang/sdk repo
runs these tests in order to ensure that changes to the dart fix file
format do not break Flutter.
See [tools/bots/flutter/analyze_flutter_flutter.sh](https://github.com/dart-lang/sdk/blob/main/tools/bots/flutter/analyze_flutter_flutter.sh)
for where the flutter fix tests are invoked for the dart repo.
See [dev/bots/test.dart](https://github.com/flutter/flutter/blob/master/dev/bots/test.dart)
for where the flutter fix tests are invoked for the flutter/flutter repo.
When possible, please coordinate changes to this directory that might affect the
`analyze_flutter_flutter.sh` script.
| flutter/packages/integration_test/lib/fix_data/README.md/0 | {
"file_path": "flutter/packages/integration_test/lib/fix_data/README.md",
"repo_id": "flutter",
"token_count": 567
} | 849 |
Files in this directory are not invoked directly by the test command.
They are used as inputs for the other test files outside of this directory, so
that failures can be tested. | flutter/packages/integration_test/test/data/README.md/0 | {
"file_path": "flutter/packages/integration_test/test/data/README.md",
"repo_id": "flutter",
"token_count": 38
} | 850 |
name: flutter_clock_helper
description: Helper classes for Flutter Clock contest.
version: 1.0.0+1
environment:
sdk: ">=2.2.2 <3.0.0"
dependencies:
flutter:
sdk: flutter
intl: "^0.16.0"
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| flutter_clock/flutter_clock_helper/pubspec.yaml/0 | {
"file_path": "flutter_clock/flutter_clock_helper/pubspec.yaml",
"repo_id": "flutter_clock",
"token_count": 140
} | 851 |
source "https://rubygems.org"
gem "fastlane"
| gallery/android/Gemfile/0 | {
"file_path": "gallery/android/Gemfile",
"repo_id": "gallery",
"token_count": 18
} | 852 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="craneName">crane</string>
</resources>
| gallery/android/app/src/main/res/values/strings.xml/0 | {
"file_path": "gallery/android/app/src/main/res/values/strings.xml",
"repo_id": "gallery",
"token_count": 39
} | 853 |
{
"file_generated_by": "FlutterFire CLI",
"purpose": "FirebaseAppID & ProjectID for this Firebase app in this directory",
"GOOGLE_APP_ID": "1:934901241041:ios:8d4c8bde3db3391fe621f0",
"FIREBASE_PROJECT_ID": "gallery-flutter-dev",
"GCM_SENDER_ID": "934901241041"
} | gallery/ios/firebase_app_id_file.json/0 | {
"file_path": "gallery/ios/firebase_app_id_file.json",
"repo_id": "gallery",
"token_count": 122
} | 854 |
// Copyright 2019 The Flutter team. 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 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:intl/intl.dart';
// BEGIN cupertinoPickersDemo
class CupertinoPickerDemo extends StatefulWidget {
const CupertinoPickerDemo({super.key});
@override
State<CupertinoPickerDemo> createState() => _CupertinoPickerDemoState();
}
class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
Duration timer = const Duration();
// Value that is shown in the date picker in date mode.
DateTime date = DateTime.now();
// Value that is shown in the date picker in time mode.
DateTime time = DateTime.now();
// Value that is shown in the date picker in dateAndTime mode.
DateTime dateTime = DateTime.now();
int _selectedWeekday = 0;
static List<String> getDaysOfWeek([String? locale]) {
final now = DateTime.now();
final firstDayOfWeek = now.subtract(Duration(days: now.weekday - 1));
return List.generate(7, (index) => index)
.map((value) => DateFormat(DateFormat.WEEKDAY, locale)
.format(firstDayOfWeek.add(Duration(days: value))))
.toList();
}
void _showDemoPicker({
required BuildContext context,
required Widget child,
}) {
final themeData = CupertinoTheme.of(context);
final dialogBody = CupertinoTheme(
data: themeData,
child: child,
);
showCupertinoModalPopup<void>(
context: context,
builder: (context) => dialogBody,
);
}
Widget _buildDatePicker(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
_showDemoPicker(
context: context,
child: _BottomPicker(
child: CupertinoDatePicker(
backgroundColor:
CupertinoColors.systemBackground.resolveFrom(context),
mode: CupertinoDatePickerMode.date,
initialDateTime: date,
onDateTimeChanged: (newDateTime) {
setState(() => date = newDateTime);
},
),
),
);
},
child: _Menu(
children: [
Text(GalleryLocalizations.of(context)!.demoCupertinoPickerDate),
Text(
DateFormat.yMMMMd().format(date),
style: const TextStyle(color: CupertinoColors.inactiveGray),
),
],
),
),
);
}
Widget _buildTimePicker(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
_showDemoPicker(
context: context,
child: _BottomPicker(
child: CupertinoDatePicker(
backgroundColor:
CupertinoColors.systemBackground.resolveFrom(context),
mode: CupertinoDatePickerMode.time,
initialDateTime: time,
onDateTimeChanged: (newDateTime) {
setState(() => time = newDateTime);
},
),
),
);
},
child: _Menu(
children: [
Text(GalleryLocalizations.of(context)!.demoCupertinoPickerTime),
Text(
DateFormat.jm().format(time),
style: const TextStyle(color: CupertinoColors.inactiveGray),
),
],
),
),
);
}
Widget _buildDateAndTimePicker(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
_showDemoPicker(
context: context,
child: _BottomPicker(
child: CupertinoDatePicker(
backgroundColor:
CupertinoColors.systemBackground.resolveFrom(context),
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: dateTime,
onDateTimeChanged: (newDateTime) {
setState(() => dateTime = newDateTime);
},
),
),
);
},
child: _Menu(
children: [
Text(GalleryLocalizations.of(context)!.demoCupertinoPickerDateTime),
Flexible(
child: Text(
DateFormat.yMMMd().add_jm().format(dateTime),
style: const TextStyle(color: CupertinoColors.inactiveGray),
),
),
],
),
),
);
}
Widget _buildCountdownTimerPicker(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
_showDemoPicker(
context: context,
child: _BottomPicker(
child: CupertinoTimerPicker(
backgroundColor:
CupertinoColors.systemBackground.resolveFrom(context),
initialTimerDuration: timer,
onTimerDurationChanged: (newTimer) {
setState(() => timer = newTimer);
},
),
),
);
},
child: _Menu(
children: [
Text(GalleryLocalizations.of(context)!.demoCupertinoPickerTimer),
Text(
'${timer.inHours}:'
'${(timer.inMinutes % 60).toString().padLeft(2, '0')}:'
'${(timer.inSeconds % 60).toString().padLeft(2, '0')}',
style: const TextStyle(color: CupertinoColors.inactiveGray),
),
],
),
),
);
}
Widget _buildPicker(BuildContext context) {
final locale = GalleryLocalizations.of(context)?.localeName;
final daysOfWeek = getDaysOfWeek(locale);
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
_showDemoPicker(
context: context,
child: _BottomPicker(
child: CupertinoPicker(
backgroundColor:
CupertinoColors.systemBackground.resolveFrom(context),
itemExtent: 32.0,
magnification: 1.22,
squeeze: 1.2,
useMagnifier: true,
// This is called when selected item is changed.
onSelectedItemChanged: (selectedItem) {
setState(() {
_selectedWeekday = selectedItem;
});
},
children: List<Widget>.generate(daysOfWeek.length, (index) {
return Center(
child: Text(
daysOfWeek[index],
),
);
}),
),
),
);
},
child: _Menu(
children: [
Text(GalleryLocalizations.of(context)!.demoCupertinoPicker),
Text(
daysOfWeek[_selectedWeekday],
style: const TextStyle(color: CupertinoColors.inactiveGray),
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
middle:
Text(GalleryLocalizations.of(context)!.demoCupertinoPickerTitle),
),
child: DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: ListView(
children: [
const SizedBox(height: 32),
_buildDatePicker(context),
_buildTimePicker(context),
_buildDateAndTimePicker(context),
_buildCountdownTimerPicker(context),
_buildPicker(context),
],
),
),
);
}
}
class _BottomPicker extends StatelessWidget {
const _BottomPicker({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return Container(
height: 216,
padding: const EdgeInsets.only(top: 6),
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
color: CupertinoColors.systemBackground.resolveFrom(context),
child: DefaultTextStyle(
style: TextStyle(
color: CupertinoColors.label.resolveFrom(context),
fontSize: 22,
),
child: GestureDetector(
// Blocks taps from propagating to the modal sheet and popping.
onTap: () {},
child: SafeArea(
top: false,
child: child,
),
),
),
);
}
}
class _Menu extends StatelessWidget {
const _Menu({required this.children});
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: CupertinoColors.inactiveGray, width: 0),
bottom: BorderSide(color: CupertinoColors.inactiveGray, width: 0),
),
),
height: 44,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: children,
),
),
);
}
}
// END
| gallery/lib/demos/cupertino/cupertino_picker_demo.dart/0 | {
"file_path": "gallery/lib/demos/cupertino/cupertino_picker_demo.dart",
"repo_id": "gallery",
"token_count": 4667
} | 855 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/demos/material/material_demo_types.dart';
class ChipDemo extends StatelessWidget {
const ChipDemo({
super.key,
required this.type,
});
final ChipDemoType type;
String _title(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
switch (type) {
case ChipDemoType.action:
return localizations.demoActionChipTitle;
case ChipDemoType.choice:
return localizations.demoChoiceChipTitle;
case ChipDemoType.filter:
return localizations.demoFilterChipTitle;
case ChipDemoType.input:
return localizations.demoInputChipTitle;
}
}
@override
Widget build(BuildContext context) {
Widget? buttons;
switch (type) {
case ChipDemoType.action:
buttons = _ActionChipDemo();
break;
case ChipDemoType.choice:
buttons = _ChoiceChipDemo();
break;
case ChipDemoType.filter:
buttons = _FilterChipDemo();
break;
case ChipDemoType.input:
buttons = _InputChipDemo();
break;
}
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(_title(context)),
),
body: buttons,
);
}
}
// BEGIN chipDemoAction
class _ActionChipDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: ActionChip(
onPressed: () {},
avatar: const Icon(
Icons.brightness_5,
color: Colors.black54,
),
label: Text(GalleryLocalizations.of(context)!.chipTurnOnLights),
),
);
}
}
// END
// BEGIN chipDemoChoice
class _ChoiceChipDemo extends StatefulWidget {
@override
_ChoiceChipDemoState createState() => _ChoiceChipDemoState();
}
class _ChoiceChipDemoState extends State<_ChoiceChipDemo>
with RestorationMixin {
final RestorableIntN _indexSelected = RestorableIntN(null);
@override
String get restorationId => 'choice_chip_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_indexSelected, 'choice_chip');
}
@override
void dispose() {
_indexSelected.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Wrap(
children: [
ChoiceChip(
label: Text(localizations.chipSmall),
selected: _indexSelected.value == 0,
onSelected: (value) {
setState(() {
_indexSelected.value = value ? 0 : -1;
});
},
),
const SizedBox(width: 8),
ChoiceChip(
label: Text(localizations.chipMedium),
selected: _indexSelected.value == 1,
onSelected: (value) {
setState(() {
_indexSelected.value = value ? 1 : -1;
});
},
),
const SizedBox(width: 8),
ChoiceChip(
label: Text(localizations.chipLarge),
selected: _indexSelected.value == 2,
onSelected: (value) {
setState(() {
_indexSelected.value = value ? 2 : -1;
});
},
),
],
),
const SizedBox(height: 12),
// Disabled chips
Wrap(
children: [
ChoiceChip(
label: Text(localizations.chipSmall),
selected: _indexSelected.value == 0,
onSelected: null,
),
const SizedBox(width: 8),
ChoiceChip(
label: Text(localizations.chipMedium),
selected: _indexSelected.value == 1,
onSelected: null,
),
const SizedBox(width: 8),
ChoiceChip(
label: Text(localizations.chipLarge),
selected: _indexSelected.value == 2,
onSelected: null,
),
],
),
],
),
);
}
}
// END
// BEGIN chipDemoFilter
class _FilterChipDemo extends StatefulWidget {
@override
_FilterChipDemoState createState() => _FilterChipDemoState();
}
class _FilterChipDemoState extends State<_FilterChipDemo>
with RestorationMixin {
final RestorableBool isSelectedElevator = RestorableBool(false);
final RestorableBool isSelectedWasher = RestorableBool(false);
final RestorableBool isSelectedFireplace = RestorableBool(false);
@override
String get restorationId => 'filter_chip_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(isSelectedElevator, 'selected_elevator');
registerForRestoration(isSelectedWasher, 'selected_washer');
registerForRestoration(isSelectedFireplace, 'selected_fireplace');
}
@override
void dispose() {
isSelectedElevator.dispose();
isSelectedWasher.dispose();
isSelectedFireplace.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Wrap(
spacing: 8.0,
children: [
FilterChip(
label: Text(localizations.chipElevator),
selected: isSelectedElevator.value,
onSelected: (value) {
setState(() {
isSelectedElevator.value = !isSelectedElevator.value;
});
},
),
FilterChip(
label: Text(localizations.chipWasher),
selected: isSelectedWasher.value,
onSelected: (value) {
setState(() {
isSelectedWasher.value = !isSelectedWasher.value;
});
},
),
FilterChip(
label: Text(localizations.chipFireplace),
selected: isSelectedFireplace.value,
onSelected: (value) {
setState(() {
isSelectedFireplace.value = !isSelectedFireplace.value;
});
},
),
],
),
const SizedBox(height: 12),
// Disabled chips
Wrap(
spacing: 8.0,
children: [
FilterChip(
label: Text(localizations.chipElevator),
selected: isSelectedElevator.value,
onSelected: null,
),
FilterChip(
label: Text(localizations.chipWasher),
selected: isSelectedWasher.value,
onSelected: null,
),
FilterChip(
label: Text(localizations.chipFireplace),
selected: isSelectedFireplace.value,
onSelected: null,
),
],
),
],
),
);
}
}
// END
// BEGIN chipDemoInput
class _InputChipDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InputChip(
onPressed: () {},
onDeleted: () {},
avatar: const Icon(
Icons.directions_bike,
size: 20,
color: Colors.black54,
),
deleteIconColor: Colors.black54,
label: Text(GalleryLocalizations.of(context)!.chipBiking),
),
const SizedBox(height: 12),
// Disabled chip
InputChip(
onPressed: null,
onDeleted: null,
avatar: const Icon(
Icons.directions_bike,
size: 20,
color: Colors.black54,
),
deleteIconColor: Colors.black54,
label: Text(GalleryLocalizations.of(context)!.chipBiking),
),
],
),
);
}
}
// END
| gallery/lib/demos/material/chip_demo.dart/0 | {
"file_path": "gallery/lib/demos/material/chip_demo.dart",
"repo_id": "gallery",
"token_count": 4329
} | 856 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/demos/material/material_demo_types.dart';
class TabsDemo extends StatelessWidget {
const TabsDemo({super.key, required this.type});
final TabsDemoType type;
@override
Widget build(BuildContext context) {
Widget tabs;
switch (type) {
case TabsDemoType.scrollable:
tabs = _TabsScrollableDemo();
break;
case TabsDemoType.nonScrollable:
tabs = _TabsNonScrollableDemo();
}
return tabs;
}
}
// BEGIN tabsScrollableDemo
class _TabsScrollableDemo extends StatefulWidget {
@override
__TabsScrollableDemoState createState() => __TabsScrollableDemoState();
}
class __TabsScrollableDemoState extends State<_TabsScrollableDemo>
with SingleTickerProviderStateMixin, RestorationMixin {
TabController? _tabController;
final RestorableInt tabIndex = RestorableInt(0);
@override
String get restorationId => 'tab_scrollable_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(tabIndex, 'tab_index');
_tabController!.index = tabIndex.value;
}
@override
void initState() {
_tabController = TabController(
initialIndex: 0,
length: 12,
vsync: this,
);
_tabController!.addListener(() {
// When the tab controller's value is updated, make sure to update the
// tab index value, which is state restorable.
setState(() {
tabIndex.value = _tabController!.index;
});
});
super.initState();
}
@override
void dispose() {
_tabController!.dispose();
tabIndex.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
final tabs = [
localizations.colorsRed,
localizations.colorsOrange,
localizations.colorsGreen,
localizations.colorsBlue,
localizations.colorsIndigo,
localizations.colorsPurple,
localizations.colorsRed,
localizations.colorsOrange,
localizations.colorsGreen,
localizations.colorsBlue,
localizations.colorsIndigo,
localizations.colorsPurple,
];
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(localizations.demoTabsScrollingTitle),
bottom: TabBar(
controller: _tabController,
isScrollable: true,
tabs: [
for (final tab in tabs) Tab(text: tab),
],
),
),
body: TabBarView(
controller: _tabController,
children: [
for (final tab in tabs)
Center(
child: Text(tab),
),
],
),
);
}
}
// END
// BEGIN tabsNonScrollableDemo
class _TabsNonScrollableDemo extends StatefulWidget {
@override
__TabsNonScrollableDemoState createState() => __TabsNonScrollableDemoState();
}
class __TabsNonScrollableDemoState extends State<_TabsNonScrollableDemo>
with SingleTickerProviderStateMixin, RestorationMixin {
late TabController _tabController;
final RestorableInt tabIndex = RestorableInt(0);
@override
String get restorationId => 'tab_non_scrollable_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(tabIndex, 'tab_index');
_tabController.index = tabIndex.value;
}
@override
void initState() {
super.initState();
_tabController = TabController(
initialIndex: 0,
length: 3,
vsync: this,
);
_tabController.addListener(() {
// When the tab controller's value is updated, make sure to update the
// tab index value, which is state restorable.
setState(() {
tabIndex.value = _tabController.index;
});
});
}
@override
void dispose() {
_tabController.dispose();
tabIndex.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final localizations = GalleryLocalizations.of(context)!;
final tabs = [
localizations.colorsRed,
localizations.colorsOrange,
localizations.colorsGreen,
];
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(
localizations.demoTabsNonScrollingTitle,
),
bottom: TabBar(
controller: _tabController,
isScrollable: false,
tabs: [
for (final tab in tabs) Tab(text: tab),
],
),
),
body: TabBarView(
controller: _tabController,
children: [
for (final tab in tabs)
Center(
child: Text(tab),
),
],
),
);
}
}
// END
| gallery/lib/demos/material/tabs_demo.dart/0 | {
"file_path": "gallery/lib/demos/material/tabs_demo.dart",
"repo_id": "gallery",
"token_count": 2009
} | 857 |
// Copyright 2019 The Flutter team. 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';
/// Animations class to compute animation values for overlay widgets.
///
/// Values are loosely based on Material Design specs, which are minimal.
class Animations {
final AnimationController openController;
final AnimationController tapController;
final AnimationController rippleController;
final AnimationController dismissController;
static const backgroundMaxOpacity = 0.96;
static const backgroundTapRadius = 20.0;
static const rippleMaxOpacity = 0.75;
static const tapTargetToContentDistance = 20.0;
static const tapTargetMaxRadius = 44.0;
static const tapTargetMinRadius = 20.0;
static const tapTargetRippleRadius = 64.0;
Animations(
this.openController,
this.tapController,
this.rippleController,
this.dismissController,
);
Animation<double> backgroundOpacity(FeatureDiscoveryStatus status) {
switch (status) {
case FeatureDiscoveryStatus.closed:
return const AlwaysStoppedAnimation<double>(0);
case FeatureDiscoveryStatus.open:
return Tween<double>(begin: 0, end: backgroundMaxOpacity)
.animate(CurvedAnimation(
parent: openController,
curve: const Interval(0, 0.5, curve: Curves.ease),
));
case FeatureDiscoveryStatus.tap:
return Tween<double>(begin: backgroundMaxOpacity, end: 0)
.animate(CurvedAnimation(
parent: tapController,
curve: Curves.ease,
));
case FeatureDiscoveryStatus.dismiss:
return Tween<double>(begin: backgroundMaxOpacity, end: 0)
.animate(CurvedAnimation(
parent: dismissController,
curve: const Interval(0.2, 1.0, curve: Curves.ease),
));
default:
return const AlwaysStoppedAnimation<double>(backgroundMaxOpacity);
}
}
Animation<double> backgroundRadius(
FeatureDiscoveryStatus status,
double backgroundRadiusMax,
) {
switch (status) {
case FeatureDiscoveryStatus.closed:
return const AlwaysStoppedAnimation<double>(0);
case FeatureDiscoveryStatus.open:
return Tween<double>(begin: 0, end: backgroundRadiusMax)
.animate(CurvedAnimation(
parent: openController,
curve: const Interval(0, 0.5, curve: Curves.ease),
));
case FeatureDiscoveryStatus.tap:
return Tween<double>(
begin: backgroundRadiusMax,
end: backgroundRadiusMax + backgroundTapRadius)
.animate(CurvedAnimation(
parent: tapController,
curve: Curves.ease,
));
case FeatureDiscoveryStatus.dismiss:
return Tween<double>(begin: backgroundRadiusMax, end: 0)
.animate(CurvedAnimation(
parent: dismissController,
curve: Curves.ease,
));
default:
return AlwaysStoppedAnimation<double>(backgroundRadiusMax);
}
}
Animation<Offset> backgroundCenter(
FeatureDiscoveryStatus status,
Offset start,
Offset end,
) {
switch (status) {
case FeatureDiscoveryStatus.closed:
return AlwaysStoppedAnimation<Offset>(start);
case FeatureDiscoveryStatus.open:
return Tween<Offset>(begin: start, end: end).animate(CurvedAnimation(
parent: openController,
curve: const Interval(0, 0.5, curve: Curves.ease),
));
case FeatureDiscoveryStatus.tap:
return Tween<Offset>(begin: end, end: start).animate(CurvedAnimation(
parent: tapController,
curve: Curves.ease,
));
case FeatureDiscoveryStatus.dismiss:
return Tween<Offset>(begin: end, end: start).animate(CurvedAnimation(
parent: dismissController,
curve: Curves.ease,
));
default:
return AlwaysStoppedAnimation<Offset>(end);
}
}
Animation<double> contentOpacity(FeatureDiscoveryStatus status) {
switch (status) {
case FeatureDiscoveryStatus.closed:
return const AlwaysStoppedAnimation<double>(0);
case FeatureDiscoveryStatus.open:
return Tween<double>(begin: 0, end: 1.0).animate(CurvedAnimation(
parent: openController,
curve: const Interval(0.4, 0.7, curve: Curves.ease),
));
case FeatureDiscoveryStatus.tap:
return Tween<double>(begin: 1.0, end: 0).animate(CurvedAnimation(
parent: tapController,
curve: const Interval(0, 0.4, curve: Curves.ease),
));
case FeatureDiscoveryStatus.dismiss:
return Tween<double>(begin: 1.0, end: 0).animate(CurvedAnimation(
parent: dismissController,
curve: const Interval(0, 0.4, curve: Curves.ease),
));
default:
return const AlwaysStoppedAnimation<double>(1.0);
}
}
Animation<double> rippleOpacity(FeatureDiscoveryStatus status) {
switch (status) {
case FeatureDiscoveryStatus.ripple:
return Tween<double>(begin: rippleMaxOpacity, end: 0)
.animate(CurvedAnimation(
parent: rippleController,
curve: const Interval(0.3, 0.8, curve: Curves.ease),
));
default:
return const AlwaysStoppedAnimation<double>(0);
}
}
Animation<double> rippleRadius(FeatureDiscoveryStatus status) {
switch (status) {
case FeatureDiscoveryStatus.ripple:
if (rippleController.value >= 0.3 && rippleController.value <= 0.8) {
return Tween<double>(begin: tapTargetMaxRadius, end: 79.0)
.animate(CurvedAnimation(
parent: rippleController,
curve: const Interval(0.3, 0.8, curve: Curves.ease),
));
}
return const AlwaysStoppedAnimation<double>(tapTargetMaxRadius);
default:
return const AlwaysStoppedAnimation<double>(0);
}
}
Animation<double> tapTargetOpacity(FeatureDiscoveryStatus status) {
switch (status) {
case FeatureDiscoveryStatus.closed:
return const AlwaysStoppedAnimation<double>(0);
case FeatureDiscoveryStatus.open:
return Tween<double>(begin: 0, end: 1.0).animate(CurvedAnimation(
parent: openController,
curve: const Interval(0, 0.4, curve: Curves.ease),
));
case FeatureDiscoveryStatus.tap:
return Tween<double>(begin: 1.0, end: 0).animate(CurvedAnimation(
parent: tapController,
curve: const Interval(0.1, 0.6, curve: Curves.ease),
));
case FeatureDiscoveryStatus.dismiss:
return Tween<double>(begin: 1.0, end: 0).animate(CurvedAnimation(
parent: dismissController,
curve: const Interval(0.2, 0.8, curve: Curves.ease),
));
default:
return const AlwaysStoppedAnimation<double>(1.0);
}
}
Animation<double> tapTargetRadius(FeatureDiscoveryStatus status) {
switch (status) {
case FeatureDiscoveryStatus.closed:
return const AlwaysStoppedAnimation<double>(tapTargetMinRadius);
case FeatureDiscoveryStatus.open:
return Tween<double>(begin: tapTargetMinRadius, end: tapTargetMaxRadius)
.animate(CurvedAnimation(
parent: openController,
curve: const Interval(0, 0.4, curve: Curves.ease),
));
case FeatureDiscoveryStatus.ripple:
if (rippleController.value < 0.3) {
return Tween<double>(
begin: tapTargetMaxRadius, end: tapTargetRippleRadius)
.animate(CurvedAnimation(
parent: rippleController,
curve: const Interval(0, 0.3, curve: Curves.ease),
));
} else if (rippleController.value < 0.6) {
return Tween<double>(
begin: tapTargetRippleRadius, end: tapTargetMaxRadius)
.animate(CurvedAnimation(
parent: rippleController,
curve: const Interval(0.3, 0.6, curve: Curves.ease),
));
}
return const AlwaysStoppedAnimation<double>(tapTargetMaxRadius);
case FeatureDiscoveryStatus.tap:
return Tween<double>(begin: tapTargetMaxRadius, end: tapTargetMinRadius)
.animate(CurvedAnimation(
parent: tapController,
curve: Curves.ease,
));
case FeatureDiscoveryStatus.dismiss:
return Tween<double>(begin: tapTargetMaxRadius, end: tapTargetMinRadius)
.animate(CurvedAnimation(
parent: dismissController,
curve: Curves.ease,
));
default:
return const AlwaysStoppedAnimation<double>(tapTargetMaxRadius);
}
}
}
/// Enum to indicate the current status of a [FeatureDiscovery] widget.
enum FeatureDiscoveryStatus {
closed, // Overlay is closed.
open, // Overlay is opening.
ripple, // Overlay is rippling.
tap, // Overlay is tapped.
dismiss, // Overlay is being dismissed.
}
| gallery/lib/feature_discovery/animation.dart/0 | {
"file_path": "gallery/lib/feature_discovery/animation.dart",
"repo_id": "gallery",
"token_count": 3628
} | 858 |
{
"loading": "Učitavanje",
"deselect": "Poništi odabir",
"select": "Odaberi",
"selectable": "Moguće je odabrati (dugi pritisak)",
"selected": "Odabrano",
"demo": "Demo verzija",
"bottomAppBar": "Donja traka aplikacije",
"notSelected": "Nije odabrano",
"demoCupertinoSearchTextFieldTitle": "Polje za tekst pretraživanja",
"demoCupertinoPicker": "Odabirač",
"demoCupertinoSearchTextFieldSubtitle": "Polje za tekst pretraživanja u stilu iOS-a",
"demoCupertinoSearchTextFieldDescription": "Polje za tekst pretraživanja koje omogućuje korisniku da pretražuje unosom teksta i koje može ponuditi i filtrirati prijedloge.",
"demoCupertinoSearchTextFieldPlaceholder": "Unesite neki tekst",
"demoCupertinoScrollbarTitle": "Traka za pomicanje",
"demoCupertinoScrollbarSubtitle": "Traka za pomicanje u stilu iOS-a",
"demoCupertinoScrollbarDescription": "Traka za pomicanje koja obuhvata dato dijete",
"demoTwoPaneItem": "Stavka {value}",
"demoTwoPaneList": "Lista",
"demoTwoPaneFoldableLabel": "Sklopivo",
"demoTwoPaneSmallScreenLabel": "Mali ekran",
"demoTwoPaneSmallScreenDescription": "Ovako TwoPane funkcionira na uređaju s malim ekranom.",
"demoTwoPaneTabletLabel": "Tablet / računar",
"demoTwoPaneTabletDescription": "Ovako TwoPane funkcionira na uređaju s većim ekranom kao što je tablet ili računar.",
"demoTwoPaneTitle": "TwoPane",
"demoTwoPaneSubtitle": "Prilagodljivi rasporedi na sklopivim, velikim i malim ekranima",
"splashSelectDemo": "Odaberite demonstraciju",
"demoTwoPaneFoldableDescription": "Ovako TwoPane funkcionira na sklopivom uređaju.",
"demoTwoPaneDetails": "Detalji",
"demoTwoPaneSelectItem": "Odaberite stavku",
"demoTwoPaneItemDetails": "Detalji o stavci {value}",
"demoCupertinoContextMenuActionText": "Dodirnite i zadržite logotip Fluttera da prikažete kontekstni meni.",
"demoCupertinoContextMenuDescription": "Kontekstni meni u iOS stilu prikazan na cijelom ekranu koji se pojavljuje kada pritisnete element i dugo zadržite.",
"demoAppBarTitle": "Traka aplikacije",
"demoAppBarDescription": "Traka aplikacije pruža sadržaj i radnje povezane s trenutnim ekranom. Koristi se za brendiranje, naslove ekrana, navigaciju i radnje",
"demoDividerTitle": "Graničnik",
"demoDividerSubtitle": "Graničnik je tanka linija koja grupiše sadržaj u liste i rasporede",
"demoDividerDescription": "Graničnici se mogu koristiti na listama, panelima i na drugim mjestima za razdvajanje sadržaja.",
"demoVerticalDividerTitle": "Vertikalni graničnik",
"demoCupertinoContextMenuTitle": "Kontekstni meni",
"demoCupertinoContextMenuSubtitle": "Kontekstni meni u iOS stilu",
"demoAppBarSubtitle": "Prikazuje informacije i radnje povezane s trenutnim ekranom",
"demoCupertinoContextMenuActionOne": "Prva radnja",
"demoCupertinoContextMenuActionTwo": "Druga radnja",
"demoDateRangePickerDescription": "Prikazuje dijaloški okvir koji sadrži birač raspona datuma u materijalnom dizajnu.",
"demoDateRangePickerTitle": "Birač raspona datuma",
"demoNavigationDrawerUserName": "Korisničko ime",
"demoNavigationDrawerUserEmail": "[email protected]",
"demoNavigationDrawerText": "Prevucite od ruba ili dodirnite ikonu u gornjem lijevom uglu da se prikaže panel",
"demoNavigationRailTitle": "Traka za navigaciju",
"demoNavigationRailSubtitle": "Prikaz trake za navigaciju unutar aplikacije",
"demoNavigationRailDescription": "Materijalni vidžet koji se treba prikazivati na lijevoj ili desnoj strani aplikacije radi navigiranja između malog broja prikaza, obično između tri i pet.",
"demoNavigationRailFirst": "Prvo",
"demoNavigationDrawerTitle": "Panel za navigaciju",
"demoNavigationRailThird": "Treće",
"replyStarredLabel": "Označeno zvjezdicom",
"demoTextButtonDescription": "Dugme za tekst prikazuje mrlju od tinte kada ga pritisnete, ali se ne podiže. Koristite dugmad za tekst na alatnim trakama, u dijaloškim okvirima i u ravni s razmakom od ruba",
"demoElevatedButtonTitle": "Izdignuto dugme",
"demoElevatedButtonDescription": "Izdignuta dugmad daju trodimenzionalni izgled uglavnom ravnim prikazima. Ona naglašavaju funkcije u prostorima s puno elemenata ili širokim prostorima.",
"demoOutlinedButtonTitle": "Ocrtano dugme",
"demoOutlinedButtonDescription": "Ocrtana dugmad postaju neprozirna i podižu se kada se pritisnu. Obično se uparuju s izdignutom dugmadi kako bi se ukazalo na alternativnu, sekundarnu radnju.",
"demoContainerTransformDemoInstructions": "Kartice, liste i FAB",
"demoNavigationDrawerSubtitle": "Prikaz panela unutar trake s aplikacijama",
"replyDescription": "Efikasna, fokusirana aplikacija za e-poštu",
"demoNavigationDrawerDescription": "Panel materijalnog dizajna koji se privuče horizontalno od ruba ekrana da prikaže linkove za navigaciju u aplikaciji.",
"replyDraftsLabel": "Nedovršene verzije",
"demoNavigationDrawerToPageOne": "1. stavka",
"replyInboxLabel": "Pristigla pošta",
"demoSharedXAxisDemoInstructions": "Dugmad \"Naprijed\" i \"Nazad\"",
"replySpamLabel": "Neželjena pošta",
"replyTrashLabel": "Otpad",
"replySentLabel": "Poslano",
"demoNavigationRailSecond": "Drugo",
"demoNavigationDrawerToPageTwo": "2. stavka",
"demoFadeScaleDemoInstructions": "Modal i FAB",
"demoFadeThroughDemoInstructions": "Donja navigacija",
"demoSharedZAxisDemoInstructions": "Dugme ikone postavki",
"demoSharedYAxisDemoInstructions": "Poredaj prema kriteriju \"Nedavno slušano\"",
"demoTextButtonTitle": "Dugme za tekst",
"demoSharedZAxisBeefSandwichRecipeTitle": "Sendvič s govedinom",
"demoSharedZAxisDessertRecipeDescription": "Recept za desert",
"demoSharedYAxisAlbumTileSubtitle": "Izvođač",
"demoSharedYAxisAlbumTileTitle": "Album",
"demoSharedYAxisRecentSortTitle": "Nedavno slušano",
"demoSharedYAxisAlphabeticalSortTitle": "A–Ž",
"demoSharedYAxisAlbumCount": "286 albuma",
"demoSharedYAxisTitle": "Dijeljena y osa",
"demoSharedXAxisCreateAccountButtonText": "KREIRAJ RAČUN",
"demoFadeScaleAlertDialogDiscardButton": "ODBACI",
"demoSharedXAxisSignInTextFieldLabel": "Adresa e-pošte ili broj telefona",
"demoSharedXAxisSignInSubtitleText": "Prijavite se putem svog računa",
"demoSharedXAxisSignInWelcomeText": "Zdravo, David Park",
"demoSharedXAxisIndividualCourseSubtitle": "Prikazano pojedinačno",
"demoSharedXAxisBundledCourseSubtitle": "Upakovano",
"demoFadeThroughAlbumsDestination": "Albumi",
"demoSharedXAxisDesignCourseTitle": "Dizajn",
"demoSharedXAxisIllustrationCourseTitle": "Ilustracija",
"demoSharedXAxisBusinessCourseTitle": "Biznis",
"demoSharedXAxisArtsAndCraftsCourseTitle": "Umjetnost i zanati",
"demoMotionPlaceholderSubtitle": "Sekundarni tekst",
"demoFadeScaleAlertDialogCancelButton": "OTKAŽI",
"demoFadeScaleAlertDialogHeader": "Dijaloški okvir upozorenja",
"demoFadeScaleHideFabButton": "SAKRIJ FAB",
"demoFadeScaleShowFabButton": "PRIKAŽI FAB",
"demoFadeScaleShowAlertDialogButton": "PRIKAŽI MODAL",
"demoFadeScaleDescription": "Obrazac iščezavanja se koristi za elemente korisničkog interfejsa koji ulaze unutar granica ekrana ili izlaze izvan njih, kao što je dijaloški okvir koji iščezava na sredini ekrana.",
"demoFadeScaleTitle": "Iščezavanje",
"demoFadeThroughTextPlaceholder": "123 fotografije",
"demoFadeThroughSearchDestination": "Pretraži",
"demoFadeThroughPhotosDestination": "Fotografije",
"demoSharedXAxisCoursePageSubtitle": "Upakovane kategorije se prikazuju u grupama u vašem sažetku sadržaja. Ovo uvijek možete promijeniti kasnije.",
"demoFadeThroughDescription": "Obrazac iščezavanja s prijelazom se koristi za prijelaz između elemenata korisničkog interfejsa koji nisu međusobno čvrsto povezani.",
"demoFadeThroughTitle": "Iščezavanje s prijelazom",
"demoSharedZAxisHelpSettingLabel": "Pomoć",
"demoMotionSubtitle": "Svi unaprijed definirani obrasci prijelaza",
"demoSharedZAxisNotificationSettingLabel": "Obavještenja",
"demoSharedZAxisProfileSettingLabel": "Profil",
"demoSharedZAxisSavedRecipesListTitle": "Sačuvani recepti",
"demoSharedZAxisBeefSandwichRecipeDescription": "Recept za sendvič s govedinom",
"demoSharedZAxisCrabPlateRecipeDescription": "Recept za jelo od raka",
"demoSharedXAxisCoursePageTitle": "Prilagodite svoje tokove",
"demoSharedZAxisCrabPlateRecipeTitle": "Rak",
"demoSharedZAxisShrimpPlateRecipeDescription": "Recept za jelo od škampa",
"demoSharedZAxisShrimpPlateRecipeTitle": "Škampi",
"demoContainerTransformTypeFadeThrough": "IŠČEZAVANJE S PRIJELAZOM",
"demoSharedZAxisDessertRecipeTitle": "Desert",
"demoSharedZAxisSandwichRecipeDescription": "Recept za sendvič",
"demoSharedZAxisSandwichRecipeTitle": "Sendvič",
"demoSharedZAxisBurgerRecipeDescription": "Recept za pljeskavicu",
"demoSharedZAxisBurgerRecipeTitle": "Pljeskavica",
"demoSharedZAxisSettingsPageTitle": "Postavke",
"demoSharedZAxisTitle": "Dijeljena z osa",
"demoSharedZAxisPrivacySettingLabel": "Privatnost",
"demoMotionTitle": "Pokret",
"demoContainerTransformTitle": "Transformiranje spremnika",
"demoContainerTransformDescription": "Obrazac transformiranja spremnika je dizajniran za prijelaze između elemenata korisničkog interfejsa koji uključuju spremnik. Ovim obrascem se kreira vidljiva veza između dva elementa korisničkog interfejsa",
"demoContainerTransformModalBottomSheetTitle": "Način rada za iščezavanje",
"demoContainerTransformTypeFade": "IŠČEZAVANJE",
"demoSharedYAxisAlbumTileDurationUnit": "min",
"demoMotionPlaceholderTitle": "Naslov",
"demoSharedXAxisForgotEmailButtonText": "ZABORAVILI STE ADRESU E-POŠTE?",
"demoMotionSmallPlaceholderSubtitle": "Sekundarno",
"demoMotionDetailsPageTitle": "Stranica s detaljima",
"demoMotionListTileTitle": "Stavka liste",
"demoSharedAxisDescription": "Obrazac dijeljene ose se koristi za prijelaze između elemenata korisničkog interfejsa koji imaju prostornu ili navigacijsku vezu. Ovaj obrazac koristi dijeljenu transformaciju na x, y ili z osi da ojača vezu između elemenata.",
"demoSharedXAxisTitle": "Dijeljena x osa",
"demoSharedXAxisBackButtonText": "NAZAD",
"demoSharedXAxisNextButtonText": "NAPRIJED",
"demoSharedXAxisCulinaryCourseTitle": "Kulinarstvo",
"githubRepo": "{repoName} GitHub spremište",
"fortnightlyMenuUS": "SAD",
"fortnightlyMenuBusiness": "Biznis",
"fortnightlyMenuScience": "Nauka",
"fortnightlyMenuSports": "Sport",
"fortnightlyMenuTravel": "Putovanja",
"fortnightlyMenuCulture": "Kultura",
"fortnightlyTrendingTechDesign": "Tehnološki dizajn",
"rallyBudgetDetailAmountLeft": "Preostali iznos",
"fortnightlyHeadlineArmy": "Reforma zelene armije iznutra",
"fortnightlyDescription": "Aplikacija za vijesti s fokusom na sadržaj",
"rallyBillDetailAmountDue": "Dospjeli iznos",
"rallyBudgetDetailTotalCap": "Ukupno ograničenje",
"rallyBudgetDetailAmountUsed": "Iskorišteni iznos",
"fortnightlyTrendingHealthcareRevolution": "Revolucija u zdravstvu",
"fortnightlyMenuFrontPage": "Naslovnica",
"fortnightlyMenuWorld": "Svijet",
"rallyBillDetailAmountPaid": "Plaćeni iznos",
"fortnightlyMenuPolitics": "Politika",
"fortnightlyHeadlineBees": "Domaće pčele deficitarne",
"fortnightlyHeadlineGasoline": "Budućnost benzina",
"fortnightlyTrendingGreenArmy": "Zelena armija",
"fortnightlyHeadlineFeminists": "Feministkinje protiv stranačkog svrstavanja",
"fortnightlyHeadlineFabrics": "Dizajneri koriste tehnologiju za izradu materijala budućnosti",
"fortnightlyHeadlineStocks": "Dok berze stagniraju, mnogi se uzdaju u valutu",
"fortnightlyTrendingReform": "Reforma",
"fortnightlyMenuTech": "Tehnologija",
"fortnightlyHeadlineWar": "Podijeljeni životi Amerikanaca za vrijeme rata",
"fortnightlyHeadlineHealthcare": "Mirna, ali moćna revolucija u zdravstvu",
"fortnightlyLatestUpdates": "Najnovije vijesti",
"fortnightlyTrendingStocks": "Berza",
"rallyBillDetailTotalAmount": "Ukupan iznos",
"demoCupertinoPickerDateTime": "Datum i vrijeme",
"signIn": "PRIJAVA",
"dataTableRowWithSugar": "{value} sa šećerom",
"dataTableRowApplePie": "Pita od jabuka",
"dataTableRowDonut": "Krofna",
"dataTableRowHoneycomb": "Saće",
"dataTableRowLollipop": "Lizalo",
"dataTableRowJellyBean": "Bombon",
"dataTableRowGingerbread": "Medenjak",
"dataTableRowCupcake": "Kolač",
"dataTableRowEclair": "Ekler",
"dataTableRowIceCreamSandwich": "Sendvič od sladoleda",
"dataTableRowFrozenYogurt": "Zamrznuti jogurt",
"dataTableColumnIron": "Željezo (%)",
"dataTableColumnCalcium": "Kalcij (%)",
"dataTableColumnSodium": "Natrij (mg)",
"demoTimePickerTitle": "Birač vremena",
"demo2dTransformationsResetTooltip": "Vratite transformacije na zadano",
"dataTableColumnFat": "Masnoća (g)",
"dataTableColumnCalories": "Kalorije",
"dataTableColumnDessert": "Desert (1 porcija)",
"cardsDemoTravelDestinationLocation1": "Thanjavur, Tamil Nadu",
"demoTimePickerDescription": "Prikazuje dijaloški okvir koji sadrži birač vremena u materijalnom dizajnu.",
"demoPickersShowPicker": "PRIKAŽI BIRAČ",
"demoTabsScrollingTitle": "Klizanje",
"demoTabsNonScrollingTitle": "Bez klizanja",
"craneHours": "{hours,plural,=1{1 h}few{{hours} h}other{{hours} h}}",
"craneMinutes": "{minutes,plural,=1{1 min}few{{minutes} min}other{{minutes} min}}",
"craneFlightDuration": "{hoursShortForm} {minutesShortForm}",
"dataTableHeader": "Ishrana",
"demoDatePickerTitle": "Birač datuma",
"demoPickersSubtitle": "Odabir datuma i vremena",
"demoPickersTitle": "Birači",
"demo2dTransformationsEditTooltip": "Uredite naslov",
"demoDataTableDescription": "Informacije u tabelama s podacima su prikazane u formatu mreže redova i kolona. Informacije su organizirane na način koji olakšava pregled da korisnici mogu tražiti uzorke i uvide.",
"demo2dTransformationsDescription": "Dodirnite da uredite naslove i koristite pokrete da se krećete po prizoru. Povucite da pomičete, uhvatite prstima da zumirate, rotirajte s dva prsta. Pritisnite dugme za poništavanje da se vratite na početnu orijentaciju.",
"demo2dTransformationsSubtitle": "Pomičite, zumirajte, rotirate",
"demo2dTransformationsTitle": "2D transformacije",
"demoCupertinoTextFieldPIN": "PIN",
"demoCupertinoTextFieldDescription": "Polje za tekst omogućava korisniku da unese tekst, bilo pomoću hardverske tastature ili pomoću tastature na ekranu.",
"demoCupertinoTextFieldSubtitle": "Polja za tekst u stilu iOS-a",
"demoCupertinoTextFieldTitle": "Polja za tekst",
"demoDatePickerDescription": "Prikazuje dijaloški okvir koji sadrži birač datuma u materijalnom dizajnu.",
"demoCupertinoPickerTime": "Vrijeme",
"demoCupertinoPickerDate": "Datum",
"demoCupertinoPickerTimer": "Tajmer",
"demoCupertinoPickerDescription": "Vidžet birača u stilu iOS-a koji se može koristiti za odabir nizova, datuma, vremena ili i datuma i vremena.",
"demoCupertinoPickerSubtitle": "Odabirači u stilu iOS-a",
"demoCupertinoPickerTitle": "Birači",
"dataTableRowWithHoney": "{value} s medom",
"cardsDemoTravelDestinationCity2": "Chettinada",
"bannerDemoResetText": "Poništi prikaz banera",
"bannerDemoMultipleText": "Više radnji",
"bannerDemoLeadingText": "Početna ikona",
"dismiss": "ODBACI",
"cardsDemoTappable": "Moguće je dodirnuti",
"cardsDemoSelectable": "Moguće je odabrati (dugi pritisak)",
"cardsDemoExplore": "Istraži",
"cardsDemoExploreSemantics": "Istražite: {destinationName}",
"cardsDemoShareSemantics": "Dijelite: {destinationName}",
"cardsDemoTravelDestinationTitle1": "Deset gradova koje trebate posjetiti u Tamil Naduu",
"cardsDemoTravelDestinationDescription1": "Na 10. mjestu",
"cardsDemoTravelDestinationCity1": "Thanjavur",
"dataTableColumnProtein": "Proteini (g)",
"cardsDemoTravelDestinationTitle2": "Obrtnici južne Indije",
"cardsDemoTravelDestinationDescription2": "Prelci svile",
"bannerDemoText": "Vaša lozinka je ažurirana na drugom uređaju. Prijavite se ponovo.",
"cardsDemoTravelDestinationLocation2": "Sivaganga, Tamil Nadu",
"cardsDemoTravelDestinationTitle3": "Hram Brihadisvara",
"cardsDemoTravelDestinationDescription3": "Hramovi",
"demoBannerTitle": "Baner",
"demoBannerSubtitle": "Prikazivanje banera na listi",
"demoBannerDescription": "Baner prikazuje važnu i sažetu poruku i navodi radnje koje korisnici mogu izvršiti (ili mogu odbaciti baner). Za odbacivanje banera je potrebna radnja korisnika.",
"demoCardTitle": "Kartice",
"demoCardSubtitle": "Osnovne kartice sa zaobljenim uglovima",
"demoCardDescription": "Kartica je list materijala koji se koristi za prikaz povezanih podataka kao što je album, geografska lokacija, obrok, detalji o kontaktu itd.",
"demoDataTableTitle": "Tabele s podacima",
"demoDataTableSubtitle": "Redovi i kolone s informacijama",
"dataTableColumnCarbs": "Ugljikohidrati (g)",
"placeTanjore": "Tanjavur",
"demoGridListsTitle": "Mrežaste liste",
"placeFlowerMarket": "Cvjetna tržnica",
"placeBronzeWorks": "Proizvodi od bronze",
"placeMarket": "Tržnica",
"placeThanjavurTemple": "Hram u Tanjavuru",
"placeSaltFarm": "Solana",
"placeScooters": "Skuteri",
"placeSilkMaker": "Proizvođač svile",
"placeLunchPrep": "Pripremanje ručka",
"placeBeach": "Plaža",
"placeFisherman": "Ribar",
"demoMenuSelected": "Odabrano: {value}",
"demoMenuRemove": "Ukloni",
"demoMenuGetLink": "Preuzmi link",
"demoMenuShare": "Dijeli",
"demoBottomAppBarSubtitle": "Prikazuje navigaciju i radnje na dnu",
"demoMenuAnItemWithASectionedMenu": "Stavka s menijem s odjeljcima",
"demoMenuADisabledMenuItem": "Onemogućena stavka menija",
"demoLinearProgressIndicatorTitle": "Linearni pokazatelj napretka",
"demoMenuContextMenuItemOne": "Prva stavka kontekstnog menija",
"demoMenuAnItemWithASimpleMenu": "Stavka s jednostavnim menijem",
"demoCustomSlidersTitle": "Prilagođeni klizači",
"demoMenuAnItemWithAChecklistMenu": "Stavka s menijem s kontrolnim listama",
"demoCupertinoActivityIndicatorTitle": "Pokazatelj aktivnosti",
"demoCupertinoActivityIndicatorSubtitle": "Pokazatelji aktivnosti u stilu iOS-a",
"demoCupertinoActivityIndicatorDescription": "Pokazatelj aktivnosti u stilu iOS-a koji se okreće u smjeru kretanja kazaljke na satu.",
"demoCupertinoNavigationBarTitle": "Navigaciona traka",
"demoCupertinoNavigationBarSubtitle": "Traka za navigaciju u stilu iOS-a",
"demoCupertinoNavigationBarDescription": "Traka za navigaciju u stilu iOS-a. Traka za navigaciju je alatna traka koja sadrži barem naziv stranice na sredini alatne trake.",
"demoCupertinoPullToRefreshTitle": "Povucite da osvježite",
"demoCupertinoPullToRefreshSubtitle": "Kontrola povlačenja za osvježavanje u stilu iOS-a",
"demoCupertinoPullToRefreshDescription": "Vidžet kojim se primjenjuje kontrola povlačenja za osvježavanje u stilu iOS-a.",
"demoProgressIndicatorTitle": "Pokazatelji napretka",
"demoProgressIndicatorSubtitle": "Linearno, kružno, neodređeno",
"demoCircularProgressIndicatorTitle": "Kružni pokazatelj napretka",
"demoCircularProgressIndicatorDescription": "Kružni pokazatelj napretka materijalnog dizajna koji se okreće da pokaže da je aplikacija zauzeta.",
"demoMenuFour": "Četiri",
"demoLinearProgressIndicatorDescription": "Linearni pokazatelj napretka materijalnog dizajna, također poznat kao traka napretka.",
"demoTooltipTitle": "Opisi",
"demoTooltipSubtitle": "Kratka poruka koja se prikazuje dugim pritiskom ili postavljanjem kursora iznad elementa",
"demoTooltipDescription": "Opisi pružaju tekstualne oznake kojima se objašnjava funkcija dugmeta ili druge radnje korisničkog interfejsa. Opisi prikazuju informativni tekst kada korisnik postavi kursor iznad elementa, fokusira se na njega ili ga dugo pritisne.",
"demoTooltipInstructions": "Koristite dugi pritisak ili postavite kursor iznad elementa za prikazivanje skočnog opisa.",
"placeChennai": "Chennai",
"demoMenuChecked": "Označeno: {value}",
"placeChettinad": "Chettinada",
"demoMenuPreview": "Pregled",
"demoBottomAppBarTitle": "Donja traka aplikacije",
"demoBottomAppBarDescription": "Donje trake aplikacije pružaju pristup donjem panelu za navigaciju i maksimalno četiri radnje, uključujući plutajuće dugme za radnju.",
"bottomAppBarNotch": "Urez",
"bottomAppBarPosition": "Položaj plutajućeg dugmeta za radnju",
"bottomAppBarPositionDockedEnd": "Na traci – Na kraju",
"bottomAppBarPositionDockedCenter": "Na traci – U sredini",
"bottomAppBarPositionFloatingEnd": "Plutajuće – Na kraju",
"bottomAppBarPositionFloatingCenter": "Plutajuće – U sredini",
"demoSlidersEditableNumericalValue": "Izmjenjiva brojčana vrijednost",
"demoGridListsSubtitle": "Raspored redova i kolona",
"demoGridListsDescription": "Mrežaste liste su najpogodnije za prikaz homogenih podataka, obično slika. Svaka stavka na mrežastoj listi se naziva polje.",
"demoGridListsImageOnlyTitle": "Samo slika",
"demoGridListsHeaderTitle": "Sa zaglavljem",
"demoGridListsFooterTitle": "S podnožjem",
"demoSlidersTitle": "Klizači",
"demoSlidersSubtitle": "Vidžeti za odabir vrijednosti prevlačenjem",
"demoSlidersDescription": "Klizači prikazuju raspon vrijednosti duž trake odakle korisnici mogu odabrati jednu vrijednost. Idealni su za podešavanje postavki kao što su jačina zvuka, osvijetljenost ili primjena filtera za slike.",
"demoRangeSlidersTitle": "Klizači s rasponom vrijednosti",
"demoRangeSlidersDescription": "Klizači prikazuju raspon vrijednosti duž trake. Na oba kraja se mogu nalaziti ikone koje prikazuju raspon vrijednosti. Idealni su za podešavanje postavki kao što su jačina zvuka, osvijetljenost ili primjena filtera za slike.",
"demoMenuAnItemWithAContextMenuButton": "Stavka s kontekstnim menijem",
"demoCustomSlidersDescription": "Klizači prikazuju raspon vrijednosti duž trake odakle korisnici mogu odabrati jednu vrijednost ili niz vrijednosti. Klizače je moguće urediti temom i prilagoditi.",
"demoSlidersContinuousWithEditableNumericalValue": "Neprekidno s izmjenjivom brojčanom vrijednosti",
"demoSlidersDiscrete": "Diskretno",
"demoSlidersDiscreteSliderWithCustomTheme": "Diskretni klizač s prilagođenom temom",
"demoSlidersContinuousRangeSliderWithCustomTheme": "Neprekidni klizač s rasponom vrijednosti s prilagođenom temom",
"demoSlidersContinuous": "Neprekidno",
"placePondicherry": "Puducherry",
"demoMenuTitle": "Meni",
"demoContextMenuTitle": "Kontekstni meni",
"demoSectionedMenuTitle": "Meni s odjeljcima",
"demoSimpleMenuTitle": "Jednostavan meni",
"demoChecklistMenuTitle": "Meni s kontrolnim listama",
"demoMenuSubtitle": "Dugmad menija i jednostavni meniji",
"demoMenuDescription": "Na meniju se prikazuje lista odabira na privremenoj površini. Oni se prikazuju kada korisnik koristi dugmad, radnje ili druge kontrole.",
"demoMenuItemValueOne": "Prva stavka menija",
"demoMenuItemValueTwo": "Druga stavka menija",
"demoMenuItemValueThree": "Treća stavka menija",
"demoMenuOne": "Jedan",
"demoMenuTwo": "Dva",
"demoMenuThree": "Tri",
"demoMenuContextMenuItemThree": "Treća stavka kontekstnog menija",
"demoCupertinoSwitchSubtitle": "Prekidač u stilu iOS-a",
"demoSnackbarsText": "Ovo je kratko obavještenje.",
"demoCupertinoSliderSubtitle": "Klizač u stilu iOS-a",
"demoCupertinoSliderDescription": "Klizač možete koristiti za odabir kontinuiranog ili diskretnog skupa vrijednosti.",
"demoCupertinoSliderContinuous": "Kontinuirano: {value}",
"demoCupertinoSliderDiscrete": "Diskretno: {value}",
"demoSnackbarsAction": "Pritisnuli ste radnju za kratko obavještenje.",
"backToGallery": "Nazad u Gallery",
"demoCupertinoTabBarTitle": "Traka tabulatora",
"demoCupertinoSwitchDescription": "Prekidač se koristi za aktiviranje/deaktiviranje jedne postavke.",
"demoSnackbarsActionButtonLabel": "RADNJA",
"cupertinoTabBarProfileTab": "Profil",
"demoSnackbarsButtonLabel": "PRIKAŽI KRATKO OBAVJEŠTENJE",
"demoSnackbarsDescription": "Kratka obavještenja informiraju korisnike o postupku koji je aplikacija izvršila ili će tek izvršiti. Pojavljajuju se privremeno, prema dnu ekrana. Ne bi trebala ometati iskustvo korisnika, a za nestajanje ne zahtijevaju unos korisnika.",
"demoSnackbarsSubtitle": "Kratka obavještenja prikazuju poruke na dnu ekrana",
"demoSnackbarsTitle": "Kratka obavještenja",
"demoCupertinoSliderTitle": "Klizač",
"cupertinoTabBarChatTab": "Chat",
"cupertinoTabBarHomeTab": "Početna stranica",
"demoCupertinoTabBarDescription": "Donja traka s karticama za navigaciju u stilu iOS-a. Prikazuje više kartica dok je jedna kartica aktivna, a to je prva kartica prema zadanim postavkama.",
"demoCupertinoTabBarSubtitle": "Donja traka s karticama u stilu iOS-a",
"demoOptionsFeatureTitle": "Pogledajte opcije",
"demoOptionsFeatureDescription": "Dodirnite ovdje da pogledate opcije dostupne za ovu demonstraciju.",
"demoCodeViewerCopyAll": "KOPIRAJ SVE",
"shrineScreenReaderRemoveProductButton": "Uklonite proizvod {product}",
"shrineScreenReaderProductAddToCart": "Dodavanje u korpu",
"shrineScreenReaderCart": "{quantity,plural,=0{Kolica za kupovinu bez artikala}=1{Kolica za kupovinu s 1 artiklom}few{Kolica za kupovinu sa {quantity} artikla}other{Kolica za kupovinu sa {quantity} artikala}}",
"demoCodeViewerFailedToCopyToClipboardMessage": "Kopiranje u međumemoriju nije uspjelo: {error}",
"demoCodeViewerCopiedToClipboardMessage": "Kopirano u međumemoriju.",
"craneSleep8SemanticLabel": "Majanske ruševine na litici iznad plaže",
"craneSleep4SemanticLabel": "Hotel pored jezera ispred planina",
"craneSleep2SemanticLabel": "Tvrđava Machu Picchu",
"craneSleep1SemanticLabel": "Planinska kućica u snježnom krajoliku sa zimzelenim drvećem",
"craneSleep0SemanticLabel": "Kućice na vodi",
"craneFly13SemanticLabel": "Bazen pored mora okružen palmama",
"craneFly12SemanticLabel": "Bazen okružen palmama",
"craneFly11SemanticLabel": "Svjetionik od cigle na moru",
"craneFly10SemanticLabel": "Minareti džamije Al-Azhar u suton",
"craneFly9SemanticLabel": "Muškarac naslonjen na starinski plavi automobil",
"craneFly8SemanticLabel": "Supertree Grove",
"craneEat9SemanticLabel": "Štand za kafu i peciva",
"craneEat2SemanticLabel": "Pljeskavica",
"craneFly5SemanticLabel": "Hotel pored jezera ispred planina",
"demoSelectionControlsSubtitle": "Polja za potvrdu, dugmad za izbor i prekidači",
"craneEat10SemanticLabel": "Žena drži ogromni sendvič s dimljenom govedinom",
"craneFly4SemanticLabel": "Kućice na vodi",
"craneEat7SemanticLabel": "Ulaz u pekaru",
"craneEat6SemanticLabel": "Jelo od škampi",
"craneEat5SemanticLabel": "Prostor za sjedenje u umjetničkom restoranu",
"craneEat4SemanticLabel": "Čokoladni desert",
"craneEat3SemanticLabel": "Korejski tako",
"craneFly3SemanticLabel": "Tvrđava Machu Picchu",
"craneEat1SemanticLabel": "Prazan bar s barskim stolicama",
"craneEat0SemanticLabel": "Pizza u krušnoj peći",
"craneSleep11SemanticLabel": "Neboder Taipei 101",
"craneSleep10SemanticLabel": "Minareti džamije Al-Azhar u suton",
"craneSleep9SemanticLabel": "Svjetionik od cigle na moru",
"craneEat8SemanticLabel": "Tanjir s rečnim rakovima",
"craneSleep7SemanticLabel": "Šareni stanovi na Trgu Riberia",
"craneSleep6SemanticLabel": "Bazen okružen palmama",
"craneSleep5SemanticLabel": "Šator u polju",
"settingsButtonCloseLabel": "Zatvori postavke",
"demoSelectionControlsCheckboxDescription": "Polja za potvrdu omogućavaju korisniku da odabere više opcija iz skupa. Normalna vrijednost polja za potvrdu je tačno ili netačno, a treća vrijednost polja za potvrdu može biti i nula.",
"settingsButtonLabel": "Postavke",
"demoListsTitle": "Liste",
"demoListsSubtitle": "Izgledi liste koju je moguće klizati",
"demoListsDescription": "Jedan red fiksne visine koji uglavnom sadrži tekst te ikonu na početku ili na kraju.",
"demoOneLineListsTitle": "Jedan red",
"demoTwoLineListsTitle": "Dva reda",
"demoListsSecondary": "Sekundarni tekst",
"demoSelectionControlsTitle": "Kontrole odabira",
"craneFly7SemanticLabel": "Planina Rushmore",
"demoSelectionControlsCheckboxTitle": "Polje za potvrdu",
"craneSleep3SemanticLabel": "Muškarac naslonjen na starinski plavi automobil",
"demoSelectionControlsRadioTitle": "Dugme za izbor",
"demoSelectionControlsRadioDescription": "Dugmad za izbor omogućava korisniku da odabere jednu opciju iz seta. Koristite dugmad za izbor za ekskluzivni odabir ako smatrate da korisnik treba vidjeti sve dostupne opcije jednu pored druge.",
"demoSelectionControlsSwitchTitle": "Prekidač",
"demoSelectionControlsSwitchDescription": "Prekidači za uključivanje/isključivanje mijenjaju stanje jedne opcije postavki. Opcija koju kontrolira prekidač, kao i status te opcije, trebaju biti jasno naglašeni u odgovarajućoj direktnoj oznaci.",
"craneFly0SemanticLabel": "Planinska kućica u snježnom krajoliku sa zimzelenim drvećem",
"craneFly1SemanticLabel": "Šator u polju",
"craneFly2SemanticLabel": "Molitvene zastave ispred snijegom prekrivene planine",
"craneFly6SemanticLabel": "Pogled iz zraka na Palacio de Bellas Artes",
"rallySeeAllAccounts": "Vidi sve račune",
"rallyBillAmount": "Rok za plaćanje računa ({billName}) u iznosu od {amount} je {date}.",
"shrineTooltipCloseCart": "Zatvaranje korpe",
"shrineTooltipCloseMenu": "Zatvaranje menija",
"shrineTooltipOpenMenu": "Otvaranje menija",
"shrineTooltipSettings": "Postavke",
"shrineTooltipSearch": "Pretraživanje",
"demoTabsDescription": "Kartice organiziraju sadržaj na različitim ekranima, skupovima podataka i drugim interakcijama.",
"demoTabsSubtitle": "Kartice s prikazima koji se mogu nezavisno klizati",
"demoTabsTitle": "Kartice",
"rallyBudgetAmount": "Od ukupnog budžeta ({budgetName}) od {amountTotal} iskorišteno je {amountUsed}, a preostalo je {amountLeft}",
"shrineTooltipRemoveItem": "Uklanjanje stavke",
"rallyAccountAmount": "Na račun ({accountName}) s brojem {accountNumber} je uplaćen iznos od {amount}.",
"rallySeeAllBudgets": "Vidi sve budžete",
"rallySeeAllBills": "Prikaži sve račune",
"craneFormDate": "Odaberite datum",
"craneFormOrigin": "Odaberite polazište",
"craneFly2": "Dolina Khumbu, Nepal",
"craneFly3": "Machu Picchu, Peru",
"craneFly4": "Malé, Maldivi",
"craneFly5": "Vitznau, Švicarska",
"craneFly6": "Mexico City, Meksiko",
"craneFly7": "Planina Rushmore, Sjedinjene Američke Države",
"settingsTextDirectionLocaleBased": "Na osnovu jezika/zemlje",
"craneFly9": "Havana, Kuba",
"craneFly10": "Kairo, Egipat",
"craneFly11": "Lisabon, Portugal",
"craneFly12": "Napa, Sjedinjene Američke Države",
"craneFly13": "Bali, Indonezija",
"craneSleep0": "Malé, Maldivi",
"craneSleep1": "Aspen, Sjedinjene Američke Države",
"craneSleep2": "Machu Picchu, Peru",
"demoCupertinoSegmentedControlTitle": "Segmentirano kontroliranje",
"craneSleep4": "Vitznau, Švicarska",
"craneSleep5": "Big Sur, Sjedinjene Američke Države",
"craneSleep6": "Napa, Sjedinjene Američke Države",
"craneSleep7": "Porto, Portugal",
"craneSleep8": "Tulum, Meksiko",
"craneEat5": "Seul, Južna Koreja",
"demoChipTitle": "Čipovi",
"demoChipSubtitle": "Kompaktni elementi koji predstavljaju unos, atribut ili radnju",
"demoActionChipTitle": "Čip za radnju",
"demoActionChipDescription": "Čipovi za radnje su skupovi opcija koje aktiviraju određenu radnju povezanu s primarnim sadržajem. Čipovi za radnje trebali bi se prikazivati dinamički i kontekstualno u korisničkom interfejsu.",
"demoChoiceChipTitle": "Čip za odabir",
"demoChoiceChipDescription": "Čipovi za odabir predstavljaju izbor jedne stavke iz ponuđenog skupa. Čipovi za odabir sadrže povezani tekst s opisom ili kategorije.",
"demoFilterChipTitle": "Čip za filtriranje",
"demoFilterChipDescription": "Čipovi za filtriranje koriste oznake ili opisne riječi kao način za filtriranje sadržaja.",
"demoInputChipTitle": "Čip unosa",
"demoInputChipDescription": "Čipovi unosa predstavljaju kompleksne informacije, kao što su entitet (osoba, mjesto ili stvar) ili tekst razgovora, u kompaktnoj formi.",
"craneSleep9": "Lisabon, Portugal",
"craneEat10": "Lisabon, Portugal",
"demoCupertinoSegmentedControlDescription": "Koristi se za odabir između više opcija koje se međusobno isključuju. Kada se u segmentiranom kontroliranju odabere jedna opcija, poništava se odabir ostalih opcija.",
"chipTurnOnLights": "Uključivanje svjetla",
"chipSmall": "Malo",
"chipMedium": "Srednje",
"chipLarge": "Veliko",
"chipElevator": "Lift",
"chipWasher": "Veš mašina",
"chipFireplace": "Kamin",
"chipBiking": "Vožnja bicikla",
"craneFormDiners": "Mali restorani",
"rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Povećajte potencijalne porezne olakšice! Dodijelite kategorije za 1 nedodijeljenu transakciju.}few{Povećajte potencijalne porezne olakšice! Dodijelite kategorije za {count} nedodijeljene transakcije.}other{Povećajte potencijalne porezne olakšice! Dodijelite kategorije za {count} nedodijeljenih transakcija.}}",
"craneFormTime": "Odaberite vrijeme",
"craneFormLocation": "Odaberite lokaciju",
"craneFormTravelers": "Putnici",
"craneEat8": "Atlanta, Sjedinjene Američke Države",
"craneFormDestination": "Odaberite odredište",
"craneFormDates": "Odaberite datume",
"craneFly": "LETITE",
"craneSleep": "STANJE MIROVANJA",
"craneEat": "HRANA",
"craneFlySubhead": "Istražite letove po odredištima",
"craneSleepSubhead": "Istražite smještaje po odredištima",
"craneEatSubhead": "Istražite restorane po odredištima",
"craneFlyStops": "{numberOfStops,plural,=0{Bez presjedanja}=1{1 presjedanje}few{{numberOfStops} presjedanja}other{{numberOfStops} presjedanja}}",
"craneSleepProperties": "{totalProperties,plural,=0{Nema dostupnih smještaja}=1{1 dostupan smještaj}few{{totalProperties} dostupna smještaja}other{{totalProperties} dostupnih smještaja}}",
"craneEatRestaurants": "{totalRestaurants,plural,=0{Nema restorana}=1{1 restoran}few{{totalRestaurants} restorana}other{{totalRestaurants} restorana}}",
"craneFly0": "Aspen, Sjedinjene Američke Države",
"demoCupertinoSegmentedControlSubtitle": "Segmentirano kontroliranje u stilu iOS-a",
"craneSleep10": "Kairo, Egipat",
"craneEat9": "Madrid, Španija",
"craneFly1": "Big Sur, Sjedinjene Američke Države",
"craneEat7": "Nashville, Sjedinjene Američke Države",
"craneEat6": "Seattle, Sjedinjene Američke Države",
"craneFly8": "Singapur",
"craneEat4": "Pariz, Francuska",
"craneEat3": "Portland, Sjedinjene Američke Države",
"craneEat2": "Kordoba, Argentina",
"craneEat1": "Dalas, Sjedinjene Američke Države",
"craneEat0": "Napulj, Italija",
"craneSleep11": "Taipei, Tajvan",
"craneSleep3": "Havana, Kuba",
"shrineLogoutButtonCaption": "ODJAVA",
"rallyTitleBills": "RAČUNI",
"rallyTitleAccounts": "RAČUNI",
"shrineProductVagabondSack": "Torba Vagabond",
"rallyAccountDetailDataInterestYtd": "Kamate od početka godine",
"shrineProductWhitneyBelt": "Pojas Whitney",
"shrineProductGardenStrand": "Vrtno ukrasno uže",
"shrineProductStrutEarrings": "Naušnice Strut",
"shrineProductVarsitySocks": "Čarape s prugama",
"shrineProductWeaveKeyring": "Pleteni privjesak za ključeve",
"shrineProductGatsbyHat": "Kapa Gatsby",
"shrineProductShrugBag": "Torba za nošenje na ramenu",
"shrineProductGiltDeskTrio": "Tri pozlaćena stolića",
"shrineProductCopperWireRack": "Bakarna vješalica",
"shrineProductSootheCeramicSet": "Keramički set Soothe",
"shrineProductHurrahsTeaSet": "Čajni set Hurrahs",
"shrineProductBlueStoneMug": "Plava kamena šolja",
"shrineProductRainwaterTray": "Posuda za kišnicu",
"shrineProductChambrayNapkins": "Ubrusi od chambraya",
"shrineProductSucculentPlanters": "Posude za sukulentne biljke",
"shrineProductQuartetTable": "Stol za četiri osobe",
"shrineProductKitchenQuattro": "Četverodijelni kuhinjski set",
"shrineProductClaySweater": "Džemper boje gline",
"shrineProductSeaTunic": "Morska tunika",
"shrineProductPlasterTunic": "Tunika boje gipsa",
"rallyBudgetCategoryRestaurants": "Restorani",
"shrineProductChambrayShirt": "Košulja od chambraya",
"shrineProductSeabreezeSweater": "Džemper boje mora",
"shrineProductGentryJacket": "Jakna Gentry",
"shrineProductNavyTrousers": "Tamnoplave hlače",
"shrineProductWalterHenleyWhite": "Majica s Henley ovratnikom (bijela)",
"shrineProductSurfAndPerfShirt": "Surferska majica",
"shrineProductGingerScarf": "Šal boje đumbira",
"shrineProductRamonaCrossover": "Ramona crossover",
"shrineProductClassicWhiteCollar": "Klasična bijela košulja",
"shrineProductSunshirtDress": "Haljina za plažu",
"rallyAccountDetailDataInterestRate": "Kamatna stopa",
"rallyAccountDetailDataAnnualPercentageYield": "Godišnji procenat prinosa",
"rallyAccountDataVacation": "Odmor",
"shrineProductFineLinesTee": "Majica s tankim crtama",
"rallyAccountDataHomeSavings": "Štednja za kupovinu kuće",
"rallyAccountDataChecking": "Provjera",
"rallyAccountDetailDataInterestPaidLastYear": "Kamate plaćene prošle godine",
"rallyAccountDetailDataNextStatement": "Sljedeći izvod",
"rallyAccountDetailDataAccountOwner": "Vlasnik računa",
"rallyBudgetCategoryCoffeeShops": "Kafići",
"rallyBudgetCategoryGroceries": "Namirnice",
"shrineProductCeriseScallopTee": "Tamnoroza majica sa zaobljenim rubom",
"rallyBudgetCategoryClothing": "Odjeća",
"rallySettingsManageAccounts": "Upravljajte računima",
"rallyAccountDataCarSavings": "Štednja za automobil",
"rallySettingsTaxDocuments": "Porezni dokumenti",
"rallySettingsPasscodeAndTouchId": "Šifra i Touch ID",
"rallySettingsNotifications": "Obavještenja",
"rallySettingsPersonalInformation": "Lični podaci",
"rallySettingsPaperlessSettings": "Postavke bez papira",
"rallySettingsFindAtms": "Pronađite bankomate",
"rallySettingsHelp": "Pomoć",
"rallySettingsSignOut": "Odjava",
"rallyAccountTotal": "Ukupno",
"rallyBillsDue": "Rok",
"rallyBudgetLeft": "Preostalo",
"rallyAccounts": "Računi",
"rallyBills": "Računi",
"rallyBudgets": "Budžeti",
"rallyAlerts": "Obavještenja",
"rallySeeAll": "PRIKAŽI SVE",
"rallyFinanceLeft": "PREOSTALO",
"rallyTitleOverview": "PREGLED",
"shrineProductShoulderRollsTee": "Majica s podvrnutim rukavima",
"shrineNextButtonCaption": "NAPRIJED",
"rallyTitleBudgets": "BUDŽETI",
"rallyTitleSettings": "POSTAVKE",
"rallyLoginLoginToRally": "Prijavite se u aplikaciju Rally",
"rallyLoginNoAccount": "Nemate račun?",
"rallyLoginSignUp": "REGISTRACIJA",
"rallyLoginUsername": "Korisničko ime",
"rallyLoginPassword": "Lozinka",
"rallyLoginLabelLogin": "Prijava",
"rallyLoginRememberMe": "Zapamti me",
"rallyLoginButtonLogin": "PRIJAVA",
"rallyAlertsMessageHeadsUpShopping": "Pažnja! Iskoristili ste {percent} budžeta za kupovinu za ovaj mjesec.",
"rallyAlertsMessageSpentOnRestaurants": "Ove sedmice ste potrošili {amount} na restorane.",
"rallyAlertsMessageATMFees": "Ovog mjeseca ste potrošili {amount} na naknade bankomata",
"rallyAlertsMessageCheckingAccount": "Odlično! Na tekućem računu imate {percent} više nego prošlog mjeseca.",
"shrineMenuCaption": "MENI",
"shrineCategoryNameAll": "SVE",
"shrineCategoryNameAccessories": "ODJEVNI DODACI",
"shrineCategoryNameClothing": "ODJEĆA",
"shrineCategoryNameHome": "Tipka DOM",
"shrineLoginUsernameLabel": "Korisničko ime",
"shrineLoginPasswordLabel": "Lozinka",
"shrineCancelButtonCaption": "OTKAŽI",
"shrineCartTaxCaption": "Porez:",
"shrineCartPageCaption": "KORPA",
"shrineProductQuantity": "Količina: {quantity}",
"shrineProductPrice": "x {price}",
"shrineCartItemCount": "{quantity,plural,=0{NEMA STAVKI}=1{1 STAVKA}few{{quantity} STAVKE}other{{quantity} STAVKI}}",
"shrineCartClearButtonCaption": "ISPRAZNI KORPU",
"shrineCartTotalCaption": "UKUPNO",
"shrineCartSubtotalCaption": "Međuzbir:",
"shrineCartShippingCaption": "Isporuka:",
"shrineProductGreySlouchTank": "Siva majica bez rukava",
"shrineProductStellaSunglasses": "Sunčane naočale Stella",
"shrineProductWhitePinstripeShirt": "Prugasta bijela košulja",
"demoTextFieldWhereCanWeReachYou": "Putem kojeg broja vas možemo kontaktirati?",
"settingsTextDirectionLTR": "Slijeva nadesno",
"settingsTextScalingLarge": "Veliko",
"demoBottomSheetHeader": "Zaglavlje",
"demoBottomSheetItem": "Stavka {value}",
"demoBottomTextFieldsTitle": "Polja za tekst",
"demoTextFieldTitle": "Polja za tekst",
"demoTextFieldSubtitle": "Jedan red teksta i brojeva koji se mogu uređivati",
"demoTextFieldDescription": "Polja za tekst omogućavaju korisnicima da unesu tekst u korisnički interfejs. Obično su u obliku obrazaca i dijaloških okvira.",
"demoTextFieldShowPasswordLabel": "Prikaži lozinku",
"demoTextFieldHidePasswordLabel": "Sakrivanje lozinke",
"demoTextFieldFormErrors": "Prije slanja, ispravite greške označene crvenom bojom.",
"demoTextFieldNameRequired": "Ime je obavezno.",
"demoTextFieldOnlyAlphabeticalChars": "Unesite samo slova abecede.",
"demoTextFieldEnterUSPhoneNumber": "(###) ###-#### – unesite broj telefona u SAD-u.",
"demoTextFieldEnterPassword": "Unesite lozinku.",
"demoTextFieldPasswordsDoNotMatch": "Lozinke se ne podudaraju",
"demoTextFieldWhatDoPeopleCallYou": "Kako vas drugi zovu?",
"demoTextFieldNameField": "Ime i prezime*",
"demoBottomSheetButtonText": "PRIKAŽI DONJU TABELU",
"demoTextFieldPhoneNumber": "Broj telefona*",
"demoBottomSheetTitle": "Donja tabela",
"demoTextFieldEmail": "Adresa e-pošte",
"demoTextFieldTellUsAboutYourself": "Recite nam nešto o sebi (npr. napišite čime se bavite ili koji su vam hobiji)",
"demoTextFieldKeepItShort": "Neka bude kratko, ovo je samo demonstracija.",
"starterAppGenericButton": "DUGME",
"demoTextFieldLifeStory": "Životna priča",
"demoTextFieldSalary": "Plata",
"demoTextFieldUSD": "USD",
"demoTextFieldNoMoreThan": "Ne možete unijeti više od 8 znakova.",
"demoTextFieldPassword": "Lozinka*",
"demoTextFieldRetypePassword": "Ponovo unesite lozinku*",
"demoTextFieldSubmit": "POŠALJI",
"demoBottomNavigationSubtitle": "Donja navigacija koja se postupno prikazuje i nestaje",
"demoBottomSheetAddLabel": "Dodajte",
"demoBottomSheetModalDescription": "Modalna donja tabela je alternativa meniju ili dijaloškom okviru i onemogućava korisnicima interakciju s ostatkom aplikacije.",
"demoBottomSheetModalTitle": "Modalna donja tabela",
"demoBottomSheetPersistentDescription": "Fiksna donja tabela prikazuje informacije koje nadopunjuju primarni sadržaj aplikacije. Fiksna donja tabela ostaje vidljiva čak i tokom interakcije korisnika s drugim dijelovima aplikacije.",
"demoBottomSheetPersistentTitle": "Fiksna donja tabela",
"demoBottomSheetSubtitle": "Fiksna i modalna donja tabela",
"demoTextFieldNameHasPhoneNumber": "Broj telefona korisnika {name} je {phoneNumber}",
"buttonText": "DUGME",
"demoTypographyDescription": "Definicije raznih tipografskih stilova u materijalnom dizajnu.",
"demoTypographySubtitle": "Svi unaprijed definirani stilovi teksta",
"demoTypographyTitle": "Tipografija",
"demoFullscreenDialogDescription": "Funkcija fullscreenDialog određuje da li se sljedeća stranica otvara u dijaloškom okviru preko cijelog ekrana",
"demoFlatButtonDescription": "Ravno dugme prikazuje mrlju od tinte kada ga pritisnete, ali se ne podiže. Koristite ravnu dugmad na alatnim trakama, u dijalozijma i u tekstu s razmakom",
"demoBottomNavigationDescription": "Donje navigacijske trake prikazuju tri do pet odredišta na dnu ekrana. Svako odredište predstavlja ikona i tekstualna oznaka koja nije obavezna. Kada korisnik dodirne ikonu donje navigacije, otvorit će se odredište navigacije na najvišem nivou povezano s tom ikonom.",
"demoBottomNavigationSelectedLabel": "Odabrana oznaka",
"demoBottomNavigationPersistentLabels": "Fiksne oznake",
"starterAppDrawerItem": "Stavka {value}",
"demoTextFieldRequiredField": "* označava obavezno polje",
"demoBottomNavigationTitle": "Donja navigacija",
"settingsLightTheme": "Svijetla",
"settingsTheme": "Tema",
"settingsPlatformIOS": "iOS",
"settingsPlatformAndroid": "Android",
"settingsTextDirectionRTL": "Zdesna nalijevo",
"settingsTextScalingHuge": "Ogromno",
"cupertinoButton": "Dugme",
"settingsTextScalingNormal": "Normalno",
"settingsTextScalingSmall": "Malo",
"settingsSystemDefault": "Sistem",
"settingsTitle": "Postavke",
"rallyDescription": "Aplikacija za lične finansije",
"aboutDialogDescription": "Da vidite izvorni kôd za ovu aplikaciju, posjetite {repoLink}.",
"bottomNavigationCommentsTab": "Komentari",
"starterAppGenericBody": "Glavni tekst",
"starterAppGenericHeadline": "Naslov",
"starterAppGenericSubtitle": "Titlovi",
"starterAppGenericTitle": "Naslov",
"starterAppTooltipSearch": "Pretražite",
"starterAppTooltipShare": "Dijeljenje",
"starterAppTooltipFavorite": "Omiljeno",
"starterAppTooltipAdd": "Dodajte",
"bottomNavigationCalendarTab": "Kalendar",
"starterAppDescription": "Prilagodljiv izgled aplikacije za pokretanje",
"starterAppTitle": "Aplikacija za pokretanje",
"aboutFlutterSamplesRepo": "Spremište primjera za Flutter na GitHubu",
"bottomNavigationContentPlaceholder": "Rezervirano mjesto za karticu {title}",
"bottomNavigationCameraTab": "Kamera",
"bottomNavigationAlarmTab": "Alarm",
"bottomNavigationAccountTab": "Račun",
"demoTextFieldYourEmailAddress": "Vaša adresa e-pošte",
"demoToggleButtonDescription": "Dugmad za uključivanje/isključivanje može se koristiti za grupisanje srodnih opcija. Da naglasite grupe srodne dugmadi za uključivanje/isključivanje, grupa treba imati zajednički spremnik",
"colorsGrey": "SIVA",
"colorsBrown": "SMEĐA",
"colorsDeepOrange": "JAKA NARANDŽASTA",
"colorsOrange": "NARANDŽASTA",
"colorsAmber": "TAMNOŽUTA",
"colorsYellow": "ŽUTA",
"colorsLime": "ŽUTOZELENA",
"colorsLightGreen": "SVIJETLOZELENA",
"colorsGreen": "ZELENA",
"homeHeaderGallery": "Galerija",
"homeHeaderCategories": "Kategorije",
"shrineDescription": "Moderna aplikacija za maloprodaju",
"craneDescription": "Personalizirana aplikacija za putovanja",
"homeCategoryReference": "STILOVI I DRUGO",
"demoInvalidURL": "Prikazivanje URL-a nije uspjelo:",
"demoOptionsTooltip": "Opcije",
"demoInfoTooltip": "Informacije",
"demoCodeTooltip": "Kôd za demo verziju",
"demoDocumentationTooltip": "Dokumentacija za API",
"demoFullscreenTooltip": "Cijeli ekran",
"settingsTextScaling": "Promjena veličine teksta",
"settingsTextDirection": "Smjer unosa teksta",
"settingsLocale": "Jezik/zemlja",
"settingsPlatformMechanics": "Mehanika platforme",
"settingsDarkTheme": "Tamna",
"settingsSlowMotion": "Usporeni snimak",
"settingsAbout": "O usluzi Flutter Gallery",
"settingsFeedback": "Pošalji povratne informacije",
"settingsAttribution": "Dizajnirala agencija TOASTER iz Londona",
"demoButtonTitle": "Dugmad",
"demoButtonSubtitle": "Tekst, izdignut, ocrtan i još mnogo toga",
"demoFlatButtonTitle": "Ravno dugme",
"demoRaisedButtonDescription": "Izdignuta dugmad daje trodimenzionalni izgled uglavnom ravnim prikazima. Ona naglašava funkcije u prostorima s puno elemenata ili širokim prostorima.",
"demoRaisedButtonTitle": "Izdignuto dugme",
"demoOutlineButtonTitle": "Ocrtano dugme",
"demoOutlineButtonDescription": "Ocrtana dugmad postaje neprozirna i podiže se kada se pritisne. Obično se uparuje s izdignutom dugmadi kako bi se ukazalo na alternativnu, sekundarnu radnju.",
"demoToggleButtonTitle": "Dugmad za uključivanje/isključivanje",
"colorsTeal": "TIRKIZNA",
"demoFloatingButtonTitle": "Plutajuće dugme za radnju",
"demoFloatingButtonDescription": "Plutajuće dugme za radnju je okrugla ikona dugmeta koja se nalazi iznad sadržaja kako bi istakla primarnu radnju u aplikaciji.",
"demoDialogTitle": "Dijaloški okviri",
"demoDialogSubtitle": "Jednostavno, obavještenje i preko cijelog ekrana",
"demoAlertDialogTitle": "Obavještenje",
"demoAlertDialogDescription": "Dijaloški okvir za obavještenje informira korisnika o situacijama koje zahtijevaju potvrdu. Dijaloški okvir za obavještenje ima neobavezni naslov i neobavezni spisak radnji.",
"demoAlertTitleDialogTitle": "Obavještenje s naslovom",
"demoSimpleDialogTitle": "Jednostavno",
"demoSimpleDialogDescription": "Jednostavni dijaloški okvir korisniku nudi izbor između nekoliko opcija. Jednostavni dijaloški okvir ima neobavezni naslov koji se prikazuje iznad izbora.",
"demoFullscreenDialogTitle": "Preko cijelog ekrana",
"demoCupertinoButtonsTitle": "Dugmad",
"demoCupertinoButtonsSubtitle": "Dugmad u stilu iOS-a",
"demoCupertinoButtonsDescription": "Dugme u stilu iOS-a. Sadrži tekst i/ili ikonu koja nestaje ili se prikazuje kada se dugme dodirne. Opcionalno može imati pozadinu.",
"demoCupertinoAlertsTitle": "Obavještenja",
"demoCupertinoAlertsSubtitle": "Dijaloški okvir za obavještenja u stilu iOS-a",
"demoCupertinoAlertTitle": "Obavještenje",
"demoCupertinoAlertDescription": "Dijaloški okvir za obavještenje informira korisnika o situacijama koje zahtijevaju potvrdu. Dijaloški okvir za obavještenje ima neobavezni naslov, neobavezni sadržaj i neobavezni spisak radnji. Naslov se prikazuje iznad sadržaja, a radnje se prikazuju ispod sadržaja.",
"demoCupertinoAlertWithTitleTitle": "Obavještenje s naslovom",
"demoCupertinoAlertButtonsTitle": "Obavještenje s dugmadi",
"demoCupertinoAlertButtonsOnlyTitle": "Samo dugmad za obavještenje",
"demoCupertinoActionSheetTitle": "Tabela radnji",
"demoCupertinoActionSheetDescription": "Tabela radnji je posebna vrsta obavještenja koja korisniku daje dva ili više izbora u vezi s trenutnim kontekstom. Tabela radnji može imati naslov, dodatnu poruku i spisak radnji.",
"demoColorsTitle": "Boje",
"demoColorsSubtitle": "Sve unaprijed definirane boje",
"demoColorsDescription": "Boja i uzorci boja koji predstavljaju paletu boja materijalnog dizajna.",
"buttonTextEnabled": "ENABLED",
"buttonTextDisabled": "DISABLED",
"buttonTextCreate": "Kreirajte",
"dialogSelectedOption": "Odabrali ste: \"{value}\"",
"dialogDiscardTitle": "Odbaciti nedovršenu verziju?",
"dialogLocationTitle": "Koristiti Googleovu uslugu lokacije?",
"dialogLocationDescription": "Dozvolite da Google pomogne aplikacijama da odrede lokaciju. To podrazumijeva slanje anonimnih podataka o lokaciji Googleu, čak i kada nijedna aplikacija nije pokrenuta.",
"dialogCancel": "OTKAŽI",
"dialogDiscard": "ODBACI",
"dialogDisagree": "NE SLAŽEM SE",
"dialogAgree": "PRIHVATAM",
"dialogSetBackup": "Postavljanje računa za sigurnosne kopije",
"colorsBlueGrey": "PLAVOSIVA",
"dialogShow": "PRIKAŽI DIJALOŠKI OKVIR",
"dialogFullscreenTitle": "DIjaloški okvir preko cijelog ekrana",
"dialogFullscreenSave": "SAČUVAJ",
"dialogFullscreenDescription": "Demo prikaz dijaloškog okvira preko cijelog ekrana",
"cupertinoButtonEnabled": "Enabled",
"cupertinoButtonDisabled": "Disabled",
"cupertinoButtonWithBackground": "S pozadinom",
"cupertinoAlertCancel": "Otkaži",
"cupertinoAlertDiscard": "Odbaci",
"cupertinoAlertLocationTitle": "Dozvoliti \"Mapama\" pristup vašoj lokaciji dok koristite aplikaciju?",
"cupertinoAlertLocationDescription": "Vaša trenutna lokacija bit će prikazana na mapi i koristit će se za smjernice, rezultate pretraživanje stvari u blizini i procjenu trajanja putovanja.",
"cupertinoAlertAllow": "Dozvoli",
"cupertinoAlertDontAllow": "Nemoj dozvoliti",
"cupertinoAlertFavoriteDessert": "Odaberite omiljeni desert",
"cupertinoAlertDessertDescription": "Odaberite omiljenu vrstu deserta s liste u nastavku. Vaš odabir koristit će se za prilagođavanje liste prijedloga restorana u vašem području.",
"cupertinoAlertCheesecake": "Torta sa sirom",
"cupertinoAlertTiramisu": "Tiramisu",
"cupertinoAlertApplePie": "Pita od jabuka",
"cupertinoAlertChocolateBrownie": "Čokoladni kolač",
"cupertinoShowAlert": "Prikaži obavještenje",
"colorsRed": "CRVENA",
"colorsPink": "RUŽIČASTA",
"colorsPurple": "LJUBIČASTA",
"colorsDeepPurple": "TAMNOLJUBIČASTA",
"colorsIndigo": "INDIGO",
"colorsBlue": "PLAVA",
"colorsLightBlue": "SVIJETLOPLAVA",
"colorsCyan": "CIJAN",
"dialogAddAccount": "Dodaj račun",
"Gallery": "Galerija",
"Categories": "Kategorije",
"SHRINE": "SHRINE",
"Basic shopping app": "Osnovna aplikacija za kupovinu",
"RALLY": "RALLY",
"CRANE": "CRANE",
"Travel app": "Aplikacija za putovanja",
"MATERIAL": "MATERIJAL",
"CUPERTINO": "CUPERTINO",
"REFERENCE STYLES & MEDIA": "REFERENTNI STILOVI I MEDIJSKI SADRŽAJ"
}
| gallery/lib/l10n/intl_bs.arb/0 | {
"file_path": "gallery/lib/l10n/intl_bs.arb",
"repo_id": "gallery",
"token_count": 21692
} | 859 |
{
"loading": "Cargando",
"deselect": "Anular a selección",
"select": "Seleccionar",
"selectable": "Pódese seleccionar (pulsación longa)",
"selected": "Seleccionado",
"demo": "Versión de demostración",
"bottomAppBar": "Barra de aplicacións inferior",
"notSelected": "Non seleccionado",
"demoCupertinoSearchTextFieldTitle": "Campo de texto de busca",
"demoCupertinoPicker": "Selector",
"demoCupertinoSearchTextFieldSubtitle": "Campo de texto de busca de tipo iOS",
"demoCupertinoSearchTextFieldDescription": "Un campo de texto que permite que os usuarios fagan buscas poñendo texto. Pode ofrecer e filtrar suxestións.",
"demoCupertinoSearchTextFieldPlaceholder": "Pon texto",
"demoCupertinoScrollbarTitle": "Barra de desprazamento",
"demoCupertinoScrollbarSubtitle": "Barra de desprazamento de tipo iOS",
"demoCupertinoScrollbarDescription": "Unha barra de desprazamento que envolve o elemento secundario en cuestión",
"demoTwoPaneItem": "Elemento {value}",
"demoTwoPaneList": "Lista",
"demoTwoPaneFoldableLabel": "Pregable",
"demoTwoPaneSmallScreenLabel": "Pantalla pequena",
"demoTwoPaneSmallScreenDescription": "Así se comporta TwoPane nun dispositivo cunha pantalla pequena.",
"demoTwoPaneTabletLabel": "Tableta/Escritorio",
"demoTwoPaneTabletDescription": "Así se comporta TwoPane nun dispositivo cunha pantalla máis grande, como unha tableta ou un ordenador.",
"demoTwoPaneTitle": "TwoPane",
"demoTwoPaneSubtitle": "Deseños adaptables en pantallas pregables, grandes e pequenas",
"splashSelectDemo": "Selecciona unha versión de demostración",
"demoTwoPaneFoldableDescription": "Así se comporta TwoPane nun dispositivo pregable.",
"demoTwoPaneDetails": "Detalles",
"demoTwoPaneSelectItem": "Selecciona un elemento",
"demoTwoPaneItemDetails": "Detalles do elemento {value}",
"demoCupertinoContextMenuActionText": "Mantén premido o logotipo de Flutter para ver o menú contextual.",
"demoCupertinoContextMenuDescription": "Un menú contextual de tipo iOS a pantalla completa que aparece ao manter premido un elemento.",
"demoAppBarTitle": "Barra de aplicacións",
"demoAppBarDescription": "Na barra de aplicacións podes atopar contidos e accións relacionados coa pantalla actual. Utilízase para a construción de marca, os títulos de pantallas, a navegación e as accións",
"demoDividerTitle": "Separador",
"demoDividerSubtitle": "Un separador é unha liña fina que agrupa contido en listas e deseños.",
"demoDividerDescription": "Os separadores poden usarse en listas, paneis e outros elementos para separar contido.",
"demoVerticalDividerTitle": "Separador vertical",
"demoCupertinoContextMenuTitle": "Menú contextual",
"demoCupertinoContextMenuSubtitle": "Menú contextual de tipo iOS",
"demoAppBarSubtitle": "Mostra información e accións relacionadas coa pantalla actual",
"demoCupertinoContextMenuActionOne": "Acción 1",
"demoCupertinoContextMenuActionTwo": "Acción 2",
"demoDateRangePickerDescription": "Mostra un cadro de diálogo que inclúe un selector de intervalo de datas de Material Design.",
"demoDateRangePickerTitle": "Selector de intervalo de datas",
"demoNavigationDrawerUserName": "Nome de usuario",
"demoNavigationDrawerUserEmail": "[email protected]",
"demoNavigationDrawerText": "Para ver o panel, pasa o dedo desde o bordo ou toca a icona da parte superior esquerda",
"demoNavigationRailTitle": "Raíl de navegación",
"demoNavigationRailSubtitle": "Móstrase un raíl de navegación dentro dunha aplicación",
"demoNavigationRailDescription": "Un widget de Material Design que se mostra á esquerda ou á dereita dunha aplicación para navegar por un número pequeno de vistas (normalmente 3-5).",
"demoNavigationRailFirst": "Primeiro",
"demoNavigationDrawerTitle": "Panel de navegación",
"demoNavigationRailThird": "Terceiro",
"replyStarredLabel": "Con estrela",
"demoTextButtonDescription": "Os botóns de texto mostran unha salpicadura de tinta ao premelos, pero non sobresaen. Úsaos nas barras de ferramentas, nos cadros de diálogo e inseridos con recheo",
"demoElevatedButtonTitle": "Botón elevado",
"demoElevatedButtonDescription": "Os botóns elevados engaden dimensión a deseños principalmente planos. Destacan funcións en espazos reducidos ou amplos.",
"demoOutlinedButtonTitle": "Botón con contorno",
"demoOutlinedButtonDescription": "Os botóns con contorno vólvense opacos e elévanse ao premelos. Adoitan estar emparellados con botóns con relevo para indicar unha acción secundaria e alternativa.",
"demoContainerTransformDemoInstructions": "Tarxetas, listas e botón de acción flotante",
"demoNavigationDrawerSubtitle": "Móstrase un panel dentro dunha barra de aplicacións",
"replyDescription": "Unha aplicación de correo electrónico eficaz e sen distraccións",
"demoNavigationDrawerDescription": "Un panel de Material Design que aparece desprazándose horizontalmente desde o bordo da pantalla para mostrar ligazóns de navegación nunha aplicación.",
"replyDraftsLabel": "Borradores",
"demoNavigationDrawerToPageOne": "Elemento un",
"replyInboxLabel": "Caixa de entrada",
"demoSharedXAxisDemoInstructions": "Botóns Seguinte e Atrás",
"replySpamLabel": "Spam",
"replyTrashLabel": "Papeleira",
"replySentLabel": "Enviados",
"demoNavigationRailSecond": "Segundo",
"demoNavigationDrawerToPageTwo": "Elemento dous",
"demoFadeScaleDemoInstructions": "Modal e botón de acción flotante",
"demoFadeThroughDemoInstructions": "Navegación da parte inferior",
"demoSharedZAxisDemoInstructions": "Botón da icona de configuración",
"demoSharedYAxisDemoInstructions": "Ordenar por Reproducidas recentemente",
"demoTextButtonTitle": "Botón de texto",
"demoSharedZAxisBeefSandwichRecipeTitle": "Sándwich de carne de vaca",
"demoSharedZAxisDessertRecipeDescription": "Receita de sobremesa",
"demoSharedYAxisAlbumTileSubtitle": "Artista",
"demoSharedYAxisAlbumTileTitle": "Álbum",
"demoSharedYAxisRecentSortTitle": "Reproducións recentes",
"demoSharedYAxisAlphabeticalSortTitle": "A-Z",
"demoSharedYAxisAlbumCount": "268 álbums",
"demoSharedYAxisTitle": "Eixe y compartido",
"demoSharedXAxisCreateAccountButtonText": "CREAR CONTA",
"demoFadeScaleAlertDialogDiscardButton": "DESCARTAR",
"demoSharedXAxisSignInTextFieldLabel": "Correo electrónico ou número de teléfono",
"demoSharedXAxisSignInSubtitleText": "Inicia sesión coa túa conta",
"demoSharedXAxisSignInWelcomeText": "Ola, David Park",
"demoSharedXAxisIndividualCourseSubtitle": "Mostrado individualmente",
"demoSharedXAxisBundledCourseSubtitle": "Agrupado",
"demoFadeThroughAlbumsDestination": "Álbums",
"demoSharedXAxisDesignCourseTitle": "Deseño",
"demoSharedXAxisIllustrationCourseTitle": "Ilustración",
"demoSharedXAxisBusinessCourseTitle": "Empresa",
"demoSharedXAxisArtsAndCraftsCourseTitle": "Artesanía",
"demoMotionPlaceholderSubtitle": "Texto secundario",
"demoFadeScaleAlertDialogCancelButton": "CANCELAR",
"demoFadeScaleAlertDialogHeader": "Diálogo da alerta",
"demoFadeScaleHideFabButton": "OCULTAR BOTÓN DE ACCIÓN FLOTANTE",
"demoFadeScaleShowFabButton": "MOSTRAR BOTÓN DE ACCIÓN FLOTANTE",
"demoFadeScaleShowAlertDialogButton": "MOSTRAR MODAL",
"demoFadeScaleDescription": "O padrón de atenuación utilízase para elementos da IU que entran ou saen do límite da pantalla, como un cadro de diálogo que se atenúa no centro da pantalla.",
"demoFadeScaleTitle": "Atenuar",
"demoFadeThroughTextPlaceholder": "123 fotos",
"demoFadeThroughSearchDestination": "Buscar",
"demoFadeThroughPhotosDestination": "Fotos",
"demoSharedXAxisCoursePageSubtitle": "As categorías integradas aparecen como grupos no teu feed. Sempre podes cambiar esta opción máis tarde.",
"demoFadeThroughDescription": "O padrón de esvaecemento utilízase para transicións entre os elementos da IU que non teñen unha relación forte entre si.",
"demoFadeThroughTitle": "Esvaecer",
"demoSharedZAxisHelpSettingLabel": "Axuda",
"demoMotionSubtitle": "Todos os padróns de transición predefinidos",
"demoSharedZAxisNotificationSettingLabel": "Notificacións",
"demoSharedZAxisProfileSettingLabel": "Perfil",
"demoSharedZAxisSavedRecipesListTitle": "Receitas gardadas",
"demoSharedZAxisBeefSandwichRecipeDescription": "Receita de sándwich de carne de vaca",
"demoSharedZAxisCrabPlateRecipeDescription": "Receita de prato de cangrexo",
"demoSharedXAxisCoursePageTitle": "Optimiza as túas accións",
"demoSharedZAxisCrabPlateRecipeTitle": "Cangrexo",
"demoSharedZAxisShrimpPlateRecipeDescription": "Receita de prato de camarón",
"demoSharedZAxisShrimpPlateRecipeTitle": "Camarón",
"demoContainerTransformTypeFadeThrough": "ESVAECER",
"demoSharedZAxisDessertRecipeTitle": "Sobremesa",
"demoSharedZAxisSandwichRecipeDescription": "Receita de sándwich",
"demoSharedZAxisSandwichRecipeTitle": "Sándwich",
"demoSharedZAxisBurgerRecipeDescription": "Receita de hamburguesa",
"demoSharedZAxisBurgerRecipeTitle": "Hamburguesa",
"demoSharedZAxisSettingsPageTitle": "Configuración",
"demoSharedZAxisTitle": "Eixe z compartido",
"demoSharedZAxisPrivacySettingLabel": "Privacidade",
"demoMotionTitle": "Movemento",
"demoContainerTransformTitle": "Transformación de contedores",
"demoContainerTransformDescription": "O padrón de transformación de contedores está deseñado para transicións entre elementos da IU que inclúen un contedor. Este padrón crea unha conexión visible entre dous elementos da IU",
"demoContainerTransformModalBottomSheetTitle": "Modo de esvaecemento",
"demoContainerTransformTypeFade": "ATENUAR",
"demoSharedYAxisAlbumTileDurationUnit": "min",
"demoMotionPlaceholderTitle": "Título",
"demoSharedXAxisForgotEmailButtonText": "ESQUECICHES O CORREO ELECTRÓNICO?",
"demoMotionSmallPlaceholderSubtitle": "Secundario",
"demoMotionDetailsPageTitle": "Páxina de detalles",
"demoMotionListTileTitle": "Elemento de lista",
"demoSharedAxisDescription": "O padrón do eixe compartido utilízase para transicións entre os elementos da IU que teñen unha relación espacial ou de navegación. Este padrón utiliza unha transformación compartida no eixe x, y ou z para reforzar a relación entre os elementos.",
"demoSharedXAxisTitle": "Eixe x compartido",
"demoSharedXAxisBackButtonText": "ATRÁS",
"demoSharedXAxisNextButtonText": "SEGUINTE",
"demoSharedXAxisCulinaryCourseTitle": "Cociña",
"githubRepo": "almacén de GitHub de {repoName}",
"fortnightlyMenuUS": "Estados Unidos",
"fortnightlyMenuBusiness": "Negocios",
"fortnightlyMenuScience": "Ciencia",
"fortnightlyMenuSports": "Deportes",
"fortnightlyMenuTravel": "Viaxes",
"fortnightlyMenuCulture": "Cultura",
"fortnightlyTrendingTechDesign": "DeseñoDeTecnoloxía",
"rallyBudgetDetailAmountLeft": "Importe restante",
"fortnightlyHeadlineArmy": "Reformando o Exército Verde desde dentro",
"fortnightlyDescription": "Unha aplicación de noticias centrada no contido",
"rallyBillDetailAmountDue": "Importe debido",
"rallyBudgetDetailTotalCap": "Límite total",
"rallyBudgetDetailAmountUsed": "Importe utilizado",
"fortnightlyTrendingHealthcareRevolution": "RevoluciónDaSanidade",
"fortnightlyMenuFrontPage": "Portada",
"fortnightlyMenuWorld": "Internacional",
"rallyBillDetailAmountPaid": "Importe pagado",
"fortnightlyMenuPolitics": "Política",
"fortnightlyHeadlineBees": "As abellas das terras de cultivo están en perigo de extinción",
"fortnightlyHeadlineGasoline": "O futuro da gasolina",
"fortnightlyTrendingGreenArmy": "ExércitoVerde",
"fortnightlyHeadlineFeminists": "O feminismo únese á causa",
"fortnightlyHeadlineFabrics": "Os deseñadores utilizan a tecnoloxía para crear tecidos futuristas",
"fortnightlyHeadlineStocks": "A medida que se estancan as accións, moitos miran a moeda",
"fortnightlyTrendingReform": "Reforma",
"fortnightlyMenuTech": "Tecnoloxía",
"fortnightlyHeadlineWar": "Vidas estadounidenses divididas durante a guerra",
"fortnightlyHeadlineHealthcare": "A revolución silenciosa e firme da sanidade",
"fortnightlyLatestUpdates": "Últimas novidades",
"fortnightlyTrendingStocks": "Accións",
"rallyBillDetailTotalAmount": "Importe total",
"demoCupertinoPickerDateTime": "Data e hora",
"signIn": "INICIAR SESIÓN",
"dataTableRowWithSugar": "{value} con azucre",
"dataTableRowApplePie": "Torta de mazá",
"dataTableRowDonut": "Rosca",
"dataTableRowHoneycomb": "Panal",
"dataTableRowLollipop": "Piruleta",
"dataTableRowJellyBean": "Gominola",
"dataTableRowGingerbread": "Galleta de xenxibre",
"dataTableRowCupcake": "Madalena",
"dataTableRowEclair": "Eclair",
"dataTableRowIceCreamSandwich": "Xeado",
"dataTableRowFrozenYogurt": "Iogur conxelado",
"dataTableColumnIron": "Ferro (%)",
"dataTableColumnCalcium": "Calcio (%)",
"dataTableColumnSodium": "Sodio (mg)",
"demoTimePickerTitle": "Selector de hora",
"demo2dTransformationsResetTooltip": "Restablecer as transformacións",
"dataTableColumnFat": "Graxas (g)",
"dataTableColumnCalories": "Calorías",
"dataTableColumnDessert": "Sobremesa (1 ración)",
"cardsDemoTravelDestinationLocation1": "Thanjavur, Tamil Nadu",
"demoTimePickerDescription": "Mostra un cadro de diálogo que inclúe un selector de data de Material Design.",
"demoPickersShowPicker": "MOSTRAR SELECTOR",
"demoTabsScrollingTitle": "Desprázase",
"demoTabsNonScrollingTitle": "Non se despraza",
"craneHours": "{hours,plural,=1{1 h}other{{hours} h}}",
"craneMinutes": "{minutes,plural,=1{1 min}other{{minutes} min}}",
"craneFlightDuration": "{hoursShortForm} e {minutesShortForm}",
"dataTableHeader": "Nutrición",
"demoDatePickerTitle": "Selector de data",
"demoPickersSubtitle": "Selección de data e hora",
"demoPickersTitle": "Selectores",
"demo2dTransformationsEditTooltip": "Editar o mosaico",
"demoDataTableDescription": "As táboas de datos mostran información en forma de grades distribuídas en filas e columnas, o que facilita a busca de datos e a visualización de padróns e tendencias.",
"demo2dTransformationsDescription": "Toca para editar os mosaicos e utiliza xestos para moverte pola escena. Arrastra para desprazarte, belisca para usar o zoom e xira con dous dedos. Toca o botón de restablecer para volver á orientación inicial.",
"demo2dTransformationsSubtitle": "Despraza, usa o zoom e xira",
"demo2dTransformationsTitle": "Transformacións 2D",
"demoCupertinoTextFieldPIN": "PIN",
"demoCupertinoTextFieldDescription": "Un campo de texto utilízase para escribir texto ben cun teclado físico, ben cun teclado en pantalla.",
"demoCupertinoTextFieldSubtitle": "Campos de texto de tipo iOS",
"demoCupertinoTextFieldTitle": "Campos de texto",
"demoDatePickerDescription": "Mostra un cadro de diálogo que inclúe un selector de data de Material Design.",
"demoCupertinoPickerTime": "Hora",
"demoCupertinoPickerDate": "Data",
"demoCupertinoPickerTimer": "Temporizador",
"demoCupertinoPickerDescription": "Widget de selector de tipo iOS que se pode usar para seleccionar cadeas, datas, horas ou datas e horas.",
"demoCupertinoPickerSubtitle": "Selectores de tipo iOS",
"demoCupertinoPickerTitle": "Selectores",
"dataTableRowWithHoney": "{value} con mel",
"cardsDemoTravelDestinationCity2": "Chettinad",
"bannerDemoResetText": "Restablecer o báner",
"bannerDemoMultipleText": "Varias accións",
"bannerDemoLeadingText": "Icona que precede o texto",
"dismiss": "IGNORAR",
"cardsDemoTappable": "Pódese tocar",
"cardsDemoSelectable": "Pódese seleccionar (pulsación longa)",
"cardsDemoExplore": "Explorar",
"cardsDemoExploreSemantics": "Explorar: {destinationName}",
"cardsDemoShareSemantics": "Compartir: {destinationName}",
"cardsDemoTravelDestinationTitle1": "10 cidades de visita obrigada en Tamil Nadu",
"cardsDemoTravelDestinationDescription1": "Número 10",
"cardsDemoTravelDestinationCity1": "Thanjavur",
"dataTableColumnProtein": "Proteínas (g))",
"cardsDemoTravelDestinationTitle2": "Artesáns da India meridional",
"cardsDemoTravelDestinationDescription2": "Rodas de fiar seda",
"bannerDemoText": "Actualizouse o teu contrasinal no teu outro dispositivo. Inicia sesión de novo.",
"cardsDemoTravelDestinationLocation2": "Sivaganga, Tamil Nadu",
"cardsDemoTravelDestinationTitle3": "Templo de Brihadisvara",
"cardsDemoTravelDestinationDescription3": "Templos",
"demoBannerTitle": "Báner",
"demoBannerSubtitle": "Visualización dun báner nunha lista",
"demoBannerDescription": "Un báner mostra unha mensaxe importante e concisa, así como accións que poden levar a cabo os usuarios (ou unha opción para ignorar o báner). O usuario debe realizar unha acción para ignoralo.",
"demoCardTitle": "Tarxetas",
"demoCardSubtitle": "Tarxetas básicas con esquinas en forma redonda",
"demoCardDescription": "Unha tarxeta é un cadro utilizado para representar información relacionada, por exemplo, un álbum, unha localización xeográfica, unha comida, os datos de contacto etc.",
"demoDataTableTitle": "Táboas de datos",
"demoDataTableSubtitle": "Filas e columnas de información",
"dataTableColumnCarbs": "Carbohidratos (g)",
"placeTanjore": "Thanjavur",
"demoGridListsTitle": "Listas con grade",
"placeFlowerMarket": "Mercado de flores",
"placeBronzeWorks": "Fundición de bronce",
"placeMarket": "Mercado",
"placeThanjavurTemple": "Templo de Thanjavur",
"placeSaltFarm": "Salina",
"placeScooters": "Motos",
"placeSilkMaker": "Fabricante de seda",
"placeLunchPrep": "Preparación da comida",
"placeBeach": "Praia",
"placeFisherman": "Pescador",
"demoMenuSelected": "Seleccionado: {value}",
"demoMenuRemove": "Quitar",
"demoMenuGetLink": "Obter ligazón",
"demoMenuShare": "Compartir",
"demoBottomAppBarSubtitle": "Mostra a navegación e as accións na parte inferior",
"demoMenuAnItemWithASectionedMenu": "Un elemento cun menú con seccións",
"demoMenuADisabledMenuItem": "Elemento de menú desactivado",
"demoLinearProgressIndicatorTitle": "Indicador de progreso lineal",
"demoMenuContextMenuItemOne": "Elemento do menú contextual un",
"demoMenuAnItemWithASimpleMenu": "Un elemento cun menú simple",
"demoCustomSlidersTitle": "Controis desprazables personalizados",
"demoMenuAnItemWithAChecklistMenu": "Un elemento cun menú con lista de comprobación",
"demoCupertinoActivityIndicatorTitle": "Indicador de actividade",
"demoCupertinoActivityIndicatorSubtitle": "Indicador de actividade de tipo iOS",
"demoCupertinoActivityIndicatorDescription": "Un indicador de actividade de tipo iOS que xira cara á dereita.",
"demoCupertinoNavigationBarTitle": "Barra de navegación",
"demoCupertinoNavigationBarSubtitle": "Barra de navegación de tipo iOS",
"demoCupertinoNavigationBarDescription": "Unha barra de navegación de tipo iOS. A barra de navegación é unha barra de ferramentas que basicamente contén o título dunha páxina no medio da barra de ferramentas.",
"demoCupertinoPullToRefreshTitle": "Arrastrar cara abaixo para actualizar",
"demoCupertinoPullToRefreshSubtitle": "Control de arrastrar para actualizar de tipo iOS",
"demoCupertinoPullToRefreshDescription": "Un widget que implementa o control de contido de arrastrar para actualizar de tipo iOS.",
"demoProgressIndicatorTitle": "Indicadores de progreso",
"demoProgressIndicatorSubtitle": "Lineais, circulares e indeterminados",
"demoCircularProgressIndicatorTitle": "Indicador de progreso circular",
"demoCircularProgressIndicatorDescription": "Un indicador de progreso circular de Material Design que xira para indicar que a aplicación está ocupada.",
"demoMenuFour": "Catro",
"demoLinearProgressIndicatorDescription": "Un indicador de progreso lineal de Material Design, tamén coñecido como barra de progreso.",
"demoTooltipTitle": "Cadros de información",
"demoTooltipSubtitle": "Mensaxe curta que se mostra ao manter premido un elemento ou ao pasar por enriba del",
"demoTooltipDescription": "Os cadros de información proporcionan etiquetas de texto que axudan a explicar a función dun botón ou outra acción da interface de usuario. Amosan texto informativo cando os usuarios pasan por enriba dun elemento, se centran nel ou o manteñen premido.",
"demoTooltipInstructions": "Para mostrar o cadro de información, mantén premido o elemento ou pasa por enriba del",
"placeChennai": "Chennai",
"demoMenuChecked": "Marcado: {value}",
"placeChettinad": "Chettinad",
"demoMenuPreview": "Vista previa",
"demoBottomAppBarTitle": "Barra de aplicacións inferior",
"demoBottomAppBarDescription": "Coas barras de aplicacións inferiores pódese acceder a un panel de navegación inferior e como máximo a catro accións, incluído o botón de acción flotante.",
"bottomAppBarNotch": "Rañura",
"bottomAppBarPosition": "Posición do botón de acción flotante",
"bottomAppBarPositionDockedEnd": "Ancorado (final)",
"bottomAppBarPositionDockedCenter": "Ancorado (centro)",
"bottomAppBarPositionFloatingEnd": "Flotante (final)",
"bottomAppBarPositionFloatingCenter": "Flotante (centro)",
"demoSlidersEditableNumericalValue": "Valor numérico editable",
"demoGridListsSubtitle": "Deseño de columnas e filas",
"demoGridListsDescription": "As listas con grade son as máis adecuadas para presentar datos homoxéneos, normalmente imaxes. Os elementos das listas con grade chámanse mosaicos.",
"demoGridListsImageOnlyTitle": "Só imaxes",
"demoGridListsHeaderTitle": "Con título",
"demoGridListsFooterTitle": "Con pé de páxina",
"demoSlidersTitle": "Controis desprazables",
"demoSlidersSubtitle": "Widgets para seleccionar un valor ao pasar o dedo",
"demoSlidersDescription": "Os controis desprazables reflicten un intervalo de valores ao longo dunha barra e os usuarios só poden seleccionar un valor. Son ideais para axustar opcións de configuración (como o volume ou o brillo) ou para aplicar filtros de imaxe.",
"demoRangeSlidersTitle": "Controis desprazables de intervalos",
"demoRangeSlidersDescription": "Os controis desprazables reflicten un intervalo de valores ao longo dunha barra. Poden ter iconas en ambos os extremos da barra para mostrar un intervalo de valores. Son ideais para axustar opcións de configuración (como o volume ou o brillo) ou para aplicar filtros de imaxe.",
"demoMenuAnItemWithAContextMenuButton": "Un elemento cun menú contextual",
"demoCustomSlidersDescription": "Os controis desprazables reflicten un intervalo de valores ao longo dunha barra e os usuarios poden seleccionar un valor ou un intervalo deles. Os controis desprazables poden estar personalizados ou incluír temas.",
"demoSlidersContinuousWithEditableNumericalValue": "Continuo cun valor numérico editable",
"demoSlidersDiscrete": "Descontinuo",
"demoSlidersDiscreteSliderWithCustomTheme": "Control desprazable descontinuo con tema personalizado",
"demoSlidersContinuousRangeSliderWithCustomTheme": "Control desprazable de intervalo continuo con tema personalizado",
"demoSlidersContinuous": "Continuo",
"placePondicherry": "Puducherry",
"demoMenuTitle": "Menú",
"demoContextMenuTitle": "Menú contextual",
"demoSectionedMenuTitle": "Menú con seccións",
"demoSimpleMenuTitle": "Menú simple",
"demoChecklistMenuTitle": "Menú con lista de comprobación",
"demoMenuSubtitle": "Botóns de menú e menús simples",
"demoMenuDescription": "Un menú mostra unha lista de opcións nunha superficie temporal e aparece cando os usuarios interactúan cun botón, cunha acción ou con outro control.",
"demoMenuItemValueOne": "Elemento do menú un",
"demoMenuItemValueTwo": "Elemento do menú dous",
"demoMenuItemValueThree": "Elemento do menú tres",
"demoMenuOne": "Un",
"demoMenuTwo": "Dúas",
"demoMenuThree": "Tres",
"demoMenuContextMenuItemThree": "Elemento do menú contextual tres",
"demoCupertinoSwitchSubtitle": "Interruptor de tipo iOS",
"demoSnackbarsText": "Esta é unha barra de notificacións.",
"demoCupertinoSliderSubtitle": "Control desprazable de tipo iOS",
"demoCupertinoSliderDescription": "Os controis desprazables poden usarse para un conxunto de valores continuo ou descontinuo.",
"demoCupertinoSliderContinuous": "Continuo: {value}",
"demoCupertinoSliderDiscrete": "Descontinuo: {value}",
"demoSnackbarsAction": "Premiches a acción da barra de notificacións.",
"backToGallery": "Volver á galería",
"demoCupertinoTabBarTitle": "Barra de pestanas",
"demoCupertinoSwitchDescription": "Os interruptores utilízanse para activar e desactivar o estado dunha soa opción de configuración.",
"demoSnackbarsActionButtonLabel": "ACCIÓN",
"cupertinoTabBarProfileTab": "Perfil",
"demoSnackbarsButtonLabel": "MOSTRAR UNHA BARRA DE NOTIFICACIÓNS",
"demoSnackbarsDescription": "As barras de notificacións aparecen temporalmente na parte inferior da pantalla e ofrecen información aos usuarios sobre os procesos que unha aplicación executou ou executará. Non deberían interferir na experiencia do usuario e desaparecen da pantalla por si soas.",
"demoSnackbarsSubtitle": "As barras de notificacións mostran mensaxes na parte inferior da pantalla",
"demoSnackbarsTitle": "Barras de notificacións",
"demoCupertinoSliderTitle": "Control desprazable",
"cupertinoTabBarChatTab": "Chat",
"cupertinoTabBarHomeTab": "Inicio",
"demoCupertinoTabBarDescription": "Unha barra de pestanas de navegación de tipo iOS situada na parte inferior. Mostra varias pestanas e só unha delas está activa: a primeira de forma predeterminada.",
"demoCupertinoTabBarSubtitle": "Barra de pestanas inferior de tipo iOS",
"demoOptionsFeatureTitle": "Ver opcións",
"demoOptionsFeatureDescription": "Toca aquí para ver as opcións dispoñibles nesta demostración.",
"demoCodeViewerCopyAll": "COPIAR TODO",
"shrineScreenReaderRemoveProductButton": "Quitar {product}",
"shrineScreenReaderProductAddToCart": "Engadir á cesta",
"shrineScreenReaderCart": "{quantity,plural,=0{Cesta da compra (sen artigos)}=1{Cesta da compra (1 artigo)}other{Cesta da compra ({quantity} artigos)}}",
"demoCodeViewerFailedToCopyToClipboardMessage": "Produciuse un erro ao copiar o contido no portapapeis: {error}",
"demoCodeViewerCopiedToClipboardMessage": "Copiouse o contido no portapapeis.",
"craneSleep8SemanticLabel": "Ruínas maias no alto dun cantil xunto a unha praia",
"craneSleep4SemanticLabel": "Hotel á beira dun lago e fronte ás montañas",
"craneSleep2SemanticLabel": "Cidadela de Machu Picchu",
"craneSleep1SemanticLabel": "Chalé nunha paisaxe nevada con árbores de folla perenne",
"craneSleep0SemanticLabel": "Cabanas flotantes",
"craneFly13SemanticLabel": "Piscina xunto ao mar con palmeiras",
"craneFly12SemanticLabel": "Piscina con palmeiras",
"craneFly11SemanticLabel": "Faro de ladrillos xunto ao mar",
"craneFly10SemanticLabel": "Minaretes da mesquita de al-Azhar ao solpor",
"craneFly9SemanticLabel": "Home apoiado nun coche azul antigo",
"craneFly8SemanticLabel": "Supertree Grove",
"craneEat9SemanticLabel": "Mostrador dunha cafetaría con pastas",
"craneEat2SemanticLabel": "Hamburguesa",
"craneFly5SemanticLabel": "Hotel á beira dun lago e fronte ás montañas",
"demoSelectionControlsSubtitle": "Caixas de verificación, botóns de opción e interruptores",
"craneEat10SemanticLabel": "Muller que suxeita un gran sándwich de pastrami",
"craneFly4SemanticLabel": "Cabanas flotantes",
"craneEat7SemanticLabel": "Entrada dunha panadaría",
"craneEat6SemanticLabel": "Prato con camaróns",
"craneEat5SemanticLabel": "Sala dun restaurante artístico",
"craneEat4SemanticLabel": "Sobremesa con chocolate",
"craneEat3SemanticLabel": "Taco coreano",
"craneFly3SemanticLabel": "Cidadela de Machu Picchu",
"craneEat1SemanticLabel": "Bar baleiro con tallos",
"craneEat0SemanticLabel": "Pizza nun forno de leña",
"craneSleep11SemanticLabel": "Rañaceos Taipei 101",
"craneSleep10SemanticLabel": "Minaretes da mesquita de al-Azhar ao solpor",
"craneSleep9SemanticLabel": "Faro de ladrillos xunto ao mar",
"craneEat8SemanticLabel": "Prato con caranguexos de río",
"craneSleep7SemanticLabel": "Casas coloridas na Praza da Ribeira",
"craneSleep6SemanticLabel": "Piscina con palmeiras",
"craneSleep5SemanticLabel": "Tenda de campaña nun campo",
"settingsButtonCloseLabel": "Pechar configuración",
"demoSelectionControlsCheckboxDescription": "As caixas de verificación permiten que os usuarios seleccionen varias opcións dun conxunto e adoitan ter dous valores (verdadeiro ou falso), pero tamén poden incluír un terceiro (nulo).",
"settingsButtonLabel": "Configuración",
"demoListsTitle": "Listas",
"demoListsSubtitle": "Desprazando deseños de listas",
"demoListsDescription": "Unha única liña de altura fixa que normalmente contén texto así como unha icona ao principio ou ao final.",
"demoOneLineListsTitle": "Unha liña",
"demoTwoLineListsTitle": "Dúas liñas",
"demoListsSecondary": "Texto secundario",
"demoSelectionControlsTitle": "Controis de selección",
"craneFly7SemanticLabel": "Monte Rushmore",
"demoSelectionControlsCheckboxTitle": "Caixa de verificación",
"craneSleep3SemanticLabel": "Home apoiado nun coche azul antigo",
"demoSelectionControlsRadioTitle": "Botón de opción",
"demoSelectionControlsRadioDescription": "Os botóns de opción permiten que os usuarios seleccionen unha opción dun conxunto. Utilízaos se queres que os usuarios escollan unha única opción, pero á vez queres mostrarlles todas as opcións dispoñibles.",
"demoSelectionControlsSwitchTitle": "Interruptor",
"demoSelectionControlsSwitchDescription": "Os interruptores de activación e desactivación controlan o estado dunha soa opción de configuración. A etiqueta inserida do interruptor correspondente debería indicar de forma clara a opción que controla e o estado no que se atopa.",
"craneFly0SemanticLabel": "Chalé nunha paisaxe nevada con árbores de folla perenne",
"craneFly1SemanticLabel": "Tenda de campaña nun campo",
"craneFly2SemanticLabel": "Bandeiras de pregaria fronte a unha montaña nevada",
"craneFly6SemanticLabel": "Vista aérea do Palacio de Belas Artes",
"rallySeeAllAccounts": "Ver todas as contas",
"rallyBillAmount": "A data límite da factura ({billName}) é o {date} e o seu importe é de {amount}.",
"shrineTooltipCloseCart": "Pechar a cesta",
"shrineTooltipCloseMenu": "Pechar o menú",
"shrineTooltipOpenMenu": "Abrir o menú",
"shrineTooltipSettings": "Configuración",
"shrineTooltipSearch": "Buscar",
"demoTabsDescription": "As pestanas permiten organizar o contido en diversas pantallas, conxuntos de datos e outras interaccións.",
"demoTabsSubtitle": "Pestanas con vistas que se poden desprazar de forma independente",
"demoTabsTitle": "Pestanas",
"rallyBudgetAmount": "O orzamento {budgetName} é de {amountTotal}; utilizouse un importe de {amountUsed} e queda unha cantidade de {amountLeft}",
"shrineTooltipRemoveItem": "Quitar o artigo",
"rallyAccountAmount": "A conta {accountNumber} ({accountName}) contén {amount}.",
"rallySeeAllBudgets": "Ver todos os orzamentos",
"rallySeeAllBills": "Ver todas as facturas",
"craneFormDate": "Seleccionar data",
"craneFormOrigin": "Escoller orixe",
"craneFly2": "Val de Khumbu, Nepal",
"craneFly3": "Machu Picchu, Perú",
"craneFly4": "Malé, Maldivas",
"craneFly5": "Vitznau, Suíza",
"craneFly6": "Cidade de México, México",
"craneFly7": "Monte Rushmore, Estados Unidos",
"settingsTextDirectionLocaleBased": "Baseada na configuración rexional",
"craneFly9": "A Habana, Cuba",
"craneFly10": "O Cairo, Exipto",
"craneFly11": "Lisboa, Portugal",
"craneFly12": "Napa, Estados Unidos",
"craneFly13": "Bali, Indonesia",
"craneSleep0": "Malé, Maldivas",
"craneSleep1": "Aspen, Estados Unidos",
"craneSleep2": "Machu Picchu, Perú",
"demoCupertinoSegmentedControlTitle": "Control segmentado",
"craneSleep4": "Vitznau, Suíza",
"craneSleep5": "Big Sur, Estados Unidos",
"craneSleep6": "Napa, Estados Unidos",
"craneSleep7": "Porto, Portugal",
"craneSleep8": "Tulum, México",
"craneEat5": "Seúl, Corea do Sur",
"demoChipTitle": "Etiquetas",
"demoChipSubtitle": "Elementos compactos que representan atributos, accións ou entradas de texto",
"demoActionChipTitle": "Etiqueta de acción",
"demoActionChipDescription": "As pílulas de acción son un conxunto de opcións que permiten levar a cabo tarefas relacionadas co contido principal. Deberían aparecer de forma dinámica e contextual na IU.",
"demoChoiceChipTitle": "Etiqueta de elección",
"demoChoiceChipDescription": "As pílulas de elección representan unha opción dun conxunto de opcións. Inclúen descricións ou categorías relacionadas.",
"demoFilterChipTitle": "Etiqueta de filtro",
"demoFilterChipDescription": "As pílulas de filtro serven para filtrar contido por etiquetas ou palabras descritivas.",
"demoInputChipTitle": "Etiqueta de entrada",
"demoInputChipDescription": "As pílulas de entrada representan datos complexos de forma compacta, como textos de conversas ou entidades (por exemplo, persoas, lugares ou cousas).",
"craneSleep9": "Lisboa, Portugal",
"craneEat10": "Lisboa, Portugal",
"demoCupertinoSegmentedControlDescription": "Utilízase para seleccionar unha opción entre varias que se exclúen mutuamente. Cando se selecciona unha opción do control segmentado, anúlase a selección das outras opcións que hai nel.",
"chipTurnOnLights": "Activar luces",
"chipSmall": "Pequeno",
"chipMedium": "Mediano",
"chipLarge": "Grande",
"chipElevator": "Ascensor",
"chipWasher": "Lavadora",
"chipFireplace": "Cheminea",
"chipBiking": "En bici",
"craneFormDiners": "Restaurantes",
"rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Aumenta a túa posible dedución de impostos. Escolle categorías para 1 transacción sen asignar.}other{Aumenta a túa posible dedución de impostos. Escolle categorías para {count} transaccións sen asignar.}}",
"craneFormTime": "Seleccionar hora",
"craneFormLocation": "Seleccionar localización",
"craneFormTravelers": "Viaxeiros",
"craneEat8": "Atlanta, Estados Unidos",
"craneFormDestination": "Escoller destino",
"craneFormDates": "Seleccionar datas",
"craneFly": "VOAR",
"craneSleep": "DURMIR",
"craneEat": "COMIDA",
"craneFlySubhead": "Explorar voos por destino",
"craneSleepSubhead": "Explorar propiedades por destino",
"craneEatSubhead": "Explorar restaurantes por destino",
"craneFlyStops": "{numberOfStops,plural,=0{Directo}=1{1 escala}other{{numberOfStops} escalas}}",
"craneSleepProperties": "{totalProperties,plural,=0{Non hai propiedades dispoñibles}=1{1 propiedade dispoñible}other{{totalProperties} propiedades dispoñibles}}",
"craneEatRestaurants": "{totalRestaurants,plural,=0{Non hai restaurantes}=1{1 restaurante}other{{totalRestaurants} restaurantes}}",
"craneFly0": "Aspen, Estados Unidos",
"demoCupertinoSegmentedControlSubtitle": "Control segmentado ao estilo de iOS",
"craneSleep10": "O Cairo, Exipto",
"craneEat9": "Madrid, España",
"craneFly1": "Big Sur, Estados Unidos",
"craneEat7": "Nashville, Estados Unidos",
"craneEat6": "Seattle, Estados Unidos",
"craneFly8": "Singapur",
"craneEat4": "París, Francia",
"craneEat3": "Portland, Estados Unidos",
"craneEat2": "Córdoba, Arxentina",
"craneEat1": "Dallas, Estados Unidos",
"craneEat0": "Nápoles, Italia",
"craneSleep11": "Taipei, Taiwán",
"craneSleep3": "A Habana, Cuba",
"shrineLogoutButtonCaption": "PECHAR SESIÓN",
"rallyTitleBills": "FACTURAS",
"rallyTitleAccounts": "CONTAS",
"shrineProductVagabondSack": "Saco de vagabundo",
"rallyAccountDetailDataInterestYtd": "Xuros do ano ata a data de hoxe",
"shrineProductWhitneyBelt": "Cinto Whitney",
"shrineProductGardenStrand": "Praia con xardín",
"shrineProductStrutEarrings": "Pendentes Strut",
"shrineProductVarsitySocks": "Calcetíns universitarios",
"shrineProductWeaveKeyring": "Chaveiro de punto",
"shrineProductGatsbyHat": "Pucho de tipo Gatsby",
"shrineProductShrugBag": "Bolso de ombreiro",
"shrineProductGiltDeskTrio": "Accesorios de escritorio dourados",
"shrineProductCopperWireRack": "Estante de fío de cobre",
"shrineProductSootheCeramicSet": "Xogo de cerámica Soothe",
"shrineProductHurrahsTeaSet": "Xogo de té Hurrahs",
"shrineProductBlueStoneMug": "Cunca de pedra azul",
"shrineProductRainwaterTray": "Rexistro para a auga da chuvia",
"shrineProductChambrayNapkins": "Panos de mesa de chambray",
"shrineProductSucculentPlanters": "Testos para plantas suculentas",
"shrineProductQuartetTable": "Mesa redonda",
"shrineProductKitchenQuattro": "Cociña quattro",
"shrineProductClaySweater": "Xersei de cor arxila",
"shrineProductSeaTunic": "Chaqueta cor mar",
"shrineProductPlasterTunic": "Chaqueta cor xeso",
"rallyBudgetCategoryRestaurants": "Restaurantes",
"shrineProductChambrayShirt": "Camisa de chambray",
"shrineProductSeabreezeSweater": "Xersei de cor celeste",
"shrineProductGentryJacket": "Chaqueta estilo gentry",
"shrineProductNavyTrousers": "Pantalóns azul mariño",
"shrineProductWalterHenleyWhite": "Camiseta henley (branca)",
"shrineProductSurfAndPerfShirt": "Camiseta Surf and perf",
"shrineProductGingerScarf": "Bufanda alaranxada",
"shrineProductRamonaCrossover": "Blusa cruzada Ramona",
"shrineProductClassicWhiteCollar": "Colo branco clásico",
"shrineProductSunshirtDress": "Vestido Sunshirt",
"rallyAccountDetailDataInterestRate": "Tipo de interese",
"rallyAccountDetailDataAnnualPercentageYield": "Interese porcentual anual",
"rallyAccountDataVacation": "Vacacións",
"shrineProductFineLinesTee": "Camiseta de raias finas",
"rallyAccountDataHomeSavings": "Aforros para a casa",
"rallyAccountDataChecking": "Comprobando",
"rallyAccountDetailDataInterestPaidLastYear": "Intereses pagados o ano pasado",
"rallyAccountDetailDataNextStatement": "Seguinte extracto",
"rallyAccountDetailDataAccountOwner": "Propietario da conta",
"rallyBudgetCategoryCoffeeShops": "Cafetarías",
"rallyBudgetCategoryGroceries": "Alimentos",
"shrineProductCeriseScallopTee": "Camiseta de vieira de cor vermello cereixa",
"rallyBudgetCategoryClothing": "Roupa",
"rallySettingsManageAccounts": "Xestionar contas",
"rallyAccountDataCarSavings": "Aforros para o coche",
"rallySettingsTaxDocuments": "Documentos fiscais",
"rallySettingsPasscodeAndTouchId": "Contrasinal e Touch ID",
"rallySettingsNotifications": "Notificacións",
"rallySettingsPersonalInformation": "Información persoal",
"rallySettingsPaperlessSettings": "Configuración sen papel",
"rallySettingsFindAtms": "Buscar caixeiros automáticos",
"rallySettingsHelp": "Axuda",
"rallySettingsSignOut": "Pechar sesión",
"rallyAccountTotal": "Total",
"rallyBillsDue": "Pendentes",
"rallyBudgetLeft": "Cantidade restante",
"rallyAccounts": "Contas",
"rallyBills": "Facturas",
"rallyBudgets": "Orzamentos",
"rallyAlerts": "Alertas",
"rallySeeAll": "VER TODO",
"rallyFinanceLeft": "É A CANTIDADE RESTANTE",
"rallyTitleOverview": "VISIÓN XERAL",
"shrineProductShoulderRollsTee": "Camiseta de manga corta arremangada",
"shrineNextButtonCaption": "SEGUINTE",
"rallyTitleBudgets": "ORZAMENTOS",
"rallyTitleSettings": "CONFIGURACIÓN",
"rallyLoginLoginToRally": "Inicia sesión en Rally",
"rallyLoginNoAccount": "Non tes unha conta?",
"rallyLoginSignUp": "REXISTRARSE",
"rallyLoginUsername": "Nome de usuario",
"rallyLoginPassword": "Contrasinal",
"rallyLoginLabelLogin": "Iniciar sesión",
"rallyLoginRememberMe": "Lembrarme",
"rallyLoginButtonLogin": "INICIAR SESIÓN",
"rallyAlertsMessageHeadsUpShopping": "Aviso: Consumiches o {percent} do teu orzamento de compras para este mes.",
"rallyAlertsMessageSpentOnRestaurants": "Gastaches {amount} en restaurantes esta semana.",
"rallyAlertsMessageATMFees": "Gastaches {amount} en comisións de caixeiro automático este mes",
"rallyAlertsMessageCheckingAccount": "Fantástico! A túa conta corrente ten un {percent} máis de fondos que o mes pasado.",
"shrineMenuCaption": "MENÚ",
"shrineCategoryNameAll": "TODO",
"shrineCategoryNameAccessories": "ACCESORIOS",
"shrineCategoryNameClothing": "ROUPA",
"shrineCategoryNameHome": "CASA",
"shrineLoginUsernameLabel": "Nome de usuario",
"shrineLoginPasswordLabel": "Contrasinal",
"shrineCancelButtonCaption": "CANCELAR",
"shrineCartTaxCaption": "Impostos:",
"shrineCartPageCaption": "CESTA",
"shrineProductQuantity": "Cantidade: {quantity}",
"shrineProductPrice": "x {price}",
"shrineCartItemCount": "{quantity,plural,=0{NON HAI ARTIGOS}=1{1 ARTIGO}other{{quantity} ARTIGOS}}",
"shrineCartClearButtonCaption": "BALEIRAR CESTA",
"shrineCartTotalCaption": "TOTAL",
"shrineCartSubtotalCaption": "Subtotal:",
"shrineCartShippingCaption": "Envío:",
"shrineProductGreySlouchTank": "Depósito curvado gris",
"shrineProductStellaSunglasses": "Lentes de sol Stella",
"shrineProductWhitePinstripeShirt": "Camisa de raia diplomática branca",
"demoTextFieldWhereCanWeReachYou": "En que número podemos contactar contigo?",
"settingsTextDirectionLTR": "De esquerda a dereita",
"settingsTextScalingLarge": "Grande",
"demoBottomSheetHeader": "Cabeceira",
"demoBottomSheetItem": "Artigo {value}",
"demoBottomTextFieldsTitle": "Campos de texto",
"demoTextFieldTitle": "Campos de texto",
"demoTextFieldSubtitle": "Unha soa liña de texto editable e números",
"demoTextFieldDescription": "Os campos de texto permiten aos usuarios escribir texto nunha IU. Adoitan aparecer en formularios e cadros de diálogo.",
"demoTextFieldShowPasswordLabel": "Mostrar contrasinal",
"demoTextFieldHidePasswordLabel": "Ocultar contrasinal",
"demoTextFieldFormErrors": "Corrixe os erros marcados en vermello antes de enviar.",
"demoTextFieldNameRequired": "É necesario indicar un nome.",
"demoTextFieldOnlyAlphabeticalChars": "Introduce só caracteres alfabéticos.",
"demoTextFieldEnterUSPhoneNumber": "(###) ###-####: Introduce un número de teléfono dos EUA.",
"demoTextFieldEnterPassword": "Escribe un contrasinal.",
"demoTextFieldPasswordsDoNotMatch": "Os contrasinais non coinciden",
"demoTextFieldWhatDoPeopleCallYou": "Como te chama a xente?",
"demoTextFieldNameField": "Nome*",
"demoBottomSheetButtonText": "MOSTRAR PANEL INFERIOR",
"demoTextFieldPhoneNumber": "Número de teléfono*",
"demoBottomSheetTitle": "Panel inferior",
"demoTextFieldEmail": "Correo electrónico",
"demoTextFieldTellUsAboutYourself": "Fálanos de ti (por exemplo, escribe en que traballas ou que pasatempos tes)",
"demoTextFieldKeepItShort": "Sé breve, isto só é unha demostración.",
"starterAppGenericButton": "BOTÓN",
"demoTextFieldLifeStory": "Biografía",
"demoTextFieldSalary": "Salario",
"demoTextFieldUSD": "USD",
"demoTextFieldNoMoreThan": "Non máis de 8 caracteres.",
"demoTextFieldPassword": "Contrasinal*",
"demoTextFieldRetypePassword": "Volve escribir o contrasinal*",
"demoTextFieldSubmit": "ENVIAR",
"demoBottomNavigationSubtitle": "Navegación pola parte inferior con vistas que se atenúan entre si",
"demoBottomSheetAddLabel": "Engadir",
"demoBottomSheetModalDescription": "Un panel de modo situado na parte inferior é unha alternativa a un menú ou cadro de diálogo e impide ao usuario interactuar co resto da aplicación.",
"demoBottomSheetModalTitle": "Panel inferior modal",
"demoBottomSheetPersistentDescription": "Un panel mostrado de xeito permanente na parte inferior que complementa o contido principal da aplicación. Un panel mostrado de xeito permanente na parte inferior permanece visible incluso cando o usuario interactúa con outras partes da aplicación.",
"demoBottomSheetPersistentTitle": "Panel inferior que se mostra de xeito permanente",
"demoBottomSheetSubtitle": "Paneis inferiores mostrados de xeito permanente e de modo",
"demoTextFieldNameHasPhoneNumber": "O número de teléfono de {name} é o {phoneNumber}",
"buttonText": "BOTÓN",
"demoTypographyDescription": "Definicións dos diferentes estilos tipográficos atopados en Material Design.",
"demoTypographySubtitle": "Todos os estilos de texto predefinidos",
"demoTypographyTitle": "Tipografía",
"demoFullscreenDialogDescription": "A propiedade fullscreenDialog especifica se a páxina entrante é un cadro de diálogo modal de pantalla completa",
"demoFlatButtonDescription": "Un botón plano mostra unha salpicadura de tinta ao premelo pero non sobresae. Usa botóns planos nas barras de ferramentas, nos cadros de diálogo e inseridos con recheo",
"demoBottomNavigationDescription": "As barras de navegación da parte inferior mostran entre tres e cinco destinos na parte inferior da pantalla. Cada destino represéntase mediante unha icona e unha etiqueta de texto opcional. Ao tocar unha icona de navegación da parte inferior, diríxese ao usuario ao destino de navegación de nivel superior asociado con esa icona.",
"demoBottomNavigationSelectedLabel": "Etiqueta seleccionada",
"demoBottomNavigationPersistentLabels": "Etiquetas persistentes",
"starterAppDrawerItem": "Artigo {value}",
"demoTextFieldRequiredField": "O símbolo \"*\" indica que o campo é obrigatorio",
"demoBottomNavigationTitle": "Navegación da parte inferior",
"settingsLightTheme": "Claro",
"settingsTheme": "Tema",
"settingsPlatformIOS": "iOS",
"settingsPlatformAndroid": "Android",
"settingsTextDirectionRTL": "De dereita a esquerda",
"settingsTextScalingHuge": "Moi grande",
"cupertinoButton": "Botón",
"settingsTextScalingNormal": "Normal",
"settingsTextScalingSmall": "Pequena",
"settingsSystemDefault": "Sistema",
"settingsTitle": "Configuración",
"rallyDescription": "Aplicación financeira persoal",
"aboutDialogDescription": "Para ver o código fonte desta aplicación, accede ao {repoLink}.",
"bottomNavigationCommentsTab": "Comentarios",
"starterAppGenericBody": "Corpo",
"starterAppGenericHeadline": "Titular",
"starterAppGenericSubtitle": "Subtítulo",
"starterAppGenericTitle": "Título",
"starterAppTooltipSearch": "Buscar",
"starterAppTooltipShare": "Compartir",
"starterAppTooltipFavorite": "Favorito",
"starterAppTooltipAdd": "Engadir",
"bottomNavigationCalendarTab": "Calendario",
"starterAppDescription": "Deseño para principiantes adaptado",
"starterAppTitle": "Aplicación de base",
"aboutFlutterSamplesRepo": "Exemplos de Flutter no repositorio de GitHub",
"bottomNavigationContentPlaceholder": "Marcador de posición para a pestana {title}",
"bottomNavigationCameraTab": "Cámara",
"bottomNavigationAlarmTab": "Alarma",
"bottomNavigationAccountTab": "Conta",
"demoTextFieldYourEmailAddress": "O teu enderezo de correo electrónico",
"demoToggleButtonDescription": "Os botóns de activación/desactivación poden utilizarse para agrupar opcións relacionadas. Para destacar grupos de botóns de activación/desactivación relacionados, un deles debe ter un contedor común",
"colorsGrey": "GRIS",
"colorsBrown": "MARRÓN",
"colorsDeepOrange": "LARANXA INTENSO",
"colorsOrange": "LARANXA",
"colorsAmber": "ÁMBAR",
"colorsYellow": "AMARELO",
"colorsLime": "VERDE LIMA",
"colorsLightGreen": "VERDE CLARO",
"colorsGreen": "VERDE",
"homeHeaderGallery": "Galería",
"homeHeaderCategories": "Categorías",
"shrineDescription": "Aplicación de venda de moda",
"craneDescription": "Aplicación de viaxes personalizada",
"homeCategoryReference": "ESTILOS E OUTRAS DEMOSTRACIÓNS",
"demoInvalidURL": "Non se puido mostrar o URL:",
"demoOptionsTooltip": "Opcións",
"demoInfoTooltip": "Información",
"demoCodeTooltip": "Código de demostración",
"demoDocumentationTooltip": "Documentación da API",
"demoFullscreenTooltip": "Pantalla completa",
"settingsTextScaling": "Axuste de texto",
"settingsTextDirection": "Dirección do texto",
"settingsLocale": "Configuración rexional",
"settingsPlatformMechanics": "Mecánica da plataforma",
"settingsDarkTheme": "Escuro",
"settingsSlowMotion": "Cámara lenta",
"settingsAbout": "Acerca da Flutter Gallery",
"settingsFeedback": "Enviar comentarios",
"settingsAttribution": "Deseñado por TOASTER en Londres",
"demoButtonTitle": "Botóns",
"demoButtonSubtitle": "Texto, elevacións, contornos e moito máis",
"demoFlatButtonTitle": "Botón plano",
"demoRaisedButtonDescription": "Os botóns con relevo engaden dimensión a deseños principalmente planos. Destacan funcións en espazos reducidos ou amplos.",
"demoRaisedButtonTitle": "Botón con relevo",
"demoOutlineButtonTitle": "Botón de contorno",
"demoOutlineButtonDescription": "Os botóns de contorno vólvense opacos e elévanse ao premelos. Adoitan estar emparellados con botóns con relevo para indicar unha acción secundaria e alternativa.",
"demoToggleButtonTitle": "Botóns de activación/desactivación",
"colorsTeal": "TURQUESA",
"demoFloatingButtonTitle": "Botón de acción flotante",
"demoFloatingButtonDescription": "Un botón de acción flotante é un botón de icona circular pasa por enriba do contido para promover unha acción principal na aplicación.",
"demoDialogTitle": "Cadros de diálogo",
"demoDialogSubtitle": "Simple, alerta e pantalla completa",
"demoAlertDialogTitle": "Alerta",
"demoAlertDialogDescription": "Un cadro de diálogo de alerta informa ao usuario das situacións que requiren unha confirmación. Un cadro de diálogo de alerta ten un título opcional e unha lista opcional de accións.",
"demoAlertTitleDialogTitle": "Alerta con título",
"demoSimpleDialogTitle": "Simple",
"demoSimpleDialogDescription": "Un cadro de diálogo simple ofrécelle ao usuario unha escolla entre varias opcións. Ten un título opcional que se mostra enriba das escollas.",
"demoFullscreenDialogTitle": "Pantalla completa",
"demoCupertinoButtonsTitle": "Botóns",
"demoCupertinoButtonsSubtitle": "Botóns de tipo iOS",
"demoCupertinoButtonsDescription": "Un botón de tipo iOS. Utilízase en texto ou nunha icona que se esvaece e volve aparecer cando se toca. Tamén pode dispor de fondo.",
"demoCupertinoAlertsTitle": "Alertas",
"demoCupertinoAlertsSubtitle": "Cadros de diálogo de alertas de tipo iOS",
"demoCupertinoAlertTitle": "Alerta",
"demoCupertinoAlertDescription": "Un cadro de diálogo de alerta informa ao usuario das situacións que requiren unha confirmación. Un cadro de diálogo de alerta ten un título opcional, contido opcional e unha lista opcional de accións. O título móstrase enriba do contido, mentres que as accións aparecen debaixo.",
"demoCupertinoAlertWithTitleTitle": "Alerta con título",
"demoCupertinoAlertButtonsTitle": "Alerta con botóns",
"demoCupertinoAlertButtonsOnlyTitle": "Só botóns de alerta",
"demoCupertinoActionSheetTitle": "Folla de acción",
"demoCupertinoActionSheetDescription": "Unha folla de acción é un tipo de alerta que lle ofrece ao usuario un conxunto de dúas ou máis escollas relacionadas co contexto actual. Pode ter un título, unha mensaxe adicional e unha lista de accións.",
"demoColorsTitle": "Cores",
"demoColorsSubtitle": "Todas as cores predefinidas",
"demoColorsDescription": "Constantes de cores e de coleccións de cores que representan a paleta de cores de Material Design.",
"buttonTextEnabled": "ENABLED",
"buttonTextDisabled": "DISABLED",
"buttonTextCreate": "Crear",
"dialogSelectedOption": "Seleccionaches: \"{value}\"",
"dialogDiscardTitle": "Queres descartar o borrador?",
"dialogLocationTitle": "Queres utilizar o servizo de localización de Google?",
"dialogLocationDescription": "Permite que Google axude ás aplicacións a determinar a localización. Esta acción supón o envío de datos de localización anónimos a Google, aínda que non se execute ningunha aplicación.",
"dialogCancel": "CANCELAR",
"dialogDiscard": "DESCARTAR",
"dialogDisagree": "NON ACEPTAR",
"dialogAgree": "ACEPTAR",
"dialogSetBackup": "Definir conta para a copia de seguranza",
"colorsBlueGrey": "GRIS AZULADO",
"dialogShow": "MOSTRAR CADRO DE DIÁLOGO",
"dialogFullscreenTitle": "Cadro de diálogo de pantalla completa",
"dialogFullscreenSave": "GARDAR",
"dialogFullscreenDescription": "Unha demostración dun cadro de diálogo de pantalla completa",
"cupertinoButtonEnabled": "Enabled",
"cupertinoButtonDisabled": "Disabled",
"cupertinoButtonWithBackground": "Con fondo",
"cupertinoAlertCancel": "Cancelar",
"cupertinoAlertDiscard": "Descartar",
"cupertinoAlertLocationTitle": "Queres permitir que Maps acceda á túa localización mentres utilizas a aplicación?",
"cupertinoAlertLocationDescription": "A túa localización actual mostrarase no mapa e utilizarase para obter indicacións, resultados de busca próximos e duracións estimadas de viaxes.",
"cupertinoAlertAllow": "Permitir",
"cupertinoAlertDontAllow": "Non permitir",
"cupertinoAlertFavoriteDessert": "Seleccionar sobremesa favorita",
"cupertinoAlertDessertDescription": "Selecciona o teu tipo de sobremesa preferido na lista que aparece a continuación. A escolla utilizarase para personalizar a lista de restaurantes recomendados da túa zona.",
"cupertinoAlertCheesecake": "Torta de queixo",
"cupertinoAlertTiramisu": "Tiramisú",
"cupertinoAlertApplePie": "Gráfico circular",
"cupertinoAlertChocolateBrownie": "Biscoito de chocolate",
"cupertinoShowAlert": "Mostrar alerta",
"colorsRed": "VERMELLO",
"colorsPink": "ROSA",
"colorsPurple": "VIOLETA",
"colorsDeepPurple": "VIOLETA INTENSO",
"colorsIndigo": "ÍNDIGO",
"colorsBlue": "AZUL",
"colorsLightBlue": "AZUL CLARO",
"colorsCyan": "CIANO",
"dialogAddAccount": "Engadir conta",
"Gallery": "Galería",
"Categories": "Categorías",
"SHRINE": "SHRINE",
"Basic shopping app": "Aplicación de compras básica",
"RALLY": "RALLY",
"CRANE": "CRANE",
"Travel app": "Aplicación de viaxes",
"MATERIAL": "MATERIAL",
"CUPERTINO": "CUPERTINO",
"REFERENCE STYLES & MEDIA": "REFERENCE STYLES & MEDIA"
}
| gallery/lib/l10n/intl_gl.arb/0 | {
"file_path": "gallery/lib/l10n/intl_gl.arb",
"repo_id": "gallery",
"token_count": 19604
} | 860 |
{
"loading": "로드 중",
"deselect": "선택 해제",
"select": "선택",
"selectable": "선택 가능(길게 누르기)",
"selected": "선택됨",
"demo": "데모",
"bottomAppBar": "하단 앱 바",
"notSelected": "선택되지 않음",
"demoCupertinoSearchTextFieldTitle": "검색 텍스트 입력란",
"demoCupertinoPicker": "선택 도구",
"demoCupertinoSearchTextFieldSubtitle": "iOS 스타일 검색 텍스트 입력란",
"demoCupertinoSearchTextFieldDescription": "사용자가 텍스트를 입력하여 검색할 수 있고 추천 검색어를 제시하고 필터링할 수 있는 검색 텍스트 입력란입니다.",
"demoCupertinoSearchTextFieldPlaceholder": "텍스트를 입력하세요.",
"demoCupertinoScrollbarTitle": "스크롤바",
"demoCupertinoScrollbarSubtitle": "iOS 스타일 스크롤바",
"demoCupertinoScrollbarDescription": "지정된 하위 요소를 래핑하는 스크롤바",
"demoTwoPaneItem": "{value} 항목",
"demoTwoPaneList": "목록",
"demoTwoPaneFoldableLabel": "폴더블",
"demoTwoPaneSmallScreenLabel": "소형 화면",
"demoTwoPaneSmallScreenDescription": "소형 화면 기기에서 TwoPane이 작동하는 방식입니다.",
"demoTwoPaneTabletLabel": "태블릿/데스크톱",
"demoTwoPaneTabletDescription": "태블릿 또는 데스크톱 등 대형 화면에서 TwoPane이 작동하는 방식입니다.",
"demoTwoPaneTitle": "TwoPane",
"demoTwoPaneSubtitle": "폴더블, 대형, 소형 화면의 반응형 레이아웃",
"splashSelectDemo": "데모 선택",
"demoTwoPaneFoldableDescription": "폴더블 기기에서 TwoPane이 작동하는 방식입니다.",
"demoTwoPaneDetails": "세부정보",
"demoTwoPaneSelectItem": "항목 선택",
"demoTwoPaneItemDetails": "{value} 항목 세부정보",
"demoCupertinoContextMenuActionText": "Flutter 로고를 길게 탭하여 컨텍스트 메뉴를 표시합니다.",
"demoCupertinoContextMenuDescription": "요소를 길게 누르면 표시되는 iOS 스타일의 전체 화면 컨텍스트 메뉴입니다.",
"demoAppBarTitle": "앱 바",
"demoAppBarDescription": "앱 바는 현재 화면과 관련된 콘텐츠 및 작업을 제공합니다. 브랜딩, 화면 제목, 탐색, 작업에 사용됩니다.",
"demoDividerTitle": "구분선",
"demoDividerSubtitle": "목록 및 레이아웃에서 콘텐츠를 그룹으로 묶는 얇은 선",
"demoDividerDescription": "구분선은 목록, 창 등에서 콘텐츠를 구분하는 데 사용될 수 있습니다.",
"demoVerticalDividerTitle": "세로 구분선",
"demoCupertinoContextMenuTitle": "컨텍스트 메뉴",
"demoCupertinoContextMenuSubtitle": "iOS 스타일 컨텍스트 메뉴",
"demoAppBarSubtitle": "현재 화면과 관련된 정보 및 작업 표시",
"demoCupertinoContextMenuActionOne": "작업 1",
"demoCupertinoContextMenuActionTwo": "작업 2",
"demoDateRangePickerDescription": "머티리얼 디자인의 기간 선택 도구가 포함된 대화상자를 표시합니다.",
"demoDateRangePickerTitle": "기간 선택 도구",
"demoNavigationDrawerUserName": "사용자 이름",
"demoNavigationDrawerUserEmail": "[email protected]",
"demoNavigationDrawerText": "창을 보려면 가장자리에서 스와이프하거나 왼쪽 상단에 위치한 아이콘을 탭하세요.",
"demoNavigationRailTitle": "탐색 레일",
"demoNavigationRailSubtitle": "앱 안에 탐색 레일 표시",
"demoNavigationRailDescription": "앱의 왼쪽이나 오른쪽에 위치하여 적은 수의 뷰(일반적으로 3~5개)를 탐색하게 해 주는 머티리얼 디자인 위젯입니다.",
"demoNavigationRailFirst": "첫 번째",
"demoNavigationDrawerTitle": "탐색 창",
"demoNavigationRailThird": "세 번째",
"replyStarredLabel": "별표편지함",
"demoTextButtonDescription": "텍스트 버튼은 누르면 잉크가 퍼지는 모양이 나타나지만 버튼이 올라오지는 않습니다. 툴바, 대화상자, 인라인에서 텍스트 버튼을 패딩과 함께 사용합니다.",
"demoElevatedButtonTitle": "돌출 버튼",
"demoElevatedButtonDescription": "돌출 버튼은 대부분 평면인 레이아웃에 공간감을 주는 데 사용합니다. 꽉 차 있거나 넓은 공간에서 해당 버튼에 표시된 기능을 강조합니다.",
"demoOutlinedButtonTitle": "윤곽 버튼",
"demoOutlinedButtonDescription": "윤곽 버튼은 누르면 불투명해지면서 돌출됩니다. 돌출 버튼과 함께 사용하여 대체 작업이나 보조 작업을 나타내는 경우가 많습니다.",
"demoContainerTransformDemoInstructions": "카드, 목록 및 FAB",
"demoNavigationDrawerSubtitle": "앱 바 안에 창 표시",
"replyDescription": "효율적인 이메일 전용 앱",
"demoNavigationDrawerDescription": "화면 가장자리에서 수평으로 슬라이드해서 표시되는 머티리얼 디자인 패널로, 애플리케이션의 탐색 링크를 표시합니다.",
"replyDraftsLabel": "임시보관함",
"demoNavigationDrawerToPageOne": "항목 1",
"replyInboxLabel": "받은편지함",
"demoSharedXAxisDemoInstructions": "다음 및 뒤로 버튼",
"replySpamLabel": "스팸",
"replyTrashLabel": "휴지통",
"replySentLabel": "보낸편지함",
"demoNavigationRailSecond": "두 번째",
"demoNavigationDrawerToPageTwo": "항목 2",
"demoFadeScaleDemoInstructions": "모달 및 FAB",
"demoFadeThroughDemoInstructions": "하단 탐색",
"demoSharedZAxisDemoInstructions": "설정 아이콘 버튼",
"demoSharedYAxisDemoInstructions": "'최근 재생' 기준으로 정렬",
"demoTextButtonTitle": "텍스트 버튼",
"demoSharedZAxisBeefSandwichRecipeTitle": "비프 샌드위치",
"demoSharedZAxisDessertRecipeDescription": "디저트 레시피",
"demoSharedYAxisAlbumTileSubtitle": "아티스트",
"demoSharedYAxisAlbumTileTitle": "앨범",
"demoSharedYAxisRecentSortTitle": "최근 재생한 항목",
"demoSharedYAxisAlphabeticalSortTitle": "가나다순",
"demoSharedYAxisAlbumCount": "앨범 268개",
"demoSharedYAxisTitle": "공유된 y축",
"demoSharedXAxisCreateAccountButtonText": "계정 만들기",
"demoFadeScaleAlertDialogDiscardButton": "삭제",
"demoSharedXAxisSignInTextFieldLabel": "이메일 주소 또는 전화번호",
"demoSharedXAxisSignInSubtitleText": "내 계정으로 로그인",
"demoSharedXAxisSignInWelcomeText": "David Park님, 안녕하세요.",
"demoSharedXAxisIndividualCourseSubtitle": "개별적으로 표시됨",
"demoSharedXAxisBundledCourseSubtitle": "번들",
"demoFadeThroughAlbumsDestination": "앨범",
"demoSharedXAxisDesignCourseTitle": "디자인",
"demoSharedXAxisIllustrationCourseTitle": "일러스트레이션",
"demoSharedXAxisBusinessCourseTitle": "비즈니스",
"demoSharedXAxisArtsAndCraftsCourseTitle": "예술 및 공예",
"demoMotionPlaceholderSubtitle": "보조 텍스트",
"demoFadeScaleAlertDialogCancelButton": "취소",
"demoFadeScaleAlertDialogHeader": "알림 대화상자",
"demoFadeScaleHideFabButton": "FAB 숨기기",
"demoFadeScaleShowFabButton": "FAB 표시",
"demoFadeScaleShowAlertDialogButton": "모달 표시",
"demoFadeScaleDescription": "페이드 패턴은 화면 중앙에서 점점 뚜렷해지며 나타나는 대화상자와 같이 화면 경계 내에서 나타나거나 사라지는 UI 요소에 사용됩니다.",
"demoFadeScaleTitle": "페이드",
"demoFadeThroughTextPlaceholder": "사진 123장",
"demoFadeThroughSearchDestination": "검색",
"demoFadeThroughPhotosDestination": "사진",
"demoSharedXAxisCoursePageSubtitle": "번들 카테고리가 피드에 그룹으로 표시됩니다. 나중에 언제든지 변경할 수 있습니다.",
"demoFadeThroughDescription": "페이드 스루 패턴은 서로 큰 관련이 없는 UI 요소 간의 전환에 사용됩니다.",
"demoFadeThroughTitle": "페이드 스루",
"demoSharedZAxisHelpSettingLabel": "도움말",
"demoMotionSubtitle": "사전 정의된 전환 패턴 전체",
"demoSharedZAxisNotificationSettingLabel": "알림",
"demoSharedZAxisProfileSettingLabel": "프로필",
"demoSharedZAxisSavedRecipesListTitle": "저장된 레시피",
"demoSharedZAxisBeefSandwichRecipeDescription": "비프 샌드위치 레시피",
"demoSharedZAxisCrabPlateRecipeDescription": "게 요리 레시피",
"demoSharedXAxisCoursePageTitle": "과정 간소화",
"demoSharedZAxisCrabPlateRecipeTitle": "게",
"demoSharedZAxisShrimpPlateRecipeDescription": "새우 요리 레시피",
"demoSharedZAxisShrimpPlateRecipeTitle": "새우",
"demoContainerTransformTypeFadeThrough": "페이드 스루",
"demoSharedZAxisDessertRecipeTitle": "디저트",
"demoSharedZAxisSandwichRecipeDescription": "샌드위치 레시피",
"demoSharedZAxisSandwichRecipeTitle": "샌드위치",
"demoSharedZAxisBurgerRecipeDescription": "햄버거 레시피",
"demoSharedZAxisBurgerRecipeTitle": "햄버거",
"demoSharedZAxisSettingsPageTitle": "설정",
"demoSharedZAxisTitle": "공유된 z축",
"demoSharedZAxisPrivacySettingLabel": "개인정보 보호",
"demoMotionTitle": "모션",
"demoContainerTransformTitle": "컨테이너 변환",
"demoContainerTransformDescription": "컨테이너 변환 패턴은 컨테이너가 포함된 UI 요소 간의 전환을 위해 디자인되었습니다. 이 패턴은 두 UI 요소 간 시각적인 연결을 만들어 줍니다.",
"demoContainerTransformModalBottomSheetTitle": "페이드 모드",
"demoContainerTransformTypeFade": "페이드",
"demoSharedYAxisAlbumTileDurationUnit": "분",
"demoMotionPlaceholderTitle": "제목",
"demoSharedXAxisForgotEmailButtonText": "이메일을 잊으셨나요?",
"demoMotionSmallPlaceholderSubtitle": "보조",
"demoMotionDetailsPageTitle": "세부정보 페이지",
"demoMotionListTileTitle": "목록 항목",
"demoSharedAxisDescription": "공유된 축 패턴은 공간 또는 탐색 관계를 가진 UI 패턴 간의 전환에 사용됩니다. 이 패턴은 x, y 또는 z축의 공유된 변환을 사용하여 요소 간 관계를 강화해 줍니다.",
"demoSharedXAxisTitle": "공유된 x축",
"demoSharedXAxisBackButtonText": "뒤로",
"demoSharedXAxisNextButtonText": "다음",
"demoSharedXAxisCulinaryCourseTitle": "요리",
"githubRepo": "{repoName} GitHub 저장소",
"fortnightlyMenuUS": "미국",
"fortnightlyMenuBusiness": "비즈니스",
"fortnightlyMenuScience": "과학",
"fortnightlyMenuSports": "스포츠",
"fortnightlyMenuTravel": "여행",
"fortnightlyMenuCulture": "문화",
"fortnightlyTrendingTechDesign": "기술_디자인",
"rallyBudgetDetailAmountLeft": "남은 금액",
"fortnightlyHeadlineArmy": "내부에서부터 진행되는 녹색군의 개혁",
"fortnightlyDescription": "콘텐츠를 주력으로 하는 뉴스 앱",
"rallyBillDetailAmountDue": "미결제 금액",
"rallyBudgetDetailTotalCap": "총한도",
"rallyBudgetDetailAmountUsed": "사용 금액",
"fortnightlyTrendingHealthcareRevolution": "건강보험_개혁",
"fortnightlyMenuFrontPage": "메인 페이지",
"fortnightlyMenuWorld": "세계",
"rallyBillDetailAmountPaid": "결제 금액",
"fortnightlyMenuPolitics": "정치",
"fortnightlyHeadlineBees": "사라져가는 농지의 꿀벌",
"fortnightlyHeadlineGasoline": "휘발유의 미래",
"fortnightlyTrendingGreenArmy": "녹색군",
"fortnightlyHeadlineFeminists": "페미니스트, 당을 결성하다",
"fortnightlyHeadlineFabrics": "기술로 미래지향적인 원단을 만드는 디자이너들",
"fortnightlyHeadlineStocks": "주식 침체에 따른 외환 투자",
"fortnightlyTrendingReform": "개혁",
"fortnightlyMenuTech": "기술",
"fortnightlyHeadlineWar": "전쟁 중 이별을 겪은 미국인",
"fortnightlyHeadlineHealthcare": "단계적으로, 혁신적으로 진행되는 건강보험 개혁",
"fortnightlyLatestUpdates": "최신 소식",
"fortnightlyTrendingStocks": "주식",
"rallyBillDetailTotalAmount": "총액",
"demoCupertinoPickerDateTime": "날짜 및 시간",
"signIn": "로그인",
"dataTableRowWithSugar": "설탕이 든 {value}",
"dataTableRowApplePie": "애플파이",
"dataTableRowDonut": "도넛",
"dataTableRowHoneycomb": "벌집꿀",
"dataTableRowLollipop": "롤리팝",
"dataTableRowJellyBean": "젤리빈",
"dataTableRowGingerbread": "진저브레드",
"dataTableRowCupcake": "컵케이크",
"dataTableRowEclair": "에클레르",
"dataTableRowIceCreamSandwich": "아이스크림 샌드위치",
"dataTableRowFrozenYogurt": "프로즌 요거트",
"dataTableColumnIron": "철분(%)",
"dataTableColumnCalcium": "칼슘(%)",
"dataTableColumnSodium": "나트륨(mg)",
"demoTimePickerTitle": "시간 선택도구",
"demo2dTransformationsResetTooltip": "변환 재설정",
"dataTableColumnFat": "지방(g)",
"dataTableColumnCalories": "칼로리",
"dataTableColumnDessert": "디저트(1인분)",
"cardsDemoTravelDestinationLocation1": "타밀 나두 탄자부르",
"demoTimePickerDescription": "머티리얼 디자인의 시간 선택도구가 포함된 대화상자를 표시합니다.",
"demoPickersShowPicker": "선택도구 표시",
"demoTabsScrollingTitle": "스크롤",
"demoTabsNonScrollingTitle": "스크롤 불가능",
"craneHours": "{hours,plural,=1{1시간}other{{hours}시간}}",
"craneMinutes": "{minutes,plural,=1{1분}other{{minutes}분}}",
"craneFlightDuration": "{hoursShortForm} {minutesShortForm}",
"dataTableHeader": "영양",
"demoDatePickerTitle": "날짜 선택도구",
"demoPickersSubtitle": "날짜 및 시간 선택",
"demoPickersTitle": "선택도구",
"demo2dTransformationsEditTooltip": "타일 수정",
"demoDataTableDescription": "데이터 표는 행과 열로 구성된 그리드 형식으로 정보를 표시합니다. 사용자가 패턴이나 통계를 파악할 수 있도록 훑어보기 쉬운 방식으로 데이터가 정리됩니다.",
"demo2dTransformationsDescription": "탭하여 타일을 수정하고 동작으로 화면에서 이동하세요. 드래그하여 화면 간에 이동하고 손가락을 모으거나 펼쳐 확대/축소하거나 두 손가락을 사용하여 회전하세요. 재설정 버튼을 누르면 시작한 방향으로 돌아갑니다.",
"demo2dTransformationsSubtitle": "이동, 확대/축소, 회전",
"demo2dTransformationsTitle": "2D 변환",
"demoCupertinoTextFieldPIN": "PIN",
"demoCupertinoTextFieldDescription": "사용자가 하드웨어 키보드 또는 터치 키보드를 사용해 텍스트를 입력할 수 있는 텍스트 입력란입니다.",
"demoCupertinoTextFieldSubtitle": "iOS 스타일 텍스트 입력란",
"demoCupertinoTextFieldTitle": "입력란",
"demoDatePickerDescription": "머티리얼 디자인의 날짜 선택도구가 포함된 대화상자를 표시합니다.",
"demoCupertinoPickerTime": "시간",
"demoCupertinoPickerDate": "날짜",
"demoCupertinoPickerTimer": "타이머",
"demoCupertinoPickerDescription": "날짜와 시간을 동시에 선택하거나 날짜, 시간, 문자열을 각각 선택하는 데 사용할 수 있는 iOS 스타일의 선택 도구 위젯입니다.",
"demoCupertinoPickerSubtitle": "iOS 스타일 선택 도구",
"demoCupertinoPickerTitle": "선택도구",
"dataTableRowWithHoney": "꿀이 든 {value}",
"cardsDemoTravelDestinationCity2": "체티나드",
"bannerDemoResetText": "배너 재설정",
"bannerDemoMultipleText": "여러 작업",
"bannerDemoLeadingText": "앞부분 아이콘",
"dismiss": "닫기",
"cardsDemoTappable": "탭 가능",
"cardsDemoSelectable": "선택 가능(길게 누르기)",
"cardsDemoExplore": "살펴보기",
"cardsDemoExploreSemantics": "{destinationName} 살펴보기",
"cardsDemoShareSemantics": "{destinationName} 공유하기",
"cardsDemoTravelDestinationTitle1": "타밀 나두에서 가 봐야 할 도시 10곳",
"cardsDemoTravelDestinationDescription1": "10번",
"cardsDemoTravelDestinationCity1": "탄자부르",
"dataTableColumnProtein": "단백질(g)",
"cardsDemoTravelDestinationTitle2": "인도 남부의 장인들",
"cardsDemoTravelDestinationDescription2": "비단 방적공",
"bannerDemoText": "다른 기기에서 비밀번호가 업데이트되었습니다. 다시 로그인해 주세요.",
"cardsDemoTravelDestinationLocation2": "타밀 나두 시바간가",
"cardsDemoTravelDestinationTitle3": "브리하디스와라 사원",
"cardsDemoTravelDestinationDescription3": "사원",
"demoBannerTitle": "배너",
"demoBannerSubtitle": "목록 안에 배너 표시됨",
"demoBannerDescription": "배너는 중요한 메시지를 간결하게 표시하며 사용자가 작업을 실행하거나 배너를 닫을 수 있게 합니다. 배너를 닫으려면 사용자 작업이 필요합니다.",
"demoCardTitle": "카드",
"demoCardSubtitle": "둥근 모서리가 사용된 기준 카드",
"demoCardDescription": "카드는 머티리얼 디자인에서 관련 정보(예: 앨범, 지리적 위치, 식사, 연락처 세부정보)를 표시하는 데 사용되는 시트입니다.",
"demoDataTableTitle": "데이터 표",
"demoDataTableSubtitle": "정보의 행과 열",
"dataTableColumnCarbs": "탄수화물(g)",
"placeTanjore": "탄자부르",
"demoGridListsTitle": "바둑판식 목록",
"placeFlowerMarket": "꽃 시장",
"placeBronzeWorks": "청동 세공",
"placeMarket": "시장",
"placeThanjavurTemple": "탄자부르 사원",
"placeSaltFarm": "염전",
"placeScooters": "스쿠터",
"placeSilkMaker": "비단 제작자",
"placeLunchPrep": "점심 준비",
"placeBeach": "해변",
"placeFisherman": "어부",
"demoMenuSelected": "선택된 값: {value}",
"demoMenuRemove": "삭제",
"demoMenuGetLink": "링크 생성",
"demoMenuShare": "공유",
"demoBottomAppBarSubtitle": "하단에 탐색 메뉴 및 작업 표시",
"demoMenuAnItemWithASectionedMenu": "섹션으로 구분된 메뉴가 포함된 항목",
"demoMenuADisabledMenuItem": "사용 중지된 메뉴 항목",
"demoLinearProgressIndicatorTitle": "선형 진행 상태 표시기",
"demoMenuContextMenuItemOne": "컨텍스트 메뉴 항목 1",
"demoMenuAnItemWithASimpleMenu": "단순 메뉴가 포함된 항목",
"demoCustomSlidersTitle": "맞춤 슬라이더",
"demoMenuAnItemWithAChecklistMenu": "체크리스트 메뉴가 포함된 항목",
"demoCupertinoActivityIndicatorTitle": "활동 표시기",
"demoCupertinoActivityIndicatorSubtitle": "iOS 스타일 활동 표시기",
"demoCupertinoActivityIndicatorDescription": "시계 방향으로 회전하는 iOS 스타일 활동 표시기입니다.",
"demoCupertinoNavigationBarTitle": "탐색 메뉴",
"demoCupertinoNavigationBarSubtitle": "iOS 스타일 탐색 메뉴",
"demoCupertinoNavigationBarDescription": "iOS 스타일의 탐색 메뉴입니다. 이 탐색 메뉴는 페이지 제목으로만 구성된 툴바입니다. 페이지 제목은 툴바 중간에 표시됩니다.",
"demoCupertinoPullToRefreshTitle": "당겨서 새로고침",
"demoCupertinoPullToRefreshSubtitle": "iOS 스타일의 당겨서 새로고침하는 컨트롤",
"demoCupertinoPullToRefreshDescription": "iOS 스타일의 콘텐츠를 당겨서 새로고침하는 컨트롤을 구현하는 위젯입니다.",
"demoProgressIndicatorTitle": "진행 상태 표시기",
"demoProgressIndicatorSubtitle": "선형, 원형, 미확정",
"demoCircularProgressIndicatorTitle": "원형 진행 상태 표시기",
"demoCircularProgressIndicatorDescription": "회전하여 애플리케이션이 작업 중임을 나타내는 머티리얼 디자인 원형 진행 상태 표시기입니다.",
"demoMenuFour": "4",
"demoLinearProgressIndicatorDescription": "머티리얼 디자인 선형 진행 상태 표시기로 진행률 표시줄이라고도 합니다.",
"demoTooltipTitle": "도움말",
"demoTooltipSubtitle": "길게 누르거나 마우스를 가져가면 표시되는 짧은 메시지",
"demoTooltipDescription": "도움말에는 버튼 또는 기타 사용자 인터페이스 작업의 기능을 설명하는 텍스트 라벨이 있습니다. 사용자가 요소 위로 마우스를 가져가거나, 요소를 포커스하거나 길게 누르면 도움말에서 정보를 전달하는 텍스트가 표시됩니다.",
"demoTooltipInstructions": "도움말을 표시하려면 길게 누르거나 마우스를 가져가세요.",
"placeChennai": "첸나이",
"demoMenuChecked": "선택된 값: {value}",
"placeChettinad": "체티나드",
"demoMenuPreview": "미리보기",
"demoBottomAppBarTitle": "하단 앱 바",
"demoBottomAppBarDescription": "하단 앱 바를 통해 플로팅 작업 버튼을 포함한 최대 4개의 작업과 하단 탐색 창에 액세스할 수 있습니다.",
"bottomAppBarNotch": "노치",
"bottomAppBarPosition": "플로팅 작업 버튼 위치",
"bottomAppBarPositionDockedEnd": "도킹됨 - 끝",
"bottomAppBarPositionDockedCenter": "도킹됨 - 중앙",
"bottomAppBarPositionFloatingEnd": "플로팅 - 끝",
"bottomAppBarPositionFloatingCenter": "플로팅 - 중앙",
"demoSlidersEditableNumericalValue": "수정 가능한 숫자값",
"demoGridListsSubtitle": "행 및 열 레이아웃",
"demoGridListsDescription": "바둑판식 목록은 일반적으로 이미지처럼 같은 종류의 데이터를 표시하는 데 가장 적합합니다. 바둑판식 목록에 있는 각 항목을 타일이라고 합니다.",
"demoGridListsImageOnlyTitle": "이미지만",
"demoGridListsHeaderTitle": "머리글 포함",
"demoGridListsFooterTitle": "바닥글 포함",
"demoSlidersTitle": "슬라이더",
"demoSlidersSubtitle": "스와이프하여 값을 선택하는 위젯",
"demoSlidersDescription": "슬라이더는 막대를 따라 분포된 값 범위를 나타내어 사용자가 특정 값을 선택할 수 있게 합니다. 볼륨, 밝기 등의 설정을 조정하거나 이미지 필터를 적용하는 데 적합합니다.",
"demoRangeSlidersTitle": "범위 슬라이더",
"demoRangeSlidersDescription": "슬라이더는 막대를 따라 분포된 값 범위를 나타냅니다. 막대 양쪽 끝에 값 범위를 나타내는 아이콘이 표시될 수 있습니다. 볼륨, 밝기 등의 설정을 조정하거나 이미지 필터를 적용하는 데 적합합니다.",
"demoMenuAnItemWithAContextMenuButton": "컨텍스트 메뉴가 포함된 항목",
"demoCustomSlidersDescription": "슬라이더는 막대를 따라 분포된 값 범위를 나타내어 사용자가 특정 값이나 값 범위를 선택할 수 있게 합니다. 슬라이더에 테마와 맞춤설정을 적용할 수 있습니다.",
"demoSlidersContinuousWithEditableNumericalValue": "수정 가능한 숫자값이 포함된 연속 슬라이더",
"demoSlidersDiscrete": "불연속 슬라이더",
"demoSlidersDiscreteSliderWithCustomTheme": "맞춤 테마가 포함된 불연속 슬라이더",
"demoSlidersContinuousRangeSliderWithCustomTheme": "맞춤 테마가 포함된 연속 범위 슬라이더",
"demoSlidersContinuous": "연속 슬라이더",
"placePondicherry": "퐁디셰리",
"demoMenuTitle": "메뉴",
"demoContextMenuTitle": "컨텍스트 메뉴",
"demoSectionedMenuTitle": "섹션으로 구분된 메뉴",
"demoSimpleMenuTitle": "단순 메뉴",
"demoChecklistMenuTitle": "체크리스트 메뉴",
"demoMenuSubtitle": "메뉴 버튼 및 단순 메뉴",
"demoMenuDescription": "메뉴에는 일시적으로 나타나는 창에 선택 항목이 목록 형식으로 표시됩니다. 선택 항목은 사용자가 버튼, 작업 또는 기타 컨트롤과 상호작용할 때 표시됩니다.",
"demoMenuItemValueOne": "메뉴 항목 1",
"demoMenuItemValueTwo": "메뉴 항목 2",
"demoMenuItemValueThree": "메뉴 항목 3",
"demoMenuOne": "1",
"demoMenuTwo": "2",
"demoMenuThree": "3",
"demoMenuContextMenuItemThree": "컨텍스트 메뉴 항목 3",
"demoCupertinoSwitchSubtitle": "iOS 스타일 스위치",
"demoSnackbarsText": "스낵바입니다.",
"demoCupertinoSliderSubtitle": "iOS 스타일 슬라이더",
"demoCupertinoSliderDescription": "슬라이더는 연속적이거나 분리된 값의 세트 중에 선택하는 데 사용됩니다.",
"demoCupertinoSliderContinuous": "연속: {value}",
"demoCupertinoSliderDiscrete": "분리: {value}",
"demoSnackbarsAction": "스낵바 작업을 눌렀습니다.",
"backToGallery": "갤러리로 돌아가기",
"demoCupertinoTabBarTitle": "탭바",
"demoCupertinoSwitchDescription": "스위치는 단일 설정을 켜짐/꺼짐 상태 간에 전환하는 데 사용됩니다.",
"demoSnackbarsActionButtonLabel": "작업",
"cupertinoTabBarProfileTab": "프로필",
"demoSnackbarsButtonLabel": "스낵바 표시",
"demoSnackbarsDescription": "스낵바는 앱이 실행했거나 실행할 예정인 프로세스를 사용자에게 알려 줍니다. 화면 하단에 임시로 나타납니다. 사용자 환경을 방해하지 않고 사용자 입력이 없어도 사라져야 합니다.",
"demoSnackbarsSubtitle": "스낵바는 화면 하단에 메시지를 표시합니다.",
"demoSnackbarsTitle": "스낵바",
"demoCupertinoSliderTitle": "슬라이더",
"cupertinoTabBarChatTab": "채팅",
"cupertinoTabBarHomeTab": "홈",
"demoCupertinoTabBarDescription": "iOS 스타일의 하단 탐색 탭바입니다. 여러 개의 탭이 표시되고 그중 하나가 활성화됩니다. 기본적으로 첫 번째 탭이 활성화됩니다.",
"demoCupertinoTabBarSubtitle": "iOS 스타일 하단 탭바",
"demoOptionsFeatureTitle": "옵션 보기",
"demoOptionsFeatureDescription": "이 데모의 사용 가능한 옵션을 보려면 여기를 탭하세요.",
"demoCodeViewerCopyAll": "모두 복사",
"shrineScreenReaderRemoveProductButton": "{product} 삭제\n",
"shrineScreenReaderProductAddToCart": "장바구니에 추가",
"shrineScreenReaderCart": "{quantity,plural,=0{장바구니, 상품 없음}=1{장바구니, 상품 1개}other{장바구니, 상품 {quantity}개}}",
"demoCodeViewerFailedToCopyToClipboardMessage": "클립보드에 복사할 수 없습니다. {error}",
"demoCodeViewerCopiedToClipboardMessage": "클립보드에 복사되었습니다.",
"craneSleep8SemanticLabel": "해안가 절벽 위 마야 문명 유적지",
"craneSleep4SemanticLabel": "산을 배경으로 한 호숫가 호텔",
"craneSleep2SemanticLabel": "마추픽추 시타델",
"craneSleep1SemanticLabel": "상록수가 있는 설경 속 샬레",
"craneSleep0SemanticLabel": "수상 방갈로",
"craneFly13SemanticLabel": "야자수가 있는 바닷가 수영장",
"craneFly12SemanticLabel": "야자수가 있는 수영장",
"craneFly11SemanticLabel": "벽돌로 지은 바다의 등대",
"craneFly10SemanticLabel": "해질녘의 알아즈하르 모스크 탑",
"craneFly9SemanticLabel": "파란색 앤티크 자동차에 기대 있는 남자",
"craneFly8SemanticLabel": "수퍼트리 그로브",
"craneEat9SemanticLabel": "페이스트리가 있는 카페 카운터",
"craneEat2SemanticLabel": "햄버거",
"craneFly5SemanticLabel": "산을 배경으로 한 호숫가 호텔",
"demoSelectionControlsSubtitle": "체크박스, 라디오 버튼, 스위치",
"craneEat10SemanticLabel": "거대한 파스트라미 샌드위치를 들고 있는 여성",
"craneFly4SemanticLabel": "수상 방갈로",
"craneEat7SemanticLabel": "베이커리 입구",
"craneEat6SemanticLabel": "새우 요리",
"craneEat5SemanticLabel": "예술적인 레스토랑 좌석",
"craneEat4SemanticLabel": "초콜릿 디저트",
"craneEat3SemanticLabel": "한국식 타코",
"craneFly3SemanticLabel": "마추픽추 시타델",
"craneEat1SemanticLabel": "다이너식 스툴이 있는 빈 술집",
"craneEat0SemanticLabel": "화덕 오븐 속 피자",
"craneSleep11SemanticLabel": "타이베이 101 마천루",
"craneSleep10SemanticLabel": "해질녘의 알아즈하르 모스크 탑",
"craneSleep9SemanticLabel": "벽돌로 지은 바다의 등대",
"craneEat8SemanticLabel": "민물 가재 요리",
"craneSleep7SemanticLabel": "히베이라 광장의 알록달록한 아파트",
"craneSleep6SemanticLabel": "야자수가 있는 수영장",
"craneSleep5SemanticLabel": "들판의 텐트",
"settingsButtonCloseLabel": "설정 닫기",
"demoSelectionControlsCheckboxDescription": "체크박스를 사용하면 집합에서 여러 옵션을 선택할 수 있습니다. 체크박스의 값은 보통 true 또는 false이며, 3상 체크박스의 경우 null 값도 가질 수 있습니다.",
"settingsButtonLabel": "설정",
"demoListsTitle": "목록",
"demoListsSubtitle": "스크롤 목록 레이아웃",
"demoListsDescription": "목록은 고정된 높이의 단일 행으로 구성되어 있으며 각 행에는 일반적으로 일부 텍스트와 선행 및 후행 들여쓰기 아이콘이 포함됩니다.",
"demoOneLineListsTitle": "한 줄",
"demoTwoLineListsTitle": "두 줄",
"demoListsSecondary": "보조 텍스트",
"demoSelectionControlsTitle": "선택 컨트롤",
"craneFly7SemanticLabel": "러시모어산",
"demoSelectionControlsCheckboxTitle": "체크박스",
"craneSleep3SemanticLabel": "파란색 앤티크 자동차에 기대 있는 남자",
"demoSelectionControlsRadioTitle": "라디오",
"demoSelectionControlsRadioDescription": "라디오 버튼을 사용하면 세트에서 한 가지 옵션을 선택할 수 있습니다. 사용자에게 선택 가능한 모든 옵션을 나란히 표시해야 한다고 판단된다면 라디오 버튼을 사용하여 한 가지만 선택할 수 있도록 하세요.",
"demoSelectionControlsSwitchTitle": "스위치",
"demoSelectionControlsSwitchDescription": "사용/사용 중지 스위치로 설정 옵션 하나의 상태를 전환합니다. 스위치로 제어하는 옵션 및 옵션의 상태는 해당하는 인라인 라벨에 명확하게 나타나야 합니다.",
"craneFly0SemanticLabel": "상록수가 있는 설경 속 샬레",
"craneFly1SemanticLabel": "들판의 텐트",
"craneFly2SemanticLabel": "눈이 내린 산 앞에 있는 티베트 기도 깃발",
"craneFly6SemanticLabel": "팔라시꾸 공연장 항공 사진",
"rallySeeAllAccounts": "모든 계좌 보기",
"rallyBillAmount": "{billName} 청구서({amount}) 결제 기한은 {date}입니다.",
"shrineTooltipCloseCart": "장바구니 닫기",
"shrineTooltipCloseMenu": "메뉴 닫기",
"shrineTooltipOpenMenu": "메뉴 열기",
"shrineTooltipSettings": "설정",
"shrineTooltipSearch": "검색",
"demoTabsDescription": "탭을 사용하면 다양한 화면, 데이터 세트 및 기타 상호작용에서 콘텐츠를 정리할 수 있습니다.",
"demoTabsSubtitle": "개별적으로 스크롤 가능한 뷰가 있는 탭",
"demoTabsTitle": "탭",
"rallyBudgetAmount": "{budgetName} 예산 {amountTotal} 중 {amountUsed} 사용, {amountLeft} 남음",
"shrineTooltipRemoveItem": "항목 삭제",
"rallyAccountAmount": "{accountName} 계좌 {accountNumber}의 잔액은 {amount}입니다.",
"rallySeeAllBudgets": "모든 예산 보기",
"rallySeeAllBills": "모든 청구서 보기",
"craneFormDate": "날짜 선택",
"craneFormOrigin": "출발지 선택",
"craneFly2": "네팔 쿰부 밸리",
"craneFly3": "페루 마추픽추",
"craneFly4": "몰디브 말레",
"craneFly5": "스위스 비츠나우",
"craneFly6": "멕시코 멕시코시티",
"craneFly7": "미국 러시모어산",
"settingsTextDirectionLocaleBased": "언어 기준",
"craneFly9": "쿠바 아바나",
"craneFly10": "이집트 카이로",
"craneFly11": "포르투갈 리스본",
"craneFly12": "미국 나파",
"craneFly13": "인도네시아, 발리",
"craneSleep0": "몰디브 말레",
"craneSleep1": "미국 애스펀",
"craneSleep2": "페루 마추픽추",
"demoCupertinoSegmentedControlTitle": "세그먼트 컨트롤",
"craneSleep4": "스위스 비츠나우",
"craneSleep5": "미국 빅 서어",
"craneSleep6": "미국 나파",
"craneSleep7": "포르투갈 포르토",
"craneSleep8": "멕시코 툴룸",
"craneEat5": "대한민국 서울",
"demoChipTitle": "칩",
"demoChipSubtitle": "입력, 속성, 작업을 나타내는 간단한 요소입니다.",
"demoActionChipTitle": "작업 칩",
"demoActionChipDescription": "작업 칩은 주 콘텐츠와 관련된 작업을 실행하는 옵션 세트입니다. 작업 칩은 동적이고 맥락에 맞는 방식으로 UI에 표시되어야 합니다.",
"demoChoiceChipTitle": "선택 칩",
"demoChoiceChipDescription": "선택 칩은 세트 중 하나의 선택지를 나타냅니다. 선택 칩은 관련 설명 텍스트 또는 카테고리를 포함합니다.",
"demoFilterChipTitle": "필터 칩",
"demoFilterChipDescription": "필터 칩은 태그 또는 설명을 사용해 콘텐츠를 필터링합니다.",
"demoInputChipTitle": "입력 칩",
"demoInputChipDescription": "입력 칩은 항목(사람, 장소, 사물) 또는 대화 텍스트 등의 복잡한 정보를 간단한 형식으로 나타낸 것입니다.",
"craneSleep9": "포르투갈 리스본",
"craneEat10": "포르투갈 리스본",
"demoCupertinoSegmentedControlDescription": "여러 개의 상호 배타적인 옵션 중에 선택할 때 사용됩니다. 세그먼트 컨트롤에서 하나의 옵션을 선택하면 세그먼트 컨트롤에 포함된 다른 옵션은 선택이 해제됩니다.",
"chipTurnOnLights": "조명 켜기",
"chipSmall": "작게",
"chipMedium": "보통",
"chipLarge": "크게",
"chipElevator": "엘리베이터",
"chipWasher": "세탁기",
"chipFireplace": "벽난로",
"chipBiking": "자전거 타기",
"craneFormDiners": "식당",
"rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{세금 공제 가능액을 늘릴 수 있습니다. 1개의 미할당 거래에 카테고리를 지정하세요.}other{세금 공제 가능액을 늘릴 수 있습니다. {count}개의 미할당 거래에 카테고리를 지정하세요.}}",
"craneFormTime": "시간 선택",
"craneFormLocation": "지역 선택",
"craneFormTravelers": "여행자 수",
"craneEat8": "미국 애틀랜타",
"craneFormDestination": "목적지 선택",
"craneFormDates": "날짜 선택",
"craneFly": "항공편",
"craneSleep": "숙박",
"craneEat": "음식점",
"craneFlySubhead": "목적지별 항공편 살펴보기",
"craneSleepSubhead": "목적지별 숙박업체 살펴보기",
"craneEatSubhead": "목적지별 음식점 살펴보기",
"craneFlyStops": "{numberOfStops,plural,=0{직항}=1{경유 1회}other{경유 {numberOfStops}회}}",
"craneSleepProperties": "{totalProperties,plural,=0{이용 가능한 숙박업체 없음}=1{이용 가능한 숙박업체 1개}other{이용 가능한 숙박업체 {totalProperties}개}}",
"craneEatRestaurants": "{totalRestaurants,plural,=0{음식점 없음}=1{음식점 1개}other{음식점 {totalRestaurants}개}}",
"craneFly0": "미국 애스펀",
"demoCupertinoSegmentedControlSubtitle": "iOS 스타일 세그먼트 컨트롤",
"craneSleep10": "이집트 카이로",
"craneEat9": "스페인 마드리드",
"craneFly1": "미국 빅 서어",
"craneEat7": "미국 내슈빌",
"craneEat6": "미국 시애틀",
"craneFly8": "싱가포르",
"craneEat4": "프랑스 파리",
"craneEat3": "미국 포틀랜드",
"craneEat2": "아르헨티나 코르도바",
"craneEat1": "미국 댈러스",
"craneEat0": "이탈리아 나폴리",
"craneSleep11": "대만 타이베이",
"craneSleep3": "쿠바 아바나",
"shrineLogoutButtonCaption": "로그아웃",
"rallyTitleBills": "청구서",
"rallyTitleAccounts": "계정",
"shrineProductVagabondSack": "배가본드 색",
"rallyAccountDetailDataInterestYtd": "연간 발생 이자",
"shrineProductWhitneyBelt": "휘트니 벨트",
"shrineProductGardenStrand": "가든 스트랜드",
"shrineProductStrutEarrings": "스트러트 귀고리",
"shrineProductVarsitySocks": "스포츠 양말",
"shrineProductWeaveKeyring": "위빙 열쇠고리",
"shrineProductGatsbyHat": "개츠비 햇",
"shrineProductShrugBag": "슈러그 백",
"shrineProductGiltDeskTrio": "길트 데스크 3개 세트",
"shrineProductCopperWireRack": "코퍼 와이어 랙",
"shrineProductSootheCeramicSet": "수드 세라믹 세트",
"shrineProductHurrahsTeaSet": "허라스 티 세트",
"shrineProductBlueStoneMug": "블루 스톤 머그잔",
"shrineProductRainwaterTray": "빗물받이",
"shrineProductChambrayNapkins": "샴브레이 냅킨",
"shrineProductSucculentPlanters": "다육식물 화분",
"shrineProductQuartetTable": "테이블 4개 세트",
"shrineProductKitchenQuattro": "키친 콰트로",
"shrineProductClaySweater": "클레이 스웨터",
"shrineProductSeaTunic": "시 튜닉",
"shrineProductPlasterTunic": "플라스터 튜닉",
"rallyBudgetCategoryRestaurants": "음식점",
"shrineProductChambrayShirt": "샴브레이 셔츠",
"shrineProductSeabreezeSweater": "시 브리즈 스웨터",
"shrineProductGentryJacket": "젠트리 재킷",
"shrineProductNavyTrousers": "네이비 트라우저",
"shrineProductWalterHenleyWhite": "월터 헨리(화이트)",
"shrineProductSurfAndPerfShirt": "서프 앤 퍼프 셔츠",
"shrineProductGingerScarf": "진저 스카프",
"shrineProductRamonaCrossover": "라모나 크로스오버",
"shrineProductClassicWhiteCollar": "클래식 화이트 칼라",
"shrineProductSunshirtDress": "선셔츠 드레스",
"rallyAccountDetailDataInterestRate": "이율",
"rallyAccountDetailDataAnnualPercentageYield": "연이율",
"rallyAccountDataVacation": "휴가 대비 저축",
"shrineProductFineLinesTee": "파인 라인 티",
"rallyAccountDataHomeSavings": "주택마련 저축",
"rallyAccountDataChecking": "자유 입출금",
"rallyAccountDetailDataInterestPaidLastYear": "작년 지급 이자",
"rallyAccountDetailDataNextStatement": "다음 명세서",
"rallyAccountDetailDataAccountOwner": "계정 소유자",
"rallyBudgetCategoryCoffeeShops": "커피숍",
"rallyBudgetCategoryGroceries": "식료품",
"shrineProductCeriseScallopTee": "세리즈 스캘롭 티",
"rallyBudgetCategoryClothing": "의류",
"rallySettingsManageAccounts": "계정 관리",
"rallyAccountDataCarSavings": "자동차 구매 저축",
"rallySettingsTaxDocuments": "세무 서류",
"rallySettingsPasscodeAndTouchId": "비밀번호 및 Touch ID",
"rallySettingsNotifications": "알림",
"rallySettingsPersonalInformation": "개인정보",
"rallySettingsPaperlessSettings": "페이퍼리스 설정",
"rallySettingsFindAtms": "ATM 찾기",
"rallySettingsHelp": "도움말",
"rallySettingsSignOut": "로그아웃",
"rallyAccountTotal": "합계",
"rallyBillsDue": "마감일:",
"rallyBudgetLeft": "남음",
"rallyAccounts": "계정",
"rallyBills": "청구서",
"rallyBudgets": "예산",
"rallyAlerts": "알림",
"rallySeeAll": "모두 보기",
"rallyFinanceLeft": "남음",
"rallyTitleOverview": "개요",
"shrineProductShoulderRollsTee": "숄더 롤 티",
"shrineNextButtonCaption": "다음",
"rallyTitleBudgets": "예산",
"rallyTitleSettings": "설정",
"rallyLoginLoginToRally": "Rally 로그인",
"rallyLoginNoAccount": "계정이 없나요?",
"rallyLoginSignUp": "가입",
"rallyLoginUsername": "사용자 이름",
"rallyLoginPassword": "비밀번호",
"rallyLoginLabelLogin": "로그인",
"rallyLoginRememberMe": "로그인 유지",
"rallyLoginButtonLogin": "로그인",
"rallyAlertsMessageHeadsUpShopping": "알림: 이번 달 쇼핑 예산의 {percent}를 사용했습니다.",
"rallyAlertsMessageSpentOnRestaurants": "이번 주에 음식점에서 {amount}을(를) 사용했습니다.",
"rallyAlertsMessageATMFees": "이번 달에 ATM 수수료로 {amount}을(를) 사용했습니다.",
"rallyAlertsMessageCheckingAccount": "잘하고 계십니다. 입출금계좌 잔고가 지난달에 비해 {percent} 많습니다.",
"shrineMenuCaption": "메뉴",
"shrineCategoryNameAll": "전체",
"shrineCategoryNameAccessories": "액세서리",
"shrineCategoryNameClothing": "의류",
"shrineCategoryNameHome": "홈",
"shrineLoginUsernameLabel": "사용자 이름",
"shrineLoginPasswordLabel": "비밀번호",
"shrineCancelButtonCaption": "취소",
"shrineCartTaxCaption": "세금:",
"shrineCartPageCaption": "장바구니",
"shrineProductQuantity": "수량: {quantity}",
"shrineProductPrice": "x {price}",
"shrineCartItemCount": "{quantity,plural,=0{항목 없음}=1{항목 1개}other{항목 {quantity}개}}",
"shrineCartClearButtonCaption": "장바구니 비우기",
"shrineCartTotalCaption": "합계",
"shrineCartSubtotalCaption": "소계:",
"shrineCartShippingCaption": "배송:",
"shrineProductGreySlouchTank": "회색 슬라우치 탱크톱",
"shrineProductStellaSunglasses": "스텔라 선글라스",
"shrineProductWhitePinstripeShirt": "화이트 핀스트라이프 셔츠",
"demoTextFieldWhereCanWeReachYou": "연락 가능한 전화번호",
"settingsTextDirectionLTR": "왼쪽에서 오른쪽으로",
"settingsTextScalingLarge": "크게",
"demoBottomSheetHeader": "헤더",
"demoBottomSheetItem": "항목 {value}",
"demoBottomTextFieldsTitle": "입력란",
"demoTextFieldTitle": "입력란",
"demoTextFieldSubtitle": "편집 가능한 텍스트와 숫자 행 1개",
"demoTextFieldDescription": "사용자는 입력란을 통해 UI에 텍스트를 입력할 수 있습니다. 일반적으로 양식 및 대화상자로 표시됩니다.",
"demoTextFieldShowPasswordLabel": "비밀번호 표시",
"demoTextFieldHidePasswordLabel": "비밀번호 숨기기",
"demoTextFieldFormErrors": "제출하기 전에 빨간색으로 표시된 오류를 수정해 주세요.",
"demoTextFieldNameRequired": "이름을 입력해야 합니다.",
"demoTextFieldOnlyAlphabeticalChars": "영문자만 입력해 주세요.",
"demoTextFieldEnterUSPhoneNumber": "(###) ###-#### - 미국 전화번호를 입력하세요.",
"demoTextFieldEnterPassword": "비밀번호를 입력하세요.",
"demoTextFieldPasswordsDoNotMatch": "비밀번호가 일치하지 않습니다.",
"demoTextFieldWhatDoPeopleCallYou": "이름",
"demoTextFieldNameField": "이름*",
"demoBottomSheetButtonText": "하단 시트 표시",
"demoTextFieldPhoneNumber": "전화번호*",
"demoBottomSheetTitle": "하단 시트",
"demoTextFieldEmail": "이메일",
"demoTextFieldTellUsAboutYourself": "자기소개(예: 직업, 취미 등)",
"demoTextFieldKeepItShort": "데모이므로 간결하게 적으세요.",
"starterAppGenericButton": "버튼",
"demoTextFieldLifeStory": "전기",
"demoTextFieldSalary": "급여",
"demoTextFieldUSD": "USD",
"demoTextFieldNoMoreThan": "8자를 넘을 수 없습니다.",
"demoTextFieldPassword": "비밀번호*",
"demoTextFieldRetypePassword": "비밀번호 확인*",
"demoTextFieldSubmit": "제출",
"demoBottomNavigationSubtitle": "크로스 페이딩 보기가 있는 하단 탐색 메뉴",
"demoBottomSheetAddLabel": "추가",
"demoBottomSheetModalDescription": "모달 하단 시트는 메뉴나 대화상자의 대안으로, 사용자가 앱의 나머지 부분과 상호작용하지 못하도록 합니다.",
"demoBottomSheetModalTitle": "모달 하단 시트",
"demoBottomSheetPersistentDescription": "지속적 하단 시트는 앱의 주요 콘텐츠를 보완하는 정보를 표시합니다. 또한 사용자가 앱의 다른 부분과 상호작용할 때도 계속해서 표시됩니다.",
"demoBottomSheetPersistentTitle": "지속적 하단 시트",
"demoBottomSheetSubtitle": "지속적 하단 시트 및 모달 하단 시트",
"demoTextFieldNameHasPhoneNumber": "{name}의 전화번호는 {phoneNumber}입니다.",
"buttonText": "버튼",
"demoTypographyDescription": "머티리얼 디자인에서 찾을 수 있는 다양한 타이포그래피 스타일의 정의입니다.",
"demoTypographySubtitle": "사전 정의된 모든 텍스트 스타일",
"demoTypographyTitle": "타이포그래피",
"demoFullscreenDialogDescription": "fullscreenDialog 속성은 수신 페이지가 전체 화면 모달 대화상자인지 여부를 지정합니다.",
"demoFlatButtonDescription": "평면 버튼은 누르면 잉크가 퍼지는 모양이 나타나지만 버튼이 올라오지는 않습니다. 툴바, 대화상자, 인라인에서 평면 버튼을 패딩과 함께 사용합니다.",
"demoBottomNavigationDescription": "하단 탐색 메뉴는 화면 하단에 3~5개의 대상을 표시합니다. 각 대상은 아이콘과 텍스트 라벨(선택사항)로 표현됩니다. 하단 탐색 아이콘을 탭하면 아이콘과 연결된 최상위 탐색 대상으로 이동합니다.",
"demoBottomNavigationSelectedLabel": "선택한 라벨",
"demoBottomNavigationPersistentLabels": "지속적 라벨",
"starterAppDrawerItem": "항목 {value}",
"demoTextFieldRequiredField": "* 기호는 필수 입력란을 의미합니다.",
"demoBottomNavigationTitle": "하단 탐색 메뉴",
"settingsLightTheme": "밝게",
"settingsTheme": "테마",
"settingsPlatformIOS": "iOS",
"settingsPlatformAndroid": "Android",
"settingsTextDirectionRTL": "오른쪽에서 왼쪽으로",
"settingsTextScalingHuge": "아주 크게",
"cupertinoButton": "버튼",
"settingsTextScalingNormal": "보통",
"settingsTextScalingSmall": "작게",
"settingsSystemDefault": "시스템",
"settingsTitle": "설정",
"rallyDescription": "개인 자산관리 앱",
"aboutDialogDescription": "앱의 소스 코드를 보려면 {repoLink}(으)로 이동하세요.",
"bottomNavigationCommentsTab": "댓글",
"starterAppGenericBody": "본문",
"starterAppGenericHeadline": "헤드라인",
"starterAppGenericSubtitle": "자막",
"starterAppGenericTitle": "제목",
"starterAppTooltipSearch": "검색",
"starterAppTooltipShare": "공유",
"starterAppTooltipFavorite": "즐겨찾기",
"starterAppTooltipAdd": "추가",
"bottomNavigationCalendarTab": "캘린더",
"starterAppDescription": "반응형 스타터 레이아웃",
"starterAppTitle": "스타터 앱",
"aboutFlutterSamplesRepo": "Flutter 샘플 GitHub 저장소",
"bottomNavigationContentPlaceholder": "{title} 탭 자리표시자",
"bottomNavigationCameraTab": "카메라",
"bottomNavigationAlarmTab": "알람",
"bottomNavigationAccountTab": "계정",
"demoTextFieldYourEmailAddress": "이메일 주소",
"demoToggleButtonDescription": "전환 버튼은 관련 옵션을 그룹으로 묶는 데 사용할 수 있습니다. 관련 전환 버튼 그룹임을 강조하기 위해 하나의 그룹은 동일한 컨테이너를 공유해야 합니다.",
"colorsGrey": "회색",
"colorsBrown": "갈색",
"colorsDeepOrange": "짙은 주황색",
"colorsOrange": "주황색",
"colorsAmber": "황색",
"colorsYellow": "노란색",
"colorsLime": "라임색",
"colorsLightGreen": "연한 초록색",
"colorsGreen": "초록색",
"homeHeaderGallery": "갤러리",
"homeHeaderCategories": "카테고리",
"shrineDescription": "패셔너블한 리테일 앱",
"craneDescription": "맞춤 여행 앱",
"homeCategoryReference": "스타일 및 기타",
"demoInvalidURL": "다음 URL을 표시할 수 없습니다.",
"demoOptionsTooltip": "옵션",
"demoInfoTooltip": "정보",
"demoCodeTooltip": "데모 코드",
"demoDocumentationTooltip": "API 도움말",
"demoFullscreenTooltip": "전체 화면",
"settingsTextScaling": "텍스트 크기 조정",
"settingsTextDirection": "텍스트 방향",
"settingsLocale": "언어",
"settingsPlatformMechanics": "플랫폼 메커니즘",
"settingsDarkTheme": "어둡게",
"settingsSlowMotion": "슬로 모션",
"settingsAbout": "Flutter Gallery 정보",
"settingsFeedback": "의견 보내기",
"settingsAttribution": "Designed by TOASTER in London",
"demoButtonTitle": "버튼",
"demoButtonSubtitle": "텍스트 버튼, 돌출 버튼, 윤곽 버튼 등",
"demoFlatButtonTitle": "평면 버튼",
"demoRaisedButtonDescription": "돌출 버튼은 대부분 평면인 레이아웃에 깊이감을 주는 데 사용합니다. 돌출 버튼은 꽉 차 있거나 넓은 공간에서 기능을 강조합니다.",
"demoRaisedButtonTitle": "돌출 버튼",
"demoOutlineButtonTitle": "윤곽 버튼",
"demoOutlineButtonDescription": "윤곽 버튼은 누르면 불투명해지면서 올라옵니다. 돌출 버튼과 함께 사용하여 대체 작업이나 보조 작업을 나타내는 경우가 많습니다.",
"demoToggleButtonTitle": "전환 버튼",
"colorsTeal": "청록색",
"demoFloatingButtonTitle": "플로팅 작업 버튼",
"demoFloatingButtonDescription": "플로팅 작업 버튼은 콘텐츠 위에 마우스를 가져가면 애플리케이션의 기본 작업을 알려주는 원형 아이콘 버튼입니다.",
"demoDialogTitle": "대화상자",
"demoDialogSubtitle": "단순함, 알림, 전체 화면",
"demoAlertDialogTitle": "알림",
"demoAlertDialogDescription": "알림 대화상자는 사용자에게 인지가 필요한 상황을 알려줍니다. 알림 대화상자에는 제목과 작업 목록이 선택사항으로 포함됩니다.",
"demoAlertTitleDialogTitle": "제목이 있는 알림",
"demoSimpleDialogTitle": "단순함",
"demoSimpleDialogDescription": "단순 대화상자는 사용자가 택일할 몇 가지 옵션을 제공합니다. 단순 대화상자에는 옵션 위에 표시되는 제목이 선택사항으로 포함됩니다.",
"demoFullscreenDialogTitle": "전체 화면",
"demoCupertinoButtonsTitle": "버튼",
"demoCupertinoButtonsSubtitle": "iOS 스타일 버튼",
"demoCupertinoButtonsDescription": "iOS 스타일 버튼입니다. 터치하면 페이드인 또는 페이드아웃되는 텍스트 및 아이콘을 담을 수 있습니다. 선택사항으로 배경을 넣을 수 있습니다.",
"demoCupertinoAlertsTitle": "알림",
"demoCupertinoAlertsSubtitle": "iOS 스타일 알림 대화상자",
"demoCupertinoAlertTitle": "알림",
"demoCupertinoAlertDescription": "알림 대화상자는 사용자에게 인지가 필요한 상황을 알려줍니다. 알림 대화상자에는 제목, 콘텐츠, 작업 목록이 선택사항으로 포함됩니다. 제목은 콘텐츠 위에 표시되고 작업은 콘텐츠 아래에 표시됩니다.",
"demoCupertinoAlertWithTitleTitle": "제목이 있는 알림",
"demoCupertinoAlertButtonsTitle": "버튼이 있는 알림",
"demoCupertinoAlertButtonsOnlyTitle": "알림 버튼만",
"demoCupertinoActionSheetTitle": "작업 시트",
"demoCupertinoActionSheetDescription": "작업 시트는 현재 컨텍스트와 관련하여 사용자에게 2개 이상의 선택지를 제시하는 섹션별 스타일 알림입니다. 작업 시트에는 제목, 추가 메시지, 작업 목록이 포함될 수 있습니다.",
"demoColorsTitle": "색상",
"demoColorsSubtitle": "사전 정의된 모든 색상",
"demoColorsDescription": "머티리얼 디자인의 색상 팔레트를 나타내는 색상 및 색상 견본 상수입니다.",
"buttonTextEnabled": "ENABLED",
"buttonTextDisabled": "DISABLED",
"buttonTextCreate": "만들기",
"dialogSelectedOption": "'{value}'을(를) 선택했습니다.",
"dialogDiscardTitle": "초안을 삭제할까요?",
"dialogLocationTitle": "Google의 위치 서비스를 사용하시겠습니까?",
"dialogLocationDescription": "앱이 Google을 통해 위치 정보를 파악할 수 있도록 설정하세요. 이 경우 실행되는 앱이 없을 때도 익명의 위치 데이터가 Google에 전송됩니다.",
"dialogCancel": "취소",
"dialogDiscard": "삭제",
"dialogDisagree": "동의 안함",
"dialogAgree": "동의",
"dialogSetBackup": "백업 계정 설정",
"colorsBlueGrey": "푸른 회색",
"dialogShow": "대화상자 표시",
"dialogFullscreenTitle": "전체 화면 대화상자",
"dialogFullscreenSave": "저장",
"dialogFullscreenDescription": "전체 화면 대화상자 데모",
"cupertinoButtonEnabled": "Enabled",
"cupertinoButtonDisabled": "Disabled",
"cupertinoButtonWithBackground": "배경 포함",
"cupertinoAlertCancel": "취소",
"cupertinoAlertDiscard": "삭제",
"cupertinoAlertLocationTitle": "'지도'를 사용하는 동안 앱에서 사용자의 위치에 액세스할 수 있도록 허용할까요?",
"cupertinoAlertLocationDescription": "현재 위치가 지도에 표시되며 길안내, 근처 검색결과, 예상 소요 시간 계산에 사용됩니다.",
"cupertinoAlertAllow": "허용",
"cupertinoAlertDontAllow": "허용 안함",
"cupertinoAlertFavoriteDessert": "가장 좋아하는 디저트 선택",
"cupertinoAlertDessertDescription": "아래 목록에서 가장 좋아하는 디저트를 선택하세요. 선택한 옵션은 지역 내 식당 추천 목록을 맞춤설정하는 데 사용됩니다.",
"cupertinoAlertCheesecake": "치즈 케이크",
"cupertinoAlertTiramisu": "티라미수",
"cupertinoAlertApplePie": "애플 파이",
"cupertinoAlertChocolateBrownie": "초콜릿 브라우니",
"cupertinoShowAlert": "알림 표시",
"colorsRed": "빨간색",
"colorsPink": "분홍색",
"colorsPurple": "보라색",
"colorsDeepPurple": "짙은 자주색",
"colorsIndigo": "남색",
"colorsBlue": "파란색",
"colorsLightBlue": "하늘색",
"colorsCyan": "청록색",
"dialogAddAccount": "계정 추가",
"Gallery": "갤러리",
"Categories": "카테고리",
"SHRINE": "성지",
"Basic shopping app": "기본 쇼핑 앱",
"RALLY": "집회",
"CRANE": "기중기",
"Travel app": "여행 앱",
"MATERIAL": "머티리얼",
"CUPERTINO": "쿠퍼티노",
"REFERENCE STYLES & MEDIA": "참조 스타일 및 미디어"
}
| gallery/lib/l10n/intl_ko.arb/0 | {
"file_path": "gallery/lib/l10n/intl_ko.arb",
"repo_id": "gallery",
"token_count": 33355
} | 861 |
{
"loading": "Wczytuję",
"deselect": "Odznacz",
"select": "Zaznacz",
"selectable": "Możliwość zaznaczenia (przez przytrzymanie)",
"selected": "Zaznaczono",
"demo": "Wersja demonstracyjna",
"bottomAppBar": "Dolny pasek aplikacji",
"notSelected": "Nie zaznaczono",
"demoCupertinoSearchTextFieldTitle": "Pole tekstowe wyszukiwania",
"demoCupertinoPicker": "Selektor",
"demoCupertinoSearchTextFieldSubtitle": "Pole tekstowe wyszukiwania w stylu iOS",
"demoCupertinoSearchTextFieldDescription": "Pole pozwalające użytkownikowi na wpisanie tekstu do wyszukania, które może też wyświetlać i filtrować sugestie.",
"demoCupertinoSearchTextFieldPlaceholder": "Wpisz tekst",
"demoCupertinoScrollbarTitle": "Pasek przewijania",
"demoCupertinoScrollbarSubtitle": "Pasek przewijania w stylu iOS",
"demoCupertinoScrollbarDescription": "Pasek przewijania, który pakuje dany element podrzędny",
"demoTwoPaneItem": "Element {value}",
"demoTwoPaneList": "Lista",
"demoTwoPaneFoldableLabel": "Składane",
"demoTwoPaneSmallScreenLabel": "Mały ekran",
"demoTwoPaneSmallScreenDescription": "Tak wygląda widżet TwoPane na urządzeniu z małym ekranem.",
"demoTwoPaneTabletLabel": "Tablet/komputer",
"demoTwoPaneTabletDescription": "Tak wygląda widżet TwoPane na większym ekranie, np. tablecie lub komputerze.",
"demoTwoPaneTitle": "TwoPane",
"demoTwoPaneSubtitle": "Układy elastyczne na składanych, dużych i małych ekranach",
"splashSelectDemo": "Wybierz wersję demonstracyjną",
"demoTwoPaneFoldableDescription": "Tak wygląda widżet TwoPane na urządzeniu składanym.",
"demoTwoPaneDetails": "Szczegóły",
"demoTwoPaneSelectItem": "Wybierz element",
"demoTwoPaneItemDetails": "Szczegóły elementu {value}",
"demoCupertinoContextMenuActionText": "Aby zobaczyć menu kontekstowe, naciśnij i przytrzymaj logo Flutter.",
"demoCupertinoContextMenuDescription": "Menu kontekstowe znane z iOS i wyświetlane w widoku pełnego ekranu. Pojawia się, gdy użytkownik przytrzyma dany element.",
"demoAppBarTitle": "Pasek aplikacji",
"demoAppBarDescription": "Pasek aplikacji zawiera treści i czynności dotyczące aktualnego ekranu. Można na nim umieścić oznaczenia marki, nazwę ekranu, elementy nawigacyjne i opcje czynności",
"demoDividerTitle": "Separator",
"demoDividerSubtitle": "Separator to cienka linia oddzielająca elementy listy i layoutu.",
"demoDividerDescription": "Separatorów można używać na listach, panelach i w innych miejscach, gdzie chcemy oddzielić od siebie poszczególne treści.",
"demoVerticalDividerTitle": "Separator pionowy",
"demoCupertinoContextMenuTitle": "Menu kontekstowe",
"demoCupertinoContextMenuSubtitle": "Menu kontekstowe znane z iOS",
"demoAppBarSubtitle": "Zawiera informacje i czynności dotyczące aktualnego ekranu",
"demoCupertinoContextMenuActionOne": "Czynność pierwsza",
"demoCupertinoContextMenuActionTwo": "Czynność druga",
"demoDateRangePickerDescription": "Wyświetla okno z selektorem zakresu dat w stylu Material Design.",
"demoDateRangePickerTitle": "Selektor zakresu dat",
"demoNavigationDrawerUserName": "Nazwa użytkownika",
"demoNavigationDrawerUserEmail": "nazwa.uż[email protected]",
"demoNavigationDrawerText": "Przesuń od krawędzi ekranu lub kliknij ikonę w lewym górnym rogu, by otworzyć panel",
"demoNavigationRailTitle": "Kolumna nawigacji",
"demoNavigationRailSubtitle": "Wyświetla kolumnę nawigacji w aplikacji",
"demoNavigationRailDescription": "Widżet Material Design, który wyświetla się z lewej lub prawej strony aplikacji i ułatwia nawigację po niewielkiej liczbie widoków (zazwyczaj 3 lub 5).",
"demoNavigationRailFirst": "Pierwszy",
"demoNavigationDrawerTitle": "Panel nawigacji",
"demoNavigationRailThird": "Trzeci",
"replyStarredLabel": "Oznaczone gwiazdką",
"demoTextButtonDescription": "Przycisk tekstowy wyświetla plamę po naciśnięciu, ale nie podnosi się. Takich przycisków należy używać na paskach narzędzi, w oknach dialogowych oraz w tekście z dopełnieniem.",
"demoElevatedButtonTitle": "Przycisk podniesiony",
"demoElevatedButtonDescription": "Przyciski podniesione dodają głębi układom, które są w znacznej mierze płaskie. Zwracają uwagę na funkcje w mocno wypełnionych lub dużych obszarach.",
"demoOutlinedButtonTitle": "Przycisk z konturem",
"demoOutlinedButtonDescription": "Przyciski z konturem stają się nieprzezroczyste i podnoszą się po naciśnięciu. Często występują w parze z przyciskami podniesionymi, by wskazać działanie alternatywne.",
"demoContainerTransformDemoInstructions": "Karty, listy i przyciski typu FAB",
"demoNavigationDrawerSubtitle": "Wyświetla panel na pasku w aplikacji",
"replyDescription": "Przydatna i wygodna aplikacja do poczty e-mail",
"demoNavigationDrawerDescription": "Panel Material Design, który wysuwa się poziomo od krawędzi ekranu. Zawiera linki nawigacyjne do różnych sekcji w aplikacji.",
"replyDraftsLabel": "Wersje robocze",
"demoNavigationDrawerToPageOne": "Pierwszy element",
"replyInboxLabel": "Odebrane",
"demoSharedXAxisDemoInstructions": "Przyciski Dalej i Wstecz",
"replySpamLabel": "Spam",
"replyTrashLabel": "Kosz",
"replySentLabel": "Wysłane",
"demoNavigationRailSecond": "Drugi",
"demoNavigationDrawerToPageTwo": "Drugi element",
"demoFadeScaleDemoInstructions": "Okno modalne i FAB",
"demoFadeThroughDemoInstructions": "Dolna nawigacja",
"demoSharedZAxisDemoInstructions": "Przycisk ikony Ustawienia",
"demoSharedYAxisDemoInstructions": "Sortuj według opcji „Ostatnio odtwarzane”",
"demoTextButtonTitle": "Przycisk tekstowy",
"demoSharedZAxisBeefSandwichRecipeTitle": "Kanapka z wołowiną",
"demoSharedZAxisDessertRecipeDescription": "Przepis na deser",
"demoSharedYAxisAlbumTileSubtitle": "Wykonawca",
"demoSharedYAxisAlbumTileTitle": "Album",
"demoSharedYAxisRecentSortTitle": "Ostatnio odtwarzane",
"demoSharedYAxisAlphabeticalSortTitle": "A–Z",
"demoSharedYAxisAlbumCount": "268 albumów",
"demoSharedYAxisTitle": "Wspólna oś y",
"demoSharedXAxisCreateAccountButtonText": "UTWÓRZ KONTO",
"demoFadeScaleAlertDialogDiscardButton": "ODRZUĆ",
"demoSharedXAxisSignInTextFieldLabel": "E-mail lub numer telefonu",
"demoSharedXAxisSignInSubtitleText": "Zaloguj się na swoje konto",
"demoSharedXAxisSignInWelcomeText": "Cześć,",
"demoSharedXAxisIndividualCourseSubtitle": "Wyświetlane osobno",
"demoSharedXAxisBundledCourseSubtitle": "W pakiecie",
"demoFadeThroughAlbumsDestination": "Albumy",
"demoSharedXAxisDesignCourseTitle": "Projektowanie i design",
"demoSharedXAxisIllustrationCourseTitle": "Ilustracja",
"demoSharedXAxisBusinessCourseTitle": "Firma",
"demoSharedXAxisArtsAndCraftsCourseTitle": "Sztuka i rzemiosło",
"demoMotionPlaceholderSubtitle": "Tekst dodatkowy",
"demoFadeScaleAlertDialogCancelButton": "ANULUJ",
"demoFadeScaleAlertDialogHeader": "Okno alertu",
"demoFadeScaleHideFabButton": "UKRYJ FAB",
"demoFadeScaleShowFabButton": "POKAŻ FAB",
"demoFadeScaleShowAlertDialogButton": "POKAŻ MODALNE",
"demoFadeScaleDescription": "Wzorzec Zanikanie jest przeznaczony dla elementów interfejsu, które pojawiają się lub znikają na ekranie, na przykład okien dialogowych pojawiających się na środku ekranu.",
"demoFadeScaleTitle": "Zanikanie",
"demoFadeThroughTextPlaceholder": "123 zdjęcia",
"demoFadeThroughSearchDestination": "Szukaj",
"demoFadeThroughPhotosDestination": "Zdjęcia",
"demoSharedXAxisCoursePageSubtitle": "Na Twojej karcie pakiety kategorii są widoczne jako grupy. Później możesz zmienić to ustawienie.",
"demoFadeThroughDescription": "Wzorzec Przenikanie jest przeznaczony dla przejść między elementami interfejsu, między którymi nie ma wyraźnego związku.",
"demoFadeThroughTitle": "Przenikanie",
"demoSharedZAxisHelpSettingLabel": "Pomoc",
"demoMotionSubtitle": "Wszystkie predefiniowane wzorce przejść",
"demoSharedZAxisNotificationSettingLabel": "Powiadomienia",
"demoSharedZAxisProfileSettingLabel": "Profil",
"demoSharedZAxisSavedRecipesListTitle": "Zapisane przepisy",
"demoSharedZAxisBeefSandwichRecipeDescription": "Przepis na kanapkę z wołowiną",
"demoSharedZAxisCrabPlateRecipeDescription": "Przepis na kraba",
"demoSharedXAxisCoursePageTitle": "Usprawnij swoje kursy",
"demoSharedZAxisCrabPlateRecipeTitle": "Krab",
"demoSharedZAxisShrimpPlateRecipeDescription": "Przepis na krewetki",
"demoSharedZAxisShrimpPlateRecipeTitle": "Krewetka",
"demoContainerTransformTypeFadeThrough": "PRZENIKANIE",
"demoSharedZAxisDessertRecipeTitle": "Deser",
"demoSharedZAxisSandwichRecipeDescription": "Przepis na kanapkę",
"demoSharedZAxisSandwichRecipeTitle": "Kanapka",
"demoSharedZAxisBurgerRecipeDescription": "Przepis na burgera",
"demoSharedZAxisBurgerRecipeTitle": "Burger",
"demoSharedZAxisSettingsPageTitle": "Ustawienia",
"demoSharedZAxisTitle": "Wspólna oś z",
"demoSharedZAxisPrivacySettingLabel": "Prywatność",
"demoMotionTitle": "Animacja",
"demoContainerTransformTitle": "Przekształcenie kontenera",
"demoContainerTransformDescription": "Wzorzec przekształcenia kontenera jest przeznaczony dla przejść między elementami interfejsu, które zawierają kontener. Tworzy on widoczne połączenie między dwoma elementami interfejsu.",
"demoContainerTransformModalBottomSheetTitle": "Tryb zanikania",
"demoContainerTransformTypeFade": "ZANIKANIE",
"demoSharedYAxisAlbumTileDurationUnit": "min",
"demoMotionPlaceholderTitle": "Tytuł",
"demoSharedXAxisForgotEmailButtonText": "NIE PAMIĘTASZ ADRESU?",
"demoMotionSmallPlaceholderSubtitle": "Dodatkowy",
"demoMotionDetailsPageTitle": "Strona z informacjami",
"demoMotionListTileTitle": "Element listy",
"demoSharedAxisDescription": "Wzorzec wspólnej osi jest przeznaczony dla przejść między elementami interfejsu, między którymi istnieje związek przestrzenny lub nawigacyjny. Ten wzorzec używa wspólnej transformacji na osi x, y lub z do wzmocnienia związku między elementami.",
"demoSharedXAxisTitle": "Wspólna oś x",
"demoSharedXAxisBackButtonText": "WSTECZ",
"demoSharedXAxisNextButtonText": "DALEJ",
"demoSharedXAxisCulinaryCourseTitle": "Kuchnia",
"githubRepo": "repozytorium {repoName} na GitHubie",
"fortnightlyMenuUS": "Stany Zjednoczone",
"fortnightlyMenuBusiness": "Biznes",
"fortnightlyMenuScience": "Nauka",
"fortnightlyMenuSports": "Sport",
"fortnightlyMenuTravel": "Podróże",
"fortnightlyMenuCulture": "Kultura",
"fortnightlyTrendingTechDesign": "TechDesign",
"rallyBudgetDetailAmountLeft": "Pozostała kwota",
"fortnightlyHeadlineArmy": "Wewnętrzna reforma Green Army",
"fortnightlyDescription": "Aplikacja z wiadomościami, w której liczy się treść",
"rallyBillDetailAmountDue": "Należna kwota",
"rallyBudgetDetailTotalCap": "Łączny limit",
"rallyBudgetDetailAmountUsed": "Wykorzystana kwota",
"fortnightlyTrendingHealthcareRevolution": "HealthcareRevolution",
"fortnightlyMenuFrontPage": "Pierwsza strona",
"fortnightlyMenuWorld": "Świat",
"rallyBillDetailAmountPaid": "Zapłacona kwota",
"fortnightlyMenuPolitics": "Polityka",
"fortnightlyHeadlineBees": "Coraz mniej pszczół na polach uprawnych",
"fortnightlyHeadlineGasoline": "Przyszłość benzyny",
"fortnightlyTrendingGreenArmy": "GreenArmy",
"fortnightlyHeadlineFeminists": "Feministki a stronniczość",
"fortnightlyHeadlineFabrics": "Projektanci tworzą futurystyczne materiały za pomocą technologii",
"fortnightlyHeadlineStocks": "Przez stagnację na giełdzie rośnie popularność pieniądza",
"fortnightlyTrendingReform": "Reform",
"fortnightlyMenuTech": "Technologie",
"fortnightlyHeadlineWar": "Podzieleni Amerykanie podczas wojny",
"fortnightlyHeadlineHealthcare": "Cicha, ale skuteczna rewolucja w opiece zdrowotnej",
"fortnightlyLatestUpdates": "Najnowsze informacje",
"fortnightlyTrendingStocks": "Stocks",
"rallyBillDetailTotalAmount": "Łączna kwota",
"demoCupertinoPickerDateTime": "Data i godzina",
"signIn": "ZALOGUJ SIĘ",
"dataTableRowWithSugar": "{value} z cukrem",
"dataTableRowApplePie": "Szarlotka",
"dataTableRowDonut": "Pączek",
"dataTableRowHoneycomb": "Plaster miodu",
"dataTableRowLollipop": "Lizak",
"dataTableRowJellyBean": "Żelka",
"dataTableRowGingerbread": "Piernik",
"dataTableRowCupcake": "Babeczka",
"dataTableRowEclair": "Ekler",
"dataTableRowIceCreamSandwich": "Kanapka lodowa",
"dataTableRowFrozenYogurt": "Jogurt mrożony",
"dataTableColumnIron": "Żelazo (%)",
"dataTableColumnCalcium": "Wapń (%)",
"dataTableColumnSodium": "Sód (mg)",
"demoTimePickerTitle": "Selektor godziny",
"demo2dTransformationsResetTooltip": "Resetuj przekształcenia",
"dataTableColumnFat": "Tłuszcze (g)",
"dataTableColumnCalories": "Kalorie",
"dataTableColumnDessert": "Deser (1 porcja)",
"cardsDemoTravelDestinationLocation1": "Tańdźawur, Tamilnadu",
"demoTimePickerDescription": "Wyświetla okno z selektorem godziny w stylu Material Design.",
"demoPickersShowPicker": "POKAŻ SELEKTOR",
"demoTabsScrollingTitle": "Przewijany",
"demoTabsNonScrollingTitle": "Nieprzewijany",
"craneHours": "{hours,plural,=1{1 g}few{{hours} g}many{{hours} g}other{{hours} g}}",
"craneMinutes": "{minutes,plural,=1{1 min}few{{minutes} min}many{{minutes} min}other{{minutes} min}}",
"craneFlightDuration": "{hoursShortForm} {minutesShortForm}",
"dataTableHeader": "Wartości odżywcze",
"demoDatePickerTitle": "Selektor daty",
"demoPickersSubtitle": "Wybór daty i godziny",
"demoPickersTitle": "Selektory",
"demo2dTransformationsEditTooltip": "Edytuj kafelek",
"demoDataTableDescription": "Tabele danych wyświetlają informacje w formacie siatki podzielonej na wiersze i kolumny. Organizują one dane w formie sprzyjającej szybkiemu przeglądaniu, dzięki czemu łatwiej można zauważyć wzorce i trendy.",
"demo2dTransformationsDescription": "Klikaj kafelki, by je edytować, i używaj gestów, by poruszać się po scenie. Przeciągnij palcem, by przesunąć widok, ściągnij palce do siebie, by go powiększyć, i przesuń dwoma palcami, by go obrócić. Naciśnij przycisk resetowania, by wrócić do widoku początkowego.",
"demo2dTransformationsSubtitle": "Przesunięcie, powiększenie, obrót",
"demo2dTransformationsTitle": "Przekształcenia 2D",
"demoCupertinoTextFieldPIN": "Kod PIN",
"demoCupertinoTextFieldDescription": "Pole tekstowe pozwala użytkownikowi na wpisywanie tekstu za pomocą klawiatury fizycznej lub ekranowej.",
"demoCupertinoTextFieldSubtitle": "Pola tekstowe w stylu iOS",
"demoCupertinoTextFieldTitle": "Pola tekstowe",
"demoDatePickerDescription": "Wyświetla okno z selektorem daty w stylu Material Design.",
"demoCupertinoPickerTime": "Godzina",
"demoCupertinoPickerDate": "Data",
"demoCupertinoPickerTimer": "Licznik czasu",
"demoCupertinoPickerDescription": "Widżet z selektorem w stylu iOS, którego można używać do wybierania tekstu, daty, godziny lub równocześnie daty i godziny.",
"demoCupertinoPickerSubtitle": "Selektory w stylu iOS",
"demoCupertinoPickerTitle": "Selektory",
"dataTableRowWithHoney": "{value} z miodem",
"cardsDemoTravelDestinationCity2": "Chettinad",
"bannerDemoResetText": "Zresetuj baner",
"bannerDemoMultipleText": "Wiele działań",
"bannerDemoLeadingText": "Ikona główna",
"dismiss": "ZAMKNIJ",
"cardsDemoTappable": "Przycisk do kliknięcia",
"cardsDemoSelectable": "Możliwość wyboru (przez przytrzymanie)",
"cardsDemoExplore": "Zobacz więcej",
"cardsDemoExploreSemantics": "{destinationName} – zobacz to miejsce",
"cardsDemoShareSemantics": "{destinationName} – udostępnij informacje o tym miejscu",
"cardsDemoTravelDestinationTitle1": "10 najciekawszych miast w Tamilnadu",
"cardsDemoTravelDestinationDescription1": "Numer 10",
"cardsDemoTravelDestinationCity1": "Tańdźawur",
"dataTableColumnProtein": "Białka (g)",
"cardsDemoTravelDestinationTitle2": "Rzemieślnicy z południowych Indii",
"cardsDemoTravelDestinationDescription2": "Przędzarze jedwabiu",
"bannerDemoText": "Hasło zostało zaktualizowane na drugim urządzeniu. Zaloguj się ponownie.",
"cardsDemoTravelDestinationLocation2": "Sivaganga, Tamilnadu",
"cardsDemoTravelDestinationTitle3": "Świątynia Brihadisvara",
"cardsDemoTravelDestinationDescription3": "Świątynie",
"demoBannerTitle": "Baner",
"demoBannerSubtitle": "Wyświetlanie banera na liście",
"demoBannerDescription": "Na banerze wyświetla się krótki, ważny komunikat do użytkowników wraz z możliwością podjęcia działań (lub zamknięcia banera). Aby zamknąć baner, użytkownik musi wykonać działanie.",
"demoCardTitle": "Karty",
"demoCardSubtitle": "Karty bazowe z zaokrąglonymi rogami",
"demoCardDescription": "Karta to element interfejsu w stylu Material Design, na którym wyświetlane są powiązane informacje, na przykład album, położenie geograficzne, opis potrawy czy dane kontaktowe.",
"demoDataTableTitle": "Tabele danych",
"demoDataTableSubtitle": "Wiersze i kolumny z informacjami",
"dataTableColumnCarbs": "Węglowodany (g)",
"placeTanjore": "Tańdźawur",
"demoGridListsTitle": "Listy w postaci siatki",
"placeFlowerMarket": "Targ kwiatowy",
"placeBronzeWorks": "Zakład wyrobów z brązu",
"placeMarket": "Rynek",
"placeThanjavurTemple": "Świątynia w Tańdźawur",
"placeSaltFarm": "Farma solna",
"placeScooters": "Hulajnogi",
"placeSilkMaker": "Producent jedwabiu",
"placeLunchPrep": "Przygotowanie lunchu",
"placeBeach": "Plaża",
"placeFisherman": "Rybak",
"demoMenuSelected": "Wybrano: {value}",
"demoMenuRemove": "Usuń",
"demoMenuGetLink": "Pobierz link",
"demoMenuShare": "Udostępnij",
"demoBottomAppBarSubtitle": "Wyświetla opcje nawigacji i działań na dole ekranu",
"demoMenuAnItemWithASectionedMenu": "Element z menu z podziałem na sekcje",
"demoMenuADisabledMenuItem": "Wyłączona pozycja menu",
"demoLinearProgressIndicatorTitle": "Liniowy wskaźnik postępu",
"demoMenuContextMenuItemOne": "Pierwsza pozycja menu kontekstowego",
"demoMenuAnItemWithASimpleMenu": "Element z prostym menu",
"demoCustomSlidersTitle": "Suwaki niestandardowe",
"demoMenuAnItemWithAChecklistMenu": "Element z menu listy kontrolnej",
"demoCupertinoActivityIndicatorTitle": "Wskaźnik aktywności",
"demoCupertinoActivityIndicatorSubtitle": "Wskaźniki aktywności w stylu iOS",
"demoCupertinoActivityIndicatorDescription": "Wskaźnik aktywności w stylu iOS, który obraca się w prawo.",
"demoCupertinoNavigationBarTitle": "Pasek nawigacyjny",
"demoCupertinoNavigationBarSubtitle": "Pasek nawigacyjny w stylu iOS",
"demoCupertinoNavigationBarDescription": "Pasek nawigacyjny w stylu iOS. Pasek nawigacyjny to pasek narzędzi, który zawiera co najmniej tytuł strony na środku.",
"demoCupertinoPullToRefreshTitle": "Przeciągnij w dół, by odświeżyć",
"demoCupertinoPullToRefreshSubtitle": "Element sterujący „przeciągnij, by odświeżyć” w stylu iOS",
"demoCupertinoPullToRefreshDescription": "Widżet z zaimplementowanym elementem sterującym „przeciągnij, by odświeżyć” w stylu iOS.",
"demoProgressIndicatorTitle": "Wskaźniki postępu",
"demoProgressIndicatorSubtitle": "Liniowe, kołowe, nieokreślone",
"demoCircularProgressIndicatorTitle": "Kołowy wskaźnik postępu",
"demoCircularProgressIndicatorDescription": "Kołowy wskaźnik postępu w stylu Material Design, który poprzez obracanie się sygnalizuje, że aplikacja jest zajęta.",
"demoMenuFour": "Cztery",
"demoLinearProgressIndicatorDescription": "Liniowy wskaźnik postępu w stylu Material Design, nazywany też paskiem postępu.",
"demoTooltipTitle": "Etykietki",
"demoTooltipSubtitle": "Krótki komunikat wyświetlany po najechaniu na element lub przytrzymaniu go",
"demoTooltipDescription": "Etykietki zawierają tekst z objaśnieniem funkcji przycisku lub działania innego elementu interfejsu. Etykietka z podpowiedzią wyświetla się, gdy użytkownik najedzie myszą na element, wybierze go lub przytrzyma.",
"demoTooltipInstructions": "Aby wyświetlić etykietkę, najedź na element lub go przytrzymaj.",
"placeChennai": "Madras",
"demoMenuChecked": "Zaznaczono: {value}",
"placeChettinad": "Chettinad",
"demoMenuPreview": "Podgląd",
"demoBottomAppBarTitle": "Dolny pasek aplikacji",
"demoBottomAppBarDescription": "Dolne paski aplikacji oferują dostęp do dolnego panelu nawigacji i maksymalnie czterech działań, w tym za pomocą pływającego przycisku polecenia.",
"bottomAppBarNotch": "Z wycięciem",
"bottomAppBarPosition": "Położenie pływającego przycisku polecenia",
"bottomAppBarPositionDockedEnd": "Zadokowany – na końcu",
"bottomAppBarPositionDockedCenter": "Zadokowany – na środku",
"bottomAppBarPositionFloatingEnd": "Pływający – na końcu",
"bottomAppBarPositionFloatingCenter": "Pływający – na środku",
"demoSlidersEditableNumericalValue": "Pole do wpisania wartości liczbowej",
"demoGridListsSubtitle": "Układ wierszy i kolumn",
"demoGridListsDescription": "Listy w postaci siatki najlepiej nadają się do prezentowania danych jednorodnych. Typowym przykładem są obrazy. Poszczególne elementy listy w postaci siatki nazywane są kafelkami.",
"demoGridListsImageOnlyTitle": "Tylko obraz",
"demoGridListsHeaderTitle": "Z nagłówkiem",
"demoGridListsFooterTitle": "Ze stopką",
"demoSlidersTitle": "Suwaki",
"demoSlidersSubtitle": "Widżety pozwalające wybrać wartość poprzez przesuwanie",
"demoSlidersDescription": "Suwaki prezentują zakres na pasku, z którego użytkownicy mogą wybrać jedną wartość. Ten element interfejsu idealnie nadaje się do regulacji ustawień takich jak głośność, jasność czy stopień zastosowania filtra graficznego.",
"demoRangeSlidersTitle": "Suwaki zakresowe",
"demoRangeSlidersDescription": "Suwaki prezentują zakres wartości na pasku. Na obu końcach paska mogą znajdować się ikony ilustrujące dany zakres. Ten element interfejsu idealnie nadaje się do regulacji ustawień takich jak głośność, jasność czy stopień zastosowania filtra graficznego.",
"demoMenuAnItemWithAContextMenuButton": "Element z menu kontekstowym",
"demoCustomSlidersDescription": "Suwaki prezentują zakres wartości na pasku, z którego użytkownicy mogą wybrać jedną wartość lub ich zakres. Suwaki mogą być dostosowane pod kątem motywu i innych cech.",
"demoSlidersContinuousWithEditableNumericalValue": "Ciągły z możliwością wpisania liczby",
"demoSlidersDiscrete": "Z określonymi wartościami",
"demoSlidersDiscreteSliderWithCustomTheme": "Suwak z określonymi wartościami i niestandardowym motywem",
"demoSlidersContinuousRangeSliderWithCustomTheme": "Ciągły suwak zakresowy z niestandardowym motywem",
"demoSlidersContinuous": "Ciągły",
"placePondicherry": "Puducherry",
"demoMenuTitle": "Menu",
"demoContextMenuTitle": "Menu kontekstowe",
"demoSectionedMenuTitle": "Menu z podziałem na sekcje",
"demoSimpleMenuTitle": "Proste menu",
"demoChecklistMenuTitle": "Menu listy kontrolnej",
"demoMenuSubtitle": "Przyciski menu i proste menu",
"demoMenuDescription": "Menu wyświetla listę opcji w tymczasowym interfejsie. Opcje wyświetlają się, gdy użytkownik wejdzie w interakcję z przyciskiem, opcją lub innym elementem sterującym.",
"demoMenuItemValueOne": "Pierwsza pozycja menu",
"demoMenuItemValueTwo": "Druga pozycja menu",
"demoMenuItemValueThree": "Trzecia pozycja menu",
"demoMenuOne": "Jeden",
"demoMenuTwo": "Dwa",
"demoMenuThree": "Trzy",
"demoMenuContextMenuItemThree": "Trzecia pozycja menu kontekstowego",
"demoCupertinoSwitchSubtitle": "Przełącznik w stylu iOS",
"demoSnackbarsText": "To jest pasek powiadomień.",
"demoCupertinoSliderSubtitle": "Suwak w stylu iOS",
"demoCupertinoSliderDescription": "Suwak umożliwia wybieranie wartości z ciągłego zakresu lub określonego zestawu.",
"demoCupertinoSliderContinuous": "Giągła: {value}",
"demoCupertinoSliderDiscrete": "Określona: {value}",
"demoSnackbarsAction": "Wybrano działanie paska powiadomień.",
"backToGallery": "Powrót do Galerii",
"demoCupertinoTabBarTitle": "Pasek kart",
"demoCupertinoSwitchDescription": "Przełącznik służy do włączania i wyłączania pojedynczego ustawienia.",
"demoSnackbarsActionButtonLabel": "DZIAŁANIE",
"cupertinoTabBarProfileTab": "Profil",
"demoSnackbarsButtonLabel": "POKAŻ PASEK POWIADOMIEŃ",
"demoSnackbarsDescription": "Paski powiadomień informują użytkowników o działaniach, które aplikacje wykonały lub mają wykonać. Pojawiają się tymczasowo u dołu ekranu. Zazwyczaj nie przeszkadzają w korzystaniu z urządzenia, ponieważ znikają bez żadnych działań użytkownika.",
"demoSnackbarsSubtitle": "Paski powiadomień wyświetlają komunikaty u dołu ekranu",
"demoSnackbarsTitle": "Paski powiadomień",
"demoCupertinoSliderTitle": "Suwak",
"cupertinoTabBarChatTab": "Czat",
"cupertinoTabBarHomeTab": "Strona główna",
"demoCupertinoTabBarDescription": "Dolny pasek nawigacyjny w stylu iOS z kartami. Wyświetla wiele kart, w tym jedną aktywną (domyślnie pierwszą).",
"demoCupertinoTabBarSubtitle": "Dolny pasek kart w stylu iOS",
"demoOptionsFeatureTitle": "Wyświetl opcje",
"demoOptionsFeatureDescription": "Kliknij tutaj, by zobaczyć opcje dostępne w tej wersji demonstracyjnej.",
"demoCodeViewerCopyAll": "KOPIUJ WSZYSTKO",
"shrineScreenReaderRemoveProductButton": "Usuń {product}",
"shrineScreenReaderProductAddToCart": "Dodaj do koszyka",
"shrineScreenReaderCart": "{quantity,plural,=0{Koszyk, pusty}=1{Koszyk, 1 produkt}few{Koszyk, {quantity} produkty}many{Koszyk, {quantity} produktów}other{Koszyk, {quantity} produktu}}",
"demoCodeViewerFailedToCopyToClipboardMessage": "Nie udało się skopiować do schowka: {error}",
"demoCodeViewerCopiedToClipboardMessage": "Skopiowano do schowka.",
"craneSleep8SemanticLabel": "Ruiny budowli Majów na klifie przy plaży",
"craneSleep4SemanticLabel": "Hotel nad jeziorem z górami w tle",
"craneSleep2SemanticLabel": "Cytadela Machu Picchu",
"craneSleep1SemanticLabel": "Zimowa chatka wśród zielonych drzew",
"craneSleep0SemanticLabel": "Bungalowy na wodzie",
"craneFly13SemanticLabel": "Nadmorski basen z palmami",
"craneFly12SemanticLabel": "Basen z palmami",
"craneFly11SemanticLabel": "Ceglana latarnia na tle morza",
"craneFly10SemanticLabel": "Wieże meczetu Al-Azhar w promieniach zachodzącego słońca",
"craneFly9SemanticLabel": "Mężczyzna opierający się o zabytkowy niebieski samochód",
"craneFly8SemanticLabel": "Supertree Grove",
"craneEat9SemanticLabel": "Kawiarniana lada z wypiekami",
"craneEat2SemanticLabel": "Burger",
"craneFly5SemanticLabel": "Hotel nad jeziorem z górami w tle",
"demoSelectionControlsSubtitle": "Pola wyboru, przyciski opcji i przełączniki",
"craneEat10SemanticLabel": "Kobieta trzymająca dużą kanapkę z pastrami",
"craneFly4SemanticLabel": "Bungalowy na wodzie",
"craneEat7SemanticLabel": "Wejście do piekarni",
"craneEat6SemanticLabel": "Talerz pełen krewetek",
"craneEat5SemanticLabel": "Miejsca do siedzenia w artystycznej restauracji",
"craneEat4SemanticLabel": "Deser czekoladowy",
"craneEat3SemanticLabel": "Koreańskie taco",
"craneFly3SemanticLabel": "Cytadela Machu Picchu",
"craneEat1SemanticLabel": "Pusty bar ze stołkami barowymi",
"craneEat0SemanticLabel": "Pizza w piecu opalanym drewnem",
"craneSleep11SemanticLabel": "Wieżowiec Taipei 101",
"craneSleep10SemanticLabel": "Wieże meczetu Al-Azhar w promieniach zachodzącego słońca",
"craneSleep9SemanticLabel": "Ceglana latarnia na tle morza",
"craneEat8SemanticLabel": "Talerz pełen raków",
"craneSleep7SemanticLabel": "Kolorowe domy na placu Ribeira",
"craneSleep6SemanticLabel": "Basen z palmami",
"craneSleep5SemanticLabel": "Namiot w polu",
"settingsButtonCloseLabel": "Zamknij ustawienia",
"demoSelectionControlsCheckboxDescription": "Pola wyboru pozwalają użytkownikowi na wybranie jednej lub kilku opcji z wielu dostępnych. Zazwyczaj pole wyboru ma wartość „prawda” i „fałsz”. Pole trójstanowe może mieć też wartość zerową (null).",
"settingsButtonLabel": "Ustawienia",
"demoListsTitle": "Listy",
"demoListsSubtitle": "Przewijanie układów list",
"demoListsDescription": "Jeden wiersz o stałej wysokości, który zwykle zawiera tekst i ikonę na początku lub na końcu.",
"demoOneLineListsTitle": "Jeden wiersz",
"demoTwoLineListsTitle": "Dwa wiersze",
"demoListsSecondary": "Tekst dodatkowy",
"demoSelectionControlsTitle": "Elementy wyboru",
"craneFly7SemanticLabel": "Mount Rushmore",
"demoSelectionControlsCheckboxTitle": "Pole wyboru",
"craneSleep3SemanticLabel": "Mężczyzna opierający się o zabytkowy niebieski samochód",
"demoSelectionControlsRadioTitle": "Przycisk opcji",
"demoSelectionControlsRadioDescription": "Przyciski opcji pozwalają na wybranie jednej z kilku dostępnych opcji. Należy ich używać, by użytkownik wybrał tylko jedną opcję, ale mógł zobaczyć wszystkie pozostałe.",
"demoSelectionControlsSwitchTitle": "Przełącznik",
"demoSelectionControlsSwitchDescription": "Przełączniki służą do włączania i wyłączania opcji w ustawieniach. Opcja związana z przełącznikiem oraz jej stan powinny być w jasny sposób opisane za pomocą etykiety tekstowej.",
"craneFly0SemanticLabel": "Zimowa chatka wśród zielonych drzew",
"craneFly1SemanticLabel": "Namiot w polu",
"craneFly2SemanticLabel": "Flagi modlitewne na tle zaśnieżonej góry",
"craneFly6SemanticLabel": "Palacio de Bellas Artes z lotu ptaka",
"rallySeeAllAccounts": "Wyświetl wszystkie konta",
"rallyBillAmount": "{billName} ma termin: {date}, kwota: {amount}.",
"shrineTooltipCloseCart": "Zamknij koszyk",
"shrineTooltipCloseMenu": "Zamknij menu",
"shrineTooltipOpenMenu": "Otwórz menu",
"shrineTooltipSettings": "Ustawienia",
"shrineTooltipSearch": "Szukaj",
"demoTabsDescription": "Karty pozwalają na porządkowanie treści z wielu ekranów, ze zbiorów danych oraz interakcji.",
"demoTabsSubtitle": "Karty, które można przewijać niezależnie",
"demoTabsTitle": "Karty",
"rallyBudgetAmount": "Budżet {budgetName}: wykorzystano {amountUsed} z {amountTotal}, pozostało: {amountLeft}",
"shrineTooltipRemoveItem": "Usuń element",
"rallyAccountAmount": "Nazwa konta: {accountName}, nr konta {accountNumber}, kwota {amount}.",
"rallySeeAllBudgets": "Wyświetl wszystkie budżety",
"rallySeeAllBills": "Wyświetl wszystkie rachunki",
"craneFormDate": "Wybierz datę",
"craneFormOrigin": "Wybierz miejsce wylotu",
"craneFly2": "Khumbu, Nepal",
"craneFly3": "Machu Picchu, Peru",
"craneFly4": "Malé, Malediwy",
"craneFly5": "Vitznau, Szwajcaria",
"craneFly6": "Meksyk (miasto), Meksyk",
"craneFly7": "Mount Rushmore, Stany Zjednoczone",
"settingsTextDirectionLocaleBased": "Na podstawie regionu",
"craneFly9": "Hawana, Kuba",
"craneFly10": "Kair, Egipt",
"craneFly11": "Lizbona, Portugalia",
"craneFly12": "Napa, Stany Zjednoczone",
"craneFly13": "Bali, Indonezja",
"craneSleep0": "Malé, Malediwy",
"craneSleep1": "Aspen, Stany Zjednoczone",
"craneSleep2": "Machu Picchu, Peru",
"demoCupertinoSegmentedControlTitle": "Sterowanie segmentowe",
"craneSleep4": "Vitznau, Szwajcaria",
"craneSleep5": "Big Sur, Stany Zjednoczone",
"craneSleep6": "Napa, Stany Zjednoczone",
"craneSleep7": "Porto, Portugalia",
"craneSleep8": "Tulum, Meksyk",
"craneEat5": "Seul, Korea Południowa",
"demoChipTitle": "Elementy",
"demoChipSubtitle": "Drobne elementy reprezentujące atrybut, działanie lub tekst do wpisania",
"demoActionChipTitle": "Ikona działania",
"demoActionChipDescription": "Elementy działań to zestawy opcji, które wywołują określone akcje związane z treścią główną. Wyświetlanie tych elementów w interfejsie powinno następować dynamicznie i zależeć od kontekstu.",
"demoChoiceChipTitle": "Element wyboru",
"demoChoiceChipDescription": "Elementy wyboru reprezentują poszczególne opcje z grupy. Elementy te zawierają powiązany z nimi opis lub kategorię.",
"demoFilterChipTitle": "Ikona filtra",
"demoFilterChipDescription": "Ikony filtrów korzystają z tagów lub słów opisowych do filtrowania treści.",
"demoInputChipTitle": "Element wprowadzania tekstu",
"demoInputChipDescription": "Elementy wprowadzania tekstu reprezentują skrócony opis złożonych informacji (na przykład na temat osób, miejsc czy przedmiotów) oraz wyrażeń używanych podczas rozmów.",
"craneSleep9": "Lizbona, Portugalia",
"craneEat10": "Lizbona, Portugalia",
"demoCupertinoSegmentedControlDescription": "Służy do wyboru opcji, które się wzajemnie wykluczają. Po wyborze jednej z opcji w sterowaniu segmentowym wybór pozostałych opcji jest anulowany.",
"chipTurnOnLights": "Włącz światła",
"chipSmall": "Małe",
"chipMedium": "Średnie",
"chipLarge": "Duże",
"chipElevator": "Winda",
"chipWasher": "Pralka",
"chipFireplace": "Kominek",
"chipBiking": "Jazda na rowerze",
"craneFormDiners": "Stołówki",
"rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Możesz zwiększyć potencjalną kwotę możliwą do odliczenia od podatku. Przydziel kategorie do 1 nieprzypisanej transakcji.}few{Możesz zwiększyć potencjalną kwotę możliwą do odliczenia od podatku. Przydziel kategorie do {count} nieprzypisanych transakcji.}many{Możesz zwiększyć potencjalną kwotę możliwą do odliczenia od podatku. Przydziel kategorie do {count} nieprzypisanych transakcji.}other{Możesz zwiększyć potencjalną kwotę możliwą do odliczenia od podatku. Przydziel kategorie do {count} nieprzypisanej transakcji.}}",
"craneFormTime": "Wybierz godzinę",
"craneFormLocation": "Wybierz lokalizację",
"craneFormTravelers": "Podróżujący",
"craneEat8": "Atlanta, Stany Zjednoczone",
"craneFormDestination": "Wybierz cel podróży",
"craneFormDates": "Wybierz daty",
"craneFly": "LOTY",
"craneSleep": "SEN",
"craneEat": "JEDZENIE",
"craneFlySubhead": "Przeglądaj loty według celu podróży",
"craneSleepSubhead": "Przeglądaj miejsca zakwaterowania według celu podróży",
"craneEatSubhead": "Przeglądaj restauracje według celu podróży",
"craneFlyStops": "{numberOfStops,plural,=0{Bez przesiadek}=1{1 przesiadka}few{{numberOfStops} przesiadki}many{{numberOfStops} przesiadek}other{{numberOfStops} przesiadki}}",
"craneSleepProperties": "{totalProperties,plural,=0{Brak dostępnych miejsc zakwaterowania}=1{1 dostępne miejsce zakwaterowania}few{{totalProperties} dostępne miejsca zakwaterowania}many{{totalProperties} dostępnych miejsc zakwaterowania}other{{totalProperties} dostępnego miejsca zakwaterowania}}",
"craneEatRestaurants": "{totalRestaurants,plural,=0{Brak restauracji}=1{1 restauracja}few{{totalRestaurants} restauracje}many{{totalRestaurants} restauracji}other{{totalRestaurants} restauracji}}",
"craneFly0": "Aspen, Stany Zjednoczone",
"demoCupertinoSegmentedControlSubtitle": "Sterowanie segmentowe w stylu iOS",
"craneSleep10": "Kair, Egipt",
"craneEat9": "Madryt, Hiszpania",
"craneFly1": "Big Sur, Stany Zjednoczone",
"craneEat7": "Nashville, Stany Zjednoczone",
"craneEat6": "Seattle, Stany Zjednoczone",
"craneFly8": "Singapur",
"craneEat4": "Paryż, Francja",
"craneEat3": "Portland, Stany Zjednoczone",
"craneEat2": "Córdoba, Argentyna",
"craneEat1": "Dallas, Stany Zjednoczone",
"craneEat0": "Neapol, Włochy",
"craneSleep11": "Tajpej, Tajwan",
"craneSleep3": "Hawana, Kuba",
"shrineLogoutButtonCaption": "WYLOGUJ SIĘ",
"rallyTitleBills": "RACHUNKI",
"rallyTitleAccounts": "KONTA",
"shrineProductVagabondSack": "Worek podróżny",
"rallyAccountDetailDataInterestYtd": "Odsetki od początku roku",
"shrineProductWhitneyBelt": "Pasek Whitney",
"shrineProductGardenStrand": "Ogród",
"shrineProductStrutEarrings": "Kolczyki",
"shrineProductVarsitySocks": "Długie skarpety sportowe",
"shrineProductWeaveKeyring": "Pleciony brelok",
"shrineProductGatsbyHat": "Kaszkiet",
"shrineProductShrugBag": "Torba",
"shrineProductGiltDeskTrio": "Potrójny stolik z pozłacanymi elementami",
"shrineProductCopperWireRack": "Półka z drutu miedzianego",
"shrineProductSootheCeramicSet": "Zestaw ceramiczny Soothe",
"shrineProductHurrahsTeaSet": "Zestaw do herbaty Hurrahs",
"shrineProductBlueStoneMug": "Niebieski kubek z kamionki",
"shrineProductRainwaterTray": "Pojemnik na deszczówkę",
"shrineProductChambrayNapkins": "Batystowe chusteczki",
"shrineProductSucculentPlanters": "Doniczki na sukulenty",
"shrineProductQuartetTable": "Kwadratowy stół",
"shrineProductKitchenQuattro": "Kuchenne quattro",
"shrineProductClaySweater": "Sweter dziergany",
"shrineProductSeaTunic": "Tunika kąpielowa",
"shrineProductPlasterTunic": "Tunika",
"rallyBudgetCategoryRestaurants": "Restauracje",
"shrineProductChambrayShirt": "Koszula batystowa",
"shrineProductSeabreezeSweater": "Sweter z oczkami",
"shrineProductGentryJacket": "Kurtka męska",
"shrineProductNavyTrousers": "Granatowe spodnie",
"shrineProductWalterHenleyWhite": "Koszulka Walter Henley (biała)",
"shrineProductSurfAndPerfShirt": "Sportowa bluza do surfingu",
"shrineProductGingerScarf": "Rudy szalik",
"shrineProductRamonaCrossover": "Torebka na ramię Ramona Crossover",
"shrineProductClassicWhiteCollar": "Klasyczna z białym kołnierzykiem",
"shrineProductSunshirtDress": "Sukienka plażowa",
"rallyAccountDetailDataInterestRate": "Stopa procentowa",
"rallyAccountDetailDataAnnualPercentageYield": "Roczny zysk procentowo",
"rallyAccountDataVacation": "Urlop",
"shrineProductFineLinesTee": "Koszulka w prążki",
"rallyAccountDataHomeSavings": "Oszczędności na dom",
"rallyAccountDataChecking": "Rozliczeniowe",
"rallyAccountDetailDataInterestPaidLastYear": "Odsetki wypłacone w ubiegłym roku",
"rallyAccountDetailDataNextStatement": "Następne zestawienie",
"rallyAccountDetailDataAccountOwner": "Właściciel konta",
"rallyBudgetCategoryCoffeeShops": "Kawiarnie",
"rallyBudgetCategoryGroceries": "Produkty spożywcze",
"shrineProductCeriseScallopTee": "Koszulka Cerise z lamówkami",
"rallyBudgetCategoryClothing": "Odzież",
"rallySettingsManageAccounts": "Zarządzaj kontami",
"rallyAccountDataCarSavings": "Oszczędności na samochód",
"rallySettingsTaxDocuments": "Dokumenty podatkowe",
"rallySettingsPasscodeAndTouchId": "Hasło i Touch ID",
"rallySettingsNotifications": "Powiadomienia",
"rallySettingsPersonalInformation": "Dane osobowe",
"rallySettingsPaperlessSettings": "Ustawienia rezygnacji z wersji papierowych",
"rallySettingsFindAtms": "Znajdź bankomaty",
"rallySettingsHelp": "Pomoc",
"rallySettingsSignOut": "Wyloguj się",
"rallyAccountTotal": "Łącznie",
"rallyBillsDue": "Termin",
"rallyBudgetLeft": "Pozostało",
"rallyAccounts": "Konta",
"rallyBills": "Rachunki",
"rallyBudgets": "Budżety",
"rallyAlerts": "Alerty",
"rallySeeAll": "ZOBACZ WSZYSTKO",
"rallyFinanceLeft": "POZOSTAŁO",
"rallyTitleOverview": "PRZEGLĄD",
"shrineProductShoulderRollsTee": "Bluzka z odsłoniętymi ramionami",
"shrineNextButtonCaption": "DALEJ",
"rallyTitleBudgets": "BUDŻETY",
"rallyTitleSettings": "USTAWIENIA",
"rallyLoginLoginToRally": "Zaloguj się w Rally",
"rallyLoginNoAccount": "Nie masz konta?",
"rallyLoginSignUp": "ZAREJESTRUJ SIĘ",
"rallyLoginUsername": "Nazwa użytkownika",
"rallyLoginPassword": "Hasło",
"rallyLoginLabelLogin": "Zaloguj się",
"rallyLoginRememberMe": "Zapamiętaj mnie",
"rallyLoginButtonLogin": "ZALOGUJ SIĘ",
"rallyAlertsMessageHeadsUpShopping": "Uwaga – budżet zakupowy na ten miesiąc został już wykorzystany w {percent}.",
"rallyAlertsMessageSpentOnRestaurants": "Kwota wydana w restauracjach w tym tygodniu to {amount}.",
"rallyAlertsMessageATMFees": "Opłaty pobrane za wypłaty w bankomatach w tym miesiącu wyniosły {amount}",
"rallyAlertsMessageCheckingAccount": "Dobra robota. Saldo na Twoim koncie rozliczeniowym jest o {percent} wyższe niż w zeszłym miesiącu.",
"shrineMenuCaption": "MENU",
"shrineCategoryNameAll": "WSZYSTKIE",
"shrineCategoryNameAccessories": "DODATKI",
"shrineCategoryNameClothing": "ODZIEŻ",
"shrineCategoryNameHome": "AGD",
"shrineLoginUsernameLabel": "Nazwa użytkownika",
"shrineLoginPasswordLabel": "Hasło",
"shrineCancelButtonCaption": "ANULUJ",
"shrineCartTaxCaption": "Podatek:",
"shrineCartPageCaption": "KOSZYK",
"shrineProductQuantity": "Ilość: {quantity}",
"shrineProductPrice": "x {price}",
"shrineCartItemCount": "{quantity,plural,=0{Brak elementów}=1{1 ELEMENT}few{{quantity} ELEMENTY}many{{quantity} ELEMENTÓW}other{{quantity} ELEMENTU}}",
"shrineCartClearButtonCaption": "WYCZYŚĆ KOSZYK",
"shrineCartTotalCaption": "ŁĄCZNIE",
"shrineCartSubtotalCaption": "Suma częściowa:",
"shrineCartShippingCaption": "Dostawa:",
"shrineProductGreySlouchTank": "Szara bluzka na ramiączkach",
"shrineProductStellaSunglasses": "Okulary przeciwsłoneczne Stella",
"shrineProductWhitePinstripeShirt": "Biała koszula w paski",
"demoTextFieldWhereCanWeReachYou": "Jak możemy się z Tobą skontaktować?",
"settingsTextDirectionLTR": "Od lewej do prawej",
"settingsTextScalingLarge": "Duży",
"demoBottomSheetHeader": "Nagłówek",
"demoBottomSheetItem": "Element {value}",
"demoBottomTextFieldsTitle": "Pola tekstowe",
"demoTextFieldTitle": "Pola tekstowe",
"demoTextFieldSubtitle": "Pojedynczy, edytowalny wiersz tekstowo-liczbowy",
"demoTextFieldDescription": "Pola tekstowe w interfejsie pozwalają użytkownikom wpisywać tekst. Zazwyczaj używa się ich w formularzach i oknach.",
"demoTextFieldShowPasswordLabel": "Pokaż hasło",
"demoTextFieldHidePasswordLabel": "Ukryj hasło",
"demoTextFieldFormErrors": "Zanim ponownie prześlesz formularz, popraw błędy oznaczone na czerwono.",
"demoTextFieldNameRequired": "Imię i nazwisko są wymagane.",
"demoTextFieldOnlyAlphabeticalChars": "Użyj tylko znaków alfabetu.",
"demoTextFieldEnterUSPhoneNumber": "(###) ###-#### – wpisz numer telefonu w USA.",
"demoTextFieldEnterPassword": "Wpisz hasło.",
"demoTextFieldPasswordsDoNotMatch": "Hasła nie pasują do siebie",
"demoTextFieldWhatDoPeopleCallYou": "Jak się nazywasz?",
"demoTextFieldNameField": "Nazwa*",
"demoBottomSheetButtonText": "POKAŻ PLANSZĘ DOLNĄ",
"demoTextFieldPhoneNumber": "Numer telefonu*",
"demoBottomSheetTitle": "Plansza dolna",
"demoTextFieldEmail": "E-mail",
"demoTextFieldTellUsAboutYourself": "Opowiedz nam o sobie (np. napisz, czym się zajmujesz lub jakie masz hobby)",
"demoTextFieldKeepItShort": "Nie rozpisuj się – to tylko wersja demonstracyjna.",
"starterAppGenericButton": "PRZYCISK",
"demoTextFieldLifeStory": "Historia mojego życia",
"demoTextFieldSalary": "Wynagrodzenie",
"demoTextFieldUSD": "USD",
"demoTextFieldNoMoreThan": "Nie może mieć więcej niż osiem znaków.",
"demoTextFieldPassword": "Hasło*",
"demoTextFieldRetypePassword": "Wpisz ponownie hasło*",
"demoTextFieldSubmit": "PRZEŚLIJ",
"demoBottomNavigationSubtitle": "Dolna nawigacja z zanikaniem",
"demoBottomSheetAddLabel": "Dodaj",
"demoBottomSheetModalDescription": "Modalna plansza dolna to alternatywa dla menu lub okna. Uniemożliwia użytkownikowi interakcję z resztą aplikacji.",
"demoBottomSheetModalTitle": "Modalna plansza dolna",
"demoBottomSheetPersistentDescription": "Trwała plansza dolna zawiera informacje, które dopełniają podstawową zawartość aplikacji. Plansza ta jest widoczna nawet wtedy, gdy użytkownik korzysta z innych elementów aplikacji.",
"demoBottomSheetPersistentTitle": "Trwała plansza dolna",
"demoBottomSheetSubtitle": "Trwałe i modalne plansze dolne",
"demoTextFieldNameHasPhoneNumber": "{name} ma następujący numer telefonu: {phoneNumber}",
"buttonText": "PRZYCISK",
"demoTypographyDescription": "Definicje różnych stylów typograficznych dostępnych w Material Design.",
"demoTypographySubtitle": "Wszystkie predefiniowane style tekstu",
"demoTypographyTitle": "Typografia",
"demoFullscreenDialogDescription": "Właściwość fullscreenDialog określa, czy następna strona jest pełnoekranowym oknem modalnym",
"demoFlatButtonDescription": "Płaski przycisk wyświetla plamę po naciśnięciu, ale nie podnosi się. Płaskich przycisków należy używać na paskach narzędzi, w oknach dialogowych oraz w tekście z dopełnieniem.",
"demoBottomNavigationDescription": "Na paskach dolnej nawigacji u dołu ekranu może wyświetlać się od trzech do pięciu miejsc docelowych. Każde miejsce docelowe jest oznaczone ikoną i opcjonalną etykietą tekstową. Po kliknięciu ikony w dolnej nawigacji użytkownik jest przenoszony do związanego z tą ikoną miejsca docelowego w nawigacji głównego poziomu.",
"demoBottomNavigationSelectedLabel": "Wybrana etykieta",
"demoBottomNavigationPersistentLabels": "Trwałe etykiety",
"starterAppDrawerItem": "Element {value}",
"demoTextFieldRequiredField": "* pole wymagane",
"demoBottomNavigationTitle": "Dolna nawigacja",
"settingsLightTheme": "Jasny",
"settingsTheme": "Motyw",
"settingsPlatformIOS": "iOS",
"settingsPlatformAndroid": "Android",
"settingsTextDirectionRTL": "Od prawej do lewej",
"settingsTextScalingHuge": "Wielki",
"cupertinoButton": "Przycisk",
"settingsTextScalingNormal": "Normalny",
"settingsTextScalingSmall": "Mały",
"settingsSystemDefault": "Systemowy",
"settingsTitle": "Ustawienia",
"rallyDescription": "Aplikacja do zarządzania finansami osobistymi",
"aboutDialogDescription": "Aby zobaczyć kod źródłowy tej aplikacji, odwiedź {repoLink}.",
"bottomNavigationCommentsTab": "Komentarze",
"starterAppGenericBody": "Treść",
"starterAppGenericHeadline": "Nagłówek",
"starterAppGenericSubtitle": "Podtytuł",
"starterAppGenericTitle": "Tytuł",
"starterAppTooltipSearch": "Szukaj",
"starterAppTooltipShare": "Udostępnij",
"starterAppTooltipFavorite": "Ulubione",
"starterAppTooltipAdd": "Dodaj",
"bottomNavigationCalendarTab": "Kalendarz",
"starterAppDescription": "Elastyczny układ początkowy",
"starterAppTitle": "Aplikacja wyjściowa",
"aboutFlutterSamplesRepo": "Repozytorium z przykładami Flutter w serwisie GitHub",
"bottomNavigationContentPlaceholder": "Obiekt zastępczy karty {title}",
"bottomNavigationCameraTab": "Aparat",
"bottomNavigationAlarmTab": "Alarm",
"bottomNavigationAccountTab": "Konto",
"demoTextFieldYourEmailAddress": "Twój adres e-mail",
"demoToggleButtonDescription": "Za pomocą przycisków przełączania można grupować powiązane opcje. Aby uwyraźnić grupę powiązanych przycisków przełączania, grupa powinna znajdować się we wspólnej sekcji.",
"colorsGrey": "SZARY",
"colorsBrown": "BRĄZOWY",
"colorsDeepOrange": "GŁĘBOKI POMARAŃCZOWY",
"colorsOrange": "POMARAŃCZOWY",
"colorsAmber": "BURSZTYNOWY",
"colorsYellow": "ŻÓŁTY",
"colorsLime": "LIMONKOWY",
"colorsLightGreen": "JASNOZIELONY",
"colorsGreen": "ZIELONY",
"homeHeaderGallery": "Galeria",
"homeHeaderCategories": "Kategorie",
"shrineDescription": "Aplikacja dla sklepów z modą",
"craneDescription": "Spersonalizowana aplikacja dla podróżujących",
"homeCategoryReference": "STYLE I INNE",
"demoInvalidURL": "Nie udało się wyświetlić adresu URL:",
"demoOptionsTooltip": "Opcje",
"demoInfoTooltip": "Informacje",
"demoCodeTooltip": "Kod wersji demonstracyjnej",
"demoDocumentationTooltip": "Dokumentacja interfejsu API",
"demoFullscreenTooltip": "Pełny ekran",
"settingsTextScaling": "Skalowanie tekstu",
"settingsTextDirection": "Kierunek tekstu",
"settingsLocale": "Region",
"settingsPlatformMechanics": "Mechanika platformy",
"settingsDarkTheme": "Ciemny",
"settingsSlowMotion": "Zwolnione tempo",
"settingsAbout": "Flutter Gallery – informacje",
"settingsFeedback": "Prześlij opinię",
"settingsAttribution": "Zaprojektowane przez TOASTER w Londynie",
"demoButtonTitle": "Przyciski",
"demoButtonSubtitle": "Przycisk tekstowy, podniesiony, z konturem itp.",
"demoFlatButtonTitle": "Płaski przycisk",
"demoRaisedButtonDescription": "Przyciski podniesione dodają głębi układom, które są w znacznej mierze płaskie. Zwracają uwagę na funkcje w mocno wypełnionych lub dużych obszarach.",
"demoRaisedButtonTitle": "Uniesiony przycisk",
"demoOutlineButtonTitle": "Przycisk z konturem",
"demoOutlineButtonDescription": "Przyciski z konturem stają się nieprzezroczyste i podnoszą się po naciśnięciu. Często występują w parze z przyciskami podniesionymi, by wskazać działanie alternatywne.",
"demoToggleButtonTitle": "Przyciski przełączania",
"colorsTeal": "MORSKI",
"demoFloatingButtonTitle": "Pływający przycisk polecenia",
"demoFloatingButtonDescription": "Pływający przycisk polecenia to okrągły przycisk z ikoną wyświetlany nad treścią, by promować główne działanie w aplikacji.",
"demoDialogTitle": "Okna",
"demoDialogSubtitle": "Proste, alertu i pełnoekranowe",
"demoAlertDialogTitle": "Alert",
"demoAlertDialogDescription": "Okno alertu informuje użytkownika o sytuacjach wymagających potwierdzenia. Okno alertu ma opcjonalny tytuł i opcjonalną listę działań.",
"demoAlertTitleDialogTitle": "Alert z tytułem",
"demoSimpleDialogTitle": "Proste",
"demoSimpleDialogDescription": "Proste okno dające użytkownikowi kilka opcji do wyboru. Proste okno z opcjonalnym tytułem wyświetlanym nad opcjami.",
"demoFullscreenDialogTitle": "Pełny ekran",
"demoCupertinoButtonsTitle": "Przyciski",
"demoCupertinoButtonsSubtitle": "Przyciski w stylu iOS",
"demoCupertinoButtonsDescription": "Przycisk w stylu iOS. Przyjmuje tekst lub ikonę, które zanikają i powracają po naciśnięciu. Opcjonalnie może mieć tło.",
"demoCupertinoAlertsTitle": "Alerty",
"demoCupertinoAlertsSubtitle": "Okna alertów w stylu iOS",
"demoCupertinoAlertTitle": "Alert",
"demoCupertinoAlertDescription": "Okno alertu informuje użytkownika o sytuacjach wymagających potwierdzenia. Okno alertu ma opcjonalny tytuł, opcjonalną treść i opcjonalną listę działań. Tytuł jest wyświetlany nad treścią, a działania pod treścią.",
"demoCupertinoAlertWithTitleTitle": "Alert z tytułem",
"demoCupertinoAlertButtonsTitle": "Alert z przyciskami",
"demoCupertinoAlertButtonsOnlyTitle": "Tylko przyciski alertu",
"demoCupertinoActionSheetTitle": "Arkusz działań",
"demoCupertinoActionSheetDescription": "Arkusz działań to styl alertu, który prezentuje użytkownikowi co najmniej dwie opcje związane z bieżącym kontekstem. Arkusz działań może mieć tytuł, dodatkowy komunikat i listę działań.",
"demoColorsTitle": "Kolory",
"demoColorsSubtitle": "Wszystkie predefiniowane kolory",
"demoColorsDescription": "Stałe kolorów i próbek kolorów, które reprezentują paletę interfejsu Material Design.",
"buttonTextEnabled": "ENABLED",
"buttonTextDisabled": "DISABLED",
"buttonTextCreate": "Utwórz",
"dialogSelectedOption": "Wybrano: „{value}”",
"dialogDiscardTitle": "Odrzucić wersję roboczą?",
"dialogLocationTitle": "Użyć usługi lokalizacyjnej Google?",
"dialogLocationDescription": "Google może ułatwiać aplikacjom określanie lokalizacji. Wymaga to wysyłania do Google anonimowych informacji o lokalizacji, nawet gdy nie są uruchomione żadne aplikacje.",
"dialogCancel": "ANULUJ",
"dialogDiscard": "ODRZUĆ",
"dialogDisagree": "NIE ZGADZAM SIĘ",
"dialogAgree": "ZGADZAM SIĘ",
"dialogSetBackup": "Ustaw konto kopii zapasowej",
"colorsBlueGrey": "NIEBIESKOSZARY",
"dialogShow": "WYŚWIETL OKNO",
"dialogFullscreenTitle": "Okno pełnoekranowe",
"dialogFullscreenSave": "ZAPISZ",
"dialogFullscreenDescription": "Prezentacja okna pełnoekranowego",
"cupertinoButtonEnabled": "Enabled",
"cupertinoButtonDisabled": "Disabled",
"cupertinoButtonWithBackground": "Z tłem",
"cupertinoAlertCancel": "Anuluj",
"cupertinoAlertDiscard": "Odrzuć",
"cupertinoAlertLocationTitle": "Zezwolić „Mapom” na dostęp do Twojej lokalizacji, gdy używasz aplikacji?",
"cupertinoAlertLocationDescription": "Twoja bieżąca lokalizacja będzie wyświetlana na mapie i używana do pokazywania trasy, wyników wyszukiwania w pobliżu oraz szacunkowych czasów podróży.",
"cupertinoAlertAllow": "Zezwól",
"cupertinoAlertDontAllow": "Nie zezwalaj",
"cupertinoAlertFavoriteDessert": "Wybierz ulubiony deser",
"cupertinoAlertDessertDescription": "Wybierz z poniższej listy swój ulubiony rodzaj deseru. Na tej podstawie dostosujemy listę sugerowanych punktów gastronomicznych w Twojej okolicy.",
"cupertinoAlertCheesecake": "Sernik",
"cupertinoAlertTiramisu": "Tiramisu",
"cupertinoAlertApplePie": "Szarlotka",
"cupertinoAlertChocolateBrownie": "Brownie czekoladowe",
"cupertinoShowAlert": "Pokaż alert",
"colorsRed": "CZERWONY",
"colorsPink": "RÓŻOWY",
"colorsPurple": "FIOLETOWY",
"colorsDeepPurple": "GŁĘBOKI FIOLETOWY",
"colorsIndigo": "INDYGO",
"colorsBlue": "NIEBIESKI",
"colorsLightBlue": "JASNONIEBIESKI",
"colorsCyan": "CYJAN",
"dialogAddAccount": "Dodaj konto",
"Gallery": "Galeria",
"Categories": "Kategorie",
"SHRINE": "SHRINE",
"Basic shopping app": "Prosta aplikacja zakupowa",
"RALLY": "RALLY",
"CRANE": "CRANE",
"Travel app": "Aplikacja dla podróżujących",
"MATERIAL": "MATERIAL",
"CUPERTINO": "CUPERTINO",
"REFERENCE STYLES & MEDIA": "REFERENCYJNE STYLE I MULTIMEDIA"
}
| gallery/lib/l10n/intl_pl.arb/0 | {
"file_path": "gallery/lib/l10n/intl_pl.arb",
"repo_id": "gallery",
"token_count": 23273
} | 862 |
{
"loading": "กำลังโหลด",
"deselect": "ยกเลิกการเลือก",
"select": "เลือก",
"selectable": "เลือกได้ (กดค้าง)",
"selected": "เลือกแล้ว",
"demo": "เดโม",
"bottomAppBar": "แถบด้านล่างของแอป",
"notSelected": "ไม่ได้เลือก",
"demoCupertinoSearchTextFieldTitle": "ช่องข้อความค้นหา",
"demoCupertinoPicker": "เครื่องมือเลือก",
"demoCupertinoSearchTextFieldSubtitle": "ช่องข้อความค้นหารูปแบบ iOS",
"demoCupertinoSearchTextFieldDescription": "ช่องข้อความค้นหาที่ช่วยให้ผู้ใช้ค้นหาได้โดยการป้อนข้อความ ทั้งยังเสนอและกรองตัวเลือกที่แนะนำได้",
"demoCupertinoSearchTextFieldPlaceholder": "ป้อนข้อความ",
"demoCupertinoScrollbarTitle": "แถบเลื่อน",
"demoCupertinoScrollbarSubtitle": "แถบเลื่อนรูปแบบ iOS",
"demoCupertinoScrollbarDescription": "แถบเลื่อนที่รวมองค์ประกอบย่อยที่ระบุ",
"demoTwoPaneItem": "รายการ {value}",
"demoTwoPaneList": "รายการ",
"demoTwoPaneFoldableLabel": "พับได้",
"demoTwoPaneSmallScreenLabel": "หน้าจอขนาดเล็ก",
"demoTwoPaneSmallScreenDescription": "นี่คือลักษณะการทำงานของ TwoPane ในอุปกรณ์ที่มีหน้าจอขนาดเล็ก",
"demoTwoPaneTabletLabel": "แท็บเล็ต/เดสก์ท็อป",
"demoTwoPaneTabletDescription": "นี่คือลักษณะการทำงานของ TwoPane ในอุปกรณ์ที่มีหน้าจอขนาดใหญ่ขึ้น เช่น แท็บเล็ตหรือเดสก์ท็อป",
"demoTwoPaneTitle": "TwoPane",
"demoTwoPaneSubtitle": "เลย์เอาต์ที่ปรับเปลี่ยนตามอุปกรณ์ในอุปกรณ์ที่พับได้ อุปกรณ์หน้าจอขนาดใหญ่ และอุปกรณ์หน้าจอขนาดเล็ก",
"splashSelectDemo": "เลือกเดโม",
"demoTwoPaneFoldableDescription": "นี่คือลักษณะการทำงานของ TwoPane ในอุปกรณ์ที่พับได้",
"demoTwoPaneDetails": "รายละเอียด",
"demoTwoPaneSelectItem": "เลือกรายการ",
"demoTwoPaneItemDetails": "รายละเอียดรายการ {value}",
"demoCupertinoContextMenuActionText": "แตะโลโก้ Flutter ค้างไว้เพื่อดูเมนูตามบริบท",
"demoCupertinoContextMenuDescription": "เมนูตามบริบทเต็มหน้าจอแบบ iOS ที่ปรากฏเมื่อมีการกดองค์ประกอบค้างไว้",
"demoAppBarTitle": "แถบแอป",
"demoAppBarDescription": "แถบแอปแสดงเนื้อหาและการทำงานที่เกี่ยวข้องกับหน้าจอปัจจุบัน ใช้สำหรับการสร้างแบรนด์ ชื่อหน้าจอ การนำทาง และการทำงาน",
"demoDividerTitle": "ตัวแบ่ง",
"demoDividerSubtitle": "ตัวแบ่งคือเส้นบางๆ ที่จัดเนื้อหาในรายการและเลย์เอาต์ไว้เป็นกลุ่ม",
"demoDividerDescription": "ตัวแบ่งสามารถใช้แยกเนื้อหาในรายการ ลิ้นชัก และตำแหน่งอื่นๆ",
"demoVerticalDividerTitle": "ตัวแบ่งแนวตั้ง",
"demoCupertinoContextMenuTitle": "เมนูตามบริบท",
"demoCupertinoContextMenuSubtitle": "เมนูตามบริบทแบบ iOS",
"demoAppBarSubtitle": "แสดงข้อมูลและการทำงานที่เกี่ยวข้องกับหน้าจอปัจจุบัน",
"demoCupertinoContextMenuActionOne": "การทำงาน 1",
"demoCupertinoContextMenuActionTwo": "การทำงาน 2",
"demoDateRangePickerDescription": "แสดงกล่องโต้ตอบที่มีเครื่องมือเลือกช่วงวันที่แบบ Material Design",
"demoDateRangePickerTitle": "เครื่องมือเลือกช่วงวันที่",
"demoNavigationDrawerUserName": "ชื่อผู้ใช้",
"demoNavigationDrawerUserEmail": "[email protected]",
"demoNavigationDrawerText": "เลื่อนจากขอบหรือแตะไอคอนด้านซ้ายบนเพื่อดูลิ้นชัก",
"demoNavigationRailTitle": "แถบข้างสำหรับไปยังส่วนต่างๆ",
"demoNavigationRailSubtitle": "การแสดงแถบข้างสำหรับไปยังส่วนต่างๆ ภายในแอป",
"demoNavigationRailDescription": "วิดเจ็ตแบบ Material ที่มีไว้เพื่อแสดงบริเวณด้านซ้ายหรือขวาของแอปสำหรับการไปยังส่วนต่างๆ ระหว่างมุมมองไม่กี่มุมมอง โดยทั่วไปจะอยู่ที่ระหว่าง 3 ถึง 5 มุมมอง",
"demoNavigationRailFirst": "อันดับที่ 1",
"demoNavigationDrawerTitle": "ลิ้นชักการนำทาง",
"demoNavigationRailThird": "อันดับที่ 3",
"replyStarredLabel": "ที่ติดดาว",
"demoTextButtonDescription": "ปุ่มข้อความจะแสดงการไฮไลต์เมื่อกดแต่จะไม่ยกขึ้น ใช้ปุ่มข้อความกับแถบเครื่องมือ ในกล่องโต้ตอบ และแทรกในบรรทัดแบบมีระยะห่างจากขอบ",
"demoElevatedButtonTitle": "ปุ่มแบบยกขึ้น",
"demoElevatedButtonDescription": "ปุ่มแบบยกขึ้นช่วยเพิ่มมิติให้แก่เลย์เอาต์แบบแบนราบเป็นส่วนใหญ่ โดยจะช่วยเน้นฟังก์ชันในพื้นที่ที่มีการใช้งานมากหรือกว้างขวาง",
"demoOutlinedButtonTitle": "ปุ่มแบบเติมขอบ",
"demoOutlinedButtonDescription": "ปุ่มแบบเติมขอบจะเปลี่ยนเป็นสีทึบและยกขึ้นเมื่อกด มักจับคู่กับปุ่มแบบยกขึ้นเพื่อระบุว่ามีการดำเนินการสำรองอย่างอื่น",
"demoContainerTransformDemoInstructions": "การ์ด รายการ และ FAB",
"demoNavigationDrawerSubtitle": "การแสดงลิ้นชักภายในแถบแอป",
"replyDescription": "แอปอีเมลที่ตรงจุดและมีประสิทธิภาพ",
"demoNavigationDrawerDescription": "แผงแบบ Material Design ที่เลื่อนในแนวนอนจากขอบของหน้าจอเพื่อแสดงลิงก์ไปยังส่วนต่างๆ ในแอปพลิเคชัน",
"replyDraftsLabel": "ร่างจดหมาย",
"demoNavigationDrawerToPageOne": "รายการที่ 1",
"replyInboxLabel": "กล่องจดหมาย",
"demoSharedXAxisDemoInstructions": "ปุ่มถัดไปและย้อนกลับ",
"replySpamLabel": "จดหมายขยะ",
"replyTrashLabel": "ถังขยะ",
"replySentLabel": "ส่งแล้ว",
"demoNavigationRailSecond": "อันดับที่ 2",
"demoNavigationDrawerToPageTwo": "รายการที่ 2",
"demoFadeScaleDemoInstructions": "รูปแบบและ FAB",
"demoFadeThroughDemoInstructions": "การไปยังส่วนต่างๆ ด้านล่าง",
"demoSharedZAxisDemoInstructions": "ปุ่มไอคอนการตั้งค่า",
"demoSharedYAxisDemoInstructions": "เรียงตาม \"ฟังล่าสุด\"",
"demoTextButtonTitle": "ปุ่มข้อความ",
"demoSharedZAxisBeefSandwichRecipeTitle": "แซนด์วิชเนื้อ",
"demoSharedZAxisDessertRecipeDescription": "สูตรของหวาน",
"demoSharedYAxisAlbumTileSubtitle": "ศิลปิน",
"demoSharedYAxisAlbumTileTitle": "อัลบั้ม",
"demoSharedYAxisRecentSortTitle": "ฟังล่าสุด",
"demoSharedYAxisAlphabeticalSortTitle": "A-Z",
"demoSharedYAxisAlbumCount": "268 อัลบั้ม",
"demoSharedYAxisTitle": "แกน Y ที่ใช้ร่วมกัน",
"demoSharedXAxisCreateAccountButtonText": "สร้างบัญชี",
"demoFadeScaleAlertDialogDiscardButton": "ทิ้ง",
"demoSharedXAxisSignInTextFieldLabel": "อีเมลหรือหมายเลขโทรศัพท์",
"demoSharedXAxisSignInSubtitleText": "ลงชื่อเข้าใช้บัญชีของคุณ",
"demoSharedXAxisSignInWelcomeText": "สวัสดี David Park",
"demoSharedXAxisIndividualCourseSubtitle": "แสดงแยกแต่ละรายการ",
"demoSharedXAxisBundledCourseSubtitle": "แพ็กเกจ",
"demoFadeThroughAlbumsDestination": "อัลบั้ม",
"demoSharedXAxisDesignCourseTitle": "การออกแบบ",
"demoSharedXAxisIllustrationCourseTitle": "ภาพ",
"demoSharedXAxisBusinessCourseTitle": "ธุรกิจ",
"demoSharedXAxisArtsAndCraftsCourseTitle": "ศิลปะและหัตถกรรม",
"demoMotionPlaceholderSubtitle": "ข้อความรอง",
"demoFadeScaleAlertDialogCancelButton": "ยกเลิก",
"demoFadeScaleAlertDialogHeader": "กล่องโต้ตอบการแจ้งเตือน",
"demoFadeScaleHideFabButton": "ซ่อน FAB",
"demoFadeScaleShowFabButton": "แสดง FAB",
"demoFadeScaleShowAlertDialogButton": "แสดงรูปแบบ",
"demoFadeScaleDescription": "รูปแบบ \"จางลง\" ใช้กับองค์ประกอบ UI ที่เข้าหรือออกภายในขอบเขตหน้าจอ เช่นกล่องโต้ตอบที่จางลงตรงกลางของหน้าจอ",
"demoFadeScaleTitle": "จางลง",
"demoFadeThroughTextPlaceholder": "123 รูปภาพ",
"demoFadeThroughSearchDestination": "ค้นหา",
"demoFadeThroughPhotosDestination": "รูปภาพ",
"demoSharedXAxisCoursePageSubtitle": "หมวดหมู่ตามกลุ่มจะแสดงเป็นกลุ่มในฟีดของคุณ ซึ่งคุณจะเปลี่ยนแปลงได้ในภายหลังเสมอ",
"demoFadeThroughDescription": "รูปแบบ \"จางผ่าน\" ใช้กับการเปลี่ยนระหว่างองค์ประกอบ UI ที่ไม่มีความสัมพันธ์ที่มีอิทธิพลต่อกัน",
"demoFadeThroughTitle": "จางผ่าน",
"demoSharedZAxisHelpSettingLabel": "ความช่วยเหลือ",
"demoMotionSubtitle": "รูปแบบต่างๆ ของการเปลี่ยนที่กำหนดค่าไว้ล่วงหน้า",
"demoSharedZAxisNotificationSettingLabel": "การแจ้งเตือน",
"demoSharedZAxisProfileSettingLabel": "โปรไฟล์",
"demoSharedZAxisSavedRecipesListTitle": "สูตรที่บันทึกไว้",
"demoSharedZAxisBeefSandwichRecipeDescription": "สูตรแซนด์วิชเนื้อ",
"demoSharedZAxisCrabPlateRecipeDescription": "สูตรอาหารจานปู",
"demoSharedXAxisCoursePageTitle": "ปรับปรุงหลักสูตรของคุณให้มีประสิทธิภาพ",
"demoSharedZAxisCrabPlateRecipeTitle": "ปู",
"demoSharedZAxisShrimpPlateRecipeDescription": "สูตรอาหารจานกุ้ง",
"demoSharedZAxisShrimpPlateRecipeTitle": "กุ้ง",
"demoContainerTransformTypeFadeThrough": "จางผ่าน",
"demoSharedZAxisDessertRecipeTitle": "ของหวาน",
"demoSharedZAxisSandwichRecipeDescription": "สูตรแซนด์วิช",
"demoSharedZAxisSandwichRecipeTitle": "แซนด์วิช",
"demoSharedZAxisBurgerRecipeDescription": "สูตรเบอร์เกอร์",
"demoSharedZAxisBurgerRecipeTitle": "เบอร์เกอร์",
"demoSharedZAxisSettingsPageTitle": "การตั้งค่า",
"demoSharedZAxisTitle": "แกน Z ที่ใช้ร่วมกัน",
"demoSharedZAxisPrivacySettingLabel": "ความเป็นส่วนตัว",
"demoMotionTitle": "การเคลื่อนไหว",
"demoContainerTransformTitle": "เปลี่ยนรูปแบบคอนเทนเนอร์",
"demoContainerTransformDescription": "รูปแบบ \"เปลี่ยนรูปแบบคอนเทนเนอร์\" ออกแบบมาสำหรับการเปลี่ยนระหว่างองค์ประกอบ UI ที่มีคอนเทนเนอร์ รูปแบบนี้สร้างการเชื่อมต่อที่มองเห็นได้ระหว่างองค์ประกอบ UI 2 รายการ",
"demoContainerTransformModalBottomSheetTitle": "โหมดจาง",
"demoContainerTransformTypeFade": "จางลง",
"demoSharedYAxisAlbumTileDurationUnit": "นาที",
"demoMotionPlaceholderTitle": "ชื่อ",
"demoSharedXAxisForgotEmailButtonText": "หากลืมอีเมล",
"demoMotionSmallPlaceholderSubtitle": "รอง",
"demoMotionDetailsPageTitle": "หน้ารายละเอียด",
"demoMotionListTileTitle": "รายการย่อย",
"demoSharedAxisDescription": "รูปแบบ \"แกนร่วม\" ใช้ในการเปลี่ยนระหว่างองค์ประกอบ UI ที่มีความสัมพันธ์ในการนำทางหรือเชิงพื้นที่ รูปแบบนี้ใช้การเปลี่ยนรูปแบบร่วมกันบนแกน X, Y, หรือ Z เพื่อเสริมความสัมพันธ์ระหว่างองค์ประกอบต่างๆ",
"demoSharedXAxisTitle": "แกน X ที่ใช้ร่วมกัน",
"demoSharedXAxisBackButtonText": "กลับ",
"demoSharedXAxisNextButtonText": "ถัดไป",
"demoSharedXAxisCulinaryCourseTitle": "การทำอาหาร",
"githubRepo": "ที่เก็บ {repoName} ใน GitHub",
"fortnightlyMenuUS": "สหรัฐอเมริกา",
"fortnightlyMenuBusiness": "ธุรกิจ",
"fortnightlyMenuScience": "วิทยาศาสตร์",
"fortnightlyMenuSports": "กีฬา",
"fortnightlyMenuTravel": "ท่องเที่ยว",
"fortnightlyMenuCulture": "วัฒนธรรม",
"fortnightlyTrendingTechDesign": "การออกแบบและเทคโนโลยี",
"rallyBudgetDetailAmountLeft": "จำนวนที่เหลือ",
"fortnightlyHeadlineArmy": "การปฏิรูป Green Army จากภายใน",
"fortnightlyDescription": "แอปข่าวที่มุ่งเน้นเนื้อหา",
"rallyBillDetailAmountDue": "จำนวนที่ครบกำหนดชำระ",
"rallyBudgetDetailTotalCap": "จำนวนรวมสูงสุดที่กำหนด",
"rallyBudgetDetailAmountUsed": "จำนวนที่ใช้",
"fortnightlyTrendingHealthcareRevolution": "การปฏิวัติสาธารณสุข",
"fortnightlyMenuFrontPage": "หน้าแรก",
"fortnightlyMenuWorld": "ต่างประเทศ",
"rallyBillDetailAmountPaid": "จำนวนที่ชำระ",
"fortnightlyMenuPolitics": "การเมือง",
"fortnightlyHeadlineBees": "ขาดแคลนผึ้งเลี้ยง",
"fortnightlyHeadlineGasoline": "อนาคตของน้ำมันเชื้อเพลิง",
"fortnightlyTrendingGreenArmy": "GreenArmy",
"fortnightlyHeadlineFeminists": "เกิดการแบ่งพวกในหมู่นักสิทธิสตรี",
"fortnightlyHeadlineFabrics": "นักออกแบบใช้เทคโนโลยีในการสร้างผ้าแห่งอนาคต",
"fortnightlyHeadlineStocks": "คนจำนวนมากหวังพึ่งการแลกเปลี่ยนสกุลเงินขณะที่หุ้นซบเซา",
"fortnightlyTrendingReform": "การปฏิรูป",
"fortnightlyMenuTech": "เทคโนโลยี",
"fortnightlyHeadlineWar": "ชีวิตที่มีการแบ่งแยกของชาวอเมริกันในช่วงสงคราม",
"fortnightlyHeadlineHealthcare": "การปฏิวัติสาธารณสุขที่เงียบแต่ทรงพลัง",
"fortnightlyLatestUpdates": "ข้อมูลอัปเดตล่าสุด",
"fortnightlyTrendingStocks": "หุ้น",
"rallyBillDetailTotalAmount": "จำนวนรวม",
"demoCupertinoPickerDateTime": "วันที่และเวลา",
"signIn": "ลงชื่อเข้าใช้",
"dataTableRowWithSugar": "{value} ใส่น้ำตาล",
"dataTableRowApplePie": "พายแอปเปิล",
"dataTableRowDonut": "โดนัท",
"dataTableRowHoneycomb": "รังผึ้ง",
"dataTableRowLollipop": "อมยิ้ม",
"dataTableRowJellyBean": "เจลลี่บีน",
"dataTableRowGingerbread": "ขนมปังขิง",
"dataTableRowCupcake": "คัพเค้ก",
"dataTableRowEclair": "เอแคลร์",
"dataTableRowIceCreamSandwich": "แซนด์วิชไอศกรีม",
"dataTableRowFrozenYogurt": "โฟรเซนโยเกิร์ต",
"dataTableColumnIron": "เหล็ก (%)",
"dataTableColumnCalcium": "แคลเซียม (%)",
"dataTableColumnSodium": "โซเดียม (มก.)",
"demoTimePickerTitle": "เครื่องมือเลือกเวลา",
"demo2dTransformationsResetTooltip": "รีเซ็ตการเปลี่ยนรูปแบบ",
"dataTableColumnFat": "ไขมัน (ก.)",
"dataTableColumnCalories": "แคลอรี",
"dataTableColumnDessert": "ของหวาน (สำหรับ 1 ที่)",
"cardsDemoTravelDestinationLocation1": "เมืองตัญชาวร์ รัฐทมิฬนาฑู",
"demoTimePickerDescription": "แสดงกล่องโต้ตอบที่มีเครื่องมือเลือกเวลาแบบดีไซน์ Material",
"demoPickersShowPicker": "แสดงเครื่องมือเลือก",
"demoTabsScrollingTitle": "แบบเลื่อน",
"demoTabsNonScrollingTitle": "แบบไม่เลื่อน",
"craneHours": "{hours,plural,=1{1 ชม.}other{{hours} ชม.}}",
"craneMinutes": "{minutes,plural,=1{1 นาที}other{{minutes} นาที}}",
"craneFlightDuration": "{hoursShortForm} {minutesShortForm}",
"dataTableHeader": "โภชนาการ",
"demoDatePickerTitle": "เครื่องมือเลือกวันที่",
"demoPickersSubtitle": "การเลือกวันที่และเวลา",
"demoPickersTitle": "เครื่องมือเลือก",
"demo2dTransformationsEditTooltip": "แก้ไขชิ้นส่วน",
"demoDataTableDescription": "ตารางข้อมูลแสดงข้อมูลในรูปแบบตารางกริดที่ประกอบด้วยแถวและคอลัมน์ ใช้ในการจัดระเบียบข้อมูลให้ค้นหาได้ง่ายเพื่อให้ผู้ใช้มองหารูปแบบและข้อมูลเชิงลึกได้",
"demo2dTransformationsDescription": "แตะเพื่อแก้ไขชิ้นส่วนแล้วใช้ท่าทางสัมผัสเพื่อเคลื่อนไหวไปรอบๆ ฉาก ใช้ 2 นิ้วลากเพื่อเลื่อน บีบเพื่อซูม หมุน กดปุ่มรีเซ็ตเพื่อกลับไปที่การวางแนวเริ่มต้น",
"demo2dTransformationsSubtitle": "เลื่อน ซูม หมุน",
"demo2dTransformationsTitle": "การเปลี่ยนรูปแบบ 2 มิติ",
"demoCupertinoTextFieldPIN": "PIN",
"demoCupertinoTextFieldDescription": "ช่องข้อความที่ให้ผู้ใช้ป้อนข้อความด้วยแป้นพิมพ์ที่เป็นฮาร์ดแวร์หรือแป้นพิมพ์บนหน้าจอ",
"demoCupertinoTextFieldSubtitle": "ช่องข้อความแบบ iOS",
"demoCupertinoTextFieldTitle": "ช่องข้อความ",
"demoDatePickerDescription": "แสดงกล่องโต้ตอบที่มีเครื่องมือเลือกวันที่แบบดีไซน์ Material",
"demoCupertinoPickerTime": "เวลา",
"demoCupertinoPickerDate": "วันที่",
"demoCupertinoPickerTimer": "ตัวจับเวลา",
"demoCupertinoPickerDescription": "วิดเจ็ตเครื่องมือเลือกรูปแบบ iOS ที่ใช้ในการเลือกสตริง วันที่ เวลา หรือทั้งวันที่และเวลาได้",
"demoCupertinoPickerSubtitle": "เครื่องมือเลือกรูปแบบ iOS",
"demoCupertinoPickerTitle": "เครื่องมือเลือก",
"dataTableRowWithHoney": "{value} ใส่น้ำผึ้ง",
"cardsDemoTravelDestinationCity2": "เมืองเชตินาถ",
"bannerDemoResetText": "รีเซ็ตแบนเนอร์",
"bannerDemoMultipleText": "การดำเนินการหลายรายการ",
"bannerDemoLeadingText": "ไอคอนแสดงอันดับที่นำอยู่",
"dismiss": "ปิด",
"cardsDemoTappable": "แตะได้",
"cardsDemoSelectable": "เลือกได้ (กดค้าง)",
"cardsDemoExplore": "สำรวจ",
"cardsDemoExploreSemantics": "สำรวจ {destinationName}",
"cardsDemoShareSemantics": "แชร์ {destinationName}",
"cardsDemoTravelDestinationTitle1": "10 อันดับเมืองน่าไปเยือนในทมิฬนาฑู",
"cardsDemoTravelDestinationDescription1": "หมายเลข 10",
"cardsDemoTravelDestinationCity1": "เมืองตัญชาวร์",
"dataTableColumnProtein": "โปรตีน (ก.)",
"cardsDemoTravelDestinationTitle2": "ช่างฝีมือแห่งอินเดียใต้",
"cardsDemoTravelDestinationDescription2": "เครื่องปั่นไหม",
"bannerDemoText": "มีการอัปเดตรหัสผ่านในอุปกรณ์เครื่องอื่น โปรดลงชื่อเข้าใช้อีกครั้ง",
"cardsDemoTravelDestinationLocation2": "เมือง Sivaganga รัฐทมิฬนาฑู",
"cardsDemoTravelDestinationTitle3": "วัดพฤหธิศวร",
"cardsDemoTravelDestinationDescription3": "วัด",
"demoBannerTitle": "แบนเนอร์",
"demoBannerSubtitle": "กำลังแสดงแบนเนอร์ภายในรายการ",
"demoBannerDescription": "แบนเนอร์แสดงข้อความสำคัญที่สั้นกระชับและเสนอการดำเนินการให้ผู้ใช้พูด (หรือปิดแบนเนอร์) ผู้ใช้ต้องดำเนินการอย่างใดอย่างหนึ่งหากจะปิดแบนเนอร์",
"demoCardTitle": "การ์ด",
"demoCardSubtitle": "การ์ดพื้นฐานแบบมีมุมโค้งมน",
"demoCardDescription": "การ์ดคือแผ่นเอกสารที่ใช้แสดงข้อมูลที่เกี่ยวข้อง เช่น อัลบั้ม สถานที่ตั้งทางภูมิศาสตร์ มื้ออาหาร ข้อมูลติดต่อ เป็นต้น",
"demoDataTableTitle": "ตารางข้อมูล",
"demoDataTableSubtitle": "แถวและคอลัมน์ข้อมูล",
"dataTableColumnCarbs": "คาร์โบไฮเดรต (ก.)",
"placeTanjore": "ธานจาวูร์",
"demoGridListsTitle": "รายการแบบตารางกริด",
"placeFlowerMarket": "ตลาดดอกไม้",
"placeBronzeWorks": "โรงหล่อทองแดง",
"placeMarket": "ตลาด",
"placeThanjavurTemple": "วัดธานจาวูร์",
"placeSaltFarm": "นาเกลือ",
"placeScooters": "สกู๊ตเตอร์",
"placeSilkMaker": "เครื่องทอผ้าไหม",
"placeLunchPrep": "เตรียมอาหารกลางวัน",
"placeBeach": "ชายหาด",
"placeFisherman": "ชาวประมง",
"demoMenuSelected": "เลือกไว้: {value}",
"demoMenuRemove": "นำออก",
"demoMenuGetLink": "รับลิงก์",
"demoMenuShare": "แชร์",
"demoBottomAppBarSubtitle": "แสดงการนำทางและการทำงานที่ด้านล่าง",
"demoMenuAnItemWithASectionedMenu": "รายการพร้อมเมนูแบบเป็นส่วน",
"demoMenuADisabledMenuItem": "รายการในเมนูที่ปิดใช้",
"demoLinearProgressIndicatorTitle": "สัญญาณบอกสถานะความคืบหน้าแบบเชิงเส้น",
"demoMenuContextMenuItemOne": "รายการในเมนูตามบริบทที่ 1",
"demoMenuAnItemWithASimpleMenu": "รายการพร้อมเมนูแบบง่าย",
"demoCustomSlidersTitle": "แถบเลื่อนที่กำหนดเอง",
"demoMenuAnItemWithAChecklistMenu": "รายการพร้อมเมนูแบบรายการตรวจสอบ",
"demoCupertinoActivityIndicatorTitle": "สัญญาณบอกสถานะกิจกรรม",
"demoCupertinoActivityIndicatorSubtitle": "สัญญาณบอกสถานะกิจกรรมแบบ iOS",
"demoCupertinoActivityIndicatorDescription": "สัญญาณบอกสถานะกิจกรรมแบบ iOS ที่หมุนตามเข็มนาฬิกา",
"demoCupertinoNavigationBarTitle": "แถบนำทาง",
"demoCupertinoNavigationBarSubtitle": "แถบนำทางแบบ iOS",
"demoCupertinoNavigationBarDescription": "แถบนำทางแบบ iOS แถบนำทางคือแถบเครื่องมือที่มีชื่อหน้าเว็บแสดงอย่างน้อยที่สุดตรงกลางของแถบเครื่องมือ",
"demoCupertinoPullToRefreshTitle": "ดึงเพื่อรีเฟรช",
"demoCupertinoPullToRefreshSubtitle": "ตัวควบคุมแบบ iOS สำหรับดึงเพื่อรีเฟรช",
"demoCupertinoPullToRefreshDescription": "วิดเจ็ตที่ใช้ตัวควบคุมเนื้อหาแบบ iOS สำหรับดึงเพื่อรีเฟรช",
"demoProgressIndicatorTitle": "สัญญาณบอกสถานะความคืบหน้า",
"demoProgressIndicatorSubtitle": "เชิงเส้น วงกลม ไม่ชัดเจน",
"demoCircularProgressIndicatorTitle": "สัญญาณบอกสถานะความคืบหน้าแบบวงกลม",
"demoCircularProgressIndicatorDescription": "สัญญาณบอกสถานะความคืบหน้าแบบวงกลมของดีไซน์ Material ที่หมุนเพื่อบอกให้ทราบว่าแอปพลิเคชันยังไม่พร้อมทำงาน",
"demoMenuFour": "4",
"demoLinearProgressIndicatorDescription": "สัญญาณบอกสถานะความคืบหน้าแบบเชิงเส้นของดีไซน์ Material หรือเรียกอีกอย่างว่าแถบความคืบหน้า",
"demoTooltipTitle": "เคล็ดลับเครื่องมือ",
"demoTooltipSubtitle": "ข้อความสั้นๆ ที่แสดงเมื่อกดค้างหรือวางเมาส์เหนือองค์ประกอบ",
"demoTooltipDescription": "เคล็ดลับเครื่องมือมีป้ายกำกับข้อความที่ช่วยอธิบายฟังก์ชันของปุ่มหรือการดำเนินการผ่านอินเทอร์เฟซผู้ใช้อื่นๆ เคล็ดลับเครื่องมือจะแสดงข้อความที่เป็นประโยชน์เมื่อผู้ใช้วางเมาส์เหนือ โฟกัสที่ หรือกดค้างองค์ประกอบ",
"demoTooltipInstructions": "กดค้างหรือวางเมาส์เหนือองค์ประกอบเพื่อแสดงเคล็ดลับเครื่องมือ",
"placeChennai": "เจนไน",
"demoMenuChecked": "เลือกไว้: {value}",
"placeChettinad": "เชตินาถ",
"demoMenuPreview": "แสดงตัวอย่าง",
"demoBottomAppBarTitle": "แถบด้านล่างของแอป",
"demoBottomAppBarDescription": "แถบด้านล่างของแอปช่วยในการเข้าถึงลิ้นชักการนำทางด้านล่างและการทำงานสูงสุด 4 รายการ ซึ่งรวมถึงปุ่มการทำงานแบบลอย",
"bottomAppBarNotch": "รอยบาก",
"bottomAppBarPosition": "ตำแหน่งของปุ่มการทำงานแบบลอย",
"bottomAppBarPositionDockedEnd": "อยู่กับที่ - ส่วนท้าย",
"bottomAppBarPositionDockedCenter": "อยู่กับที่ - ตรงกลาง",
"bottomAppBarPositionFloatingEnd": "ลอย - ส่วนท้าย",
"bottomAppBarPositionFloatingCenter": "ลอย - ตรงกลาง",
"demoSlidersEditableNumericalValue": "ค่าตัวเลขที่แก้ไขได้",
"demoGridListsSubtitle": "เลย์เอาต์แบบแถวและคอลัมน์",
"demoGridListsDescription": "ลิสต์แบบตารางกริดเหมาะสมที่สุดสำหรับการนำเสนอข้อมูลที่มีลักษณะเหมือนกันซึ่งมักจะเป็นรูปภาพ โดยแต่ละรายการในลิสต์แบบตารางกริดเรียกว่าการ์ด",
"demoGridListsImageOnlyTitle": "รูปภาพเท่านั้น",
"demoGridListsHeaderTitle": "พร้อมส่วนหัว",
"demoGridListsFooterTitle": "พร้อมส่วนท้าย",
"demoSlidersTitle": "แถบเลื่อน",
"demoSlidersSubtitle": "วิดเจ็ตสำหรับเลือกค่าด้วยการเลื่อน",
"demoSlidersDescription": "แถบเลื่อนแสดงช่วงของค่าในแถบซึ่งให้ผู้ใช้เลือกค่าใดค่าหนึ่ง เหมาะสำหรับการปรับการตั้งค่า เช่น ระดับเสียง ความสว่าง หรือการใช้ฟิลเตอร์รูปภาพ",
"demoRangeSlidersTitle": "แถบเลื่อนสำหรับช่วง",
"demoRangeSlidersDescription": "แถบเลื่อนแสดงช่วงของค่าในแถบ และอาจมีไอคอนอยู่ที่ปลายทั้ง 2 ด้านเพื่อแสดงช่วงของค่า เหมาะสำหรับการปรับการตั้งค่า เช่น ระดับเสียง ความสว่าง หรือการใช้ฟิลเตอร์รูปภาพ",
"demoMenuAnItemWithAContextMenuButton": "รายการพร้อมเมนูตามบริบท",
"demoCustomSlidersDescription": "แถบเลื่อนแสดงช่วงของค่าในแถบซึ่งให้ผู้ใช้เลือกค่าเดียวหรือช่วงค่าก็ได้ รวมถึงอาจมีธีมและการปรับแต่ง",
"demoSlidersContinuousWithEditableNumericalValue": "ต่อเนื่องโดยมีค่าตัวเลขที่แก้ไขได้",
"demoSlidersDiscrete": "ไม่ต่อเนื่อง",
"demoSlidersDiscreteSliderWithCustomTheme": "แถบเลื่อนแบบค่าไม่ต่อเนื่องซึ่งมีธีมที่กำหนดเอง",
"demoSlidersContinuousRangeSliderWithCustomTheme": "แถบเลื่อนสำหรับช่วงต่อเนื่องซึ่งมีธีมที่กำหนดเอง",
"demoSlidersContinuous": "ต่อเนื่อง",
"placePondicherry": "พอนดิเชอร์รี",
"demoMenuTitle": "เมนู",
"demoContextMenuTitle": "เมนูตามบริบท",
"demoSectionedMenuTitle": "เมนูแบบเป็นส่วน",
"demoSimpleMenuTitle": "เมนูแบบง่าย",
"demoChecklistMenuTitle": "เมนูแบบรายการตรวจสอบ",
"demoMenuSubtitle": "ปุ่มเมนูและเมนูแบบง่าย",
"demoMenuDescription": "เมนูจะแสดงรายการตัวเลือกบนพื้นผิวชั่วคราว โดยจะปรากฏขึ้นเมื่อผู้ใช้โต้ตอบกับปุ่ม การดำเนินการ หรือตัวควบคุมอื่นๆ",
"demoMenuItemValueOne": "รายการในเมนูที่ 1",
"demoMenuItemValueTwo": "รายการในเมนูที่ 2",
"demoMenuItemValueThree": "รายการในเมนูที่ 3",
"demoMenuOne": "1",
"demoMenuTwo": "2",
"demoMenuThree": "3",
"demoMenuContextMenuItemThree": "รายการในเมนูตามบริบทที่ 3",
"demoCupertinoSwitchSubtitle": "สวิตช์แบบ iOS",
"demoSnackbarsText": "นี่คือแถบแสดงข้อความ",
"demoCupertinoSliderSubtitle": "แถบเลื่อนแบบ iOS",
"demoCupertinoSliderDescription": "แถบเลื่อนอาจใช้ในการเลือกชุดค่าที่ต่อเนื่องหรือไม่ต่อเนื่อง",
"demoCupertinoSliderContinuous": "ต่อเนื่อง: {value}",
"demoCupertinoSliderDiscrete": "ไม่ต่อเนื่อง: {value}",
"demoSnackbarsAction": "คุณกดการทำงานของแถบแสดงข้อความ",
"backToGallery": "กลับไปที่แกลเลอรี",
"demoCupertinoTabBarTitle": "แถบแท็บ",
"demoCupertinoSwitchDescription": "สวิตช์ใช้ในการสลับสถานะเปิด/ปิดของการตั้งค่ารายการเดียว",
"demoSnackbarsActionButtonLabel": "การทำงาน",
"cupertinoTabBarProfileTab": "โปรไฟล์",
"demoSnackbarsButtonLabel": "แสดงแถบแสดงข้อความ",
"demoSnackbarsDescription": "แถบแสดงข้อความจะแจ้งให้ผู้ใช้ทราบเกี่ยวกับขั้นตอนที่แอปได้ทำไปแล้วหรือจะทำ แถบนี้ปรากฏชั่วคราวที่บริเวณด้านล่างของหน้าจอ ไม่ควรรบกวนประสบการณ์ของผู้ใช้ และผู้ใช้ไม่ต้องป้อนข้อมูลเพื่อให้แถบนี้หายไป",
"demoSnackbarsSubtitle": "แถบแสดงข้อความจะแสดงข้อความที่ด้านล่างของหน้าจอ",
"demoSnackbarsTitle": "แถบแสดงข้อความ",
"demoCupertinoSliderTitle": "แถบเลื่อน",
"cupertinoTabBarChatTab": "แชท",
"cupertinoTabBarHomeTab": "หน้าแรก",
"demoCupertinoTabBarDescription": "แถบแท็บการนำทางด้านล่างแบบ iOS แสดงแท็บหลายแท็บที่มี 1 แท็บใช้งานอยู่ ซึ่งโดยค่าเริ่มต้นคือแท็บแรก",
"demoCupertinoTabBarSubtitle": "แถบแท็บด้านล่างแบบ iOS",
"demoOptionsFeatureTitle": "ดูตัวเลือก",
"demoOptionsFeatureDescription": "แตะที่นี่เพื่อดูตัวเลือกสำหรับการสาธิตนี้",
"demoCodeViewerCopyAll": "คัดลอกทั้งหมด",
"shrineScreenReaderRemoveProductButton": "นำ {product} ออก",
"shrineScreenReaderProductAddToCart": "เพิ่มในรถเข็น",
"shrineScreenReaderCart": "{quantity,plural,=0{รถเข็นช็อปปิ้งไม่มีสินค้า}=1{รถเข็นช็อปปิ้งมีสินค้า 1 รายการ}other{รถเข็นช็อปปิ้งมีสินค้า {quantity} รายการ}}",
"demoCodeViewerFailedToCopyToClipboardMessage": "คัดลอกไปยังคลิปบอร์ดไม่สำเร็จ: {error}",
"demoCodeViewerCopiedToClipboardMessage": "คัดลอกไปยังคลิปบอร์ดแล้ว",
"craneSleep8SemanticLabel": "ซากปรักหักพังของอารยธรรมมายันบนหน้าผาเหนือชายหาด",
"craneSleep4SemanticLabel": "โรงแรมริมทะเลสาบที่อยู่หน้าภูเขา",
"craneSleep2SemanticLabel": "ป้อมมาชูปิกชู",
"craneSleep1SemanticLabel": "กระท่อมหลังเล็กท่ามกลางทิวทัศน์ที่มีหิมะและต้นไม้เขียวชอุ่ม",
"craneSleep0SemanticLabel": "บังกะโลที่ตั้งอยู่เหนือน้ำ",
"craneFly13SemanticLabel": "สระว่ายน้ำริมทะเลซึ่งมีต้นปาล์ม",
"craneFly12SemanticLabel": "สระว่ายน้ำที่มีต้นปาล์ม",
"craneFly11SemanticLabel": "ประภาคารอิฐกลางทะเล",
"craneFly10SemanticLabel": "มัสยิดอัลอัซฮัรช่วงพระอาทิตย์ตก",
"craneFly9SemanticLabel": "ผู้ชายพิงรถโบราณสีน้ำเงิน",
"craneFly8SemanticLabel": "ซูเปอร์ทรี โกรฟ",
"craneEat9SemanticLabel": "เคาน์เตอร์ในคาเฟ่ที่มีขนมอบต่างๆ",
"craneEat2SemanticLabel": "เบอร์เกอร์",
"craneFly5SemanticLabel": "โรงแรมริมทะเลสาบที่อยู่หน้าภูเขา",
"demoSelectionControlsSubtitle": "ช่องทำเครื่องหมาย ปุ่มตัวเลือก และสวิตช์",
"craneEat10SemanticLabel": "ผู้หญิงถือแซนด์วิชเนื้อชิ้นใหญ่",
"craneFly4SemanticLabel": "บังกะโลที่ตั้งอยู่เหนือน้ำ",
"craneEat7SemanticLabel": "ทางเข้าร้านเบเกอรี่",
"craneEat6SemanticLabel": "เมนูที่ใส่กุ้ง",
"craneEat5SemanticLabel": "บริเวณที่นั่งในร้านอาหารซึ่งดูมีศิลปะ",
"craneEat4SemanticLabel": "ของหวานที่เป็นช็อกโกแลต",
"craneEat3SemanticLabel": "ทาโก้แบบเกาหลี",
"craneFly3SemanticLabel": "ป้อมมาชูปิกชู",
"craneEat1SemanticLabel": "บาร์ที่ไม่มีลูกค้าซึ่งมีม้านั่งสูงแบบไม่มีพนัก",
"craneEat0SemanticLabel": "พิซซ่าในเตาอบฟืนไม้",
"craneSleep11SemanticLabel": "ตึกระฟ้าไทเป 101",
"craneSleep10SemanticLabel": "มัสยิดอัลอัซฮัรช่วงพระอาทิตย์ตก",
"craneSleep9SemanticLabel": "ประภาคารอิฐกลางทะเล",
"craneEat8SemanticLabel": "จานใส่กุ้งน้ำจืด",
"craneSleep7SemanticLabel": "อพาร์ตเมนต์สีสันสดใสที่จัตุรัส Ribeira",
"craneSleep6SemanticLabel": "สระว่ายน้ำที่มีต้นปาล์ม",
"craneSleep5SemanticLabel": "เต็นท์ในทุ่ง",
"settingsButtonCloseLabel": "ปิดการตั้งค่า",
"demoSelectionControlsCheckboxDescription": "ช่องทำเครื่องหมายให้ผู้ใช้เลือกตัวเลือกจากชุดตัวเลือกได้หลายรายการ ค่าปกติของช่องทำเครื่องหมายคือ \"จริง\" หรือ \"เท็จ\" และค่า 3 สถานะของช่องทำเครื่องหมายอาจเป็น \"ว่าง\" ได้ด้วย",
"settingsButtonLabel": "การตั้งค่า",
"demoListsTitle": "รายการ",
"demoListsSubtitle": "เลย์เอาต์รายการแบบเลื่อน",
"demoListsDescription": "แถวเดี่ยวความสูงคงที่ซึ่งมักจะมีข้อความบางอย่างรวมถึงไอคอนนำหน้าหรือต่อท้าย",
"demoOneLineListsTitle": "หนึ่งบรรทัด",
"demoTwoLineListsTitle": "สองบรรทัด",
"demoListsSecondary": "ข้อความรอง",
"demoSelectionControlsTitle": "การควบคุมการเลือก",
"craneFly7SemanticLabel": "ภูเขารัชมอร์",
"demoSelectionControlsCheckboxTitle": "ช่องทำเครื่องหมาย",
"craneSleep3SemanticLabel": "ผู้ชายพิงรถโบราณสีน้ำเงิน",
"demoSelectionControlsRadioTitle": "ปุ่มตัวเลือก",
"demoSelectionControlsRadioDescription": "ปุ่มตัวเลือกให้ผู้ใช้เลือก 1 ตัวเลือกจากชุดตัวเลือก ใช้ปุ่มตัวเลือกสำหรับการเลือกพิเศษในกรณีที่คุณคิดว่าผู้ใช้จำเป็นต้องเห็นตัวเลือกที่มีอยู่ทั้งหมดแสดงข้างกัน",
"demoSelectionControlsSwitchTitle": "สวิตช์",
"demoSelectionControlsSwitchDescription": "สวิตช์เปิด/ปิดสลับสถานะของตัวเลือกการตั้งค่า 1 รายการ ตัวเลือกที่สวิตช์ควบคุมและสถานะของตัวเลือกควรแตกต่างอย่างชัดเจนจากป้ายกำกับในบรรทัดที่เกี่ยวข้อง",
"craneFly0SemanticLabel": "กระท่อมหลังเล็กท่ามกลางทิวทัศน์ที่มีหิมะและต้นไม้เขียวชอุ่ม",
"craneFly1SemanticLabel": "เต็นท์ในทุ่ง",
"craneFly2SemanticLabel": "ธงมนตราหน้าภูเขาที่ปกคลุมด้วยหิมะ",
"craneFly6SemanticLabel": "มุมมองทางอากาศของพระราชวัง Bellas Artes",
"rallySeeAllAccounts": "ดูบัญชีทั้งหมด",
"rallyBillAmount": "บิล{billName}ครบกำหนดชำระในวันที่ {date} จำนวน {amount}",
"shrineTooltipCloseCart": "ปิดหน้ารถเข็น",
"shrineTooltipCloseMenu": "ปิดเมนู",
"shrineTooltipOpenMenu": "เปิดเมนู",
"shrineTooltipSettings": "การตั้งค่า",
"shrineTooltipSearch": "ค้นหา",
"demoTabsDescription": "แท็บช่วยจัดระเบียบเนื้อหาในหน้าจอต่างๆ ชุดข้อมูล และการโต้ตอบอื่นๆ",
"demoTabsSubtitle": "แท็บซึ่งมีมุมมองที่เลื่อนได้แบบอิสระ",
"demoTabsTitle": "แท็บ",
"rallyBudgetAmount": "ใช้งบประมาณ{budgetName}ไปแล้ว {amountUsed} จากทั้งหมด {amountTotal} เหลืออีก {amountLeft}",
"shrineTooltipRemoveItem": "นำสินค้าออก",
"rallyAccountAmount": "บัญชี{accountName} เลขที่ {accountNumber} จำนวน {amount}",
"rallySeeAllBudgets": "ดูงบประมาณทั้งหมด",
"rallySeeAllBills": "ดูบิลทั้งหมด",
"craneFormDate": "เลือกวันที่",
"craneFormOrigin": "เลือกต้นทาง",
"craneFly2": "หุบเขาคุมบู เนปาล",
"craneFly3": "มาชูปิกชู เปรู",
"craneFly4": "มาเล มัลดีฟส์",
"craneFly5": "วิทซ์นาว สวิตเซอร์แลนด์",
"craneFly6": "เม็กซิโกซิตี้ เม็กซิโก",
"craneFly7": "ภูเขารัชมอร์ สหรัฐอเมริกา",
"settingsTextDirectionLocaleBased": "อิงตามภาษา",
"craneFly9": "ฮาวานา คิวบา",
"craneFly10": "ไคโร อียิปต์",
"craneFly11": "ลิสบอน โปรตุเกส",
"craneFly12": "นาปา สหรัฐอเมริกา",
"craneFly13": "บาหลี อินโดนีเซีย",
"craneSleep0": "มาเล มัลดีฟส์",
"craneSleep1": "แอสเพน สหรัฐอเมริกา",
"craneSleep2": "มาชูปิกชู เปรู",
"demoCupertinoSegmentedControlTitle": "ตัวควบคุมที่แบ่งกลุ่ม",
"craneSleep4": "วิทซ์นาว สวิตเซอร์แลนด์",
"craneSleep5": "บิ๊กเซอร์ สหรัฐอเมริกา",
"craneSleep6": "นาปา สหรัฐอเมริกา",
"craneSleep7": "ปอร์โต โปรตุเกส",
"craneSleep8": "ตูลุม เม็กซิโก",
"craneEat5": "โซล เกาหลีใต้",
"demoChipTitle": "ชิป",
"demoChipSubtitle": "องค์ประกอบขนาดกะทัดรัดที่แสดงอินพุต แอตทริบิวต์ หรือการทำงาน",
"demoActionChipTitle": "ชิปการทำงาน",
"demoActionChipDescription": "ชิปการทำงานคือชุดตัวเลือกที่จะเรียกใช้การทำงานที่เกี่ยวกับเนื้อหาหลัก ชิปการทำงานควรจะแสดงแบบไดนามิกและตามบริบทใน UI",
"demoChoiceChipTitle": "ชิปตัวเลือก",
"demoChoiceChipDescription": "ชิปตัวเลือกแสดงตัวเลือกเดียวจากชุดตัวเลือก ชิปตัวเลือกมีข้อความคำอธิบายหรือการจัดหมวดหมู่ที่เกี่ยวข้อง",
"demoFilterChipTitle": "ชิปตัวกรอง",
"demoFilterChipDescription": "ชิปตัวกรองใช้แท็กหรือคำอธิบายรายละเอียดเป็นวิธีกรองเนื้อหา",
"demoInputChipTitle": "ชิปอินพุต",
"demoInputChipDescription": "ชิปอินพุตที่แสดงข้อมูลที่ซับซ้อนในรูปแบบกะทัดรัด เช่น ข้อมูลเอนทิตี (บุคคล สถานที่ หรือสิ่งของ) หรือข้อความของบทสนทนา",
"craneSleep9": "ลิสบอน โปรตุเกส",
"craneEat10": "ลิสบอน โปรตุเกส",
"demoCupertinoSegmentedControlDescription": "ใช้เพื่อเลือกระหว่างตัวเลือกที่เฉพาะตัวเหมือนกัน การเลือกตัวเลือกหนึ่งในส่วนควบคุมที่แบ่งกลุ่มจะเป็นการยกเลิกการเลือกตัวเลือกอื่นๆ ในส่วนควบคุมที่แบ่งกลุ่มนั้น",
"chipTurnOnLights": "เปิดไฟ",
"chipSmall": "ขนาดเล็ก",
"chipMedium": "ขนาดกลาง",
"chipLarge": "ขนาดใหญ่",
"chipElevator": "ลิฟต์",
"chipWasher": "เครื่องซักผ้า",
"chipFireplace": "เตาผิง",
"chipBiking": "ขี่จักรยาน",
"craneFormDiners": "ร้านอาหาร",
"rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{เพิ่มโอกาสในการลดหย่อนภาษีของคุณ กำหนดหมวดหมู่ให้แก่ธุรกรรมที่ยังไม่มีหมวดหมู่ 1 รายการ}other{เพิ่มโอกาสในการลดหย่อนภาษีของคุณ กำหนดหมวดหมู่ให้แก่ธุรกรรมที่ยังไม่มีหมวดหมู่ {count} รายการ}}",
"craneFormTime": "เลือกเวลา",
"craneFormLocation": "เลือกสถานที่ตั้ง",
"craneFormTravelers": "นักเดินทาง",
"craneEat8": "แอตแลนตา สหรัฐอเมริกา",
"craneFormDestination": "เลือกจุดหมาย",
"craneFormDates": "เลือกวันที่",
"craneFly": "เที่ยวบิน",
"craneSleep": "ที่พัก",
"craneEat": "ร้านอาหาร",
"craneFlySubhead": "ค้นหาเที่ยวบินตามจุดหมาย",
"craneSleepSubhead": "ค้นหาที่พักตามจุดหมาย",
"craneEatSubhead": "ค้นหาร้านอาหารตามจุดหมาย",
"craneFlyStops": "{numberOfStops,plural,=0{บินตรง}=1{1 จุดพัก}other{{numberOfStops} จุดพัก}}",
"craneSleepProperties": "{totalProperties,plural,=0{ไม่มีตัวเลือกที่พัก}=1{มีตัวเลือกที่พัก 1 แห่ง}other{มีตัวเลือกที่พัก {totalProperties} แห่ง}}",
"craneEatRestaurants": "{totalRestaurants,plural,=0{ไม่มีร้านอาหาร}=1{มีร้านอาหาร 1 แห่ง}other{มีร้านอาหาร {totalRestaurants} แห่ง}}",
"craneFly0": "แอสเพน สหรัฐอเมริกา",
"demoCupertinoSegmentedControlSubtitle": "ส่วนควบคุมที่แบ่งกลุ่มแบบ iOS",
"craneSleep10": "ไคโร อียิปต์",
"craneEat9": "มาดริด สเปน",
"craneFly1": "บิ๊กเซอร์ สหรัฐอเมริกา",
"craneEat7": "แนชวิลล์ สหรัฐอเมริกา",
"craneEat6": "ซีแอตเทิล สหรัฐอเมริกา",
"craneFly8": "สิงคโปร์",
"craneEat4": "ปารีส ฝรั่งเศส",
"craneEat3": "พอร์ตแลนด์ สหรัฐอเมริกา",
"craneEat2": "คอร์โดบา อาร์เจนตินา",
"craneEat1": "ดัลลาส สหรัฐอเมริกา",
"craneEat0": "เนเปิลส์ อิตาลี",
"craneSleep11": "ไทเป ไต้หวัน",
"craneSleep3": "ฮาวานา คิวบา",
"shrineLogoutButtonCaption": "ออกจากระบบ",
"rallyTitleBills": "ใบเรียกเก็บเงิน",
"rallyTitleAccounts": "บัญชี",
"shrineProductVagabondSack": "ถุงย่าม",
"rallyAccountDetailDataInterestYtd": "ดอกเบี้ยตั้งแต่ต้นปีจนถึงปัจจุบัน",
"shrineProductWhitneyBelt": "เข็มขัด Whitney",
"shrineProductGardenStrand": "เชือกทำสวน",
"shrineProductStrutEarrings": "ต่างหู Strut",
"shrineProductVarsitySocks": "ถุงเท้าทีมกีฬามหาวิทยาลัย",
"shrineProductWeaveKeyring": "พวงกุญแจถัก",
"shrineProductGatsbyHat": "หมวก Gatsby",
"shrineProductShrugBag": "กระเป๋าทรงย้วย",
"shrineProductGiltDeskTrio": "โต๊ะขอบทอง 3 ตัว",
"shrineProductCopperWireRack": "ตะแกรงสีทองแดง",
"shrineProductSootheCeramicSet": "ชุดเครื่องเคลือบสีละมุน",
"shrineProductHurrahsTeaSet": "ชุดน้ำชา Hurrahs",
"shrineProductBlueStoneMug": "แก้วกาแฟสีบลูสโตน",
"shrineProductRainwaterTray": "รางน้ำฝน",
"shrineProductChambrayNapkins": "ผ้าเช็ดปากแชมเบรย์",
"shrineProductSucculentPlanters": "กระถางสำหรับพืชอวบน้ำ",
"shrineProductQuartetTable": "โต๊ะสำหรับ 4 คน",
"shrineProductKitchenQuattro": "Kitchen Quattro",
"shrineProductClaySweater": "สเวตเตอร์สีดินเหนียว",
"shrineProductSeaTunic": "ชุดกระโปรงเดินชายหาด",
"shrineProductPlasterTunic": "เสื้อคลุมสีปูนปลาสเตอร์",
"rallyBudgetCategoryRestaurants": "ร้านอาหาร",
"shrineProductChambrayShirt": "เสื้อแชมเบรย์",
"shrineProductSeabreezeSweater": "สเวตเตอร์ถักแบบห่าง",
"shrineProductGentryJacket": "แจ็กเก็ต Gentry",
"shrineProductNavyTrousers": "กางเกงขายาวสีน้ำเงินเข้ม",
"shrineProductWalterHenleyWhite": "เสื้อเฮนลีย์ Walter (ขาว)",
"shrineProductSurfAndPerfShirt": "เสื้อ Surf and Perf",
"shrineProductGingerScarf": "ผ้าพันคอสีเหลืองอมน้ำตาลแดง",
"shrineProductRamonaCrossover": "Ramona ครอสโอเวอร์",
"shrineProductClassicWhiteCollar": "เสื้อเชิ้ตสีขาวแบบคลาสสิก",
"shrineProductSunshirtDress": "ชุดกระโปรง Sunshirt",
"rallyAccountDetailDataInterestRate": "อัตราดอกเบี้ย",
"rallyAccountDetailDataAnnualPercentageYield": "ผลตอบแทนรายปีเป็นเปอร์เซ็นต์",
"rallyAccountDataVacation": "วันหยุดพักผ่อน",
"shrineProductFineLinesTee": "เสื้อยืดลายขวางแบบถี่",
"rallyAccountDataHomeSavings": "เงินเก็บสำหรับซื้อบ้าน",
"rallyAccountDataChecking": "กระแสรายวัน",
"rallyAccountDetailDataInterestPaidLastYear": "ดอกเบี้ยที่จ่ายเมื่อปีที่แล้ว",
"rallyAccountDetailDataNextStatement": "รายการเคลื่อนไหวของบัญชีรอบถัดไป",
"rallyAccountDetailDataAccountOwner": "เจ้าของบัญชี",
"rallyBudgetCategoryCoffeeShops": "ร้านกาแฟ",
"rallyBudgetCategoryGroceries": "ของชำ",
"shrineProductCeriseScallopTee": "เสื้อยืดชายโค้งสีแดงอมชมพู",
"rallyBudgetCategoryClothing": "เสื้อผ้า",
"rallySettingsManageAccounts": "จัดการบัญชี",
"rallyAccountDataCarSavings": "เงินเก็บสำหรับซื้อรถ",
"rallySettingsTaxDocuments": "เอกสารเกี่ยวกับภาษี",
"rallySettingsPasscodeAndTouchId": "รหัสผ่านและ Touch ID",
"rallySettingsNotifications": "การแจ้งเตือน",
"rallySettingsPersonalInformation": "ข้อมูลส่วนบุคคล",
"rallySettingsPaperlessSettings": "การตั้งค่าสำหรับเอกสารที่ไม่ใช้กระดาษ",
"rallySettingsFindAtms": "ค้นหา ATM",
"rallySettingsHelp": "ความช่วยเหลือ",
"rallySettingsSignOut": "ออกจากระบบ",
"rallyAccountTotal": "รวม",
"rallyBillsDue": "ครบกำหนด",
"rallyBudgetLeft": "ที่เหลือ",
"rallyAccounts": "บัญชี",
"rallyBills": "ใบเรียกเก็บเงิน",
"rallyBudgets": "งบประมาณ",
"rallyAlerts": "การแจ้งเตือน",
"rallySeeAll": "ดูทั้งหมด",
"rallyFinanceLeft": "ที่เหลือ",
"rallyTitleOverview": "ภาพรวม",
"shrineProductShoulderRollsTee": "เสื้อยืด Shoulder Rolls",
"shrineNextButtonCaption": "ถัดไป",
"rallyTitleBudgets": "งบประมาณ",
"rallyTitleSettings": "การตั้งค่า",
"rallyLoginLoginToRally": "เข้าสู่ระบบของ Rally",
"rallyLoginNoAccount": "หากยังไม่มีบัญชี",
"rallyLoginSignUp": "ลงชื่อสมัครใช้",
"rallyLoginUsername": "ชื่อผู้ใช้",
"rallyLoginPassword": "รหัสผ่าน",
"rallyLoginLabelLogin": "เข้าสู่ระบบ",
"rallyLoginRememberMe": "จดจำข้อมูลของฉัน",
"rallyLoginButtonLogin": "เข้าสู่ระบบ",
"rallyAlertsMessageHeadsUpShopping": "โปรดทราบ คุณใช้งบประมาณสำหรับการช็อปปิ้งของเดือนนี้ไปแล้ว {percent}",
"rallyAlertsMessageSpentOnRestaurants": "สัปดาห์นี้คุณใช้จ่ายไปกับการทานอาหารในร้าน {amount}",
"rallyAlertsMessageATMFees": "เดือนนี้คุณจ่ายค่าธรรมเนียมการใช้ ATM {amount}",
"rallyAlertsMessageCheckingAccount": "ดีมาก คุณมีเงินฝากมากกว่าเดือนที่แล้ว {percent}",
"shrineMenuCaption": "เมนู",
"shrineCategoryNameAll": "ทั้งหมด",
"shrineCategoryNameAccessories": "อุปกรณ์เสริม",
"shrineCategoryNameClothing": "เสื้อผ้า",
"shrineCategoryNameHome": "บ้าน",
"shrineLoginUsernameLabel": "ชื่อผู้ใช้",
"shrineLoginPasswordLabel": "รหัสผ่าน",
"shrineCancelButtonCaption": "ยกเลิก",
"shrineCartTaxCaption": "ภาษี:",
"shrineCartPageCaption": "รถเข็น",
"shrineProductQuantity": "จำนวน: {quantity}",
"shrineProductPrice": "x {price}",
"shrineCartItemCount": "{quantity,plural,=0{ไม่มีสินค้า}=1{มีสินค้า 1 รายการ}other{มีสินค้า {quantity} รายการ}}",
"shrineCartClearButtonCaption": "ล้างรถเข็น",
"shrineCartTotalCaption": "รวม",
"shrineCartSubtotalCaption": "ยอดรวมย่อย:",
"shrineCartShippingCaption": "การจัดส่ง:",
"shrineProductGreySlouchTank": "เสื้อกล้ามทรงย้วยสีเทา",
"shrineProductStellaSunglasses": "แว่นกันแดด Stella",
"shrineProductWhitePinstripeShirt": "เสื้อเชิ้ตสีขาวลายทางแนวตั้ง",
"demoTextFieldWhereCanWeReachYou": "หมายเลขโทรศัพท์ของคุณ",
"settingsTextDirectionLTR": "LTR",
"settingsTextScalingLarge": "ใหญ่",
"demoBottomSheetHeader": "ส่วนหัว",
"demoBottomSheetItem": "รายการ {value}",
"demoBottomTextFieldsTitle": "ช่องข้อความ",
"demoTextFieldTitle": "ช่องข้อความ",
"demoTextFieldSubtitle": "บรรทัดข้อความและตัวเลขที่แก้ไขได้",
"demoTextFieldDescription": "ช่องข้อความให้ผู้ใช้ป้อนข้อความใน UI ซึ่งมักปรากฏอยู่ในฟอร์มและกล่องโต้ตอบ",
"demoTextFieldShowPasswordLabel": "แสดงรหัสผ่าน",
"demoTextFieldHidePasswordLabel": "ซ่อนรหัสผ่าน",
"demoTextFieldFormErrors": "โปรดแก้ไขข้อผิดพลาดที่แสดงเป็นสีแดงก่อนส่ง",
"demoTextFieldNameRequired": "ต้องระบุชื่อ",
"demoTextFieldOnlyAlphabeticalChars": "โปรดป้อนอักขระที่เป็นตัวอักษรเท่านั้น",
"demoTextFieldEnterUSPhoneNumber": "(###) ###-#### - ป้อนหมายเลขโทรศัพท์ในสหรัฐอเมริกา",
"demoTextFieldEnterPassword": "โปรดป้อนรหัสผ่าน",
"demoTextFieldPasswordsDoNotMatch": "รหัสผ่านไม่ตรงกัน",
"demoTextFieldWhatDoPeopleCallYou": "ชื่อของคุณ",
"demoTextFieldNameField": "ชื่อ*",
"demoBottomSheetButtonText": "แสดง Bottom Sheet",
"demoTextFieldPhoneNumber": "หมายเลขโทรศัพท์*",
"demoBottomSheetTitle": "Bottom Sheet",
"demoTextFieldEmail": "อีเมล",
"demoTextFieldTellUsAboutYourself": "แนะนำตัวให้เรารู้จัก (เช่น เขียนว่าคุณทำงานอะไรหรือมีงานอดิเรกอะไรบ้าง)",
"demoTextFieldKeepItShort": "เขียนสั้นๆ เพราะนี่เป็นเพียงการสาธิต",
"starterAppGenericButton": "ปุ่ม",
"demoTextFieldLifeStory": "เรื่องราวชีวิต",
"demoTextFieldSalary": "รายได้ต่อปี",
"demoTextFieldUSD": "USD",
"demoTextFieldNoMoreThan": "ไม่เกิน 8 อักขระ",
"demoTextFieldPassword": "รหัสผ่าน*",
"demoTextFieldRetypePassword": "พิมพ์รหัสผ่านอีกครั้ง*",
"demoTextFieldSubmit": "ส่ง",
"demoBottomNavigationSubtitle": "Bottom Navigation ที่มีมุมมองแบบค่อยๆ ปรากฏ",
"demoBottomSheetAddLabel": "เพิ่ม",
"demoBottomSheetModalDescription": "Modal Bottom Sheet เป็นทางเลือกที่ใช้แทนเมนูหรือกล่องโต้ตอบและป้องกันไม่ให้ผู้ใช้โต้ตอบกับส่วนที่เหลือของแอป",
"demoBottomSheetModalTitle": "Modal Bottom Sheet",
"demoBottomSheetPersistentDescription": "Persistent Bottom Sheet แสดงข้อมูลที่เสริมเนื้อหาหลักของแอป ผู้ใช้จะยังมองเห็นองค์ประกอบนี้ได้แม้จะโต้ตอบอยู่กับส่วนอื่นๆ ของแอป",
"demoBottomSheetPersistentTitle": "Persistent Bottom Sheet",
"demoBottomSheetSubtitle": "Persistent และ Modal Bottom Sheet",
"demoTextFieldNameHasPhoneNumber": "หมายเลขโทรศัพท์ของ {name} คือ {phoneNumber}",
"buttonText": "ปุ่ม",
"demoTypographyDescription": "คำจำกัดความของตัวอักษรรูปแบบต่างๆ ที่พบในดีไซน์ Material",
"demoTypographySubtitle": "รูปแบบข้อความทั้งหมดที่กำหนดไว้ล่วงหน้า",
"demoTypographyTitle": "ตัวอย่างการพิมพ์",
"demoFullscreenDialogDescription": "พร็อพเพอร์ตี้ fullscreenDialog จะระบุว่าหน้าที่เข้ามาใหม่เป็นกล่องโต้ตอบในโหมดเต็มหน้าจอหรือไม่",
"demoFlatButtonDescription": "ปุ่มแบบแบนราบจะแสดงการไฮไลต์เมื่อกดแต่จะไม่ยกขึ้น ใช้ปุ่มแบบแบนราบกับแถบเครื่องมือ ในกล่องโต้ตอบ และแทรกในบรรทัดแบบมีระยะห่างจากขอบ",
"demoBottomNavigationDescription": "แถบ Bottom Navigation จะแสดงปลายทาง 3-5 แห่งที่ด้านล่างของหน้าจอ ปลายทางแต่ละแห่งจะแสดงด้วยไอคอนและป้ายกำกับแบบข้อความที่ไม่บังคับ เมื่อผู้ใช้แตะไอคอน Bottom Navigation ระบบจะนำไปที่ปลายทางของการนำทางระดับบนสุดที่เชื่อมโยงกับไอคอนนั้น",
"demoBottomNavigationSelectedLabel": "ป้ายกำกับที่เลือก",
"demoBottomNavigationPersistentLabels": "ป้ายกำกับที่แสดงเสมอ",
"starterAppDrawerItem": "รายการ {value}",
"demoTextFieldRequiredField": "* เป็นช่องที่ต้องกรอก",
"demoBottomNavigationTitle": "Bottom Navigation",
"settingsLightTheme": "สีสว่าง",
"settingsTheme": "ธีม",
"settingsPlatformIOS": "iOS",
"settingsPlatformAndroid": "Android",
"settingsTextDirectionRTL": "RTL",
"settingsTextScalingHuge": "ใหญ่มาก",
"cupertinoButton": "ปุ่ม",
"settingsTextScalingNormal": "ปกติ",
"settingsTextScalingSmall": "เล็ก",
"settingsSystemDefault": "ระบบ",
"settingsTitle": "การตั้งค่า",
"rallyDescription": "แอปการเงินส่วนบุคคล",
"aboutDialogDescription": "โปรดไปที่ {repoLink} เพื่อดูซอร์สโค้ดของแอปนี้",
"bottomNavigationCommentsTab": "ความคิดเห็น",
"starterAppGenericBody": "เนื้อความ",
"starterAppGenericHeadline": "บรรทัดแรก",
"starterAppGenericSubtitle": "คำบรรยาย",
"starterAppGenericTitle": "ชื่อ",
"starterAppTooltipSearch": "ค้นหา",
"starterAppTooltipShare": "แชร์",
"starterAppTooltipFavorite": "รายการโปรด",
"starterAppTooltipAdd": "เพิ่ม",
"bottomNavigationCalendarTab": "ปฏิทิน",
"starterAppDescription": "เลย์เอาต์เริ่มต้นที่มีการตอบสนอง",
"starterAppTitle": "แอปเริ่มต้น",
"aboutFlutterSamplesRepo": "ที่เก็บของ GitHub สำหรับตัวอย่าง Flutter",
"bottomNavigationContentPlaceholder": "ตัวยึดตำแหน่งของแท็บ {title}",
"bottomNavigationCameraTab": "กล้องถ่ายรูป",
"bottomNavigationAlarmTab": "การปลุก",
"bottomNavigationAccountTab": "บัญชี",
"demoTextFieldYourEmailAddress": "อีเมลของคุณ",
"demoToggleButtonDescription": "ปุ่มเปิด-ปิดอาจใช้เพื่อจับกลุ่มตัวเลือกที่เกี่ยวข้องกัน กลุ่มของปุ่มเปิด-ปิดที่เกี่ยวข้องกันควรใช้คอนเทนเนอร์ร่วมกันเพื่อเป็นการเน้นกลุ่มเหล่านั้น",
"colorsGrey": "เทา",
"colorsBrown": "น้ำตาล",
"colorsDeepOrange": "ส้มแก่",
"colorsOrange": "ส้ม",
"colorsAmber": "เหลืองอำพัน",
"colorsYellow": "เหลือง",
"colorsLime": "เหลืองมะนาว",
"colorsLightGreen": "เขียวอ่อน",
"colorsGreen": "เขียว",
"homeHeaderGallery": "แกลเลอรี",
"homeHeaderCategories": "หมวดหมู่",
"shrineDescription": "แอปค้าปลีกด้านแฟชั่น",
"craneDescription": "แอปการเดินทางที่ปรับเปลี่ยนในแบบของคุณ",
"homeCategoryReference": "รูปแบบและอื่นๆ",
"demoInvalidURL": "แสดง URL ไม่ได้:",
"demoOptionsTooltip": "ตัวเลือก",
"demoInfoTooltip": "ข้อมูล",
"demoCodeTooltip": "รหัสการสาธิต",
"demoDocumentationTooltip": "เอกสารประกอบของ API",
"demoFullscreenTooltip": "เต็มหน้าจอ",
"settingsTextScaling": "อัตราส่วนข้อความ",
"settingsTextDirection": "ทิศทางข้อความ",
"settingsLocale": "ภาษา",
"settingsPlatformMechanics": "กลไกการทำงานของแพลตฟอร์ม",
"settingsDarkTheme": "สีเข้ม",
"settingsSlowMotion": "Slow Motion",
"settingsAbout": "เกี่ยวกับ Flutter Gallery",
"settingsFeedback": "ส่งความคิดเห็น",
"settingsAttribution": "ออกแบบโดย TOASTER ในลอนดอน",
"demoButtonTitle": "ปุ่ม",
"demoButtonSubtitle": "ข้อความ ยกขึ้น เติมขอบ และอื่นๆ",
"demoFlatButtonTitle": "ปุ่มแบบแบนราบ",
"demoRaisedButtonDescription": "ปุ่มแบบยกขึ้นช่วยเพิ่มมิติให้แก่เลย์เอาต์แบบแบนราบเป็นส่วนใหญ่ โดยจะช่วยเน้นฟังก์ชันในพื้นที่ที่มีการใช้งานมากหรือกว้างขวาง",
"demoRaisedButtonTitle": "ปุ่มแบบยกขึ้น",
"demoOutlineButtonTitle": "ปุ่มแบบเติมขอบ",
"demoOutlineButtonDescription": "ปุ่มที่เติมขอบจะเปลี่ยนเป็นสีทึบและยกขึ้นเมื่อกด มักจับคู่กับปุ่มแบบยกขึ้นเพื่อระบุว่ามีการดำเนินการสำรองอย่างอื่น",
"demoToggleButtonTitle": "ปุ่มเปิด-ปิด",
"colorsTeal": "น้ำเงินอมเขียว",
"demoFloatingButtonTitle": "ปุ่มการทำงานแบบลอย",
"demoFloatingButtonDescription": "ปุ่มการทำงานแบบลอยเป็นปุ่มไอคอนรูปวงกลมที่ลอยเหนือเนื้อหาเพื่อโปรโมตการดำเนินการหลักในแอปพลิเคชัน",
"demoDialogTitle": "กล่องโต้ตอบ",
"demoDialogSubtitle": "แบบง่าย การแจ้งเตือน และเต็มหน้าจอ",
"demoAlertDialogTitle": "การแจ้งเตือน",
"demoAlertDialogDescription": "กล่องโต้ตอบการแจ้งเตือนจะแจ้งผู้ใช้เกี่ยวกับสถานการณ์ที่ต้องการการตอบรับ กล่องโต้ตอบการแจ้งเตือนมีชื่อที่ไม่บังคับและรายการที่ไม่บังคับของการดำเนินการ",
"demoAlertTitleDialogTitle": "การแจ้งเตือนที่มีชื่อ",
"demoSimpleDialogTitle": "แบบง่าย",
"demoSimpleDialogDescription": "กล่องโต้ตอบแบบง่ายจะนำเสนอทางเลือกระหว่างตัวเลือกหลายๆ อย่าง โดยกล่องโต้ตอบแบบง่ายจะมีชื่อที่ไม่บังคับซึ่งจะแสดงเหนือทางเลือกต่างๆ",
"demoFullscreenDialogTitle": "เต็มหน้าจอ",
"demoCupertinoButtonsTitle": "ปุ่ม",
"demoCupertinoButtonsSubtitle": "ปุ่มแบบ iOS",
"demoCupertinoButtonsDescription": "ปุ่มแบบ iOS จะใส่ข้อความและ/หรือไอคอนที่ค่อยๆ ปรากฏขึ้นและค่อยๆ จางลงเมื่อแตะ อาจมีหรือไม่มีพื้นหลังก็ได้",
"demoCupertinoAlertsTitle": "การแจ้งเตือน",
"demoCupertinoAlertsSubtitle": "กล่องโต้ตอบการแจ้งเตือนแบบ iOS",
"demoCupertinoAlertTitle": "การแจ้งเตือน",
"demoCupertinoAlertDescription": "กล่องโต้ตอบการแจ้งเตือนจะแจ้งผู้ใช้เกี่ยวกับสถานการณ์ที่ต้องการการตอบรับ กล่องโต้ตอบการแจ้งเตือนมีชื่อที่ไม่บังคับ เนื้อหาที่ไม่บังคับ และรายการที่ไม่บังคับของการดำเนินการ ชื่อจะแสดงเหนือเนื้อหาและการดำเนินการจะแสดงใต้เนื้อหา",
"demoCupertinoAlertWithTitleTitle": "การแจ้งเตือนที่มีชื่อ",
"demoCupertinoAlertButtonsTitle": "การแจ้งเตือนแบบมีปุ่ม",
"demoCupertinoAlertButtonsOnlyTitle": "ปุ่มการแจ้งเตือนเท่านั้น",
"demoCupertinoActionSheetTitle": "แผ่นงานการดำเนินการ",
"demoCupertinoActionSheetDescription": "แผ่นงานการดำเนินการเป็นการแจ้งเตือนรูปแบบหนึ่งที่นำเสนอชุดทางเลือกตั้งแต่ 2 รายการขึ้นไปเกี่ยวกับบริบทปัจจุบันให้แก่ผู้ใช้ แผ่นงานการดำเนินการอาจมีชื่อ ข้อความเพิ่มเติม และรายการของการดำเนินการ",
"demoColorsTitle": "สี",
"demoColorsSubtitle": "สีที่กำหนดไว้ล่วงหน้าทั้งหมด",
"demoColorsDescription": "สีหรือแผงสีคงที่ซึ่งเป็นตัวแทนชุดสีของดีไซน์ Material",
"buttonTextEnabled": "ENABLED",
"buttonTextDisabled": "DISABLED",
"buttonTextCreate": "สร้าง",
"dialogSelectedOption": "คุณเลือก \"{value}\"",
"dialogDiscardTitle": "ทิ้งฉบับร่างไหม",
"dialogLocationTitle": "ใช้บริการตำแหน่งของ Google ไหม",
"dialogLocationDescription": "ให้ Google ช่วยแอประบุตำแหน่ง ซึ่งหมายถึงการส่งข้อมูลตำแหน่งแบบไม่เปิดเผยชื่อไปยัง Google แม้ว่าจะไม่มีแอปทำงานอยู่",
"dialogCancel": "ยกเลิก",
"dialogDiscard": "ทิ้ง",
"dialogDisagree": "ไม่ยอมรับ",
"dialogAgree": "ยอมรับ",
"dialogSetBackup": "ตั้งค่าบัญชีสำรอง",
"colorsBlueGrey": "เทาน้ำเงิน",
"dialogShow": "แสดงกล่องโต้ตอบ",
"dialogFullscreenTitle": "กล่องโต้ตอบแบบเต็มหน้าจอ",
"dialogFullscreenSave": "บันทึก",
"dialogFullscreenDescription": "การสาธิตกล่องโต้ตอบแบบเต็มหน้าจอ",
"cupertinoButtonEnabled": "Enabled",
"cupertinoButtonDisabled": "Disabled",
"cupertinoButtonWithBackground": "มีพื้นหลัง",
"cupertinoAlertCancel": "ยกเลิก",
"cupertinoAlertDiscard": "ทิ้ง",
"cupertinoAlertLocationTitle": "อนุญาตให้ Maps เข้าถึงตำแหน่งของคุณขณะที่ใช้แอปหรือไม่",
"cupertinoAlertLocationDescription": "ตำแหน่งปัจจุบันของคุณจะแสดงในแผนที่และใช้เพื่อแสดงคำแนะนำ ผลการค้นหาใกล้เคียง และเวลาเดินทางโดยประมาณ",
"cupertinoAlertAllow": "อนุญาต",
"cupertinoAlertDontAllow": "ไม่อนุญาต",
"cupertinoAlertFavoriteDessert": "เลือกของหวานที่คุณชอบ",
"cupertinoAlertDessertDescription": "โปรดเลือกชนิดของหวานที่คุณชอบจากรายการด้านล่าง ตัวเลือกของคุณจะใช้เพื่อปรับแต่งรายการร้านอาหารแนะนำในพื้นที่ของคุณ",
"cupertinoAlertCheesecake": "ชีสเค้ก",
"cupertinoAlertTiramisu": "ทิรามิสุ",
"cupertinoAlertApplePie": "พายแอปเปิล",
"cupertinoAlertChocolateBrownie": "บราวนี่ช็อกโกแลต",
"cupertinoShowAlert": "แสดงการแจ้งเตือน",
"colorsRed": "แดง",
"colorsPink": "ชมพู",
"colorsPurple": "ม่วง",
"colorsDeepPurple": "ม่วงเข้ม",
"colorsIndigo": "น้ำเงินอมม่วง",
"colorsBlue": "น้ำเงิน",
"colorsLightBlue": "ฟ้าอ่อน",
"colorsCyan": "น้ำเงินเขียว",
"dialogAddAccount": "เพิ่มบัญชี",
"Gallery": "แกลเลอรี",
"Categories": "หมวดหมู่",
"SHRINE": "เทวสถาน",
"Basic shopping app": "แอปช็อปปิ้งทั่วไป",
"RALLY": "การแข่งรถ",
"CRANE": "เครน",
"Travel app": "แอปการเดินทาง",
"MATERIAL": "วัตถุ",
"CUPERTINO": "คูเปอร์ติโน",
"REFERENCE STYLES & MEDIA": "รูปแบบการอ้างอิงและสื่อ"
}
| gallery/lib/l10n/intl_th.arb/0 | {
"file_path": "gallery/lib/l10n/intl_th.arb",
"repo_id": "gallery",
"token_count": 48870
} | 863 |
// Copyright 2019 The Flutter team. 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';
import 'package:flutter/material.dart';
import 'package:gallery/data/gallery_options.dart';
double _textScaleFactor(BuildContext context) {
return GalleryOptions.of(context).textScaleFactor(context);
}
// When text is larger, this factor becomes larger, but at half the rate.
//
// | Text scaling | Text scale factor | reducedTextScale(context) |
// |--------------|-------------------|---------------------------|
// | Small | 0.8 | 1.0 |
// | Normal | 1.0 | 1.0 |
// | Large | 2.0 | 1.5 |
// | Huge | 3.0 | 2.0 |
double reducedTextScale(BuildContext context) {
final textScaleFactor = _textScaleFactor(context);
return textScaleFactor >= 1 ? (1 + textScaleFactor) / 2 : 1;
}
// When text is larger, this factor becomes larger at the same rate.
// But when text is smaller, this factor stays at 1.
//
// | Text scaling | Text scale factor | cappedTextScale(context) |
// |--------------|-------------------|---------------------------|
// | Small | 0.8 | 1.0 |
// | Normal | 1.0 | 1.0 |
// | Large | 2.0 | 2.0 |
// | Huge | 3.0 | 3.0 |
double cappedTextScale(BuildContext context) {
final textScaleFactor = _textScaleFactor(context);
return max(textScaleFactor, 1);
}
| gallery/lib/layout/text_scale.dart/0 | {
"file_path": "gallery/lib/layout/text_scale.dart",
"repo_id": "gallery",
"token_count": 759
} | 864 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/layout/text_scale.dart';
import 'package:gallery/studies/rally/colors.dart';
import 'package:gallery/studies/rally/data.dart';
import 'package:gallery/studies/rally/formatters.dart';
import 'package:intl/intl.dart' as intl;
class RallyLineChart extends StatelessWidget {
const RallyLineChart({
super.key,
this.events = const <DetailedEventData>[],
});
final List<DetailedEventData> events;
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: RallyLineChartPainter(
dateFormat: dateFormatMonthYear(context),
numberFormat: usdWithSignFormat(context),
events: events,
labelStyle: Theme.of(context).textTheme.bodyMedium!,
textDirection: GalleryOptions.of(context).resolvedTextDirection(),
textScaleFactor: reducedTextScale(context),
padding: isDisplayDesktop(context)
? const EdgeInsets.symmetric(vertical: 22)
: EdgeInsets.zero,
),
);
}
}
class RallyLineChartPainter extends CustomPainter {
RallyLineChartPainter({
required this.dateFormat,
required this.numberFormat,
required this.events,
required this.labelStyle,
required this.textDirection,
required this.textScaleFactor,
required this.padding,
});
// The style for the labels.
final TextStyle labelStyle;
// The text direction for the text.
final TextDirection? textDirection;
// The text scale factor for the text.
final double textScaleFactor;
// The padding around the text.
final EdgeInsets padding;
// The format for the dates.
final intl.DateFormat dateFormat;
// The currency format.
final intl.NumberFormat numberFormat;
// Events to plot on the line as points.
final List<DetailedEventData> events;
// Number of days to plot.
// This is hardcoded to reflect the dummy data, but would be dynamic in a real
// app.
final int numDays = 52;
// Beginning of window. The end is this plus numDays.
// This is hardcoded to reflect the dummy data, but would be dynamic in a real
// app.
final DateTime startDate = DateTime.utc(2018, 12, 1);
// Ranges uses to lerp the pixel points.
// This is hardcoded to reflect the dummy data, but would be dynamic in a real
// app.
final double maxAmount = 2000; // minAmount is assumed to be 0
// The number of milliseconds in a day. This is the inherit period fot the
// points in this line.
static const int millisInDay = 24 * 60 * 60 * 1000;
// Amount to shift the tick drawing by so that the Sunday ticks do not start
// on the edge.
final int tickShift = 3;
// Arbitrary unit of space for absolute positioned painting.
final double space = 16;
@override
void paint(Canvas canvas, Size size) {
final labelHeight = space + space * (textScaleFactor - 1);
final ticksHeight = 3 * space;
final ticksTop = size.height - labelHeight - ticksHeight - space;
final labelsTop = size.height - labelHeight;
_drawLine(
canvas,
Rect.fromLTWH(0, 0, size.width, size.height - labelHeight - ticksHeight),
);
_drawXAxisTicks(
canvas,
Rect.fromLTWH(0, ticksTop, size.width, ticksHeight),
);
_drawXAxisLabels(
canvas,
Rect.fromLTWH(0, labelsTop, size.width, labelHeight),
);
}
// Since we're only using fixed dummy data, we can set this to false. In a
// real app we would have the data as part of the state and repaint when it's
// changed.
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
@override
SemanticsBuilderCallback get semanticsBuilder {
return (size) {
final amounts = _amountsPerDay(numDays);
// We divide the graph and the amounts into [numGroups] groups, with
// [numItemsPerGroup] amounts per group.
const numGroups = 10;
final numItemsPerGroup = amounts.length ~/ numGroups;
// For each group we calculate the median value.
final medians = List.generate(
numGroups,
(i) {
final middleIndex = i * numItemsPerGroup + numItemsPerGroup ~/ 2;
if (numItemsPerGroup.isEven) {
return (amounts[middleIndex] + amounts[middleIndex + 1]) / 2;
} else {
return amounts[middleIndex];
}
},
);
// Return a list of [CustomPainterSemantics] with the length of
// [numGroups], all have the same width with the median amount as label.
return List.generate(numGroups, (i) {
return CustomPainterSemantics(
rect: Offset((i / numGroups) * size.width, 0) &
Size(size.width / numGroups, size.height),
properties: SemanticsProperties(
label: numberFormat.format(medians[i]),
textDirection: textDirection,
),
);
});
};
}
/// Returns the amount of money in the account for the [numDays] given
/// from the [startDate].
List<double> _amountsPerDay(int numDays) {
// Arbitrary value for the first point. In a real app, a wider range of
// points would be used that go beyond the boundaries of the screen.
var lastAmount = 600.0;
// Align the points with equal deltas (1 day) as a cumulative sum.
var startMillis = startDate.millisecondsSinceEpoch;
final amounts = <double>[];
for (var i = 0; i < numDays; i++) {
final endMillis = startMillis + millisInDay * 1;
final filteredEvents = events.where(
(e) {
return startMillis <= e.date.millisecondsSinceEpoch &&
e.date.millisecondsSinceEpoch < endMillis;
},
).toList();
lastAmount += sumOf<DetailedEventData>(filteredEvents, (e) => e.amount);
amounts.add(lastAmount);
startMillis = endMillis;
}
return amounts;
}
void _drawLine(Canvas canvas, Rect rect) {
final linePaint = Paint()
..color = RallyColors.accountColor(2)
..style = PaintingStyle.stroke
..strokeWidth = 2;
// Try changing this value between 1, 7, 15, etc.
const smoothing = 1;
final amounts = _amountsPerDay(numDays + smoothing);
final points = <Offset>[];
for (var i = 0; i < amounts.length; i++) {
final x = i / numDays * rect.width;
final y = (maxAmount - amounts[i]) / maxAmount * rect.height;
points.add(Offset(x, y));
}
// Add last point of the graph to make sure we take up the full width.
points.add(
Offset(
rect.width,
(maxAmount - amounts[numDays - 1]) / maxAmount * rect.height,
),
);
final path = Path();
path.moveTo(points[0].dx, points[0].dy);
for (var i = 1; i < numDays - smoothing + 2; i += smoothing) {
final x1 = points[i].dx;
final y1 = points[i].dy;
final x2 = (x1 + points[i + smoothing].dx) / 2;
final y2 = (y1 + points[i + smoothing].dy) / 2;
path.quadraticBezierTo(x1, y1, x2, y2);
}
canvas.drawPath(path, linePaint);
}
/// Draw the X-axis increment markers at constant width intervals.
void _drawXAxisTicks(Canvas canvas, Rect rect) {
for (var i = 0; i < numDays; i++) {
final x = rect.width / numDays * i;
canvas.drawRect(
Rect.fromPoints(
Offset(x, i % 7 == tickShift ? rect.top : rect.center.dy),
Offset(x, rect.bottom),
),
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1
..color = RallyColors.gray25,
);
}
}
/// Set X-axis labels under the X-axis increment markers.
void _drawXAxisLabels(Canvas canvas, Rect rect) {
final selectedLabelStyle = labelStyle.copyWith(
fontWeight: FontWeight.w700,
fontSize: labelStyle.fontSize! * textScaleFactor,
);
final unselectedLabelStyle = labelStyle.copyWith(
fontWeight: FontWeight.w700,
color: RallyColors.gray25,
fontSize: labelStyle.fontSize! * textScaleFactor,
);
// We use toUpperCase to format the dates. This function uses the language
// independent Unicode mapping and thus only works in some languages.
final leftLabel = TextPainter(
text: TextSpan(
text: dateFormat.format(startDate).toUpperCase(),
style: unselectedLabelStyle,
),
textDirection: textDirection,
);
leftLabel.layout();
leftLabel.paint(canvas,
Offset(rect.left + space / 2 + padding.vertical, rect.topCenter.dy));
final centerLabel = TextPainter(
text: TextSpan(
text: dateFormat
.format(DateTime(startDate.year, startDate.month + 1))
.toUpperCase(),
style: selectedLabelStyle,
),
textDirection: textDirection,
);
centerLabel.layout();
final x = (rect.width - centerLabel.width) / 2;
final y = rect.topCenter.dy;
centerLabel.paint(canvas, Offset(x, y));
final rightLabel = TextPainter(
text: TextSpan(
text: dateFormat
.format(DateTime(startDate.year, startDate.month + 2))
.toUpperCase(),
style: unselectedLabelStyle,
),
textDirection: textDirection,
);
rightLabel.layout();
rightLabel.paint(
canvas,
Offset(rect.right - centerLabel.width - space / 2 - padding.vertical,
rect.topCenter.dy),
);
}
}
| gallery/lib/studies/rally/charts/line_chart.dart/0 | {
"file_path": "gallery/lib/studies/rally/charts/line_chart.dart",
"repo_id": "gallery",
"token_count": 3630
} | 865 |
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:animations/animations.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/studies/reply/app.dart';
import 'package:gallery/studies/reply/bottom_drawer.dart';
import 'package:gallery/studies/reply/colors.dart';
import 'package:gallery/studies/reply/compose_page.dart';
import 'package:gallery/studies/reply/mailbox_body.dart';
import 'package:gallery/studies/reply/model/email_model.dart';
import 'package:gallery/studies/reply/model/email_store.dart';
import 'package:gallery/studies/reply/profile_avatar.dart';
import 'package:gallery/studies/reply/search_page.dart';
import 'package:gallery/studies/reply/waterfall_notched_rectangle.dart';
import 'package:provider/provider.dart';
const _assetsPackage = 'flutter_gallery_assets';
const _iconAssetLocation = 'reply/icons';
const _folderIconAssetLocation = '$_iconAssetLocation/twotone_folder.png';
final desktopMailNavKey = GlobalKey<NavigatorState>();
final mobileMailNavKey = GlobalKey<NavigatorState>();
const double _kFlingVelocity = 2.0;
const _kAnimationDuration = Duration(milliseconds: 300);
class AdaptiveNav extends StatefulWidget {
const AdaptiveNav({super.key});
@override
State<AdaptiveNav> createState() => _AdaptiveNavState();
}
class _AdaptiveNavState extends State<AdaptiveNav> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final isDesktop = isDisplayDesktop(context);
final isTablet = isDisplaySmallDesktop(context);
final localizations = GalleryLocalizations.of(context)!;
final navigationDestinations = <_Destination>[
_Destination(
type: MailboxPageType.inbox,
textLabel: localizations.replyInboxLabel,
icon: '$_iconAssetLocation/twotone_inbox.png',
),
_Destination(
type: MailboxPageType.starred,
textLabel: localizations.replyStarredLabel,
icon: '$_iconAssetLocation/twotone_star.png',
),
_Destination(
type: MailboxPageType.sent,
textLabel: localizations.replySentLabel,
icon: '$_iconAssetLocation/twotone_send.png',
),
_Destination(
type: MailboxPageType.trash,
textLabel: localizations.replyTrashLabel,
icon: '$_iconAssetLocation/twotone_delete.png',
),
_Destination(
type: MailboxPageType.spam,
textLabel: localizations.replySpamLabel,
icon: '$_iconAssetLocation/twotone_error.png',
),
_Destination(
type: MailboxPageType.drafts,
textLabel: localizations.replyDraftsLabel,
icon: '$_iconAssetLocation/twotone_drafts.png',
),
];
final folders = <String, String>{
'Receipts': _folderIconAssetLocation,
'Pine Elementary': _folderIconAssetLocation,
'Taxes': _folderIconAssetLocation,
'Vacation': _folderIconAssetLocation,
'Mortgage': _folderIconAssetLocation,
'Freelance': _folderIconAssetLocation,
};
if (isDesktop) {
return _DesktopNav(
extended: !isTablet,
destinations: navigationDestinations,
folders: folders,
onItemTapped: _onDestinationSelected,
);
} else {
return _MobileNav(
destinations: navigationDestinations,
folders: folders,
onItemTapped: _onDestinationSelected,
);
}
}
void _onDestinationSelected(int index, MailboxPageType destination) {
var emailStore = Provider.of<EmailStore>(
context,
listen: false,
);
final isDesktop = isDisplayDesktop(context);
emailStore.selectedMailboxPage = destination;
if (isDesktop) {
while (desktopMailNavKey.currentState!.canPop()) {
desktopMailNavKey.currentState!.pop();
}
}
if (emailStore.onMailView) {
if (!isDesktop) {
mobileMailNavKey.currentState!.pop();
}
emailStore.selectedEmailId = -1;
}
}
}
class _DesktopNav extends StatefulWidget {
const _DesktopNav({
required this.extended,
required this.destinations,
required this.folders,
required this.onItemTapped,
});
final bool extended;
final List<_Destination> destinations;
final Map<String, String> folders;
final void Function(int, MailboxPageType) onItemTapped;
@override
_DesktopNavState createState() => _DesktopNavState();
}
class _DesktopNavState extends State<_DesktopNav>
with SingleTickerProviderStateMixin {
late ValueNotifier<bool> _isExtended;
@override
void initState() {
super.initState();
_isExtended = ValueNotifier<bool>(widget.extended);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
Consumer<EmailStore>(
builder: (context, model, child) {
return LayoutBuilder(
builder: (context, constraints) {
final selectedIndex =
widget.destinations.indexWhere((destination) {
return destination.type == model.selectedMailboxPage;
});
return Container(
color:
Theme.of(context).navigationRailTheme.backgroundColor,
child: SingleChildScrollView(
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: constraints.maxHeight,
),
child: IntrinsicHeight(
child: ValueListenableBuilder<bool>(
valueListenable: _isExtended,
builder: (context, value, child) {
return NavigationRail(
destinations: [
for (var destination in widget.destinations)
NavigationRailDestination(
icon: Material(
key: ValueKey(
'Reply-${destination.textLabel}',
),
color: Colors.transparent,
child: ImageIcon(
AssetImage(
destination.icon,
package: _assetsPackage,
),
),
),
label: Text(destination.textLabel),
),
],
extended: _isExtended.value,
labelType: NavigationRailLabelType.none,
leading: _NavigationRailHeader(
extended: _isExtended,
),
trailing: _NavigationRailFolderSection(
folders: widget.folders,
),
selectedIndex: selectedIndex,
onDestinationSelected: (index) {
widget.onItemTapped(
index,
widget.destinations[index].type,
);
},
);
},
),
),
),
),
);
},
);
},
),
const VerticalDivider(thickness: 1, width: 1),
Expanded(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 1340),
child: const _SharedAxisTransitionSwitcher(
defaultChild: _MailNavigator(
child: MailboxBody(),
),
),
),
),
),
],
),
);
}
}
class _NavigationRailHeader extends StatelessWidget {
const _NavigationRailHeader({required this.extended});
final ValueNotifier<bool> extended;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
final animation = NavigationRail.extendedAnimation(context);
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Align(
alignment: AlignmentDirectional.centerStart,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 56,
child: Row(
children: [
const SizedBox(width: 6),
InkWell(
key: const ValueKey('ReplyLogo'),
borderRadius: const BorderRadius.all(Radius.circular(16)),
onTap: () {
extended.value = !extended.value;
},
child: Row(
children: [
Transform.rotate(
angle: animation.value * math.pi,
child: const Icon(
Icons.arrow_left,
color: ReplyColors.white50,
size: 16,
),
),
const _ReplyLogo(),
const SizedBox(width: 10),
Align(
alignment: AlignmentDirectional.centerStart,
widthFactor: animation.value,
child: Opacity(
opacity: animation.value,
child: Text(
'REPLY',
style: textTheme.bodyLarge!.copyWith(
color: ReplyColors.white50,
),
),
),
),
SizedBox(width: 18 * animation.value),
],
),
),
if (animation.value > 0)
Opacity(
opacity: animation.value,
child: const Row(
children: [
SizedBox(width: 18),
ProfileAvatar(
avatar: 'reply/avatars/avatar_2.jpg',
radius: 16,
),
SizedBox(width: 12),
Icon(
Icons.settings,
color: ReplyColors.white50,
),
],
),
),
],
),
),
const SizedBox(height: 20),
Padding(
padding: const EdgeInsetsDirectional.only(
start: 8,
),
child: _ReplyFab(extended: extended.value),
),
const SizedBox(height: 8),
],
),
);
},
);
}
}
class _NavigationRailFolderSection extends StatelessWidget {
const _NavigationRailFolderSection({required this.folders});
final Map<String, String> folders;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final textTheme = theme.textTheme;
final navigationRailTheme = theme.navigationRailTheme;
final animation = NavigationRail.extendedAnimation(context);
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Visibility(
maintainAnimation: true,
maintainState: true,
visible: animation.value > 0,
child: Opacity(
opacity: animation.value,
child: Align(
widthFactor: animation.value,
alignment: AlignmentDirectional.centerStart,
child: SizedBox(
height: 485,
width: 256,
child: ListView(
padding: const EdgeInsets.all(12),
physics: const NeverScrollableScrollPhysics(),
children: [
const Divider(
color: ReplyColors.blue200,
thickness: 0.4,
indent: 14,
endIndent: 16,
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsetsDirectional.only(
start: 16,
),
child: Text(
'FOLDERS',
style: textTheme.bodySmall!.copyWith(
color: navigationRailTheme
.unselectedLabelTextStyle!.color,
),
),
),
const SizedBox(height: 8),
for (var folder in folders.keys)
InkWell(
borderRadius: const BorderRadius.all(
Radius.circular(36),
),
onTap: () {},
child: Column(
children: [
Row(
children: [
const SizedBox(width: 12),
ImageIcon(
AssetImage(
folders[folder]!,
package: _assetsPackage,
),
color: navigationRailTheme
.unselectedLabelTextStyle!.color,
),
const SizedBox(width: 24),
Text(
folder,
style: textTheme.bodyLarge!.copyWith(
color: navigationRailTheme
.unselectedLabelTextStyle!.color,
),
),
const SizedBox(height: 72),
],
),
],
),
),
],
),
),
),
),
);
},
);
}
}
class _MobileNav extends StatefulWidget {
const _MobileNav({
required this.destinations,
required this.folders,
required this.onItemTapped,
});
final List<_Destination> destinations;
final Map<String, String> folders;
final void Function(int, MailboxPageType) onItemTapped;
@override
_MobileNavState createState() => _MobileNavState();
}
class _MobileNavState extends State<_MobileNav> with TickerProviderStateMixin {
final _bottomDrawerKey = GlobalKey(debugLabel: 'Bottom Drawer');
late AnimationController _drawerController;
late AnimationController _dropArrowController;
late AnimationController _bottomAppBarController;
late Animation<double> _drawerCurve;
late Animation<double> _dropArrowCurve;
late Animation<double> _bottomAppBarCurve;
@override
void initState() {
super.initState();
_drawerController = AnimationController(
duration: _kAnimationDuration,
value: 0,
vsync: this,
)..addListener(() {
if (_drawerController.value < 0.01) {
setState(() {
//Reload state when drawer is at its smallest to toggle visibility
//If state is reloaded before this drawer closes abruptly instead
//of animating.
});
}
});
_dropArrowController = AnimationController(
duration: _kAnimationDuration,
vsync: this,
);
_bottomAppBarController = AnimationController(
vsync: this,
value: 1,
duration: const Duration(milliseconds: 250),
);
_drawerCurve = CurvedAnimation(
parent: _drawerController,
curve: standardEasing,
reverseCurve: standardEasing.flipped,
);
_dropArrowCurve = CurvedAnimation(
parent: _dropArrowController,
curve: standardEasing,
reverseCurve: standardEasing.flipped,
);
_bottomAppBarCurve = CurvedAnimation(
parent: _bottomAppBarController,
curve: standardEasing,
reverseCurve: standardEasing.flipped,
);
}
@override
void dispose() {
_drawerController.dispose();
_dropArrowController.dispose();
_bottomAppBarController.dispose();
super.dispose();
}
bool get _bottomDrawerVisible {
final status = _drawerController.status;
return status == AnimationStatus.completed ||
status == AnimationStatus.forward;
}
void _toggleBottomDrawerVisibility() {
if (_drawerController.value < 0.4) {
_drawerController.animateTo(0.4, curve: standardEasing);
_dropArrowController.animateTo(0.35, curve: standardEasing);
return;
}
_dropArrowController.forward();
_drawerController.fling(
velocity: _bottomDrawerVisible ? -_kFlingVelocity : _kFlingVelocity,
);
}
double get _bottomDrawerHeight {
final renderBox =
_bottomDrawerKey.currentContext!.findRenderObject() as RenderBox;
return renderBox.size.height;
}
void _handleDragUpdate(DragUpdateDetails details) {
_drawerController.value -= details.primaryDelta! / _bottomDrawerHeight;
}
void _handleDragEnd(DragEndDetails details) {
if (_drawerController.isAnimating ||
_drawerController.status == AnimationStatus.completed) {
return;
}
final flingVelocity =
details.velocity.pixelsPerSecond.dy / _bottomDrawerHeight;
if (flingVelocity < 0.0) {
_drawerController.fling(
velocity: math.max(_kFlingVelocity, -flingVelocity),
);
} else if (flingVelocity > 0.0) {
_dropArrowController.forward();
_drawerController.fling(
velocity: math.min(-_kFlingVelocity, -flingVelocity),
);
} else {
if (_drawerController.value < 0.6) {
_dropArrowController.forward();
}
_drawerController.fling(
velocity:
_drawerController.value < 0.6 ? -_kFlingVelocity : _kFlingVelocity,
);
}
}
bool _handleScrollNotification(ScrollNotification notification) {
if (notification.depth == 0) {
if (notification is UserScrollNotification) {
switch (notification.direction) {
case ScrollDirection.forward:
_bottomAppBarController.forward();
break;
case ScrollDirection.reverse:
_bottomAppBarController.reverse();
break;
case ScrollDirection.idle:
break;
}
}
}
return false;
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
final drawerSize = constraints.biggest;
final drawerTop = drawerSize.height;
final drawerAnimation = RelativeRectTween(
begin: RelativeRect.fromLTRB(0.0, drawerTop, 0.0, 0.0),
end: const RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0),
).animate(_drawerCurve);
return Stack(
clipBehavior: Clip.none,
key: _bottomDrawerKey,
children: [
NotificationListener<ScrollNotification>(
onNotification: _handleScrollNotification,
child: const _MailNavigator(
child: MailboxBody(),
),
),
MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
_drawerController.reverse();
_dropArrowController.reverse();
},
child: Visibility(
maintainAnimation: true,
maintainState: true,
visible: _bottomDrawerVisible,
child: FadeTransition(
opacity: _drawerCurve,
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color:
Theme.of(context).bottomSheetTheme.modalBackgroundColor,
),
),
),
),
),
PositionedTransition(
rect: drawerAnimation,
child: Visibility(
visible: _bottomDrawerVisible,
child: BottomDrawer(
onVerticalDragUpdate: _handleDragUpdate,
onVerticalDragEnd: _handleDragEnd,
leading: Consumer<EmailStore>(
builder: (context, model, child) {
return _BottomDrawerDestinations(
destinations: widget.destinations,
drawerController: _drawerController,
dropArrowController: _dropArrowController,
selectedMailbox: model.selectedMailboxPage,
onItemTapped: widget.onItemTapped,
);
},
),
trailing: _BottomDrawerFolderSection(folders: widget.folders),
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
return _SharedAxisTransitionSwitcher(
defaultChild: Scaffold(
extendBody: true,
body: LayoutBuilder(
builder: _buildStack,
),
bottomNavigationBar: Consumer<EmailStore>(
builder: (context, model, child) {
return _AnimatedBottomAppBar(
bottomAppBarController: _bottomAppBarController,
bottomAppBarCurve: _bottomAppBarCurve,
bottomDrawerVisible: _bottomDrawerVisible,
drawerController: _drawerController,
dropArrowCurve: _dropArrowCurve,
navigationDestinations: widget.destinations,
selectedMailbox: model.selectedMailboxPage,
toggleBottomDrawerVisibility: _toggleBottomDrawerVisibility,
);
},
),
floatingActionButton: _bottomDrawerVisible
? null
: const Padding(
padding: EdgeInsetsDirectional.only(bottom: 8),
child: _ReplyFab(),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
),
);
}
}
class _AnimatedBottomAppBar extends StatelessWidget {
const _AnimatedBottomAppBar({
required this.bottomAppBarController,
required this.bottomAppBarCurve,
required this.bottomDrawerVisible,
required this.drawerController,
required this.dropArrowCurve,
required this.navigationDestinations,
this.selectedMailbox,
this.toggleBottomDrawerVisibility,
});
final AnimationController bottomAppBarController;
final Animation<double> bottomAppBarCurve;
final bool bottomDrawerVisible;
final AnimationController drawerController;
final Animation<double> dropArrowCurve;
final List<_Destination> navigationDestinations;
final MailboxPageType? selectedMailbox;
final ui.VoidCallback? toggleBottomDrawerVisibility;
@override
Widget build(BuildContext context) {
var fadeOut = Tween<double>(begin: 1, end: -1).animate(
drawerController.drive(CurveTween(curve: standardEasing)),
);
return Selector<EmailStore, bool>(
selector: (context, emailStore) => emailStore.onMailView,
builder: (context, onMailView, child) {
bottomAppBarController.forward();
return SizeTransition(
sizeFactor: bottomAppBarCurve,
axisAlignment: -1,
child: Padding(
padding: const EdgeInsetsDirectional.only(top: 2),
child: BottomAppBar(
shape: const WaterfallNotchedRectangle(),
notchMargin: 6,
child: Container(
color: Colors.transparent,
height: kToolbarHeight,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InkWell(
key: const ValueKey('navigation_button'),
borderRadius: const BorderRadius.all(Radius.circular(16)),
onTap: toggleBottomDrawerVisibility,
child: Row(
children: [
const SizedBox(width: 16),
RotationTransition(
turns: Tween(
begin: 0.0,
end: 1.0,
).animate(dropArrowCurve),
child: const Icon(
Icons.arrow_drop_up,
color: ReplyColors.white50,
),
),
const SizedBox(width: 8),
const _ReplyLogo(),
const SizedBox(width: 10),
_FadeThroughTransitionSwitcher(
fillColor: Colors.transparent,
child: onMailView
? const SizedBox(width: 48)
: FadeTransition(
opacity: fadeOut,
child: Text(
navigationDestinations
.firstWhere((destination) {
return destination.type ==
selectedMailbox;
}).textLabel,
style: Theme.of(context)
.textTheme
.bodyLarge!
.copyWith(color: ReplyColors.white50),
),
),
),
],
),
),
Expanded(
child: Container(
color: Colors.transparent,
child: _BottomAppBarActionItems(
drawerVisible: bottomDrawerVisible,
),
),
),
],
),
),
),
),
);
},
);
}
}
class _BottomAppBarActionItems extends StatelessWidget {
const _BottomAppBarActionItems({required this.drawerVisible});
final bool drawerVisible;
@override
Widget build(BuildContext context) {
return Consumer<EmailStore>(
builder: (context, model, child) {
final onMailView = model.onMailView;
Color? starIconColor;
if (onMailView) {
starIconColor = model.isCurrentEmailStarred
? Theme.of(context).colorScheme.secondary
: ReplyColors.white50;
}
return _FadeThroughTransitionSwitcher(
fillColor: Colors.transparent,
child: drawerVisible
? Align(
key: UniqueKey(),
alignment: Alignment.centerRight,
child: IconButton(
icon: const Icon(Icons.settings),
color: ReplyColors.white50,
onPressed: () {},
),
)
: onMailView
? Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
key: const ValueKey('star_email_button'),
icon: ImageIcon(
const AssetImage(
'$_iconAssetLocation/twotone_star.png',
package: _assetsPackage,
),
color: starIconColor,
),
onPressed: () {
final currentEmail = model.currentEmail;
if (model.isCurrentEmailStarred) {
model.unstarEmail(currentEmail.id);
} else {
model.starEmail(currentEmail.id);
}
if (model.selectedMailboxPage ==
MailboxPageType.starred) {
mobileMailNavKey.currentState!.pop();
model.selectedEmailId = -1;
}
},
color: ReplyColors.white50,
),
IconButton(
icon: const ImageIcon(
AssetImage(
'$_iconAssetLocation/twotone_delete.png',
package: _assetsPackage,
),
),
onPressed: () {
model.deleteEmail(
model.selectedEmailId,
);
mobileMailNavKey.currentState!.pop();
model.selectedEmailId = -1;
},
color: ReplyColors.white50,
),
IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () {},
color: ReplyColors.white50,
),
],
)
: Align(
alignment: Alignment.centerRight,
child: IconButton(
key: const ValueKey('ReplySearch'),
icon: const Icon(Icons.search),
color: ReplyColors.white50,
onPressed: () {
Provider.of<EmailStore>(
context,
listen: false,
).onSearchPage = true;
},
),
),
);
},
);
}
}
class _BottomDrawerDestinations extends StatelessWidget {
const _BottomDrawerDestinations({
required this.destinations,
required this.drawerController,
required this.dropArrowController,
required this.selectedMailbox,
required this.onItemTapped,
});
final List<_Destination> destinations;
final AnimationController drawerController;
final AnimationController dropArrowController;
final MailboxPageType selectedMailbox;
final void Function(int, MailboxPageType) onItemTapped;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final destinationButtons = <Widget>[];
for (var index = 0; index < destinations.length; index += 1) {
var destination = destinations[index];
destinationButtons.add(
InkWell(
key: ValueKey('Reply-${destination.textLabel}'),
onTap: () {
drawerController.reverse();
dropArrowController.forward();
Future.delayed(
Duration(
milliseconds: (drawerController.value == 1 ? 300 : 120) *
GalleryOptions.of(context).timeDilation.toInt(),
),
() {
// Wait until animations are complete to reload the state.
// Delay scales with the timeDilation value of the gallery.
onItemTapped(index, destination.type);
},
);
},
child: ListTile(
mouseCursor: SystemMouseCursors.click,
leading: ImageIcon(
AssetImage(
destination.icon,
package: _assetsPackage,
),
color: destination.type == selectedMailbox
? theme.colorScheme.secondary
: theme.navigationRailTheme.unselectedLabelTextStyle!.color,
),
title: Text(
destination.textLabel,
style: theme.textTheme.bodyMedium!.copyWith(
color: destination.type == selectedMailbox
? theme.colorScheme.secondary
: theme.navigationRailTheme.unselectedLabelTextStyle!.color,
),
),
),
),
);
}
return Column(
children: destinationButtons,
);
}
}
class _Destination {
const _Destination({
required this.type,
required this.textLabel,
required this.icon,
});
// Which mailbox page to display. For example, 'Starred' or 'Trash'.
final MailboxPageType type;
// The localized text label for the inbox.
final String textLabel;
// The icon that appears next to the text label for the inbox.
final String icon;
}
class _BottomDrawerFolderSection extends StatelessWidget {
const _BottomDrawerFolderSection({required this.folders});
final Map<String, String> folders;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final navigationRailTheme = theme.navigationRailTheme;
return Column(
children: [
for (var folder in folders.keys)
InkWell(
onTap: () {},
child: ListTile(
mouseCursor: SystemMouseCursors.click,
leading: ImageIcon(
AssetImage(
folders[folder]!,
package: _assetsPackage,
),
color: navigationRailTheme.unselectedLabelTextStyle!.color,
),
title: Text(
folder,
style: theme.textTheme.bodyMedium!.copyWith(
color: navigationRailTheme.unselectedLabelTextStyle!.color,
),
),
),
),
],
);
}
}
class _MailNavigator extends StatefulWidget {
const _MailNavigator({
required this.child,
});
final Widget child;
@override
_MailNavigatorState createState() => _MailNavigatorState();
}
class _MailNavigatorState extends State<_MailNavigator> {
static const inboxRoute = '/reply/inbox';
@override
Widget build(BuildContext context) {
final isDesktop = isDisplayDesktop(context);
return Navigator(
restorationScopeId: 'replyMailNavigator',
key: isDesktop ? desktopMailNavKey : mobileMailNavKey,
initialRoute: inboxRoute,
onGenerateRoute: (settings) {
switch (settings.name) {
case inboxRoute:
return MaterialPageRoute<void>(
builder: (context) {
return _FadeThroughTransitionSwitcher(
fillColor: Theme.of(context).scaffoldBackgroundColor,
child: widget.child,
);
},
settings: settings,
);
case ReplyApp.composeRoute:
return ReplyApp.createComposeRoute(settings);
}
return null;
},
);
}
}
class _ReplyLogo extends StatelessWidget {
const _ReplyLogo();
@override
Widget build(BuildContext context) {
return const ImageIcon(
AssetImage(
'reply/reply_logo.png',
package: _assetsPackage,
),
size: 32,
color: ReplyColors.white50,
);
}
}
class _ReplyFab extends StatefulWidget {
const _ReplyFab({this.extended = false});
final bool extended;
@override
_ReplyFabState createState() => _ReplyFabState();
}
class _ReplyFabState extends State<_ReplyFab>
with SingleTickerProviderStateMixin {
static final fabKey = UniqueKey();
static const double _mobileFabDimension = 56;
void onPressed() {
var onSearchPage = Provider.of<EmailStore>(
context,
listen: false,
).onSearchPage;
// Navigator does not have an easy way to access the current
// route when using a GlobalKey to keep track of NavigatorState.
// We can use [Navigator.popUntil] in order to access the current
// route, and check if it is a ComposePage. If it is not a
// ComposePage and we are not on the SearchPage, then we can push
// a ComposePage onto our navigator. We return true at the end
// so nothing is popped.
desktopMailNavKey.currentState!.popUntil(
(route) {
var currentRoute = route.settings.name;
if (currentRoute != ReplyApp.composeRoute && !onSearchPage) {
desktopMailNavKey.currentState!
.restorablePushNamed(ReplyApp.composeRoute);
}
return true;
},
);
}
@override
Widget build(BuildContext context) {
final isDesktop = isDisplayDesktop(context);
final theme = Theme.of(context);
const circleFabBorder = CircleBorder();
return Selector<EmailStore, bool>(
selector: (context, emailStore) => emailStore.onMailView,
builder: (context, onMailView, child) {
final fabSwitcher = _FadeThroughTransitionSwitcher(
fillColor: Colors.transparent,
child: onMailView
? Icon(
Icons.reply_all,
key: fabKey,
color: Colors.black,
)
: const Icon(
Icons.create,
color: Colors.black,
),
);
final tooltip = onMailView ? 'Reply' : 'Compose';
if (isDesktop) {
final animation = NavigationRail.extendedAnimation(context);
return Container(
height: 56,
padding: EdgeInsets.symmetric(
vertical: ui.lerpDouble(0, 6, animation.value)!,
),
child: animation.value == 0
? FloatingActionButton(
tooltip: tooltip,
key: const ValueKey('ReplyFab'),
onPressed: onPressed,
child: fabSwitcher,
)
: Align(
alignment: AlignmentDirectional.centerStart,
child: FloatingActionButton.extended(
key: const ValueKey('ReplyFab'),
label: Row(
children: [
fabSwitcher,
SizedBox(width: 16 * animation.value),
Align(
alignment: AlignmentDirectional.centerStart,
widthFactor: animation.value,
child: Text(
tooltip.toUpperCase(),
style: Theme.of(context)
.textTheme
.headlineSmall!
.copyWith(
fontSize: 16,
color: theme.colorScheme.onSecondary,
),
),
),
],
),
onPressed: onPressed,
),
),
);
} else {
// TODO(x): State restoration of compose page on mobile is blocked because OpenContainer does not support restorablePush, https://github.com/flutter/gallery/issues/570.
return OpenContainer(
openBuilder: (context, closedContainer) {
return const ComposePage();
},
openColor: theme.cardColor,
closedShape: circleFabBorder,
closedColor: theme.colorScheme.secondary,
closedElevation: 6,
closedBuilder: (context, openContainer) {
return Tooltip(
message: tooltip,
child: InkWell(
key: const ValueKey('ReplyFab'),
customBorder: circleFabBorder,
onTap: openContainer,
child: SizedBox(
height: _mobileFabDimension,
width: _mobileFabDimension,
child: Center(
child: fabSwitcher,
),
),
),
);
},
);
}
},
);
}
}
class _FadeThroughTransitionSwitcher extends StatelessWidget {
const _FadeThroughTransitionSwitcher({
required this.fillColor,
required this.child,
});
final Widget child;
final Color fillColor;
@override
Widget build(BuildContext context) {
return PageTransitionSwitcher(
transitionBuilder: (child, animation, secondaryAnimation) {
return FadeThroughTransition(
fillColor: fillColor,
animation: animation,
secondaryAnimation: secondaryAnimation,
child: child,
);
},
child: child,
);
}
}
class _SharedAxisTransitionSwitcher extends StatelessWidget {
const _SharedAxisTransitionSwitcher({required this.defaultChild});
final Widget defaultChild;
@override
Widget build(BuildContext context) {
return Selector<EmailStore, bool>(
selector: (context, emailStore) => emailStore.onSearchPage,
builder: (context, onSearchPage, child) {
return PageTransitionSwitcher(
reverse: !onSearchPage,
transitionBuilder: (child, animation, secondaryAnimation) {
return SharedAxisTransition(
fillColor: Theme.of(context).colorScheme.background,
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.scaled,
child: child,
);
},
child: onSearchPage ? const SearchPage() : defaultChild,
);
},
);
}
}
| gallery/lib/studies/reply/adaptive_nav.dart/0 | {
"file_path": "gallery/lib/studies/reply/adaptive_nav.dart",
"repo_id": "gallery",
"token_count": 22884
} | 866 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/layout/text_scale.dart';
import 'package:gallery/studies/shrine/app.dart';
import 'package:gallery/studies/shrine/colors.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/page_status.dart';
import 'package:gallery/studies/shrine/triangle_category_indicator.dart';
import 'package:scoped_model/scoped_model.dart';
double desktopCategoryMenuPageWidth({
required BuildContext context,
}) {
return 232 * reducedTextScale(context);
}
class CategoryMenuPage extends StatelessWidget {
const CategoryMenuPage({
super.key,
this.onCategoryTap,
});
final VoidCallback? onCategoryTap;
Widget _buttonText(String caption, TextStyle style) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
caption,
style: style,
textAlign: TextAlign.center,
),
);
}
Widget _divider({required BuildContext context}) {
return Container(
width: 56 * GalleryOptions.of(context).textScaleFactor(context),
height: 1,
color: const Color(0xFF8F716D),
);
}
Widget _buildCategory(Category category, BuildContext context) {
final isDesktop = isDisplayDesktop(context);
final categoryString = category.name(context);
final selectedCategoryTextStyle = Theme.of(context)
.textTheme
.bodyLarge!
.copyWith(fontSize: isDesktop ? 17 : 19);
final unselectedCategoryTextStyle = selectedCategoryTextStyle.copyWith(
color: shrineBrown900.withOpacity(0.6));
final indicatorHeight = (isDesktop ? 28 : 30) *
GalleryOptions.of(context).textScaleFactor(context);
final indicatorWidth = indicatorHeight * 34 / 28;
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) => Semantics(
selected: model.selectedCategory == category,
button: true,
enabled: true,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
model.setCategory(category);
if (onCategoryTap != null) {
onCategoryTap!();
}
},
child: model.selectedCategory == category
? CustomPaint(
painter: TriangleCategoryIndicator(
indicatorWidth,
indicatorHeight,
),
child:
_buttonText(categoryString, selectedCategoryTextStyle),
)
: _buttonText(categoryString, unselectedCategoryTextStyle),
),
),
),
);
}
@override
Widget build(BuildContext context) {
final isDesktop = isDisplayDesktop(context);
final logoutTextStyle = Theme.of(context).textTheme.bodyLarge!.copyWith(
fontSize: isDesktop ? 17 : 19,
color: shrineBrown900.withOpacity(0.6),
);
if (isDesktop) {
return AnimatedBuilder(
animation: PageStatus.of(context)!.cartController,
builder: (context, child) => ExcludeSemantics(
excluding: !menuPageIsVisible(context),
child: Material(
child: Container(
color: shrinePink100,
width: desktopCategoryMenuPageWidth(context: context),
child: Column(
children: [
const SizedBox(height: 64),
Image.asset(
'packages/shrine_images/diamond.png',
excludeFromSemantics: true,
),
const SizedBox(height: 16),
Semantics(
container: true,
child: Text(
'SHRINE',
style: Theme.of(context).textTheme.headlineSmall,
),
),
const Spacer(),
for (final category in categories)
_buildCategory(category, context),
_divider(context: context),
Semantics(
button: true,
enabled: true,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
Navigator.of(context)
.restorablePushNamed(ShrineApp.loginRoute);
},
child: _buttonText(
GalleryLocalizations.of(context)!
.shrineLogoutButtonCaption,
logoutTextStyle,
),
),
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.search),
tooltip:
GalleryLocalizations.of(context)!.shrineTooltipSearch,
onPressed: () {},
),
const SizedBox(height: 72),
],
),
),
),
),
);
} else {
return AnimatedBuilder(
animation: PageStatus.of(context)!.cartController,
builder: (context, child) => AnimatedBuilder(
animation: PageStatus.of(context)!.menuController,
builder: (context, child) => ExcludeSemantics(
excluding: !menuPageIsVisible(context),
child: Center(
child: Container(
padding: const EdgeInsets.only(top: 40),
color: shrinePink100,
child: ListView(
children: [
for (final category in categories)
_buildCategory(category, context),
Center(
child: _divider(context: context),
),
Semantics(
button: true,
enabled: true,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
if (onCategoryTap != null) {
onCategoryTap!();
}
Navigator.of(context)
.restorablePushNamed(ShrineApp.loginRoute);
},
child: _buttonText(
GalleryLocalizations.of(context)!
.shrineLogoutButtonCaption,
logoutTextStyle,
),
),
),
),
],
),
),
),
),
),
);
}
}
}
| gallery/lib/studies/shrine/category_menu_page.dart/0 | {
"file_path": "gallery/lib/studies/shrine/category_menu_page.dart",
"repo_id": "gallery",
"token_count": 3910
} | 867 |
{
"images" : [
{
"filename" : "app_icon_16.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
"filename" : "app_icon_32.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
"filename" : "app_icon_32.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
"filename" : "app_icon_64.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
"filename" : "app_icon_128.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
"filename" : "app_icon_256.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
"filename" : "app_icon_256.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
"filename" : "app_icon_512.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
"filename" : "app_icon_512.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
"filename" : "app_icon_1024.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
| gallery/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json/0 | {
"file_path": "gallery/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json",
"repo_id": "gallery",
"token_count": 765
} | 868 |
// Copyright 2020 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file:avoid_print
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gallery/data/demos.dart';
import 'package:gallery/main.dart';
import 'scroll.dart';
const Duration _initialWaitingDuration = Duration(milliseconds: 1500);
const List<String> _demosWithAnimation = <String>[
'progress-indicator@material',
'cupertino-activity-indicator@cupertino',
];
const Duration _defaultWaitingDuration = Duration(seconds: 3);
enum DemoType {
study,
animatedWidget,
unanimatedWidget,
}
DemoType typeOfDemo(String demo) {
if (demo.contains('@study')) {
return DemoType.study;
} else if (_demosWithAnimation.contains(demo)) {
return DemoType.animatedWidget;
} else {
return DemoType.unanimatedWidget;
}
}
/// A class that automates the gallery.
class GalleryAutomator {
GalleryAutomator({
required this.benchmarkName,
this.shouldRunPredicate,
this.testScrollsOnly = false,
required this.stopWarmingUpCallback,
}) : assert(testScrollsOnly || shouldRunPredicate != null);
/// The name of the current benchmark.
final String benchmarkName;
/// A function deciding whether a demo should be run in this benchmark.
final bool Function(String)? shouldRunPredicate;
/// Whether we only test scrolling in this benchmark.
final bool testScrollsOnly;
/// A function to call when warm-up is finished.
///
/// This function is intended to ask `Recorder` to mark the warm-up phase
/// as over.
final void Function() stopWarmingUpCallback;
/// Whether the automation has ended.
bool finished = false;
/// A widget controller for automation.
late LiveWidgetController controller;
/// An iterable that generates all demo names.
Iterable<String> get demoNames => Demos.allDescriptions();
/// The gallery widget, with automation.
Widget createWidget() {
// There is no `catchError` here, because all errors are caught by
// the zone set up in `lib/web_benchmarks.dart` in `flutter/flutter`.
Future<void>.delayed(
_initialWaitingDuration,
testScrollsOnly ? automateScrolls : automateDemoGestures,
);
return const GalleryApp();
}
/// Opens and quits demos that are specified by [shouldRunPredicate], twice.
Future<void> automateDemoGestures() async {
await warmUp();
print('==== List of demos to be run ====');
for (final demo in demoNames) {
if (shouldRunPredicate!(demo)) {
print(demo);
}
}
print('==== End of list of demos to be run ====');
var finishedStudyDemos = false;
for (final demo in demoNames) {
if (!finishedStudyDemos && typeOfDemo(demo) != DemoType.study) {
finishedStudyDemos = true;
await scrollUntilVisible(
element: find.text('Categories').evaluate().single,
strict: true,
animated: false,
);
}
final demoButton =
find.byKey(ValueKey(demo), skipOffstage: false).evaluate().single;
await scrollUntilVisible(
element: demoButton,
animated: false,
);
// Run demo if it passes `runCriterion`.
// Note that the above scrolling is required even for demos *not*
// satisfying `runCriterion`, because we need to scroll
// through every `Scrollable` to find the `demoButton`.
if (shouldRunPredicate!(demo)) {
print('Running demo "$demo"');
for (var i = 0; i < 2; ++i) {
await controller.tap(find.byKey(ValueKey(demo)));
if (typeOfDemo(demo) == DemoType.animatedWidget) {
await Future<void>.delayed(_defaultWaitingDuration);
} else {
await animationStops();
}
await controller.tap(find.byKey(const ValueKey('Back')));
await animationStops();
}
}
}
print('All demos finished.');
// At the end of the test, mark as finished.
finished = true;
}
/// Scrolls various parts of the gallery.
Future<void> automateScrolls() async {
await warmUp();
print('Running scrolling test.');
final selectedDemos = firstDemosOfCategories(demoNames);
var scrolled = false;
// For each category
for (final demo in selectedDemos) {
// Scroll to that category
if (!scrolled && categoryOf(demo) != 'study') {
scrolled = true;
await scrollUntilVisible(
element: find.text('Categories').evaluate().single,
strict: true,
);
} else if (scrolled && categoryOf(demo) == 'study') {
scrolled = false;
final pageScrollable =
Scrollable.of(find.text('Categories').evaluate().single);
await scrollToExtreme(scrollable: pageScrollable, toEnd: false);
}
// Scroll that scrollable
final demoButton =
find.byKey(ValueKey(demo), skipOffstage: false).evaluate().single;
final scrollable = Scrollable.of(demoButton);
for (var i = 0; i < 2; ++i) {
await scrollToExtreme(scrollable: scrollable, toEnd: true);
await scrollToExtreme(scrollable: scrollable, toEnd: false);
}
}
print('Scrolling test finished.');
finished = true;
}
/// Warm up the animation.
Future<void> warmUp() async {
print('Warming up.');
await pumpDeferredLibraries();
// Let animation stop.
await animationStops();
// Set controller.
controller = LiveWidgetController(WidgetsBinding.instance);
// Find first demo of each category.
final candidateDemos = firstDemosOfCategories(demoNames);
// Find first demo that is not being tested here.
// We open this demo as a way to warm up the engine, so we need to use an
// untested demo to avoid biasing the benchmarks.
String? firstUntestedDemo;
for (final demo in candidateDemos) {
if (testScrollsOnly || !shouldRunPredicate!(demo)) {
firstUntestedDemo = demo;
break;
}
}
assert(firstUntestedDemo != null);
// Open and close the demo twice to warm up.
for (var i = 0; i < 2; ++i) {
await controller.tap(find.byKey(ValueKey(firstUntestedDemo!)));
if (typeOfDemo(firstUntestedDemo) == DemoType.animatedWidget) {
await Future<void>.delayed(_defaultWaitingDuration);
} else {
await animationStops();
}
await controller.tap(find.byKey(const ValueKey('Back')));
await animationStops();
}
// When warm-up finishes, inform the recorder.
stopWarmingUpCallback();
print('Warm-up finished.');
}
/// A function to find the category of a demo.
String categoryOf(String demo) {
final atSymbolIndex = demo.lastIndexOf('@');
if (atSymbolIndex < 0) {
return '';
} else {
return demo.substring(atSymbolIndex + 1);
}
}
/// A function to find the first demo of each category.
List<String> firstDemosOfCategories(Iterable<String> demoList) {
// Select the first demo from each category.
final coveredCategories = <String>{};
final selectedDemos = <String>[];
for (final demo in demoList) {
final category = categoryOf(demo);
if (!coveredCategories.contains(category)) {
coveredCategories.add(category);
selectedDemos.add(demo);
}
}
return selectedDemos;
}
}
| gallery/test_benchmarks/benchmarks/gallery_automator.dart/0 | {
"file_path": "gallery/test_benchmarks/benchmarks/gallery_automator.dart",
"repo_id": "gallery",
"token_count": 2700
} | 869 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="development" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="additionalArgs" value="--dart-define=ENCRYPTION_KEY=$ENCRYPTION_KEY --dart-define=ENCRYPTION_IV=$ENCRYPTION_IV --dart-define=RECAPTCHA_KEY=$RECAPTCHA_KEY --dart-define=APPCHECK_DEBUG_TOKEN=$APPCHECK_DEBUG_TOKEN --dart-define ALLOW_PRIVATE_MATCHES=true" />
<option name="buildFlavor" value="development" />
<option name="filePath" value="$PROJECT_DIR$/lib/main_development.dart" />
<method v="2" />
</configuration>
</component>
| io_flip/.idea/runConfigurations/development.xml/0 | {
"file_path": "io_flip/.idea/runConfigurations/development.xml",
"repo_id": "io_flip",
"token_count": 220
} | 870 |
import 'package:dart_frog/dart_frog.dart';
import 'package:jwt_middleware/jwt_middleware.dart';
import 'package:shelf_cors_headers/shelf_cors_headers.dart';
Middleware allowHeaders() {
return (handler) {
return (context) async {
final response = await handler(context);
final headers = Map<String, String>.from(response.headers);
final accessControlAllowHeaders = headers[ACCESS_CONTROL_ALLOW_HEADERS];
if (accessControlAllowHeaders != null) {
headers[ACCESS_CONTROL_ALLOW_HEADERS] =
'$accessControlAllowHeaders, $X_FIREBASE_APPCHECK';
return response.copyWith(headers: headers);
}
return response;
};
};
}
| io_flip/api/headers/allow_headers.dart/0 | {
"file_path": "io_flip/api/headers/allow_headers.dart",
"repo_id": "io_flip",
"token_count": 267
} | 871 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'leaderboard_player.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
LeaderboardPlayer _$LeaderboardPlayerFromJson(Map<String, dynamic> json) =>
LeaderboardPlayer(
id: json['id'] as String,
longestStreak: json['longestStreak'] as int,
initials: json['initials'] as String,
);
Map<String, dynamic> _$LeaderboardPlayerToJson(LeaderboardPlayer instance) =>
<String, dynamic>{
'id': instance.id,
'longestStreak': instance.longestStreak,
'initials': instance.initials,
};
| io_flip/api/packages/game_domain/lib/src/models/leaderboard_player.g.dart/0 | {
"file_path": "io_flip/api/packages/game_domain/lib/src/models/leaderboard_player.g.dart",
"repo_id": "io_flip",
"token_count": 221
} | 872 |
name: game_domain
description: Domain classes for the game
version: 0.1.0+1
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dev_dependencies:
build_runner: ^2.4.1
json_serializable: ^6.6.1
mocktail: ^0.3.0
test: ^1.24.1
very_good_analysis: ^4.0.0
dependencies:
equatable: ^2.0.5
game_script_machine:
path: ../game_script_machine
json_annotation: ^4.8.0
# There seems to be a breaking change in the current beta
# that makes the resolved verion of pub_semver that is
# a transitive dependency from build_runner to break.
#
# Overriding to the latest one in the mean time.
dependency_overrides:
pub_semver: ^2.1.3
| io_flip/api/packages/game_domain/pubspec.yaml/0 | {
"file_path": "io_flip/api/packages/game_domain/pubspec.yaml",
"repo_id": "io_flip",
"token_count": 251
} | 873 |
/// Holds and proccess the scripts responsible for calculating the result of a
/// game match
library game_script_machine;
export 'src/default_script.dart';
export 'src/game_script_machine.dart';
| io_flip/api/packages/game_script_machine/lib/game_script_machine.dart/0 | {
"file_path": "io_flip/api/packages/game_script_machine/lib/game_script_machine.dart",
"repo_id": "io_flip",
"token_count": 55
} | 874 |
// ignore_for_file: prefer_const_constructors
import 'dart:math';
import 'package:db_client/db_client.dart';
import 'package:game_domain/game_domain.dart';
import 'package:language_model_repository/language_model_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:prompt_repository/prompt_repository.dart';
import 'package:test/test.dart';
class _MockDbClient extends Mock implements DbClient {}
class _MockPromptRepository extends Mock implements PromptRepository {}
class _MockRandom extends Mock implements Random {}
void main() {
group('LanguageModelRepository', () {
late DbClient dbClient;
late PromptRepository promptRepository;
late Random rng;
late LanguageModelRepository languageModelRepository;
setUp(() {
dbClient = _MockDbClient();
promptRepository = _MockPromptRepository();
when(() => promptRepository.getByTerm('Baggles')).thenAnswer(
(_) async => PromptTerm(
id: '1',
term: 'Baggles',
shortenedTerm: 'Baggles',
type: PromptTermType.power,
),
);
rng = _MockRandom();
languageModelRepository = LanguageModelRepository(
dbClient: dbClient,
promptRepository: promptRepository,
rng: rng,
);
});
test('can be instantiated', () {
expect(
LanguageModelRepository(
dbClient: _MockDbClient(),
promptRepository: _MockPromptRepository(),
),
isNotNull,
);
});
group('generateCardName', () {
test('generates with class', () async {
when(() => rng.nextInt(2)).thenReturn(0);
expect(
await languageModelRepository.generateCardName(
characterName: 'Dash',
characterClass: 'Mage',
characterPower: 'Baggles',
),
equals('Mage Dash'),
);
});
test('generates with power', () async {
when(() => rng.nextInt(2)).thenReturn(1);
expect(
await languageModelRepository.generateCardName(
characterName: 'Dash',
characterClass: 'Mage',
characterPower: 'Baggles',
),
equals('Baggles Dash'),
);
});
test('generates with the shorter power when there is one', () async {
when(() => promptRepository.getByTerm('Breaking Dance')).thenAnswer(
(_) async => PromptTerm(
id: '1',
term: 'Breaking Dance',
shortenedTerm: 'Break Dance',
type: PromptTermType.power,
),
);
when(() => rng.nextInt(2)).thenReturn(1);
expect(
await languageModelRepository.generateCardName(
characterName: 'Dash',
characterClass: 'Mage',
characterPower: 'Breaking Dance',
),
equals('Break Dance Dash'),
);
});
test("uses the informed power when there isn't a shorter one", () async {
when(() => promptRepository.getByTerm('Breaking Dance')).thenAnswer(
(_) async => null,
);
when(() => rng.nextInt(2)).thenReturn(1);
expect(
await languageModelRepository.generateCardName(
characterName: 'Dash',
characterClass: 'Mage',
characterPower: 'Breaking Dance',
),
equals('Breaking Dance Dash'),
);
});
});
group('generateFlavorText', () {
test('returns a random value of the query', () async {
when(() => rng.nextInt(2)).thenReturn(1);
when(
() => dbClient.find('card_descriptions', {
'character': 'dash',
'characterClass': 'wizard',
'power': 'baggles',
'location': 'beach',
}),
).thenAnswer(
(_) async => [
DbEntityRecord(id: '', data: const {'description': 'A'}),
DbEntityRecord(id: '', data: const {'description': 'B'}),
],
);
expect(
await languageModelRepository.generateFlavorText(
character: 'Dash',
characterClass: 'Wizard',
characterPower: 'Baggles',
location: 'Beach',
),
equals('B'),
);
});
test('makes the correct query', () async {
when(() => rng.nextInt(2)).thenReturn(1);
when(
() => dbClient.find('card_descriptions', {
'character': 'super_dash',
'characterClass': 'ice_wizard',
'power': 'super_baggles',
'location': 'active_volcano',
}),
).thenAnswer(
(_) async => [
DbEntityRecord(id: '', data: const {'description': 'A'}),
DbEntityRecord(id: '', data: const {'description': 'B'}),
],
);
expect(
await languageModelRepository.generateFlavorText(
character: 'Super Dash',
characterClass: 'Ice Wizard',
characterPower: 'Super Baggles',
location: 'Active Volcano',
),
equals('B'),
);
});
test('returns empty is nothing is found', () async {
when(() => rng.nextInt(2)).thenReturn(1);
when(
() => dbClient.find('card_descriptions', {
'character': 'dash',
'characterClass': 'wizard',
'power': 'baggles',
'location': 'beach',
}),
).thenAnswer(
(_) async => [],
);
expect(
await languageModelRepository.generateFlavorText(
character: 'Dash',
characterPower: 'Baggles',
characterClass: 'Wizard',
location: 'Beach',
),
isEmpty,
);
});
});
});
}
| io_flip/api/packages/language_model_repository/test/src/language_model_repository_test.dart/0 | {
"file_path": "io_flip/api/packages/language_model_repository/test/src/language_model_repository_test.dart",
"repo_id": "io_flip",
"token_count": 2740
} | 875 |
import 'dart:async';
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:match_repository/match_repository.dart';
FutureOr<Response> onRequest(RequestContext context, String matchId) async {
if (context.request.method == HttpMethod.get) {
final matchRepository = context.read<MatchRepository>();
final matchState = await matchRepository.getMatchState(matchId);
if (matchState == null) {
return Response(statusCode: HttpStatus.notFound);
}
return Response.json(body: matchState.toJson());
}
return Response(statusCode: HttpStatus.methodNotAllowed);
}
| io_flip/api/routes/game/matches/[matchId]/state.dart/0 | {
"file_path": "io_flip/api/routes/game/matches/[matchId]/state.dart",
"repo_id": "io_flip",
"token_count": 207
} | 876 |
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';
import 'package:jwt_middleware/jwt_middleware.dart';
import 'package:logging/logging.dart';
import 'package:match_repository/match_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import '../../../../../../../routes/game/matches/[matchId]/decks/[deckId]/cards/[cardId].dart'
as route;
class _MockRequestContext extends Mock implements RequestContext {}
class _MockMatchRepository extends Mock implements MatchRepository {}
class _MockRequest extends Mock implements Request {}
class _MockLogger extends Mock implements Logger {}
void main() {
group('POST /game/matches/[matchId]/decks/[deckId]/cards/[cardId]', () {
late MatchRepository matchRepository;
late Request request;
late RequestContext context;
late Logger logger;
const matchId = 'matchId';
const deckId = 'deckId';
const cardId = 'cardId';
const userId = 'userId';
const user = AuthenticatedUser(userId);
setUp(() {
matchRepository = _MockMatchRepository();
when(
() => matchRepository.playCard(
matchId: matchId,
deckId: deckId,
cardId: cardId,
userId: userId,
),
).thenAnswer(
(_) async {},
);
request = _MockRequest();
when(() => request.method).thenReturn(HttpMethod.post);
logger = _MockLogger();
context = _MockRequestContext();
when(() => context.request).thenReturn(request);
when(() => context.read<MatchRepository>()).thenReturn(matchRepository);
when(() => context.read<Logger>()).thenReturn(logger);
when(() => context.read<AuthenticatedUser>()).thenReturn(user);
});
test('responds with a 200', () async {
final response = await route.onRequest(context, matchId, deckId, cardId);
expect(response.statusCode, equals(HttpStatus.noContent));
});
test('returns bad request when the move is invalid', () async {
when(
() => matchRepository.playCard(
matchId: matchId,
cardId: cardId,
deckId: deckId,
userId: userId,
),
).thenThrow(
PlayCardFailure(),
);
final response = await route.onRequest(context, matchId, deckId, cardId);
expect(response.statusCode, equals(HttpStatus.badRequest));
});
test('returns not found when the resources cannot be found', () async {
when(
() => matchRepository.playCard(
matchId: matchId,
cardId: cardId,
deckId: deckId,
userId: userId,
),
).thenThrow(
MatchNotFoundFailure(),
);
final response = await route.onRequest(context, matchId, deckId, cardId);
expect(response.statusCode, equals(HttpStatus.notFound));
});
test("rethrows error when the card can't be played", () async {
when(
() => matchRepository.playCard(
matchId: matchId,
cardId: cardId,
deckId: deckId,
userId: userId,
),
).thenThrow(
Exception('Ops'),
);
final response = route.onRequest(context, matchId, deckId, cardId);
expect(response, throwsA(isA<Exception>()));
});
test('allows only post methods', () async {
when(() => request.method).thenReturn(HttpMethod.get);
final response = await route.onRequest(context, matchId, deckId, cardId);
expect(response.statusCode, equals(HttpStatus.methodNotAllowed));
});
});
}
| io_flip/api/test/routes/game/matches/[matchId]/decks/[deckId]/[cardId]_test.dart/0 | {
"file_path": "io_flip/api/test/routes/game/matches/[matchId]/decks/[deckId]/[cardId]_test.dart",
"repo_id": "io_flip",
"token_count": 1428
} | 877 |
import 'dart:io';
import 'package:data_loader/src/prompt_mapper.dart';
import 'package:game_domain/game_domain.dart';
import 'package:path/path.dart' as path;
/// {@template character_folder_validator}
/// Dart tool that checks if the character folder is valid
/// given the prompts stored in csv file.
/// {@endtemplate}
class CharacterFolderValidator {
/// {@macro character_folder_validator}
const CharacterFolderValidator({
required File csv,
required Directory imagesFolder,
required String character,
required int variations,
}) : _csv = csv,
_imagesFolder = imagesFolder,
_character = character,
_variations = variations;
final File _csv;
final Directory _imagesFolder;
final String _character;
final int _variations;
/// Loads the data from the CSV file into the database
/// [onProgress] is called everytime there is progress,
/// it takes in the current inserted and the total to insert.
Future<List<String>> validate(void Function(int, int) onProgress) async {
final lines = await _csv.readAsLines();
final map = mapCsvToPrompts(lines);
final fileNames = <String>[];
final missingFiles = <String>[];
for (final characterClass in map[PromptTermType.characterClass]!) {
for (final location in map[PromptTermType.location]!) {
for (var i = 0; i < _variations; i++) {
fileNames.add(
path
.join(
_imagesFolder.path,
[
_character,
characterClass,
location,
'$i.png',
].join('_').replaceAll(' ', '_'),
)
.toLowerCase(),
);
}
}
}
var progress = 0;
onProgress(progress, fileNames.length);
for (final filename in fileNames) {
progress++;
if (!File(filename).existsSync()) {
missingFiles.add(filename);
}
onProgress(progress, fileNames.length);
}
return missingFiles;
}
}
| io_flip/api/tools/data_loader/lib/src/character_folder_validator.dart/0 | {
"file_path": "io_flip/api/tools/data_loader/lib/src/character_folder_validator.dart",
"repo_id": "io_flip",
"token_count": 841
} | 878 |
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members, no_default_cases
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show TargetPlatform, defaultTargetPlatform, kIsWeb;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for android - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.iOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for ios - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.macOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for macos - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions web = FirebaseOptions(
apiKey: 'AIzaSyC4vPpnkAspixD-NN8aYZ1HjEUFNa72cds',
appId: '1:933036048132:web:87d22a04cda0d96ecd9a51',
messagingSenderId: '933036048132',
projectId: 'top-dash-dev',
authDomain: 'top-dash-dev.firebaseapp.com',
storageBucket: 'top-dash-dev.appspot.com',
measurementId: 'G-F7PXP7CEE4',
);
}
| io_flip/flop/lib/firebase_options_development.dart/0 | {
"file_path": "io_flip/flop/lib/firebase_options_development.dart",
"repo_id": "io_flip",
"token_count": 883
} | 879 |
{
"name": "Flop",
"short_name": "Flop",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A Very Good Project created by Very Good CLI.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
| io_flip/flop/web/manifest.json/0 | {
"file_path": "io_flip/flop/web/manifest.json",
"repo_id": "io_flip",
"token_count": 307
} | 880 |
// Copyright 2022, the Flutter 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.
import 'package:flutter/widgets.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
class AppLifecycleObserver extends StatefulWidget {
const AppLifecycleObserver({required this.child, super.key});
final Widget child;
@override
State<AppLifecycleObserver> createState() => AppLifecycleObserverState();
}
@visibleForTesting
class AppLifecycleObserverState extends State<AppLifecycleObserver>
with WidgetsBindingObserver {
static final _log = Logger('AppLifecycleObserver');
final ValueNotifier<AppLifecycleState> lifecycleListenable =
ValueNotifier(AppLifecycleState.inactive);
@override
Widget build(BuildContext context) {
// Using InheritedProvider because we don't want to use Consumer
// or context.watch or anything like that to listen to this. We want
// to manually add listeners. We're interested in the _events_ of lifecycle
// state changes, and not so much in the state itself. (For example,
// we want to stop sound when the app goes into the background, and
// restart sound again when the app goes back into focus. We're not
// rebuilding any widgets.)
//
// Provider, by default, throws when one
// is trying to provide a Listenable (such as ValueNotifier) without using
// something like ValueListenableProvider. InheritedProvider is more
// low-level and doesn't have this problem.
return InheritedProvider<ValueNotifier<AppLifecycleState>>.value(
value: lifecycleListenable,
child: widget.child,
);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
_log.info(() => 'didChangeAppLifecycleState: $state');
lifecycleListenable.value = state;
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_log.info('Subscribed to app lifecycle updates');
}
}
| io_flip/lib/app_lifecycle/app_lifecycle.dart/0 | {
"file_path": "io_flip/lib/app_lifecycle/app_lifecycle.dart",
"repo_id": "io_flip",
"token_count": 687
} | 881 |
part of 'draft_bloc.dart';
enum DraftStateStatus {
initial,
deckLoading,
deckLoaded,
deckFailed,
deckSelected,
playerDeckCreated,
playerDeckFailed,
}
class DraftState extends Equatable {
const DraftState({
required this.cards,
required this.status,
required this.selectedCards,
required this.firstCardOpacity,
this.deck,
this.createPrivateMatch,
this.privateMatchInviteCode,
});
const DraftState.initial()
: this(
cards: const [],
selectedCards: const [null, null, null],
status: DraftStateStatus.initial,
firstCardOpacity: 1,
);
final List<Card> cards;
final List<Card?> selectedCards;
final DraftStateStatus status;
final double firstCardOpacity;
final Deck? deck;
final bool? createPrivateMatch;
final String? privateMatchInviteCode;
DraftState copyWith({
List<Card>? cards,
List<Card?>? selectedCards,
DraftStateStatus? status,
double? firstCardOpacity,
Deck? deck,
bool? createPrivateMatch,
String? privateMatchInviteCode,
}) {
return DraftState(
cards: cards ?? this.cards,
selectedCards: selectedCards ?? this.selectedCards,
status: status ?? this.status,
firstCardOpacity: firstCardOpacity ?? this.firstCardOpacity,
deck: deck ?? this.deck,
createPrivateMatch: createPrivateMatch ?? this.createPrivateMatch,
privateMatchInviteCode:
privateMatchInviteCode ?? this.privateMatchInviteCode,
);
}
@override
List<Object?> get props =>
[cards, status, selectedCards, firstCardOpacity, deck];
}
| io_flip/lib/draft/bloc/draft_state.dart/0 | {
"file_path": "io_flip/lib/draft/bloc/draft_state.dart",
"repo_id": "io_flip",
"token_count": 598
} | 882 |
export 'game_page.dart';
export 'game_summary.dart';
export 'game_view.dart';
| io_flip/lib/game/views/views.dart/0 | {
"file_path": "io_flip/lib/game/views/views.dart",
"repo_id": "io_flip",
"token_count": 30
} | 883 |
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:game_domain/game_domain.dart';
import 'package:io_flip/gen/assets.gen.dart';
import 'package:io_flip/how_to_play/how_to_play.dart';
import 'package:io_flip/l10n/l10n.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
const transitionDuration = Duration(milliseconds: 400);
const suitsWheelSize = 300.0;
class SuitsWheel extends StatelessWidget {
const SuitsWheel({
required this.suits,
required this.affectedIndexes,
required this.text,
super.key,
}) : assert(
suits.length == 5,
'5 suits must be present in the wheel',
);
final List<Suit> suits;
final List<int> affectedIndexes;
final String text;
static const List<Alignment> alignments = [
SuitAlignment.topCenter,
SuitAlignment.centerRight,
SuitAlignment.bottomRight,
SuitAlignment.bottomLeft,
SuitAlignment.centerLeft,
];
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
FadeAnimatedSwitcher(
duration: transitionDuration,
child: HowToPlayStyledText(
text,
key: ValueKey(text),
),
),
const SizedBox(height: IoFlipSpacing.lg),
SizedBox(
height: suitsWheelSize,
width: suitsWheelSize,
child: Stack(
children: [
...suits.mapIndexed(
(index, suit) {
return SuitItem(
key: ValueKey(suit),
initialAlignment: suit.initialAlignment,
alignment: alignments[index],
isReference: index == 0,
isAffected: affectedIndexes.contains(index - 1),
child: suit.icon,
);
},
),
_AffectedArrows(affectedIndexes),
_AffectedIndicators(affectedIndexes)
],
),
),
],
);
}
}
class SuitItem extends StatelessWidget {
const SuitItem({
required this.initialAlignment,
required this.alignment,
required this.isReference,
required this.isAffected,
required this.child,
super.key,
});
final Alignment initialAlignment;
final Alignment alignment;
final bool isReference;
final bool isAffected;
final SuitIcon child;
@override
Widget build(BuildContext context) {
return TweenAnimationBuilder<Alignment>(
duration: transitionDuration,
curve: const Cubic(.1, 0, .2, 1),
tween: CircularAlignmentTween(begin: initialAlignment, end: alignment),
builder: (context, alignment, child) => Align(
alignment: alignment,
child: child,
),
child: TweenAnimationBuilder<double>(
duration: transitionDuration,
tween: Tween<double>(
begin: 0,
end: isAffected || isReference ? 0 : 1,
),
builder: (_, number, __) {
final color = IoFlipColors.seedGrey30.withOpacity(number);
return ColorFiltered(
colorFilter: ColorFilter.mode(color, BlendMode.srcATop),
child: child,
);
},
),
);
}
}
class _AffectedArrows extends StatelessWidget {
const _AffectedArrows(this.affectedIndexes);
final List<int> affectedIndexes;
static const size = suitsWheelSize;
static const iconSize = 96;
static const topPosition = Offset(size * .5, iconSize * .5);
static const centerLeftPosition = Offset(iconSize * .5, size * .45);
static const centerRightPosition = Offset(size - iconSize * .5, size * .45);
static const bottomLeftPosition = Offset(size * .3, size - iconSize * .5);
static const bottomRightPosition = Offset(size * .7, size - iconSize * .5);
@override
Widget build(BuildContext context) {
final rightArrowStart = getMidpoint(topPosition, centerRightPosition, .45);
final rightArrowEnd = getMidpoint(topPosition, centerRightPosition, .65);
final midRightArrowStart =
getMidpoint(topPosition, bottomRightPosition, .35);
final midRightArrowEnd = getMidpoint(topPosition, bottomRightPosition, .75);
final midLeftArrowStart = getMidpoint(topPosition, bottomLeftPosition, .35);
final midLeftArrowEnd = getMidpoint(topPosition, bottomLeftPosition, .75);
final leftArrowStart = getMidpoint(topPosition, centerLeftPosition, .45);
final leftArrowEnd = getMidpoint(topPosition, centerLeftPosition, .65);
return Stack(
children: [
ArrowWidget(
rightArrowStart,
rightArrowEnd,
visible: affectedIndexes.contains(0),
),
ArrowWidget(
midRightArrowStart,
midRightArrowEnd,
visible: affectedIndexes.contains(1),
),
ArrowWidget(
midLeftArrowStart,
midLeftArrowEnd,
visible: affectedIndexes.contains(2),
),
ArrowWidget(
leftArrowStart,
leftArrowEnd,
visible: affectedIndexes.contains(3),
),
],
);
}
Offset getMidpoint(Offset p1, Offset p2, double distanceRatio) {
return p1 + (p2 - p1) * distanceRatio;
}
}
class _AffectedIndicators extends StatelessWidget {
const _AffectedIndicators(this.affectedIndexes);
final List<int> affectedIndexes;
static const List<Alignment> alignments = [
Alignment(1, -.25),
Alignment(.7, .6),
Alignment(-.7, .6),
Alignment(-1, -.25),
];
@override
Widget build(BuildContext context) {
return Stack(
children: alignments
.mapIndexed(
(i, alignment) => AnimatedOpacity(
duration: transitionDuration,
opacity: affectedIndexes.contains(i) ? 1 : 0,
child: Align(
alignment: alignment,
child: const _AffectedIndicator(),
),
),
)
.toList(),
);
}
}
class _AffectedIndicator extends StatelessWidget {
const _AffectedIndicator();
@override
Widget build(BuildContext context) {
final backgroundColor = Theme.of(context).dialogBackgroundColor;
return DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
width: 4,
strokeAlign: BorderSide.strokeAlignCenter,
color: backgroundColor,
),
color: IoFlipColors.seedRed,
),
child: Padding(
padding: const EdgeInsets.all(IoFlipSpacing.sm),
child: Assets.icons.cancel.svg(width: 20, height: 20),
),
);
}
}
extension SuitsWheelX on Suit {
SuitIcon get icon {
switch (this) {
case Suit.fire:
return SuitIcon.fire();
case Suit.water:
return SuitIcon.water();
case Suit.air:
return SuitIcon.air();
case Suit.earth:
return SuitIcon.earth();
case Suit.metal:
return SuitIcon.metal();
}
}
Alignment get initialAlignment {
switch (this) {
case Suit.fire:
return SuitAlignment.topCenter;
case Suit.air:
return SuitAlignment.centerRight;
case Suit.metal:
return SuitAlignment.bottomRight;
case Suit.earth:
return SuitAlignment.bottomLeft;
case Suit.water:
return SuitAlignment.centerLeft;
}
}
List<Suit> get suitsAffected {
switch (this) {
case Suit.fire:
return [Suit.air, Suit.metal];
case Suit.air:
return [Suit.water, Suit.earth];
case Suit.metal:
return [Suit.air, Suit.water];
case Suit.earth:
return [Suit.fire, Suit.metal];
case Suit.water:
return [Suit.fire, Suit.earth];
}
}
String Function(AppLocalizations) get text {
switch (this) {
case Suit.fire:
return (l10n) => l10n.howToPlayElementsFireTitle;
case Suit.air:
return (l10n) => l10n.howToPlayElementsAirTitle;
case Suit.metal:
return (l10n) => l10n.howToPlayElementsMetalTitle;
case Suit.earth:
return (l10n) => l10n.howToPlayElementsEarthTitle;
case Suit.water:
return (l10n) => l10n.howToPlayElementsWaterTitle;
}
}
}
class SuitAlignment {
static const Alignment topCenter = Alignment.topCenter;
static const Alignment centerRight = Alignment(1, -.1);
static const Alignment centerLeft = Alignment(-1, -.1);
static const Alignment bottomRight = Alignment(.6, 1);
static const Alignment bottomLeft = Alignment(-.6, 1);
}
| io_flip/lib/how_to_play/widgets/suits_wheel.dart/0 | {
"file_path": "io_flip/lib/how_to_play/widgets/suits_wheel.dart",
"repo_id": "io_flip",
"token_count": 3696
} | 884 |
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/l10n/l10n.dart';
import 'package:io_flip/leaderboard/initials_form/initials_form.dart';
import 'package:io_flip/share/share.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
const emptyCharacter = '\u200b';
class InitialsFormView extends StatefulWidget {
const InitialsFormView({super.key, this.shareHandPageData});
final ShareHandPageData? shareHandPageData;
@override
State<InitialsFormView> createState() => _InitialsFormViewState();
}
class _InitialsFormViewState extends State<InitialsFormView> {
final focusNodes = List.generate(3, (_) => FocusNode());
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return BlocConsumer<InitialsFormBloc, InitialsFormState>(
listener: (context, state) {
if (state.status == InitialsFormStatus.success) {
if (widget.shareHandPageData != null) {
GoRouter.of(context).goNamed(
'share_hand',
extra: ShareHandPageData(
initials: state.initials.join(),
wins: widget.shareHandPageData!.wins,
deck: widget.shareHandPageData!.deck,
),
);
} else {
GoRouter.of(context).go('/');
}
}
if (state.status == InitialsFormStatus.blacklisted) {
focusNodes.last.requestFocus();
}
},
builder: (context, state) {
if (state.status == InitialsFormStatus.failure) {
return const Center(child: Text('Error submitting initials'));
}
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_InitialFormField(
0,
focusNode: focusNodes[0],
key: ObjectKey(focusNodes[0]),
onChanged: (index, value) {
_onInitialChanged(context, value, index);
},
onBackspace: (index) {
_onInitialChanged(context, '', index, isBackspace: true);
},
),
const SizedBox(width: IoFlipSpacing.sm),
_InitialFormField(
1,
key: ObjectKey(focusNodes[1]),
focusNode: focusNodes[1],
onChanged: (index, value) {
_onInitialChanged(context, value, index);
},
onBackspace: (index) {
_onInitialChanged(context, '', index, isBackspace: true);
},
),
const SizedBox(width: IoFlipSpacing.sm),
_InitialFormField(
2,
key: ObjectKey(focusNodes[2]),
focusNode: focusNodes[2],
onChanged: (index, value) {
_onInitialChanged(context, value, index);
},
onBackspace: (index) {
_onInitialChanged(context, '', index, isBackspace: true);
},
),
],
),
const SizedBox(height: IoFlipSpacing.sm),
if (state.status == InitialsFormStatus.blacklisted)
Text(
l10n.blacklistedErrorMessage,
style: IoFlipTextStyles.bodyLG.copyWith(
color: IoFlipColors.seedRed,
),
)
else if (state.status.isInvalid)
Text(l10n.enterInitialsError),
const SizedBox(height: IoFlipSpacing.xxlg),
RoundedButton.text(
l10n.enter,
onPressed: () {
context.read<InitialsFormBloc>().add(const InitialsSubmitted());
},
)
],
);
},
);
}
void _onInitialChanged(
BuildContext context,
String value,
int index, {
bool isBackspace = false,
}) {
var text = value;
if (text == emptyCharacter) {
text = '';
}
context
.read<InitialsFormBloc>()
.add(InitialsChanged(initial: text, index: index));
if (text.isNotEmpty) {
if (index < focusNodes.length - 1) {
focusNodes[index].unfocus();
FocusScope.of(context).requestFocus(focusNodes[index + 1]);
}
} else if (index > 0) {
if (isBackspace) {
setState(() {
focusNodes[index - 1] = FocusNode();
});
SchedulerBinding.instance.scheduleFrameCallback((timeStamp) {
FocusScope.of(context).requestFocus(focusNodes[index - 1]);
});
}
}
}
}
class _InitialFormField extends StatefulWidget {
const _InitialFormField(
this.index, {
required this.onChanged,
required this.focusNode,
required this.onBackspace,
super.key,
});
final int index;
final void Function(int, String) onChanged;
final void Function(int) onBackspace;
final FocusNode focusNode;
@override
State<_InitialFormField> createState() => _InitialFormFieldState();
}
class _InitialFormFieldState extends State<_InitialFormField> {
late final TextEditingController controller =
TextEditingController.fromValue(lastValue);
bool hasFocus = false;
TextEditingValue lastValue = const TextEditingValue(
text: emptyCharacter,
selection: TextSelection.collapsed(offset: 1),
);
@override
void initState() {
super.initState();
widget.focusNode.addListener(onFocusChanged);
}
void onFocusChanged() {
if (mounted) {
final hadFocus = hasFocus;
final willFocus = widget.focusNode.hasPrimaryFocus;
setState(() {
hasFocus = willFocus;
});
if (!hadFocus && willFocus) {
final text = controller.text;
final selection = TextSelection.collapsed(offset: text.length);
controller.selection = selection;
}
}
}
@override
void dispose() {
widget.focusNode.removeListener(onFocusChanged);
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final bloc = context.watch<InitialsFormBloc>();
final blacklisted = bloc.state.status == InitialsFormStatus.blacklisted;
final decoration = BoxDecoration(
color: widget.focusNode.hasPrimaryFocus
? IoFlipColors.seedPaletteNeutral20
: IoFlipColors.seedBlack,
border: Border.all(
color: blacklisted
? IoFlipColors.seedRed
: widget.focusNode.hasPrimaryFocus
? IoFlipColors.seedYellow
: IoFlipColors.seedPaletteNeutral40,
width: 2,
),
);
return Container(
width: 64,
height: 72,
decoration: decoration,
child: TextFormField(
key: Key('initial_form_field_${widget.index}'),
controller: controller,
autofocus: widget.index == 0,
focusNode: widget.focusNode,
showCursor: false,
textInputAction: TextInputAction.next,
inputFormatters: [
BackspaceFormatter(
onBackspace: () => widget.onBackspace(widget.index),
),
FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
UpperCaseTextFormatter(),
JustOneCharacterFormatter((value) {
widget.onChanged(widget.index, value);
}),
EmptyCharacterAtEndFormatter(),
],
style: IoFlipTextStyles.mobileH1.copyWith(
color: blacklisted ? IoFlipColors.seedRed : IoFlipColors.seedYellow,
),
textCapitalization: TextCapitalization.characters,
decoration: const InputDecoration(
border: InputBorder.none,
),
textAlign: TextAlign.center,
onChanged: (value) {
widget.onChanged(widget.index, value);
},
),
);
}
}
class UpperCaseTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
return TextEditingValue(
text: newValue.text.toUpperCase(),
selection: newValue.selection,
);
}
}
class EmptyCharacterAtEndFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
final newText = newValue.text;
var text = newText;
var selection = newValue.selection;
if (newText.isEmpty) {
text = emptyCharacter;
selection = const TextSelection.collapsed(offset: 1);
}
return TextEditingValue(
text: text,
selection: selection,
);
}
}
class BackspaceFormatter extends TextInputFormatter {
BackspaceFormatter({
required this.onBackspace,
});
final VoidCallback onBackspace;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
final oldText = oldValue.text;
final newText = newValue.text;
// Heuristic for detecting backspace press on an empty field on mobile.
if (oldText == emptyCharacter && newText.isEmpty) {
onBackspace();
}
return newValue;
}
}
class JustOneCharacterFormatter extends TextInputFormatter {
JustOneCharacterFormatter(this.onSameValue);
/// If after truncation the text is the same as the previous one,
/// this callback will force an "onChange" behavior.
final ValueChanged<String> onSameValue;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
final newText = newValue.text;
var text = newText;
var selection = newValue.selection;
if (newText.length > 1) {
text = newText.substring(newText.length - 1);
selection = const TextSelection.collapsed(offset: 1);
if (text == oldValue.text) {
onSameValue(text);
}
}
return TextEditingValue(
text: text,
selection: selection,
);
}
}
| io_flip/lib/leaderboard/initials_form/view/initials_form_view.dart/0 | {
"file_path": "io_flip/lib/leaderboard/initials_form/view/initials_form_view.dart",
"repo_id": "io_flip",
"token_count": 4573
} | 885 |
import 'package:api_client/api_client.dart';
import 'package:config_repository/config_repository.dart';
import 'package:connection_repository/connection_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart' hide Card;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:game_domain/game_domain.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/match_making/match_making.dart';
import 'package:match_maker_repository/match_maker_repository.dart';
class MatchMakingPage extends StatelessWidget {
const MatchMakingPage({
required this.createPrivateMatch,
required this.inviteCode,
required this.deck,
super.key,
});
factory MatchMakingPage.routeBuilder(_, GoRouterState state) {
final data = state.extra as MatchMakingPageData?;
return MatchMakingPage(
key: const Key('match_making'),
createPrivateMatch: data?.createPrivateMatch ?? false,
inviteCode: data?.inviteCode,
deck: data!.deck,
);
}
final bool createPrivateMatch;
final String? inviteCode;
final Deck deck;
MatchMakingEvent mapEvent() {
return inviteCode != null
? GuestPrivateMatchRequested(inviteCode!)
: createPrivateMatch
? const PrivateMatchRequested()
: const MatchRequested();
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) {
final matchMakerRepository = context.read<MatchMakerRepository>();
final configRepository = context.read<ConfigRepository>();
final connectionRepository = context.read<ConnectionRepository>();
final gameResource = context.read<GameResource>();
return MatchMakingBloc(
matchMakerRepository: matchMakerRepository,
connectionRepository: connectionRepository,
configRepository: configRepository,
gameResource: gameResource,
deckId: deck.id,
)..add(mapEvent());
},
child: MatchMakingView(
deck: deck,
tryAgainEvent: mapEvent(),
),
);
}
}
class MatchMakingPageData extends Equatable {
const MatchMakingPageData({
required this.deck,
this.createPrivateMatch,
this.inviteCode,
});
final Deck deck;
final bool? createPrivateMatch;
final String? inviteCode;
@override
List<Object?> get props => [deck, createPrivateMatch, inviteCode];
}
| io_flip/lib/match_making/views/match_making_page.dart/0 | {
"file_path": "io_flip/lib/match_making/views/match_making_page.dart",
"repo_id": "io_flip",
"token_count": 877
} | 886 |
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/draft/draft.dart';
import 'package:io_flip/game/game.dart';
import 'package:io_flip/main_menu/main_menu_screen.dart';
import 'package:io_flip/match_making/match_making.dart';
import 'package:io_flip/prompt/prompt.dart';
import 'package:io_flip/scripts/scripts.dart';
import 'package:io_flip/share/share.dart';
GoRouter createRouter({required bool isScriptsEnabled}) {
return GoRouter(
routes: [
GoRoute(
path: '/',
pageBuilder: (context, state) => NoTransitionPage(
child: MainMenuScreen.routeBuilder(context, state),
),
),
GoRoute(
path: '/draft',
pageBuilder: (context, state) => NoTransitionPage(
child: DraftPage.routeBuilder(context, state),
),
),
GoRoute(
path: '/prompt',
pageBuilder: (context, state) => NoTransitionPage(
child: PromptPage.routeBuilder(context, state),
),
),
GoRoute(
name: 'match_making',
path: '/match_making',
pageBuilder: (context, state) => NoTransitionPage(
child: MatchMakingPage.routeBuilder(context, state),
),
),
GoRoute(
name: 'game',
path: '/game',
pageBuilder: (context, state) => NoTransitionPage(
child: GamePage.routeBuilder(context, state),
),
),
GoRoute(
name: 'share_hand',
path: '/share_hand',
pageBuilder: (context, state) => NoTransitionPage(
child: ShareHandPage.routeBuilder(context, state),
),
),
if (isScriptsEnabled)
GoRoute(
name: '_super_secret_scripts_page',
path: '/_super_secret_scripts_page',
builder: ScriptsPage.routeBuilder,
),
],
observers: [RedirectToHomeObserver()],
);
}
class RedirectToHomeObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
if (previousRoute == null && route.settings.name != '/') {
WidgetsBinding.instance.addPostFrameCallback((_) {
final context = route.navigator!.context;
GoRouter.of(context).go('/');
});
}
}
}
| io_flip/lib/router/router.dart/0 | {
"file_path": "io_flip/lib/router/router.dart",
"repo_id": "io_flip",
"token_count": 1010
} | 887 |
export 'views/views.dart';
export 'widgets/widgets.dart';
| io_flip/lib/share/share.dart/0 | {
"file_path": "io_flip/lib/share/share.dart",
"repo_id": "io_flip",
"token_count": 22
} | 888 |
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
extension BuildContextMaybePop on BuildContext {
void maybePop() {
final router = GoRouter.of(this);
if (router.canPop()) {
router.pop();
}
}
}
| io_flip/lib/utils/maybe_pop_extension.dart/0 | {
"file_path": "io_flip/lib/utils/maybe_pop_extension.dart",
"repo_id": "io_flip",
"token_count": 99
} | 889 |
import 'dart:io';
import 'package:api_client/api_client.dart';
/// {@template scripts_resource}
/// Resource to access the scripts api.
/// {@endtemplate}
class ScriptsResource {
/// {@macro scripts_resource}
ScriptsResource({
required ApiClient apiClient,
}) : _apiClient = apiClient;
final ApiClient _apiClient;
/// Get /scripts/current
Future<String> getCurrentScript() async {
final response = await _apiClient.get('/game/scripts/current');
if (response.statusCode != HttpStatus.ok) {
throw ApiClientError(
'GET /scripts/current returned status ${response.statusCode} with the following response: "${response.body}"',
StackTrace.current,
);
}
return response.body;
}
/// Put /scripts/:id
Future<void> updateScript(String id, String content) async {
final response = await _apiClient.put(
'/game/scripts/$id',
body: content,
);
if (response.statusCode != HttpStatus.noContent) {
throw ApiClientError(
'PUT /scripts/$id returned status ${response.statusCode} with the following response: "${response.body}"',
StackTrace.current,
);
}
}
}
| io_flip/packages/api_client/lib/src/resources/scripts_resource.dart/0 | {
"file_path": "io_flip/packages/api_client/lib/src/resources/scripts_resource.dart",
"repo_id": "io_flip",
"token_count": 413
} | 890 |
import 'package:equatable/equatable.dart';
/// {@template user}
/// User model
/// {@endtemplate}
class User extends Equatable {
/// {@macro user}
const User({
required this.id,
});
/// The current user's id.
final String id;
/// Represents an unauthenticated user.
static const unauthenticated = User(id: '');
@override
List<Object?> get props => [id];
}
| io_flip/packages/authentication_repository/lib/src/models/user.dart/0 | {
"file_path": "io_flip/packages/authentication_repository/lib/src/models/user.dart",
"repo_id": "io_flip",
"token_count": 126
} | 891 |
/// Repository to manage the connection state.
library connection_repository;
export 'src/connection_repository.dart';
| io_flip/packages/connection_repository/lib/connection_repository.dart/0 | {
"file_path": "io_flip/packages/connection_repository/lib/connection_repository.dart",
"repo_id": "io_flip",
"token_count": 33
} | 892 |
import 'package:dashbook/dashbook.dart';
import 'package:flutter/material.dart';
import 'package:gallery/stories.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
void main() {
final dashbook = Dashbook(
title: 'I/O Flip Dashbook',
theme: IoFlipTheme.themeData.copyWith(
// Edits to make drawer and its text visible with the dark theme.
cardColor: IoFlipColors.seedBlack,
expansionTileTheme:
const ExpansionTileThemeData(textColor: IoFlipColors.seedWhite),
inputDecorationTheme: const InputDecorationTheme(
hintStyle: TextStyle(color: IoFlipColors.seedWhite),
),
),
);
addStories(dashbook);
runApp(dashbook);
}
| io_flip/packages/io_flip_ui/gallery/lib/main.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/gallery/lib/main.dart",
"repo_id": "io_flip",
"token_count": 260
} | 893 |
import 'package:flutter/material.dart';
import 'package:gallery/story_scaffold.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
class GameCardSuitsStory extends StatelessWidget {
const GameCardSuitsStory({super.key});
@override
Widget build(BuildContext context) {
return const StoryScaffold(
title: 'Game Card Suits',
body: SingleChildScrollView(
child: Center(
child: Wrap(
children: [
GameCard(
image:
'https://firebasestorage.googleapis.com/v0/b/top-dash-dev.appspot.com/o/public%2FDash_pirate_trumpets_field.png?alt=media',
name: 'Air Dash',
suitName: 'air',
description: 'The best air hockey player in all the Dashland',
power: 57,
isRare: false,
),
SizedBox(height: 16),
GameCard(
image:
'https://firebasestorage.googleapis.com/v0/b/top-dash-dev.appspot.com/o/public%2FDash_pirate_trumpets_field.png?alt=media',
name: 'Fire Dash',
suitName: 'fire',
description: 'The hottest Dash in all the Dashland',
power: 57,
isRare: false,
),
SizedBox(height: 16),
GameCard(
image:
'https://firebasestorage.googleapis.com/v0/b/top-dash-dev.appspot.com/o/public%2FDash_pirate_trumpets_field.png?alt=media',
name: 'Water Dash',
suitName: 'water',
description: 'The best swimmer in all the Dashland',
power: 57,
isRare: false,
),
SizedBox(height: 16),
GameCard(
image:
'https://firebasestorage.googleapis.com/v0/b/top-dash-dev.appspot.com/o/public%2FDash_pirate_trumpets_field.png?alt=media',
name: 'Metal Dash',
suitName: 'metal',
description: 'The most heavy metal Dash in all the Dashland',
power: 57,
isRare: false,
),
SizedBox(height: 16),
GameCard(
image:
'https://firebasestorage.googleapis.com/v0/b/top-dash-dev.appspot.com/o/public%2FDash_pirate_trumpets_field.png?alt=media',
name: 'Dash the rock',
suitName: 'earth',
description: 'The most rock and roll Dash in all the Dashland',
power: 57,
isRare: false,
),
],
),
),
),
);
}
}
| io_flip/packages/io_flip_ui/gallery/lib/widgets/game_card_suits_story.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/gallery/lib/widgets/game_card_suits_story.dart",
"repo_id": "io_flip",
"token_count": 1494
} | 894 |
export 'card_animation.dart';
export 'card_animations.dart';
export 'damages/damages.dart';
export 'game_card_rect_tween.dart';
export 'stretch_animation.dart';
export 'there_and_back_again.dart';
export 'transform_tween.dart';
| io_flip/packages/io_flip_ui/lib/src/animations/animations.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/lib/src/animations/animations.dart",
"repo_id": "io_flip",
"token_count": 86
} | 895 |
export 'breakpoints.dart';
| io_flip/packages/io_flip_ui/lib/src/layout/layout.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/lib/src/layout/layout.dart",
"repo_id": "io_flip",
"token_count": 9
} | 896 |
import 'package:flame/cache.dart';
import 'package:flame/extensions.dart';
import 'package:flame/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:provider/provider.dart';
/// {@template damage_send}
/// A widget that renders a [SpriteAnimation] for the damages sent.
/// {@endtemplate}
class DamageSend extends StatelessWidget {
/// {@macro damage_send}
const DamageSend(
this.path, {
required this.size,
required this.assetSize,
required this.badgePath,
super.key,
this.onComplete,
});
/// The size of the card.
final GameCardSize size;
/// Optional callback to be called when the animation is complete.
final VoidCallback? onComplete;
/// path of the asset containing the sprite sheet
final String path;
/// The badge path of the asset.
final String badgePath;
/// Size of the assets to use, large or small
final AssetSize assetSize;
@override
Widget build(BuildContext context) {
final images = context.read<Images>();
final height = size.height;
final width = size.width;
if (assetSize == AssetSize.large) {
return SizedBox(
height: height,
width: width,
child: RotatedBox(
quarterTurns: 2,
child: SpriteAnimationWidget.asset(
path: path,
images: images,
anchor: Anchor.center,
onComplete: onComplete,
data: SpriteAnimationData.sequenced(
amount: 18,
amountPerRow: 6,
textureSize: Vector2(568, 683),
stepTime: 0.04,
loop: false,
),
),
),
);
} else {
return _MobileAnimation(
path: badgePath,
onComplete: onComplete,
size: size,
);
}
}
}
class _MobileAnimation extends StatefulWidget {
const _MobileAnimation({
required this.path,
required this.size,
this.onComplete,
});
final String path;
final VoidCallback? onComplete;
final GameCardSize size;
@override
State<_MobileAnimation> createState() => _MobileAnimationState();
}
class _MobileAnimationState extends State<_MobileAnimation> {
var _step = 0;
late double _left = widget.size.width / 2 - 25;
late double _top = widget.size.height / 2 - 25;
@override
void initState() {
super.initState();
Future<void>.delayed(
const Duration(milliseconds: 100),
_onComplete,
);
}
void _onComplete() {
if (_step == 0) {
setState(() {
_step = 1;
_left = widget.size.width * 1.5 - 25;
_top = widget.size.height * 1.5 - 25;
});
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
AnimatedPositioned(
onEnd: widget.onComplete,
curve: Curves.bounceOut,
duration: const Duration(milliseconds: 500),
left: _left,
top: _top,
width: 50,
height: 50,
child: SvgPicture.asset(
widget.path,
),
),
],
);
}
}
| io_flip/packages/io_flip_ui/lib/src/widgets/damages/damage_send.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/damages/damage_send.dart",
"repo_id": "io_flip",
"token_count": 1333
} | 897 |
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:provider/provider.dart';
/// {@template rounded_button}
/// I/O FLIP Rounded Button.
/// {@endtemplate}
class RoundedButton extends StatefulWidget {
/// Basic [RoundedButton] with black shadow.
/// Contains an [icon] as child
RoundedButton.icon(
IconData icon, {
this.onPressed,
this.onLongPress,
super.key,
this.backgroundColor = IoFlipColors.seedBlack,
Color? foregroundColor = IoFlipColors.seedWhite,
this.borderColor = IoFlipColors.seedPaletteNeutral40,
}) : child = Icon(icon, color: foregroundColor);
/// Basic [RoundedButton] with black shadow.
/// Contains an [SvgPicture] as child
RoundedButton.svg(
String asset, {
this.onPressed,
this.onLongPress,
super.key,
this.backgroundColor = IoFlipColors.seedBlack,
Color foregroundColor = IoFlipColors.seedWhite,
this.borderColor = IoFlipColors.seedPaletteNeutral40,
}) : child = SvgPicture.asset(
asset,
colorFilter: ColorFilter.mode(foregroundColor, BlendMode.srcIn),
);
/// Basic [RoundedButton] with black shadow.
/// Contains a [text] as child
RoundedButton.text(
String text, {
this.onPressed,
this.onLongPress,
super.key,
this.backgroundColor = IoFlipColors.seedYellow,
Color? foregroundColor = IoFlipColors.seedBlack,
this.borderColor = IoFlipColors.seedBlack,
}) : child = Padding(
padding: const EdgeInsets.symmetric(
horizontal: IoFlipSpacing.sm,
),
child: Text(
text,
style: IoFlipTextStyles.buttonLG.copyWith(color: foregroundColor),
),
);
/// Basic [RoundedButton] with black shadow.
/// Contains a [image] and a [label] as children
RoundedButton.image(
Widget image, {
String? label,
this.onPressed,
this.onLongPress,
super.key,
this.backgroundColor = IoFlipColors.seedBlack,
Color? foregroundColor = IoFlipColors.seedWhite,
this.borderColor = IoFlipColors.seedPaletteNeutral40,
}) : child = Padding(
padding: const EdgeInsets.symmetric(
horizontal: IoFlipSpacing.sm,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
image,
if (label != null)
Padding(
padding: const EdgeInsets.only(left: IoFlipSpacing.md),
child: Text(
label,
style: IoFlipTextStyles.buttonLG
.copyWith(color: foregroundColor),
),
),
],
),
);
/// Button Child
final Widget child;
/// On pressed callback
final GestureTapCallback? onPressed;
/// On long pressed callback
final GestureTapCallback? onLongPress;
/// Button background color
final Color backgroundColor;
/// Button border color
final Color borderColor;
@override
State<RoundedButton> createState() => RoundedButtonState();
}
/// I/O FLIP Rounded Button state.
class RoundedButtonState extends State<RoundedButton> {
/// Whether the button is pressed or not.
bool isPressed = false;
/// Offset to move the button when pressed, and draw a shadow when not.
static const Offset offset = Offset(-2, 2);
@override
void setState(VoidCallback fn) {
if (mounted) super.setState(fn);
}
void _onPressed(BuildContext context) {
context.read<UISoundAdapter>().playButtonSound();
widget.onPressed?.call();
}
void _onLongPress(BuildContext context) {
context.read<UISoundAdapter>().playButtonSound();
widget.onLongPress?.call();
}
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: widget.onPressed == null ? null : () => _onPressed(context),
onTapDown: (_) => setState(() => isPressed = true),
onTapUp: (_) => setState(() => isPressed = false),
onTapCancel: () => setState(() => isPressed = false),
onLongPress:
widget.onLongPress == null ? null : () => _onLongPress(context),
child: Transform.translate(
offset: isPressed ? offset : Offset.zero,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40),
border: Border.all(
width: 2,
color: widget.borderColor,
),
color: widget.backgroundColor,
boxShadow: [
if (!isPressed)
const BoxShadow(
offset: offset,
spreadRadius: 1,
),
],
),
child: Padding(
padding: const EdgeInsets.all(IoFlipSpacing.md),
child: widget.child,
),
),
),
),
);
}
}
| io_flip/packages/io_flip_ui/lib/src/widgets/rounded_button.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/lib/src/widgets/rounded_button.dart",
"repo_id": "io_flip",
"token_count": 2215
} | 898 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip_ui/gen/assets.gen.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
class _FakeCustomPainter extends Fake implements CustomPainter {}
void main() {
group('CardOverlay', () {
testWidgets(
'renders win asset and green background when is win type',
(tester) async {
const width = 1200.0;
const height = 800.0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: width,
height: height,
child: CardOverlay.ofType(
CardOverlayType.win,
borderRadius: BorderRadius.circular(4),
isDimmed: false,
),
),
),
);
expect(
tester.widget(find.byType(CardOverlay)),
isA<CardOverlay>()
.having(
(o) => o.asset,
'asset',
equals(Assets.images.resultBadges.win.path),
)
.having(
(o) => o.color,
'color',
equals(IoFlipColors.seedGreen),
),
);
},
);
testWidgets(
'renders lose asset and red background when is lose type',
(tester) async {
const width = 1200.0;
const height = 800.0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: width,
height: height,
child: CardOverlay.ofType(
CardOverlayType.lose,
borderRadius: BorderRadius.circular(4),
isDimmed: false,
),
),
),
);
expect(
tester.widget(find.byType(CardOverlay)),
isA<CardOverlay>()
.having(
(o) => o.asset,
'asset',
equals(Assets.images.resultBadges.lose.path),
)
.having(
(o) => o.color,
'color',
equals(IoFlipColors.seedRed),
),
);
},
);
testWidgets(
'renders draw asset and neutral background when is draw type',
(tester) async {
const width = 1200.0;
const height = 800.0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: width,
height: height,
child: CardOverlay.ofType(
CardOverlayType.draw,
borderRadius: BorderRadius.circular(4),
isDimmed: false,
),
),
),
);
expect(
tester.widget(find.byType(CardOverlay)),
isA<CardOverlay>()
.having(
(o) => o.asset,
'asset',
equals(Assets.images.resultBadges.draw.path),
)
.having(
(o) => o.color,
'color',
equals(IoFlipColors.seedPaletteNeutral90),
),
);
},
);
});
group('OverlayTriangle', () {
test('shouldRepaint always returns false', () {
final customPaint = OverlayTriangle(IoFlipColors.seedBlue);
expect(customPaint.shouldRepaint(_FakeCustomPainter()), isFalse);
});
});
}
| io_flip/packages/io_flip_ui/test/src/widgets/card_overlay_test.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/test/src/widgets/card_overlay_test.dart",
"repo_id": "io_flip",
"token_count": 2016
} | 899 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
void main() {
group('IoFlipLogo', () {
testWidgets('renders correctly', (tester) async {
await tester.pumpWidget(IoFlipLogo());
expect(
find.byType(IoFlipLogo),
findsOneWidget,
);
});
testWidgets('white renders correctly', (tester) async {
await tester.pumpWidget(IoFlipLogo.white());
expect(
find.byType(IoFlipLogo),
findsOneWidget,
);
});
testWidgets('renders size correctly', (tester) async {
await tester.pumpWidget(IoFlipLogo(width: 200, height: 100));
expect(
tester.widget(find.byType(IoFlipLogo)),
isA<IoFlipLogo>()
.having((i) => i.width, 'width', 200)
.having((i) => i.height, 'height', 100),
);
});
});
}
| io_flip/packages/io_flip_ui/test/src/widgets/io_flip_logo_test.dart/0 | {
"file_path": "io_flip/packages/io_flip_ui/test/src/widgets/io_flip_logo_test.dart",
"repo_id": "io_flip",
"token_count": 432
} | 900 |
export 'draft_match.dart';
| io_flip/packages/match_maker_repository/lib/src/models/models.dart/0 | {
"file_path": "io_flip/packages/match_maker_repository/lib/src/models/models.dart",
"repo_id": "io_flip",
"token_count": 10
} | 901 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip/audio/songs.dart';
void main() {
group('Song', () {
test('toString returns correctly', () {
expect(
Song('SONG.mp3', 'SONG').toString(),
equals('Song<SONG.mp3>'),
);
});
});
}
| io_flip/test/audio/soungs_test.dart/0 | {
"file_path": "io_flip/test/audio/soungs_test.dart",
"repo_id": "io_flip",
"token_count": 145
} | 902 |
// ignore_for_file: prefer_const_constructors, one_member_abstracts
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart' hide Card;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/audio/audio_controller.dart';
import 'package:io_flip/game/game.dart';
import 'package:io_flip/gen/assets.gen.dart';
import 'package:io_flip/settings/settings.dart';
import 'package:io_flip/share/views/card_inspector_dialog.dart';
import 'package:io_flip/share/views/share_hand_page.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:mocktail/mocktail.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
import '../../helpers/helpers.dart';
class _MockSettingsController extends Mock implements SettingsController {}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockRouter extends Mock implements NeglectRouter {}
class _MockBuildContext extends Mock implements BuildContext {}
class _MockAudioController extends Mock implements AudioController {}
class _FakeGameState extends Fake implements GameState {}
void main() {
group('GameSummaryView', () {
late GameBloc bloc;
setUpAll(() {
registerFallbackValue(
Card(
id: '',
name: '',
description: '',
image: '',
power: 0,
rarity: false,
suit: Suit.air,
),
);
registerFallbackValue(LeaderboardEntryRequested());
registerFallbackValue(_FakeGameState());
});
setUp(() {
bloc = _MockGameBloc();
when(() => bloc.isHost).thenReturn(true);
when(() => bloc.isWinningCard(any(), isPlayer: any(named: 'isPlayer')))
.thenReturn(null);
when(() => bloc.canPlayerPlay(any())).thenReturn(true);
when(() => bloc.isPlayerAllowedToPlay).thenReturn(true);
when(() => bloc.matchCompleted(any())).thenReturn(true);
});
void mockState(GameState state) {
whenListen(
bloc,
Stream.value(state),
initialState: state,
);
}
const cards = [
Card(
id: 'player_card',
name: 'host_card',
description: '',
image: '',
rarity: true,
power: 2,
suit: Suit.air,
),
Card(
id: 'player_card_2',
name: 'host_card_2',
description: '',
image: '',
rarity: true,
power: 2,
suit: Suit.earth,
),
Card(
id: 'player_card_3',
name: 'host_card_3',
description: '',
image: '',
rarity: true,
power: 4,
suit: Suit.metal,
),
];
final baseState = MatchLoadedState(
playerScoreCard: ScoreCard(id: 'scoreCardId'),
match: Match(
id: '',
hostDeck: Deck(
id: '',
userId: '',
cards: cards,
),
guestDeck: Deck(
id: '',
userId: '',
cards: const [
Card(
id: 'opponent_card',
name: 'guest_card',
description: '',
image: '',
rarity: true,
power: 1,
suit: Suit.fire,
),
Card(
id: 'opponent_card_2',
name: 'guest_card_2',
description: '',
image: '',
rarity: false,
power: 1,
suit: Suit.air,
),
Card(
id: 'opponent_card_3',
name: 'guest_card_3',
description: '',
image: '',
rarity: false,
power: 10,
suit: Suit.water,
),
],
),
),
matchState: MatchState(
id: '',
matchId: '',
guestPlayedCards: const [],
hostPlayedCards: const [],
),
rounds: const [],
turnTimeRemaining: 10,
turnAnimationsFinished: false,
isClashScene: false,
showCardLanding: false,
);
void defaultMockState({
ScoreCard? scoreCard,
MatchResult matchResult = MatchResult.guest,
}) {
mockState(
baseState.copyWith(
playerScoreCard: scoreCard,
matchState: MatchState(
id: '',
matchId: '',
guestPlayedCards: const [
'opponent_card_2',
'opponent_card_3',
'opponent_card'
],
hostPlayedCards: const [
'player_card_2',
'player_card',
'player_card_3',
],
result: matchResult,
),
turnAnimationsFinished: true,
),
);
}
group('Gameplay', () {
testWidgets('Play lostMatch sound when the player loses the game',
(tester) async {
final audioController = _MockAudioController();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.lose);
await tester.pumpSubject(bloc, audioController: audioController);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
verify(() => audioController.playSfx(Assets.sfx.lostMatch)).called(1);
});
testWidgets('Play winMatch sound when the player wins the game',
(tester) async {
final audioController = _MockAudioController();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.win);
await tester.pumpSubject(bloc, audioController: audioController);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
verify(() => audioController.playSfx(Assets.sfx.winMatch)).called(1);
});
testWidgets('Play drawMatch sound when there is a draw', (tester) async {
final audioController = _MockAudioController();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.draw);
await tester.pumpSubject(bloc, audioController: audioController);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
verify(() => audioController.playSfx(Assets.sfx.drawMatch)).called(1);
});
testWidgets(
'renders in small phone layout',
(tester) async {
tester.setSmallestPhoneDisplaySize();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.draw);
await tester.pumpSubject(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(
find.byType(GameSummaryView),
findsOneWidget,
);
},
);
testWidgets(
'renders win splash on small phone layout',
(tester) async {
tester.setSmallestPhoneDisplaySize();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.win);
final SettingsController settingsController =
_MockSettingsController();
when(() => settingsController.muted).thenReturn(ValueNotifier(true));
await mockNetworkImages(() async {
await tester.pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryView(isWeb: true),
),
settingsController: settingsController,
);
});
expect(
find.byKey(Key('matchResultSplash_win_mobile')),
findsOneWidget,
);
},
);
testWidgets(
'renders loss splash on small phone layout',
(tester) async {
tester.setSmallestPhoneDisplaySize();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.lose);
final SettingsController settingsController =
_MockSettingsController();
when(() => settingsController.muted).thenReturn(ValueNotifier(true));
await mockNetworkImages(() async {
await tester.pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryView(isWeb: true),
),
settingsController: settingsController,
);
});
expect(
find.byKey(Key('matchResultSplash_loss_mobile')),
findsOneWidget,
);
},
);
testWidgets(
'renders draw splash on small phone layout',
(tester) async {
tester.setSmallestPhoneDisplaySize();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.draw);
final SettingsController settingsController =
_MockSettingsController();
when(() => settingsController.muted).thenReturn(ValueNotifier(true));
await mockNetworkImages(() async {
await tester.pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryView(isWeb: true),
),
settingsController: settingsController,
);
});
expect(
find.byKey(Key('matchResultSplash_draw_mobile')),
findsOneWidget,
);
},
);
testWidgets(
'renders in large phone layout',
(tester) async {
tester.setLargePhoneDisplaySize();
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.draw);
await tester.pumpSubject(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(
find.byType(GameSummaryView),
findsOneWidget,
);
},
);
testWidgets(
'renders the draw message when the players make a draw',
(tester) async {
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.draw);
await tester.pumpSubject(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(
find.text(tester.l10n.gameTiedTitle),
findsOneWidget,
);
},
);
testWidgets(
'renders the logo message only when the screen is big enough',
(tester) async {
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.lose);
await tester.pumpSubject(bloc);
expect(
find.byType(IoFlipLogo),
findsNothing,
);
tester.setLandscapeDisplaySize();
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(
find.byType(IoFlipLogo),
findsOneWidget,
);
},
);
testWidgets(
'renders the win message when the player won',
(tester) async {
mockState(
baseState.copyWith(
matchState: MatchState(
id: '',
matchId: '',
guestPlayedCards: const [
'opponent_card_2',
'opponent_card_3',
'opponent_card'
],
hostPlayedCards: const [
'player_card_2',
'player_card',
'player_card_3',
],
result: MatchResult.host,
),
turnAnimationsFinished: true,
),
);
when(bloc.gameResult).thenReturn(GameResult.win);
await tester.pumpSubject(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(
find.text(tester.l10n.gameWonTitle),
findsOneWidget,
);
},
);
testWidgets(
'renders the lose message when the player lost',
(tester) async {
defaultMockState();
when(bloc.gameResult).thenReturn(GameResult.lose);
await tester.pumpSubject(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(
find.text(tester.l10n.gameLostTitle),
findsOneWidget,
);
},
);
testWidgets(
'renders all 6 cards with overlay, 3 for player and 3 for opponent',
(tester) async {
when(
() => bloc.isWinningCard(any(), isPlayer: any(named: 'isPlayer')),
).thenReturn(CardOverlayType.win);
when(() => bloc.isHost).thenReturn(false);
defaultMockState();
await tester.pumpSubject(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(
find.byType(GameCard),
findsNWidgets(6),
);
expect(
find.byType(CardOverlay),
findsNWidgets(6),
);
},
);
testWidgets(
'Renders correct score messages',
(tester) async {
when(
() =>
bloc.isWinningCard(cards[0], isPlayer: any(named: 'isPlayer')),
).thenReturn(CardOverlayType.win);
when(
() =>
bloc.isWinningCard(cards[1], isPlayer: any(named: 'isPlayer')),
).thenReturn(CardOverlayType.lose);
when(
() =>
bloc.isWinningCard(cards[2], isPlayer: any(named: 'isPlayer')),
).thenReturn(CardOverlayType.draw);
when(() => bloc.isHost).thenReturn(true);
defaultMockState();
await tester.pumpSubject(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(find.textContaining('W'), findsOneWidget);
expect(find.textContaining('D'), findsOneWidget);
expect(find.textContaining('L'), findsOneWidget);
},
);
testWidgets(
'navigates to inspector page when card is tapped',
(tester) async {
final goRouter = MockGoRouter();
when(
() => goRouter.pushNamed(
'card_inspector',
extra: any(named: 'extra'),
),
).thenAnswer((_) async {
return;
});
when(
() => bloc.isWinningCard(any(), isPlayer: any(named: 'isPlayer')),
).thenReturn(CardOverlayType.win);
when(() => bloc.isHost).thenReturn(false);
defaultMockState();
await tester.pumpSubject(bloc, goRouter: goRouter);
await tester.tap(find.byType(GameCard).first);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(find.byType(CardInspectorDialog), findsOneWidget);
},
);
});
group('GameSummaryFooter', () {
late NeglectRouter router;
setUpAll(() {
registerFallbackValue(_MockBuildContext());
});
setUp(() {
router = _MockRouter();
when(() => router.neglect(any(), any())).thenAnswer((_) {
final callback = _.positionalArguments[1] as VoidCallback;
callback();
});
});
testWidgets(
'navigates to matchmaking when the next match button is tapped',
(tester) async {
final goRouter = MockGoRouter();
when(() => bloc.playerCards).thenReturn([]);
when(() => bloc.playerDeck)
.thenReturn(Deck(id: 'id', userId: 'userId', cards: cards));
when(() => bloc.isHost).thenReturn(false);
defaultMockState();
await tester.pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryFooter(
routerNeglectCall: router.neglect,
),
),
router: goRouter,
);
await tester.tap(find.text(tester.l10n.nextMatch));
await tester.pumpAndSettle();
verifyNever(() => bloc.sendMatchLeft());
verify(
() => goRouter.goNamed(
'match_making',
extra: any(named: 'extra'),
),
).called(1);
},
);
testWidgets(
'navigates to matchmaking when the next match button is tapped '
'if there is a draw',
(tester) async {
final goRouter = MockGoRouter();
when(() => bloc.playerCards).thenReturn([]);
when(() => bloc.playerDeck)
.thenReturn(Deck(id: 'id', userId: 'userId', cards: cards));
defaultMockState(matchResult: MatchResult.draw);
await tester.pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryFooter(
routerNeglectCall: router.neglect,
),
),
router: goRouter,
);
await tester.tap(find.text(tester.l10n.nextMatch));
await tester.pumpAndSettle();
verifyNever(() => bloc.sendMatchLeft());
verify(
() => goRouter.goNamed(
'match_making',
extra: any(named: 'extra'),
),
).called(1);
},
);
testWidgets(
'pops navigation when the submit score button is tapped and canceled',
(tester) async {
when(() => bloc.isHost).thenReturn(false);
when(() => bloc.playerCards).thenReturn([]);
defaultMockState();
await tester.pumpSubjectWithRouter(bloc);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
await tester.tap(find.text(tester.l10n.submitScore));
await tester.pumpAndSettle();
expect(find.byType(QuitGameDialog), findsOneWidget);
await tester.tap(find.text(tester.l10n.cancel));
await tester.pumpAndSettle();
expect(find.byType(QuitGameDialog), findsNothing);
},
);
testWidgets(
'pops navigation when the submit score button is tapped by winner '
'and confirmed and adds LeaderboardEntryRequested event to bloc',
(tester) async {
final goRouter = MockGoRouter();
when(() => bloc.isHost).thenReturn(false);
when(() => bloc.playerCards).thenReturn([]);
defaultMockState();
await tester.pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryFooter(
routerNeglectCall: router.neglect,
),
),
router: goRouter,
);
await tester.tap(find.text(tester.l10n.submitScore));
await tester.pumpAndSettle();
expect(find.byType(QuitGameDialog), findsOneWidget);
await tester.tap(find.text(tester.l10n.continueLabel));
await tester.pumpAndSettle();
verify(goRouter.pop).called(1);
verify(
() => bloc.add(
LeaderboardEntryRequested(
shareHandPageData: ShareHandPageData(
initials: '',
deck: baseState.match.guestDeck,
wins: 0,
),
),
),
).called(1);
},
);
testWidgets(
'adds LeaderboardEntryRequested event to bloc when submit score button '
'is tapped by loser',
(tester) async {
final goRouter = MockGoRouter();
when(() => bloc.playerCards).thenReturn([]);
defaultMockState();
await tester.pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryFooter(
routerNeglectCall: router.neglect,
),
),
router: goRouter,
);
await tester.tap(find.text(tester.l10n.submitScore));
await tester.pumpAndSettle();
verify(
() => bloc.add(
LeaderboardEntryRequested(
shareHandPageData: ShareHandPageData(
initials: '',
deck: baseState.match.hostDeck,
wins: 0,
),
),
),
).called(1);
},
);
testWidgets(
'pops snackbar when duration ends',
(tester) async {
when(() => bloc.isHost).thenReturn(false);
when(() => bloc.playerCards).thenReturn([]);
defaultMockState();
await tester.pumpSubjectWithRouter(bloc);
await tester.pumpAndSettle();
expect(find.text(tester.l10n.cardInspectorText), findsOneWidget);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
expect(find.text(tester.l10n.cardInspectorText), findsNothing);
},
);
testWidgets(
'pops snackbar when tapping',
(tester) async {
when(() => bloc.isHost).thenReturn(false);
when(() => bloc.playerCards).thenReturn([]);
defaultMockState();
await tester.pumpSubjectWithRouter(bloc);
await tester.pumpAndSettle();
expect(find.text(tester.l10n.cardInspectorText), findsOneWidget);
await tester.tapAt(Offset.zero);
await tester.pumpAndSettle();
expect(find.text(tester.l10n.cardInspectorText), findsNothing);
await tester.pumpAndSettle(GameSummaryView.cardInspectorDuration);
},
);
});
});
}
extension GameSummaryViewTest on WidgetTester {
Future<void> pumpSubject(
GameBloc bloc, {
GoRouter? goRouter,
AudioController? audioController,
}) {
final SettingsController settingsController = _MockSettingsController();
when(() => settingsController.muted).thenReturn(ValueNotifier(true));
return mockNetworkImages(() async {
await pumpApp(
BlocProvider<GameBloc>.value(
value: bloc,
child: GameView(),
),
router: goRouter,
settingsController: settingsController,
audioController: audioController,
);
state<MatchResultSplashState>(
find.byType(MatchResultSplash),
).onComplete();
await pump();
});
}
Future<void> pumpSubjectWithRouter(
GameBloc bloc, {
AudioController? audioController,
}) {
final SettingsController settingsController = _MockSettingsController();
final goRouter = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (_, __) {
return BlocProvider<GameBloc>.value(
value: bloc,
child: GameSummaryView(),
);
},
),
],
);
when(() => settingsController.muted).thenReturn(ValueNotifier(true));
return mockNetworkImages(() async {
await pumpAppWithRouter(
goRouter,
settingsController: settingsController,
audioController: audioController,
);
state<MatchResultSplashState>(
find.byType(MatchResultSplash),
).onComplete();
await pump();
});
}
}
| io_flip/test/game/views/game_summary_test.dart/0 | {
"file_path": "io_flip/test/game/views/game_summary_test.dart",
"repo_id": "io_flip",
"token_count": 11407
} | 903 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip/info/info.dart';
import '../../helpers/helpers.dart';
void main() {
group('InfoView', () {
testWidgets('can navigate to the info view', (tester) async {
await tester.pumpApp(const Scaffold(body: InfoButton()));
await tester.tap(find.byType(InfoButton));
await tester.pumpAndSettle();
expect(find.byType(InfoView), findsOneWidget);
});
});
}
| io_flip/test/info/widgets/info_button_test.dart/0 | {
"file_path": "io_flip/test/info/widgets/info_button_test.dart",
"repo_id": "io_flip",
"token_count": 191
} | 904 |
// ignore_for_file: prefer_const_constructors, one_member_abstracts
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart' hide Card;
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:game_domain/game_domain.dart';
import 'package:go_router/go_router.dart';
import 'package:io_flip/game/game.dart';
import 'package:io_flip/match_making/match_making.dart';
import 'package:io_flip/settings/settings.dart';
import 'package:io_flip/utils/utils.dart';
import 'package:io_flip_ui/io_flip_ui.dart';
import 'package:match_maker_repository/match_maker_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
import '../../helpers/helpers.dart';
class _MockMatchMakingBloc extends Mock implements MatchMakingBloc {}
class _MockSettingsController extends Mock implements SettingsController {}
class _MockRouter extends Mock implements NeglectRouter {}
class _MockBuildContext extends Mock implements BuildContext {}
const deck = Deck(
id: 'deckId',
userId: 'userId',
cards: [
Card(
id: 'a',
name: '',
description: '',
image: '',
power: 1,
rarity: false,
suit: Suit.air,
),
Card(
id: 'b',
name: '',
description: '',
image: '',
power: 1,
rarity: false,
suit: Suit.air,
),
Card(
id: 'c',
name: '',
description: '',
image: '',
power: 1,
rarity: false,
suit: Suit.air,
),
],
);
void main() {
group('MatchMakingView', () {
late MatchMakingBloc bloc;
late NeglectRouter router;
setUp(() {
bloc = _MockMatchMakingBloc();
router = _MockRouter();
when(() => router.neglect(any(), any())).thenAnswer((_) {
final callback = _.positionalArguments[1] as VoidCallback;
callback();
});
});
setUpAll(() {
registerFallbackValue(_MockBuildContext());
registerFallbackValue(
GamePageData(
isHost: true,
matchId: null,
deck: deck,
),
);
});
void mockState(MatchMakingState state) {
whenListen(
bloc,
Stream.value(state),
initialState: state,
);
}
group('initial state', () {
testWidgets('renders a fading dot loading indicator', (tester) async {
mockState(MatchMakingState.initial());
await tester.pumpSubject(bloc);
expect(find.byType(FadingDotLoader), findsOneWidget);
});
testWidgets('renders the players deck', (tester) async {
mockState(MatchMakingState.initial());
await tester.pumpSubject(bloc);
expect(find.byType(GameCard), findsNWidgets(3));
});
testWidgets('renders the title in landscape mode', (tester) async {
tester.setLandscapeDisplaySize();
mockState(MatchMakingState.initial());
await tester.pumpSubject(bloc);
expect(find.text(tester.l10n.findingMatch), findsOneWidget);
expect(find.text(tester.l10n.searchingForOpponents), findsOneWidget);
expect(
find.byKey(const Key('large_waiting_for_match_view')),
findsOneWidget,
);
});
testWidgets('renders the title in portrait mode', (tester) async {
tester.setPortraitDisplaySize();
mockState(MatchMakingState.initial());
await tester.pumpSubject(bloc);
expect(find.text(tester.l10n.findingMatch), findsOneWidget);
expect(find.text(tester.l10n.searchingForOpponents), findsOneWidget);
expect(
find.byKey(const Key('small_waiting_for_match_view')),
findsOneWidget,
);
});
testWidgets(
'renders the invite code button when one is available',
(tester) async {
mockState(
MatchMakingState(
status: MatchMakingStatus.processing,
match: DraftMatch(
id: 'matchId',
host: 'hostId',
guest: 'guestId',
inviteCode: 'hello-join-my-match',
),
isHost: true,
),
);
await tester.pumpSubject(bloc);
expect(find.text(tester.l10n.copyInviteCode), findsOneWidget);
},
);
testWidgets(
'copies invite code on invite code button tap',
(tester) async {
ClipboardData? clipboardData;
mockState(
MatchMakingState(
status: MatchMakingStatus.processing,
match: DraftMatch(
id: 'matchId',
host: 'hostId',
guest: 'guestId',
inviteCode: 'hello-join-my-match',
),
isHost: true,
),
);
await tester.pumpSubject(
bloc,
setClipboardData: (data) async => clipboardData = data,
);
await tester.tap(find.text(tester.l10n.copyInviteCode));
await tester.pump();
expect(
clipboardData?.text,
equals('hello-join-my-match'),
);
},
);
});
testWidgets(
'renders a timeout message when match making times out and navigates to '
'match making again',
(tester) async {
mockState(MatchMakingState(status: MatchMakingStatus.timeout));
await tester.pumpSubject(bloc);
expect(find.text('Match making timed out, sorry!'), findsOneWidget);
await tester.tap(find.byType(RoundedButton));
await tester.pumpAndSettle();
verify(() => bloc.add(PrivateMatchRequested())).called(1);
},
);
testWidgets(
'renders an error message when it fails adds event to the bloc on retry',
(tester) async {
mockState(MatchMakingState(status: MatchMakingStatus.failed));
await tester.pumpSubject(bloc);
expect(find.text('Match making failed, sorry!'), findsOneWidget);
await tester.tap(find.byType(RoundedButton));
await tester.pumpAndSettle();
verify(() => bloc.add(PrivateMatchRequested())).called(1);
},
);
testWidgets(
'renders transition screen when matchmaking is completed, before going '
'to the game page',
(tester) async {
mockState(
MatchMakingState(
status: MatchMakingStatus.completed,
match: DraftMatch(
id: 'matchId',
host: 'hostId',
guest: 'guestId',
),
isHost: true,
),
);
await tester.pumpSubject(
bloc,
routerNeglectCall: router.neglect,
);
expect(find.text(tester.l10n.getReadyToFlip), findsOneWidget);
// Let timers finish before ending test
await tester.pump(Duration(seconds: 3));
},
);
testWidgets(
'navigates to game page once matchmaking is completed',
(tester) async {
mockState(
MatchMakingState(
status: MatchMakingStatus.completed,
match: DraftMatch(
id: 'matchId',
host: 'hostId',
guest: 'guestId',
),
isHost: true,
),
);
final goRouter = MockGoRouter();
await tester.pumpSubject(
bloc,
goRouter: goRouter,
routerNeglectCall: router.neglect,
);
final data = GamePageData(
isHost: true,
matchId: 'matchId',
deck: deck,
);
await tester.pump(Duration(seconds: 3));
verify(
() => goRouter.goNamed(
'game',
extra: data,
),
).called(1);
},
);
});
}
extension MatchMakingViewTest on WidgetTester {
Future<void> pumpSubject(
MatchMakingBloc bloc, {
GoRouter? goRouter,
Future<void> Function(ClipboardData)? setClipboardData,
RouterNeglectCall routerNeglectCall = Router.neglect,
MatchMakingEvent? tryAgainEvent,
}) {
final SettingsController settingsController = _MockSettingsController();
when(() => settingsController.muted).thenReturn(ValueNotifier(true));
return mockNetworkImages(() {
return pumpApp(
BlocProvider<MatchMakingBloc>.value(
value: bloc,
child: MatchMakingView(
setClipboardData: setClipboardData ?? Clipboard.setData,
routerNeglectCall: routerNeglectCall,
deck: deck,
tryAgainEvent: tryAgainEvent ?? PrivateMatchRequested(),
),
),
router: goRouter,
settingsController: settingsController,
);
});
}
}
| io_flip/test/match_making/views/match_making_view_test.dart/0 | {
"file_path": "io_flip/test/match_making/views/match_making_view_test.dart",
"repo_id": "io_flip",
"token_count": 4055
} | 905 |
import 'package:flutter_test/flutter_test.dart';
import 'package:io_flip/settings/persistence/persistence.dart';
import 'package:io_flip/settings/settings.dart';
import 'package:mocktail/mocktail.dart';
class _MockSettingsPersistence extends Mock implements SettingsPersistence {}
void main() {
group('SettingsController', () {
late SettingsPersistence persistence;
late SettingsController controller;
setUp(() {
persistence = _MockSettingsPersistence();
when(persistence.getMusicOn).thenAnswer((_) async => true);
when(persistence.getSoundsOn).thenAnswer((_) async => true);
when(() => persistence.getMuted(defaultValue: any(named: 'defaultValue')))
.thenAnswer((_) async => false);
when(() => persistence.saveMuted(active: any(named: 'active')))
.thenAnswer((_) async {});
when(() => persistence.saveMusicOn(active: any(named: 'active')))
.thenAnswer((_) async {});
when(() => persistence.saveSoundsOn(active: any(named: 'active')))
.thenAnswer((_) async {});
controller = SettingsController(persistence: persistence);
});
test('loads the values from persistence', () async {
await controller.loadStateFromPersistence();
expect(controller.musicOn.value, isTrue);
expect(controller.soundsOn.value, isTrue);
expect(controller.muted.value, isFalse);
});
test('can toggle musicOn', () async {
await controller.loadStateFromPersistence();
controller.toggleMusicOn();
verify(() => persistence.saveMusicOn(active: false)).called(1);
});
test('can toggle soundsOn', () async {
await controller.loadStateFromPersistence();
controller.toggleSoundsOn();
verify(() => persistence.saveSoundsOn(active: false)).called(1);
});
test('can toggle muted', () async {
await controller.loadStateFromPersistence();
controller.toggleMuted();
verify(() => persistence.saveMuted(active: true)).called(1);
});
});
}
| io_flip/test/settings/settings_controller_test.dart/0 | {
"file_path": "io_flip/test/settings/settings_controller_test.dart",
"repo_id": "io_flip",
"token_count": 702
} | 906 |
node_modules
/build
/public/build
.env
.docusaurus
| news_toolkit/docs/.prettierignore/0 | {
"file_path": "news_toolkit/docs/.prettierignore",
"repo_id": "news_toolkit",
"token_count": 20
} | 907 |
---
slug: /
sidebar_position: 1
---
# Overview
Flutter and the [Google News Initiative](https://newsinitiative.withgoogle.com/) have co-sponsored the development of a news application template. The goal of this project is to help news publishers build mobile applications easily in order to make reliable information accessible to all.
This template aims to **significantly reduce the development time for typical news applications** by giving developers a head start on core components and features.
The Flutter News Toolkit:
- Contains common news app UI workflows and core features built with Flutter and Firebase
- Implements best practices for news apps based on [Google News Initiative research](https://newsinitiative.withgoogle.com/info/assets/static/docs/nci/nci-playbook-en.pdf)
- Allows publishers to monetize immediately with ads and subscription services
Common services such as authentication, notifications, analytics, and ads have been implemented using [Firebase](https://firebase.flutter.dev/docs/overview/) and [Google Mobile Ads](https://pub.dev/packages/google_mobile_ads). Developers are free to substitute these services and can find publicly available packages on [pub.dev](https://pub.dev).
If you're just getting started with Flutter, we recommend first developing familiarity with the framework by reviewing the [onboarding guides](https://docs.flutter.dev/get-started/install), [tutorials](https://docs.flutter.dev/reference/tutorials), and [codelabs](https://docs.flutter.dev/codelabs) before using this template.
:::note
Depending on the number of flavors you plan to create for your project, the setup time may vary. For example, you can complete end-to-end setup in less than 10 minutes for one flavor. For additional flavors, you can expect this setup time to increase. Check out flutter.dev/news for additional information and video tutorials.
:::
## Getting Started
### Prerequisites
**Dart**
In order to generate a project using the news template, you must have the [Dart SDK][dart_installation_link] installed on your machine.
:::info
Dart `">=3.0.0 <4.0.0"` is required.
:::
**Mason**
In addition, make sure you have installed the latest version of [mason_cli][mason_cli_link].
```bash
dart pub global activate mason_cli
```
:::info
[Mason][mason_link] is a command-line tool that allows you to generate a customized codebase based on your specifications.
You'll use mason to generate your customized news application from the Flutter News Template.
:::
**Dart Frog**
Lastly, make sure you have the latest version of [dart_frog_cli][dart_frog_cli_link] installed.
```bash
dart pub global activate dart_frog_cli
```
:::info
[Dart Frog][dart_frog_link] is a fast, minimalistic backend framework for Dart. It is stable as of [v0.1.0](https://github.com/VeryGoodOpenSource/dart_frog/releases/tag/dart_frog-v0.1.0).
You'll use Dart Frog as a [backend for frontends (BFF)](https://learn.microsoft.com/en-us/azure/architecture/patterns/backends-for-frontends), which allows you to connect your existing backend to the Flutter News Template frontend. Dart Frog reduces the barrier for entry for all publishers, despite any existing backend, and brings your app to market faster without required client modifications.
:::
### Generate your project
To generate your app using Mason, follow the steps below:
:::note
Projects generated from the Flutter News Template will use the latest stable version of Flutter.
:::
#### Install the Flutter News Template
Use the `mason add` command to install the [Flutter News Template](https://brickhub.dev/bricks/flutter_news_template) globally on your machine:
:::info
You only need to install the `flutter_news_template` once. You can generate multiple projects from the template after it's installed.
You can verify whether you have the `flutter_news_template` installed by using the `mason list --global` command.
:::
```bash
mason add -g flutter_news_template
```
#### Generate the app
Use the `mason make` command to generate your new app from the Flutter News Template:
```bash
mason make flutter_news_template
```
:::info
Running `mason make` will generate over 900 files that will be listed in the console.
You may need to increase your console scrollback buffer size to see all of the files listed in your console.
:::
#### Template configuration
You'll be prompted with several questions. Be prepared to provide the following information in order to generate your project:
```bash
# The name of your application as displayed on the device for end users.
? What is the user-facing application name? (Flutter News Template)
# The application identifier also know as the bundle identifier on iOS.
? What is the application bundle identifier? (com.flutter.news.template)
# A list of GitHub usernames who will be code owners on the repository.
# See https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners
? Who are the code owners? (separated by spaces) (@githubUser)
# Select all flavors that you want the generated application to include.
# We recommend having at least development and production flavors.
# For more information see https://docs.flutter.dev/deployment/flavors
? What flavors do you want your application to include?
❯ ◉ development
◯ integration
◯ staging
◉ production
```
After answering the above questions, your custom news application is generated. You are now ready to run the application locally!
#### Configure Firebase
:::caution
Before you can run your generated app, you must configure Firebase.
Please follow the instructions specified in the [Firebase setup](/project_configuration/firebase) section.
:::
#### Configure or remove ads
:::info
Your project includes sample configurations for ads so that you can run your generated app with minimal setup. You will need to follow additional steps to [configure or remove ads](/project_configuration/ads).
:::
### Run the API Server
Before running the Flutter application, run the API server locally. Change directories into the `api` directory of the newly-generated project and start the development server:
```bash
dart_frog dev
```
### Run the Flutter app
We recommend running the project directly from [VS Code](https://code.visualstudio.com) or [Android Studio](https://developer.android.com/studio).
:::info
You can also run the project directly from the command-line using the following command from the root project directory:
```bash
flutter run \
--flavor development \
--target lib/main/main_development.dart \
--dart-define FLAVOR_DEEP_LINK_DOMAIN=<YOUR-DEEP-LINK-DOMAIN> \
--dart-define FLAVOR_DEEP_LINK_PATH=<YOUR-DEEP-LINK-PATH> \
--dart-define TWITTER_API_KEY=<YOUR-TWITTER-API-KEY> \
--dart-define TWITTER_API_SECRET=<YOUR-TWITTER-API-SECRET> \
--dart-define TWITTER_REDIRECT_URI=<YOUR-TWITTER-REDIRECT-URI>
```
:::
Congrats 🎉
You've generated and run your custom news app! Head over to [project configuration](/category/project-configuration) for next steps.
[dart_frog_cli_link]: https://pub.dev/packages/dart_frog_cli
[dart_frog_link]: https://dartfrog.vgv.dev
[dart_installation_link]: https://dart.dev/get-dart
[mason_link]: https://github.com/felangel/mason
[mason_cli_link]: https://pub.dev/packages/mason_cli
## Contributions
We invite contributions from the Flutter community. Please review the [Contributing to Flutter](https://github.com/flutter/flutter/blob/master/CONTRIBUTING.md) documentation and [Contributor access](https://github.com/flutter/flutter/wiki/Contributor-access) page on our wiki to get started.
## Opening issues
Please open an issue in the main [flutter/flutter](https://github.com/flutter/flutter/issues) issue tracker if you encounter any bugs or have enhancement suggestions for this toolkit. Issues should follow the [Issue hygiene](https://github.com/flutter/flutter/wiki/Issue-hygiene) guidelines and will be [triaged](https://github.com/flutter/flutter/wiki/Triage) by the Flutter team with the appropriate labels and priority.
| news_toolkit/docs/docs/overview.md/0 | {
"file_path": "news_toolkit/docs/docs/overview.md",
"repo_id": "news_toolkit",
"token_count": 2244
} | 908 |
---
sidebar_position: 3
description: Learn how to write and run tests for your API.
---
# Testing
The Flutter News Toolkit server comes with 100% test coverage out of the box. Tests are located in a parallel file structure relative to your server source code, residing in the `api/test` directory that mirrors the `api/lib` and `api/routes` directories. Tests are automatically run on your server codebase using [Very Good Workflows](https://github.com/VeryGoodOpenSource/very_good_workflows).
Server tests are written in pure Dart and don't test any Flutter functionality. These tests evaluate the routes, middleware, and any additional classes and functions implemented in the `api/lib` folder.
Changes you make to your server such as [implementing an API data source](connecting_your_data_source) might reduce test coverage or cause existing tests to fail. We recommend maintaining 100% test coverage within your server in order to support stability and scalability.
To support 100% test coverage in your server, make sure that your tests capture any changes you make to the server behavior. For example, if you implement a new data source `your_data_source.dart`, create a corresponding `your_data_source_test.dart` file that properly tests your new data source's behavior.
:::info
for information on testing Dart Frog servers, check out the [Dart Frog testing documentation](https://dartfrog.vgv.dev/docs/basics/testing).
:::
| news_toolkit/docs/docs/server_development/testing.md/0 | {
"file_path": "news_toolkit/docs/docs/server_development/testing.md",
"repo_id": "news_toolkit",
"token_count": 344
} | 909 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.flutter.news.example">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<!--Required for Android 13 or above-->
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
</manifest>
| news_toolkit/flutter_news_example/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "news_toolkit/flutter_news_example/android/app/src/debug/AndroidManifest.xml",
"repo_id": "news_toolkit",
"token_count": 182
} | 910 |
import 'dart:convert';
import 'dart:io';
import 'package:flutter_news_example_api/client.dart';
import 'package:http/http.dart' as http;
/// {@template flutter_news_example_api_malformed_response}
/// An exception thrown when there is a problem decoded the response body.
/// {@endtemplate}
class FlutterNewsExampleApiMalformedResponse implements Exception {
/// {@macro flutter_news_example_api_malformed_response}
const FlutterNewsExampleApiMalformedResponse({required this.error});
/// The associated error.
final Object error;
}
/// {@template flutter_news_example_api_request_failure}
/// An exception thrown when an http request failure occurs.
/// {@endtemplate}
class FlutterNewsExampleApiRequestFailure implements Exception {
/// {@macro flutter_news_example_api_request_failure}
const FlutterNewsExampleApiRequestFailure({
required this.statusCode,
required this.body,
});
/// The associated http status code.
final int statusCode;
/// The associated response body.
final Map<String, dynamic> body;
}
/// Signature for the authentication token provider.
typedef TokenProvider = Future<String?> Function();
/// {@template flutter_news_example_api_client}
/// A Dart API client for the Flutter News Example API.
/// {@endtemplate}
class FlutterNewsExampleApiClient {
/// Create an instance of [FlutterNewsExampleApiClient] that integrates
/// with the remote API.
///
/// {@macro flutter_news_example_api_client}
FlutterNewsExampleApiClient({
required TokenProvider tokenProvider,
http.Client? httpClient,
}) : this._(
baseUrl: 'https://example-api.a.run.app',
httpClient: httpClient,
tokenProvider: tokenProvider,
);
/// Create an instance of [FlutterNewsExampleApiClient] that integrates
/// with a local instance of the API (http://localhost:8080).
///
/// {@macro flutter_news_example_api_client}
FlutterNewsExampleApiClient.localhost({
required TokenProvider tokenProvider,
http.Client? httpClient,
}) : this._(
baseUrl: 'http://localhost:8080',
httpClient: httpClient,
tokenProvider: tokenProvider,
);
/// {@macro flutter_news_example_api_client}
FlutterNewsExampleApiClient._({
required String baseUrl,
required TokenProvider tokenProvider,
http.Client? httpClient,
}) : _baseUrl = baseUrl,
_httpClient = httpClient ?? http.Client(),
_tokenProvider = tokenProvider;
final String _baseUrl;
final http.Client _httpClient;
final TokenProvider _tokenProvider;
/// GET /api/v1/articles/<id>
/// Requests article content metadata.
///
/// Supported parameters:
/// * [id] - Article id for which content is requested.
/// * [limit] - The number of results to return.
/// * [offset] - The (zero-based) offset of the first item
/// in the collection to return.
/// * [preview] - Whether to return a preview of the article.
Future<ArticleResponse> getArticle({
required String id,
int? limit,
int? offset,
bool preview = false,
}) async {
final uri = Uri.parse('$_baseUrl/api/v1/articles/$id').replace(
queryParameters: <String, String>{
if (limit != null) 'limit': '$limit',
if (offset != null) 'offset': '$offset',
'preview': '$preview',
},
);
final response = await _httpClient.get(
uri,
headers: await _getRequestHeaders(),
);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: body,
statusCode: response.statusCode,
);
}
return ArticleResponse.fromJson(body);
}
/// GET /api/v1/articles/<id>/related
/// Requests related articles.
///
/// Supported parameters:
/// * [id] - Article id for which related content is requested.
/// * [limit] - The number of results to return.
/// * [offset] - The (zero-based) offset of the first item
/// in the collection to return.
Future<RelatedArticlesResponse> getRelatedArticles({
required String id,
int? limit,
int? offset,
}) async {
final uri = Uri.parse('$_baseUrl/api/v1/articles/$id/related').replace(
queryParameters: <String, String>{
if (limit != null) 'limit': '$limit',
if (offset != null) 'offset': '$offset',
},
);
final response = await _httpClient.get(
uri,
headers: await _getRequestHeaders(),
);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: body,
statusCode: response.statusCode,
);
}
return RelatedArticlesResponse.fromJson(body);
}
/// GET /api/v1/feed
/// Requests news feed metadata.
///
/// Supported parameters:
/// * [category] - The desired news [Category].
/// * [limit] - The number of results to return.
/// * [offset] - The (zero-based) offset of the first item
/// in the collection to return.
Future<FeedResponse> getFeed({
Category? category,
int? limit,
int? offset,
}) async {
final uri = Uri.parse('$_baseUrl/api/v1/feed').replace(
queryParameters: <String, String>{
if (category != null) 'category': category.name,
if (limit != null) 'limit': '$limit',
if (offset != null) 'offset': '$offset',
},
);
final response = await _httpClient.get(
uri,
headers: await _getRequestHeaders(),
);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: body,
statusCode: response.statusCode,
);
}
return FeedResponse.fromJson(body);
}
/// GET /api/v1/categories
/// Requests the available news categories.
Future<CategoriesResponse> getCategories() async {
final uri = Uri.parse('$_baseUrl/api/v1/categories');
final response = await _httpClient.get(
uri,
headers: await _getRequestHeaders(),
);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: body,
statusCode: response.statusCode,
);
}
return CategoriesResponse.fromJson(body);
}
/// GET /api/v1/users/me
/// Requests the current user.
Future<CurrentUserResponse> getCurrentUser() async {
final uri = Uri.parse('$_baseUrl/api/v1/users/me');
final response = await _httpClient.get(
uri,
headers: await _getRequestHeaders(),
);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: body,
statusCode: response.statusCode,
);
}
return CurrentUserResponse.fromJson(body);
}
/// GET /api/v1/search/popular
/// Requests current, popular content.
Future<PopularSearchResponse> popularSearch() async {
final uri = Uri.parse('$_baseUrl/api/v1/search/popular');
final response = await _httpClient.get(
uri,
headers: await _getRequestHeaders(),
);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: body,
statusCode: response.statusCode,
);
}
return PopularSearchResponse.fromJson(body);
}
/// GET /api/v1/search/relevant?q=term
/// Requests relevant content based on the provided search [term].
Future<RelevantSearchResponse> relevantSearch({required String term}) async {
final uri = Uri.parse('$_baseUrl/api/v1/search/relevant').replace(
queryParameters: <String, String>{'q': term},
);
final response = await _httpClient.get(
uri,
headers: await _getRequestHeaders(),
);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: body,
statusCode: response.statusCode,
);
}
return RelevantSearchResponse.fromJson(body);
}
/// POST /api/v1/newsletter/subscription
/// Subscribes the provided [email] to the newsletter.
Future<void> subscribeToNewsletter({required String email}) async {
final uri = Uri.parse('$_baseUrl/api/v1/newsletter/subscription');
final response = await _httpClient.post(
uri,
headers: await _getRequestHeaders(),
body: json.encode(<String, String>{'email': email}),
);
if (response.statusCode != HttpStatus.created) {
throw FlutterNewsExampleApiRequestFailure(
body: const <String, dynamic>{},
statusCode: response.statusCode,
);
}
}
/// POST /api/v1/subscriptions
/// Creates a new subscription for the associated user.
Future<void> createSubscription({
required String subscriptionId,
}) async {
final uri = Uri.parse('$_baseUrl/api/v1/subscriptions').replace(
queryParameters: <String, String>{'subscriptionId': subscriptionId},
);
final response = await _httpClient.post(
uri,
headers: await _getRequestHeaders(),
);
if (response.statusCode != HttpStatus.created) {
throw FlutterNewsExampleApiRequestFailure(
body: const <String, dynamic>{},
statusCode: response.statusCode,
);
}
}
/// GET /api/v1/subscriptions
/// Requests a list of all available subscriptions.
Future<SubscriptionsResponse> getSubscriptions() async {
final uri = Uri.parse('$_baseUrl/api/v1/subscriptions');
final response = await _httpClient.get(uri);
final body = response.json();
if (response.statusCode != HttpStatus.ok) {
throw FlutterNewsExampleApiRequestFailure(
body: const <String, dynamic>{},
statusCode: response.statusCode,
);
}
return SubscriptionsResponse.fromJson(body);
}
Future<Map<String, String>> _getRequestHeaders() async {
final token = await _tokenProvider();
return <String, String>{
HttpHeaders.contentTypeHeader: ContentType.json.value,
HttpHeaders.acceptHeader: ContentType.json.value,
if (token != null) HttpHeaders.authorizationHeader: 'Bearer $token',
};
}
}
extension on http.Response {
Map<String, dynamic> json() {
try {
final decodedBody = utf8.decode(bodyBytes);
return jsonDecode(decodedBody) as Map<String, dynamic>;
} catch (error, stackTrace) {
Error.throwWithStackTrace(
FlutterNewsExampleApiMalformedResponse(error: error),
stackTrace,
);
}
}
}
| news_toolkit/flutter_news_example/api/lib/src/client/flutter_news_example_api_client.dart/0 | {
"file_path": "news_toolkit/flutter_news_example/api/lib/src/client/flutter_news_example_api_client.dart",
"repo_id": "news_toolkit",
"token_count": 3801
} | 911 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.