Skip to content

Commit

Permalink
Implement dartPluginClass support for plugins (flutter#74469)
Browse files Browse the repository at this point in the history
  • Loading branch information
Emmanuel Garcia authored Feb 19, 2021
1 parent d9fca66 commit b7d4806
Show file tree
Hide file tree
Showing 21 changed files with 1,466 additions and 21 deletions.
10 changes: 10 additions & 0 deletions dev/devicelab/bin/tasks/dart_plugin_registry_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter_devicelab/tasks/dart_plugin_registry_tests.dart';
import 'package:flutter_devicelab/framework/framework.dart';

Future<void> main() async {
await task(dartPluginRegistryTest());
}
181 changes: 181 additions & 0 deletions dev/devicelab/lib/tasks/dart_plugin_registry_tests.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:path/path.dart' as path;
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'package:flutter_devicelab/framework/utils.dart';

TaskFunction dartPluginRegistryTest({
String deviceIdOverride,
Map<String, String> environment,
}) {
final Directory tempDir = Directory.systemTemp
.createTempSync('flutter_devicelab_dart_plugin_test.');
return () async {
try {
section('Create implementation plugin');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--template=plugin',
'--org',
'io.flutter.devicelab',
'--platforms',
'macos',
'plugin_platform_implementation',
],
environment: environment,
);
});

final File pluginMain = File(path.join(
tempDir.absolute.path,
'plugin_platform_implementation',
'lib',
'plugin_platform_implementation.dart',
));
if (!pluginMain.existsSync()) {
return TaskResult.failure('${pluginMain.path} does not exist');
}

// Patch plugin main dart file.
await pluginMain.writeAsString('''
class PluginPlatformInterfaceMacOS {
static void registerWith() {
print('PluginPlatformInterfaceMacOS.registerWith() was called');
}
}
''', flush: true);

// Patch plugin main pubspec file.
final File pluginImplPubspec = File(path.join(
tempDir.absolute.path,
'plugin_platform_implementation',
'pubspec.yaml',
));
String pluginImplPubspecContent = await pluginImplPubspec.readAsString();
pluginImplPubspecContent = pluginImplPubspecContent.replaceFirst(
' pluginClass: PluginPlatformImplementationPlugin',
' pluginClass: PluginPlatformImplementationPlugin\n'
' dartPluginClass: PluginPlatformInterfaceMacOS\n',
);
pluginImplPubspecContent = pluginImplPubspecContent.replaceFirst(
' platforms:\n',
' implements: plugin_platform_interface\n'
' platforms:\n');
await pluginImplPubspec.writeAsString(pluginImplPubspecContent,
flush: true);

section('Create interface plugin');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--template=plugin',
'--org',
'io.flutter.devicelab',
'--platforms',
'macos',
'plugin_platform_interface',
],
environment: environment,
);
});
final File pluginInterfacePubspec = File(path.join(
tempDir.absolute.path,
'plugin_platform_interface',
'pubspec.yaml',
));
String pluginInterfacePubspecContent =
await pluginInterfacePubspec.readAsString();
pluginInterfacePubspecContent =
pluginInterfacePubspecContent.replaceFirst(
' pluginClass: PluginPlatformInterfacePlugin',
' default_package: plugin_platform_implementation\n');
pluginInterfacePubspecContent =
pluginInterfacePubspecContent.replaceFirst(
'dependencies:',
'dependencies:\n'
' plugin_platform_implementation:\n'
' path: ../plugin_platform_implementation\n');
await pluginInterfacePubspec.writeAsString(pluginInterfacePubspecContent,
flush: true);

section('Create app');

await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--template=app',
'--org',
'io.flutter.devicelab',
'--platforms',
'macos',
'app',
],
environment: environment,
);
});

final File appPubspec = File(path.join(
tempDir.absolute.path,
'app',
'pubspec.yaml',
));
String appPubspecContent = await appPubspec.readAsString();
appPubspecContent = appPubspecContent.replaceFirst(
'dependencies:',
'dependencies:\n'
' plugin_platform_interface:\n'
' path: ../plugin_platform_interface\n');
await appPubspec.writeAsString(appPubspecContent, flush: true);

section('Flutter run for macos');

await inDirectory(path.join(tempDir.path, 'app'), () async {
final Process run = await startProcess(
path.join(flutterDirectory.path, 'bin', 'flutter'),
flutterCommandArgs('run', <String>['-d', 'macos', '-v']),
environment: null,
);
Completer<void> registryExecutedCompleter = Completer<void>();
final StreamSubscription<void> subscription = run.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
if (line.contains(
'PluginPlatformInterfaceMacOS.registerWith() was called')) {
registryExecutedCompleter.complete();
}
print('stdout: $line');
});

section('Wait for registry execution');
await registryExecutedCompleter.future
.timeout(const Duration(minutes: 1));

// Hot restart.
run.stdin.write('R');
registryExecutedCompleter = Completer<void>();

section('Wait for registry execution after hot restart');
await registryExecutedCompleter.future
.timeout(const Duration(minutes: 1));

subscription.cancel();
run.kill();
});
return TaskResult.success(null);
} finally {
rmTree(tempDir);
}
};
}
10 changes: 10 additions & 0 deletions packages/flutter_tools/lib/src/build_system/build_system.dart
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ class Environment {
@required Artifacts artifacts,
@required ProcessManager processManager,
@required String engineVersion,
@required bool generateDartPluginRegistry,
Directory buildDir,
Map<String, String> defines = const <String, String>{},
Map<String, String> inputs = const <String, String>{},
Expand Down Expand Up @@ -347,6 +348,7 @@ class Environment {
processManager: processManager,
engineVersion: engineVersion,
inputs: inputs,
generateDartPluginRegistry: generateDartPluginRegistry,
);
}

Expand All @@ -363,6 +365,7 @@ class Environment {
Map<String, String> defines = const <String, String>{},
Map<String, String> inputs = const <String, String>{},
String engineVersion,
bool generateDartPluginRegistry = false,
@required FileSystem fileSystem,
@required Logger logger,
@required Artifacts artifacts,
Expand All @@ -381,6 +384,7 @@ class Environment {
artifacts: artifacts,
processManager: processManager,
engineVersion: engineVersion,
generateDartPluginRegistry: generateDartPluginRegistry,
);
}

Expand All @@ -398,6 +402,7 @@ class Environment {
@required this.artifacts,
@required this.engineVersion,
@required this.inputs,
@required this.generateDartPluginRegistry,
});

/// The [Source] value which is substituted with the path to [projectDir].
Expand Down Expand Up @@ -475,6 +480,11 @@ class Environment {

/// The version of the current engine, or `null` if built with a local engine.
final String engineVersion;

/// Whether to generate the Dart plugin registry.
/// When [true], the main entrypoint is wrapped and the wrapper becomes
/// the new entrypoint.
final bool generateDartPluginRegistry;
}

/// The result information from the build system.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,8 @@ class KernelSnapshot extends Target {
fileSystemScheme: fileSystemScheme,
dartDefines: decodeDartDefines(environment.defines, kDartDefines),
packageConfig: packageConfig,
buildDir: environment.buildDir,
generateDartPluginRegistry: environment.generateDartPluginRegistry,
);
if (output == null || output.errorCount != 0) {
throw Exception();
Expand Down
1 change: 1 addition & 0 deletions packages/flutter_tools/lib/src/bundle.dart
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ Future<void> buildWithAssemble({
fileSystem: globals.fs,
logger: globals.logger,
processManager: globals.processManager,
generateDartPluginRegistry: true,
);
final Target target = buildMode == BuildMode.debug
? const CopyFlutterBundle()
Expand Down
3 changes: 2 additions & 1 deletion packages/flutter_tools/lib/src/commands/assemble.dart
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ class AssembleCommand extends FlutterCommand {
processManager: globals.processManager,
engineVersion: globals.artifacts.isLocalEngine
? null
: globals.flutterVersion.engineRevision
: globals.flutterVersion.engineRevision,
generateDartPluginRegistry: true,
);
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ end
engineVersion: globals.artifacts.isLocalEngine
? null
: globals.flutterVersion.engineRevision,
generateDartPluginRegistry: true,
);
Target target;
// Always build debug for simulator.
Expand Down
2 changes: 2 additions & 0 deletions packages/flutter_tools/lib/src/commands/packages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ class PackagesGetCommand extends FlutterCommand {
outputDir: globals.fs.directory(getBuildDirectory()),
processManager: globals.processManager,
projectDir: flutterProject.directory,
generateDartPluginRegistry: true,
);

await generateLocalizationsSyntheticPackage(
Expand Down Expand Up @@ -324,6 +325,7 @@ class PackagesInteractiveGetCommand extends FlutterCommand {
outputDir: globals.fs.directory(getBuildDirectory()),
processManager: globals.processManager,
projectDir: flutterProject.directory,
generateDartPluginRegistry: true,
);

await generateLocalizationsSyntheticPackage(
Expand Down
23 changes: 21 additions & 2 deletions packages/flutter_tools/lib/src/compile.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import 'base/logger.dart';
import 'base/platform.dart';
import 'build_info.dart';
import 'convert.dart';
import 'plugins.dart';
import 'project.dart';

/// The target model describes the set of core libraries that are available within
/// the SDK.
Expand Down Expand Up @@ -209,6 +211,8 @@ class KernelCompiler {
String fileSystemScheme,
String initializeFromDill,
String platformDill,
Directory buildDir,
bool generateDartPluginRegistry = false,
@required String packagesPath,
@required BuildMode buildMode,
@required bool trackWidgetCreation,
Expand All @@ -227,14 +231,30 @@ class KernelCompiler {
throwToolExit('Unable to find Dart binary at $engineDartPath');
}
String mainUri;
final Uri mainFileUri = _fileSystem.file(mainPath).uri;
final File mainFile = _fileSystem.file(mainPath);
final Uri mainFileUri = mainFile.uri;
if (packagesPath != null) {
mainUri = packageConfig.toPackageUri(mainFileUri)?.toString();
}
mainUri ??= toMultiRootPath(mainFileUri, _fileSystemScheme, _fileSystemRoots, _fileSystem.path.separator == r'\');
if (outputFilePath != null && !_fileSystem.isFileSync(outputFilePath)) {
_fileSystem.file(outputFilePath).createSync(recursive: true);
}
if (buildDir != null && generateDartPluginRegistry) {
// `generated_main.dart` is under `.dart_tools/flutter_build/`,
// so the resident compiler can find it.
final File newMainDart = buildDir.parent.childFile('generated_main.dart');
if (await generateMainDartWithPluginRegistrant(
FlutterProject.current(),
packageConfig,
mainUri,
newMainDart,
mainFile,
)) {
mainUri = newMainDart.path;
}
}

final List<String> command = <String>[
engineDartPath,
'--disable-dart-dev',
Expand Down Expand Up @@ -579,7 +599,6 @@ class DefaultResidentCompiler implements ResidentCompiler {
if (!_controller.hasListener) {
_controller.stream.listen(_handleCompilationRequest);
}

final Completer<CompilerOutput> completer = Completer<CompilerOutput>();
_controller.add(
_RecompileRequest(completer, mainUri, invalidatedFiles, outputPath, packageConfig, suppressErrors)
Expand Down
14 changes: 14 additions & 0 deletions packages/flutter_tools/lib/src/devfs.dart
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,20 @@ class DevFS {
// dill files that depend on the invalidated files.
_logger.printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files');

// `generated_main.dart` contains the Dart plugin registry.
if (projectRootPath != null) {
final File generatedMainDart = _fileSystem.file(
_fileSystem.path.join(
projectRootPath,
'.dart_tool',
'flutter_build',
'generated_main.dart',
),
);
if (generatedMainDart != null && generatedMainDart.existsSync()) {
mainUri = generatedMainDart.uri;
}
}
// Await the compiler response after checking if the bundle is updated. This allows the file
// stating to be done while waiting for the frontend_server response.
final Future<CompilerOutput> pendingCompilerOutput = generator.recompile(
Expand Down
7 changes: 7 additions & 0 deletions packages/flutter_tools/lib/src/flutter_manifest.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ class FlutterManifest {
/// The string value of the top-level `name` property in the `pubspec.yaml` file.
String get appName => _descriptor['name'] as String ?? '';

/// Contains the name of the dependencies.
/// These are the keys specified in the `dependency` map.
Set<String> get dependencies {
final YamlMap dependencies = _descriptor['dependencies'] as YamlMap;
return dependencies != null ? <String>{...dependencies.keys.cast<String>()} : <String>{};
}

// Flag to avoid printing multiple invalid version messages.
bool _hasShowInvalidVersionMsg = false;

Expand Down
Loading

0 comments on commit b7d4806

Please sign in to comment.