From d40cc5af8f60b52e5c01058aaeddbd8e13e34e1a Mon Sep 17 00:00:00 2001 From: Jenn Magder Date: Tue, 13 Apr 2021 13:52:58 -0700 Subject: [PATCH] Migrate flutter_tool plugins.dart to null safety (#80304) --- .../lib/src/commands/build_ios_framework.dart | 2 +- .../lib/src/commands/packages.dart | 1 + .../lib/src/flutter_plugins.dart | 981 +++++++++++++++++ .../lib/src/isolated/resident_web_runner.dart | 1 + .../lib/src/linux/build_linux.dart | 2 +- .../lib/src/macos/cocoapod_utils.dart | 2 +- .../lib/src/platform_plugins.dart | 12 +- packages/flutter_tools/lib/src/plugins.dart | 998 +----------------- packages/flutter_tools/lib/src/project.dart | 2 +- .../flutter_tools/lib/src/web/compile.dart | 1 + .../lib/src/windows/build_windows.dart | 2 +- .../general.shard/macos/cocoapods_test.dart | 2 +- .../general.shard/plugin_parsing_test.dart | 38 +- .../test/general.shard/plugins_test.dart | 1 + .../general.shard/windows/plugins_test.dart | 1 + 15 files changed, 1029 insertions(+), 1017 deletions(-) create mode 100644 packages/flutter_tools/lib/src/flutter_plugins.dart diff --git a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart index 9e7c635d88..86c73ceb50 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart @@ -19,9 +19,9 @@ import '../build_system/targets/common.dart'; import '../build_system/targets/icon_tree_shaker.dart'; import '../build_system/targets/ios.dart'; import '../cache.dart'; +import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../macos/cocoapod_utils.dart'; -import '../plugins.dart'; import '../project.dart'; import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult; import '../version.dart'; diff --git a/packages/flutter_tools/lib/src/commands/packages.dart b/packages/flutter_tools/lib/src/commands/packages.dart index 2af50c07ec..581a097ac0 100644 --- a/packages/flutter_tools/lib/src/commands/packages.dart +++ b/packages/flutter_tools/lib/src/commands/packages.dart @@ -13,6 +13,7 @@ import '../build_system/build_system.dart'; import '../cache.dart'; import '../dart/generate_synthetic_packages.dart'; import '../dart/pub.dart'; +import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../plugins.dart'; import '../project.dart'; diff --git a/packages/flutter_tools/lib/src/flutter_plugins.dart b/packages/flutter_tools/lib/src/flutter_plugins.dart new file mode 100644 index 0000000000..a641ab9b13 --- /dev/null +++ b/packages/flutter_tools/lib/src/flutter_plugins.dart @@ -0,0 +1,981 @@ +// 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. + +// @dart = 2.8 + +import 'package:meta/meta.dart'; +import 'package:package_config/package_config.dart'; +import 'package:path/path.dart' as path; // flutter_ignore: package_path_import +import 'package:yaml/yaml.dart'; + +import 'android/gradle.dart'; +import 'base/common.dart'; +import 'base/error_handling_io.dart'; +import 'base/file_system.dart'; +import 'base/os.dart'; +import 'base/platform.dart'; +import 'base/template.dart'; +import 'base/version.dart'; +import 'convert.dart'; +import 'dart/package_map.dart'; +import 'features.dart'; +import 'globals.dart' as globals; +import 'platform_plugins.dart'; +import 'plugins.dart'; +import 'project.dart'; + +void _renderTemplateToFile(String template, dynamic context, File file, TemplateRenderer templateRenderer) { + final String renderedTemplate = templateRenderer + .renderString(template, context, htmlEscapeValues: false); + file.createSync(recursive: true); + file.writeAsStringSync(renderedTemplate); +} + +Plugin _pluginFromPackage(String name, Uri packageRoot) { + final String pubspecPath = globals.fs.path.fromUri(packageRoot.resolve('pubspec.yaml')); + if (!globals.fs.isFileSync(pubspecPath)) { + return null; + } + dynamic pubspec; + + try { + pubspec = loadYaml(globals.fs.file(pubspecPath).readAsStringSync()); + } on YamlException catch (err) { + globals.printTrace('Failed to parse plugin manifest for $name: $err'); + // Do nothing, potentially not a plugin. + } + if (pubspec == null) { + return null; + } + final dynamic flutterConfig = pubspec['flutter']; + if (flutterConfig == null || !(flutterConfig.containsKey('plugin') as bool)) { + return null; + } + final String packageRootPath = globals.fs.path.fromUri(packageRoot); + final YamlMap dependencies = pubspec['dependencies'] as YamlMap; + globals.printTrace('Found plugin $name at $packageRootPath'); + return Plugin.fromYaml( + name, + packageRootPath, + flutterConfig['plugin'] as YamlMap, + dependencies == null ? [] : [...dependencies.keys.cast()], + fileSystem: globals.fs, + ); +} + +Future> findPlugins(FlutterProject project, { bool throwOnError = true}) async { + final List plugins = []; + final String packagesFile = globals.fs.path.join( + project.directory.path, + '.packages', + ); + final PackageConfig packageConfig = await loadPackageConfigWithLogging( + globals.fs.file(packagesFile), + logger: globals.logger, + throwOnError: throwOnError, + ); + for (final Package package in packageConfig.packages) { + final Uri packageRoot = package.packageUriRoot.resolve('..'); + final Plugin plugin = _pluginFromPackage(package.name, packageRoot); + if (plugin != null) { + plugins.add(plugin); + } + } + return plugins; +} + +// Key strings for the .flutter-plugins-dependencies file. +const String _kFlutterPluginsPluginListKey = 'plugins'; +const String _kFlutterPluginsNameKey = 'name'; +const String _kFlutterPluginsPathKey = 'path'; +const String _kFlutterPluginsDependenciesKey = 'dependencies'; + + /// Filters [plugins] to those supported by [platformKey]. + List> _filterPluginsByPlatform(Listplugins, String platformKey) { + final Iterable platformPlugins = plugins.where((Plugin p) { + return p.platforms.containsKey(platformKey); + }); + + final Set pluginNames = platformPlugins.map((Plugin plugin) => plugin.name).toSet(); + final List> list = >[]; + for (final Plugin plugin in platformPlugins) { + list.add({ + _kFlutterPluginsNameKey: plugin.name, + _kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path), + _kFlutterPluginsDependenciesKey: [...plugin.dependencies.where(pluginNames.contains)], + }); + } + return list; + } + +/// Writes the .flutter-plugins-dependencies file based on the list of plugins. +/// If there aren't any plugins, then the files aren't written to disk. The resulting +/// file looks something like this (order of keys is not guaranteed): +/// { +/// "info": "This is a generated file; do not edit or check into version control.", +/// "plugins": { +/// "ios": [ +/// { +/// "name": "test", +/// "path": "test_path", +/// "dependencies": [ +/// "plugin-a", +/// "plugin-b" +/// ] +/// } +/// ], +/// "android": [], +/// "macos": [], +/// "linux": [], +/// "windows": [], +/// "web": [] +/// }, +/// "dependencyGraph": [ +/// { +/// "name": "plugin-a", +/// "dependencies": [ +/// "plugin-b", +/// "plugin-c" +/// ] +/// }, +/// { +/// "name": "plugin-b", +/// "dependencies": [ +/// "plugin-c" +/// ] +/// }, +/// { +/// "name": "plugin-c", +/// "dependencies": [] +/// } +/// ], +/// "date_created": "1970-01-01 00:00:00.000", +/// "version": "0.0.0-unknown" +/// } +/// +/// +/// Finally, returns [true] if the plugins list has changed, otherwise returns [false]. +bool _writeFlutterPluginsList(FlutterProject project, List plugins) { + final File pluginsFile = project.flutterPluginsDependenciesFile; + if (plugins.isEmpty) { + return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); + } + + final String iosKey = project.ios.pluginConfigKey; + final String androidKey = project.android.pluginConfigKey; + final String macosKey = project.macos.pluginConfigKey; + final String linuxKey = project.linux.pluginConfigKey; + final String windowsKey = project.windows.pluginConfigKey; + final String webKey = project.web.pluginConfigKey; + + final Map pluginsMap = {}; + pluginsMap[iosKey] = _filterPluginsByPlatform(plugins, iosKey); + pluginsMap[androidKey] = _filterPluginsByPlatform(plugins, androidKey); + pluginsMap[macosKey] = _filterPluginsByPlatform(plugins, macosKey); + pluginsMap[linuxKey] = _filterPluginsByPlatform(plugins, linuxKey); + pluginsMap[windowsKey] = _filterPluginsByPlatform(plugins, windowsKey); + pluginsMap[webKey] = _filterPluginsByPlatform(plugins, webKey); + + final Map result = {}; + + result['info'] = 'This is a generated file; do not edit or check into version control.'; + result[_kFlutterPluginsPluginListKey] = pluginsMap; + /// The dependencyGraph object is kept for backwards compatibility, but + /// should be removed once migration is complete. + /// https://github.com/flutter/flutter/issues/48918 + result['dependencyGraph'] = _createPluginLegacyDependencyGraph(plugins); + result['date_created'] = globals.systemClock.now().toString(); + result['version'] = globals.flutterVersion.frameworkVersion; + + // Only notify if the plugins list has changed. [date_created] will always be different, + // [version] is not relevant for this check. + final String oldPluginsFileStringContent = _readFileContent(pluginsFile); + bool pluginsChanged = true; + if (oldPluginsFileStringContent != null) { + pluginsChanged = oldPluginsFileStringContent.contains(pluginsMap.toString()); + } + final String pluginFileContent = json.encode(result); + pluginsFile.writeAsStringSync(pluginFileContent, flush: true); + + return pluginsChanged; +} + +List _createPluginLegacyDependencyGraph(List plugins) { + final List directAppDependencies = []; + + final Set pluginNames = plugins.map((Plugin plugin) => plugin.name).toSet(); + for (final Plugin plugin in plugins) { + directAppDependencies.add({ + 'name': plugin.name, + // Extract the plugin dependencies which happen to be plugins. + 'dependencies': [...plugin.dependencies.where(pluginNames.contains)], + }); + } + return directAppDependencies; +} + +// The .flutter-plugins file will be DEPRECATED in favor of .flutter-plugins-dependencies. +// TODO(franciscojma): Remove this method once deprecated. +// https://github.com/flutter/flutter/issues/48918 +// +/// Writes the .flutter-plugins files based on the list of plugins. +/// If there aren't any plugins, then the files aren't written to disk. +/// +/// Finally, returns [true] if .flutter-plugins has changed, otherwise returns [false]. +bool _writeFlutterPluginsListLegacy(FlutterProject project, List plugins) { + final File pluginsFile = project.flutterPluginsFile; + if (plugins.isEmpty) { + return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); + } + + const String info = 'This is a generated file; do not edit or check into version control.'; + final StringBuffer flutterPluginsBuffer = StringBuffer('# $info\n'); + + for (final Plugin plugin in plugins) { + flutterPluginsBuffer.write('${plugin.name}=${globals.fsUtils.escapePath(plugin.path)}\n'); + } + final String oldPluginFileContent = _readFileContent(pluginsFile); + final String pluginFileContent = flutterPluginsBuffer.toString(); + pluginsFile.writeAsStringSync(pluginFileContent, flush: true); + + return oldPluginFileContent != _readFileContent(pluginsFile); +} + +/// Returns the contents of [File] or [null] if that file does not exist. +String _readFileContent(File file) { + return file.existsSync() ? file.readAsStringSync() : null; +} + +const String _androidPluginRegistryTemplateOldEmbedding = ''' +package io.flutter.plugins; + +import io.flutter.plugin.common.PluginRegistry; +{{#plugins}} +import {{package}}.{{class}}; +{{/plugins}} + +/** + * Generated file. Do not edit. + */ +public final class GeneratedPluginRegistrant { + public static void registerWith(PluginRegistry registry) { + if (alreadyRegisteredWith(registry)) { + return; + } +{{#plugins}} + {{class}}.registerWith(registry.registrarFor("{{package}}.{{class}}")); +{{/plugins}} + } + + private static boolean alreadyRegisteredWith(PluginRegistry registry) { + final String key = GeneratedPluginRegistrant.class.getCanonicalName(); + if (registry.hasPlugin(key)) { + return true; + } + registry.registrarFor(key); + return false; + } +} +'''; + +const String _androidPluginRegistryTemplateNewEmbedding = ''' +package io.flutter.plugins; + +import androidx.annotation.Keep; +import androidx.annotation.NonNull; +import io.flutter.Log; + +import io.flutter.embedding.engine.FlutterEngine; +{{#needsShim}} +import io.flutter.embedding.engine.plugins.shim.ShimPluginRegistry; +{{/needsShim}} + +/** + * Generated file. Do not edit. + * This file is generated by the Flutter tool based on the + * plugins that support the Android platform. + */ +@Keep +public final class GeneratedPluginRegistrant { + private static final String TAG = "GeneratedPluginRegistrant"; + public static void registerWith(@NonNull FlutterEngine flutterEngine) { +{{#needsShim}} + ShimPluginRegistry shimPluginRegistry = new ShimPluginRegistry(flutterEngine); +{{/needsShim}} +{{#plugins}} + {{#supportsEmbeddingV2}} + try { + flutterEngine.getPlugins().add(new {{package}}.{{class}}()); + } catch(Exception e) { + Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e); + } + {{/supportsEmbeddingV2}} + {{^supportsEmbeddingV2}} + {{#supportsEmbeddingV1}} + try { + {{package}}.{{class}}.registerWith(shimPluginRegistry.registrarFor("{{package}}.{{class}}")); + } catch(Exception e) { + Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e); + } + {{/supportsEmbeddingV1}} + {{/supportsEmbeddingV2}} +{{/plugins}} + } +} +'''; + +List> _extractPlatformMaps(List plugins, String type) { + final List> pluginConfigs = >[]; + for (final Plugin p in plugins) { + final PluginPlatform platformPlugin = p.platforms[type]; + if (platformPlugin != null) { + pluginConfigs.add(platformPlugin.toMap()); + } + } + return pluginConfigs; +} + +/// Returns the version of the Android embedding that the current +/// [project] is using. +AndroidEmbeddingVersion _getAndroidEmbeddingVersion(FlutterProject project) { + assert(project.android != null); + + return project.android.getEmbeddingVersion(); +} + +Future _writeAndroidPluginRegistrant(FlutterProject project, List plugins) async { + final List> androidPlugins = + _extractPlatformMaps(plugins, AndroidPlugin.kConfigKey); + + final Map templateContext = { + 'plugins': androidPlugins, + 'androidX': isAppUsingAndroidX(project.android.hostAppGradleRoot), + }; + final String javaSourcePath = globals.fs.path.join( + project.android.pluginRegistrantHost.path, + 'src', + 'main', + 'java', + ); + final String registryPath = globals.fs.path.join( + javaSourcePath, + 'io', + 'flutter', + 'plugins', + 'GeneratedPluginRegistrant.java', + ); + String templateContent; + final AndroidEmbeddingVersion appEmbeddingVersion = _getAndroidEmbeddingVersion(project); + switch (appEmbeddingVersion) { + case AndroidEmbeddingVersion.v2: + templateContext['needsShim'] = false; + // If a plugin is using an embedding version older than 2.0 and the app is using 2.0, + // then add shim for the old plugins. + for (final Map plugin in androidPlugins) { + if (plugin['supportsEmbeddingV1'] as bool && !(plugin['supportsEmbeddingV2'] as bool)) { + templateContext['needsShim'] = true; + if (project.isModule) { + globals.printStatus( + 'The plugin `${plugin['name']}` is built using an older version ' + "of the Android plugin API which assumes that it's running in a " + 'full-Flutter environment. It may have undefined behaviors when ' + 'Flutter is integrated into an existing app as a module.\n' + 'The plugin can be updated to the v2 Android Plugin APIs by ' + 'following https://flutter.dev/go/android-plugin-migration.' + ); + } + } + } + templateContent = _androidPluginRegistryTemplateNewEmbedding; + break; + case AndroidEmbeddingVersion.v1: + default: + for (final Map plugin in androidPlugins) { + if (!(plugin['supportsEmbeddingV1'] as bool) && plugin['supportsEmbeddingV2'] as bool) { + throwToolExit( + 'The plugin `${plugin['name']}` requires your app to be migrated to ' + 'the Android embedding v2. Follow the steps on https://flutter.dev/go/android-project-migration ' + 'and re-run this command.' + ); + } + } + templateContent = _androidPluginRegistryTemplateOldEmbedding; + break; + } + globals.printTrace('Generating $registryPath'); + _renderTemplateToFile( + templateContent, + templateContext, + globals.fs.file(registryPath), + globals.templateRenderer, + ); +} + +const String _objcPluginRegistryHeaderTemplate = ''' +// +// Generated file. Do not edit. +// + +#ifndef GeneratedPluginRegistrant_h +#define GeneratedPluginRegistrant_h + +#import <{{framework}}/{{framework}}.h> + +NS_ASSUME_NONNULL_BEGIN + +@interface GeneratedPluginRegistrant : NSObject ++ (void)registerWithRegistry:(NSObject*)registry; +@end + +NS_ASSUME_NONNULL_END +#endif /* GeneratedPluginRegistrant_h */ +'''; + +const String _objcPluginRegistryImplementationTemplate = ''' +// +// Generated file. Do not edit. +// + +#import "GeneratedPluginRegistrant.h" + +{{#plugins}} +#if __has_include(<{{name}}/{{class}}.h>) +#import <{{name}}/{{class}}.h> +#else +@import {{name}}; +#endif + +{{/plugins}} +@implementation GeneratedPluginRegistrant + ++ (void)registerWithRegistry:(NSObject*)registry { +{{#plugins}} + [{{prefix}}{{class}} registerWithRegistrar:[registry registrarForPlugin:@"{{prefix}}{{class}}"]]; +{{/plugins}} +} + +@end +'''; + +const String _swiftPluginRegistryTemplate = ''' +// +// Generated file. Do not edit. +// + +import {{framework}} +import Foundation + +{{#plugins}} +import {{name}} +{{/plugins}} + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + {{#plugins}} + {{class}}.register(with: registry.registrar(forPlugin: "{{class}}")) +{{/plugins}} +} +'''; + +const String _pluginRegistrantPodspecTemplate = ''' +# +# Generated file, do not edit. +# + +Pod::Spec.new do |s| + s.name = 'FlutterPluginRegistrant' + s.version = '0.0.1' + s.summary = 'Registers plugins with your flutter app' + s.description = <<-DESC +Depends on all your plugins, and provides a function to register them. + DESC + s.homepage = 'https://flutter.dev' + s.license = { :type => 'BSD' } + s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } + s.{{os}}.deployment_target = '{{deploymentTarget}}' + s.source_files = "Classes", "Classes/**/*.{h,m}" + s.source = { :path => '.' } + s.public_header_files = './Classes/**/*.h' + s.static_framework = true + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.dependency '{{framework}}' + {{#plugins}} + s.dependency '{{name}}' + {{/plugins}} +end +'''; + +const String _dartPluginRegistryTemplate = ''' +// +// Generated file. Do not edit. +// + +// ignore_for_file: lines_longer_than_80_chars + +{{#plugins}} +import 'package:{{name}}/{{file}}'; +{{/plugins}} + +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +// ignore: public_member_api_docs +void registerPlugins(Registrar registrar) { +{{#plugins}} + {{class}}.registerWith(registrar); +{{/plugins}} + registrar.registerMessageHandler(); +} +'''; + +const String _cppPluginRegistryHeaderTemplate = ''' +// +// Generated file. Do not edit. +// + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ +'''; + +const String _cppPluginRegistryImplementationTemplate = ''' +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + +{{#plugins}} +#include <{{name}}/{{filename}}.h> +{{/plugins}} + +void RegisterPlugins(flutter::PluginRegistry* registry) { +{{#plugins}} + {{class}}RegisterWithRegistrar( + registry->GetRegistrarForPlugin("{{class}}")); +{{/plugins}} +} +'''; + +const String _linuxPluginRegistryHeaderTemplate = ''' +// +// Generated file. Do not edit. +// + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ +'''; + +const String _linuxPluginRegistryImplementationTemplate = ''' +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + +{{#plugins}} +#include <{{name}}/{{filename}}.h> +{{/plugins}} + +void fl_register_plugins(FlPluginRegistry* registry) { +{{#plugins}} + g_autoptr(FlPluginRegistrar) {{name}}_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "{{class}}"); + {{filename}}_register_with_registrar({{name}}_registrar); +{{/plugins}} +} +'''; + +const String _pluginCmakefileTemplate = r''' +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +{{#plugins}} + {{name}} +{{/plugins}} +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory({{pluginsDir}}/${plugin}/{{os}} plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) +'''; + +Future _writeIOSPluginRegistrant(FlutterProject project, List plugins) async { + final List> iosPlugins = _extractPlatformMaps(plugins, IOSPlugin.kConfigKey); + final Map context = { + 'os': 'ios', + 'deploymentTarget': '9.0', + 'framework': 'Flutter', + 'plugins': iosPlugins, + }; + if (project.isModule) { + final Directory registryDirectory = project.ios.pluginRegistrantHost; + _renderTemplateToFile( + _pluginRegistrantPodspecTemplate, + context, + registryDirectory.childFile('FlutterPluginRegistrant.podspec'), + globals.templateRenderer, + ); + } + _renderTemplateToFile( + _objcPluginRegistryHeaderTemplate, + context, + project.ios.pluginRegistrantHeader, + globals.templateRenderer, + ); + _renderTemplateToFile( + _objcPluginRegistryImplementationTemplate, + context, + project.ios.pluginRegistrantImplementation, + globals.templateRenderer, + ); +} + +/// The relative path from a project's main CMake file to the plugin symlink +/// directory to use in the generated plugin CMake file. +/// +/// Because the generated file is checked in, it can't use absolute paths. It is +/// designed to be included by the main CMakeLists.txt, so it relative to +/// that file, rather than the generated file. +String _cmakeRelativePluginSymlinkDirectoryPath(CmakeBasedProject project) { + final FileSystem fileSystem = project.pluginSymlinkDirectory.fileSystem; + final String makefileDirPath = project.cmakeFile.parent.absolute.path; + // CMake always uses posix-style path separators, regardless of the platform. + final path.Context cmakePathContext = path.Context(style: path.Style.posix); + final List relativePathComponents = fileSystem.path.split(fileSystem.path.relative( + project.pluginSymlinkDirectory.absolute.path, + from: makefileDirPath, + )); + return cmakePathContext.joinAll(relativePathComponents); +} + +Future _writeLinuxPluginFiles(FlutterProject project, List plugins) async { + final ListnativePlugins = _filterNativePlugins(plugins, LinuxPlugin.kConfigKey); + final List> linuxPlugins = _extractPlatformMaps(nativePlugins, LinuxPlugin.kConfigKey); + final Map context = { + 'os': 'linux', + 'plugins': linuxPlugins, + 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.linux), + }; + await _writeLinuxPluginRegistrant(project.linux.managedDirectory, context); + await _writePluginCmakefile(project.linux.generatedPluginCmakeFile, context, globals.templateRenderer); +} + +Future _writeLinuxPluginRegistrant(Directory destination, Map templateContext) async { + _renderTemplateToFile( + _linuxPluginRegistryHeaderTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.h'), + globals.templateRenderer, + ); + _renderTemplateToFile( + _linuxPluginRegistryImplementationTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.cc'), + globals.templateRenderer, + ); +} + +Future _writePluginCmakefile(File destinationFile, Map templateContext, TemplateRenderer templateRenderer) async { + _renderTemplateToFile( + _pluginCmakefileTemplate, + templateContext, + destinationFile, + templateRenderer, + ); +} + +Future _writeMacOSPluginRegistrant(FlutterProject project, List plugins) async { + final ListnativePlugins = _filterNativePlugins(plugins, MacOSPlugin.kConfigKey); + final List> macosPlugins = _extractPlatformMaps(nativePlugins, MacOSPlugin.kConfigKey); + final Map context = { + 'os': 'macos', + 'framework': 'FlutterMacOS', + 'plugins': macosPlugins, + }; + _renderTemplateToFile( + _swiftPluginRegistryTemplate, + context, + project.macos.managedDirectory.childFile('GeneratedPluginRegistrant.swift'), + globals.templateRenderer, + ); +} + +/// Filters out Dart-only plugins, which shouldn't be added to the native generated registrants. +List _filterNativePlugins(List plugins, String platformKey) { + return plugins.where((Plugin element) { + final PluginPlatform plugin = element.platforms[platformKey]; + if (plugin == null) { + return false; + } + if (plugin is NativeOrDartPlugin) { + return (plugin as NativeOrDartPlugin).isNative(); + } + // Not all platforms have the ability to create Dart-only plugins. Therefore, any plugin that doesn't + // implement NativeOrDartPlugin is always native. + return true; + }).toList(); +} + +@visibleForTesting +Future writeWindowsPluginFiles(FlutterProject project, List plugins, TemplateRenderer templateRenderer) async { + final List nativePlugins = _filterNativePlugins(plugins, WindowsPlugin.kConfigKey); + final List> windowsPlugins = _extractPlatformMaps(nativePlugins, WindowsPlugin.kConfigKey); + final Map context = { + 'os': 'windows', + 'plugins': windowsPlugins, + 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windows), + }; + await _writeCppPluginRegistrant(project.windows.managedDirectory, context, templateRenderer); + await _writePluginCmakefile(project.windows.generatedPluginCmakeFile, context, templateRenderer); +} + +/// The tooling currently treats UWP and win32 as identical for the +/// purposes of tooling support and initial UWP bootstrap. +@visibleForTesting +Future writeWindowsUwpPluginFiles(FlutterProject project, List plugins, TemplateRenderer templateRenderer) async { + final List nativePlugins = _filterNativePlugins(plugins, WindowsPlugin.kConfigKey); + final List> windowsPlugins = _extractPlatformMaps(nativePlugins, WindowsPlugin.kConfigKey); + final Map context = { + 'os': 'windows', + 'plugins': windowsPlugins, + 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windowsUwp), + }; + await _writeCppPluginRegistrant(project.windowsUwp.managedDirectory, context, templateRenderer); + await _writePluginCmakefile(project.windowsUwp.generatedPluginCmakeFile, context, templateRenderer); +} + +Future _writeCppPluginRegistrant(Directory destination, Map templateContext, TemplateRenderer templateRenderer) async { + _renderTemplateToFile( + _cppPluginRegistryHeaderTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.h'), + templateRenderer, + ); + _renderTemplateToFile( + _cppPluginRegistryImplementationTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.cc'), + templateRenderer, + ); +} + +Future _writeWebPluginRegistrant(FlutterProject project, List plugins) async { + final List> webPlugins = _extractPlatformMaps(plugins, WebPlugin.kConfigKey); + final Map context = { + 'plugins': webPlugins, + }; + final File pluginFile = project.web.libDirectory.childFile('generated_plugin_registrant.dart'); + if (webPlugins.isEmpty) { + return ErrorHandlingFileSystem.deleteIfExists(pluginFile); + } else { + _renderTemplateToFile( + _dartPluginRegistryTemplate, + context, + pluginFile, + globals.templateRenderer, + ); + } +} + +/// For each platform that uses them, creates symlinks within the platform +/// directory to each plugin used on that platform. +/// +/// If |force| is true, the symlinks will be recreated, otherwise they will +/// be created only if missing. +/// +/// This uses [project.flutterPluginsDependenciesFile], so it should only be +/// run after refreshPluginList has been run since the last plugin change. +void createPluginSymlinks(FlutterProject project, {bool force = false, @visibleForTesting FeatureFlags featureFlagsOverride}) { + final FeatureFlags localFeatureFlags = featureFlagsOverride ?? featureFlags; + Map platformPlugins; + final String pluginFileContent = _readFileContent(project.flutterPluginsDependenciesFile); + if (pluginFileContent != null) { + final Map pluginInfo = json.decode(pluginFileContent) as Map; + platformPlugins = pluginInfo[_kFlutterPluginsPluginListKey] as Map; + } + platformPlugins ??= {}; + + if (localFeatureFlags.isWindowsEnabled && project.windows.existsSync()) { + _createPlatformPluginSymlinks( + project.windows.pluginSymlinkDirectory, + platformPlugins[project.windows.pluginConfigKey] as List, + force: force, + ); + } + if (localFeatureFlags.isLinuxEnabled && project.linux.existsSync()) { + _createPlatformPluginSymlinks( + project.linux.pluginSymlinkDirectory, + platformPlugins[project.linux.pluginConfigKey] as List, + force: force, + ); + } + if (localFeatureFlags.isWindowsUwpEnabled && project.windowsUwp.existsSync()) { + _createPlatformPluginSymlinks( + project.windowsUwp.pluginSymlinkDirectory, + platformPlugins[project.windows.pluginConfigKey] as List, + force: force, + ); + } +} + +/// Handler for symlink failures which provides specific instructions for known +/// failure cases. +@visibleForTesting +void handleSymlinkException(FileSystemException e, { + @required Platform platform, + @required OperatingSystemUtils os, +}) { + if (platform.isWindows && (e.osError?.errorCode ?? 0) == 1314) { + final String versionString = RegExp(r'[\d.]+').firstMatch(os.name)?.group(0); + final Version version = Version.parse(versionString); + // Windows 10 14972 is the oldest version that allows creating symlinks + // just by enabling developer mode; before that it requires running the + // terminal as Administrator. + // https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/ + final String instructions = (version != null && version >= Version(10, 0, 14972)) + ? 'Please enable Developer Mode in your system settings. Run\n' + ' start ms-settings:developers\n' + 'to open settings.' + : 'You must build from a terminal run as administrator.'; + throwToolExit('Building with plugins requires symlink support.\n\n' + + instructions); + } +} + +/// Creates [symlinkDirectory] containing symlinks to each plugin listed in [platformPlugins]. +/// +/// If [force] is true, the directory will be created only if missing. +void _createPlatformPluginSymlinks(Directory symlinkDirectory, List platformPlugins, {bool force = false}) { + if (force && symlinkDirectory.existsSync()) { + // Start fresh to avoid stale links. + symlinkDirectory.deleteSync(recursive: true); + } + symlinkDirectory.createSync(recursive: true); + if (platformPlugins == null) { + return; + } + for (final Map pluginInfo in platformPlugins.cast>()) { + final String name = pluginInfo[_kFlutterPluginsNameKey] as String; + final String path = pluginInfo[_kFlutterPluginsPathKey] as String; + final Link link = symlinkDirectory.childLink(name); + if (link.existsSync()) { + continue; + } + try { + link.createSync(path); + } on FileSystemException catch (e) { + handleSymlinkException(e, platform: globals.platform, os: globals.os); + rethrow; + } + } +} + +/// Rewrites the `.flutter-plugins` file of [project] based on the plugin +/// dependencies declared in `pubspec.yaml`. +/// +/// Assumes `pub get` has been executed since last change to `pubspec.yaml`. +Future refreshPluginsList( + FlutterProject project, { + bool iosPlatform = false, + bool macOSPlatform = false, +}) async { + final List plugins = await findPlugins(project); + // Sort the plugins by name to keep ordering stable in generated files. + plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); + // TODO(franciscojma): Remove once migration is complete. + // Write the legacy plugin files to avoid breaking existing apps. + final bool legacyChanged = _writeFlutterPluginsListLegacy(project, plugins); + + final bool changed = _writeFlutterPluginsList(project, plugins); + if (changed || legacyChanged) { + createPluginSymlinks(project, force: true); + if (iosPlatform) { + globals.cocoaPods.invalidatePodInstallOutput(project.ios); + } + if (macOSPlatform) { + globals.cocoaPods.invalidatePodInstallOutput(project.macos); + } + } +} + +/// Injects plugins found in `pubspec.yaml` into the platform-specific projects. +/// +/// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`. +Future injectPlugins( + FlutterProject project, { + bool androidPlatform = false, + bool iosPlatform = false, + bool linuxPlatform = false, + bool macOSPlatform = false, + bool windowsPlatform = false, + bool winUwpPlatform = false, + bool webPlatform = false, +}) async { + final List plugins = await findPlugins(project); + // Sort the plugins by name to keep ordering stable in generated files. + plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); + if (androidPlatform) { + await _writeAndroidPluginRegistrant(project, plugins); + } + if (iosPlatform) { + await _writeIOSPluginRegistrant(project, plugins); + } + if (linuxPlatform) { + await _writeLinuxPluginFiles(project, plugins); + } + if (macOSPlatform) { + await _writeMacOSPluginRegistrant(project, plugins); + } + if (windowsPlatform) { + await writeWindowsPluginFiles(project, plugins, globals.templateRenderer); + } + if (winUwpPlatform) { + await writeWindowsUwpPluginFiles(project, plugins, globals.templateRenderer); + } + if (!project.isModule) { + final List darwinProjects = [ + if (iosPlatform) project.ios, + if (macOSPlatform) project.macos, + ]; + for (final XcodeBasedProject subproject in darwinProjects) { + if (plugins.isNotEmpty) { + await globals.cocoaPods.setupPodfile(subproject); + } + /// The user may have a custom maintained Podfile that they're running `pod install` + /// on themselves. + else if (subproject.podfile.existsSync() && subproject.podfileLock.existsSync()) { + globals.cocoaPods.addPodsDependencyToFlutterXcconfig(subproject); + } + } + } + if (webPlatform) { + await _writeWebPluginRegistrant(project, plugins); + } +} + +/// Returns whether the specified Flutter [project] has any plugin dependencies. +/// +/// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`. +bool hasPlugins(FlutterProject project) { + return _readFileContent(project.flutterPluginsFile) != null; +} diff --git a/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart b/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart index 4b3b4991ea..4c3a91f004 100644 --- a/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart +++ b/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart @@ -30,6 +30,7 @@ import '../dart/language_version.dart'; import '../devfs.dart'; import '../device.dart'; import '../features.dart'; +import '../flutter_plugins.dart'; import '../platform_plugins.dart'; import '../plugins.dart'; import '../project.dart'; diff --git a/packages/flutter_tools/lib/src/linux/build_linux.dart b/packages/flutter_tools/lib/src/linux/build_linux.dart index ba7c1ab344..38c8478659 100644 --- a/packages/flutter_tools/lib/src/linux/build_linux.dart +++ b/packages/flutter_tools/lib/src/linux/build_linux.dart @@ -15,9 +15,9 @@ import '../build_info.dart'; import '../cache.dart'; import '../cmake.dart'; import '../convert.dart'; +import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../migrations/cmake_custom_command_migration.dart'; -import '../plugins.dart'; import '../project.dart'; // Matches the following error and warning patterns: diff --git a/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart b/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart index 771e9136c1..7b80544ab8 100644 --- a/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart +++ b/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart @@ -7,8 +7,8 @@ import '../base/fingerprint.dart'; import '../build_info.dart'; import '../cache.dart'; +import '../flutter_plugins.dart'; import '../globals.dart' as globals; -import '../plugins.dart'; import '../project.dart'; /// For a given build, determines whether dependencies have changed since the diff --git a/packages/flutter_tools/lib/src/platform_plugins.dart b/packages/flutter_tools/lib/src/platform_plugins.dart index c3fb431096..34e1619b39 100644 --- a/packages/flutter_tools/lib/src/platform_plugins.dart +++ b/packages/flutter_tools/lib/src/platform_plugins.dart @@ -209,14 +209,14 @@ class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin { factory MacOSPlugin.fromYaml(String name, YamlMap yaml) { assert(validate(yaml)); // Treat 'none' as not present. See https://github.com/flutter/flutter/issues/57497. - String? pluginClass = yaml[kPluginClass] as String; + String? pluginClass = yaml[kPluginClass] as String?; if (pluginClass == 'none') { pluginClass = null; } return MacOSPlugin( name: name, pluginClass: pluginClass, - dartPluginClass: yaml[kDartPluginClass] as String, + dartPluginClass: yaml[kDartPluginClass] as String?, ); } @@ -260,14 +260,14 @@ class WindowsPlugin extends PluginPlatform implements NativeOrDartPlugin{ factory WindowsPlugin.fromYaml(String name, YamlMap yaml) { assert(validate(yaml)); // Treat 'none' as not present. See https://github.com/flutter/flutter/issues/57497. - String? pluginClass = yaml[kPluginClass] as String; + String? pluginClass = yaml[kPluginClass] as String?; if (pluginClass == 'none') { pluginClass = null; } return WindowsPlugin( name: name, pluginClass: pluginClass, - dartPluginClass: yaml[kDartPluginClass] as String, + dartPluginClass: yaml[kDartPluginClass] as String?, ); } @@ -312,14 +312,14 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin { factory LinuxPlugin.fromYaml(String name, YamlMap yaml) { assert(validate(yaml)); // Treat 'none' as not present. See https://github.com/flutter/flutter/issues/57497. - String? pluginClass = yaml[kPluginClass] as String; + String? pluginClass = yaml[kPluginClass] as String?; if (pluginClass == 'none') { pluginClass = null; } return LinuxPlugin( name: name, pluginClass: pluginClass, - dartPluginClass: yaml[kDartPluginClass] as String, + dartPluginClass: yaml[kDartPluginClass] as String?, ); } diff --git a/packages/flutter_tools/lib/src/plugins.dart b/packages/flutter_tools/lib/src/plugins.dart index be8de7c477..1f8a0e52aa 100644 --- a/packages/flutter_tools/lib/src/plugins.dart +++ b/packages/flutter_tools/lib/src/plugins.dart @@ -2,41 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.8 - -import 'package:meta/meta.dart'; -import 'package:package_config/package_config.dart'; -import 'package:path/path.dart' as path; // flutter_ignore: package_path_import import 'package:yaml/yaml.dart'; -import 'android/gradle.dart'; import 'base/common.dart'; -import 'base/error_handling_io.dart'; import 'base/file_system.dart'; -import 'base/os.dart'; -import 'base/platform.dart'; -import 'base/template.dart'; -import 'base/version.dart'; -import 'convert.dart'; -import 'dart/package_map.dart'; -import 'features.dart'; -import 'globals.dart' as globals; import 'platform_plugins.dart'; -import 'project.dart'; - -void _renderTemplateToFile(String template, dynamic context, File file, TemplateRenderer templateRenderer) { - final String renderedTemplate = templateRenderer - .renderString(template, context, htmlEscapeValues: false); - file.createSync(recursive: true); - file.writeAsStringSync(renderedTemplate); -} class Plugin { Plugin({ - @required this.name, - @required this.path, - @required this.platforms, - @required this.dependencies, + required this.name, + required this.path, + required this.platforms, + required this.dependencies, }) : assert(name != null), assert(path != null), assert(platforms != null), @@ -73,9 +50,9 @@ class Plugin { factory Plugin.fromYaml( String name, String path, - YamlMap pluginYaml, + YamlMap? pluginYaml, List dependencies, { - @required FileSystem fileSystem, + required FileSystem fileSystem, }) { final List errors = validatePluginYaml(pluginYaml); if (errors.isNotEmpty) { @@ -166,7 +143,7 @@ class Plugin { ); } - final String iosPrefix = pluginYaml['iosPrefix'] as String ?? ''; + final String iosPrefix = pluginYaml['iosPrefix'] as String? ?? ''; platforms[IOSPlugin.kConfigKey] = IOSPlugin( name: name, @@ -202,7 +179,7 @@ class Plugin { return YamlMap.wrap(map); } - static List validatePluginYaml(YamlMap yaml) { + static List validatePluginYaml(YamlMap? yaml) { if (yaml == null) { return ['Invalid "plugin" specification.']; } @@ -236,22 +213,21 @@ class Plugin { const String errorMessage = 'flutter.plugin.platforms should be a map with the platform name as the key'; return [errorMessage]; } - return _validateMultiPlatformYaml(yaml['platforms'] as YamlMap); + return _validateMultiPlatformYaml(yaml['platforms'] as YamlMap?); } else { return _validateLegacyYaml(yaml); } } - static List _validateMultiPlatformYaml(YamlMap yaml) { + static List _validateMultiPlatformYaml(YamlMap? yaml) { bool isInvalid(String key, bool Function(YamlMap) validate) { - if (!yaml.containsKey(key)) { + if (!yaml!.containsKey(key)) { return false; } - final dynamic value = yaml[key]; - if (value is! YamlMap) { + final dynamic yamlValue = yaml[key]; + if (yamlValue is! YamlMap) { return true; } - final YamlMap yamlValue = value as YamlMap; if (yamlValue.containsKey('default_package')) { return false; } @@ -314,951 +290,3 @@ class Plugin { /// This is a mapping from platform config key to the plugin platform spec. final Map platforms; } - -Plugin _pluginFromPackage(String name, Uri packageRoot) { - final String pubspecPath = globals.fs.path.fromUri(packageRoot.resolve('pubspec.yaml')); - if (!globals.fs.isFileSync(pubspecPath)) { - return null; - } - dynamic pubspec; - - try { - pubspec = loadYaml(globals.fs.file(pubspecPath).readAsStringSync()); - } on YamlException catch (err) { - globals.printTrace('Failed to parse plugin manifest for $name: $err'); - // Do nothing, potentially not a plugin. - } - if (pubspec == null) { - return null; - } - final dynamic flutterConfig = pubspec['flutter']; - if (flutterConfig == null || !(flutterConfig.containsKey('plugin') as bool)) { - return null; - } - final String packageRootPath = globals.fs.path.fromUri(packageRoot); - final YamlMap dependencies = pubspec['dependencies'] as YamlMap; - globals.printTrace('Found plugin $name at $packageRootPath'); - return Plugin.fromYaml( - name, - packageRootPath, - flutterConfig['plugin'] as YamlMap, - dependencies == null ? [] : [...dependencies.keys.cast()], - fileSystem: globals.fs, - ); -} - -Future> findPlugins(FlutterProject project, { bool throwOnError = true}) async { - final List plugins = []; - final String packagesFile = globals.fs.path.join( - project.directory.path, - '.packages', - ); - final PackageConfig packageConfig = await loadPackageConfigWithLogging( - globals.fs.file(packagesFile), - logger: globals.logger, - throwOnError: throwOnError, - ); - for (final Package package in packageConfig.packages) { - final Uri packageRoot = package.packageUriRoot.resolve('..'); - final Plugin plugin = _pluginFromPackage(package.name, packageRoot); - if (plugin != null) { - plugins.add(plugin); - } - } - return plugins; -} - -// Key strings for the .flutter-plugins-dependencies file. -const String _kFlutterPluginsPluginListKey = 'plugins'; -const String _kFlutterPluginsNameKey = 'name'; -const String _kFlutterPluginsPathKey = 'path'; -const String _kFlutterPluginsDependenciesKey = 'dependencies'; - - /// Filters [plugins] to those supported by [platformKey]. - List> _filterPluginsByPlatform(Listplugins, String platformKey) { - final Iterable platformPlugins = plugins.where((Plugin p) { - return p.platforms.containsKey(platformKey); - }); - - final Set pluginNames = platformPlugins.map((Plugin plugin) => plugin.name).toSet(); - final List> list = >[]; - for (final Plugin plugin in platformPlugins) { - list.add({ - _kFlutterPluginsNameKey: plugin.name, - _kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path), - _kFlutterPluginsDependenciesKey: [...plugin.dependencies.where(pluginNames.contains)], - }); - } - return list; - } - -/// Writes the .flutter-plugins-dependencies file based on the list of plugins. -/// If there aren't any plugins, then the files aren't written to disk. The resulting -/// file looks something like this (order of keys is not guaranteed): -/// { -/// "info": "This is a generated file; do not edit or check into version control.", -/// "plugins": { -/// "ios": [ -/// { -/// "name": "test", -/// "path": "test_path", -/// "dependencies": [ -/// "plugin-a", -/// "plugin-b" -/// ] -/// } -/// ], -/// "android": [], -/// "macos": [], -/// "linux": [], -/// "windows": [], -/// "web": [] -/// }, -/// "dependencyGraph": [ -/// { -/// "name": "plugin-a", -/// "dependencies": [ -/// "plugin-b", -/// "plugin-c" -/// ] -/// }, -/// { -/// "name": "plugin-b", -/// "dependencies": [ -/// "plugin-c" -/// ] -/// }, -/// { -/// "name": "plugin-c", -/// "dependencies": [] -/// } -/// ], -/// "date_created": "1970-01-01 00:00:00.000", -/// "version": "0.0.0-unknown" -/// } -/// -/// -/// Finally, returns [true] if the plugins list has changed, otherwise returns [false]. -bool _writeFlutterPluginsList(FlutterProject project, List plugins) { - final File pluginsFile = project.flutterPluginsDependenciesFile; - if (plugins.isEmpty) { - return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); - } - - final String iosKey = project.ios.pluginConfigKey; - final String androidKey = project.android.pluginConfigKey; - final String macosKey = project.macos.pluginConfigKey; - final String linuxKey = project.linux.pluginConfigKey; - final String windowsKey = project.windows.pluginConfigKey; - final String webKey = project.web.pluginConfigKey; - - final Map pluginsMap = {}; - pluginsMap[iosKey] = _filterPluginsByPlatform(plugins, iosKey); - pluginsMap[androidKey] = _filterPluginsByPlatform(plugins, androidKey); - pluginsMap[macosKey] = _filterPluginsByPlatform(plugins, macosKey); - pluginsMap[linuxKey] = _filterPluginsByPlatform(plugins, linuxKey); - pluginsMap[windowsKey] = _filterPluginsByPlatform(plugins, windowsKey); - pluginsMap[webKey] = _filterPluginsByPlatform(plugins, webKey); - - final Map result = {}; - - result['info'] = 'This is a generated file; do not edit or check into version control.'; - result[_kFlutterPluginsPluginListKey] = pluginsMap; - /// The dependencyGraph object is kept for backwards compatibility, but - /// should be removed once migration is complete. - /// https://github.com/flutter/flutter/issues/48918 - result['dependencyGraph'] = _createPluginLegacyDependencyGraph(plugins); - result['date_created'] = globals.systemClock.now().toString(); - result['version'] = globals.flutterVersion.frameworkVersion; - - // Only notify if the plugins list has changed. [date_created] will always be different, - // [version] is not relevant for this check. - final String oldPluginsFileStringContent = _readFileContent(pluginsFile); - bool pluginsChanged = true; - if (oldPluginsFileStringContent != null) { - pluginsChanged = oldPluginsFileStringContent.contains(pluginsMap.toString()); - } - final String pluginFileContent = json.encode(result); - pluginsFile.writeAsStringSync(pluginFileContent, flush: true); - - return pluginsChanged; -} - -List _createPluginLegacyDependencyGraph(List plugins) { - final List directAppDependencies = []; - - final Set pluginNames = plugins.map((Plugin plugin) => plugin.name).toSet(); - for (final Plugin plugin in plugins) { - directAppDependencies.add({ - 'name': plugin.name, - // Extract the plugin dependencies which happen to be plugins. - 'dependencies': [...plugin.dependencies.where(pluginNames.contains)], - }); - } - return directAppDependencies; -} - -// The .flutter-plugins file will be DEPRECATED in favor of .flutter-plugins-dependencies. -// TODO(franciscojma): Remove this method once deprecated. -// https://github.com/flutter/flutter/issues/48918 -// -/// Writes the .flutter-plugins files based on the list of plugins. -/// If there aren't any plugins, then the files aren't written to disk. -/// -/// Finally, returns [true] if .flutter-plugins has changed, otherwise returns [false]. -bool _writeFlutterPluginsListLegacy(FlutterProject project, List plugins) { - final File pluginsFile = project.flutterPluginsFile; - if (plugins.isEmpty) { - return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); - } - - const String info = 'This is a generated file; do not edit or check into version control.'; - final StringBuffer flutterPluginsBuffer = StringBuffer('# $info\n'); - - for (final Plugin plugin in plugins) { - flutterPluginsBuffer.write('${plugin.name}=${globals.fsUtils.escapePath(plugin.path)}\n'); - } - final String oldPluginFileContent = _readFileContent(pluginsFile); - final String pluginFileContent = flutterPluginsBuffer.toString(); - pluginsFile.writeAsStringSync(pluginFileContent, flush: true); - - return oldPluginFileContent != _readFileContent(pluginsFile); -} - -/// Returns the contents of [File] or [null] if that file does not exist. -String _readFileContent(File file) { - return file.existsSync() ? file.readAsStringSync() : null; -} - -const String _androidPluginRegistryTemplateOldEmbedding = ''' -package io.flutter.plugins; - -import io.flutter.plugin.common.PluginRegistry; -{{#plugins}} -import {{package}}.{{class}}; -{{/plugins}} - -/** - * Generated file. Do not edit. - */ -public final class GeneratedPluginRegistrant { - public static void registerWith(PluginRegistry registry) { - if (alreadyRegisteredWith(registry)) { - return; - } -{{#plugins}} - {{class}}.registerWith(registry.registrarFor("{{package}}.{{class}}")); -{{/plugins}} - } - - private static boolean alreadyRegisteredWith(PluginRegistry registry) { - final String key = GeneratedPluginRegistrant.class.getCanonicalName(); - if (registry.hasPlugin(key)) { - return true; - } - registry.registrarFor(key); - return false; - } -} -'''; - -const String _androidPluginRegistryTemplateNewEmbedding = ''' -package io.flutter.plugins; - -import androidx.annotation.Keep; -import androidx.annotation.NonNull; -import io.flutter.Log; - -import io.flutter.embedding.engine.FlutterEngine; -{{#needsShim}} -import io.flutter.embedding.engine.plugins.shim.ShimPluginRegistry; -{{/needsShim}} - -/** - * Generated file. Do not edit. - * This file is generated by the Flutter tool based on the - * plugins that support the Android platform. - */ -@Keep -public final class GeneratedPluginRegistrant { - private static final String TAG = "GeneratedPluginRegistrant"; - public static void registerWith(@NonNull FlutterEngine flutterEngine) { -{{#needsShim}} - ShimPluginRegistry shimPluginRegistry = new ShimPluginRegistry(flutterEngine); -{{/needsShim}} -{{#plugins}} - {{#supportsEmbeddingV2}} - try { - flutterEngine.getPlugins().add(new {{package}}.{{class}}()); - } catch(Exception e) { - Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e); - } - {{/supportsEmbeddingV2}} - {{^supportsEmbeddingV2}} - {{#supportsEmbeddingV1}} - try { - {{package}}.{{class}}.registerWith(shimPluginRegistry.registrarFor("{{package}}.{{class}}")); - } catch(Exception e) { - Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e); - } - {{/supportsEmbeddingV1}} - {{/supportsEmbeddingV2}} -{{/plugins}} - } -} -'''; - -List> _extractPlatformMaps(List plugins, String type) { - final List> pluginConfigs = >[]; - for (final Plugin p in plugins) { - final PluginPlatform platformPlugin = p.platforms[type]; - if (platformPlugin != null) { - pluginConfigs.add(platformPlugin.toMap()); - } - } - return pluginConfigs; -} - -/// Returns the version of the Android embedding that the current -/// [project] is using. -AndroidEmbeddingVersion _getAndroidEmbeddingVersion(FlutterProject project) { - assert(project.android != null); - - return project.android.getEmbeddingVersion(); -} - -Future _writeAndroidPluginRegistrant(FlutterProject project, List plugins) async { - final List> androidPlugins = - _extractPlatformMaps(plugins, AndroidPlugin.kConfigKey); - - final Map templateContext = { - 'plugins': androidPlugins, - 'androidX': isAppUsingAndroidX(project.android.hostAppGradleRoot), - }; - final String javaSourcePath = globals.fs.path.join( - project.android.pluginRegistrantHost.path, - 'src', - 'main', - 'java', - ); - final String registryPath = globals.fs.path.join( - javaSourcePath, - 'io', - 'flutter', - 'plugins', - 'GeneratedPluginRegistrant.java', - ); - String templateContent; - final AndroidEmbeddingVersion appEmbeddingVersion = _getAndroidEmbeddingVersion(project); - switch (appEmbeddingVersion) { - case AndroidEmbeddingVersion.v2: - templateContext['needsShim'] = false; - // If a plugin is using an embedding version older than 2.0 and the app is using 2.0, - // then add shim for the old plugins. - for (final Map plugin in androidPlugins) { - if (plugin['supportsEmbeddingV1'] as bool && !(plugin['supportsEmbeddingV2'] as bool)) { - templateContext['needsShim'] = true; - if (project.isModule) { - globals.printStatus( - 'The plugin `${plugin['name']}` is built using an older version ' - "of the Android plugin API which assumes that it's running in a " - 'full-Flutter environment. It may have undefined behaviors when ' - 'Flutter is integrated into an existing app as a module.\n' - 'The plugin can be updated to the v2 Android Plugin APIs by ' - 'following https://flutter.dev/go/android-plugin-migration.' - ); - } - } - } - templateContent = _androidPluginRegistryTemplateNewEmbedding; - break; - case AndroidEmbeddingVersion.v1: - default: - for (final Map plugin in androidPlugins) { - if (!(plugin['supportsEmbeddingV1'] as bool) && plugin['supportsEmbeddingV2'] as bool) { - throwToolExit( - 'The plugin `${plugin['name']}` requires your app to be migrated to ' - 'the Android embedding v2. Follow the steps on https://flutter.dev/go/android-project-migration ' - 'and re-run this command.' - ); - } - } - templateContent = _androidPluginRegistryTemplateOldEmbedding; - break; - } - globals.printTrace('Generating $registryPath'); - _renderTemplateToFile( - templateContent, - templateContext, - globals.fs.file(registryPath), - globals.templateRenderer, - ); -} - -const String _objcPluginRegistryHeaderTemplate = ''' -// -// Generated file. Do not edit. -// - -#ifndef GeneratedPluginRegistrant_h -#define GeneratedPluginRegistrant_h - -#import <{{framework}}/{{framework}}.h> - -NS_ASSUME_NONNULL_BEGIN - -@interface GeneratedPluginRegistrant : NSObject -+ (void)registerWithRegistry:(NSObject*)registry; -@end - -NS_ASSUME_NONNULL_END -#endif /* GeneratedPluginRegistrant_h */ -'''; - -const String _objcPluginRegistryImplementationTemplate = ''' -// -// Generated file. Do not edit. -// - -#import "GeneratedPluginRegistrant.h" - -{{#plugins}} -#if __has_include(<{{name}}/{{class}}.h>) -#import <{{name}}/{{class}}.h> -#else -@import {{name}}; -#endif - -{{/plugins}} -@implementation GeneratedPluginRegistrant - -+ (void)registerWithRegistry:(NSObject*)registry { -{{#plugins}} - [{{prefix}}{{class}} registerWithRegistrar:[registry registrarForPlugin:@"{{prefix}}{{class}}"]]; -{{/plugins}} -} - -@end -'''; - -const String _swiftPluginRegistryTemplate = ''' -// -// Generated file. Do not edit. -// - -import {{framework}} -import Foundation - -{{#plugins}} -import {{name}} -{{/plugins}} - -func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { - {{#plugins}} - {{class}}.register(with: registry.registrar(forPlugin: "{{class}}")) -{{/plugins}} -} -'''; - -const String _pluginRegistrantPodspecTemplate = ''' -# -# Generated file, do not edit. -# - -Pod::Spec.new do |s| - s.name = 'FlutterPluginRegistrant' - s.version = '0.0.1' - s.summary = 'Registers plugins with your flutter app' - s.description = <<-DESC -Depends on all your plugins, and provides a function to register them. - DESC - s.homepage = 'https://flutter.dev' - s.license = { :type => 'BSD' } - s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } - s.{{os}}.deployment_target = '{{deploymentTarget}}' - s.source_files = "Classes", "Classes/**/*.{h,m}" - s.source = { :path => '.' } - s.public_header_files = './Classes/**/*.h' - s.static_framework = true - s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } - s.dependency '{{framework}}' - {{#plugins}} - s.dependency '{{name}}' - {{/plugins}} -end -'''; - -const String _dartPluginRegistryTemplate = ''' -// -// Generated file. Do not edit. -// - -// ignore_for_file: lines_longer_than_80_chars - -{{#plugins}} -import 'package:{{name}}/{{file}}'; -{{/plugins}} - -import 'package:flutter_web_plugins/flutter_web_plugins.dart'; - -// ignore: public_member_api_docs -void registerPlugins(Registrar registrar) { -{{#plugins}} - {{class}}.registerWith(registrar); -{{/plugins}} - registrar.registerMessageHandler(); -} -'''; - -const String _cppPluginRegistryHeaderTemplate = ''' -// -// Generated file. Do not edit. -// - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void RegisterPlugins(flutter::PluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ -'''; - -const String _cppPluginRegistryImplementationTemplate = ''' -// -// Generated file. Do not edit. -// - -#include "generated_plugin_registrant.h" - -{{#plugins}} -#include <{{name}}/{{filename}}.h> -{{/plugins}} - -void RegisterPlugins(flutter::PluginRegistry* registry) { -{{#plugins}} - {{class}}RegisterWithRegistrar( - registry->GetRegistrarForPlugin("{{class}}")); -{{/plugins}} -} -'''; - -const String _linuxPluginRegistryHeaderTemplate = ''' -// -// Generated file. Do not edit. -// - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ -'''; - -const String _linuxPluginRegistryImplementationTemplate = ''' -// -// Generated file. Do not edit. -// - -#include "generated_plugin_registrant.h" - -{{#plugins}} -#include <{{name}}/{{filename}}.h> -{{/plugins}} - -void fl_register_plugins(FlPluginRegistry* registry) { -{{#plugins}} - g_autoptr(FlPluginRegistrar) {{name}}_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "{{class}}"); - {{filename}}_register_with_registrar({{name}}_registrar); -{{/plugins}} -} -'''; - -const String _pluginCmakefileTemplate = r''' -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST -{{#plugins}} - {{name}} -{{/plugins}} -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory({{pluginsDir}}/${plugin}/{{os}} plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) -'''; - -Future _writeIOSPluginRegistrant(FlutterProject project, List plugins) async { - final List> iosPlugins = _extractPlatformMaps(plugins, IOSPlugin.kConfigKey); - final Map context = { - 'os': 'ios', - 'deploymentTarget': '9.0', - 'framework': 'Flutter', - 'plugins': iosPlugins, - }; - if (project.isModule) { - final Directory registryDirectory = project.ios.pluginRegistrantHost; - _renderTemplateToFile( - _pluginRegistrantPodspecTemplate, - context, - registryDirectory.childFile('FlutterPluginRegistrant.podspec'), - globals.templateRenderer, - ); - } - _renderTemplateToFile( - _objcPluginRegistryHeaderTemplate, - context, - project.ios.pluginRegistrantHeader, - globals.templateRenderer, - ); - _renderTemplateToFile( - _objcPluginRegistryImplementationTemplate, - context, - project.ios.pluginRegistrantImplementation, - globals.templateRenderer, - ); -} - -/// The relative path from a project's main CMake file to the plugin symlink -/// directory to use in the generated plugin CMake file. -/// -/// Because the generated file is checked in, it can't use absolute paths. It is -/// designed to be included by the main CMakeLists.txt, so it relative to -/// that file, rather than the generated file. -String _cmakeRelativePluginSymlinkDirectoryPath(CmakeBasedProject project) { - final FileSystem fileSystem = project.pluginSymlinkDirectory.fileSystem; - final String makefileDirPath = project.cmakeFile.parent.absolute.path; - // CMake always uses posix-style path separators, regardless of the platform. - final path.Context cmakePathContext = path.Context(style: path.Style.posix); - final List relativePathComponents = fileSystem.path.split(fileSystem.path.relative( - project.pluginSymlinkDirectory.absolute.path, - from: makefileDirPath, - )); - return cmakePathContext.joinAll(relativePathComponents); -} - -Future _writeLinuxPluginFiles(FlutterProject project, List plugins) async { - final ListnativePlugins = _filterNativePlugins(plugins, LinuxPlugin.kConfigKey); - final List> linuxPlugins = _extractPlatformMaps(nativePlugins, LinuxPlugin.kConfigKey); - final Map context = { - 'os': 'linux', - 'plugins': linuxPlugins, - 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.linux), - }; - await _writeLinuxPluginRegistrant(project.linux.managedDirectory, context); - await _writePluginCmakefile(project.linux.generatedPluginCmakeFile, context, globals.templateRenderer); -} - -Future _writeLinuxPluginRegistrant(Directory destination, Map templateContext) async { - _renderTemplateToFile( - _linuxPluginRegistryHeaderTemplate, - templateContext, - destination.childFile('generated_plugin_registrant.h'), - globals.templateRenderer, - ); - _renderTemplateToFile( - _linuxPluginRegistryImplementationTemplate, - templateContext, - destination.childFile('generated_plugin_registrant.cc'), - globals.templateRenderer, - ); -} - -Future _writePluginCmakefile(File destinationFile, Map templateContext, TemplateRenderer templateRenderer) async { - _renderTemplateToFile( - _pluginCmakefileTemplate, - templateContext, - destinationFile, - templateRenderer, - ); -} - -Future _writeMacOSPluginRegistrant(FlutterProject project, List plugins) async { - final ListnativePlugins = _filterNativePlugins(plugins, MacOSPlugin.kConfigKey); - final List> macosPlugins = _extractPlatformMaps(nativePlugins, MacOSPlugin.kConfigKey); - final Map context = { - 'os': 'macos', - 'framework': 'FlutterMacOS', - 'plugins': macosPlugins, - }; - _renderTemplateToFile( - _swiftPluginRegistryTemplate, - context, - project.macos.managedDirectory.childFile('GeneratedPluginRegistrant.swift'), - globals.templateRenderer, - ); -} - -/// Filters out Dart-only plugins, which shouldn't be added to the native generated registrants. -List _filterNativePlugins(List plugins, String platformKey) { - return plugins.where((Plugin element) { - final PluginPlatform plugin = element.platforms[platformKey]; - if (plugin == null) { - return false; - } - if (plugin is NativeOrDartPlugin) { - return (plugin as NativeOrDartPlugin).isNative(); - } - // Not all platforms have the ability to create Dart-only plugins. Therefore, any plugin that doesn't - // implement NativeOrDartPlugin is always native. - return true; - }).toList(); -} - -@visibleForTesting -Future writeWindowsPluginFiles(FlutterProject project, List plugins, TemplateRenderer templateRenderer) async { - final List nativePlugins = _filterNativePlugins(plugins, WindowsPlugin.kConfigKey); - final List> windowsPlugins = _extractPlatformMaps(nativePlugins, WindowsPlugin.kConfigKey); - final Map context = { - 'os': 'windows', - 'plugins': windowsPlugins, - 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windows), - }; - await _writeCppPluginRegistrant(project.windows.managedDirectory, context, templateRenderer); - await _writePluginCmakefile(project.windows.generatedPluginCmakeFile, context, templateRenderer); -} - -/// The tooling currently treats UWP and win32 as identical for the -/// purposes of tooling support and initial UWP bootstrap. -@visibleForTesting -Future writeWindowsUwpPluginFiles(FlutterProject project, List plugins, TemplateRenderer templateRenderer) async { - final List nativePlugins = _filterNativePlugins(plugins, WindowsPlugin.kConfigKey); - final List> windowsPlugins = _extractPlatformMaps(nativePlugins, WindowsPlugin.kConfigKey); - final Map context = { - 'os': 'windows', - 'plugins': windowsPlugins, - 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windowsUwp), - }; - await _writeCppPluginRegistrant(project.windowsUwp.managedDirectory, context, templateRenderer); - await _writePluginCmakefile(project.windowsUwp.generatedPluginCmakeFile, context, templateRenderer); -} - -Future _writeCppPluginRegistrant(Directory destination, Map templateContext, TemplateRenderer templateRenderer) async { - _renderTemplateToFile( - _cppPluginRegistryHeaderTemplate, - templateContext, - destination.childFile('generated_plugin_registrant.h'), - templateRenderer, - ); - _renderTemplateToFile( - _cppPluginRegistryImplementationTemplate, - templateContext, - destination.childFile('generated_plugin_registrant.cc'), - templateRenderer, - ); -} - -Future _writeWebPluginRegistrant(FlutterProject project, List plugins) async { - final List> webPlugins = _extractPlatformMaps(plugins, WebPlugin.kConfigKey); - final Map context = { - 'plugins': webPlugins, - }; - final File pluginFile = project.web.libDirectory.childFile('generated_plugin_registrant.dart'); - if (webPlugins.isEmpty) { - return ErrorHandlingFileSystem.deleteIfExists(pluginFile); - } else { - _renderTemplateToFile( - _dartPluginRegistryTemplate, - context, - pluginFile, - globals.templateRenderer, - ); - } -} - -/// For each platform that uses them, creates symlinks within the platform -/// directory to each plugin used on that platform. -/// -/// If |force| is true, the symlinks will be recreated, otherwise they will -/// be created only if missing. -/// -/// This uses [project.flutterPluginsDependenciesFile], so it should only be -/// run after refreshPluginList has been run since the last plugin change. -void createPluginSymlinks(FlutterProject project, {bool force = false, @visibleForTesting FeatureFlags featureFlagsOverride}) { - final FeatureFlags localFeatureFlags = featureFlagsOverride ?? featureFlags; - Map platformPlugins; - final String pluginFileContent = _readFileContent(project.flutterPluginsDependenciesFile); - if (pluginFileContent != null) { - final Map pluginInfo = json.decode(pluginFileContent) as Map; - platformPlugins = pluginInfo[_kFlutterPluginsPluginListKey] as Map; - } - platformPlugins ??= {}; - - if (localFeatureFlags.isWindowsEnabled && project.windows.existsSync()) { - _createPlatformPluginSymlinks( - project.windows.pluginSymlinkDirectory, - platformPlugins[project.windows.pluginConfigKey] as List, - force: force, - ); - } - if (localFeatureFlags.isLinuxEnabled && project.linux.existsSync()) { - _createPlatformPluginSymlinks( - project.linux.pluginSymlinkDirectory, - platformPlugins[project.linux.pluginConfigKey] as List, - force: force, - ); - } - if (localFeatureFlags.isWindowsUwpEnabled && project.windowsUwp.existsSync()) { - _createPlatformPluginSymlinks( - project.windowsUwp.pluginSymlinkDirectory, - platformPlugins[project.windows.pluginConfigKey] as List, - force: force, - ); - } -} - -/// Handler for symlink failures which provides specific instructions for known -/// failure cases. -@visibleForTesting -void handleSymlinkException(FileSystemException e, { - @required Platform platform, - @required OperatingSystemUtils os, -}) { - if (platform.isWindows && (e.osError?.errorCode ?? 0) == 1314) { - final String versionString = RegExp(r'[\d.]+').firstMatch(os.name)?.group(0); - final Version version = Version.parse(versionString); - // Windows 10 14972 is the oldest version that allows creating symlinks - // just by enabling developer mode; before that it requires running the - // terminal as Administrator. - // https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/ - final String instructions = (version != null && version >= Version(10, 0, 14972)) - ? 'Please enable Developer Mode in your system settings. Run\n' - ' start ms-settings:developers\n' - 'to open settings.' - : 'You must build from a terminal run as administrator.'; - throwToolExit('Building with plugins requires symlink support.\n\n' + - instructions); - } -} - -/// Creates [symlinkDirectory] containing symlinks to each plugin listed in [platformPlugins]. -/// -/// If [force] is true, the directory will be created only if missing. -void _createPlatformPluginSymlinks(Directory symlinkDirectory, List platformPlugins, {bool force = false}) { - if (force && symlinkDirectory.existsSync()) { - // Start fresh to avoid stale links. - symlinkDirectory.deleteSync(recursive: true); - } - symlinkDirectory.createSync(recursive: true); - if (platformPlugins == null) { - return; - } - for (final Map pluginInfo in platformPlugins.cast>()) { - final String name = pluginInfo[_kFlutterPluginsNameKey] as String; - final String path = pluginInfo[_kFlutterPluginsPathKey] as String; - final Link link = symlinkDirectory.childLink(name); - if (link.existsSync()) { - continue; - } - try { - link.createSync(path); - } on FileSystemException catch (e) { - handleSymlinkException(e, platform: globals.platform, os: globals.os); - rethrow; - } - } -} - -/// Rewrites the `.flutter-plugins` file of [project] based on the plugin -/// dependencies declared in `pubspec.yaml`. -/// -/// Assumes `pub get` has been executed since last change to `pubspec.yaml`. -Future refreshPluginsList( - FlutterProject project, { - bool iosPlatform = false, - bool macOSPlatform = false, -}) async { - final List plugins = await findPlugins(project); - // Sort the plugins by name to keep ordering stable in generated files. - plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); - // TODO(franciscojma): Remove once migration is complete. - // Write the legacy plugin files to avoid breaking existing apps. - final bool legacyChanged = _writeFlutterPluginsListLegacy(project, plugins); - - final bool changed = _writeFlutterPluginsList(project, plugins); - if (changed || legacyChanged) { - createPluginSymlinks(project, force: true); - if (iosPlatform) { - globals.cocoaPods.invalidatePodInstallOutput(project.ios); - } - if (macOSPlatform) { - globals.cocoaPods.invalidatePodInstallOutput(project.macos); - } - } -} - -/// Injects plugins found in `pubspec.yaml` into the platform-specific projects. -/// -/// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`. -Future injectPlugins( - FlutterProject project, { - bool androidPlatform = false, - bool iosPlatform = false, - bool linuxPlatform = false, - bool macOSPlatform = false, - bool windowsPlatform = false, - bool winUwpPlatform = false, - bool webPlatform = false, -}) async { - final List plugins = await findPlugins(project); - // Sort the plugins by name to keep ordering stable in generated files. - plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); - if (androidPlatform) { - await _writeAndroidPluginRegistrant(project, plugins); - } - if (iosPlatform) { - await _writeIOSPluginRegistrant(project, plugins); - } - if (linuxPlatform) { - await _writeLinuxPluginFiles(project, plugins); - } - if (macOSPlatform) { - await _writeMacOSPluginRegistrant(project, plugins); - } - if (windowsPlatform) { - await writeWindowsPluginFiles(project, plugins, globals.templateRenderer); - } - if (winUwpPlatform) { - await writeWindowsUwpPluginFiles(project, plugins, globals.templateRenderer); - } - if (!project.isModule) { - final List darwinProjects = [ - if (iosPlatform) project.ios, - if (macOSPlatform) project.macos, - ]; - for (final XcodeBasedProject subproject in darwinProjects) { - if (plugins.isNotEmpty) { - await globals.cocoaPods.setupPodfile(subproject); - } - /// The user may have a custom maintained Podfile that they're running `pod install` - /// on themselves. - else if (subproject.podfile.existsSync() && subproject.podfileLock.existsSync()) { - globals.cocoaPods.addPodsDependencyToFlutterXcconfig(subproject); - } - } - } - if (webPlatform) { - await _writeWebPluginRegistrant(project, plugins); - } -} - -/// Returns whether the specified Flutter [project] has any plugin dependencies. -/// -/// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`. -bool hasPlugins(FlutterProject project) { - return _readFileContent(project.flutterPluginsFile) != null; -} diff --git a/packages/flutter_tools/lib/src/project.dart b/packages/flutter_tools/lib/src/project.dart index a89afa0c0c..568e57d80d 100644 --- a/packages/flutter_tools/lib/src/project.dart +++ b/packages/flutter_tools/lib/src/project.dart @@ -18,12 +18,12 @@ import 'build_info.dart'; import 'bundle.dart' as bundle; import 'features.dart'; import 'flutter_manifest.dart'; +import 'flutter_plugins.dart'; import 'globals.dart' as globals; import 'ios/plist_parser.dart'; import 'ios/xcodeproj.dart' as xcode; import 'ios/xcodeproj.dart'; import 'platform_plugins.dart'; -import 'plugins.dart'; import 'template.dart'; class FlutterProjectFactory { diff --git a/packages/flutter_tools/lib/src/web/compile.dart b/packages/flutter_tools/lib/src/web/compile.dart index 5b406a8052..27e9ed1e3a 100644 --- a/packages/flutter_tools/lib/src/web/compile.dart +++ b/packages/flutter_tools/lib/src/web/compile.dart @@ -14,6 +14,7 @@ import '../build_system/targets/common.dart'; import '../build_system/targets/icon_tree_shaker.dart'; import '../build_system/targets/web.dart'; import '../cache.dart'; +import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../platform_plugins.dart'; import '../plugins.dart'; diff --git a/packages/flutter_tools/lib/src/windows/build_windows.dart b/packages/flutter_tools/lib/src/windows/build_windows.dart index dec2ad23f0..a4e31d26dc 100644 --- a/packages/flutter_tools/lib/src/windows/build_windows.dart +++ b/packages/flutter_tools/lib/src/windows/build_windows.dart @@ -15,9 +15,9 @@ import '../build_info.dart'; import '../cache.dart'; import '../cmake.dart'; import '../convert.dart'; +import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../migrations/cmake_custom_command_migration.dart'; -import '../plugins.dart'; import '../project.dart'; import 'visual_studio.dart'; diff --git a/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart b/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart index 23e02de231..67294d47d6 100644 --- a/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart +++ b/packages/flutter_tools/test/general.shard/macos/cocoapods_test.dart @@ -11,9 +11,9 @@ 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 'package:flutter_tools/src/flutter_plugins.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/macos/cocoapods.dart'; -import 'package:flutter_tools/src/plugins.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:test/fake.dart'; diff --git a/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart b/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart index 3158bc431f..da59b44c97 100644 --- a/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart +++ b/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.8 - import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/platform_plugins.dart'; @@ -31,8 +29,8 @@ void main() { fileSystem: fileSystem, ); - final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey] as AndroidPlugin; - final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey] as IOSPlugin; + final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin; + final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin; final String androidPluginClass = androidPlugin.pluginClass; final String iosPluginClass = iosPlugin.pluginClass; @@ -69,12 +67,12 @@ void main() { 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; + 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; final String androidPluginClass = androidPlugin.pluginClass; final String iosPluginClass = iosPlugin.pluginClass; @@ -118,12 +116,12 @@ void main() { 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; + 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; final String androidPluginClass = androidPlugin.pluginClass; final String iosPluginClass = iosPlugin.pluginClass; @@ -159,9 +157,9 @@ void main() { fileSystem: fileSystem, ); - 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; + 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(linuxPlugin.pluginClass, isNull); expect(macOSPlugin.pluginClass, isNull); @@ -224,7 +222,7 @@ void main() { testWithoutContext('Plugin parsing throws a fatal error on an empty plugin', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); - final YamlMap pluginYaml = loadYaml('') as YamlMap; + final YamlMap? pluginYaml = loadYaml('') as YamlMap?; expect( () => Plugin.fromYaml( diff --git a/packages/flutter_tools/test/general.shard/plugins_test.dart b/packages/flutter_tools/test/general.shard/plugins_test.dart index 5d479d3ea8..c73df53c6c 100644 --- a/packages/flutter_tools/test/general.shard/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -14,6 +14,7 @@ import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/time.dart'; import 'package:flutter_tools/src/base/utils.dart'; import 'package:flutter_tools/src/features.dart'; +import 'package:flutter_tools/src/flutter_plugins.dart'; import 'package:flutter_tools/src/globals_null_migrated.dart' as globals; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/plugins.dart'; diff --git a/packages/flutter_tools/test/general.shard/windows/plugins_test.dart b/packages/flutter_tools/test/general.shard/windows/plugins_test.dart index 895f65e1b1..6a00c3adb7 100644 --- a/packages/flutter_tools/test/general.shard/windows/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/windows/plugins_test.dart @@ -8,6 +8,7 @@ import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/base/template.dart'; +import 'package:flutter_tools/src/flutter_plugins.dart'; import 'package:flutter_tools/src/isolated/mustache_template.dart'; import 'package:flutter_tools/src/platform_plugins.dart'; import 'package:flutter_tools/src/plugins.dart';