flutter_plugins.dart 53.7 KB
Newer Older
1 2 3 4 5 6 7
// 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:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:path/path.dart' as path; // flutter_ignore: package_path_import
8
import 'package:pub_semver/pub_semver.dart' as semver;
9 10 11 12 13 14 15 16 17 18
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';
19
import 'cache.dart';
20
import 'convert.dart';
21
import 'dart/language_version.dart';
22 23
import 'dart/package_map.dart';
import 'features.dart';
24
import 'globals.dart' as globals;
25 26 27 28
import 'platform_plugins.dart';
import 'plugins.dart';
import 'project.dart';

29 30 31 32 33 34
Future<void> _renderTemplateToFile(
  String template,
  Object? context,
  File file,
  TemplateRenderer templateRenderer,
) async {
35
  final String renderedTemplate = templateRenderer
36
    .renderString(template, context);
37 38
  await file.create(recursive: true);
  await file.writeAsString(renderedTemplate);
39 40
}

41 42
Future<Plugin?> _pluginFromPackage(String name, Uri packageRoot, Set<String> appDependencies,
    {FileSystem? fileSystem}) async {
43
  final FileSystem fs = fileSystem ?? globals.fs;
44 45
  final File pubspecFile = fs.file(packageRoot.resolve('pubspec.yaml'));
  if (!pubspecFile.existsSync()) {
46 47
    return null;
  }
48
  Object? pubspec;
49 50

  try {
51
    pubspec = loadYaml(await pubspecFile.readAsString());
52 53 54 55
  } on YamlException catch (err) {
    globals.printTrace('Failed to parse plugin manifest for $name: $err');
    // Do nothing, potentially not a plugin.
  }
56
  if (pubspec == null || pubspec is! YamlMap) {
57 58
    return null;
  }
59 60
  final Object? flutterConfig = pubspec['flutter'];
  if (flutterConfig == null || flutterConfig is! YamlMap || !flutterConfig.containsKey('plugin')) {
61 62
    return null;
  }
63 64 65
  final String? flutterConstraintText = (pubspec['environment'] as YamlMap?)?['flutter'] as String?;
  final semver.VersionConstraint? flutterConstraint = flutterConstraintText == null ?
    null : semver.VersionConstraint.parse(flutterConstraintText);
66
  final String packageRootPath = fs.path.fromUri(packageRoot);
67
  final YamlMap? dependencies = pubspec['dependencies'] as YamlMap?;
68 69 70 71
  globals.printTrace('Found plugin $name at $packageRootPath');
  return Plugin.fromYaml(
    name,
    packageRootPath,
72
    flutterConfig['plugin'] as YamlMap?,
73
    flutterConstraint,
74
    dependencies == null ? <String>[] : <String>[...dependencies.keys.cast<String>()],
75 76
    fileSystem: fs,
    appDependencies: appDependencies,
77 78 79 80 81
  );
}

Future<List<Plugin>> findPlugins(FlutterProject project, { bool throwOnError = true}) async {
  final List<Plugin> plugins = <Plugin>[];
82 83
  final FileSystem fs = project.directory.fileSystem;
  final String packagesFile = fs.path.join(
84 85 86 87
    project.directory.path,
    '.packages',
  );
  final PackageConfig packageConfig = await loadPackageConfigWithLogging(
88
    fs.file(packagesFile),
89 90 91 92 93
    logger: globals.logger,
    throwOnError: throwOnError,
  );
  for (final Package package in packageConfig.packages) {
    final Uri packageRoot = package.packageUriRoot.resolve('..');
94
    final Plugin? plugin = await _pluginFromPackage(
95 96 97 98 99
      package.name,
      packageRoot,
      project.manifest.dependencies,
      fileSystem: fs
    );
100 101 102 103 104 105 106 107 108 109 110 111
    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';
112
const String _kFlutterPluginsHasNativeBuildKey = 'native_build';
113
const String _kFlutterPluginsSharedDarwinSource = 'shared_darwin_source';
114

115
/// Filters [plugins] to those supported by [platformKey].
116
List<Map<String, Object>> _filterPluginsByPlatform(List<Plugin> plugins, String platformKey) {
117 118 119 120 121
  final Iterable<Plugin> platformPlugins = plugins.where((Plugin p) {
    return p.platforms.containsKey(platformKey);
  });

  final Set<String> pluginNames = platformPlugins.map((Plugin plugin) => plugin.name).toSet();
122
  final List<Map<String, Object>> pluginInfo = <Map<String, Object>>[];
123
  for (final Plugin plugin in platformPlugins) {
124 125
    // This is guaranteed to be non-null due to the `where` filter above.
    final PluginPlatform platformPlugin = plugin.platforms[platformKey]!;
126
    pluginInfo.add(<String, Object>{
127 128
      _kFlutterPluginsNameKey: plugin.name,
      _kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path),
129 130
      if (platformPlugin is DarwinPlugin && (platformPlugin as DarwinPlugin).sharedDarwinSource)
        _kFlutterPluginsSharedDarwinSource: (platformPlugin as DarwinPlugin).sharedDarwinSource,
131
      if (platformPlugin is NativeOrDartPlugin)
Daco Harkes's avatar
Daco Harkes committed
132
        _kFlutterPluginsHasNativeBuildKey: (platformPlugin as NativeOrDartPlugin).hasMethodChannel() || (platformPlugin as NativeOrDartPlugin).hasFfi(),
133
      _kFlutterPluginsDependenciesKey: <String>[...plugin.dependencies.where(pluginNames.contains)],
134 135
    });
  }
136 137
  return pluginInfo;
}
138 139 140 141 142 143 144 145 146 147 148 149 150 151

/// 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"
152 153
///         ],
///         "native_build": true
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
///       }
///     ],
///     "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<Plugin> 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;

200
  final Map<String, Object> pluginsMap = <String, Object>{};
201 202 203 204 205 206 207
  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);

208
  final Map<String, Object> result = <String, Object> {};
209 210 211 212 213 214 215 216 217 218 219 220

  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.
221
  final String? oldPluginsFileStringContent = _readFileContent(pluginsFile);
222 223 224 225 226 227 228 229 230 231
  bool pluginsChanged = true;
  if (oldPluginsFileStringContent != null) {
    pluginsChanged = oldPluginsFileStringContent.contains(pluginsMap.toString());
  }
  final String pluginFileContent = json.encode(result);
  pluginsFile.writeAsStringSync(pluginFileContent, flush: true);

  return pluginsChanged;
}

232 233
List<Object?> _createPluginLegacyDependencyGraph(List<Plugin> plugins) {
  final List<Object> directAppDependencies = <Object>[];
234 235 236

  final Set<String> pluginNames = plugins.map((Plugin plugin) => plugin.name).toSet();
  for (final Plugin plugin in plugins) {
237
    directAppDependencies.add(<String, Object>{
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
      'name': plugin.name,
      // Extract the plugin dependencies which happen to be plugins.
      'dependencies': <String>[...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<Plugin> 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');
  }
266
  final String? oldPluginFileContent = _readFileContent(pluginsFile);
267 268 269 270 271 272 273
  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.
274
String? _readFileContent(File file) {
275 276 277 278 279 280 281
  return file.existsSync() ? file.readAsStringSync() : null;
}

const String _androidPluginRegistryTemplateOldEmbedding = '''
package io.flutter.plugins;

import io.flutter.plugin.common.PluginRegistry;
Daco Harkes's avatar
Daco Harkes committed
282
{{#methodChannelPlugins}}
283
import {{package}}.{{class}};
Daco Harkes's avatar
Daco Harkes committed
284
{{/methodChannelPlugins}}
285 286 287 288 289 290 291 292 293

/**
 * Generated file. Do not edit.
 */
public final class GeneratedPluginRegistrant {
  public static void registerWith(PluginRegistry registry) {
    if (alreadyRegisteredWith(registry)) {
      return;
    }
Daco Harkes's avatar
Daco Harkes committed
294
{{#methodChannelPlugins}}
295
    {{class}}.registerWith(registry.registrarFor("{{package}}.{{class}}"));
Daco Harkes's avatar
Daco Harkes committed
296
{{/methodChannelPlugins}}
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  }

  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}}
Daco Harkes's avatar
Daco Harkes committed
334
{{#methodChannelPlugins}}
335 336 337
  {{#supportsEmbeddingV2}}
    try {
      flutterEngine.getPlugins().add(new {{package}}.{{class}}());
338
    } catch (Exception e) {
339 340 341 342 343 344 345
      Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e);
    }
  {{/supportsEmbeddingV2}}
  {{^supportsEmbeddingV2}}
    {{#supportsEmbeddingV1}}
    try {
      {{package}}.{{class}}.registerWith(shimPluginRegistry.registrarFor("{{package}}.{{class}}"));
346
    } catch (Exception e) {
347 348 349 350
      Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e);
    }
    {{/supportsEmbeddingV1}}
  {{/supportsEmbeddingV2}}
Daco Harkes's avatar
Daco Harkes committed
351
{{/methodChannelPlugins}}
352 353 354 355
  }
}
''';

356 357
List<Map<String, Object?>> _extractPlatformMaps(List<Plugin> plugins, String type) {
  final List<Map<String, Object?>> pluginConfigs = <Map<String, Object?>>[];
358
  for (final Plugin p in plugins) {
359
    final PluginPlatform? platformPlugin = p.platforms[type];
360 361 362 363 364 365 366 367 368 369 370 371 372 373
    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) {
  return project.android.getEmbeddingVersion();
}

Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
Daco Harkes's avatar
Daco Harkes committed
374 375
  final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, AndroidPlugin.kConfigKey);
  final List<Map<String, Object?>> androidPlugins = _extractPlatformMaps(methodChannelPlugins, AndroidPlugin.kConfigKey);
376

377
  final Map<String, Object> templateContext = <String, Object>{
Daco Harkes's avatar
Daco Harkes committed
378
    'methodChannelPlugins': androidPlugins,
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    '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.
401 402

      final List<String> pluginsUsingV1 = <String>[];
403
      for (final Map<String, Object?> plugin in androidPlugins) {
404 405
        final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false;
        final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false;
406
        if (supportsEmbeddingV1 && !supportsEmbeddingV2) {
407
          templateContext['needsShim'] = true;
408 409
          if (plugin['name'] != null) {
            pluginsUsingV1.add(plugin['name']! as String);
410 411 412
          }
        }
      }
413
      if (pluginsUsingV1.length > 1) {
414
        globals.printWarning(
415 416 417 418 419 420 421 422
          'The plugins `${pluginsUsingV1.join(', ')}` use a deprecated version of the Android embedding.\n'
          'To avoid unexpected runtime failures, or future build failures, try to see if these plugins '
          'support the Android V2 embedding. Otherwise, consider removing them since a future release '
          'of Flutter will remove these deprecated APIs.\n'
          'If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: '
          'https://flutter.dev/go/android-plugin-migration.'
        );
      } else if (pluginsUsingV1.isNotEmpty) {
423
        globals.printWarning(
424 425 426 427 428 429 430 431
          'The plugin `${pluginsUsingV1.first}` uses a deprecated version of the Android embedding.\n'
          'To avoid unexpected runtime failures, or future build failures, try to see if this plugin '
          'supports the Android V2 embedding. Otherwise, consider removing it since a future release '
          'of Flutter will remove these deprecated APIs.\n'
          'If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: '
          'https://flutter.dev/go/android-plugin-migration.'
        );
      }
432 433
      templateContent = _androidPluginRegistryTemplateNewEmbedding;
    case AndroidEmbeddingVersion.v1:
434
      globals.printWarning(
435 436 437 438 439
        'This app is using a deprecated version of the Android embedding.\n'
        'To avoid unexpected runtime failures, or future build failures, try to migrate this '
        'app to the V2 embedding.\n'
        'Take a look at the docs for migrating an app: https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects'
      );
440
      for (final Map<String, Object?> plugin in androidPlugins) {
441 442
        final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false;
        final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false;
443
        if (!supportsEmbeddingV1 && supportsEmbeddingV2) {
444 445
          throwToolExit(
            'The plugin `${plugin['name']}` requires your app to be migrated to '
446
            'the Android embedding v2. Follow the steps on the migration doc above '
447 448 449 450 451 452 453
            'and re-run this command.'
          );
        }
      }
      templateContent = _androidPluginRegistryTemplateOldEmbedding;
  }
  globals.printTrace('Generating $registryPath');
454
  await _renderTemplateToFile(
455 456 457 458 459 460 461 462 463 464 465 466
    templateContent,
    templateContext,
    globals.fs.file(registryPath),
    globals.templateRenderer,
  );
}

const String _objcPluginRegistryHeaderTemplate = '''
//
//  Generated file. Do not edit.
//

467 468
// clang-format off

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
#ifndef GeneratedPluginRegistrant_h
#define GeneratedPluginRegistrant_h

#import <{{framework}}/{{framework}}.h>

NS_ASSUME_NONNULL_BEGIN

@interface GeneratedPluginRegistrant : NSObject
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry;
@end

NS_ASSUME_NONNULL_END
#endif /* GeneratedPluginRegistrant_h */
''';

const String _objcPluginRegistryImplementationTemplate = '''
//
//  Generated file. Do not edit.
//

489 490
// clang-format off

491 492
#import "GeneratedPluginRegistrant.h"

Daco Harkes's avatar
Daco Harkes committed
493
{{#methodChannelPlugins}}
494 495 496 497 498 499
#if __has_include(<{{name}}/{{class}}.h>)
#import <{{name}}/{{class}}.h>
#else
@import {{name}};
#endif

Daco Harkes's avatar
Daco Harkes committed
500
{{/methodChannelPlugins}}
501 502 503
@implementation GeneratedPluginRegistrant

+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {
Daco Harkes's avatar
Daco Harkes committed
504
{{#methodChannelPlugins}}
505
  [{{prefix}}{{class}} registerWithRegistrar:[registry registrarForPlugin:@"{{prefix}}{{class}}"]];
Daco Harkes's avatar
Daco Harkes committed
506
{{/methodChannelPlugins}}
507 508 509 510 511 512 513 514 515 516 517 518 519
}

@end
''';

const String _swiftPluginRegistryTemplate = '''
//
//  Generated file. Do not edit.
//

import {{framework}}
import Foundation

Daco Harkes's avatar
Daco Harkes committed
520
{{#methodChannelPlugins}}
521
import {{name}}
Daco Harkes's avatar
Daco Harkes committed
522
{{/methodChannelPlugins}}
523 524

func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
Daco Harkes's avatar
Daco Harkes committed
525
  {{#methodChannelPlugins}}
526
  {{class}}.register(with: registry.registrar(forPlugin: "{{class}}"))
Daco Harkes's avatar
Daco Harkes committed
527
{{/methodChannelPlugins}}
528 529 530 531 532 533 534 535 536 537 538
}
''';

const String _pluginRegistrantPodspecTemplate = '''
#
# Generated file, do not edit.
#

Pod::Spec.new do |s|
  s.name             = 'FlutterPluginRegistrant'
  s.version          = '0.0.1'
539
  s.summary          = 'Registers plugins with your Flutter app'
540 541 542 543 544 545 546 547 548 549 550 551 552
  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}}'
Daco Harkes's avatar
Daco Harkes committed
553
  {{#methodChannelPlugins}}
554
  s.dependency '{{name}}'
Daco Harkes's avatar
Daco Harkes committed
555
  {{/methodChannelPlugins}}
556 557 558
end
''';

559 560 561 562 563 564 565 566 567 568 569
const String _noopDartPluginRegistryTemplate = '''
// Flutter web plugin registrant file.
//
// Generated file. Do not edit.
//

// ignore_for_file: type=lint

void registerPlugins() {}
''';

570
const String _dartPluginRegistryTemplate = '''
571
// Flutter web plugin registrant file.
572 573 574 575
//
// Generated file. Do not edit.
//

576
// @dart = 2.13
577
// ignore_for_file: type=lint
578

Daco Harkes's avatar
Daco Harkes committed
579
{{#methodChannelPlugins}}
580
import 'package:{{name}}/{{file}}';
Daco Harkes's avatar
Daco Harkes committed
581
{{/methodChannelPlugins}}
582 583
import 'package:flutter_web_plugins/flutter_web_plugins.dart';

584 585
void registerPlugins([final Registrar? pluginRegistrar]) {
  final Registrar registrar = pluginRegistrar ?? webPluginRegistrar;
Daco Harkes's avatar
Daco Harkes committed
586
{{#methodChannelPlugins}}
587
  {{class}}.registerWith(registrar);
Daco Harkes's avatar
Daco Harkes committed
588
{{/methodChannelPlugins}}
589 590 591 592 593 594 595 596 597
  registrar.registerMessageHandler();
}
''';

const String _cppPluginRegistryHeaderTemplate = '''
//
//  Generated file. Do not edit.
//

598 599
// clang-format off

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_

#include <flutter/plugin_registry.h>

// Registers Flutter plugins.
void RegisterPlugins(flutter::PluginRegistry* registry);

#endif  // GENERATED_PLUGIN_REGISTRANT_
''';

const String _cppPluginRegistryImplementationTemplate = '''
//
//  Generated file. Do not edit.
//

616 617
// clang-format off

618 619
#include "generated_plugin_registrant.h"

Daco Harkes's avatar
Daco Harkes committed
620
{{#methodChannelPlugins}}
621
#include <{{name}}/{{filename}}.h>
Daco Harkes's avatar
Daco Harkes committed
622
{{/methodChannelPlugins}}
623 624

void RegisterPlugins(flutter::PluginRegistry* registry) {
Daco Harkes's avatar
Daco Harkes committed
625
{{#methodChannelPlugins}}
626 627
  {{class}}RegisterWithRegistrar(
      registry->GetRegistrarForPlugin("{{class}}"));
Daco Harkes's avatar
Daco Harkes committed
628
{{/methodChannelPlugins}}
629 630 631 632 633 634 635 636
}
''';

const String _linuxPluginRegistryHeaderTemplate = '''
//
//  Generated file. Do not edit.
//

637 638
// clang-format off

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_

#include <flutter_linux/flutter_linux.h>

// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);

#endif  // GENERATED_PLUGIN_REGISTRANT_
''';

const String _linuxPluginRegistryImplementationTemplate = '''
//
//  Generated file. Do not edit.
//

655 656
// clang-format off

657 658
#include "generated_plugin_registrant.h"

Daco Harkes's avatar
Daco Harkes committed
659
{{#methodChannelPlugins}}
660
#include <{{name}}/{{filename}}.h>
Daco Harkes's avatar
Daco Harkes committed
661
{{/methodChannelPlugins}}
662 663

void fl_register_plugins(FlPluginRegistry* registry) {
Daco Harkes's avatar
Daco Harkes committed
664
{{#methodChannelPlugins}}
665 666 667
  g_autoptr(FlPluginRegistrar) {{name}}_registrar =
      fl_plugin_registry_get_registrar_for_plugin(registry, "{{class}}");
  {{filename}}_register_with_registrar({{name}}_registrar);
Daco Harkes's avatar
Daco Harkes committed
668
{{/methodChannelPlugins}}
669 670 671 672 673 674 675 676 677
}
''';

const String _pluginCmakefileTemplate = r'''
#
# Generated file, do not edit.
#

list(APPEND FLUTTER_PLUGIN_LIST
Daco Harkes's avatar
Daco Harkes committed
678
{{#methodChannelPlugins}}
679
  {{name}}
Daco Harkes's avatar
Daco Harkes committed
680 681 682 683 684 685 686
{{/methodChannelPlugins}}
)

list(APPEND FLUTTER_FFI_PLUGIN_LIST
{{#ffiPlugins}}
  {{name}}
{{/ffiPlugins}}
687 688 689 690 691 692 693 694 695 696
)

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 $<TARGET_FILE:${plugin}_plugin>)
  list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
Daco Harkes's avatar
Daco Harkes committed
697 698 699 700 701

foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
  add_subdirectory({{pluginsDir}}/${ffi_plugin}/{{os}} plugins/${ffi_plugin})
  list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
702 703
''';

704 705 706 707 708 709 710 711 712 713 714
const String _dartPluginRegisterWith = r'''
      try {
        {{dartClass}}.registerWith();
      } catch (err) {
        print(
          '`{{pluginName}}` threw an error: $err. '
          'The app may not function as expected until you remove this plugin from pubspec.yaml'
        );
      }
''';

715
// TODO(egarciad): Evaluate merging the web and non-web plugin registry templates.
716
// https://github.com/flutter/flutter/issues/80406
717
const String _dartPluginRegistryForNonWebTemplate = '''
718 719 720 721 722 723 724 725
//
// Generated file. Do not edit.
// This file is generated from template in file `flutter_tools/lib/src/flutter_plugins.dart`.
//

// @dart = {{dartLanguageVersion}}

import 'dart:io'; // flutter_ignore: dart_io_import.
726 727 728 729 730 731
{{#android}}
import 'package:{{pluginName}}/{{pluginName}}.dart';
{{/android}}
{{#ios}}
import 'package:{{pluginName}}/{{pluginName}}.dart';
{{/ios}}
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
{{#linux}}
import 'package:{{pluginName}}/{{pluginName}}.dart';
{{/linux}}
{{#macos}}
import 'package:{{pluginName}}/{{pluginName}}.dart';
{{/macos}}
{{#windows}}
import 'package:{{pluginName}}/{{pluginName}}.dart';
{{/windows}}

@pragma('vm:entry-point')
class _PluginRegistrant {

  @pragma('vm:entry-point')
  static void register() {
747 748 749 750 751 752 753 754 755
    if (Platform.isAndroid) {
      {{#android}}
$_dartPluginRegisterWith
      {{/android}}
    } else if (Platform.isIOS) {
      {{#ios}}
$_dartPluginRegisterWith
      {{/ios}}
    } else if (Platform.isLinux) {
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
      {{#linux}}
$_dartPluginRegisterWith
      {{/linux}}
    } else if (Platform.isMacOS) {
      {{#macos}}
$_dartPluginRegisterWith
      {{/macos}}
    } else if (Platform.isWindows) {
      {{#windows}}
$_dartPluginRegisterWith
      {{/windows}}
    }
  }
}
''';

772
Future<void> _writeIOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
Daco Harkes's avatar
Daco Harkes committed
773 774
  final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, IOSPlugin.kConfigKey);
  final List<Map<String, Object?>> iosPlugins = _extractPlatformMaps(methodChannelPlugins, IOSPlugin.kConfigKey);
775
  final Map<String, Object> context = <String, Object>{
776
    'os': 'ios',
777
    'deploymentTarget': '11.0',
778
    'framework': 'Flutter',
Daco Harkes's avatar
Daco Harkes committed
779
    'methodChannelPlugins': iosPlugins,
780 781 782
  };
  if (project.isModule) {
    final Directory registryDirectory = project.ios.pluginRegistrantHost;
783
    await _renderTemplateToFile(
784 785 786 787 788 789
      _pluginRegistrantPodspecTemplate,
      context,
      registryDirectory.childFile('FlutterPluginRegistrant.podspec'),
      globals.templateRenderer,
    );
  }
790
  await _renderTemplateToFile(
791 792 793 794 795
    _objcPluginRegistryHeaderTemplate,
    context,
    project.ios.pluginRegistrantHeader,
    globals.templateRenderer,
  );
796
  await _renderTemplateToFile(
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    _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<String> relativePathComponents = fileSystem.path.split(fileSystem.path.relative(
    project.pluginSymlinkDirectory.absolute.path,
    from: makefileDirPath,
  ));
  return cmakePathContext.joinAll(relativePathComponents);
}

Future<void> _writeLinuxPluginFiles(FlutterProject project, List<Plugin> plugins) async {
Daco Harkes's avatar
Daco Harkes committed
823 824 825 826
  final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, LinuxPlugin.kConfigKey);
  final List<Map<String, Object?>> linuxMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, LinuxPlugin.kConfigKey);
  final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, LinuxPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains);
  final List<Map<String, Object?>> linuxFfiPlugins = _extractPlatformMaps(ffiPlugins, LinuxPlugin.kConfigKey);
827
  final Map<String, Object> context = <String, Object>{
828
    'os': 'linux',
Daco Harkes's avatar
Daco Harkes committed
829 830
    'methodChannelPlugins': linuxMethodChannelPlugins,
    'ffiPlugins': linuxFfiPlugins,
831 832 833 834 835 836
    'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.linux),
  };
  await _writeLinuxPluginRegistrant(project.linux.managedDirectory, context);
  await _writePluginCmakefile(project.linux.generatedPluginCmakeFile, context, globals.templateRenderer);
}

837
Future<void> _writeLinuxPluginRegistrant(Directory destination, Map<String, Object> templateContext) async {
838
  await _renderTemplateToFile(
839 840 841 842 843
    _linuxPluginRegistryHeaderTemplate,
    templateContext,
    destination.childFile('generated_plugin_registrant.h'),
    globals.templateRenderer,
  );
844
  await _renderTemplateToFile(
845 846 847 848 849 850 851
    _linuxPluginRegistryImplementationTemplate,
    templateContext,
    destination.childFile('generated_plugin_registrant.cc'),
    globals.templateRenderer,
  );
}

852
Future<void> _writePluginCmakefile(File destinationFile, Map<String, Object> templateContext, TemplateRenderer templateRenderer) async {
853
  await _renderTemplateToFile(
854 855 856 857 858 859 860 861
    _pluginCmakefileTemplate,
    templateContext,
    destinationFile,
    templateRenderer,
  );
}

Future<void> _writeMacOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
Daco Harkes's avatar
Daco Harkes committed
862 863
  final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, MacOSPlugin.kConfigKey);
  final List<Map<String, Object?>> macosMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, MacOSPlugin.kConfigKey);
864
  final Map<String, Object> context = <String, Object>{
865 866
    'os': 'macos',
    'framework': 'FlutterMacOS',
Daco Harkes's avatar
Daco Harkes committed
867
    'methodChannelPlugins': macosMethodChannelPlugins,
868
  };
869
  await _renderTemplateToFile(
870 871 872 873 874 875 876
    _swiftPluginRegistryTemplate,
    context,
    project.macos.managedDirectory.childFile('GeneratedPluginRegistrant.swift'),
    globals.templateRenderer,
  );
}

Daco Harkes's avatar
Daco Harkes committed
877 878
/// Filters out any plugins that don't use method channels, and thus shouldn't be added to the native generated registrants.
List<Plugin> _filterMethodChannelPlugins(List<Plugin> plugins, String platformKey) {
879
  return plugins.where((Plugin element) {
880
    final PluginPlatform? plugin = element.platforms[platformKey];
881 882 883 884
    if (plugin == null) {
      return false;
    }
    if (plugin is NativeOrDartPlugin) {
Daco Harkes's avatar
Daco Harkes committed
885
      return (plugin as NativeOrDartPlugin).hasMethodChannel();
886 887 888 889 890 891 892
    }
    // 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();
}

Daco Harkes's avatar
Daco Harkes committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
/// Filters out Dart-only and method channel plugins.
///
/// FFI plugins do not need native code registration, but their binaries need to be bundled.
List<Plugin> _filterFfiPlugins(List<Plugin> plugins, String platformKey) {
  return plugins.where((Plugin element) {
    final PluginPlatform? plugin = element.platforms[platformKey];
    if (plugin == null) {
      return false;
    }
    if (plugin is NativeOrDartPlugin) {
      final NativeOrDartPlugin plugin_ = plugin as NativeOrDartPlugin;
      return plugin_.hasFfi();
    }
    return false;
  }).toList();
}

910 911 912
/// Returns only the plugins with the given platform variant.
List<Plugin> _filterPluginsByVariant(List<Plugin> plugins, String platformKey, PluginPlatformVariant variant) {
  return plugins.where((Plugin element) {
913
    final PluginPlatform? platformPlugin = element.platforms[platformKey];
914 915 916
    if (platformPlugin == null) {
      return false;
    }
917 918
    assert(platformPlugin is VariantPlatformPlugin);
    return (platformPlugin as VariantPlatformPlugin).supportedVariants.contains(variant);
919 920 921
  }).toList();
}

922
@visibleForTesting
923 924 925 926 927 928
Future<void> writeWindowsPluginFiles(
  FlutterProject project,
  List<Plugin> plugins,
  TemplateRenderer templateRenderer, {
  Iterable<String>? allowedPlugins,
}) async {
Daco Harkes's avatar
Daco Harkes committed
929
  final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, WindowsPlugin.kConfigKey);
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
  if (allowedPlugins != null) {
    final List<Plugin> disallowedPlugins = methodChannelPlugins
        .toList()
        ..removeWhere((Plugin plugin) => allowedPlugins.contains(plugin.name));
    if (disallowedPlugins.isNotEmpty) {
      final StringBuffer buffer = StringBuffer();
      buffer.writeln('The Flutter Preview device does not support the following plugins from your pubspec.yaml:');
      buffer.writeln();
      buffer.writeln(disallowedPlugins.map((Plugin p) => p.name).toList().toString());
      buffer.writeln();
      buffer.writeln('In order to build a Flutter app with plugins, you must use another target platform,');
      buffer.writeln('such as Windows. Type `flutter doctor` into your terminal to see which target platforms');
      buffer.writeln('are ready to be used, and how to get required dependencies for other platforms.');
      throwToolExit(buffer.toString());
    }
  }
Daco Harkes's avatar
Daco Harkes committed
946 947 948 949
  final List<Plugin> win32Plugins = _filterPluginsByVariant(methodChannelPlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.win32);
  final List<Map<String, Object?>> windowsMethodChannelPlugins = _extractPlatformMaps(win32Plugins, WindowsPlugin.kConfigKey);
  final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, WindowsPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains);
  final List<Map<String, Object?>> windowsFfiPlugins = _extractPlatformMaps(ffiPlugins, WindowsPlugin.kConfigKey);
950
  final Map<String, Object> context = <String, Object>{
951
    'os': 'windows',
Daco Harkes's avatar
Daco Harkes committed
952 953
    'methodChannelPlugins': windowsMethodChannelPlugins,
    'ffiPlugins': windowsFfiPlugins,
954 955 956 957 958 959
    'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windows),
  };
  await _writeCppPluginRegistrant(project.windows.managedDirectory, context, templateRenderer);
  await _writePluginCmakefile(project.windows.generatedPluginCmakeFile, context, templateRenderer);
}

960
Future<void> _writeCppPluginRegistrant(Directory destination, Map<String, Object> templateContext, TemplateRenderer templateRenderer) async {
961
  await _renderTemplateToFile(
962 963 964 965 966
    _cppPluginRegistryHeaderTemplate,
    templateContext,
    destination.childFile('generated_plugin_registrant.h'),
    templateRenderer,
  );
967
  await _renderTemplateToFile(
968 969 970 971 972 973 974
    _cppPluginRegistryImplementationTemplate,
    templateContext,
    destination.childFile('generated_plugin_registrant.cc'),
    templateRenderer,
  );
}

975
Future<void> _writeWebPluginRegistrant(FlutterProject project, List<Plugin> plugins, Directory destination) async {
976 977
  final List<Map<String, Object?>> webPlugins = _extractPlatformMaps(plugins, WebPlugin.kConfigKey);
  final Map<String, Object> context = <String, Object>{
Daco Harkes's avatar
Daco Harkes committed
978
    'methodChannelPlugins': webPlugins,
979
  };
980 981 982 983 984

  final File pluginFile = destination.childFile('web_plugin_registrant.dart');

  final String template = webPlugins.isEmpty ? _noopDartPluginRegistryTemplate : _dartPluginRegistryTemplate;

985
  await _renderTemplateToFile(
986 987 988 989 990
    template,
    context,
    pluginFile,
    globals.templateRenderer,
  );
991 992 993 994 995 996 997 998 999
}

/// 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
1000
/// run after [refreshPluginsList] has been run since the last plugin change.
1001
void createPluginSymlinks(FlutterProject project, {bool force = false, @visibleForTesting FeatureFlags? featureFlagsOverride}) {
1002
  final FeatureFlags localFeatureFlags = featureFlagsOverride ?? featureFlags;
1003 1004
  Map<String, Object?>? platformPlugins;
  final String? pluginFileContent = _readFileContent(project.flutterPluginsDependenciesFile);
1005
  if (pluginFileContent != null) {
1006 1007
    final Map<String, Object?>? pluginInfo = json.decode(pluginFileContent) as Map<String, Object?>?;
    platformPlugins = pluginInfo?[_kFlutterPluginsPluginListKey] as Map<String, Object?>?;
1008
  }
1009
  platformPlugins ??= <String, Object?>{};
1010 1011 1012 1013

  if (localFeatureFlags.isWindowsEnabled && project.windows.existsSync()) {
    _createPlatformPluginSymlinks(
      project.windows.pluginSymlinkDirectory,
1014
      platformPlugins[project.windows.pluginConfigKey] as List<Object?>?,
1015 1016 1017 1018 1019 1020
      force: force,
    );
  }
  if (localFeatureFlags.isLinuxEnabled && project.linux.existsSync()) {
    _createPlatformPluginSymlinks(
      project.linux.pluginSymlinkDirectory,
1021
      platformPlugins[project.linux.pluginConfigKey] as List<Object?>?,
1022 1023 1024 1025 1026 1027 1028 1029 1030
      force: force,
    );
  }
}

/// Handler for symlink failures which provides specific instructions for known
/// failure cases.
@visibleForTesting
void handleSymlinkException(FileSystemException e, {
1031 1032
  required Platform platform,
  required OperatingSystemUtils os,
1033 1034
  required String destination,
  required String source,
1035
}) {
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
  if (platform.isWindows) {
    // ERROR_ACCESS_DENIED
    if (e.osError?.errorCode == 5) {
      throwToolExit(
        'ERROR_ACCESS_DENIED file system exception thrown while trying to '
        'create a symlink from $source to $destination',
      );
    }
    // ERROR_PRIVILEGE_NOT_HELD, user cannot symlink
    if (e.osError?.errorCode == 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');
    }
1059 1060 1061 1062 1063 1064 1065 1066
    // ERROR_INVALID_FUNCTION, trying to link across drives, which is not supported
    if (e.osError?.errorCode == 1) {
      throwToolExit(
        'Creating symlink from $source to $destination failed with '
        'ERROR_INVALID_FUNCTION. Try moving your Flutter project to the same '
        'drive as your Flutter SDK.',
      );
    }
1067 1068 1069 1070 1071 1072
  }
}

/// Creates [symlinkDirectory] containing symlinks to each plugin listed in [platformPlugins].
///
/// If [force] is true, the directory will be created only if missing.
1073
void _createPlatformPluginSymlinks(Directory symlinkDirectory, List<Object?>? platformPlugins, {bool force = false}) {
1074 1075 1076 1077 1078 1079 1080 1081
  if (force && symlinkDirectory.existsSync()) {
    // Start fresh to avoid stale links.
    symlinkDirectory.deleteSync(recursive: true);
  }
  symlinkDirectory.createSync(recursive: true);
  if (platformPlugins == null) {
    return;
  }
1082 1083 1084
  for (final Map<String, Object?> pluginInfo in platformPlugins.cast<Map<String, Object?>>()) {
    final String name = pluginInfo[_kFlutterPluginsNameKey]! as String;
    final String path = pluginInfo[_kFlutterPluginsPathKey]! as String;
1085 1086 1087 1088 1089 1090 1091
    final Link link = symlinkDirectory.childLink(name);
    if (link.existsSync()) {
      continue;
    }
    try {
      link.createSync(path);
    } on FileSystemException catch (e) {
1092 1093 1094 1095 1096 1097 1098
      handleSymlinkException(
        e,
        platform: globals.platform,
        os: globals.os,
        destination: 'dest',
        source: 'source',
      );
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
      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<void> refreshPluginsList(
  FlutterProject project, {
  bool iosPlatform = false,
  bool macOSPlatform = false,
}) async {
  final List<Plugin> 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) {
1124
      globals.cocoaPods?.invalidatePodInstallOutput(project.ios);
1125 1126
    }
    if (macOSPlatform) {
1127
      globals.cocoaPods?.invalidatePodInstallOutput(project.macos);
1128 1129 1130 1131
    }
  }
}

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
/// Injects plugins found in `pubspec.yaml` into the platform-specific projects
/// only at build-time.
///
/// This method is similar to [injectPlugins], but used only for platforms where
/// the plugin files are not required when the app is created (currently: Web).
///
/// This method will create files in the temporary flutter build directory
/// specified by `destination`.
///
/// In the Web platform, `destination` can point to a real filesystem (`flutter build`)
/// or an in-memory filesystem (`flutter run`).
1143 1144 1145 1146 1147
///
/// This method is also used by [WebProject.ensureReadyForPlatformSpecificTooling]
/// to inject a copy of the plugin registrant for web into .dart_tool/dartpad so
/// dartpad can get the plugin registrant without needing to build the complete
/// project. See: https://github.com/dart-lang/dart-services/pull/874
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
Future<void> injectBuildTimePluginFiles(
  FlutterProject project, {
  required Directory destination,
  bool webPlatform = false,
}) async {
  final List<Plugin> 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 (webPlatform) {
    await _writeWebPluginRegistrant(project, plugins, destination);
  }
}

1161 1162
/// Injects plugins found in `pubspec.yaml` into the platform-specific projects.
///
1163 1164 1165 1166 1167 1168 1169 1170 1171
/// The injected files are required by the flutter app as soon as possible, so
/// it can be built.
///
/// Files written by this method end up in platform-specific locations that are
/// configured by each [FlutterProject] subclass (except for the Web).
///
/// Web tooling uses [injectBuildTimePluginFiles] instead, which places files in the
/// current build (temp) directory, and doesn't modify the users' working copy.
///
1172 1173 1174 1175 1176 1177 1178 1179
/// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`.
Future<void> injectPlugins(
  FlutterProject project, {
  bool androidPlatform = false,
  bool iosPlatform = false,
  bool linuxPlatform = false,
  bool macOSPlatform = false,
  bool windowsPlatform = false,
1180
  Iterable<String>? allowedPlugins,
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
}) async {
  final List<Plugin> 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) {
1198
    await writeWindowsPluginFiles(project, plugins, globals.templateRenderer, allowedPlugins: allowedPlugins);
1199 1200 1201 1202 1203 1204 1205 1206
  }
  if (!project.isModule) {
    final List<XcodeBasedProject> darwinProjects = <XcodeBasedProject>[
      if (iosPlatform) project.ios,
      if (macOSPlatform) project.macos,
    ];
    for (final XcodeBasedProject subproject in darwinProjects) {
      if (plugins.isNotEmpty) {
1207
        await globals.cocoaPods?.setupPodfile(subproject);
1208 1209 1210 1211
      }
      /// The user may have a custom maintained Podfile that they're running `pod install`
      /// on themselves.
      else if (subproject.podfile.existsSync() && subproject.podfileLock.existsSync()) {
1212
        globals.cocoaPods?.addPodsDependencyToFlutterXcconfig(subproject);
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
      }
    }
  }
}

/// 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;
}
1224 1225 1226

/// Resolves the platform implementation for Dart-only plugins.
///
1227 1228
///   * If there is only one dependency on a package that implements the
///     frontend plugin for the current platform, use that.
1229
///   * If there is a single direct dependency on a package that implements the
1230 1231 1232 1233
///     frontend plugin for the current platform, use that.
///   * If there is no direct dependency on a package that implements the
///     frontend plugin, but there is a default for the current platform,
///     use that.
1234 1235 1236
///   * Else fail.
///
///  For more details, https://flutter.dev/go/federated-plugins.
1237 1238
// TODO(stuartmorgan): Expand implementation to apply to all implementations,
// not just Dart-only, per the federated plugin spec.
1239 1240 1241 1242 1243
List<PluginInterfaceResolution> resolvePlatformImplementation(
  List<Plugin> plugins, {
  bool throwOnPluginPubspecError = true,
}) {
  final List<String> platforms = <String>[
1244 1245
    AndroidPlugin.kConfigKey,
    IOSPlugin.kConfigKey,
1246 1247 1248 1249
    LinuxPlugin.kConfigKey,
    MacOSPlugin.kConfigKey,
    WindowsPlugin.kConfigKey,
  ];
1250 1251
  final Map<String, List<PluginInterfaceResolution>> possibleResolutions
      = <String, List<PluginInterfaceResolution>>{};
1252
  final Map<String, String> defaultImplementations = <String, String>{};
1253 1254 1255 1256
  // Generates a key for the maps above.
  String getResolutionKey({required String platform, required String packageName}) {
    return '$packageName:$platform';
  }
1257

1258
  bool hasPubspecError = false;
1259 1260 1261 1262
  for (final Plugin plugin in plugins) {
    for (final String platform in platforms) {
      if (plugin.platforms[platform] == null &&
          plugin.defaultPackagePlatforms[platform] == null) {
1263
        // The plugin doesn't implement this platform.
1264 1265
        continue;
      }
1266
      String? implementsPackage = plugin.implementsPackage;
1267
      if (implementsPackage == null || implementsPackage.isEmpty) {
1268
        final String? defaultImplementation = plugin.defaultPackagePlatforms[platform];
1269 1270 1271
        final bool hasInlineDartImplementation =
          plugin.pluginDartClassPlatforms[platform] != null;
        if (defaultImplementation == null && !hasInlineDartImplementation) {
1272 1273
          if (throwOnPluginPubspecError) {
            globals.printError(
1274 1275 1276 1277 1278 1279 1280 1281 1282
              "Plugin `${plugin.name}` doesn't implement a plugin interface, nor does "
              'it specify an implementation in pubspec.yaml.\n\n'
              'To set an inline implementation, use:\n'
              'flutter:\n'
              '  plugin:\n'
              '    platforms:\n'
              '      $platform:\n'
              '        $kDartPluginClass: <plugin-class>\n'
              '\n'
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
              'To set a default implementation, use:\n'
              'flutter:\n'
              '  plugin:\n'
              '    platforms:\n'
              '      $platform:\n'
              '        $kDefaultPackage: <plugin-implementation>\n'
              '\n'
              'To implement an interface, use:\n'
              'flutter:\n'
              '  plugin:\n'
              '    implements: <plugin-interface>'
              '\n'
            );
          }
1297
          hasPubspecError = true;
1298 1299
          continue;
        }
1300
        final String defaultImplementationKey = getResolutionKey(platform: platform, packageName: plugin.name);
1301
        if (defaultImplementation != null) {
1302
          defaultImplementations[defaultImplementationKey] = defaultImplementation;
1303
          continue;
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        } else {
          // An app-facing package (i.e., one with no 'implements') with an
          // inline implementation should be its own default implementation.
          // Desktop platforms originally did not work that way, and enabling
          // it unconditionally would break existing published plugins, so
          // only treat it as such if either:
          // - the platform is not desktop, or
          // - the plugin requires at least Flutter 2.11 (when this opt-in logic
          //   was added), so that existing plugins continue to work.
          // See https://github.com/flutter/flutter/issues/87862 for details.
          final bool isDesktop = platform == 'linux' || platform == 'macos' || platform == 'windows';
          final semver.VersionConstraint? flutterConstraint = plugin.flutterConstraint;
          final semver.Version? minFlutterVersion = flutterConstraint != null &&
            flutterConstraint is semver.VersionRange ? flutterConstraint.min : null;
          final bool hasMinVersionForImplementsRequirement = minFlutterVersion != null &&
            minFlutterVersion.compareTo(semver.Version(2, 11, 0)) >= 0;
          if (!isDesktop || hasMinVersionForImplementsRequirement) {
            implementsPackage = plugin.name;
1322 1323 1324 1325 1326
            defaultImplementations[defaultImplementationKey] = plugin.name;
          } else {
            // If it doesn't meet any of the conditions, it isn't eligible for
            // auto-registration.
            continue;
1327
          }
1328
        }
1329
      }
1330
      // If there's no Dart implementation, there's nothing to register.
1331 1332 1333 1334
      if (plugin.pluginDartClassPlatforms[platform] == null ||
          plugin.pluginDartClassPlatforms[platform] == 'none') {
        continue;
      }
1335 1336 1337 1338 1339 1340

      // If it hasn't been skipped, it's a candidate for auto-registration, so
      // add it as a possible resolution.
      final String resolutionKey = getResolutionKey(platform: platform, packageName: implementsPackage);
      if (!possibleResolutions.containsKey(resolutionKey)) {
        possibleResolutions[resolutionKey] = <PluginInterfaceResolution>[];
1341
      }
1342
      possibleResolutions[resolutionKey]!.add(PluginInterfaceResolution(
1343 1344
        plugin: plugin,
        platform: platform,
1345
      ));
1346 1347
    }
  }
1348
  if (hasPubspecError && throwOnPluginPubspecError) {
1349 1350
    throwToolExit('Please resolve the errors');
  }
1351 1352 1353 1354

  // Now resolve all the possible resolutions to a single option for each
  // plugin, or throw if that's not possible.
  bool hasResolutionError = false;
1355
  final List<PluginInterfaceResolution> finalResolution = <PluginInterfaceResolution>[];
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
  for (final MapEntry<String, List<PluginInterfaceResolution>> entry in possibleResolutions.entries) {
    final List<PluginInterfaceResolution> candidates = entry.value;
    // If there's only one candidate, use it.
    if (candidates.length == 1) {
      finalResolution.add(candidates.first);
      continue;
    }
    // Next, try direct dependencies of the resolving application.
    final Iterable<PluginInterfaceResolution> directDependencies = candidates.where((PluginInterfaceResolution r) {
      return r.plugin.isDirectDependency;
    });
    if (directDependencies.isNotEmpty) {
      if (directDependencies.length > 1) {
        globals.printError(
          'Plugin ${entry.key} has conflicting direct dependency implementations:\n'
          '${directDependencies.map((PluginInterfaceResolution r) => '  ${r.plugin.name}\n').join()}'
          'To fix this issue, remove all but one of these dependencies from pubspec.yaml.\n'
        );
        hasResolutionError = true;
      } else {
        finalResolution.add(directDependencies.first);
      }
      continue;
    }
    // Next, defer to the default implementation if there is one.
    final String? defaultPackageName = defaultImplementations[entry.key];
    if (defaultPackageName != null) {
      final int defaultIndex = candidates
          .indexWhere((PluginInterfaceResolution r) => r.plugin.name == defaultPackageName);
      if (defaultIndex != -1) {
        finalResolution.add(candidates[defaultIndex]);
        continue;
1388 1389
      }
    }
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    // Otherwise, require an explicit choice.
    if (candidates.length > 1) {
      globals.printError(
        'Plugin ${entry.key} has multiple possible implementations:\n'
        '${candidates.map((PluginInterfaceResolution r) => '  ${r.plugin.name}\n').join()}'
        'To fix this issue, add one of these dependencies to pubspec.yaml.\n'
      );
      hasResolutionError = true;
      continue;
    }
  }
  if (hasResolutionError) {
    throwToolExit('Please resolve the errors');
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
  }
  return finalResolution;
}

/// Generates the Dart plugin registrant, which allows to bind a platform
/// implementation of a Dart only plugin to its interface.
/// The new entrypoint wraps [currentMainUri], adds the [_PluginRegistrant] class,
/// and writes the file to [newMainDart].
///
/// [mainFile] is the main entrypoint file. e.g. /<app>/lib/main.dart.
///
/// A successful run will create a new generate_main.dart file or update the existing file.
/// Throws [ToolExit] if unable to generate the file.
///
/// This method also validates each plugin's pubspec.yaml, but errors are only
/// reported if [throwOnPluginPubspecError] is [true].
///
/// For more details, see https://flutter.dev/go/federated-plugins.
Future<void> generateMainDartWithPluginRegistrant(
  FlutterProject rootProject,
  PackageConfig packageConfig,
  String currentMainUri,
  File mainFile, {
1426
  bool throwOnPluginPubspecError = false,
1427 1428 1429 1430
}) async {
  final List<Plugin> plugins = await findPlugins(rootProject);
  final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(
    plugins,
1431
    throwOnPluginPubspecError: throwOnPluginPubspecError,
1432 1433 1434 1435
  );
  final LanguageVersion entrypointVersion = determineLanguageVersion(
    mainFile,
    packageConfig.packageOf(mainFile.absolute.uri),
1436
    Cache.flutterRoot!,
1437
  );
1438
  final Map<String, Object> templateContext = <String, Object>{
1439 1440
    'mainEntrypoint': currentMainUri,
    'dartLanguageVersion': entrypointVersion.toString(),
1441 1442
    AndroidPlugin.kConfigKey: <Object?>[],
    IOSPlugin.kConfigKey: <Object?>[],
1443 1444 1445
    LinuxPlugin.kConfigKey: <Object?>[],
    MacOSPlugin.kConfigKey: <Object?>[],
    WindowsPlugin.kConfigKey: <Object?>[],
1446
  };
1447
  final File newMainDart = rootProject.dartPluginRegistrant;
1448 1449
  if (resolutions.isEmpty) {
    try {
1450 1451
      if (await newMainDart.exists()) {
        await newMainDart.delete();
1452 1453
      }
    } on FileSystemException catch (error) {
1454
      globals.printWarning(
1455 1456 1457 1458 1459 1460 1461 1462 1463
        'Unable to remove ${newMainDart.path}, received error: $error.\n'
        'You might need to run flutter clean.'
      );
      rethrow;
    }
    return;
  }
  for (final PluginInterfaceResolution resolution in resolutions) {
    assert(templateContext.containsKey(resolution.platform));
1464
    (templateContext[resolution.platform] as List<Object?>?)?.add(resolution.toMap());
1465 1466
  }
  try {
1467
    await _renderTemplateToFile(
1468
      _dartPluginRegistryForNonWebTemplate,
1469 1470 1471 1472 1473 1474 1475 1476 1477
      templateContext,
      newMainDart,
      globals.templateRenderer,
    );
  } on FileSystemException catch (error) {
    globals.printError('Unable to write ${newMainDart.path}, received error: $error');
    rethrow;
  }
}