diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/adb.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/adb.dart new file mode 100644 index 0000000000000000000000000000000000000000..a500a1b3ee060c3fc71445b3e5259a96cb8b8e7a --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/adb.dart @@ -0,0 +1,18 @@ +// 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. + +final RegExp _whitespace = RegExp(r'\s+'); + +/// Convert adb device names into more human readable descriptions. +String cleanAdbDeviceName(String name) { + // Some emulators use `___` in the name as separators. + name = name.replaceAll('___', ', '); + + // Convert `Nexus_7` / `Nexus_5X` style names to `Nexus 7` ones. + name = name.replaceAll('_', ' '); + + name = name.replaceAll(_whitespace, ' ').trim(); + + return name; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android.dart new file mode 100644 index 0000000000000000000000000000000000000000..6ecd6b6938cf4614bebb60d26edacb919d007c7b --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android.dart @@ -0,0 +1,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. + +const int minApiLevel = 16; +const String minVersionName = 'Jelly Bean'; +const String minVersionText = '4.1.x'; diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_builder.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_builder.dart new file mode 100644 index 0000000000000000000000000000000000000000..f50bfb0b3d365880e231b49380bb87b02ba1d0f5 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_builder.dart @@ -0,0 +1,53 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../base/context.dart'; +import '../build_info.dart'; +import '../project.dart'; + +/// The builder in the current context. +AndroidBuilder? get androidBuilder { + return context.get(); +} + +abstract class AndroidBuilder { + const AndroidBuilder(); + /// Builds an AAR artifact. + Future buildAar({ + required FlutterProject project, + required Set androidBuildInfo, + required String target, + String? outputDirectoryPath, + required String buildNumber, + }); + + /// Builds an APK artifact. + Future buildApk({ + required FlutterProject project, + required AndroidBuildInfo androidBuildInfo, + required String target, + bool configOnly = false, + }); + + /// Builds an App Bundle artifact. + Future buildAab({ + required FlutterProject project, + required AndroidBuildInfo androidBuildInfo, + required String target, + bool validateDeferredComponents = true, + bool deferredComponentsEnabled = false, + bool configOnly = false, + }); + + /// Returns a list of available build variant from the Android project. + Future> getBuildVariants({required FlutterProject project}); + + /// Outputs app link related project settings into a json file. + /// + /// The return future resolves to the path of the json file. + Future outputsAppLinkSettings( + String buildVariant, { + required FlutterProject project, + }); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_console.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_console.dart new file mode 100644 index 0000000000000000000000000000000000000000..252208ecdb287f7ca09157c60b4d7efe91331a9e --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_console.dart @@ -0,0 +1,84 @@ +// 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:async/async.dart'; + +import '../base/io.dart'; +import '../convert.dart'; + +/// Default factory that creates a real Android console connection. +/// +/// The default implementation will create real connections to a device. +/// Override this in tests with an implementation that returns mock responses. +Future kAndroidConsoleSocketFactory(String host, int port) => Socket.connect(host, port); + +/// Currently active implementation of the AndroidConsoleFactory. +/// +/// The default implementation will create real connections to a device. +/// Override this in tests with an implementation that returns mock responses. +typedef AndroidConsoleSocketFactory = Future Function(String host, int port); + +/// Creates a console connection to an Android emulator that can be used to run +/// commands such as "avd name" which are not available to ADB. +/// +/// See documentation at +/// https://developer.android.com/studio/run/emulator-console +class AndroidConsole { + AndroidConsole(this._socket); + + Socket? _socket; + StreamQueue? _queue; + + Future connect() async { + assert(_socket != null); + assert(_queue == null); + + _queue = StreamQueue(_socket!.asyncMap(ascii.decode)); + + // Discard any initial connection text. + await _readResponse(); + } + + Future getAvdName() async { + if (_queue == null) { + return null; + } + _write('avd name\n'); + return _readResponse(); + } + + void destroy() { + _socket?.destroy(); + _socket = null; + _queue = null; + } + + Future _readResponse() async { + if (_queue == null) { + return null; + } + final StringBuffer output = StringBuffer(); + while (true) { + if (!await _queue!.hasNext) { + destroy(); + return null; + } + final String text = await _queue!.next; + final String trimmedText = text.trim(); + if (trimmedText == 'OK') { + break; + } + if (trimmedText.endsWith('\nOK')) { + output.write(trimmedText.substring(0, trimmedText.length - 3)); + break; + } + output.write(text); + } + return output.toString().trim(); + } + + void _write(String text) { + _socket?.add(ascii.encode(text)); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device.dart new file mode 100644 index 0000000000000000000000000000000000000000..90f029371e6a6a47d2ea84e791c07da32eb03a5a --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device.dart @@ -0,0 +1,1365 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import '../application_package.dart'; +import '../base/common.dart' show throwToolExit; +import '../base/file_system.dart'; +import '../base/io.dart'; +import '../base/logger.dart'; +import '../base/platform.dart'; +import '../base/process.dart'; +import '../build_info.dart'; +import '../convert.dart'; +import '../device.dart'; +import '../device_port_forwarder.dart'; +import '../project.dart'; +import '../protocol_discovery.dart'; +import 'android.dart'; +import 'android_builder.dart'; +import 'android_console.dart'; +import 'android_sdk.dart'; +import 'application_package.dart'; + +/// Whether the [AndroidDevice] is believed to be a physical device or an emulator. +enum HardwareType { emulator, physical } + +/// Map to help our `isLocalEmulator` detection. +/// +/// See [AndroidDevice] for more explanation of why this is needed. +const Map kKnownHardware = { + 'goldfish': HardwareType.emulator, + 'qcom': HardwareType.physical, + 'ranchu': HardwareType.emulator, + 'samsungexynos7420': HardwareType.physical, + 'samsungexynos7580': HardwareType.physical, + 'samsungexynos7870': HardwareType.physical, + 'samsungexynos7880': HardwareType.physical, + 'samsungexynos8890': HardwareType.physical, + 'samsungexynos8895': HardwareType.physical, + 'samsungexynos9810': HardwareType.physical, + 'samsungexynos7570': HardwareType.physical, +}; + +/// A physical Android device or emulator. +/// +/// While [isEmulator] attempts to distinguish between the device categories, +/// this is a best effort process and not a guarantee; certain physical devices +/// identify as emulators. These device identifiers may be added to the [kKnownHardware] +/// map to specify that they are actually physical devices. +class AndroidDevice extends Device { + AndroidDevice( + super.id, { + this.productID, + required this.modelID, + this.deviceCodeName, + required Logger logger, + required ProcessManager processManager, + required Platform platform, + required AndroidSdk androidSdk, + required FileSystem fileSystem, + AndroidConsoleSocketFactory androidConsoleSocketFactory = kAndroidConsoleSocketFactory, + }) : _logger = logger, + _processManager = processManager, + _androidSdk = androidSdk, + _platform = platform, + _fileSystem = fileSystem, + _androidConsoleSocketFactory = androidConsoleSocketFactory, + _processUtils = ProcessUtils(logger: logger, processManager: processManager), + super( + category: Category.mobile, + platformType: PlatformType.android, + ephemeral: true, + ); + + final Logger _logger; + final ProcessManager _processManager; + final AndroidSdk _androidSdk; + final Platform _platform; + final FileSystem _fileSystem; + final ProcessUtils _processUtils; + final AndroidConsoleSocketFactory _androidConsoleSocketFactory; + + final String? productID; + final String modelID; + final String? deviceCodeName; + + @override + // Wirelessly paired Android devices should have `adb-tls-connect` in the id. + // Source: https://android.googlesource.com/platform/packages/modules/adb/+/f4ba8d73079b99532069dbe888a58167b8723d6c/adb_mdns.h#30 + DeviceConnectionInterface get connectionInterface => + id.contains('adb-tls-connect') + ? DeviceConnectionInterface.wireless + : DeviceConnectionInterface.attached; + + late final Future> _properties = () async { + Map properties = {}; + + final List propCommand = adbCommandForDevice(['shell', 'getprop']); + _logger.printTrace(propCommand.join(' ')); + + try { + // We pass an encoding of latin1 so that we don't try and interpret the + // `adb shell getprop` result as UTF8. + final ProcessResult result = await _processManager.run( + propCommand, + stdoutEncoding: latin1, + stderrEncoding: latin1, + ); + if (result.exitCode == 0 || _allowHeapCorruptionOnWindows(result.exitCode, _platform)) { + properties = parseAdbDeviceProperties(result.stdout as String); + } else { + _logger.printError('Error ${result.exitCode} retrieving device properties for $name:'); + _logger.printError(result.stderr as String); + } + } on ProcessException catch (error) { + _logger.printError('Error retrieving device properties for $name: $error'); + } + return properties; + }(); + + Future _getProperty(String name) async { + return (await _properties)[name]; + } + + @override + late final Future isLocalEmulator = () async { + final String? hardware = await _getProperty('ro.hardware'); + _logger.printTrace('ro.hardware = $hardware'); + if (kKnownHardware.containsKey(hardware)) { + // Look for known hardware models. + return kKnownHardware[hardware] == HardwareType.emulator; + } + // Fall back to a best-effort heuristic-based approach. + final String? characteristics = await _getProperty('ro.build.characteristics'); + _logger.printTrace('ro.build.characteristics = $characteristics'); + return characteristics != null && characteristics.contains('emulator'); + }(); + + /// The unique identifier for the emulator that corresponds to this device, or + /// null if it is not an emulator. + /// + /// The ID returned matches that in the output of `flutter emulators`. Fetching + /// this name may require connecting to the device and if an error occurs null + /// will be returned. + @override + Future get emulatorId async { + if (!(await isLocalEmulator)) { + return null; + } + + // Emulators always have IDs in the format emulator-(port) where port is the + // Android Console port number. + final RegExp emulatorPortRegex = RegExp(r'emulator-(\d+)'); + + final Match? portMatch = emulatorPortRegex.firstMatch(id); + if (portMatch == null || portMatch.groupCount < 1) { + return null; + } + + const String host = 'localhost'; + final int port = int.parse(portMatch.group(1)!); + _logger.printTrace('Fetching avd name for $name via Android console on $host:$port'); + + try { + final Socket socket = await _androidConsoleSocketFactory(host, port); + final AndroidConsole console = AndroidConsole(socket); + + try { + await console + .connect() + .timeout(const Duration(seconds: 2), + onTimeout: () => throw TimeoutException('Connection timed out')); + + return await console + .getAvdName() + .timeout(const Duration(seconds: 2), + onTimeout: () => throw TimeoutException('"avd name" timed out')); + } finally { + console.destroy(); + } + } on Exception catch (e) { + _logger.printTrace('Failed to fetch avd name for emulator at $host:$port: $e'); + // If we fail to connect to the device, we should not fail so just return + // an empty name. This data is best-effort. + return null; + } + } + + @override + late final Future targetPlatform = () async { + // http://developer.android.com/ndk/guides/abis.html (x86, armeabi-v7a, ...) + switch (await _getProperty('ro.product.cpu.abi')) { + case 'arm64-v8a': + // Perform additional verification for 64 bit ABI. Some devices, + // like the Kindle Fire 8, misreport the abilist. We might not + // be able to retrieve this property, in which case we fall back + // to assuming 64 bit. + final String? abilist = await _getProperty('ro.product.cpu.abilist'); + if (abilist == null || abilist.contains('arm64-v8a')) { + return TargetPlatform.android_arm64; + } else { + return TargetPlatform.android_arm; + } + case 'x86_64': + return TargetPlatform.android_x64; + case 'x86': + return TargetPlatform.android_x86; + default: + return TargetPlatform.android_arm; + } + }(); + + @override + Future supportsRuntimeMode(BuildMode buildMode) async { + switch (await targetPlatform) { + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + return buildMode != BuildMode.jitRelease; + case TargetPlatform.android_x86: + return buildMode == BuildMode.debug; + case TargetPlatform.android: + case TargetPlatform.darwin: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.ios: + case TargetPlatform.linux_arm64: + case TargetPlatform.linux_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case TargetPlatform.windows_x64: + throw UnsupportedError('Invalid target platform for Android'); + } + } + + @override + Future get sdkNameAndVersion async => 'Android ${await _sdkVersion} (API ${await apiVersion})'; + + Future get _sdkVersion => _getProperty('ro.build.version.release'); + + @visibleForTesting + Future get apiVersion => _getProperty('ro.build.version.sdk'); + + AdbLogReader? _logReader; + AdbLogReader? _pastLogReader; + + List adbCommandForDevice(List args) { + return [_androidSdk.adbPath!, '-s', id, ...args]; + } + + Future runAdbCheckedAsync( + List params, { + String? workingDirectory, + bool allowReentrantFlutter = false, + }) async { + return _processUtils.run( + adbCommandForDevice(params), + throwOnError: true, + workingDirectory: workingDirectory, + allowReentrantFlutter: allowReentrantFlutter, + allowedFailures: (int value) => _allowHeapCorruptionOnWindows(value, _platform), + ); + } + + bool _isValidAdbVersion(String adbVersion) { + // Sample output: 'Android Debug Bridge version 1.0.31' + final Match? versionFields = RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion); + if (versionFields != null) { + final int majorVersion = int.parse(versionFields[1]!); + final int minorVersion = int.parse(versionFields[2]!); + final int patchVersion = int.parse(versionFields[3]!); + if (majorVersion > 1) { + return true; + } + if (majorVersion == 1 && minorVersion > 0) { + return true; + } + if (majorVersion == 1 && minorVersion == 0 && patchVersion >= 39) { + return true; + } + return false; + } + _logger.printError( + 'Unrecognized adb version string $adbVersion. Skipping version check.'); + return true; + } + + Future _checkForSupportedAdbVersion() async { + final String? adbPath = _androidSdk.adbPath; + if (adbPath == null) { + return false; + } + + try { + final RunResult adbVersion = await _processUtils.run( + [adbPath, 'version'], + throwOnError: true, + ); + if (_isValidAdbVersion(adbVersion.stdout)) { + return true; + } + _logger.printError('The ADB at "$adbPath" is too old; please install version 1.0.39 or later.'); + } on Exception catch (error, trace) { + _logger.printError('Error running ADB: $error', stackTrace: trace); + } + + return false; + } + + Future _checkForSupportedAndroidVersion() async { + final String? adbPath = _androidSdk.adbPath; + if (adbPath == null) { + return false; + } + try { + // If the server is automatically restarted, then we get irrelevant + // output lines like this, which we want to ignore: + // adb server is out of date. killing.. + // * daemon started successfully * + await _processUtils.run( + [adbPath, 'start-server'], + throwOnError: true, + ); + + // This has been reported to return null on some devices. In this case, + // assume the lowest supported API to still allow Flutter to run. + // Sample output: '22' + final String sdkVersion = await _getProperty('ro.build.version.sdk') + ?? minApiLevel.toString(); + + final int? sdkVersionParsed = int.tryParse(sdkVersion); + if (sdkVersionParsed == null) { + _logger.printError('Unexpected response from getprop: "$sdkVersion"'); + return false; + } + + if (sdkVersionParsed < minApiLevel) { + _logger.printError( + 'The Android version ($sdkVersion) on the target device is too old. Please ' + 'use a $minVersionName (version $minApiLevel / $minVersionText) device or later.'); + return false; + } + + return true; + } on Exception catch (e, stacktrace) { + _logger.printError('Unexpected failure from adb: $e'); + _logger.printError('Stacktrace: $stacktrace'); + return false; + } + } + + String _getDeviceSha1Path(AndroidApk apk) { + return '/data/local/tmp/sky.${apk.id}.sha1'; + } + + Future _getDeviceApkSha1(AndroidApk apk) async { + final RunResult result = await _processUtils.run( + adbCommandForDevice(['shell', 'cat', _getDeviceSha1Path(apk)])); + return result.stdout; + } + + String _getSourceSha1(AndroidApk apk) { + final File shaFile = _fileSystem.file('${apk.applicationPackage.path}.sha1'); + return shaFile.existsSync() ? shaFile.readAsStringSync() : ''; + } + + @override + String get name => modelID; + + @override + bool get supportsFlavors => true; + + @override + Future isAppInstalled( + ApplicationPackage app, { + String? userIdentifier, + }) async { + // This call takes 400ms - 600ms. + try { + final RunResult listOut = await runAdbCheckedAsync([ + 'shell', + 'pm', + 'list', + 'packages', + if (userIdentifier != null) + ...['--user', userIdentifier], + app.id, + ]); + return LineSplitter.split(listOut.stdout).contains('package:${app.id}'); + } on Exception catch (error) { + _logger.printTrace('$error'); + return false; + } + } + + @override + Future isLatestBuildInstalled(covariant AndroidApk app) async { + final String installedSha1 = await _getDeviceApkSha1(app); + return installedSha1.isNotEmpty && installedSha1 == _getSourceSha1(app); + } + + @override + Future installApp( + covariant AndroidApk app, { + String? userIdentifier, + }) async { + if (!await _adbIsValid) { + return false; + } + final bool wasInstalled = await isAppInstalled(app, userIdentifier: userIdentifier); + if (wasInstalled && await isLatestBuildInstalled(app)) { + _logger.printTrace('Latest build already installed.'); + return true; + } + _logger.printTrace('Installing APK.'); + if (await _installApp(app, userIdentifier: userIdentifier)) { + return true; + } + _logger.printTrace('Warning: Failed to install APK.'); + if (!wasInstalled) { + return false; + } + _logger.printStatus('Uninstalling old version...'); + if (!await uninstallApp(app, userIdentifier: userIdentifier)) { + _logger.printError('Error: Uninstalling old version failed.'); + return false; + } + if (!await _installApp(app, userIdentifier: userIdentifier)) { + _logger.printError('Error: Failed to install APK again.'); + return false; + } + return true; + } + + Future _installApp( + AndroidApk app, { + String? userIdentifier, + }) async { + if (!app.applicationPackage.existsSync()) { + _logger.printError('"${_fileSystem.path.relative(app.applicationPackage.path)}" does not exist.'); + return false; + } + + final Status status = _logger.startProgress( + 'Installing ${_fileSystem.path.relative(app.applicationPackage.path)}...', + ); + final RunResult installResult = await _processUtils.run( + adbCommandForDevice([ + 'install', + '-t', + '-r', + if (userIdentifier != null) + ...['--user', userIdentifier], + app.applicationPackage.path, + ])); + status.stop(); + // Some versions of adb exit with exit code 0 even on failure :( + // Parsing the output to check for failures. + final RegExp failureExp = RegExp(r'^Failure.*$', multiLine: true); + final String? failure = failureExp.stringMatch(installResult.stdout); + if (failure != null) { + _logger.printError('Package install error: $failure'); + return false; + } + if (installResult.exitCode != 0) { + if (installResult.stderr.contains('Bad user number')) { + _logger.printError('Error: User "$userIdentifier" not found. Run "adb shell pm list users" to see list of available identifiers.'); + } else { + _logger.printError('Error: ADB exited with exit code ${installResult.exitCode}'); + _logger.printError('$installResult'); + } + return false; + } + try { + await runAdbCheckedAsync([ + 'shell', 'echo', '-n', _getSourceSha1(app), '>', _getDeviceSha1Path(app), + ]); + } on ProcessException catch (error) { + _logger.printError('adb shell failed to write the SHA hash: $error.'); + return false; + } + return true; + } + + @override + Future uninstallApp( + ApplicationPackage app, { + String? userIdentifier, + }) async { + if (!await _adbIsValid) { + return false; + } + + String uninstallOut; + try { + final RunResult uninstallResult = await _processUtils.run( + adbCommandForDevice([ + 'uninstall', + if (userIdentifier != null) + ...['--user', userIdentifier], + app.id, + ]), + throwOnError: true, + ); + uninstallOut = uninstallResult.stdout; + } on Exception catch (error) { + _logger.printError('adb uninstall failed: $error'); + return false; + } + final RegExp failureExp = RegExp(r'^Failure.*$', multiLine: true); + final String? failure = failureExp.stringMatch(uninstallOut); + if (failure != null) { + _logger.printError('Package uninstall error: $failure'); + return false; + } + return true; + } + + // Whether the adb and Android versions are aligned. + late final Future _adbIsValid = () async { + return await _checkForSupportedAdbVersion() && await _checkForSupportedAndroidVersion(); + }(); + + AndroidApk? _package; + + @override + Future startApp( + AndroidApk? package, { + String? mainPath, + String? route, + required DebuggingOptions debuggingOptions, + Map platformArgs = const {}, + bool prebuiltApplication = false, + bool ipv6 = false, + String? userIdentifier, + }) async { + if (!await _adbIsValid) { + return LaunchResult.failed(); + } + + final TargetPlatform devicePlatform = await targetPlatform; + if (devicePlatform == TargetPlatform.android_x86 && + !debuggingOptions.buildInfo.isDebug) { + _logger.printError('Profile and release builds are only supported on ARM/x64 targets.'); + return LaunchResult.failed(); + } + + AndroidApk? builtPackage = package; + AndroidArch androidArch; + switch (devicePlatform) { + case TargetPlatform.android_arm: + androidArch = AndroidArch.armeabi_v7a; + case TargetPlatform.android_arm64: + androidArch = AndroidArch.arm64_v8a; + case TargetPlatform.android_x64: + androidArch = AndroidArch.x86_64; + case TargetPlatform.android_x86: + androidArch = AndroidArch.x86; + case TargetPlatform.android: + case TargetPlatform.darwin: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.ios: + case TargetPlatform.linux_arm64: + case TargetPlatform.linux_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case TargetPlatform.windows_x64: + _logger.printError('Android platforms are only supported.'); + return LaunchResult.failed(); + } + + if (!prebuiltApplication || _androidSdk.licensesAvailable && _androidSdk.latestVersion == null) { + _logger.printTrace('Building APK'); + final FlutterProject project = FlutterProject.current(); + await androidBuilder!.buildApk( + project: project, + target: mainPath ?? 'lib/main.dart', + androidBuildInfo: AndroidBuildInfo( + debuggingOptions.buildInfo, + targetArchs: [androidArch], + fastStart: debuggingOptions.fastStart, + multidexEnabled: (platformArgs['multidex'] as bool?) ?? false, + ), + ); + // Package has been built, so we can get the updated application ID and + // activity name from the .apk. + builtPackage = await ApplicationPackageFactory.instance! + .getPackageForPlatform(devicePlatform, buildInfo: debuggingOptions.buildInfo) as AndroidApk?; + } + // There was a failure parsing the android project information. + if (builtPackage == null) { + throwToolExit('Problem building Android application: see above error(s).'); + } + + _logger.printTrace("Stopping app '${builtPackage.name}' on $name."); + await stopApp(builtPackage, userIdentifier: userIdentifier); + + if (!await installApp(builtPackage, userIdentifier: userIdentifier)) { + return LaunchResult.failed(); + } + + final bool traceStartup = platformArgs['trace-startup'] as bool? ?? false; + ProtocolDiscovery? vmServiceDiscovery; + + if (debuggingOptions.debuggingEnabled) { + vmServiceDiscovery = ProtocolDiscovery.vmService( + // Avoid using getLogReader, which returns a singleton instance, because the + // VM Service discovery will dipose at the end. creating a new logger here allows + // logs to be surfaced normally during `flutter drive`. + await AdbLogReader.createLogReader( + this, + _processManager, + ), + portForwarder: portForwarder, + hostPort: debuggingOptions.hostVmServicePort, + devicePort: debuggingOptions.deviceVmServicePort, + ipv6: ipv6, + logger: _logger, + ); + } + + final String dartVmFlags = computeDartVmFlags(debuggingOptions); + final String? traceAllowlist = debuggingOptions.traceAllowlist; + final String? traceSkiaAllowlist = debuggingOptions.traceSkiaAllowlist; + final String? traceToFile = debuggingOptions.traceToFile; + final List cmd = [ + 'shell', 'am', 'start', + '-a', 'android.intent.action.MAIN', + '-c', 'android.intent.category.LAUNCHER', + '-f', '0x20000000', // FLAG_ACTIVITY_SINGLE_TOP + if (debuggingOptions.enableDartProfiling) + ...['--ez', 'enable-dart-profiling', 'true'], + if (traceStartup) + ...['--ez', 'trace-startup', 'true'], + if (route != null) + ...['--es', 'route', route], + if (debuggingOptions.enableSoftwareRendering) + ...['--ez', 'enable-software-rendering', 'true'], + if (debuggingOptions.skiaDeterministicRendering) + ...['--ez', 'skia-deterministic-rendering', 'true'], + if (debuggingOptions.traceSkia) + ...['--ez', 'trace-skia', 'true'], + if (traceAllowlist != null) + ...['--es', 'trace-allowlist', traceAllowlist], + if (traceSkiaAllowlist != null) + ...['--es', 'trace-skia-allowlist', traceSkiaAllowlist], + if (debuggingOptions.traceSystrace) + ...['--ez', 'trace-systrace', 'true'], + if (traceToFile != null) + ...['--es', 'trace-to-file', traceToFile], + if (debuggingOptions.endlessTraceBuffer) + ...['--ez', 'endless-trace-buffer', 'true'], + if (debuggingOptions.dumpSkpOnShaderCompilation) + ...['--ez', 'dump-skp-on-shader-compilation', 'true'], + if (debuggingOptions.cacheSkSL) + ...['--ez', 'cache-sksl', 'true'], + if (debuggingOptions.purgePersistentCache) + ...['--ez', 'purge-persistent-cache', 'true'], + if (debuggingOptions.enableImpeller == ImpellerStatus.enabled) + ...['--ez', 'enable-impeller', 'true'], + if (debuggingOptions.enableImpeller == ImpellerStatus.disabled) + ...['--ez', 'enable-impeller', 'false'], + if (debuggingOptions.enableVulkanValidation) + ...['--ez', 'enable-vulkan-validation', 'true'], + if (debuggingOptions.debuggingEnabled) ...[ + if (debuggingOptions.buildInfo.isDebug) ...[ + ...['--ez', 'enable-checked-mode', 'true'], + ...['--ez', 'verify-entry-points', 'true'], + ], + if (debuggingOptions.startPaused) + ...['--ez', 'start-paused', 'true'], + if (debuggingOptions.disableServiceAuthCodes) + ...['--ez', 'disable-service-auth-codes', 'true'], + if (dartVmFlags.isNotEmpty) + ...['--es', 'dart-flags', dartVmFlags], + if (debuggingOptions.useTestFonts) + ...['--ez', 'use-test-fonts', 'true'], + if (debuggingOptions.verboseSystemLogs) + ...['--ez', 'verbose-logging', 'true'], + if (userIdentifier != null) + ...['--user', userIdentifier], + ], + builtPackage.launchActivity, + ]; + final String result = (await runAdbCheckedAsync(cmd)).stdout; + // This invocation returns 0 even when it fails. + if (result.contains('Error: ')) { + _logger.printError(result.trim(), wrap: false); + return LaunchResult.failed(); + } + + _package = builtPackage; + if (!debuggingOptions.debuggingEnabled) { + return LaunchResult.succeeded(); + } + + // Wait for the service protocol port here. This will complete once the + // device has printed "VM Service is listening on...". + _logger.printTrace('Waiting for VM Service port to be available...'); + try { + Uri? vmServiceUri; + if (debuggingOptions.buildInfo.isDebug || debuggingOptions.buildInfo.isProfile) { + vmServiceUri = await vmServiceDiscovery?.uri; + if (vmServiceUri == null) { + _logger.printError( + 'Error waiting for a debug connection: ' + 'The log reader stopped unexpectedly', + ); + return LaunchResult.failed(); + } + } + return LaunchResult.succeeded(vmServiceUri: vmServiceUri); + } on Exception catch (error) { + _logger.printError('Error waiting for a debug connection: $error'); + return LaunchResult.failed(); + } finally { + await vmServiceDiscovery?.cancel(); + } + } + + @override + bool get supportsHotReload => true; + + @override + bool get supportsHotRestart => true; + + @override + bool get supportsFastStart => true; + + @override + Future stopApp( + ApplicationPackage? app, { + String? userIdentifier, + }) async { + if (app == null) { + return false; + } + final List command = adbCommandForDevice([ + 'shell', + 'am', + 'force-stop', + if (userIdentifier != null) + ...['--user', userIdentifier], + app.id, + ]); + return _processUtils.stream(command).then( + (int exitCode) => exitCode == 0 || _allowHeapCorruptionOnWindows(exitCode, _platform)); + } + + @override + Future queryMemoryInfo() async { + final AndroidApk? package = _package; + if (package == null) { + _logger.printError('Android package unknown, skipping dumpsys meminfo.'); + return const MemoryInfo.empty(); + } + final RunResult runResult = await _processUtils.run(adbCommandForDevice([ + 'shell', + 'dumpsys', + 'meminfo', + package.id, + '-d', + ])); + + if (runResult.exitCode != 0) { + return const MemoryInfo.empty(); + } + return parseMeminfoDump(runResult.stdout); + } + + @override + void clearLogs() { + _processUtils.runSync(adbCommandForDevice(['logcat', '-c'])); + } + + @override + FutureOr getLogReader({ + ApplicationPackage? app, + bool includePastLogs = false, + }) async { + // The Android log reader isn't app-specific. The `app` parameter isn't used. + if (includePastLogs) { + return _pastLogReader ??= await AdbLogReader.createLogReader( + this, + _processManager, + includePastLogs: true, + ); + } else { + return _logReader ??= await AdbLogReader.createLogReader( + this, + _processManager, + ); + } + } + + @override + late final DevicePortForwarder? portForwarder = () { + final String? adbPath = _androidSdk.adbPath; + if (adbPath == null) { + return null; + } + return AndroidDevicePortForwarder( + processManager: _processManager, + logger: _logger, + deviceId: id, + adbPath: adbPath, + ); + }(); + + static final RegExp _timeRegExp = RegExp(r'^\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}', multiLine: true); + + /// Return the most recent timestamp in the Android log or [null] if there is + /// no available timestamp. The format can be passed to logcat's -T option. + @visibleForTesting + Future lastLogcatTimestamp() async { + RunResult output; + try { + output = await runAdbCheckedAsync([ + 'shell', '-x', 'logcat', '-v', 'time', '-t', '1', + ]); + } on Exception catch (error) { + _logger.printError('Failed to extract the most recent timestamp from the Android log: $error.'); + return null; + } + final Match? timeMatch = _timeRegExp.firstMatch(output.stdout); + return timeMatch?.group(0); + } + + @override + bool isSupported() => true; + + @override + bool get supportsScreenshot => true; + + @override + Future takeScreenshot(File outputFile) async { + const String remotePath = '/data/local/tmp/flutter_screenshot.png'; + await runAdbCheckedAsync(['shell', 'screencap', '-p', remotePath]); + await _processUtils.run( + adbCommandForDevice(['pull', remotePath, outputFile.path]), + throwOnError: true, + ); + await runAdbCheckedAsync(['shell', 'rm', remotePath]); + } + + @override + bool isSupportedForProject(FlutterProject flutterProject) { + return flutterProject.android.existsSync(); + } + + @override + Future dispose() async { + _logReader?._stop(); + _pastLogReader?._stop(); + } +} + +Map parseAdbDeviceProperties(String str) { + final Map properties = {}; + final RegExp propertyExp = RegExp(r'\[(.*?)\]: \[(.*?)\]'); + for (final Match match in propertyExp.allMatches(str)) { + properties[match.group(1)!] = match.group(2)!; + } + return properties; +} + +/// Process the dumpsys info formatted in a table-like structure. +/// +/// Currently this only pulls information from the "App Summary" subsection. +/// +/// Example output: +/// +/// ``` +/// Applications Memory Usage (in Kilobytes): +/// Uptime: 441088659 Realtime: 521464097 +/// +/// ** MEMINFO in pid 16141 [io.flutter.demo.gallery] ** +/// Pss Private Private SwapPss Heap Heap Heap +/// Total Dirty Clean Dirty Size Alloc Free +/// ------ ------ ------ ------ ------ ------ ------ +/// Native Heap 8648 8620 0 16 20480 12403 8076 +/// Dalvik Heap 547 424 40 18 2628 1092 1536 +/// Dalvik Other 464 464 0 0 +/// Stack 496 496 0 0 +/// Ashmem 2 0 0 0 +/// Gfx dev 212 204 0 0 +/// Other dev 48 0 48 0 +/// .so mmap 10770 708 9372 25 +/// .apk mmap 240 0 0 0 +/// .ttf mmap 35 0 32 0 +/// .dex mmap 2205 4 1172 0 +/// .oat mmap 64 0 0 0 +/// .art mmap 4228 3848 24 2 +/// Other mmap 20713 4 20704 0 +/// GL mtrack 2380 2380 0 0 +/// Unknown 43971 43968 0 1 +/// TOTAL 95085 61120 31392 62 23108 13495 9612 +/// +/// App Summary +/// Pss(KB) +/// ------ +/// Java Heap: 4296 +/// Native Heap: 8620 +/// Code: 11288 +/// Stack: 496 +/// Graphics: 2584 +/// Private Other: 65228 +/// System: 2573 +/// +/// TOTAL: 95085 TOTAL SWAP PSS: 62 +/// +/// Objects +/// Views: 9 ViewRootImpl: 1 +/// AppContexts: 3 Activities: 1 +/// Assets: 4 AssetManagers: 3 +/// Local Binders: 10 Proxy Binders: 18 +/// Parcel memory: 6 Parcel count: 24 +/// Death Recipients: 0 OpenSSL Sockets: 0 +/// WebViews: 0 +/// +/// SQL +/// MEMORY_USED: 0 +/// PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0 +/// ... +/// ``` +/// +/// For more information, see https://developer.android.com/studio/command-line/dumpsys. +@visibleForTesting +AndroidMemoryInfo parseMeminfoDump(String input) { + final AndroidMemoryInfo androidMemoryInfo = AndroidMemoryInfo(); + + final List lines = input.split('\n'); + + final String timelineData = lines.firstWhere((String line) => + line.startsWith('${AndroidMemoryInfo._kUpTimeKey}: ')); + final List times = timelineData.trim().split('${AndroidMemoryInfo._kRealTimeKey}:'); + androidMemoryInfo.realTime = int.tryParse(times.last.trim()) ?? 0; + + lines + .skipWhile((String line) => !line.contains('App Summary')) + .takeWhile((String line) => !line.contains('TOTAL')) + .where((String line) => line.contains(':')) + .forEach((String line) { + final List sections = line.trim().split(':'); + final String key = sections.first.trim(); + final int value = int.tryParse(sections.last.trim()) ?? 0; + switch (key) { + case AndroidMemoryInfo._kJavaHeapKey: + androidMemoryInfo.javaHeap = value; + case AndroidMemoryInfo._kNativeHeapKey: + androidMemoryInfo.nativeHeap = value; + case AndroidMemoryInfo._kCodeKey: + androidMemoryInfo.code = value; + case AndroidMemoryInfo._kStackKey: + androidMemoryInfo.stack = value; + case AndroidMemoryInfo._kGraphicsKey: + androidMemoryInfo.graphics = value; + case AndroidMemoryInfo._kPrivateOtherKey: + androidMemoryInfo.privateOther = value; + case AndroidMemoryInfo._kSystemKey: + androidMemoryInfo.system = value; + } + }); + return androidMemoryInfo; +} + +/// Android specific implementation of memory info. +class AndroidMemoryInfo extends MemoryInfo { + static const String _kUpTimeKey = 'Uptime'; + static const String _kRealTimeKey = 'Realtime'; + static const String _kJavaHeapKey = 'Java Heap'; + static const String _kNativeHeapKey = 'Native Heap'; + static const String _kCodeKey = 'Code'; + static const String _kStackKey = 'Stack'; + static const String _kGraphicsKey = 'Graphics'; + static const String _kPrivateOtherKey = 'Private Other'; + static const String _kSystemKey = 'System'; + static const String _kTotalKey = 'Total'; + + // Realtime is time since the system was booted includes deep sleep. Clock + // is monotonic, and ticks even when the CPU is in power saving modes. + int realTime = 0; + + // Each measurement has KB as a unit. + int javaHeap = 0; + int nativeHeap = 0; + int code = 0; + int stack = 0; + int graphics = 0; + int privateOther = 0; + int system = 0; + + @override + Map toJson() { + return { + 'platform': 'Android', + _kRealTimeKey: realTime, + _kJavaHeapKey: javaHeap, + _kNativeHeapKey: nativeHeap, + _kCodeKey: code, + _kStackKey: stack, + _kGraphicsKey: graphics, + _kPrivateOtherKey: privateOther, + _kSystemKey: system, + _kTotalKey: javaHeap + nativeHeap + code + stack + graphics + privateOther + system, + }; + } +} + +/// A log reader that logs from `adb logcat`. +class AdbLogReader extends DeviceLogReader { + AdbLogReader._(this._adbProcess, this.name); + + @visibleForTesting + factory AdbLogReader.test(Process adbProcess, String name) = AdbLogReader._; + + /// Create a new [AdbLogReader] from an [AndroidDevice] instance. + static Future createLogReader( + AndroidDevice device, + ProcessManager processManager, { + bool includePastLogs = false, + }) async { + // logcat -T is not supported on Android releases before Lollipop. + const int kLollipopVersionCode = 21; + final int? apiVersion = (String? v) { + // If the API version string isn't found, conservatively assume that the + // version is less recent than the one we're looking for. + return v == null ? kLollipopVersionCode - 1 : int.tryParse(v); + }(await device.apiVersion); + + // Start the adb logcat process and filter the most recent logs since `lastTimestamp`. + // Some devices (notably LG) will only output logcat via shell + // https://github.com/flutter/flutter/issues/51853 + final List args = [ + 'shell', + '-x', + 'logcat', + '-v', + 'time', + ]; + + // If past logs are included then filter for 'flutter' logs only. + if (includePastLogs) { + args.addAll(['-s', 'flutter']); + } else if (apiVersion != null && apiVersion >= kLollipopVersionCode) { + // Otherwise, filter for logs appearing past the present. + // '-T 0` means the timestamp of the logcat command invocation. + final String? lastLogcatTimestamp = await device.lastLogcatTimestamp(); + args.addAll([ + '-T', + if (lastLogcatTimestamp != null) "'$lastLogcatTimestamp'" else '0', + ]); + } + final Process process = await processManager.start(device.adbCommandForDevice(args)); + return AdbLogReader._(process, device.name); + } + + final Process _adbProcess; + + @override + final String name; + + late final StreamController _linesController = StreamController.broadcast( + onListen: _start, + onCancel: _stop, + ); + + @override + Stream get logLines => _linesController.stream; + + void _start() { + // We expect logcat streams to occasionally contain invalid utf-8, + // see: https://github.com/flutter/flutter/pull/8864. + const Utf8Decoder decoder = Utf8Decoder(reportErrors: false); + _adbProcess.stdout.transform(decoder) + .transform(const LineSplitter()) + .listen(_onLine); + _adbProcess.stderr.transform(decoder) + .transform(const LineSplitter()) + .listen(_onLine); + unawaited(_adbProcess.exitCode.whenComplete(() { + if (_linesController.hasListener) { + _linesController.close(); + } + })); + } + + // 'W/ActivityManager(pid): ' + static final RegExp _logFormat = RegExp(r'^[VDIWEF]\/.*?\(\s*(\d+)\):\s'); + + static final List _allowedTags = [ + RegExp(r'^[VDIWEF]\/flutter[^:]*:\s+', caseSensitive: false), + RegExp(r'^[IE]\/DartVM[^:]*:\s+'), + RegExp(r'^[WEF]\/AndroidRuntime:\s+'), + RegExp(r'^[WEF]\/AndroidRuntime\([0-9]+\):\s+'), + RegExp(r'^[WEF]\/ActivityManager:\s+.*(\bflutter\b|\bdomokit\b|\bsky\b)'), + RegExp(r'^[WEF]\/System\.err:\s+'), + RegExp(r'^[F]\/[\S^:]+:\s+'), + ]; + + // E/SurfaceSyncer(22636): Failed to find sync for id=9 + // Some versions of Android spew this out. It is inactionable to the end user + // and causes no problems for the application. + static final RegExp _surfaceSyncerSpam = RegExp(r'^E/SurfaceSyncer\(\s*\d+\): Failed to find sync for id=\d+'); + + // 'F/libc(pid): Fatal signal 11' + static final RegExp _fatalLog = RegExp(r'^F\/libc\s*\(\s*\d+\):\sFatal signal (\d+)'); + + // 'I/DEBUG(pid): ...' + static final RegExp _tombstoneLine = RegExp(r'^[IF]\/DEBUG\s*\(\s*\d+\):\s(.+)$'); + + // 'I/DEBUG(pid): Tombstone written to: ' + static final RegExp _tombstoneTerminator = RegExp(r'^Tombstone written to:\s'); + + // we default to true in case none of the log lines match + bool _acceptedLastLine = true; + + // Whether a fatal crash is happening or not. + // During a fatal crash only lines from the crash are accepted, the rest are + // dropped. + bool _fatalCrash = false; + + // The format of the line is controlled by the '-v' parameter passed to + // adb logcat. We are currently passing 'time', which has the format: + // mm-dd hh:mm:ss.milliseconds Priority/Tag( PID): .... + void _onLine(String line) { + // This line might be processed after the subscription is closed but before + // adb stops streaming logs. + if (_linesController.isClosed) { + return; + } + final Match? timeMatch = AndroidDevice._timeRegExp.firstMatch(line); + if (timeMatch == null || line.length == timeMatch.end) { + _acceptedLastLine = false; + return; + } + // Chop off the time. + line = line.substring(timeMatch.end + 1); + final Match? logMatch = _logFormat.firstMatch(line); + if (logMatch != null) { + bool acceptLine = false; + + if (_fatalCrash) { + // While a fatal crash is going on, only accept lines from the crash + // Otherwise the crash log in the console may get interrupted + + final Match? fatalMatch = _tombstoneLine.firstMatch(line); + + if (fatalMatch != null) { + acceptLine = true; + + line = fatalMatch[1]!; + + if (_tombstoneTerminator.hasMatch(line)) { + // Hit crash terminator, stop logging the crash info + _fatalCrash = false; + } + } + } else if (appPid != null && int.parse(logMatch.group(1)!) == appPid) { + acceptLine = !_surfaceSyncerSpam.hasMatch(line); + + if (_fatalLog.hasMatch(line)) { + // Hit fatal signal, app is now crashing + _fatalCrash = true; + } + } else { + // Filter on approved names and levels. + acceptLine = _allowedTags.any((RegExp re) => re.hasMatch(line)); + } + + if (acceptLine) { + _acceptedLastLine = true; + _linesController.add(line); + return; + } + _acceptedLastLine = false; + } else if (line == '--------- beginning of system' || + line == '--------- beginning of main') { + // hide the ugly adb logcat log boundaries at the start + _acceptedLastLine = false; + } else { + // If it doesn't match the log pattern at all, then pass it through if we + // passed the last matching line through. It might be a multiline message. + if (_acceptedLastLine) { + _linesController.add(line); + return; + } + } + } + + void _stop() { + _linesController.close(); + _adbProcess.kill(); + } + + @override + void dispose() { + _stop(); + } +} + +/// A [DevicePortForwarder] implemented for Android devices that uses adb. +class AndroidDevicePortForwarder extends DevicePortForwarder { + AndroidDevicePortForwarder({ + required ProcessManager processManager, + required Logger logger, + required String deviceId, + required String adbPath, + }) : _deviceId = deviceId, + _adbPath = adbPath, + _logger = logger, + _processUtils = ProcessUtils(logger: logger, processManager: processManager); + + final String _deviceId; + final String _adbPath; + final Logger _logger; + final ProcessUtils _processUtils; + + static int? _extractPort(String portString) { + return int.tryParse(portString.trim()); + } + + @override + List get forwardedPorts { + final List ports = []; + + String stdout; + try { + stdout = _processUtils.runSync( + [ + _adbPath, + '-s', + _deviceId, + 'forward', + '--list', + ], + throwOnError: true, + ).stdout.trim(); + } on ProcessException catch (error) { + _logger.printError('Failed to list forwarded ports: $error.'); + return ports; + } + + final List lines = LineSplitter.split(stdout).toList(); + for (final String line in lines) { + if (!line.startsWith(_deviceId)) { + continue; + } + final List splitLine = line.split('tcp:'); + + // Sanity check splitLine. + if (splitLine.length != 3) { + continue; + } + + // Attempt to extract ports. + final int? hostPort = _extractPort(splitLine[1]); + final int? devicePort = _extractPort(splitLine[2]); + + // Failed, skip. + if (hostPort == null || devicePort == null) { + continue; + } + + ports.add(ForwardedPort(hostPort, devicePort)); + } + + return ports; + } + + @override + Future forward(int devicePort, { int? hostPort }) async { + hostPort ??= 0; + final RunResult process = await _processUtils.run( + [ + _adbPath, + '-s', + _deviceId, + 'forward', + 'tcp:$hostPort', + 'tcp:$devicePort', + ], + throwOnError: true, + ); + + if (process.stderr.isNotEmpty) { + process.throwException('adb returned error:\n${process.stderr}'); + } + + if (process.exitCode != 0) { + if (process.stdout.isNotEmpty) { + process.throwException('adb returned error:\n${process.stdout}'); + } + process.throwException('adb failed without a message'); + } + + if (hostPort == 0) { + if (process.stdout.isEmpty) { + process.throwException('adb did not report forwarded port'); + } + hostPort = int.tryParse(process.stdout); + if (hostPort == null) { + process.throwException('adb returned invalid port number:\n${process.stdout}'); + } + } else { + // stdout may be empty or the port we asked it to forward, though it's + // not documented (or obvious) what triggers each case. + // + // Observations are: + // - On MacOS it's always empty when Flutter spawns the process, but + // - On MacOS it prints the port number when run from the terminal, unless + // the port is already forwarded, when it also prints nothing. + // - On ChromeOS, the port appears to be printed even when Flutter spawns + // the process + // + // To cover all cases, we accept the output being either empty or exactly + // the port number, but treat any other output as probably being an error + // message. + if (process.stdout.isNotEmpty && process.stdout.trim() != '$hostPort') { + process.throwException('adb returned error:\n${process.stdout}'); + } + } + + return hostPort!; + } + + @override + Future unforward(ForwardedPort forwardedPort) async { + final String tcpLine = 'tcp:${forwardedPort.hostPort}'; + final RunResult runResult = await _processUtils.run( + [ + _adbPath, + '-s', + _deviceId, + 'forward', + '--remove', + tcpLine, + ], + ); + if (runResult.exitCode == 0) { + return; + } + _logger.printError('Failed to unforward port: $runResult'); + } + + @override + Future dispose() async { + for (final ForwardedPort port in forwardedPorts) { + await unforward(port); + } + } +} + +// In platform tools 29.0.0 adb.exe seems to be ending with this heap +// corruption error code on seemingly successful termination. Ignore +// this error on windows. +bool _allowHeapCorruptionOnWindows(int exitCode, Platform platform) { + return exitCode == -1073740940 && platform.isWindows; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device_discovery.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device_discovery.dart new file mode 100644 index 0000000000000000000000000000000000000000..e41d0a061dfac35a3084996391417cf89d53b5e5 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device_discovery.dart @@ -0,0 +1,199 @@ +// 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:process/process.dart'; + +import '../base/common.dart'; +import '../base/file_system.dart'; +import '../base/io.dart'; +import '../base/logger.dart'; +import '../base/platform.dart'; +import '../base/process.dart'; +import '../base/user_messages.dart'; +import '../device.dart'; +import 'adb.dart'; +import 'android_device.dart'; +import 'android_sdk.dart'; +import 'android_workflow.dart'; + +/// Device discovery for Android physical devices and emulators. +/// +/// This class primarily delegates to the `adb` command line tool provided by +/// the Android SDK to discover instances of connected android devices. +/// +/// See also: +/// * [AndroidDevice], the type of discovered device. +class AndroidDevices extends PollingDeviceDiscovery { + AndroidDevices({ + required AndroidWorkflow androidWorkflow, + required ProcessManager processManager, + required Logger logger, + AndroidSdk? androidSdk, + required FileSystem fileSystem, + required Platform platform, + required UserMessages userMessages, + }) : _androidWorkflow = androidWorkflow, + _androidSdk = androidSdk, + _processUtils = ProcessUtils( + logger: logger, + processManager: processManager, + ), + _processManager = processManager, + _logger = logger, + _fileSystem = fileSystem, + _platform = platform, + _userMessages = userMessages, + super('Android devices'); + + final AndroidWorkflow _androidWorkflow; + final ProcessUtils _processUtils; + final AndroidSdk? _androidSdk; + final ProcessManager _processManager; + final Logger _logger; + final FileSystem _fileSystem; + final Platform _platform; + final UserMessages _userMessages; + + @override + bool get supportsPlatform => _androidWorkflow.appliesToHostPlatform; + + @override + bool get canListAnything => _androidWorkflow.canListDevices; + + @override + Future> pollingGetDevices({ Duration? timeout }) async { + if (_doesNotHaveAdb()) { + return []; + } + String text; + try { + text = (await _processUtils.run([_androidSdk!.adbPath!, 'devices', '-l'], + throwOnError: true, + )).stdout.trim(); + } on ProcessException catch (exception) { + throwToolExit( + 'Unable to run "adb", check your Android SDK installation and ' + '$kAndroidHome environment variable: ${exception.executable}', + ); + } + final List devices = []; + _parseADBDeviceOutput( + text, + devices: devices, + ); + return devices; + } + + @override + Future> getDiagnostics() async { + if (_doesNotHaveAdb()) { + return []; + } + + final RunResult result = await _processUtils.run([_androidSdk!.adbPath!, 'devices', '-l']); + if (result.exitCode != 0) { + return []; + } + final List diagnostics = []; + _parseADBDeviceOutput( + result.stdout, + diagnostics: diagnostics, + ); + return diagnostics; + } + + bool _doesNotHaveAdb() { + return _androidSdk == null || + _androidSdk.adbPath == null || + !_processManager.canRun(_androidSdk.adbPath); + } + + // 015d172c98400a03 device usb:340787200X product:nakasi model:Nexus_7 device:grouper + static final RegExp _kDeviceRegex = RegExp(r'^(\S+)\s+(\S+)(.*)'); + + /// Parse the given `adb devices` output in [text], and fill out the given list + /// of devices and possible device issue diagnostics. Either argument can be null, + /// in which case information for that parameter won't be populated. + void _parseADBDeviceOutput( + String text, { + List? devices, + List? diagnostics, + }) { + // Check for error messages from adb + if (!text.contains('List of devices')) { + diagnostics?.add(text); + return; + } + + for (final String line in text.trim().split('\n')) { + // Skip lines like: * daemon started successfully * + if (line.startsWith('* daemon ')) { + continue; + } + + // Skip lines about adb server and client version not matching + if (line.startsWith(RegExp(r'adb server (version|is out of date)'))) { + diagnostics?.add(line); + continue; + } + + if (line.startsWith('List of devices')) { + continue; + } + + if (_kDeviceRegex.hasMatch(line)) { + final Match match = _kDeviceRegex.firstMatch(line)!; + + final String deviceID = match[1]!; + final String deviceState = match[2]!; + String? rest = match[3]; + + final Map info = {}; + if (rest != null && rest.isNotEmpty) { + rest = rest.trim(); + for (final String data in rest.split(' ')) { + if (data.contains(':')) { + final List fields = data.split(':'); + info[fields[0]] = fields[1]; + } + } + } + + final String? model = info['model']; + if (model != null) { + info['model'] = cleanAdbDeviceName(model); + } + + if (deviceState == 'unauthorized') { + diagnostics?.add( + 'Device $deviceID is not authorized.\n' + 'You might need to check your device for an authorization dialog.' + ); + } else if (deviceState == 'offline') { + diagnostics?.add('Device $deviceID is offline.'); + } else { + devices?.add(AndroidDevice( + deviceID, + productID: info['product'], + modelID: info['model'] ?? deviceID, + deviceCodeName: info['device'], + androidSdk: _androidSdk!, + fileSystem: _fileSystem, + logger: _logger, + platform: _platform, + processManager: _processManager, + )); + } + } else { + diagnostics?.add( + 'Unexpected failure parsing device information from adb output:\n' + '$line\n' + '${_userMessages.flutterToolBugInstructions}'); + } + } + } + + @override + List get wellKnownIds => const []; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_emulator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_emulator.dart new file mode 100644 index 0000000000000000000000000000000000000000..bb92bb5be9aba1db7db41d714f1eb00415f96428 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_emulator.dart @@ -0,0 +1,232 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import '../base/file_system.dart'; +import '../base/io.dart'; +import '../base/logger.dart'; +import '../base/process.dart'; +import '../convert.dart'; +import '../device.dart'; +import '../emulator.dart'; +import 'android_sdk.dart'; +import 'android_workflow.dart'; + +class AndroidEmulators extends EmulatorDiscovery { + AndroidEmulators({ + AndroidSdk? androidSdk, + required AndroidWorkflow androidWorkflow, + required FileSystem fileSystem, + required Logger logger, + required ProcessManager processManager, + }) : _androidSdk = androidSdk, + _androidWorkflow = androidWorkflow, + _fileSystem = fileSystem, + _logger = logger, + _processManager = processManager, + _processUtils = ProcessUtils(logger: logger, processManager: processManager); + + final AndroidWorkflow _androidWorkflow; + final AndroidSdk? _androidSdk; + final FileSystem _fileSystem; + final Logger _logger; + final ProcessManager _processManager; + final ProcessUtils _processUtils; + + @override + bool get supportsPlatform => true; + + @override + bool get canListAnything => _androidWorkflow.canListEmulators; + + @override + bool get canLaunchAnything => _androidWorkflow.canListEmulators + && _androidSdk?.getAvdManagerPath() != null; + + @override + Future> get emulators => _getEmulatorAvds(); + + /// Return the list of available emulator AVDs. + Future> _getEmulatorAvds() async { + final String? emulatorPath = _androidSdk?.emulatorPath; + if (emulatorPath == null) { + return []; + } + + final String listAvdsOutput = (await _processUtils.run( + [emulatorPath, '-list-avds'])).stdout.trim(); + + final List emulators = []; + _extractEmulatorAvdInfo(listAvdsOutput, emulators); + return emulators; + } + + /// Parse the given `emulator -list-avds` output in [text], and fill out the given list + /// of emulators by reading information from the relevant ini files. + void _extractEmulatorAvdInfo(String text, List emulators) { + for (final String id in text.trim().split('\n').where((String l) => l != '')) { + emulators.add(_loadEmulatorInfo(id)); + } + } + + AndroidEmulator _loadEmulatorInfo(String id) { + id = id.trim(); + final String? avdPath = _androidSdk?.getAvdPath(); + final AndroidEmulator androidEmulatorWithoutProperties = AndroidEmulator( + id, + processManager: _processManager, + logger: _logger, + androidSdk: _androidSdk, + ); + if (avdPath == null) { + return androidEmulatorWithoutProperties; + } + final File iniFile = _fileSystem.file(_fileSystem.path.join(avdPath, '$id.ini')); + if (!iniFile.existsSync()) { + return androidEmulatorWithoutProperties; + } + final Map ini = parseIniLines(iniFile.readAsLinesSync()); + final String? path = ini['path']; + if (path == null) { + return androidEmulatorWithoutProperties; + } + final File configFile = _fileSystem.file(_fileSystem.path.join(path, 'config.ini')); + if (!configFile.existsSync()) { + return androidEmulatorWithoutProperties; + } + final Map properties = parseIniLines(configFile.readAsLinesSync()); + return AndroidEmulator( + id, + properties: properties, + processManager: _processManager, + logger: _logger, + androidSdk: _androidSdk, + ); + } +} + +class AndroidEmulator extends Emulator { + AndroidEmulator(String id, { + Map? properties, + required Logger logger, + AndroidSdk? androidSdk, + required ProcessManager processManager, + }) : _properties = properties, + _logger = logger, + _androidSdk = androidSdk, + _processUtils = ProcessUtils(logger: logger, processManager: processManager), + super(id, properties != null && properties.isNotEmpty); + + final Map? _properties; + final Logger _logger; + final ProcessUtils _processUtils; + final AndroidSdk? _androidSdk; + + // Android Studio uses the ID with underscores replaced with spaces + // for the name if displayname is not set so we do the same. + @override + String get name => _prop('avd.ini.displayname') ?? id.replaceAll('_', ' ').trim(); + + @override + String? get manufacturer => _prop('hw.device.manufacturer'); + + @override + Category get category => Category.mobile; + + @override + PlatformType get platformType => PlatformType.android; + + String? _prop(String name) => _properties != null ? _properties[name] : null; + + @override + Future launch({@visibleForTesting Duration? startupDuration, bool coldBoot = false}) async { + final String? emulatorPath = _androidSdk?.emulatorPath; + if (emulatorPath == null) { + throw Exception('Emulator is missing from the Android SDK'); + } + final List command = [ + emulatorPath, + '-avd', + id, + if (coldBoot) + '-no-snapshot-load', + ]; + final Process process = await _processUtils.start(command); + + // Record output from the emulator process. + final List stdoutList = []; + final List stderrList = []; + final StreamSubscription stdoutSubscription = process.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(stdoutList.add); + final StreamSubscription stderrSubscription = process.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(stderrList.add); + final Future stdioFuture = Future.wait(>[ + stdoutSubscription.asFuture(), + stderrSubscription.asFuture(), + ]); + + // The emulator continues running on success, so we don't wait for the + // process to complete before continuing. However, if the process fails + // after the startup phase (3 seconds), then we only echo its output if + // its error code is non-zero and its stderr is non-empty. + bool earlyFailure = true; + unawaited(process.exitCode.then((int status) async { + if (status == 0) { + _logger.printTrace('The Android emulator exited successfully'); + return; + } + // Make sure the process' stdout and stderr are drained. + await stdioFuture; + unawaited(stdoutSubscription.cancel()); + unawaited(stderrSubscription.cancel()); + if (stdoutList.isNotEmpty) { + _logger.printTrace('Android emulator stdout:'); + stdoutList.forEach(_logger.printTrace); + } + if (!earlyFailure && stderrList.isEmpty) { + _logger.printStatus('The Android emulator exited with code $status'); + return; + } + final String when = earlyFailure ? 'during startup' : 'after startup'; + _logger.printError('The Android emulator exited with code $status $when'); + _logger.printError('Android emulator stderr:'); + stderrList.forEach(_logger.printError); + _logger.printError('Address these issues and try again.'); + })); + + // Wait a few seconds for the emulator to start. + await Future.delayed(startupDuration ?? const Duration(seconds: 3)); + earlyFailure = false; + return; + } +} + + +@visibleForTesting +Map parseIniLines(List contents) { + final Map results = {}; + + final Iterable> properties = contents + .map((String l) => l.trim()) + // Strip blank lines/comments + .where((String l) => l != '' && !l.startsWith('#')) + // Discard anything that isn't simple name=value + .where((String l) => l.contains('=')) + // Split into name/value + .map>((String l) => l.split('=')); + + for (final List property in properties) { + results[property[0].trim()] = property[1].trim(); + } + + return results; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_sdk.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_sdk.dart new file mode 100644 index 0000000000000000000000000000000000000000..03f525db4ff58b891db41e24d66551cb61af86c9 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_sdk.dart @@ -0,0 +1,623 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../base/common.dart'; +import '../base/config.dart'; +import '../base/file_system.dart'; +import '../base/platform.dart'; +import '../base/process.dart'; +import '../base/version.dart'; +import '../convert.dart'; +import '../globals.dart' as globals; +import 'java.dart'; + +// ANDROID_SDK_ROOT is deprecated. +// See https://developer.android.com/studio/command-line/variables.html#envar +const String kAndroidSdkRoot = 'ANDROID_SDK_ROOT'; +const String kAndroidHome = 'ANDROID_HOME'; + +// No official environment variable for the NDK root is documented: +// https://developer.android.com/tools/variables#envar +// The follow three seem to be most commonly used. +const String kAndroidNdkHome = 'ANDROID_NDK_HOME'; +const String kAndroidNdkPath = 'ANDROID_NDK_PATH'; +const String kAndroidNdkRoot = 'ANDROID_NDK_ROOT'; + +final RegExp _numberedAndroidPlatformRe = RegExp(r'^android-([0-9]+)$'); +final RegExp _sdkVersionRe = RegExp(r'^ro.build.version.sdk=([0-9]+)$'); + +// Android SDK layout: + +// $ANDROID_HOME/platform-tools/adb + +// $ANDROID_HOME/build-tools/19.1.0/aapt, dx, zipalign +// $ANDROID_HOME/build-tools/22.0.1/aapt +// $ANDROID_HOME/build-tools/23.0.2/aapt +// $ANDROID_HOME/build-tools/24.0.0-preview/aapt +// $ANDROID_HOME/build-tools/25.0.2/apksigner + +// $ANDROID_HOME/platforms/android-22/android.jar +// $ANDROID_HOME/platforms/android-23/android.jar +// $ANDROID_HOME/platforms/android-N/android.jar +class AndroidSdk { + AndroidSdk(this.directory, { + Java? java, + FileSystem? fileSystem, + }): _java = java { + reinitialize(fileSystem: fileSystem); + } + + /// The Android SDK root directory. + final Directory directory; + + final Java? _java; + + List _sdkVersions = []; + AndroidSdkVersion? _latestVersion; + + /// Whether the `cmdline-tools` directory exists in the Android SDK. + /// + /// This is required to use the newest SDK manager which only works with + /// the newer JDK. + bool get cmdlineToolsAvailable => directory.childDirectory('cmdline-tools').existsSync(); + + /// Whether the `platform-tools` or `cmdline-tools` directory exists in the Android SDK. + /// + /// It is possible to have an Android SDK folder that is missing this with + /// the expectation that it will be downloaded later, e.g. by gradle or the + /// sdkmanager. The [licensesAvailable] property should be used to determine + /// whether the licenses are at least possibly accepted. + bool get platformToolsAvailable => cmdlineToolsAvailable + || directory.childDirectory('platform-tools').existsSync(); + + /// Whether the `licenses` directory exists in the Android SDK. + /// + /// The existence of this folder normally indicates that the SDK licenses have + /// been accepted, e.g. via the sdkmanager, Android Studio, or by copying them + /// from another workstation such as in CI scenarios. If these files are valid + /// gradle or the sdkmanager will be able to download and use other parts of + /// the SDK on demand. + bool get licensesAvailable => directory.childDirectory('licenses').existsSync(); + + static AndroidSdk? locateAndroidSdk() { + String? findAndroidHomeDir() { + String? androidHomeDir; + if (globals.config.containsKey('android-sdk')) { + androidHomeDir = globals.config.getValue('android-sdk') as String?; + } else if (globals.platform.environment.containsKey(kAndroidHome)) { + androidHomeDir = globals.platform.environment[kAndroidHome]; + } else if (globals.platform.environment.containsKey(kAndroidSdkRoot)) { + androidHomeDir = globals.platform.environment[kAndroidSdkRoot]; + } else if (globals.platform.isLinux) { + if (globals.fsUtils.homeDirPath != null) { + androidHomeDir = globals.fs.path.join( + globals.fsUtils.homeDirPath!, + 'Android', + 'Sdk', + ); + } + } else if (globals.platform.isMacOS) { + if (globals.fsUtils.homeDirPath != null) { + androidHomeDir = globals.fs.path.join( + globals.fsUtils.homeDirPath!, + 'Library', + 'Android', + 'sdk', + ); + } + } else if (globals.platform.isWindows) { + if (globals.fsUtils.homeDirPath != null) { + androidHomeDir = globals.fs.path.join( + globals.fsUtils.homeDirPath!, + 'AppData', + 'Local', + 'Android', + 'sdk', + ); + } + } + + if (androidHomeDir != null) { + if (validSdkDirectory(androidHomeDir)) { + return androidHomeDir; + } + if (validSdkDirectory(globals.fs.path.join(androidHomeDir, 'sdk'))) { + return globals.fs.path.join(androidHomeDir, 'sdk'); + } + } + + // in build-tools/$version/aapt + final List aaptBins = globals.os.whichAll('aapt'); + for (File aaptBin in aaptBins) { + // Make sure we're using the aapt from the SDK. + aaptBin = globals.fs.file(aaptBin.resolveSymbolicLinksSync()); + final String dir = aaptBin.parent.parent.parent.path; + if (validSdkDirectory(dir)) { + return dir; + } + } + + // in platform-tools/adb + final List adbBins = globals.os.whichAll('adb'); + for (File adbBin in adbBins) { + // Make sure we're using the adb from the SDK. + adbBin = globals.fs.file(adbBin.resolveSymbolicLinksSync()); + final String dir = adbBin.parent.parent.path; + if (validSdkDirectory(dir)) { + return dir; + } + } + + return null; + } + + final String? androidHomeDir = findAndroidHomeDir(); + if (androidHomeDir == null) { + // No dice. + globals.printTrace('Unable to locate an Android SDK.'); + return null; + } + + return AndroidSdk(globals.fs.directory(androidHomeDir)); + } + + static bool validSdkDirectory(String dir) { + return sdkDirectoryHasLicenses(dir) || sdkDirectoryHasPlatformTools(dir); + } + + static bool sdkDirectoryHasPlatformTools(String dir) { + return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'platform-tools')); + } + + static bool sdkDirectoryHasLicenses(String dir) { + return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'licenses')); + } + + List get sdkVersions => _sdkVersions; + + AndroidSdkVersion? get latestVersion => _latestVersion; + + late final String? adbPath = getPlatformToolsPath(globals.platform.isWindows ? 'adb.exe' : 'adb'); + + String? get emulatorPath => getEmulatorPath(); + + String? get avdManagerPath => getAvdManagerPath(); + + /// Locate the path for storing AVD emulator images. Returns null if none found. + String? getAvdPath() { + final String? avdHome = globals.platform.environment['ANDROID_AVD_HOME']; + final String? home = globals.platform.environment['HOME']; + final List searchPaths = [ + if (avdHome != null) + avdHome, + if (home != null) + globals.fs.path.join(home, '.android', 'avd'), + ]; + + if (globals.platform.isWindows) { + final String? homeDrive = globals.platform.environment['HOMEDRIVE']; + final String? homePath = globals.platform.environment['HOMEPATH']; + + if (homeDrive != null && homePath != null) { + // Can't use path.join for HOMEDRIVE/HOMEPATH + // https://github.com/dart-lang/path/issues/37 + final String home = homeDrive + homePath; + searchPaths.add(globals.fs.path.join(home, '.android', 'avd')); + } + } + + for (final String searchPath in searchPaths) { + if (globals.fs.directory(searchPath).existsSync()) { + return searchPath; + } + } + return null; + } + + Directory get _platformsDir => directory.childDirectory('platforms'); + + Iterable get _platforms { + Iterable platforms = []; + if (_platformsDir.existsSync()) { + platforms = _platformsDir + .listSync() + .whereType(); + } + return platforms; + } + + /// Validate the Android SDK. This returns an empty list if there are no + /// issues; otherwise, it returns a list of issues found. + List validateSdkWellFormed() { + if (adbPath == null || !globals.processManager.canRun(adbPath)) { + return ['Android SDK file not found: ${adbPath ?? 'adb'}.']; + } + + if (sdkVersions.isEmpty || latestVersion == null) { + final StringBuffer msg = StringBuffer('No valid Android SDK platforms found in ${_platformsDir.path}.'); + if (_platforms.isEmpty) { + msg.write(' Directory was empty.'); + } else { + msg.write(' Candidates were:\n'); + msg.write(_platforms + .map((Directory dir) => ' - ${dir.basename}') + .join('\n')); + } + return [msg.toString()]; + } + + return latestVersion!.validateSdkWellFormed(); + } + + String? getPlatformToolsPath(String binaryName) { + final File cmdlineToolsBinary = directory.childDirectory('cmdline-tools').childFile(binaryName); + if (cmdlineToolsBinary.existsSync()) { + return cmdlineToolsBinary.path; + } + final File platformToolBinary = directory.childDirectory('platform-tools').childFile(binaryName); + if (platformToolBinary.existsSync()) { + return platformToolBinary.path; + } + return null; + } + + String? getEmulatorPath() { + final String binaryName = globals.platform.isWindows ? 'emulator.exe' : 'emulator'; + // Emulator now lives inside "emulator" but used to live inside "tools" so + // try both. + final List searchFolders = ['emulator', 'tools']; + for (final String folder in searchFolders) { + final File file = directory.childDirectory(folder).childFile(binaryName); + if (file.existsSync()) { + return file.path; + } + } + return null; + } + + String? getCmdlineToolsPath(String binaryName, {bool skipOldTools = false}) { + // First look for the latest version of the command-line tools + final File cmdlineToolsLatestBinary = directory + .childDirectory('cmdline-tools') + .childDirectory('latest') + .childDirectory('bin') + .childFile(binaryName); + if (cmdlineToolsLatestBinary.existsSync()) { + return cmdlineToolsLatestBinary.path; + } + + // Next look for the highest version of the command-line tools + final Directory cmdlineToolsDir = directory.childDirectory('cmdline-tools'); + if (cmdlineToolsDir.existsSync()) { + final List cmdlineTools = cmdlineToolsDir + .listSync() + .whereType() + .map((Directory subDirectory) { + try { + return Version.parse(subDirectory.basename); + } on Exception { + return null; + } + }) + .whereType() + .toList(); + cmdlineTools.sort(); + + for (final Version cmdlineToolsVersion in cmdlineTools.reversed) { + final File cmdlineToolsBinary = directory + .childDirectory('cmdline-tools') + .childDirectory(cmdlineToolsVersion.toString()) + .childDirectory('bin') + .childFile(binaryName); + if (cmdlineToolsBinary.existsSync()) { + return cmdlineToolsBinary.path; + } + } + } + if (skipOldTools) { + return null; + } + + // Finally fallback to the old SDK tools + final File toolsBinary = directory.childDirectory('tools').childDirectory('bin').childFile(binaryName); + if (toolsBinary.existsSync()) { + return toolsBinary.path; + } + + return null; + } + + String? getAvdManagerPath() => getCmdlineToolsPath(globals.platform.isWindows ? 'avdmanager.bat' : 'avdmanager'); + + /// From https://developer.android.com/ndk/guides/other_build_systems. + static const Map _llvmHostDirectoryName = { + 'macos': 'darwin-x86_64', + 'linux': 'linux-x86_64', + 'windows': 'windows-x86_64', + }; + + /// Locates the binary path for an NDK binary. + /// + /// The order of resolution is as follows: + /// + /// 1. If [globals.config] defines an `'android-ndk'` use that. + /// 2. If the environment variable `ANDROID_NDK_HOME` is defined, use that. + /// 3. If the environment variable `ANDROID_NDK_PATH` is defined, use that. + /// 4. If the environment variable `ANDROID_NDK_ROOT` is defined, use that. + /// 5. Look for the default install location inside the Android SDK: + /// [directory]/ndk/\/. If multiple versions exist, use the + /// newest. + String? getNdkBinaryPath( + String binaryName, { + Platform? platform, + Config? config, + }) { + platform ??= globals.platform; + config ??= globals.config; + Directory? findAndroidNdkHomeDir() { + String? androidNdkHomeDir; + if (config!.containsKey('android-ndk')) { + androidNdkHomeDir = config.getValue('android-ndk') as String?; + } else if (platform!.environment.containsKey(kAndroidNdkHome)) { + androidNdkHomeDir = platform.environment[kAndroidNdkHome]; + } else if (platform.environment.containsKey(kAndroidNdkPath)) { + androidNdkHomeDir = platform.environment[kAndroidNdkPath]; + } else if (platform.environment.containsKey(kAndroidNdkRoot)) { + androidNdkHomeDir = platform.environment[kAndroidNdkRoot]; + } + if (androidNdkHomeDir != null) { + return directory.fileSystem.directory(androidNdkHomeDir); + } + + // Look for the default install location of the NDK inside the Android + // SDK when installed through `sdkmanager` or Android studio. + final Directory ndk = directory.childDirectory('ndk'); + if (!ndk.existsSync()) { + return null; + } + final List ndkVersions = ndk + .listSync() + .map((FileSystemEntity entity) { + try { + return Version.parse(entity.basename); + } on Exception { + return null; + } + }) + .whereType() + .toList() + // Use latest NDK first. + ..sort((Version a, Version b) => -a.compareTo(b)); + if (ndkVersions.isEmpty) { + return null; + } + return ndk.childDirectory(ndkVersions.first.toString()); + } + + final Directory? androidNdkHomeDir = findAndroidNdkHomeDir(); + if (androidNdkHomeDir == null) { + return null; + } + final File executable = androidNdkHomeDir + .childDirectory('toolchains') + .childDirectory('llvm') + .childDirectory('prebuilt') + .childDirectory(_llvmHostDirectoryName[platform.operatingSystem]!) + .childDirectory('bin') + .childFile(binaryName); + if (executable.existsSync()) { + // LLVM missing in this NDK version. + return executable.path; + } + return null; + } + + String? getNdkClangPath({Platform? platform, Config? config}) { + platform ??= globals.platform; + return getNdkBinaryPath( + platform.isWindows ? 'clang.exe' : 'clang', + platform: platform, + config: config, + ); + } + + String? getNdkArPath({Platform? platform, Config? config}) { + platform ??= globals.platform; + return getNdkBinaryPath( + platform.isWindows ? 'llvm-ar.exe' : 'llvm-ar', + platform: platform, + config: config, + ); + } + + String? getNdkLdPath({Platform? platform, Config? config}) { + platform ??= globals.platform; + return getNdkBinaryPath( + platform.isWindows ? 'ld.lld.exe' : 'ld.lld', + platform: platform, + config: config, + ); + } + + /// Sets up various paths used internally. + /// + /// This method should be called in a case where the tooling may have updated + /// SDK artifacts, such as after running a gradle build. + void reinitialize({FileSystem? fileSystem}) { + List buildTools = []; // 19.1.0, 22.0.1, ... + + final Directory buildToolsDir = directory.childDirectory('build-tools'); + if (buildToolsDir.existsSync()) { + buildTools = buildToolsDir + .listSync() + .map((FileSystemEntity entity) { + try { + return Version.parse(entity.basename); + } on Exception { + return null; + } + }) + .whereType() + .toList(); + } + + // Match up platforms with the best corresponding build-tools. + _sdkVersions = _platforms.map((Directory platformDir) { + final String platformName = platformDir.basename; + int platformVersion; + + try { + final Match? numberedVersion = _numberedAndroidPlatformRe.firstMatch(platformName); + if (numberedVersion != null) { + platformVersion = int.parse(numberedVersion.group(1)!); + } else { + final String buildProps = platformDir.childFile('build.prop').readAsStringSync(); + final Iterable versionMatches = const LineSplitter() + .convert(buildProps) + .map(_sdkVersionRe.firstMatch) + .whereType(); + + if (versionMatches.isEmpty) { + return null; + } + + final String? versionString = versionMatches.first.group(1); + if (versionString == null) { + return null; + } + platformVersion = int.parse(versionString); + } + } on Exception { + return null; + } + + Version? buildToolsVersion = Version.primary(buildTools.where((Version version) { + return version.major == platformVersion; + }).toList()); + + buildToolsVersion ??= Version.primary(buildTools); + + if (buildToolsVersion == null) { + return null; + } + + return AndroidSdkVersion._( + this, + sdkLevel: platformVersion, + platformName: platformName, + buildToolsVersion: buildToolsVersion, + fileSystem: fileSystem ?? globals.fs, + ); + }).whereType().toList(); + + _sdkVersions.sort(); + + _latestVersion = _sdkVersions.isEmpty ? null : _sdkVersions.last; + } + + /// Returns the filesystem path of the Android SDK manager tool. + String? get sdkManagerPath { + final String executable = globals.platform.isWindows + ? 'sdkmanager.bat' + : 'sdkmanager'; + final String? path = getCmdlineToolsPath(executable, skipOldTools: true); + if (path != null) { + return path; + } + return null; + } + + /// Returns the version of the Android SDK manager tool or null if not found. + String? get sdkManagerVersion { + if (sdkManagerPath == null || !globals.processManager.canRun(sdkManagerPath)) { + throwToolExit( + 'Android sdkmanager not found. Update to the latest Android SDK and ensure that ' + 'the cmdline-tools are installed to resolve this.' + ); + } + final RunResult result = globals.processUtils.runSync( + [sdkManagerPath!, '--version'], + environment: _java?.environment, + ); + if (result.exitCode != 0) { + globals.printTrace('sdkmanager --version failed: exitCode: ${result.exitCode} stdout: ${result.stdout} stderr: ${result.stderr}'); + return null; + } + return result.stdout.trim(); + } + + @override + String toString() => 'AndroidSdk: $directory'; +} + +class AndroidSdkVersion implements Comparable { + AndroidSdkVersion._( + this.sdk, { + required this.sdkLevel, + required this.platformName, + required this.buildToolsVersion, + required FileSystem fileSystem, + }) : _fileSystem = fileSystem; + + final AndroidSdk sdk; + final int sdkLevel; + final String platformName; + final Version buildToolsVersion; + + final FileSystem _fileSystem; + + String get buildToolsVersionName => buildToolsVersion.toString(); + + String get androidJarPath => getPlatformsPath('android.jar'); + + /// Return the path to the android application package tool. + /// + /// This is used to dump the xml in order to launch built android applications. + /// + /// See also: + /// * [AndroidApk.fromApk], which depends on this to determine application identifiers. + String get aaptPath => getBuildToolsPath('aapt'); + + List validateSdkWellFormed() { + final String? existsAndroidJarPath = _exists(androidJarPath); + if (existsAndroidJarPath != null) { + return [existsAndroidJarPath]; + } + + final String? canRunAaptPath = _canRun(aaptPath); + if (canRunAaptPath != null) { + return [canRunAaptPath]; + } + + return []; + } + + String getPlatformsPath(String itemName) { + return sdk.directory.childDirectory('platforms').childDirectory(platformName).childFile(itemName).path; + } + + String getBuildToolsPath(String binaryName) { + return sdk.directory.childDirectory('build-tools').childDirectory(buildToolsVersionName).childFile(binaryName).path; + } + + @override + int compareTo(AndroidSdkVersion other) => sdkLevel - other.sdkLevel; + + @override + String toString() => '[${sdk.directory}, SDK version $sdkLevel, build-tools $buildToolsVersionName]'; + + String? _exists(String path) { + if (!_fileSystem.isFileSync(path)) { + return 'Android SDK file not found: $path.'; + } + return null; + } + + String? _canRun(String path) { + if (!globals.processManager.canRun(path)) { + return 'Android SDK file not found: $path.'; + } + return null; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio.dart new file mode 100644 index 0000000000000000000000000000000000000000..72d987583bdfe88b766e2274b5e6936c4da524f8 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio.dart @@ -0,0 +1,579 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../base/common.dart'; +import '../base/file_system.dart'; +import '../base/io.dart'; +import '../base/process.dart'; +import '../base/utils.dart'; +import '../base/version.dart'; +import '../convert.dart'; +import '../globals.dart' as globals; +import '../ios/plist_parser.dart'; +import 'android_studio_validator.dart'; + +// Android Studio layout: + +// Linux/Windows: +// $HOME/.AndroidStudioX.Y/system/.home +// $HOME/.cache/Google/AndroidStudioX.Y/.home + +// macOS: +// /Applications/Android Studio.app/Contents/ +// $HOME/Applications/Android Studio.app/Contents/ + +// Match Android Studio >= 4.1 base folder (AndroidStudio*.*) +// and < 4.1 (.AndroidStudio*.*) +final RegExp _dotHomeStudioVersionMatcher = + RegExp(r'^\.?(AndroidStudio[^\d]*)([\d.]+)'); + +class AndroidStudio { + /// A [version] value of null represents an unknown version. + AndroidStudio( + this.directory, { + this.version, + this.configuredPath, + this.studioAppName = 'AndroidStudio', + this.presetPluginsPath, + }) { + _initAndValidate(); + } + + static AndroidStudio? fromMacOSBundle( + String bundlePath, { + String? configuredPath, + }) { + final String studioPath = globals.fs.path.join(bundlePath, 'Contents'); + final String plistFile = globals.fs.path.join(studioPath, 'Info.plist'); + final Map plistValues = globals.plistParser.parseFile(plistFile); + // If we've found a JetBrainsToolbox wrapper, ignore it. + if (plistValues.containsKey('JetBrainsToolboxApp')) { + return null; + } + + final String? versionString = plistValues[PlistParser.kCFBundleShortVersionStringKey] as String?; + + Version? version; + if (versionString != null) { + version = Version.parse(versionString); + } + + String? pathsSelectorValue; + final Map? jvmOptions = castStringKeyedMap(plistValues['JVMOptions']); + if (jvmOptions != null) { + final Map? jvmProperties = castStringKeyedMap(jvmOptions['Properties']); + if (jvmProperties != null) { + pathsSelectorValue = jvmProperties['idea.paths.selector'] as String; + } + } + + final int? major = version?.major; + final int? minor = version?.minor; + String? presetPluginsPath; + final String? homeDirPath = globals.fsUtils.homeDirPath; + if (homeDirPath != null && pathsSelectorValue != null) { + if (major != null && major >= 4 && minor != null && minor >= 1) { + presetPluginsPath = globals.fs.path.join( + homeDirPath, + 'Library', + 'Application Support', + 'Google', + pathsSelectorValue, + ); + } else { + presetPluginsPath = globals.fs.path.join( + homeDirPath, + 'Library', + 'Application Support', + pathsSelectorValue, + ); + } + } + return AndroidStudio( + studioPath, + version: version, + presetPluginsPath: presetPluginsPath, + configuredPath: configuredPath, + ); + } + + static AndroidStudio? fromHomeDot(Directory homeDotDir) { + final Match? versionMatch = + _dotHomeStudioVersionMatcher.firstMatch(homeDotDir.basename); + if (versionMatch?.groupCount != 2) { + return null; + } + final Version? version = Version.parse(versionMatch![2]); + final String? studioAppName = versionMatch[1]; + if (studioAppName == null || version == null) { + return null; + } + + final int major = version.major; + final int minor = version.minor; + + // The install path is written in a .home text file, + // it location is in /.home for Android Studio >= 4.1 + // and /system/.home for Android Studio < 4.1 + String dotHomeFilePath; + + if (major >= 4 && minor >= 1) { + dotHomeFilePath = globals.fs.path.join(homeDotDir.path, '.home'); + } else { + dotHomeFilePath = + globals.fs.path.join(homeDotDir.path, 'system', '.home'); + } + + String? installPath; + + try { + installPath = globals.fs.file(dotHomeFilePath).readAsStringSync(); + } on Exception { + // ignored, installPath will be null, which is handled below + } + + if (installPath != null && globals.fs.isDirectorySync(installPath)) { + return AndroidStudio( + installPath, + version: version, + studioAppName: studioAppName, + ); + } + return null; + } + + final String directory; + final String studioAppName; + + /// The version of Android Studio. + /// + /// A null value represents an unknown version. + final Version? version; + + final String? configuredPath; + final String? presetPluginsPath; + + String? _javaPath; + bool _isValid = false; + final List _validationMessages = []; + + /// The path of the JDK bundled with Android Studio. + /// + /// This will be null if the bundled JDK could not be found or run. + /// + /// If you looking to invoke the java binary or add it to the system + /// environment variables, consider using the [Java] class instead. + String? get javaPath => _javaPath; + + bool get isValid => _isValid; + + String? get pluginsPath { + if (presetPluginsPath != null) { + return presetPluginsPath!; + } + + // TODO(andrewkolos): This is a bug. We shouldn't treat an unknown + // version as equivalent to 0.0. + // See https://github.com/flutter/flutter/issues/121468. + final int major = version?.major ?? 0; + final int minor = version?.minor ?? 0; + final String? homeDirPath = globals.fsUtils.homeDirPath; + if (homeDirPath == null) { + return null; + } + if (globals.platform.isMacOS) { + /// plugin path of Android Studio has been changed after version 4.1. + if (major >= 4 && minor >= 1) { + return globals.fs.path.join( + homeDirPath, + 'Library', + 'Application Support', + 'Google', + 'AndroidStudio$major.$minor', + ); + } else { + return globals.fs.path.join( + homeDirPath, + 'Library', + 'Application Support', + 'AndroidStudio$major.$minor', + ); + } + } else { + // JetBrains Toolbox write plugins here + final String toolboxPluginsPath = '$directory.plugins'; + + if (globals.fs.directory(toolboxPluginsPath).existsSync()) { + return toolboxPluginsPath; + } + + if (major >= 4 && minor >= 1 && + globals.platform.isLinux) { + return globals.fs.path.join( + homeDirPath, + '.local', + 'share', + 'Google', + '$studioAppName$major.$minor', + ); + } + + return globals.fs.path.join( + homeDirPath, + '.$studioAppName$major.$minor', + 'config', + 'plugins', + ); + } + } + + List get validationMessages => _validationMessages; + + /// Locates the newest, valid version of Android Studio. + /// + /// In the case that `--android-studio-dir` is configured, the version of + /// Android Studio found at that location is always returned, even if it is + /// invalid. + static AndroidStudio? latestValid() { + final Directory? configuredStudioDir = _configuredDir(); + + // Find all available Studio installations. + final List studios = allInstalled(); + if (studios.isEmpty) { + return null; + } + + final AndroidStudio? manuallyConfigured = studios + .where((AndroidStudio studio) => studio.configuredPath != null && + configuredStudioDir != null && + _pathsAreEqual(studio.configuredPath!, configuredStudioDir.path)) + .firstOrNull; + + if (manuallyConfigured != null) { + return manuallyConfigured; + } + + AndroidStudio? newest; + for (final AndroidStudio studio in studios.where((AndroidStudio s) => s.isValid)) { + if (newest == null) { + newest = studio; + continue; + } + + // We prefer installs with known versions. + if (studio.version != null && newest.version == null) { + newest = studio; + } else if (studio.version != null && newest.version != null && + studio.version! > newest.version!) { + newest = studio; + } else if (studio.version == null && newest.version == null && + studio.directory.compareTo(newest.directory) > 0) { + newest = studio; + } + } + + return newest; + } + + static List allInstalled() => + globals.platform.isMacOS ? _allMacOS() : _allLinuxOrWindows(); + + static List _allMacOS() { + final List candidatePaths = []; + + void checkForStudio(String path) { + if (!globals.fs.isDirectorySync(path)) { + return; + } + try { + final Iterable directories = globals.fs + .directory(path) + .listSync(followLinks: false) + .whereType(); + for (final Directory directory in directories) { + final String name = directory.basename; + // An exact match, or something like 'Android Studio 3.0 Preview.app'. + if (name.startsWith('Android Studio') && name.endsWith('.app')) { + candidatePaths.add(directory); + } else if (!directory.path.endsWith('.app')) { + checkForStudio(directory.path); + } + } + } on Exception catch (e) { + globals.printTrace('Exception while looking for Android Studio: $e'); + } + } + + checkForStudio('/Applications'); + final String? homeDirPath = globals.fsUtils.homeDirPath; + if (homeDirPath != null) { + checkForStudio(globals.fs.path.join( + homeDirPath, + 'Applications', + )); + } + + Directory? configuredStudioDir = _configuredDir(); + if (configuredStudioDir != null) { + if (configuredStudioDir.basename == 'Contents') { + configuredStudioDir = configuredStudioDir.parent; + } + if (!candidatePaths + .any((FileSystemEntity e) => _pathsAreEqual(e.path, configuredStudioDir!.path))) { + candidatePaths.add(configuredStudioDir); + } + } + + // Query Spotlight for unexpected installation locations. + String spotlightQueryResult = ''; + try { + final ProcessResult spotlightResult = globals.processManager.runSync([ + 'mdfind', + // com.google.android.studio, com.google.android.studio-EAP + 'kMDItemCFBundleIdentifier="com.google.android.studio*"', + ]); + spotlightQueryResult = spotlightResult.stdout as String; + } on ProcessException { + // The Spotlight query is a nice-to-have, continue checking known installation locations. + } + for (final String studioPath in LineSplitter.split(spotlightQueryResult)) { + final Directory appBundle = globals.fs.directory(studioPath); + if (!candidatePaths.any((FileSystemEntity e) => e.path == studioPath)) { + candidatePaths.add(appBundle); + } + } + + return candidatePaths + .map((FileSystemEntity e) { + if (configuredStudioDir == null) { + return AndroidStudio.fromMacOSBundle(e.path); + } + + return AndroidStudio.fromMacOSBundle( + e.path, + configuredPath: _pathsAreEqual(configuredStudioDir.path, e.path) ? configuredStudioDir.path : null, + ); + }) + .whereType() + .toList(); + } + + static List _allLinuxOrWindows() { + final List studios = []; + + bool alreadyFoundStudioAt(String path, { Version? newerThan }) { + return studios.any((AndroidStudio studio) { + if (studio.directory != path) { + return false; + } + if (newerThan != null) { + if (studio.version == null) { + return false; + } + return studio.version!.compareTo(newerThan) >= 0; + } + return true; + }); + } + + // Read all $HOME/.AndroidStudio*/system/.home + // or $HOME/.cache/Google/AndroidStudio*/.home files. + // There may be several pointing to the same installation, + // so we grab only the latest one. + final String? homeDirPath = globals.fsUtils.homeDirPath; + + if (homeDirPath != null && globals.fs.directory(homeDirPath).existsSync()) { + final Directory homeDir = globals.fs.directory(homeDirPath); + + final List directoriesToSearch = [homeDir]; + + // >=4.1 has new install location at $HOME/.cache/Google + final String cacheDirPath = + globals.fs.path.join(homeDirPath, '.cache', 'Google'); + + if (globals.fs.isDirectorySync(cacheDirPath)) { + directoriesToSearch.add(globals.fs.directory(cacheDirPath)); + } + + final List entities = []; + + for (final Directory baseDir in directoriesToSearch) { + final Iterable directories = + baseDir.listSync(followLinks: false).whereType(); + entities.addAll(directories.where((Directory directory) => + _dotHomeStudioVersionMatcher.hasMatch(directory.basename))); + } + + for (final Directory entity in entities) { + final AndroidStudio? studio = AndroidStudio.fromHomeDot(entity); + if (studio != null && !alreadyFoundStudioAt(studio.directory, newerThan: studio.version)) { + studios.removeWhere((AndroidStudio other) => other.directory == studio.directory); + studios.add(studio); + } + } + } + + // Discover Android Studio > 4.1 + if (globals.platform.isWindows && globals.platform.environment.containsKey('LOCALAPPDATA')) { + final Directory cacheDir = globals.fs.directory(globals.fs.path.join(globals.platform.environment['LOCALAPPDATA']!, 'Google')); + if (!cacheDir.existsSync()) { + return studios; + } + for (final Directory dir in cacheDir.listSync().whereType()) { + final String name = globals.fs.path.basename(dir.path); + AndroidStudioValidator.idToTitle.forEach((String id, String title) { + if (name.startsWith(id)) { + final String version = name.substring(id.length); + String? installPath; + + try { + installPath = globals.fs.file(globals.fs.path.join(dir.path, '.home')).readAsStringSync(); + } on FileSystemException { + // ignored + } + if (installPath != null && globals.fs.isDirectorySync(installPath)) { + final AndroidStudio studio = AndroidStudio( + installPath, + version: Version.parse(version), + studioAppName: title, + ); + if (!alreadyFoundStudioAt(studio.directory, newerThan: studio.version)) { + studios.removeWhere((AndroidStudio other) => _pathsAreEqual(other.directory, studio.directory)); + studios.add(studio); + } + } + } + }); + } + } + + final String? configuredStudioDir = globals.config.getValue('android-studio-dir') as String?; + if (configuredStudioDir != null) { + final AndroidStudio? matchingAlreadyFoundInstall = studios + .where((AndroidStudio other) => _pathsAreEqual(configuredStudioDir, other.directory)) + .firstOrNull; + if (matchingAlreadyFoundInstall != null) { + studios.remove(matchingAlreadyFoundInstall); + studios.add( + AndroidStudio( + configuredStudioDir, + configuredPath: configuredStudioDir, + version: matchingAlreadyFoundInstall.version, + ), + ); + } else { + studios.add(AndroidStudio(configuredStudioDir, + configuredPath: configuredStudioDir)); + } + } + + if (globals.platform.isLinux) { + void checkWellKnownPath(String path) { + if (globals.fs.isDirectorySync(path) && !alreadyFoundStudioAt(path)) { + studios.add(AndroidStudio(path)); + } + } + + // Add /opt/android-studio and $HOME/android-studio, if they exist. + checkWellKnownPath('/opt/android-studio'); + checkWellKnownPath('${globals.fsUtils.homeDirPath}/android-studio'); + } + return studios; + } + + /// Gets the Android Studio install directory set by the user, if it is configured. + /// + /// The returned [Directory], if not null, is guaranteed to have existed during + /// this function's execution. + static Directory? _configuredDir() { + final String? configuredPath = globals.config.getValue('android-studio-dir') as String?; + if (configuredPath == null) { + return null; + } + final Directory result = globals.fs.directory(configuredPath); + + bool? configuredStudioPathExists; + String? exceptionMessage; + try { + configuredStudioPathExists = result.existsSync(); + } on FileSystemException catch (e) { + exceptionMessage = e.toString(); + } + + if (configuredStudioPathExists == false || exceptionMessage != null) { + throwToolExit(''' +Could not find the Android Studio installation at the manually configured path "$configuredPath". +${exceptionMessage == null ? '' : 'Encountered exception: $exceptionMessage\n\n'} +Please verify that the path is correct and update it by running this command: flutter config --android-studio-dir '' +To have flutter search for Android Studio installations automatically, remove +the configured path by running this command: flutter config --android-studio-dir +'''); + } + + return result; + } + + static String? extractStudioPlistValueWithMatcher(String plistValue, RegExp keyMatcher) { + return keyMatcher.stringMatch(plistValue)?.split('=').last.trim().replaceAll('"', ''); + } + + void _initAndValidate() { + _isValid = false; + _validationMessages.clear(); + + if (configuredPath != null) { + _validationMessages.add('android-studio-dir = $configuredPath'); + } + + if (!globals.fs.isDirectorySync(directory)) { + _validationMessages.add('Android Studio not found at $directory'); + return; + } + + final String javaPath; + if (globals.platform.isMacOS) { + if (version != null && version!.major < 2020) { + javaPath = globals.fs.path.join(directory, 'jre', 'jdk', 'Contents', 'Home'); + } else if (version != null && version!.major < 2022) { + javaPath = globals.fs.path.join(directory, 'jre', 'Contents', 'Home'); + // See https://github.com/flutter/flutter/issues/125246 for more context. + } else { + javaPath = globals.fs.path.join(directory, 'jbr', 'Contents', 'Home'); + } + } else { + if (version != null && version!.major < 2022) { + javaPath = globals.fs.path.join(directory, 'jre'); + } else { + javaPath = globals.fs.path.join(directory, 'jbr'); + } + } + final String javaExecutable = globals.fs.path.join(javaPath, 'bin', 'java'); + if (!globals.processManager.canRun(javaExecutable)) { + _validationMessages.add('Unable to find bundled Java version.'); + } else { + RunResult? result; + try { + result = globals.processUtils.runSync([javaExecutable, '-version']); + } on ProcessException catch (e) { + _validationMessages.add('Failed to run Java: $e'); + } + if (result != null && result.exitCode == 0) { + final List versionLines = result.stderr.split('\n'); + final String javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; + _validationMessages.add('Java version $javaVersion'); + _javaPath = javaPath; + _isValid = true; + } else { + _validationMessages.add('Unable to determine bundled Java version.'); + } + } + } + + @override + String toString() => 'Android Studio ($version)'; +} + +bool _pathsAreEqual(String path, String other) { + return globals.fs.path.canonicalize(path) == globals.fs.path.canonicalize(other); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..c35ee5ebb7c126317bdf1e23a29fe933c78ab26b --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio_validator.dart @@ -0,0 +1,141 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../base/config.dart'; +import '../base/file_system.dart'; +import '../base/platform.dart'; +import '../base/user_messages.dart'; +import '../doctor_validator.dart'; +import '../intellij/intellij.dart'; +import 'android_studio.dart'; + +const String _androidStudioTitle = 'Android Studio'; +const String _androidStudioId = 'AndroidStudio'; +const String _androidStudioPreviewTitle = 'Android Studio Preview'; +const String _androidStudioPreviewId = 'AndroidStudioPreview'; + +class AndroidStudioValidator extends DoctorValidator { + AndroidStudioValidator(this._studio, { + required FileSystem fileSystem, + required UserMessages userMessages, + }) + : _userMessages = userMessages, + _fileSystem = fileSystem, + super('Android Studio'); + + final AndroidStudio _studio; + final FileSystem _fileSystem; + final UserMessages _userMessages; + + static const Map idToTitle = { + _androidStudioId: _androidStudioTitle, + _androidStudioPreviewId: _androidStudioPreviewTitle, + }; + + static List allValidators(Config config, Platform platform, FileSystem fileSystem, UserMessages userMessages) { + final List studios = AndroidStudio.allInstalled(); + return [ + if (studios.isEmpty) + NoAndroidStudioValidator(config: config, platform: platform, userMessages: userMessages) + else + ...studios.map( + (AndroidStudio studio) => AndroidStudioValidator(studio, fileSystem: fileSystem, userMessages: userMessages) + ), + ]; + } + + @override + Future validate() async { + final List messages = []; + ValidationType type = ValidationType.missing; + + final String studioVersionText = _studio.version == null + ? _userMessages.androidStudioVersion('unknown') + : _userMessages.androidStudioVersion(_studio.version.toString()); + messages.add(ValidationMessage( + _userMessages.androidStudioLocation(_studio.directory), + )); + + if (_studio.pluginsPath != null) { + final IntelliJPlugins plugins = IntelliJPlugins(_studio.pluginsPath!, fileSystem: _fileSystem); + plugins.validatePackage( + messages, + ['flutter-intellij', 'flutter-intellij.jar'], + 'Flutter', + IntelliJPlugins.kIntellijFlutterPluginUrl, + minVersion: IntelliJPlugins.kMinFlutterPluginVersion, + ); + plugins.validatePackage( + messages, + ['Dart'], + 'Dart', + IntelliJPlugins.kIntellijDartPluginUrl, + ); + } + + if (_studio.version == null) { + messages.add(const ValidationMessage.error('Unable to determine Android Studio version.')); + } + + if (_studio.isValid) { + type = _hasIssues(messages) + ? ValidationType.partial + : ValidationType.success; + messages.addAll(_studio.validationMessages.map( + (String m) => ValidationMessage(m), + )); + } else { + type = ValidationType.partial; + messages.addAll(_studio.validationMessages.map( + (String m) => ValidationMessage.error(m), + )); + messages.add(ValidationMessage(_userMessages.androidStudioNeedsUpdate)); + if (_studio.configuredPath != null) { + messages.add(ValidationMessage(_userMessages.androidStudioResetDir)); + } + } + + return ValidationResult(type, messages, statusInfo: studioVersionText); + } + + bool _hasIssues(List messages) { + return messages.any((ValidationMessage message) => message.isError); + } +} + +class NoAndroidStudioValidator extends DoctorValidator { + NoAndroidStudioValidator({ + required Config config, + required Platform platform, + required UserMessages userMessages, + }) : _config = config, + _platform = platform, + _userMessages = userMessages, + super('Android Studio'); + + final Config _config; + final Platform _platform; + final UserMessages _userMessages; + + @override + Future validate() async { + final List messages = []; + + final String? cfgAndroidStudio = _config.getValue( + 'android-studio-dir', + ) as String?; + if (cfgAndroidStudio != null) { + messages.add(ValidationMessage.error( + _userMessages.androidStudioMissing(cfgAndroidStudio), + )); + } + messages.add(ValidationMessage(_userMessages.androidStudioInstallation(_platform))); + + return ValidationResult( + ValidationType.notAvailable, + messages, + statusInfo: 'not installed', + ); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_workflow.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_workflow.dart new file mode 100644 index 0000000000000000000000000000000000000000..786cd5d9141082ceea070c30114d5cf0138ec757 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_workflow.dart @@ -0,0 +1,455 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:process/process.dart'; + +import '../base/common.dart'; +import '../base/context.dart'; +import '../base/io.dart'; +import '../base/logger.dart'; +import '../base/platform.dart'; +import '../base/user_messages.dart' hide userMessages; +import '../base/version.dart'; +import '../convert.dart'; +import '../doctor_validator.dart'; +import '../features.dart'; +import 'android_sdk.dart'; +import 'java.dart'; + +const int kAndroidSdkMinVersion = 29; +final Version kAndroidJavaMinVersion = Version(1, 8, 0); +final Version kAndroidSdkBuildToolsMinVersion = Version(28, 0, 3); + +AndroidWorkflow? get androidWorkflow => context.get(); +AndroidValidator? get androidValidator => context.get(); +AndroidLicenseValidator? get androidLicenseValidator => context.get(); + +enum LicensesAccepted { + none, + some, + all, + unknown, +} + +final RegExp licenseCounts = RegExp(r'(\d+) of (\d+) SDK package licenses? not accepted.'); +final RegExp licenseNotAccepted = RegExp(r'licenses? not accepted', caseSensitive: false); +final RegExp licenseAccepted = RegExp(r'All SDK package licenses accepted.'); + +class AndroidWorkflow implements Workflow { + AndroidWorkflow({ + required AndroidSdk? androidSdk, + required FeatureFlags featureFlags, + }) : _androidSdk = androidSdk, + _featureFlags = featureFlags; + + final AndroidSdk? _androidSdk; + final FeatureFlags _featureFlags; + + @override + bool get appliesToHostPlatform => _featureFlags.isAndroidEnabled; + + @override + bool get canListDevices => appliesToHostPlatform && _androidSdk != null + && _androidSdk.adbPath != null; + + @override + bool get canLaunchDevices => appliesToHostPlatform && _androidSdk != null + && _androidSdk.adbPath != null + && _androidSdk.validateSdkWellFormed().isEmpty; + + @override + bool get canListEmulators => canListDevices && _androidSdk?.emulatorPath != null; +} + +/// A validator that checks if the Android SDK and Java SDK are available and +/// installed correctly. +/// +/// Android development requires the Android SDK, and at least one Java SDK. While +/// newer Java compilers can be used to compile the Java application code, the SDK +/// tools themselves required JDK 1.8. This older JDK is normally bundled with +/// Android Studio. +class AndroidValidator extends DoctorValidator { + AndroidValidator({ + required Java? java, + required AndroidSdk? androidSdk, + required Logger logger, + required Platform platform, + required UserMessages userMessages, + }) : _java = java, + _androidSdk = androidSdk, + _logger = logger, + _platform = platform, + _userMessages = userMessages, + super('Android toolchain - develop for Android devices'); + + final Java? _java; + final AndroidSdk? _androidSdk; + final Logger _logger; + final Platform _platform; + final UserMessages _userMessages; + + @override + String get slowWarning => '${_task ?? 'This'} is taking a long time...'; + String? _task; + + /// Returns false if we cannot determine the Java version or if the version + /// is older that the minimum allowed version of 1.8. + Future _checkJavaVersion(List messages) async { + _task = 'Checking Java status'; + try { + if (_java?.binaryPath == null) { + messages.add(ValidationMessage.error(_userMessages.androidMissingJdk)); + return false; + } + messages.add(ValidationMessage(_userMessages.androidJdkLocation(_java!.binaryPath))); + if (!_java.canRun()) { + messages.add(ValidationMessage.error(_userMessages.androidCantRunJavaBinary(_java.binaryPath))); + return false; + } + Version? javaVersion; + try { + javaVersion = _java.version; + } on Exception catch (error) { + _logger.printTrace(error.toString()); + } + if (javaVersion == null) { + // Could not determine the java version. + messages.add(ValidationMessage.error(_userMessages.androidUnknownJavaVersion)); + return false; + } + if (javaVersion < kAndroidJavaMinVersion) { + messages.add(ValidationMessage.error(_userMessages.androidJavaMinimumVersion(javaVersion.toString()))); + return false; + } + messages.add(ValidationMessage(_userMessages.androidJavaVersion(javaVersion.toString()))); + return true; + } finally { + _task = null; + } + } + + @override + Future validate() async { + final List messages = []; + final AndroidSdk? androidSdk = _androidSdk; + if (androidSdk == null) { + // No Android SDK found. + if (_platform.environment.containsKey(kAndroidHome)) { + final String androidHomeDir = _platform.environment[kAndroidHome]!; + messages.add(ValidationMessage.error(_userMessages.androidBadSdkDir(kAndroidHome, androidHomeDir))); + } else { + // Instruct user to set [kAndroidSdkRoot] and not deprecated [kAndroidHome] + // See https://github.com/flutter/flutter/issues/39301 + messages.add(ValidationMessage.error(_userMessages.androidMissingSdkInstructions(_platform))); + } + return ValidationResult(ValidationType.missing, messages); + } + + messages.add(ValidationMessage(_userMessages.androidSdkLocation(androidSdk.directory.path))); + + _task = 'Validating Android SDK command line tools are available'; + if (!androidSdk.cmdlineToolsAvailable) { + messages.add(ValidationMessage.error(_userMessages.androidMissingCmdTools)); + return ValidationResult(ValidationType.missing, messages); + } + + _task = 'Validating Android SDK licenses'; + if (androidSdk.licensesAvailable && !androidSdk.platformToolsAvailable) { + messages.add(ValidationMessage.hint(_userMessages.androidSdkLicenseOnly(kAndroidHome))); + return ValidationResult(ValidationType.partial, messages); + } + + String? sdkVersionText; + final AndroidSdkVersion? androidSdkLatestVersion = androidSdk.latestVersion; + if (androidSdkLatestVersion != null) { + if (androidSdkLatestVersion.sdkLevel < kAndroidSdkMinVersion || androidSdkLatestVersion.buildToolsVersion < kAndroidSdkBuildToolsMinVersion) { + messages.add(ValidationMessage.error( + _userMessages.androidSdkBuildToolsOutdated( + kAndroidSdkMinVersion, + kAndroidSdkBuildToolsMinVersion.toString(), + _platform, + )), + ); + return ValidationResult(ValidationType.missing, messages); + } + sdkVersionText = _userMessages.androidStatusInfo(androidSdkLatestVersion.buildToolsVersionName); + + messages.add(ValidationMessage(_userMessages.androidSdkPlatformToolsVersion( + androidSdkLatestVersion.platformName, + androidSdkLatestVersion.buildToolsVersionName))); + } else { + messages.add(ValidationMessage.error(_userMessages.androidMissingSdkInstructions(_platform))); + } + + if (_platform.environment.containsKey(kAndroidHome)) { + final String androidHomeDir = _platform.environment[kAndroidHome]!; + messages.add(ValidationMessage('$kAndroidHome = $androidHomeDir')); + } + if (_platform.environment.containsKey(kAndroidSdkRoot)) { + final String androidSdkRoot = _platform.environment[kAndroidSdkRoot]!; + messages.add(ValidationMessage('$kAndroidSdkRoot = $androidSdkRoot')); + } + + _task = 'Validating Android SDK'; + final List validationResult = androidSdk.validateSdkWellFormed(); + + if (validationResult.isNotEmpty) { + // Android SDK is not functional. + messages.addAll(validationResult.map((String message) { + return ValidationMessage.error(message); + })); + messages.add(ValidationMessage(_userMessages.androidSdkInstallHelp(_platform))); + return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); + } + + _task = 'Finding Java binary'; + + // Check JDK version. + if (!await _checkJavaVersion(messages)) { + return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); + } + + // Success. + return ValidationResult(ValidationType.success, messages, statusInfo: sdkVersionText); + } +} + +/// A subvalidator that checks if the licenses within the detected Android +/// SDK have been accepted. +class AndroidLicenseValidator extends DoctorValidator { + AndroidLicenseValidator({ + required Java? java, + required AndroidSdk? androidSdk, + required Platform platform, + required ProcessManager processManager, + required Logger logger, + required Stdio stdio, + required UserMessages userMessages, + }) : _java = java, + _androidSdk = androidSdk, + _platform = platform, + _processManager = processManager, + _logger = logger, + _stdio = stdio, + _userMessages = userMessages, + super('Android license subvalidator'); + + final Java? _java; + final AndroidSdk? _androidSdk; + final Stdio _stdio; + final Platform _platform; + final ProcessManager _processManager; + final Logger _logger; + final UserMessages _userMessages; + + @override + String get slowWarning => 'Checking Android licenses is taking an unexpectedly long time...'; + + @override + Future validate() async { + final List messages = []; + + // Match pre-existing early termination behavior + if (_androidSdk == null || _androidSdk.latestVersion == null || + _androidSdk.validateSdkWellFormed().isNotEmpty || + ! await _checkJavaVersionNoOutput()) { + return ValidationResult(ValidationType.missing, messages); + } + + final String sdkVersionText = _userMessages.androidStatusInfo(_androidSdk.latestVersion!.buildToolsVersionName); + + // Check for licenses. + switch (await licensesAccepted) { + case LicensesAccepted.all: + messages.add(ValidationMessage(_userMessages.androidLicensesAll)); + case LicensesAccepted.some: + messages.add(ValidationMessage.hint(_userMessages.androidLicensesSome)); + return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); + case LicensesAccepted.none: + messages.add(ValidationMessage.error(_userMessages.androidLicensesNone)); + return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); + case LicensesAccepted.unknown: + messages.add(ValidationMessage.error(_userMessages.androidLicensesUnknown(_platform))); + return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); + } + return ValidationResult(ValidationType.success, messages, statusInfo: sdkVersionText); + } + + Future _checkJavaVersionNoOutput() async { + final String? javaBinary = _java?.binaryPath; + + if (javaBinary == null) { + return false; + } + if (!_processManager.canRun(javaBinary)) { + return false; + } + String? javaVersion; + try { + final ProcessResult result = await _processManager.run([javaBinary, '-version']); + if (result.exitCode == 0) { + final List versionLines = (result.stderr as String).split('\n'); + javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; + } + } on Exception catch (error) { + _logger.printTrace(error.toString()); + } + if (javaVersion == null) { + // Could not determine the java version. + return false; + } + return true; + } + + Future get licensesAccepted async { + LicensesAccepted? status; + + void handleLine(String line) { + if (licenseCounts.hasMatch(line)) { + final Match? match = licenseCounts.firstMatch(line); + if (match?.group(1) != match?.group(2)) { + status = LicensesAccepted.some; + } else { + status = LicensesAccepted.none; + } + } else if (licenseNotAccepted.hasMatch(line)) { + // The licenseNotAccepted pattern is trying to match the same line as + // licenseCounts, but is more general. In case the format changes, a + // more general match may keep doctor mostly working. + status = LicensesAccepted.none; + } else if (licenseAccepted.hasMatch(line)) { + status ??= LicensesAccepted.all; + } + } + + if (!_canRunSdkManager()) { + return LicensesAccepted.unknown; + } + + try { + final Process process = await _processManager.start( + [_androidSdk!.sdkManagerPath!, '--licenses'], + environment: _java?.environment, + ); + process.stdin.write('n\n'); + // We expect logcat streams to occasionally contain invalid utf-8, + // see: https://github.com/flutter/flutter/pull/8864. + final Future output = process.stdout + .transform(const Utf8Decoder(reportErrors: false)) + .transform(const LineSplitter()) + .listen(handleLine) + .asFuture(); + final Future errors = process.stderr + .transform(const Utf8Decoder(reportErrors: false)) + .transform(const LineSplitter()) + .listen(handleLine) + .asFuture(); + await Future.wait(>[output, errors]); + return status ?? LicensesAccepted.unknown; + } on ProcessException catch (e) { + _logger.printTrace('Failed to run Android sdk manager: $e'); + return LicensesAccepted.unknown; + } + } + + /// Run the Android SDK manager tool in order to accept SDK licenses. + Future runLicenseManager() async { + if (_androidSdk == null) { + _logger.printStatus(_userMessages.androidSdkShort); + return false; + } + + if (!_canRunSdkManager()) { + throwToolExit( + 'Android sdkmanager not found. Update to the latest Android SDK and ensure that ' + 'the cmdline-tools are installed to resolve this.' + ); + } + + try { + final Process process = await _processManager.start( + [_androidSdk.sdkManagerPath!, '--licenses'], + environment: _java?.environment, + ); + + // The real stdin will never finish streaming. Pipe until the child process + // finishes. + unawaited(process.stdin.addStream(_stdio.stdin) + // If the process exits unexpectedly with an error, that will be + // handled by the caller. + .then( + (Object? socket) => socket, + onError: (dynamic err, StackTrace stack) { + _logger.printTrace('Echoing stdin to the licenses subprocess failed:'); + _logger.printTrace('$err\n$stack'); + }, + ), + ); + + final List stderrLines = []; + // Wait for stdout and stderr to be fully processed, because process.exitCode + // may complete first. + try { + await Future.wait(>[ + _stdio.addStdoutStream(process.stdout), + process.stderr.forEach((List event) { + _stdio.stderr.add(event); + stderrLines.add(utf8.decode(event)); + }), + ]); + } on Exception catch (err, stack) { + _logger.printTrace('Echoing stdout or stderr from the license subprocess failed:'); + _logger.printTrace('$err\n$stack'); + } + + final int exitCode = await process.exitCode; + if (exitCode != 0) { + throwToolExit(_messageForSdkManagerError(stderrLines, exitCode)); + } + return true; + } on ProcessException catch (e) { + throwToolExit(_userMessages.androidCannotRunSdkManager( + _androidSdk.sdkManagerPath ?? '', + e.toString(), + _platform, + )); + } + } + + bool _canRunSdkManager() { + final String? sdkManagerPath = _androidSdk?.sdkManagerPath; + if (sdkManagerPath == null) { + return false; + } + return _processManager.canRun(sdkManagerPath); + } + + String _messageForSdkManagerError( + List androidSdkStderr, + int exitCode, + ) { + final String sdkManagerPath = _androidSdk!.sdkManagerPath!; + + final bool failedDueToJdkIncompatibility = androidSdkStderr.join().contains( + RegExp(r'java\.lang\.UnsupportedClassVersionError.*SdkManagerCli ' + r'has been compiled by a more recent version of the Java Runtime')); + + if (failedDueToJdkIncompatibility) { + return 'Android sdkmanager tool was found, but failed to run ($sdkManagerPath): "exited code $exitCode".\n' + 'It appears the version of the Java binary used (${_java!.binaryPath}) is ' + 'too out-of-date and is incompatible with the Android sdkmanager tool.\n' + 'If the Java binary came bundled with Android Studio, consider updating ' + 'your installation of Android studio. Alternatively, you can uninstall ' + 'the Android SDK command-line tools and install an earlier version. '; + } + + return _userMessages.androidCannotRunSdkManager( + sdkManagerPath, + 'exited code $exitCode', + _platform, + ); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/application_package.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/application_package.dart new file mode 100644 index 0000000000000000000000000000000000000000..7eb9c2b2797d990b9211849e2825cec480382029 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/application_package.dart @@ -0,0 +1,431 @@ +// 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:collection'; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; +import 'package:xml/xml.dart'; + +import '../application_package.dart'; +import '../base/common.dart'; +import '../base/file_system.dart'; +import '../base/io.dart'; +import '../base/logger.dart'; +import '../base/process.dart'; +import '../base/user_messages.dart'; +import '../build_info.dart'; +import '../project.dart'; +import 'android_sdk.dart'; +import 'gradle.dart'; + +/// An application package created from an already built Android APK. +class AndroidApk extends ApplicationPackage implements PrebuiltApplicationPackage { + AndroidApk({ + required super.id, + required this.applicationPackage, + required this.versionCode, + required this.launchActivity, + }); + + /// Creates a new AndroidApk from an existing APK. + /// + /// Returns `null` if the APK was invalid or any required tooling was missing. + static AndroidApk? fromApk( + File apk, { + required AndroidSdk androidSdk, + required ProcessManager processManager, + required UserMessages userMessages, + required Logger logger, + required ProcessUtils processUtils, + }) { + final String? aaptPath = androidSdk.latestVersion?.aaptPath; + if (aaptPath == null || !processManager.canRun(aaptPath)) { + logger.printError(userMessages.aaptNotFound); + return null; + } + + String apptStdout; + try { + apptStdout = processUtils.runSync( + [ + aaptPath, + 'dump', + 'xmltree', + apk.path, + 'AndroidManifest.xml', + ], + throwOnError: true, + ).stdout.trim(); + } on ProcessException catch (error) { + logger.printError('Failed to extract manifest from APK: $error.'); + return null; + } + + final ApkManifestData? data = ApkManifestData.parseFromXmlDump(apptStdout, logger); + + if (data == null) { + logger.printError('Unable to read manifest info from ${apk.path}.'); + return null; + } + + final String? packageName = data.packageName; + if (packageName == null || data.launchableActivityName == null) { + logger.printError('Unable to read manifest info from ${apk.path}.'); + return null; + } + + return AndroidApk( + id: packageName, + applicationPackage: apk, + versionCode: data.versionCode == null ? null : int.tryParse(data.versionCode!), + launchActivity: '${data.packageName}/${data.launchableActivityName}', + ); + } + + @override + final FileSystemEntity applicationPackage; + + /// The path to the activity that should be launched. + final String launchActivity; + + /// The version code of the APK. + final int? versionCode; + + /// Creates a new AndroidApk based on the information in the Android manifest. + static Future fromAndroidProject( + AndroidProject androidProject, { + required AndroidSdk? androidSdk, + required ProcessManager processManager, + required UserMessages userMessages, + required ProcessUtils processUtils, + required Logger logger, + required FileSystem fileSystem, + BuildInfo? buildInfo, + }) async { + final File apkFile; + final String filename; + if (buildInfo == null) { + filename = 'app.apk'; + } else if (buildInfo.flavor == null) { + filename = 'app-${buildInfo.mode.cliName}.apk'; + } else { + filename = 'app-${buildInfo.lowerCasedFlavor}-${buildInfo.mode.cliName}.apk'; + } + + if (androidProject.isUsingGradle && androidProject.isSupportedVersion) { + Directory apkDirectory = getApkDirectory(androidProject.parent); + if (androidProject.parent.isModule) { + // Module builds output the apk in a subdirectory that corresponds + // to the buildmode of the apk. + apkDirectory = apkDirectory.childDirectory(buildInfo!.mode.cliName); + } + apkFile = apkDirectory.childFile(filename); + if (apkFile.existsSync()) { + // Grab information from the .apk. The gradle build script might alter + // the application Id, so we need to look at what was actually built. + return AndroidApk.fromApk( + apkFile, + androidSdk: androidSdk!, + processManager: processManager, + logger: logger, + userMessages: userMessages, + processUtils: processUtils, + ); + } + // The .apk hasn't been built yet, so we work with what we have. The run + // command will grab a new AndroidApk after building, to get the updated + // IDs. + } else { + apkFile = fileSystem.file(fileSystem.path.join(getAndroidBuildDirectory(), filename)); + } + + final File manifest = androidProject.appManifestFile; + + if (!manifest.existsSync()) { + logger.printError('AndroidManifest.xml could not be found.'); + logger.printError('Please check ${manifest.path} for errors.'); + return null; + } + + final String manifestString = manifest.readAsStringSync(); + XmlDocument document; + try { + document = XmlDocument.parse(manifestString); + } on XmlException catch (exception) { + String manifestLocation; + if (androidProject.isUsingGradle) { + manifestLocation = fileSystem.path.join(androidProject.hostAppGradleRoot.path, 'app', 'src', 'main', 'AndroidManifest.xml'); + } else { + manifestLocation = fileSystem.path.join(androidProject.hostAppGradleRoot.path, 'AndroidManifest.xml'); + } + logger.printError('AndroidManifest.xml is not a valid XML document.'); + logger.printError('Please check $manifestLocation for errors.'); + throwToolExit('XML Parser error message: $exception'); + } + + final Iterable manifests = document.findElements('manifest'); + if (manifests.isEmpty) { + logger.printError('AndroidManifest.xml has no manifest element.'); + logger.printError('Please check ${manifest.path} for errors.'); + return null; + } + + // Starting from AGP version 7.3, the `package` attribute in Manifest.xml + // can be replaced with the `namespace` attribute under the `android` section in `android/app/build.gradle`. + final String? packageId = manifests.first.getAttribute('package') ?? androidProject.namespace; + + String? launchActivity; + for (final XmlElement activity in document.findAllElements('activity')) { + final String? enabled = activity.getAttribute('android:enabled'); + if (enabled != null && enabled == 'false') { + continue; + } + + for (final XmlElement element in activity.findElements('intent-filter')) { + String? actionName = ''; + String? categoryName = ''; + for (final XmlNode node in element.children) { + if (node is! XmlElement) { + continue; + } + final String? name = node.getAttribute('android:name'); + if (name == 'android.intent.action.MAIN') { + actionName = name; + } else if (name == 'android.intent.category.LAUNCHER') { + categoryName = name; + } + } + if (actionName != null && categoryName != null && actionName.isNotEmpty && categoryName.isNotEmpty) { + final String? activityName = activity.getAttribute('android:name'); + launchActivity = '$packageId/$activityName'; + break; + } + } + } + + if (packageId == null || launchActivity == null) { + logger.printError('package identifier or launch activity not found.'); + logger.printError('Please check ${manifest.path} for errors.'); + return null; + } + + return AndroidApk( + id: packageId, + applicationPackage: apkFile, + versionCode: null, + launchActivity: launchActivity, + ); + } + + @override + String get name => applicationPackage.basename; +} + +abstract class _Entry { + const _Entry(this.parent, this.level); + + final _Element? parent; + final int level; +} + +class _Element extends _Entry { + _Element._(this.name, _Element? parent, int level) : super(parent, level); + + factory _Element.fromLine(String line, _Element? parent) { + // E: application (line=29) + final List parts = line.trimLeft().split(' '); + return _Element._(parts[1], parent, line.length - line.trimLeft().length); + } + + final List<_Entry> children = <_Entry>[]; + final String? name; + + void addChild(_Entry child) { + children.add(child); + } + + _Attribute? firstAttribute(String name) { + for (final _Attribute child in children.whereType<_Attribute>()) { + if (child.key?.startsWith(name) ?? false) { + return child; + } + } + return null; + } + + _Element? firstElement(String name) { + for (final _Element child in children.whereType<_Element>()) { + if (child.name?.startsWith(name) ?? false) { + return child; + } + } + return null; + } + + Iterable<_Element> allElements(String name) { + return children.whereType<_Element>().where((_Element e) => e.name?.startsWith(name) ?? false); + } +} + +class _Attribute extends _Entry { + const _Attribute._(this.key, this.value, _Element? parent, int level) : super(parent, level); + + factory _Attribute.fromLine(String line, _Element parent) { + // A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + const String attributePrefix = 'A: '; + final List keyVal = line.substring(line.indexOf(attributePrefix) + attributePrefix.length).split('='); + return _Attribute._(keyVal[0], keyVal[1], parent, line.length - line.trimLeft().length); + } + + final String? key; + final String? value; +} + +class ApkManifestData { + ApkManifestData._(this._data); + + static bool _isAttributeWithValuePresent( + _Element baseElement, String childElement, String attributeName, String attributeValue) { + final Iterable<_Element> allElements = baseElement.allElements(childElement); + for (final _Element oneElement in allElements) { + final String? elementAttributeValue = oneElement + .firstAttribute(attributeName) + ?.value; + if (elementAttributeValue != null && + elementAttributeValue.startsWith(attributeValue)) { + return true; + } + } + return false; + } + + static ApkManifestData? parseFromXmlDump(String data, Logger logger) { + if (data.trim().isEmpty) { + return null; + } + + final List lines = data.split('\n'); + assert(lines.length > 3); + + final int manifestLine = lines.indexWhere((String line) => line.contains('E: manifest')); + final _Element manifest = _Element.fromLine(lines[manifestLine], null); + _Element currentElement = manifest; + + for (final String line in lines.skip(manifestLine)) { + final String trimLine = line.trimLeft(); + final int level = line.length - trimLine.length; + + // Handle level out + while (currentElement.parent != null && level <= currentElement.level) { + currentElement = currentElement.parent!; + } + + if (level > currentElement.level) { + switch (trimLine[0]) { + case 'A': + currentElement + .addChild(_Attribute.fromLine(line, currentElement)); + case 'E': + final _Element element = _Element.fromLine(line, currentElement); + currentElement.addChild(element); + currentElement = element; + } + } + } + + final _Element? application = manifest.firstElement('application'); + if (application == null) { + return null; + } + + final Iterable<_Element> activities = application.allElements('activity'); + + _Element? launchActivity; + for (final _Element activity in activities) { + final _Attribute? enabled = activity.firstAttribute('android:enabled'); + final Iterable<_Element> intentFilters = activity.allElements('intent-filter'); + final bool isEnabledByDefault = enabled == null; + final bool isExplicitlyEnabled = enabled != null && (enabled.value?.contains('0xffffffff') ?? false); + if (!(isEnabledByDefault || isExplicitlyEnabled)) { + continue; + } + + for (final _Element element in intentFilters) { + final bool isMainAction = _isAttributeWithValuePresent( + element, 'action', 'android:name', '"android.intent.action.MAIN"'); + if (!isMainAction) { + continue; + } + final bool isLauncherCategory = _isAttributeWithValuePresent( + element, 'category', 'android:name', + '"android.intent.category.LAUNCHER"'); + if (!isLauncherCategory) { + continue; + } + launchActivity = activity; + break; + } + if (launchActivity != null) { + break; + } + } + + final _Attribute? package = manifest.firstAttribute('package'); + // "io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + final String? packageName = package?.value?.substring(1, package.value?.indexOf('" ')); + + if (launchActivity == null) { + logger.printError('Error running $packageName. Default activity not found'); + return null; + } + + final _Attribute? nameAttribute = launchActivity.firstAttribute('android:name'); + // "io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + final String? activityName = nameAttribute?.value?.substring(1, nameAttribute.value?.indexOf('" ')); + + // Example format: (type 0x10)0x1 + final _Attribute? versionCodeAttr = manifest.firstAttribute('android:versionCode'); + if (versionCodeAttr == null) { + logger.printError('Error running $packageName. Manifest versionCode not found'); + return null; + } + if (versionCodeAttr.value?.startsWith('(type 0x10)') != true) { + logger.printError('Error running $packageName. Manifest versionCode invalid'); + return null; + } + final int? versionCode = versionCodeAttr.value == null ? null : int.tryParse(versionCodeAttr.value!.substring(11)); + if (versionCode == null) { + logger.printError('Error running $packageName. Manifest versionCode invalid'); + return null; + } + + final Map> map = >{ + if (packageName != null) + 'package': {'name': packageName}, + 'version-code': {'name': versionCode.toString()}, + if (activityName != null) + 'launchable-activity': {'name': activityName}, + }; + + return ApkManifestData._(map); + } + + final Map> _data; + + @visibleForTesting + Map> get data => + UnmodifiableMapView>(_data); + + String? get packageName => _data['package'] == null ? null : _data['package']?['name']; + + String? get versionCode => _data['version-code'] == null ? null : _data['version-code']?['name']; + + String? get launchableActivityName { + return _data['launchable-activity'] == null ? null : _data['launchable-activity']?['name']; + } + + @override + String toString() => _data.toString(); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/build_validation.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/build_validation.dart new file mode 100644 index 0000000000000000000000000000000000000000..c61d353bd61c428cf774fa9f4766b3c6eea8bc42 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/build_validation.dart @@ -0,0 +1,49 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../base/common.dart'; +import '../build_info.dart'; + +const String kGooglePlayVersioning = 'https://developer.android.com/studio/publish/versioning.html'; +const String kSupportedAbis = 'https://flutter.dev/docs/deployment/android#what-are-the-supported-target-architectures'; + +/// Validates that the build mode and build number are valid for a given build. +void validateBuild(AndroidBuildInfo androidBuildInfo) { + final BuildInfo buildInfo = androidBuildInfo.buildInfo; + if (buildInfo.codeSizeDirectory != null && androidBuildInfo.targetArchs.length > 1) { + throwToolExit( + 'Cannot perform code size analysis when building for multiple ABIs. ' + 'Specify one of android-arm, android-arm64, or android-x64 in the ' + '--target-platform flag.' + ); + } + if (buildInfo.mode.isPrecompiled && androidBuildInfo.targetArchs.contains(AndroidArch.x86)) { + throwToolExit( + 'Cannot build ${androidBuildInfo.buildInfo.mode.cliName} mode for x86 ABI.\n' + 'For more information see $kSupportedAbis .' + ); + } + if (buildInfo.buildNumber != null) { + final int? result = int.tryParse(buildInfo.buildNumber!); + if (result == null) { + throwToolExit( + 'buildNumber: ${buildInfo.buildNumber} was not a valid integer value.\n' + 'For more information see $kGooglePlayVersioning .' + ); + } + if (result < 0) { + throwToolExit( + 'buildNumber: ${buildInfo.buildNumber} must be a positive integer value.\n' + 'For more information see $kGooglePlayVersioning .' + ); + } + if (result > 2100000000) { + throwToolExit( + 'buildNumber: ${buildInfo.buildNumber} is greater than the maximum ' + 'allowed value of 2100000000.\n' + 'For more information see $kGooglePlayVersioning .' + ); + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_gen_snapshot_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_gen_snapshot_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..72197cce47b4c4938f8fb1690f364dc4a08ea434 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_gen_snapshot_validator.dart @@ -0,0 +1,342 @@ +// 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:xml/xml.dart'; +import 'package:yaml/yaml.dart'; + +import '../base/deferred_component.dart'; +import '../base/error_handling_io.dart'; +import '../base/file_system.dart'; +import '../build_system/build_system.dart'; +import 'deferred_components_validator.dart'; + +/// A class to configure and run deferred component setup verification checks +/// and tasks. +/// +/// Once constructed, checks and tasks can be executed by calling the respective +/// methods. The results of the checks are stored internally and can be +/// displayed to the user by calling [displayResults]. +class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator { + /// Constructs a validator instance. + /// + /// The [env] property is used to locate the project files that are checked. + /// + /// The [templatesDir] parameter is optional. If null, the tool's default + /// templates directory will be used. + /// + /// When [exitOnFail] is set to true, the [handleResults] and [attemptToolExit] + /// methods will exit the tool when this validator detects a recommended + /// change. This defaults to true. + DeferredComponentsGenSnapshotValidator(this.env, { + bool exitOnFail = true, + String? title, + }) : super(env.projectDir, env.logger, env.platform, exitOnFail: exitOnFail, title: title); + + /// The build environment that should be used to find the input files to run + /// checks against. + /// + /// The checks in this class are meant to be used as part of a build process, + /// so an environment should be available. + final Environment env; + + // The key used to identify the metadata element as the loading unit id to + // deferred component mapping. + static const String _mappingKey = 'io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping'; + + /// Checks if the base module `app`'s `AndroidManifest.xml` contains the + /// required meta-data that maps loading units to deferred components. + /// + /// Returns true if the check passed with no recommended changes, and false + /// otherwise. + /// + /// Flutter engine uses a manifest meta-data mapping to determine which + /// deferred component includes a particular loading unit id. This method + /// checks if `app`'s `AndroidManifest.xml` contains this metadata. If not, it + /// will generate a modified AndroidManifest.xml with the correct metadata + /// entry. + /// + /// An example mapping: + /// + /// 2:componentA,3:componentB,4:componentC + /// + /// Where loading unit 2 is included in componentA, loading unit 3 is included + /// in componentB, and loading unit 4 is included in componentC. + bool checkAppAndroidManifestComponentLoadingUnitMapping(List components, List generatedLoadingUnits) { + final Directory androidDir = projectDir.childDirectory('android'); + inputs.add(projectDir.childFile('pubspec.yaml')); + + // We do not use the Xml package to handle the writing, as we do not want to + // erase any user applied formatting and comments. The changes can be + // applied with dart io and custom parsing. + final File appManifestFile = androidDir + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + inputs.add(appManifestFile); + if (!appManifestFile.existsSync()) { + invalidFiles[appManifestFile.path] = 'Error: $appManifestFile does not ' + 'exist or could not be found. Please ensure an AndroidManifest.xml ' + "exists for the app's base module."; + return false; + } + XmlDocument document; + try { + document = XmlDocument.parse(appManifestFile.readAsStringSync()); + } on XmlException { + invalidFiles[appManifestFile.path] = 'Error parsing $appManifestFile ' + 'Please ensure that the android manifest is a valid XML document and ' + 'try again.'; + return false; + } on FileSystemException { + invalidFiles[appManifestFile.path] = 'Error reading $appManifestFile ' + 'even though it exists. Please ensure that you have read permission for ' + 'this file and try again.'; + return false; + } + // Create loading unit mapping. + final Map mapping = {}; + for (final DeferredComponent component in components) { + component.assignLoadingUnits(generatedLoadingUnits); + final Set? loadingUnits = component.loadingUnits; + if (loadingUnits == null) { + continue; + } + for (final LoadingUnit unit in loadingUnits) { + if (!mapping.containsKey(unit.id)) { + mapping[unit.id] = component.name; + } + } + } + for (final LoadingUnit unit in generatedLoadingUnits) { + if (!mapping.containsKey(unit.id)) { + // Store an empty string for unassigned loading units, + // indicating that it is in the base component. + mapping[unit.id] = ''; + } + } + // Encode the mapping as a string. + final StringBuffer mappingBuffer = StringBuffer(); + for (final int key in mapping.keys) { + mappingBuffer.write('$key:${mapping[key]},'); + } + String encodedMapping = mappingBuffer.toString(); + // remove trailing comma if any + if (encodedMapping.endsWith(',')) { + encodedMapping = encodedMapping.substring(0, encodedMapping.length - 1); + } + // Check for existing metadata entry and see if needs changes. + bool exists = false; + bool modified = false; + for (final XmlElement application in document.findAllElements('application')) { + for (final XmlElement metaData in application.findElements('meta-data')) { + final String? name = metaData.getAttribute('android:name'); + if (name == _mappingKey) { + exists = true; + final String? storedMappingString = metaData.getAttribute('android:value'); + if (storedMappingString != encodedMapping) { + metaData.setAttribute('android:value', encodedMapping); + modified = true; + } + } + } + } + if (!exists) { + // Create an meta-data XmlElement that contains the mapping. + final XmlElement mappingMetadataElement = XmlElement(XmlName.fromString('meta-data'), + [ + XmlAttribute(XmlName.fromString('android:name'), _mappingKey), + XmlAttribute(XmlName.fromString('android:value'), encodedMapping), + ], + ); + for (final XmlElement application in document.findAllElements('application')) { + application.children.add(mappingMetadataElement); + break; + } + } + if (!exists || modified) { + final File manifestOutput = outputDir + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + ErrorHandlingFileSystem.deleteIfExists(manifestOutput); + manifestOutput.createSync(recursive: true); + manifestOutput.writeAsStringSync(document.toXmlString(pretty: true), flush: true); + modifiedFiles.add(manifestOutput.path); + return false; + } + return true; + } + + /// Compares the provided loading units against the contents of the + /// `deferred_components_loading_units.yaml` file. + /// + /// Returns true if a loading unit cache file exists and all loading units + /// match, and false otherwise. + /// + /// This method will parse the cached loading units file if it exists and + /// compare it to the provided generatedLoadingUnits. It will distinguish + /// between newly added loading units and no longer existing loading units. If + /// the cache file does not exist, then all generatedLoadingUnits will be + /// considered new. + bool checkAgainstLoadingUnitsCache( + List generatedLoadingUnits) { + final List cachedLoadingUnits = _parseLoadingUnitsCache(projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName)); + loadingUnitComparisonResults = {}; + final Set unmatchedLoadingUnits = {}; + final List newLoadingUnits = []; + unmatchedLoadingUnits.addAll(cachedLoadingUnits); + final Set addedNewIds = {}; + for (final LoadingUnit genUnit in generatedLoadingUnits) { + bool matched = false; + for (final LoadingUnit cacheUnit in cachedLoadingUnits) { + if (genUnit.equalsIgnoringPath(cacheUnit)) { + matched = true; + unmatchedLoadingUnits.remove(cacheUnit); + break; + } + } + if (!matched && !addedNewIds.contains(genUnit.id)) { + newLoadingUnits.add(genUnit); + addedNewIds.add(genUnit.id); + } + } + loadingUnitComparisonResults!['new'] = newLoadingUnits; + loadingUnitComparisonResults!['missing'] = unmatchedLoadingUnits; + loadingUnitComparisonResults!['match'] = newLoadingUnits.isEmpty && unmatchedLoadingUnits.isEmpty; + return loadingUnitComparisonResults!['match']! as bool; + } + + List _parseLoadingUnitsCache(File cacheFile) { + final List loadingUnits = []; + inputs.add(cacheFile); + if (!cacheFile.existsSync()) { + return loadingUnits; + } + final YamlMap data = loadYaml(cacheFile.readAsStringSync()) as YamlMap; + // validate yaml format. + if (!data.containsKey('loading-units')) { + invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'loading-units' " + 'entry did not exist.'; + return loadingUnits; + } else { + if (data['loading-units'] is! YamlList && data['loading-units'] != null) { + invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'loading-units' " + 'is not a list.'; + return loadingUnits; + } + if (data['loading-units'] != null) { + for (final Object? loadingUnitData in data['loading-units'] as List) { + if (loadingUnitData is! YamlMap) { + invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'loading-units' " + 'is not a list of maps.'; + return loadingUnits; + } + final YamlMap loadingUnitDataMap = loadingUnitData; + if (loadingUnitDataMap['id'] == null) { + invalidFiles[cacheFile.path] = 'Invalid loading units yaml file, all ' + "loading units must have an 'id'"; + return loadingUnits; + } + if (loadingUnitDataMap['libraries'] != null) { + if (loadingUnitDataMap['libraries'] is! YamlList) { + invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'libraries' " + 'is not a list.'; + return loadingUnits; + } + for (final Object? node in loadingUnitDataMap['libraries'] as YamlList) { + if (node is! String) { + invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'libraries' " + 'is not a list of strings.'; + return loadingUnits; + } + } + } + } + } + } + + // Parse out validated yaml. + if (data.containsKey('loading-units')) { + if (data['loading-units'] != null) { + for (final Object? loadingUnitData in data['loading-units'] as List) { + final YamlMap? loadingUnitDataMap = loadingUnitData as YamlMap?; + final List libraries = []; + final YamlList? nodes = loadingUnitDataMap?['libraries'] as YamlList?; + if (nodes != null) { + for (final Object node in nodes.whereType()) { + libraries.add(node as String); + } + } + loadingUnits.add( + LoadingUnit( + id: loadingUnitDataMap!['id'] as int, + libraries: libraries, + )); + } + } + } + return loadingUnits; + } + + /// Writes the provided generatedLoadingUnits as `deferred_components_loading_units.yaml` + /// + /// This cache file is used to detect any changes in the loading units + /// produced by gen_snapshot. Running [checkAgainstLoadingUnitCache] with a + /// mismatching or missing cache will result in a failed validation. This + /// prevents unexpected changes in loading units causing misconfigured + /// deferred components. + void writeLoadingUnitsCache(List? generatedLoadingUnits) { + generatedLoadingUnits ??= []; + final File cacheFile = projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + outputs.add(cacheFile); + ErrorHandlingFileSystem.deleteIfExists(cacheFile); + cacheFile.createSync(recursive: true); + + final StringBuffer buffer = StringBuffer(); + buffer.write(''' +# ============================================================================== +# The contents of this file are automatically generated and it is not +# recommended to modify this file manually. +# ============================================================================== +# +# In order to prevent unexpected splitting of deferred apps, this file records +# the last generated set of loading units. It only possible to obtain the final +# configuration of loading units after compilation is complete. This means +# improperly setup deferred imports can only be detected after compilation. +# +# This file allows the build tool to detect any changes in the generated +# loading units. During the next build attempt, loading units in this file are +# compared against the newly generated loading units to check for any new or +# removed loading units. In the case where loading units do not match, the build +# will fail and ask the developer to verify that the `deferred-components` +# configuration in `pubspec.yaml` is correct. Developers should make any +# necessary changes to integrate new and changed loading units or remove no +# longer existing loading units from the configuration. The build command should +# then be re-run to continue the build process. +# +# Sometimes, changes to the generated loading units may be unintentional. If +# the list of loading units in this file is not what is expected, the app's +# deferred imports should be reviewed. Third party plugins and packages may +# also introduce deferred imports that result in unexpected loading units. +loading-units: +'''); + final Set usedIds = {}; + for (final LoadingUnit unit in generatedLoadingUnits) { + if (usedIds.contains(unit.id)) { + continue; + } + buffer.write(' - id: ${unit.id}\n'); + if (unit.libraries.isNotEmpty) { + buffer.write(' libraries:\n'); + for (final String lib in unit.libraries) { + buffer.write(' - $lib\n'); + } + } + usedIds.add(unit.id); + } + cacheFile.writeAsStringSync(buffer.toString(), flush: true); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_prebuild_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_prebuild_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..6cda9c7a2ceff6759e194648b292b383c5db5391 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_prebuild_validator.dart @@ -0,0 +1,294 @@ +// 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:xml/xml.dart'; + +import '../base/deferred_component.dart'; +import '../base/error_handling_io.dart'; +import '../base/file_system.dart'; +import '../base/logger.dart'; +import '../globals.dart' as globals; +import '../project.dart'; +import '../template.dart'; +import 'deferred_components_validator.dart'; + +/// A class to configure and run deferred component setup verification checks +/// and tasks. +/// +/// Once constructed, checks and tasks can be executed by calling the respective +/// methods. The results of the checks are stored internally and can be +/// displayed to the user by calling [displayResults]. +class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator { + /// Constructs a validator instance. + /// + /// The [templatesDir] parameter is optional. If null, the tool's default + /// templates directory will be used. + /// + /// When [exitOnFail] is set to true, the [handleResults] and [attemptToolExit] + /// methods will exit the tool when this validator detects a recommended + /// change. This defaults to true. + DeferredComponentsPrebuildValidator(super.projectDir, super.logger, super.platform, { + super.exitOnFail, + super.title, + Directory? templatesDir, + }) : _templatesDir = templatesDir; + + final Directory? _templatesDir; + + /// Checks if an android dynamic feature module exists for each deferred + /// component. + /// + /// Returns true if the check passed with no recommended changes, and false + /// otherwise. + /// + /// This method looks for the existence of `android//build.gradle` + /// and `android//src/main/AndroidManifest.xml`. If either of + /// these files does not exist, it will generate it in the validator output + /// directory based off of a template. + /// + /// This method does not check if the contents of either of the files are + /// valid, as there are many ways that they can be validly configured. + Future checkAndroidDynamicFeature(List components) async { + inputs.add(projectDir.childFile('pubspec.yaml')); + if (components.isEmpty) { + return false; + } + bool changesMade = false; + for (final DeferredComponent component in components) { + final _DeferredComponentAndroidFiles androidFiles = _DeferredComponentAndroidFiles( + name: component.name, + projectDir: projectDir, + logger: logger, + templatesDir: _templatesDir + ); + if (!androidFiles.verifyFilesExist()) { + // generate into temp directory + final Map> results = await androidFiles.generateFiles( + alternateAndroidDir: outputDir, + clearAlternateOutputDir: true, + ); + if (results.containsKey('outputs')) { + for (final File file in results['outputs']!) { + generatedFiles.add(file.path); + changesMade = true; + } + outputs.addAll(results['outputs']!); + } + if (results.containsKey('inputs')) { + inputs.addAll(results['inputs']!); + } + } + } + return !changesMade; + } + + /// Checks if the base module `app`'s `strings.xml` contain string + /// resources for each component's name. + /// + /// Returns true if the check passed with no recommended changes, and false + /// otherwise. + /// + /// In each dynamic feature module's AndroidManifest.xml, the + /// name of the module is a string resource. This checks if + /// the needed string resources are in the base module `strings.xml`. + /// If not, this method will generate a modified `strings.xml` (or a + /// completely new one if the original file did not exist) in the + /// validator's output directory. + /// + /// For example, if there is a deferred component named `component1`, + /// there should be the following string resource: + /// + /// component1 + /// + /// The string element's name attribute should be the component name with + /// `Name` as a suffix, and the text contents should be the component name. + bool checkAndroidResourcesStrings(List components) { + final Directory androidDir = projectDir.childDirectory('android'); + inputs.add(projectDir.childFile('pubspec.yaml')); + + // Add component name mapping to strings.xml + final File stringRes = androidDir + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('res') + .childDirectory('values') + .childFile('strings.xml'); + inputs.add(stringRes); + final File stringResOutput = outputDir + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('res') + .childDirectory('values') + .childFile('strings.xml'); + ErrorHandlingFileSystem.deleteIfExists(stringResOutput); + if (components.isEmpty) { + return true; + } + final Map requiredEntriesMap = {}; + for (final DeferredComponent component in components) { + requiredEntriesMap['${component.name}Name'] = component.name; + } + if (stringRes.existsSync()) { + bool modified = false; + XmlDocument document; + try { + document = XmlDocument.parse(stringRes.readAsStringSync()); + } on XmlException { + invalidFiles[stringRes.path] = 'Error parsing $stringRes ' + 'Please ensure that the strings.xml is a valid XML document and ' + 'try again.'; + return false; + } + // Check if all required lines are present, and fix if name exists, but + // wrong string stored. + for (final XmlElement resources in document.findAllElements('resources')) { + for (final XmlElement element in resources.findElements('string')) { + final String? name = element.getAttribute('name'); + if (requiredEntriesMap.containsKey(name)) { + if (element.innerText != requiredEntriesMap[name]) { + element.innerText = requiredEntriesMap[name]!; + modified = true; + } + requiredEntriesMap.remove(name); + } + } + requiredEntriesMap.forEach((String key, String value) { + modified = true; + final XmlElement newStringElement = XmlElement( + XmlName.fromString('string'), + [ + XmlAttribute(XmlName.fromString('name'), key), + ], + [ + XmlText(value), + ], + ); + resources.children.add(newStringElement); + }); + break; + } + if (modified) { + stringResOutput.createSync(recursive: true); + stringResOutput.writeAsStringSync(document.toXmlString(pretty: true)); + modifiedFiles.add(stringResOutput.path); + return false; + } + return true; + } + // strings.xml does not exist, generate completely new file. + stringResOutput.createSync(recursive: true); + final StringBuffer buffer = StringBuffer(); + buffer.writeln(''' + + +'''); + for (final String key in requiredEntriesMap.keys) { + buffer.write(' ${requiredEntriesMap[key]}\n'); + } + buffer.write( +''' + + +'''); + stringResOutput.writeAsStringSync(buffer.toString(), flush: true, mode: FileMode.append); + generatedFiles.add(stringResOutput.path); + return false; + } + + /// Deletes all files inside of the validator's output directory. + void clearOutputDir() { + final Directory dir = projectDir.childDirectory('build').childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory); + ErrorHandlingFileSystem.deleteIfExists(dir, recursive: true); + } +} + +// Handles a single deferred component's android dynamic feature module +// directory. +class _DeferredComponentAndroidFiles { + _DeferredComponentAndroidFiles({ + required this.name, + required this.projectDir, + required this.logger, + Directory? templatesDir, + }) : _templatesDir = templatesDir; + + // The name of the deferred component. + final String name; + final Directory projectDir; + final Logger logger; + final Directory? _templatesDir; + + Directory get androidDir => projectDir.childDirectory('android'); + Directory get componentDir => androidDir.childDirectory(name); + + File get androidManifestFile => componentDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml'); + File get buildGradleFile => componentDir.childFile('build.gradle'); + + // True when AndroidManifest.xml and build.gradle exist for the android dynamic feature. + bool verifyFilesExist() { + return androidManifestFile.existsSync() && buildGradleFile.existsSync(); + } + + // Generates any missing basic files for the dynamic feature into a temporary directory. + Future>> generateFiles({Directory? alternateAndroidDir, bool clearAlternateOutputDir = false}) async { + final Directory outputDir = alternateAndroidDir?.childDirectory(name) ?? componentDir; + if (clearAlternateOutputDir && alternateAndroidDir != null) { + ErrorHandlingFileSystem.deleteIfExists(outputDir); + } + final List inputs = []; + inputs.add(androidManifestFile); + inputs.add(buildGradleFile); + final Map> results = >{'inputs': inputs}; + results['outputs'] = await _setupComponentFiles(outputDir); + return results; + } + + // generates default build.gradle and AndroidManifest.xml for the deferred component. + Future> _setupComponentFiles(Directory outputDir) async { + Template template; + final Directory? templatesDir = _templatesDir; + if (templatesDir != null) { + final Directory templateComponentDir = templatesDir.childDirectory('module${globals.fs.path.separator}android${globals.fs.path.separator}deferred_component'); + template = Template(templateComponentDir, templateComponentDir, + fileSystem: globals.fs, + logger: logger, + templateRenderer: globals.templateRenderer, + ); + } else { + template = await Template.fromName('module${globals.fs.path.separator}android${globals.fs.path.separator}deferred_component', + fileSystem: globals.fs, + templateManifest: null, + logger: logger, + templateRenderer: globals.templateRenderer, + ); + } + final Map context = { + 'androidIdentifier': FlutterProject.current().manifest.androidPackage ?? 'com.example.${FlutterProject.current().manifest.appName}', + 'componentName': name, + }; + + template.render(outputDir, context); + + final List generatedFiles = []; + + final File tempBuildGradle = outputDir.childFile('build.gradle'); + if (!buildGradleFile.existsSync()) { + generatedFiles.add(tempBuildGradle); + } else { + ErrorHandlingFileSystem.deleteIfExists(tempBuildGradle); + } + final File tempAndroidManifest = outputDir + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + if (!androidManifestFile.existsSync()) { + generatedFiles.add(tempAndroidManifest); + } else { + ErrorHandlingFileSystem.deleteIfExists(tempAndroidManifest); + } + return generatedFiles; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..f22a40240a1be6623cd5124949e168ed041f8216 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_validator.dart @@ -0,0 +1,223 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import '../base/common.dart'; +import '../base/deferred_component.dart'; +import '../base/file_system.dart'; +import '../base/logger.dart'; +import '../base/platform.dart'; +import '../base/terminal.dart'; + +/// A class to configure and run deferred component setup verification checks +/// and tasks. +/// +/// Once constructed, checks and tasks can be executed by calling the respective +/// methods. The results of the checks are stored internally and can be +/// displayed to the user by calling [displayResults]. +/// +/// The results of each check are handled internally as they are not meant to +/// be run isolated. +abstract class DeferredComponentsValidator { + DeferredComponentsValidator(this.projectDir, this.logger, this.platform, { + this.exitOnFail = true, + String? title, + }) : outputDir = projectDir + .childDirectory('build') + .childDirectory(kDeferredComponentsTempDirectory), + inputs = [], + outputs = [], + title = title ?? 'Deferred components setup verification', + generatedFiles = [], + modifiedFiles = [], + invalidFiles = {}, + diffLines = []; + + /// Logger to use for [displayResults] output. + final Logger logger; + + final Platform platform; + + /// When true, failed checks and tasks will result in [attemptToolExit] + /// triggering [throwToolExit]. + final bool exitOnFail; + + /// The name of the golden file that tracks the latest loading units + /// generated. + static const String kLoadingUnitsCacheFileName = 'deferred_components_loading_units.yaml'; + /// The directory in the build folder to generate missing/modified files into. + static const String kDeferredComponentsTempDirectory = 'android_deferred_components_setup_files'; + + /// The title printed at the top of the results of [displayResults] + final String title; + + /// The root directory of the flutter project. + final Directory projectDir; + + /// The temporary directory that the validator writes recommended files into. + final Directory outputDir; + + /// Files that were newly generated by this validator. + final List generatedFiles; + + /// Existing files that were modified by this validator. + final List modifiedFiles; + + /// Files that were invalid and unable to be checked. These files are input + /// files that the validator tries to read rather than output files the + /// validator generates. The key is the file name and the value is the message + /// or reason it was invalid. + final Map invalidFiles; + + // TODO(garyq): implement the diff task. + /// Output of the diff task. + final List diffLines; + + /// Tracks the new and missing loading units. + Map? loadingUnitComparisonResults; + + /// All files read by the validator. + final List inputs; + /// All files output by the validator. + final List outputs; + + /// Returns true if there were any recommended changes that should + /// be applied. + /// + /// Returns false if no problems or recommendations were detected. + /// + /// If no checks are run, then this will default to false and will remain so + /// until a failing check finishes running. + bool get changesNeeded => generatedFiles.isNotEmpty + || modifiedFiles.isNotEmpty + || invalidFiles.isNotEmpty + || (loadingUnitComparisonResults != null && !(loadingUnitComparisonResults!['match'] as bool)); + + /// Handles the results of all executed checks by calling [displayResults] and + /// [attemptToolExit]. + /// + /// This should be called after all desired checks and tasks are executed. + void handleResults() { + displayResults(); + attemptToolExit(); + } + + static const String _thickDivider = '================================================================================='; + static const String _thinDivider = '---------------------------------------------------------------------------------'; + + /// Displays the results of this validator's executed checks and tasks in a + /// human readable format. + /// + /// All checks that are desired should be run before calling this method. + void displayResults() { + if (changesNeeded) { + logger.printStatus(_thickDivider); + logger.printStatus(title, indent: (_thickDivider.length - title.length) ~/ 2, emphasis: true); + logger.printStatus(_thickDivider); + // Log any file reading/existence errors. + if (invalidFiles.isNotEmpty) { + logger.printStatus('Errors checking the following files:\n', emphasis: true); + for (final String key in invalidFiles.keys) { + logger.printStatus(' - $key: ${invalidFiles[key]}\n'); + } + } + // Log diff file contents, with color highlighting + if (diffLines.isNotEmpty) { + logger.printStatus('Diff between `android` and expected files:', emphasis: true); + logger.printStatus(''); + for (final String line in diffLines) { + // We only care about diffs in files that have + // counterparts. + if (line.startsWith('Only in android')) { + continue; + } + TerminalColor color = TerminalColor.grey; + if (line.startsWith('+')) { + color = TerminalColor.green; + } else if (line.startsWith('-')) { + color = TerminalColor.red; + } + logger.printStatus(line, color: color); + } + logger.printStatus(''); + } + // Log any newly generated and modified files. + if (generatedFiles.isNotEmpty) { + logger.printStatus('Newly generated android files:', emphasis: true); + for (final String filePath in generatedFiles) { + final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1); + logger.printStatus(' - $shortenedPath', color: TerminalColor.grey); + } + logger.printStatus(''); + } + if (modifiedFiles.isNotEmpty) { + logger.printStatus('Modified android files:', emphasis: true); + for (final String filePath in modifiedFiles) { + final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1); + logger.printStatus(' - $shortenedPath', color: TerminalColor.grey); + } + logger.printStatus(''); + } + if (generatedFiles.isNotEmpty || modifiedFiles.isNotEmpty) { + logger.printStatus(''' +The above files have been placed into `build/$kDeferredComponentsTempDirectory`, +a temporary directory. The files should be reviewed and moved into the project's +`android` directory.'''); + if (diffLines.isNotEmpty && !platform.isWindows) { + logger.printStatus(r''' + +The recommended changes can be quickly applied by running: + + $ patch -p0 < build/setup_deferred_components.diff +'''); + } + logger.printStatus('$_thinDivider\n'); + } + // Log loading unit golden changes, if any. + if (loadingUnitComparisonResults != null) { + if ((loadingUnitComparisonResults!['new'] as List).isNotEmpty) { + logger.printStatus('New loading units were found:', emphasis: true); + for (final LoadingUnit unit in loadingUnitComparisonResults!['new'] as List) { + logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2); + } + logger.printStatus(''); + } + if ((loadingUnitComparisonResults!['missing'] as Set).isNotEmpty) { + logger.printStatus('Previously existing loading units no longer exist:', emphasis: true); + for (final LoadingUnit unit in loadingUnitComparisonResults!['missing'] as Set) { + logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2); + } + logger.printStatus(''); + } + if (loadingUnitComparisonResults!['match'] as bool) { + logger.printStatus('No change in generated loading units.\n'); + } else { + logger.printStatus(''' +It is recommended to verify that the changed loading units are expected +and to update the `deferred-components` section in `pubspec.yaml` to +incorporate any changes. The full list of generated loading units can be +referenced in the $kLoadingUnitsCacheFileName file located alongside +pubspec.yaml. + +This loading unit check will not fail again on the next build attempt +if no additional changes to the loading units are detected. +$_thinDivider\n'''); + } + } + // TODO(garyq): Add link to web tutorial/guide once it is written. + logger.printStatus(''' +Setup verification can be skipped by passing the `--no-validate-deferred-components` +flag, however, doing so may put your app at risk of not functioning even if the +build is successful. +$_thickDivider'''); + return; + } + logger.printStatus('$title passed.'); + } + + void attemptToolExit() { + if (exitOnFail && changesNeeded) { + throwToolExit('Setup for deferred components incomplete. See recommended actions.', exitCode: 1); + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle.dart new file mode 100644 index 0000000000000000000000000000000000000000..50f5ffcd9656f8caf1f915fea79b435891990180 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle.dart @@ -0,0 +1,1277 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:math'; + +import 'package:crypto/crypto.dart'; +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; +import 'package:unified_analytics/unified_analytics.dart'; +import 'package:xml/xml.dart'; + +import '../artifacts.dart'; +import '../base/analyze_size.dart'; +import '../base/common.dart'; +import '../base/deferred_component.dart'; +import '../base/file_system.dart'; +import '../base/io.dart'; +import '../base/logger.dart'; +import '../base/net.dart'; +import '../base/platform.dart'; +import '../base/process.dart'; +import '../base/project_migrator.dart'; +import '../base/terminal.dart'; +import '../base/utils.dart'; +import '../build_info.dart'; +import '../cache.dart'; +import '../convert.dart'; +import '../flutter_manifest.dart'; +import '../globals.dart' as globals; +import '../project.dart'; +import '../reporting/reporting.dart'; +import 'android_builder.dart'; +import 'android_studio.dart'; +import 'gradle_errors.dart'; +import 'gradle_utils.dart'; +import 'java.dart'; +import 'migrations/android_studio_java_gradle_conflict_migration.dart'; +import 'migrations/min_sdk_version_migration.dart'; +import 'migrations/top_level_gradle_build_file_migration.dart'; +import 'multidex.dart'; + +/// The regex to grab variant names from printBuildVariants gradle task +/// +/// The task is defined in flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy +/// +/// The expected output from the task should be similar to: +/// +/// BuildVariant: debug +/// BuildVariant: release +/// BuildVariant: profile +final RegExp _kBuildVariantRegex = RegExp('^BuildVariant: (?<$_kBuildVariantRegexGroupName>.*)\$'); +const String _kBuildVariantRegexGroupName = 'variant'; +const String _kBuildVariantTaskName = 'printBuildVariants'; + +String _getOutputAppLinkSettingsTaskFor(String buildVariant) { + return _taskForBuildVariant('output', buildVariant, 'AppLinkSettings'); +} + +/// The directory where the APK artifact is generated. +Directory getApkDirectory(FlutterProject project) { + return project.isModule + ? project.android.buildDirectory + .childDirectory('host') + .childDirectory('outputs') + .childDirectory('apk') + : project.android.buildDirectory + .childDirectory('app') + .childDirectory('outputs') + .childDirectory('flutter-apk'); +} + +/// The directory where the app bundle artifact is generated. +@visibleForTesting +Directory getBundleDirectory(FlutterProject project) { + return project.isModule + ? project.android.buildDirectory + .childDirectory('host') + .childDirectory('outputs') + .childDirectory('bundle') + : project.android.buildDirectory + .childDirectory('app') + .childDirectory('outputs') + .childDirectory('bundle'); +} + +/// The directory where the repo is generated. +/// Only applicable to AARs. +Directory getRepoDirectory(Directory buildDirectory) { + return buildDirectory + .childDirectory('outputs') + .childDirectory('repo'); +} + +/// Returns the name of Gradle task that starts with [prefix]. +String _taskFor(String prefix, BuildInfo buildInfo) { + final String buildType = camelCase(buildInfo.modeName); + final String productFlavor = buildInfo.flavor ?? ''; + return _taskForBuildVariant(prefix, '$productFlavor${sentenceCase(buildType)}'); +} + +String _taskForBuildVariant(String prefix, String buildVariant, [String suffix = '']) { + return '$prefix${sentenceCase(buildVariant)}$suffix'; +} + + +/// Returns the task to build an APK. +@visibleForTesting +String getAssembleTaskFor(BuildInfo buildInfo) { + return _taskFor('assemble', buildInfo); +} + +/// Returns the task to build an AAB. +@visibleForTesting +String getBundleTaskFor(BuildInfo buildInfo) { + return _taskFor('bundle', buildInfo); +} + +/// Returns the task to build an AAR. +@visibleForTesting +String getAarTaskFor(BuildInfo buildInfo) { + return _taskFor('assembleAar', buildInfo); +} + +/// Returns the output APK file names for a given [AndroidBuildInfo]. +/// +/// For example, when [splitPerAbi] is true, multiple APKs are created. +Iterable _apkFilesFor(AndroidBuildInfo androidBuildInfo) { + final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); + final String productFlavor = androidBuildInfo.buildInfo.lowerCasedFlavor ?? ''; + final String flavorString = productFlavor.isEmpty ? '' : '-$productFlavor'; + if (androidBuildInfo.splitPerAbi) { + return androidBuildInfo.targetArchs.map((AndroidArch arch) { + final String abi = arch.archName; + return 'app$flavorString-$abi-$buildType.apk'; + }); + } + return ['app$flavorString-$buildType.apk']; +} + +// The maximum time to wait before the tool retries a Gradle build. +const Duration kMaxRetryTime = Duration(seconds: 10); + +/// An implementation of the [AndroidBuilder] that delegates to gradle. +class AndroidGradleBuilder implements AndroidBuilder { + AndroidGradleBuilder({ + required Java? java, + required Logger logger, + required ProcessManager processManager, + required FileSystem fileSystem, + required Artifacts artifacts, + required Usage usage, + required Analytics analytics, + required GradleUtils gradleUtils, + required Platform platform, + required AndroidStudio? androidStudio, + }) : _java = java, + _logger = logger, + _fileSystem = fileSystem, + _artifacts = artifacts, + _usage = usage, + _analytics = analytics, + _gradleUtils = gradleUtils, + _androidStudio = androidStudio, + _fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform), + _processUtils = ProcessUtils(logger: logger, processManager: processManager); + + final Java? _java; + final Logger _logger; + final ProcessUtils _processUtils; + final FileSystem _fileSystem; + final Artifacts _artifacts; + final Usage _usage; + final Analytics _analytics; + final GradleUtils _gradleUtils; + final FileSystemUtils _fileSystemUtils; + final AndroidStudio? _androidStudio; + + /// Builds the AAR and POM files for the current Flutter module or plugin. + @override + Future buildAar({ + required FlutterProject project, + required Set androidBuildInfo, + required String target, + String? outputDirectoryPath, + required String buildNumber, + }) async { + Directory outputDirectory = + _fileSystem.directory(outputDirectoryPath ?? project.android.buildDirectory); + if (project.isModule) { + // Module projects artifacts are located in `build/host`. + outputDirectory = outputDirectory.childDirectory('host'); + } + for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) { + await buildGradleAar( + project: project, + androidBuildInfo: androidBuildInfo, + target: target, + outputDirectory: outputDirectory, + buildNumber: buildNumber, + ); + } + printHowToConsumeAar( + buildModes: androidBuildInfo + .map((AndroidBuildInfo androidBuildInfo) { + return androidBuildInfo.buildInfo.modeName; + }).toSet(), + androidPackage: project.manifest.androidPackage, + repoDirectory: getRepoDirectory(outputDirectory), + buildNumber: buildNumber, + logger: _logger, + fileSystem: _fileSystem, + ); + } + + /// Builds the APK. + @override + Future buildApk({ + required FlutterProject project, + required AndroidBuildInfo androidBuildInfo, + required String target, + bool configOnly = false, + }) async { + await buildGradleApp( + project: project, + androidBuildInfo: androidBuildInfo, + target: target, + isBuildingBundle: false, + localGradleErrors: gradleErrors, + configOnly: configOnly, + maxRetries: 1, + ); + } + + /// Builds the App Bundle. + @override + Future buildAab({ + required FlutterProject project, + required AndroidBuildInfo androidBuildInfo, + required String target, + bool validateDeferredComponents = true, + bool deferredComponentsEnabled = false, + bool configOnly = false, + }) async { + await buildGradleApp( + project: project, + androidBuildInfo: androidBuildInfo, + target: target, + isBuildingBundle: true, + localGradleErrors: gradleErrors, + validateDeferredComponents: validateDeferredComponents, + deferredComponentsEnabled: deferredComponentsEnabled, + configOnly: configOnly, + maxRetries: 1, + ); + } + + Future _runGradleTask( + String taskName, { + List options = const [], + required FlutterProject project + }) async { + final Status status = _logger.startProgress( + "Running Gradle task '$taskName'...", + ); + final List command = [ + _gradleUtils.getExecutable(project), + ...options, // suppresses gradle output. + taskName, + ]; + + RunResult result; + try { + result = await _processUtils.run( + command, + workingDirectory: project.android.hostAppGradleRoot.path, + allowReentrantFlutter: true, + environment: _java?.environment, + ); + } finally { + status.stop(); + } + return result; + } + + /// Builds an app. + /// + /// * [project] is typically [FlutterProject.current()]. + /// * [androidBuildInfo] is the build configuration. + /// * [target] is the target dart entry point. Typically, `lib/main.dart`. + /// * If [isBuildingBundle] is `true`, then the output artifact is an `*.aab`, + /// otherwise the output artifact is an `*.apk`. + /// * [maxRetries] If not `null`, this is the max number of build retries in case a retry is triggered. + Future buildGradleApp({ + required FlutterProject project, + required AndroidBuildInfo androidBuildInfo, + required String target, + required bool isBuildingBundle, + required List localGradleErrors, + required bool configOnly, + bool validateDeferredComponents = true, + bool deferredComponentsEnabled = false, + int retry = 0, + @visibleForTesting int? maxRetries, + }) async { + if (!project.android.isSupportedVersion) { + _exitWithUnsupportedProjectMessage(_usage, _logger.terminal, analytics: _analytics); + } + + final List migrators = [ + TopLevelGradleBuildFileMigration(project.android, _logger), + AndroidStudioJavaGradleConflictMigration(_logger, + project: project.android, + androidStudio: _androidStudio, + java: globals.java), + MinSdkVersionMigration(project.android, _logger), + ]; + + final ProjectMigration migration = ProjectMigration(migrators); + migration.run(); + + final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot); + if (usesAndroidX) { + BuildEvent('app-using-android-x', type: 'gradle', flutterUsage: _usage).send(); + _analytics.send(Event.flutterBuildInfo(label: 'app-using-android-x', buildType: 'gradle')); + } else if (!usesAndroidX) { + BuildEvent('app-not-using-android-x', type: 'gradle', flutterUsage: _usage).send(); + _analytics.send(Event.flutterBuildInfo(label: 'app-not-using-android-x', buildType: 'gradle')); + + _logger.printStatus("${_logger.terminal.warningMark} Your app isn't using AndroidX.", emphasis: true); + _logger.printStatus( + 'To avoid potential build failures, you can quickly migrate your app ' + 'by following the steps on https://goo.gl/CP92wY .', + indent: 4, + ); + } + // The default Gradle script reads the version name and number + // from the local.properties file. + updateLocalProperties( + project: project, buildInfo: androidBuildInfo.buildInfo); + + final List command = [ + // This does more than get gradlewrapper. It creates the file, ensures it + // exists and verifies the file is executable. + _gradleUtils.getExecutable(project), + ]; + + // All automatically created files should exist. + if (configOnly) { + _logger.printStatus('Config complete.'); + return; + } + + // Assembly work starts here. + final BuildInfo buildInfo = androidBuildInfo.buildInfo; + final String assembleTask = isBuildingBundle + ? getBundleTaskFor(buildInfo) + : getAssembleTaskFor(buildInfo); + + final Status status = _logger.startProgress( + "Running Gradle task '$assembleTask'...", + ); + + if (_logger.isVerbose) { + command.add('--full-stacktrace'); + command.add('--info'); + command.add('-Pverbose=true'); + } else { + command.add('-q'); + } + if (!buildInfo.androidGradleDaemon) { + command.add('--no-daemon'); + } + final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; + if (localEngineInfo != null) { + final Directory localEngineRepo = _getLocalEngineRepo( + engineOutPath: localEngineInfo.targetOutPath, + androidBuildInfo: androidBuildInfo, + fileSystem: _fileSystem, + ); + _logger.printTrace( + 'Using local engine: ${localEngineInfo.targetOutPath}\n' + 'Local Maven repo: ${localEngineRepo.path}' + ); + command.add('-Plocal-engine-repo=${localEngineRepo.path}'); + command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); + command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); + command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}'); + command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( + localEngineInfo.targetOutPath)}'); + } else if (androidBuildInfo.targetArchs.isNotEmpty) { + final String targetPlatforms = androidBuildInfo + .targetArchs + .map((AndroidArch e) => e.platformName).join(','); + command.add('-Ptarget-platform=$targetPlatforms'); + } + command.add('-Ptarget=$target'); + // Only attempt adding multidex support if all the flutter generated files exist. + // If the files do not exist and it was unintentional, the app will fail to build + // and prompt the developer if they wish Flutter to add the files again via gradle_error.dart. + if (androidBuildInfo.multidexEnabled && + multiDexApplicationExists(project.directory) && + androidManifestHasNameVariable(project.directory)) { + command.add('-Pmultidex-enabled=true'); + ensureMultiDexApplicationExists(project.directory); + _logger.printStatus('Building with Flutter multidex support enabled.'); + } + // If using v1 embedding, we want to use FlutterApplication as the base app. + final String baseApplicationName = + project.android.getEmbeddingVersion() == AndroidEmbeddingVersion.v2 ? + 'android.app.Application' : + 'io.flutter.app.FlutterApplication'; + command.add('-Pbase-application-name=$baseApplicationName'); + final List? deferredComponents = project.manifest.deferredComponents; + if (deferredComponents != null) { + if (deferredComponentsEnabled) { + command.add('-Pdeferred-components=true'); + androidBuildInfo.buildInfo.dartDefines.add('validate-deferred-components=$validateDeferredComponents'); + } + // Pass in deferred components regardless of building split aot to satisfy + // android dynamic features registry in build.gradle. + final List componentNames = []; + for (final DeferredComponent component in deferredComponents) { + componentNames.add(component.name); + } + if (componentNames.isNotEmpty) { + command.add('-Pdeferred-component-names=${componentNames.join(',')}'); + // Multi-apk applications cannot use shrinking. This is only relevant when using + // android dynamic feature modules. + _logger.printStatus( + 'Shrinking has been disabled for this build due to deferred components. Shrinking is ' + 'not available for multi-apk applications. This limitation is expected to be removed ' + 'when Gradle plugin 4.2+ is available in Flutter.', color: TerminalColor.yellow); + command.add('-Pshrink=false'); + } + } + command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); + if (buildInfo.fileSystemRoots.isNotEmpty) { + command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); + } + if (buildInfo.fileSystemScheme != null) { + command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}'); + } + if (androidBuildInfo.splitPerAbi) { + command.add('-Psplit-per-abi=true'); + } + if (androidBuildInfo.fastStart) { + command.add('-Pfast-start=true'); + } + command.add(assembleTask); + + GradleHandledError? detectedGradleError; + String? detectedGradleErrorLine; + String? consumeLog(String line) { + if (detectedGradleError != null) { + // Pipe stdout/stderr from Gradle. + return line; + } + for (final GradleHandledError gradleError in localGradleErrors) { + if (gradleError.test(line)) { + detectedGradleErrorLine = line; + detectedGradleError = gradleError; + // The first error match wins. + break; + } + } + // Pipe stdout/stderr from Gradle. + return line; + } + + final Stopwatch sw = Stopwatch() + ..start(); + int exitCode = 1; + try { + exitCode = await _processUtils.stream( + command, + workingDirectory: project.android.hostAppGradleRoot.path, + allowReentrantFlutter: true, + environment: _java?.environment, + mapFunction: consumeLog, + ); + } on ProcessException catch (exception) { + consumeLog(exception.toString()); + // Rethrow the exception if the error isn't handled by any of the + // `localGradleErrors`. + if (detectedGradleError == null) { + rethrow; + } + } finally { + status.stop(); + } + + final Duration elapsedDuration = sw.elapsed; + _usage.sendTiming('build', 'gradle', elapsedDuration); + _analytics.send(Event.timing( + workflow: 'build', + variableName: 'gradle', + elapsedMilliseconds: elapsedDuration.inMilliseconds, + )); + + if (exitCode != 0) { + if (detectedGradleError == null) { + BuildEvent('gradle-unknown-failure', type: 'gradle', flutterUsage: _usage).send(); + _analytics.send(Event.flutterBuildInfo(label: 'gradle-unknown-failure', buildType: 'gradle')); + + throwToolExit( + 'Gradle task $assembleTask failed with exit code $exitCode', + exitCode: exitCode, + ); + } + final GradleBuildStatus status = await detectedGradleError!.handler( + line: detectedGradleErrorLine!, + project: project, + usesAndroidX: usesAndroidX, + multidexEnabled: androidBuildInfo.multidexEnabled, + ); + + if (maxRetries == null || retry < maxRetries) { + switch (status) { + case GradleBuildStatus.retry: + // Use binary exponential backoff before retriggering the build. + // The expected wait times are: 100ms, 200ms, 400ms, and so on... + final int waitTime = min(pow(2, retry).toInt() * 100, kMaxRetryTime.inMicroseconds); + retry += 1; + _logger.printStatus('Retrying Gradle Build: #$retry, wait time: ${waitTime}ms'); + await Future.delayed(Duration(milliseconds: waitTime)); + await buildGradleApp( + project: project, + androidBuildInfo: androidBuildInfo, + target: target, + isBuildingBundle: isBuildingBundle, + localGradleErrors: localGradleErrors, + retry: retry, + maxRetries: maxRetries, + configOnly: configOnly, + ); + final String successEventLabel = 'gradle-${detectedGradleError!.eventLabel}-success'; + + BuildEvent(successEventLabel, type: 'gradle', flutterUsage: _usage).send(); + _analytics.send(Event.flutterBuildInfo(label: successEventLabel, buildType: 'gradle')); + + return; + case GradleBuildStatus.exit: + // Continue and throw tool exit. + } + } + final String usageLabel = 'gradle-${detectedGradleError?.eventLabel}-failure'; + BuildEvent(usageLabel, type: 'gradle', flutterUsage: _usage).send(); + _analytics.send(Event.flutterBuildInfo(label: usageLabel, buildType: 'gradle')); + + throwToolExit( + 'Gradle task $assembleTask failed with exit code $exitCode', + exitCode: exitCode, + ); + } + + if (isBuildingBundle) { + final File bundleFile = findBundleFile(project, buildInfo, _logger, _usage, _analytics); + final String appSize = (buildInfo.mode == BuildMode.debug) + ? '' // Don't display the size when building a debug variant. + : ' (${getSizeAsMB(bundleFile.lengthSync())})'; + + if (buildInfo.codeSizeDirectory != null) { + await _performCodeSizeAnalysis('aab', bundleFile, androidBuildInfo); + } + + _logger.printStatus( + '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(bundleFile.path)}$appSize.', + color: TerminalColor.green, + ); + return; + } + // Gradle produced APKs. + final Iterable apkFilesPaths = project.isModule + ? findApkFilesModule(project, androidBuildInfo, _logger, _usage, _analytics) + : listApkPaths(androidBuildInfo); + final Directory apkDirectory = getApkDirectory(project); + + // Generate sha1 for every generated APKs. + for (final File apkFile in apkFilesPaths.map(apkDirectory.childFile)) { + if (!apkFile.existsSync()) { + _exitWithExpectedFileNotFound( + project: project, + fileExtension: '.apk', + logger: _logger, + usage: _usage, + analytics: _analytics, + ); + } + + final String filename = apkFile.basename; + _logger.printTrace('Calculate SHA1: $apkDirectory/$filename'); + final File apkShaFile = apkDirectory.childFile('$filename.sha1'); + apkShaFile.writeAsStringSync(_calculateSha(apkFile)); + + final String appSize = (buildInfo.mode == BuildMode.debug) + ? '' // Don't display the size when building a debug variant. + : ' (${getSizeAsMB(apkFile.lengthSync())})'; + _logger.printStatus( + '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(apkFile.path)}$appSize.', + color: TerminalColor.green, + ); + + if (buildInfo.codeSizeDirectory != null) { + await _performCodeSizeAnalysis('apk', apkFile, androidBuildInfo); + } + } + } + + Future _performCodeSizeAnalysis(String kind, + File zipFile, + AndroidBuildInfo androidBuildInfo,) async { + final SizeAnalyzer sizeAnalyzer = SizeAnalyzer( + fileSystem: _fileSystem, + logger: _logger, + flutterUsage: _usage, + analytics: _analytics, + ); + final String archName = androidBuildInfo.targetArchs.single.archName; + final BuildInfo buildInfo = androidBuildInfo.buildInfo; + final File aotSnapshot = _fileSystem.directory(buildInfo.codeSizeDirectory) + .childFile('snapshot.$archName.json'); + final File precompilerTrace = _fileSystem.directory(buildInfo.codeSizeDirectory) + .childFile('trace.$archName.json'); + final Map output = await sizeAnalyzer.analyzeZipSizeAndAotSnapshot( + zipFile: zipFile, + aotSnapshot: aotSnapshot, + precompilerTrace: precompilerTrace, + kind: kind, + ); + final File outputFile = _fileSystemUtils.getUniqueFile( + _fileSystem + .directory(_fileSystemUtils.homeDirPath) + .childDirectory('.flutter-devtools'), '$kind-code-size-analysis', 'json', + ) + ..writeAsStringSync(jsonEncode(output)); + // This message is used as a sentinel in analyze_apk_size_test.dart + _logger.printStatus( + 'A summary of your ${kind.toUpperCase()} analysis can be found at: ${outputFile.path}', + ); + + // DevTools expects a file path relative to the .flutter-devtools/ dir. + final String relativeAppSizePath = outputFile.path + .split('.flutter-devtools/') + .last + .trim(); + _logger.printStatus( + '\nTo analyze your app size in Dart DevTools, run the following command:\n' + 'dart devtools --appSizeBase=$relativeAppSizePath' + ); + } + + /// Builds AAR and POM files. + /// + /// * [project] is typically [FlutterProject.current()]. + /// * [androidBuildInfo] is the build configuration. + /// * [outputDir] is the destination of the artifacts, + /// * [buildNumber] is the build number of the output aar, + Future buildGradleAar({ + required FlutterProject project, + required AndroidBuildInfo androidBuildInfo, + required String target, + required Directory outputDirectory, + required String buildNumber, + }) async { + final FlutterManifest manifest = project.manifest; + if (!manifest.isModule) { + throwToolExit('AARs can only be built for module projects.'); + } + + final BuildInfo buildInfo = androidBuildInfo.buildInfo; + final String aarTask = getAarTaskFor(buildInfo); + final Status status = _logger.startProgress( + "Running Gradle task '$aarTask'...", + ); + + final String flutterRoot = _fileSystem.path.absolute(Cache.flutterRoot!); + final String initScript = _fileSystem.path.join( + flutterRoot, + 'packages', + 'flutter_tools', + 'gradle', + 'aar_init_script.gradle', + ); + final List command = [ + _gradleUtils.getExecutable(project), + '-I=$initScript', + '-Pflutter-root=$flutterRoot', + '-Poutput-dir=${outputDirectory.path}', + '-Pis-plugin=${manifest.isPlugin}', + '-PbuildNumber=$buildNumber', + ]; + if (_logger.isVerbose) { + command.add('--full-stacktrace'); + command.add('--info'); + command.add('-Pverbose=true'); + } else { + command.add('-q'); + } + if (!buildInfo.androidGradleDaemon) { + command.add('--no-daemon'); + } + + if (target.isNotEmpty) { + command.add('-Ptarget=$target'); + } + command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); + if (buildInfo.dartObfuscation && buildInfo.mode != BuildMode.release) { + _logger.printStatus( + 'Dart obfuscation is not supported in ${sentenceCase(buildInfo.friendlyModeName)}' + ' mode, building as un-obfuscated.', + ); + } + + final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; + if (localEngineInfo != null) { + final Directory localEngineRepo = _getLocalEngineRepo( + engineOutPath: localEngineInfo.targetOutPath, + androidBuildInfo: androidBuildInfo, + fileSystem: _fileSystem, + ); + _logger.printTrace( + 'Using local engine: ${localEngineInfo.targetOutPath}\n' + 'Local Maven repo: ${localEngineRepo.path}' + ); + command.add('-Plocal-engine-repo=${localEngineRepo.path}'); + command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); + command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); + command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}'); + + // Copy the local engine repo in the output directory. + try { + copyDirectory( + localEngineRepo, + getRepoDirectory(outputDirectory), + ); + } on FileSystemException catch (error, st) { + throwToolExit( + 'Failed to copy the local engine ${localEngineRepo.path} repo ' + 'in ${outputDirectory.path}: $error, $st' + ); + } + command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( + localEngineInfo.targetOutPath)}'); + } else if (androidBuildInfo.targetArchs.isNotEmpty) { + final String targetPlatforms = androidBuildInfo.targetArchs + .map((AndroidArch e) => e.platformName).join(','); + command.add('-Ptarget-platform=$targetPlatforms'); + } + + command.add(aarTask); + + final Stopwatch sw = Stopwatch() + ..start(); + RunResult result; + try { + result = await _processUtils.run( + command, + workingDirectory: project.android.hostAppGradleRoot.path, + allowReentrantFlutter: true, + environment: _java?.environment, + ); + } finally { + status.stop(); + } + final Duration elapsedDuration = sw.elapsed; + _usage.sendTiming('build', 'gradle-aar', elapsedDuration); + _analytics.send(Event.timing( + workflow: 'build', + variableName: 'gradle-aar', + elapsedMilliseconds: elapsedDuration.inMilliseconds, + )); + + if (result.exitCode != 0) { + _logger.printStatus(result.stdout, wrap: false); + _logger.printError(result.stderr, wrap: false); + throwToolExit( + 'Gradle task $aarTask failed with exit code ${result.exitCode}.', + exitCode: result.exitCode, + ); + } + final Directory repoDirectory = getRepoDirectory(outputDirectory); + if (!repoDirectory.existsSync()) { + _logger.printStatus(result.stdout, wrap: false); + _logger.printError(result.stderr, wrap: false); + throwToolExit( + 'Gradle task $aarTask failed to produce $repoDirectory.', + exitCode: exitCode, + ); + } + _logger.printStatus( + '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(repoDirectory.path)}.', + color: TerminalColor.green, + ); + } + + @override + Future> getBuildVariants({required FlutterProject project}) async { + final Stopwatch sw = Stopwatch() + ..start(); + final RunResult result = await _runGradleTask( + _kBuildVariantTaskName, + options: const ['-q'], + project: project, + ); + + final Duration elapsedDuration = sw.elapsed; + _usage.sendTiming('print', 'android build variants', elapsedDuration); + _analytics.send(Event.timing( + workflow: 'print', + variableName: 'android build variants', + elapsedMilliseconds: elapsedDuration.inMilliseconds, + )); + + if (result.exitCode != 0) { + _logger.printStatus(result.stdout, wrap: false); + _logger.printError(result.stderr, wrap: false); + return const []; + } + final List options = []; + for (final String line in LineSplitter.split(result.stdout)) { + final RegExpMatch? match = _kBuildVariantRegex.firstMatch(line); + if (match != null) { + options.add(match.namedGroup(_kBuildVariantRegexGroupName)!); + } + } + return options; + } + + @override + Future outputsAppLinkSettings( + String buildVariant, { + required FlutterProject project, + }) async { + final String taskName = _getOutputAppLinkSettingsTaskFor(buildVariant); + final Directory directory = await project.buildDirectory + .childDirectory('deeplink_data').create(recursive: true); + final String outputPath = globals.fs.path.join( + directory.absolute.path, + 'app-link-settings-$buildVariant.json', + ); + final Stopwatch sw = Stopwatch() + ..start(); + final RunResult result = await _runGradleTask( + taskName, + options: ['-q', '-PoutputPath=$outputPath'], + project: project, + ); + final Duration elapsedDuration = sw.elapsed; + _usage.sendTiming('outputs', 'app link settings', elapsedDuration); + _analytics.send(Event.timing( + workflow: 'outputs', + variableName: 'app link settings', + elapsedMilliseconds: elapsedDuration.inMilliseconds, + )); + + if (result.exitCode != 0) { + _logger.printStatus(result.stdout, wrap: false); + _logger.printError(result.stderr, wrap: false); + throwToolExit(result.stderr); + } + return outputPath; + } +} + +/// Prints how to consume the AAR from a host app. +void printHowToConsumeAar({ + required Set buildModes, + String? androidPackage = 'unknown', + required Directory repoDirectory, + required Logger logger, + required FileSystem fileSystem, + String? buildNumber, +}) { + assert(buildModes.isNotEmpty); + buildNumber ??= '1.0'; + + logger.printStatus('\nConsuming the Module', emphasis: true); + logger.printStatus(''' + 1. Open ${fileSystem.path.join('', 'app', 'build.gradle')} + 2. Ensure you have the repositories configured, otherwise add them: + + String storageUrl = System.env.$kFlutterStorageBaseUrl ?: "https://storage.googleapis.com" + repositories { + maven { + url '${repoDirectory.path}' + } + maven { + url "\$storageUrl/download.flutter.io" + } + } + + 3. Make the host app depend on the Flutter module: + + dependencies {'''); + + for (final String buildMode in buildModes) { + logger.printStatus(""" + ${buildMode}Implementation '$androidPackage:flutter_$buildMode:$buildNumber'"""); + } + + logger.printStatus(''' + } +'''); + + if (buildModes.contains('profile')) { + logger.printStatus(''' + + 4. Add the `profile` build type: + + android { + buildTypes { + profile { + initWith debug + } + } + } +'''); + } + + logger.printStatus('To learn more, visit https://flutter.dev/go/build-aar'); +} + +String _hex(List bytes) { + final StringBuffer result = StringBuffer(); + for (final int part in bytes) { + result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); + } + return result.toString(); +} + +String _calculateSha(File file) { + final List bytes = file.readAsBytesSync(); + return _hex(sha1.convert(bytes).bytes); +} + +void _exitWithUnsupportedProjectMessage(Usage usage, Terminal terminal, {required Analytics analytics}) { + BuildEvent('unsupported-project', type: 'gradle', eventError: 'gradle-plugin', flutterUsage: usage).send(); + analytics.send(Event.flutterBuildInfo( + label: 'unsupported-project', + buildType: 'gradle', + error: 'gradle-plugin', + )); + + throwToolExit( + '${terminal.warningMark} Your app is using an unsupported Gradle project. ' + 'To fix this problem, create a new project by running `flutter create -t app ` ' + 'and then move the dart code, assets and pubspec.yaml to the new project.', + ); +} + +/// Returns [true] if the current app uses AndroidX. +// TODO(egarciad): https://github.com/flutter/flutter/issues/40800 +// Remove `FlutterManifest.usesAndroidX` and provide a unified `AndroidProject.usesAndroidX`. +bool isAppUsingAndroidX(Directory androidDirectory) { + final File properties = androidDirectory.childFile('gradle.properties'); + if (!properties.existsSync()) { + return false; + } + return properties.readAsStringSync().contains('android.useAndroidX=true'); +} + +/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo]. +@visibleForTesting +Iterable findApkFilesModule( + FlutterProject project, + AndroidBuildInfo androidBuildInfo, + Logger logger, + Usage usage, + Analytics analytics, +) { + final Iterable apkFileNames = _apkFilesFor(androidBuildInfo); + final Directory apkDirectory = getApkDirectory(project); + final Iterable apks = apkFileNames.expand((String apkFileName) { + File apkFile = apkDirectory.childFile(apkFileName); + if (apkFile.existsSync()) { + return [apkFile]; + } + final BuildInfo buildInfo = androidBuildInfo.buildInfo; + final String modeName = camelCase(buildInfo.modeName); + apkFile = apkDirectory + .childDirectory(modeName) + .childFile(apkFileName); + if (apkFile.existsSync()) { + return [apkFile]; + } + final String? flavor = buildInfo.flavor; + if (flavor != null) { + // Android Studio Gradle plugin v3 adds flavor to path. + apkFile = apkDirectory + .childDirectory(flavor) + .childDirectory(modeName) + .childFile(apkFileName); + if (apkFile.existsSync()) { + return [apkFile]; + } + } + return const []; + }); + if (apks.isEmpty) { + _exitWithExpectedFileNotFound( + project: project, + fileExtension: '.apk', + logger: logger, + usage: usage, + analytics: analytics, + ); + } + return apks.map((File file) => file.path); +} + +/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo]. +/// +/// The flutter.gradle plugin will copy APK outputs into: +/// `$buildDir/app/outputs/flutter-apk/app---.apk` +@visibleForTesting +Iterable listApkPaths( + AndroidBuildInfo androidBuildInfo, +) { + final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); + final List apkPartialName = [ + if (androidBuildInfo.buildInfo.flavor?.isNotEmpty ?? false) + androidBuildInfo.buildInfo.lowerCasedFlavor!, + '$buildType.apk', + ]; + if (androidBuildInfo.splitPerAbi) { + return [ + for (final AndroidArch androidArch in androidBuildInfo.targetArchs) + [ + 'app', + androidArch.archName, + ...apkPartialName, + ].join('-'), + ]; + } + return [ + [ + 'app', + ...apkPartialName, + ].join('-'), + ]; +} + +@visibleForTesting +File findBundleFile(FlutterProject project, BuildInfo buildInfo, Logger logger, Usage usage, Analytics analytics) { + final List fileCandidates = [ + getBundleDirectory(project) + .childDirectory(camelCase(buildInfo.modeName)) + .childFile('app.aab'), + getBundleDirectory(project) + .childDirectory(camelCase(buildInfo.modeName)) + .childFile('app-${buildInfo.modeName}.aab'), + ]; + if (buildInfo.flavor != null) { + // The Android Gradle plugin 3.0.0 adds the flavor name to the path. + // For example: In release mode, if the flavor name is `foo_bar`, then + // the directory name is `foo_barRelease`. + fileCandidates.add( + getBundleDirectory(project) + .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') + .childFile('app.aab')); + + // The Android Gradle plugin 3.5.0 adds the flavor name to file name. + // For example: In release mode, if the flavor name is `foo_bar`, then + // the file name is `app-foo_bar-release.aab`. + fileCandidates.add( + getBundleDirectory(project) + .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') + .childFile('app-${buildInfo.lowerCasedFlavor}-${buildInfo.modeName}.aab')); + + // The Android Gradle plugin 4.1.0 does only lowercase the first character of flavor name. + fileCandidates.add(getBundleDirectory(project) + .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') + .childFile('app-${buildInfo.uncapitalizedFlavor}-${buildInfo.modeName}.aab')); + + // The Android Gradle plugin uses kebab-case and lowercases the first character of the flavor name + // when multiple flavor dimensions are used: + // e.g. + // flavorDimensions "dimension1","dimension2" + // productFlavors { + // foo { + // dimension "dimension1" + // } + // bar { + // dimension "dimension2" + // } + // } + fileCandidates.add(getBundleDirectory(project) + .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') + .childFile('app-${kebabCase(buildInfo.uncapitalizedFlavor!)}-${buildInfo.modeName}.aab')); + } + for (final File bundleFile in fileCandidates) { + if (bundleFile.existsSync()) { + return bundleFile; + } + } + _exitWithExpectedFileNotFound( + project: project, + fileExtension: '.aab', + logger: logger, + usage: usage, + analytics: analytics, + ); +} + +/// Throws a [ToolExit] exception and logs the event. +Never _exitWithExpectedFileNotFound({ + required FlutterProject project, + required String fileExtension, + required Logger logger, + required Usage usage, + required Analytics analytics, +}) { + + final String androidGradlePluginVersion = + getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger); + final String gradleBuildSettings = 'androidGradlePluginVersion: $androidGradlePluginVersion, ' + 'fileExtension: $fileExtension'; + + BuildEvent('gradle-expected-file-not-found', + type: 'gradle', + settings: gradleBuildSettings, + flutterUsage: usage, + ).send(); + analytics.send(Event.flutterBuildInfo( + label: 'gradle-expected-file-not-found', + buildType: 'gradle', + settings: gradleBuildSettings, + )); + + throwToolExit( + 'Gradle build failed to produce an $fileExtension file. ' + "It's likely that this file was generated under ${project.android.buildDirectory.path}, " + "but the tool couldn't find it." + ); +} + +void _createSymlink(String targetPath, String linkPath, FileSystem fileSystem) { + final File targetFile = fileSystem.file(targetPath); + if (!targetFile.existsSync()) { + throwToolExit("The file $targetPath wasn't found in the local engine out directory."); + } + final File linkFile = fileSystem.file(linkPath); + final Link symlink = linkFile.parent.childLink(linkFile.basename); + try { + symlink.createSync(targetPath, recursive: true); + } on FileSystemException catch (exception) { + throwToolExit( + 'Failed to create the symlink $linkPath->$targetPath: $exception' + ); + } +} + +String _getLocalArtifactVersion(String pomPath, FileSystem fileSystem) { + final File pomFile = fileSystem.file(pomPath); + if (!pomFile.existsSync()) { + throwToolExit("The file $pomPath wasn't found in the local engine out directory."); + } + XmlDocument document; + try { + document = XmlDocument.parse(pomFile.readAsStringSync()); + } on XmlException { + throwToolExit( + 'Error parsing $pomPath. Please ensure that this is a valid XML document.' + ); + } on FileSystemException { + throwToolExit( + 'Error reading $pomPath. Please ensure that you have read permission to this ' + 'file and try again.'); + } + final Iterable project = document.findElements('project'); + assert(project.isNotEmpty); + for (final XmlElement versionElement in document.findAllElements('version')) { + if (versionElement.parent == project.first) { + return versionElement.innerText; + } + } + throwToolExit('Error while parsing the element from $pomPath'); +} + +/// Returns the local Maven repository for a local engine build. +/// For example, if the engine is built locally at /engine/src/out/android_release_unopt +/// This method generates symlinks in the temp directory to the engine artifacts +/// following the convention specified on https://maven.apache.org/pom.html#Repositories +Directory _getLocalEngineRepo({ + required String engineOutPath, + required AndroidBuildInfo androidBuildInfo, + required FileSystem fileSystem, +}) { + + final String abi = _getAbiByLocalEnginePath(engineOutPath); + final Directory localEngineRepo = fileSystem.systemTempDirectory + .createTempSync('flutter_tool_local_engine_repo.'); + final String buildMode = androidBuildInfo.buildInfo.modeName; + final String artifactVersion = _getLocalArtifactVersion( + fileSystem.path.join( + engineOutPath, + 'flutter_embedding_$buildMode.pom', + ), + fileSystem, + ); + for (final String artifact in const ['pom', 'jar']) { + // The Android embedding artifacts. + _createSymlink( + fileSystem.path.join( + engineOutPath, + 'flutter_embedding_$buildMode.$artifact', + ), + fileSystem.path.join( + localEngineRepo.path, + 'io', + 'flutter', + 'flutter_embedding_$buildMode', + artifactVersion, + 'flutter_embedding_$buildMode-$artifactVersion.$artifact', + ), + fileSystem, + ); + // The engine artifacts (libflutter.so). + _createSymlink( + fileSystem.path.join( + engineOutPath, + '${abi}_$buildMode.$artifact', + ), + fileSystem.path.join( + localEngineRepo.path, + 'io', + 'flutter', + '${abi}_$buildMode', + artifactVersion, + '${abi}_$buildMode-$artifactVersion.$artifact', + ), + fileSystem, + ); + } + for (final String artifact in ['flutter_embedding_$buildMode', '${abi}_$buildMode']) { + _createSymlink( + fileSystem.path.join( + engineOutPath, + '$artifact.maven-metadata.xml', + ), + fileSystem.path.join( + localEngineRepo.path, + 'io', + 'flutter', + artifact, + 'maven-metadata.xml', + ), + fileSystem, + ); + } + return localEngineRepo; +} + +String _getAbiByLocalEnginePath(String engineOutPath) { + String result = 'armeabi_v7a'; + if (engineOutPath.contains('x86')) { + result = 'x86'; + } else if (engineOutPath.contains('x64')) { + result = 'x86_64'; + } else if (engineOutPath.contains('arm64')) { + result = 'arm64_v8a'; + } + return result; +} + +String _getTargetPlatformByLocalEnginePath(String engineOutPath) { + String result = 'android-arm'; + if (engineOutPath.contains('x86')) { + result = 'android-x86'; + } else if (engineOutPath.contains('x64')) { + result = 'android-x64'; + } else if (engineOutPath.contains('arm64')) { + result = 'android-arm64'; + } + return result; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_errors.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_errors.dart new file mode 100644 index 0000000000000000000000000000000000000000..4246751cfff5bfad973a26861bd9572e61a03083 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_errors.dart @@ -0,0 +1,750 @@ +// 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 '../base/error_handling_io.dart'; +import '../base/file_system.dart'; +import '../base/process.dart'; +import '../base/terminal.dart'; +import '../globals.dart' as globals; +import '../project.dart'; +import '../reporting/reporting.dart'; +import 'gradle_utils.dart'; +import 'multidex.dart'; + +typedef GradleErrorTest = bool Function(String); + +/// A Gradle error handled by the tool. +class GradleHandledError { + const GradleHandledError({ + required this.test, + required this.handler, + this.eventLabel, + }); + + /// The test function. + /// Returns [true] if the current error message should be handled. + final GradleErrorTest test; + + /// The handler function. + final Future Function({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) handler; + + /// The [BuildEvent] label is named gradle-[eventLabel]. + /// If not empty, the build event is logged along with + /// additional metadata such as the attempt number. + final String? eventLabel; +} + +/// The status of the Gradle build. +enum GradleBuildStatus { + /// The tool cannot recover from the failure and should exit. + exit, + /// The tool can retry the exact same build. + retry, +} + +/// Returns a simple test function that evaluates to `true` if at least one of +/// `errorMessages` is contained in the error message. +GradleErrorTest _lineMatcher(List errorMessages) { + return (String line) { + return errorMessages.any((String errorMessage) => line.contains(errorMessage)); + }; +} + +/// The list of Gradle errors that the tool can handle. +/// +/// The handlers are executed in the order in which they appear in the list. +/// +/// Only the first error handler for which the [test] function returns [true] +/// is handled. As a result, sort error handlers based on how strict the [test] +/// function is to eliminate false positives. +final List gradleErrors = [ + licenseNotAcceptedHandler, + networkErrorHandler, + permissionDeniedErrorHandler, + flavorUndefinedHandler, + r8FailureHandler, + minSdkVersionHandler, + transformInputIssueHandler, + lockFileDepMissingHandler, + multidexErrorHandler, + incompatibleKotlinVersionHandler, + minCompileSdkVersionHandler, + jvm11RequiredHandler, + outdatedGradleHandler, + sslExceptionHandler, + zipExceptionHandler, + incompatibleJavaAndGradleVersionsHandler, + remoteTerminatedHandshakeHandler, + couldNotOpenCacheDirectoryHandler, +]; + +const String _boxTitle = 'Flutter Fix'; + +// Multidex error message. +@visibleForTesting +final GradleHandledError multidexErrorHandler = GradleHandledError( + test: _lineMatcher(const [ + 'com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:', + 'The number of method references in a .dex file cannot exceed 64K.', + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printStatus('${globals.logger.terminal.warningMark} App requires Multidex support', emphasis: true); + if (multidexEnabled) { + globals.printStatus( + 'Multidex support is required for your android app to build since the number of methods has exceeded 64k. ' + 'See https://docs.flutter.dev/deployment/android#enabling-multidex-support for more information. ' + "You may pass the --no-multidex flag to skip Flutter's multidex support to use a manual solution.\n", + indent: 4, + ); + if (!androidManifestHasNameVariable(project.directory)) { + globals.printStatus( + r'Your `android/app/src/main/AndroidManifest.xml` does not contain `android:name="${applicationName}"` ' + 'under the `application` element. This may be due to creating your project with an old version of Flutter. ' + 'Add the `android:name="\${applicationName}"` attribute to your AndroidManifest.xml to enable Flutter\'s multidex support:\n', + indent: 4, + ); + globals.printStatus(r''' + +''', + indent: 8, + color: TerminalColor.grey, + ); + + globals.printStatus( + 'You may also roll your own multidex support by following the guide at: https://developer.android.com/studio/build/multidex\n', + indent: 4, + ); + return GradleBuildStatus.exit; + } + if (!multiDexApplicationExists(project.directory)) { + globals.printStatus( + 'Flutter tool can add multidex support. The following file will be added by flutter:\n', + indent: 4, + ); + globals.printStatus( + 'android/app/src/main/java/io/flutter/app/FlutterMultiDexApplication.java\n', + indent: 8, + ); + String selection = 'n'; + // Default to 'no' if no interactive terminal. + try { + selection = await globals.terminal.promptForCharInput( + ['y', 'n'], + logger: globals.logger, + prompt: 'Do you want to continue with adding multidex support for Android?', + defaultChoiceIndex: 0, + ); + } on StateError catch (e) { + globals.printError( + e.message, + indent: 0, + ); + } + if (selection == 'y') { + ensureMultiDexApplicationExists(project.directory); + globals.printStatus( + 'Multidex enabled. Retrying build.\n', + indent: 0, + ); + return GradleBuildStatus.retry; + } + } + } else { + globals.printBox( + 'Flutter multidex handling is disabled. If you wish to let the tool configure multidex, use the --multidex flag.', + title: _boxTitle, + ); + } + return GradleBuildStatus.exit; + }, + eventLabel: 'multidex-error', +); + +// Permission defined error message. +@visibleForTesting +final GradleHandledError permissionDeniedErrorHandler = GradleHandledError( + test: _lineMatcher(const [ + 'Permission denied', + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printBox( + '${globals.logger.terminal.warningMark} Gradle does not have execution permission.\n' + 'You should change the ownership of the project directory to your user, ' + 'or move the project to a directory with execute permissions.', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'permission-denied', +); + +/// Gradle crashes for several known reasons when downloading that are not +/// actionable by Flutter. +@visibleForTesting +final GradleHandledError networkErrorHandler = GradleHandledError( + test: _lineMatcher(const [ + 'java.io.FileNotFoundException: https://downloads.gradle.org', + 'java.io.IOException: Unable to tunnel through proxy', + 'java.io.IOException: Server returned HTTP response code: 502', + 'java.lang.RuntimeException: Timeout of', + 'java.util.zip.ZipException: error in opening zip file', + 'javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake', + 'java.net.SocketException: Connection reset', + 'java.io.FileNotFoundException', + "> Could not get resource 'http", + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printError( + '${globals.logger.terminal.warningMark} ' + 'Gradle threw an error while downloading artifacts from the network.' + ); + return GradleBuildStatus.retry; + }, + eventLabel: 'network', +); + +/// Handles corrupted jar or other types of zip files. +/// +/// If a terminal is attached, this handler prompts the user if they would like to +/// delete the $HOME/.gradle directory prior to retrying the build. +/// +/// If this handler runs on a bot (e.g. a CI bot), the $HOME/.gradle is automatically deleted. +/// +/// See also: +/// * https://github.com/flutter/flutter/issues/51195 +/// * https://github.com/flutter/flutter/issues/89959 +/// * https://docs.gradle.org/current/userguide/directory_layout.html#dir:gradle_user_home +@visibleForTesting +final GradleHandledError zipExceptionHandler = GradleHandledError( + test: _lineMatcher(const [ + 'java.util.zip.ZipException: error in opening zip file', + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printError( + '${globals.logger.terminal.warningMark} ' + 'Your .gradle directory under the home directory might be corrupted.' + ); + bool shouldDeleteUserGradle = await globals.botDetector.isRunningOnBot; + if (!shouldDeleteUserGradle && globals.terminal.stdinHasTerminal) { + try { + final String selection = await globals.terminal.promptForCharInput( + ['y', 'n'], + logger: globals.logger, + prompt: 'Do you want to delete the .gradle directory under the home directory?', + defaultChoiceIndex: 0, + ); + shouldDeleteUserGradle = selection == 'y'; + } on StateError catch (e) { + globals.printError( + e.message, + indent: 0, + ); + } + } + if (shouldDeleteUserGradle) { + final String? homeDir = globals.platform.environment['HOME']; + if (homeDir == null) { + globals.logger.printStatus("Could not delete .gradle directory because there isn't a HOME env variable"); + return GradleBuildStatus.retry; + } + final Directory userGradle = globals.fs.directory(globals.fs.path.join(homeDir, '.gradle')); + globals.logger.printStatus('Deleting ${userGradle.path}'); + try { + ErrorHandlingFileSystem.deleteIfExists(userGradle, recursive: true); + } on FileSystemException catch (err) { + globals.printTrace('Failed to delete Gradle cache: $err'); + } + } + return GradleBuildStatus.retry; + }, + eventLabel: 'zip-exception', +); + +// R8 failure. +@visibleForTesting +final GradleHandledError r8FailureHandler = GradleHandledError( + test: _lineMatcher(const [ + 'com.android.tools.r8', + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printBox( + '${globals.logger.terminal.warningMark} The shrinker may have failed to optimize the Java bytecode.\n' + 'To disable the shrinker, pass the `--no-shrink` flag to this command.\n' + 'To learn more, see: https://developer.android.com/studio/build/shrink-code', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'r8', +); + +/// Handle Gradle error thrown when Gradle needs to download additional +/// Android SDK components (e.g. Platform Tools), and the license +/// for that component has not been accepted. +@visibleForTesting +final GradleHandledError licenseNotAcceptedHandler = GradleHandledError( + test: _lineMatcher(const [ + 'You have not accepted the license agreements of the following SDK components', + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + const String licenseNotAcceptedMatcher = + r'You have not accepted the license agreements of the following SDK components:\s*\[(.+)\]'; + + final RegExp licenseFailure = RegExp(licenseNotAcceptedMatcher, multiLine: true); + final Match? licenseMatch = licenseFailure.firstMatch(line); + globals.printBox( + '${globals.logger.terminal.warningMark} Unable to download needed Android SDK components, as the ' + 'following licenses have not been accepted: ' + '${licenseMatch?.group(1)}\n\n' + 'To resolve this, please run the following command in a Terminal:\n' + 'flutter doctor --android-licenses', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'license-not-accepted', +); + +final RegExp _undefinedTaskPattern = RegExp(r'Task .+ not found in root project.'); + +final RegExp _assembleTaskPattern = RegExp(r'assemble(\S+)'); + +/// Handler when a flavor is undefined. +@visibleForTesting +final GradleHandledError flavorUndefinedHandler = GradleHandledError( + test: (String line) { + return _undefinedTaskPattern.hasMatch(line); + }, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final RunResult tasksRunResult = await globals.processUtils.run( + [ + globals.gradleUtils!.getExecutable(project), + 'app:tasks' , + '--all', + '--console=auto', + ], + throwOnError: true, + workingDirectory: project.android.hostAppGradleRoot.path, + environment: globals.java?.environment, + ); + // Extract build types and product flavors. + final Set variants = {}; + for (final String task in tasksRunResult.stdout.split('\n')) { + final Match? match = _assembleTaskPattern.matchAsPrefix(task); + if (match != null) { + final String variant = match.group(1)!.toLowerCase(); + if (!variant.endsWith('test')) { + variants.add(variant); + } + } + } + final Set productFlavors = {}; + for (final String variant1 in variants) { + for (final String variant2 in variants) { + if (variant2.startsWith(variant1) && variant2 != variant1) { + final String buildType = variant2.substring(variant1.length); + if (variants.contains(buildType)) { + productFlavors.add(variant1); + } + } + } + } + final String errorMessage = '${globals.logger.terminal.warningMark} Gradle project does not define a task suitable for the requested build.'; + final File buildGradle = project.directory.childDirectory('android').childDirectory('app').childFile('build.gradle'); + if (productFlavors.isEmpty) { + globals.printBox( + '$errorMessage\n\n' + 'The ${buildGradle.absolute.path} file does not define ' + 'any custom product flavors. ' + 'You cannot use the --flavor option.', + title: _boxTitle, + ); + } else { + globals.printBox( + '$errorMessage\n\n' + 'The ${buildGradle.absolute.path} file defines product ' + 'flavors: ${productFlavors.join(', ')}. ' + 'You must specify a --flavor option to select one of them.', + title: _boxTitle, + ); + } + return GradleBuildStatus.exit; + }, + eventLabel: 'flavor-undefined', +); + + +final RegExp _minSdkVersionPattern = RegExp(r'uses-sdk:minSdkVersion ([0-9]+) cannot be smaller than version ([0-9]+) declared in library \[\:(.+)\]'); + +/// Handler when a plugin requires a higher Android API level. +@visibleForTesting +final GradleHandledError minSdkVersionHandler = GradleHandledError( + test: (String line) { + return _minSdkVersionPattern.hasMatch(line); + }, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final File gradleFile = project.directory + .childDirectory('android') + .childDirectory('app') + .childFile('build.gradle'); + + final Match? minSdkVersionMatch = _minSdkVersionPattern.firstMatch(line); + assert(minSdkVersionMatch?.groupCount == 3); + + final String textInBold = globals.logger.terminal.bolden( + 'Fix this issue by adding the following to the file ${gradleFile.path}:\n' + 'android {\n' + ' defaultConfig {\n' + ' minSdkVersion ${minSdkVersionMatch?.group(2)}\n' + ' }\n' + '}\n' + ); + globals.printBox( + 'The plugin ${minSdkVersionMatch?.group(3)} requires a higher Android SDK version.\n' + '$textInBold\n' + 'Following this change, your app will not be available to users running Android SDKs below ${minSdkVersionMatch?.group(2)}.\n' + 'Consider searching for a version of this plugin that supports these lower versions of the Android SDK instead.\n' + 'For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'plugin-min-sdk', +); + +/// Handler when https://issuetracker.google.com/issues/141126614 or +/// https://github.com/flutter/flutter/issues/58247 is triggered. +@visibleForTesting +final GradleHandledError transformInputIssueHandler = GradleHandledError( + test: (String line) { + return line.contains('https://issuetracker.google.com/issues/158753935'); + }, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final File gradleFile = project.directory + .childDirectory('android') + .childDirectory('app') + .childFile('build.gradle'); + final String textInBold = globals.logger.terminal.bolden( + 'Fix this issue by adding the following to the file ${gradleFile.path}:\n' + 'android {\n' + ' lintOptions {\n' + ' checkReleaseBuilds false\n' + ' }\n' + '}' + ); + globals.printBox( + 'This issue appears to be https://github.com/flutter/flutter/issues/58247.\n' + '$textInBold', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'transform-input-issue', +); + +/// Handler when a dependency is missing in the lockfile. +@visibleForTesting +final GradleHandledError lockFileDepMissingHandler = GradleHandledError( + test: (String line) { + return line.contains('which is not part of the dependency lock state'); + }, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final File gradleFile = project.directory + .childDirectory('android') + .childFile('build.gradle'); + final String textInBold = globals.logger.terminal.bolden( + 'To regenerate the lockfiles run: `./gradlew :generateLockfiles` in ${gradleFile.path}\n' + 'To remove dependency locking, remove the `dependencyLocking` from ${gradleFile.path}' + ); + globals.printBox( + 'You need to update the lockfile, or disable Gradle dependency locking.\n' + '$textInBold', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'lock-dep-issue', +); + +@visibleForTesting +final GradleHandledError incompatibleKotlinVersionHandler = GradleHandledError( + test: _lineMatcher(const [ + 'was compiled with an incompatible version of Kotlin', + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final File gradleFile = project.directory + .childDirectory('android') + .childFile('build.gradle'); + globals.printBox( + '${globals.logger.terminal.warningMark} Your project requires a newer version of the Kotlin Gradle plugin.\n' + 'Find the latest version on https://kotlinlang.org/docs/releases.html#release-details, then update ${gradleFile.path}:\n' + "ext.kotlin_version = ''", + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'incompatible-kotlin-version', +); + +final RegExp _outdatedGradlePattern = RegExp(r'The current Gradle version (.+) is not compatible with the Kotlin Gradle plugin'); + +@visibleForTesting +final GradleHandledError outdatedGradleHandler = GradleHandledError( + test: _outdatedGradlePattern.hasMatch, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final File gradleFile = project.directory + .childDirectory('android') + .childFile('build.gradle'); + final File gradlePropertiesFile = project.directory + .childDirectory('android') + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties'); + globals.printBox( + '${globals.logger.terminal.warningMark} Your project needs to upgrade Gradle and the Android Gradle plugin.\n\n' + 'To fix this issue, replace the following content:\n' + '${gradleFile.path}:\n' + ' ${globals.terminal.color("- classpath 'com.android.tools.build:gradle:'", TerminalColor.red)}\n' + ' ${globals.terminal.color("+ classpath 'com.android.tools.build:gradle:$templateAndroidGradlePluginVersion'", TerminalColor.green)}\n' + '${gradlePropertiesFile.path}:\n' + ' ${globals.terminal.color('- https://services.gradle.org/distributions/gradle--all.zip', TerminalColor.red)}\n' + ' ${globals.terminal.color('+ https://services.gradle.org/distributions/gradle-$templateDefaultGradleVersion-all.zip', TerminalColor.green)}', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'outdated-gradle-version', +); + +final RegExp _minCompileSdkVersionPattern = RegExp(r'The minCompileSdk \(([0-9]+)\) specified in a'); + +@visibleForTesting +final GradleHandledError minCompileSdkVersionHandler = GradleHandledError( + test: _minCompileSdkVersionPattern.hasMatch, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final Match? minCompileSdkVersionMatch = _minCompileSdkVersionPattern.firstMatch(line); + assert(minCompileSdkVersionMatch?.groupCount == 1); + + final File gradleFile = project.directory + .childDirectory('android') + .childDirectory('app') + .childFile('build.gradle'); + globals.printBox( + '${globals.logger.terminal.warningMark} Your project requires a higher compileSdk version.\n' + 'Fix this issue by bumping the compileSdk version in ${gradleFile.path}:\n' + 'android {\n' + ' compileSdk ${minCompileSdkVersionMatch?.group(1)}\n' + '}', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'min-compile-sdk-version', +); + +@visibleForTesting +final GradleHandledError jvm11RequiredHandler = GradleHandledError( + test: (String line) { + return line.contains('Android Gradle plugin requires Java 11 to run'); + }, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printBox( + '${globals.logger.terminal.warningMark} You need Java 11 or higher to build your app with this version of Gradle.\n\n' + 'To get Java 11, update to the latest version of Android Studio on https://developer.android.com/studio/install.\n\n' + 'To check the Java version used by Flutter, run `flutter doctor -v`.', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'java11-required', +); + +/// Handles SSL exceptions: https://github.com/flutter/flutter/issues/104628 +@visibleForTesting +final GradleHandledError sslExceptionHandler = GradleHandledError( + test: _lineMatcher(const [ + 'javax.net.ssl.SSLException: Tag mismatch!', + 'javax.crypto.AEADBadTagException: Tag mismatch!', + ]), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printError( + '${globals.logger.terminal.warningMark} ' + 'Gradle threw an error while downloading artifacts from the network.' + ); + return GradleBuildStatus.retry; + }, + eventLabel: 'ssl-exception-tag-mismatch', +); + +/// If an incompatible Java and Gradle versions error is caught, we expect an +/// error specifying that the Java major class file version, one of +/// https://javaalmanac.io/bytecode/versions/, is unsupported by Gradle. +final RegExp _unsupportedClassFileMajorVersionPattern = RegExp(r'Unsupported class file major version\s+\d+'); + +@visibleForTesting +final GradleHandledError incompatibleJavaAndGradleVersionsHandler = GradleHandledError( + test: (String line) { + return _unsupportedClassFileMajorVersionPattern.hasMatch(line); + }, + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + final File gradlePropertiesFile = project.directory + .childDirectory('android') + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties'); + // TODO(reidbaker): Replace URL with constant defined in + // https://github.com/flutter/flutter/pull/123916. + globals.printBox( + "${globals.logger.terminal.warningMark} Your project's Gradle version " + 'is incompatible with the Java version that Flutter is using for Gradle.\n\n' + 'If you recently upgraded Android Studio, consult the migration guide ' + 'at docs.flutter.dev/go/android-java-gradle-error.\n\n' + 'Otherwise, to fix this issue, first, check the Java version used by Flutter by ' + 'running `flutter doctor --verbose`.\n\n' + 'Then, update the Gradle version specified in ${gradlePropertiesFile.path} ' + 'to be compatible with that Java version. ' + 'See the link below for more information on compatible Java/Gradle versions:\n' + 'https://docs.gradle.org/current/userguide/compatibility.html#java\n\n', + title: _boxTitle, + ); + return GradleBuildStatus.exit; + }, + eventLabel: 'incompatible-java-gradle-version', +); + +@visibleForTesting +final GradleHandledError remoteTerminatedHandshakeHandler = GradleHandledError( + test: (String line) => line.contains('Remote host terminated the handshake'), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printError( + '${globals.logger.terminal.warningMark} ' + 'Gradle threw an error while downloading artifacts from the network.' + ); + + return GradleBuildStatus.retry; + }, + eventLabel: 'remote-terminated-handshake', +); + +@visibleForTesting +final GradleHandledError couldNotOpenCacheDirectoryHandler = GradleHandledError( + test: (String line) => line.contains('> Could not open cache directory '), + handler: ({ + required String line, + required FlutterProject project, + required bool usesAndroidX, + required bool multidexEnabled, + }) async { + globals.printError( + '${globals.logger.terminal.warningMark} ' + 'Gradle threw an error while resolving dependencies.' + ); + + return GradleBuildStatus.retry; + }, + eventLabel: 'could-not-open-cache-directory', +); diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_utils.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_utils.dart new file mode 100644 index 0000000000000000000000000000000000000000..2070de6d1accd4351e9a0a9bff0041516fc83951 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_utils.dart @@ -0,0 +1,974 @@ +// 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:process/process.dart'; +import 'package:unified_analytics/unified_analytics.dart'; + +import '../base/common.dart'; +import '../base/file_system.dart'; +import '../base/logger.dart'; +import '../base/os.dart'; +import '../base/platform.dart'; +import '../base/utils.dart'; +import '../base/version.dart'; +import '../base/version_range.dart'; +import '../build_info.dart'; +import '../cache.dart'; +import '../globals.dart' as globals; +import '../project.dart'; +import '../reporting/reporting.dart'; +import 'android_sdk.dart'; + +// These are the versions used in the project templates. +// +// In general, Flutter aims to default to the latest version. +// However, this currently requires to migrate existing integration tests to the latest supported values. +// +// Please see the README before changing any of these values. +const String templateDefaultGradleVersion = '7.6.3'; +const String templateAndroidGradlePluginVersion = '7.3.0'; +const String templateAndroidGradlePluginVersionForModule = '7.3.0'; +const String templateKotlinGradlePluginVersion = '1.7.10'; + +// The Flutter Gradle Plugin is only applied to app projects, and modules that +// are built from source using (`include_flutter.groovy`). The remaining +// projects are: plugins, and modules compiled as AARs. In modules, the +// ephemeral directory `.android` is always regenerated after `flutter pub get`, +// so new versions are picked up after a Flutter upgrade. +// +// Please see the README before changing any of these values. +const String compileSdkVersion = '34'; +const String minSdkVersion = '19'; +const String targetSdkVersion = '33'; +const String ndkVersion = '23.1.7779620'; + + +// Update these when new major versions of Java are supported by new Gradle +// versions that we support. +// Source of truth: https://docs.gradle.org/current/userguide/compatibility.html +const String oneMajorVersionHigherJavaVersion = '20'; + +// Update this when new versions of Gradle come out including minor versions +// and should correspond to the maximum Gradle version we test in CI. +// +// Supported here means supported by the tooling for +// flutter analyze --suggestions and does not imply broader flutter support. +const String maxKnownAndSupportedGradleVersion = '8.0.2'; + +// Update this when new versions of AGP come out. +// +// Supported here means tooling is aware of this version's Java <-> AGP +// compatibility. +@visibleForTesting +const String maxKnownAndSupportedAgpVersion = '8.1'; + +// Update this when new versions of AGP come out. +const String maxKnownAgpVersion = '8.3'; + +// Oldest documented version of AGP that has a listed minimum +// compatible Java version. +const String oldestDocumentedJavaAgpCompatibilityVersion = '4.2'; + +// Constant used in [_buildAndroidGradlePluginRegExp] and +// [_settingsAndroidGradlePluginRegExp] to identify the version section. +const String _versionGroupName = 'version'; + +// AGP can be defined in build.gradle +// Expected content: +// "classpath 'com.android.tools.build:gradle:7.3.0'" +// ? is used to name the version group which helps with extraction. +final RegExp _buildAndroidGradlePluginRegExp = + RegExp(r'com\.android\.tools\.build:gradle:(?\d+\.\d+\.\d+)'); + +// AGP can be defined in settings.gradle. +// Expected content: +// "id "com.android.application" version "{{agpVersion}}"" +// ? is used to name the version group which helps with extraction. +final RegExp _settingsAndroidGradlePluginRegExp = RegExp( + r'^\s+id\s+"com.android.application"\s+version\s+"(?\d+\.\d+\.\d+)"', + multiLine: true); + +// Expected content format (with lines above and below). +// Version can have 2 or 3 numbers. +// 'distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip' +// '^\s*' protects against commented out lines. +final RegExp distributionUrlRegex = + RegExp(r'^\s*distributionUrl\s*=\s*.*\.zip', multiLine: true); + +// Modified version of the gradle distribution url match designed to only match +// gradle.org urls so that we can guarantee any modifications to the url +// still points to a hosted zip. +final RegExp gradleOrgVersionMatch = + RegExp( + r'^\s*distributionUrl\s*=\s*https\\://services\.gradle\.org/distributions/gradle-((?:\d|\.)+)-(.*)\.zip', + multiLine: true + ); + +// This matches uncommented minSdkVersion lines in the module-level build.gradle +// file which have minSdkVersion 16,17, or 18 (the Jelly Bean api levels). +final RegExp jellyBeanMinSdkVersionMatch = + RegExp(r'(?<=^\s*)minSdkVersion 1[678](?=\s*(?://|$))', multiLine: true); + +// From https://docs.gradle.org/current/userguide/command_line_interface.html#command_line_interface +const String gradleVersionFlag = r'--version'; + +// Directory under android/ that gradle uses to store gradle information. +// Regularly used with [gradleWrapperDirectory] and +// [gradleWrapperPropertiesFilename]. +// Different from the directory of gradle files stored in +// `_cache.getArtifactDirectory('gradle_wrapper')` +const String gradleDirectoryName = 'gradle'; +const String gradleWrapperDirectoryName = 'wrapper'; +const String gradleWrapperPropertiesFilename = 'gradle-wrapper.properties'; + +/// Provides utilities to run a Gradle task, such as finding the Gradle executable +/// or constructing a Gradle project. +class GradleUtils { + GradleUtils({ + required Platform platform, + required Logger logger, + required Cache cache, + required OperatingSystemUtils operatingSystemUtils, + }) : _platform = platform, + _logger = logger, + _cache = cache, + _operatingSystemUtils = operatingSystemUtils; + + final Cache _cache; + final Platform _platform; + final Logger _logger; + final OperatingSystemUtils _operatingSystemUtils; + + /// Gets the Gradle executable path and prepares the Gradle project. + /// This is the `gradlew` or `gradlew.bat` script in the `android/` directory. + String getExecutable(FlutterProject project) { + final Directory androidDir = project.android.hostAppGradleRoot; + injectGradleWrapperIfNeeded(androidDir); + + final File gradle = androidDir.childFile(getGradlewFileName(_platform)); + + if (gradle.existsSync()) { + _logger.printTrace('Using gradle from ${gradle.absolute.path}.'); + // If the Gradle executable doesn't have execute permission, + // then attempt to set it. + _operatingSystemUtils.makeExecutable(gradle); + return gradle.absolute.path; + } + throwToolExit( + 'Unable to locate gradlew script. Please check that ${gradle.path} ' + 'exists or that ${gradle.dirname} can be read.'); + } + + /// Injects the Gradle wrapper files if any of these files don't exist in [directory]. + void injectGradleWrapperIfNeeded(Directory directory) { + copyDirectory( + _cache.getArtifactDirectory('gradle_wrapper'), + directory, + shouldCopyFile: (File sourceFile, File destinationFile) { + // Don't override the existing files in the project. + return !destinationFile.existsSync(); + }, + onFileCopied: (File source, File dest) { + _operatingSystemUtils.makeExecutable(dest); + } + ); + // Add the `gradle-wrapper.properties` file if it doesn't exist. + final Directory propertiesDirectory = directory + .childDirectory(gradleDirectoryName) + .childDirectory(gradleWrapperDirectoryName); + final File propertiesFile = + propertiesDirectory.childFile(gradleWrapperPropertiesFilename); + + if (propertiesFile.existsSync()) { + return; + } + propertiesDirectory.createSync(recursive: true); + final String gradleVersion = + getGradleVersionForAndroidPlugin(directory, _logger); + final String propertyContents = ''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\\://services.gradle.org/distributions/gradle-$gradleVersion-all.zip +'''; + propertiesFile.writeAsStringSync(propertyContents); + } +} + +/// Returns the Gradle version that the current Android plugin depends on when found, +/// otherwise it returns a default version. +/// +/// The Android plugin version is specified in the [build.gradle] file within +/// the project's Android directory. +String getGradleVersionForAndroidPlugin(Directory directory, Logger logger) { + final File buildFile = directory.childFile('build.gradle'); + if (!buildFile.existsSync()) { + logger.printTrace( + "$buildFile doesn't exist, assuming Gradle version: $templateDefaultGradleVersion"); + return templateDefaultGradleVersion; + } + final String buildFileContent = buildFile.readAsStringSync(); + final Iterable pluginMatches = _buildAndroidGradlePluginRegExp.allMatches(buildFileContent); + if (pluginMatches.isEmpty) { + logger.printTrace("$buildFile doesn't provide an AGP version, assuming Gradle version: $templateDefaultGradleVersion"); + return templateDefaultGradleVersion; + } + final String? androidPluginVersion = pluginMatches.first.group(1); + logger.printTrace('$buildFile provides AGP version: $androidPluginVersion'); + return getGradleVersionFor(androidPluginVersion ?? 'unknown'); +} + +/// Returns the gradle file from the top level directory. +/// The returned file is not guaranteed to be present. +File getGradleWrapperFile(Directory directory) { + return directory.childDirectory(gradleDirectoryName) + .childDirectory(gradleWrapperDirectoryName) + .childFile(gradleWrapperPropertiesFilename); +} + +/// Parses the gradle wrapper distribution url to return a string containing +/// the version number. +/// +/// Expected input is of the form '...gradle-7.4.2-all.zip', and the output +/// would be of the form '7.4.2'. +String? parseGradleVersionFromDistributionUrl(String? distributionUrl) { + if (distributionUrl == null) { + return null; + } + final List zipParts = distributionUrl.split('-'); + if (zipParts.length < 2) { + return null; + } + return zipParts[1]; +} + +/// Returns either the gradle-wrapper.properties value from the passed in +/// [directory] or if not present the version available in local path. +/// +/// If gradle version is not found null is returned. +/// [directory] should be an android directory with a build.gradle file. +Future getGradleVersion( + Directory directory, Logger logger, ProcessManager processManager) async { + final File propertiesFile = getGradleWrapperFile(directory); + + if (propertiesFile.existsSync()) { + final String wrapperFileContent = propertiesFile.readAsStringSync(); + + final RegExpMatch? distributionUrl = + distributionUrlRegex.firstMatch(wrapperFileContent); + if (distributionUrl != null) { + final String? gradleVersion = + parseGradleVersionFromDistributionUrl(distributionUrl.group(0)); + if (gradleVersion != null) { + return gradleVersion; + } else { + // Did not find gradle zip url. Likely this is a bug in our parsing. + logger.printWarning(_formatParseWarning(wrapperFileContent)); + } + } else { + // If no distributionUrl log then treat as if there was no propertiesFile. + logger.printTrace( + '$propertiesFile does not provide a Gradle version falling back to system gradle.'); + } + } else { + // Could not find properties file. + logger.printTrace( + '$propertiesFile does not exist falling back to system gradle'); + } + // System installed Gradle version. + if (processManager.canRun('gradle')) { + final String gradleVersionVerbose = + (await processManager.run(['gradle', gradleVersionFlag])).stdout + as String; + // Expected format: +/* + +------------------------------------------------------------ +Gradle 7.6 +------------------------------------------------------------ + +Build time: 2022-11-25 13:35:10 UTC +Revision: daece9dbc5b79370cc8e4fd6fe4b2cd400e150a8 + +Kotlin: 1.7.10 +Groovy: 3.0.13 +Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021 +JVM: 17.0.6 (Homebrew 17.0.6+0) +OS: Mac OS X 13.2.1 aarch64 + */ + // Observation shows that the version can have 2 or 3 numbers. + // Inner parentheticals `(\.\d+)?` denote the optional third value. + // Outer parentheticals `Gradle (...)` denote a grouping used to extract + // the version number. + final RegExp gradleVersionRegex = RegExp(r'Gradle\s+(\d+\.\d+(?:\.\d+)?)'); + final RegExpMatch? version = + gradleVersionRegex.firstMatch(gradleVersionVerbose); + if (version == null) { + // Most likely a bug in our parse implementation/regex. + logger.printWarning(_formatParseWarning(gradleVersionVerbose)); + return null; + } + return version.group(1); + } else { + logger.printTrace('Could not run system gradle'); + return null; + } +} + +/// Returns the Android Gradle Plugin (AGP) version that the current project +/// depends on when found, null otherwise. +/// +/// The Android plugin version is specified in the [build.gradle] or +/// [settings.gradle] file within the project's +/// Android directory ([androidDirectory]). +String? getAgpVersion(Directory androidDirectory, Logger logger) { + final File buildFile = androidDirectory.childFile('build.gradle'); + if (!buildFile.existsSync()) { + logger.printTrace('Can not find build.gradle in $androidDirectory'); + return null; + } + final String buildFileContent = buildFile.readAsStringSync(); + final RegExpMatch? buildMatch = + _buildAndroidGradlePluginRegExp.firstMatch(buildFileContent); + if (buildMatch != null) { + final String? androidPluginVersion = + buildMatch.namedGroup(_versionGroupName); + logger.printTrace('$buildFile provides AGP version: $androidPluginVersion'); + return androidPluginVersion; + } + logger.printTrace( + "$buildFile doesn't provide an AGP version. Checking settings."); + final File settingsFile = androidDirectory.childFile('settings.gradle'); + if (!settingsFile.existsSync()) { + logger.printTrace('$settingsFile does not exist.'); + return null; + } + final String settingsFileContent = settingsFile.readAsStringSync(); + final RegExpMatch? settingsMatch = + _settingsAndroidGradlePluginRegExp.firstMatch(settingsFileContent); + + if (settingsMatch != null) { + final String? androidPluginVersion = + settingsMatch.namedGroup(_versionGroupName); + logger.printTrace( + '$settingsFile provides AGP version: $androidPluginVersion'); + return androidPluginVersion; + } + logger.printTrace("$settingsFile doesn't provide an AGP version."); + return null; +} + +String _formatParseWarning(String content) { + return 'Could not parse gradle version from: \n' + '$content \n' + 'If there is a version please look for an existing bug ' + 'https://github.com/flutter/flutter/issues/' + ' and if one does not exist file a new issue.'; +} + +// Validate that Gradle version and AGP are compatible with each other. +// +// Returns true if versions are compatible. +// Null Gradle version or AGP version returns false. +// If compatibility can not be evaluated returns false. +// If versions are newer than the max known version a warning is logged and true +// returned. +// +// Source of truth found here: +// https://developer.android.com/studio/releases/gradle-plugin#updating-gradle +// AGP has a minimum version of gradle required but no max starting at +// AGP version 2.3.0+. +bool validateGradleAndAgp(Logger logger, + {required String? gradleV, required String? agpV}) { + + const String oldestSupportedAgpVersion = '3.3.0'; + const String oldestSupportedGradleVersion = '4.10.1'; + + if (gradleV == null || agpV == null) { + logger + .printTrace('Gradle version or AGP version unknown ($gradleV, $agpV).'); + return false; + } + + // First check if versions are too old. + if (isWithinVersionRange(agpV, + min: '0.0', max: oldestSupportedAgpVersion, inclusiveMax: false)) { + logger.printTrace('AGP Version: $agpV is too old.'); + return false; + } + if (isWithinVersionRange(gradleV, + min: '0.0', max: oldestSupportedGradleVersion, inclusiveMax: false)) { + logger.printTrace('Gradle Version: $gradleV is too old.'); + return false; + } + + // Check highest supported version before checking unknown versions. + if (isWithinVersionRange(agpV, min: '8.0', max: maxKnownAndSupportedAgpVersion)) { + return isWithinVersionRange(gradleV, + min: '8.0', max: maxKnownAndSupportedGradleVersion); + } + // Check if versions are newer than the max known versions. + if (isWithinVersionRange(agpV, + min: maxKnownAndSupportedAgpVersion, max: '100.100')) { + // Assume versions we do not know about are valid but log. + final bool validGradle = + isWithinVersionRange(gradleV, min: '8.0', max: '100.00'); + logger.printTrace('Newer than known AGP version ($agpV), gradle ($gradleV).' + '\n Treating as valid configuration.'); + return validGradle; + } + + // Begin Known Gradle <-> AGP validation. + // Max agp here is a made up version to contain all 7.4 changes. + if (isWithinVersionRange(agpV, min: '7.4', max: '7.5')) { + return isWithinVersionRange(gradleV, + min: '7.5', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange(agpV, + min: '7.3', max: '7.4', inclusiveMax: false)) { + return isWithinVersionRange(gradleV, + min: '7.4', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange(agpV, + min: '7.2', max: '7.3', inclusiveMax: false)) { + return isWithinVersionRange(gradleV, + min: '7.3.3', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange(agpV, + min: '7.1', max: '7.2', inclusiveMax: false)) { + return isWithinVersionRange(gradleV, + min: '7.2', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange(agpV, + min: '7.0', max: '7.1', inclusiveMax: false)) { + return isWithinVersionRange(gradleV, + min: '7.0', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange(agpV, + min: '4.2.0', max: '7.0', inclusiveMax: false)) { + return isWithinVersionRange(gradleV, + min: '6.7.1', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange(agpV, + min: '4.1.0', max: '4.2.0', inclusiveMax: false)) { + return isWithinVersionRange(gradleV, + min: '6.5', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange(agpV, + min: '4.0.0', max: '4.1.0', inclusiveMax: false)) { + return isWithinVersionRange(gradleV, + min: '6.1.1', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange( + agpV, + min: '3.6.0', + max: '3.6.4', + )) { + return isWithinVersionRange(gradleV, + min: '5.6.4', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange( + agpV, + min: '3.5.0', + max: '3.5.4', + )) { + return isWithinVersionRange(gradleV, + min: '5.4.1', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange( + agpV, + min: '3.4.0', + max: '3.4.3', + )) { + return isWithinVersionRange(gradleV, + min: '5.1.1', max: maxKnownAndSupportedGradleVersion); + } + if (isWithinVersionRange( + agpV, + min: '3.3.0', + max: '3.3.3', + )) { + return isWithinVersionRange(gradleV, + min: '4.10.1', max: maxKnownAndSupportedGradleVersion); + } + + logger.printTrace('Unknown Gradle-Agp compatibility, $gradleV, $agpV'); + return false; +} + +/// Validate that the [javaVersion] and Gradle version are compatible with +/// each other. +/// +/// Source of truth: +/// https://docs.gradle.org/current/userguide/compatibility.html#java +bool validateJavaAndGradle(Logger logger, + {required String? javaV, required String? gradleV}) { + // https://docs.gradle.org/current/userguide/compatibility.html#java + const String oldestSupportedJavaVersion = '1.8'; + const String oldestDocumentedJavaGradleCompatibility = '2.0'; + + // Begin Java <-> Gradle validation. + + if (javaV == null || gradleV == null) { + logger.printTrace( + 'Java version or Gradle version unknown ($javaV, $gradleV).'); + return false; + } + + // First check if versions are too old. + if (isWithinVersionRange(javaV, + min: '1.1', max: oldestSupportedJavaVersion, inclusiveMax: false)) { + logger.printTrace('Java Version: $javaV is too old.'); + return false; + } + if (isWithinVersionRange(gradleV, + min: '0.0', max: oldestDocumentedJavaGradleCompatibility, inclusiveMax: false)) { + logger.printTrace('Gradle Version: $gradleV is too old.'); + return false; + } + + // Check if versions are newer than the max supported versions. + if (isWithinVersionRange( + javaV, + min: oneMajorVersionHigherJavaVersion, + max: '100.100', + )) { + // Assume versions Java versions newer than [maxSupportedJavaVersion] + // required a higher gradle version. + final bool validGradle = isWithinVersionRange(gradleV, + min: maxKnownAndSupportedGradleVersion, max: '100.00'); + logger.printWarning( + 'Newer than known valid Java version ($javaV), gradle ($gradleV).' + '\n Treating as valid configuration.'); + return validGradle; + } + + // Begin known Java <-> Gradle evaluation. + for (final JavaGradleCompat data in _javaGradleCompatList) { + if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) { + return isWithinVersionRange(gradleV, min: data.gradleMin, max: data.gradleMax); + } + } + + logger.printTrace('Unknown Java-Gradle compatibility $javaV, $gradleV'); + return false; +} + +/// Returns compatibility information for the valid range of Gradle versions for +/// the specified Java version. +/// +/// Returns null when the tooling has not documented the compatibile Gradle +/// versions for the Java version (either the version is too old or too new). If +/// this seems like a mistake, the caller may need to update the +/// [_javaGradleCompatList] detailing Java/Gradle compatibility. +JavaGradleCompat? getValidGradleVersionRangeForJavaVersion( + Logger logger, { + required String javaV, +}) { + for (final JavaGradleCompat data in _javaGradleCompatList) { + if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) { + return data; + } + } + + logger.printTrace('Unable to determine valid Gradle version range for Java version $javaV.'); + return null; +} + +/// Validate that the specified Java and Android Gradle Plugin (AGP) versions are +/// compatible with each other. +/// +/// Returns true when the specified Java and AGP versions are +/// definitely compatible; otherwise, false is assumed by default. In addition, +/// this will return false when either a null Java or AGP version is provided. +/// +/// Source of truth are the AGP release notes: +/// https://developer.android.com/build/releases/gradle-plugin +bool validateJavaAndAgp(Logger logger, + {required String? javaV, required String? agpV}) { + if (javaV == null || agpV == null) { + logger.printTrace( + 'Java version or AGP version unknown ($javaV, $agpV).'); + return false; + } + + // Check if AGP version is too old to perform validation. + if (isWithinVersionRange(agpV, + min: '1.0', max: oldestDocumentedJavaAgpCompatibilityVersion, inclusiveMax: false)) { + logger.printTrace('AGP Version: $agpV is too old to determine Java compatibility.'); + return false; + } + + if (isWithinVersionRange(agpV, + min: maxKnownAndSupportedAgpVersion, max: '100.100', inclusiveMin: false)) { + logger.printTrace('AGP Version: $agpV is too new to determine Java compatibility.'); + return false; + } + + // Begin known Java <-> AGP evaluation. + for (final JavaAgpCompat data in _javaAgpCompatList) { + if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) { + return isWithinVersionRange(javaV, min: data.javaMin, max: '100.100'); + } + } + + logger.printTrace('Unknown Java-AGP compatibility $javaV, $agpV'); + return false; + } + + /// Returns compatibility information concerning the minimum AGP + /// version for the specified Java version. + JavaAgpCompat? getMinimumAgpVersionForJavaVersion(Logger logger, + {required String javaV}) { + for (final JavaAgpCompat data in _javaAgpCompatList) { + if (isWithinVersionRange(javaV, min: data.javaMin, max: '100.100')) { + return data; + } + } + + logger.printTrace('Unable to determine minimum AGP version for specified Java version.'); + return null; +} + +/// Returns valid Java range for specified Gradle and AGP verisons. +/// +/// Assumes that gradleV and agpV are compatible versions. +VersionRange getJavaVersionFor({required String gradleV, required String agpV}) { + // Find minimum Java version based on AGP compatibility. + String? minJavaVersion; + for (final JavaAgpCompat data in _javaAgpCompatList) { + if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) { + minJavaVersion = data.javaMin; + } + } + + // Find maximum Java version based on Gradle compatibility. + String? maxJavaVersion; + for (final JavaGradleCompat data in _javaGradleCompatList.reversed) { + if (isWithinVersionRange(gradleV, min: data.gradleMin, max: maxKnownAndSupportedGradleVersion)) { + maxJavaVersion = data.javaMax; + } + } + + return VersionRange(minJavaVersion, maxJavaVersion); +} + +/// Returns the Gradle version that is required by the given Android Gradle plugin version +/// by picking the largest compatible version from +/// https://developer.android.com/studio/releases/gradle-plugin#updating-gradle +String getGradleVersionFor(String androidPluginVersion) { + final List compatList = [ + GradleForAgp(agpMin: '1.0.0', agpMax: '1.1.3', minRequiredGradle: '2.3'), + GradleForAgp(agpMin: '1.2.0', agpMax: '1.3.1', minRequiredGradle: '2.9'), + GradleForAgp(agpMin: '1.5.0', agpMax: '1.5.0', minRequiredGradle: '2.2.1'), + GradleForAgp(agpMin: '2.0.0', agpMax: '2.1.2', minRequiredGradle: '2.13'), + GradleForAgp(agpMin: '2.1.3', agpMax: '2.2.3', minRequiredGradle: '2.14.1'), + GradleForAgp(agpMin: '2.3.0', agpMax: '2.9.9', minRequiredGradle: '3.3'), + GradleForAgp(agpMin: '3.0.0', agpMax: '3.0.9', minRequiredGradle: '4.1'), + GradleForAgp(agpMin: '3.1.0', agpMax: '3.1.9', minRequiredGradle: '4.4'), + GradleForAgp(agpMin: '3.2.0', agpMax: '3.2.1', minRequiredGradle: '4.6'), + GradleForAgp(agpMin: '3.3.0', agpMax: '3.3.2', minRequiredGradle: '4.10.2'), + GradleForAgp(agpMin: '3.4.0', agpMax: '3.5.0', minRequiredGradle: '5.6.2'), + GradleForAgp(agpMin: '4.0.0', agpMax: '4.1.0', minRequiredGradle: '6.7'), + // 7.5 is a made up value to include everything through 7.4.* + GradleForAgp(agpMin: '7.0.0', agpMax: '7.5', minRequiredGradle: '7.5'), + GradleForAgp(agpMin: '7.5.0', agpMax: '100.100', minRequiredGradle: '8.0'), + // Assume if AGP is newer than this code know about return the highest gradle + // version we know about. + GradleForAgp(agpMin: maxKnownAgpVersion, agpMax: maxKnownAgpVersion, minRequiredGradle: maxKnownAndSupportedGradleVersion), + + + ]; + for (final GradleForAgp data in compatList) { + if (isWithinVersionRange(androidPluginVersion, min: data.agpMin, max: data.agpMax)) { + return data.minRequiredGradle; + } + } + if (isWithinVersionRange(androidPluginVersion, min: maxKnownAgpVersion, max: '100.100')) { + return maxKnownAndSupportedGradleVersion; + } + throwToolExit('Unsupported Android Plugin version: $androidPluginVersion.'); +} + +/// Overwrite local.properties in the specified Flutter project's Android +/// sub-project, if needed. +/// +/// If [requireAndroidSdk] is true (the default) and no Android SDK is found, +/// this will fail with a [ToolExit]. +void updateLocalProperties({ + required FlutterProject project, + BuildInfo? buildInfo, + bool requireAndroidSdk = true, +}) { + if (requireAndroidSdk && globals.androidSdk == null) { + exitWithNoSdkMessage(); + } + final File localProperties = project.android.localPropertiesFile; + bool changed = false; + + SettingsFile settings; + if (localProperties.existsSync()) { + settings = SettingsFile.parseFromFile(localProperties); + } else { + settings = SettingsFile(); + changed = true; + } + + void changeIfNecessary(String key, String? value) { + if (settings.values[key] == value) { + return; + } + if (value == null) { + settings.values.remove(key); + } else { + settings.values[key] = value; + } + changed = true; + } + + final AndroidSdk? androidSdk = globals.androidSdk; + if (androidSdk != null) { + changeIfNecessary('sdk.dir', globals.fsUtils.escapePath(androidSdk.directory.path)); + } + + changeIfNecessary('flutter.sdk', globals.fsUtils.escapePath(Cache.flutterRoot!)); + if (buildInfo != null) { + changeIfNecessary('flutter.buildMode', buildInfo.modeName); + final String? buildName = validatedBuildNameForPlatform( + TargetPlatform.android_arm, + buildInfo.buildName ?? project.manifest.buildName, + globals.logger, + ); + changeIfNecessary('flutter.versionName', buildName); + final String? buildNumber = validatedBuildNumberForPlatform( + TargetPlatform.android_arm, + buildInfo.buildNumber ?? project.manifest.buildNumber, + globals.logger, + ); + changeIfNecessary('flutter.versionCode', buildNumber); + } + + if (changed) { + settings.writeContents(localProperties); + } +} + +/// Writes standard Android local properties to the specified [properties] file. +/// +/// Writes the path to the Android SDK, if known. +void writeLocalProperties(File properties) { + final SettingsFile settings = SettingsFile(); + final AndroidSdk? androidSdk = globals.androidSdk; + if (androidSdk != null) { + settings.values['sdk.dir'] = globals.fsUtils.escapePath(androidSdk.directory.path); + } + settings.writeContents(properties); +} + +void exitWithNoSdkMessage() { + BuildEvent('unsupported-project', + type: 'gradle', + eventError: 'android-sdk-not-found', + flutterUsage: globals.flutterUsage) + .send(); + globals.analytics.send(Event.flutterBuildInfo( + label: 'unsupported-project', + buildType: 'gradle', + error: 'android-sdk-not-found', + )); + throwToolExit('${globals.logger.terminal.warningMark} No Android SDK found. ' + 'Try setting the ANDROID_HOME environment variable.'); +} + +// Data class to hold normal/defined Java <-> Gradle compatability criteria. +// +// The [javaMax] is exclusive in terms of supporting the noted [gradleMin], +// whereas [javaMin] is inclusive. +@immutable +class JavaGradleCompat { + const JavaGradleCompat({ + required this.javaMin, + required this.javaMax, + required this.gradleMin, + required this.gradleMax, + }); + + final String javaMin; + final String javaMax; + final String gradleMin; + final String gradleMax; + + @override + bool operator ==(Object other) => + other is JavaGradleCompat && + other.javaMin == javaMin && + other.javaMax == javaMax && + other.gradleMin == gradleMin && + other.gradleMax == gradleMax; + + @override + int get hashCode => Object.hash(javaMin, javaMax, gradleMin, gradleMax); +} + +// Data class to hold defined Java <-> AGP compatibility criteria. +// +// The [agpMin] and [agpMax] are inclusive in terms of having the +// noted [javaMin] and [javaDefault] versions. +@immutable +class JavaAgpCompat { + const JavaAgpCompat({ + required this.javaMin, + required this.javaDefault, + required this.agpMin, + required this.agpMax, + }); + + final String javaMin; + final String javaDefault; + final String agpMin; + final String agpMax; + + @override + bool operator ==(Object other) => + other is JavaAgpCompat && + other.javaMin == javaMin && + other.javaDefault == javaDefault && + other.agpMin == agpMin && + other.agpMax == agpMax; + + @override + int get hashCode => Object.hash(javaMin, javaDefault, agpMin, agpMax); +} + +class GradleForAgp { + GradleForAgp({ + required this.agpMin, + required this.agpMax, + required this.minRequiredGradle, + }); + + final String agpMin; + final String agpMax; + final String minRequiredGradle; +} + +// Returns gradlew file name based on the platform. +String getGradlewFileName(Platform platform) { + if (platform.isWindows) { + return 'gradlew.bat'; + } else { + return 'gradlew'; + } +} + +/// List of compatible Java/Gradle versions. +/// +/// Should be updated when a new version of Java is supported by a new version +/// of Gradle, as https://docs.gradle.org/current/userguide/compatibility.html +/// details. +List _javaGradleCompatList = const [ + JavaGradleCompat( + javaMin: '19', + javaMax: '20', + gradleMin: '7.6', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '18', + javaMax: '19', + gradleMin: '7.5', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '17', + javaMax: '18', + gradleMin: '7.3', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '16', + javaMax: '17', + gradleMin: '7.0', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '15', + javaMax: '16', + gradleMin: '6.7', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '14', + javaMax: '15', + gradleMin: '6.3', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '13', + javaMax: '14', + gradleMin: '6.0', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '12', + javaMax: '13', + gradleMin: '5.4', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '11', + javaMax: '12', + gradleMin: '5.0', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + // 1.11 is a made up java version to cover everything in 1.10.* + JavaGradleCompat( + javaMin: '1.10', + javaMax: '1.11', + gradleMin: '4.7', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '1.9', + javaMax: '1.10', + gradleMin: '4.3', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + JavaGradleCompat( + javaMin: '1.8', + javaMax: '1.9', + gradleMin: '2.0', + gradleMax: maxKnownAndSupportedGradleVersion, + ), + ]; + + // List of compatible Java/AGP versions, where agpMax versions are inclusive. + // + // Should be updated whenever a new version of AGP is released as + // https://developer.android.com/build/releases/gradle-plugin details. + List _javaAgpCompatList = const [ + JavaAgpCompat( + javaMin: '17', + javaDefault: '17', + agpMin: '8.0', + agpMax: maxKnownAndSupportedAgpVersion, + ), + JavaAgpCompat( + javaMin: '11', + javaDefault: '11', + agpMin: '7.0', + agpMax: '7.4', + ), + JavaAgpCompat( + // You may use JDK 1.7 with AGP 4.2, but we treat 1.8 as the default since + // it is used by default for this AGP version and lower versions of Java + // are deprecated for executing Gradle. + javaMin: '1.8', + javaDefault: '1.8', + agpMin: '4.2', + agpMax: '4.2', + ), + ]; diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/android/java.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/java.dart new file mode 100644 index 0000000000000000000000000000000000000000..8830ef69dda604a3bfe856d1771169514d713bc6 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/android/java.dart @@ -0,0 +1,247 @@ +// 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:process/process.dart'; + +import '../base/config.dart'; +import '../base/file_system.dart'; +import '../base/logger.dart'; +import '../base/os.dart'; +import '../base/platform.dart'; +import '../base/process.dart'; +import '../base/version.dart'; +import 'android_studio.dart'; + +const String _javaExecutable = 'java'; + +/// Represents an installation of Java. +class Java { + Java({ + required this.javaHome, + required this.binaryPath, + required Logger logger, + required FileSystem fileSystem, + required OperatingSystemUtils os, + required Platform platform, + required ProcessManager processManager, + }): _logger = logger, + _fileSystem = fileSystem, + _os = os, + _platform = platform, + _processManager = processManager, + _processUtils = ProcessUtils(processManager: processManager, logger: logger); + + /// Within the Java ecosystem, this environment variable is typically set + /// the install location of a Java Runtime Environment (JRE) or Java + /// Development Kit (JDK). + /// + /// Tools that depend on Java and need to find it will often check this + /// variable. If you are looking to set `JAVA_HOME` when stating a process, + /// consider using the [environment] instance property instead. + static String javaHomeEnvironmentVariable = 'JAVA_HOME'; + + /// Finds the Java runtime environment that should be used for all java-dependent + /// operations across the tool. + /// + /// This searches for Java in the following places, in order: + /// + /// 1. the runtime environment bundled with Android Studio; + /// 2. the runtime environment found in the JAVA_HOME env variable, if set; or + /// 3. the java binary found on PATH. + /// + /// Returns null if no java binary could be found. + static Java? find({ + required Config config, + required AndroidStudio? androidStudio, + required Logger logger, + required FileSystem fileSystem, + required Platform platform, + required ProcessManager processManager, + }) { + final OperatingSystemUtils os = OperatingSystemUtils( + fileSystem: fileSystem, + logger: logger, + platform: platform, + processManager: processManager + ); + final String? home = _findJavaHome( + config: config, + logger: logger, + androidStudio: androidStudio, + platform: platform + ); + final String? binary = _findJavaBinary( + logger: logger, + javaHome: home, + fileSystem: fileSystem, + operatingSystemUtils: os, + platform: platform + ); + + if (binary == null) { + return null; + } + + return Java( + javaHome: home, + binaryPath: binary, + logger: logger, + fileSystem: fileSystem, + os: os, + platform: platform, + processManager: processManager, + ); + } + + /// The path of the runtime environments' home directory. + /// + /// This should only be used for logging and validation purposes. + /// If you need to set JAVA_HOME when starting a process, consider + /// using [environment] instead. + /// If you need to inspect the files of the runtime, considering adding + /// a new method to this class instead. + final String? javaHome; + + /// The path of the runtime environments' java binary. + /// + /// This should be only used for logging and validation purposes. + /// If you need to invoke the binary directly, consider adding a new method + /// to this class instead. + final String binaryPath; + + final Logger _logger; + final FileSystem _fileSystem; + final OperatingSystemUtils _os; + final Platform _platform; + final ProcessManager _processManager; + final ProcessUtils _processUtils; + + /// Returns an environment variable map with + /// 1. JAVA_HOME set if this object has a known home directory, and + /// 2. The java binary folder appended onto PATH, if the binary location is known. + /// + /// This map should be used as the environment when invoking any Java-dependent + /// processes, such as Gradle or Android SDK tools (avdmanager, sdkmanager, etc.) + Map get environment { + return { + if (javaHome != null) javaHomeEnvironmentVariable: javaHome!, + 'PATH': _fileSystem.path.dirname(binaryPath) + + _os.pathVarSeparator + + _platform.environment['PATH']!, + }; + } + + /// Returns the version of java in the format \d(.\d)+(.\d)+ + /// Returns null if version could not be determined. + late final Version? version = (() { + if (!canRun()) { + return null; + } + + final RunResult result = _processUtils.runSync( + [binaryPath, '--version'], + environment: environment, + ); + if (result.exitCode != 0) { + _logger.printTrace('java --version failed: exitCode: ${result.exitCode}' + ' stdout: ${result.stdout} stderr: ${result.stderr}'); + return null; + } + final String rawVersionOutput = result.stdout; + final List versionLines = rawVersionOutput.split('\n'); + // Should look something like 'openjdk 19.0.2 2023-01-17'. + final String longVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; + + // The contents that matter come in the format '11.0.18', '1.8.0_202 or 21'. + final RegExp jdkVersionRegex = RegExp(r'(?\d+(\.\d+(\.\d+(?:_\d+)?)?)?)'); + final Iterable matches = + jdkVersionRegex.allMatches(rawVersionOutput); + if (matches.isEmpty) { + // Fallback to second string format like "java 21.0.1 2023-09-19 LTS" + final RegExp secondJdkVersionRegex = + RegExp(r'java\s+(?\d+(\.\d+)?(\.\d+)?)\s+\d\d\d\d-\d\d-\d\d'); + final RegExpMatch? match = secondJdkVersionRegex.firstMatch(versionLines[0]); + if (match != null) { + final Version? parsedVersion = Version.parse(match.namedGroup('version')); + if (parsedVersion == null) { + return null; + } + return parsedVersion; + } + _logger.printWarning(_formatJavaVersionWarning(rawVersionOutput)); + return null; + } + final String? version = matches.first.namedGroup('version'); + if (version == null || version.split('_').isEmpty) { + _logger.printWarning(_formatJavaVersionWarning(rawVersionOutput)); + return null; + } + + // Trim away _d+ from versions 1.8 and below. + final String versionWithoutBuildInfo = version.split('_').first; + + final Version? parsedVersion = Version.parse(versionWithoutBuildInfo); + if (parsedVersion == null) { + return null; + } + return Version.withText( + parsedVersion.major, + parsedVersion.minor, + parsedVersion.patch, + longVersionText, + ); + })(); + + bool canRun() { + return _processManager.canRun(binaryPath); + } +} + +String? _findJavaHome({ + required Config config, + required Logger logger, + required AndroidStudio? androidStudio, + required Platform platform, +}) { + final Object? configured = config.getValue('jdk-dir'); + if (configured != null) { + return configured as String; + } + + final String? androidStudioJavaPath = androidStudio?.javaPath; + if (androidStudioJavaPath != null) { + return androidStudioJavaPath; + } + + final String? javaHomeEnv = platform.environment[Java.javaHomeEnvironmentVariable]; + if (javaHomeEnv != null) { + return javaHomeEnv; + } + return null; +} + +String? _findJavaBinary({ + required Logger logger, + required String? javaHome, + required FileSystem fileSystem, + required OperatingSystemUtils operatingSystemUtils, + required Platform platform, +}) { + if (javaHome != null) { + return fileSystem.path.join(javaHome, 'bin', 'java'); + } + + // Fallback to PATH based lookup. + return operatingSystemUtils.which(_javaExecutable)?.path; +} + +// Returns a user visible String that says the tool failed to parse +// the version of java along with the output. +String _formatJavaVersionWarning(String javaVersionRaw) { + return 'Could not parse java version from: \n' + '$javaVersionRaw \n' + 'If there is a version please look for an existing bug ' + 'https://github.com/flutter/flutter/issues/ ' + 'and if one does not exist file a new issue.'; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/application_package.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/application_package.dart new file mode 100644 index 0000000000000000000000000000000000000000..58ced1cd860965e99d847f581bcc1aae82e0dc6d --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/application_package.dart @@ -0,0 +1,41 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'build_info.dart'; + +abstract class ApplicationPackageFactory { + static ApplicationPackageFactory? get instance => context.get(); + + /// Create an [ApplicationPackage] for the given platform. + Future getPackageForPlatform( + TargetPlatform platform, { + BuildInfo? buildInfo, + File? applicationBinary, + }); +} + +abstract class ApplicationPackage { + ApplicationPackage({ required this.id }); + + /// Package ID from the Android Manifest or equivalent. + final String id; + + String? get name; + + String? get displayName => name; + + @override + String toString() => displayName ?? id; +} + +/// An interface for application package that is created from prebuilt binary. +abstract class PrebuiltApplicationPackage implements ApplicationPackage { + /// The application bundle of the prebuilt application. + /// + /// The same ApplicationPackage should be able to be recreated by passing + /// the file to [FlutterApplicationPackageFactory.getPackageForPlatform]. + FileSystemEntity get applicationPackage; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/artifacts.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/artifacts.dart new file mode 100644 index 0000000000000000000000000000000000000000..386741a0e40df65f52d1c3cb00d29b3a22286c61 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/artifacts.dart @@ -0,0 +1,1468 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:file/memory.dart'; +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import 'base/common.dart'; +import 'base/file_system.dart'; +import 'base/os.dart'; +import 'base/platform.dart'; +import 'base/user_messages.dart'; +import 'base/utils.dart'; +import 'build_info.dart'; +import 'cache.dart'; +import 'globals.dart' as globals; + +enum Artifact { + /// The tool which compiles a dart kernel file into native code. + genSnapshot, + /// The flutter tester binary. + flutterTester, + flutterFramework, + flutterXcframework, + /// The framework directory of the macOS desktop. + flutterMacOSFramework, + vmSnapshotData, + isolateSnapshotData, + icuData, + platformKernelDill, + platformLibrariesJson, + flutterPatchedSdkPath, + + /// The root directory of the dart SDK. + engineDartSdkPath, + /// The dart binary used to execute any of the required snapshots. + engineDartBinary, + /// The dart binary for running aot snapshots + engineDartAotRuntime, + /// The snapshot of frontend_server compiler. + frontendServerSnapshotForEngineDartSdk, + /// The dart snapshot of the dart2js compiler. + dart2jsSnapshot, + /// The dart snapshot of the dart2wasm compiler. + dart2wasmSnapshot, + /// The wasm-opt binary that ships with the dart-sdk + wasmOptBinary, + + /// The root of the Linux desktop sources. + linuxDesktopPath, + // The root of the cpp headers for Linux desktop. + linuxHeaders, + /// The root of the Windows desktop sources. + windowsDesktopPath, + /// The root of the cpp client code for Windows desktop. + windowsCppClientWrapper, + + /// The root of the sky_engine package. + skyEnginePath, + + // Fuchsia artifacts from the engine prebuilts. + fuchsiaKernelCompiler, + fuchsiaFlutterRunner, + + /// Tools related to subsetting or icon font files. + fontSubset, + constFinder, + + /// The location of file generators. + flutterToolsFileGenerators, + + /// Pre-built desktop debug app. + flutterPreviewDevice, +} + +/// A subset of [Artifact]s that are platform and build mode independent +enum HostArtifact { + /// The root of the web implementation of the dart SDK. + flutterWebSdk, + /// The libraries JSON file for web release builds. + flutterWebLibrariesJson, + + // The flutter.js bootstrapping file provided by the engine. + flutterJsDirectory, + + /// Folder that contains platform dill files for the web sdk. + webPlatformKernelFolder, + + /// The summary dill for the dartdevc target. + webPlatformDDCKernelDill, + /// The summary dill with null safety enabled for the dartdevc target.g + webPlatformDDCSoundKernelDill, + /// The summary dill for the dartdevc target. + webPlatformDart2JSKernelDill, + /// The summary dill with null safety enabled for the dartdevc target. + webPlatformDart2JSSoundKernelDill, + + /// The precompiled SDKs and sourcemaps for web debug builds. + webPrecompiledSdk, + webPrecompiledSdkSourcemaps, + webPrecompiledCanvaskitSdk, + webPrecompiledCanvaskitSdkSourcemaps, + webPrecompiledCanvaskitAndHtmlSdk, + webPrecompiledCanvaskitAndHtmlSdkSourcemaps, + webPrecompiledSoundSdk, + webPrecompiledSoundSdkSourcemaps, + webPrecompiledCanvaskitSoundSdk, + webPrecompiledCanvaskitSoundSdkSourcemaps, + webPrecompiledCanvaskitAndHtmlSoundSdk, + webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps, + + iosDeploy, + idevicesyslog, + idevicescreenshot, + iproxy, + + /// The root of the sky_engine package. + skyEnginePath, + + // The Impeller shader compiler. + impellerc, + // The Impeller Scene 3D model importer. + scenec, + // Impeller's tessellation library. + libtessellator, +} + +// TODO(knopp): Remove once darwin artifacts are universal and moved out of darwin-x64 +String _enginePlatformDirectoryName(TargetPlatform platform) { + if (platform == TargetPlatform.darwin) { + return 'darwin-x64'; + } + return getNameForTargetPlatform(platform); +} + +// Remove android target platform type. +TargetPlatform? _mapTargetPlatform(TargetPlatform? targetPlatform) { + switch (targetPlatform) { + case TargetPlatform.android: + return TargetPlatform.android_arm64; + case TargetPlatform.ios: + case TargetPlatform.darwin: + case TargetPlatform.linux_x64: + case TargetPlatform.linux_arm64: + case TargetPlatform.windows_x64: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + case null: + return targetPlatform; + } +} + +String? _artifactToFileName(Artifact artifact, Platform hostPlatform, [ BuildMode? mode ]) { + final String exe = hostPlatform.isWindows ? '.exe' : ''; + switch (artifact) { + case Artifact.genSnapshot: + return 'gen_snapshot'; + case Artifact.flutterTester: + return 'flutter_tester$exe'; + case Artifact.flutterFramework: + return 'Flutter.framework'; + case Artifact.flutterXcframework: + return 'Flutter.xcframework'; + case Artifact.flutterMacOSFramework: + return 'FlutterMacOS.framework'; + case Artifact.vmSnapshotData: + return 'vm_isolate_snapshot.bin'; + case Artifact.isolateSnapshotData: + return 'isolate_snapshot.bin'; + case Artifact.icuData: + return 'icudtl.dat'; + case Artifact.platformKernelDill: + return 'platform_strong.dill'; + case Artifact.platformLibrariesJson: + return 'libraries.json'; + case Artifact.flutterPatchedSdkPath: + assert(false, 'No filename for sdk path, should not be invoked'); + return null; + case Artifact.engineDartSdkPath: + return 'dart-sdk'; + case Artifact.engineDartBinary: + return 'dart$exe'; + case Artifact.engineDartAotRuntime: + return 'dartaotruntime$exe'; + case Artifact.dart2jsSnapshot: + return 'dart2js.dart.snapshot'; + case Artifact.dart2wasmSnapshot: + return 'dart2wasm_product.snapshot'; + case Artifact.wasmOptBinary: + return 'wasm-opt$exe'; + case Artifact.frontendServerSnapshotForEngineDartSdk: + return 'frontend_server_aot.dart.snapshot'; + case Artifact.linuxDesktopPath: + return ''; + case Artifact.linuxHeaders: + return 'flutter_linux'; + case Artifact.windowsCppClientWrapper: + return 'cpp_client_wrapper'; + case Artifact.windowsDesktopPath: + return ''; + case Artifact.skyEnginePath: + return 'sky_engine'; + case Artifact.fuchsiaKernelCompiler: + return 'kernel_compiler.snapshot'; + case Artifact.fuchsiaFlutterRunner: + final String jitOrAot = mode!.isJit ? '_jit' : '_aot'; + final String productOrNo = mode.isRelease ? '_product' : ''; + return 'flutter$jitOrAot${productOrNo}_runner-0.far'; + case Artifact.fontSubset: + return 'font-subset$exe'; + case Artifact.constFinder: + return 'const_finder.dart.snapshot'; + case Artifact.flutterToolsFileGenerators: + return ''; + case Artifact.flutterPreviewDevice: + return 'flutter_preview$exe'; + } +} + +String _hostArtifactToFileName(HostArtifact artifact, Platform platform) { + final String exe = platform.isWindows ? '.exe' : ''; + String dll = '.so'; + if (platform.isWindows) { + dll = '.dll'; + } else if (platform.isMacOS) { + dll = '.dylib'; + } + switch (artifact) { + case HostArtifact.flutterWebSdk: + return ''; + case HostArtifact.flutterJsDirectory: + return 'flutter_js'; + case HostArtifact.iosDeploy: + return 'ios-deploy'; + case HostArtifact.idevicesyslog: + return 'idevicesyslog'; + case HostArtifact.idevicescreenshot: + return 'idevicescreenshot'; + case HostArtifact.iproxy: + return 'iproxy'; + case HostArtifact.skyEnginePath: + return 'sky_engine'; + case HostArtifact.webPlatformKernelFolder: + return 'kernel'; + case HostArtifact.webPlatformDDCKernelDill: + return 'ddc_outline.dill'; + case HostArtifact.webPlatformDDCSoundKernelDill: + return 'ddc_outline_sound.dill'; + case HostArtifact.webPlatformDart2JSKernelDill: + return 'dart2js_platform_unsound.dill'; + case HostArtifact.webPlatformDart2JSSoundKernelDill: + return 'dart2js_platform.dill'; + case HostArtifact.flutterWebLibrariesJson: + return 'libraries.json'; + case HostArtifact.webPrecompiledSdk: + case HostArtifact.webPrecompiledCanvaskitSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: + case HostArtifact.webPrecompiledSoundSdk: + case HostArtifact.webPrecompiledCanvaskitSoundSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: + return 'dart_sdk.js'; + case HostArtifact.webPrecompiledSdkSourcemaps: + case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: + case HostArtifact.webPrecompiledSoundSdkSourcemaps: + case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: + return 'dart_sdk.js.map'; + case HostArtifact.impellerc: + return 'impellerc$exe'; + case HostArtifact.scenec: + return 'scenec$exe'; + case HostArtifact.libtessellator: + return 'libtessellator$dll'; + } +} + +class EngineBuildPaths { + const EngineBuildPaths({ + required this.targetEngine, + required this.hostEngine, + required this.webSdk, + }); + + final String? targetEngine; + final String? hostEngine; + final String? webSdk; +} + +/// Information about a local engine build (i.e. `--local-engine[-host]=...`). +/// +/// See https://github.com/flutter/flutter/wiki/The-flutter-tool#using-a-locally-built-engine-with-the-flutter-tool +/// for more information about local engine builds. +class LocalEngineInfo { + /// Creates a reference to a local engine build. + /// + /// The [targetOutPath] and [hostOutPath] are assumed to be resolvable + /// paths to the built engine artifacts for the target (device) and host + /// (build) platforms, respectively. + const LocalEngineInfo({ + required this.targetOutPath, + required this.hostOutPath, + }); + + /// The path to the engine artifacts for the target (device) platform. + /// + /// For example, if the target platform is Android debug, this would be a path + /// like `/path/to/engine/src/out/android_debug_unopt`. To retrieve just the + /// name (platform), see [localTargetName]. + final String targetOutPath; + + /// The path to the engine artifacts for the host (build) platform. + /// + /// For example, if the host platform is debug, this would be a path like + /// `/path/to/engine/src/out/host_debug_unopt`. To retrieve just the name + /// (platform), see [localHostName]. + final String hostOutPath; + + /// The name of the target (device) platform, i.e. `android_debug_unopt`. + String get localTargetName => globals.fs.path.basename(targetOutPath); + + /// The name of the host (build) platform, e.g. `host_debug_unopt`. + String get localHostName => globals.fs.path.basename(hostOutPath); +} + +// Manages the engine artifacts of Flutter. +abstract class Artifacts { + /// A test-specific implementation of artifacts that returns stable paths for + /// all artifacts. + /// + /// If a [fileSystem] is not provided, creates a new [MemoryFileSystem] instance. + /// + /// Creates a [LocalEngineArtifacts] if `localEngine` is non-null + @visibleForTesting + factory Artifacts.test({FileSystem? fileSystem}) { + return _TestArtifacts(fileSystem ?? MemoryFileSystem.test()); + } + + /// A test-specific implementation of artifacts that returns stable paths for + /// all artifacts, and uses a local engine. + /// + /// If a [fileSystem] is not provided, creates a new [MemoryFileSystem] instance. + @visibleForTesting + factory Artifacts.testLocalEngine({ + required String localEngine, + required String localEngineHost, + FileSystem? fileSystem, + }) { + return _TestLocalEngine( + localEngine, localEngineHost, fileSystem ?? MemoryFileSystem.test()); + } + + static Artifacts getLocalEngine(EngineBuildPaths engineBuildPaths) { + Artifacts artifacts = CachedArtifacts( + fileSystem: globals.fs, + platform: globals.platform, + cache: globals.cache, + operatingSystemUtils: globals.os + ); + if (engineBuildPaths.hostEngine != null && engineBuildPaths.targetEngine != null) { + artifacts = CachedLocalEngineArtifacts( + engineBuildPaths.hostEngine!, + engineOutPath: engineBuildPaths.targetEngine!, + cache: globals.cache, + fileSystem: globals.fs, + processManager: globals.processManager, + platform: globals.platform, + operatingSystemUtils: globals.os, + parent: artifacts, + ); + } + if (engineBuildPaths.webSdk != null) { + artifacts = CachedLocalWebSdkArtifacts( + parent: artifacts, + webSdkPath: engineBuildPaths.webSdk!, + fileSystem: globals.fs, + platform: globals.platform, + operatingSystemUtils: globals.os + ); + } + return artifacts; + } + + /// Returns the requested [artifact] for the [platform], [mode], and [environmentType] combination. + String getArtifactPath( + Artifact artifact, { + TargetPlatform? platform, + BuildMode? mode, + EnvironmentType? environmentType, + }); + + /// Retrieve a host specific artifact that does not depend on the + /// current build mode or environment. + FileSystemEntity getHostArtifact( + HostArtifact artifact, + ); + + // Returns which set of engine artifacts is currently used for the [platform] + // and [mode] combination. + String getEngineType(TargetPlatform platform, [ BuildMode? mode ]); + + /// Whether these artifacts correspond to a non-versioned local engine. + bool get isLocalEngine; + + /// If these artifacts are bound to a local engine build, returns info about + /// the location and name of the local engine, otherwise returns null. + LocalEngineInfo? get localEngineInfo; +} + +/// Manages the engine artifacts downloaded to the local cache. +class CachedArtifacts implements Artifacts { + CachedArtifacts({ + required FileSystem fileSystem, + required Platform platform, + required Cache cache, + required OperatingSystemUtils operatingSystemUtils, + }) : _fileSystem = fileSystem, + _platform = platform, + _cache = cache, + _operatingSystemUtils = operatingSystemUtils; + + final FileSystem _fileSystem; + final Platform _platform; + final Cache _cache; + final OperatingSystemUtils _operatingSystemUtils; + + @override + LocalEngineInfo? get localEngineInfo => null; + + @override + FileSystemEntity getHostArtifact( + HostArtifact artifact, + ) { + switch (artifact) { + case HostArtifact.flutterWebSdk: + final String path = _getFlutterWebSdkPath(); + return _fileSystem.directory(path); + case HostArtifact.flutterWebLibrariesJson: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.flutterJsDirectory: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); + return _fileSystem.directory(path); + case HostArtifact.webPlatformKernelFolder: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); + return _fileSystem.file(path); + case HostArtifact.webPlatformDDCKernelDill: + case HostArtifact.webPlatformDDCSoundKernelDill: + case HostArtifact.webPlatformDart2JSKernelDill: + case HostArtifact.webPlatformDart2JSSoundKernelDill: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledSdk: + case HostArtifact.webPrecompiledSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitSdk: + case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledSoundSdk: + case HostArtifact.webPrecompiledSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitSoundSdk: + case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.idevicesyslog: + case HostArtifact.idevicescreenshot: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + return _cache.getArtifactDirectory('libimobiledevice').childFile(artifactFileName); + case HostArtifact.skyEnginePath: + final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); + final String path = _fileSystem.path.join(dartPackageDirectory.path, _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.directory(path); + case HostArtifact.iosDeploy: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + return _cache.getArtifactDirectory('ios-deploy').childFile(artifactFileName); + case HostArtifact.iproxy: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + return _cache.getArtifactDirectory('usbmuxd').childFile(artifactFileName); + case HostArtifact.impellerc: + case HostArtifact.scenec: + case HostArtifact.libtessellator: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + final String engineDir = _getEngineArtifactsPath(_currentHostPlatform(_platform, _operatingSystemUtils))!; + return _fileSystem.file(_fileSystem.path.join(engineDir, artifactFileName)); + } + } + + @override + String getArtifactPath( + Artifact artifact, { + TargetPlatform? platform, + BuildMode? mode, + EnvironmentType? environmentType, + }) { + platform = _mapTargetPlatform(platform); + switch (platform) { + case TargetPlatform.android: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + assert(platform != TargetPlatform.android); + return _getAndroidArtifactPath(artifact, platform!, mode!); + case TargetPlatform.ios: + return _getIosArtifactPath(artifact, platform!, mode, environmentType); + case TargetPlatform.darwin: + case TargetPlatform.linux_x64: + case TargetPlatform.linux_arm64: + case TargetPlatform.windows_x64: + return _getDesktopArtifactPath(artifact, platform, mode); + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + return _getFuchsiaArtifactPath(artifact, platform!, mode!); + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case null: + return _getHostArtifactPath(artifact, platform ?? _currentHostPlatform(_platform, _operatingSystemUtils), mode); + } + } + + @override + String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { + return _fileSystem.path.basename(_getEngineArtifactsPath(platform, mode)!); + } + + String _getDesktopArtifactPath(Artifact artifact, TargetPlatform? platform, BuildMode? mode) { + // When platform is null, a generic host platform artifact is being requested + // and not the gen_snapshot for darwin as a target platform. + if (platform != null && artifact == Artifact.genSnapshot) { + final String engineDir = _getEngineArtifactsPath(platform, mode)!; + return _fileSystem.path.join(engineDir, _artifactToFileName(artifact, _platform)); + } + return _getHostArtifactPath(artifact, platform ?? _currentHostPlatform(_platform, _operatingSystemUtils), mode); + } + + String _getAndroidArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) { + final String engineDir = _getEngineArtifactsPath(platform, mode)!; + switch (artifact) { + case Artifact.genSnapshot: + assert(mode != BuildMode.debug, 'Artifact $artifact only available in non-debug mode.'); + final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform()); + return _fileSystem.path.join(engineDir, hostPlatform, _artifactToFileName(artifact, _platform)); + case Artifact.engineDartSdkPath: + case Artifact.engineDartBinary: + case Artifact.engineDartAotRuntime: + case Artifact.dart2jsSnapshot: + case Artifact.dart2wasmSnapshot: + case Artifact.wasmOptBinary: + case Artifact.frontendServerSnapshotForEngineDartSdk: + case Artifact.constFinder: + case Artifact.flutterFramework: + case Artifact.flutterMacOSFramework: + case Artifact.flutterPatchedSdkPath: + case Artifact.flutterTester: + case Artifact.flutterXcframework: + case Artifact.fontSubset: + case Artifact.fuchsiaFlutterRunner: + case Artifact.fuchsiaKernelCompiler: + case Artifact.icuData: + case Artifact.isolateSnapshotData: + case Artifact.linuxDesktopPath: + case Artifact.linuxHeaders: + case Artifact.platformKernelDill: + case Artifact.platformLibrariesJson: + case Artifact.skyEnginePath: + case Artifact.vmSnapshotData: + case Artifact.windowsCppClientWrapper: + case Artifact.windowsDesktopPath: + case Artifact.flutterToolsFileGenerators: + case Artifact.flutterPreviewDevice: + return _getHostArtifactPath(artifact, platform, mode); + } + } + + String _getIosArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode, EnvironmentType? environmentType) { + switch (artifact) { + case Artifact.genSnapshot: + case Artifact.flutterXcframework: + final String artifactFileName = _artifactToFileName(artifact, _platform)!; + final String engineDir = _getEngineArtifactsPath(platform, mode)!; + return _fileSystem.path.join(engineDir, artifactFileName); + case Artifact.flutterFramework: + final String engineDir = _getEngineArtifactsPath(platform, mode)!; + return _getIosEngineArtifactPath(engineDir, environmentType, _fileSystem, _platform); + case Artifact.engineDartSdkPath: + case Artifact.engineDartBinary: + case Artifact.engineDartAotRuntime: + case Artifact.dart2jsSnapshot: + case Artifact.dart2wasmSnapshot: + case Artifact.wasmOptBinary: + case Artifact.frontendServerSnapshotForEngineDartSdk: + case Artifact.constFinder: + case Artifact.flutterMacOSFramework: + case Artifact.flutterPatchedSdkPath: + case Artifact.flutterTester: + case Artifact.fontSubset: + case Artifact.fuchsiaFlutterRunner: + case Artifact.fuchsiaKernelCompiler: + case Artifact.icuData: + case Artifact.isolateSnapshotData: + case Artifact.linuxDesktopPath: + case Artifact.linuxHeaders: + case Artifact.platformKernelDill: + case Artifact.platformLibrariesJson: + case Artifact.skyEnginePath: + case Artifact.vmSnapshotData: + case Artifact.windowsCppClientWrapper: + case Artifact.windowsDesktopPath: + case Artifact.flutterToolsFileGenerators: + case Artifact.flutterPreviewDevice: + return _getHostArtifactPath(artifact, platform, mode); + } + } + + String _getFuchsiaArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) { + final String root = _fileSystem.path.join( + _cache.getArtifactDirectory('flutter_runner').path, + 'flutter', + platform.fuchsiaArchForTargetPlatform, + mode.isRelease ? 'release' : mode.toString(), + ); + final String runtime = mode.isJit ? 'jit' : 'aot'; + switch (artifact) { + case Artifact.genSnapshot: + final String genSnapshot = mode.isRelease ? 'gen_snapshot_product' : 'gen_snapshot'; + return _fileSystem.path.join(root, runtime, 'dart_binaries', genSnapshot); + case Artifact.flutterPatchedSdkPath: + const String artifactFileName = 'flutter_runner_patched_sdk'; + return _fileSystem.path.join(root, runtime, artifactFileName); + case Artifact.platformKernelDill: + final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; + return _fileSystem.path.join(root, runtime, 'flutter_runner_patched_sdk', artifactFileName); + case Artifact.fuchsiaKernelCompiler: + final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; + return _fileSystem.path.join(root, runtime, 'dart_binaries', artifactFileName); + case Artifact.fuchsiaFlutterRunner: + final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; + return _fileSystem.path.join(root, runtime, artifactFileName); + case Artifact.constFinder: + case Artifact.flutterFramework: + case Artifact.flutterMacOSFramework: + case Artifact.flutterTester: + case Artifact.flutterXcframework: + case Artifact.fontSubset: + case Artifact.engineDartSdkPath: + case Artifact.engineDartBinary: + case Artifact.engineDartAotRuntime: + case Artifact.dart2jsSnapshot: + case Artifact.dart2wasmSnapshot: + case Artifact.wasmOptBinary: + case Artifact.frontendServerSnapshotForEngineDartSdk: + case Artifact.icuData: + case Artifact.isolateSnapshotData: + case Artifact.linuxDesktopPath: + case Artifact.linuxHeaders: + case Artifact.platformLibrariesJson: + case Artifact.skyEnginePath: + case Artifact.vmSnapshotData: + case Artifact.windowsCppClientWrapper: + case Artifact.windowsDesktopPath: + case Artifact.flutterToolsFileGenerators: + case Artifact.flutterPreviewDevice: + return _getHostArtifactPath(artifact, platform, mode); + } + } + + String _getFlutterPatchedSdkPath(BuildMode? mode) { + final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; + return _fileSystem.path.join(engineArtifactsPath, 'common', + mode == BuildMode.release ? 'flutter_patched_sdk_product' : 'flutter_patched_sdk'); + } + + String _getFlutterWebSdkPath() { + return _cache.getWebSdkDirectory().path; + } + + String _getHostArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode) { + switch (artifact) { + case Artifact.genSnapshot: + // For script snapshots any gen_snapshot binary will do. Returning gen_snapshot for + // android_arm in profile mode because it is available on all supported host platforms. + return _getAndroidArtifactPath(artifact, TargetPlatform.android_arm, BuildMode.profile); + case Artifact.dart2jsSnapshot: + case Artifact.dart2wasmSnapshot: + case Artifact.frontendServerSnapshotForEngineDartSdk: + return _fileSystem.path.join( + _dartSdkPath(_cache), 'bin', 'snapshots', + _artifactToFileName(artifact, _platform), + ); + case Artifact.wasmOptBinary: + return _fileSystem.path.join( + _dartSdkPath(_cache), 'bin', 'utils', + _artifactToFileName(artifact, _platform), + ); + case Artifact.flutterTester: + case Artifact.vmSnapshotData: + case Artifact.isolateSnapshotData: + case Artifact.icuData: + final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; + final String platformDirName = _enginePlatformDirectoryName(platform); + return _fileSystem.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact, _platform, mode)); + case Artifact.platformKernelDill: + return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), _artifactToFileName(artifact, _platform)); + case Artifact.platformLibrariesJson: + return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), 'lib', _artifactToFileName(artifact, _platform)); + case Artifact.flutterPatchedSdkPath: + return _getFlutterPatchedSdkPath(mode); + case Artifact.engineDartSdkPath: + return _dartSdkPath(_cache); + case Artifact.engineDartBinary: + case Artifact.engineDartAotRuntime: + return _fileSystem.path.join(_dartSdkPath(_cache), 'bin', _artifactToFileName(artifact, _platform)); + case Artifact.flutterMacOSFramework: + case Artifact.linuxDesktopPath: + case Artifact.windowsDesktopPath: + case Artifact.linuxHeaders: + // TODO(zanderso): remove once debug desktop artifacts are uploaded + // under a separate directory from the host artifacts. + // https://github.com/flutter/flutter/issues/38935 + String platformDirName = _enginePlatformDirectoryName(platform); + if (mode == BuildMode.profile || mode == BuildMode.release) { + platformDirName = '$platformDirName-${mode!.cliName}'; + } + final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; + return _fileSystem.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact, _platform, mode)); + case Artifact.windowsCppClientWrapper: + final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; + return _fileSystem.path.join(engineArtifactsPath, 'windows-x64', _artifactToFileName(artifact, _platform, mode)); + case Artifact.skyEnginePath: + final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); + return _fileSystem.path.join(dartPackageDirectory.path, _artifactToFileName(artifact, _platform)); + case Artifact.fontSubset: + case Artifact.constFinder: + return _cache.getArtifactDirectory('engine') + .childDirectory(_enginePlatformDirectoryName(platform)) + .childFile(_artifactToFileName(artifact, _platform, mode)!) + .path; + case Artifact.flutterFramework: + case Artifact.flutterXcframework: + case Artifact.fuchsiaFlutterRunner: + case Artifact.fuchsiaKernelCompiler: + throw StateError('Artifact $artifact not available for platform $platform.'); + case Artifact.flutterToolsFileGenerators: + return _getFileGeneratorsPath(); + case Artifact.flutterPreviewDevice: + assert(platform == TargetPlatform.windows_x64); + return _cache.getArtifactDirectory('flutter_preview').childFile('flutter_preview.exe').path; + } + } + + String? _getEngineArtifactsPath(TargetPlatform platform, [ BuildMode? mode ]) { + final String engineDir = _cache.getArtifactDirectory('engine').path; + final String platformName = _enginePlatformDirectoryName(platform); + switch (platform) { + case TargetPlatform.linux_x64: + case TargetPlatform.linux_arm64: + case TargetPlatform.darwin: + case TargetPlatform.windows_x64: + // TODO(zanderso): remove once debug desktop artifacts are uploaded + // under a separate directory from the host artifacts. + // https://github.com/flutter/flutter/issues/38935 + if (mode == BuildMode.debug || mode == null) { + return _fileSystem.path.join(engineDir, platformName); + } + final String suffix = mode != BuildMode.debug ? '-${snakeCase(mode.cliName, '-')}' : ''; + return _fileSystem.path.join(engineDir, platformName + suffix); + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + assert(mode == null, 'Platform $platform does not support different build modes.'); + return _fileSystem.path.join(engineDir, platformName); + case TargetPlatform.ios: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + assert(mode != null, 'Need to specify a build mode for platform $platform.'); + final String suffix = mode != BuildMode.debug ? '-${snakeCase(mode!.cliName, '-')}' : ''; + return _fileSystem.path.join(engineDir, platformName + suffix); + case TargetPlatform.android: + assert(false, 'cannot use TargetPlatform.android to look up artifacts'); + return null; + } + } + + @override + bool get isLocalEngine => false; +} + +TargetPlatform _currentHostPlatform(Platform platform, OperatingSystemUtils operatingSystemUtils) { + if (platform.isMacOS) { + return TargetPlatform.darwin; + } + if (platform.isLinux) { + return operatingSystemUtils.hostPlatform == HostPlatform.linux_x64 ? + TargetPlatform.linux_x64 : TargetPlatform.linux_arm64; + } + if (platform.isWindows) { + return TargetPlatform.windows_x64; + } + throw UnimplementedError('Host OS not supported.'); +} + +String _getIosEngineArtifactPath(String engineDirectory, + EnvironmentType? environmentType, FileSystem fileSystem, Platform hostPlatform) { + final Directory xcframeworkDirectory = fileSystem + .directory(engineDirectory) + .childDirectory(_artifactToFileName(Artifact.flutterXcframework, hostPlatform)!); + + if (!xcframeworkDirectory.existsSync()) { + throwToolExit('No xcframework found at ${xcframeworkDirectory.path}. Try running "flutter precache --ios".'); + } + Directory? flutterFrameworkSource; + for (final Directory platformDirectory + in xcframeworkDirectory.listSync().whereType()) { + if (!platformDirectory.basename.startsWith('ios-')) { + continue; + } + // ios-x86_64-simulator, ios-arm64_x86_64-simulator, or ios-arm64. + final bool simulatorDirectory = platformDirectory.basename.endsWith('-simulator'); + if ((environmentType == EnvironmentType.simulator && simulatorDirectory) || + (environmentType == EnvironmentType.physical && !simulatorDirectory)) { + flutterFrameworkSource = platformDirectory; + } + } + if (flutterFrameworkSource == null) { + throwToolExit('No iOS frameworks found in ${xcframeworkDirectory.path}'); + } + + return flutterFrameworkSource + .childDirectory(_artifactToFileName(Artifact.flutterFramework, hostPlatform)!) + .path; +} + +/// Manages the artifacts of a locally built engine. +class CachedLocalEngineArtifacts implements Artifacts { + CachedLocalEngineArtifacts( + this._hostEngineOutPath, { + required String engineOutPath, + required FileSystem fileSystem, + required Cache cache, + required ProcessManager processManager, + required Platform platform, + required OperatingSystemUtils operatingSystemUtils, + Artifacts? parent, + }) : _fileSystem = fileSystem, + localEngineInfo = + LocalEngineInfo( + targetOutPath: engineOutPath, + hostOutPath: _hostEngineOutPath, + ), + _cache = cache, + _processManager = processManager, + _platform = platform, + _operatingSystemUtils = operatingSystemUtils, + _backupCache = parent ?? + CachedArtifacts( + fileSystem: fileSystem, + platform: platform, + cache: cache, + operatingSystemUtils: operatingSystemUtils + ); + + @override + final LocalEngineInfo localEngineInfo; + + final String _hostEngineOutPath; + final FileSystem _fileSystem; + final Cache _cache; + final ProcessManager _processManager; + final Platform _platform; + final OperatingSystemUtils _operatingSystemUtils; + final Artifacts _backupCache; + + @override + FileSystemEntity getHostArtifact(HostArtifact artifact) { + switch (artifact) { + case HostArtifact.flutterWebSdk: + final String path = _getFlutterWebSdkPath(); + return _fileSystem.directory(path); + case HostArtifact.flutterWebLibrariesJson: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.flutterJsDirectory: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); + return _fileSystem.directory(path); + case HostArtifact.webPlatformKernelFolder: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); + return _fileSystem.file(path); + case HostArtifact.webPlatformDDCKernelDill: + case HostArtifact.webPlatformDDCSoundKernelDill: + case HostArtifact.webPlatformDart2JSKernelDill: + case HostArtifact.webPlatformDart2JSSoundKernelDill: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledSdk: + case HostArtifact.webPrecompiledSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitSdk: + case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledSoundSdk: + case HostArtifact.webPrecompiledSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitSoundSdk: + case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.idevicesyslog: + case HostArtifact.idevicescreenshot: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + return _cache.getArtifactDirectory('libimobiledevice').childFile(artifactFileName); + case HostArtifact.skyEnginePath: + final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); + final String path = _fileSystem.path.join(dartPackageDirectory.path, _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.directory(path); + case HostArtifact.iosDeploy: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + return _cache.getArtifactDirectory('ios-deploy').childFile(artifactFileName); + case HostArtifact.iproxy: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + return _cache.getArtifactDirectory('usbmuxd').childFile(artifactFileName); + case HostArtifact.impellerc: + case HostArtifact.scenec: + case HostArtifact.libtessellator: + final String artifactFileName = _hostArtifactToFileName(artifact, _platform); + final File file = _fileSystem.file(_fileSystem.path.join(_hostEngineOutPath, artifactFileName)); + if (!file.existsSync()) { + return _backupCache.getHostArtifact(artifact); + } + return file; + } + } + + @override + String getArtifactPath( + Artifact artifact, { + TargetPlatform? platform, + BuildMode? mode, + EnvironmentType? environmentType, + }) { + platform ??= _currentHostPlatform(_platform, _operatingSystemUtils); + platform = _mapTargetPlatform(platform); + final bool isDirectoryArtifact = artifact == Artifact.flutterPatchedSdkPath; + final String? artifactFileName = isDirectoryArtifact ? null : _artifactToFileName(artifact, _platform, mode); + switch (artifact) { + case Artifact.genSnapshot: + return _genSnapshotPath(); + case Artifact.flutterTester: + return _flutterTesterPath(platform!); + case Artifact.isolateSnapshotData: + case Artifact.vmSnapshotData: + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'gen', 'flutter', 'lib', 'snapshot', artifactFileName); + case Artifact.icuData: + case Artifact.flutterXcframework: + case Artifact.flutterMacOSFramework: + return _fileSystem.path.join(localEngineInfo.targetOutPath, artifactFileName); + case Artifact.platformKernelDill: + if (platform == TargetPlatform.fuchsia_x64 || platform == TargetPlatform.fuchsia_arm64) { + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_runner_patched_sdk', artifactFileName); + } + return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), artifactFileName); + case Artifact.platformLibrariesJson: + return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), 'lib', artifactFileName); + case Artifact.flutterFramework: + return _getIosEngineArtifactPath( + localEngineInfo.targetOutPath, environmentType, _fileSystem, _platform); + case Artifact.flutterPatchedSdkPath: + // When using local engine always use [BuildMode.debug] regardless of + // what was specified in [mode] argument because local engine will + // have only one flutter_patched_sdk in standard location, that + // is happen to be what debug(non-release) mode is using. + if (platform == TargetPlatform.fuchsia_x64 || platform == TargetPlatform.fuchsia_arm64) { + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_runner_patched_sdk'); + } + return _getFlutterPatchedSdkPath(BuildMode.debug); + case Artifact.skyEnginePath: + return _fileSystem.path.join(_hostEngineOutPath, 'gen', 'dart-pkg', artifactFileName); + case Artifact.fuchsiaKernelCompiler: + final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform()); + final String modeName = mode!.isRelease ? 'release' : mode.toString(); + final String dartBinaries = 'dart_binaries-$modeName-$hostPlatform'; + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'host_bundle', dartBinaries, 'kernel_compiler.dart.snapshot'); + case Artifact.fuchsiaFlutterRunner: + final String jitOrAot = mode!.isJit ? '_jit' : '_aot'; + final String productOrNo = mode.isRelease ? '_product' : ''; + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter$jitOrAot${productOrNo}_runner-0.far'); + case Artifact.fontSubset: + return _fileSystem.path.join(_hostEngineOutPath, artifactFileName); + case Artifact.constFinder: + return _fileSystem.path.join(_hostEngineOutPath, 'gen', artifactFileName); + case Artifact.linuxDesktopPath: + case Artifact.linuxHeaders: + case Artifact.windowsDesktopPath: + case Artifact.windowsCppClientWrapper: + return _fileSystem.path.join(_hostEngineOutPath, artifactFileName); + case Artifact.engineDartSdkPath: + return _getDartSdkPath(); + case Artifact.engineDartBinary: + case Artifact.engineDartAotRuntime: + return _fileSystem.path.join(_getDartSdkPath(), 'bin', artifactFileName); + case Artifact.dart2jsSnapshot: + case Artifact.dart2wasmSnapshot: + case Artifact.frontendServerSnapshotForEngineDartSdk: + return _fileSystem.path.join(_getDartSdkPath(), 'bin', 'snapshots', artifactFileName); + case Artifact.wasmOptBinary: + return _fileSystem.path.join(_getDartSdkPath(), 'bin', 'utils', artifactFileName); + case Artifact.flutterToolsFileGenerators: + return _getFileGeneratorsPath(); + case Artifact.flutterPreviewDevice: + return _backupCache.getArtifactPath( + artifact, + platform: platform, + mode: mode, + environmentType: environmentType, + ); + } + } + + @override + String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { + return _fileSystem.path.basename(localEngineInfo.targetOutPath); + } + + String _getFlutterPatchedSdkPath(BuildMode? buildMode) { + return _fileSystem.path.join(localEngineInfo.targetOutPath, + buildMode == BuildMode.release ? 'flutter_patched_sdk_product' : 'flutter_patched_sdk'); + } + + String _getDartSdkPath() { + final String builtPath = _fileSystem.path.join(_hostEngineOutPath, 'dart-sdk'); + if (_fileSystem.isDirectorySync(_fileSystem.path.join(builtPath, 'bin'))) { + return builtPath; + } + + // If we couldn't find a built dart sdk, let's look for a prebuilt one. + final String prebuiltPath = _fileSystem.path.join(_getFlutterPrebuiltsPath(), _getPrebuiltTarget(), 'dart-sdk'); + if (_fileSystem.isDirectorySync(prebuiltPath)) { + return prebuiltPath; + } + + throw ToolExit('Unable to find a built dart sdk at: "$builtPath" or a prebuilt dart sdk at: "$prebuiltPath"'); + } + + String _getFlutterPrebuiltsPath() { + final String engineSrcPath = _fileSystem.path.dirname(_fileSystem.path.dirname(_hostEngineOutPath)); + return _fileSystem.path.join(engineSrcPath, 'flutter', 'prebuilts'); + } + + String _getPrebuiltTarget() { + final TargetPlatform hostPlatform = _currentHostPlatform(_platform, _operatingSystemUtils); + switch (hostPlatform) { + case TargetPlatform.darwin: + return 'macos-x64'; + case TargetPlatform.linux_arm64: + return 'linux-arm64'; + case TargetPlatform.linux_x64: + return 'linux-x64'; + case TargetPlatform.windows_x64: + return 'windows-x64'; + case TargetPlatform.ios: + case TargetPlatform.android: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.web_javascript: + case TargetPlatform.tester: + throwToolExit('Unsupported host platform: $hostPlatform'); + } + } + + String _getFlutterWebSdkPath() { + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_web_sdk'); + } + + String _genSnapshotPath() { + const List clangDirs = ['.', 'clang_x64', 'clang_x86', 'clang_i386', 'clang_arm64']; + final String genSnapshotName = _artifactToFileName(Artifact.genSnapshot, _platform)!; + for (final String clangDir in clangDirs) { + final String genSnapshotPath = _fileSystem.path.join(localEngineInfo.targetOutPath, clangDir, genSnapshotName); + if (_processManager.canRun(genSnapshotPath)) { + return genSnapshotPath; + } + } + throw Exception('Unable to find $genSnapshotName'); + } + + String _flutterTesterPath(TargetPlatform platform) { + if (_platform.isLinux) { + return _fileSystem.path.join(localEngineInfo.targetOutPath, _artifactToFileName(Artifact.flutterTester, _platform)); + } else if (_platform.isMacOS) { + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_tester'); + } else if (_platform.isWindows) { + return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_tester.exe'); + } + throw Exception('Unsupported platform $platform.'); + } + + @override + bool get isLocalEngine => true; +} + +class CachedLocalWebSdkArtifacts implements Artifacts { + CachedLocalWebSdkArtifacts({ + required Artifacts parent, + required String webSdkPath, + required FileSystem fileSystem, + required Platform platform, + required OperatingSystemUtils operatingSystemUtils + }) : _parent = parent, + _webSdkPath = webSdkPath, + _fileSystem = fileSystem, + _platform = platform, + _operatingSystemUtils = operatingSystemUtils; + + final Artifacts _parent; + final String _webSdkPath; + final FileSystem _fileSystem; + final Platform _platform; + final OperatingSystemUtils _operatingSystemUtils; + + @override + String getArtifactPath(Artifact artifact, {TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType}) { + if (platform == TargetPlatform.web_javascript) { + switch (artifact) { + case Artifact.engineDartSdkPath: + return _getDartSdkPath(); + case Artifact.engineDartBinary: + case Artifact.engineDartAotRuntime: + return _fileSystem.path.join( + _getDartSdkPath(), 'bin', + _artifactToFileName(artifact, _platform, mode)); + case Artifact.dart2jsSnapshot: + case Artifact.dart2wasmSnapshot: + case Artifact.frontendServerSnapshotForEngineDartSdk: + return _fileSystem.path.join( + _getDartSdkPath(), 'bin', 'snapshots', + _artifactToFileName(artifact, _platform, mode), + ); + case Artifact.wasmOptBinary: + return _fileSystem.path.join( + _getDartSdkPath(), 'bin', 'utils', + _artifactToFileName(artifact, _platform, mode), + ); + case Artifact.genSnapshot: + case Artifact.flutterTester: + case Artifact.flutterFramework: + case Artifact.flutterXcframework: + case Artifact.flutterMacOSFramework: + case Artifact.vmSnapshotData: + case Artifact.isolateSnapshotData: + case Artifact.icuData: + case Artifact.platformKernelDill: + case Artifact.platformLibrariesJson: + case Artifact.flutterPatchedSdkPath: + case Artifact.linuxDesktopPath: + case Artifact.linuxHeaders: + case Artifact.windowsDesktopPath: + case Artifact.windowsCppClientWrapper: + case Artifact.skyEnginePath: + case Artifact.fuchsiaKernelCompiler: + case Artifact.fuchsiaFlutterRunner: + case Artifact.fontSubset: + case Artifact.constFinder: + case Artifact.flutterToolsFileGenerators: + case Artifact.flutterPreviewDevice: + break; + } + } + return _parent.getArtifactPath(artifact, platform: platform, mode: mode, environmentType: environmentType); + } + + @override + String getEngineType(TargetPlatform platform, [BuildMode? mode]) => _parent.getEngineType(platform, mode); + + @override + FileSystemEntity getHostArtifact(HostArtifact artifact) { + switch (artifact) { + case HostArtifact.flutterWebSdk: + final String path = _getFlutterWebSdkPath(); + return _fileSystem.directory(path); + case HostArtifact.flutterWebLibrariesJson: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.flutterJsDirectory: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); + return _fileSystem.directory(path); + case HostArtifact.webPlatformKernelFolder: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); + return _fileSystem.file(path); + case HostArtifact.webPlatformDDCKernelDill: + case HostArtifact.webPlatformDDCSoundKernelDill: + case HostArtifact.webPlatformDart2JSKernelDill: + case HostArtifact.webPlatformDart2JSSoundKernelDill: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledSdk: + case HostArtifact.webPrecompiledSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitSdk: + case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledSoundSdk: + case HostArtifact.webPrecompiledSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitSoundSdk: + case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: + case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: + final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); + return _fileSystem.file(path); + case HostArtifact.iosDeploy: + case HostArtifact.idevicesyslog: + case HostArtifact.idevicescreenshot: + case HostArtifact.iproxy: + case HostArtifact.skyEnginePath: + case HostArtifact.impellerc: + case HostArtifact.scenec: + case HostArtifact.libtessellator: + return _parent.getHostArtifact(artifact); + } + } + + String _getDartSdkPath() { + // If we couldn't find a built dart sdk, let's look for a prebuilt one. + final String prebuiltPath = _fileSystem.path.join(_getFlutterPrebuiltsPath(), _getPrebuiltTarget(), 'dart-sdk'); + if (_fileSystem.isDirectorySync(prebuiltPath)) { + return prebuiltPath; + } + + throw ToolExit('Unable to find a prebuilt dart sdk at: "$prebuiltPath"'); + } + + String _getFlutterPrebuiltsPath() { + final String engineSrcPath = _fileSystem.path.dirname(_fileSystem.path.dirname(_webSdkPath)); + return _fileSystem.path.join(engineSrcPath, 'flutter', 'prebuilts'); + } + + String _getPrebuiltTarget() { + final TargetPlatform hostPlatform = _currentHostPlatform(_platform, _operatingSystemUtils); + switch (hostPlatform) { + case TargetPlatform.darwin: + return 'macos-x64'; + case TargetPlatform.linux_arm64: + return 'linux-arm64'; + case TargetPlatform.linux_x64: + return 'linux-x64'; + case TargetPlatform.windows_x64: + return 'windows-x64'; + case TargetPlatform.ios: + case TargetPlatform.android: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.web_javascript: + case TargetPlatform.tester: + throwToolExit('Unsupported host platform: $hostPlatform'); + } + } + + String _getFlutterWebSdkPath() { + return _fileSystem.path.join(_webSdkPath, 'flutter_web_sdk'); + } + + @override + bool get isLocalEngine => _parent.isLocalEngine; + + @override + LocalEngineInfo? get localEngineInfo => _parent.localEngineInfo; +} + +/// An implementation of [Artifacts] that provides individual overrides. +/// +/// If an artifact is not provided, the lookup delegates to the parent. +class OverrideArtifacts implements Artifacts { + /// Creates a new [OverrideArtifacts]. + /// + /// [parent] must be provided. + OverrideArtifacts({ + required this.parent, + this.frontendServer, + this.engineDartBinary, + this.platformKernelDill, + this.flutterPatchedSdk, + }); + + final Artifacts parent; + final File? frontendServer; + final File? engineDartBinary; + final File? platformKernelDill; + final File? flutterPatchedSdk; + + @override + LocalEngineInfo? get localEngineInfo => parent.localEngineInfo; + + @override + String getArtifactPath( + Artifact artifact, { + TargetPlatform? platform, + BuildMode? mode, + EnvironmentType? environmentType, + }) { + if (artifact == Artifact.engineDartBinary && engineDartBinary != null) { + return engineDartBinary!.path; + } + if (artifact == Artifact.frontendServerSnapshotForEngineDartSdk && frontendServer != null) { + return frontendServer!.path; + } + if (artifact == Artifact.platformKernelDill && platformKernelDill != null) { + return platformKernelDill!.path; + } + if (artifact == Artifact.flutterPatchedSdkPath && flutterPatchedSdk != null) { + return flutterPatchedSdk!.path; + } + return parent.getArtifactPath( + artifact, + platform: platform, + mode: mode, + environmentType: environmentType, + ); + } + + @override + String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) => parent.getEngineType(platform, mode); + + @override + bool get isLocalEngine => parent.isLocalEngine; + + @override + FileSystemEntity getHostArtifact(HostArtifact artifact) { + return parent.getHostArtifact( + artifact, + ); + } +} + +/// Locate the Dart SDK. +String _dartSdkPath(Cache cache) { + return cache.getRoot().childDirectory('dart-sdk').path; +} + +class _TestArtifacts implements Artifacts { + _TestArtifacts(this.fileSystem); + + final FileSystem fileSystem; + + @override + LocalEngineInfo? get localEngineInfo => null; + + @override + String getArtifactPath( + Artifact artifact, { + TargetPlatform? platform, + BuildMode? mode, + EnvironmentType? environmentType, + }) { + // The path to file generators is the same even in the test environment. + if (artifact == Artifact.flutterToolsFileGenerators) { + return _getFileGeneratorsPath(); + } + + final StringBuffer buffer = StringBuffer(); + buffer.write(artifact); + if (platform != null) { + buffer.write('.$platform'); + } + if (mode != null) { + buffer.write('.$mode'); + } + if (environmentType != null) { + buffer.write('.$environmentType'); + } + return buffer.toString(); + } + + @override + String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { + return 'test-engine'; + } + + @override + bool get isLocalEngine => false; + + @override + FileSystemEntity getHostArtifact(HostArtifact artifact) { + return fileSystem.file(artifact.toString()); + } +} + +class _TestLocalEngine extends _TestArtifacts { + _TestLocalEngine( + String engineOutPath, + String engineHostOutPath, + super.fileSystem, + ) : localEngineInfo = LocalEngineInfo( + targetOutPath: engineOutPath, + hostOutPath: engineHostOutPath, + ); + + @override + bool get isLocalEngine => true; + + @override + final LocalEngineInfo localEngineInfo; +} + +String _getFileGeneratorsPath() { + final String flutterRoot = Cache.defaultFlutterRoot( + fileSystem: globals.localFileSystem, + platform: const LocalPlatform(), + userMessages: UserMessages(), + ); + return globals.localFileSystem.path.join( + flutterRoot, + 'packages', + 'flutter_tools', + 'lib', + 'src', + 'web', + 'file_generators', + ); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/asset.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/asset.dart new file mode 100644 index 0000000000000000000000000000000000000000..9d936156d5f2b34a24a0d122f2821ffbe6a91722 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/asset.dart @@ -0,0 +1,1283 @@ +// 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:typed_data'; + +import 'package:meta/meta.dart'; +import 'package:package_config/package_config.dart'; +import 'package:standard_message_codec/standard_message_codec.dart'; + +import 'base/common.dart'; +import 'base/context.dart'; +import 'base/deferred_component.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'build_info.dart'; +import 'cache.dart'; +import 'convert.dart'; +import 'dart/package_map.dart'; +import 'devfs.dart'; +import 'flutter_manifest.dart'; +import 'license_collector.dart'; +import 'project.dart'; + +const String defaultManifestPath = 'pubspec.yaml'; + +const String kFontManifestJson = 'FontManifest.json'; + +// Should match '2x', '/1x', '1.5x', etc. +final RegExp _assetVariantDirectoryRegExp = RegExp(r'/?(\d+(\.\d*)?)x$'); + +/// The effect of adding `uses-material-design: true` to the pubspec is to insert +/// the following snippet into the asset manifest: +/// +/// ```yaml +/// material: +/// - family: MaterialIcons +/// fonts: +/// - asset: fonts/MaterialIcons-Regular.otf +/// ``` +const List> kMaterialFonts = >[ + { + 'family': 'MaterialIcons', + 'fonts': >[ + { + 'asset': 'fonts/MaterialIcons-Regular.otf', + }, + ], + }, +]; + +const List kMaterialShaders = [ + 'shaders/ink_sparkle.frag', +]; + +/// Injected factory class for spawning [AssetBundle] instances. +abstract class AssetBundleFactory { + /// The singleton instance, pulled from the [AppContext]. + static AssetBundleFactory get instance => context.get()!; + + static AssetBundleFactory defaultInstance({ + required Logger logger, + required FileSystem fileSystem, + required Platform platform, + bool splitDeferredAssets = false, + }) => _ManifestAssetBundleFactory(logger: logger, fileSystem: fileSystem, platform: platform, splitDeferredAssets: splitDeferredAssets); + + /// Creates a new [AssetBundle]. + AssetBundle createBundle(); +} + +enum AssetKind { + regular, + font, + shader, + model, +} + +abstract class AssetBundle { + Map get entries; + + Map get entryKinds; + + /// The files that were specified under the deferred components assets sections + /// in pubspec. + Map> get deferredComponentsEntries; + + /// Additional files that this bundle depends on that are not included in the + /// output result. + List get additionalDependencies; + + /// Input files used to build this asset bundle. + List get inputFiles; + + bool wasBuiltOnce(); + + bool needsBuild({ String manifestPath = defaultManifestPath }); + + /// Returns 0 for success; non-zero for failure. + Future build({ + String manifestPath = defaultManifestPath, + required String packagesPath, + bool deferredComponentsEnabled = false, + TargetPlatform? targetPlatform, + String? flavor, + }); +} + +class _ManifestAssetBundleFactory implements AssetBundleFactory { + _ManifestAssetBundleFactory({ + required Logger logger, + required FileSystem fileSystem, + required Platform platform, + bool splitDeferredAssets = false, + }) : _logger = logger, + _fileSystem = fileSystem, + _platform = platform, + _splitDeferredAssets = splitDeferredAssets; + + final Logger _logger; + final FileSystem _fileSystem; + final Platform _platform; + final bool _splitDeferredAssets; + + @override + AssetBundle createBundle() => ManifestAssetBundle(logger: _logger, fileSystem: _fileSystem, platform: _platform, splitDeferredAssets: _splitDeferredAssets); +} + +/// An asset bundle based on a pubspec.yaml file. +class ManifestAssetBundle implements AssetBundle { + /// Constructs an [ManifestAssetBundle] that gathers the set of assets from the + /// pubspec.yaml manifest. + ManifestAssetBundle({ + required Logger logger, + required FileSystem fileSystem, + required Platform platform, + bool splitDeferredAssets = false, + }) : _logger = logger, + _fileSystem = fileSystem, + _platform = platform, + _splitDeferredAssets = splitDeferredAssets, + _licenseCollector = LicenseCollector(fileSystem: fileSystem); + + final Logger _logger; + final FileSystem _fileSystem; + final LicenseCollector _licenseCollector; + final Platform _platform; + final bool _splitDeferredAssets; + + @override + final Map entries = {}; + + @override + final Map entryKinds = {}; + + @override + final Map> deferredComponentsEntries = >{}; + + @override + final List inputFiles = []; + + // If an asset corresponds to a wildcard directory, then it may have been + // updated without changes to the manifest. These are only tracked for + // the current project. + final Map _wildcardDirectories = {}; + + DateTime? _lastBuildTimestamp; + + // We assume the main asset is designed for a device pixel ratio of 1.0. + static const String _kAssetManifestJsonFilename = 'AssetManifest.json'; + static const String _kAssetManifestBinFilename = 'AssetManifest.bin'; + static const String _kAssetManifestBinJsonFilename = 'AssetManifest.bin.json'; + + static const String _kNoticeFile = 'NOTICES'; + // Comically, this can't be name with the more common .gz file extension + // because when it's part of an AAR and brought into another APK via gradle, + // gradle individually traverses all the files of the AAR and unzips .gz + // files (b/37117906). A less common .Z extension still describes how the + // file is formatted if users want to manually inspect the application + // bundle and is recognized by default file handlers on OS such as macOS.˚ + static const String _kNoticeZippedFile = 'NOTICES.Z'; + + @override + bool wasBuiltOnce() => _lastBuildTimestamp != null; + + @override + bool needsBuild({ String manifestPath = defaultManifestPath }) { + final DateTime? lastBuildTimestamp = _lastBuildTimestamp; + if (lastBuildTimestamp == null) { + return true; + } + + final FileStat stat = _fileSystem.file(manifestPath).statSync(); + if (stat.type == FileSystemEntityType.notFound) { + return true; + } + + for (final Directory directory in _wildcardDirectories.values) { + if (!directory.existsSync()) { + return true; // directory was deleted. + } + for (final File file in directory.listSync().whereType()) { + final DateTime dateTime = file.statSync().modified; + if (dateTime.isAfter(lastBuildTimestamp)) { + return true; + } + } + } + + return stat.modified.isAfter(lastBuildTimestamp); + } + + @override + Future build({ + String manifestPath = defaultManifestPath, + FlutterProject? flutterProject, + required String packagesPath, + bool deferredComponentsEnabled = false, + TargetPlatform? targetPlatform, + String? flavor, + }) async { + if (flutterProject == null) { + try { + flutterProject = FlutterProject.fromDirectory(_fileSystem.file(manifestPath).parent); + } on Exception catch (e) { + _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); + _logger.printError('$e'); + return 1; + } + } + + final FlutterManifest flutterManifest = flutterProject.manifest; + // If the last build time isn't set before this early return, empty pubspecs will + // hang on hot reload, as the incremental dill files will never be copied to the + // device. + _lastBuildTimestamp = DateTime.now(); + if (flutterManifest.isEmpty) { + entries[_kAssetManifestJsonFilename] = DevFSStringContent('{}'); + entryKinds[_kAssetManifestJsonFilename] = AssetKind.regular; + final ByteData emptyAssetManifest = + const StandardMessageCodec().encodeMessage({})!; + entries[_kAssetManifestBinFilename] = + DevFSByteContent(emptyAssetManifest.buffer.asUint8List(0, emptyAssetManifest.lengthInBytes)); + entryKinds[_kAssetManifestBinFilename] = AssetKind.regular; + // Create .bin.json on web builds. + if (targetPlatform == TargetPlatform.web_javascript) { + entries[_kAssetManifestBinJsonFilename] = DevFSStringContent('""'); + entryKinds[_kAssetManifestBinJsonFilename] = AssetKind.regular; + } + return 0; + } + + final String assetBasePath = _fileSystem.path.dirname(_fileSystem.path.absolute(manifestPath)); + final File packageConfigFile = _fileSystem.file(packagesPath); + inputFiles.add(packageConfigFile); + final PackageConfig packageConfig = await loadPackageConfigWithLogging( + packageConfigFile, + logger: _logger, + ); + final List wildcardDirectories = []; + + // The _assetVariants map contains an entry for each asset listed + // in the pubspec.yaml file's assets and font sections. The + // value of each image asset is a list of resolution-specific "variants", + // see _AssetDirectoryCache. + final Map<_Asset, List<_Asset>>? assetVariants = _parseAssets( + packageConfig, + flutterManifest, + wildcardDirectories, + assetBasePath, + targetPlatform, + flavor: flavor, + ); + + if (assetVariants == null) { + return 1; + } + + // Parse assets for deferred components. + final Map>> deferredComponentsAssetVariants = _parseDeferredComponentsAssets( + flutterManifest, + packageConfig, + assetBasePath, + wildcardDirectories, + flutterProject.directory, + flavor: flavor, + ); + if (!_splitDeferredAssets || !deferredComponentsEnabled) { + // Include the assets in the regular set of assets if not using deferred + // components. + deferredComponentsAssetVariants.values.forEach(assetVariants.addAll); + deferredComponentsAssetVariants.clear(); + deferredComponentsEntries.clear(); + } + + final bool includesMaterialFonts = flutterManifest.usesMaterialDesign; + final List> fonts = _parseFonts( + flutterManifest, + packageConfig, + primary: true, + ); + + // Add fonts, assets, and licenses from packages. + final Map> additionalLicenseFiles = >{}; + for (final Package package in packageConfig.packages) { + final Uri packageUri = package.packageUriRoot; + if (packageUri.scheme == 'file') { + final String packageManifestPath = _fileSystem.path.fromUri(packageUri.resolve('../pubspec.yaml')); + inputFiles.add(_fileSystem.file(packageManifestPath)); + final FlutterManifest? packageFlutterManifest = FlutterManifest.createFromPath( + packageManifestPath, + logger: _logger, + fileSystem: _fileSystem, + ); + if (packageFlutterManifest == null) { + continue; + } + // Collect any additional licenses from each package. + final List licenseFiles = []; + for (final String relativeLicensePath in packageFlutterManifest.additionalLicenses) { + final String absoluteLicensePath = _fileSystem.path.fromUri(package.root.resolve(relativeLicensePath)); + licenseFiles.add(_fileSystem.file(absoluteLicensePath).absolute); + } + additionalLicenseFiles[packageFlutterManifest.appName] = licenseFiles; + + // Skip the app itself + if (packageFlutterManifest.appName == flutterManifest.appName) { + continue; + } + final String packageBasePath = _fileSystem.path.dirname(packageManifestPath); + + final Map<_Asset, List<_Asset>>? packageAssets = _parseAssets( + packageConfig, + packageFlutterManifest, + // Do not track wildcard directories for dependencies. + [], + packageBasePath, + targetPlatform, + packageName: package.name, + attributedPackage: package, + ); + + if (packageAssets == null) { + return 1; + } + assetVariants.addAll(packageAssets); + if (!includesMaterialFonts && packageFlutterManifest.usesMaterialDesign) { + _logger.printError( + 'package:${package.name} has `uses-material-design: true` set but ' + 'the primary pubspec contains `uses-material-design: false`. ' + 'If the application needs material icons, then `uses-material-design` ' + ' must be set to true.' + ); + } + fonts.addAll(_parseFonts( + packageFlutterManifest, + packageConfig, + packageName: package.name, + primary: false, + )); + } + } + + // Save the contents of each image, image variant, and font + // asset in entries. + for (final _Asset asset in assetVariants.keys) { + final File assetFile = asset.lookupAssetFile(_fileSystem); + final List<_Asset> variants = assetVariants[asset]!; + if (!assetFile.existsSync() && variants.isEmpty) { + _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); + _logger.printError('No file or variants found for $asset.\n'); + if (asset.package != null) { + _logger.printError('This asset was included from package ${asset.package?.name}.'); + } + return 1; + } + // The file name for an asset's "main" entry is whatever appears in + // the pubspec.yaml file. The main entry's file must always exist for + // font assets. It need not exist for an image if resolution-specific + // variant files exist. An image's main entry is treated the same as a + // "1x" resolution variant and if both exist then the explicit 1x + // variant is preferred. + if (assetFile.existsSync() && !variants.contains(asset)) { + variants.insert(0, asset); + } + for (final _Asset variant in variants) { + final File variantFile = variant.lookupAssetFile(_fileSystem); + inputFiles.add(variantFile); + assert(variantFile.existsSync()); + entries[variant.entryUri.path] ??= DevFSFileContent(variantFile); + entryKinds[variant.entryUri.path] ??= variant.assetKind; + } + } + // Save the contents of each deferred component image, image variant, and font + // asset in deferredComponentsEntries. + for (final String componentName in deferredComponentsAssetVariants.keys) { + deferredComponentsEntries[componentName] = {}; + final Map<_Asset, List<_Asset>> assetsMap = deferredComponentsAssetVariants[componentName]!; + for (final _Asset asset in assetsMap.keys) { + final File assetFile = asset.lookupAssetFile(_fileSystem); + if (!assetFile.existsSync() && assetsMap[asset]!.isEmpty) { + _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); + _logger.printError('No file or variants found for $asset.\n'); + if (asset.package != null) { + _logger.printError('This asset was included from package ${asset.package?.name}.'); + } + return 1; + } + // The file name for an asset's "main" entry is whatever appears in + // the pubspec.yaml file. The main entry's file must always exist for + // font assets. It need not exist for an image if resolution-specific + // variant files exist. An image's main entry is treated the same as a + // "1x" resolution variant and if both exist then the explicit 1x + // variant is preferred. + if (assetFile.existsSync() && !assetsMap[asset]!.contains(asset)) { + assetsMap[asset]!.insert(0, asset); + } + for (final _Asset variant in assetsMap[asset]!) { + final File variantFile = variant.lookupAssetFile(_fileSystem); + assert(variantFile.existsSync()); + deferredComponentsEntries[componentName]![variant.entryUri.path] ??= DevFSFileContent(variantFile); + } + } + } + final List<_Asset> materialAssets = <_Asset>[ + if (flutterManifest.usesMaterialDesign) + ..._getMaterialFonts(), + // For all platforms, include the shaders unconditionally. They are + // small, and whether they're used is determined only by the app source + // code and not by the Flutter manifest. + ..._getMaterialShaders(), + ]; + for (final _Asset asset in materialAssets) { + final File assetFile = asset.lookupAssetFile(_fileSystem); + assert(assetFile.existsSync(), 'Missing ${assetFile.path}'); + entries[asset.entryUri.path] ??= DevFSFileContent(assetFile); + entryKinds[asset.entryUri.path] ??= asset.assetKind; + } + + // Update wildcard directories we can detect changes in them. + for (final Uri uri in wildcardDirectories) { + _wildcardDirectories[uri] ??= _fileSystem.directory(uri); + } + + final Map> assetManifest = + _createAssetManifest(assetVariants, deferredComponentsAssetVariants); + final DevFSByteContent assetManifestBinary = _createAssetManifestBinary(assetManifest); + final DevFSStringContent assetManifestJson = DevFSStringContent(json.encode(assetManifest)); + final DevFSStringContent fontManifest = DevFSStringContent(json.encode(fonts)); + final LicenseResult licenseResult = _licenseCollector.obtainLicenses(packageConfig, additionalLicenseFiles); + if (licenseResult.errorMessages.isNotEmpty) { + licenseResult.errorMessages.forEach(_logger.printError); + return 1; + } + + additionalDependencies = licenseResult.dependencies; + inputFiles.addAll(additionalDependencies); + + if (wildcardDirectories.isNotEmpty) { + // Force the depfile to contain missing files so that Gradle does not skip + // the task. Wildcard directories are not compatible with full incremental + // builds. For more context see https://github.com/flutter/flutter/issues/56466 . + _logger.printTrace( + 'Manifest contained wildcard assets. Inserting missing file into ' + 'build graph to force rerun. for more information see #56466.' + ); + final int suffix = Object().hashCode; + additionalDependencies.add( + _fileSystem.file('DOES_NOT_EXIST_RERUN_FOR_WILDCARD$suffix').absolute); + } + + _setIfChanged(_kAssetManifestJsonFilename, assetManifestJson, AssetKind.regular); + _setIfChanged(_kAssetManifestBinFilename, assetManifestBinary, AssetKind.regular); + // Create .bin.json on web builds. + if (targetPlatform == TargetPlatform.web_javascript) { + final DevFSStringContent assetManifestBinaryJson = DevFSStringContent(json.encode( + base64.encode(assetManifestBinary.bytes) + )); + _setIfChanged(_kAssetManifestBinJsonFilename, assetManifestBinaryJson, AssetKind.regular); + } + _setIfChanged(kFontManifestJson, fontManifest, AssetKind.regular); + _setLicenseIfChanged(licenseResult.combinedLicenses, targetPlatform); + return 0; + } + + @override + List additionalDependencies = []; + void _setIfChanged(String key, DevFSContent content, AssetKind assetKind) { + final DevFSContent? oldContent = entries[key]; + // In the case that the content is unchanged, we want to avoid an overwrite + // as the isModified property may be reset to true, + if (oldContent is DevFSByteContent && content is DevFSByteContent && + _compareIntLists(oldContent.bytes, content.bytes)) { + return; + } + + entries[key] = content; + entryKinds[key] = assetKind; + } + + static bool _compareIntLists(List o1, List o2) { + if (o1.length != o2.length) { + return false; + } + + for (int index = 0; index < o1.length; index++) { + if (o1[index] != o2[index]) { + return false; + } + } + + return true; + } + + void _setLicenseIfChanged( + String combinedLicenses, + TargetPlatform? targetPlatform, + ) { + // On the web, don't compress the NOTICES file since the client doesn't have + // dart:io to decompress it. So use the standard _setIfChanged to check if + // the strings still match. + if (targetPlatform == TargetPlatform.web_javascript) { + _setIfChanged(_kNoticeFile, DevFSStringContent(combinedLicenses), AssetKind.regular); + return; + } + + // On other platforms, let the NOTICES file be compressed. But use a + // specialized DevFSStringCompressingBytesContent class to compare + // the uncompressed strings to not incur decompression/decoding while making + // the comparison. + if (!entries.containsKey(_kNoticeZippedFile) || + (entries[_kNoticeZippedFile] as DevFSStringCompressingBytesContent?) + ?.equals(combinedLicenses) != true) { + entries[_kNoticeZippedFile] = DevFSStringCompressingBytesContent( + combinedLicenses, + // A zlib dictionary is a hinting string sequence with the most + // likely string occurrences at the end. This ends up just being + // common English words with domain specific words like copyright. + hintString: 'copyrightsoftwaretothisinandorofthe', + ); + entryKinds[_kNoticeZippedFile] = AssetKind.regular; + } + } + + List<_Asset> _getMaterialFonts() { + final List<_Asset> result = <_Asset>[]; + for (final Map family in kMaterialFonts) { + final Object? fonts = family['fonts']; + if (fonts == null) { + continue; + } + for (final Map font in fonts as List>) { + final String? asset = font['asset'] as String?; + if (asset == null) { + continue; + } + final Uri entryUri = _fileSystem.path.toUri(asset); + result.add(_Asset( + baseDir: _fileSystem.path.join( + Cache.flutterRoot!, + 'bin', 'cache', 'artifacts', 'material_fonts', + ), + relativeUri: Uri(path: entryUri.pathSegments.last), + entryUri: entryUri, + package: null, + assetKind: AssetKind.font, + )); + } + } + + return result; + } + + List<_Asset> _getMaterialShaders() { + final String shaderPath = _fileSystem.path.join( + Cache.flutterRoot!, + 'packages', 'flutter', 'lib', 'src', 'material', 'shaders', + ); + // This file will exist in a real invocation unless the git checkout is + // corrupted somehow, but unit tests generally don't create this file + // in their mock file systems. Leaving it out in those cases is harmless. + if (!_fileSystem.directory(shaderPath).existsSync()) { + return <_Asset>[]; + } + + final List<_Asset> result = <_Asset>[]; + for (final String shader in kMaterialShaders) { + final Uri entryUri = _fileSystem.path.toUri(shader); + result.add(_Asset( + baseDir: shaderPath, + relativeUri: Uri(path: entryUri.pathSegments.last), + entryUri: entryUri, + package: null, + assetKind: AssetKind.shader, + )); + } + + return result; + } + + List> _parseFonts( + FlutterManifest manifest, + PackageConfig packageConfig, { + String? packageName, + required bool primary, + }) { + return >[ + if (primary && manifest.usesMaterialDesign) + ...kMaterialFonts, + if (packageName == null) + ...manifest.fontsDescriptor + else + for (final Font font in _parsePackageFonts( + manifest, + packageName, + packageConfig, + )) font.descriptor, + ]; + } + + Map>> _parseDeferredComponentsAssets( + FlutterManifest flutterManifest, + PackageConfig packageConfig, + String assetBasePath, + List wildcardDirectories, + Directory projectDirectory, { + String? flavor, + }) { + final List? components = flutterManifest.deferredComponents; + final Map>> deferredComponentsAssetVariants = >>{}; + if (components == null) { + return deferredComponentsAssetVariants; + } + for (final DeferredComponent component in components) { + final _AssetDirectoryCache cache = _AssetDirectoryCache(_fileSystem); + final Map<_Asset, List<_Asset>> componentAssets = <_Asset, List<_Asset>>{}; + for (final AssetsEntry assetsEntry in component.assets) { + if (assetsEntry.uri.path.endsWith('/')) { + wildcardDirectories.add(assetsEntry.uri); + _parseAssetsFromFolder( + packageConfig, + flutterManifest, + assetBasePath, + cache, + componentAssets, + assetsEntry.uri, + ); + } else { + _parseAssetFromFile( + packageConfig, + flutterManifest, + assetBasePath, + cache, + componentAssets, + assetsEntry.uri, + ); + } + } + + componentAssets.removeWhere((_Asset asset, List<_Asset> variants) => !asset.matchesFlavor(flavor)); + deferredComponentsAssetVariants[component.name] = componentAssets; + } + return deferredComponentsAssetVariants; + } + + Map> _createAssetManifest( + Map<_Asset, List<_Asset>> assetVariants, + Map>> deferredComponentsAssetVariants + ) { + final Map> manifest = >{}; + final Map<_Asset, List> entries = <_Asset, List>{}; + assetVariants.forEach((_Asset main, List<_Asset> variants) { + entries[main] = [ + for (final _Asset variant in variants) + variant.entryUri.path, + ]; + }); + for (final Map<_Asset, List<_Asset>> componentAssets in deferredComponentsAssetVariants.values) { + componentAssets.forEach((_Asset main, List<_Asset> variants) { + entries[main] = [ + for (final _Asset variant in variants) + variant.entryUri.path, + ]; + }); + } + final List<_Asset> sortedKeys = entries.keys.toList() + ..sort((_Asset left, _Asset right) => left.entryUri.path.compareTo(right.entryUri.path)); + for (final _Asset main in sortedKeys) { + final String decodedEntryPath = Uri.decodeFull(main.entryUri.path); + final List rawEntryVariantsPaths = entries[main]!; + final List decodedEntryVariantPaths = rawEntryVariantsPaths + .map((String value) => Uri.decodeFull(value)) + .toList(); + manifest[decodedEntryPath] = decodedEntryVariantPaths; + } + return manifest; + } + + // Matches path-like strings ending in a number followed by an 'x'. + // Example matches include "assets/animals/2.0x", "plants/3x", and "2.7x". + static final RegExp _extractPixelRatioFromKeyRegExp = RegExp(r'/?(\d+(\.\d*)?)x$'); + + DevFSByteContent _createAssetManifestBinary( + Map> assetManifest + ) { + double? parseScale(String key) { + final Uri assetUri = Uri.parse(key); + String directoryPath = ''; + if (assetUri.pathSegments.length > 1) { + directoryPath = assetUri.pathSegments[assetUri.pathSegments.length - 2]; + } + + final Match? match = _extractPixelRatioFromKeyRegExp.firstMatch(directoryPath); + if (match != null && match.groupCount > 0) { + return double.parse(match.group(1)!); + } + + return null; + } + + final Map result = {}; + + for (final MapEntry manifestEntry in assetManifest.entries) { + final List resultVariants = []; + final List entries = (manifestEntry.value as List).cast(); + for (final String variant in entries) { + final Map resultVariant = {}; + final double? variantDevicePixelRatio = parseScale(variant); + resultVariant['asset'] = variant; + if (variantDevicePixelRatio != null) { + resultVariant['dpr'] = variantDevicePixelRatio; + } + resultVariants.add(resultVariant); + } + result[manifestEntry.key] = resultVariants; + } + + final ByteData message = const StandardMessageCodec().encodeMessage(result)!; + return DevFSByteContent(message.buffer.asUint8List(0, message.lengthInBytes)); + } + + /// Prefixes family names and asset paths of fonts included from packages with + /// 'packages/' + List _parsePackageFonts( + FlutterManifest manifest, + String packageName, + PackageConfig packageConfig, + ) { + final List packageFonts = []; + for (final Font font in manifest.fonts) { + final List packageFontAssets = []; + for (final FontAsset fontAsset in font.fontAssets) { + final Uri assetUri = fontAsset.assetUri; + if (assetUri.pathSegments.first == 'packages' && + !_fileSystem.isFileSync(_fileSystem.path.fromUri( + packageConfig[packageName]?.packageUriRoot.resolve('../${assetUri.path}')))) { + packageFontAssets.add(FontAsset( + fontAsset.assetUri, + weight: fontAsset.weight, + style: fontAsset.style, + )); + } else { + packageFontAssets.add(FontAsset( + Uri(pathSegments: ['packages', packageName, ...assetUri.pathSegments]), + weight: fontAsset.weight, + style: fontAsset.style, + )); + } + } + packageFonts.add(Font('packages/$packageName/${font.familyName}', packageFontAssets)); + } + return packageFonts; + } + + /// Given an assetBase location and a pubspec.yaml Flutter manifest, return a + /// map of assets to asset variants. + /// + /// Returns null on missing assets. + /// + /// Given package: 'test_package' and an assets directory like this: + /// + /// - assets/foo + /// - assets/var1/foo + /// - assets/var2/foo + /// - assets/bar + /// + /// This will return: + /// ``` + /// { + /// asset: packages/test_package/assets/foo: [ + /// asset: packages/test_package/assets/foo, + /// asset: packages/test_package/assets/var1/foo, + /// asset: packages/test_package/assets/var2/foo, + /// ], + /// asset: packages/test_package/assets/bar: [ + /// asset: packages/test_package/assets/bar, + /// ], + /// } + /// ``` + Map<_Asset, List<_Asset>>? _parseAssets( + PackageConfig packageConfig, + FlutterManifest flutterManifest, + List wildcardDirectories, + String assetBase, + TargetPlatform? targetPlatform, { + String? packageName, + Package? attributedPackage, + String? flavor, + }) { + final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{}; + + final _AssetDirectoryCache cache = _AssetDirectoryCache(_fileSystem); + for (final AssetsEntry assetsEntry in flutterManifest.assets) { + if (assetsEntry.uri.path.endsWith('/')) { + wildcardDirectories.add(assetsEntry.uri); + _parseAssetsFromFolder( + packageConfig, + flutterManifest, + assetBase, + cache, + result, + assetsEntry.uri, + packageName: packageName, + attributedPackage: attributedPackage, + flavors: assetsEntry.flavors, + ); + } else { + _parseAssetFromFile( + packageConfig, + flutterManifest, + assetBase, + cache, + result, + assetsEntry.uri, + packageName: packageName, + attributedPackage: attributedPackage, + flavors: assetsEntry.flavors, + ); + } + } + + result.removeWhere((_Asset asset, List<_Asset> variants) { + if (!asset.matchesFlavor(flavor)) { + _logger.printTrace('Skipping assets entry "${asset.entryUri.path}" since ' + 'its configured flavor(s) did not match the provided flavor (if any).\n' + 'Configured flavors: ${asset.flavors.join(', ')}\n'); + return true; + } + return false; + }); + + for (final Uri shaderUri in flutterManifest.shaders) { + _parseAssetFromFile( + packageConfig, + flutterManifest, + assetBase, + cache, + result, + shaderUri, + packageName: packageName, + attributedPackage: attributedPackage, + assetKind: AssetKind.shader, + ); + } + + for (final Uri modelUri in flutterManifest.models) { + _parseAssetFromFile( + packageConfig, + flutterManifest, + assetBase, + cache, + result, + modelUri, + packageName: packageName, + attributedPackage: attributedPackage, + assetKind: AssetKind.model, + ); + } + + // Add assets referenced in the fonts section of the manifest. + for (final Font font in flutterManifest.fonts) { + for (final FontAsset fontAsset in font.fontAssets) { + final _Asset baseAsset = _resolveAsset( + packageConfig, + assetBase, + fontAsset.assetUri, + packageName, + attributedPackage, + assetKind: AssetKind.font, + ); + final File baseAssetFile = baseAsset.lookupAssetFile(_fileSystem); + if (!baseAssetFile.existsSync()) { + _logger.printError('Error: unable to locate asset entry in pubspec.yaml: "${fontAsset.assetUri}".'); + return null; + } + result[baseAsset] = <_Asset>[]; + } + } + + return result; + } + + void _parseAssetsFromFolder( + PackageConfig packageConfig, + FlutterManifest flutterManifest, + String assetBase, + _AssetDirectoryCache cache, + Map<_Asset, List<_Asset>> result, + Uri assetUri, { + String? packageName, + Package? attributedPackage, + List? flavors, + }) { + final String directoryPath = _fileSystem.path.join( + assetBase, assetUri.toFilePath(windows: _platform.isWindows)); + + if (!_fileSystem.directory(directoryPath).existsSync()) { + _logger.printError('Error: unable to find directory entry in pubspec.yaml: $directoryPath'); + return; + } + + final Iterable entities = _fileSystem.directory(directoryPath).listSync(); + + final Iterable files = entities.whereType(); + for (final File file in files) { + final String relativePath = _fileSystem.path.relative(file.path, from: assetBase); + final Uri uri = Uri.file(relativePath, windows: _platform.isWindows); + + _parseAssetFromFile( + packageConfig, + flutterManifest, + assetBase, + cache, + result, + uri, + packageName: packageName, + attributedPackage: attributedPackage, + originUri: assetUri, + flavors: flavors, + ); + } + } + + void _parseAssetFromFile( + PackageConfig packageConfig, + FlutterManifest flutterManifest, + String assetBase, + _AssetDirectoryCache cache, + Map<_Asset, List<_Asset>> result, + Uri assetUri, { + Uri? originUri, + String? packageName, + Package? attributedPackage, + AssetKind assetKind = AssetKind.regular, + List? flavors, + }) { + final _Asset asset = _resolveAsset( + packageConfig, + assetBase, + assetUri, + packageName, + attributedPackage, + assetKind: assetKind, + originUri: originUri, + flavors: flavors, + ); + + _checkForFlavorConflicts(asset, result.keys.toList()); + + final List<_Asset> variants = <_Asset>[]; + final File assetFile = asset.lookupAssetFile(_fileSystem); + + for (final String path in cache.variantsFor(assetFile.path)) { + final String relativePath = _fileSystem.path.relative(path, from: asset.baseDir); + final Uri relativeUri = _fileSystem.path.toUri(relativePath); + final Uri? entryUri = asset.symbolicPrefixUri == null + ? relativeUri + : asset.symbolicPrefixUri?.resolveUri(relativeUri); + if (entryUri != null) { + variants.add( + _Asset( + baseDir: asset.baseDir, + entryUri: entryUri, + relativeUri: relativeUri, + package: attributedPackage, + assetKind: assetKind, + ), + ); + } + } + + result[asset] = variants; + } + + // Since it is not clear how overlapping asset declarations should work in the + // presence of conditions such as `flavor`, we throw an Error. + // + // To be more specific, it is not clear if conditions should be combined with + // or-logic or and-logic, or if it should depend on the specificity of the + // declarations (file versus directory). If you would like examples, consider these: + // + // ```yaml + // # Should assets/free.mp3 always be included since "assets/" has no flavor? + // assets: + // - assets/ + // - path: assets/free.mp3 + // flavor: free + // + // # Should "assets/paid/pip.mp3" be included for both the "paid" and "free" flavors? + // # Or, since "assets/paid/pip.mp3" is more specific than "assets/paid/"", should + // # it take precedence over the latter (included only in "free" flavor)? + // assets: + // - path: assets/paid/ + // flavor: paid + // - path: assets/paid/pip.mp3 + // flavor: free + // - asset + // ``` + // + // Since it is not obvious what logic (if any) would be intuitive and preferable + // to the vast majority of users (if any), we play it safe by throwing a `ToolExit` + // in any of these situations. We can always loosen up this restriction later + // without breaking anyone. + void _checkForFlavorConflicts(_Asset newAsset, List<_Asset> previouslyParsedAssets) { + bool cameFromDirectoryEntry(_Asset asset) { + return asset.originUri.path.endsWith('/'); + } + + String flavorErrorInfo(_Asset asset) { + if (asset.flavors.isEmpty) { + return 'An entry with the path "${asset.originUri}" does not specify any flavors.'; + } + + final Iterable flavorsWrappedWithQuotes = asset.flavors.map((String e) => '"$e"'); + return 'An entry with the path "${asset.originUri}" specifies the flavor(s): ' + '${flavorsWrappedWithQuotes.join(', ')}.'; + } + + final _Asset? preExistingAsset = previouslyParsedAssets + .where((_Asset other) => other.entryUri == newAsset.entryUri) + .firstOrNull; + + if (preExistingAsset == null || preExistingAsset.hasEquivalentFlavorsWith(newAsset)) { + return; + } + + final StringBuffer errorMessage = StringBuffer( + 'Multiple assets entries include the file ' + '"${newAsset.entryUri.path}", but they specify different lists of flavors.\n'); + + errorMessage.writeln(flavorErrorInfo(preExistingAsset)); + errorMessage.writeln(flavorErrorInfo(newAsset)); + + if (cameFromDirectoryEntry(newAsset)|| cameFromDirectoryEntry(preExistingAsset)) { + errorMessage.writeln(); + errorMessage.write('Consider organizing assets with different flavors ' + 'into different directories.'); + } + + throwToolExit(errorMessage.toString()); + } + + _Asset _resolveAsset( + PackageConfig packageConfig, + String assetsBaseDir, + Uri assetUri, + String? packageName, + Package? attributedPackage, { + Uri? originUri, + AssetKind assetKind = AssetKind.regular, + List? flavors, + }) { + final String assetPath = _fileSystem.path.fromUri(assetUri); + if (assetUri.pathSegments.first == 'packages' + && !_fileSystem.isFileSync(_fileSystem.path.join(assetsBaseDir, assetPath))) { + // The asset is referenced in the pubspec.yaml as + // 'packages/PACKAGE_NAME/PATH/TO/ASSET . + final _Asset? packageAsset = _resolvePackageAsset( + assetUri, + packageConfig, + attributedPackage, + assetKind: assetKind, + originUri: originUri, + flavors: flavors, + ); + if (packageAsset != null) { + return packageAsset; + } + } + + return _Asset( + baseDir: assetsBaseDir, + entryUri: packageName == null + ? assetUri // Asset from the current application. + : Uri(pathSegments: ['packages', packageName, ...assetUri.pathSegments]), // Asset from, and declared in $packageName. + relativeUri: assetUri, + package: attributedPackage, + originUri: originUri, + assetKind: assetKind, + flavors: flavors, + ); + } + + _Asset? _resolvePackageAsset( + Uri assetUri, + PackageConfig packageConfig, + Package? attributedPackage, { + AssetKind assetKind = AssetKind.regular, + Uri? originUri, + List? flavors, + }) { + assert(assetUri.pathSegments.first == 'packages'); + if (assetUri.pathSegments.length > 1) { + final String packageName = assetUri.pathSegments[1]; + final Package? package = packageConfig[packageName]; + final Uri? packageUri = package?.packageUriRoot; + if (packageUri != null && packageUri.scheme == 'file') { + return _Asset( + baseDir: _fileSystem.path.fromUri(packageUri), + entryUri: assetUri, + relativeUri: Uri(pathSegments: assetUri.pathSegments.sublist(2)), + package: attributedPackage, + assetKind: assetKind, + originUri: originUri, + flavors: flavors, + ); + } + } + _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); + _logger.printError('Could not resolve package for asset $assetUri.\n'); + if (attributedPackage != null) { + _logger.printError('This asset was included from package ${attributedPackage.name}'); + } + return null; + } +} + +@immutable +class _Asset { + const _Asset({ + required this.baseDir, + Uri? originUri, + required this.relativeUri, + required this.entryUri, + required this.package, + this.assetKind = AssetKind.regular, + List? flavors, + }): originUri = originUri ?? entryUri, flavors = flavors ?? const []; + + final String baseDir; + + final Package? package; + + /// The platform-independent URL provided by the user in the pubspec that this + /// asset was found from. + final Uri originUri; + + /// A platform-independent URL where this asset can be found on disk on the + /// host system relative to [baseDir]. + final Uri relativeUri; + + /// A platform-independent URL representing the entry for the asset manifest. + final Uri entryUri; + + final AssetKind assetKind; + + final List flavors; + + File lookupAssetFile(FileSystem fileSystem) { + return fileSystem.file(fileSystem.path.join(baseDir, fileSystem.path.fromUri(relativeUri))); + } + + /// The delta between what the entryUri is and the relativeUri (e.g., + /// packages/flutter_gallery). + Uri? get symbolicPrefixUri { + if (entryUri == relativeUri) { + return null; + } + final int index = entryUri.path.indexOf(relativeUri.path); + return index == -1 ? null : Uri(path: entryUri.path.substring(0, index)); + } + + bool matchesFlavor(String? flavor) { + if (flavors.isEmpty) { + return true; + } + + if (flavor == null) { + return false; + } + + return flavors.contains(flavor); + } + + bool hasEquivalentFlavorsWith(_Asset other) { + final Set assetFlavors = flavors.toSet(); + final Set otherFlavors = other.flavors.toSet(); + return assetFlavors.length == otherFlavors.length && assetFlavors.every( + (String e) => otherFlavors.contains(e), + ); + } + + @override + String toString() => 'asset: $entryUri'; + + @override + bool operator ==(Object other) { + if (identical(other, this)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is _Asset + && other.baseDir == baseDir + && other.relativeUri == relativeUri + && other.entryUri == entryUri + && other.assetKind == assetKind + && hasEquivalentFlavorsWith(other); + } + + @override + int get hashCode => Object.hashAll([ + baseDir, + relativeUri, + entryUri, + assetKind, + ...flavors, + ]); +} + +// Given an assets directory like this: +// +// assets/foo.png +// assets/2x/foo.png +// assets/3.0x/foo.png +// assets/bar/foo.png +// assets/bar.png +// +// variantsFor('assets/foo.png') => ['/assets/foo.png', '/assets/2x/foo.png', 'assets/3.0x/foo.png'] +// variantsFor('assets/bar.png') => ['/assets/bar.png'] +// variantsFor('assets/bar/foo.png') => ['/assets/bar/foo.png'] +class _AssetDirectoryCache { + _AssetDirectoryCache(this._fileSystem); + + final FileSystem _fileSystem; + final Map> _cache = >{}; + final Map> _variantsPerFolder = >{}; + + List variantsFor(String assetPath) { + final String directory = _fileSystem.path.dirname(assetPath); + + if (!_fileSystem.directory(directory).existsSync()) { + return const []; + } + + if (_cache.containsKey(assetPath)) { + return _cache[assetPath]!; + } + if (!_variantsPerFolder.containsKey(directory)) { + _variantsPerFolder[directory] = _fileSystem.directory(directory) + .listSync() + .whereType() + .where((Directory dir) => _assetVariantDirectoryRegExp.hasMatch(dir.basename)) + .expand((Directory dir) => dir.listSync()) + .whereType() + .toList(); + } + final File assetFile = _fileSystem.file(assetPath); + final List potentialVariants = _variantsPerFolder[directory]!; + final String basename = assetFile.basename; + return _cache[assetPath] = [ + // It's possible that the user specifies only explicit variants (e.g. .../1x/asset.png), + // so there does not necessarily need to be a file at the given path. + if (assetFile.existsSync()) + assetPath, + ...potentialVariants + .where((File file) => file.basename == basename) + .map((File file) => file.path), + ]; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/build_info.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/build_info.dart new file mode 100644 index 0000000000000000000000000000000000000000..b42edc1d51f5d454ffad77db1854c3e18b706b3c --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/build_info.dart @@ -0,0 +1,1063 @@ +// 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:package_config/package_config_types.dart'; + +import 'artifacts.dart'; +import 'base/config.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/os.dart'; +import 'base/utils.dart'; +import 'convert.dart'; +import 'globals.dart' as globals; +import 'web/compile.dart'; + +/// Whether icon font subsetting is enabled by default. +const bool kIconTreeShakerEnabledDefault = true; + +/// Information about a build to be performed or used. +class BuildInfo { + const BuildInfo( + this.mode, + this.flavor, { + this.trackWidgetCreation = false, + this.frontendServerStarterPath, + List? extraFrontEndOptions, + List? extraGenSnapshotOptions, + List? fileSystemRoots, + this.androidProjectArgs = const [], + this.fileSystemScheme, + this.buildNumber, + this.buildName, + this.splitDebugInfoPath, + this.dartObfuscation = false, + List? dartDefines, + this.bundleSkSLPath, + List? dartExperiments, + this.webRenderer = WebRendererMode.auto, + required this.treeShakeIcons, + this.performanceMeasurementFile, + this.packagesPath = '.dart_tool/package_config.json', // TODO(zanderso): make this required and remove the default. + this.nullSafetyMode = NullSafetyMode.sound, + this.codeSizeDirectory, + this.androidGradleDaemon = true, + this.packageConfig = PackageConfig.empty, + this.initializeFromDill, + this.assumeInitializeFromDillUpToDate = false, + this.buildNativeAssets = true, + }) : extraFrontEndOptions = extraFrontEndOptions ?? const [], + extraGenSnapshotOptions = extraGenSnapshotOptions ?? const [], + fileSystemRoots = fileSystemRoots ?? const [], + dartDefines = dartDefines ?? const [], + dartExperiments = dartExperiments ?? const []; + + final BuildMode mode; + + /// The null safety mode the application should be run in. + /// + /// If not provided, defaults to [NullSafetyMode.autodetect]. + final NullSafetyMode nullSafetyMode; + + /// Whether the build should subset icon fonts. + final bool treeShakeIcons; + + /// Represents a custom Android product flavor or an Xcode scheme, null for + /// using the default. + /// + /// If not null, the Gradle build task will be `assembleFlavorMode` (e.g. + /// `assemblePaidRelease`), and the Xcode build configuration will be + /// Mode-Flavor (e.g. Release-Paid). + final String? flavor; + + /// The path to the package configuration file to use for compilation. + /// + /// This is used by package:package_config to locate the actual package_config.json + /// file. If not provided, defaults to `.dart_tool/package_config.json`. + final String packagesPath; + + final List fileSystemRoots; + final String? fileSystemScheme; + + /// Whether the build should track widget creation locations. + final bool trackWidgetCreation; + + /// If provided, the frontend server will be started in JIT mode from this + /// file. + final String? frontendServerStarterPath; + + /// Extra command-line options for front-end. + final List extraFrontEndOptions; + + /// Extra command-line options for gen_snapshot. + final List extraGenSnapshotOptions; + + /// Internal version number (not displayed to users). + /// Each build must have a unique number to differentiate it from previous builds. + /// It is used to determine whether one build is more recent than another, with higher numbers indicating more recent build. + /// On Android it is used as versionCode. + /// On Xcode builds it is used as CFBundleVersion. + /// On Windows it is used as the build suffix for the product and file versions. + final String? buildNumber; + + /// A "x.y.z" string used as the version number shown to users. + /// For each new version of your app, you will provide a version number to differentiate it from previous versions. + /// On Android it is used as versionName. + /// On Xcode builds it is used as CFBundleShortVersionString. + /// On Windows it is used as the major, minor, and patch parts of the product and file versions. + final String? buildName; + + /// An optional directory path to save debugging information from dwarf stack + /// traces. If null, stack trace information is not stripped from the + /// executable. + final String? splitDebugInfoPath; + + /// Whether to apply dart source code obfuscation. + final bool dartObfuscation; + + /// An optional path to a JSON containing object SkSL shaders. + /// + /// Currently this is only supported for Android builds. + final String? bundleSkSLPath; + + /// Additional constant values to be made available in the Dart program. + /// + /// These values can be used with the const `fromEnvironment` constructors of + /// [bool], [String], [int], and [double]. + final List dartDefines; + + /// A list of Dart experiments. + final List dartExperiments; + + /// When compiling to web, which web renderer mode we are using (html, canvaskit, auto) + final WebRendererMode webRenderer; + + /// The name of a file where flutter assemble will output performance + /// information in a JSON format. + /// + /// This is not considered a build input and will not force assemble to + /// rerun tasks. + final String? performanceMeasurementFile; + + /// If provided, an output directory where one or more v8-style heap snapshots + /// will be written for code size profiling. + final String? codeSizeDirectory; + + /// Whether to enable the Gradle daemon when performing an Android build. + /// + /// Starting the daemon is the default behavior of the gradle wrapper script created + /// in a Flutter project. Setting this value to false will cause the tool to pass + /// `--no-daemon` to the gradle wrapper script, preventing it from spawning a daemon + /// process. + /// + /// For one-off builds or CI systems, preventing the daemon from spawning will + /// reduce system resource usage, at the cost of any subsequent builds starting + /// up slightly slower. + /// + /// The Gradle daemon may also be disabled in the Android application's properties file. + final bool androidGradleDaemon; + + /// Additional key value pairs that are passed directly to the gradle project via the `-P` + /// flag. + final List androidProjectArgs; + + /// The package configuration for the loaded application. + /// + /// This is captured once during startup, but the actual package configuration + /// may change during a 'flutter run` workflow. + final PackageConfig packageConfig; + + /// The kernel file that the resident compiler will be initialized with. + /// + /// If this is null, it will be initialized from the default cached location. + final String? initializeFromDill; + + /// If set, assumes that the file passed in [initializeFromDill] is up to date + /// and skips the check and potential invalidation of files. + final bool assumeInitializeFromDillUpToDate; + + /// If set, builds native assets with `build.dart` from all packages. + final bool buildNativeAssets; + + static const BuildInfo debug = BuildInfo(BuildMode.debug, null, trackWidgetCreation: true, treeShakeIcons: false); + static const BuildInfo profile = BuildInfo(BuildMode.profile, null, treeShakeIcons: kIconTreeShakerEnabledDefault); + static const BuildInfo jitRelease = BuildInfo(BuildMode.jitRelease, null, treeShakeIcons: kIconTreeShakerEnabledDefault); + static const BuildInfo release = BuildInfo(BuildMode.release, null, treeShakeIcons: kIconTreeShakerEnabledDefault); + + /// Returns whether a debug build is requested. + /// + /// Exactly one of [isDebug], [isProfile], or [isRelease] is true. + bool get isDebug => mode == BuildMode.debug; + + /// Returns whether a profile build is requested. + /// + /// Exactly one of [isDebug], [isProfile], [isJitRelease], + /// or [isRelease] is true. + bool get isProfile => mode == BuildMode.profile; + + /// Returns whether a release build is requested. + /// + /// Exactly one of [isDebug], [isProfile], [isJitRelease], + /// or [isRelease] is true. + bool get isRelease => mode == BuildMode.release; + + /// Returns whether a JIT release build is requested. + /// + /// Exactly one of [isDebug], [isProfile], [isJitRelease], + /// or [isRelease] is true. + bool get isJitRelease => mode == BuildMode.jitRelease; + + bool get usesAot => isAotBuildMode(mode); + bool get supportsEmulator => isEmulatorBuildMode(mode); + bool get supportsSimulator => isEmulatorBuildMode(mode); + String get modeName => mode.cliName; + String get friendlyModeName => getFriendlyModeName(mode); + + /// the flavor name in the output apk files is lower-cased (see Flutter Gradle Plugin), + /// so the lower cased flavor name is used to compute the output file name + String? get lowerCasedFlavor => flavor?.toLowerCase(); + + /// the flavor name in the output bundle files has the first character lower-cased, + /// so the uncapitalized flavor name is used to compute the output file name + String? get uncapitalizedFlavor => _uncapitalize(flavor); + + /// Convert to a structured string encoded structure appropriate for usage + /// in build system [Environment.defines]. + /// + /// Fields that are `null` are excluded from this configuration. + Map toBuildSystemEnvironment() { + // packagesPath and performanceMeasurementFile are not passed into + // the Environment map. + return { + kBuildMode: mode.cliName, + if (dartDefines.isNotEmpty) + kDartDefines: encodeDartDefines(dartDefines), + kDartObfuscation: dartObfuscation.toString(), + if (frontendServerStarterPath != null) + kFrontendServerStarterPath: frontendServerStarterPath!, + if (extraFrontEndOptions.isNotEmpty) + kExtraFrontEndOptions: extraFrontEndOptions.join(','), + if (extraGenSnapshotOptions.isNotEmpty) + kExtraGenSnapshotOptions: extraGenSnapshotOptions.join(','), + if (splitDebugInfoPath != null) + kSplitDebugInfo: splitDebugInfoPath!, + kTrackWidgetCreation: trackWidgetCreation.toString(), + kIconTreeShakerFlag: treeShakeIcons.toString(), + if (bundleSkSLPath != null) + kBundleSkSLPath: bundleSkSLPath!, + if (codeSizeDirectory != null) + kCodeSizeDirectory: codeSizeDirectory!, + if (fileSystemRoots.isNotEmpty) + kFileSystemRoots: fileSystemRoots.join(','), + if (fileSystemScheme != null) + kFileSystemScheme: fileSystemScheme!, + if (buildName != null) + kBuildName: buildName!, + if (buildNumber != null) + kBuildNumber: buildNumber!, + }; + } + + + /// Convert to a structured string encoded structure appropriate for usage as + /// environment variables or to embed in other scripts. + /// + /// Fields that are `null` are excluded from this configuration. + Map toEnvironmentConfig() { + return { + if (dartDefines.isNotEmpty) + 'DART_DEFINES': encodeDartDefines(dartDefines), + 'DART_OBFUSCATION': dartObfuscation.toString(), + if (frontendServerStarterPath != null) + 'FRONTEND_SERVER_STARTER_PATH': frontendServerStarterPath!, + if (extraFrontEndOptions.isNotEmpty) + 'EXTRA_FRONT_END_OPTIONS': extraFrontEndOptions.join(','), + if (extraGenSnapshotOptions.isNotEmpty) + 'EXTRA_GEN_SNAPSHOT_OPTIONS': extraGenSnapshotOptions.join(','), + if (splitDebugInfoPath != null) + 'SPLIT_DEBUG_INFO': splitDebugInfoPath!, + 'TRACK_WIDGET_CREATION': trackWidgetCreation.toString(), + 'TREE_SHAKE_ICONS': treeShakeIcons.toString(), + if (performanceMeasurementFile != null) + 'PERFORMANCE_MEASUREMENT_FILE': performanceMeasurementFile!, + if (bundleSkSLPath != null) + 'BUNDLE_SKSL_PATH': bundleSkSLPath!, + 'PACKAGE_CONFIG': packagesPath, + if (codeSizeDirectory != null) + 'CODE_SIZE_DIRECTORY': codeSizeDirectory!, + if (flavor != null) + 'FLAVOR': flavor!, + }; + } + + /// Convert this config to a series of project level arguments to be passed + /// on the command line to gradle. + List toGradleConfig() { + // PACKAGE_CONFIG not currently supported. + return [ + if (dartDefines.isNotEmpty) + '-Pdart-defines=${encodeDartDefines(dartDefines)}', + '-Pdart-obfuscation=$dartObfuscation', + if (frontendServerStarterPath != null) + '-Pfrontend-server-starter-path=$frontendServerStarterPath', + if (extraFrontEndOptions.isNotEmpty) + '-Pextra-front-end-options=${extraFrontEndOptions.join(',')}', + if (extraGenSnapshotOptions.isNotEmpty) + '-Pextra-gen-snapshot-options=${extraGenSnapshotOptions.join(',')}', + if (splitDebugInfoPath != null) + '-Psplit-debug-info=$splitDebugInfoPath', + '-Ptrack-widget-creation=$trackWidgetCreation', + '-Ptree-shake-icons=$treeShakeIcons', + if (performanceMeasurementFile != null) + '-Pperformance-measurement-file=$performanceMeasurementFile', + if (bundleSkSLPath != null) + '-Pbundle-sksl-path=$bundleSkSLPath', + if (codeSizeDirectory != null) + '-Pcode-size-directory=$codeSizeDirectory', + for (final String projectArg in androidProjectArgs) + '-P$projectArg', + ]; + } +} + +/// Information about an Android build to be performed or used. +class AndroidBuildInfo { + const AndroidBuildInfo( + this.buildInfo, { + this.targetArchs = const [ + AndroidArch.armeabi_v7a, + AndroidArch.arm64_v8a, + AndroidArch.x86_64, + ], + this.splitPerAbi = false, + this.fastStart = false, + this.multidexEnabled = false, + }); + + // The build info containing the mode and flavor. + final BuildInfo buildInfo; + + /// Whether to split the shared library per ABI. + /// + /// When this is false, multiple ABIs will be contained within one primary + /// build artifact. When this is true, multiple build artifacts (one per ABI) + /// will be produced. + final bool splitPerAbi; + + /// The target platforms for the build. + final Iterable targetArchs; + + /// Whether to bootstrap an empty application. + final bool fastStart; + + /// Whether to enable multidex support for apps with more than 64k methods. + final bool multidexEnabled; +} + +/// A summary of the compilation strategy used for Dart. +enum BuildMode { + /// Built in JIT mode with no optimizations, enabled asserts, and a VM service. + debug, + + /// Built in AOT mode with some optimizations and a VM service. + profile, + + /// Built in AOT mode with all optimizations and no VM service. + release, + + /// Built in JIT mode with all optimizations and no VM service. + jitRelease; + + factory BuildMode.fromCliName(String value) => values.singleWhere( + (BuildMode element) => element.cliName == value, + orElse: () => + throw ArgumentError('$value is not a supported build mode'), + ); + + static const Set releaseModes = { + release, + jitRelease, + }; + static const Set jitModes = { + debug, + jitRelease, + }; + + /// Whether this mode is considered release. + /// + /// Useful for determining whether we should enable/disable asserts or + /// other development features. + bool get isRelease => releaseModes.contains(this); + + /// Whether this mode is using the JIT runtime. + bool get isJit => jitModes.contains(this); + + /// Whether this mode is using the precompiled runtime. + bool get isPrecompiled => !isJit; + + String get cliName => snakeCase(name); + + @override + String toString() => cliName; +} + +/// Environment type of the target device. +enum EnvironmentType { + physical, + simulator, +} + +String? validatedBuildNumberForPlatform(TargetPlatform targetPlatform, String? buildNumber, Logger logger) { + if (buildNumber == null) { + return null; + } + if (targetPlatform == TargetPlatform.ios || + targetPlatform == TargetPlatform.darwin) { + // See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html + final RegExp disallowed = RegExp(r'[^\d\.]'); + String tmpBuildNumber = buildNumber.replaceAll(disallowed, ''); + if (tmpBuildNumber.isEmpty) { + return null; + } + final List segments = tmpBuildNumber + .split('.') + .where((String segment) => segment.isNotEmpty) + .toList(); + if (segments.isEmpty) { + segments.add('0'); + } + tmpBuildNumber = segments.join('.'); + if (tmpBuildNumber != buildNumber) { + logger.printTrace('Invalid build-number: $buildNumber for iOS/macOS, overridden by $tmpBuildNumber.\n' + 'See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); + } + return tmpBuildNumber; + } + if (targetPlatform == TargetPlatform.android_arm || + targetPlatform == TargetPlatform.android_arm64 || + targetPlatform == TargetPlatform.android_x64 || + targetPlatform == TargetPlatform.android_x86) { + // See versionCode at https://developer.android.com/studio/publish/versioning + final RegExp disallowed = RegExp(r'[^\d]'); + String tmpBuildNumberStr = buildNumber.replaceAll(disallowed, ''); + int tmpBuildNumberInt = int.tryParse(tmpBuildNumberStr) ?? 0; + if (tmpBuildNumberInt < 1) { + tmpBuildNumberInt = 1; + } + tmpBuildNumberStr = tmpBuildNumberInt.toString(); + if (tmpBuildNumberStr != buildNumber) { + logger.printTrace('Invalid build-number: $buildNumber for Android, overridden by $tmpBuildNumberStr.\n' + 'See versionCode at https://developer.android.com/studio/publish/versioning'); + } + return tmpBuildNumberStr; + } + return buildNumber; +} + +String? validatedBuildNameForPlatform(TargetPlatform targetPlatform, String? buildName, Logger logger) { + if (buildName == null) { + return null; + } + if (targetPlatform == TargetPlatform.ios || + targetPlatform == TargetPlatform.darwin) { + // See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html + final RegExp disallowed = RegExp(r'[^\d\.]'); + String tmpBuildName = buildName.replaceAll(disallowed, ''); + if (tmpBuildName.isEmpty) { + return null; + } + final List segments = tmpBuildName + .split('.') + .where((String segment) => segment.isNotEmpty) + .toList(); + while (segments.length < 3) { + segments.add('0'); + } + tmpBuildName = segments.join('.'); + if (tmpBuildName != buildName) { + logger.printTrace('Invalid build-name: $buildName for iOS/macOS, overridden by $tmpBuildName.\n' + 'See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); + } + return tmpBuildName; + } + if (targetPlatform == TargetPlatform.android || + targetPlatform == TargetPlatform.android_arm || + targetPlatform == TargetPlatform.android_arm64 || + targetPlatform == TargetPlatform.android_x64 || + targetPlatform == TargetPlatform.android_x86) { + // See versionName at https://developer.android.com/studio/publish/versioning + return buildName; + } + return buildName; +} + +String getFriendlyModeName(BuildMode mode) { + return snakeCase(mode.cliName).replaceAll('_', ' '); +} + +// Returns true if the selected build mode uses ahead-of-time compilation. +bool isAotBuildMode(BuildMode mode) { + return mode == BuildMode.profile || mode == BuildMode.release; +} + +// Returns true if the given build mode can be used on emulators / simulators. +bool isEmulatorBuildMode(BuildMode mode) { + return mode == BuildMode.debug; +} + +enum TargetPlatform { + android, + ios, + darwin, + linux_x64, + linux_arm64, + windows_x64, + fuchsia_arm64, + fuchsia_x64, + tester, + web_javascript, + // The arch specific android target platforms are soft-deprecated. + // Instead of using TargetPlatform as a combination arch + platform + // the code will be updated to carry arch information in [DarwinArch] + // and [AndroidArch]. + android_arm, + android_arm64, + android_x64, + android_x86; + + String get fuchsiaArchForTargetPlatform { + switch (this) { + case TargetPlatform.fuchsia_arm64: + return 'arm64'; + case TargetPlatform.fuchsia_x64: + return 'x64'; + case TargetPlatform.android: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + case TargetPlatform.darwin: + case TargetPlatform.ios: + case TargetPlatform.linux_arm64: + case TargetPlatform.linux_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case TargetPlatform.windows_x64: + throw UnsupportedError('Unexpected Fuchsia platform $this'); + } + } + + String get simpleName { + switch (this) { + case TargetPlatform.linux_x64: + case TargetPlatform.darwin: + case TargetPlatform.windows_x64: + return 'x64'; + case TargetPlatform.linux_arm64: + return 'arm64'; + case TargetPlatform.android: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.ios: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + throw UnsupportedError('Unexpected target platform $this'); + } + } +} + +/// iOS and macOS target device architecture. +// +// TODO(cbracken): split TargetPlatform.ios into ios_armv7, ios_arm64. +enum DarwinArch { + armv7, // Deprecated. Used to display 32-bit unsupported devices. + arm64, + x86_64; + + /// Returns the Dart SDK's name for the specified target architecture. + /// + /// When building for Darwin platforms, the tool invokes architecture-specific + /// variants of `gen_snapshot`, one for each target architecture. The output + /// instructions are then built into architecture-specific binaries, which are + /// merged into a universal binary using the `lipo` tool. + String get dartName { + return switch (this) { + DarwinArch.armv7 => 'armv7', + DarwinArch.arm64 => 'arm64', + DarwinArch.x86_64 => 'x64' + }; + } +} + +// TODO(zanderso): replace all android TargetPlatform usage with AndroidArch. +enum AndroidArch { + armeabi_v7a, + arm64_v8a, + x86, + x86_64; + + String get archName { + return switch (this) { + AndroidArch.armeabi_v7a => 'armeabi-v7a', + AndroidArch.arm64_v8a => 'arm64-v8a', + AndroidArch.x86_64 => 'x86_64', + AndroidArch.x86 => 'x86' + }; + } + + String get platformName { + return switch (this) { + AndroidArch.armeabi_v7a => 'android-arm', + AndroidArch.arm64_v8a => 'android-arm64', + AndroidArch.x86_64 => 'android-x64', + AndroidArch.x86 => 'android-x86' + }; + } +} + +/// The default set of iOS device architectures to build for. +List defaultIOSArchsForEnvironment( + EnvironmentType environmentType, + Artifacts artifacts, +) { + // Handle single-arch local engines. + final LocalEngineInfo? localEngineInfo = artifacts.localEngineInfo; + if (localEngineInfo != null) { + final String localEngineName = localEngineInfo.localTargetName; + if (localEngineName.contains('_arm64')) { + return [ DarwinArch.arm64 ]; + } + if (localEngineName.contains('_sim')) { + return [ DarwinArch.x86_64 ]; + } + } else if (environmentType == EnvironmentType.simulator) { + return [ + DarwinArch.x86_64, + DarwinArch.arm64, + ]; + } + return [ + DarwinArch.arm64, + ]; +} + +/// The default set of macOS device architectures to build for. +List defaultMacOSArchsForEnvironment(Artifacts artifacts) { + // Handle single-arch local engines. + final LocalEngineInfo? localEngineInfo = artifacts.localEngineInfo; + if (localEngineInfo != null) { + if (localEngineInfo.localTargetName.contains('_arm64')) { + return [ DarwinArch.arm64 ]; + } + return [ DarwinArch.x86_64 ]; + } + return [ + DarwinArch.x86_64, + DarwinArch.arm64, + ]; +} + +DarwinArch getIOSArchForName(String arch) { + switch (arch) { + case 'armv7': + case 'armv7f': // iPhone 4S. + case 'armv7s': // iPad 4. + return DarwinArch.armv7; + case 'arm64': + case 'arm64e': // iPhone XS/XS Max/XR and higher. arm64 runs on arm64e devices. + return DarwinArch.arm64; + case 'x86_64': + return DarwinArch.x86_64; + } + throw Exception('Unsupported iOS arch name "$arch"'); +} + +DarwinArch getDarwinArchForName(String arch) { + switch (arch) { + case 'arm64': + return DarwinArch.arm64; + case 'x86_64': + return DarwinArch.x86_64; + } + throw Exception('Unsupported MacOS arch name "$arch"'); +} + +String getNameForTargetPlatform(TargetPlatform platform, {DarwinArch? darwinArch}) { + switch (platform) { + case TargetPlatform.android_arm: + return 'android-arm'; + case TargetPlatform.android_arm64: + return 'android-arm64'; + case TargetPlatform.android_x64: + return 'android-x64'; + case TargetPlatform.android_x86: + return 'android-x86'; + case TargetPlatform.ios: + if (darwinArch != null) { + return 'ios-${darwinArch.name}'; + } + return 'ios'; + case TargetPlatform.darwin: + if (darwinArch != null) { + return 'darwin-${darwinArch.name}'; + } + return 'darwin'; + case TargetPlatform.linux_x64: + return 'linux-x64'; + case TargetPlatform.linux_arm64: + return 'linux-arm64'; + case TargetPlatform.windows_x64: + return 'windows-x64'; + case TargetPlatform.fuchsia_arm64: + return 'fuchsia-arm64'; + case TargetPlatform.fuchsia_x64: + return 'fuchsia-x64'; + case TargetPlatform.tester: + return 'flutter-tester'; + case TargetPlatform.web_javascript: + return 'web-javascript'; + case TargetPlatform.android: + return 'android'; + } +} + +TargetPlatform getTargetPlatformForName(String platform) { + switch (platform) { + case 'android': + return TargetPlatform.android; + case 'android-arm': + return TargetPlatform.android_arm; + case 'android-arm64': + return TargetPlatform.android_arm64; + case 'android-x64': + return TargetPlatform.android_x64; + case 'android-x86': + return TargetPlatform.android_x86; + case 'fuchsia-arm64': + return TargetPlatform.fuchsia_arm64; + case 'fuchsia-x64': + return TargetPlatform.fuchsia_x64; + case 'ios': + return TargetPlatform.ios; + case 'darwin': + // For backward-compatibility and also for Tester, where it must match + // host platform name (HostPlatform.darwin_x64) + case 'darwin-x64': + case 'darwin-arm64': + return TargetPlatform.darwin; + case 'linux-x64': + return TargetPlatform.linux_x64; + case 'linux-arm64': + return TargetPlatform.linux_arm64; + case 'windows-x64': + return TargetPlatform.windows_x64; + case 'web-javascript': + return TargetPlatform.web_javascript; + case 'flutter-tester': + return TargetPlatform.tester; + } + throw Exception('Unsupported platform name "$platform"'); +} + +AndroidArch getAndroidArchForName(String platform) { + switch (platform) { + case 'android-arm': + return AndroidArch.armeabi_v7a; + case 'android-arm64': + return AndroidArch.arm64_v8a; + case 'android-x64': + return AndroidArch.x86_64; + case 'android-x86': + return AndroidArch.x86; + } + throw Exception('Unsupported Android arch name "$platform"'); +} + +HostPlatform getCurrentHostPlatform() { + if (globals.platform.isMacOS) { + return HostPlatform.darwin_x64; + } + if (globals.platform.isLinux) { + // support x64 and arm64 architecture. + return globals.os.hostPlatform; + } + if (globals.platform.isWindows) { + return HostPlatform.windows_x64; + } + + globals.printWarning('Unsupported host platform, defaulting to Linux'); + + return HostPlatform.linux_x64; +} + +FileSystemEntity getWebPlatformBinariesDirectory(Artifacts artifacts, WebRendererMode webRenderer) { + return artifacts.getHostArtifact(HostArtifact.webPlatformKernelFolder); +} + +/// Returns the top-level build output directory. +String getBuildDirectory([Config? config, FileSystem? fileSystem]) { + // TODO(johnmccutchan): Stop calling this function as part of setting + // up command line argument processing. + final Config localConfig = config ?? globals.config; + final FileSystem localFilesystem = fileSystem ?? globals.fs; + + final String buildDir = localConfig.getValue('build-dir') as String? ?? 'build'; + if (localFilesystem.path.isAbsolute(buildDir)) { + throw Exception( + 'build-dir config setting in ${globals.config.configPath} must be relative'); + } + return buildDir; +} + +/// Returns the Android build output directory. +String getAndroidBuildDirectory() { + // TODO(cbracken): move to android subdir. + return getBuildDirectory(); +} + +/// Returns the AOT build output directory. +String getAotBuildDirectory() { + return globals.fs.path.join(getBuildDirectory(), 'aot'); +} + +/// Returns the asset build output directory. +String getAssetBuildDirectory() { + return globals.fs.path.join(getBuildDirectory(), 'flutter_assets'); +} + +/// Returns the iOS build output directory. +String getIosBuildDirectory() { + return globals.fs.path.join(getBuildDirectory(), 'ios'); +} + +/// Returns the macOS build output directory. +String getMacOSBuildDirectory() { + return globals.fs.path.join(getBuildDirectory(), 'macos'); +} + +/// Returns the web build output directory. +String getWebBuildDirectory([bool isWasm = false]) { + return globals.fs.path.join(getBuildDirectory(), isWasm ? 'web_wasm' : 'web'); +} + +/// Returns the Linux build output directory. +String getLinuxBuildDirectory([TargetPlatform? targetPlatform]) { + final String arch = (targetPlatform == null) ? + _getCurrentHostPlatformArchName() : + targetPlatform.simpleName; + final String subDirs = 'linux/$arch'; + return globals.fs.path.join(getBuildDirectory(), subDirs); +} + +/// Returns the Windows build output directory. +String getWindowsBuildDirectory(TargetPlatform targetPlatform) { + final String arch = targetPlatform.simpleName; + return globals.fs.path.join(getBuildDirectory(), 'windows', arch); +} + +/// Returns the Fuchsia build output directory. +String getFuchsiaBuildDirectory() { + return globals.fs.path.join(getBuildDirectory(), 'fuchsia'); +} + +/// Defines specified via the `--dart-define` command-line option. +/// +/// These values are URI-encoded and then combined into a comma-separated string. +const String kDartDefines = 'DartDefines'; + +/// The define to pass a [BuildMode]. +const String kBuildMode = 'BuildMode'; + +/// The define to pass whether we compile 64-bit android-arm code. +const String kTargetPlatform = 'TargetPlatform'; + +/// The define to control what target file is used. +const String kTargetFile = 'TargetFile'; + +/// Whether to enable or disable track widget creation. +const String kTrackWidgetCreation = 'TrackWidgetCreation'; + +/// If provided, the frontend server will be started in JIT mode from this file. +const String kFrontendServerStarterPath = 'FrontendServerStarterPath'; + +/// Additional configuration passed to the dart front end. +/// +/// This is expected to be a comma separated list of strings. +const String kExtraFrontEndOptions = 'ExtraFrontEndOptions'; + +/// Additional configuration passed to gen_snapshot. +/// +/// This is expected to be a comma separated list of strings. +const String kExtraGenSnapshotOptions = 'ExtraGenSnapshotOptions'; + +/// Whether the build should run gen_snapshot as a split aot build for deferred +/// components. +const String kDeferredComponents = 'DeferredComponents'; + +/// Whether to strip source code information out of release builds and where to save it. +const String kSplitDebugInfo = 'SplitDebugInfo'; + +/// Alternative scheme for file URIs. +/// +/// May be used along with [kFileSystemRoots] to support a multi-root +/// filesystem. +const String kFileSystemScheme = 'FileSystemScheme'; + +/// Additional filesystem roots. +/// +/// If provided, must be used along with [kFileSystemScheme]. +const String kFileSystemRoots = 'FileSystemRoots'; + +/// The define to control what iOS architectures are built for. +/// +/// This is expected to be a space-delimited list of architectures. If not +/// provided, defaults to arm64. +const String kIosArchs = 'IosArchs'; + +/// The define to control what macOS architectures are built for. +/// +/// This is expected to be a space-delimited list of architectures. If not +/// provided, defaults to x86_64 and arm64. +/// +/// Supported values are x86_64 and arm64. +const String kDarwinArchs = 'DarwinArchs'; + +/// The define to control what Android architectures are built for. +/// +/// This is expected to be a space-delimited list of architectures. +const String kAndroidArchs = 'AndroidArchs'; + +/// If the current build is `flutter build aar`. +/// +/// This is expected to be a boolean. +/// +/// If not provided, defaults to false. +const String kIsAndroidLibrary = 'IsAndroidLibrary'; + +/// The define to control what min Android SDK version is built for. +/// +/// This is expected to be int. +/// +/// If not provided, defaults to `minSdkVersion` from gradle_utils.dart. +/// +/// This is passed in by flutter.groovy's invocation of `flutter assemble`. +/// +/// For more info, see: +/// https://developer.android.com/ndk/guides/sdk-versions#minsdkversion +/// https://developer.android.com/ndk/guides/other_build_systems#overview +const String kMinSdkVersion = 'MinSdkVersion'; + +/// Path to the SDK root to be used as the isysroot. +const String kSdkRoot = 'SdkRoot'; + +/// Whether to enable Dart obfuscation and where to save the symbol map. +const String kDartObfuscation = 'DartObfuscation'; + +/// Whether to enable Native Assets. +/// +/// If true, native assets are built and the mapping for native assets lookup +/// at runtime is embedded in the kernel file. +/// +/// If false, native assets are not built, and an empty mapping is embedded in +/// the kernel file. Used for targets that trigger kernel builds but +/// are not OS/architecture specific. +/// +/// Supported values are 'true' and 'false'. +/// +/// Defaults to 'true'. +const String kNativeAssets = 'NativeAssets'; + +/// An output directory where one or more code-size measurements may be written. +const String kCodeSizeDirectory = 'CodeSizeDirectory'; + +/// SHA identifier of the Apple developer code signing identity. +/// +/// Same as EXPANDED_CODE_SIGN_IDENTITY Xcode build setting. +/// Also discoverable via `security find-identity -p codesigning`. +const String kCodesignIdentity = 'CodesignIdentity'; + +/// The build define controlling whether icon fonts should be stripped down to +/// only the glyphs used by the application. +const String kIconTreeShakerFlag = 'TreeShakeIcons'; + +/// The input key for an SkSL bundle path. +const String kBundleSkSLPath = 'BundleSkSLPath'; + +/// The define to pass build name +const String kBuildName = 'BuildName'; + +/// The app flavor to build. +const String kFlavor = 'Flavor'; + +/// The define to pass build number +const String kBuildNumber = 'BuildNumber'; + +/// The action Xcode is taking. +/// +/// Will be "build" when building and "install" when archiving. +const String kXcodeAction = 'Action'; + +final Converter _defineEncoder = utf8.encoder.fuse(base64.encoder); +final Converter _defineDecoder = base64.decoder.fuse(utf8.decoder); + +/// Encode a List of dart defines in a base64 string. +/// +/// This encoding does not include `,`, which is used to distinguish +/// the individual entries, nor does it include `%` which is often a +/// control character on windows command lines. +/// +/// When decoding this string, it can be safely split on commas, since any +/// user provided commands will still be encoded. +/// +/// If the presence of the `/` character ends up being an issue, this can +/// be changed to use base32 instead. +String encodeDartDefines(List defines) { + return defines.map(_defineEncoder.convert).join(','); +} + +List decodeCommaSeparated(Map environmentDefines, String key) { + if (!environmentDefines.containsKey(key) || environmentDefines[key]!.isEmpty) { + return []; + } + return environmentDefines[key]! + .split(',') + .cast() + .toList(); +} + +/// Dart defines are encoded inside [environmentDefines] as a comma-separated list. +List decodeDartDefines(Map environmentDefines, String key) { + if (!environmentDefines.containsKey(key) || environmentDefines[key]!.isEmpty) { + return []; + } + return environmentDefines[key]! + .split(',') + .map(_defineDecoder.convert) + .cast() + .toList(); +} + +/// The null safety runtime mode the app should be built in. +enum NullSafetyMode { + sound, + unsound, + /// The null safety mode was not detected. Only supported for 'flutter test'. + autodetect, +} + +String _getCurrentHostPlatformArchName() { + final HostPlatform hostPlatform = getCurrentHostPlatform(); + return hostPlatform.platformName; +} + +String? _uncapitalize(String? s) { + if (s == null || s.isEmpty) { + return s; + } + return s.substring(0, 1).toLowerCase() + s.substring(1); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/bundle.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/bundle.dart new file mode 100644 index 0000000000000000000000000000000000000000..ef7bfdbddb09532df93bde781deb3de8ddac84ff --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/bundle.dart @@ -0,0 +1,64 @@ +// 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:convert/convert.dart'; +import 'package:crypto/crypto.dart'; + +import 'base/config.dart'; +import 'base/file_system.dart'; +import 'build_info.dart'; +import 'convert.dart'; +import 'globals.dart' as globals; + +String get defaultMainPath => globals.fs.path.join('lib', 'main.dart'); +const String defaultManifestPath = 'pubspec.yaml'; +String get defaultDepfilePath => globals.fs.path.join(getBuildDirectory(), 'snapshot_blob.bin.d'); + +String getDefaultApplicationKernelPath({ + required bool trackWidgetCreation, +}) { + return getKernelPathForTransformerOptions( + globals.fs.path.join(getBuildDirectory(), 'app.dill'), + trackWidgetCreation: trackWidgetCreation, + ); +} + +String getDefaultCachedKernelPath({ + required bool trackWidgetCreation, + required List dartDefines, + List extraFrontEndOptions = const [], + FileSystem? fileSystem, + Config? config, +}) { + final StringBuffer buffer = StringBuffer(); + final List cacheFrontEndOptions = extraFrontEndOptions.toList() + ..removeWhere((String arg) => arg.startsWith('--enable-experiment=')); + buffer.writeAll(dartDefines); + buffer.writeAll(cacheFrontEndOptions); + String buildPrefix = ''; + if (buffer.isNotEmpty) { + final String output = buffer.toString(); + final Digest digest = md5.convert(utf8.encode(output)); + buildPrefix = '${hex.encode(digest.bytes)}.'; + } + return getKernelPathForTransformerOptions( + (fileSystem ?? globals.fs).path.join(getBuildDirectory( + config ?? globals.config, + fileSystem ?? globals.fs + ), '${buildPrefix}cache.dill'), + trackWidgetCreation: trackWidgetCreation, + ); +} + +String getKernelPathForTransformerOptions( + String path, { + required bool trackWidgetCreation, +}) { + if (trackWidgetCreation) { + path += '.track.dill'; + } + return path; +} + +const String defaultPrivateKeyPath = 'privatekey.der'; diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/bundle_builder.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/bundle_builder.dart new file mode 100644 index 0000000000000000000000000000000000000000..496f2d0138e5c37ba1570b65c15edaf6f6aff006 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/bundle_builder.dart @@ -0,0 +1,217 @@ +// 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:pool/pool.dart'; + +import 'asset.dart' hide defaultManifestPath; +import 'base/common.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'build_info.dart'; +import 'build_system/build_system.dart'; +import 'build_system/depfile.dart'; +import 'build_system/targets/common.dart'; +import 'build_system/targets/scene_importer.dart'; +import 'build_system/targets/shader_compiler.dart'; +import 'bundle.dart'; +import 'cache.dart'; +import 'devfs.dart'; +import 'globals.dart' as globals; +import 'project.dart'; + +/// Provides a `build` method that builds the bundle. +class BundleBuilder { + /// Builds the bundle for the given target platform. + /// + /// The default `mainPath` is `lib/main.dart`. + /// The default `manifestPath` is `pubspec.yaml`. + /// + /// If [buildNativeAssets], native assets are built and the mapping for native + /// assets lookup at runtime is embedded in the kernel file, otherwise an + /// empty native assets mapping is embedded in the kernel file. + Future build({ + required TargetPlatform platform, + required BuildInfo buildInfo, + FlutterProject? project, + String? mainPath, + String manifestPath = defaultManifestPath, + String? applicationKernelFilePath, + String? depfilePath, + String? assetDirPath, + bool buildNativeAssets = true, + @visibleForTesting BuildSystem? buildSystem, + }) async { + project ??= FlutterProject.current(); + mainPath ??= defaultMainPath; + depfilePath ??= defaultDepfilePath; + assetDirPath ??= getAssetBuildDirectory(); + buildSystem ??= globals.buildSystem; + + // If the precompiled flag was not passed, force us into debug mode. + final Environment environment = Environment( + projectDir: project.directory, + outputDir: globals.fs.directory(assetDirPath), + buildDir: project.dartTool.childDirectory('flutter_build'), + cacheDir: globals.cache.getRoot(), + flutterRootDir: globals.fs.directory(Cache.flutterRoot), + engineVersion: globals.artifacts!.isLocalEngine + ? null + : globals.flutterVersion.engineRevision, + defines: { + // used by the KernelSnapshot target + kTargetPlatform: getNameForTargetPlatform(platform), + kTargetFile: mainPath, + kDeferredComponents: 'false', + ...buildInfo.toBuildSystemEnvironment(), + if (!buildNativeAssets) kNativeAssets: 'false' + }, + artifacts: globals.artifacts!, + fileSystem: globals.fs, + logger: globals.logger, + processManager: globals.processManager, + usage: globals.flutterUsage, + analytics: globals.analytics, + platform: globals.platform, + generateDartPluginRegistry: true, + ); + final Target target = buildInfo.mode == BuildMode.debug + ? const CopyFlutterBundle() + : const ReleaseCopyFlutterBundle(); + final BuildResult result = await buildSystem.build(target, environment); + + if (!result.success) { + for (final ExceptionMeasurement measurement in result.exceptions.values) { + globals.printError('Target ${measurement.target} failed: ${measurement.exception}', + stackTrace: measurement.fatal + ? measurement.stackTrace + : null, + ); + } + throwToolExit('Failed to build bundle.'); + } + final Depfile depfile = Depfile(result.inputFiles, result.outputFiles); + final File outputDepfile = globals.fs.file(depfilePath); + if (!outputDepfile.parent.existsSync()) { + outputDepfile.parent.createSync(recursive: true); + } + environment.depFileService.writeToFile(depfile, outputDepfile); + + // Work around for flutter_tester placing kernel artifacts in odd places. + if (applicationKernelFilePath != null) { + final File outputDill = globals.fs.directory(assetDirPath).childFile('kernel_blob.bin'); + if (outputDill.existsSync()) { + outputDill.copySync(applicationKernelFilePath); + } + } + return; + } +} + +Future buildAssets({ + required String manifestPath, + String? assetDirPath, + String? packagesPath, + TargetPlatform? targetPlatform, + String? flavor, +}) async { + assetDirPath ??= getAssetBuildDirectory(); + packagesPath ??= globals.fs.path.absolute('.packages'); + + // Build the asset bundle. + final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle(); + final int result = await assetBundle.build( + manifestPath: manifestPath, + packagesPath: packagesPath, + targetPlatform: targetPlatform, + flavor: flavor, + ); + if (result != 0) { + return null; + } + + return assetBundle; +} + +Future writeBundle( + Directory bundleDir, + Map assetEntries, + Map entryKinds, { + Logger? loggerOverride, + required TargetPlatform targetPlatform, +}) async { + loggerOverride ??= globals.logger; + if (bundleDir.existsSync()) { + try { + bundleDir.deleteSync(recursive: true); + } on FileSystemException catch (err) { + loggerOverride.printWarning( + 'Failed to clean up asset directory ${bundleDir.path}: $err\n' + 'To clean build artifacts, use the command "flutter clean".' + ); + } + } + bundleDir.createSync(recursive: true); + + final ShaderCompiler shaderCompiler = ShaderCompiler( + processManager: globals.processManager, + logger: globals.logger, + fileSystem: globals.fs, + artifacts: globals.artifacts!, + ); + + final SceneImporter sceneImporter = SceneImporter( + processManager: globals.processManager, + logger: globals.logger, + fileSystem: globals.fs, + artifacts: globals.artifacts!, + ); + + // Limit number of open files to avoid running out of file descriptors. + final Pool pool = Pool(64); + await Future.wait( + assetEntries.entries.map>((MapEntry entry) async { + final PoolResource resource = await pool.request(); + try { + // This will result in strange looking files, for example files with `/` + // on Windows or files that end up getting URI encoded such as `#.ext` + // to `%23.ext`. However, we have to keep it this way since the + // platform channels in the framework will URI encode these values, + // and the native APIs will look for files this way. + final File file = globals.fs.file(globals.fs.path.join(bundleDir.path, entry.key)); + final AssetKind assetKind = entryKinds[entry.key] ?? AssetKind.regular; + file.parent.createSync(recursive: true); + final DevFSContent devFSContent = entry.value; + if (devFSContent is DevFSFileContent) { + final File input = devFSContent.file as File; + bool doCopy = true; + switch (assetKind) { + case AssetKind.regular: + break; + case AssetKind.font: + break; + case AssetKind.shader: + doCopy = !await shaderCompiler.compileShader( + input: input, + outputPath: file.path, + target: ShaderTarget.sksl, // TODO(zanderso): configure impeller target when enabled. + json: targetPlatform == TargetPlatform.web_javascript, + ); + case AssetKind.model: + doCopy = !await sceneImporter.importScene( + input: input, + outputPath: file.path, + ); + } + if (doCopy) { + input.copySync(file.path); + } + } else { + await file.writeAsBytes(await entry.value.contentsAsBytes()); + } + } finally { + resource.release(); + } + })); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/cache.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/cache.dart new file mode 100644 index 0000000000000000000000000000000000000000..5a03827cb3ecd76bb7aaec147f3e7587200cebfe --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/cache.dart @@ -0,0 +1,1351 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:crypto/crypto.dart'; +import 'package:file/memory.dart'; +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import 'base/common.dart'; +import 'base/error_handling_io.dart'; +import 'base/file_system.dart'; +import 'base/io.dart' show HttpClient, HttpClientRequest, HttpClientResponse, HttpHeaders, HttpStatus, SocketException; +import 'base/logger.dart'; +import 'base/net.dart'; +import 'base/os.dart' show OperatingSystemUtils; +import 'base/platform.dart'; +import 'base/terminal.dart'; +import 'base/user_messages.dart'; +import 'convert.dart'; +import 'features.dart'; + +const String kFlutterRootEnvironmentVariableName = 'FLUTTER_ROOT'; // should point to //flutter/ (root of flutter/flutter repo) +const String kFlutterEngineEnvironmentVariableName = 'FLUTTER_ENGINE'; // should point to //engine/src/ (root of flutter/engine repo) +const String kSnapshotFileName = 'flutter_tools.snapshot'; // in //flutter/bin/cache/ +const String kFlutterToolsScriptFileName = 'flutter_tools.dart'; // in //flutter/packages/flutter_tools/bin/ +const String kFlutterEnginePackageName = 'sky_engine'; + +/// A tag for a set of development artifacts that need to be cached. +class DevelopmentArtifact { + + const DevelopmentArtifact._(this.name, {this.feature}); + + /// The name of the artifact. + /// + /// This should match the flag name in precache.dart. + final String name; + + /// A feature to control the visibility of this artifact. + final Feature? feature; + + /// Artifacts required for Android development. + static const DevelopmentArtifact androidGenSnapshot = DevelopmentArtifact._('android_gen_snapshot', feature: flutterAndroidFeature); + static const DevelopmentArtifact androidMaven = DevelopmentArtifact._('android_maven', feature: flutterAndroidFeature); + + // Artifacts used for internal builds. + static const DevelopmentArtifact androidInternalBuild = DevelopmentArtifact._('android_internal_build', feature: flutterAndroidFeature); + + /// Artifacts required for iOS development. + static const DevelopmentArtifact iOS = DevelopmentArtifact._('ios', feature: flutterIOSFeature); + + /// Artifacts required for web development. + static const DevelopmentArtifact web = DevelopmentArtifact._('web', feature: flutterWebFeature); + + /// Artifacts required for desktop macOS. + static const DevelopmentArtifact macOS = DevelopmentArtifact._('macos', feature: flutterMacOSDesktopFeature); + + /// Artifacts required for desktop Windows. + static const DevelopmentArtifact windows = DevelopmentArtifact._('windows', feature: flutterWindowsDesktopFeature); + + /// Artifacts required for desktop Linux. + static const DevelopmentArtifact linux = DevelopmentArtifact._('linux', feature: flutterLinuxDesktopFeature); + + /// Artifacts required for Fuchsia. + static const DevelopmentArtifact fuchsia = DevelopmentArtifact._('fuchsia', feature: flutterFuchsiaFeature); + + /// Artifacts required for the Flutter Runner. + static const DevelopmentArtifact flutterRunner = DevelopmentArtifact._('flutter_runner', feature: flutterFuchsiaFeature); + + /// Artifacts required for any development platform. + /// + /// This does not need to be explicitly returned from requiredArtifacts as + /// it will always be downloaded. + static const DevelopmentArtifact universal = DevelopmentArtifact._('universal'); + + /// The values of DevelopmentArtifacts. + static final List values = [ + androidGenSnapshot, + androidMaven, + androidInternalBuild, + iOS, + web, + macOS, + windows, + linux, + fuchsia, + universal, + flutterRunner, + ]; + + @override + String toString() => 'Artifact($name)'; +} + +/// A wrapper around the `bin/cache/` directory. +/// +/// This does not provide any artifacts by default. See [FlutterCache] for the default +/// artifact set. +/// +/// ## Artifact mirrors +/// +/// Some environments cannot reach the Google Cloud Storage buckets and CIPD due +/// to regional or corporate policies. +/// +/// To enable Flutter users in these environments, the Flutter tool supports +/// custom artifact mirrors that the administrators of such environments may +/// provide. To use an artifact mirror, the user defines the [kFlutterStorageBaseUrl] +/// (`FLUTTER_STORAGE_BASE_URL`) environment variable that points to the mirror. +/// Flutter tool reads this variable and uses it instead of the default URLs. +/// +/// For more details on specific URLs used to download artifacts, see +/// [storageBaseUrl] and [cipdBaseUrl]. +class Cache { + /// [rootOverride] is configurable for testing. + /// [artifacts] is configurable for testing. + Cache({ + @protected Directory? rootOverride, + @protected List? artifacts, + required Logger logger, + required FileSystem fileSystem, + required Platform platform, + required OperatingSystemUtils osUtils, + }) : _rootOverride = rootOverride, + _logger = logger, + _fileSystem = fileSystem, + _platform = platform, + _osUtils = osUtils, + _net = Net(logger: logger, platform: platform), + _fsUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform), + _artifacts = artifacts ?? []; + + /// Create a [Cache] for testing. + /// + /// Defaults to a memory file system, fake platform, + /// buffer logger, and no accessible artifacts. + /// By default, the root cache directory path is "cache". + factory Cache.test({ + Directory? rootOverride, + List? artifacts, + Logger? logger, + FileSystem? fileSystem, + Platform? platform, + required ProcessManager processManager, + }) { + fileSystem ??= rootOverride?.fileSystem ?? MemoryFileSystem.test(); + platform ??= FakePlatform(environment: {}); + logger ??= BufferLogger.test(); + return Cache( + rootOverride: rootOverride ?? fileSystem.directory('cache'), + artifacts: artifacts ?? [], + logger: logger, + fileSystem: fileSystem, + platform: platform, + osUtils: OperatingSystemUtils( + fileSystem: fileSystem, + logger: logger, + platform: platform, + processManager: processManager, + ), + ); + } + + final Logger _logger; + final Platform _platform; + final FileSystem _fileSystem; + final OperatingSystemUtils _osUtils; + final Directory? _rootOverride; + final List _artifacts; + final Net _net; + final FileSystemUtils _fsUtils; + + late final ArtifactUpdater _artifactUpdater = _createUpdater(); + + @visibleForTesting + @protected + void registerArtifact(ArtifactSet artifactSet) { + _artifacts.add(artifactSet); + } + + /// This has to be lazy because it requires FLUTTER_ROOT to be initialized. + ArtifactUpdater _createUpdater() { + return ArtifactUpdater( + operatingSystemUtils: _osUtils, + logger: _logger, + fileSystem: _fileSystem, + tempStorage: getDownloadDir(), + platform: _platform, + httpClient: HttpClient(), + allowedBaseUrls: [ + storageBaseUrl, + realmlessStorageBaseUrl, + cipdBaseUrl, + ], + ); + } + + static const List _hostsBlockedInChina = [ + 'storage.googleapis.com', + 'chrome-infra-packages.appspot.com', + ]; + + // Initialized by FlutterCommandRunner on startup. + // Explore making this field lazy to catch non-initialized access. + static String? flutterRoot; + + /// Determine the absolute and normalized path for the root of the current + /// Flutter checkout. + /// + /// This method has a series of fallbacks for determining the repo location. The + /// first success will immediately return the root without further checks. + /// + /// The order of these tests is: + /// 1. FLUTTER_ROOT environment variable contains the path. + /// 2. Platform script is a data URI scheme, returning `../..` to support + /// tests run from `packages/flutter_tools`. + /// 3. Platform script is package URI scheme, returning the grandparent directory + /// of the package config file location from `packages/flutter_tools/.packages`. + /// 4. Platform script file path is the snapshot path generated by `bin/flutter`, + /// returning the grandparent directory from `bin/cache`. + /// 5. Platform script file name is the entrypoint in `packages/flutter_tools/bin/flutter_tools.dart`, + /// returning the 4th parent directory. + /// 6. The current directory + /// + /// If an exception is thrown during any of these checks, an error message is + /// printed and `.` is returned by default (6). + static String defaultFlutterRoot({ + required Platform platform, + required FileSystem fileSystem, + required UserMessages userMessages, + }) { + String normalize(String path) { + return fileSystem.path.normalize(fileSystem.path.absolute(path)); + } + if (platform.environment.containsKey(kFlutterRootEnvironmentVariableName)) { + return normalize(platform.environment[kFlutterRootEnvironmentVariableName]!); + } + try { + if (platform.script.scheme == 'data') { + return normalize('../..'); // The tool is running as a test. + } + final String Function(String) dirname = fileSystem.path.dirname; + + if (platform.script.scheme == 'package') { + final String packageConfigPath = Uri.parse(platform.packageConfig!).toFilePath( + windows: platform.isWindows, + ); + return normalize(dirname(dirname(dirname(packageConfigPath)))); + } + + if (platform.script.scheme == 'file') { + final String script = platform.script.toFilePath( + windows: platform.isWindows, + ); + if (fileSystem.path.basename(script) == kSnapshotFileName) { + return normalize(dirname(dirname(fileSystem.path.dirname(script)))); + } + if (fileSystem.path.basename(script) == kFlutterToolsScriptFileName) { + return normalize(dirname(dirname(dirname(dirname(script))))); + } + } + } on Exception catch (error) { + // There is currently no logger attached since this is computed at startup. + // ignore: avoid_print + print(userMessages.runnerNoRoot('$error')); + } + return normalize('.'); + } + + // Whether to cache artifacts for all platforms. Defaults to only caching + // artifacts for the current platform. + bool includeAllPlatforms = false; + + // Names of artifacts which should be cached even if they would normally + // be filtered out for the current platform. + Set? platformOverrideArtifacts; + + // Whether to cache the unsigned mac binaries. Defaults to caching the signed binaries. + bool useUnsignedMacBinaries = false; + + // Whether the warning printed when a custom artifact URL is used is fatal. + bool fatalStorageWarning = true; + + static RandomAccessFile? _lock; + static bool _lockEnabled = true; + + /// Turn off the [lock]/[releaseLock] mechanism. + /// + /// This is used by the tests since they run simultaneously and all in one + /// process and so it would be a mess if they had to use the lock. + @visibleForTesting + static void disableLocking() { + _lockEnabled = false; + } + + /// Turn on the [lock]/[releaseLock] mechanism. + /// + /// This is used by the tests. + @visibleForTesting + static void enableLocking() { + _lockEnabled = true; + } + + /// Check if lock acquired, skipping FLUTTER_ALREADY_LOCKED reentrant checks. + /// + /// This is used by the tests. + @visibleForTesting + static bool isLocked() { + return _lock != null; + } + + /// Lock the cache directory. + /// + /// This happens while required artifacts are updated + /// (see [FlutterCommandRunner.runCommand]). + /// + /// This uses normal POSIX flock semantics. + Future lock() async { + if (!_lockEnabled) { + return; + } + assert(_lock == null); + final File lockFile = + _fileSystem.file(_fileSystem.path.join(flutterRoot!, 'bin', 'cache', 'lockfile')); + try { + _lock = lockFile.openSync(mode: FileMode.write); + } on FileSystemException catch (e) { + _logger.printError('Failed to open or create the artifact cache lockfile: "$e"'); + _logger.printError('Please ensure you have permissions to create or open ${lockFile.path}'); + throwToolExit('Failed to open or create the lockfile'); + } + bool locked = false; + bool printed = false; + while (!locked) { + try { + _lock!.lockSync(); + locked = true; + } on FileSystemException { + if (!printed) { + _logger.printTrace('Waiting to be able to obtain lock of Flutter binary artifacts directory: ${_lock!.path}'); + // This needs to go to stderr to avoid cluttering up stdout if a + // parent process is collecting stdout (e.g. when calling "flutter + // version --machine"). It's not really a "warning" though, so print it + // in grey. Also, make sure that it isn't counted as a warning for + // Logger.warningsAreFatal. + _logger.printWarning( + 'Waiting for another flutter command to release the startup lock...', + color: TerminalColor.grey, + fatal: false, + ); + printed = true; + } + await Future.delayed(const Duration(milliseconds: 50)); + } + } + } + + /// Releases the lock. + /// + /// This happens automatically on startup (see [FlutterCommand.verifyThenRunCommand]) + /// after the command's required artifacts are updated. + void releaseLock() { + if (!_lockEnabled || _lock == null) { + return; + } + _lock!.closeSync(); + _lock = null; + } + + /// Checks if the current process owns the lock for the cache directory at + /// this very moment; throws a [StateError] if it doesn't. + void checkLockAcquired() { + if (_lockEnabled && _lock == null && _platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') { + throw StateError( + 'The current process does not own the lock for the cache directory. This is a bug in Flutter CLI tools.', + ); + } + } + + String get devToolsVersion { + if (_devToolsVersion == null) { + const String devToolsDirPath = 'dart-sdk/bin/resources/devtools'; + final Directory devToolsDir = getCacheDir(devToolsDirPath, shouldCreate: false); + if (!devToolsDir.existsSync()) { + throw Exception('Could not find directory at ${devToolsDir.path}'); + } + final String versionFilePath = '${devToolsDir.path}/version.json'; + final File versionFile = _fileSystem.file(versionFilePath); + if (!versionFile.existsSync()) { + throw Exception('Could not find file at $versionFilePath'); + } + final dynamic data = jsonDecode(versionFile.readAsStringSync()); + if (data is! Map) { + throw Exception("Expected object of type 'Map' but got one of type '${data.runtimeType}'"); + } + final Object? version = data['version']; + if (version == null) { + throw Exception('Could not parse DevTools version from $version'); + } + if (version is! String) { + throw Exception("Could not parse DevTools version. Expected object of type 'String', but got one of type '${version.runtimeType}'"); + } + return _devToolsVersion = version; + } + return _devToolsVersion!; + } + String ? _devToolsVersion; + + /// The current version of Dart used to build Flutter and run the tool. + String get dartSdkVersion { + if (_dartSdkVersion == null) { + // Make the version string more customer-friendly. + // Changes '2.1.0-dev.8.0.flutter-4312ae32' to '2.1.0 (build 2.1.0-dev.8.0 4312ae32)' + final String justVersion = _platform.version.split(' ')[0]; + _dartSdkVersion = justVersion.replaceFirstMapped(RegExp(r'(\d+\.\d+\.\d+)(.+)'), (Match match) { + final String noFlutter = match[2]!.replaceAll('.flutter-', ' '); + return '${match[1]} (build ${match[1]}$noFlutter)'; + }); + } + return _dartSdkVersion!; + } + String? _dartSdkVersion; + + /// The current version of Dart used to build Flutter and run the tool. + String get dartSdkBuild { + if (_dartSdkBuild == null) { + // Make the version string more customer-friendly. + // Changes '2.1.0-dev.8.0.flutter-4312ae32' to '2.1.0 (build 2.1.0-dev.8.0 4312ae32)' + final String justVersion = _platform.version.split(' ')[0]; + _dartSdkBuild = justVersion.replaceFirstMapped(RegExp(r'(\d+\.\d+\.\d+)(.+)'), (Match match) { + final String noFlutter = match[2]!.replaceAll('.flutter-', ' '); + return '${match[1]}$noFlutter'; + }); + } + return _dartSdkBuild!; + } + String? _dartSdkBuild; + + + /// The current version of the Flutter engine the flutter tool will download. + String get engineRevision { + _engineRevision ??= getVersionFor('engine'); + if (_engineRevision == null) { + throwToolExit('Could not determine engine revision.'); + } + return _engineRevision!; + } + String? _engineRevision; + + /// The "realm" for the storage URL. + /// + /// For production artifacts from Engine post-submit and release builds, + /// this string will be empty, and the `storageBaseUrl` will be unmodified. + /// When non-empty, this string will be appended to the `storageBaseUrl` after + /// a '/'. For artifacts generated by Engine presubmits, the realm should be + /// "flutter_archives_v2". + String get storageRealm { + _storageRealm ??= getRealmFor('engine'); + if (_storageRealm == null) { + throwToolExit('Could not determine engine realm.'); + } + return _storageRealm!; + } + String? _storageRealm; + + /// The base for URLs that store Flutter engine artifacts that are fetched + /// during the installation of the Flutter SDK. + /// + /// By default the base URL is https://storage.googleapis.com. However, if + /// `FLUTTER_STORAGE_BASE_URL` environment variable ([kFlutterStorageBaseUrl]) + /// is provided, the environment variable value is returned instead. + /// + /// See also: + /// + /// * [cipdBaseUrl], which determines how CIPD artifacts are fetched. + /// * [Cache] class-level dartdocs that explain how artifact mirrors work. + String get storageBaseUrl { + String? overrideUrl = _platform.environment[kFlutterStorageBaseUrl]; + if (overrideUrl == null) { + return storageRealm.isEmpty + ? 'https://storage.googleapis.com' + : 'https://storage.googleapis.com/$storageRealm'; + } + // verify that this is a valid URI. + overrideUrl = storageRealm.isEmpty ? overrideUrl : '$overrideUrl/$storageRealm'; + try { + Uri.parse(overrideUrl); + } on FormatException catch (err) { + throwToolExit('"$kFlutterStorageBaseUrl" contains an invalid URL:\n$err'); + } + _maybeWarnAboutStorageOverride(overrideUrl); + return overrideUrl; + } + + String get realmlessStorageBaseUrl { + return storageRealm.isEmpty + ? storageBaseUrl + : storageBaseUrl.replaceAll('/$storageRealm', ''); + } + + /// The base for URLs that store Flutter engine artifacts in CIPD. + /// + /// For some platforms, such as Web and Fuchsia, CIPD artifacts are fetched + /// during the installation of the Flutter SDK, in addition to those fetched + /// from [storageBaseUrl]. + /// + /// By default the base URL is https://chrome-infra-packages.appspot.com/dl. + /// However, if `FLUTTER_STORAGE_BASE_URL` environment variable is provided + /// ([kFlutterStorageBaseUrl]), then the following value is used: + /// + /// FLUTTER_STORAGE_BASE_URL/flutter_infra_release/cipd + /// + /// See also: + /// + /// * [storageBaseUrl], which determines how engine artifacts stored in the + /// Google Cloud Storage buckets are fetched. + /// * https://chromium.googlesource.com/infra/luci/luci-go/+/refs/heads/main/cipd, + /// which contains information about CIPD. + /// * [Cache] class-level dartdocs that explain how artifact mirrors work. + String get cipdBaseUrl { + final String? overrideUrl = _platform.environment[kFlutterStorageBaseUrl]; + if (overrideUrl == null) { + return 'https://chrome-infra-packages.appspot.com/dl'; + } + + final Uri original; + try { + original = Uri.parse(overrideUrl); + } on FormatException catch (err) { + throwToolExit('"$kFlutterStorageBaseUrl" contains an invalid URL:\n$err'); + } + + final String cipdOverride = original.replace( + pathSegments: [ + ...original.pathSegments, + 'flutter_infra_release', + 'cipd', + ], + ).toString(); + return cipdOverride; + } + + bool _hasWarnedAboutStorageOverride = false; + + void _maybeWarnAboutStorageOverride(String overrideUrl) { + if (_hasWarnedAboutStorageOverride) { + return; + } + _logger.printWarning( + 'Flutter assets will be downloaded from $overrideUrl. Make sure you trust this source!', + emphasis: true, + fatal: false, + ); + _hasWarnedAboutStorageOverride = true; + } + + /// Return the top-level directory in the cache; this is `bin/cache`. + Directory getRoot() { + if (_rootOverride != null) { + return _fileSystem.directory(_fileSystem.path.join(_rootOverride.path, 'bin', 'cache')); + } else { + return _fileSystem.directory(_fileSystem.path.join(flutterRoot!, 'bin', 'cache')); + } + } + + String getHostPlatformArchName() { + return _osUtils.hostPlatform.platformName; + } + + /// Return a directory in the cache dir. For `pkg`, this will return `bin/cache/pkg`. + /// + /// When [shouldCreate] is true, the cache directory at [name] will be created + /// if it does not already exist. + Directory getCacheDir(String name, { bool shouldCreate = true }) { + final Directory dir = _fileSystem.directory(_fileSystem.path.join(getRoot().path, name)); + if (!dir.existsSync() && shouldCreate) { + dir.createSync(recursive: true); + _osUtils.chmod(dir, '755'); + } + return dir; + } + + /// Return the top-level directory for artifact downloads. + Directory getDownloadDir() => getCacheDir('downloads'); + + /// Return the top-level mutable directory in the cache; this is `bin/cache/artifacts`. + Directory getCacheArtifacts() => getCacheDir('artifacts'); + + /// Location of LICENSE file. + File getLicenseFile() => _fileSystem.file(_fileSystem.path.join(flutterRoot!, 'LICENSE')); + + /// Get a named directory from with the cache's artifact directory; for example, + /// `material_fonts` would return `bin/cache/artifacts/material_fonts`. + Directory getArtifactDirectory(String name) { + return getCacheArtifacts().childDirectory(name); + } + + MapEntry get dyLdLibEntry { + if (_dyLdLibEntry != null) { + return _dyLdLibEntry!; + } + final List paths = []; + for (final ArtifactSet artifact in _artifacts) { + final Map env = artifact.environment; + if (!env.containsKey('DYLD_LIBRARY_PATH')) { + continue; + } + final String path = env['DYLD_LIBRARY_PATH']!; + if (path.isEmpty) { + continue; + } + paths.add(path); + } + _dyLdLibEntry = MapEntry('DYLD_LIBRARY_PATH', paths.join(':')); + return _dyLdLibEntry!; + } + MapEntry? _dyLdLibEntry; + + /// The web sdk has to be co-located with the dart-sdk so that they can share source + /// code. + Directory getWebSdkDirectory() { + return getRoot().childDirectory('flutter_web_sdk'); + } + + String? getVersionFor(String artifactName) { + final File versionFile = _fileSystem.file(_fileSystem.path.join( + _rootOverride?.path ?? flutterRoot!, + 'bin', + 'internal', + '$artifactName.version', + )); + return versionFile.existsSync() ? versionFile.readAsStringSync().trim() : null; + } + + String? getRealmFor(String artifactName) { + final File realmFile = _fileSystem.file(_fileSystem.path.join( + _rootOverride?.path ?? flutterRoot!, + 'bin', + 'internal', + '$artifactName.realm', + )); + return realmFile.existsSync() ? realmFile.readAsStringSync().trim() : ''; + } + + /// Delete all stamp files maintained by the cache. + void clearStampFiles() { + try { + getStampFileFor('flutter_tools').deleteSync(); + for (final ArtifactSet artifact in _artifacts) { + final File file = getStampFileFor(artifact.stampName); + ErrorHandlingFileSystem.deleteIfExists(file); + } + } on FileSystemException catch (err) { + _logger.printWarning('Failed to delete some stamp files: $err'); + } + } + + /// Read the stamp for [artifactName]. + /// + /// If the file is missing or cannot be parsed, returns `null`. + String? getStampFor(String artifactName) { + final File stampFile = getStampFileFor(artifactName); + if (!stampFile.existsSync()) { + return null; + } + try { + return stampFile.readAsStringSync().trim(); + } on FileSystemException { + return null; + } + } + + void setStampFor(String artifactName, String version) { + getStampFileFor(artifactName).writeAsStringSync(version); + } + + File getStampFileFor(String artifactName) { + return _fileSystem.file(_fileSystem.path.join(getRoot().path, '$artifactName.stamp')); + } + + /// Returns `true` if either [entity] is older than the tools stamp or if + /// [entity] doesn't exist. + bool isOlderThanToolsStamp(FileSystemEntity entity) { + final File flutterToolsStamp = getStampFileFor('flutter_tools'); + return _fsUtils.isOlderThanReference( + entity: entity, + referenceFile: flutterToolsStamp, + ); + } + + Future isUpToDate() async { + for (final ArtifactSet artifact in _artifacts) { + if (!await artifact.isUpToDate(_fileSystem)) { + return false; + } + } + return true; + } + + /// Update the cache to contain all `requiredArtifacts`. + Future updateAll(Set requiredArtifacts, {bool offline = false}) async { + if (!_lockEnabled) { + return; + } + for (final ArtifactSet artifact in _artifacts) { + if (!requiredArtifacts.contains(artifact.developmentArtifact)) { + _logger.printTrace('Artifact $artifact is not required, skipping update.'); + continue; + } + if (await artifact.isUpToDate(_fileSystem)) { + continue; + } + try { + await artifact.update(_artifactUpdater, _logger, _fileSystem, _osUtils, offline: offline); + } on SocketException catch (e) { + if (_hostsBlockedInChina.contains(e.address?.host)) { + _logger.printError( + 'Failed to retrieve Flutter tool dependencies: ${e.message}.\n' + "If you're in China, please see this page: " + 'https://flutter.dev/community/china', + emphasis: true, + ); + } + rethrow; + } + } + } + + Future areRemoteArtifactsAvailable({ + String? engineVersion, + bool includeAllPlatforms = true, + }) async { + final bool includeAllPlatformsState = this.includeAllPlatforms; + bool allAvailable = true; + this.includeAllPlatforms = includeAllPlatforms; + for (final ArtifactSet cachedArtifact in _artifacts) { + if (cachedArtifact is EngineCachedArtifact) { + allAvailable &= await cachedArtifact.checkForArtifacts(engineVersion); + } + } + this.includeAllPlatforms = includeAllPlatformsState; + return allAvailable; + } + + Future doesRemoteExist(String message, Uri url) async { + final Status status = _logger.startProgress( + message, + ); + bool exists; + try { + exists = await _net.doesRemoteFileExist(url); + } finally { + status.stop(); + } + return exists; + } +} + +/// Representation of a set of artifacts used by the tool. +abstract class ArtifactSet { + ArtifactSet(this.developmentArtifact); + + /// The development artifact. + final DevelopmentArtifact developmentArtifact; + + /// [true] if the artifact is up to date. + Future isUpToDate(FileSystem fileSystem); + + /// The environment variables (if any) required to consume the artifacts. + Map get environment { + return const {}; + } + + /// Updates the artifact. + Future update( + ArtifactUpdater artifactUpdater, + Logger logger, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + {bool offline = false} + ); + + /// The canonical name of the artifact. + String get name; + + // The name of the stamp file. Defaults to the same as the + // artifact name. + String get stampName => name; +} + +/// An artifact set managed by the cache. +abstract class CachedArtifact extends ArtifactSet { + CachedArtifact( + this.name, + this.cache, + DevelopmentArtifact developmentArtifact, + ) : super(developmentArtifact); + + final Cache cache; + + @override + final String name; + + @override + String get stampName => name; + + Directory get location => cache.getArtifactDirectory(name); + + String? get version => cache.getVersionFor(name); + + // Whether or not to bypass normal platform filtering for this artifact. + bool get ignorePlatformFiltering { + return cache.includeAllPlatforms || + (cache.platformOverrideArtifacts != null && cache.platformOverrideArtifacts!.contains(developmentArtifact.name)); + } + + @override + Future isUpToDate(FileSystem fileSystem) async { + if (!location.existsSync()) { + return false; + } + if (version != cache.getStampFor(stampName)) { + return false; + } + return isUpToDateInner(fileSystem); + } + + @override + Future update( + ArtifactUpdater artifactUpdater, + Logger logger, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + {bool offline = false} + ) async { + if (!location.existsSync()) { + try { + location.createSync(recursive: true); + } on FileSystemException catch (err) { + logger.printError(err.toString()); + throwToolExit( + 'Failed to create directory for flutter cache at ${location.path}. ' + 'Flutter may be missing permissions in its cache directory.' + ); + } + } + await updateInner(artifactUpdater, fileSystem, operatingSystemUtils); + try { + if (version == null) { + logger.printWarning( + 'No known version for the artifact name "$name". ' + 'Flutter can continue, but the artifact may be re-downloaded on ' + 'subsequent invocations until the problem is resolved.', + ); + } else { + cache.setStampFor(stampName, version!); + } + } on FileSystemException catch (err) { + logger.printWarning( + 'The new artifact "$name" was downloaded, but Flutter failed to update ' + 'its stamp file, receiving the error "$err". ' + 'Flutter can continue, but the artifact may be re-downloaded on ' + 'subsequent invocations until the problem is resolved.', + ); + } + artifactUpdater.removeDownloadedFiles(); + } + + /// Hook method for extra checks for being up-to-date. + bool isUpToDateInner(FileSystem fileSystem) => true; + + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ); +} + + +abstract class EngineCachedArtifact extends CachedArtifact { + EngineCachedArtifact( + this.stampName, + Cache cache, + DevelopmentArtifact developmentArtifact, + ) : super('engine', cache, developmentArtifact); + + @override + final String stampName; + + /// Return a list of (directory path, download URL path) tuples. + List> getBinaryDirs(); + + /// A list of cache directory paths to which the LICENSE file should be copied. + List getLicenseDirs(); + + /// A list of the dart package directories to download. + List getPackageDirs(); + + @override + bool isUpToDateInner(FileSystem fileSystem) { + final Directory pkgDir = cache.getCacheDir('pkg'); + for (final String pkgName in getPackageDirs()) { + final String pkgPath = fileSystem.path.join(pkgDir.path, pkgName); + if (!fileSystem.directory(pkgPath).existsSync()) { + return false; + } + } + + for (final List toolsDir in getBinaryDirs()) { + final Directory dir = fileSystem.directory(fileSystem.path.join(location.path, toolsDir[0])); + if (!dir.existsSync()) { + return false; + } + } + + for (final String licenseDir in getLicenseDirs()) { + final File file = fileSystem.file(fileSystem.path.join(location.path, licenseDir, 'LICENSE')); + if (!file.existsSync()) { + return false; + } + } + return true; + } + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + final String url = '${cache.storageBaseUrl}/flutter_infra_release/flutter/$version/'; + + final Directory pkgDir = cache.getCacheDir('pkg'); + for (final String pkgName in getPackageDirs()) { + await artifactUpdater.downloadZipArchive('Downloading package $pkgName...', Uri.parse('$url$pkgName.zip'), pkgDir); + } + + for (final List toolsDir in getBinaryDirs()) { + final String cacheDir = toolsDir[0]; + final String urlPath = toolsDir[1]; + final Directory dir = fileSystem.directory(fileSystem.path.join(location.path, cacheDir)); + + // Avoid printing things like 'Downloading linux-x64 tools...' multiple times. + final String friendlyName = urlPath.replaceAll('/artifacts.zip', '').replaceAll('.zip', ''); + await artifactUpdater.downloadZipArchive('Downloading $friendlyName tools...', Uri.parse(url + urlPath), dir); + + _makeFilesExecutable(dir, operatingSystemUtils); + + final File frameworkZip = fileSystem.file(fileSystem.path.join(dir.path, 'FlutterMacOS.framework.zip')); + if (frameworkZip.existsSync()) { + final Directory framework = fileSystem.directory(fileSystem.path.join(dir.path, 'FlutterMacOS.framework')); + ErrorHandlingFileSystem.deleteIfExists(framework, recursive: true); + framework.createSync(); + operatingSystemUtils.unzip(frameworkZip, framework); + } + } + + final File licenseSource = cache.getLicenseFile(); + for (final String licenseDir in getLicenseDirs()) { + final String licenseDestinationPath = fileSystem.path.join(location.path, licenseDir, 'LICENSE'); + await licenseSource.copy(licenseDestinationPath); + } + } + + Future checkForArtifacts(String? engineVersion) async { + engineVersion ??= version; + final String url = '${cache.storageBaseUrl}/flutter_infra_release/flutter/$engineVersion/'; + + bool exists = false; + for (final String pkgName in getPackageDirs()) { + exists = await cache.doesRemoteExist('Checking package $pkgName is available...', Uri.parse('$url$pkgName.zip')); + if (!exists) { + return false; + } + } + + for (final List toolsDir in getBinaryDirs()) { + final String cacheDir = toolsDir[0]; + final String urlPath = toolsDir[1]; + exists = await cache.doesRemoteExist('Checking $cacheDir tools are available...', + Uri.parse(url + urlPath)); + if (!exists) { + return false; + } + } + return true; + } + + void _makeFilesExecutable(Directory dir, OperatingSystemUtils operatingSystemUtils) { + operatingSystemUtils.chmod(dir, 'a+r,a+x'); + for (final File file in dir.listSync(recursive: true).whereType()) { + final FileStat stat = file.statSync(); + final bool isUserExecutable = ((stat.mode >> 6) & 0x1) == 1; + if (file.basename == 'flutter_tester' || isUserExecutable) { + // Make the file readable and executable by all users. + operatingSystemUtils.chmod(file, 'a+r,a+x'); + } + } + } +} + +/// An API for downloading and un-archiving artifacts, such as engine binaries or +/// additional source code. +class ArtifactUpdater { + ArtifactUpdater({ + required OperatingSystemUtils operatingSystemUtils, + required Logger logger, + required FileSystem fileSystem, + required Directory tempStorage, + required HttpClient httpClient, + required Platform platform, + required List allowedBaseUrls, + }) : _operatingSystemUtils = operatingSystemUtils, + _httpClient = httpClient, + _logger = logger, + _fileSystem = fileSystem, + _tempStorage = tempStorage, + _platform = platform, + _allowedBaseUrls = allowedBaseUrls; + + /// The number of times the artifact updater will repeat the artifact download loop. + static const int _kRetryCount = 2; + + final Logger _logger; + final OperatingSystemUtils _operatingSystemUtils; + final FileSystem _fileSystem; + final Directory _tempStorage; + final HttpClient _httpClient; + final Platform _platform; + + /// Artifacts should only be downloaded from URLs that use one of these + /// prefixes. + /// + /// [ArtifactUpdater] will issue a warning if an attempt to download from a + /// non-compliant URL is made. + final List _allowedBaseUrls; + + /// Keep track of the files we've downloaded for this execution so we + /// can delete them after completion. We don't delete them right after + /// extraction in case [update] is interrupted, so we can restart without + /// starting from scratch. + @visibleForTesting + final List downloadedFiles = []; + + /// These filenames, should they exist after extracting an archive, should be deleted. + static const Set _denylistedBasenames = {'entitlements.txt', 'without_entitlements.txt'}; + void _removeDenylistedFiles(Directory directory) { + for (final FileSystemEntity entity in directory.listSync(recursive: true)) { + if (entity is! File) { + continue; + } + if (_denylistedBasenames.contains(entity.basename)) { + entity.deleteSync(); + } + } + } + + /// Download a zip archive from the given [url] and unzip it to [location]. + Future downloadZipArchive( + String message, + Uri url, + Directory location, + ) { + return _downloadArchive( + message, + url, + location, + _operatingSystemUtils.unzip, + ); + } + + /// Download a gzipped tarball from the given [url] and unpack it to [location]. + Future downloadZippedTarball(String message, Uri url, Directory location) { + return _downloadArchive( + message, + url, + location, + _operatingSystemUtils.unpack, + ); + } + + /// Download an archive from the given [url] and unzip it to [location]. + Future _downloadArchive( + String message, + Uri url, + Directory location, + void Function(File, Directory) extractor, + ) async { + final String downloadPath = flattenNameSubdirs(url, _fileSystem); + final File tempFile = _createDownloadFile(downloadPath); + Status status; + int retries = _kRetryCount; + + while (retries > 0) { + status = _logger.startProgress( + message, + ); + try { + _ensureExists(tempFile.parent); + if (tempFile.existsSync()) { + tempFile.deleteSync(); + } + await _download(url, tempFile, status); + + if (!tempFile.existsSync()) { + throw Exception('Did not find downloaded file ${tempFile.path}'); + } + } on Exception catch (err) { + _logger.printTrace(err.toString()); + retries -= 1; + if (retries == 0) { + throwToolExit( + 'Failed to download $url. Ensure you have network connectivity and then try again.\n$err', + ); + } + continue; + } on ArgumentError catch (error) { + final String? overrideUrl = _platform.environment[kFlutterStorageBaseUrl]; + if (overrideUrl != null && url.toString().contains(overrideUrl)) { + _logger.printError(error.toString()); + throwToolExit( + 'The value of $kFlutterStorageBaseUrl ($overrideUrl) could not be ' + 'parsed as a valid url. Please see https://flutter.dev/community/china ' + 'for an example of how to use it.\n' + 'Full URL: $url', + exitCode: kNetworkProblemExitCode, + ); + } + // This error should not be hit if there was not a storage URL override, allow the + // tool to crash. + rethrow; + } finally { + status.stop(); + } + /// Unzipping multiple file into a directory will not remove old files + /// from previous versions that are not present in the new bundle. + final Directory destination = location.childDirectory( + tempFile.fileSystem.path.basenameWithoutExtension(tempFile.path) + ); + try { + ErrorHandlingFileSystem.deleteIfExists( + destination, + recursive: true, + ); + } on FileSystemException catch (error) { + // Error that indicates another program has this file open and that it + // cannot be deleted. For the cache, this is either the analyzer reading + // the sky_engine package or a running flutter_tester device. + const int kSharingViolation = 32; + if (_platform.isWindows && error.osError?.errorCode == kSharingViolation) { + throwToolExit( + 'Failed to delete ${destination.path} because the local file/directory is in use ' + 'by another process. Try closing any running IDEs or editors and trying ' + 'again' + ); + } + } + _ensureExists(location); + + try { + extractor(tempFile, location); + } on Exception catch (err) { + retries -= 1; + if (retries == 0) { + throwToolExit( + 'Flutter could not download and/or extract $url. Ensure you have ' + 'network connectivity and all of the required dependencies listed at ' + 'flutter.dev/setup.\nThe original exception was: $err.' + ); + } + _deleteIgnoringErrors(tempFile); + continue; + } + _removeDenylistedFiles(location); + return; + } + } + + /// Download bytes from [url], throwing non-200 responses as an exception. + /// + /// Validates that the md5 of the content bytes matches the provided + /// `x-goog-hash` header, if present. This header should contain an md5 hash + /// if the download source is Google cloud storage. + /// + /// See also: + /// * https://cloud.google.com/storage/docs/xml-api/reference-headers#xgooghash + Future _download(Uri url, File file, Status status) async { + final bool isAllowedUrl = _allowedBaseUrls.any((String baseUrl) => url.toString().startsWith(baseUrl)); + + // In tests make this a hard failure. + assert( + isAllowedUrl, + 'URL not allowed: $url\n' + 'Allowed URLs must be based on one of: ${_allowedBaseUrls.join(', ')}', + ); + + // In production, issue a warning but allow the download to proceed. + if (!isAllowedUrl) { + status.pause(); + _logger.printWarning( + 'Downloading an artifact that may not be reachable in some environments (e.g. firewalled environments): $url\n' + 'This should not have happened. This is likely a Flutter SDK bug. Please file an issue at https://github.com/flutter/flutter/issues/new?template=1_activation.yml' + ); + status.resume(); + } + + final HttpClientRequest request = await _httpClient.getUrl(url); + final HttpClientResponse response = await request.close(); + if (response.statusCode != HttpStatus.ok) { + throw Exception(response.statusCode); + } + + final String? md5Hash = _expectedMd5(response.headers); + ByteConversionSink? inputSink; + late StreamController digests; + if (md5Hash != null) { + _logger.printTrace('Content $url md5 hash: $md5Hash'); + digests = StreamController(); + inputSink = md5.startChunkedConversion(digests); + } + final RandomAccessFile randomAccessFile = file.openSync(mode: FileMode.writeOnly); + await response.forEach((List chunk) { + inputSink?.add(chunk); + randomAccessFile.writeFromSync(chunk); + }); + randomAccessFile.closeSync(); + if (inputSink != null) { + inputSink.close(); + final Digest digest = await digests.stream.last; + final String rawDigest = base64.encode(digest.bytes); + if (rawDigest != md5Hash) { + throw Exception( + 'Expected $url to have md5 checksum $md5Hash, but was $rawDigest. This ' + 'may indicate a problem with your connection to the Flutter backend servers. ' + 'Please re-try the download after confirming that your network connection is ' + 'stable.' + ); + } + } + } + + String? _expectedMd5(HttpHeaders httpHeaders) { + final List? values = httpHeaders['x-goog-hash']; + if (values == null) { + return null; + } + String? rawMd5Hash; + for (final String value in values) { + if (value.startsWith('md5=')) { + rawMd5Hash = value; + break; + } + } + if (rawMd5Hash == null) { + return null; + } + final List segments = rawMd5Hash.split('md5='); + if (segments.length < 2) { + return null; + } + final String md5Hash = segments[1]; + if (md5Hash.isEmpty) { + return null; + } + return md5Hash; + } + + /// Create a temporary file and invoke [onTemporaryFile] with the file as + /// argument, then add the temporary file to the [downloadedFiles]. + File _createDownloadFile(String name) { + final File tempFile = _fileSystem.file(_fileSystem.path.join(_tempStorage.path, name)); + downloadedFiles.add(tempFile); + return tempFile; + } + + /// Create the given [directory] and parents, as necessary. + void _ensureExists(Directory directory) { + if (!directory.existsSync()) { + directory.createSync(recursive: true); + } + } + + /// Clear any zip/gzip files downloaded. + void removeDownloadedFiles() { + for (final File file in downloadedFiles) { + if (!file.existsSync()) { + continue; + } + try { + file.deleteSync(); + } on FileSystemException catch (e) { + _logger.printWarning('Failed to delete "${file.path}". Please delete manually. $e'); + continue; + } + for (Directory directory = file.parent; directory.absolute.path != _tempStorage.absolute.path; directory = directory.parent) { + // Handle race condition when the directory is deleted before this step + if (!directory.existsSync()) { + break; + } + if (directory.listSync().isNotEmpty) { + break; + } + _deleteIgnoringErrors(directory); + } + } + } + + static void _deleteIgnoringErrors(FileSystemEntity entity) { + if (!entity.existsSync()) { + return; + } + try { + entity.deleteSync(); + } on FileSystemException { + // Ignore errors. + } + } +} + +@visibleForTesting +String flattenNameSubdirs(Uri url, FileSystem fileSystem) { + final List pieces = [url.host, ...url.pathSegments]; + final Iterable convertedPieces = pieces.map(_flattenNameNoSubdirs); + return fileSystem.path.joinAll(convertedPieces); +} + +/// Given a name containing slashes, colons, and backslashes, expand it into +/// something that doesn't. +String _flattenNameNoSubdirs(String fileName) { + final List replacedCodeUnits = [ + for (final int codeUnit in fileName.codeUnits) + ..._flattenNameSubstitutions[codeUnit] ?? [codeUnit], + ]; + return String.fromCharCodes(replacedCodeUnits); +} + +// Many characters are problematic in filenames, especially on Windows. +final Map> _flattenNameSubstitutions = >{ + r'@'.codeUnitAt(0): '@@'.codeUnits, + r'/'.codeUnitAt(0): '@s@'.codeUnits, + r'\'.codeUnitAt(0): '@bs@'.codeUnits, + r':'.codeUnitAt(0): '@c@'.codeUnits, + r'%'.codeUnitAt(0): '@per@'.codeUnits, + r'*'.codeUnitAt(0): '@ast@'.codeUnits, + r'<'.codeUnitAt(0): '@lt@'.codeUnits, + r'>'.codeUnitAt(0): '@gt@'.codeUnits, + r'"'.codeUnitAt(0): '@q@'.codeUnits, + r'|'.codeUnitAt(0): '@pip@'.codeUnits, + r'?'.codeUnitAt(0): '@ques@'.codeUnits, +}; diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/cmake.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/cmake.dart new file mode 100644 index 0000000000000000000000000000000000000000..2ac7d88e31bfd67d646a07cd5ac684dca2617781 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/cmake.dart @@ -0,0 +1,125 @@ +// 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:pub_semver/pub_semver.dart'; + +import 'base/logger.dart'; +import 'build_info.dart'; +import 'cmake_project.dart'; + +/// Extracts the `BINARY_NAME` from a project's CMake file. +/// +/// Returns `null` if it cannot be found. +String? getCmakeExecutableName(CmakeBasedProject project) { + if (!project.cmakeFile.existsSync()) { + return null; + } + final RegExp nameSetPattern = RegExp(r'^\s*set\(BINARY_NAME\s*"(.*)"\s*\)\s*$'); + for (final String line in project.cmakeFile.readAsLinesSync()) { + final RegExpMatch? match = nameSetPattern.firstMatch(line); + if (match != null) { + return match.group(1); + } + } + return null; +} + +String _escapeBackslashes(String s) { + return s.replaceAll(r'\', r'\\'); +} + +String _determineVersionString(CmakeBasedProject project, BuildInfo buildInfo) { + // Prefer the build arguments for version information. + final String buildName = buildInfo.buildName ?? project.parent.manifest.buildName ?? '1.0.0'; + final String? buildNumber = buildInfo.buildName != null + ? buildInfo.buildNumber + : (buildInfo.buildNumber ?? project.parent.manifest.buildNumber); + + return buildNumber != null + ? '$buildName+$buildNumber' + : buildName; +} + +Version _determineVersion(CmakeBasedProject project, BuildInfo buildInfo, Logger logger) { + final String version = _determineVersionString(project, buildInfo); + try { + return Version.parse(version); + } on FormatException { + logger.printWarning('Warning: could not parse version $version, defaulting to 1.0.0.'); + + return Version(1, 0, 0); + } +} + +/// Attempts to map a Dart version's build identifier (the part after a +) into +/// a single integer. Returns null for complex build identifiers like `foo` or `1.2`. +int? _tryDetermineBuildVersion(Version version) { + if (version.build.isEmpty) { + return 0; + } + + if (version.build.length != 1) { + return null; + } + + final Object buildIdentifier = version.build.first; + return buildIdentifier is int ? buildIdentifier : null; +} + +/// Writes a generated CMake configuration file for [project], including +/// variables expected by the build template and an environment variable list +/// for calling back into Flutter. +void writeGeneratedCmakeConfig( + String flutterRoot, + CmakeBasedProject project, + BuildInfo buildInfo, + Map environment, + Logger logger, +) { + // Only a limited set of variables are needed by the CMake files themselves, + // the rest are put into a list to pass to the re-entrant build step. + final String escapedFlutterRoot = _escapeBackslashes(flutterRoot); + final String escapedProjectDir = _escapeBackslashes(project.parent.directory.path); + + final Version version = _determineVersion(project, buildInfo, logger); + final int? buildVersion = _tryDetermineBuildVersion(version); + + // Since complex Dart build identifiers cannot be converted into integers, + // different Dart versions may be converted into the same Windows numeric version. + // Warn the user as some Windows installers, like MSI, don't update files if their versions are equal. + if (buildVersion == null && project is WindowsProject) { + final String buildIdentifier = version.build.join('.'); + logger.printWarning( + 'Warning: build identifier $buildIdentifier in version $version is not numeric ' + 'and cannot be converted into a Windows build version number. Defaulting to 0.\n' + 'This may cause issues with Windows installers.' + ); + } + + final StringBuffer buffer = StringBuffer(''' +# Generated code do not commit. +file(TO_CMAKE_PATH "$escapedFlutterRoot" FLUTTER_ROOT) +file(TO_CMAKE_PATH "$escapedProjectDir" PROJECT_DIR) + +set(FLUTTER_VERSION "$version" PARENT_SCOPE) +set(FLUTTER_VERSION_MAJOR ${version.major} PARENT_SCOPE) +set(FLUTTER_VERSION_MINOR ${version.minor} PARENT_SCOPE) +set(FLUTTER_VERSION_PATCH ${version.patch} PARENT_SCOPE) +set(FLUTTER_VERSION_BUILD ${buildVersion ?? 0} PARENT_SCOPE) + +# Environment variables to pass to tool_backend.sh +list(APPEND FLUTTER_TOOL_ENVIRONMENT + "FLUTTER_ROOT=$escapedFlutterRoot" + "PROJECT_DIR=$escapedProjectDir" +'''); + environment.forEach((String key, String value) { + final String configValue = _escapeBackslashes(value); + buffer.writeln(' "$key=$configValue"'); + }); + buffer.writeln(')'); + + project.generatedCmakeConfigFile + ..createSync(recursive: true) + ..writeAsStringSync(buffer.toString()); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/cmake_project.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/cmake_project.dart new file mode 100644 index 0000000000000000000000000000000000000000..7c8a594918f902c551e16b8a69ed3c01bf5664ba --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/cmake_project.dart @@ -0,0 +1,144 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'base/file_system.dart'; +import 'base/utils.dart'; +import 'platform_plugins.dart'; +import 'project.dart'; + +/// Represents a CMake-based sub-project. +/// +/// This defines interfaces common to Windows and Linux projects. +abstract class CmakeBasedProject { + /// The parent of this project. + FlutterProject get parent; + + /// Whether the subproject (either Windows or Linux) exists in the Flutter project. + bool existsSync(); + + /// The native project CMake specification. + File get cmakeFile; + + /// Contains definitions for the Flutter library and the tool. + File get managedCmakeFile; + + /// Contains definitions for FLUTTER_ROOT, LOCAL_ENGINE, and more flags for + /// the build. + File get generatedCmakeConfigFile; + + /// Included CMake with rules and variables for plugin builds. + File get generatedPluginCmakeFile; + + /// The directory to write plugin symlinks. + Directory get pluginSymlinkDirectory; +} + +/// The Windows sub project. +class WindowsProject extends FlutterProjectPlatform implements CmakeBasedProject { + WindowsProject.fromFlutter(this.parent); + + @override + final FlutterProject parent; + + @override + String get pluginConfigKey => WindowsPlugin.kConfigKey; + + String get _childDirectory => 'windows'; + + @override + bool existsSync() => _editableDirectory.existsSync() && cmakeFile.existsSync(); + + @override + File get cmakeFile => _editableDirectory.childFile('CMakeLists.txt'); + + @override + File get managedCmakeFile => managedDirectory.childFile('CMakeLists.txt'); + + @override + File get generatedCmakeConfigFile => ephemeralDirectory.childFile('generated_config.cmake'); + + @override + File get generatedPluginCmakeFile => managedDirectory.childFile('generated_plugins.cmake'); + + /// The native entrypoint's CMake specification. + File get runnerCmakeFile => runnerDirectory.childFile('CMakeLists.txt'); + + /// The native entrypoint's file that adds Flutter to the window. + File get runnerFlutterWindowFile => runnerDirectory.childFile('flutter_window.cpp'); + + /// The native entrypoint's resource file. Used to configure things + /// like the application icon, name, and version. + File get runnerResourceFile => runnerDirectory.childFile('Runner.rc'); + + @override + Directory get pluginSymlinkDirectory => ephemeralDirectory.childDirectory('.plugin_symlinks'); + + Directory get _editableDirectory => parent.directory.childDirectory(_childDirectory); + + /// The directory in the project that is managed by Flutter. As much as + /// possible, files that are edited by Flutter tooling after initial project + /// creation should live here. + Directory get managedDirectory => _editableDirectory.childDirectory('flutter'); + + /// The subdirectory of [managedDirectory] that contains files that are + /// generated on the fly. All generated files that are not intended to be + /// checked in should live here. + Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral'); + + /// The directory in the project that is owned by the app. As much as + /// possible, Flutter tooling should not edit files in this directory after + /// initial project creation. + Directory get runnerDirectory => _editableDirectory.childDirectory('runner'); + + Future ensureReadyForPlatformSpecificTooling() async {} +} + +/// The Linux sub project. +class LinuxProject extends FlutterProjectPlatform implements CmakeBasedProject { + LinuxProject.fromFlutter(this.parent); + + @override + final FlutterProject parent; + + @override + String get pluginConfigKey => LinuxPlugin.kConfigKey; + + static final RegExp _applicationIdPattern = RegExp(r'''^\s*set\s*\(\s*APPLICATION_ID\s*"(.*)"\s*\)\s*$'''); + + Directory get _editableDirectory => parent.directory.childDirectory('linux'); + + /// The directory in the project that is managed by Flutter. As much as + /// possible, files that are edited by Flutter tooling after initial project + /// creation should live here. + Directory get managedDirectory => _editableDirectory.childDirectory('flutter'); + + /// The subdirectory of [managedDirectory] that contains files that are + /// generated on the fly. All generated files that are not intended to be + /// checked in should live here. + Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral'); + + @override + bool existsSync() => _editableDirectory.existsSync(); + + @override + File get cmakeFile => _editableDirectory.childFile('CMakeLists.txt'); + + @override + File get managedCmakeFile => managedDirectory.childFile('CMakeLists.txt'); + + @override + File get generatedCmakeConfigFile => ephemeralDirectory.childFile('generated_config.cmake'); + + @override + File get generatedPluginCmakeFile => managedDirectory.childFile('generated_plugins.cmake'); + + @override + Directory get pluginSymlinkDirectory => ephemeralDirectory.childDirectory('.plugin_symlinks'); + + Future ensureReadyForPlatformSpecificTooling() async {} + + String? get applicationId { + return firstMatchInFile(cmakeFile, _applicationIdPattern)?.group(1); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/compile.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/compile.dart new file mode 100644 index 0000000000000000000000000000000000000000..15d209367f15688dcd3d5d29721626183a2f1501 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/compile.dart @@ -0,0 +1,1082 @@ +// 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:typed_data'; + +import 'package:meta/meta.dart'; +import 'package:package_config/package_config.dart'; +import 'package:process/process.dart'; +import 'package:usage/uuid/uuid.dart'; + +import 'artifacts.dart'; +import 'base/common.dart'; +import 'base/file_system.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'build_info.dart'; +import 'convert.dart'; + +/// Opt-in changes to the dart compilers. +const List kDartCompilerExperiments = [ +]; + +/// The target model describes the set of core libraries that are available within +/// the SDK. +class TargetModel { + /// Parse a [TargetModel] from a raw string. + /// + /// Throws an exception if passed a value other than 'flutter', + /// 'flutter_runner', 'vm', or 'dartdevc'. + factory TargetModel(String rawValue) { + switch (rawValue) { + case 'flutter': + return flutter; + case 'flutter_runner': + return flutterRunner; + case 'vm': + return vm; + case 'dartdevc': + return dartdevc; + } + throw Exception('Unexpected target model $rawValue'); + } + + const TargetModel._(this._value); + + /// The Flutter patched Dart SDK. + static const TargetModel flutter = TargetModel._('flutter'); + + /// The Fuchsia patched SDK. + static const TargetModel flutterRunner = TargetModel._('flutter_runner'); + + /// The Dart VM. + static const TargetModel vm = TargetModel._('vm'); + + /// The development compiler for JavaScript. + static const TargetModel dartdevc = TargetModel._('dartdevc'); + + final String _value; + + @override + String toString() => _value; +} + +class CompilerOutput { + const CompilerOutput(this.outputFilename, this.errorCount, this.sources, {this.expressionData}); + + final String outputFilename; + final int errorCount; + final List sources; + + /// This field is only non-null for expression compilation requests. + final Uint8List? expressionData; +} + +enum StdoutState { CollectDiagnostic, CollectDependencies } + +/// Handles stdin/stdout communication with the frontend server. +class StdoutHandler { + StdoutHandler({ + required Logger logger, + required FileSystem fileSystem, + }) : _logger = logger, + _fileSystem = fileSystem { + reset(); + } + + final Logger _logger; + final FileSystem _fileSystem; + + String? boundaryKey; + StdoutState state = StdoutState.CollectDiagnostic; + Completer? compilerOutput; + final List sources = []; + + bool _suppressCompilerMessages = false; + bool _expectSources = true; + bool _readFile = false; + + void handler(String message) { + const String kResultPrefix = 'result '; + if (boundaryKey == null && message.startsWith(kResultPrefix)) { + boundaryKey = message.substring(kResultPrefix.length); + return; + } + final String? messageBoundaryKey = boundaryKey; + if (messageBoundaryKey != null && message.startsWith(messageBoundaryKey)) { + if (_expectSources) { + if (state == StdoutState.CollectDiagnostic) { + state = StdoutState.CollectDependencies; + return; + } + } + if (message.length <= messageBoundaryKey.length) { + compilerOutput?.complete(); + return; + } + final int spaceDelimiter = message.lastIndexOf(' '); + final String fileName = message.substring(messageBoundaryKey.length + 1, spaceDelimiter); + final int errorCount = int.parse(message.substring(spaceDelimiter + 1).trim()); + Uint8List? expressionData; + if (_readFile) { + expressionData = _fileSystem.file(fileName).readAsBytesSync(); + } + final CompilerOutput output = CompilerOutput( + fileName, + errorCount, + sources, + expressionData: expressionData, + ); + compilerOutput?.complete(output); + return; + } + if (state == StdoutState.CollectDiagnostic) { + if (!_suppressCompilerMessages) { + _logger.printError(message); + } else { + _logger.printTrace(message); + } + } else { + assert(state == StdoutState.CollectDependencies); + switch (message[0]) { + case '+': + sources.add(Uri.parse(message.substring(1))); + case '-': + sources.remove(Uri.parse(message.substring(1))); + default: + _logger.printTrace('Unexpected prefix for $message uri - ignoring'); + } + } + } + + // This is needed to get ready to process next compilation result output, + // with its own boundary key and new completer. + void reset({ bool suppressCompilerMessages = false, bool expectSources = true, bool readFile = false }) { + boundaryKey = null; + compilerOutput = Completer(); + _suppressCompilerMessages = suppressCompilerMessages; + _expectSources = expectSources; + _readFile = readFile; + state = StdoutState.CollectDiagnostic; + } +} + +/// List the preconfigured build options for a given build mode. +List buildModeOptions(BuildMode mode, List dartDefines) => + switch (mode) { + BuildMode.debug => [ + // These checks allow the CLI to override the value of this define for unit + // testing the framework. + if (!dartDefines.any((String define) => define.startsWith('dart.vm.profile'))) + '-Ddart.vm.profile=false', + if (!dartDefines.any((String define) => define.startsWith('dart.vm.product'))) + '-Ddart.vm.product=false', + '--enable-asserts', + ], + BuildMode.profile => [ + // These checks allow the CLI to override the value of this define for + // benchmarks with most timeline traces disabled. + if (!dartDefines.any((String define) => define.startsWith('dart.vm.profile'))) + '-Ddart.vm.profile=true', + if (!dartDefines.any((String define) => define.startsWith('dart.vm.product'))) + '-Ddart.vm.product=false', + ...kDartCompilerExperiments, + ], + BuildMode.release => [ + '-Ddart.vm.profile=false', + '-Ddart.vm.product=true', + ...kDartCompilerExperiments, + ], + _ => throw Exception('Unknown BuildMode: $mode') + }; + +/// A compiler interface for producing single (non-incremental) kernel files. +class KernelCompiler { + KernelCompiler({ + required FileSystem fileSystem, + required Logger logger, + required ProcessManager processManager, + required Artifacts artifacts, + required List fileSystemRoots, + String? fileSystemScheme, + @visibleForTesting StdoutHandler? stdoutHandler, + }) : _logger = logger, + _fileSystem = fileSystem, + _artifacts = artifacts, + _processManager = processManager, + _fileSystemScheme = fileSystemScheme, + _fileSystemRoots = fileSystemRoots, + _stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem); + + final FileSystem _fileSystem; + final Artifacts _artifacts; + final ProcessManager _processManager; + final Logger _logger; + final String? _fileSystemScheme; + final List _fileSystemRoots; + final StdoutHandler _stdoutHandler; + + Future compile({ + required String sdkRoot, + String? mainPath, + String? outputFilePath, + String? depFilePath, + TargetModel targetModel = TargetModel.flutter, + bool linkPlatformKernelIn = false, + bool aot = false, + String? frontendServerStarterPath, + List? extraFrontEndOptions, + List? fileSystemRoots, + String? fileSystemScheme, + String? initializeFromDill, + String? platformDill, + Directory? buildDir, + String? targetOS, + bool checkDartPluginRegistry = false, + required String? packagesPath, + required BuildMode buildMode, + required bool trackWidgetCreation, + required List dartDefines, + required PackageConfig packageConfig, + String? nativeAssets, + }) async { + final TargetPlatform? platform = targetModel == TargetModel.dartdevc ? TargetPlatform.web_javascript : null; + // This is a URI, not a file path, so the forward slash is correct even on Windows. + if (!sdkRoot.endsWith('/')) { + sdkRoot = '$sdkRoot/'; + } + String? mainUri; + 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); + } + + // Check if there's a Dart plugin registrant. + // This is contained in the file `dart_plugin_registrant.dart` under `.dart_tools/flutter_build/`. + final File? dartPluginRegistrant = checkDartPluginRegistry + ? buildDir?.parent.childFile('dart_plugin_registrant.dart') + : null; + + String? dartPluginRegistrantUri; + if (dartPluginRegistrant != null && dartPluginRegistrant.existsSync()) { + final Uri dartPluginRegistrantFileUri = dartPluginRegistrant.uri; + dartPluginRegistrantUri = packageConfig.toPackageUri(dartPluginRegistrantFileUri)?.toString() ?? + toMultiRootPath(dartPluginRegistrantFileUri, _fileSystemScheme, _fileSystemRoots, _fileSystem.path.separator == r'\'); + } + + final List commandToStartFrontendServer; + if (frontendServerStarterPath != null && frontendServerStarterPath.isNotEmpty) { + final String engineDartPath = _artifacts.getArtifactPath(Artifact.engineDartBinary, platform: platform); + if (!_processManager.canRun(engineDartPath)) { + throwToolExit('Unable to find Dart binary at $engineDartPath'); + } + commandToStartFrontendServer = [ + engineDartPath, + '--disable-dart-dev', + frontendServerStarterPath, + ]; + } else { + final String engineDartAotRuntimePath = _artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: platform); + if (!_processManager.canRun(engineDartAotRuntimePath)) { + throwToolExit('Unable to find dartaotruntime binary at $engineDartAotRuntimePath'); + } + commandToStartFrontendServer = [ + engineDartAotRuntimePath, + '--disable-dart-dev', + _artifacts.getArtifactPath( + Artifact.frontendServerSnapshotForEngineDartSdk, + platform: platform, + ), + ]; + } + + final List command = commandToStartFrontendServer + [ + '--sdk-root', + sdkRoot, + '--target=$targetModel', + '--no-print-incremental-dependencies', + for (final Object dartDefine in dartDefines) + '-D$dartDefine', + ...buildModeOptions(buildMode, dartDefines), + if (trackWidgetCreation) '--track-widget-creation', + if (!linkPlatformKernelIn) '--no-link-platform', + if (aot) ...[ + '--aot', + '--tfa', + // The --target-os flag only makes sense for whole program compilation. + if (targetOS != null) ...[ + '--target-os', + targetOS, + ], + ], + if (packagesPath != null) ...[ + '--packages', + packagesPath, + ], + if (outputFilePath != null) ...[ + '--output-dill', + outputFilePath, + ], + if (depFilePath != null && (fileSystemRoots == null || fileSystemRoots.isEmpty)) ...[ + '--depfile', + depFilePath, + ], + if (fileSystemRoots != null) + for (final String root in fileSystemRoots) ...[ + '--filesystem-root', + root, + ], + if (fileSystemScheme != null) ...[ + '--filesystem-scheme', + fileSystemScheme, + ], + if (initializeFromDill != null) ...[ + '--incremental', + '--initialize-from-dill', + initializeFromDill, + ], + if (platformDill != null) ...[ + '--platform', + platformDill, + ], + if (dartPluginRegistrantUri != null) ...[ + '--source', + dartPluginRegistrantUri, + '--source', + 'package:flutter/src/dart_plugin_registrant.dart', + '-Dflutter.dart_plugin_registrant=$dartPluginRegistrantUri', + ], + if (nativeAssets != null) ...[ + '--native-assets', + nativeAssets, + ], + // See: https://github.com/flutter/flutter/issues/103994 + '--verbosity=error', + ...?extraFrontEndOptions, + mainUri, + ]; + + _logger.printTrace(command.join(' ')); + final Process server = await _processManager.start(command); + + server.stderr + .transform(utf8.decoder) + .listen(_logger.printError); + server.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(_stdoutHandler.handler); + final int exitCode = await server.exitCode; + if (exitCode == 0) { + return _stdoutHandler.compilerOutput?.future; + } + return null; + } +} + +/// Class that allows to serialize compilation requests to the compiler. +abstract class _CompilationRequest { + _CompilationRequest(this.completer); + + Completer completer; + + Future _run(DefaultResidentCompiler compiler); + + Future run(DefaultResidentCompiler compiler) async { + completer.complete(await _run(compiler)); + } +} + +class _RecompileRequest extends _CompilationRequest { + _RecompileRequest( + super.completer, + this.mainUri, + this.invalidatedFiles, + this.outputPath, + this.packageConfig, + this.suppressErrors, { + this.additionalSourceUri, + this.nativeAssetsYamlUri, + }); + + Uri mainUri; + List? invalidatedFiles; + String outputPath; + PackageConfig packageConfig; + bool suppressErrors; + final Uri? additionalSourceUri; + final Uri? nativeAssetsYamlUri; + + @override + Future _run(DefaultResidentCompiler compiler) async => + compiler._recompile(this); +} + +class _CompileExpressionRequest extends _CompilationRequest { + _CompileExpressionRequest( + super.completer, + this.expression, + this.definitions, + this.definitionTypes, + this.typeDefinitions, + this.typeBounds, + this.typeDefaults, + this.libraryUri, + this.klass, + this.method, + this.isStatic, + ); + + String expression; + List? definitions; + List? definitionTypes; + List? typeDefinitions; + List? typeBounds; + List? typeDefaults; + String? libraryUri; + String? klass; + String? method; + bool isStatic; + + @override + Future _run(DefaultResidentCompiler compiler) async => + compiler._compileExpression(this); +} + +class _CompileExpressionToJsRequest extends _CompilationRequest { + _CompileExpressionToJsRequest( + super.completer, + this.libraryUri, + this.line, + this.column, + this.jsModules, + this.jsFrameValues, + this.moduleName, + this.expression, + ); + + final String? libraryUri; + final int line; + final int column; + final Map? jsModules; + final Map? jsFrameValues; + final String? moduleName; + final String? expression; + + @override + Future _run(DefaultResidentCompiler compiler) async => + compiler._compileExpressionToJs(this); +} + +class _RejectRequest extends _CompilationRequest { + _RejectRequest(super.completer); + + @override + Future _run(DefaultResidentCompiler compiler) async => + compiler._reject(); +} + +/// Wrapper around incremental frontend server compiler, that communicates with +/// server via stdin/stdout. +/// +/// The wrapper is intended to stay resident in memory as user changes, reloads, +/// restarts the Flutter app. +abstract class ResidentCompiler { + factory ResidentCompiler(String sdkRoot, { + required BuildMode buildMode, + required Logger logger, + required ProcessManager processManager, + required Artifacts artifacts, + required Platform platform, + required FileSystem fileSystem, + bool testCompilation, + bool trackWidgetCreation, + String packagesPath, + List fileSystemRoots, + String? fileSystemScheme, + String initializeFromDill, + bool assumeInitializeFromDillUpToDate, + TargetModel targetModel, + bool unsafePackageSerialization, + String? frontendServerStarterPath, + List extraFrontEndOptions, + String platformDill, + List? dartDefines, + String librariesSpec, + }) = DefaultResidentCompiler; + + // TODO(zanderso): find a better way to configure additional file system + // roots from the runner. + // See: https://github.com/flutter/flutter/issues/50494 + void addFileSystemRoot(String root); + + /// If invoked for the first time, it compiles Dart script identified by + /// [mainPath], [invalidatedFiles] list is ignored. + /// On successive runs [invalidatedFiles] indicates which files need to be + /// recompiled. If [mainPath] is [null], previously used [mainPath] entry + /// point that is used for recompilation. + /// Binary file name is returned if compilation was successful, otherwise + /// null is returned. + /// + /// If [checkDartPluginRegistry] is true, it is the caller's responsibility + /// to ensure that the generated registrant file has been updated such that + /// it is wrapping [mainUri]. + Future recompile( + Uri mainUri, + List? invalidatedFiles, { + required String outputPath, + required PackageConfig packageConfig, + required FileSystem fs, + String? projectRootPath, + bool suppressErrors = false, + bool checkDartPluginRegistry = false, + File? dartPluginRegistrant, + Uri? nativeAssetsYaml, + }); + + Future compileExpression( + String expression, + List? definitions, + List? definitionTypes, + List? typeDefinitions, + List? typeBounds, + List? typeDefaults, + String? libraryUri, + String? klass, + String? method, + bool isStatic, + ); + + /// Compiles [expression] in [libraryUri] at [line]:[column] to JavaScript + /// in [moduleName]. + /// + /// Values listed in [jsFrameValues] are substituted for their names in the + /// [expression]. + /// + /// Ensures that all [jsModules] are loaded and accessible inside the + /// expression. + /// + /// Example values of parameters: + /// [moduleName] is of the form '/packages/hello_world_main.dart' + /// [jsFrameValues] is a map from js variable name to its primitive value + /// or another variable name, for example + /// { 'x': '1', 'y': 'y', 'o': 'null' } + /// [jsModules] is a map from variable name to the module name, where + /// variable name is the name originally used in JavaScript to contain the + /// module object, for example: + /// { 'dart':'dart_sdk', 'main': '/packages/hello_world_main.dart' } + /// Returns a [CompilerOutput] including the name of the file containing the + /// compilation result and a number of errors. + Future compileExpressionToJs( + String libraryUri, + int line, + int column, + Map jsModules, + Map jsFrameValues, + String moduleName, + String expression, + ); + + /// Should be invoked when results of compilation are accepted by the client. + /// + /// Either [accept] or [reject] should be called after every [recompile] call. + void accept(); + + /// Should be invoked when results of compilation are rejected by the client. + /// + /// Either [accept] or [reject] should be called after every [recompile] call. + Future reject(); + + /// Should be invoked when frontend server compiler should forget what was + /// accepted previously so that next call to [recompile] produces complete + /// kernel file. + void reset(); + + Future shutdown(); +} + +@visibleForTesting +class DefaultResidentCompiler implements ResidentCompiler { + DefaultResidentCompiler( + String sdkRoot, { + required this.buildMode, + required Logger logger, + required ProcessManager processManager, + required this.artifacts, + required Platform platform, + required FileSystem fileSystem, + this.testCompilation = false, + this.trackWidgetCreation = true, + this.packagesPath, + List fileSystemRoots = const [], + this.fileSystemScheme, + this.initializeFromDill, + this.assumeInitializeFromDillUpToDate = false, + this.targetModel = TargetModel.flutter, + this.unsafePackageSerialization = false, + this.frontendServerStarterPath, + this.extraFrontEndOptions, + this.platformDill, + List? dartDefines, + this.librariesSpec, + @visibleForTesting StdoutHandler? stdoutHandler, + }) : _logger = logger, + _processManager = processManager, + _stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem), + _platform = platform, + dartDefines = dartDefines ?? const [], + // This is a URI, not a file path, so the forward slash is correct even on Windows. + sdkRoot = sdkRoot.endsWith('/') ? sdkRoot : '$sdkRoot/', + // Make a copy, we might need to modify it later. + fileSystemRoots = List.from(fileSystemRoots); + + final Logger _logger; + final ProcessManager _processManager; + final Artifacts artifacts; + final Platform _platform; + + final bool testCompilation; + final BuildMode buildMode; + final bool trackWidgetCreation; + final String? packagesPath; + final TargetModel targetModel; + final List fileSystemRoots; + final String? fileSystemScheme; + final String? initializeFromDill; + final bool assumeInitializeFromDillUpToDate; + final bool unsafePackageSerialization; + final String? frontendServerStarterPath; + final List? extraFrontEndOptions; + final List dartDefines; + final String? librariesSpec; + + @override + void addFileSystemRoot(String root) { + fileSystemRoots.add(root); + } + + /// The path to the root of the Dart SDK used to compile. + /// + /// This is used to resolve the [platformDill]. + final String sdkRoot; + + /// The path to the platform dill file. + /// + /// This does not need to be provided for the normal Flutter workflow. + final String? platformDill; + + Process? _server; + final StdoutHandler _stdoutHandler; + bool _compileRequestNeedsConfirmation = false; + + final StreamController<_CompilationRequest> _controller = StreamController<_CompilationRequest>(); + + @override + Future recompile( + Uri mainUri, + List? invalidatedFiles, { + required String outputPath, + required PackageConfig packageConfig, + bool suppressErrors = false, + bool checkDartPluginRegistry = false, + File? dartPluginRegistrant, + String? projectRootPath, + FileSystem? fs, + Uri? nativeAssetsYaml, + }) async { + if (!_controller.hasListener) { + _controller.stream.listen(_handleCompilationRequest); + } + Uri? additionalSourceUri; + // `dart_plugin_registrant.dart` contains the Dart plugin registry. + if (checkDartPluginRegistry && dartPluginRegistrant != null && dartPluginRegistrant.existsSync()) { + additionalSourceUri = dartPluginRegistrant.uri; + } + final Completer completer = Completer(); + _controller.add(_RecompileRequest( + completer, + mainUri, + invalidatedFiles, + outputPath, + packageConfig, + suppressErrors, + additionalSourceUri: additionalSourceUri, + nativeAssetsYamlUri: nativeAssetsYaml, + )); + return completer.future; + } + + Future _recompile(_RecompileRequest request) async { + _stdoutHandler.reset(); + _compileRequestNeedsConfirmation = true; + _stdoutHandler._suppressCompilerMessages = request.suppressErrors; + + final String mainUri = request.packageConfig.toPackageUri(request.mainUri)?.toString() ?? + toMultiRootPath(request.mainUri, fileSystemScheme, fileSystemRoots, _platform.isWindows); + + String? additionalSourceUri; + if (request.additionalSourceUri != null) { + additionalSourceUri = request.packageConfig.toPackageUri(request.additionalSourceUri!)?.toString() ?? + toMultiRootPath(request.additionalSourceUri!, fileSystemScheme, fileSystemRoots, _platform.isWindows); + } + + final String? nativeAssets = request.nativeAssetsYamlUri?.toString(); + final Process? server = _server; + if (server == null) { + return _compile( + mainUri, + request.outputPath, + additionalSourceUri: additionalSourceUri, + nativeAssetsUri: nativeAssets, + ); + } + final String inputKey = Uuid().generateV4(); + + if (nativeAssets != null && nativeAssets.isNotEmpty) { + server.stdin.writeln('native-assets $nativeAssets'); + _logger.printTrace('<- native-assets $nativeAssets'); + } + server.stdin.writeln('recompile $mainUri $inputKey'); + _logger.printTrace('<- recompile $mainUri $inputKey'); + final List? invalidatedFiles = request.invalidatedFiles; + if (invalidatedFiles != null) { + for (final Uri fileUri in invalidatedFiles) { + String message; + if (fileUri.scheme == 'package') { + message = fileUri.toString(); + } else { + message = request.packageConfig.toPackageUri(fileUri)?.toString() ?? + toMultiRootPath(fileUri, fileSystemScheme, fileSystemRoots, _platform.isWindows); + } + server.stdin.writeln(message); + _logger.printTrace(message); + } + } + server.stdin.writeln(inputKey); + _logger.printTrace('<- $inputKey'); + + return _stdoutHandler.compilerOutput?.future; + } + + final List<_CompilationRequest> _compilationQueue = <_CompilationRequest>[]; + + Future _handleCompilationRequest(_CompilationRequest request) async { + final bool isEmpty = _compilationQueue.isEmpty; + _compilationQueue.add(request); + // Only trigger processing if queue was empty - i.e. no other requests + // are currently being processed. This effectively enforces "one + // compilation request at a time". + if (isEmpty) { + while (_compilationQueue.isNotEmpty) { + final _CompilationRequest request = _compilationQueue.first; + await request.run(this); + _compilationQueue.removeAt(0); + } + } + } + + Future _compile( + String scriptUri, + String? outputPath, { + String? additionalSourceUri, + String? nativeAssetsUri, + }) async { + final TargetPlatform? platform = (targetModel == TargetModel.dartdevc) ? TargetPlatform.web_javascript : null; + late final List commandToStartFrontendServer; + if (frontendServerStarterPath != null && frontendServerStarterPath!.isNotEmpty) { + commandToStartFrontendServer = [ + artifacts.getArtifactPath(Artifact.engineDartBinary, platform: platform), + '--disable-dart-dev', + frontendServerStarterPath!, + ]; + } else { + commandToStartFrontendServer = [ + artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: platform), + '--disable-dart-dev', + artifacts.getArtifactPath( + Artifact.frontendServerSnapshotForEngineDartSdk, + platform: platform, + ), + ]; + } + + final List command = commandToStartFrontendServer + [ + '--sdk-root', + sdkRoot, + '--incremental', + if (testCompilation) + '--no-print-incremental-dependencies', + '--target=$targetModel', + // TODO(annagrin): remove once this becomes the default behavior + // in the frontend_server. + // https://github.com/flutter/flutter/issues/59902 + '--experimental-emit-debug-metadata', + for (final Object dartDefine in dartDefines) + '-D$dartDefine', + if (outputPath != null) ...[ + '--output-dill', + outputPath, + ], + // If we have a platform dill, we don't need to pass the libraries spec, + // since the information is embedded in the .dill file. + if (librariesSpec != null && platformDill == null) ...[ + '--libraries-spec', + librariesSpec!, + ], + if (packagesPath != null) ...[ + '--packages', + packagesPath!, + ], + ...buildModeOptions(buildMode, dartDefines), + if (trackWidgetCreation) '--track-widget-creation', + for (final String root in fileSystemRoots) ...[ + '--filesystem-root', + root, + ], + if (fileSystemScheme != null) ...[ + '--filesystem-scheme', + fileSystemScheme!, + ], + if (initializeFromDill != null) ...[ + '--initialize-from-dill', + initializeFromDill!, + ], + if (assumeInitializeFromDillUpToDate) '--assume-initialize-from-dill-up-to-date', + if (additionalSourceUri != null) ...[ + '--source', + additionalSourceUri, + '--source', + 'package:flutter/src/dart_plugin_registrant.dart', + '-Dflutter.dart_plugin_registrant=$additionalSourceUri', + ], + if (nativeAssetsUri != null) ...[ + '--native-assets', + nativeAssetsUri, + ], + if (platformDill != null) ...[ + '--platform', + platformDill!, + ], + if (unsafePackageSerialization) '--unsafe-package-serialization', + // See: https://github.com/flutter/flutter/issues/103994 + '--verbosity=error', + ...?extraFrontEndOptions, + ]; + _logger.printTrace(command.join(' ')); + _server = await _processManager.start(command); + _server?.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen( + _stdoutHandler.handler, + onDone: () { + // when outputFilename future is not completed, but stdout is closed + // process has died unexpectedly. + if (_stdoutHandler.compilerOutput?.isCompleted == false) { + _stdoutHandler.compilerOutput?.complete(); + throwToolExit('the Dart compiler exited unexpectedly.'); + } + }); + + _server?.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(_logger.printError); + + unawaited(_server?.exitCode.then((int code) { + if (code != 0) { + throwToolExit('the Dart compiler exited unexpectedly.'); + } + })); + + if (nativeAssetsUri != null && nativeAssetsUri.isNotEmpty) { + _server?.stdin.writeln('native-assets $nativeAssetsUri'); + _logger.printTrace('<- native-assets $nativeAssetsUri'); + } + + _server?.stdin.writeln('compile $scriptUri'); + _logger.printTrace('<- compile $scriptUri'); + + return _stdoutHandler.compilerOutput?.future; + } + + @override + Future compileExpression( + String expression, + List? definitions, + List? definitionTypes, + List? typeDefinitions, + List? typeBounds, + List? typeDefaults, + String? libraryUri, + String? klass, + String? method, + bool isStatic, + ) async { + if (!_controller.hasListener) { + _controller.stream.listen(_handleCompilationRequest); + } + + final Completer completer = Completer(); + final _CompileExpressionRequest request = _CompileExpressionRequest( + completer, expression, definitions, definitionTypes, typeDefinitions, + typeBounds, typeDefaults, libraryUri, klass, method, isStatic); + _controller.add(request); + return completer.future; + } + + Future _compileExpression(_CompileExpressionRequest request) async { + _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false, readFile: true); + + // 'compile-expression' should be invoked after compiler has been started, + // program was compiled. + final Process? server = _server; + if (server == null) { + return null; + } + + final String inputKey = Uuid().generateV4(); + server.stdin + ..writeln('compile-expression $inputKey') + ..writeln(request.expression); + request.definitions?.forEach(server.stdin.writeln); + server.stdin.writeln(inputKey); + request.definitionTypes?.forEach(server.stdin.writeln); + server.stdin.writeln(inputKey); + request.typeDefinitions?.forEach(server.stdin.writeln); + server.stdin.writeln(inputKey); + request.typeBounds?.forEach(server.stdin.writeln); + server.stdin.writeln(inputKey); + request.typeDefaults?.forEach(server.stdin.writeln); + server.stdin + ..writeln(inputKey) + ..writeln(request.libraryUri ?? '') + ..writeln(request.klass ?? '') + ..writeln(request.method ?? '') + ..writeln(request.isStatic); + + return _stdoutHandler.compilerOutput?.future; + } + + @override + Future compileExpressionToJs( + String libraryUri, + int line, + int column, + Map jsModules, + Map jsFrameValues, + String moduleName, + String expression, + ) { + if (!_controller.hasListener) { + _controller.stream.listen(_handleCompilationRequest); + } + + final Completer completer = Completer(); + _controller.add( + _CompileExpressionToJsRequest( + completer, libraryUri, line, column, jsModules, jsFrameValues, moduleName, expression) + ); + return completer.future; + } + + Future _compileExpressionToJs(_CompileExpressionToJsRequest request) async { + _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false); + + // 'compile-expression-to-js' should be invoked after compiler has been started, + // program was compiled. + final Process? server = _server; + if (server == null) { + return null; + } + + final String inputKey = Uuid().generateV4(); + server.stdin + ..writeln('compile-expression-to-js $inputKey') + ..writeln(request.libraryUri ?? '') + ..writeln(request.line) + ..writeln(request.column); + request.jsModules?.forEach((String k, String v) { server.stdin.writeln('$k:$v'); }); + server.stdin.writeln(inputKey); + request.jsFrameValues?.forEach((String k, String v) { server.stdin.writeln('$k:$v'); }); + server.stdin + ..writeln(inputKey) + ..writeln(request.moduleName ?? '') + ..writeln(request.expression ?? ''); + + return _stdoutHandler.compilerOutput?.future; + } + + @override + void accept() { + if (_compileRequestNeedsConfirmation) { + _server?.stdin.writeln('accept'); + _logger.printTrace('<- accept'); + } + _compileRequestNeedsConfirmation = false; + } + + @override + Future reject() { + if (!_controller.hasListener) { + _controller.stream.listen(_handleCompilationRequest); + } + + final Completer completer = Completer(); + _controller.add(_RejectRequest(completer)); + return completer.future; + } + + Future _reject() async { + if (!_compileRequestNeedsConfirmation) { + return Future.value(); + } + _stdoutHandler.reset(expectSources: false); + _server?.stdin.writeln('reject'); + _logger.printTrace('<- reject'); + _compileRequestNeedsConfirmation = false; + return _stdoutHandler.compilerOutput?.future; + } + + @override + void reset() { + _server?.stdin.writeln('reset'); + _logger.printTrace('<- reset'); + } + + @override + Future shutdown() async { + // Server was never successfully created. + final Process? server = _server; + if (server == null) { + return 0; + } + _logger.printTrace('killing pid ${server.pid}'); + server.kill(); + return server.exitCode; + } +} + +/// Convert a file URI into a multi-root scheme URI if provided, otherwise +/// return unmodified. +@visibleForTesting +String toMultiRootPath(Uri fileUri, String? scheme, List fileSystemRoots, bool windows) { + if (scheme == null || fileSystemRoots.isEmpty || fileUri.scheme != 'file') { + return fileUri.toString(); + } + final String filePath = fileUri.toFilePath(windows: windows); + for (final String fileSystemRoot in fileSystemRoots) { + if (filePath.startsWith(fileSystemRoot)) { + return '$scheme://${filePath.substring(fileSystemRoot.length)}'; + } + } + return fileUri.toString(); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/context_runner.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/context_runner.dart new file mode 100644 index 0000000000000000000000000000000000000000..35ec96274109dfb30e44421f06fb3a7fe9c1be6c --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/context_runner.dart @@ -0,0 +1,400 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:process/process.dart'; +import 'package:unified_analytics/unified_analytics.dart'; + +import 'android/android_builder.dart'; +import 'android/android_sdk.dart'; +import 'android/android_studio.dart'; +import 'android/android_workflow.dart'; +import 'android/gradle.dart'; +import 'android/gradle_utils.dart'; +import 'android/java.dart'; +import 'application_package.dart'; +import 'artifacts.dart'; +import 'asset.dart'; +import 'base/config.dart'; +import 'base/context.dart'; +import 'base/error_handling_io.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/os.dart'; +import 'base/process.dart'; +import 'base/terminal.dart'; +import 'base/time.dart'; +import 'base/user_messages.dart'; +import 'build_system/build_system.dart'; +import 'cache.dart'; +import 'custom_devices/custom_devices_config.dart'; +import 'dart/pub.dart'; +import 'devfs.dart'; +import 'device.dart'; +import 'devtools_launcher.dart'; +import 'doctor.dart'; +import 'emulator.dart'; +import 'features.dart'; +import 'flutter_application_package.dart'; +import 'flutter_cache.dart'; +import 'flutter_device_manager.dart'; +import 'flutter_features.dart'; +import 'fuchsia/fuchsia_device.dart' show FuchsiaDeviceTools; +import 'fuchsia/fuchsia_sdk.dart' show FuchsiaArtifacts, FuchsiaSdk; +import 'fuchsia/fuchsia_workflow.dart' show FuchsiaWorkflow, fuchsiaWorkflow; +import 'globals.dart' as globals; +import 'ios/ios_workflow.dart'; +import 'ios/iproxy.dart'; +import 'ios/simulators.dart'; +import 'ios/xcodeproj.dart'; +import 'macos/cocoapods.dart'; +import 'macos/cocoapods_validator.dart'; +import 'macos/macos_workflow.dart'; +import 'macos/xcdevice.dart'; +import 'macos/xcode.dart'; +import 'mdns_discovery.dart'; +import 'persistent_tool_state.dart'; +import 'reporting/crash_reporting.dart'; +import 'reporting/first_run.dart'; +import 'reporting/reporting.dart'; +import 'reporting/unified_analytics.dart'; +import 'resident_runner.dart'; +import 'run_hot.dart'; +import 'runner/local_engine.dart'; +import 'version.dart'; +import 'web/workflow.dart'; +import 'windows/visual_studio.dart'; +import 'windows/visual_studio_validator.dart'; +import 'windows/windows_workflow.dart'; + +Future runInContext( + FutureOr Function() runner, { + Map? overrides, +}) async { + + // Wrap runner with any asynchronous initialization that should run with the + // overrides and callbacks. + late bool runningOnBot; + FutureOr runnerWrapper() async { + runningOnBot = await globals.isRunningOnBot; + return runner(); + } + + // TODO(ianh): We should split this into two, one for tests (which should be + // in test/), and one for production (which should be in executable.dart). + return context.run( + name: 'global fallbacks', + body: runnerWrapper, + overrides: overrides, + fallbacks: { + Analytics: () => getAnalytics( + runningOnBot: runningOnBot, + flutterVersion: globals.flutterVersion, + environment: globals.platform.environment, + clientIde: globals.platform.environment['FLUTTER_HOST'], + config: globals.config, + ), + AndroidBuilder: () => AndroidGradleBuilder( + java: globals.java, + logger: globals.logger, + processManager: globals.processManager, + fileSystem: globals.fs, + artifacts: globals.artifacts!, + usage: globals.flutterUsage, + analytics: globals.analytics, + gradleUtils: globals.gradleUtils!, + platform: globals.platform, + androidStudio: globals.androidStudio, + ), + AndroidLicenseValidator: () => AndroidLicenseValidator( + platform: globals.platform, + userMessages: globals.userMessages, + processManager: globals.processManager, + java: globals.java, + androidSdk: globals.androidSdk, + logger: globals.logger, + stdio: globals.stdio, + ), + AndroidSdk: AndroidSdk.locateAndroidSdk, + AndroidStudio: AndroidStudio.latestValid, + AndroidValidator: () => AndroidValidator( + java: globals.java, + androidSdk: globals.androidSdk, + logger: globals.logger, + platform: globals.platform, + userMessages: globals.userMessages, + ), + AndroidWorkflow: () => AndroidWorkflow( + androidSdk: globals.androidSdk, + featureFlags: featureFlags, + ), + ApplicationPackageFactory: () => FlutterApplicationPackageFactory( + userMessages: globals.userMessages, + processManager: globals.processManager, + logger: globals.logger, + fileSystem: globals.fs, + androidSdk: globals.androidSdk, + ), + Artifacts: () => CachedArtifacts( + fileSystem: globals.fs, + cache: globals.cache, + platform: globals.platform, + operatingSystemUtils: globals.os, + ), + AssetBundleFactory: () { + return AssetBundleFactory.defaultInstance( + logger: globals.logger, + fileSystem: globals.fs, + platform: globals.platform, + ); + }, + BuildSystem: () => FlutterBuildSystem( + fileSystem: globals.fs, + logger: globals.logger, + platform: globals.platform, + ), + Cache: () => FlutterCache( + fileSystem: globals.fs, + logger: globals.logger, + platform: globals.platform, + osUtils: globals.os, + projectFactory: globals.projectFactory, + ), + CocoaPods: () => CocoaPods( + fileSystem: globals.fs, + processManager: globals.processManager, + logger: globals.logger, + platform: globals.platform, + xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, + usage: globals.flutterUsage, + analytics: globals.analytics, + ), + CocoaPodsValidator: () => CocoaPodsValidator( + globals.cocoaPods!, + globals.userMessages, + ), + Config: () => Config( + Config.kFlutterSettings, + fileSystem: globals.fs, + logger: globals.logger, + platform: globals.platform, + ), + CustomDevicesConfig: () => CustomDevicesConfig( + fileSystem: globals.fs, + logger: globals.logger, + platform: globals.platform + ), + CrashReporter: () => CrashReporter( + fileSystem: globals.fs, + logger: globals.logger, + flutterProjectFactory: globals.projectFactory, + ), + DevFSConfig: () => DevFSConfig(), + DeviceManager: () => FlutterDeviceManager( + logger: globals.logger, + processManager: globals.processManager, + platform: globals.platform, + androidSdk: globals.androidSdk, + iosSimulatorUtils: globals.iosSimulatorUtils!, + featureFlags: featureFlags, + fileSystem: globals.fs, + iosWorkflow: globals.iosWorkflow!, + artifacts: globals.artifacts!, + flutterVersion: globals.flutterVersion, + androidWorkflow: androidWorkflow!, + fuchsiaWorkflow: fuchsiaWorkflow!, + xcDevice: globals.xcdevice!, + userMessages: globals.userMessages, + windowsWorkflow: windowsWorkflow!, + macOSWorkflow: MacOSWorkflow( + platform: globals.platform, + featureFlags: featureFlags, + ), + fuchsiaSdk: globals.fuchsiaSdk!, + operatingSystemUtils: globals.os, + customDevicesConfig: globals.customDevicesConfig, + ), + DevtoolsLauncher: () => DevtoolsServerLauncher( + processManager: globals.processManager, + dartExecutable: globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), + logger: globals.logger, + botDetector: globals.botDetector, + ), + Doctor: () => Doctor( + logger: globals.logger, + clock: globals.systemClock, + ), + DoctorValidatorsProvider: () => DoctorValidatorsProvider.defaultInstance, + EmulatorManager: () => EmulatorManager( + java: globals.java, + androidSdk: globals.androidSdk, + processManager: globals.processManager, + logger: globals.logger, + fileSystem: globals.fs, + androidWorkflow: androidWorkflow!, + ), + FeatureFlags: () => FlutterFeatureFlags( + flutterVersion: globals.flutterVersion, + config: globals.config, + platform: globals.platform, + ), + FlutterVersion: () => FlutterVersion( + fs: globals.fs, + flutterRoot: Cache.flutterRoot!, + ), + FuchsiaArtifacts: () => FuchsiaArtifacts.find(), + FuchsiaDeviceTools: () => FuchsiaDeviceTools(), + FuchsiaSdk: () => FuchsiaSdk(), + FuchsiaWorkflow: () => FuchsiaWorkflow( + featureFlags: featureFlags, + platform: globals.platform, + fuchsiaArtifacts: globals.fuchsiaArtifacts!, + ), + GradleUtils: () => GradleUtils( + operatingSystemUtils: globals.os, + logger: globals.logger, + platform: globals.platform, + cache: globals.cache, + ), + HotRunnerConfig: () => HotRunnerConfig(), + IOSSimulatorUtils: () => IOSSimulatorUtils( + logger: globals.logger, + processManager: globals.processManager, + xcode: globals.xcode!, + ), + IOSWorkflow: () => IOSWorkflow( + featureFlags: featureFlags, + xcode: globals.xcode!, + platform: globals.platform, + ), + Java: () => Java.find( + config: globals.config, + androidStudio: globals.androidStudio, + logger: globals.logger, + fileSystem: globals.fs, + platform: globals.platform, + processManager: globals.processManager + ), + LocalEngineLocator: () => LocalEngineLocator( + userMessages: userMessages, + logger: globals.logger, + platform: globals.platform, + fileSystem: globals.fs, + flutterRoot: Cache.flutterRoot!, + ), + Logger: () => globals.platform.isWindows + ? WindowsStdoutLogger( + terminal: globals.terminal, + stdio: globals.stdio, + outputPreferences: globals.outputPreferences, + ) + : StdoutLogger( + terminal: globals.terminal, + stdio: globals.stdio, + outputPreferences: globals.outputPreferences, + ), + MacOSWorkflow: () => MacOSWorkflow( + featureFlags: featureFlags, + platform: globals.platform, + ), + MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery( + logger: globals.logger, + flutterUsage: globals.flutterUsage, + analytics: globals.analytics, + ), + OperatingSystemUtils: () => OperatingSystemUtils( + fileSystem: globals.fs, + logger: globals.logger, + platform: globals.platform, + processManager: globals.processManager, + ), + OutputPreferences: () => OutputPreferences( + wrapText: globals.stdio.hasTerminal, + showColor: globals.platform.stdoutSupportsAnsi, + stdio: globals.stdio, + ), + PersistentToolState: () => PersistentToolState( + fileSystem: globals.fs, + logger: globals.logger, + platform: globals.platform, + ), + ProcessInfo: () => ProcessInfo(globals.fs), + ProcessManager: () => ErrorHandlingProcessManager( + delegate: const LocalProcessManager(), + platform: globals.platform, + ), + ProcessUtils: () => ProcessUtils( + processManager: globals.processManager, + logger: globals.logger, + ), + Pub: () => Pub( + fileSystem: globals.fs, + logger: globals.logger, + processManager: globals.processManager, + botDetector: globals.botDetector, + platform: globals.platform, + usage: globals.flutterUsage, + ), + Stdio: () => Stdio(), + SystemClock: () => const SystemClock(), + Usage: () => Usage( + runningOnBot: runningOnBot, + firstRunMessenger: FirstRunMessenger(persistentToolState: globals.persistentToolState!), + ), + UserMessages: () => UserMessages(), + VisualStudioValidator: () => VisualStudioValidator( + userMessages: globals.userMessages, + visualStudio: VisualStudio( + fileSystem: globals.fs, + platform: globals.platform, + logger: globals.logger, + processManager: globals.processManager, + ) + ), + WebWorkflow: () => WebWorkflow( + featureFlags: featureFlags, + platform: globals.platform, + ), + WindowsWorkflow: () => WindowsWorkflow( + featureFlags: featureFlags, + platform: globals.platform, + ), + Xcode: () => Xcode( + logger: globals.logger, + processManager: globals.processManager, + platform: globals.platform, + fileSystem: globals.fs, + xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, + userMessages: globals.userMessages, + ), + XCDevice: () => XCDevice( + processManager: globals.processManager, + logger: globals.logger, + artifacts: globals.artifacts!, + cache: globals.cache, + platform: globals.platform, + xcode: globals.xcode!, + iproxy: IProxy( + iproxyPath: globals.artifacts!.getHostArtifact( + HostArtifact.iproxy, + ).path, + logger: globals.logger, + processManager: globals.processManager, + dyLdLibEntry: globals.cache.dyLdLibEntry, + ), + fileSystem: globals.fs, + analytics: globals.analytics, + ), + XcodeProjectInterpreter: () => XcodeProjectInterpreter( + logger: globals.logger, + processManager: globals.processManager, + platform: globals.platform, + fileSystem: globals.fs, + usage: globals.flutterUsage, + analytics: globals.analytics, + ), + }, + ); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/convert.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/convert.dart new file mode 100644 index 0000000000000000000000000000000000000000..a17b910831f609ffb7acc0ecff14e256e60b3643 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/convert.dart @@ -0,0 +1,81 @@ +// 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. + +// Hide the original utf8 [Codec] so that we can export our own implementation +// which adds additional error handling. +import 'dart:convert' hide utf8; +import 'dart:convert' as cnv show Utf8Decoder, utf8; + +import 'package:meta/meta.dart'; + +import 'base/common.dart'; +export 'dart:convert' hide Utf8Codec, Utf8Decoder, utf8; + +/// The original utf8 encoding for testing overrides only. +/// +/// Attempting to use the flutter tool utf8 decoder will surface an analyzer +/// warning that overrides cannot change the default value of a named +/// parameter. +@visibleForTesting +const Encoding utf8ForTesting = cnv.utf8; + +/// A [Codec] which reports malformed bytes when decoding. +/// +/// Occasionally people end up in a situation where we try to decode bytes +/// that aren't UTF-8 and we're not quite sure how this is happening. +/// This tells people to report a bug when they see this. +class Utf8Codec extends Encoding { + const Utf8Codec({this.reportErrors = true}); + + final bool reportErrors; + + @override + Converter, String> get decoder => reportErrors + ? const Utf8Decoder() + : const Utf8Decoder(reportErrors: false); + + @override + Converter> get encoder => cnv.utf8.encoder; + + @override + String get name => cnv.utf8.name; +} + +const Encoding utf8 = Utf8Codec(); + +class Utf8Decoder extends Converter, String> { + const Utf8Decoder({this.reportErrors = true}); + + static const cnv.Utf8Decoder _systemDecoder = + cnv.Utf8Decoder(allowMalformed: true); + + final bool reportErrors; + + @override + String convert(List input, [int start = 0, int? end]) { + final String result = _systemDecoder.convert(input, start, end); + // Finding a Unicode replacement character indicates that the input + // was malformed. + if (reportErrors && result.contains('\u{FFFD}')) { + throwToolExit( + 'Bad UTF-8 encoding (U+FFFD; REPLACEMENT CHARACTER) found while decoding string: $result. ' + 'The Flutter team would greatly appreciate if you could file a bug explaining ' + 'exactly what you were doing when this happened:\n' + 'https://github.com/flutter/flutter/issues/new/choose\n' + 'The source bytes were:\n$input\n\n'); + } + return result; + } + + @override + ByteConversionSink startChunkedConversion(Sink sink) => + _systemDecoder.startChunkedConversion(sink); + + @override + Stream bind(Stream> stream) => _systemDecoder.bind(stream); + + @override + Converter, T> fuse(Converter other) => + _systemDecoder.fuse(other); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/daemon.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/daemon.dart new file mode 100644 index 0000000000000000000000000000000000000000..898d2ee1b04c9a5af3750e1c51b90baf98873959 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/daemon.dart @@ -0,0 +1,378 @@ +// 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:typed_data'; + +import 'package:meta/meta.dart'; + +import 'base/common.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/utils.dart'; +import 'convert.dart'; + +/// A single message passed through the [DaemonConnection]. +class DaemonMessage { + DaemonMessage(this.data, [this.binary]); + + /// Content of the JSON message in the message. + final Map data; + + /// Stream of the binary content of the message. + /// + /// Must be listened to if binary data is present. + final Stream>? binary; +} + +/// Data of an event passed through the [DaemonConnection]. +class DaemonEventData { + DaemonEventData(this.eventName, this.data, [this.binary]); + + /// The name of the event. + final String eventName; + + /// The data of the event. + final Object? data; + + /// Stream of the binary content of the event. + /// + /// Must be listened to if binary data is present. + final Stream>? binary; +} + +const String _binaryLengthKey = '_binaryLength'; + +enum _InputStreamParseState { + json, + binary, +} + +/// Converts a binary stream to a stream of [DaemonMessage]. +/// +/// The daemon JSON-RPC protocol is defined as follows: every single line of +/// text that starts with `[{` and ends with `}]` will be parsed as a JSON +/// message. The array should contain only one single object which contains the +/// message data. +/// +/// If the JSON object contains the key [_binaryLengthKey] with an integer +/// value (will be referred to as N), the following N bytes after the newline +/// character will contain the binary part of the message. +@visibleForTesting +class DaemonInputStreamConverter { + DaemonInputStreamConverter(this.inputStream) { + // Lazily listen to the input stream. + _controller.onListen = () { + final StreamSubscription> subscription = inputStream.listen((List chunk) { + _processChunk(chunk); + }, onError: (Object error, StackTrace stackTrace) { + _controller.addError(error, stackTrace); + }, onDone: () { + unawaited(_controller.close()); + }); + + _controller.onCancel = subscription.cancel; + // We should not handle onPause or onResume. When the stream is paused, we + // still need to read from the input stream. + }; + } + + final Stream> inputStream; + + final StreamController _controller = StreamController(); + Stream get convertedStream => _controller.stream; + + // Internal states + /// The current parse state, whether we are expecting JSON or binary data. + _InputStreamParseState state = _InputStreamParseState.json; + + /// The binary stream that is being transferred. + late StreamController> currentBinaryStream; + + /// Remaining length in bytes that have to be sent to the binary stream. + int remainingBinaryLength = 0; + + /// Buffer to hold the current line of input data. + final BytesBuilder bytesBuilder = BytesBuilder(copy: false); + + // Processes a single chunk received in the input stream. + void _processChunk(List chunk) { + + int start = 0; + while (start < chunk.length) { + if (state == _InputStreamParseState.json) { + start += _processChunkInJsonMode(chunk, start); + } else if (state == _InputStreamParseState.binary) { + final int bytesSent = _addBinaryChunk(chunk, start, remainingBinaryLength); + start += bytesSent; + remainingBinaryLength -= bytesSent; + + if (remainingBinaryLength <= 0) { + assert(remainingBinaryLength == 0); + + unawaited(currentBinaryStream.close()); + state = _InputStreamParseState.json; + } + } + } + } + + /// Processes a chunk in JSON mode, and returns the number of bytes processed. + int _processChunkInJsonMode(List chunk, int start) { + const int LF = 10; // The '\n' character + + // Search for newline character. + final int indexOfNewLine = chunk.indexOf(LF, start); + if (indexOfNewLine < 0) { + bytesBuilder.add(chunk.sublist(start)); + return chunk.length - start; + } + + bytesBuilder.add(chunk.sublist(start, indexOfNewLine + 1)); + + // Process chunk here + final Uint8List combinedChunk = bytesBuilder.takeBytes(); + String jsonString = utf8.decode(combinedChunk).trim(); + if (jsonString.startsWith('[{') && jsonString.endsWith('}]')) { + jsonString = jsonString.substring(1, jsonString.length - 1); + final Map? value = castStringKeyedMap(json.decode(jsonString)); + if (value != null) { + // Check if we need to consume another binary blob. + if (value[_binaryLengthKey] != null) { + remainingBinaryLength = value[_binaryLengthKey]! as int; + currentBinaryStream = StreamController>(); + state = _InputStreamParseState.binary; + _controller.add(DaemonMessage(value, currentBinaryStream.stream)); + } else { + _controller.add(DaemonMessage(value)); + } + } + } + + return indexOfNewLine + 1 - start; + } + + int _addBinaryChunk(List chunk, int start, int maximumSizeToRead) { + if (start == 0 && chunk.length <= remainingBinaryLength) { + currentBinaryStream.add(chunk); + return chunk.length; + } else { + final int chunkRemainingLength = chunk.length - start; + final int sizeToRead = chunkRemainingLength < remainingBinaryLength ? chunkRemainingLength : remainingBinaryLength; + currentBinaryStream.add(chunk.sublist(start, start + sizeToRead)); + return sizeToRead; + } + } +} + +/// A stream that a [DaemonConnection] uses to communicate with each other. +class DaemonStreams { + DaemonStreams( + Stream> rawInputStream, + StreamSink> outputSink, { + required Logger logger, + }) : + _outputSink = outputSink, + inputStream = DaemonInputStreamConverter(rawInputStream).convertedStream, + _logger = logger; + + /// Creates a [DaemonStreams] that uses stdin and stdout as the underlying streams. + DaemonStreams.fromStdio(Stdio stdio, { required Logger logger }) + : this(stdio.stdin, stdio.stdout, logger: logger); + + /// Creates a [DaemonStreams] that uses [Socket] as the underlying streams. + DaemonStreams.fromSocket(Socket socket, { required Logger logger }) + : this(socket, socket, logger: logger); + + /// Connects to a server and creates a [DaemonStreams] from the connection as the underlying streams. + factory DaemonStreams.connect(String host, int port, { required Logger logger }) { + final Future socketFuture = Socket.connect(host, port); + final StreamController> inputStreamController = StreamController>(); + final StreamController> outputStreamController = StreamController>(); + socketFuture.then((Socket socket) { + inputStreamController.addStream(socket); + socket.addStream(outputStreamController.stream); + }).onError((Object error, StackTrace stackTrace) { + logger.printError('Socket error: $error'); + logger.printTrace('$stackTrace'); + // Propagate the error to the streams. + inputStreamController.addError(error, stackTrace); + unawaited(outputStreamController.close()); + }); + return DaemonStreams(inputStreamController.stream, outputStreamController.sink, logger: logger); + } + + final StreamSink> _outputSink; + final Logger _logger; + + /// Stream that contains input to the [DaemonConnection]. + final Stream inputStream; + + /// Outputs a message through the connection. + void send(Map message, [ List? binary ]) { + try { + if (binary != null) { + message[_binaryLengthKey] = binary.length; + } + _outputSink.add(utf8.encode('[${json.encode(message)}]\n')); + if (binary != null) { + _outputSink.add(binary); + } + } on StateError catch (error) { + _logger.printError('Failed to write daemon command response: $error'); + // Failed to send, close the connection + _outputSink.close(); + } on IOException catch (error) { + _logger.printError('Failed to write daemon command response: $error'); + // Failed to send, close the connection + _outputSink.close(); + } + } + + /// Cleans up any resources used. + Future dispose() async { + unawaited(_outputSink.close()); + } +} + +/// Connection between a flutter daemon and a client. +class DaemonConnection { + DaemonConnection({ + required DaemonStreams daemonStreams, + required Logger logger, + }): _logger = logger, + _daemonStreams = daemonStreams { + _commandSubscription = daemonStreams.inputStream.listen( + _handleMessage, + onError: (Object error, StackTrace stackTrace) { + // We have to listen for on error otherwise the error on the socket + // will end up in the Zone error handler. + // Do nothing here and let the stream close handlers handle shutting + // down the daemon. + } + ); + } + + final DaemonStreams _daemonStreams; + + final Logger _logger; + + late final StreamSubscription _commandSubscription; + + int _outgoingRequestId = 0; + final Map> _outgoingRequestCompleters = >{}; + + final StreamController _events = StreamController.broadcast(); + final StreamController _incomingCommands = StreamController(); + + /// A stream that contains all the incoming requests. + Stream get incomingCommands => _incomingCommands.stream; + + /// Listens to the event with the event name [eventToListen]. + Stream listenToEvent(String eventToListen) { + return _events.stream + .where((DaemonEventData event) => event.eventName == eventToListen); + } + + /// Sends a request to the other end of the connection. + /// + /// Returns a [Future] that resolves with the content. + Future sendRequest(String method, [Object? params, List? binary]) async { + final String id = '${++_outgoingRequestId}'; + final Completer completer = Completer(); + _outgoingRequestCompleters[id] = completer; + final Map data = { + 'id': id, + 'method': method, + if (params != null) 'params': params, + }; + _logger.printTrace('-> Sending to daemon, id = $id, method = $method'); + _daemonStreams.send(data, binary); + return completer.future; + } + + /// Sends a response to the other end of the connection. + void sendResponse(Object id, [Object? result]) { + _daemonStreams.send({ + 'id': id, + if (result != null) 'result': result, + }); + } + + /// Sends an error response to the other end of the connection. + void sendErrorResponse(Object id, Object? error, StackTrace trace) { + _daemonStreams.send({ + 'id': id, + 'error': error, + 'trace': '$trace', + }); + } + + /// Sends an event to the client. + void sendEvent(String name, [ Object? params, List? binary ]) { + _daemonStreams.send({ + 'event': name, + if (params != null) 'params': params, + }, binary); + } + + /// Handles the input from the stream. + /// + /// There are three kinds of data: Request, Response, Event. + /// + /// Request: + /// {"id": . "method": , "params": } + /// + /// Response: + /// {"id": . "result": } for a successful response. + /// {"id": . "error": , "stackTrace": } for an error response. + /// + /// Event: + /// {"event": . "params": } + void _handleMessage(DaemonMessage message) { + final Map data = message.data; + if (data['id'] != null) { + if (data['method'] == null) { + // This is a response to previously sent request. + final String id = data['id']! as String; + if (data['error'] != null) { + // This is an error response. + _logger.printTrace('<- Error response received from daemon, id = $id'); + final Object error = data['error']!; + final String stackTrace = data['stackTrace'] as String? ?? ''; + _outgoingRequestCompleters.remove(id)?.completeError(error, StackTrace.fromString(stackTrace)); + } else { + _logger.printTrace('<- Response received from daemon, id = $id'); + final Object? result = data['result']; + _outgoingRequestCompleters.remove(id)?.complete(result); + } + } else { + _incomingCommands.add(message); + } + } else if (data['event'] != null) { + // This is an event + _logger.printTrace('<- Event received: ${data['event']}'); + final Object? eventName = data['event']; + if (eventName is String) { + _events.add(DaemonEventData( + eventName, + data['params'], + message.binary, + )); + } else { + throwToolExit('event name received is not string!'); + } + } else { + _logger.printError('Unknown data received from daemon'); + } + } + + /// Cleans up any resources used in the connection. + Future dispose() async { + await _commandSubscription.cancel(); + await _daemonStreams.dispose(); + unawaited(_events.close()); + unawaited(_incomingCommands.close()); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/dart_pub_json_formatter.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/dart_pub_json_formatter.dart new file mode 100644 index 0000000000000000000000000000000000000000..156df4804ddc833f656bd80f163e8514ac02e7b0 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/dart_pub_json_formatter.dart @@ -0,0 +1,71 @@ +// 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:collection'; + +/// Parsing the output of "dart pub deps --json" +/// +/// expected structure: {"name": "package name", "source": "hosted", "dependencies": [...]} +class DartDependencyPackage { + DartDependencyPackage({ + required this.name, + required this.version, + required this.source, + required this.dependencies, + }); + + factory DartDependencyPackage.fromHashMap(dynamic packageInfo) { + String name = ''; + String version = ''; + String source = ''; + List dependencies = []; + + if (packageInfo is LinkedHashMap) { + final LinkedHashMap info = packageInfo as LinkedHashMap; + if (info.containsKey('name')) { + name = info['name'] as String; + } + if (info.containsKey('version')) { + version = info['version'] as String; + } + if (info.containsKey('source')) { + source = info['source'] as String; + } + if (info.containsKey('dependencies')) { + dependencies = info['dependencies'] as List; + } + } + return DartDependencyPackage( + name: name, + version: version, + source: source, + dependencies: dependencies.map((dynamic e) => e.toString()).toList(), + ); + } + + final String name; + final String version; + final String source; + final List dependencies; + +} + +class DartPubJson { + DartPubJson(this._json); + final LinkedHashMap _json; + final List _packages = []; + + List get packages { + if (_packages.isNotEmpty) { + return _packages; + } + if (_json.containsKey('packages')) { + final List packagesInfo = _json['packages'] as List; + for (final dynamic info in packagesInfo) { + _packages.add(DartDependencyPackage.fromHashMap(info)); + } + } + return _packages; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/desktop_device.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/desktop_device.dart new file mode 100644 index 0000000000000000000000000000000000000000..6931a1731a4832dbb994410789c17efb73900015 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/desktop_device.dart @@ -0,0 +1,353 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:process/process.dart'; + +import 'application_package.dart'; +import 'base/file_system.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/os.dart'; +import 'build_info.dart'; +import 'convert.dart'; +import 'devfs.dart'; +import 'device.dart'; +import 'device_port_forwarder.dart'; +import 'protocol_discovery.dart'; + +/// A partial implementation of Device for desktop-class devices to inherit +/// from, containing implementations that are common to all desktop devices. +abstract class DesktopDevice extends Device { + DesktopDevice(super.id, { + required PlatformType super.platformType, + required super.ephemeral, + required Logger logger, + required ProcessManager processManager, + required FileSystem fileSystem, + required OperatingSystemUtils operatingSystemUtils, + }) : _logger = logger, + _processManager = processManager, + _fileSystem = fileSystem, + _operatingSystemUtils = operatingSystemUtils, + super( + category: Category.desktop, + ); + + final Logger _logger; + final ProcessManager _processManager; + final FileSystem _fileSystem; + final OperatingSystemUtils _operatingSystemUtils; + final Set _runningProcesses = {}; + final DesktopLogReader _deviceLogReader = DesktopLogReader(); + + @override + DevFSWriter createDevFSWriter(ApplicationPackage? app, String? userIdentifier) { + return LocalDevFSWriter(fileSystem: _fileSystem); + } + + // Since the host and target devices are the same, no work needs to be done + // to install the application. + @override + Future isAppInstalled( + ApplicationPackage app, { + String? userIdentifier, + }) async => true; + + // Since the host and target devices are the same, no work needs to be done + // to install the application. + @override + Future isLatestBuildInstalled(ApplicationPackage app) async => true; + + // Since the host and target devices are the same, no work needs to be done + // to install the application. + @override + Future installApp( + ApplicationPackage app, { + String? userIdentifier, + }) async => true; + + // Since the host and target devices are the same, no work needs to be done + // to uninstall the application. + @override + Future uninstallApp( + ApplicationPackage app, { + String? userIdentifier, + }) async => true; + + @override + Future get isLocalEmulator async => false; + + @override + Future get emulatorId async => null; + + @override + DevicePortForwarder get portForwarder => const NoOpDevicePortForwarder(); + + @override + Future get sdkNameAndVersion async => _operatingSystemUtils.name; + + @override + bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease; + + @override + DeviceLogReader getLogReader({ + ApplicationPackage? app, + bool includePastLogs = false, + }) { + assert(!includePastLogs, 'Past log reading not supported on desktop.'); + return _deviceLogReader; + } + + @override + void clearLogs() {} + + @override + Future startApp( + ApplicationPackage package, { + String? mainPath, + String? route, + required DebuggingOptions debuggingOptions, + Map platformArgs = const {}, + bool prebuiltApplication = false, + bool ipv6 = false, + String? userIdentifier, + }) async { + if (!prebuiltApplication) { + await buildForDevice( + buildInfo: debuggingOptions.buildInfo, + mainPath: mainPath, + ); + } + + // Ensure that the executable is locatable. + final BuildInfo buildInfo = debuggingOptions.buildInfo; + final bool traceStartup = platformArgs['trace-startup'] as bool? ?? false; + final String? executable = executablePathForDevice(package, buildInfo); + if (executable == null) { + _logger.printError('Unable to find executable to run'); + return LaunchResult.failed(); + } + + Process process; + final List command = [ + executable, + ...debuggingOptions.dartEntrypointArgs, + ]; + try { + process = await _processManager.start( + command, + environment: _computeEnvironment(debuggingOptions, traceStartup, route), + ); + } on ProcessException catch (e) { + _logger.printError('Unable to start executable "${command.join(' ')}": $e'); + rethrow; + } + _runningProcesses.add(process); + unawaited(process.exitCode.then((_) => _runningProcesses.remove(process))); + + _deviceLogReader.initializeProcess(process); + if (debuggingOptions.buildInfo.isRelease) { + return LaunchResult.succeeded(); + } + final ProtocolDiscovery vmServiceDiscovery = ProtocolDiscovery.vmService(_deviceLogReader, + devicePort: debuggingOptions.deviceVmServicePort, + hostPort: debuggingOptions.hostVmServicePort, + ipv6: ipv6, + logger: _logger, + ); + try { + final Uri? vmServiceUri = await vmServiceDiscovery.uri; + if (vmServiceUri != null) { + onAttached(package, buildInfo, process); + return LaunchResult.succeeded(vmServiceUri: vmServiceUri); + } + _logger.printError( + 'Error waiting for a debug connection: ' + 'The log reader stopped unexpectedly, or never started.', + ); + } on Exception catch (error) { + _logger.printError('Error waiting for a debug connection: $error'); + } finally { + await vmServiceDiscovery.cancel(); + } + return LaunchResult.failed(); + } + + @override + Future stopApp( + ApplicationPackage? app, { + String? userIdentifier, + }) async { + bool succeeded = true; + // Walk a copy of _runningProcesses, since the exit handler removes from the + // set. + for (final Process process in Set.of(_runningProcesses)) { + succeeded &= _processManager.killPid(process.pid); + } + return succeeded; + } + + @override + Future dispose() async { + await portForwarder.dispose(); + } + + /// Builds the current project for this device, with the given options. + Future buildForDevice({ + required BuildInfo buildInfo, + String? mainPath, + }); + + /// Returns the path to the executable to run for [package] on this device for + /// the given [buildMode]. + String? executablePathForDevice(ApplicationPackage package, BuildInfo buildInfo); + + /// Called after a process is attached, allowing any device-specific extra + /// steps to be run. + void onAttached(ApplicationPackage package, BuildInfo buildInfo, Process process) {} + + /// Computes a set of environment variables used to pass debugging information + /// to the engine without interfering with application level command line + /// arguments. + /// + /// The format of the environment variables is: + /// * FLUTTER_ENGINE_SWITCHES to the number of switches. + /// * FLUTTER_ENGINE_SWITCH_ (indexing from 1) to the individual switches. + Map _computeEnvironment(DebuggingOptions debuggingOptions, bool traceStartup, String? route) { + int flags = 0; + final Map environment = {}; + + void addFlag(String value) { + flags += 1; + environment['FLUTTER_ENGINE_SWITCH_$flags'] = value; + } + void finish() { + environment['FLUTTER_ENGINE_SWITCHES'] = flags.toString(); + } + + addFlag('enable-dart-profiling=true'); + + if (traceStartup) { + addFlag('trace-startup=true'); + } + if (route != null) { + addFlag('route=$route'); + } + if (debuggingOptions.enableSoftwareRendering) { + addFlag('enable-software-rendering=true'); + } + if (debuggingOptions.skiaDeterministicRendering) { + addFlag('skia-deterministic-rendering=true'); + } + if (debuggingOptions.traceSkia) { + addFlag('trace-skia=true'); + } + if (debuggingOptions.traceAllowlist != null) { + addFlag('trace-allowlist=${debuggingOptions.traceAllowlist}'); + } + if (debuggingOptions.traceSkiaAllowlist != null) { + addFlag('trace-skia-allowlist=${debuggingOptions.traceSkiaAllowlist}'); + } + if (debuggingOptions.traceSystrace) { + addFlag('trace-systrace=true'); + } + if (debuggingOptions.traceToFile != null) { + addFlag('trace-to-file=${debuggingOptions.traceToFile}'); + } + if (debuggingOptions.endlessTraceBuffer) { + addFlag('endless-trace-buffer=true'); + } + if (debuggingOptions.dumpSkpOnShaderCompilation) { + addFlag('dump-skp-on-shader-compilation=true'); + } + if (debuggingOptions.cacheSkSL) { + addFlag('cache-sksl=true'); + } + if (debuggingOptions.purgePersistentCache) { + addFlag('purge-persistent-cache=true'); + } + switch (debuggingOptions.enableImpeller) { + case ImpellerStatus.enabled: + addFlag('enable-impeller=true'); + case ImpellerStatus.disabled: + case ImpellerStatus.platformDefault: + addFlag('enable-impeller=false'); + } + // Options only supported when there is a VM Service connection between the + // tool and the device, usually in debug or profile mode. + if (debuggingOptions.debuggingEnabled) { + if (debuggingOptions.deviceVmServicePort != null) { + addFlag('vm-service-port=${debuggingOptions.deviceVmServicePort}'); + } + if (debuggingOptions.buildInfo.isDebug) { + addFlag('enable-checked-mode=true'); + addFlag('verify-entry-points=true'); + } + if (debuggingOptions.startPaused) { + addFlag('start-paused=true'); + } + if (debuggingOptions.disableServiceAuthCodes) { + addFlag('disable-service-auth-codes=true'); + } + final String dartVmFlags = computeDartVmFlags(debuggingOptions); + if (dartVmFlags.isNotEmpty) { + addFlag('dart-flags=$dartVmFlags'); + } + if (debuggingOptions.useTestFonts) { + addFlag('use-test-fonts=true'); + } + if (debuggingOptions.verboseSystemLogs) { + addFlag('verbose-logging=true'); + } + } + finish(); + return environment; + } +} + +/// A log reader for desktop applications that delegates to a [Process] stdout +/// and stderr streams. +class DesktopLogReader extends DeviceLogReader { + final StreamController> _inputController = StreamController>.broadcast(); + + /// Begin listening to the stdout and stderr streams of the provided [process]. + void initializeProcess(Process process) { + final StreamSubscription> stdoutSub = process.stdout.listen( + _inputController.add, + ); + final StreamSubscription> stderrSub = process.stderr.listen( + _inputController.add, + ); + final Future stdioFuture = Future.wait(>[ + stdoutSub.asFuture(), + stderrSub.asFuture(), + ]); + process.exitCode.whenComplete(() async { + // Wait for output to be fully processed. + await stdioFuture; + // The streams have already completed, so waiting for the stream + // cancellation to complete is not needed. + unawaited(stdoutSub.cancel()); + unawaited(stderrSub.cancel()); + await _inputController.close(); + }); + } + + @override + Stream get logLines { + return _inputController.stream + .transform(utf8.decoder) + .transform(const LineSplitter()); + } + + @override + String get name => 'desktop'; + + @override + void dispose() { + // Nothing to dispose. + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/devfs.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/devfs.dart new file mode 100644 index 0000000000000000000000000000000000000000..93e0f3a363aded07b1eb4b9d4bb43dd789134572 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/devfs.dart @@ -0,0 +1,768 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:package_config/package_config.dart'; +import 'package:vm_service/vm_service.dart' as vm_service; + +import 'asset.dart'; +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/net.dart'; +import 'base/os.dart'; +import 'build_info.dart'; +import 'build_system/targets/scene_importer.dart'; +import 'build_system/targets/shader_compiler.dart'; +import 'compile.dart'; +import 'convert.dart' show base64, utf8; +import 'vmservice.dart'; + +const String _kFontManifest = 'FontManifest.json'; + +class DevFSConfig { + /// Should DevFS assume that symlink targets are stable? + bool cacheSymlinks = false; + /// Should DevFS assume that there are no symlinks to directories? + bool noDirectorySymlinks = false; +} + +DevFSConfig? get devFSConfig => context.get(); + +/// Common superclass for content copied to the device. +abstract class DevFSContent { + /// Return true if this is the first time this method is called + /// or if the entry has been modified since this method was last called. + bool get isModified; + + /// Return true if this is the first time this method is called + /// or if the entry has been modified after the given time + /// or if the given time is null. + bool isModifiedAfter(DateTime time); + + int get size; + + Future> contentsAsBytes(); + + Stream> contentsAsStream(); + + Stream> contentsAsCompressedStream( + OperatingSystemUtils osUtils, + ) { + return osUtils.gzipLevel1Stream(contentsAsStream()); + } +} + +// File content to be copied to the device. +class DevFSFileContent extends DevFSContent { + DevFSFileContent(this.file); + + final FileSystemEntity file; + File? _linkTarget; + FileStat? _fileStat; + + File _getFile() { + final File? linkTarget = _linkTarget; + if (linkTarget != null) { + return linkTarget; + } + if (file is Link) { + // The link target. + return file.fileSystem.file(file.resolveSymbolicLinksSync()); + } + return file as File; + } + + void _stat() { + final File? linkTarget = _linkTarget; + if (linkTarget != null) { + // Stat the cached symlink target. + final FileStat fileStat = linkTarget.statSync(); + if (fileStat.type == FileSystemEntityType.notFound) { + _linkTarget = null; + } else { + _fileStat = fileStat; + return; + } + } + final FileStat fileStat = file.statSync(); + _fileStat = fileStat.type == FileSystemEntityType.notFound ? null : fileStat; + if (_fileStat != null && _fileStat?.type == FileSystemEntityType.link) { + // Resolve, stat, and maybe cache the symlink target. + final String resolved = file.resolveSymbolicLinksSync(); + final File linkTarget = file.fileSystem.file(resolved); + // Stat the link target. + final FileStat fileStat = linkTarget.statSync(); + if (fileStat.type == FileSystemEntityType.notFound) { + _fileStat = null; + _linkTarget = null; + } else if (devFSConfig?.cacheSymlinks ?? false) { + _linkTarget = linkTarget; + } + } + } + + @override + bool get isModified { + final FileStat? oldFileStat = _fileStat; + _stat(); + final FileStat? newFileStat = _fileStat; + if (oldFileStat == null && newFileStat == null) { + return false; + } + return oldFileStat == null || newFileStat == null || newFileStat.modified.isAfter(oldFileStat.modified); + } + + @override + bool isModifiedAfter(DateTime time) { + final FileStat? oldFileStat = _fileStat; + _stat(); + final FileStat? newFileStat = _fileStat; + if (oldFileStat == null && newFileStat == null) { + return false; + } + return oldFileStat == null + || newFileStat == null + || newFileStat.modified.isAfter(time); + } + + @override + int get size { + if (_fileStat == null) { + _stat(); + } + // Can still be null if the file wasn't found. + return _fileStat?.size ?? 0; + } + + @override + Future> contentsAsBytes() async => _getFile().readAsBytes(); + + @override + Stream> contentsAsStream() => _getFile().openRead(); +} + +/// Byte content to be copied to the device. +class DevFSByteContent extends DevFSContent { + DevFSByteContent(this._bytes); + + List _bytes; + + bool _isModified = true; + DateTime _modificationTime = DateTime.now(); + + List get bytes => _bytes; + + set bytes(List value) { + _bytes = value; + _isModified = true; + _modificationTime = DateTime.now(); + } + + /// Return true only once so that the content is written to the device only once. + @override + bool get isModified { + final bool modified = _isModified; + _isModified = false; + return modified; + } + + @override + bool isModifiedAfter(DateTime time) { + return _modificationTime.isAfter(time); + } + + @override + int get size => _bytes.length; + + @override + Future> contentsAsBytes() async => _bytes; + + @override + Stream> contentsAsStream() => + Stream>.fromIterable(>[_bytes]); +} + +/// String content to be copied to the device. +class DevFSStringContent extends DevFSByteContent { + DevFSStringContent(String string) + : _string = string, + super(utf8.encode(string)); + + String _string; + + String get string => _string; + + set string(String value) { + _string = value; + super.bytes = utf8.encode(_string); + } + + @override + set bytes(List value) { + string = utf8.decode(value); + } +} + +/// A string compressing DevFSContent. +/// +/// A specialized DevFSContent similar to DevFSByteContent where the contents +/// are the compressed bytes of a string. Its difference is that the original +/// uncompressed string can be compared with directly without the indirection +/// of a compute-expensive uncompress/decode and compress/encode to compare +/// the strings. +/// +/// The `hintString` parameter is a zlib dictionary hinting mechanism to suggest +/// the most common string occurrences to potentially assist with compression. +class DevFSStringCompressingBytesContent extends DevFSContent { + DevFSStringCompressingBytesContent(this._string, { String? hintString }) + : _compressor = ZLibEncoder( + dictionary: hintString == null + ? null + : utf8.encode(hintString), + gzip: true, + level: 9, + ); + + final String _string; + final ZLibEncoder _compressor; + final DateTime _modificationTime = DateTime.now(); + + bool _isModified = true; + + late final List bytes = _compressor.convert(utf8.encode(_string)); + + /// Return true only once so that the content is written to the device only once. + @override + bool get isModified { + final bool modified = _isModified; + _isModified = false; + return modified; + } + + @override + bool isModifiedAfter(DateTime time) { + return _modificationTime.isAfter(time); + } + + @override + int get size => bytes.length; + + @override + Future> contentsAsBytes() async => bytes; + + @override + Stream> contentsAsStream() => Stream>.value(bytes); + + /// This checks the source string with another string. + bool equals(String string) => _string == string; +} + +class DevFSException implements Exception { + DevFSException(this.message, [this.error, this.stackTrace]); + final String message; + final dynamic error; + final StackTrace? stackTrace; + + @override + String toString() => 'DevFSException($message, $error, $stackTrace)'; +} + +/// Interface responsible for syncing asset files to a development device. +abstract class DevFSWriter { + /// Write the assets in [entries] to the target device. + /// + /// The keys of the map are relative from the [baseUri]. + /// + /// Throws a [DevFSException] if the process fails to complete. + Future write(Map entries, Uri baseUri, DevFSWriter parent); +} + +class _DevFSHttpWriter implements DevFSWriter { + _DevFSHttpWriter( + this.fsName, + FlutterVmService serviceProtocol, { + required OperatingSystemUtils osUtils, + required HttpClient httpClient, + required Logger logger, + Duration? uploadRetryThrottle, + }) + : httpAddress = serviceProtocol.httpAddress, + _client = httpClient, + _osUtils = osUtils, + _uploadRetryThrottle = uploadRetryThrottle, + _logger = logger; + + final HttpClient _client; + final OperatingSystemUtils _osUtils; + final Logger _logger; + final Duration? _uploadRetryThrottle; + + final String fsName; + final Uri? httpAddress; + + // 3 was chosen to try to limit the variance in the time it takes to execute + // `await request.close()` since there is a known bug in Dart where it doesn't + // always return a status code in response to a PUT request: + // https://github.com/dart-lang/sdk/issues/43525. + static const int kMaxInFlight = 3; + + int _inFlight = 0; + late Map _outstanding; + late Completer _completer; + + @override + Future write(Map entries, Uri devFSBase, [DevFSWriter? parent]) async { + try { + _client.maxConnectionsPerHost = kMaxInFlight; + _completer = Completer(); + _outstanding = Map.of(entries); + _scheduleWrites(); + await _completer.future; + } on SocketException catch (socketException, stackTrace) { + _logger.printTrace('DevFS sync failed. Lost connection to device: $socketException'); + throw DevFSException('Lost connection to device.', socketException, stackTrace); + } on Exception catch (exception, stackTrace) { + _logger.printError('Could not update files on device: $exception'); + throw DevFSException('Sync failed', exception, stackTrace); + } + } + + void _scheduleWrites() { + while ((_inFlight < kMaxInFlight) && (!_completer.isCompleted) && _outstanding.isNotEmpty) { + final Uri deviceUri = _outstanding.keys.first; + final DevFSContent content = _outstanding.remove(deviceUri)!; + _startWrite(deviceUri, content, retry: 10); + _inFlight += 1; + } + if ((_inFlight == 0) && (!_completer.isCompleted) && _outstanding.isEmpty) { + _completer.complete(); + } + } + + Future _startWrite( + Uri deviceUri, + DevFSContent content, { + int retry = 0, + }) async { + while (true) { + try { + final HttpClientRequest request = await _client.putUrl(httpAddress!); + request.headers.removeAll(HttpHeaders.acceptEncodingHeader); + request.headers.add('dev_fs_name', fsName); + request.headers.add('dev_fs_uri_b64', base64.encode(utf8.encode('$deviceUri'))); + final Stream> contents = content.contentsAsCompressedStream( + _osUtils, + ); + await request.addStream(contents); + // Once the bug in Dart is solved we can remove the timeout + // (https://github.com/dart-lang/sdk/issues/43525). + try { + final HttpClientResponse response = await request.close().timeout( + const Duration(seconds: 60)); + response.listen((_) {}, + onError: (dynamic error) { + _logger.printTrace('error: $error'); + }, + cancelOnError: true, + ); + } on TimeoutException { + request.abort(); + // This should throw "HttpException: Request has been aborted". + await request.done; + // Just to be safe we rethrow the TimeoutException. + rethrow; + } + break; + } on Exception catch (error, trace) { + if (!_completer.isCompleted) { + _logger.printTrace('Error writing "$deviceUri" to DevFS: $error'); + if (retry > 0) { + retry--; + _logger.printTrace('trying again in a few - $retry more attempts left'); + await Future.delayed(_uploadRetryThrottle ?? const Duration(milliseconds: 500)); + continue; + } + _completer.completeError(error, trace); + } + } + } + _inFlight -= 1; + _scheduleWrites(); + } +} + +// Basic statistics for DevFS update operation. +class UpdateFSReport { + UpdateFSReport({ + bool success = false, + int invalidatedSourcesCount = 0, + int syncedBytes = 0, + int scannedSourcesCount = 0, + Duration compileDuration = Duration.zero, + Duration transferDuration = Duration.zero, + Duration findInvalidatedDuration = Duration.zero, + }) : _success = success, + _invalidatedSourcesCount = invalidatedSourcesCount, + _syncedBytes = syncedBytes, + _scannedSourcesCount = scannedSourcesCount, + _compileDuration = compileDuration, + _transferDuration = transferDuration, + _findInvalidatedDuration = findInvalidatedDuration; + + bool get success => _success; + int get invalidatedSourcesCount => _invalidatedSourcesCount; + int get syncedBytes => _syncedBytes; + int get scannedSourcesCount => _scannedSourcesCount; + Duration get compileDuration => _compileDuration; + Duration get transferDuration => _transferDuration; + Duration get findInvalidatedDuration => _findInvalidatedDuration; + + bool _success; + int _invalidatedSourcesCount; + int _syncedBytes; + int _scannedSourcesCount; + Duration _compileDuration; + Duration _transferDuration; + Duration _findInvalidatedDuration; + + void incorporateResults(UpdateFSReport report) { + if (!report._success) { + _success = false; + } + _invalidatedSourcesCount += report._invalidatedSourcesCount; + _syncedBytes += report._syncedBytes; + _scannedSourcesCount += report._scannedSourcesCount; + _compileDuration += report._compileDuration; + _transferDuration += report._transferDuration; + _findInvalidatedDuration += report._findInvalidatedDuration; + } +} + +class DevFS { + /// Create a [DevFS] named [fsName] for the local files in [rootDirectory]. + /// + /// Failed uploads are retried after [uploadRetryThrottle] duration, defaults to 500ms. + DevFS( + FlutterVmService serviceProtocol, + this.fsName, + this.rootDirectory, { + required OperatingSystemUtils osUtils, + required Logger logger, + required FileSystem fileSystem, + HttpClient? httpClient, + Duration? uploadRetryThrottle, + StopwatchFactory stopwatchFactory = const StopwatchFactory(), + }) : _vmService = serviceProtocol, + _logger = logger, + _fileSystem = fileSystem, + _httpWriter = _DevFSHttpWriter( + fsName, + serviceProtocol, + osUtils: osUtils, + logger: logger, + uploadRetryThrottle: uploadRetryThrottle, + httpClient: httpClient ?? ((context.get() == null) + ? HttpClient() + : context.get()!())), + _stopwatchFactory = stopwatchFactory; + + final FlutterVmService _vmService; + final _DevFSHttpWriter _httpWriter; + final Logger _logger; + final FileSystem _fileSystem; + final StopwatchFactory _stopwatchFactory; + + final String fsName; + final Directory? rootDirectory; + final Set assetPathsToEvict = {}; + final Set shaderPathsToEvict = {}; + final Set scenePathsToEvict = {}; + + // A flag to indicate whether we have called `setAssetDirectory` on the target device. + bool hasSetAssetDirectory = false; + + /// Whether the font manifest was uploaded during [update]. + bool didUpdateFontManifest = false; + + List sources = []; + DateTime? lastCompiled; + DateTime? _previousCompiled; + PackageConfig? lastPackageConfig; + + Uri? _baseUri; + Uri? get baseUri => _baseUri; + + Uri deviceUriToHostUri(Uri deviceUri) { + final String deviceUriString = deviceUri.toString(); + final String baseUriString = baseUri.toString(); + if (deviceUriString.startsWith(baseUriString)) { + final String deviceUriSuffix = deviceUriString.substring(baseUriString.length); + return rootDirectory!.uri.resolve(deviceUriSuffix); + } + return deviceUri; + } + + Future create() async { + _logger.printTrace('DevFS: Creating new filesystem on the device ($_baseUri)'); + try { + final vm_service.Response response = await _vmService.createDevFS(fsName); + _baseUri = Uri.parse(response.json!['uri'] as String); + } on vm_service.RPCError catch (rpcException) { + if (rpcException.code == RPCErrorCodes.kServiceDisappeared) { + // This can happen if the device has been disconnected, so translate to + // a DevFSException, which the caller will handle. + throw DevFSException('Service disconnected', rpcException); + } + // 1001 is kFileSystemAlreadyExists in //dart/runtime/vm/json_stream.h + if (rpcException.code != 1001) { + // Other RPCErrors are unexpected. Rethrow so it will hit crash + // logging. + rethrow; + } + _logger.printTrace('DevFS: Creating failed. Destroying and trying again'); + await destroy(); + final vm_service.Response response = await _vmService.createDevFS(fsName); + _baseUri = Uri.parse(response.json!['uri'] as String); + } + _logger.printTrace('DevFS: Created new filesystem on the device ($_baseUri)'); + return _baseUri!; + } + + Future destroy() async { + _logger.printTrace('DevFS: Deleting filesystem on the device ($_baseUri)'); + await _vmService.deleteDevFS(fsName); + _logger.printTrace('DevFS: Deleted filesystem on the device ($_baseUri)'); + } + + /// Mark the [lastCompiled] time to the previous successful compile. + /// + /// Sometimes a hot reload will be rejected by the VM due to a change in the + /// structure of the code not supporting the hot reload. In these cases, + /// the best resolution is a hot restart. However, the resident runner + /// will not recognize this file as having been changed since the delta + /// will already have been accepted. Instead, reset the compile time so + /// that the last updated files are included in subsequent compilations until + /// a reload is accepted. + void resetLastCompiled() { + lastCompiled = _previousCompiled; + } + + /// Updates files on the device. + /// + /// Returns the number of bytes synced. + Future update({ + required Uri mainUri, + required ResidentCompiler generator, + required bool trackWidgetCreation, + required String pathToReload, + required List invalidatedFiles, + required PackageConfig packageConfig, + required String dillOutputPath, + required DevelopmentShaderCompiler shaderCompiler, + DevelopmentSceneImporter? sceneImporter, + DevFSWriter? devFSWriter, + String? target, + AssetBundle? bundle, + DateTime? firstBuildTime, + bool bundleFirstUpload = false, + bool fullRestart = false, + String? projectRootPath, + File? dartPluginRegistrant, + }) async { + final DateTime candidateCompileTime = DateTime.now(); + didUpdateFontManifest = false; + lastPackageConfig = packageConfig; + + // Update modified files + final Map dirtyEntries = {}; + final List> pendingAssetBuilds = >[]; + bool assetBuildFailed = false; + int syncedBytes = 0; + if (fullRestart) { + generator.reset(); + } + // On a full restart, or on an initial compile for the attach based workflow, + // this will produce a full dill. Subsequent invocations will produce incremental + // dill files that depend on the invalidated files. + _logger.printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files'); + + // 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 Stopwatch compileTimer = _stopwatchFactory.createStopwatch('compile')..start(); + final Future pendingCompilerOutput = generator.recompile( + mainUri, + invalidatedFiles, + outputPath: dillOutputPath, + fs: _fileSystem, + projectRootPath: projectRootPath, + packageConfig: packageConfig, + checkDartPluginRegistry: true, // The entry point is assumed not to have changed. + dartPluginRegistrant: dartPluginRegistrant, + ).then((CompilerOutput? result) { + compileTimer.stop(); + return result; + }); + + if (bundle != null) { + // Mark processing of bundle started for testability of starting the compile + // before processing bundle. + _logger.printTrace('Processing bundle.'); + // await null to give time for telling the compiler to compile. + await null; + + // The tool writes the assets into the AssetBundle working dir so that they + // are in the same location in DevFS and the iOS simulator. + final String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory()); + final String assetDirectory = getAssetBuildDirectory(); + bundle.entries.forEach((String archivePath, DevFSContent content) { + // If the content is backed by a real file, isModified will file stat and return true if + // it was modified since the last time this was called. + if (!content.isModified || bundleFirstUpload) { + return; + } + // Modified shaders must be recompiled per-target platform. + final Uri deviceUri = _fileSystem.path.toUri(_fileSystem.path.join(assetDirectory, archivePath)); + if (deviceUri.path.startsWith(assetBuildDirPrefix)) { + archivePath = deviceUri.path.substring(assetBuildDirPrefix.length); + } + // If the font manifest is updated, mark this as true so the hot runner + // can invoke a service extension to force the engine to reload fonts. + if (archivePath == _kFontManifest) { + didUpdateFontManifest = true; + } + + switch (bundle.entryKinds[archivePath]) { + case AssetKind.shader: + final Future pending = shaderCompiler.recompileShader(content); + pendingAssetBuilds.add(pending); + pending.then((DevFSContent? content) { + if (content == null) { + assetBuildFailed = true; + return; + } + dirtyEntries[deviceUri] = content; + syncedBytes += content.size; + if (!bundleFirstUpload) { + shaderPathsToEvict.add(archivePath); + } + }); + case AssetKind.model: + if (sceneImporter == null) { + break; + } + final Future pending = sceneImporter.reimportScene(content); + pendingAssetBuilds.add(pending); + pending.then((DevFSContent? content) { + if (content == null) { + assetBuildFailed = true; + return; + } + dirtyEntries[deviceUri] = content; + syncedBytes += content.size; + if (!bundleFirstUpload) { + scenePathsToEvict.add(archivePath); + } + }); + case AssetKind.regular: + case AssetKind.font: + case null: + dirtyEntries[deviceUri] = content; + syncedBytes += content.size; + if (!bundleFirstUpload) { + assetPathsToEvict.add(archivePath); + } + } + }); + + // Mark processing of bundle done for testability of starting the compile + // before processing bundle. + _logger.printTrace('Bundle processing done.'); + } + final CompilerOutput? compilerOutput = await pendingCompilerOutput; + if (compilerOutput == null || compilerOutput.errorCount > 0) { + return UpdateFSReport(); + } + // Only update the last compiled time if we successfully compiled. + _previousCompiled = lastCompiled; + lastCompiled = candidateCompileTime; + // list of sources that needs to be monitored are in [compilerOutput.sources] + sources = compilerOutput.sources; + // + // Don't send full kernel file that would overwrite what VM already + // started loading from. + if (!bundleFirstUpload) { + final String compiledBinary = compilerOutput.outputFilename; + if (compiledBinary.isNotEmpty) { + final Uri entryUri = _fileSystem.path.toUri(pathToReload); + final DevFSFileContent content = DevFSFileContent(_fileSystem.file(compiledBinary)); + syncedBytes += content.size; + dirtyEntries[entryUri] = content; + } + } + _logger.printTrace('Updating files.'); + final Stopwatch transferTimer = _stopwatchFactory.createStopwatch('transfer')..start(); + + await Future.wait(pendingAssetBuilds); + if (assetBuildFailed) { + return UpdateFSReport(); + } + + if (dirtyEntries.isNotEmpty) { + await (devFSWriter ?? _httpWriter).write(dirtyEntries, _baseUri!, _httpWriter); + } + transferTimer.stop(); + _logger.printTrace('DevFS: Sync finished'); + return UpdateFSReport( + success: true, + syncedBytes: syncedBytes, + invalidatedSourcesCount: invalidatedFiles.length, + compileDuration: compileTimer.elapsed, + transferDuration: transferTimer.elapsed, + ); + } + + /// Converts a platform-specific file path to a platform-independent URL path. + String _asUriPath(String filePath) => '${_fileSystem.path.toUri(filePath).path}/'; +} + +/// An implementation of a devFS writer which copies physical files for devices +/// running on the same host. +/// +/// DevFS entries which correspond to physical files are copied using [File.copySync], +/// while entries that correspond to arbitrary string/byte values are written from +/// memory. +/// +/// Requires that the file system is the same for both the tool and application. +class LocalDevFSWriter implements DevFSWriter { + LocalDevFSWriter({ + required FileSystem fileSystem, + }) : _fileSystem = fileSystem; + + final FileSystem _fileSystem; + + @override + Future write(Map entries, Uri baseUri, [DevFSWriter? parent]) async { + try { + for (final MapEntry entry in entries.entries) { + final Uri uri = entry.key; + final DevFSContent devFSContent = entry.value; + final File destination = _fileSystem.file(baseUri.resolveUri(uri)); + if (!destination.parent.existsSync()) { + destination.parent.createSync(recursive: true); + } + if (devFSContent is DevFSFileContent) { + final File content = devFSContent.file as File; + content.copySync(destination.path); + continue; + } + destination.writeAsBytesSync(await devFSContent.contentsAsBytes()); + } + } on FileSystemException catch (err) { + throw DevFSException(err.toString()); + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/device.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/device.dart new file mode 100644 index 0000000000000000000000000000000000000000..2639448d0d9717591c15cc78f40df27333e8fff3 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/device.dart @@ -0,0 +1,1400 @@ +// 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:math' as math; + +import 'package:meta/meta.dart'; + +import 'application_package.dart'; +import 'base/context.dart'; +import 'base/dds.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/utils.dart'; +import 'build_info.dart'; +import 'devfs.dart'; +import 'device_port_forwarder.dart'; +import 'project.dart'; +import 'vmservice.dart'; + +DeviceManager? get deviceManager => context.get(); + +/// A description of the kind of workflow the device supports. +enum Category { + web._('web'), + desktop._('desktop'), + mobile._('mobile'); + + const Category._(this.value); + + final String value; + + @override + String toString() => value; + + static Category? fromString(String category) { + return const { + 'web': web, + 'desktop': desktop, + 'mobile': mobile, + }[category]; + } +} + +/// The platform sub-folder that a device type supports. +enum PlatformType { + web, + android, + ios, + linux, + macos, + windows, + fuchsia, + custom, + windowsPreview; + + @override + String toString() => name; + + static PlatformType? fromString(String platformType) => values.asNameMap()[platformType]; +} + +/// A discovery mechanism for flutter-supported development devices. +abstract class DeviceManager { + DeviceManager({ + required Logger logger, + }) : _logger = logger; + + final Logger _logger; + + /// Constructing DeviceManagers is cheap; they only do expensive work if some + /// of their methods are called. + List get deviceDiscoverers; + + String? _specifiedDeviceId; + + /// A user-specified device ID. + String? get specifiedDeviceId { + if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') { + return null; + } + return _specifiedDeviceId; + } + + set specifiedDeviceId(String? id) { + _specifiedDeviceId = id; + } + + /// A minimum duration to use when discovering wireless iOS devices. + static const Duration minimumWirelessDeviceDiscoveryTimeout = Duration( + seconds: 5, + ); + + /// True when the user has specified a single specific device. + bool get hasSpecifiedDeviceId => specifiedDeviceId != null; + + /// True when the user has specified all devices by setting + /// specifiedDeviceId = 'all'. + bool get hasSpecifiedAllDevices => _specifiedDeviceId == 'all'; + + /// Get devices filtered by [filter] that match the given device id/name. + /// + /// If [filter] is not provided, a default filter that requires devices to be + /// connected will be used. + /// + /// If an exact match is found, return it immediately. Otherwise wait for all + /// discoverers to complete and return any partial matches. + Future> getDevicesById( + String deviceId, { + DeviceDiscoveryFilter? filter, + }) async { + filter ??= DeviceDiscoveryFilter(); + + final String lowerDeviceId = deviceId.toLowerCase(); + bool exactlyMatchesDeviceId(Device device) => + device.id.toLowerCase() == lowerDeviceId || + device.name.toLowerCase() == lowerDeviceId; + bool startsWithDeviceId(Device device) => + device.id.toLowerCase().startsWith(lowerDeviceId) || + device.name.toLowerCase().startsWith(lowerDeviceId); + + // Some discoverers have hard-coded device IDs and return quickly, and others + // shell out to other processes and can take longer. + // If an ID was specified, first check if it was a "well-known" device id. + final Set wellKnownIds = _platformDiscoverers + .expand((DeviceDiscovery discovery) => discovery.wellKnownIds) + .toSet(); + final bool hasWellKnownId = hasSpecifiedDeviceId && wellKnownIds.contains(specifiedDeviceId); + + // Process discoverers as they can return results, so if an exact match is + // found quickly, we don't wait for all the discoverers to complete. + final List prefixMatches = []; + final Completer exactMatchCompleter = Completer(); + final List?>> futureDevices = ?>>[ + for (final DeviceDiscovery discoverer in _platformDiscoverers) + if (!hasWellKnownId || discoverer.wellKnownIds.contains(specifiedDeviceId)) + discoverer + .devices(filter: filter) + .then((List devices) { + for (final Device device in devices) { + if (exactlyMatchesDeviceId(device)) { + exactMatchCompleter.complete(device); + return null; + } + if (startsWithDeviceId(device)) { + prefixMatches.add(device); + } + } + return null; + }, onError: (dynamic error, StackTrace stackTrace) { + // Return matches from other discoverers even if one fails. + _logger.printTrace('Ignored error discovering $deviceId: $error'); + }), + ]; + + // Wait for an exact match, or for all discoverers to return results. + await Future.any(>[ + exactMatchCompleter.future, + Future.wait?>(futureDevices), + ]); + + if (exactMatchCompleter.isCompleted) { + return [await exactMatchCompleter.future]; + } + return prefixMatches; + } + + /// Returns a list of devices filtered by the user-specified device + /// id/name (if applicable) and [filter]. + /// + /// If [filter] is not provided, a default filter that requires devices to be + /// connected will be used. + Future> getDevices({ + DeviceDiscoveryFilter? filter, + }) { + filter ??= DeviceDiscoveryFilter(); + final String? id = specifiedDeviceId; + if (id == null) { + return getAllDevices(filter: filter); + } + return getDevicesById(id, filter: filter); + } + + Iterable get _platformDiscoverers { + return deviceDiscoverers.where((DeviceDiscovery discoverer) => discoverer.supportsPlatform); + } + + /// Returns a list of devices filtered by [filter]. + /// + /// If [filter] is not provided, a default filter that requires devices to be + /// connected will be used. + Future> getAllDevices({ + DeviceDiscoveryFilter? filter, + }) async { + filter ??= DeviceDiscoveryFilter(); + final List> devices = await Future.wait>(>>[ + for (final DeviceDiscovery discoverer in _platformDiscoverers) + discoverer.devices(filter: filter), + ]); + + return devices.expand((List deviceList) => deviceList).toList(); + } + + /// Returns a list of devices filtered by [filter]. Discards existing cache of devices. + /// + /// If [filter] is not provided, a default filter that requires devices to be + /// connected will be used. + /// + /// Search for devices to populate the cache for no longer than [timeout]. + Future> refreshAllDevices({ + Duration? timeout, + DeviceDiscoveryFilter? filter, + }) async { + filter ??= DeviceDiscoveryFilter(); + final List> devices = await Future.wait>(>>[ + for (final DeviceDiscovery discoverer in _platformDiscoverers) + discoverer.discoverDevices(filter: filter, timeout: timeout), + ]); + + return devices.expand((List deviceList) => deviceList).toList(); + } + + /// Discard existing cache of discoverers that are known to take longer to + /// discover wireless devices. + /// + /// Then, search for devices for those discoverers to populate the cache for + /// no longer than [timeout]. + Future refreshExtendedWirelessDeviceDiscoverers({ + Duration? timeout, + DeviceDiscoveryFilter? filter, + }) async { + await Future.wait>(>>[ + for (final DeviceDiscovery discoverer in _platformDiscoverers) + if (discoverer.requiresExtendedWirelessDeviceDiscovery) + discoverer.discoverDevices(timeout: timeout) + ]); + } + + /// Whether we're capable of listing any devices given the current environment configuration. + bool get canListAnything { + return _platformDiscoverers.any((DeviceDiscovery discoverer) => discoverer.canListAnything); + } + + /// Get diagnostics about issues with any connected devices. + Future> getDeviceDiagnostics() async { + return [ + for (final DeviceDiscovery discoverer in _platformDiscoverers) + ...await discoverer.getDiagnostics(), + ]; + } + + /// Determines how to filter devices. + /// + /// By default, filters to only include devices that are supported by Flutter. + /// + /// If the user has not specified a device, filters to only include devices + /// that are supported by Flutter and supported by the project. + /// + /// If the user has specified `--device all`, filters to only include devices + /// that are supported by Flutter, supported by the project, and supported for `all`. + /// + /// If [includeDevicesUnsupportedByProject] is true, all devices will be + /// considered supported by the project, regardless of user specifications. + /// + /// This also exists to allow the check to be overridden for google3 clients. + DeviceDiscoverySupportFilter deviceSupportFilter({ + bool includeDevicesUnsupportedByProject = false, + }) { + FlutterProject? flutterProject; + if (!includeDevicesUnsupportedByProject) { + flutterProject = FlutterProject.current(); + } + if (hasSpecifiedAllDevices) { + return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProjectOrAll( + flutterProject: flutterProject, + ); + } else if (!hasSpecifiedDeviceId) { + return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProject( + flutterProject: flutterProject, + ); + } else { + return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter(); + } + } + + /// If the user did not specify to run all or a specific device, then attempt + /// to prioritize ephemeral devices. + /// + /// If there is not exactly one ephemeral device return null. + /// + /// For example, if the user only typed 'flutter run' and both an Android + /// device and desktop device are available, choose the Android device. + /// + /// Note: ephemeral is nullable for device types where this is not well + /// defined. + Device? getSingleEphemeralDevice(List devices){ + if (!hasSpecifiedDeviceId) { + try { + return devices.singleWhere((Device device) => device.ephemeral); + } on StateError { + return null; + } + } + return null; + } +} + +/// A class for determining how to filter devices based on if they are supported. +class DeviceDiscoverySupportFilter { + /// Filter devices to only include those supported by Flutter. + DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter() + : _excludeDevicesNotSupportedByProject = false, + _excludeDevicesNotSupportedByAll = false, + _flutterProject = null; + + /// Filter devices to only include those supported by Flutter and the + /// provided [flutterProject]. + /// + /// If [flutterProject] is null, all devices will be considered supported by + /// the project. + DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProject({ + required FlutterProject? flutterProject, + }) : _flutterProject = flutterProject, + _excludeDevicesNotSupportedByProject = true, + _excludeDevicesNotSupportedByAll = false; + + /// Filter devices to only include those supported by Flutter, the provided + /// [flutterProject], and `--device all`. + /// + /// If [flutterProject] is null, all devices will be considered supported by + /// the project. + DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProjectOrAll({ + required FlutterProject? flutterProject, + }) : _flutterProject = flutterProject, + _excludeDevicesNotSupportedByProject = true, + _excludeDevicesNotSupportedByAll = true; + + final FlutterProject? _flutterProject; + final bool _excludeDevicesNotSupportedByProject; + final bool _excludeDevicesNotSupportedByAll; + + Future matchesRequirements(Device device) async { + final bool meetsSupportByFlutterRequirement = device.isSupported(); + final bool meetsSupportForProjectRequirement = !_excludeDevicesNotSupportedByProject || isDeviceSupportedForProject(device); + final bool meetsSupportForAllRequirement = !_excludeDevicesNotSupportedByAll || await isDeviceSupportedForAll(device); + + return meetsSupportByFlutterRequirement && + meetsSupportForProjectRequirement && + meetsSupportForAllRequirement; + } + + /// User has specified `--device all`. + /// + /// Always remove web and fuchsia devices from `all`. This setting + /// currently requires devices to share a frontend_server and resident + /// runner instance. Both web and fuchsia require differently configured + /// compilers, and web requires an entirely different resident runner. + Future isDeviceSupportedForAll(Device device) async { + final TargetPlatform devicePlatform = await device.targetPlatform; + return device.isSupported() && + devicePlatform != TargetPlatform.fuchsia_arm64 && + devicePlatform != TargetPlatform.fuchsia_x64 && + devicePlatform != TargetPlatform.web_javascript && + isDeviceSupportedForProject(device); + } + + /// Returns whether the device is supported for the project. + /// + /// A device can be supported by Flutter but not supported for the project + /// (e.g. when the user has removed the iOS directory from their project). + /// + /// This also exists to allow the check to be overridden for google3 clients. If + /// [_flutterProject] is null then return true. + bool isDeviceSupportedForProject(Device device) { + if (!device.isSupported()) { + return false; + } + if (_flutterProject == null) { + return true; + } + return device.isSupportedForProject(_flutterProject); + } +} + +/// A class for filtering devices. +/// +/// If [excludeDisconnected] is true, only devices detected as connected will be included. +/// +/// If [supportFilter] is provided, only devices matching the requirements will be included. +/// +/// If [deviceConnectionInterface] is provided, only devices matching the DeviceConnectionInterface will be included. +class DeviceDiscoveryFilter { + DeviceDiscoveryFilter({ + this.excludeDisconnected = true, + this.supportFilter, + this.deviceConnectionInterface, + }); + + final bool excludeDisconnected; + final DeviceDiscoverySupportFilter? supportFilter; + final DeviceConnectionInterface? deviceConnectionInterface; + + Future matchesRequirements(Device device) async { + final DeviceDiscoverySupportFilter? localSupportFilter = supportFilter; + + final bool meetsConnectionRequirement = !excludeDisconnected || device.isConnected; + final bool meetsSupportRequirements = localSupportFilter == null || (await localSupportFilter.matchesRequirements(device)); + final bool meetsConnectionInterfaceRequirement = matchesDeviceConnectionInterface(device, deviceConnectionInterface); + + return meetsConnectionRequirement && + meetsSupportRequirements && + meetsConnectionInterfaceRequirement; + } + + Future> filterDevices(List devices) async { + devices = [ + for (final Device device in devices) + if (await matchesRequirements(device)) device, + ]; + return devices; + } + + bool matchesDeviceConnectionInterface( + Device device, + DeviceConnectionInterface? deviceConnectionInterface, + ) { + if (deviceConnectionInterface == null) { + return true; + } + return device.connectionInterface == deviceConnectionInterface; + } +} + +/// An abstract class to discover and enumerate a specific type of devices. +abstract class DeviceDiscovery { + bool get supportsPlatform; + + /// Whether this device discovery is capable of listing any devices given the + /// current environment configuration. + bool get canListAnything; + + /// Whether this device discovery is known to take longer to discover + /// wireless devices. + bool get requiresExtendedWirelessDeviceDiscovery => false; + + /// Return all connected devices, cached on subsequent calls. + Future> devices({DeviceDiscoveryFilter? filter}); + + /// Return all connected devices. Discards existing cache of devices. + Future> discoverDevices({ + Duration? timeout, + DeviceDiscoveryFilter? filter, + }); + + /// Gets a list of diagnostic messages pertaining to issues with any connected + /// devices (will be an empty list if there are no issues). + Future> getDiagnostics() => Future>.value([]); + + /// Hard-coded device IDs that the discoverer can produce. + /// + /// These values are used by the device discovery to determine if it can + /// short-circuit the other detectors if a specific ID is provided. If a + /// discoverer has no valid fixed IDs, these should be left empty. + /// + /// For example, 'windows' or 'linux'. + List get wellKnownIds; +} + +/// A [DeviceDiscovery] implementation that uses polling to discover device adds +/// and removals. +abstract class PollingDeviceDiscovery extends DeviceDiscovery { + PollingDeviceDiscovery(this.name); + + static const Duration _pollingInterval = Duration(seconds: 4); + static const Duration _pollingTimeout = Duration(seconds: 30); + + final String name; + + @protected + @visibleForTesting + ItemListNotifier? deviceNotifier; + + Timer? _timer; + + Future> pollingGetDevices({Duration? timeout}); + + void startPolling() { + if (_timer == null) { + deviceNotifier ??= ItemListNotifier(); + // Make initial population the default, fast polling timeout. + _timer = _initTimer(null, initialCall: true); + } + } + + Timer _initTimer(Duration? pollingTimeout, {bool initialCall = false}) { + // Poll for devices immediately on the initial call for faster initial population. + return Timer(initialCall ? Duration.zero : _pollingInterval, () async { + try { + final List devices = await pollingGetDevices(timeout: pollingTimeout); + deviceNotifier!.updateWithNewList(devices); + } on TimeoutException { + // Do nothing on a timeout. + } + // Subsequent timeouts after initial population should wait longer. + _timer = _initTimer(_pollingTimeout); + }); + } + + void stopPolling() { + _timer?.cancel(); + _timer = null; + } + + /// Get devices from cache filtered by [filter]. + /// + /// If the cache is empty, populate the cache. + /// + /// If [filter] is null, it may return devices that are not connected. + @override + Future> devices({DeviceDiscoveryFilter? filter}) { + return _populateDevices(filter: filter); + } + + /// Empty the cache and repopulate it before getting devices from cache filtered by [filter]. + /// + /// Search for devices to populate the cache for no longer than [timeout]. + /// + /// If [filter] is null, it may return devices that are not connected. + @override + Future> discoverDevices({ + Duration? timeout, + DeviceDiscoveryFilter? filter, + }) { + return _populateDevices(timeout: timeout, filter: filter, resetCache: true); + } + + /// Get devices from cache filtered by [filter]. + /// + /// If the cache is empty or [resetCache] is true, populate the cache. + /// + /// Search for devices to populate the cache for no longer than [timeout]. + Future> _populateDevices({ + Duration? timeout, + DeviceDiscoveryFilter? filter, + bool resetCache = false, + }) async { + if (deviceNotifier == null || resetCache) { + final List devices = await pollingGetDevices(timeout: timeout); + // If the cache was populated while the polling was ongoing, do not + // overwrite the cache unless it's explicitly refreshing the cache. + if (resetCache) { + deviceNotifier = ItemListNotifier.from(devices); + } else { + deviceNotifier ??= ItemListNotifier.from(devices); + } + } + + // If a filter is provided, filter cache to only return devices matching. + if (filter != null) { + return filter.filterDevices(deviceNotifier!.items); + } + return deviceNotifier!.items; + } + + Stream get onAdded { + deviceNotifier ??= ItemListNotifier(); + return deviceNotifier!.onAdded; + } + + Stream get onRemoved { + deviceNotifier ??= ItemListNotifier(); + return deviceNotifier!.onRemoved; + } + + void dispose() => stopPolling(); + + @override + String toString() => '$name device discovery'; +} + +/// How a device is connected. +enum DeviceConnectionInterface { + attached, + wireless, +} + +/// A device is a physical hardware that can run a Flutter application. +/// +/// This may correspond to a connected iOS or Android device, or represent +/// the host operating system in the case of Flutter Desktop. +abstract class Device { + Device(this.id, { + required this.category, + required this.platformType, + required this.ephemeral, + }); + + final String id; + + /// The [Category] for this device type. + final Category? category; + + /// The [PlatformType] for this device. + final PlatformType? platformType; + + /// Whether this is an ephemeral device. + final bool ephemeral; + + bool get isConnected => true; + + DeviceConnectionInterface get connectionInterface => + DeviceConnectionInterface.attached; + + bool get isWirelesslyConnected => + connectionInterface == DeviceConnectionInterface.wireless; + + String get name; + + bool get supportsStartPaused => true; + + /// Whether it is an emulated device running on localhost. + /// + /// This may return `true` for certain physical Android devices, and is + /// generally only a best effort guess. + Future get isLocalEmulator; + + /// The unique identifier for the emulator that corresponds to this device, or + /// null if it is not an emulator. + /// + /// The ID returned matches that in the output of `flutter emulators`. Fetching + /// this name may require connecting to the device and if an error occurs null + /// will be returned. + Future get emulatorId; + + /// Whether this device can run the provided [buildMode]. + /// + /// For example, some emulator architectures cannot run profile or + /// release builds. + FutureOr supportsRuntimeMode(BuildMode buildMode) => true; + + /// Whether the device is a simulator on a platform which supports hardware rendering. + // This is soft-deprecated since the logic is not correct expect for iOS simulators. + Future get supportsHardwareRendering async { + return true; + } + + /// Whether the device is supported for the current project directory. + bool isSupportedForProject(FlutterProject flutterProject); + + /// Check if a version of the given app is already installed. + /// + /// Specify [userIdentifier] to check if installed for a particular user (Android only). + Future isAppInstalled( + ApplicationPackage app, { + String? userIdentifier, + }); + + /// Check if the latest build of the [app] is already installed. + Future isLatestBuildInstalled(ApplicationPackage app); + + /// Install an app package on the current device. + /// + /// Specify [userIdentifier] to install for a particular user (Android only). + Future installApp( + ApplicationPackage app, { + String? userIdentifier, + }); + + /// Uninstall an app package from the current device. + /// + /// Specify [userIdentifier] to uninstall for a particular user, + /// defaults to all users (Android only). + Future uninstallApp( + ApplicationPackage app, { + String? userIdentifier, + }); + + /// Check if the device is supported by Flutter. + bool isSupported(); + + // String meant to be displayed to the user indicating if the device is + // supported by Flutter, and, if not, why. + String supportMessage() => isSupported() ? 'Supported' : 'Unsupported'; + + /// The device's platform. + Future get targetPlatform; + + /// Platform name for display only. + Future get targetPlatformDisplayName async => + getNameForTargetPlatform(await targetPlatform); + + Future get sdkNameAndVersion; + + /// Create a platform-specific [DevFSWriter] for the given [app], or + /// null if the device does not support them. + /// + /// For example, the desktop device classes can use a writer which + /// copies the files across the local file system. + DevFSWriter? createDevFSWriter( + ApplicationPackage? app, + String? userIdentifier, + ) { + return null; + } + + /// Get a log reader for this device. + /// + /// If `app` is specified, this will return a log reader specific to that + /// application. Otherwise, a global log reader will be returned. + /// + /// If `includePastLogs` is true and the device type supports it, the log + /// reader will also include log messages from before the invocation time. + /// Defaults to false. + FutureOr getLogReader({ + ApplicationPackage? app, + bool includePastLogs = false, + }); + + /// Get the port forwarder for this device. + DevicePortForwarder? get portForwarder; + + /// Get the DDS instance for this device. + final DartDevelopmentService dds = DartDevelopmentService(); + + /// Clear the device's logs. + void clearLogs(); + + /// Start an app package on the current device. + /// + /// [platformArgs] allows callers to pass platform-specific arguments to the + /// start call. The build mode is not used by all platforms. + Future startApp( + covariant ApplicationPackage? package, { + String? mainPath, + String? route, + required DebuggingOptions debuggingOptions, + Map platformArgs, + bool prebuiltApplication = false, + bool ipv6 = false, + String? userIdentifier, + }); + + /// Whether this device implements support for hot reload. + bool get supportsHotReload => true; + + /// Whether this device implements support for hot restart. + bool get supportsHotRestart => true; + + /// Whether Flutter applications running on this device can be terminated + /// from the VM Service. + bool get supportsFlutterExit => true; + + /// Whether the device supports taking screenshots of a running flutter + /// application. + bool get supportsScreenshot => false; + + /// Whether the device supports the '--fast-start' development mode. + bool get supportsFastStart => false; + + /// Whether the Flavors feature ('--flavor') is supported for this device. + bool get supportsFlavors => false; + + /// Stop an app package on the current device. + /// + /// Specify [userIdentifier] to stop app installed to a profile (Android only). + Future stopApp( + ApplicationPackage? app, { + String? userIdentifier, + }); + + /// Query the current application memory usage.. + /// + /// If the device does not support this callback, an empty map + /// is returned. + Future queryMemoryInfo() { + return Future.value(const MemoryInfo.empty()); + } + + Future takeScreenshot(File outputFile) => Future.error('unimplemented'); + + @nonVirtual + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => id.hashCode; + + @nonVirtual + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + return other is Device + && other.id == id; + } + + @override + String toString() => name; + + static Future> descriptions(List devices) async { + if (devices.isEmpty) { + return const []; + } + + // Extract device information + final List> table = >[]; + for (final Device device in devices) { + String supportIndicator = device.isSupported() ? '' : ' (unsupported)'; + final TargetPlatform targetPlatform = await device.targetPlatform; + if (await device.isLocalEmulator) { + final String type = targetPlatform == TargetPlatform.ios ? 'simulator' : 'emulator'; + supportIndicator += ' ($type)'; + } + table.add([ + '${device.name} (${device.category})', + device.id, + await device.targetPlatformDisplayName, + '${await device.sdkNameAndVersion}$supportIndicator', + ]); + } + + // Calculate column widths + final List indices = List.generate(table[0].length - 1, (int i) => i); + List widths = indices.map((int i) => 0).toList(); + for (final List row in table) { + widths = indices.map((int i) => math.max(widths[i], row[i].length)).toList(); + } + + // Join columns into lines of text + return [ + for (final List row in table) + indices.map((int i) => row[i].padRight(widths[i])).followedBy([row.last]).join(' • '), + ]; + } + + static Future printDevices(List devices, Logger logger, { String prefix = '' }) async { + for (final String line in await descriptions(devices)) { + logger.printStatus('$prefix$line'); + } + } + + static List devicesPlatformTypes(List devices) { + return devices + .map( + (Device d) => d.platformType.toString(), + ).toSet().toList()..sort(); + } + + /// Convert the Device object to a JSON representation suitable for serialization. + Future> toJson() async { + final bool isLocalEmu = await isLocalEmulator; + return { + 'name': name, + 'id': id, + 'isSupported': isSupported(), + 'targetPlatform': getNameForTargetPlatform(await targetPlatform), + 'emulator': isLocalEmu, + 'sdk': await sdkNameAndVersion, + 'capabilities': { + 'hotReload': supportsHotReload, + 'hotRestart': supportsHotRestart, + 'screenshot': supportsScreenshot, + 'fastStart': supportsFastStart, + 'flutterExit': supportsFlutterExit, + 'hardwareRendering': isLocalEmu && await supportsHardwareRendering, + 'startPaused': supportsStartPaused, + }, + }; + } + + /// Clean up resources allocated by device. + /// + /// For example log readers or port forwarders. + Future dispose(); +} + +/// Information about an application's memory usage. +abstract class MemoryInfo { + /// Const constructor to allow subclasses to be const. + const MemoryInfo(); + + /// Create a [MemoryInfo] object with no information. + const factory MemoryInfo.empty() = _NoMemoryInfo; + + /// Convert the object to a JSON representation suitable for serialization. + Map toJson(); +} + +class _NoMemoryInfo implements MemoryInfo { + const _NoMemoryInfo(); + + @override + Map toJson() => {}; +} + +enum ImpellerStatus { + platformDefault._(null), + enabled._(true), + disabled._(false); + + const ImpellerStatus._(this.asBool); + + factory ImpellerStatus.fromBool(bool? b) { + if (b == null) { + return platformDefault; + } + return b ? enabled : disabled; + } + + final bool? asBool; +} + +class DebuggingOptions { + DebuggingOptions.enabled( + this.buildInfo, { + this.startPaused = false, + this.disableServiceAuthCodes = false, + this.enableDds = true, + this.cacheStartupProfile = false, + this.dartEntrypointArgs = const [], + this.dartFlags = '', + this.enableSoftwareRendering = false, + this.skiaDeterministicRendering = false, + this.traceSkia = false, + this.traceAllowlist, + this.traceSkiaAllowlist, + this.traceSystrace = false, + this.traceToFile, + this.endlessTraceBuffer = false, + this.dumpSkpOnShaderCompilation = false, + this.cacheSkSL = false, + this.purgePersistentCache = false, + this.useTestFonts = false, + this.verboseSystemLogs = false, + this.hostVmServicePort, + this.disablePortPublication = false, + this.deviceVmServicePort, + this.ddsPort, + this.devToolsServerAddress, + this.hostname, + this.port, + this.tlsCertPath, + this.tlsCertKeyPath, + this.webEnableExposeUrl, + this.webUseSseForDebugProxy = true, + this.webUseSseForDebugBackend = true, + this.webUseSseForInjectedClient = true, + this.webRunHeadless = false, + this.webBrowserDebugPort, + this.webBrowserFlags = const [], + this.webEnableExpressionEvaluation = false, + this.webHeaders = const {}, + this.webLaunchUrl, + this.vmserviceOutFile, + this.fastStart = false, + this.nullAssertions = false, + this.nativeNullAssertions = false, + this.enableImpeller = ImpellerStatus.platformDefault, + this.enableVulkanValidation = false, + this.uninstallFirst = false, + this.serveObservatory = false, + this.enableDartProfiling = true, + this.enableEmbedderApi = false, + this.usingCISystem = false, + }) : debuggingEnabled = true; + + DebuggingOptions.disabled(this.buildInfo, { + this.dartEntrypointArgs = const [], + this.port, + this.hostname, + this.tlsCertPath, + this.tlsCertKeyPath, + this.webEnableExposeUrl, + this.webUseSseForDebugProxy = true, + this.webUseSseForDebugBackend = true, + this.webUseSseForInjectedClient = true, + this.webRunHeadless = false, + this.webBrowserDebugPort, + this.webBrowserFlags = const [], + this.webLaunchUrl, + this.webHeaders = const {}, + this.cacheSkSL = false, + this.traceAllowlist, + this.enableImpeller = ImpellerStatus.platformDefault, + this.enableVulkanValidation = false, + this.uninstallFirst = false, + this.enableDartProfiling = true, + this.enableEmbedderApi = false, + this.usingCISystem = false, + }) : debuggingEnabled = false, + useTestFonts = false, + startPaused = false, + dartFlags = '', + disableServiceAuthCodes = false, + enableDds = true, + cacheStartupProfile = false, + enableSoftwareRendering = false, + skiaDeterministicRendering = false, + traceSkia = false, + traceSkiaAllowlist = null, + traceSystrace = false, + traceToFile = null, + endlessTraceBuffer = false, + dumpSkpOnShaderCompilation = false, + purgePersistentCache = false, + verboseSystemLogs = false, + hostVmServicePort = null, + disablePortPublication = false, + deviceVmServicePort = null, + ddsPort = null, + devToolsServerAddress = null, + vmserviceOutFile = null, + fastStart = false, + webEnableExpressionEvaluation = false, + nullAssertions = false, + nativeNullAssertions = false, + serveObservatory = false; + + DebuggingOptions._({ + required this.buildInfo, + required this.debuggingEnabled, + required this.startPaused, + required this.dartFlags, + required this.dartEntrypointArgs, + required this.disableServiceAuthCodes, + required this.enableDds, + required this.cacheStartupProfile, + required this.enableSoftwareRendering, + required this.skiaDeterministicRendering, + required this.traceSkia, + required this.traceAllowlist, + required this.traceSkiaAllowlist, + required this.traceSystrace, + required this.traceToFile, + required this.endlessTraceBuffer, + required this.dumpSkpOnShaderCompilation, + required this.cacheSkSL, + required this.purgePersistentCache, + required this.useTestFonts, + required this.verboseSystemLogs, + required this.hostVmServicePort, + required this.deviceVmServicePort, + required this.disablePortPublication, + required this.ddsPort, + required this.devToolsServerAddress, + required this.port, + required this.hostname, + required this.tlsCertPath, + required this.tlsCertKeyPath, + required this.webEnableExposeUrl, + required this.webUseSseForDebugProxy, + required this.webUseSseForDebugBackend, + required this.webUseSseForInjectedClient, + required this.webRunHeadless, + required this.webBrowserDebugPort, + required this.webBrowserFlags, + required this.webEnableExpressionEvaluation, + required this.webHeaders, + required this.webLaunchUrl, + required this.vmserviceOutFile, + required this.fastStart, + required this.nullAssertions, + required this.nativeNullAssertions, + required this.enableImpeller, + required this.enableVulkanValidation, + required this.uninstallFirst, + required this.serveObservatory, + required this.enableDartProfiling, + required this.enableEmbedderApi, + required this.usingCISystem, + }); + + final bool debuggingEnabled; + + final BuildInfo buildInfo; + final bool startPaused; + final String dartFlags; + final List dartEntrypointArgs; + final bool disableServiceAuthCodes; + final bool enableDds; + final bool cacheStartupProfile; + final bool enableSoftwareRendering; + final bool skiaDeterministicRendering; + final bool traceSkia; + final String? traceAllowlist; + final String? traceSkiaAllowlist; + final bool traceSystrace; + final String? traceToFile; + final bool endlessTraceBuffer; + final bool dumpSkpOnShaderCompilation; + final bool cacheSkSL; + final bool purgePersistentCache; + final bool useTestFonts; + final bool verboseSystemLogs; + final int? hostVmServicePort; + final int? deviceVmServicePort; + final bool disablePortPublication; + final int? ddsPort; + final Uri? devToolsServerAddress; + final String? port; + final String? hostname; + final String? tlsCertPath; + final String? tlsCertKeyPath; + final bool? webEnableExposeUrl; + final bool webUseSseForDebugProxy; + final bool webUseSseForDebugBackend; + final bool webUseSseForInjectedClient; + final ImpellerStatus enableImpeller; + final bool enableVulkanValidation; + final bool serveObservatory; + final bool enableDartProfiling; + final bool enableEmbedderApi; + final bool usingCISystem; + + /// Whether the tool should try to uninstall a previously installed version of the app. + /// + /// This is not implemented for every platform. + final bool uninstallFirst; + + /// Whether to run the browser in headless mode. + /// + /// Some CI environments do not provide a display and fail to launch the + /// browser with full graphics stack. Some browsers provide a special + /// "headless" mode that runs the browser with no graphics. + final bool webRunHeadless; + + /// The port the browser should use for its debugging protocol. + final int? webBrowserDebugPort; + + /// Arbitrary browser flags. + final List webBrowserFlags; + + /// Enable expression evaluation for web target. + final bool webEnableExpressionEvaluation; + + /// Allow developers to customize the browser's launch URL + final String? webLaunchUrl; + + /// Allow developers to add custom headers to web server + final Map webHeaders; + + /// A file where the VM Service URL should be written after the application is started. + final String? vmserviceOutFile; + final bool fastStart; + + final bool nullAssertions; + + /// Additional null runtime checks inserted for web applications. + /// + /// See also: + /// * https://github.com/dart-lang/sdk/blob/main/sdk/lib/html/doc/NATIVE_NULL_ASSERTIONS.md + final bool nativeNullAssertions; + + List getIOSLaunchArguments( + EnvironmentType environmentType, + String? route, + Map platformArgs, { + bool ipv6 = false, + DeviceConnectionInterface interfaceType = DeviceConnectionInterface.attached, + bool isCoreDevice = false, + }) { + final String dartVmFlags = computeDartVmFlags(this); + return [ + if (enableDartProfiling) '--enable-dart-profiling', + if (disableServiceAuthCodes) '--disable-service-auth-codes', + if (disablePortPublication) '--disable-vm-service-publication', + if (startPaused) '--start-paused', + // Wrap dart flags in quotes for physical devices + if (environmentType == EnvironmentType.physical && dartVmFlags.isNotEmpty) + '--dart-flags="$dartVmFlags"', + if (environmentType == EnvironmentType.simulator && dartVmFlags.isNotEmpty) + '--dart-flags=$dartVmFlags', + if (useTestFonts) '--use-test-fonts', + // Core Devices (iOS 17 devices) are debugged through Xcode so don't + // include these flags, which are used to check if the app was launched + // via Flutter CLI and `ios-deploy`. + if (debuggingEnabled && !isCoreDevice) ...[ + '--enable-checked-mode', + '--verify-entry-points', + ], + if (enableSoftwareRendering) '--enable-software-rendering', + if (traceSystrace) '--trace-systrace', + if (traceToFile != null) '--trace-to-file="$traceToFile"', + if (skiaDeterministicRendering) '--skia-deterministic-rendering', + if (traceSkia) '--trace-skia', + if (traceAllowlist != null) '--trace-allowlist="$traceAllowlist"', + if (traceSkiaAllowlist != null) '--trace-skia-allowlist="$traceSkiaAllowlist"', + if (endlessTraceBuffer) '--endless-trace-buffer', + if (dumpSkpOnShaderCompilation) '--dump-skp-on-shader-compilation', + if (verboseSystemLogs) '--verbose-logging', + if (cacheSkSL) '--cache-sksl', + if (purgePersistentCache) '--purge-persistent-cache', + if (route != null) '--route=$route', + if (platformArgs['trace-startup'] as bool? ?? false) '--trace-startup', + if (enableImpeller == ImpellerStatus.enabled) '--enable-impeller=true', + if (enableImpeller == ImpellerStatus.disabled) '--enable-impeller=false', + if (environmentType == EnvironmentType.physical && deviceVmServicePort != null) + '--vm-service-port=$deviceVmServicePort', + // The simulator "device" is actually on the host machine so no ports will be forwarded. + // Use the suggested host port. + if (environmentType == EnvironmentType.simulator && hostVmServicePort != null) + '--vm-service-port=$hostVmServicePort', + // Tell the VM service to listen on all interfaces, don't restrict to the loopback. + if (interfaceType == DeviceConnectionInterface.wireless) + '--vm-service-host=${ipv6 ? '::0' : '0.0.0.0'}', + if (enableEmbedderApi) '--enable-embedder-api', + ]; + } + + Map toJson() => { + 'debuggingEnabled': debuggingEnabled, + 'startPaused': startPaused, + 'dartFlags': dartFlags, + 'dartEntrypointArgs': dartEntrypointArgs, + 'disableServiceAuthCodes': disableServiceAuthCodes, + 'enableDds': enableDds, + 'cacheStartupProfile': cacheStartupProfile, + 'enableSoftwareRendering': enableSoftwareRendering, + 'skiaDeterministicRendering': skiaDeterministicRendering, + 'traceSkia': traceSkia, + 'traceAllowlist': traceAllowlist, + 'traceSkiaAllowlist': traceSkiaAllowlist, + 'traceSystrace': traceSystrace, + 'traceToFile': traceToFile, + 'endlessTraceBuffer': endlessTraceBuffer, + 'dumpSkpOnShaderCompilation': dumpSkpOnShaderCompilation, + 'cacheSkSL': cacheSkSL, + 'purgePersistentCache': purgePersistentCache, + 'useTestFonts': useTestFonts, + 'verboseSystemLogs': verboseSystemLogs, + 'hostVmServicePort': hostVmServicePort, + 'deviceVmServicePort': deviceVmServicePort, + 'disablePortPublication': disablePortPublication, + 'ddsPort': ddsPort, + 'devToolsServerAddress': devToolsServerAddress.toString(), + 'port': port, + 'hostname': hostname, + 'tlsCertPath': tlsCertPath, + 'tlsCertKeyPath': tlsCertKeyPath, + 'webEnableExposeUrl': webEnableExposeUrl, + 'webUseSseForDebugProxy': webUseSseForDebugProxy, + 'webUseSseForDebugBackend': webUseSseForDebugBackend, + 'webUseSseForInjectedClient': webUseSseForInjectedClient, + 'webRunHeadless': webRunHeadless, + 'webBrowserDebugPort': webBrowserDebugPort, + 'webBrowserFlags': webBrowserFlags, + 'webEnableExpressionEvaluation': webEnableExpressionEvaluation, + 'webLaunchUrl': webLaunchUrl, + 'webHeaders': webHeaders, + 'vmserviceOutFile': vmserviceOutFile, + 'fastStart': fastStart, + 'nullAssertions': nullAssertions, + 'nativeNullAssertions': nativeNullAssertions, + 'enableImpeller': enableImpeller.asBool, + 'enableVulkanValidation': enableVulkanValidation, + 'serveObservatory': serveObservatory, + 'enableDartProfiling': enableDartProfiling, + 'enableEmbedderApi': enableEmbedderApi, + 'usingCISystem': usingCISystem, + }; + + static DebuggingOptions fromJson(Map json, BuildInfo buildInfo) => + DebuggingOptions._( + buildInfo: buildInfo, + debuggingEnabled: json['debuggingEnabled']! as bool, + startPaused: json['startPaused']! as bool, + dartFlags: json['dartFlags']! as String, + dartEntrypointArgs: (json['dartEntrypointArgs']! as List).cast(), + disableServiceAuthCodes: json['disableServiceAuthCodes']! as bool, + enableDds: json['enableDds']! as bool, + cacheStartupProfile: json['cacheStartupProfile']! as bool, + enableSoftwareRendering: json['enableSoftwareRendering']! as bool, + skiaDeterministicRendering: json['skiaDeterministicRendering']! as bool, + traceSkia: json['traceSkia']! as bool, + traceAllowlist: json['traceAllowlist'] as String?, + traceSkiaAllowlist: json['traceSkiaAllowlist'] as String?, + traceSystrace: json['traceSystrace']! as bool, + traceToFile: json['traceToFile'] as String?, + endlessTraceBuffer: json['endlessTraceBuffer']! as bool, + dumpSkpOnShaderCompilation: json['dumpSkpOnShaderCompilation']! as bool, + cacheSkSL: json['cacheSkSL']! as bool, + purgePersistentCache: json['purgePersistentCache']! as bool, + useTestFonts: json['useTestFonts']! as bool, + verboseSystemLogs: json['verboseSystemLogs']! as bool, + hostVmServicePort: json['hostVmServicePort'] as int? , + deviceVmServicePort: json['deviceVmServicePort'] as int?, + disablePortPublication: json['disablePortPublication']! as bool, + ddsPort: json['ddsPort'] as int?, + devToolsServerAddress: json['devToolsServerAddress'] != null ? Uri.parse(json['devToolsServerAddress']! as String) : null, + port: json['port'] as String?, + hostname: json['hostname'] as String?, + tlsCertPath: json['tlsCertPath'] as String?, + tlsCertKeyPath: json['tlsCertKeyPath'] as String?, + webEnableExposeUrl: json['webEnableExposeUrl'] as bool?, + webUseSseForDebugProxy: json['webUseSseForDebugProxy']! as bool, + webUseSseForDebugBackend: json['webUseSseForDebugBackend']! as bool, + webUseSseForInjectedClient: json['webUseSseForInjectedClient']! as bool, + webRunHeadless: json['webRunHeadless']! as bool, + webBrowserDebugPort: json['webBrowserDebugPort'] as int?, + webBrowserFlags: (json['webBrowserFlags']! as List).cast(), + webEnableExpressionEvaluation: json['webEnableExpressionEvaluation']! as bool, + webHeaders: (json['webHeaders']! as Map).cast(), + webLaunchUrl: json['webLaunchUrl'] as String?, + vmserviceOutFile: json['vmserviceOutFile'] as String?, + fastStart: json['fastStart']! as bool, + nullAssertions: json['nullAssertions']! as bool, + nativeNullAssertions: json['nativeNullAssertions']! as bool, + enableImpeller: ImpellerStatus.fromBool(json['enableImpeller'] as bool?), + enableVulkanValidation: (json['enableVulkanValidation'] as bool?) ?? false, + uninstallFirst: (json['uninstallFirst'] as bool?) ?? false, + serveObservatory: (json['serveObservatory'] as bool?) ?? false, + enableDartProfiling: (json['enableDartProfiling'] as bool?) ?? true, + enableEmbedderApi: (json['enableEmbedderApi'] as bool?) ?? false, + usingCISystem: (json['usingCISystem'] as bool?) ?? false, + ); +} + +class LaunchResult { + LaunchResult.succeeded({ Uri? vmServiceUri, Uri? observatoryUri }) : + started = true, + vmServiceUri = vmServiceUri ?? observatoryUri; + + LaunchResult.failed() + : started = false, + vmServiceUri = null; + + bool get hasVmService => vmServiceUri != null; + + final bool started; + final Uri? vmServiceUri; + + @override + String toString() { + final StringBuffer buf = StringBuffer('started=$started'); + if (vmServiceUri != null) { + buf.write(', vmService=$vmServiceUri'); + } + return buf.toString(); + } +} + +/// Read the log for a particular device. +abstract class DeviceLogReader { + String get name; + + /// A broadcast stream where each element in the string is a line of log output. + Stream get logLines; + + /// Some logs can be obtained from a VM service stream. + /// Set this after the VM services are connected. + FlutterVmService? connectedVMService; + + @override + String toString() => name; + + /// Process ID of the app on the device. + int? appPid; + + // Clean up resources allocated by log reader e.g. subprocesses + void dispose(); +} + +/// Describes an app running on the device. +class DiscoveredApp { + DiscoveredApp(this.id, this.vmServicePort); + final String id; + final int vmServicePort; +} + +// An empty device log reader +class NoOpDeviceLogReader implements DeviceLogReader { + NoOpDeviceLogReader(String? nameOrNull) : name = nameOrNull ?? ''; + + @override + final String name; + + @override + int? appPid; + + @override + FlutterVmService? connectedVMService; + + @override + Stream get logLines => const Stream.empty(); + + @override + void dispose() { } +} + +/// Append --null_assertions to any existing Dart VM flags if +/// [debuggingOptions.nullAssertions] is true. +String computeDartVmFlags(DebuggingOptions debuggingOptions) { + return [ + if (debuggingOptions.dartFlags.isNotEmpty) + debuggingOptions.dartFlags, + if (debuggingOptions.nullAssertions) + '--null_assertions', + ].join(','); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/device_port_forwarder.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/device_port_forwarder.dart new file mode 100644 index 0000000000000000000000000000000000000000..36725deffd79e11831f7d90f5c0a2a18134c562f --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/device_port_forwarder.dart @@ -0,0 +1,61 @@ +// 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 'base/io.dart'; + +class ForwardedPort { + ForwardedPort(this.hostPort, this.devicePort) : context = null; + ForwardedPort.withContext(this.hostPort, this.devicePort, this.context); + + final int hostPort; + final int devicePort; + final Process? context; + + @override + String toString() => 'ForwardedPort HOST:$hostPort to DEVICE:$devicePort'; + + /// Kill subprocess (if present) used in forwarding. + void dispose() { + if (context != null) { + context!.kill(); + } + } +} + +/// Forward ports from the host machine to the device. +abstract class DevicePortForwarder { + /// Returns a Future that completes with the current list of forwarded + /// ports for this device. + List get forwardedPorts; + + /// Forward [hostPort] on the host to [devicePort] on the device. + /// If [hostPort] is null or zero, will auto select a host port. + /// Returns a Future that completes with the host port. + Future forward(int devicePort, { int? hostPort }); + + /// Stops forwarding [forwardedPort]. + Future unforward(ForwardedPort forwardedPort); + + /// Cleanup allocated resources, like [forwardedPorts]. + Future dispose(); +} + +// A port forwarder which does not support forwarding ports. +class NoOpDevicePortForwarder implements DevicePortForwarder { + const NoOpDevicePortForwarder(); + + @override + Future forward(int devicePort, { int? hostPort }) async => devicePort; + + @override + List get forwardedPorts => []; + + @override + Future unforward(ForwardedPort forwardedPort) async { } + + @override + Future dispose() async { } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/device_vm_service_discovery_for_attach.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/device_vm_service_discovery_for_attach.dart new file mode 100644 index 0000000000000000000000000000000000000000..5b4920b377596819c0c21c720c50fa069e4ccd10 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/device_vm_service_discovery_for_attach.dart @@ -0,0 +1,110 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:async/async.dart'; + +import 'base/logger.dart'; +import 'device.dart'; +import 'device_port_forwarder.dart'; +import 'mdns_discovery.dart'; +import 'protocol_discovery.dart'; + +/// Discovers the VM service uri on a device, and forwards the port to the host. +/// +/// This is mainly used during a `flutter attach`. +abstract class VMServiceDiscoveryForAttach { + VMServiceDiscoveryForAttach(); + + /// The discovered VM service URis. + /// + /// Port forwarding is only attempted when this is invoked, for each VM + /// Service URI in the stream. + Stream get uris; +} + +/// An implementation of [VMServiceDiscoveryForAttach] that uses log scanning +/// for the discovery. +class LogScanningVMServiceDiscoveryForAttach extends VMServiceDiscoveryForAttach { + LogScanningVMServiceDiscoveryForAttach( + Future logReader, { + DevicePortForwarder? portForwarder, + int? hostPort, + int? devicePort, + required bool ipv6, + required Logger logger, + }) { + _protocolDiscovery = (() async => ProtocolDiscovery.vmService( + await logReader, + portForwarder: portForwarder, + ipv6: ipv6, + devicePort: devicePort, + hostPort: hostPort, + logger: logger, + ))(); + } + + late final Future _protocolDiscovery; + + @override + Stream get uris { + final StreamController controller = StreamController(); + _protocolDiscovery.then( + (ProtocolDiscovery protocolDiscovery) async { + await controller.addStream(protocolDiscovery.uris); + await controller.close(); + }, + onError: (Object error) => controller.addError(error), + ); + return controller.stream; + } +} + +/// An implementation of [VMServiceDiscoveryForAttach] that uses mdns for the +/// discovery. +class MdnsVMServiceDiscoveryForAttach extends VMServiceDiscoveryForAttach { + MdnsVMServiceDiscoveryForAttach({ + required this.device, + this.appId, + required this.usesIpv6, + required this.useDeviceIPAsHost, + this.deviceVmservicePort, + this.hostVmservicePort, + }); + + final Device device; + final String? appId; + final bool usesIpv6; + final bool useDeviceIPAsHost; + final int? deviceVmservicePort; + final int? hostVmservicePort; + + @override + Stream get uris { + final Future mDNSDiscoveryFuture = MDnsVmServiceDiscovery.instance!.getVMServiceUriForAttach( + appId, + device, + usesIpv6: usesIpv6, + useDeviceIPAsHost: useDeviceIPAsHost, + deviceVmservicePort: deviceVmservicePort, + hostVmservicePort: hostVmservicePort, + ); + + return Stream.fromFuture(mDNSDiscoveryFuture).where((Uri? uri) => uri != null).cast().asBroadcastStream(); + } +} + +/// An implementation of [VMServiceDiscoveryForAttach] that delegates to other +/// [VMServiceDiscoveryForAttach] instances for discovery. +class DelegateVMServiceDiscoveryForAttach extends VMServiceDiscoveryForAttach { + DelegateVMServiceDiscoveryForAttach(this.delegates); + + final List delegates; + + @override + Stream get uris => + StreamGroup.merge( + delegates.map((VMServiceDiscoveryForAttach delegate) => delegate.uris)); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/devtools_launcher.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/devtools_launcher.dart new file mode 100644 index 0000000000000000000000000000000000000000..25811c73a76cf11a10b4d7a9cfc90b7bf9fa93a0 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/devtools_launcher.dart @@ -0,0 +1,111 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + + + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import 'base/bot_detector.dart'; +import 'base/common.dart'; +import 'base/io.dart' as io; +import 'base/logger.dart'; +import 'convert.dart'; +import 'resident_runner.dart'; + +/// An implementation of the devtools launcher that uses `pub global activate` to +/// start a server instance. +class DevtoolsServerLauncher extends DevtoolsLauncher { + DevtoolsServerLauncher({ + required ProcessManager processManager, + required String dartExecutable, + required Logger logger, + required BotDetector botDetector, + }) : _processManager = processManager, + _dartExecutable = dartExecutable, + _logger = logger, + _botDetector = botDetector; + + final ProcessManager _processManager; + final String _dartExecutable; + final Logger _logger; + final BotDetector _botDetector; + final Completer _processStartCompleter = Completer(); + + io.Process? _devToolsProcess; + bool _devToolsProcessKilled = false; + @visibleForTesting + Future? devToolsProcessExit; + + static final RegExp _serveDevToolsPattern = + RegExp(r'Serving DevTools at ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+?)\.?$'); + + @override + Future get processStart => _processStartCompleter.future; + + @override + Future launch(Uri? vmServiceUri, {List? additionalArguments}) async { + // Place this entire method in a try/catch that swallows exceptions because + // this method is guaranteed not to return a Future that throws. + try { + _devToolsProcess = await _processManager.start([ + _dartExecutable, + 'devtools', + '--no-launch-browser', + if (vmServiceUri != null) '--vm-uri=$vmServiceUri', + ...?additionalArguments, + ]); + _processStartCompleter.complete(); + final Completer completer = Completer(); + _devToolsProcess!.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen((String line) { + final Match? match = _serveDevToolsPattern.firstMatch(line); + if (match != null) { + final String url = match[1]!; + completer.complete(Uri.parse(url)); + } + }); + _devToolsProcess!.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(_logger.printError); + + final bool runningOnBot = await _botDetector.isRunningOnBot; + devToolsProcessExit = _devToolsProcess!.exitCode.then( + (int exitCode) { + if (!_devToolsProcessKilled && runningOnBot) { + throwToolExit('DevTools process failed: exitCode=$exitCode'); + } + } + ); + + devToolsUrl = await completer.future; + } on Exception catch (e, st) { + _logger.printError('Failed to launch DevTools: $e', stackTrace: st); + } + } + + @override + Future serve() async { + if (activeDevToolsServer == null) { + await launch(null); + } + return activeDevToolsServer; + } + + @override + Future close() async { + if (devToolsUrl != null) { + devToolsUrl = null; + } + if (_devToolsProcess != null) { + _devToolsProcessKilled = true; + _devToolsProcess!.kill(); + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/doctor.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/doctor.dart new file mode 100644 index 0000000000000000000000000000000000000000..01ea9f727a9b56ec755a9409cf1518188a2f85dc --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/doctor.dart @@ -0,0 +1,806 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; +import 'package:unified_analytics/unified_analytics.dart'; + +import 'android/android_studio_validator.dart'; +import 'android/android_workflow.dart'; +import 'artifacts.dart'; +import 'base/async_guard.dart'; +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/net.dart'; +import 'base/os.dart'; +import 'base/platform.dart'; +import 'base/terminal.dart'; +import 'base/time.dart'; +import 'base/user_messages.dart'; +import 'base/utils.dart'; +import 'cache.dart'; +import 'custom_devices/custom_device_workflow.dart'; +import 'device.dart'; +import 'doctor_validator.dart'; +import 'features.dart'; +import 'fuchsia/fuchsia_workflow.dart'; +import 'globals.dart' as globals; +import 'http_host_validator.dart'; +import 'intellij/intellij_validator.dart'; +import 'linux/linux_doctor.dart'; +import 'linux/linux_workflow.dart'; +import 'macos/macos_workflow.dart'; +import 'macos/xcode_validator.dart'; +import 'proxy_validator.dart'; +import 'reporting/reporting.dart'; +import 'tester/flutter_tester.dart'; +import 'version.dart'; +import 'vscode/vscode_validator.dart'; +import 'web/chrome.dart'; +import 'web/web_validator.dart'; +import 'web/workflow.dart'; +import 'windows/visual_studio_validator.dart'; +import 'windows/windows_version_validator.dart'; +import 'windows/windows_workflow.dart'; + +abstract class DoctorValidatorsProvider { + // Allow tests to construct a [_DefaultDoctorValidatorsProvider] with explicit + // [FeatureFlags]. + factory DoctorValidatorsProvider.test({ + Platform? platform, + Logger? logger, + required FeatureFlags featureFlags, + }) { + return _DefaultDoctorValidatorsProvider( + featureFlags: featureFlags, + platform: platform ?? FakePlatform(), + logger: logger ?? BufferLogger.test(), + ); + } + /// The singleton instance, pulled from the [AppContext]. + static DoctorValidatorsProvider get _instance => context.get()!; + + static final DoctorValidatorsProvider defaultInstance = _DefaultDoctorValidatorsProvider( + logger: globals.logger, + platform: globals.platform, + featureFlags: featureFlags, + ); + + List get validators; + List get workflows; +} + +class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider { + _DefaultDoctorValidatorsProvider({ + required this.platform, + required this.featureFlags, + required Logger logger, + }) : _logger = logger; + + List? _validators; + List? _workflows; + final Platform platform; + final FeatureFlags featureFlags; + final Logger _logger; + + late final LinuxWorkflow linuxWorkflow = LinuxWorkflow( + platform: platform, + featureFlags: featureFlags, + ); + + late final WebWorkflow webWorkflow = WebWorkflow( + platform: platform, + featureFlags: featureFlags, + ); + + late final MacOSWorkflow macOSWorkflow = MacOSWorkflow( + platform: platform, + featureFlags: featureFlags, + ); + + late final CustomDeviceWorkflow customDeviceWorkflow = CustomDeviceWorkflow( + featureFlags: featureFlags, + ); + + @override + List get validators { + if (_validators != null) { + return _validators!; + } + + final List ideValidators = [ + if (androidWorkflow!.appliesToHostPlatform) + ...AndroidStudioValidator.allValidators(globals.config, platform, globals.fs, globals.userMessages), + ...IntelliJValidator.installedValidators( + fileSystem: globals.fs, + platform: platform, + userMessages: userMessages, + plistParser: globals.plistParser, + processManager: globals.processManager, + logger: _logger, + ), + ...VsCodeValidator.installedValidators(globals.fs, platform, globals.processManager), + ]; + final ProxyValidator proxyValidator = ProxyValidator(platform: platform); + _validators = [ + FlutterValidator( + fileSystem: globals.fs, + platform: globals.platform, + flutterVersion: () => globals.flutterVersion.fetchTagsAndGetVersion(clock: globals.systemClock), + devToolsVersion: () => globals.cache.devToolsVersion, + processManager: globals.processManager, + userMessages: userMessages, + artifacts: globals.artifacts!, + flutterRoot: () => Cache.flutterRoot!, + operatingSystemUtils: globals.os, + ), + if (platform.isWindows) + WindowsVersionValidator( + operatingSystemUtils: globals.os, + ), + if (androidWorkflow!.appliesToHostPlatform) + GroupedValidator([androidValidator!, androidLicenseValidator!]), + if (globals.iosWorkflow!.appliesToHostPlatform || macOSWorkflow.appliesToHostPlatform) + GroupedValidator([ + XcodeValidator( + xcode: globals.xcode!, + userMessages: userMessages, + iosSimulatorUtils: globals.iosSimulatorUtils!, + ), + globals.cocoapodsValidator!, + ]), + if (webWorkflow.appliesToHostPlatform) + ChromeValidator( + chromiumLauncher: ChromiumLauncher( + browserFinder: findChromeExecutable, + fileSystem: globals.fs, + operatingSystemUtils: globals.os, + platform: globals.platform, + processManager: globals.processManager, + logger: globals.logger, + ), + platform: globals.platform, + ), + if (linuxWorkflow.appliesToHostPlatform) + LinuxDoctorValidator( + processManager: globals.processManager, + userMessages: userMessages, + ), + if (windowsWorkflow!.appliesToHostPlatform) + visualStudioValidator!, + if (ideValidators.isNotEmpty) + ...ideValidators + else + NoIdeValidator(), + if (proxyValidator.shouldShow) + proxyValidator, + if (globals.deviceManager?.canListAnything ?? false) + DeviceValidator( + deviceManager: globals.deviceManager, + userMessages: globals.userMessages, + ), + HttpHostValidator( + platform: globals.platform, + featureFlags: featureFlags, + httpClient: globals.httpClientFactory?.call() ?? HttpClient(), + ), + ]; + return _validators!; + } + + @override + List get workflows { + if (_workflows == null) { + _workflows = []; + + if (globals.iosWorkflow!.appliesToHostPlatform) { + _workflows!.add(globals.iosWorkflow!); + } + + if (androidWorkflow?.appliesToHostPlatform ?? false) { + _workflows!.add(androidWorkflow!); + } + + if (fuchsiaWorkflow?.appliesToHostPlatform ?? false) { + _workflows!.add(fuchsiaWorkflow!); + } + + if (linuxWorkflow.appliesToHostPlatform) { + _workflows!.add(linuxWorkflow); + } + + if (macOSWorkflow.appliesToHostPlatform) { + _workflows!.add(macOSWorkflow); + } + + if (windowsWorkflow?.appliesToHostPlatform ?? false) { + _workflows!.add(windowsWorkflow!); + } + + if (webWorkflow.appliesToHostPlatform) { + _workflows!.add(webWorkflow); + } + + if (customDeviceWorkflow.appliesToHostPlatform) { + _workflows!.add(customDeviceWorkflow); + } + } + return _workflows!; + } +} + +class Doctor { + Doctor({ + required Logger logger, + required SystemClock clock, + Analytics? analytics, + }) : _logger = logger, + _clock = clock, + _analytics = analytics ?? globals.analytics; + + final Logger _logger; + final SystemClock _clock; + final Analytics _analytics; + + List get validators { + return DoctorValidatorsProvider._instance.validators; + } + + /// Return a list of [ValidatorTask] objects and starts validation on all + /// objects in [validators]. + List startValidatorTasks() => [ + for (final DoctorValidator validator in validators) + ValidatorTask( + validator, + // We use an asyncGuard() here to be absolutely certain that + // DoctorValidators do not result in an uncaught exception. Since the + // Future returned by the asyncGuard() is not awaited, we pass an + // onError callback to it and translate errors into ValidationResults. + asyncGuard( + () { + final Completer timeoutCompleter = Completer(); + final Timer timer = Timer(doctorDuration, () { + timeoutCompleter.completeError( + Exception('${validator.title} exceeded maximum allowed duration of $doctorDuration'), + ); + }); + final Future validatorFuture = validator.validate(); + return Future.any(>[ + validatorFuture, + // This future can only complete with an error + timeoutCompleter.future, + ]).then((ValidationResult result) async { + timer.cancel(); + return result; + }); + }, + onError: (Object exception, StackTrace stackTrace) { + return ValidationResult.crash(exception, stackTrace); + }, + ), + ), + ]; + + List get workflows { + return DoctorValidatorsProvider._instance.workflows; + } + + /// Print a summary of the state of the tooling, as well as how to get more info. + Future summary() async { + _logger.printStatus(await _summaryText()); + } + + Future _summaryText() async { + final StringBuffer buffer = StringBuffer(); + + bool missingComponent = false; + bool sawACrash = false; + + for (final DoctorValidator validator in validators) { + final StringBuffer lineBuffer = StringBuffer(); + ValidationResult result; + try { + result = await asyncGuard(() => validator.validate()); + } on Exception catch (exception) { + // We're generating a summary, so drop the stack trace. + result = ValidationResult.crash(exception); + } + lineBuffer.write('${result.coloredLeadingBox} ${validator.title}: '); + switch (result.type) { + case ValidationType.crash: + lineBuffer.write('the doctor check crashed without a result.'); + sawACrash = true; + case ValidationType.missing: + lineBuffer.write('is not installed.'); + case ValidationType.partial: + lineBuffer.write('is partially installed; more components are available.'); + case ValidationType.notAvailable: + lineBuffer.write('is not available.'); + case ValidationType.success: + lineBuffer.write('is fully installed.'); + } + + if (result.statusInfo != null) { + lineBuffer.write(' (${result.statusInfo})'); + } + + buffer.write(wrapText( + lineBuffer.toString(), + hangingIndent: result.leadingBox.length + 1, + columnWidth: globals.outputPreferences.wrapColumn, + shouldWrap: globals.outputPreferences.wrapText, + )); + buffer.writeln(); + + if (result.type != ValidationType.success) { + missingComponent = true; + } + } + + if (sawACrash) { + buffer.writeln(); + buffer.writeln('Run "flutter doctor" for information about why a doctor check crashed.'); + } + + if (missingComponent) { + buffer.writeln(); + buffer.writeln('Run "flutter doctor" for information about installing additional components.'); + } + + return buffer.toString(); + } + + Future checkRemoteArtifacts(String engineRevision) async { + return globals.cache.areRemoteArtifactsAvailable(engineVersion: engineRevision); + } + + /// Maximum allowed duration for an entire validator to take. + /// + /// This should only ever be reached if a process is stuck. + // Reduce this to under 5 minutes to diagnose: + // https://github.com/flutter/flutter/issues/111686 + static const Duration doctorDuration = Duration(minutes: 4, seconds: 30); + + /// Print information about the state of installed tooling. + /// + /// To exclude personally identifiable information like device names and + /// paths, set [showPii] to false. + Future diagnose({ + bool androidLicenses = false, + bool verbose = true, + AndroidLicenseValidator? androidLicenseValidator, + bool showPii = true, + List? startedValidatorTasks, + bool sendEvent = true, + }) async { + final bool showColor = globals.terminal.supportsColor; + if (androidLicenses && androidLicenseValidator != null) { + return androidLicenseValidator.runLicenseManager(); + } + + if (!verbose) { + _logger.printStatus('Doctor summary (to see all details, run flutter doctor -v):'); + } + bool doctorResult = true; + int issues = 0; + + // This timestamp will be used on the backend of GA4 to group each of the events that + // were sent for each doctor validator and its result + final int analyticsTimestamp = _clock.now().millisecondsSinceEpoch; + + for (final ValidatorTask validatorTask in startedValidatorTasks ?? startValidatorTasks()) { + final DoctorValidator validator = validatorTask.validator; + final Status status = _logger.startSpinner( + timeout: validator.slowWarningDuration, + slowWarningCallback: () => validator.slowWarning, + ); + ValidationResult result; + try { + result = await validatorTask.result; + status.stop(); + } on Exception catch (exception, stackTrace) { + result = ValidationResult.crash(exception, stackTrace); + status.cancel(); + } + + switch (result.type) { + case ValidationType.crash: + doctorResult = false; + issues += 1; + case ValidationType.missing: + doctorResult = false; + issues += 1; + case ValidationType.partial: + case ValidationType.notAvailable: + issues += 1; + case ValidationType.success: + break; + } + if (sendEvent) { + if (validator is GroupedValidator) { + for (int i = 0; i < validator.subValidators.length; i++) { + final DoctorValidator subValidator = validator.subValidators[i]; + + // Ensure that all of the subvalidators in the group have + // a corresponding subresult incase a validator crashed + final ValidationResult subResult; + try { + subResult = validator.subResults[i]; + } on RangeError { + continue; + } + + _analytics.send(Event.doctorValidatorResult( + validatorName: subValidator.title, + result: subResult.typeStr, + statusInfo: subResult.statusInfo, + partOfGroupedValidator: true, + doctorInvocationId: analyticsTimestamp, + )); + } + } else { + _analytics.send(Event.doctorValidatorResult( + validatorName: validator.title, + result: result.typeStr, + statusInfo: result.statusInfo, + partOfGroupedValidator: false, + doctorInvocationId: analyticsTimestamp, + )); + } + // TODO(eliasyishak): remove this after migrating from package:usage + DoctorResultEvent(validator: validator, result: result).send(); + } + + final String leadingBox = showColor ? result.coloredLeadingBox : result.leadingBox; + if (result.statusInfo != null) { + _logger.printStatus('$leadingBox ${validator.title} (${result.statusInfo})', + hangingIndent: result.leadingBox.length + 1); + } else { + _logger.printStatus('$leadingBox ${validator.title}', + hangingIndent: result.leadingBox.length + 1); + } + + for (final ValidationMessage message in result.messages) { + if (!message.isInformation || verbose) { + int hangingIndent = 2; + int indent = 4; + final String indicator = showColor ? message.coloredIndicator : message.indicator; + for (final String line in '$indicator ${showPii ? message.message : message.piiStrippedMessage}'.split('\n')) { + _logger.printStatus(line, hangingIndent: hangingIndent, indent: indent, emphasis: true); + // Only do hanging indent for the first line. + hangingIndent = 0; + indent = 6; + } + if (message.contextUrl != null) { + _logger.printStatus('🔨 ${message.contextUrl}', hangingIndent: hangingIndent, indent: indent, emphasis: true); + } + } + } + if (verbose) { + _logger.printStatus(''); + } + } + + // Make sure there's always one line before the summary even when not verbose. + if (!verbose) { + _logger.printStatus(''); + } + + if (issues > 0) { + _logger.printStatus('${showColor ? globals.terminal.color('!', TerminalColor.yellow) : '!'}' + ' Doctor found issues in $issues categor${issues > 1 ? "ies" : "y"}.', hangingIndent: 2); + } else { + _logger.printStatus('${showColor ? globals.terminal.color('•', TerminalColor.green) : '•'}' + ' No issues found!', hangingIndent: 2); + } + + return doctorResult; + } + + bool get canListAnything => workflows.any((Workflow workflow) => workflow.canListDevices); + + bool get canLaunchAnything { + if (FlutterTesterDevices.showFlutterTesterDevice) { + return true; + } + return workflows.any((Workflow workflow) => workflow.canLaunchDevices); + } +} + +/// A validator that checks the version of Flutter, as well as some auxiliary information +/// such as the pub or Flutter cache overrides. +/// +/// This is primarily useful for diagnosing issues on Github bug reports by displaying +/// specific commit information. +class FlutterValidator extends DoctorValidator { + FlutterValidator({ + required Platform platform, + required FlutterVersion Function() flutterVersion, + required String Function() devToolsVersion, + required UserMessages userMessages, + required FileSystem fileSystem, + required Artifacts artifacts, + required ProcessManager processManager, + required String Function() flutterRoot, + required OperatingSystemUtils operatingSystemUtils, + }) : _flutterVersion = flutterVersion, + _devToolsVersion = devToolsVersion, + _platform = platform, + _userMessages = userMessages, + _fileSystem = fileSystem, + _artifacts = artifacts, + _processManager = processManager, + _flutterRoot = flutterRoot, + _operatingSystemUtils = operatingSystemUtils, + super('Flutter'); + + final Platform _platform; + final FlutterVersion Function() _flutterVersion; + final String Function() _devToolsVersion; + final String Function() _flutterRoot; + final UserMessages _userMessages; + final FileSystem _fileSystem; + final Artifacts _artifacts; + final ProcessManager _processManager; + final OperatingSystemUtils _operatingSystemUtils; + + @override + Future validate() async { + final List messages = []; + String? versionChannel; + String? frameworkVersion; + + try { + final FlutterVersion version = _flutterVersion(); + final String? gitUrl = _platform.environment['FLUTTER_GIT_URL']; + versionChannel = version.channel; + frameworkVersion = version.frameworkVersion; + + final String flutterRoot = _flutterRoot(); + messages.add(_getFlutterVersionMessage(frameworkVersion, versionChannel, flutterRoot)); + + _validateRequiredBinaries(flutterRoot).forEach(messages.add); + messages.add(_getFlutterUpstreamMessage(version)); + if (gitUrl != null) { + messages.add(ValidationMessage(_userMessages.flutterGitUrl(gitUrl))); + } + messages.add(ValidationMessage(_userMessages.flutterRevision( + version.frameworkRevisionShort, + version.frameworkAge, + version.frameworkCommitDate, + ))); + messages.add(ValidationMessage(_userMessages.engineRevision(version.engineRevisionShort))); + messages.add(ValidationMessage(_userMessages.dartRevision(version.dartSdkVersion))); + messages.add(ValidationMessage(_userMessages.devToolsVersion(_devToolsVersion()))); + final String? pubUrl = _platform.environment[kPubDevOverride]; + if (pubUrl != null) { + messages.add(ValidationMessage(_userMessages.pubMirrorURL(pubUrl))); + } + final String? storageBaseUrl = _platform.environment[kFlutterStorageBaseUrl]; + if (storageBaseUrl != null) { + messages.add(ValidationMessage(_userMessages.flutterMirrorURL(storageBaseUrl))); + } + } on VersionCheckError catch (e) { + messages.add(ValidationMessage.error(e.message)); + } + + // Check that the binaries we downloaded for this platform actually run on it. + // If the binaries are not downloaded (because android is not enabled), then do + // not run this check. + final String genSnapshotPath = _artifacts.getArtifactPath(Artifact.genSnapshot); + if (_fileSystem.file(genSnapshotPath).existsSync() && !_genSnapshotRuns(genSnapshotPath)) { + final StringBuffer buffer = StringBuffer(); + buffer.writeln(_userMessages.flutterBinariesDoNotRun); + if (_platform.isLinux) { + buffer.writeln(_userMessages.flutterBinariesLinuxRepairCommands); + } else if (_platform.isMacOS && _operatingSystemUtils.hostPlatform == HostPlatform.darwin_arm64) { + buffer.writeln('Flutter requires the Rosetta translation environment on ARM Macs. Try running:'); + buffer.writeln(' sudo softwareupdate --install-rosetta --agree-to-license'); + } + messages.add(ValidationMessage.error(buffer.toString())); + } + + ValidationType valid; + if (messages.every((ValidationMessage message) => message.isInformation)) { + valid = ValidationType.success; + } else { + // The issues for this validator stem from broken git configuration of the local install; + // in that case, make it clear that it is fine to continue, but freshness check/upgrades + // won't be supported. + valid = ValidationType.partial; + messages.add( + ValidationMessage(_userMessages.flutterValidatorErrorIntentional), + ); + } + + return ValidationResult( + valid, + messages, + statusInfo: _userMessages.flutterStatusInfo( + versionChannel, + frameworkVersion, + _operatingSystemUtils.name, + _platform.localeName, + ), + ); + } + + ValidationMessage _getFlutterVersionMessage(String frameworkVersion, String versionChannel, String flutterRoot) { + String flutterVersionMessage = _userMessages.flutterVersion(frameworkVersion, versionChannel, flutterRoot); + + // The tool sets the channel as kUserBranch, if the current branch is on a + // "detached HEAD" state, doesn't have an upstream, or is on a user branch, + // and sets the frameworkVersion as "0.0.0-unknown" if "git describe" on + // HEAD doesn't produce an expected format to be parsed for the frameworkVersion. + if (versionChannel != kUserBranch && frameworkVersion != '0.0.0-unknown') { + return ValidationMessage(flutterVersionMessage); + } + if (versionChannel == kUserBranch) { + flutterVersionMessage = '$flutterVersionMessage\n${_userMessages.flutterUnknownChannel}'; + } + if (frameworkVersion == '0.0.0-unknown') { + flutterVersionMessage = '$flutterVersionMessage\n${_userMessages.flutterUnknownVersion}'; + } + return ValidationMessage.hint(flutterVersionMessage); + } + + List _validateRequiredBinaries(String flutterRoot) { + final ValidationMessage? flutterWarning = _validateSdkBinary('flutter', flutterRoot); + final ValidationMessage? dartWarning = _validateSdkBinary('dart', flutterRoot); + return [ + if (flutterWarning != null) flutterWarning, + if (dartWarning != null) dartWarning, + ]; + } + + /// Return a warning if the provided [binary] on the user's path does not + /// resolve within the Flutter SDK. + ValidationMessage? _validateSdkBinary(String binary, String flutterRoot) { + final String flutterBinDir = _fileSystem.path.join(flutterRoot, 'bin'); + + final File? flutterBin = _operatingSystemUtils.which(binary); + if (flutterBin == null) { + return ValidationMessage.hint( + 'The $binary binary is not on your path. Consider adding ' + '$flutterBinDir to your path.', + ); + } + final String resolvedFlutterPath = flutterBin.resolveSymbolicLinksSync(); + if (!_filePathContainsDirPath(flutterRoot, resolvedFlutterPath)) { + final String hint = 'Warning: `$binary` on your path resolves to ' + '$resolvedFlutterPath, which is not inside your current Flutter ' + 'SDK checkout at $flutterRoot. Consider adding $flutterBinDir to ' + 'the front of your path.'; + return ValidationMessage.hint(hint); + } + return null; + } + + bool _filePathContainsDirPath(String directory, String file) { + // calling .canonicalize() will normalize for alphabetic case and path + // separators + return _fileSystem.path.canonicalize(file) + .startsWith(_fileSystem.path.canonicalize(directory) + _fileSystem.path.separator); + } + + ValidationMessage _getFlutterUpstreamMessage(FlutterVersion version) { + final String? repositoryUrl = version.repositoryUrl; + final VersionCheckError? upstreamValidationError = VersionUpstreamValidator(version: version, platform: _platform).run(); + + // VersionUpstreamValidator can produce an error if repositoryUrl is null + if (upstreamValidationError != null) { + final String errorMessage = upstreamValidationError.message; + if (errorMessage.contains('could not determine the remote upstream which is being tracked')) { + return ValidationMessage.hint(_userMessages.flutterUpstreamRepositoryUnknown); + } + // At this point, repositoryUrl must not be null + if (errorMessage.contains('Flutter SDK is tracking a non-standard remote')) { + return ValidationMessage.hint(_userMessages.flutterUpstreamRepositoryUrlNonStandard(repositoryUrl!)); + } + if (errorMessage.contains('Either remove "FLUTTER_GIT_URL" from the environment or set it to')){ + return ValidationMessage.hint(_userMessages.flutterUpstreamRepositoryUrlEnvMismatch(repositoryUrl!)); + } + } + return ValidationMessage(_userMessages.flutterUpstreamRepositoryUrl(repositoryUrl!)); + } + + bool _genSnapshotRuns(String genSnapshotPath) { + const int kExpectedExitCode = 255; + try { + return _processManager.runSync([genSnapshotPath]).exitCode == kExpectedExitCode; + } on Exception { + return false; + } + } +} + +class DeviceValidator extends DoctorValidator { + // TODO(jmagman): Make required once g3 rolls and is updated. + DeviceValidator({ + DeviceManager? deviceManager, + UserMessages? userMessages, + }) : _deviceManager = deviceManager ?? globals.deviceManager!, + _userMessages = userMessages ?? globals.userMessages, + super('Connected device'); + + final DeviceManager _deviceManager; + final UserMessages _userMessages; + + @override + String get slowWarning => 'Scanning for devices is taking a long time...'; + + @override + Future validate() async { + final List devices = await _deviceManager.refreshAllDevices( + timeout: DeviceManager.minimumWirelessDeviceDiscoveryTimeout, + ); + List installedMessages = []; + if (devices.isNotEmpty) { + installedMessages = (await Device.descriptions(devices)) + .map((String msg) => ValidationMessage(msg)).toList(); + } + + List diagnosticMessages = []; + final List diagnostics = await _deviceManager.getDeviceDiagnostics(); + if (diagnostics.isNotEmpty) { + diagnosticMessages = diagnostics.map((String message) => ValidationMessage.hint(message)).toList(); + } else if (devices.isEmpty) { + diagnosticMessages = [ValidationMessage.hint(_userMessages.devicesMissing)]; + } + + if (devices.isEmpty) { + return ValidationResult(ValidationType.notAvailable, diagnosticMessages); + } else if (diagnostics.isNotEmpty) { + installedMessages.addAll(diagnosticMessages); + return ValidationResult( + ValidationType.success, + installedMessages, + statusInfo: _userMessages.devicesAvailable(devices.length) + ); + } else { + return ValidationResult( + ValidationType.success, + installedMessages, + statusInfo: _userMessages.devicesAvailable(devices.length) + ); + } + } +} + +/// Wrapper for doctor to run multiple times with PII and without, running the validators only once. +class DoctorText { + DoctorText( + BufferLogger logger, { + SystemClock? clock, + @visibleForTesting Doctor? doctor, + }) : _doctor = doctor ?? Doctor(logger: logger, clock: clock ?? globals.systemClock), + _logger = logger; + + final BufferLogger _logger; + final Doctor _doctor; + bool _sendDoctorEvent = true; + + late final Future text = _runDiagnosis(true); + late final Future piiStrippedText = _runDiagnosis(false); + + // Start the validator tasks only once. + late final List _validatorTasks = _doctor.startValidatorTasks(); + + Future _runDiagnosis(bool showPii) async { + try { + await _doctor.diagnose(startedValidatorTasks: _validatorTasks, showPii: showPii, sendEvent: _sendDoctorEvent); + // Do not send the doctor event a second time. + _sendDoctorEvent = false; + final String text = _logger.statusText; + _logger.clear(); + return text; + } on Exception catch (error, trace) { + return 'encountered exception: $error\n\n${trace.toString().trim()}\n'; + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/doctor_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/doctor_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..7670b287cfdf53e92aff52b5c8bef5fc43356ef4 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/doctor_validator.dart @@ -0,0 +1,314 @@ +// 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 'base/async_guard.dart'; +import 'base/terminal.dart'; +import 'globals.dart' as globals; + +class ValidatorTask { + ValidatorTask(this.validator, this.result); + final DoctorValidator validator; + final Future result; +} + +/// A series of tools and required install steps for a target platform (iOS or Android). +abstract class Workflow { + const Workflow(); + + /// Whether the workflow applies to this platform (as in, should we ever try and use it). + bool get appliesToHostPlatform; + + /// Are we functional enough to list devices? + bool get canListDevices; + + /// Could this thing launch *something*? It may still have minor issues. + bool get canLaunchDevices; + + /// Are we functional enough to list emulators? + bool get canListEmulators; +} + +enum ValidationType { + crash, + missing, + partial, + notAvailable, + success, +} + +enum ValidationMessageType { + error, + hint, + information, +} + +abstract class DoctorValidator { + const DoctorValidator(this.title); + + /// This is displayed in the CLI. + final String title; + + String get slowWarning => 'This is taking an unexpectedly long time...'; + + static const Duration _slowWarningDuration = Duration(seconds: 10); + + /// Duration before the spinner should display [slowWarning]. + Duration get slowWarningDuration => _slowWarningDuration; + + Future validate(); +} + +/// A validator that runs other [DoctorValidator]s and combines their output +/// into a single [ValidationResult]. It uses the title of the first validator +/// passed to the constructor and reports the statusInfo of the first validator +/// that provides one. Other titles and statusInfo strings are discarded. +class GroupedValidator extends DoctorValidator { + GroupedValidator(this.subValidators) : super(subValidators[0].title); + + final List subValidators; + + List _subResults = []; + + /// Sub-validator results. + /// + /// To avoid losing information when results are merged, the sub-results are + /// cached on this field when they are available. The results are in the same + /// order as the sub-validator list. + List get subResults => _subResults; + + @override + String get slowWarning => _currentSlowWarning; + String _currentSlowWarning = 'Initializing...'; + + @override + Future validate() async { + final List tasks = [ + for (final DoctorValidator validator in subValidators) + ValidatorTask( + validator, + asyncGuard(() => validator.validate()), + ), + ]; + + final List results = []; + for (final ValidatorTask subValidator in tasks) { + _currentSlowWarning = subValidator.validator.slowWarning; + try { + results.add(await subValidator.result); + } on Exception catch (exception, stackTrace) { + results.add(ValidationResult.crash(exception, stackTrace)); + } + } + _currentSlowWarning = 'Merging results...'; + return _mergeValidationResults(results); + } + + ValidationResult _mergeValidationResults(List results) { + assert(results.isNotEmpty, 'Validation results should not be empty'); + _subResults = results; + ValidationType mergedType = results[0].type; + final List mergedMessages = []; + String? statusInfo; + + for (final ValidationResult result in results) { + statusInfo ??= result.statusInfo; + switch (result.type) { + case ValidationType.success: + if (mergedType == ValidationType.missing) { + mergedType = ValidationType.partial; + } + case ValidationType.notAvailable: + case ValidationType.partial: + mergedType = ValidationType.partial; + case ValidationType.crash: + case ValidationType.missing: + if (mergedType == ValidationType.success) { + mergedType = ValidationType.partial; + } + } + mergedMessages.addAll(result.messages); + } + + return ValidationResult(mergedType, mergedMessages, + statusInfo: statusInfo); + } +} + +@immutable +class ValidationResult { + /// [ValidationResult.type] should only equal [ValidationResult.success] + /// if no [messages] are hints or errors. + const ValidationResult(this.type, this.messages, { this.statusInfo }); + + factory ValidationResult.crash(Object error, [StackTrace? stackTrace]) { + return ValidationResult(ValidationType.crash, [ + const ValidationMessage.error( + 'Due to an error, the doctor check did not complete. ' + 'If the error message below is not helpful, ' + 'please let us know about this issue at https://github.com/flutter/flutter/issues.'), + ValidationMessage.error('$error'), + if (stackTrace != null) + // Stacktrace is informational. Printed in verbose mode only. + ValidationMessage('$stackTrace'), + ], statusInfo: 'the doctor check crashed'); + } + + final ValidationType type; + // A short message about the status. + final String? statusInfo; + final List messages; + + String get leadingBox { + switch (type) { + case ValidationType.crash: + return '[☠]'; + case ValidationType.missing: + return '[✗]'; + case ValidationType.success: + return '[✓]'; + case ValidationType.notAvailable: + case ValidationType.partial: + return '[!]'; + } + } + + String get coloredLeadingBox { + switch (type) { + case ValidationType.crash: + return globals.terminal.color(leadingBox, TerminalColor.red); + case ValidationType.missing: + return globals.terminal.color(leadingBox, TerminalColor.red); + case ValidationType.success: + return globals.terminal.color(leadingBox, TerminalColor.green); + case ValidationType.notAvailable: + case ValidationType.partial: + return globals.terminal.color(leadingBox, TerminalColor.yellow); + } + } + + /// The string representation of the type. + String get typeStr { + switch (type) { + case ValidationType.crash: + return 'crash'; + case ValidationType.missing: + return 'missing'; + case ValidationType.success: + return 'installed'; + case ValidationType.notAvailable: + return 'notAvailable'; + case ValidationType.partial: + return 'partial'; + } + } + + @override + String toString() { + return '$runtimeType($type, $messages, $statusInfo)'; + } +} + +/// A status line for the flutter doctor validation to display. +/// +/// The [message] is required and represents either an informational statement +/// about the particular doctor validation that passed, or more context +/// on the cause and/or solution to the validation failure. +@immutable +class ValidationMessage { + /// Create a validation message with information for a passing validator. + /// + /// By default this is not displayed unless the doctor is run in + /// verbose mode. + /// + /// The [contextUrl] may be supplied to link to external resources. This + /// is displayed after the informative message in verbose modes. + const ValidationMessage(this.message, { this.contextUrl, String? piiStrippedMessage }) + : type = ValidationMessageType.information, piiStrippedMessage = piiStrippedMessage ?? message; + + /// Create a validation message with information for a failing validator. + const ValidationMessage.error(this.message, { String? piiStrippedMessage }) + : type = ValidationMessageType.error, + piiStrippedMessage = piiStrippedMessage ?? message, + contextUrl = null; + + /// Create a validation message with information for a partially failing + /// validator. + const ValidationMessage.hint(this.message, { String? piiStrippedMessage }) + : type = ValidationMessageType.hint, + piiStrippedMessage = piiStrippedMessage ?? message, + contextUrl = null; + + final ValidationMessageType type; + final String? contextUrl; + final String message; + /// Optional message with PII stripped, to show instead of [message]. + final String piiStrippedMessage; + + bool get isError => type == ValidationMessageType.error; + + bool get isHint => type == ValidationMessageType.hint; + + bool get isInformation => type == ValidationMessageType.information; + + String get indicator { + switch (type) { + case ValidationMessageType.error: + return '✗'; + case ValidationMessageType.hint: + return '!'; + case ValidationMessageType.information: + return '•'; + } + } + + String get coloredIndicator { + switch (type) { + case ValidationMessageType.error: + return globals.terminal.color(indicator, TerminalColor.red); + case ValidationMessageType.hint: + return globals.terminal.color(indicator, TerminalColor.yellow); + case ValidationMessageType.information: + return globals.terminal.color(indicator, TerminalColor.green); + } + } + + @override + String toString() => message; + + @override + bool operator ==(Object other) { + return other is ValidationMessage + && other.message == message + && other.type == type + && other.contextUrl == contextUrl; + } + + @override + int get hashCode => Object.hash(type, message, contextUrl); +} + +class NoIdeValidator extends DoctorValidator { + NoIdeValidator() : super('Flutter IDE Support'); + + @override + Future validate() async { + return ValidationResult( + // Info hint to user they do not have a supported IDE installed + ValidationType.notAvailable, + globals.userMessages.noIdeInstallationInfo.map((String ideInfo) => ValidationMessage(ideInfo)).toList(), + statusInfo: globals.userMessages.noIdeStatusInfo, + ); + } +} + +class ValidatorWithResult extends DoctorValidator { + ValidatorWithResult(super.title, this.result); + + final ValidationResult result; + + @override + Future validate() async => result; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/emulator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/emulator.dart new file mode 100644 index 0000000000000000000000000000000000000000..e210d2ac94d342a98f9f66535e8b23b60c44f121 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/emulator.dart @@ -0,0 +1,337 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:math' as math; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import 'android/android_emulator.dart'; +import 'android/android_sdk.dart'; +import 'android/android_workflow.dart'; +import 'android/java.dart'; +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/process.dart'; +import 'device.dart'; +import 'ios/ios_emulators.dart'; + +EmulatorManager? get emulatorManager => context.get(); + +/// A class to get all available emulators. +class EmulatorManager { + EmulatorManager({ + required Java? java, + AndroidSdk? androidSdk, + required Logger logger, + required ProcessManager processManager, + required AndroidWorkflow androidWorkflow, + required FileSystem fileSystem, + }) : _java = java, + _androidSdk = androidSdk, + _processUtils = ProcessUtils(logger: logger, processManager: processManager), + _androidEmulators = AndroidEmulators( + androidSdk: androidSdk, + logger: logger, + processManager: processManager, + fileSystem: fileSystem, + androidWorkflow: androidWorkflow + ) { + _emulatorDiscoverers.add(_androidEmulators); + } + + final Java? _java; + final AndroidSdk? _androidSdk; + final AndroidEmulators _androidEmulators; + final ProcessUtils _processUtils; + + // Constructing EmulatorManager is cheap; they only do expensive work if some + // of their methods are called. + final List _emulatorDiscoverers = [ + IOSEmulators(), + ]; + + Future> getEmulatorsMatching(String searchText) async { + final List emulators = await getAllAvailableEmulators(); + searchText = searchText.toLowerCase(); + bool exactlyMatchesEmulatorId(Emulator emulator) => + emulator.id.toLowerCase() == searchText || + emulator.name.toLowerCase() == searchText; + bool startsWithEmulatorId(Emulator emulator) => + emulator.id.toLowerCase().startsWith(searchText) || + emulator.name.toLowerCase().startsWith(searchText); + + Emulator? exactMatch; + for (final Emulator emulator in emulators) { + if (exactlyMatchesEmulatorId(emulator)) { + exactMatch = emulator; + break; + } + } + if (exactMatch != null) { + return [exactMatch]; + } + + // Match on a id or name starting with [emulatorId]. + return emulators.where(startsWithEmulatorId).toList(); + } + + Iterable get _platformDiscoverers { + return _emulatorDiscoverers.where((EmulatorDiscovery discoverer) => discoverer.supportsPlatform); + } + + /// Return the list of all available emulators. + Future> getAllAvailableEmulators() async { + final List emulators = []; + await Future.forEach(_platformDiscoverers, (EmulatorDiscovery discoverer) async { + emulators.addAll(await discoverer.emulators); + }); + return emulators; + } + + /// Return the list of all available emulators. + Future createEmulator({ String? name }) async { + if (name == null || name.isEmpty) { + const String autoName = 'flutter_emulator'; + // Don't use getEmulatorsMatching here, as it will only return one + // if there's an exact match and we need all those with this prefix + // so we can keep adding suffixes until we miss. + final List all = await getAllAvailableEmulators(); + final Set takenNames = all + .map((Emulator e) => e.id) + .where((String id) => id.startsWith(autoName)) + .toSet(); + int suffix = 1; + name = autoName; + while (takenNames.contains(name)) { + name = '${autoName}_${++suffix}'; + } + } + final String emulatorName = name!; + final String? avdManagerPath = _androidSdk?.avdManagerPath; + if (avdManagerPath == null || !_androidEmulators.canLaunchAnything) { + return CreateEmulatorResult(emulatorName, + success: false, error: 'avdmanager is missing from the Android SDK' + ); + } + + final String? device = await _getPreferredAvailableDevice(avdManagerPath); + if (device == null) { + return CreateEmulatorResult(emulatorName, + success: false, error: 'No device definitions are available'); + } + + final String? sdkId = await _getPreferredSdkId(avdManagerPath); + if (sdkId == null) { + return CreateEmulatorResult(emulatorName, + success: false, + error: + 'No suitable Android AVD system images are available. You may need to install these' + ' using sdkmanager, for example:\n' + ' sdkmanager "system-images;android-27;google_apis_playstore;x86"'); + } + + // Cleans up error output from avdmanager to make it more suitable to show + // to flutter users. Specifically: + // - Removes lines that say "null" (!) + // - Removes lines that tell the user to use '--force' to overwrite emulators + String? cleanError(String? error) { + if (error == null || error.trim() == '') { + return null; + } + return error + .split('\n') + .where((String l) => l.trim() != 'null') + .where((String l) => + l.trim() != 'Use --force if you want to replace it.') + .join('\n') + .trim(); + } + final RunResult runResult = await _processUtils.run([ + avdManagerPath, + 'create', + 'avd', + '-n', emulatorName, + '-k', sdkId, + '-d', device, + ], environment: _java?.environment, + ); + return CreateEmulatorResult( + emulatorName, + success: runResult.exitCode == 0, + output: runResult.stdout, + error: cleanError(runResult.stderr), + ); + } + + static const List preferredDevices = [ + 'pixel', + 'pixel_xl', + ]; + + Future _getPreferredAvailableDevice(String avdManagerPath) async { + final List args = [ + avdManagerPath, + 'list', + 'device', + '-c', + ]; + final RunResult runResult = await _processUtils.run(args, + environment: _java?.environment); + if (runResult.exitCode != 0) { + return null; + } + + final List availableDevices = runResult.stdout + .split('\n') + .where((String l) => preferredDevices.contains(l.trim())) + .toList(); + + for (final String device in preferredDevices) { + if (availableDevices.contains(device)) { + return device; + } + } + return null; + } + + static final RegExp _androidApiVersion = RegExp(r';android-(\d+);'); + + Future _getPreferredSdkId(String avdManagerPath) async { + // It seems that to get the available list of images, we need to send a + // request to create without the image and it'll provide us a list :-( + final List args = [ + avdManagerPath, + 'create', + 'avd', + '-n', 'temp', + ]; + final RunResult runResult = await _processUtils.run(args, + environment: _java?.environment); + + // Get the list of IDs that match our criteria + final List availableIDs = runResult.stderr + .split('\n') + .where((String l) => _androidApiVersion.hasMatch(l)) + .where((String l) => l.contains('system-images')) + .where((String l) => l.contains('google_apis_playstore')) + .toList(); + + final List availableApiVersions = availableIDs + .map((String id) => _androidApiVersion.firstMatch(id)!.group(1)!) + .map((String apiVersion) => int.parse(apiVersion)) + .toList(); + + // Get the highest Android API version or whats left + final int apiVersion = availableApiVersions.isNotEmpty + ? availableApiVersions.reduce(math.max) + : -1; // Don't match below + + // We're out of preferences, we just have to return the first one with the high + // API version. + for (final String id in availableIDs) { + if (id.contains(';android-$apiVersion;')) { + return id; + } + } + return null; + } + + /// Whether we're capable of listing any emulators given the current environment configuration. + bool get canListAnything { + return _platformDiscoverers.any((EmulatorDiscovery discoverer) => discoverer.canListAnything); + } +} + +/// An abstract class to discover and enumerate a specific type of emulators. +abstract class EmulatorDiscovery { + bool get supportsPlatform; + + /// Whether this emulator discovery is capable of listing any emulators. + bool get canListAnything; + + /// Whether this emulator discovery is capable of launching new emulators. + bool get canLaunchAnything; + + Future> get emulators; +} + +@immutable +abstract class Emulator { + const Emulator(this.id, this.hasConfig); + + final String id; + final bool hasConfig; + String get name; + String? get manufacturer; + Category get category; + PlatformType get platformType; + + @override + int get hashCode => id.hashCode; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + return other is Emulator + && other.id == id; + } + + Future launch({bool coldBoot}); + + @override + String toString() => name; + + static List descriptions(List emulators) { + if (emulators.isEmpty) { + return []; + } + + // Extract emulators information + final List> table = >[ + for (final Emulator emulator in emulators) + [ + emulator.id, + emulator.name, + emulator.manufacturer ?? '', + emulator.platformType.toString(), + ], + ]; + + // Calculate column widths + final List indices = List.generate(table[0].length - 1, (int i) => i); + List widths = indices.map((int i) => 0).toList(); + for (final List row in table) { + widths = indices.map((int i) => math.max(widths[i], row[i].length)).toList(); + } + + // Join columns into lines of text + final RegExp whiteSpaceAndDots = RegExp(r'[•\s]+$'); + return table + .map((List row) { + return indices + .map((int i) => row[i].padRight(widths[i])) + .followedBy([row.last]) + .join(' • '); + }) + .map((String line) => line.replaceAll(whiteSpaceAndDots, '')) + .toList(); + } + + static void printEmulators(List emulators, Logger logger) { + descriptions(emulators).forEach(logger.printStatus); + } +} + +class CreateEmulatorResult { + CreateEmulatorResult(this.emulatorName, {required this.success, this.output, this.error}); + + final bool success; + final String emulatorName; + final String? output; + final String? error; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/features.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/features.dart new file mode 100644 index 0000000000000000000000000000000000000000..41cdf617a3814579cc37a1e621325d2840095592 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/features.dart @@ -0,0 +1,316 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'base/context.dart'; + +/// The current [FeatureFlags] implementation. +FeatureFlags get featureFlags => context.get()!; + +/// The interface used to determine if a particular [Feature] is enabled. +/// +/// The rest of the tools code should use this class instead of looking up +/// features directly. To facilitate rolls to google3 and other clients, all +/// flags should be provided with a default implementation here. Clients that +/// use this class should extent instead of implement, so that new flags are +/// picked up automatically. +abstract class FeatureFlags { + /// const constructor so that subclasses can be const. + const FeatureFlags(); + + /// Whether flutter desktop for linux is enabled. + bool get isLinuxEnabled => false; + + /// Whether flutter desktop for macOS is enabled. + bool get isMacOSEnabled => false; + + /// Whether flutter web is enabled. + bool get isWebEnabled => false; + + /// Whether flutter desktop for Windows is enabled. + bool get isWindowsEnabled => false; + + /// Whether android is enabled. + bool get isAndroidEnabled => true; + + /// Whether iOS is enabled. + bool get isIOSEnabled => true; + + /// Whether fuchsia is enabled. + bool get isFuchsiaEnabled => true; + + /// Whether custom devices are enabled. + bool get areCustomDevicesEnabled => false; + + /// Whether WebAssembly compilation for Flutter Web is enabled. + bool get isFlutterWebWasmEnabled => false; + + /// Whether animations are used in the command line interface. + bool get isCliAnimationEnabled => true; + + /// Whether native assets compilation and bundling is enabled. + bool get isNativeAssetsEnabled => false; + + /// Whether native assets compilation and bundling is enabled. + bool get isPreviewDeviceEnabled => true; + + /// Whether a particular feature is enabled for the current channel. + /// + /// Prefer using one of the specific getters above instead of this API. + bool isEnabled(Feature feature); +} + +/// All current Flutter feature flags. +const List allFeatures = [ + flutterWebFeature, + flutterLinuxDesktopFeature, + flutterMacOSDesktopFeature, + flutterWindowsDesktopFeature, + flutterAndroidFeature, + flutterIOSFeature, + flutterFuchsiaFeature, + flutterCustomDevicesFeature, + flutterWebWasm, + cliAnimation, + nativeAssets, + previewDevice, +]; + +/// All current Flutter feature flags that can be configured. +/// +/// [Feature.configSetting] is not `null`. +Iterable get allConfigurableFeatures => allFeatures.where((Feature feature) => feature.configSetting != null); + +/// The [Feature] for flutter web. +const Feature flutterWebFeature = Feature.fullyEnabled( + name: 'Flutter for web', + configSetting: 'enable-web', + environmentOverride: 'FLUTTER_WEB', +); + +/// The [Feature] for macOS desktop. +const Feature flutterMacOSDesktopFeature = Feature.fullyEnabled( + name: 'support for desktop on macOS', + configSetting: 'enable-macos-desktop', + environmentOverride: 'FLUTTER_MACOS', +); + +/// The [Feature] for Linux desktop. +const Feature flutterLinuxDesktopFeature = Feature.fullyEnabled( + name: 'support for desktop on Linux', + configSetting: 'enable-linux-desktop', + environmentOverride: 'FLUTTER_LINUX', +); + +/// The [Feature] for Windows desktop. +const Feature flutterWindowsDesktopFeature = Feature.fullyEnabled( + name: 'support for desktop on Windows', + configSetting: 'enable-windows-desktop', + environmentOverride: 'FLUTTER_WINDOWS', +); + +/// The [Feature] for Android devices. +const Feature flutterAndroidFeature = Feature.fullyEnabled( + name: 'Flutter for Android', + configSetting: 'enable-android', +); + +/// The [Feature] for iOS devices. +const Feature flutterIOSFeature = Feature.fullyEnabled( + name: 'Flutter for iOS', + configSetting: 'enable-ios', +); + +/// The [Feature] for Fuchsia support. +const Feature flutterFuchsiaFeature = Feature( + name: 'Flutter for Fuchsia', + configSetting: 'enable-fuchsia', + environmentOverride: 'FLUTTER_FUCHSIA', + master: FeatureChannelSetting( + available: true, + ), +); + +const Feature flutterCustomDevicesFeature = Feature( + name: 'early support for custom device types', + configSetting: 'enable-custom-devices', + environmentOverride: 'FLUTTER_CUSTOM_DEVICES', + master: FeatureChannelSetting( + available: true, + ), + beta: FeatureChannelSetting( + available: true, + ), + stable: FeatureChannelSetting( + available: true, + ), +); + +/// Enabling WebAssembly compilation from `flutter build web` +const Feature flutterWebWasm = Feature( + name: 'WebAssembly compilation from flutter build web', + environmentOverride: 'FLUTTER_WEB_WASM', + master: FeatureChannelSetting( + available: true, + enabledByDefault: true, + ), +); + +const String kCliAnimationsFeatureName = 'cli-animations'; + +/// The [Feature] for CLI animations. +/// +/// The TERM environment variable set to "dumb" turns this off. +const Feature cliAnimation = Feature.fullyEnabled( + name: 'animations in the command line interface', + configSetting: kCliAnimationsFeatureName, +); + +/// Enable native assets compilation and bundling. +const Feature nativeAssets = Feature( + name: 'native assets compilation and bundling', + configSetting: 'enable-native-assets', + environmentOverride: 'FLUTTER_NATIVE_ASSETS', + master: FeatureChannelSetting( + available: true, + ), +); + +/// Enable Flutter preview prebuilt device. +const Feature previewDevice = Feature( + name: 'Flutter preview prebuilt device', + configSetting: 'enable-flutter-preview', + environmentOverride: 'FLUTTER_PREVIEW_DEVICE', + master: FeatureChannelSetting( + available: true, + ), + beta: FeatureChannelSetting( + available: true, + ), +); + +/// A [Feature] is a process for conditionally enabling tool features. +/// +/// All settings are optional, and if not provided will generally default to +/// a "safe" value, such as being off. +/// +/// The top level feature settings can be provided to apply to all channels. +/// Otherwise, more specific settings take precedence over higher level +/// settings. +class Feature { + /// Creates a [Feature]. + const Feature({ + required this.name, + this.environmentOverride, + this.configSetting, + this.extraHelpText, + this.master = const FeatureChannelSetting(), + this.beta = const FeatureChannelSetting(), + this.stable = const FeatureChannelSetting() + }); + + /// Creates a [Feature] that is fully enabled across channels. + const Feature.fullyEnabled( + {required this.name, + this.environmentOverride, + this.configSetting, + this.extraHelpText}) + : master = const FeatureChannelSetting( + available: true, + enabledByDefault: true, + ), + beta = const FeatureChannelSetting( + available: true, + enabledByDefault: true, + ), + stable = const FeatureChannelSetting( + available: true, + enabledByDefault: true, + ); + + /// The user visible name for this feature. + final String name; + + /// The settings for the master branch and other unknown channels. + final FeatureChannelSetting master; + + /// The settings for the beta branch. + final FeatureChannelSetting beta; + + /// The settings for the stable branch. + final FeatureChannelSetting stable; + + /// The name of an environment variable that can override the setting. + /// + /// The environment variable needs to be set to the value 'true'. This is + /// only intended for usage by CI and not as an advertised method to enable + /// a feature. + /// + /// If not provided, defaults to `null` meaning there is no override. + final String? environmentOverride; + + /// The name of a setting that can be used to enable this feature. + /// + /// If not provided, defaults to `null` meaning there is no config setting. + final String? configSetting; + + /// Additional text to add to the end of the help message. + /// + /// If not provided, defaults to `null` meaning there is no additional text. + final String? extraHelpText; + + /// A help message for the `flutter config` command, or null if unsupported. + String? generateHelpMessage() { + if (configSetting == null) { + return null; + } + final StringBuffer buffer = StringBuffer('Enable or disable $name.'); + final List channels = [ + if (master.available) 'master', + if (beta.available) 'beta', + if (stable.available) 'stable', + ]; + // Add channel info for settings only on some channels. + if (channels.length == 1) { + buffer.write('\nThis setting applies only to the ${channels.single} channel.'); + } else if (channels.length == 2) { + buffer.write('\nThis setting applies only to the ${channels.join(' and ')} channels.'); + } + if (extraHelpText != null) { + buffer.write(' $extraHelpText'); + } + return buffer.toString(); + } + + /// Retrieve the correct setting for the provided `channel`. + FeatureChannelSetting getSettingForChannel(String channel) { + switch (channel) { + case 'stable': + return stable; + case 'beta': + return beta; + case 'master': + default: + return master; + } + } +} + +/// A description of the conditions to enable a feature for a particular channel. +class FeatureChannelSetting { + const FeatureChannelSetting({ + this.available = false, + this.enabledByDefault = false, + }); + + /// Whether the feature is available on this channel. + /// + /// If not provided, defaults to `false`. This implies that the feature + /// cannot be enabled even by the settings below. + final bool available; + + /// Whether the feature is enabled by default. + /// + /// If not provided, defaults to `false`. + final bool enabledByDefault; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_application_package.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_application_package.dart new file mode 100644 index 0000000000000000000000000000000000000000..103f21c04394db5f150468d4b2b5893a049c9dc5 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_application_package.dart @@ -0,0 +1,111 @@ +// 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:process/process.dart'; + +import 'android/android_sdk.dart'; +import 'android/application_package.dart'; +import 'application_package.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/process.dart'; +import 'base/user_messages.dart'; +import 'build_info.dart'; +import 'fuchsia/application_package.dart'; +import 'globals.dart' as globals; +import 'ios/application_package.dart'; +import 'linux/application_package.dart'; +import 'macos/application_package.dart'; +import 'project.dart'; +import 'tester/flutter_tester.dart'; +import 'web/web_device.dart'; +import 'windows/application_package.dart'; + +/// A package factory that supports all Flutter target platforms. +class FlutterApplicationPackageFactory extends ApplicationPackageFactory { + FlutterApplicationPackageFactory({ + required AndroidSdk? androidSdk, + required ProcessManager processManager, + required Logger logger, + required UserMessages userMessages, + required FileSystem fileSystem, + }) : _androidSdk = androidSdk, + _processManager = processManager, + _logger = logger, + _userMessages = userMessages, + _fileSystem = fileSystem, + _processUtils = ProcessUtils(logger: logger, processManager: processManager); + + + final AndroidSdk? _androidSdk; + final ProcessManager _processManager; + final Logger _logger; + final ProcessUtils _processUtils; + final UserMessages _userMessages; + final FileSystem _fileSystem; + + @override + Future getPackageForPlatform( + TargetPlatform platform, { + BuildInfo? buildInfo, + File? applicationBinary, + }) async { + switch (platform) { + case TargetPlatform.android: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + if (applicationBinary == null) { + return AndroidApk.fromAndroidProject( + FlutterProject.current().android, + processManager: _processManager, + processUtils: _processUtils, + logger: _logger, + androidSdk: _androidSdk, + userMessages: _userMessages, + fileSystem: _fileSystem, + buildInfo: buildInfo, + ); + } + return AndroidApk.fromApk( + applicationBinary, + processManager: _processManager, + logger: _logger, + androidSdk: _androidSdk!, + userMessages: _userMessages, + processUtils: _processUtils, + ); + case TargetPlatform.ios: + return applicationBinary == null + ? await IOSApp.fromIosProject(FlutterProject.current().ios, buildInfo) + : IOSApp.fromPrebuiltApp(applicationBinary); + case TargetPlatform.tester: + return FlutterTesterApp.fromCurrentDirectory(globals.fs); + case TargetPlatform.darwin: + return applicationBinary == null + ? MacOSApp.fromMacOSProject(FlutterProject.current().macos) + : MacOSApp.fromPrebuiltApp(applicationBinary); + case TargetPlatform.web_javascript: + if (!FlutterProject.current().web.existsSync()) { + return null; + } + return WebApplicationPackage(FlutterProject.current()); + case TargetPlatform.linux_x64: + case TargetPlatform.linux_arm64: + return applicationBinary == null + ? LinuxApp.fromLinuxProject(FlutterProject.current().linux) + : LinuxApp.fromPrebuiltApp(applicationBinary); + case TargetPlatform.windows_x64: + return applicationBinary == null + ? WindowsApp.fromWindowsProject(FlutterProject.current().windows) + : WindowsApp.fromPrebuiltApp(applicationBinary); + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + return applicationBinary == null + ? FuchsiaApp.fromFuchsiaProject(FlutterProject.current().fuchsia) + : FuchsiaApp.fromPrebuiltApp(applicationBinary); + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_cache.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_cache.dart new file mode 100644 index 0000000000000000000000000000000000000000..dcba2c6da544341612890596d8b0a8e606af2d75 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_cache.dart @@ -0,0 +1,918 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:package_config/package_config.dart'; + +import 'android/java.dart'; +import 'base/common.dart'; +import 'base/error_handling_io.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/os.dart' show OperatingSystemUtils; +import 'base/platform.dart'; +import 'base/process.dart'; +import 'cache.dart'; +import 'dart/package_map.dart'; +import 'dart/pub.dart'; +import 'globals.dart' as globals; +import 'project.dart'; + +/// An implementation of the [Cache] which provides all of Flutter's default artifacts. +class FlutterCache extends Cache { + /// [rootOverride] is configurable for testing. + /// [artifacts] is configurable for testing. + FlutterCache({ + required Logger logger, + required super.fileSystem, + required Platform platform, + required super.osUtils, + required FlutterProjectFactory projectFactory, + }) : super(logger: logger, platform: platform, artifacts: []) { + registerArtifact(MaterialFonts(this)); + registerArtifact(GradleWrapper(this)); + registerArtifact(AndroidGenSnapshotArtifacts(this, platform: platform)); + registerArtifact(AndroidInternalBuildArtifacts(this)); + registerArtifact(IOSEngineArtifacts(this, platform: platform)); + registerArtifact(FlutterWebSdk(this)); + registerArtifact(LegacyCanvasKitRemover(this)); + registerArtifact(FlutterSdk(this, platform: platform)); + registerArtifact(WindowsEngineArtifacts(this, platform: platform)); + registerArtifact(MacOSEngineArtifacts(this, platform: platform)); + registerArtifact(LinuxEngineArtifacts(this, platform: platform)); + registerArtifact(LinuxFuchsiaSDKArtifacts(this, platform: platform)); + registerArtifact(MacOSFuchsiaSDKArtifacts(this, platform: platform)); + registerArtifact(FlutterRunnerSDKArtifacts(this, platform: platform)); + registerArtifact(FlutterRunnerDebugSymbols(this, platform: platform)); + for (final String artifactName in IosUsbArtifacts.artifactNames) { + registerArtifact(IosUsbArtifacts(artifactName, this, platform: platform)); + } + registerArtifact(FontSubsetArtifacts(this, platform: platform)); + registerArtifact(PubDependencies( + logger: logger, + // flutter root and pub must be lazily initialized to avoid accessing + // before the version is determined. + flutterRoot: () => Cache.flutterRoot!, + pub: () => pub, + projectFactory: projectFactory, + )); + } +} + + +/// Ensures that the source files for all of the dependencies for the +/// flutter_tool are present. +/// +/// This does not handle cases where the source files are modified or the +/// directory contents are incomplete. +class PubDependencies extends ArtifactSet { + PubDependencies({ + // Needs to be lazy to avoid reading from the cache before the root is initialized. + required String Function() flutterRoot, + required Logger logger, + required Pub Function() pub, + required FlutterProjectFactory projectFactory, + }) : _logger = logger, + _flutterRoot = flutterRoot, + _pub = pub, + _projectFactory = projectFactory, + super(DevelopmentArtifact.universal); + + final String Function() _flutterRoot; + final Logger _logger; + final Pub Function() _pub; + final FlutterProjectFactory _projectFactory; + + @override + Future isUpToDate( + FileSystem fileSystem, + ) async { + final File toolPackageConfig = fileSystem.file( + fileSystem.path.join(_flutterRoot(), 'packages', 'flutter_tools', '.dart_tool', 'package_config.json'), + ); + if (!toolPackageConfig.existsSync()) { + return false; + } + final PackageConfig packageConfig = await loadPackageConfigWithLogging( + toolPackageConfig, + logger: _logger, + throwOnError: false, + ); + if (packageConfig == PackageConfig.empty) { + return false; + } + for (final Package package in packageConfig.packages) { + if (!fileSystem.directory(package.root).childFile('pubspec.yaml').existsSync()) { + return false; + } + } + return true; + } + + @override + String get name => 'pub_dependencies'; + + @override + Future update( + ArtifactUpdater artifactUpdater, + Logger logger, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + {bool offline = false} + ) async { + await _pub().get( + context: PubContext.pubGet, + project: _projectFactory.fromDirectory( + fileSystem.directory(fileSystem.path.join(_flutterRoot(), 'packages', 'flutter_tools')) + ), + offline: offline, + outputMode: PubOutputMode.none, + ); + } +} + +/// A cached artifact containing fonts used for Material Design. +class MaterialFonts extends CachedArtifact { + MaterialFonts(Cache cache) : super( + 'material_fonts', + cache, + DevelopmentArtifact.universal, + ); + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + final Uri archiveUri = _toStorageUri(version!); + return artifactUpdater.downloadZipArchive('Downloading Material fonts...', archiveUri, location); + } + + Uri _toStorageUri(String path) => Uri.parse('${cache.storageBaseUrl}/$path'); +} + +/// A cached artifact containing the web dart:ui sources, platform dill files, +/// and libraries.json. +/// +/// This SDK references code within the regular Dart sdk to reduce download size. +class FlutterWebSdk extends CachedArtifact { + FlutterWebSdk(Cache cache) + : super( + 'flutter_web_sdk', + cache, + DevelopmentArtifact.web, + ); + + @override + Directory get location => cache.getWebSdkDirectory(); + + @override + String? get version => cache.getVersionFor('engine'); + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + final Uri url = Uri.parse('${cache.storageBaseUrl}/flutter_infra_release/flutter/$version/flutter-web-sdk.zip'); + ErrorHandlingFileSystem.deleteIfExists(location, recursive: true); + await artifactUpdater.downloadZipArchive('Downloading Web SDK...', url, location); + } +} + +// In previous builds, CanvasKit artifacts were stored in a different location +// than they are now. Leaving those old artifacts in the cache confuses the +// in-memory filesystem that the web runner uses, so this artifact will evict +// them from our cache if they are there. +class LegacyCanvasKitRemover extends ArtifactSet { + LegacyCanvasKitRemover(this.cache) : super(DevelopmentArtifact.web); + + final Cache cache; + + @override + String get name => 'legacy_canvaskit_remover'; + + Directory _getLegacyCanvasKitDirectory(FileSystem fileSystem) => + fileSystem.directory(fileSystem.path.join( + cache.getRoot().path, + 'canvaskit', + )); + + @override + Future isUpToDate(FileSystem fileSystem) async => + !(await _getLegacyCanvasKitDirectory(fileSystem).exists()); + + @override + Future update( + ArtifactUpdater artifactUpdater, + Logger logger, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + {bool offline = false} + ) => _getLegacyCanvasKitDirectory(fileSystem).delete(recursive: true); +} + +/// A cached artifact containing the dart:ui source code. +class FlutterSdk extends EngineCachedArtifact { + FlutterSdk(Cache cache, { + required Platform platform, + }) : _platform = platform, + super( + 'flutter_sdk', + cache, + DevelopmentArtifact.universal, + ); + + final Platform _platform; + + @override + List getPackageDirs() => const ['sky_engine']; + + @override + List> getBinaryDirs() { + // Currently only Linux supports both arm64 and x64. + final String arch = cache.getHostPlatformArchName(); + return >[ + ['common', 'flutter_patched_sdk.zip'], + ['common', 'flutter_patched_sdk_product.zip'], + if (cache.includeAllPlatforms) ...>[ + ['windows-x64', 'windows-x64/artifacts.zip'], + ['linux-$arch', 'linux-$arch/artifacts.zip'], + ['darwin-x64', 'darwin-$arch/artifacts.zip'], + ] + else if (_platform.isWindows) + ['windows-x64', 'windows-x64/artifacts.zip'] + else if (_platform.isMacOS) + ['darwin-x64', 'darwin-$arch/artifacts.zip'] + else if (_platform.isLinux) + ['linux-$arch', 'linux-$arch/artifacts.zip'], + ]; + } + + @override + List getLicenseDirs() => const []; +} + +class MacOSEngineArtifacts extends EngineCachedArtifact { + MacOSEngineArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super( + 'macos-sdk', + cache, + DevelopmentArtifact.macOS, + ); + + final Platform _platform; + + @override + List getPackageDirs() => const []; + + @override + List> getBinaryDirs() { + if (_platform.isMacOS || ignorePlatformFiltering) { + return _macOSDesktopBinaryDirs; + } + return const >[]; + } + + @override + List getLicenseDirs() => const []; +} + +/// Artifacts required for desktop Windows builds. +class WindowsEngineArtifacts extends EngineCachedArtifact { + WindowsEngineArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super( + 'windows-sdk', + cache, + DevelopmentArtifact.windows, + ); + + final Platform _platform; + + @override + List getPackageDirs() => const []; + + @override + List> getBinaryDirs() { + if (_platform.isWindows || ignorePlatformFiltering) { + return _windowsDesktopBinaryDirs; + } + return const >[]; + } + + @override + List getLicenseDirs() => const []; +} + +/// Artifacts required for desktop Linux builds. +class LinuxEngineArtifacts extends EngineCachedArtifact { + LinuxEngineArtifacts(Cache cache, { + required Platform platform + }) : _platform = platform, + super( + 'linux-sdk', + cache, + DevelopmentArtifact.linux, + ); + + final Platform _platform; + + @override + List getPackageDirs() => const []; + + @override + List> getBinaryDirs() { + if (_platform.isLinux || ignorePlatformFiltering) { + final String arch = cache.getHostPlatformArchName(); + return >[ + ['linux-$arch', 'linux-$arch-debug/linux-$arch-flutter-gtk.zip'], + ['linux-$arch-profile', 'linux-$arch-profile/linux-$arch-flutter-gtk.zip'], + ['linux-$arch-release', 'linux-$arch-release/linux-$arch-flutter-gtk.zip'], + ]; + } + return const >[]; + } + + @override + List getLicenseDirs() => const []; +} + +/// The artifact used to generate snapshots for Android builds. +class AndroidGenSnapshotArtifacts extends EngineCachedArtifact { + AndroidGenSnapshotArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super( + 'android-sdk', + cache, + DevelopmentArtifact.androidGenSnapshot, + ); + + final Platform _platform; + + @override + List getPackageDirs() => const []; + + @override + List> getBinaryDirs() { + return >[ + if (cache.includeAllPlatforms) ...>[ + ..._osxBinaryDirs, + ..._linuxBinaryDirs, + ..._windowsBinaryDirs, + ..._dartSdks, + ] else if (_platform.isWindows) + ..._windowsBinaryDirs + else if (_platform.isMacOS) + ..._osxBinaryDirs + else if (_platform.isLinux) + ..._linuxBinaryDirs, + ]; + } + + @override + List getLicenseDirs() { return []; } +} + +/// A cached artifact containing the Maven dependencies used to build Android projects. +/// +/// This is a no-op if the android SDK is not available. +/// +/// Set [Java] to `null` to indicate that no Java/JDK installation could be found. +class AndroidMavenArtifacts extends ArtifactSet { + AndroidMavenArtifacts(this.cache, { + required Java? java, + required Platform platform, + }) : _java = java, + _platform = platform, + super(DevelopmentArtifact.androidMaven); + + final Java? _java; + final Platform _platform; + final Cache cache; + + @override + Future update( + ArtifactUpdater artifactUpdater, + Logger logger, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + {bool offline = false} + ) async { + // TODO(andrewkolos): Should this really be no-op if the Android SDK + // is unavailable? https://github.com/flutter/flutter/issues/127848 + if (globals.androidSdk == null) { + return; + } + final Directory tempDir = cache.getRoot().createTempSync('flutter_gradle_wrapper.'); + globals.gradleUtils?.injectGradleWrapperIfNeeded(tempDir); + + final Status status = logger.startProgress('Downloading Android Maven dependencies...'); + final File gradle = tempDir.childFile( + _platform.isWindows ? 'gradlew.bat' : 'gradlew', + ); + try { + final String gradleExecutable = gradle.absolute.path; + final String flutterSdk = globals.fsUtils.escapePath(Cache.flutterRoot!); + final RunResult processResult = await globals.processUtils.run( + [ + gradleExecutable, + '-b', globals.fs.path.join(flutterSdk, 'packages', 'flutter_tools', 'gradle', 'resolve_dependencies.gradle'), + '--project-cache-dir', tempDir.path, + 'resolveDependencies', + ], + environment: _java?.environment, + ); + if (processResult.exitCode != 0) { + logger.printError('Failed to download the Android dependencies'); + } + } finally { + status.stop(); + tempDir.deleteSync(recursive: true); + globals.androidSdk?.reinitialize(); + } + } + + @override + Future isUpToDate(FileSystem fileSystem) async { + // The dependencies are downloaded and cached by Gradle. + // The tool doesn't know if the dependencies are already cached at this point. + // Therefore, call Gradle to figure this out. + return false; + } + + @override + String get name => 'android-maven-artifacts'; +} + +/// Artifacts used for internal builds. The flutter tool builds Android projects +/// using the artifacts cached by [AndroidMavenArtifacts]. +class AndroidInternalBuildArtifacts extends EngineCachedArtifact { + AndroidInternalBuildArtifacts(Cache cache) : super( + 'android-internal-build-artifacts', + cache, + DevelopmentArtifact.androidInternalBuild, + ); + + @override + List getPackageDirs() => const []; + + @override + List> getBinaryDirs() { + return _androidBinaryDirs; + } + + @override + List getLicenseDirs() { return []; } +} + +class IOSEngineArtifacts extends EngineCachedArtifact { + IOSEngineArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super( + 'ios-sdk', + cache, + DevelopmentArtifact.iOS, + ); + + final Platform _platform; + + @override + List> getBinaryDirs() { + return >[ + if (_platform.isMacOS || ignorePlatformFiltering) + ..._iosBinaryDirs, + ]; + } + + @override + List getLicenseDirs() { + if (_platform.isMacOS || ignorePlatformFiltering) { + return const ['ios', 'ios-profile', 'ios-release']; + } + return const []; + } + + @override + List getPackageDirs() { + return []; + } +} + +/// A cached artifact containing Gradle Wrapper scripts and binaries. +/// +/// While this is only required for Android, we need to always download it due +/// the ensurePlatformSpecificTooling logic. +class GradleWrapper extends CachedArtifact { + GradleWrapper(Cache cache) : super( + 'gradle_wrapper', + cache, + DevelopmentArtifact.universal, + ); + + List get _gradleScripts => ['gradlew', 'gradlew.bat']; + + Uri _toStorageUri(String path) => Uri.parse('${cache.storageBaseUrl}/$path'); + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + final Uri archiveUri = _toStorageUri(version!); + await artifactUpdater.downloadZippedTarball('Downloading Gradle Wrapper...', archiveUri, location); + // Delete property file, allowing templates to provide it. + // Remove NOTICE file. Should not be part of the template. + final File propertiesFile = fileSystem.file(fileSystem.path.join(location.path, 'gradle', 'wrapper', 'gradle-wrapper.properties')); + final File noticeFile = fileSystem.file(fileSystem.path.join(location.path, 'NOTICE')); + ErrorHandlingFileSystem.deleteIfExists(propertiesFile); + ErrorHandlingFileSystem.deleteIfExists(noticeFile); + } + + @override + bool isUpToDateInner( + FileSystem fileSystem, + ) { + final String gradleWrapper = fileSystem.path.join('gradle', 'wrapper', 'gradle-wrapper.jar'); + final Directory wrapperDir = cache.getCacheDir(fileSystem.path.join('artifacts', 'gradle_wrapper')); + if (!fileSystem.directory(wrapperDir).existsSync()) { + return false; + } + for (final String scriptName in _gradleScripts) { + final File scriptFile = fileSystem.file(fileSystem.path.join(wrapperDir.path, scriptName)); + if (!scriptFile.existsSync()) { + return false; + } + } + final File gradleWrapperJar = fileSystem.file(fileSystem.path.join(wrapperDir.path, gradleWrapper)); + if (!gradleWrapperJar.existsSync()) { + return false; + } + return true; + } +} + +/// Common functionality for pulling Fuchsia SDKs. +abstract class _FuchsiaSDKArtifacts extends CachedArtifact { + _FuchsiaSDKArtifacts(Cache cache, String platform) : + _path = 'fuchsia/sdk/core/$platform-amd64', + super( + 'fuchsia-$platform', + cache, + DevelopmentArtifact.fuchsia, + ); + + final String _path; + + @override + Directory get location => cache.getArtifactDirectory('fuchsia'); + + Future _doUpdate(ArtifactUpdater artifactUpdater) { + final String url = '${cache.cipdBaseUrl}/$_path/+/$version'; + return artifactUpdater.downloadZipArchive('Downloading package fuchsia SDK...', + Uri.parse(url), location); + } +} + +/// The pre-built flutter runner for Fuchsia development. +class FlutterRunnerSDKArtifacts extends CachedArtifact { + FlutterRunnerSDKArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super( + 'flutter_runner', + cache, + DevelopmentArtifact.flutterRunner, + ); + + final Platform _platform; + + @override + Directory get location => cache.getArtifactDirectory('flutter_runner'); + + @override + String? get version => cache.getVersionFor('engine'); + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + if (!_platform.isLinux && !_platform.isMacOS) { + return; + } + final String url = '${cache.cipdBaseUrl}/flutter/fuchsia/+/git_revision:$version'; + await artifactUpdater.downloadZipArchive('Downloading package flutter runner...', Uri.parse(url), location); + } +} + +/// Implementations of this class can resolve URLs for packages that are versioned. +/// +/// See also [CipdArchiveResolver]. +abstract class VersionedPackageResolver { + const VersionedPackageResolver(); + + /// Returns the URL for the artifact. + String resolveUrl(String packageName, String version); +} + +/// Resolves the CIPD archive URL for a given package and version. +class CipdArchiveResolver extends VersionedPackageResolver { + const CipdArchiveResolver(this.cache); + + final Cache cache; + + @override + String resolveUrl(String packageName, String version) { + return '${cache.cipdBaseUrl}/flutter/$packageName/+/git_revision:$version'; + } +} + +/// The debug symbols for flutter runner for Fuchsia development. +class FlutterRunnerDebugSymbols extends CachedArtifact { + FlutterRunnerDebugSymbols(Cache cache, { + required Platform platform, + VersionedPackageResolver? packageResolver, + }) : _platform = platform, + packageResolver = packageResolver ?? CipdArchiveResolver(cache), + super('flutter_runner_debug_symbols', cache, DevelopmentArtifact.flutterRunner); + + final VersionedPackageResolver packageResolver; + final Platform _platform; + + @override + Directory get location => cache.getArtifactDirectory(name); + + @override + String? get version => cache.getVersionFor('engine'); + + Future _downloadDebugSymbols(String targetArch, ArtifactUpdater artifactUpdater) async { + final String packageName = 'fuchsia-debug-symbols-$targetArch'; + final String url = packageResolver.resolveUrl(packageName, version!); + await artifactUpdater.downloadZipArchive( + 'Downloading debug symbols for flutter runner - arch:$targetArch...', + Uri.parse(url), + location, + ); + } + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + if (!_platform.isLinux && !_platform.isMacOS) { + return; + } + await _downloadDebugSymbols('x64', artifactUpdater); + await _downloadDebugSymbols('arm64', artifactUpdater); + } +} + +/// The Fuchsia core SDK for Linux. +class LinuxFuchsiaSDKArtifacts extends _FuchsiaSDKArtifacts { + LinuxFuchsiaSDKArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super(cache, 'linux'); + + final Platform _platform; + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + if (!_platform.isLinux) { + return; + } + return _doUpdate(artifactUpdater); + } +} + +/// The Fuchsia core SDK for MacOS. +class MacOSFuchsiaSDKArtifacts extends _FuchsiaSDKArtifacts { + MacOSFuchsiaSDKArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super(cache, 'mac'); + + final Platform _platform; + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + if (!_platform.isMacOS) { + return; + } + return _doUpdate(artifactUpdater); + } +} + +/// Cached artifacts for font subsetting. +class FontSubsetArtifacts extends EngineCachedArtifact { + FontSubsetArtifacts(Cache cache, { + required Platform platform, + }) : _platform = platform, + super(artifactName, cache, DevelopmentArtifact.universal); + + final Platform _platform; + + static const String artifactName = 'font-subset'; + + @override + List> getBinaryDirs() { + // Currently only Linux supports both arm64 and x64. + final String arch = cache.getHostPlatformArchName(); + final Map> artifacts = > { + 'macos': ['darwin-x64', 'darwin-$arch/$artifactName.zip'], + 'linux': ['linux-$arch', 'linux-$arch/$artifactName.zip'], + 'windows': ['windows-x64', 'windows-x64/$artifactName.zip'], + }; + if (cache.includeAllPlatforms) { + return artifacts.values.toList(); + } else { + final List? binaryDirs = artifacts[_platform.operatingSystem]; + if (binaryDirs == null) { + throwToolExit('Unsupported operating system: ${_platform.operatingSystem}'); + } + return >[binaryDirs]; + } + } + + @override + List getLicenseDirs() => const []; + + @override + List getPackageDirs() => const []; +} + +/// Cached iOS/USB binary artifacts. +class IosUsbArtifacts extends CachedArtifact { + IosUsbArtifacts(String name, Cache cache, { + required Platform platform, + }) : _platform = platform, + super( + name, + cache, + DevelopmentArtifact.universal, + ); + + final Platform _platform; + + static const List artifactNames = [ + 'libimobiledevice', + 'usbmuxd', + 'libplist', + 'openssl', + 'ios-deploy', + ]; + + // For unknown reasons, users are getting into bad states where libimobiledevice is + // downloaded but some executables are missing from the zip. The names here are + // used for additional download checks below, so we can re-download if they are + // missing. + static const Map> _kExecutables = >{ + 'libimobiledevice': [ + 'idevicescreenshot', + 'idevicesyslog', + ], + 'usbmuxd': [ + 'iproxy', + ], + }; + + @override + Map get environment { + return { + 'DYLD_LIBRARY_PATH': cache.getArtifactDirectory(name).path, + }; + } + + @override + bool isUpToDateInner(FileSystem fileSystem) { + final List? executables =_kExecutables[name]; + if (executables == null) { + return true; + } + for (final String executable in executables) { + if (!location.childFile(executable).existsSync()) { + return false; + } + } + return true; + } + + @override + Future updateInner( + ArtifactUpdater artifactUpdater, + FileSystem fileSystem, + OperatingSystemUtils operatingSystemUtils, + ) async { + if (!_platform.isMacOS && !ignorePlatformFiltering) { + return; + } + if (location.existsSync()) { + location.deleteSync(recursive: true); + } + await artifactUpdater.downloadZipArchive('Downloading $name...', archiveUri, location); + } + + @visibleForTesting + Uri get archiveUri => Uri.parse( + '${cache.realmlessStorageBaseUrl}/flutter_infra_release/' + 'ios-usb-dependencies${cache.useUnsignedMacBinaries ? '/unsigned' : ''}' + '/$name/$version/$name.zip', + ); +} + +// TODO(zanderso): upload debug desktop artifacts to host-debug and +// remove from existing host folder. +// https://github.com/flutter/flutter/issues/38935 +const List> _windowsDesktopBinaryDirs = >[ + ['windows-x64', 'windows-x64-debug/windows-x64-flutter.zip'], + ['windows-x64', 'windows-x64/flutter-cpp-client-wrapper.zip'], + ['windows-x64-profile', 'windows-x64-profile/windows-x64-flutter.zip'], + ['windows-x64-release', 'windows-x64-release/windows-x64-flutter.zip'], +]; + +const List> _macOSDesktopBinaryDirs = >[ + ['darwin-x64', 'darwin-x64/FlutterMacOS.framework.zip'], + ['darwin-x64', 'darwin-x64/gen_snapshot.zip'], + ['darwin-x64-profile', 'darwin-x64-profile/FlutterMacOS.framework.zip'], + ['darwin-x64-profile', 'darwin-x64-profile/artifacts.zip'], + ['darwin-x64-profile', 'darwin-x64-profile/gen_snapshot.zip'], + ['darwin-x64-release', 'darwin-x64-release/FlutterMacOS.framework.zip'], + ['darwin-x64-release', 'darwin-x64-release/artifacts.zip'], + ['darwin-x64-release', 'darwin-x64-release/gen_snapshot.zip'], +]; + +const List> _osxBinaryDirs = >[ + ['android-arm-profile/darwin-x64', 'android-arm-profile/darwin-x64.zip'], + ['android-arm-release/darwin-x64', 'android-arm-release/darwin-x64.zip'], + ['android-arm64-profile/darwin-x64', 'android-arm64-profile/darwin-x64.zip'], + ['android-arm64-release/darwin-x64', 'android-arm64-release/darwin-x64.zip'], + ['android-x64-profile/darwin-x64', 'android-x64-profile/darwin-x64.zip'], + ['android-x64-release/darwin-x64', 'android-x64-release/darwin-x64.zip'], +]; + +const List> _linuxBinaryDirs = >[ + ['android-arm-profile/linux-x64', 'android-arm-profile/linux-x64.zip'], + ['android-arm-release/linux-x64', 'android-arm-release/linux-x64.zip'], + ['android-arm64-profile/linux-x64', 'android-arm64-profile/linux-x64.zip'], + ['android-arm64-release/linux-x64', 'android-arm64-release/linux-x64.zip'], + ['android-x64-profile/linux-x64', 'android-x64-profile/linux-x64.zip'], + ['android-x64-release/linux-x64', 'android-x64-release/linux-x64.zip'], +]; + +const List> _windowsBinaryDirs = >[ + ['android-arm-profile/windows-x64', 'android-arm-profile/windows-x64.zip'], + ['android-arm-release/windows-x64', 'android-arm-release/windows-x64.zip'], + ['android-arm64-profile/windows-x64', 'android-arm64-profile/windows-x64.zip'], + ['android-arm64-release/windows-x64', 'android-arm64-release/windows-x64.zip'], + ['android-x64-profile/windows-x64', 'android-x64-profile/windows-x64.zip'], + ['android-x64-release/windows-x64', 'android-x64-release/windows-x64.zip'], +]; + +const List> _iosBinaryDirs = >[ + ['ios', 'ios/artifacts.zip'], + ['ios-profile', 'ios-profile/artifacts.zip'], + ['ios-release', 'ios-release/artifacts.zip'], +]; + +const List> _androidBinaryDirs = >[ + ['android-x86', 'android-x86/artifacts.zip'], + ['android-x64', 'android-x64/artifacts.zip'], + ['android-arm', 'android-arm/artifacts.zip'], + ['android-arm-profile', 'android-arm-profile/artifacts.zip'], + ['android-arm-release', 'android-arm-release/artifacts.zip'], + ['android-arm64', 'android-arm64/artifacts.zip'], + ['android-arm64-profile', 'android-arm64-profile/artifacts.zip'], + ['android-arm64-release', 'android-arm64-release/artifacts.zip'], + ['android-x64-profile', 'android-x64-profile/artifacts.zip'], + ['android-x64-release', 'android-x64-release/artifacts.zip'], + ['android-x86-jit-release', 'android-x86-jit-release/artifacts.zip'], +]; + +const List> _dartSdks = > [ + ['darwin-x64', 'dart-sdk-darwin-x64.zip'], + ['linux-x64', 'dart-sdk-linux-x64.zip'], + ['windows-x64', 'dart-sdk-windows-x64.zip'], +]; diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_device_manager.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_device_manager.dart new file mode 100644 index 0000000000000000000000000000000000000000..3b9558e53d0f5a46c9ccffb4d50ce16047143e8f --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_device_manager.dart @@ -0,0 +1,148 @@ +// 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:process/process.dart'; + +import 'android/android_device_discovery.dart'; +import 'android/android_sdk.dart'; +import 'android/android_workflow.dart'; +import 'artifacts.dart'; +import 'base/file_system.dart'; +import 'base/os.dart'; +import 'base/platform.dart'; +import 'base/user_messages.dart'; +import 'custom_devices/custom_device.dart'; +import 'custom_devices/custom_devices_config.dart'; +import 'device.dart'; +import 'features.dart'; +import 'fuchsia/fuchsia_device.dart'; +import 'fuchsia/fuchsia_sdk.dart'; +import 'fuchsia/fuchsia_workflow.dart'; +import 'ios/devices.dart'; +import 'ios/ios_workflow.dart'; +import 'ios/simulators.dart'; +import 'linux/linux_device.dart'; +import 'macos/macos_device.dart'; +import 'macos/macos_ipad_device.dart'; +import 'macos/macos_workflow.dart'; +import 'macos/xcdevice.dart'; +import 'preview_device.dart'; +import 'tester/flutter_tester.dart'; +import 'version.dart'; +import 'web/web_device.dart'; + +import 'windows/windows_device.dart'; +import 'windows/windows_workflow.dart'; + +/// A provider for all of the device discovery instances. +class FlutterDeviceManager extends DeviceManager { + FlutterDeviceManager({ + required super.logger, + required Platform platform, + required ProcessManager processManager, + required FileSystem fileSystem, + required AndroidSdk? androidSdk, + required FeatureFlags featureFlags, + required IOSSimulatorUtils iosSimulatorUtils, + required XCDevice xcDevice, + required AndroidWorkflow androidWorkflow, + required IOSWorkflow iosWorkflow, + required FuchsiaWorkflow fuchsiaWorkflow, + required FlutterVersion flutterVersion, + required Artifacts artifacts, + required MacOSWorkflow macOSWorkflow, + required FuchsiaSdk fuchsiaSdk, + required UserMessages userMessages, + required OperatingSystemUtils operatingSystemUtils, + required WindowsWorkflow windowsWorkflow, + required CustomDevicesConfig customDevicesConfig, + }) : deviceDiscoverers = [ + AndroidDevices( + logger: logger, + androidSdk: androidSdk, + androidWorkflow: androidWorkflow, + processManager: processManager, + fileSystem: fileSystem, + platform: platform, + userMessages: userMessages, + ), + IOSDevices( + platform: platform, + xcdevice: xcDevice, + iosWorkflow: iosWorkflow, + logger: logger, + ), + IOSSimulators( + iosSimulatorUtils: iosSimulatorUtils, + ), + FuchsiaDevices( + fuchsiaSdk: fuchsiaSdk, + logger: logger, + fuchsiaWorkflow: fuchsiaWorkflow, + platform: platform, + ), + FlutterTesterDevices( + fileSystem: fileSystem, + flutterVersion: flutterVersion, + processManager: processManager, + logger: logger, + artifacts: artifacts, + ), + MacOSDevices( + processManager: processManager, + macOSWorkflow: macOSWorkflow, + logger: logger, + platform: platform, + fileSystem: fileSystem, + operatingSystemUtils: operatingSystemUtils, + ), + MacOSDesignedForIPadDevices( + processManager: processManager, + iosWorkflow: iosWorkflow, + logger: logger, + platform: platform, + fileSystem: fileSystem, + operatingSystemUtils: operatingSystemUtils, + ), + PreviewDeviceDiscovery( + platform: platform, + artifacts: artifacts, + fileSystem: fileSystem, + logger: logger, + processManager: processManager, + featureFlags: featureFlags, + ), + LinuxDevices( + platform: platform, + featureFlags: featureFlags, + processManager: processManager, + logger: logger, + fileSystem: fileSystem, + operatingSystemUtils: operatingSystemUtils, + ), + WindowsDevices( + processManager: processManager, + operatingSystemUtils: operatingSystemUtils, + logger: logger, + fileSystem: fileSystem, + windowsWorkflow: windowsWorkflow, + ), + WebDevices( + featureFlags: featureFlags, + fileSystem: fileSystem, + platform: platform, + processManager: processManager, + logger: logger, + ), + CustomDevices( + featureFlags: featureFlags, + processManager: processManager, + logger: logger, + config: customDevicesConfig + ), + ]; + + @override + final List deviceDiscoverers; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_features.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_features.dart new file mode 100644 index 0000000000000000000000000000000000000000..ebb3403b154f50ad8ead0efcea95bc20563feb41 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_features.dart @@ -0,0 +1,85 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'base/config.dart'; +import 'base/platform.dart'; +import 'features.dart'; +import 'version.dart'; + +class FlutterFeatureFlags implements FeatureFlags { + FlutterFeatureFlags({ + required FlutterVersion flutterVersion, + required Config config, + required Platform platform, + }) : _flutterVersion = flutterVersion, + _config = config, + _platform = platform; + + final FlutterVersion _flutterVersion; + final Config _config; + final Platform _platform; + + @override + bool get isLinuxEnabled => isEnabled(flutterLinuxDesktopFeature); + + @override + bool get isMacOSEnabled => isEnabled(flutterMacOSDesktopFeature); + + @override + bool get isWebEnabled => isEnabled(flutterWebFeature); + + @override + bool get isWindowsEnabled => isEnabled(flutterWindowsDesktopFeature); + + @override + bool get isAndroidEnabled => isEnabled(flutterAndroidFeature); + + @override + bool get isIOSEnabled => isEnabled(flutterIOSFeature); + + @override + bool get isFuchsiaEnabled => isEnabled(flutterFuchsiaFeature); + + @override + bool get areCustomDevicesEnabled => isEnabled(flutterCustomDevicesFeature); + + @override + bool get isFlutterWebWasmEnabled => isEnabled(flutterWebWasm); + + @override + bool get isCliAnimationEnabled { + if (_platform.environment['TERM'] == 'dumb') { + return false; + } + return isEnabled(cliAnimation); + } + + @override + bool get isNativeAssetsEnabled => isEnabled(nativeAssets); + + @override + bool get isPreviewDeviceEnabled => isEnabled(previewDevice); + + @override + bool isEnabled(Feature feature) { + final String currentChannel = _flutterVersion.channel; + final FeatureChannelSetting featureSetting = feature.getSettingForChannel(currentChannel); + if (!featureSetting.available) { + return false; + } + bool isEnabled = featureSetting.enabledByDefault; + if (feature.configSetting != null) { + final bool? configOverride = _config.getValue(feature.configSetting!) as bool?; + if (configOverride != null) { + isEnabled = configOverride; + } + } + if (feature.environmentOverride != null) { + if (_platform.environment[feature.environmentOverride]?.toLowerCase() == 'true') { + isEnabled = true; + } + } + return isEnabled; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_manifest.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_manifest.dart new file mode 100644 index 0000000000000000000000000000000000000000..473413982b85f336c099b9a1b109b620e1b9467d --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_manifest.dart @@ -0,0 +1,796 @@ +// 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:pub_semver/pub_semver.dart'; +import 'package:yaml/yaml.dart'; + +import 'base/deferred_component.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/user_messages.dart'; +import 'base/utils.dart'; +import 'plugins.dart'; + +/// Whether or not Impeller Scene 3D model import is enabled. +const bool kIs3dSceneSupported = true; + +const Set _kValidPluginPlatforms = { + 'android', 'ios', 'web', 'windows', 'linux', 'macos', +}; + +/// A wrapper around the `flutter` section in the `pubspec.yaml` file. +class FlutterManifest { + FlutterManifest._({required Logger logger}) : _logger = logger; + + /// Returns an empty manifest. + factory FlutterManifest.empty({ required Logger logger }) = FlutterManifest._; + + /// Returns null on invalid manifest. Returns empty manifest on missing file. + static FlutterManifest? createFromPath(String path, { + required FileSystem fileSystem, + required Logger logger, + }) { + if (!fileSystem.isFileSync(path)) { + return _createFromYaml(null, logger); + } + final String manifest = fileSystem.file(path).readAsStringSync(); + return FlutterManifest.createFromString(manifest, logger: logger); + } + + /// Returns null on missing or invalid manifest. + @visibleForTesting + static FlutterManifest? createFromString(String manifest, { required Logger logger }) { + return _createFromYaml(loadYaml(manifest), logger); + } + + static FlutterManifest? _createFromYaml(Object? yamlDocument, Logger logger) { + if (yamlDocument != null && !_validate(yamlDocument, logger)) { + return null; + } + + final FlutterManifest pubspec = FlutterManifest._(logger: logger); + final Map? yamlMap = yamlDocument as YamlMap?; + if (yamlMap != null) { + pubspec._descriptor = yamlMap.cast(); + } + + final Map? flutterMap = pubspec._descriptor['flutter'] as Map?; + if (flutterMap != null) { + pubspec._flutterDescriptor = flutterMap.cast(); + } + + return pubspec; + } + + final Logger _logger; + + /// A map representation of the entire `pubspec.yaml` file. + Map _descriptor = {}; + + /// A map representation of the `flutter` section in the `pubspec.yaml` file. + Map _flutterDescriptor = {}; + + Map get flutterDescriptor => _flutterDescriptor; + + /// True if the `pubspec.yaml` file does not exist. + bool get isEmpty => _descriptor.isEmpty; + + /// 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 get dependencies { + final YamlMap? dependencies = _descriptor['dependencies'] as YamlMap?; + return dependencies != null ? {...dependencies.keys.cast()} : {}; + } + + // Flag to avoid printing multiple invalid version messages. + bool _hasShowInvalidVersionMsg = false; + + /// The version String from the `pubspec.yaml` file. + /// Can be null if it isn't set or has a wrong format. + String? get appVersion { + final String? verStr = _descriptor['version']?.toString(); + if (verStr == null) { + return null; + } + + Version? version; + try { + version = Version.parse(verStr); + } on Exception { + if (!_hasShowInvalidVersionMsg) { + _logger.printStatus(userMessages.invalidVersionSettingHintMessage(verStr), emphasis: true); + _hasShowInvalidVersionMsg = true; + } + } + return version?.toString(); + } + + /// The build version name from the `pubspec.yaml` file. + /// Can be null if version isn't set or has a wrong format. + String? get buildName { + final String? version = appVersion; + if (version != null && version.contains('+')) { + return version.split('+').elementAt(0); + } + return version; + } + + /// The build version number from the `pubspec.yaml` file. + /// Can be null if version isn't set or has a wrong format. + String? get buildNumber { + final String? version = appVersion; + if (version != null && version.contains('+')) { + final String value = version.split('+').elementAt(1); + return value; + } else { + return null; + } + } + + bool get usesMaterialDesign { + return _flutterDescriptor['uses-material-design'] as bool? ?? false; + } + + /// True if this Flutter module should use AndroidX dependencies. + /// + /// If false the deprecated Android Support library will be used. + bool get usesAndroidX { + final Object? module = _flutterDescriptor['module']; + if (module is YamlMap) { + return module['androidX'] == true; + } + return false; + } + + /// Any additional license files listed under the `flutter` key. + /// + /// This is expected to be a list of file paths that should be treated as + /// relative to the pubspec in this directory. + /// + /// For example: + /// + /// ```yaml + /// flutter: + /// licenses: + /// - assets/foo_license.txt + /// ``` + List get additionalLicenses { + final Object? licenses = _flutterDescriptor['licenses']; + if (licenses is YamlList) { + return licenses.map((Object? element) => element.toString()).toList(); + } + return []; + } + + /// True if this manifest declares a Flutter module project. + /// + /// A Flutter project is considered a module when it has a `module:` + /// descriptor. A Flutter module project supports integration into an + /// existing host app, and has managed platform host code. + /// + /// Such a project can be created using `flutter create -t module`. + bool get isModule => _flutterDescriptor.containsKey('module'); + + /// True if this manifest declares a Flutter plugin project. + /// + /// A Flutter project is considered a plugin when it has a `plugin:` + /// descriptor. A Flutter plugin project wraps custom Android and/or + /// iOS code in a Dart interface for consumption by other Flutter app + /// projects. + /// + /// Such a project can be created using `flutter create -t plugin`. + bool get isPlugin => _flutterDescriptor.containsKey('plugin'); + + /// Returns the Android package declared by this manifest in its + /// module or plugin descriptor. Returns null, if there is no + /// such declaration. + String? get androidPackage { + if (isModule) { + final Object? module = _flutterDescriptor['module']; + if (module is YamlMap) { + return module['androidPackage'] as String?; + } + } + final Map? platforms = supportedPlatforms; + if (platforms == null) { + // Pre-multi-platform plugin format + if (isPlugin) { + final YamlMap? plugin = _flutterDescriptor['plugin'] as YamlMap?; + return plugin?['androidPackage'] as String?; + } + return null; + } + if (platforms.containsKey('android')) { + final Object? android = platforms['android']; + if (android is YamlMap) { + return android['package'] as String?; + } + } + return null; + } + + /// Returns the deferred components configuration if declared. Returns + /// null if no deferred components are declared. + late final List? deferredComponents = computeDeferredComponents(); + List? computeDeferredComponents() { + if (!_flutterDescriptor.containsKey('deferred-components')) { + return null; + } + final List components = []; + final Object? deferredComponents = _flutterDescriptor['deferred-components']; + if (deferredComponents is! YamlList) { + return components; + } + for (final Object? component in deferredComponents) { + if (component is! YamlMap) { + _logger.printError('Expected deferred component manifest to be a map.'); + continue; + } + components.add( + DeferredComponent( + name: component['name'] as String, + libraries: component['libraries'] == null ? + [] : (component['libraries'] as List).cast(), + assets: _computeAssets(component['assets']), + ) + ); + } + return components; + } + + /// Returns the iOS bundle identifier declared by this manifest in its + /// module descriptor. Returns null if there is no such declaration. + String? get iosBundleIdentifier { + if (isModule) { + final Object? module = _flutterDescriptor['module']; + if (module is YamlMap) { + return module['iosBundleIdentifier'] as String?; + } + } + return null; + } + + /// Gets the supported platforms. This only supports the new `platforms` format. + /// + /// If the plugin uses the legacy pubspec format, this method returns null. + Map? get supportedPlatforms { + if (isPlugin) { + final YamlMap? plugin = _flutterDescriptor['plugin'] as YamlMap?; + if (plugin?.containsKey('platforms') ?? false) { + final YamlMap? platformsMap = plugin!['platforms'] as YamlMap?; + return platformsMap?.value.cast(); + } + } + return null; + } + + /// Like [supportedPlatforms], but only returns the valid platforms that are supported in flutter plugins. + Map? get validSupportedPlatforms { + final Map? allPlatforms = supportedPlatforms; + if (allPlatforms == null) { + return null; + } + final Map platforms = {}..addAll(allPlatforms); + platforms.removeWhere((String key, Object? _) => !_kValidPluginPlatforms.contains(key)); + if (platforms.isEmpty) { + return null; + } + return platforms; + } + + List> get fontsDescriptor { + return fonts.map((Font font) => font.descriptor).toList(); + } + + List> get _rawFontsDescriptor { + final List? fontList = _flutterDescriptor['fonts'] as List?; + return fontList == null + ? const >[] + : fontList.map?>(castStringKeyedMap).whereType>().toList(); + } + + late final List assets = _computeAssets(_flutterDescriptor['assets']); + + late final List fonts = _extractFonts(); + + List _extractFonts() { + if (!_flutterDescriptor.containsKey('fonts')) { + return []; + } + + final List fonts = []; + for (final Map fontFamily in _rawFontsDescriptor) { + final YamlList? fontFiles = fontFamily['fonts'] as YamlList?; + final String? familyName = fontFamily['family'] as String?; + if (familyName == null) { + _logger.printWarning('Warning: Missing family name for font.', emphasis: true); + continue; + } + if (fontFiles == null) { + _logger.printWarning('Warning: No fonts specified for font $familyName', emphasis: true); + continue; + } + + final List fontAssets = []; + for (final Map fontFile in fontFiles.cast>()) { + final String? asset = fontFile['asset'] as String?; + if (asset == null) { + _logger.printWarning('Warning: Missing asset in fonts for $familyName', emphasis: true); + continue; + } + + fontAssets.add(FontAsset( + Uri.parse(asset), + weight: fontFile['weight'] as int?, + style: fontFile['style'] as String?, + )); + } + if (fontAssets.isNotEmpty) { + fonts.add(Font(familyName, fontAssets)); + } + } + return fonts; + } + + late final List shaders = _extractAssetUris('shaders', 'Shader'); + late final List models = kIs3dSceneSupported ? _extractAssetUris('models', 'Model') : []; + + List _extractAssetUris(String key, String singularName) { + if (!_flutterDescriptor.containsKey(key)) { + return []; + } + + final List? items = _flutterDescriptor[key] as List?; + if (items == null) { + return const []; + } + final List results = []; + for (final Object? item in items) { + if (item is! String || item == '') { + _logger.printError('$singularName manifest contains a null or empty uri.'); + continue; + } + try { + results.add(Uri(pathSegments: item.split('/'))); + } on FormatException { + _logger.printError('$singularName manifest contains invalid uri: $item.'); + } + } + return results; + } + + /// Whether a synthetic flutter_gen package should be generated. + /// + /// This can be provided to the [Pub] interface to inject a new entry + /// into the package_config.json file which points to `.dart_tool/flutter_gen`. + /// + /// This allows generated source code to be imported using a package + /// alias. + late final bool generateSyntheticPackage = _computeGenerateSyntheticPackage(); + bool _computeGenerateSyntheticPackage() { + if (!_flutterDescriptor.containsKey('generate')) { + return false; + } + final Object? value = _flutterDescriptor['generate']; + if (value is! bool) { + return false; + } + return value; + } +} + +class Font { + Font(this.familyName, this.fontAssets) + : assert(fontAssets.isNotEmpty); + + final String familyName; + final List fontAssets; + + Map get descriptor { + return { + 'family': familyName, + 'fonts': fontAssets.map>((FontAsset a) => a.descriptor).toList(), + }; + } + + @override + String toString() => '$runtimeType(family: $familyName, assets: $fontAssets)'; +} + +class FontAsset { + FontAsset(this.assetUri, {this.weight, this.style}); + + final Uri assetUri; + final int? weight; + final String? style; + + Map get descriptor { + final Map descriptor = {}; + if (weight != null) { + descriptor['weight'] = weight; + } + + if (style != null) { + descriptor['style'] = style; + } + + descriptor['asset'] = assetUri.path; + return descriptor; + } + + @override + String toString() => '$runtimeType(asset: ${assetUri.path}, weight; $weight, style: $style)'; +} + + +bool _validate(Object? manifest, Logger logger) { + final List errors = []; + if (manifest is! YamlMap) { + errors.add('Expected YAML map'); + } else { + for (final MapEntry kvp in manifest.entries) { + if (kvp.key is! String) { + errors.add('Expected YAML key to be a string, but got ${kvp.key}.'); + continue; + } + switch (kvp.key as String?) { + case 'name': + if (kvp.value is! String) { + errors.add('Expected "${kvp.key}" to be a string, but got ${kvp.value}.'); + } + case 'flutter': + if (kvp.value == null) { + continue; + } + if (kvp.value is! YamlMap) { + errors.add('Expected "${kvp.key}" section to be an object or null, but got ${kvp.value}.'); + } else { + _validateFlutter(kvp.value as YamlMap?, errors); + } + default: + // additionalProperties are allowed. + break; + } + } + } + + if (errors.isNotEmpty) { + logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); + logger.printError(errors.join('\n')); + return false; + } + + return true; +} + +void _validateFlutter(YamlMap? yaml, List errors) { + if (yaml == null) { + return; + } + for (final MapEntry kvp in yaml.entries) { + final Object? yamlKey = kvp.key; + final Object? yamlValue = kvp.value; + if (yamlKey is! String) { + errors.add('Expected YAML key to be a string, but got $yamlKey (${yamlValue.runtimeType}).'); + continue; + } + switch (yamlKey) { + case 'uses-material-design': + if (yamlValue is! bool) { + errors.add('Expected "$yamlKey" to be a bool, but got $yamlValue (${yamlValue.runtimeType}).'); + } + case 'assets': + errors.addAll(_validateAssets(yamlValue)); + case 'shaders': + if (yamlValue is! YamlList) { + errors.add('Expected "$yamlKey" to be a list, but got $yamlValue (${yamlValue.runtimeType}).'); + } else if (yamlValue.isEmpty) { + break; + } else if (yamlValue[0] is! String) { + errors.add( + 'Expected "$yamlKey" to be a list of strings, but the first element is $yamlValue (${yamlValue.runtimeType}).', + ); + } + case 'models': + if (yamlValue is! YamlList) { + errors.add('Expected "$yamlKey" to be a list, but got $yamlValue (${yamlValue.runtimeType}).'); + } else if (yamlValue.isEmpty) { + break; + } else if (yamlValue[0] is! String) { + errors.add( + 'Expected "$yamlKey" to be a list of strings, but the first element is $yamlValue (${yamlValue.runtimeType}).', + ); + } + case 'fonts': + if (yamlValue is! YamlList) { + errors.add('Expected "$yamlKey" to be a list, but got $yamlValue (${yamlValue.runtimeType}).'); + } else if (yamlValue.isEmpty) { + break; + } else if (yamlValue.first is! YamlMap) { + errors.add( + 'Expected "$yamlKey" to contain maps, but the first element is $yamlValue (${yamlValue.runtimeType}).', + ); + } else { + _validateFonts(yamlValue, errors); + } + case 'licenses': + if (yamlValue is! YamlList) { + errors.add('Expected "$yamlKey" to be a list of files, but got $yamlValue (${yamlValue.runtimeType})'); + } else if (yamlValue.isEmpty) { + break; + } else if (yamlValue.first is! String) { + errors.add( + 'Expected "$yamlKey" to contain strings, but the first element is $yamlValue (${yamlValue.runtimeType}).', + ); + } else { + _validateListType(yamlValue, errors, '"$yamlKey"', 'files'); + } + case 'module': + if (yamlValue is! YamlMap) { + errors.add('Expected "$yamlKey" to be an object, but got $yamlValue (${yamlValue.runtimeType}).'); + break; + } + + if (yamlValue['androidX'] != null && yamlValue['androidX'] is! bool) { + errors.add('The "androidX" value must be a bool if set.'); + } + if (yamlValue['androidPackage'] != null && yamlValue['androidPackage'] is! String) { + errors.add('The "androidPackage" value must be a string if set.'); + } + if (yamlValue['iosBundleIdentifier'] != null && yamlValue['iosBundleIdentifier'] is! String) { + errors.add('The "iosBundleIdentifier" section must be a string if set.'); + } + case 'plugin': + if (yamlValue is! YamlMap) { + errors.add('Expected "$yamlKey" to be an object, but got $yamlValue (${yamlValue.runtimeType}).'); + break; + } + final List pluginErrors = Plugin.validatePluginYaml(yamlValue); + errors.addAll(pluginErrors); + case 'generate': + break; + case 'deferred-components': + _validateDeferredComponents(kvp, errors); + default: + errors.add('Unexpected child "$yamlKey" found under "flutter".'); + break; + } + } +} + +void _validateListType(YamlList yamlList, List errors, String context, String typeAlias) { + for (int i = 0; i < yamlList.length; i++) { + if (yamlList[i] is! T) { + // ignore: avoid_dynamic_calls + errors.add('Expected $context to be a list of $typeAlias, but element $i was a ${yamlList[i].runtimeType}'); + } + } +} + +void _validateDeferredComponents(MapEntry kvp, List errors) { + final Object? yamlList = kvp.value; + if (yamlList != null && (yamlList is! YamlList || yamlList[0] is! YamlMap)) { + errors.add('Expected "${kvp.key}" to be a list, but got $yamlList (${yamlList.runtimeType}).'); + } else if (yamlList is YamlList) { + for (int i = 0; i < yamlList.length; i++) { + final Object? valueMap = yamlList[i]; + if (valueMap is! YamlMap) { + // ignore: avoid_dynamic_calls + errors.add('Expected the $i element in "${kvp.key}" to be a map, but got ${yamlList[i]} (${yamlList[i].runtimeType}).'); + continue; + } + if (!valueMap.containsKey('name') || valueMap['name'] is! String) { + errors.add('Expected the $i element in "${kvp.key}" to have required key "name" of type String'); + } + if (valueMap.containsKey('libraries')) { + final Object? libraries = valueMap['libraries']; + if (libraries is! YamlList) { + errors.add('Expected "libraries" key in the $i element of "${kvp.key}" to be a list, but got $libraries (${libraries.runtimeType}).'); + } else { + _validateListType(libraries, errors, '"libraries" key in the $i element of "${kvp.key}"', 'dart library Strings'); + } + } + if (valueMap.containsKey('assets')) { + errors.addAll(_validateAssets(valueMap['assets'])); + } + } + } +} + +List _validateAssets(Object? yaml) { + final (_, List errors) = _computeAssetsSafe(yaml); + return errors; +} + +// TODO(andrewkolos): We end up parsing the assets section twice, once during +// validation and once when the assets getter is called. We should consider +// refactoring this class to parse and store everything in the constructor. +// https://github.com/flutter/flutter/issues/139183 +(List, List errors) _computeAssetsSafe(Object? yaml) { + if (yaml == null) { + return (const [], const []); + } + if (yaml is! YamlList) { + final String error = 'Expected "assets" to be a list, but got $yaml (${yaml.runtimeType}).'; + return (const [], [error]); + } + final List results = []; + final List errors = []; + for (final Object? rawAssetEntry in yaml) { + final (AssetsEntry? parsed, String? error) = AssetsEntry.parseFromYamlSafe(rawAssetEntry); + if (parsed != null) { + results.add(parsed); + } + if (error != null) { + errors.add(error); + } + } + return (results, errors); +} + +List _computeAssets(Object? assetsSection) { + final (List result, List errors) = _computeAssetsSafe(assetsSection); + if (errors.isNotEmpty) { + throw Exception('Uncaught error(s) in assets section: ' + '${errors.join('\n')}'); + } + return result; +} + +void _validateFonts(YamlList fonts, List errors) { + const Set fontWeights = { + 100, 200, 300, 400, 500, 600, 700, 800, 900, + }; + for (final Object? fontMap in fonts) { + if (fontMap is! YamlMap) { + errors.add('Unexpected child "$fontMap" found under "fonts". Expected a map.'); + continue; + } + for (final Object? key in fontMap.keys.where((Object? key) => key != 'family' && key != 'fonts')) { + errors.add('Unexpected child "$key" found under "fonts".'); + } + if (fontMap['family'] != null && fontMap['family'] is! String) { + errors.add('Font family must either be null or a String.'); + } + if (fontMap['fonts'] == null) { + continue; + } else if (fontMap['fonts'] is! YamlList) { + errors.add('Expected "fonts" to either be null or a list.'); + continue; + } + for (final Object? fontMapList in fontMap['fonts'] as List) { + if (fontMapList is! YamlMap) { + errors.add('Expected "fonts" to be a list of maps.'); + continue; + } + for (final MapEntry kvp in fontMapList.entries) { + final Object? fontKey = kvp.key; + if (fontKey is! String) { + errors.add('Expected "$fontKey" under "fonts" to be a string.'); + } + switch (fontKey) { + case 'asset': + if (kvp.value is! String) { + errors.add('Expected font asset ${kvp.value} ((${kvp.value.runtimeType})) to be a string.'); + } + case 'weight': + if (!fontWeights.contains(kvp.value)) { + errors.add('Invalid value ${kvp.value} ((${kvp.value.runtimeType})) for font -> weight.'); + } + case 'style': + if (kvp.value != 'normal' && kvp.value != 'italic') { + errors.add('Invalid value ${kvp.value} ((${kvp.value.runtimeType})) for font -> style.'); + } + default: + errors.add('Unexpected key $fontKey ((${kvp.value.runtimeType})) under font.'); + break; + } + } + } + } +} + +/// Represents an entry under the `assets` section of a pubspec. +@immutable +class AssetsEntry { + const AssetsEntry({ + required this.uri, + this.flavors = const [], + }); + + final Uri uri; + final List flavors; + + static const String _pathKey = 'path'; + static const String _flavorKey = 'flavors'; + + static AssetsEntry? parseFromYaml(Object? yaml) { + final (AssetsEntry? value, String? error) = parseFromYamlSafe(yaml); + if (error != null) { + throw Exception('Unexpected error when parsing assets entry'); + } + return value!; + } + + static (AssetsEntry? assetsEntry, String? error) parseFromYamlSafe(Object? yaml) { + + (Uri?, String?) tryParseUri(String uri) { + try { + return (Uri(pathSegments: uri.split('/')), null); + } on FormatException { + return (null, 'Asset manifest contains invalid uri: $uri.'); + } + } + + if (yaml == null || yaml == '') { + return (null, 'Asset manifest contains a null or empty uri.'); + } + + if (yaml is String) { + final (Uri? uri, String? error) = tryParseUri(yaml); + return uri == null ? (null, error) : (AssetsEntry(uri: uri), null); + } + + if (yaml is Map) { + if (yaml.keys.isEmpty) { + return (null, null); + } + + final Object? path = yaml[_pathKey]; + final Object? flavors = yaml[_flavorKey]; + + if (path == null || path is! String) { + return (null, 'Asset manifest entry is malformed. ' + 'Expected asset entry to be either a string or a map ' + 'containing a "$_pathKey" entry. Got ${path.runtimeType} instead.'); + } + + final Uri uri = Uri(pathSegments: path.split('/')); + + if (flavors == null) { + return (AssetsEntry(uri: uri), null); + } + + if (flavors is! YamlList) { + return(null, 'Asset manifest entry is malformed. ' + 'Expected "$_flavorKey" entry to be a list of strings. ' + 'Got ${flavors.runtimeType} instead.'); + } + + final List flavorsListErrors = []; + _validateListType(flavors, flavorsListErrors, 'flavors list of entry "$path"', 'String'); + if (flavorsListErrors.isNotEmpty) { + return (null, 'Asset manifest entry is malformed. ' + 'Expected "$_flavorKey" entry to be a list of strings.\n' + '${flavorsListErrors.join('\n')}'); + } + + final AssetsEntry entry = AssetsEntry( + uri: Uri(pathSegments: path.split('/')), + flavors: List.from(flavors), + ); + + return (entry, null); + } + + return (null, 'Assets entry had unexpected shape. ' + 'Expected a string or an object. Got ${yaml.runtimeType} instead.'); + } + + @override + bool operator ==(Object other) { + if (other is! AssetsEntry) { + return false; + } + + return uri == other.uri && flavors == other.flavors; + } + + @override + int get hashCode => Object.hash(uri.hashCode, flavors.hashCode); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_plugins.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_plugins.dart new file mode 100644 index 0000000000000000000000000000000000000000..01d9751db8ad83fb915e2304e1dbf065462d1657 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_plugins.dart @@ -0,0 +1,1477 @@ +// 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 +import 'package:pub_semver/pub_semver.dart' as semver; +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 'cache.dart'; +import 'convert.dart'; +import 'dart/language_version.dart'; +import 'dart/package_map.dart'; +import 'features.dart'; +import 'globals.dart' as globals; +import 'platform_plugins.dart'; +import 'plugins.dart'; +import 'project.dart'; + +Future _renderTemplateToFile( + String template, + Object? context, + File file, + TemplateRenderer templateRenderer, +) async { + final String renderedTemplate = templateRenderer + .renderString(template, context); + await file.create(recursive: true); + await file.writeAsString(renderedTemplate); +} + +Future _pluginFromPackage(String name, Uri packageRoot, Set appDependencies, + {FileSystem? fileSystem}) async { + final FileSystem fs = fileSystem ?? globals.fs; + final File pubspecFile = fs.file(packageRoot.resolve('pubspec.yaml')); + if (!pubspecFile.existsSync()) { + return null; + } + Object? pubspec; + + try { + pubspec = loadYaml(await pubspecFile.readAsString()); + } on YamlException catch (err) { + globals.printTrace('Failed to parse plugin manifest for $name: $err'); + // Do nothing, potentially not a plugin. + } + if (pubspec == null || pubspec is! YamlMap) { + return null; + } + final Object? flutterConfig = pubspec['flutter']; + if (flutterConfig == null || flutterConfig is! YamlMap || !flutterConfig.containsKey('plugin')) { + return null; + } + final String? flutterConstraintText = (pubspec['environment'] as YamlMap?)?['flutter'] as String?; + final semver.VersionConstraint? flutterConstraint = flutterConstraintText == null ? + null : semver.VersionConstraint.parse(flutterConstraintText); + final String packageRootPath = 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?, + flutterConstraint, + dependencies == null ? [] : [...dependencies.keys.cast()], + fileSystem: fs, + appDependencies: appDependencies, + ); +} + +Future> findPlugins(FlutterProject project, { bool throwOnError = true}) async { + final List plugins = []; + final FileSystem fs = project.directory.fileSystem; + final String packagesFile = fs.path.join( + project.directory.path, + '.packages', + ); + final PackageConfig packageConfig = await loadPackageConfigWithLogging( + fs.file(packagesFile), + logger: globals.logger, + throwOnError: throwOnError, + ); + for (final Package package in packageConfig.packages) { + final Uri packageRoot = package.packageUriRoot.resolve('..'); + final Plugin? plugin = await _pluginFromPackage( + package.name, + packageRoot, + project.manifest.dependencies, + fileSystem: fs + ); + 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'; +const String _kFlutterPluginsHasNativeBuildKey = 'native_build'; +const String _kFlutterPluginsSharedDarwinSource = 'shared_darwin_source'; + +/// Filters [plugins] to those supported by [platformKey]. +List> _filterPluginsByPlatform(List plugins, 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> pluginInfo = >[]; + for (final Plugin plugin in platformPlugins) { + // This is guaranteed to be non-null due to the `where` filter above. + final PluginPlatform platformPlugin = plugin.platforms[platformKey]!; + pluginInfo.add({ + _kFlutterPluginsNameKey: plugin.name, + _kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path), + if (platformPlugin is DarwinPlugin && (platformPlugin as DarwinPlugin).sharedDarwinSource) + _kFlutterPluginsSharedDarwinSource: (platformPlugin as DarwinPlugin).sharedDarwinSource, + if (platformPlugin is NativeOrDartPlugin) + _kFlutterPluginsHasNativeBuildKey: (platformPlugin as NativeOrDartPlugin).hasMethodChannel() || (platformPlugin as NativeOrDartPlugin).hasFfi(), + _kFlutterPluginsDependenciesKey: [...plugin.dependencies.where(pluginNames.contains)], + }); + } + return pluginInfo; +} + +/// 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" +/// ], +/// "native_build": true +/// } +/// ], +/// "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; +{{#methodChannelPlugins}} +import {{package}}.{{class}}; +{{/methodChannelPlugins}} + +/** + * Generated file. Do not edit. + */ +public final class GeneratedPluginRegistrant { + public static void registerWith(PluginRegistry registry) { + if (alreadyRegisteredWith(registry)) { + return; + } +{{#methodChannelPlugins}} + {{class}}.registerWith(registry.registrarFor("{{package}}.{{class}}")); +{{/methodChannelPlugins}} + } + + 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}} +{{#methodChannelPlugins}} + {{#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}} +{{/methodChannelPlugins}} + } +} +'''; + +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) { + return project.android.getEmbeddingVersion(); +} + +Future _writeAndroidPluginRegistrant(FlutterProject project, List plugins) async { + final List methodChannelPlugins = _filterMethodChannelPlugins(plugins, AndroidPlugin.kConfigKey); + final List> androidPlugins = _extractPlatformMaps(methodChannelPlugins, AndroidPlugin.kConfigKey); + + final Map templateContext = { + 'methodChannelPlugins': 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. + + final List pluginsUsingV1 = []; + for (final Map plugin in androidPlugins) { + final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false; + final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false; + if (supportsEmbeddingV1 && !supportsEmbeddingV2) { + templateContext['needsShim'] = true; + if (plugin['name'] != null) { + pluginsUsingV1.add(plugin['name']! as String); + } + } + } + if (pluginsUsingV1.length > 1) { + globals.printWarning( + '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) { + globals.printWarning( + '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.' + ); + } + templateContent = _androidPluginRegistryTemplateNewEmbedding; + case AndroidEmbeddingVersion.v1: + globals.printWarning( + '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' + ); + for (final Map plugin in androidPlugins) { + final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false; + final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false; + if (!supportsEmbeddingV1 && supportsEmbeddingV2) { + throwToolExit( + 'The plugin `${plugin['name']}` requires your app to be migrated to ' + 'the Android embedding v2. Follow the steps on the migration doc above ' + 'and re-run this command.' + ); + } + } + templateContent = _androidPluginRegistryTemplateOldEmbedding; + } + globals.printTrace('Generating $registryPath'); + await _renderTemplateToFile( + templateContent, + templateContext, + globals.fs.file(registryPath), + globals.templateRenderer, + ); +} + +const String _objcPluginRegistryHeaderTemplate = ''' +// +// Generated file. Do not edit. +// + +// clang-format off + +#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. +// + +// clang-format off + +#import "GeneratedPluginRegistrant.h" + +{{#methodChannelPlugins}} +#if __has_include(<{{name}}/{{class}}.h>) +#import <{{name}}/{{class}}.h> +#else +@import {{name}}; +#endif + +{{/methodChannelPlugins}} +@implementation GeneratedPluginRegistrant + ++ (void)registerWithRegistry:(NSObject*)registry { +{{#methodChannelPlugins}} + [{{prefix}}{{class}} registerWithRegistrar:[registry registrarForPlugin:@"{{prefix}}{{class}}"]]; +{{/methodChannelPlugins}} +} + +@end +'''; + +const String _swiftPluginRegistryTemplate = ''' +// +// Generated file. Do not edit. +// + +import {{framework}} +import Foundation + +{{#methodChannelPlugins}} +import {{name}} +{{/methodChannelPlugins}} + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + {{#methodChannelPlugins}} + {{class}}.register(with: registry.registrar(forPlugin: "{{class}}")) +{{/methodChannelPlugins}} +} +'''; + +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}}' + {{#methodChannelPlugins}} + s.dependency '{{name}}' + {{/methodChannelPlugins}} +end +'''; + +const String _noopDartPluginRegistryTemplate = ''' +// Flutter web plugin registrant file. +// +// Generated file. Do not edit. +// + +// ignore_for_file: type=lint + +void registerPlugins() {} +'''; + +const String _dartPluginRegistryTemplate = ''' +// Flutter web plugin registrant file. +// +// Generated file. Do not edit. +// + +// @dart = 2.13 +// ignore_for_file: type=lint + +{{#methodChannelPlugins}} +import 'package:{{name}}/{{file}}'; +{{/methodChannelPlugins}} +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +void registerPlugins([final Registrar? pluginRegistrar]) { + final Registrar registrar = pluginRegistrar ?? webPluginRegistrar; +{{#methodChannelPlugins}} + {{class}}.registerWith(registrar); +{{/methodChannelPlugins}} + registrar.registerMessageHandler(); +} +'''; + +const String _cppPluginRegistryHeaderTemplate = ''' +// +// Generated file. Do not edit. +// + +// clang-format off + +#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. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +{{#methodChannelPlugins}} +#include <{{name}}/{{filename}}.h> +{{/methodChannelPlugins}} + +void RegisterPlugins(flutter::PluginRegistry* registry) { +{{#methodChannelPlugins}} + {{class}}RegisterWithRegistrar( + registry->GetRegistrarForPlugin("{{class}}")); +{{/methodChannelPlugins}} +} +'''; + +const String _linuxPluginRegistryHeaderTemplate = ''' +// +// Generated file. Do not edit. +// + +// clang-format off + +#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. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +{{#methodChannelPlugins}} +#include <{{name}}/{{filename}}.h> +{{/methodChannelPlugins}} + +void fl_register_plugins(FlPluginRegistry* registry) { +{{#methodChannelPlugins}} + g_autoptr(FlPluginRegistrar) {{name}}_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "{{class}}"); + {{filename}}_register_with_registrar({{name}}_registrar); +{{/methodChannelPlugins}} +} +'''; + +const String _pluginCmakefileTemplate = r''' +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +{{#methodChannelPlugins}} + {{name}} +{{/methodChannelPlugins}} +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +{{#ffiPlugins}} + {{name}} +{{/ffiPlugins}} +) + +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) + +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) +'''; + +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' + ); + } +'''; + +// TODO(egarciad): Evaluate merging the web and non-web plugin registry templates. +// https://github.com/flutter/flutter/issues/80406 +const String _dartPluginRegistryForNonWebTemplate = ''' +// +// 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. +{{#android}} +import 'package:{{pluginName}}/{{pluginName}}.dart'; +{{/android}} +{{#ios}} +import 'package:{{pluginName}}/{{pluginName}}.dart'; +{{/ios}} +{{#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() { + if (Platform.isAndroid) { + {{#android}} +$_dartPluginRegisterWith + {{/android}} + } else if (Platform.isIOS) { + {{#ios}} +$_dartPluginRegisterWith + {{/ios}} + } else if (Platform.isLinux) { + {{#linux}} +$_dartPluginRegisterWith + {{/linux}} + } else if (Platform.isMacOS) { + {{#macos}} +$_dartPluginRegisterWith + {{/macos}} + } else if (Platform.isWindows) { + {{#windows}} +$_dartPluginRegisterWith + {{/windows}} + } + } +} +'''; + +Future _writeIOSPluginRegistrant(FlutterProject project, List plugins) async { + final List methodChannelPlugins = _filterMethodChannelPlugins(plugins, IOSPlugin.kConfigKey); + final List> iosPlugins = _extractPlatformMaps(methodChannelPlugins, IOSPlugin.kConfigKey); + final Map context = { + 'os': 'ios', + 'deploymentTarget': '12.0', + 'framework': 'Flutter', + 'methodChannelPlugins': iosPlugins, + }; + if (project.isModule) { + final Directory registryDirectory = project.ios.pluginRegistrantHost; + await _renderTemplateToFile( + _pluginRegistrantPodspecTemplate, + context, + registryDirectory.childFile('FlutterPluginRegistrant.podspec'), + globals.templateRenderer, + ); + } + await _renderTemplateToFile( + _objcPluginRegistryHeaderTemplate, + context, + project.ios.pluginRegistrantHeader, + globals.templateRenderer, + ); + await _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 List methodChannelPlugins = _filterMethodChannelPlugins(plugins, LinuxPlugin.kConfigKey); + final List> linuxMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, LinuxPlugin.kConfigKey); + final List ffiPlugins = _filterFfiPlugins(plugins, LinuxPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains); + final List> linuxFfiPlugins = _extractPlatformMaps(ffiPlugins, LinuxPlugin.kConfigKey); + final Map context = { + 'os': 'linux', + 'methodChannelPlugins': linuxMethodChannelPlugins, + 'ffiPlugins': linuxFfiPlugins, + '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 { + await _renderTemplateToFile( + _linuxPluginRegistryHeaderTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.h'), + globals.templateRenderer, + ); + await _renderTemplateToFile( + _linuxPluginRegistryImplementationTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.cc'), + globals.templateRenderer, + ); +} + +Future _writePluginCmakefile(File destinationFile, Map templateContext, TemplateRenderer templateRenderer) async { + await _renderTemplateToFile( + _pluginCmakefileTemplate, + templateContext, + destinationFile, + templateRenderer, + ); +} + +Future _writeMacOSPluginRegistrant(FlutterProject project, List plugins) async { + final List methodChannelPlugins = _filterMethodChannelPlugins(plugins, MacOSPlugin.kConfigKey); + final List> macosMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, MacOSPlugin.kConfigKey); + final Map context = { + 'os': 'macos', + 'framework': 'FlutterMacOS', + 'methodChannelPlugins': macosMethodChannelPlugins, + }; + await _renderTemplateToFile( + _swiftPluginRegistryTemplate, + context, + project.macos.managedDirectory.childFile('GeneratedPluginRegistrant.swift'), + globals.templateRenderer, + ); +} + +/// Filters out any plugins that don't use method channels, and thus shouldn't be added to the native generated registrants. +List _filterMethodChannelPlugins(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).hasMethodChannel(); + } + // 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(); +} + +/// Filters out Dart-only and method channel plugins. +/// +/// FFI plugins do not need native code registration, but their binaries need to be bundled. +List _filterFfiPlugins(List 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(); +} + +/// Returns only the plugins with the given platform variant. +List _filterPluginsByVariant(List plugins, String platformKey, PluginPlatformVariant variant) { + return plugins.where((Plugin element) { + final PluginPlatform? platformPlugin = element.platforms[platformKey]; + if (platformPlugin == null) { + return false; + } + assert(platformPlugin is VariantPlatformPlugin); + return (platformPlugin as VariantPlatformPlugin).supportedVariants.contains(variant); + }).toList(); +} + +@visibleForTesting +Future writeWindowsPluginFiles( + FlutterProject project, + List plugins, + TemplateRenderer templateRenderer, { + Iterable? allowedPlugins, +}) async { + final List methodChannelPlugins = _filterMethodChannelPlugins(plugins, WindowsPlugin.kConfigKey); + if (allowedPlugins != null) { + final List 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()); + } + } + final List win32Plugins = _filterPluginsByVariant(methodChannelPlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.win32); + final List> windowsMethodChannelPlugins = _extractPlatformMaps(win32Plugins, WindowsPlugin.kConfigKey); + final List ffiPlugins = _filterFfiPlugins(plugins, WindowsPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains); + final List> windowsFfiPlugins = _extractPlatformMaps(ffiPlugins, WindowsPlugin.kConfigKey); + final Map context = { + 'os': 'windows', + 'methodChannelPlugins': windowsMethodChannelPlugins, + 'ffiPlugins': windowsFfiPlugins, + 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windows), + }; + await _writeCppPluginRegistrant(project.windows.managedDirectory, context, templateRenderer); + await _writePluginCmakefile(project.windows.generatedPluginCmakeFile, context, templateRenderer); +} + +Future _writeCppPluginRegistrant(Directory destination, Map templateContext, TemplateRenderer templateRenderer) async { + await _renderTemplateToFile( + _cppPluginRegistryHeaderTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.h'), + templateRenderer, + ); + await _renderTemplateToFile( + _cppPluginRegistryImplementationTemplate, + templateContext, + destination.childFile('generated_plugin_registrant.cc'), + templateRenderer, + ); +} + +Future _writeWebPluginRegistrant(FlutterProject project, List plugins, Directory destination) async { + final List> webPlugins = _extractPlatformMaps(plugins, WebPlugin.kConfigKey); + final Map context = { + 'methodChannelPlugins': webPlugins, + }; + + final File pluginFile = destination.childFile('web_plugin_registrant.dart'); + + final String template = webPlugins.isEmpty ? _noopDartPluginRegistryTemplate : _dartPluginRegistryTemplate; + + await _renderTemplateToFile( + template, + 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 [refreshPluginsList] 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, + ); + } +} + +/// Handler for symlink failures which provides specific instructions for known +/// failure cases. +@visibleForTesting +void handleSymlinkException(FileSystemException e, { + required Platform platform, + required OperatingSystemUtils os, + required String destination, + required String source, +}) { + 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'); + } + // 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.', + ); + } + } +} + +/// 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, + destination: 'dest', + source: 'source', + ); + 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 +/// 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`). +/// +/// 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 +Future injectBuildTimePluginFiles( + FlutterProject project, { + required Directory destination, + 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 (webPlatform) { + await _writeWebPluginRegistrant(project, plugins, destination); + } +} + +/// Injects plugins found in `pubspec.yaml` into the platform-specific projects. +/// +/// 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. +/// +/// 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, + Iterable? allowedPlugins, +}) 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, allowedPlugins: allowedPlugins); + } + 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); + } + } + } +} + +/// 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; +} + +/// Resolves the platform implementation for Dart-only plugins. +/// +/// * If there is only one dependency on a package that implements the +/// frontend plugin for the current platform, use that. +/// * If there is a single direct dependency on a package that implements the +/// 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. +/// * Else fail. +/// +/// For more details, https://flutter.dev/go/federated-plugins. +// TODO(stuartmorgan): Expand implementation to apply to all implementations, +// not just Dart-only, per the federated plugin spec. +List resolvePlatformImplementation( + List plugins, { + bool throwOnPluginPubspecError = true, +}) { + final List platforms = [ + AndroidPlugin.kConfigKey, + IOSPlugin.kConfigKey, + LinuxPlugin.kConfigKey, + MacOSPlugin.kConfigKey, + WindowsPlugin.kConfigKey, + ]; + final Map> possibleResolutions + = >{}; + final Map defaultImplementations = {}; + // Generates a key for the maps above. + String getResolutionKey({required String platform, required String packageName}) { + return '$packageName:$platform'; + } + + bool hasPubspecError = false; + for (final Plugin plugin in plugins) { + for (final String platform in platforms) { + if (plugin.platforms[platform] == null && + plugin.defaultPackagePlatforms[platform] == null) { + // The plugin doesn't implement this platform. + continue; + } + String? implementsPackage = plugin.implementsPackage; + if (implementsPackage == null || implementsPackage.isEmpty) { + final String? defaultImplementation = plugin.defaultPackagePlatforms[platform]; + final bool hasInlineDartImplementation = + plugin.pluginDartClassPlatforms[platform] != null; + if (defaultImplementation == null && !hasInlineDartImplementation) { + if (throwOnPluginPubspecError) { + globals.printError( + "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: \n' + '\n' + 'To set a default implementation, use:\n' + 'flutter:\n' + ' plugin:\n' + ' platforms:\n' + ' $platform:\n' + ' $kDefaultPackage: \n' + '\n' + 'To implement an interface, use:\n' + 'flutter:\n' + ' plugin:\n' + ' implements: ' + '\n' + ); + } + hasPubspecError = true; + continue; + } + final String defaultImplementationKey = getResolutionKey(platform: platform, packageName: plugin.name); + if (defaultImplementation != null) { + defaultImplementations[defaultImplementationKey] = defaultImplementation; + continue; + } 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; + defaultImplementations[defaultImplementationKey] = plugin.name; + } else { + // If it doesn't meet any of the conditions, it isn't eligible for + // auto-registration. + continue; + } + } + } + // If there's no Dart implementation, there's nothing to register. + if (plugin.pluginDartClassPlatforms[platform] == null || + plugin.pluginDartClassPlatforms[platform] == 'none') { + continue; + } + + // 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] = []; + } + possibleResolutions[resolutionKey]!.add(PluginInterfaceResolution( + plugin: plugin, + platform: platform, + )); + } + } + if (hasPubspecError && throwOnPluginPubspecError) { + throwToolExit('Please resolve the errors'); + } + + // Now resolve all the possible resolutions to a single option for each + // plugin, or throw if that's not possible. + bool hasResolutionError = false; + final List finalResolution = []; + for (final MapEntry> entry in possibleResolutions.entries) { + final List 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 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; + } + } + // 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'); + } + 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. //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 generateMainDartWithPluginRegistrant( + FlutterProject rootProject, + PackageConfig packageConfig, + String currentMainUri, + File mainFile, { + bool throwOnPluginPubspecError = false, +}) async { + final List plugins = await findPlugins(rootProject); + final List resolutions = resolvePlatformImplementation( + plugins, + throwOnPluginPubspecError: throwOnPluginPubspecError, + ); + final LanguageVersion entrypointVersion = determineLanguageVersion( + mainFile, + packageConfig.packageOf(mainFile.absolute.uri), + Cache.flutterRoot!, + ); + final Map templateContext = { + 'mainEntrypoint': currentMainUri, + 'dartLanguageVersion': entrypointVersion.toString(), + AndroidPlugin.kConfigKey: [], + IOSPlugin.kConfigKey: [], + LinuxPlugin.kConfigKey: [], + MacOSPlugin.kConfigKey: [], + WindowsPlugin.kConfigKey: [], + }; + final File newMainDart = rootProject.dartPluginRegistrant; + if (resolutions.isEmpty) { + try { + if (await newMainDart.exists()) { + await newMainDart.delete(); + } + } on FileSystemException catch (error) { + globals.printWarning( + '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)); + (templateContext[resolution.platform] as List?)?.add(resolution.toMap()); + } + try { + await _renderTemplateToFile( + _dartPluginRegistryForNonWebTemplate, + templateContext, + newMainDart, + globals.templateRenderer, + ); + } on FileSystemException catch (error) { + globals.printError('Unable to write ${newMainDart.path}, received error: $error'); + rethrow; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_project_metadata.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_project_metadata.dart new file mode 100644 index 0000000000000000000000000000000000000000..c4c1e9146d1afc0720edd8fa766d591b6501b27d --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_project_metadata.dart @@ -0,0 +1,379 @@ +// 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:yaml/yaml.dart'; + +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/utils.dart'; +import 'features.dart'; +import 'project.dart'; +import 'template.dart'; +import 'version.dart'; + +enum FlutterProjectType implements CliEnum { + /// This is the default project with the user-managed host code. + /// It is different than the "module" template in that it exposes and doesn't + /// manage the platform code. + app, + + /// A List/Detail app template that follows community best practices. + skeleton, + + /// The is a project that has managed platform host code. It is an application with + /// ephemeral .ios and .android directories that can be updated automatically. + module, + + /// This is a Flutter Dart package project. It doesn't have any native + /// components, only Dart. + package, + + /// This is a Dart package project with external builds for native components. + packageFfi, + + /// This is a native plugin project. + plugin, + + /// This is an FFI native plugin project. + pluginFfi; + + @override + String get cliName => snakeCase(name); + + @override + String get helpText => switch (this) { + FlutterProjectType.app => '(default) Generate a Flutter application.', + FlutterProjectType.skeleton => + 'Generate a List View / Detail View Flutter application that follows community best practices.', + FlutterProjectType.package => + 'Generate a shareable Flutter project containing modular Dart code.', + FlutterProjectType.plugin => + 'Generate a shareable Flutter project containing an API ' + 'in Dart code with a platform-specific implementation through method channels for Android, iOS, ' + 'Linux, macOS, Windows, web, or any combination of these.', + FlutterProjectType.pluginFfi => + 'Generate a shareable Flutter project containing an API ' + 'in Dart code with a platform-specific implementation through dart:ffi for Android, iOS, ' + 'Linux, macOS, Windows, or any combination of these.', + FlutterProjectType.packageFfi => + 'Generate a shareable Dart/Flutter project containing an API ' + 'in Dart code with a platform-specific implementation through dart:ffi for Android, iOS, ' + 'Linux, macOS, and Windows.', + FlutterProjectType.module => + 'Generate a project to add a Flutter module to an existing Android or iOS application.', + }; + + static FlutterProjectType? fromCliName(String value) { + for (final FlutterProjectType type in FlutterProjectType.values) { + if (value == type.cliName) { + return type; + } + } + return null; + } + + static List get enabledValues { + return [ + for (final FlutterProjectType value in values) + if (value == FlutterProjectType.packageFfi) ...[ + if (featureFlags.isNativeAssetsEnabled) value + ] else + value, + ]; + } +} + + /// Verifies the expected yaml keys are present in the file. + bool _validateMetadataMap(YamlMap map, Map validations, Logger logger) { + bool isValid = true; + for (final MapEntry entry in validations.entries) { + if (!map.keys.contains(entry.key)) { + isValid = false; + logger.printTrace('The key `${entry.key}` was not found'); + break; + } + final Object? metadataValue = map[entry.key]; + if (metadataValue.runtimeType != entry.value) { + isValid = false; + logger.printTrace('The value of key `${entry.key}` in .metadata was expected to be ${entry.value} but was ${metadataValue.runtimeType}'); + break; + } + } + return isValid; + } + +/// A wrapper around the `.metadata` file. +class FlutterProjectMetadata { + /// Creates a MigrateConfig by parsing an existing .migrate_config yaml file. + FlutterProjectMetadata(this.file, Logger logger) : _logger = logger, + migrateConfig = MigrateConfig() { + if (!file.existsSync()) { + _logger.printTrace('No .metadata file found at ${file.path}.'); + // Create a default empty metadata. + return; + } + Object? yamlRoot; + try { + yamlRoot = loadYaml(file.readAsStringSync()); + } on YamlException { + // Handled in _validate below. + } + if (yamlRoot is! YamlMap) { + _logger.printTrace('.metadata file at ${file.path} was empty or malformed.'); + return; + } + if (_validateMetadataMap(yamlRoot, {'version': YamlMap}, _logger)) { + final Object? versionYamlMap = yamlRoot['version']; + if (versionYamlMap is YamlMap && _validateMetadataMap(versionYamlMap, { + 'revision': String, + 'channel': String, + }, _logger)) { + _versionRevision = versionYamlMap['revision'] as String?; + _versionChannel = versionYamlMap['channel'] as String?; + } + } + if (_validateMetadataMap(yamlRoot, {'project_type': String}, _logger)) { + _projectType = FlutterProjectType.fromCliName(yamlRoot['project_type'] as String); + } + final Object? migrationYaml = yamlRoot['migration']; + if (migrationYaml is YamlMap) { + migrateConfig.parseYaml(migrationYaml, _logger); + } + } + + /// Creates a FlutterProjectMetadata by explicitly providing all values. + FlutterProjectMetadata.explicit({ + required this.file, + required String? versionRevision, + required String? versionChannel, + required FlutterProjectType? projectType, + required this.migrateConfig, + required Logger logger, + }) : _logger = logger, + _versionChannel = versionChannel, + _versionRevision = versionRevision, + _projectType = projectType; + + /// The name of the config file. + static const String kFileName = '.metadata'; + + String? _versionRevision; + String? get versionRevision => _versionRevision; + + String? _versionChannel; + String? get versionChannel => _versionChannel; + + FlutterProjectType? _projectType; + FlutterProjectType? get projectType => _projectType; + + /// Metadata and configuration for the migrate command. + MigrateConfig migrateConfig; + + final Logger _logger; + + final File file; + + /// Writes the .migrate_config file in the provided project directory's platform subdirectory. + /// + /// We write the file manually instead of with a template because this + /// needs to be able to write the .migrate_config file into legacy apps. + void writeFile({File? outputFile}) { + outputFile = outputFile ?? file; + outputFile + ..createSync(recursive: true) + ..writeAsStringSync(toString(), flush: true); + } + + @override + String toString() { + return ''' +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: ${escapeYamlString(_versionRevision ?? '')} + channel: ${escapeYamlString(_versionChannel ?? kUserBranch)} + +project_type: ${projectType == null ? '' : projectType!.cliName} +${migrateConfig.getOutputFileString()}'''; + } + + void populate({ + List? platforms, + required Directory projectDirectory, + String? currentRevision, + String? createRevision, + bool create = true, + bool update = true, + required Logger logger, + }) { + migrateConfig.populate( + platforms: platforms, + projectDirectory: projectDirectory, + currentRevision: currentRevision, + createRevision: createRevision, + create: create, + update: update, + logger: logger, + ); + } + + /// Finds the fallback revision to use when no base revision is found in the migrate config. + String getFallbackBaseRevision(Logger logger, FlutterVersion flutterVersion) { + // Use the .metadata file if it exists. + if (versionRevision != null) { + return versionRevision!; + } + return flutterVersion.frameworkRevision; + } +} + +/// Represents the migrate command metadata section of a .metadata file. +/// +/// This file tracks the flutter sdk git hashes of the last successful migration ('base') and +/// the version the project was created with. +/// +/// Each platform tracks a different set of revisions because flutter create can be +/// used to add support for new platforms, so the base and create revision may not always be the same. +class MigrateConfig { + MigrateConfig({ + Map? platformConfigs, + this.unmanagedFiles = kDefaultUnmanagedFiles + }) : platformConfigs = platformConfigs ?? {}; + + /// A mapping of the files that are unmanaged by default for each platform. + static const List kDefaultUnmanagedFiles = [ + 'lib/main.dart', + 'ios/Runner.xcodeproj/project.pbxproj', + ]; + + /// The metadata for each platform supported by the project. + final Map platformConfigs; + + /// A list of paths relative to this file the migrate tool should ignore. + /// + /// These files are typically user-owned files that should not be changed. + List unmanagedFiles; + + bool get isEmpty => platformConfigs.isEmpty && (unmanagedFiles.isEmpty || unmanagedFiles == kDefaultUnmanagedFiles); + + /// Parses the project for all supported platforms and populates the [MigrateConfig] + /// to reflect the project. + void populate({ + List? platforms, + required Directory projectDirectory, + String? currentRevision, + String? createRevision, + bool create = true, + bool update = true, + required Logger logger, + }) { + final FlutterProject flutterProject = FlutterProject.fromDirectory(projectDirectory); + platforms ??= flutterProject.getSupportedPlatforms(includeRoot: true); + + for (final SupportedPlatform platform in platforms) { + if (platformConfigs.containsKey(platform)) { + if (update) { + platformConfigs[platform]!.baseRevision = currentRevision; + } + } else { + if (create) { + platformConfigs[platform] = MigratePlatformConfig(platform: platform, createRevision: createRevision, baseRevision: currentRevision); + } + } + } + } + + /// Returns the string that should be written to the .metadata file. + String getOutputFileString() { + String unmanagedFilesString = ''; + for (final String path in unmanagedFiles) { + unmanagedFilesString += "\n - '$path'"; + } + + String platformsString = ''; + for (final MapEntry entry in platformConfigs.entries) { + platformsString += '\n - platform: ${entry.key.toString().split('.').last}\n create_revision: ${entry.value.createRevision == null ? 'null' : "${entry.value.createRevision}"}\n base_revision: ${entry.value.baseRevision == null ? 'null' : "${entry.value.baseRevision}"}'; + } + + return isEmpty ? '' : ''' + +# Tracks metadata for the flutter migrate command +migration: + platforms:$platformsString + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files:$unmanagedFilesString +'''; + } + + /// Parses and validates the `migration` section of the .metadata file. + void parseYaml(YamlMap map, Logger logger) { + final Object? platformsYaml = map['platforms']; + if (_validateMetadataMap(map, {'platforms': YamlList}, logger)) { + if (platformsYaml is YamlList && platformsYaml.isNotEmpty) { + for (final YamlMap platformYamlMap in platformsYaml.whereType()) { + if (_validateMetadataMap(platformYamlMap, { + 'platform': String, + 'create_revision': String, + 'base_revision': String, + }, logger)) { + final SupportedPlatform platformValue = SupportedPlatform.values.firstWhere( + (SupportedPlatform val) => val.toString() == 'SupportedPlatform.${platformYamlMap['platform'] as String}' + ); + platformConfigs[platformValue] = MigratePlatformConfig( + platform: platformValue, + createRevision: platformYamlMap['create_revision'] as String?, + baseRevision: platformYamlMap['base_revision'] as String?, + ); + } else { + // malformed platform entry + continue; + } + } + } + } + if (_validateMetadataMap(map, {'unmanaged_files': YamlList}, logger)) { + final Object? unmanagedFilesYaml = map['unmanaged_files']; + if (unmanagedFilesYaml is YamlList && unmanagedFilesYaml.isNotEmpty) { + unmanagedFiles = List.from(unmanagedFilesYaml.value.cast()); + } + } + } +} + +/// Holds the revisions for a single platform for use by the flutter migrate command. +class MigratePlatformConfig { + MigratePlatformConfig({ + required this.platform, + this.createRevision, + this.baseRevision + }); + + /// The platform this config describes. + SupportedPlatform platform; + + /// The Flutter SDK revision this platform was created by. + /// + /// Null if the initial create git revision is unknown. + final String? createRevision; + + /// The Flutter SDK revision this platform was last migrated by. + /// + /// Null if the project was never migrated or the revision is unknown. + String? baseRevision; + + bool equals(MigratePlatformConfig other) { + return platform == other.platform && + createRevision == other.createRevision && + baseRevision == other.baseRevision; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/globals.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/globals.dart new file mode 100644 index 0000000000000000000000000000000000000000..9cdf8ad3a425bf307ff7045fc4c20e7ba9b3ddd5 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/globals.dart @@ -0,0 +1,304 @@ +// 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:process/process.dart'; +import 'package:unified_analytics/unified_analytics.dart'; + +import 'android/android_sdk.dart'; +import 'android/android_studio.dart'; +import 'android/gradle_utils.dart'; +import 'android/java.dart'; +import 'artifacts.dart'; +import 'base/bot_detector.dart'; +import 'base/config.dart'; +import 'base/context.dart'; +import 'base/error_handling_io.dart'; +import 'base/file_system.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/net.dart'; +import 'base/os.dart'; +import 'base/platform.dart'; +import 'base/process.dart'; +import 'base/signals.dart'; +import 'base/template.dart'; +import 'base/terminal.dart'; +import 'base/time.dart'; +import 'base/user_messages.dart'; +import 'build_system/build_system.dart'; +import 'cache.dart'; +import 'custom_devices/custom_devices_config.dart'; +import 'device.dart'; +import 'doctor.dart'; +import 'fuchsia/fuchsia_sdk.dart'; +import 'ios/ios_workflow.dart'; +import 'ios/plist_parser.dart'; +import 'ios/simulators.dart'; +import 'ios/xcodeproj.dart'; +import 'macos/cocoapods.dart'; +import 'macos/cocoapods_validator.dart'; +import 'macos/xcdevice.dart'; +import 'macos/xcode.dart'; +import 'persistent_tool_state.dart'; +import 'pre_run_validator.dart'; +import 'project.dart'; +import 'reporting/crash_reporting.dart'; +import 'reporting/reporting.dart'; +import 'runner/flutter_command.dart'; +import 'runner/local_engine.dart'; +import 'version.dart'; + +// TODO(ianh): We should remove all the global variables and replace them with +// arguments (to constructors, methods, etc, as appropriate). + +Artifacts? get artifacts => context.get(); +BuildSystem get buildSystem => context.get()!; +Cache get cache => context.get()!; +CocoaPodsValidator? get cocoapodsValidator => context.get(); +Config get config => context.get()!; +CrashReporter? get crashReporter => context.get(); +DeviceManager? get deviceManager => context.get(); +Doctor? get doctor => context.get(); +HttpClientFactory? get httpClientFactory => context.get(); +IOSSimulatorUtils? get iosSimulatorUtils => context.get(); +Logger get logger => context.get()!; +OperatingSystemUtils get os => context.get()!; +Signals get signals => context.get() ?? LocalSignals.instance; +AndroidStudio? get androidStudio => context.get(); +AndroidSdk? get androidSdk => context.get(); +FlutterVersion get flutterVersion => context.get()!; +FuchsiaArtifacts? get fuchsiaArtifacts => context.get(); +FuchsiaSdk? get fuchsiaSdk => context.get(); +Usage get flutterUsage => context.get()!; +XcodeProjectInterpreter? get xcodeProjectInterpreter => context.get(); +XCDevice? get xcdevice => context.get(); +Xcode? get xcode => context.get(); +IOSWorkflow? get iosWorkflow => context.get(); +LocalEngineLocator? get localEngineLocator => context.get(); + +PersistentToolState? get persistentToolState => PersistentToolState.instance; + +BotDetector get botDetector => context.get() ?? _defaultBotDetector; +final BotDetector _defaultBotDetector = BotDetector( + httpClientFactory: context.get() ?? () => HttpClient(), + platform: platform, + persistentToolState: persistentToolState ?? PersistentToolState( + fileSystem: fs, + logger: logger, + platform: platform, + ), +); +Future get isRunningOnBot => botDetector.isRunningOnBot; + +// Analytics instance for package:unified_analytics for analytics +// reporting for all Flutter and Dart related tooling +Analytics get analytics => context.get()!; + +/// Currently active implementation of the file system. +/// +/// By default it uses local disk-based implementation. Override this in tests +/// with [MemoryFileSystem]. +FileSystem get fs => ErrorHandlingFileSystem( + delegate: context.get() ?? localFileSystem, + platform: platform, +); + +FileSystemUtils get fsUtils => context.get() ?? FileSystemUtils( + fileSystem: fs, + platform: platform, +); + +const ProcessManager _kLocalProcessManager = LocalProcessManager(); + +/// The active process manager. +ProcessManager get processManager => context.get() ?? _kLocalProcessManager; +ProcessUtils get processUtils => context.get()!; + +const Platform _kLocalPlatform = LocalPlatform(); +Platform get platform => context.get() ?? _kLocalPlatform; + +UserMessages get userMessages => context.get()!; + +final OutputPreferences _default = OutputPreferences( + wrapText: stdio.hasTerminal, + showColor: platform.stdoutSupportsAnsi, + stdio: stdio, +); +OutputPreferences get outputPreferences => context.get() ?? _default; + +/// The current system clock instance. +SystemClock get systemClock => context.get() ?? _systemClock; +SystemClock _systemClock = const SystemClock(); + +ProcessInfo get processInfo => context.get()!; + +/// Display an error level message to the user. Commands should use this if they +/// fail in some way. +/// +/// Set [emphasis] to true to make the output bold if it's supported. +/// Set [color] to a [TerminalColor] to color the output, if the logger +/// supports it. The [color] defaults to [TerminalColor.red]. +void printError( + String message, { + StackTrace? stackTrace, + bool? emphasis, + TerminalColor? color, + int? indent, + int? hangingIndent, + bool? wrap, + }) { + logger.printError( + message, + stackTrace: stackTrace, + emphasis: emphasis ?? false, + color: color, + indent: indent, + hangingIndent: hangingIndent, + wrap: wrap, + ); +} + +/// Display a warning level message to the user. Commands should use this if they +/// have important warnings to convey that aren't fatal. +/// +/// Set [emphasis] to true to make the output bold if it's supported. +/// Set [color] to a [TerminalColor] to color the output, if the logger +/// supports it. The [color] defaults to [TerminalColor.cyan]. +void printWarning( + String message, { + bool? emphasis, + TerminalColor? color, + int? indent, + int? hangingIndent, + bool? wrap, + }) { + logger.printWarning( + message, + emphasis: emphasis ?? false, + color: color, + indent: indent, + hangingIndent: hangingIndent, + wrap: wrap, + ); +} + +/// Display normal output of the command. This should be used for things like +/// progress messages, success messages, or just normal command output. +/// +/// Set `emphasis` to true to make the output bold if it's supported. +/// +/// Set `newline` to false to skip the trailing linefeed. +/// +/// If `indent` is provided, each line of the message will be prepended by the +/// specified number of whitespaces. +void printStatus( + String message, { + bool? emphasis, + bool? newline, + TerminalColor? color, + int? indent, + int? hangingIndent, + bool? wrap, + }) { + logger.printStatus( + message, + emphasis: emphasis ?? false, + color: color, + newline: newline ?? true, + indent: indent, + hangingIndent: hangingIndent, + wrap: wrap, + ); +} + + +/// Display the [message] inside a box. +/// +/// For example, this is the generated output: +/// +/// ┌─ [title] ─┐ +/// │ [message] │ +/// └───────────┘ +/// +/// If a terminal is attached, the lines in [message] are automatically wrapped based on +/// the available columns. +void printBox(String message, { + String? title, +}) { + logger.printBox(message, title: title); +} + +/// Use this for verbose tracing output. Users can turn this output on in order +/// to help diagnose issues with the toolchain or with their setup. +void printTrace(String message) => logger.printTrace(message); + +AnsiTerminal get terminal { + return context.get() ?? _defaultAnsiTerminal; +} + +final AnsiTerminal _defaultAnsiTerminal = AnsiTerminal( + stdio: stdio, + platform: platform, + now: DateTime.now(), +); + +/// The global Stdio wrapper. +Stdio get stdio => context.get() ?? (_stdioInstance ??= Stdio()); +Stdio? _stdioInstance; + +PlistParser get plistParser => context.get() ?? ( + _plistInstance ??= PlistParser( + fileSystem: fs, + processManager: processManager, + logger: logger, + )); +PlistParser? _plistInstance; + +/// The global template renderer. +TemplateRenderer get templateRenderer => context.get()!; + +/// Global [ShutdownHooks] that should be run before the tool process exits. +/// +/// This is depended on by [localFileSystem] which is called before any +/// [Context] is set up, and thus this cannot be a Context getter. +final ShutdownHooks shutdownHooks = ShutdownHooks(); + +// Unless we're in a test of this class's signal handling features, we must +// have only one instance created with the singleton LocalSignals instance +// and the catchable signals it considers to be fatal. +LocalFileSystem? _instance; +LocalFileSystem get localFileSystem => _instance ??= LocalFileSystem( + LocalSignals.instance, + Signals.defaultExitSignals, + shutdownHooks, +); + +/// Gradle utils in the current [AppContext]. +GradleUtils? get gradleUtils => context.get(); + +CocoaPods? get cocoaPods => context.get(); + +FlutterProjectFactory get projectFactory { + return context.get() ?? FlutterProjectFactory( + logger: logger, + fileSystem: fs, + ); +} + +CustomDevicesConfig get customDevicesConfig => context.get()!; + +PreRunValidator get preRunValidator => context.get() ?? const NoOpPreRunValidator(); + +// Used to build RegExp instances which can detect the VM service message. +final RegExp kVMServiceMessageRegExp = RegExp(r'The Dart VM service is listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)'); + +// The official tool no longer allows non-null safe builds. This can be +// overridden in other clients. +NonNullSafeBuilds get nonNullSafeBuilds => context.get() ?? NonNullSafeBuilds.notAllowed; + +/// Contains information about the JRE/JDK to use for Java-dependent operations. +/// +/// A value of [null] indicates that no installation of java could be found on +/// the host machine. +Java? get java => context.get(); diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/html_utils.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/html_utils.dart new file mode 100644 index 0000000000000000000000000000000000000000..ad394aaa909a3ba0ea43cf665fce225bf87ed1d0 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/html_utils.dart @@ -0,0 +1,113 @@ +// 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:html/dom.dart'; +import 'package:html/parser.dart'; + +import 'base/common.dart'; + +/// Placeholder for base href +const String kBaseHrefPlaceholder = r'$FLUTTER_BASE_HREF'; + +/// Utility class for parsing and performing operations on the contents of the +/// index.html file. +/// +/// For example, to parse the base href from the index.html file: +/// +/// ```dart +/// String parseBaseHref(File indexHtmlFile) { +/// final IndexHtml indexHtml = IndexHtml(indexHtmlFile.readAsStringSync()); +/// return indexHtml.getBaseHref(); +/// } +/// ``` +class IndexHtml { + IndexHtml(this._content); + + String get content => _content; + String _content; + + Document _getDocument() => parse(_content); + + /// Parses the base href from the index.html file. + String getBaseHref() { + final Element? baseElement = _getDocument().querySelector('base'); + final String? baseHref = baseElement?.attributes == null + ? null + : baseElement!.attributes['href']; + + if (baseHref == null || baseHref == kBaseHrefPlaceholder) { + return ''; + } + + if (!baseHref.startsWith('/')) { + throw ToolExit( + 'Error: The base href in "web/index.html" must be absolute (i.e. start ' + 'with a "/"), but found: `${baseElement!.outerHtml}`.\n' + '$_kBasePathExample', + ); + } + + if (!baseHref.endsWith('/')) { + throw ToolExit( + 'Error: The base href in "web/index.html" must end with a "/", but found: `${baseElement!.outerHtml}`.\n' + '$_kBasePathExample', + ); + } + + return stripLeadingSlash(stripTrailingSlash(baseHref)); + } + + /// Applies substitutions to the content of the index.html file. + void applySubstitutions({ + required String baseHref, + required String? serviceWorkerVersion, + }) { + if (_content.contains(kBaseHrefPlaceholder)) { + _content = _content.replaceAll(kBaseHrefPlaceholder, baseHref); + } + + if (serviceWorkerVersion != null) { + _content = _content + .replaceFirst( + // Support older `var` syntax as well as new `const` syntax + RegExp('(const|var) serviceWorkerVersion = null'), + 'const serviceWorkerVersion = "$serviceWorkerVersion"', + ) + // This is for legacy index.html that still uses the old service + // worker loading mechanism. + .replaceFirst( + "navigator.serviceWorker.register('flutter_service_worker.js')", + "navigator.serviceWorker.register('flutter_service_worker.js?v=$serviceWorkerVersion')", + ); + } + } +} + +/// Strips the leading slash from a path. +String stripLeadingSlash(String path) { + while (path.startsWith('/')) { + path = path.substring(1); + } + return path; +} + +/// Strips the trailing slash from a path. +String stripTrailingSlash(String path) { + while (path.endsWith('/')) { + path = path.substring(0, path.length - 1); + } + return path; +} + +const String _kBasePathExample = ''' +For example, to serve from the root use: + + + +To serve from a subpath "foo" (i.e. http://localhost:8080/foo/ instead of http://localhost:8080/) use: + + + +For more information, see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base +'''; diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/http_host_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/http_host_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..71f1dec5c1e4d12cdeda2bee0f2cf648ffb81c30 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/http_host_validator.dart @@ -0,0 +1,149 @@ +// 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 'base/io.dart'; +import 'base/net.dart'; +import 'base/platform.dart'; +import 'doctor_validator.dart'; +import 'features.dart'; + +/// Common Flutter HTTP hosts. +const String kCloudHost = 'https://storage.googleapis.com/'; +const String kCocoaPods = 'https://cocoapods.org/'; +const String kGitHub = 'https://github.com/'; +const String kMaven = 'https://maven.google.com/'; +const String kPubDev = 'https://pub.dev/'; + +// Overridable environment variables. +const String kPubDevOverride = 'PUB_HOSTED_URL'; // https://dart.dev/tools/pub/environment-variables + +// Validator that checks all provided hosts are reachable and responsive +class HttpHostValidator extends DoctorValidator { + HttpHostValidator({ + required Platform platform, + required FeatureFlags featureFlags, + required HttpClient httpClient, + }) : _platform = platform, + _featureFlags = featureFlags, + _httpClient = httpClient, + super('Network resources'); + + final Platform _platform; + final FeatureFlags _featureFlags; + final HttpClient _httpClient; + + final Set _activeHosts = {}; + + @override + String get slowWarning { + if (_activeHosts.isEmpty) { + return 'Network resources check is taking a long time...'; + } + return 'Attempting to reach ${_activeHosts.map((Uri url) => url.host).join(", ")}...'; + } + + /// Make a head request to the HTTP host for checking availability + Future _checkHostAvailability(Uri host) async { + try { + assert(!_activeHosts.contains(host)); + _activeHosts.add(host); + final HttpClientRequest req = await _httpClient.headUrl(host); + await req.close(); + // HTTP host is available if no exception happened. + return null; + } on SocketException catch (error) { + return 'A network error occurred while checking "$host": ${error.message}'; + } on HttpException catch (error) { + return 'An HTTP error occurred while checking "$host": ${error.message}'; + } on HandshakeException catch (error) { + return 'A cryptographic error occurred while checking "$host": ${error.message}\n' + 'You may be experiencing a man-in-the-middle attack, your network may be ' + 'compromised, or you may have malware installed on your computer.'; + } on OSError catch (error) { + return 'An error occurred while checking "$host": ${error.message}'; + } finally { + _activeHosts.remove(host); + } + } + + static Uri? _parseUrl(String value) { + final Uri? url = Uri.tryParse(value); + if (url == null || !url.hasScheme || !url.hasAuthority || (!url.hasEmptyPath && !url.hasAbsolutePath) || url.hasFragment) { + return null; + } + return url; + } + + @override + Future validate() async { + final List availabilityResults = []; + + final List requiredHosts = []; + if (_platform.environment.containsKey(kPubDevOverride)) { + final Uri? url = _parseUrl(_platform.environment[kPubDevOverride]!); + if (url == null) { + availabilityResults.add( + 'Environment variable $kPubDevOverride does not specify a valid URL: "${_platform.environment[kPubDevOverride]}"\n' + 'Please see https://flutter.dev/community/china for an example of how to use it.' + ); + } else { + requiredHosts.add(url); + } + } else { + requiredHosts.add(Uri.parse(kPubDev)); + } + if (_platform.environment.containsKey(kFlutterStorageBaseUrl)) { + final Uri? url = _parseUrl(_platform.environment[kFlutterStorageBaseUrl]!); + if (url == null) { + availabilityResults.add( + 'Environment variable $kFlutterStorageBaseUrl does not specify a valid URL: "${_platform.environment[kFlutterStorageBaseUrl]}"\n' + 'Please see https://flutter.dev/community/china for an example of how to use it.' + ); + } else { + requiredHosts.add(url); + } + } else { + requiredHosts.add(Uri.parse(kCloudHost)); + if (_featureFlags.isAndroidEnabled) { + // if kFlutterStorageBaseUrl is set it is used instead of Maven + requiredHosts.add(Uri.parse(kMaven)); + } + } + if (_featureFlags.isMacOSEnabled) { + requiredHosts.add(Uri.parse(kCocoaPods)); + } + requiredHosts.add(Uri.parse(kGitHub)); + + // Check all the hosts simultaneously. + availabilityResults.addAll(await Future.wait(requiredHosts.map(_checkHostAvailability))); + + int failures = 0; + int successes = 0; + final List messages = []; + for (final String? message in availabilityResults) { + if (message == null) { + successes += 1; + } else { + failures += 1; + messages.add(ValidationMessage.error(message)); + } + } + + if (failures == 0) { + assert(successes > 0); + assert(messages.isEmpty); + return const ValidationResult( + ValidationType.success, + [ValidationMessage('All expected network resources are available.')], + ); + } + assert(messages.isNotEmpty); + return ValidationResult( + successes == 0 ? ValidationType.notAvailable : ValidationType.partial, + messages, + ); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/license_collector.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/license_collector.dart new file mode 100644 index 0000000000000000000000000000000000000000..289962a40e56490918b9768c4d097638ca6aca66 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/license_collector.dart @@ -0,0 +1,159 @@ +// 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:package_config/package_config.dart'; + +import 'base/file_system.dart'; + +/// Processes dependencies into a string representing the NOTICES file. +/// +/// Reads the NOTICES or LICENSE file from each package in the .packages file, +/// splitting each one into each component license so that it can be de-duped +/// if possible. If the NOTICES file exists, it is preferred over the LICENSE +/// file. +/// +/// Individual licenses inside each LICENSE file should be separated by 80 +/// hyphens on their own on a line. +/// +/// If a LICENSE or NOTICES file contains more than one component license, +/// then each component license must start with the names of the packages to +/// which the component license applies, with each package name on its own line +/// and the list of package names separated from the actual license text by a +/// blank line. The packages need not match the names of the pub package. For +/// example, a package might itself contain code from multiple third-party +/// sources, and might need to include a license for each one. +class LicenseCollector { + LicenseCollector({ + required FileSystem fileSystem + }) : _fileSystem = fileSystem; + + final FileSystem _fileSystem; + + /// The expected separator for multiple licenses. + static final String licenseSeparator = '\n${'-' * 80}\n'; + + /// Obtain licenses from the `packageMap` into a single result. + /// + /// [additionalLicenses] should contain aggregated license files from all + /// of the current applications dependencies. + LicenseResult obtainLicenses( + PackageConfig packageConfig, + Map> additionalLicenses, + ) { + final Map> packageLicenses = >{}; + final Set allPackages = {}; + final List dependencies = []; + + for (final Package package in packageConfig.packages) { + final Uri packageUri = package.packageUriRoot; + if (packageUri.scheme != 'file') { + continue; + } + // First check for NOTICES, then fallback to LICENSE + File file = _fileSystem.file(packageUri.resolve('../NOTICES')); + if (!file.existsSync()) { + file = _fileSystem.file(packageUri.resolve('../LICENSE')); + } + if (!file.existsSync()) { + continue; + } + + dependencies.add(file); + final List rawLicenses = file + .readAsStringSync() + .split(licenseSeparator); + for (final String rawLicense in rawLicenses) { + List packageNames = []; + String? licenseText; + if (rawLicenses.length > 1) { + final int split = rawLicense.indexOf('\n\n'); + if (split >= 0) { + packageNames = rawLicense.substring(0, split).split('\n'); + licenseText = rawLicense.substring(split + 2); + } + } + if (licenseText == null) { + packageNames = [package.name]; + licenseText = rawLicense; + } + packageLicenses.putIfAbsent(licenseText, () => {}).addAll(packageNames); + allPackages.addAll(packageNames); + } + } + + final List combinedLicensesList = packageLicenses.entries + .map((MapEntry> entry) { + final List packageNames = entry.value.toList()..sort(); + return '${packageNames.join('\n')}\n\n${entry.key}'; + }).toList(); + combinedLicensesList.sort(); + + /// Append additional LICENSE files as specified in the pubspec.yaml. + final List additionalLicenseText = []; + final List errorMessages = []; + for (final String package in additionalLicenses.keys) { + for (final File license in additionalLicenses[package]!) { + if (!license.existsSync()) { + errorMessages.add( + 'package $package specified an additional license at ${license.path}, but this file ' + 'does not exist.' + ); + continue; + } + dependencies.add(license); + try { + additionalLicenseText.add(license.readAsStringSync()); + } on FormatException catch (err) { + // File has an invalid encoding. + errorMessages.add( + 'package $package specified an additional license at ${license.path}, but this file ' + 'could not be read:\n$err' + ); + } on FileSystemException catch (err) { + // File cannot be parsed. + errorMessages.add( + 'package $package specified an additional license at ${license.path}, but this file ' + 'could not be read:\n$err' + ); + } + } + } + if (errorMessages.isNotEmpty) { + return LicenseResult( + combinedLicenses: '', + dependencies: [], + errorMessages: errorMessages, + ); + } + + final String combinedLicenses = combinedLicensesList + .followedBy(additionalLicenseText) + .join(licenseSeparator); + + return LicenseResult( + combinedLicenses: combinedLicenses, + dependencies: dependencies, + errorMessages: errorMessages, + ); + } +} + +/// The result of processing licenses with a [LicenseCollector]. +class LicenseResult { + const LicenseResult({ + required this.combinedLicenses, + required this.dependencies, + required this.errorMessages, + }); + + /// The raw text of the consumed licenses. + final String combinedLicenses; + + /// Each license file that was consumed as input. + final List dependencies; + + /// If non-empty, license collection failed and this messages should + /// be displayed by the asset parser. + final List errorMessages; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/mdns_discovery.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/mdns_discovery.dart new file mode 100644 index 0000000000000000000000000000000000000000..7034b46e5108dbd43703d04680d65f114fb3eb92 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/mdns_discovery.dart @@ -0,0 +1,592 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:multicast_dns/multicast_dns.dart'; +import 'package:unified_analytics/unified_analytics.dart'; + +import 'base/common.dart'; +import 'base/context.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'build_info.dart'; +import 'convert.dart'; +import 'device.dart'; +import 'reporting/reporting.dart'; + +/// A wrapper around [MDnsClient] to find a Dart VM Service instance. +class MDnsVmServiceDiscovery { + /// Creates a new [MDnsVmServiceDiscovery] object. + /// + /// The [_client] parameter will be defaulted to a new [MDnsClient] if null. + MDnsVmServiceDiscovery({ + MDnsClient? mdnsClient, + MDnsClient? preliminaryMDnsClient, + required Logger logger, + required Usage flutterUsage, + required Analytics analytics, + }) : _client = mdnsClient ?? MDnsClient(), + _preliminaryClient = preliminaryMDnsClient, + _logger = logger, + _flutterUsage = flutterUsage, + _analytics = analytics; + + final MDnsClient _client; + + // Used when discovering VM services with `queryForAttach` to do a preliminary + // check for already running services so that results are not cached in _client. + final MDnsClient? _preliminaryClient; + + final Logger _logger; + final Usage _flutterUsage; + final Analytics _analytics; + + @visibleForTesting + static const String dartVmServiceName = '_dartVmService._tcp.local'; + + static MDnsVmServiceDiscovery? get instance => context.get(); + + /// Executes an mDNS query for Dart VM Services. + /// Checks for services that have already been launched. + /// If none are found, it will listen for new services to become active + /// and return the first it finds that match the parameters. + /// + /// The [applicationId] parameter may be used to specify which application + /// to find. For Android, it refers to the package name; on iOS, it refers to + /// the bundle ID. + /// + /// The [deviceVmservicePort] parameter may be used to specify which port + /// to find. + /// + /// The [useDeviceIPAsHost] parameter flags whether to get the device IP + /// and the [ipv6] parameter flags whether to get an iPv6 address + /// (otherwise it will get iPv4). + /// + /// The [timeout] parameter determines how long to continue to wait for + /// services to become active. + /// + /// If [applicationId] is not null, this method will find the port and authentication code + /// of the Dart VM Service for that application. If it cannot find a service matching + /// that application identifier after the [timeout], it will call [throwToolExit]. + /// + /// If [applicationId] is null and there are multiple Dart VM Services available, + /// the user will be prompted with a list of available services with the respective + /// app-id and device-vmservice-port to use and asked to select one. + /// + /// If it is null and there is only one available or it's the first found instance + /// of Dart VM Service, it will return that instance's information regardless of + /// what application the service instance is for. + @visibleForTesting + Future queryForAttach({ + String? applicationId, + int? deviceVmservicePort, + bool ipv6 = false, + bool useDeviceIPAsHost = false, + Duration timeout = const Duration(minutes: 10), + }) async { + // Poll for 5 seconds to see if there are already services running. + // Use a new instance of MDnsClient so results don't get cached in _client. + // If no results are found, poll for a longer duration to wait for connections. + // If more than 1 result is found, throw an error since it can't be determined which to pick. + // If only one is found, return it. + final List results = await _pollingVmService( + _preliminaryClient ?? MDnsClient(), + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + ipv6: ipv6, + useDeviceIPAsHost: useDeviceIPAsHost, + timeout: const Duration(seconds: 5), + ); + if (results.isEmpty) { + return firstMatchingVmService( + _client, + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + ipv6: ipv6, + useDeviceIPAsHost: useDeviceIPAsHost, + timeout: timeout, + ); + } else if (results.length > 1) { + final StringBuffer buffer = StringBuffer(); + buffer.writeln('There are multiple Dart VM Services available.'); + buffer.writeln('Rerun this command with one of the following passed in as the app-id and device-vmservice-port:'); + buffer.writeln(); + for (final MDnsVmServiceDiscoveryResult result in results) { + buffer.writeln( + ' flutter attach --app-id "${result.domainName.replaceAll('.$dartVmServiceName', '')}" --device-vmservice-port ${result.port}'); + } + throwToolExit(buffer.toString()); + } + return results.first; + } + + /// Executes an mDNS query for Dart VM Services. + /// Listens for new services to become active and returns the first it finds that + /// match the parameters. + /// + /// The [applicationId] parameter must be set to specify which application + /// to find. For Android, it refers to the package name; on iOS, it refers to + /// the bundle ID. + /// + /// The [deviceVmservicePort] parameter must be set to specify which port + /// to find. + /// + /// [applicationId] and either [deviceVmservicePort] or [deviceName] are + /// required for launch so that if multiple flutter apps are running on + /// different devices, it will only match with the device running the desired app. + /// + /// The [useDeviceIPAsHost] parameter flags whether to get the device IP + /// and the [ipv6] parameter flags whether to get an iPv6 address + /// (otherwise it will get iPv4). + /// + /// The [timeout] parameter determines how long to continue to wait for + /// services to become active. + /// + /// If a Dart VM Service matching the [applicationId] and + /// [deviceVmservicePort]/[deviceName] cannot be found before the [timeout] + /// is reached, it will call [throwToolExit]. + @visibleForTesting + Future queryForLaunch({ + required String applicationId, + int? deviceVmservicePort, + String? deviceName, + bool ipv6 = false, + bool useDeviceIPAsHost = false, + Duration timeout = const Duration(minutes: 10), + }) async { + // Either the device port or the device name must be provided. + assert(deviceVmservicePort != null || deviceName != null); + + // Query for a specific application matching on either device port or device name. + return firstMatchingVmService( + _client, + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + deviceName: deviceName, + ipv6: ipv6, + useDeviceIPAsHost: useDeviceIPAsHost, + timeout: timeout, + ); + } + + /// Polls for Dart VM Services and returns the first it finds that match + /// the [applicationId]/[deviceVmservicePort] (if applicable). + /// Returns null if no results are found. + @visibleForTesting + Future firstMatchingVmService( + MDnsClient client, { + String? applicationId, + int? deviceVmservicePort, + String? deviceName, + bool ipv6 = false, + bool useDeviceIPAsHost = false, + Duration timeout = const Duration(minutes: 10), + }) async { + final List results = await _pollingVmService( + client, + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + deviceName: deviceName, + ipv6: ipv6, + useDeviceIPAsHost: useDeviceIPAsHost, + timeout: timeout, + quitOnFind: true, + ); + if (results.isEmpty) { + return null; + } + return results.first; + } + + Future> _pollingVmService( + MDnsClient client, { + String? applicationId, + int? deviceVmservicePort, + String? deviceName, + bool ipv6 = false, + bool useDeviceIPAsHost = false, + required Duration timeout, + bool quitOnFind = false, + }) async { + _logger.printTrace('Checking for advertised Dart VM Services...'); + try { + await client.start(); + + final List results = + []; + + // uniqueDomainNames is used to track all domain names of Dart VM services + // It is later used in this function to determine whether or not to throw an error. + // We do not want to throw the error if it was unable to find any domain + // names because that indicates it may be a problem with mDNS, which has + // a separate error message in _checkForIPv4LinkLocal. + final Set uniqueDomainNames = {}; + // uniqueDomainNamesInResults is used to filter out duplicates with exactly + // the same domain name from the results. + final Set uniqueDomainNamesInResults = {}; + + // Listen for mDNS connections until timeout. + final Stream ptrResourceStream = client.lookup( + ResourceRecordQuery.serverPointer(dartVmServiceName), + timeout: timeout + ); + await for (final PtrResourceRecord ptr in ptrResourceStream) { + uniqueDomainNames.add(ptr.domainName); + + String? domainName; + if (applicationId != null) { + // If applicationId is set, only use records that match it + if (ptr.domainName.toLowerCase().startsWith(applicationId.toLowerCase())) { + domainName = ptr.domainName; + } else { + continue; + } + } else { + domainName = ptr.domainName; + } + + // Result with same domain name was already found, skip it. + if (uniqueDomainNamesInResults.contains(domainName)) { + continue; + } + + _logger.printTrace('Checking for available port on $domainName'); + final List srvRecords = await client + .lookup( + ResourceRecordQuery.service(domainName), + ) + .toList(); + if (srvRecords.isEmpty) { + continue; + } + + // If more than one SrvResourceRecord found, it should just be a duplicate. + final SrvResourceRecord srvRecord = srvRecords.first; + if (srvRecords.length > 1) { + _logger.printWarning( + 'Unexpectedly found more than one Dart VM Service report for $domainName ' + '- using first one (${srvRecord.port}).'); + } + + // If deviceVmservicePort is set, only use records that match it + if (deviceVmservicePort != null && srvRecord.port != deviceVmservicePort) { + continue; + } + + // If deviceName is set, only use records that match it + if (deviceName != null && !deviceNameMatchesTargetName(deviceName, srvRecord.target)) { + continue; + } + + // Get the IP address of the device if using the IP as the host. + InternetAddress? ipAddress; + if (useDeviceIPAsHost) { + List ipAddresses = await client + .lookup( + ipv6 + ? ResourceRecordQuery.addressIPv6(srvRecord.target) + : ResourceRecordQuery.addressIPv4(srvRecord.target), + ) + .toList(); + if (ipAddresses.isEmpty) { + throwToolExit('Did not find IP for service ${srvRecord.target}.'); + } + + // Filter out link-local addresses. + if (ipAddresses.length > 1) { + ipAddresses = ipAddresses.where((IPAddressResourceRecord element) => !element.address.isLinkLocal).toList(); + } + + ipAddress = ipAddresses.first.address; + if (ipAddresses.length > 1) { + _logger.printWarning( + 'Unexpectedly found more than one IP for Dart VM Service ${srvRecord.target} ' + '- using first one ($ipAddress).'); + } + } + + _logger.printTrace('Checking for authentication code for $domainName'); + final List txt = await client + .lookup( + ResourceRecordQuery.text(domainName), + ) + .toList(); + + String authCode = ''; + if (txt.isNotEmpty) { + authCode = _getAuthCode(txt.first.text); + } + results.add(MDnsVmServiceDiscoveryResult( + domainName, + srvRecord.port, + authCode, + ipAddress: ipAddress + )); + uniqueDomainNamesInResults.add(domainName); + if (quitOnFind) { + return results; + } + } + + // If applicationId is set and quitOnFind is true and no results matching + // the applicationId were found but other results were found, throw an error. + if (applicationId != null && + quitOnFind && + results.isEmpty && + uniqueDomainNames.isNotEmpty) { + String message = 'Did not find a Dart VM Service advertised for $applicationId'; + if (deviceVmservicePort != null) { + message += ' on port $deviceVmservicePort'; + } + throwToolExit('$message.'); + } + + return results; + } finally { + client.stop(); + } + } + + @visibleForTesting + bool deviceNameMatchesTargetName(String deviceName, String targetName) { + // Remove `.local` from the name along with any non-word, non-digit characters. + final RegExp cleanedNameRegex = RegExp(r'\.local|\W'); + final String cleanedDeviceName = deviceName.trim().toLowerCase().replaceAll(cleanedNameRegex, ''); + final String cleanedTargetName = targetName.toLowerCase().replaceAll(cleanedNameRegex, ''); + return cleanedDeviceName == cleanedTargetName; + } + + String _getAuthCode(String txtRecord) { + const String authCodePrefix = 'authCode='; + final Iterable matchingRecords = + LineSplitter.split(txtRecord).where((String record) => record.startsWith(authCodePrefix)); + if (matchingRecords.isEmpty) { + return ''; + } + String authCode = matchingRecords.first.substring(authCodePrefix.length); + // The Dart VM Service currently expects a trailing '/' as part of the + // URI, otherwise an invalid authentication code response is given. + if (!authCode.endsWith('/')) { + authCode += '/'; + } + return authCode; + } + + /// Gets Dart VM Service Uri for `flutter attach`. + /// Executes an mDNS query and waits until a Dart VM Service is found. + /// + /// When [useDeviceIPAsHost] is true, it will use the device's IP as the + /// host and will not forward the port. + /// + /// Differs from [getVMServiceUriForLaunch] because it can search for any available Dart VM Service. + /// Since [applicationId] and [deviceVmservicePort] are optional, it can either look for any service + /// or a specific service matching [applicationId]/[deviceVmservicePort]. + /// It may find more than one service, which will throw an error listing the found services. + Future getVMServiceUriForAttach( + String? applicationId, + Device device, { + bool usesIpv6 = false, + int? hostVmservicePort, + int? deviceVmservicePort, + bool useDeviceIPAsHost = false, + Duration timeout = const Duration(minutes: 10), + }) async { + final MDnsVmServiceDiscoveryResult? result = await queryForAttach( + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + ipv6: usesIpv6, + useDeviceIPAsHost: useDeviceIPAsHost, + timeout: timeout, + ); + return _handleResult( + result, + device, + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + hostVmservicePort: hostVmservicePort, + usesIpv6: usesIpv6, + useDeviceIPAsHost: useDeviceIPAsHost + ); + } + + /// Gets Dart VM Service Uri for `flutter run`. + /// Executes an mDNS query and waits until the Dart VM Service service is found. + /// + /// When [useDeviceIPAsHost] is true, it will use the device's IP as the + /// host and will not forward the port. + /// + /// Differs from [getVMServiceUriForAttach] because it only searches for a specific service. + /// This is enforced by [applicationId] being required and using either the + /// [deviceVmservicePort] or the [device]'s name to query. + Future getVMServiceUriForLaunch( + String applicationId, + Device device, { + bool usesIpv6 = false, + int? hostVmservicePort, + int? deviceVmservicePort, + bool useDeviceIPAsHost = false, + Duration timeout = const Duration(minutes: 10), + }) async { + final MDnsVmServiceDiscoveryResult? result = await queryForLaunch( + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + deviceName: deviceVmservicePort == null ? device.name : null, + ipv6: usesIpv6, + useDeviceIPAsHost: useDeviceIPAsHost, + timeout: timeout, + ); + return _handleResult( + result, + device, + applicationId: applicationId, + deviceVmservicePort: deviceVmservicePort, + hostVmservicePort: hostVmservicePort, + usesIpv6: usesIpv6, + useDeviceIPAsHost: useDeviceIPAsHost + ); + } + + Future _handleResult( + MDnsVmServiceDiscoveryResult? result, + Device device, { + String? applicationId, + int? deviceVmservicePort, + int? hostVmservicePort, + bool usesIpv6 = false, + bool useDeviceIPAsHost = false, + }) async { + if (result == null) { + await _checkForIPv4LinkLocal(device); + return null; + } + final String host; + + final InternetAddress? ipAddress = result.ipAddress; + if (useDeviceIPAsHost && ipAddress != null) { + host = ipAddress.address; + } else { + host = usesIpv6 + ? InternetAddress.loopbackIPv6.address + : InternetAddress.loopbackIPv4.address; + } + return buildVMServiceUri( + device, + host, + result.port, + hostVmservicePort, + result.authCode, + useDeviceIPAsHost, + ); + } + + // If there's not an ipv4 link local address in `NetworkInterfaces.list`, + // then request user interventions with a `printError()` if possible. + Future _checkForIPv4LinkLocal(Device device) async { + _logger.printTrace( + 'mDNS query failed. Checking for an interface with a ipv4 link local address.' + ); + final List interfaces = await listNetworkInterfaces( + includeLinkLocal: true, + type: InternetAddressType.IPv4, + ); + if (_logger.isVerbose) { + _logInterfaces(interfaces); + } + final bool hasIPv4LinkLocal = interfaces.any( + (NetworkInterface interface) => interface.addresses.any( + (InternetAddress address) => address.isLinkLocal, + ), + ); + if (hasIPv4LinkLocal) { + _logger.printTrace('An interface with an ipv4 link local address was found.'); + return; + } + final TargetPlatform targetPlatform = await device.targetPlatform; + switch (targetPlatform) { + case TargetPlatform.ios: + UsageEvent('ios-mdns', 'no-ipv4-link-local', flutterUsage: _flutterUsage).send(); + _analytics.send(Event.appleUsageEvent(workflow: 'ios-mdns', parameter: 'no-ipv4-link-local')); + _logger.printError( + 'The mDNS query for an attached iOS device failed. It may ' + 'be necessary to disable the "Personal Hotspot" on the device, and ' + 'to ensure that the "Disable unless needed" setting is unchecked ' + 'under System Preferences > Network > iPhone USB. ' + 'See https://github.com/flutter/flutter/issues/46698 for details.' + ); + case TargetPlatform.android: + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + case TargetPlatform.darwin: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.linux_arm64: + case TargetPlatform.linux_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case TargetPlatform.windows_x64: + _logger.printTrace('No interface with an ipv4 link local address was found.'); + } + } + + void _logInterfaces(List interfaces) { + for (final NetworkInterface interface in interfaces) { + if (_logger.isVerbose) { + _logger.printTrace('Found interface "${interface.name}":'); + for (final InternetAddress address in interface.addresses) { + final String linkLocal = address.isLinkLocal ? 'link local' : ''; + _logger.printTrace('\tBound address: "${address.address}" $linkLocal'); + } + } + } + } +} + +class MDnsVmServiceDiscoveryResult { + MDnsVmServiceDiscoveryResult( + this.domainName, + this.port, + this.authCode, { + this.ipAddress + }); + final String domainName; + final int port; + final String authCode; + final InternetAddress? ipAddress; +} + +Future buildVMServiceUri( + Device device, + String host, + int devicePort, [ + int? hostVmservicePort, + String? authCode, + bool useDeviceIPAsHost = false, +]) async { + String path = '/'; + if (authCode != null) { + path = authCode; + } + // Not having a trailing slash can cause problems in some situations. + // Ensure that there's one present. + if (!path.endsWith('/')) { + path += '/'; + } + hostVmservicePort ??= 0; + + final int? actualHostPort; + if (useDeviceIPAsHost) { + // When using the device's IP as the host, port forwarding is not required + // so just use the device's port. + actualHostPort = devicePort; + } else { + actualHostPort = hostVmservicePort == 0 ? + await device.portForwarder?.forward(devicePort) : + hostVmservicePort; + } + return Uri(scheme: 'http', host: host, port: actualHostPort, path: path); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/native_assets.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/native_assets.dart new file mode 100644 index 0000000000000000000000000000000000000000..506e9d7e1d18bf6836e8839350aea4c145212f88 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/native_assets.dart @@ -0,0 +1,699 @@ +// 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. + +// Logic for native assets shared between all host OSes. + +import 'package:logging/logging.dart' as logging; +import 'package:native_assets_builder/native_assets_builder.dart' hide NativeAssetsBuildRunner; +import 'package:native_assets_builder/native_assets_builder.dart' as native_assets_builder show NativeAssetsBuildRunner; +import 'package:native_assets_cli/native_assets_cli.dart'; +import 'package:package_config/package_config_types.dart'; + +import 'android/native_assets.dart'; +import 'base/common.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'build_info.dart' as build_info; +import 'cache.dart'; +import 'features.dart'; +import 'globals.dart' as globals; +import 'ios/native_assets.dart'; +import 'linux/native_assets.dart'; +import 'macos/native_assets.dart'; +import 'macos/native_assets_host.dart'; +import 'resident_runner.dart'; +import 'windows/native_assets.dart'; + +/// Programmatic API to be used by Dart launchers to invoke native builds. +/// +/// It enables mocking `package:native_assets_builder` package. +/// It also enables mocking native toolchain discovery via [cCompilerConfig]. +abstract class NativeAssetsBuildRunner { + /// Whether the project has a `.dart_tools/package_config.json`. + /// + /// If there is no package config, [packagesWithNativeAssets], [build], and + /// [dryRun] must not be invoked. + Future hasPackageConfig(); + + /// All packages in the transitive dependencies that have a `build.dart`. + Future> packagesWithNativeAssets(); + + /// Runs all [packagesWithNativeAssets] `build.dart` in dry run. + Future dryRun({ + required bool includeParentEnvironment, + required LinkModePreference linkModePreference, + required OS targetOS, + required Uri workingDirectory, + }); + + /// Runs all [packagesWithNativeAssets] `build.dart`. + Future build({ + required bool includeParentEnvironment, + required BuildMode buildMode, + required LinkModePreference linkModePreference, + required Target target, + required Uri workingDirectory, + CCompilerConfig? cCompilerConfig, + int? targetAndroidNdkApi, + IOSSdk? targetIOSSdk, + }); + + /// The C compiler config to use for compilation. + Future get cCompilerConfig; + + /// The NDK compiler to use to use for compilation for Android. + Future get ndkCCompilerConfig; +} + +/// Uses `package:native_assets_builder` for its implementation. +class NativeAssetsBuildRunnerImpl implements NativeAssetsBuildRunner { + NativeAssetsBuildRunnerImpl( + this.projectUri, + this.packageConfig, + this.fileSystem, + this.logger, + ); + + final Uri projectUri; + final PackageConfig packageConfig; + final FileSystem fileSystem; + final Logger logger; + + late final logging.Logger _logger = logging.Logger('') + ..onRecord.listen((logging.LogRecord record) { + final int levelValue = record.level.value; + final String message = record.message; + if (levelValue >= logging.Level.SEVERE.value) { + logger.printError(message); + } else if (levelValue >= logging.Level.WARNING.value) { + logger.printWarning(message); + } else if (levelValue >= logging.Level.INFO.value) { + logger.printTrace(message); + } else { + logger.printTrace(message); + } + }); + + late final Uri _dartExecutable = fileSystem.directory(Cache.flutterRoot).uri.resolve('bin/dart'); + + late final native_assets_builder.NativeAssetsBuildRunner _buildRunner = native_assets_builder.NativeAssetsBuildRunner( + logger: _logger, + dartExecutable: _dartExecutable, + ); + + @override + Future hasPackageConfig() { + final File packageConfigJson = + fileSystem.directory(projectUri.toFilePath()).childDirectory('.dart_tool').childFile('package_config.json'); + return packageConfigJson.exists(); + } + + @override + Future> packagesWithNativeAssets() async { + final PackageLayout packageLayout = PackageLayout.fromPackageConfig( + packageConfig, + projectUri.resolve('.dart_tool/package_config.json'), + ); + return packageLayout.packagesWithNativeAssets; + } + + @override + Future dryRun({ + required bool includeParentEnvironment, + required LinkModePreference linkModePreference, + required OS targetOS, + required Uri workingDirectory, + }) { + final PackageLayout packageLayout = PackageLayout.fromPackageConfig( + packageConfig, + projectUri.resolve('.dart_tool/package_config.json'), + ); + return _buildRunner.dryRun( + includeParentEnvironment: includeParentEnvironment, + linkModePreference: linkModePreference, + targetOs: targetOS, + workingDirectory: workingDirectory, + packageLayout: packageLayout, + ); + } + + @override + Future build({ + required bool includeParentEnvironment, + required BuildMode buildMode, + required LinkModePreference linkModePreference, + required Target target, + required Uri workingDirectory, + CCompilerConfig? cCompilerConfig, + int? targetAndroidNdkApi, + IOSSdk? targetIOSSdk, + }) { + final PackageLayout packageLayout = PackageLayout.fromPackageConfig( + packageConfig, + projectUri.resolve('.dart_tool/package_config.json'), + ); + return _buildRunner.build( + buildMode: buildMode, + cCompilerConfig: cCompilerConfig, + includeParentEnvironment: includeParentEnvironment, + linkModePreference: linkModePreference, + target: target, + targetAndroidNdkApi: targetAndroidNdkApi, + targetIOSSdk: targetIOSSdk, + workingDirectory: workingDirectory, + packageLayout: packageLayout, + ); + } + + @override + late final Future cCompilerConfig = () { + if (globals.platform.isMacOS || globals.platform.isIOS) { + return cCompilerConfigMacOS(); + } + if (globals.platform.isLinux) { + return cCompilerConfigLinux(); + } + if (globals.platform.isWindows) { + return cCompilerConfigWindows(); + } + if (globals.platform.isAndroid) { + throwToolExit('Should use ndkCCompilerConfig for Android.'); + } + throwToolExit('Unknown target OS.'); + }(); + + @override + late final Future ndkCCompilerConfig = () { + return cCompilerConfigAndroid(); + }(); +} + +/// Write [assets] to `native_assets.yaml` in [yamlParentDirectory]. +Future writeNativeAssetsYaml( + Iterable assets, + Uri yamlParentDirectory, + FileSystem fileSystem, +) async { + globals.logger.printTrace('Writing native_assets.yaml.'); + final String nativeAssetsDartContents = assets.toNativeAssetsFile(); + final Directory parentDirectory = fileSystem.directory(yamlParentDirectory); + if (!await parentDirectory.exists()) { + await parentDirectory.create(recursive: true); + } + final File nativeAssetsFile = parentDirectory.childFile('native_assets.yaml'); + await nativeAssetsFile.writeAsString(nativeAssetsDartContents); + globals.logger.printTrace('Writing ${nativeAssetsFile.path} done.'); + return nativeAssetsFile.uri; +} + +/// Select the native asset build mode for a given Flutter build mode. +BuildMode nativeAssetsBuildMode(build_info.BuildMode buildMode) { + switch (buildMode) { + case build_info.BuildMode.debug: + return BuildMode.debug; + case build_info.BuildMode.jitRelease: + case build_info.BuildMode.profile: + case build_info.BuildMode.release: + return BuildMode.release; + } +} + +/// Checks whether this project does not yet have a package config file. +/// +/// A project has no package config when `pub get` has not yet been run. +/// +/// Native asset builds cannot be run without a package config. If there is +/// no package config, leave a logging trace about that. +Future _hasNoPackageConfig(NativeAssetsBuildRunner buildRunner) async { + final bool packageConfigExists = await buildRunner.hasPackageConfig(); + if (!packageConfigExists) { + globals.logger.printTrace('No package config found. Skipping native assets compilation.'); + } + return !packageConfigExists; +} + +Future nativeBuildRequired(NativeAssetsBuildRunner buildRunner) async { + if (await _hasNoPackageConfig(buildRunner)) { + return false; + } + final List packagesWithNativeAssets = await buildRunner.packagesWithNativeAssets(); + if (packagesWithNativeAssets.isEmpty) { + globals.logger.printTrace( + 'No packages with native assets. Skipping native assets compilation.', + ); + return false; + } + + if (!featureFlags.isNativeAssetsEnabled) { + final String packageNames = packagesWithNativeAssets.map((Package p) => p.name).join(' '); + throwToolExit( + 'Package(s) $packageNames require the native assets feature to be enabled. ' + 'Enable using `flutter config --enable-native-assets`.', + ); + } + return true; +} + +/// Ensures that either this project has no native assets, or that native assets +/// are supported on that operating system. +/// +/// Exits the tool if the above condition is not satisfied. +Future ensureNoNativeAssetsOrOsIsSupported( + Uri workingDirectory, + String os, + FileSystem fileSystem, + NativeAssetsBuildRunner buildRunner, +) async { + if (await _hasNoPackageConfig(buildRunner)) { + return; + } + final List packagesWithNativeAssets = await buildRunner.packagesWithNativeAssets(); + if (packagesWithNativeAssets.isEmpty) { + globals.logger.printTrace( + 'No packages with native assets. Skipping native assets compilation.', + ); + return; + } + final String packageNames = packagesWithNativeAssets.map((Package p) => p.name).join(' '); + throwToolExit( + 'Package(s) $packageNames require the native assets feature. ' + 'This feature has not yet been implemented for `$os`. ' + 'For more info see https://github.com/flutter/flutter/issues/129757.', + ); +} + +/// Ensure all native assets have a linkmode declared to be dynamic loading. +/// +/// In JIT, the link mode must always be dynamic linking. +/// In AOT, the static linking has not yet been implemented in Dart: +/// https://github.com/dart-lang/sdk/issues/49418. +/// +/// Therefore, ensure all `build.dart` scripts return only dynamic libraries. +void ensureNoLinkModeStatic(List nativeAssets) { + final Iterable staticAssets = nativeAssets.whereLinkMode(LinkMode.static); + if (staticAssets.isNotEmpty) { + final String assetIds = staticAssets.map((Asset a) => a.id).toSet().join(', '); + throwToolExit( + 'Native asset(s) $assetIds have their link mode set to static, ' + 'but this is not yet supported. ' + 'For more info see https://github.com/dart-lang/sdk/issues/49418.', + ); + } +} + +/// This should be the same for different archs, debug/release, etc. +/// It should work for all macOS. +Uri nativeAssetsBuildUri(Uri projectUri, OS os) { + final String buildDir = build_info.getBuildDirectory(); + return projectUri.resolve('$buildDir/native_assets/$os/'); +} + +/// Gets the native asset id to dylib mapping to embed in the kernel file. +/// +/// Run hot compiles a kernel file that is pushed to the device after hot +/// restart. We need to embed the native assets mapping in order to access +/// native assets after hot restart. +Future dryRunNativeAssets({ + required Uri projectUri, + required FileSystem fileSystem, + required NativeAssetsBuildRunner buildRunner, + required List flutterDevices, +}) async { + if (flutterDevices.length != 1) { + return dryRunNativeAssetsMultipeOSes( + projectUri: projectUri, + fileSystem: fileSystem, + targetPlatforms: flutterDevices.map((FlutterDevice d) => d.targetPlatform).nonNulls, + buildRunner: buildRunner, + ); + } + final FlutterDevice flutterDevice = flutterDevices.single; + final build_info.TargetPlatform targetPlatform = flutterDevice.targetPlatform!; + + final Uri? nativeAssetsYaml; + switch (targetPlatform) { + case build_info.TargetPlatform.darwin: + nativeAssetsYaml = await dryRunNativeAssetsMacOS( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + case build_info.TargetPlatform.ios: + nativeAssetsYaml = await dryRunNativeAssetsIOS( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + case build_info.TargetPlatform.tester: + if (const LocalPlatform().isMacOS) { + nativeAssetsYaml = await dryRunNativeAssetsMacOS( + projectUri: projectUri, + flutterTester: true, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + } else if (const LocalPlatform().isLinux) { + nativeAssetsYaml = await dryRunNativeAssetsLinux( + projectUri: projectUri, + flutterTester: true, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + } else if (const LocalPlatform().isWindows) { + nativeAssetsYaml = await dryRunNativeAssetsWindows( + projectUri: projectUri, + flutterTester: true, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + } else { + await nativeBuildRequired(buildRunner); + nativeAssetsYaml = null; + } + case build_info.TargetPlatform.linux_arm64: + case build_info.TargetPlatform.linux_x64: + nativeAssetsYaml = await dryRunNativeAssetsLinux( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + case build_info.TargetPlatform.windows_x64: + nativeAssetsYaml = await dryRunNativeAssetsWindows( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + case build_info.TargetPlatform.android_arm: + case build_info.TargetPlatform.android_arm64: + case build_info.TargetPlatform.android_x64: + case build_info.TargetPlatform.android_x86: + case build_info.TargetPlatform.android: + nativeAssetsYaml = await dryRunNativeAssetsAndroid( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: buildRunner, + ); + case build_info.TargetPlatform.fuchsia_arm64: + case build_info.TargetPlatform.fuchsia_x64: + case build_info.TargetPlatform.web_javascript: + await ensureNoNativeAssetsOrOsIsSupported( + projectUri, + targetPlatform.toString(), + fileSystem, + buildRunner, + ); + nativeAssetsYaml = null; + } + return nativeAssetsYaml; +} + +/// Dry run the native builds for multiple OSes. +/// +/// Needed for `flutter run -d all`. +Future dryRunNativeAssetsMultipeOSes({ + required NativeAssetsBuildRunner buildRunner, + required Uri projectUri, + required FileSystem fileSystem, + required Iterable targetPlatforms, +}) async { + if (await nativeBuildRequired(buildRunner)) { + return null; + } + + final Uri buildUri = buildUriMultiple(projectUri); + final Iterable nativeAssetPaths = [ + if (targetPlatforms.contains(build_info.TargetPlatform.darwin) || + (targetPlatforms.contains(build_info.TargetPlatform.tester) && OS.current == OS.macOS)) + ...await dryRunNativeAssetsMacOSInternal( + fileSystem, + projectUri, + false, + buildRunner, + ), + if (targetPlatforms.contains(build_info.TargetPlatform.linux_arm64) || + targetPlatforms.contains(build_info.TargetPlatform.linux_x64) || + (targetPlatforms.contains(build_info.TargetPlatform.tester) && OS.current == OS.linux)) + ...await dryRunNativeAssetsLinuxInternal( + fileSystem, + projectUri, + false, + buildRunner, + ), + if (targetPlatforms.contains(build_info.TargetPlatform.windows_x64) || + (targetPlatforms.contains(build_info.TargetPlatform.tester) && OS.current == OS.windows)) + ...await dryRunNativeAssetsWindowsInternal( + fileSystem, + projectUri, + false, + buildRunner, + ), + if (targetPlatforms.contains(build_info.TargetPlatform.ios)) + ...await dryRunNativeAssetsIOSInternal( + fileSystem, + projectUri, + buildRunner, + ), + if (targetPlatforms.contains(build_info.TargetPlatform.android) || + targetPlatforms.contains(build_info.TargetPlatform.android_arm) || + targetPlatforms.contains(build_info.TargetPlatform.android_arm64) || + targetPlatforms.contains(build_info.TargetPlatform.android_x64) || + targetPlatforms.contains(build_info.TargetPlatform.android_x86)) + ...await dryRunNativeAssetsAndroidInternal( + fileSystem, + projectUri, + buildRunner, + ), + ]; + final Uri nativeAssetsUri = await writeNativeAssetsYaml(nativeAssetPaths, buildUri, fileSystem); + return nativeAssetsUri; +} + +/// With `flutter run -d all` we need a place to store the native assets +/// mapping for multiple OSes combined. +Uri buildUriMultiple(Uri projectUri) { + final String buildDir = build_info.getBuildDirectory(); + return projectUri.resolve('$buildDir/native_assets/multiple/'); +} + +/// Dry run the native builds. +/// +/// This does not build native assets, it only simulates what the final paths +/// of all assets will be so that this can be embedded in the kernel file. +Future dryRunNativeAssetsSingleArchitecture({ + required NativeAssetsBuildRunner buildRunner, + required Uri projectUri, + bool flutterTester = false, + required FileSystem fileSystem, + required OS os, +}) async { + if (!await nativeBuildRequired(buildRunner)) { + return null; + } + + final Uri buildUri = nativeAssetsBuildUri(projectUri, os); + final Iterable nativeAssetPaths = await dryRunNativeAssetsSingleArchitectureInternal( + fileSystem, + projectUri, + flutterTester, + buildRunner, + os, + ); + final Uri nativeAssetsUri = await writeNativeAssetsYaml( + nativeAssetPaths, + buildUri, + fileSystem, + ); + return nativeAssetsUri; +} + +Future> dryRunNativeAssetsSingleArchitectureInternal( + FileSystem fileSystem, + Uri projectUri, + bool flutterTester, + NativeAssetsBuildRunner buildRunner, + OS targetOS, +) async { + final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); + + globals.logger.printTrace('Dry running native assets for $targetOS.'); + + final DryRunResult dryRunResult = await buildRunner.dryRun( + linkModePreference: LinkModePreference.dynamic, + targetOS: targetOS, + workingDirectory: projectUri, + includeParentEnvironment: true, + ); + ensureNativeAssetsBuildSucceed(dryRunResult); + final List nativeAssets = dryRunResult.assets; + ensureNoLinkModeStatic(nativeAssets); + globals.logger.printTrace('Dry running native assets for $targetOS done.'); + final Uri? absolutePath = flutterTester ? buildUri : null; + final Map assetTargetLocations = _assetTargetLocationsSingleArchitecture( + nativeAssets, + absolutePath, + ); + final Iterable nativeAssetPaths = assetTargetLocations.values; + return nativeAssetPaths; +} + +/// Builds native assets. +/// +/// If [targetPlatform] is omitted, the current target architecture is used. +/// +/// If [flutterTester] is true, absolute paths are emitted in the native +/// assets mapping. This can be used for JIT mode without sandbox on the host. +/// This is used in `flutter test` and `flutter run -d flutter-tester`. +Future<(Uri? nativeAssetsYaml, List dependencies)> buildNativeAssetsSingleArchitecture({ + required NativeAssetsBuildRunner buildRunner, + build_info.TargetPlatform? targetPlatform, + required Uri projectUri, + required build_info.BuildMode buildMode, + bool flutterTester = false, + Uri? yamlParentDirectory, + required FileSystem fileSystem, +}) async { + final Target target = targetPlatform != null ? _getNativeTarget(targetPlatform) : Target.current; + final OS targetOS = target.os; + final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); + final Directory buildDir = fileSystem.directory(buildUri); + if (!await buildDir.exists()) { + // CMake requires the folder to exist to do copying. + await buildDir.create(recursive: true); + } + if (!await nativeBuildRequired(buildRunner)) { + final Uri nativeAssetsYaml = await writeNativeAssetsYaml( + [], + yamlParentDirectory ?? buildUri, + fileSystem, + ); + return (nativeAssetsYaml, []); + } + + final BuildMode buildModeCli = nativeAssetsBuildMode(buildMode); + + globals.logger.printTrace('Building native assets for $target $buildModeCli.'); + final BuildResult result = await buildRunner.build( + linkModePreference: LinkModePreference.dynamic, + target: target, + buildMode: buildModeCli, + workingDirectory: projectUri, + includeParentEnvironment: true, + cCompilerConfig: await buildRunner.cCompilerConfig, + ); + ensureNativeAssetsBuildSucceed(result); + final List nativeAssets = result.assets; + final Set dependencies = result.dependencies.toSet(); + ensureNoLinkModeStatic(nativeAssets); + globals.logger.printTrace('Building native assets for $target done.'); + final Uri? absolutePath = flutterTester ? buildUri : null; + final Map assetTargetLocations = _assetTargetLocationsSingleArchitecture(nativeAssets, absolutePath); + await _copyNativeAssetsSingleArchitecture( + buildUri, + assetTargetLocations, + buildMode, + fileSystem, + ); + final Uri nativeAssetsUri = await writeNativeAssetsYaml( + assetTargetLocations.values, + yamlParentDirectory ?? buildUri, + fileSystem, + ); + return (nativeAssetsUri, dependencies.toList()); +} + +Map _assetTargetLocationsSingleArchitecture( + List nativeAssets, + Uri? absolutePath, +) { + return { + for (final Asset asset in nativeAssets) + asset: _targetLocationSingleArchitecture( + asset, + absolutePath, + ), + }; +} + +Asset _targetLocationSingleArchitecture(Asset asset, Uri? absolutePath) { + final AssetPath path = asset.path; + switch (path) { + case AssetSystemPath _: + case AssetInExecutable _: + case AssetInProcess _: + return asset; + case AssetAbsolutePath _: + final String fileName = path.uri.pathSegments.last; + Uri uri; + if (absolutePath != null) { + // Flutter tester needs full host paths. + uri = absolutePath.resolve(fileName); + } else { + // Flutter Desktop needs "absolute" paths inside the app. + // "relative" in the context of native assets would be relative to the + // kernel or aot snapshot. + uri = Uri(path: fileName); + } + return asset.copyWith(path: AssetAbsolutePath(uri)); + } + throw Exception('Unsupported asset path type ${path.runtimeType} in asset $asset'); +} + +/// Extract the [Target] from a [TargetPlatform]. +/// +/// Does not cover MacOS, iOS, and Android as these pass the architecture +/// in other enums. +Target _getNativeTarget(build_info.TargetPlatform targetPlatform) { + switch (targetPlatform) { + case build_info.TargetPlatform.linux_x64: + return Target.linuxX64; + case build_info.TargetPlatform.linux_arm64: + return Target.linuxArm64; + case build_info.TargetPlatform.windows_x64: + return Target.windowsX64; + case build_info.TargetPlatform.android: + case build_info.TargetPlatform.ios: + case build_info.TargetPlatform.darwin: + case build_info.TargetPlatform.fuchsia_arm64: + case build_info.TargetPlatform.fuchsia_x64: + case build_info.TargetPlatform.tester: + case build_info.TargetPlatform.web_javascript: + case build_info.TargetPlatform.android_arm: + case build_info.TargetPlatform.android_arm64: + case build_info.TargetPlatform.android_x64: + case build_info.TargetPlatform.android_x86: + throw Exception('Unknown targetPlatform: $targetPlatform.'); + } +} + +Future _copyNativeAssetsSingleArchitecture( + Uri buildUri, + Map assetTargetLocations, + build_info.BuildMode buildMode, + FileSystem fileSystem, +) async { + if (assetTargetLocations.isNotEmpty) { + globals.logger.printTrace('Copying native assets to ${buildUri.toFilePath()}.'); + final Directory buildDir = fileSystem.directory(buildUri.toFilePath()); + if (!buildDir.existsSync()) { + buildDir.createSync(recursive: true); + } + for (final MapEntry assetMapping in assetTargetLocations.entries) { + final Uri source = (assetMapping.key.path as AssetAbsolutePath).uri; + final Uri target = (assetMapping.value.path as AssetAbsolutePath).uri; + final Uri targetUri = buildUri.resolveUri(target); + final String targetFullPath = targetUri.toFilePath(); + await fileSystem.file(source).copy(targetFullPath); + } + globals.logger.printTrace('Copying native assets done.'); + } +} + +void ensureNativeAssetsBuildSucceed(DryRunResult result) { + if (!result.success) { + throwToolExit( + 'Building native assets failed. See the logs for more details.', + ); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/persistent_tool_state.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/persistent_tool_state.dart new file mode 100644 index 0000000000000000000000000000000000000000..870beee972fd69db27a8631ebfb0d5118f288ffc --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/persistent_tool_state.dart @@ -0,0 +1,138 @@ +// 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 'base/config.dart'; +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'version.dart'; + +/// A class that represents global (non-project-specific) internal state that +/// must persist across tool invocations. +abstract class PersistentToolState { + factory PersistentToolState({ + required FileSystem fileSystem, + required Logger logger, + required Platform platform, + }) => _DefaultPersistentToolState( + fileSystem: fileSystem, + logger: logger, + platform: platform, + ); + + factory PersistentToolState.test({ + required Directory directory, + required Logger logger, + }) => _DefaultPersistentToolState.test( + directory: directory, + logger: logger, + ); + + static PersistentToolState? get instance => context.get(); + + /// Whether the welcome message should be redisplayed. + /// + /// May give null if the value has not been set. + bool? get shouldRedisplayWelcomeMessage; + void setShouldRedisplayWelcomeMessage(bool value); // Enforced nonnull setter. + + /// Returns the last active version for a given [channel]. + /// + /// If there was no active prior version, returns `null` instead. + String? lastActiveVersion(Channel channel); + + /// Update the last active version for a given [channel]. + void updateLastActiveVersion(String fullGitHash, Channel channel); + + /// Return the hash of the last active license terms. + String? get lastActiveLicenseTermsHash; + void setLastActiveLicenseTermsHash(String value); // Enforced nonnull setter. + + /// Whether this client was already determined to be or not be a bot. + bool? get isRunningOnBot; + void setIsRunningOnBot(bool value); // Enforced nonnull setter. +} + +class _DefaultPersistentToolState implements PersistentToolState { + _DefaultPersistentToolState({ + required FileSystem fileSystem, + required Logger logger, + required Platform platform, + }) : _config = Config( + _kFileName, + fileSystem: fileSystem, + logger: logger, + platform: platform, + ); + + @visibleForTesting + _DefaultPersistentToolState.test({ + required Directory directory, + required Logger logger, + }) : _config = Config.test( + name: _kFileName, + directory: directory, + logger: logger, + ); + + static const String _kFileName = 'tool_state'; + static const String _kRedisplayWelcomeMessage = 'redisplay-welcome-message'; + static const Map _lastActiveVersionKeys = { + Channel.master: 'last-active-master-version', + Channel.main: 'last-active-main-version', + Channel.beta: 'last-active-beta-version', + Channel.stable: 'last-active-stable-version', + }; + static const String _kBotKey = 'is-bot'; + static const String _kLicenseHash = 'license-hash'; + + final Config _config; + + @override + bool? get shouldRedisplayWelcomeMessage { + return _config.getValue(_kRedisplayWelcomeMessage) as bool?; + } + + @override + void setShouldRedisplayWelcomeMessage(bool value) { + _config.setValue(_kRedisplayWelcomeMessage, value); + } + + @override + String? lastActiveVersion(Channel channel) { + final String? versionKey = _versionKeyFor(channel); + assert(versionKey != null); + return _config.getValue(versionKey!) as String?; + } + + @override + void updateLastActiveVersion(String fullGitHash, Channel channel) { + final String? versionKey = _versionKeyFor(channel); + assert(versionKey != null); + _config.setValue(versionKey!, fullGitHash); + } + + @override + String? get lastActiveLicenseTermsHash => _config.getValue(_kLicenseHash) as String?; + + @override + void setLastActiveLicenseTermsHash(String value) { + _config.setValue(_kLicenseHash, value); + } + + String? _versionKeyFor(Channel channel) { + return _lastActiveVersionKeys[channel]; + } + + @override + bool? get isRunningOnBot => _config.getValue(_kBotKey) as bool?; + + @override + void setIsRunningOnBot(bool value) { + _config.setValue(_kBotKey, value); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/platform_plugins.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/platform_plugins.dart new file mode 100644 index 0000000000000000000000000000000000000000..fdc47378fe1d7fab868715159de157ab4bed64ee --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/platform_plugins.dart @@ -0,0 +1,598 @@ +// 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:yaml/yaml.dart'; + +import 'base/common.dart'; +import 'base/file_system.dart'; + +/// Constant for 'pluginClass' key in plugin maps. +const String kPluginClass = 'pluginClass'; + +/// Constant for 'dartPluginClass' key in plugin maps. +const String kDartPluginClass = 'dartPluginClass'; + +/// Constant for 'ffiPlugin' key in plugin maps. +const String kFfiPlugin = 'ffiPlugin'; + +// Constant for 'defaultPackage' key in plugin maps. +const String kDefaultPackage = 'default_package'; + +/// Constant for 'sharedDarwinSource' key in plugin maps. +/// Can be set for iOS and macOS plugins. +const String kSharedDarwinSource = 'sharedDarwinSource'; + +/// Constant for 'supportedVariants' key in plugin maps. +const String kSupportedVariants = 'supportedVariants'; + +/// Platform variants that a Windows plugin can support. +enum PluginPlatformVariant { + /// Win32 variant of Windows. + win32, +} + +/// Marker interface for all platform specific plugin config implementations. +abstract class PluginPlatform { + const PluginPlatform(); + + Map toMap(); +} + +/// A plugin that has platform variants. +abstract class VariantPlatformPlugin { + /// The platform variants supported by the plugin. + Set get supportedVariants; +} + +abstract class NativeOrDartPlugin { + /// Determines whether the plugin has a Dart implementation. + bool hasDart(); + + /// Determines whether the plugin has a FFI implementation. + bool hasFfi(); + + /// Determines whether the plugin has a method channel implementation. + bool hasMethodChannel(); +} + +abstract class DarwinPlugin { + /// Indicates the iOS and macOS native code is shareable the subdirectory "darwin", + bool get sharedDarwinSource; +} + +/// Contains parameters to template an Android plugin. +/// +/// The [name] of the plugin is required. Additionally, either: +/// - [defaultPackage], or +/// - an implementation consisting of: +/// - the [package] and [pluginClass] that will be the entry point to the +/// plugin's native code, and/or +/// - the [dartPluginClass] that will be the entry point for the plugin's +/// Dart code +/// is required. +class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin { + AndroidPlugin({ + required this.name, + required this.pluginPath, + this.package, + this.pluginClass, + this.dartPluginClass, + bool? ffiPlugin, + this.defaultPackage, + required FileSystem fileSystem, + }) : _fileSystem = fileSystem, + ffiPlugin = ffiPlugin ?? false; + + factory AndroidPlugin.fromYaml(String name, YamlMap yaml, String pluginPath, FileSystem fileSystem) { + assert(validate(yaml)); + return AndroidPlugin( + name: name, + package: yaml['package'] as String?, + pluginClass: yaml[kPluginClass] as String?, + dartPluginClass: yaml[kDartPluginClass] as String?, + ffiPlugin: yaml[kFfiPlugin] as bool?, + defaultPackage: yaml[kDefaultPackage] as String?, + pluginPath: pluginPath, + fileSystem: fileSystem, + ); + } + + final FileSystem _fileSystem; + + @override + bool hasMethodChannel() => pluginClass != null; + + @override + bool hasFfi() => ffiPlugin; + + @override + bool hasDart() => dartPluginClass != null; + + static bool validate(YamlMap yaml) { + return (yaml['package'] is String && yaml[kPluginClass] is String) || + yaml[kDartPluginClass] is String || + yaml[kFfiPlugin] == true || + yaml[kDefaultPackage] is String; + } + + static const String kConfigKey = 'android'; + + /// The plugin name defined in pubspec.yaml. + final String name; + + /// The plugin package name defined in pubspec.yaml. + final String? package; + + /// The native plugin main class defined in pubspec.yaml, if any. + final String? pluginClass; + + /// The Dart plugin main class defined in pubspec.yaml, if any. + final String? dartPluginClass; + + /// Is FFI plugin defined in pubspec.yaml. + final bool ffiPlugin; + + /// The default implementation package defined in pubspec.yaml, if any. + final String? defaultPackage; + + /// The absolute path to the plugin in the pub cache. + final String pluginPath; + + @override + Map toMap() { + return { + 'name': name, + if (package != null) 'package': package, + if (pluginClass != null) 'class': pluginClass, + if (dartPluginClass != null) kDartPluginClass : dartPluginClass, + if (ffiPlugin) kFfiPlugin: true, + if (defaultPackage != null) kDefaultPackage : defaultPackage, + // Mustache doesn't support complex types. + 'supportsEmbeddingV1': _supportedEmbeddings.contains('1'), + 'supportsEmbeddingV2': _supportedEmbeddings.contains('2'), + }; + } + + /// Returns the version of the Android embedding. + late final Set _supportedEmbeddings = _getSupportedEmbeddings(); + + Set _getSupportedEmbeddings() { + final Set supportedEmbeddings = {}; + final String baseMainPath = _fileSystem.path.join( + pluginPath, + 'android', + 'src', + 'main', + ); + + final String? package = this.package; + // Don't attempt to validate the native code if there isn't supposed to + // be any. + if (package == null) { + return supportedEmbeddings; + } + + final List mainClassCandidates = [ + _fileSystem.path.join( + baseMainPath, + 'java', + package.replaceAll('.', _fileSystem.path.separator), + '$pluginClass.java', + ), + _fileSystem.path.join( + baseMainPath, + 'kotlin', + package.replaceAll('.', _fileSystem.path.separator), + '$pluginClass.kt', + ), + ]; + + File? mainPluginClass; + bool mainClassFound = false; + for (final String mainClassCandidate in mainClassCandidates) { + mainPluginClass = _fileSystem.file(mainClassCandidate); + if (mainPluginClass.existsSync()) { + mainClassFound = true; + break; + } + } + if (mainPluginClass == null || !mainClassFound) { + assert(mainClassCandidates.length <= 2); + throwToolExit( + "The plugin `$name` doesn't have a main class defined in ${mainClassCandidates.join(' or ')}. " + "This is likely to due to an incorrect `androidPackage: $package` or `mainClass` entry in the plugin's pubspec.yaml.\n" + 'If you are the author of this plugin, fix the `androidPackage` entry or move the main class to any of locations used above. ' + 'Otherwise, please contact the author of this plugin and consider using a different plugin in the meanwhile. ' + ); + } + + final String mainClassContent = mainPluginClass.readAsStringSync(); + if (mainClassContent + .contains('io.flutter.embedding.engine.plugins.FlutterPlugin')) { + supportedEmbeddings.add('2'); + } else { + supportedEmbeddings.add('1'); + } + if (mainClassContent.contains('PluginRegistry') + && mainClassContent.contains('registerWith')) { + supportedEmbeddings.add('1'); + } + return supportedEmbeddings; + } +} + +/// Contains the parameters to template an iOS plugin. +/// +/// The [name] of the plugin is required. Additionally, either: +/// - [defaultPackage], or +/// - an implementation consisting of: +/// - the [pluginClass] (with optional [classPrefix]) that will be the entry +/// point to the plugin's native code, and/or +/// - the [dartPluginClass] that will be the entry point for the plugin's +/// Dart code +/// is required. +class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin, DarwinPlugin { + const IOSPlugin({ + required this.name, + required this.classPrefix, + this.pluginClass, + this.dartPluginClass, + bool? ffiPlugin, + this.defaultPackage, + bool? sharedDarwinSource, + }) : ffiPlugin = ffiPlugin ?? false, + sharedDarwinSource = sharedDarwinSource ?? false; + + factory IOSPlugin.fromYaml(String name, YamlMap yaml) { + assert(validate(yaml)); // TODO(zanderso): https://github.com/flutter/flutter/issues/67241 + return IOSPlugin( + name: name, + classPrefix: '', + pluginClass: yaml[kPluginClass] as String?, + dartPluginClass: yaml[kDartPluginClass] as String?, + ffiPlugin: yaml[kFfiPlugin] as bool?, + defaultPackage: yaml[kDefaultPackage] as String?, + sharedDarwinSource: yaml[kSharedDarwinSource] as bool?, + ); + } + + static bool validate(YamlMap yaml) { + return yaml[kPluginClass] is String || + yaml[kDartPluginClass] is String || + yaml[kFfiPlugin] == true || + yaml[kSharedDarwinSource] == true || + yaml[kDefaultPackage] is String; + } + + static const String kConfigKey = 'ios'; + + final String name; + + /// Note, this is here only for legacy reasons. Multi-platform format + /// always sets it to empty String. + final String classPrefix; + final String? pluginClass; + final String? dartPluginClass; + final bool ffiPlugin; + final String? defaultPackage; + + /// Indicates the iOS native code is shareable with macOS in + /// the subdirectory "darwin", otherwise in the subdirectory "ios". + @override + final bool sharedDarwinSource; + + @override + bool hasMethodChannel() => pluginClass != null; + + @override + bool hasFfi() => ffiPlugin; + + @override + bool hasDart() => dartPluginClass != null; + + @override + Map toMap() { + return { + 'name': name, + 'prefix': classPrefix, + if (pluginClass != null) 'class': pluginClass, + if (dartPluginClass != null) kDartPluginClass : dartPluginClass, + if (ffiPlugin) kFfiPlugin: true, + if (sharedDarwinSource) kSharedDarwinSource: true, + if (defaultPackage != null) kDefaultPackage : defaultPackage, + }; + } +} + +/// Contains the parameters to template a macOS plugin. +/// +/// The [name] of the plugin is required. Either [dartPluginClass] or +/// [pluginClass] or [ffiPlugin] are required. +/// [pluginClass] will be the entry point to the plugin's native code. +class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin, DarwinPlugin { + const MacOSPlugin({ + required this.name, + this.pluginClass, + this.dartPluginClass, + bool? ffiPlugin, + this.defaultPackage, + bool? sharedDarwinSource, + }) : ffiPlugin = ffiPlugin ?? false, + sharedDarwinSource = sharedDarwinSource ?? false; + + 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?; + if (pluginClass == 'none') { + pluginClass = null; + } + return MacOSPlugin( + name: name, + pluginClass: pluginClass, + dartPluginClass: yaml[kDartPluginClass] as String?, + ffiPlugin: yaml[kFfiPlugin] as bool?, + defaultPackage: yaml[kDefaultPackage] as String?, + sharedDarwinSource: yaml[kSharedDarwinSource] as bool?, + ); + } + + static bool validate(YamlMap yaml) { + return yaml[kPluginClass] is String || + yaml[kDartPluginClass] is String || + yaml[kFfiPlugin] == true || + yaml[kSharedDarwinSource] == true || + yaml[kDefaultPackage] is String; + } + + static const String kConfigKey = 'macos'; + + final String name; + final String? pluginClass; + final String? dartPluginClass; + final bool ffiPlugin; + final String? defaultPackage; + + /// Indicates the macOS native code is shareable with iOS in + /// the subdirectory "darwin", otherwise in the subdirectory "macos". + @override + final bool sharedDarwinSource; + + @override + bool hasMethodChannel() => pluginClass != null; + + @override + bool hasFfi() => ffiPlugin; + + @override + bool hasDart() => dartPluginClass != null; + + @override + Map toMap() { + return { + 'name': name, + if (pluginClass != null) 'class': pluginClass, + if (dartPluginClass != null) kDartPluginClass: dartPluginClass, + if (ffiPlugin) kFfiPlugin: true, + if (sharedDarwinSource) kSharedDarwinSource: true, + if (defaultPackage != null) kDefaultPackage: defaultPackage, + }; + } +} + +/// Contains the parameters to template a Windows plugin. +/// +/// The [name] of the plugin is required. Either [dartPluginClass] or [pluginClass] are required. +/// [pluginClass] will be the entry point to the plugin's native code. +class WindowsPlugin extends PluginPlatform + implements NativeOrDartPlugin, VariantPlatformPlugin { + const WindowsPlugin({ + required this.name, + this.pluginClass, + this.dartPluginClass, + bool? ffiPlugin, + this.defaultPackage, + this.variants = const {}, + }) : ffiPlugin = ffiPlugin ?? false, + assert(pluginClass != null || dartPluginClass != null || defaultPackage != null); + + 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?; + if (pluginClass == 'none') { + pluginClass = null; + } + final Set variants = {}; + final YamlList? variantList = yaml[kSupportedVariants] as YamlList?; + if (variantList == null) { + // If no variant list is provided assume Win32 for backward compatibility. + variants.add(PluginPlatformVariant.win32); + } else { + const Map variantByName = { + 'win32': PluginPlatformVariant.win32, + }; + for (final String variantName in variantList.cast()) { + final PluginPlatformVariant? variant = variantByName[variantName]; + if (variant != null) { + variants.add(variant); + } + // Ignore unrecognized variants to make adding new variants in the + // future non-breaking. + } + } + return WindowsPlugin( + name: name, + pluginClass: pluginClass, + dartPluginClass: yaml[kDartPluginClass] as String?, + ffiPlugin: yaml[kFfiPlugin] as bool?, + defaultPackage: yaml[kDefaultPackage] as String?, + variants: variants, + ); + } + + static bool validate(YamlMap yaml) { + return yaml[kPluginClass] is String || + yaml[kDartPluginClass] is String || + yaml[kFfiPlugin] == true || + yaml[kDefaultPackage] is String; + } + + static const String kConfigKey = 'windows'; + + final String name; + final String? pluginClass; + final String? dartPluginClass; + final bool ffiPlugin; + final String? defaultPackage; + final Set variants; + + @override + Set get supportedVariants => variants; + + @override + bool hasMethodChannel() => pluginClass != null; + + @override + bool hasFfi() => ffiPlugin; + + @override + bool hasDart() => dartPluginClass != null; + + @override + Map toMap() { + return { + 'name': name, + if (pluginClass != null) 'class': pluginClass, + if (pluginClass != null) 'filename': _filenameForCppClass(pluginClass!), + if (dartPluginClass != null) kDartPluginClass: dartPluginClass, + if (ffiPlugin) kFfiPlugin: true, + if (defaultPackage != null) kDefaultPackage: defaultPackage, + }; + } +} + +/// Contains the parameters to template a Linux plugin. +/// +/// The [name] of the plugin is required. Either [dartPluginClass] or [pluginClass] are required. +/// [pluginClass] will be the entry point to the plugin's native code. +class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin { + const LinuxPlugin({ + required this.name, + this.pluginClass, + this.dartPluginClass, + bool? ffiPlugin, + this.defaultPackage, + }) : ffiPlugin = ffiPlugin ?? false, + assert(pluginClass != null || dartPluginClass != null || (ffiPlugin ?? false) || defaultPackage != null); + + 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?; + if (pluginClass == 'none') { + pluginClass = null; + } + return LinuxPlugin( + name: name, + pluginClass: pluginClass, + dartPluginClass: yaml[kDartPluginClass] as String?, + ffiPlugin: yaml[kFfiPlugin] as bool?, + defaultPackage: yaml[kDefaultPackage] as String?, + ); + } + + static bool validate(YamlMap yaml) { + return yaml[kPluginClass] is String || + yaml[kDartPluginClass] is String || + yaml[kFfiPlugin] == true || + yaml[kDefaultPackage] is String; + } + + static const String kConfigKey = 'linux'; + + final String name; + final String? pluginClass; + final String? dartPluginClass; + final bool ffiPlugin; + final String? defaultPackage; + + @override + bool hasMethodChannel() => pluginClass != null; + + @override + bool hasFfi() => ffiPlugin; + + @override + bool hasDart() => dartPluginClass != null; + + @override + Map toMap() { + return { + 'name': name, + if (pluginClass != null) 'class': pluginClass, + if (pluginClass != null) 'filename': _filenameForCppClass(pluginClass!), + if (dartPluginClass != null) kDartPluginClass: dartPluginClass, + if (ffiPlugin) kFfiPlugin: true, + if (defaultPackage != null) kDefaultPackage: defaultPackage, + }; + } +} + +/// Contains the parameters to template a web plugin. +/// +/// The required fields include: [name] of the plugin, the [pluginClass] that will +/// be the entry point to the plugin's implementation, and the [fileName] +/// containing the code. +class WebPlugin extends PluginPlatform { + const WebPlugin({ + required this.name, + required this.pluginClass, + required this.fileName, + }); + + factory WebPlugin.fromYaml(String name, YamlMap yaml) { + if (yaml['pluginClass'] is! String) { + throwToolExit('The plugin `$name` is missing the required field `pluginClass` in pubspec.yaml'); + } + if (yaml['fileName'] is! String) { + throwToolExit('The plugin `$name` is missing the required field `fileName` in pubspec.yaml'); + } + return WebPlugin( + name: name, + pluginClass: yaml['pluginClass'] as String, + fileName: yaml['fileName'] as String, + ); + } + + static const String kConfigKey = 'web'; + + /// The name of the plugin. + final String name; + + /// The class containing the plugin implementation details. + /// + /// This class should have a static `registerWith` method defined. + final String pluginClass; + + /// The name of the file containing the class implementation above. + final String fileName; + + @override + Map toMap() { + return { + 'name': name, + 'class': pluginClass, + 'file': fileName, + }; + } +} + +final RegExp _internalCapitalLetterRegex = RegExp(r'(?=(?!^)[A-Z])'); +String _filenameForCppClass(String className) { + return className.splitMapJoin( + _internalCapitalLetterRegex, + onMatch: (_) => '_', + onNonMatch: (String n) => n.toLowerCase()); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/plugins.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/plugins.dart new file mode 100644 index 0000000000000000000000000000000000000000..f43309a4e7c86310c22f0f72efa4136001b62811 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/plugins.dart @@ -0,0 +1,426 @@ +// 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:pub_semver/pub_semver.dart'; +import 'package:yaml/yaml.dart'; + +import 'base/common.dart'; +import 'base/file_system.dart'; +import 'platform_plugins.dart'; + +class Plugin { + Plugin({ + required this.name, + required this.path, + required this.platforms, + required this.defaultPackagePlatforms, + required this.pluginDartClassPlatforms, + this.flutterConstraint, + required this.dependencies, + required this.isDirectDependency, + this.implementsPackage, + }); + + /// Parses [Plugin] specification from the provided pluginYaml. + /// + /// This currently supports two formats. Legacy and Multi-platform. + /// + /// Example of the deprecated Legacy format. + /// + /// flutter: + /// plugin: + /// androidPackage: io.flutter.plugins.sample + /// iosPrefix: FLT + /// pluginClass: SamplePlugin + /// + /// Example Multi-platform format. + /// + /// flutter: + /// plugin: + /// platforms: + /// android: + /// package: io.flutter.plugins.sample + /// pluginClass: SamplePlugin + /// ios: + /// # A plugin implemented through method channels. + /// pluginClass: SamplePlugin + /// linux: + /// # A plugin implemented purely in Dart code. + /// dartPluginClass: SamplePlugin + /// macos: + /// # A plugin implemented with `dart:ffi`. + /// ffiPlugin: true + /// windows: + /// # A plugin using platform-specific Dart and method channels. + /// dartPluginClass: SamplePlugin + /// pluginClass: SamplePlugin + factory Plugin.fromYaml( + String name, + String path, + YamlMap? pluginYaml, + VersionConstraint? flutterConstraint, + List dependencies, { + required FileSystem fileSystem, + Set? appDependencies, + }) { + final List errors = validatePluginYaml(pluginYaml); + if (errors.isNotEmpty) { + throwToolExit('Invalid plugin specification $name.\n${errors.join('\n')}'); + } + if (pluginYaml != null && pluginYaml['platforms'] != null) { + return Plugin._fromMultiPlatformYaml( + name, + path, + pluginYaml, + flutterConstraint, + dependencies, + fileSystem, + appDependencies != null && appDependencies.contains(name), + ); + } + return Plugin._fromLegacyYaml( + name, + path, + pluginYaml, + flutterConstraint, + dependencies, + fileSystem, + appDependencies != null && appDependencies.contains(name), + ); + } + + factory Plugin._fromMultiPlatformYaml( + String name, + String path, + YamlMap pluginYaml, + VersionConstraint? flutterConstraint, + List dependencies, + FileSystem fileSystem, + bool isDirectDependency, + ) { + assert (pluginYaml['platforms'] != null, 'Invalid multi-platform plugin specification $name.'); + final YamlMap platformsYaml = pluginYaml['platforms'] as YamlMap; + + assert (_validateMultiPlatformYaml(platformsYaml).isEmpty, + 'Invalid multi-platform plugin specification $name.'); + + final Map platforms = {}; + + if (_providesImplementationForPlatform(platformsYaml, AndroidPlugin.kConfigKey)) { + platforms[AndroidPlugin.kConfigKey] = AndroidPlugin.fromYaml( + name, + platformsYaml[AndroidPlugin.kConfigKey] as YamlMap, + path, + fileSystem, + ); + } + + if (_providesImplementationForPlatform(platformsYaml, IOSPlugin.kConfigKey)) { + platforms[IOSPlugin.kConfigKey] = + IOSPlugin.fromYaml(name, platformsYaml[IOSPlugin.kConfigKey] as YamlMap); + } + + if (_providesImplementationForPlatform(platformsYaml, LinuxPlugin.kConfigKey)) { + platforms[LinuxPlugin.kConfigKey] = + LinuxPlugin.fromYaml(name, platformsYaml[LinuxPlugin.kConfigKey] as YamlMap); + } + + if (_providesImplementationForPlatform(platformsYaml, MacOSPlugin.kConfigKey)) { + platforms[MacOSPlugin.kConfigKey] = + MacOSPlugin.fromYaml(name, platformsYaml[MacOSPlugin.kConfigKey] as YamlMap); + } + + if (_providesImplementationForPlatform(platformsYaml, WebPlugin.kConfigKey)) { + platforms[WebPlugin.kConfigKey] = + WebPlugin.fromYaml(name, platformsYaml[WebPlugin.kConfigKey] as YamlMap); + } + + if (_providesImplementationForPlatform(platformsYaml, WindowsPlugin.kConfigKey)) { + platforms[WindowsPlugin.kConfigKey] = + WindowsPlugin.fromYaml(name, platformsYaml[WindowsPlugin.kConfigKey] as YamlMap); + } + + // TODO(stuartmorgan): Consider merging web into this common handling; the + // fact that its implementation of Dart-only plugins and default packages + // are separate is legacy. + final List sharedHandlingPlatforms = [ + AndroidPlugin.kConfigKey, + IOSPlugin.kConfigKey, + LinuxPlugin.kConfigKey, + MacOSPlugin.kConfigKey, + WindowsPlugin.kConfigKey, + ]; + final Map defaultPackages = {}; + final Map dartPluginClasses = {}; + for (final String platform in sharedHandlingPlatforms) { + final String? defaultPackage = _getDefaultPackageForPlatform(platformsYaml, platform); + if (defaultPackage != null) { + defaultPackages[platform] = defaultPackage; + } + final String? dartClass = _getPluginDartClassForPlatform(platformsYaml, platform); + if (dartClass != null) { + dartPluginClasses[platform] = dartClass; + } + } + + return Plugin( + name: name, + path: path, + platforms: platforms, + defaultPackagePlatforms: defaultPackages, + pluginDartClassPlatforms: dartPluginClasses, + flutterConstraint: flutterConstraint, + dependencies: dependencies, + isDirectDependency: isDirectDependency, + implementsPackage: pluginYaml['implements'] != null ? pluginYaml['implements'] as String : '', + ); + } + + factory Plugin._fromLegacyYaml( + String name, + String path, + dynamic pluginYaml, + VersionConstraint? flutterConstraint, + List dependencies, + FileSystem fileSystem, + bool isDirectDependency, + ) { + final Map platforms = {}; + final String? pluginClass = (pluginYaml as Map)['pluginClass'] as String?; + if (pluginClass != null) { + final String? androidPackage = pluginYaml['androidPackage'] as String?; + if (androidPackage != null) { + platforms[AndroidPlugin.kConfigKey] = AndroidPlugin( + name: name, + package: androidPackage, + pluginClass: pluginClass, + pluginPath: path, + fileSystem: fileSystem, + ); + } + + final String iosPrefix = pluginYaml['iosPrefix'] as String? ?? ''; + platforms[IOSPlugin.kConfigKey] = + IOSPlugin( + name: name, + classPrefix: iosPrefix, + pluginClass: pluginClass, + ); + } + return Plugin( + name: name, + path: path, + platforms: platforms, + defaultPackagePlatforms: {}, + pluginDartClassPlatforms: {}, + flutterConstraint: flutterConstraint, + dependencies: dependencies, + isDirectDependency: isDirectDependency, + ); + } + + /// Create a YamlMap that represents the supported platforms. + /// + /// For example, if the `platforms` contains 'ios' and 'android', the return map looks like: + /// + /// android: + /// package: io.flutter.plugins.sample + /// pluginClass: SamplePlugin + /// ios: + /// pluginClass: SamplePlugin + static YamlMap createPlatformsYamlMap(List platforms, String pluginClass, String androidPackage) { + final Map map = {}; + for (final String platform in platforms) { + map[platform] = { + 'pluginClass': pluginClass, + ...platform == 'android' ? {'package': androidPackage} : {}, + }; + } + return YamlMap.wrap(map); + } + + static List validatePluginYaml(YamlMap? yaml) { + if (yaml == null) { + return ['Invalid "plugin" specification.']; + } + + final bool usesOldPluginFormat = const { + 'androidPackage', + 'iosPrefix', + 'pluginClass', + }.any(yaml.containsKey); + + final bool usesNewPluginFormat = yaml.containsKey('platforms'); + + if (usesOldPluginFormat && usesNewPluginFormat) { + const String errorMessage = + 'The flutter.plugin.platforms key cannot be used in combination with the old ' + 'flutter.plugin.{androidPackage,iosPrefix,pluginClass} keys. ' + 'See: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin'; + return [errorMessage]; + } + + if (!usesOldPluginFormat && !usesNewPluginFormat) { + const String errorMessage = + 'Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file. ' + 'An instruction to format the `pubspec.yaml` can be found here: ' + 'https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms'; + return [errorMessage]; + } + + if (usesNewPluginFormat) { + if (yaml['platforms'] != null && yaml['platforms'] is! YamlMap) { + 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?); + } else { + return _validateLegacyYaml(yaml); + } + } + + static List _validateMultiPlatformYaml(YamlMap? yaml) { + bool isInvalid(String key, bool Function(YamlMap) validate) { + if (!yaml!.containsKey(key)) { + return false; + } + final dynamic yamlValue = yaml[key]; + if (yamlValue is! YamlMap) { + return true; + } + if (yamlValue.containsKey('default_package')) { + return false; + } + return !validate(yamlValue); + } + + if (yaml == null) { + return ['Invalid "platforms" specification.']; + } + final List errors = []; + if (isInvalid(AndroidPlugin.kConfigKey, AndroidPlugin.validate)) { + errors.add('Invalid "android" plugin specification.'); + } + if (isInvalid(IOSPlugin.kConfigKey, IOSPlugin.validate)) { + errors.add('Invalid "ios" plugin specification.'); + } + if (isInvalid(LinuxPlugin.kConfigKey, LinuxPlugin.validate)) { + errors.add('Invalid "linux" plugin specification.'); + } + if (isInvalid(MacOSPlugin.kConfigKey, MacOSPlugin.validate)) { + errors.add('Invalid "macos" plugin specification.'); + } + if (isInvalid(WindowsPlugin.kConfigKey, WindowsPlugin.validate)) { + errors.add('Invalid "windows" plugin specification.'); + } + return errors; + } + + static List _validateLegacyYaml(YamlMap yaml) { + final List errors = []; + + if (yaml['androidPackage'] != null && yaml['androidPackage'] is! String) { + errors.add('The "androidPackage" must either be null or a string.'); + } + if (yaml['iosPrefix'] != null && yaml['iosPrefix'] is! String) { + errors.add('The "iosPrefix" must either be null or a string.'); + } + if (yaml['pluginClass'] != null && yaml['pluginClass'] is! String) { + errors.add('The "pluginClass" must either be null or a string..'); + } + return errors; + } + + static bool _supportsPlatform(YamlMap platformsYaml, String platformKey) { + if (!platformsYaml.containsKey(platformKey)) { + return false; + } + if (platformsYaml[platformKey] is YamlMap) { + return true; + } + return false; + } + + static String? _getDefaultPackageForPlatform(YamlMap platformsYaml, String platformKey) { + if (!_supportsPlatform(platformsYaml, platformKey)) { + return null; + } + if ((platformsYaml[platformKey] as YamlMap).containsKey(kDefaultPackage)) { + return (platformsYaml[platformKey] as YamlMap)[kDefaultPackage] as String; + } + return null; + } + + static String? _getPluginDartClassForPlatform(YamlMap platformsYaml, String platformKey) { + if (!_supportsPlatform(platformsYaml, platformKey)) { + return null; + } + if ((platformsYaml[platformKey] as YamlMap).containsKey(kDartPluginClass)) { + return (platformsYaml[platformKey] as YamlMap)[kDartPluginClass] as String; + } + return null; + } + + static bool _providesImplementationForPlatform(YamlMap platformsYaml, String platformKey) { + if (!_supportsPlatform(platformsYaml, platformKey)) { + return false; + } + if ((platformsYaml[platformKey] as YamlMap).containsKey(kDefaultPackage)) { + return false; + } + return true; + } + + final String name; + final String path; + + /// The name of the interface package that this plugin implements. + /// If [null], this plugin doesn't implement an interface. + final String? implementsPackage; + + /// The required version of Flutter, if specified. + final VersionConstraint? flutterConstraint; + + /// The name of the packages this plugin depends on. + final List dependencies; + + /// This is a mapping from platform config key to the plugin platform spec. + final Map platforms; + + /// This is a mapping from platform config key to the default package implementation. + final Map defaultPackagePlatforms; + + /// This is a mapping from platform config key to the plugin class for the given platform. + final Map pluginDartClassPlatforms; + + /// Whether this plugin is a direct dependency of the app. + /// If [false], the plugin is a dependency of another plugin. + final bool isDirectDependency; +} + +/// Metadata associated with the resolution of a platform interface of a plugin. +class PluginInterfaceResolution { + PluginInterfaceResolution({ + required this.plugin, + required this.platform, + }); + + /// The plugin. + final Plugin plugin; + // The name of the platform that this plugin implements. + final String platform; + + Map toMap() { + return { + 'pluginName': plugin.name, + 'platform': platform, + 'dartClass': plugin.pluginDartClassPlatforms[platform] ?? '', + }; + } + + @override + String toString() { + return ''; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/pre_run_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/pre_run_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..e08cf1c60c306a432ba47e2c9708cb587e1cca48 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/pre_run_validator.dart @@ -0,0 +1,51 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'base/common.dart'; +import 'base/file_system.dart'; +import 'cache.dart'; + +/// A validator that runs before the tool runs any command. +abstract class PreRunValidator { + factory PreRunValidator({ + required FileSystem fileSystem, + }) => _DefaultPreRunValidator(fileSystem: fileSystem); + + void validate(); +} + +class _DefaultPreRunValidator implements PreRunValidator { + _DefaultPreRunValidator({ + required this.fileSystem, + }); + + final FileSystem fileSystem; + + late final Directory _toolsDir = fileSystem.directory( + fileSystem.path.join(Cache.flutterRoot!, 'packages', 'flutter_tools'), + ); + + @override + void validate() { + // If a user downloads the Flutter SDK via a pre-built archive and there is + // an error during extraction, the user could have a valid Dart snapshot of + // the tool but not the source directory. We still need the source, so + // validate the source directory exists and toolExit if not. + if (!_toolsDir.existsSync()) { + throwToolExit( + 'Flutter SDK installation appears corrupted: expected to find the ' + 'directory ${_toolsDir.path} but it does not exist! Please go to ' + 'https://flutter.dev/setup for instructions on how to re-install ' + 'Flutter.', + ); + } + } +} + +class NoOpPreRunValidator implements PreRunValidator { + const NoOpPreRunValidator(); + + @override + void validate() {} +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/preview_device.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/preview_device.dart new file mode 100644 index 0000000000000000000000000000000000000000..71eba1fcb1331eb04d3a60eb3ed26348e0a50932 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/preview_device.dart @@ -0,0 +1,256 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import 'application_package.dart'; +import 'artifacts.dart'; +import 'base/file_system.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'build_info.dart'; +import 'bundle_builder.dart'; +import 'desktop_device.dart'; +import 'devfs.dart'; +import 'device.dart'; +import 'device_port_forwarder.dart'; +import 'features.dart'; +import 'project.dart'; +import 'protocol_discovery.dart'; + +typedef BundleBuilderFactory = BundleBuilder Function(); + +BundleBuilder _defaultBundleBuilder() { + return BundleBuilder(); +} + +class PreviewDeviceDiscovery extends PollingDeviceDiscovery { + PreviewDeviceDiscovery({ + required Platform platform, + required Artifacts artifacts, + required FileSystem fileSystem, + required Logger logger, + required ProcessManager processManager, + required FeatureFlags featureFlags, + }) : _artifacts = artifacts, + _logger = logger, + _processManager = processManager, + _fileSystem = fileSystem, + _platform = platform, + _features = featureFlags, + super('Flutter preview device'); + + final Platform _platform; + final Artifacts _artifacts; + final Logger _logger; + final ProcessManager _processManager; + final FileSystem _fileSystem; + final FeatureFlags _features; + + @override + bool get canListAnything => _platform.isWindows; + + @override + bool get supportsPlatform => _platform.isWindows; + + @override + List get wellKnownIds => ['preview']; + + @override + Future> pollingGetDevices({ + Duration? timeout, + }) async { + final File previewBinary = _fileSystem.file(_artifacts.getArtifactPath(Artifact.flutterPreviewDevice)); + if (!previewBinary.existsSync()) { + return const []; + } + final PreviewDevice device = PreviewDevice( + artifacts: _artifacts, + fileSystem: _fileSystem, + logger: _logger, + processManager: _processManager, + previewBinary: previewBinary, + ); + return [ + if (_features.isPreviewDeviceEnabled) + device, + ]; + } + + @override + Future> discoverDevices({ + Duration? timeout, + DeviceDiscoveryFilter? filter, + }) { + return devices(); + } +} + +/// A device type that runs a prebuilt desktop binary alongside a locally compiled kernel file. +class PreviewDevice extends Device { + PreviewDevice({ + required ProcessManager processManager, + required Logger logger, + required FileSystem fileSystem, + required Artifacts artifacts, + required File previewBinary, + @visibleForTesting BundleBuilderFactory builderFactory = _defaultBundleBuilder, + }) : _previewBinary = previewBinary, + _processManager = processManager, + _logger = logger, + _fileSystem = fileSystem, + _bundleBuilderFactory = builderFactory, + _artifacts = artifacts, + super('preview', ephemeral: false, category: Category.desktop, platformType: PlatformType.windowsPreview); + + final ProcessManager _processManager; + final Logger _logger; + final FileSystem _fileSystem; + final BundleBuilderFactory _bundleBuilderFactory; + final Artifacts _artifacts; + final File _previewBinary; + + /// The set of plugins that are allowed to be used by Preview users. + /// + /// Currently no plugins are supported. + static const List supportedPubPlugins = []; + + @override + void clearLogs() { } + + @override + Future dispose() async { } + + @override + Future get emulatorId async => null; + + final DesktopLogReader _logReader = DesktopLogReader(); + + @override + FutureOr getLogReader({ApplicationPackage? app, bool includePastLogs = false}) => _logReader; + + @override + Future installApp(ApplicationPackage? app, {String? userIdentifier}) async => true; + + @override + Future isAppInstalled(ApplicationPackage app, {String? userIdentifier}) async => false; + + @override + Future isLatestBuildInstalled(ApplicationPackage app) async => false; + + @override + Future get isLocalEmulator async => false; + + @override + bool isSupported() => true; + + @override + bool isSupportedForProject(FlutterProject flutterProject) => true; + + @override + String get name => 'Preview'; + + @override + DevicePortForwarder get portForwarder => const NoOpDevicePortForwarder(); + + @override + Future get sdkNameAndVersion async => 'preview'; + + Process? _process; + + @override + Future startApp(ApplicationPackage? package, { + String? mainPath, + String? route, + required DebuggingOptions debuggingOptions, + Map platformArgs = const {}, + bool prebuiltApplication = false, + bool ipv6 = false, + String? userIdentifier, + }) async { + final Directory assetDirectory = _fileSystem.systemTempDirectory + .createTempSync('flutter_preview.'); + + // Build assets and perform initial compilation. + Status? status; + try { + status = _logger.startProgress('Compiling application for preview...'); + await _bundleBuilderFactory().build( + buildInfo: debuggingOptions.buildInfo, + mainPath: mainPath, + platform: TargetPlatform.windows_x64, + assetDirPath: getAssetBuildDirectory(), + ); + copyDirectory(_fileSystem.directory( + getAssetBuildDirectory()), + assetDirectory.childDirectory('data').childDirectory('flutter_assets'), + ); + } finally { + status?.stop(); + } + + // Merge with precompiled executable. + final String copiedPreviewBinaryPath = assetDirectory.childFile(_previewBinary.basename).path; + _previewBinary.copySync(copiedPreviewBinaryPath); + + final String windowsPath = _artifacts + .getArtifactPath(Artifact.windowsDesktopPath, platform: TargetPlatform.windows_x64, mode: BuildMode.debug); + final File windowsDll = _fileSystem.file(_fileSystem.path.join(windowsPath, 'flutter_windows.dll')); + final File icu = _fileSystem.file(_fileSystem.path.join(windowsPath, 'icudtl.dat')); + windowsDll.copySync(assetDirectory.childFile('flutter_windows.dll').path); + icu.copySync(assetDirectory.childDirectory('data').childFile('icudtl.dat').path); + + final Process process = await _processManager.start( + [copiedPreviewBinaryPath], + ); + _process = process; + _logReader.initializeProcess(process); + + final ProtocolDiscovery vmServiceDiscovery = ProtocolDiscovery.vmService(_logReader, + devicePort: debuggingOptions.deviceVmServicePort, + hostPort: debuggingOptions.hostVmServicePort, + ipv6: ipv6, + logger: _logger, + ); + try { + final Uri? vmServiceUri = await vmServiceDiscovery.uri; + if (vmServiceUri != null) { + return LaunchResult.succeeded(vmServiceUri: vmServiceUri); + } + _logger.printError( + 'Error waiting for a debug connection: ' + 'The log reader stopped unexpectedly.', + ); + } on Exception catch (error) { + _logger.printError('Error waiting for a debug connection: $error'); + } finally { + await vmServiceDiscovery.cancel(); + } + return LaunchResult.failed(); + } + + @override + Future stopApp(ApplicationPackage? app, {String? userIdentifier}) async { + return _process?.kill() ?? false; + } + + @override + Future get targetPlatform async { + return TargetPlatform.windows_x64; + } + + @override + Future uninstallApp(ApplicationPackage app, {String? userIdentifier}) async { + return true; + } + + @override + DevFSWriter createDevFSWriter(ApplicationPackage? app, String? userIdentifier) { + return LocalDevFSWriter(fileSystem: _fileSystem); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/project.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/project.dart new file mode 100644 index 0000000000000000000000000000000000000000..93ca512363be8aca0236ae815aa70e8a544d5df4 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/project.dart @@ -0,0 +1,960 @@ +// 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:unified_analytics/unified_analytics.dart'; +import 'package:xml/xml.dart'; +import 'package:yaml/yaml.dart'; + +import '../src/convert.dart'; +import 'android/android_builder.dart'; +import 'android/gradle_utils.dart' as gradle; +import 'base/common.dart'; +import 'base/error_handling_io.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/utils.dart'; +import 'base/version.dart'; +import 'bundle.dart' as bundle; +import 'cmake_project.dart'; +import 'features.dart'; +import 'flutter_manifest.dart'; +import 'flutter_plugins.dart'; +import 'globals.dart' as globals; +import 'platform_plugins.dart'; +import 'project_validator_result.dart'; +import 'reporting/reporting.dart'; +import 'template.dart'; +import 'xcode_project.dart'; + +export 'cmake_project.dart'; +export 'xcode_project.dart'; + +/// Enum for each officially supported platform. +enum SupportedPlatform { + android, + ios, + linux, + macos, + web, + windows, + fuchsia, + root, // Special platform to represent the root project directory +} + +class FlutterProjectFactory { + FlutterProjectFactory({ + required Logger logger, + required FileSystem fileSystem, + }) : _logger = logger, + _fileSystem = fileSystem; + + final Logger _logger; + final FileSystem _fileSystem; + + @visibleForTesting + final Map projects = + {}; + + /// Returns a [FlutterProject] view of the given directory or a ToolExit error, + /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. + FlutterProject fromDirectory(Directory directory) { + return projects.putIfAbsent(directory.path, () { + final FlutterManifest manifest = FlutterProject._readManifest( + directory.childFile(bundle.defaultManifestPath).path, + logger: _logger, + fileSystem: _fileSystem, + ); + final FlutterManifest exampleManifest = FlutterProject._readManifest( + FlutterProject._exampleDirectory(directory) + .childFile(bundle.defaultManifestPath) + .path, + logger: _logger, + fileSystem: _fileSystem, + ); + return FlutterProject(directory, manifest, exampleManifest); + }); + } +} + +/// Represents the contents of a Flutter project at the specified [directory]. +/// +/// [FlutterManifest] information is read from `pubspec.yaml` and +/// `example/pubspec.yaml` files on construction of a [FlutterProject] instance. +/// The constructed instance carries an immutable snapshot representation of the +/// presence and content of those files. Accordingly, [FlutterProject] instances +/// should be discarded upon changes to the `pubspec.yaml` files, but can be +/// used across changes to other files, as no other file-level information is +/// cached. +class FlutterProject { + @visibleForTesting + FlutterProject(this.directory, this.manifest, this._exampleManifest); + + /// Returns a [FlutterProject] view of the given directory or a ToolExit error, + /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. + static FlutterProject fromDirectory(Directory directory) => globals.projectFactory.fromDirectory(directory); + + /// Returns a [FlutterProject] view of the current directory or a ToolExit error, + /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. + static FlutterProject current() => globals.projectFactory.fromDirectory(globals.fs.currentDirectory); + + /// Create a [FlutterProject] and bypass the project caching. + @visibleForTesting + static FlutterProject fromDirectoryTest(Directory directory, [Logger? logger]) { + final FileSystem fileSystem = directory.fileSystem; + logger ??= BufferLogger.test(); + final FlutterManifest manifest = FlutterProject._readManifest( + directory.childFile(bundle.defaultManifestPath).path, + logger: logger, + fileSystem: fileSystem, + ); + final FlutterManifest exampleManifest = FlutterProject._readManifest( + FlutterProject._exampleDirectory(directory) + .childFile(bundle.defaultManifestPath) + .path, + logger: logger, + fileSystem: fileSystem, + ); + return FlutterProject(directory, manifest, exampleManifest); + } + + /// The location of this project. + final Directory directory; + + /// The location of the build folder. + Directory get buildDirectory => directory.childDirectory('build'); + + /// The manifest of this project. + final FlutterManifest manifest; + + /// The manifest of the example sub-project of this project. + final FlutterManifest _exampleManifest; + + /// The set of organization names found in this project as + /// part of iOS product bundle identifier, Android application ID, or + /// Gradle group ID. + Future> get organizationNames async { + final List candidates = []; + + if (ios.existsSync()) { + // Don't require iOS build info, this method is only + // used during create as best-effort, use the + // default target bundle identifier. + try { + final String? bundleIdentifier = await ios.productBundleIdentifier(null); + if (bundleIdentifier != null) { + candidates.add(bundleIdentifier); + } + } on ToolExit { + // It's possible that while parsing the build info for the ios project + // that the bundleIdentifier can't be resolve. However, we would like + // skip parsing that id in favor of searching in other place. We can + // consider a tool exit in this case to be non fatal for the program. + } + } + if (android.existsSync()) { + final String? applicationId = android.applicationId; + final String? group = android.group; + candidates.addAll([ + if (applicationId != null) + applicationId, + if (group != null) + group, + ]); + } + if (example.android.existsSync()) { + final String? applicationId = example.android.applicationId; + if (applicationId != null) { + candidates.add(applicationId); + } + } + if (example.ios.existsSync()) { + final String? bundleIdentifier = await example.ios.productBundleIdentifier(null); + if (bundleIdentifier != null) { + candidates.add(bundleIdentifier); + } + } + return Set.of(candidates.map(_organizationNameFromPackageName).whereType()); + } + + String? _organizationNameFromPackageName(String packageName) { + if (0 <= packageName.lastIndexOf('.')) { + return packageName.substring(0, packageName.lastIndexOf('.')); + } + return null; + } + + /// The iOS sub project of this project. + late final IosProject ios = IosProject.fromFlutter(this); + + /// The Android sub project of this project. + late final AndroidProject android = AndroidProject._(this); + + /// The web sub project of this project. + late final WebProject web = WebProject._(this); + + /// The MacOS sub project of this project. + late final MacOSProject macos = MacOSProject.fromFlutter(this); + + /// The Linux sub project of this project. + late final LinuxProject linux = LinuxProject.fromFlutter(this); + + /// The Windows sub project of this project. + late final WindowsProject windows = WindowsProject.fromFlutter(this); + + /// The Fuchsia sub project of this project. + late final FuchsiaProject fuchsia = FuchsiaProject._(this); + + /// The `pubspec.yaml` file of this project. + File get pubspecFile => directory.childFile('pubspec.yaml'); + + /// The `.packages` file of this project. + File get packagesFile => directory.childFile('.packages'); + + /// The `package_config.json` file of the project. + /// + /// This is the replacement for .packages which contains language + /// version information. + File get packageConfigFile => directory.childDirectory('.dart_tool').childFile('package_config.json'); + + /// The `.metadata` file of this project. + File get metadataFile => directory.childFile('.metadata'); + + /// The `.flutter-plugins` file of this project. + File get flutterPluginsFile => directory.childFile('.flutter-plugins'); + + /// The `.flutter-plugins-dependencies` file of this project, + /// which contains the dependencies each plugin depends on. + File get flutterPluginsDependenciesFile => directory.childFile('.flutter-plugins-dependencies'); + + /// The `.dart-tool` directory of this project. + Directory get dartTool => directory.childDirectory('.dart_tool'); + + /// The directory containing the generated code for this project. + Directory get generated => directory + .absolute + .childDirectory('.dart_tool') + .childDirectory('build') + .childDirectory('generated') + .childDirectory(manifest.appName); + + /// The generated Dart plugin registrant for non-web platforms. + File get dartPluginRegistrant => dartTool + .childDirectory('flutter_build') + .childFile('dart_plugin_registrant.dart'); + + /// The example sub-project of this project. + FlutterProject get example => FlutterProject( + _exampleDirectory(directory), + _exampleManifest, + FlutterManifest.empty(logger: globals.logger), + ); + + /// True if this project is a Flutter module project. + bool get isModule => manifest.isModule; + + /// True if this project is a Flutter plugin project. + bool get isPlugin => manifest.isPlugin; + + /// True if the Flutter project is using the AndroidX support library. + bool get usesAndroidX => manifest.usesAndroidX; + + /// True if this project has an example application. + bool get hasExampleApp => _exampleDirectory(directory).existsSync(); + + /// Returns a list of platform names that are supported by the project. + List getSupportedPlatforms({bool includeRoot = false}) { + final List platforms = includeRoot ? [SupportedPlatform.root] : []; + if (android.existsSync()) { + platforms.add(SupportedPlatform.android); + } + if (ios.exists) { + platforms.add(SupportedPlatform.ios); + } + if (web.existsSync()) { + platforms.add(SupportedPlatform.web); + } + if (macos.existsSync()) { + platforms.add(SupportedPlatform.macos); + } + if (linux.existsSync()) { + platforms.add(SupportedPlatform.linux); + } + if (windows.existsSync()) { + platforms.add(SupportedPlatform.windows); + } + if (fuchsia.existsSync()) { + platforms.add(SupportedPlatform.fuchsia); + } + return platforms; + } + + /// The directory that will contain the example if an example exists. + static Directory _exampleDirectory(Directory directory) => directory.childDirectory('example'); + + /// Reads and validates the `pubspec.yaml` file at [path], asynchronously + /// returning a [FlutterManifest] representation of the contents. + /// + /// Completes with an empty [FlutterManifest], if the file does not exist. + /// Completes with a ToolExit on validation error. + static FlutterManifest _readManifest(String path, { + required Logger logger, + required FileSystem fileSystem, + }) { + FlutterManifest? manifest; + try { + manifest = FlutterManifest.createFromPath( + path, + logger: logger, + fileSystem: fileSystem, + ); + } on YamlException catch (e) { + logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); + logger.printError('$e'); + } on FormatException catch (e) { + logger.printError('Error detected while parsing pubspec.yaml:', emphasis: true); + logger.printError('$e'); + } on FileSystemException catch (e) { + logger.printError('Error detected while reading pubspec.yaml:', emphasis: true); + logger.printError('$e'); + } + if (manifest == null) { + throwToolExit('Please correct the pubspec.yaml file at $path'); + } + return manifest; + } + + /// Reapplies template files and regenerates project files and plugin + /// registrants for app and module projects only. + /// + /// Will not create project platform directories if they do not already exist. + /// + /// If [allowedPlugins] is non-null, all plugins with method channels in the + /// project's pubspec.yaml will be validated to be in that set, or else a + /// [ToolExit] will be thrown. + Future regeneratePlatformSpecificTooling({ + DeprecationBehavior deprecationBehavior = DeprecationBehavior.none, + Iterable? allowedPlugins, + }) async { + return ensureReadyForPlatformSpecificTooling( + androidPlatform: android.existsSync(), + iosPlatform: ios.existsSync(), + // TODO(stuartmorgan): Revisit the conditions here once the plans for handling + // desktop in existing projects are in place. + linuxPlatform: featureFlags.isLinuxEnabled && linux.existsSync(), + macOSPlatform: featureFlags.isMacOSEnabled && macos.existsSync(), + windowsPlatform: featureFlags.isWindowsEnabled && windows.existsSync(), + webPlatform: featureFlags.isWebEnabled && web.existsSync(), + deprecationBehavior: deprecationBehavior, + allowedPlugins: allowedPlugins, + ); + } + + /// Applies template files and generates project files and plugin + /// registrants for app and module projects only for the specified platforms. + Future ensureReadyForPlatformSpecificTooling({ + bool androidPlatform = false, + bool iosPlatform = false, + bool linuxPlatform = false, + bool macOSPlatform = false, + bool windowsPlatform = false, + bool webPlatform = false, + DeprecationBehavior deprecationBehavior = DeprecationBehavior.none, + Iterable? allowedPlugins, + }) async { + if (!directory.existsSync() || isPlugin) { + return; + } + await refreshPluginsList(this, iosPlatform: iosPlatform, macOSPlatform: macOSPlatform); + if (androidPlatform) { + await android.ensureReadyForPlatformSpecificTooling(deprecationBehavior: deprecationBehavior); + } + if (iosPlatform) { + await ios.ensureReadyForPlatformSpecificTooling(); + } + if (linuxPlatform) { + await linux.ensureReadyForPlatformSpecificTooling(); + } + if (macOSPlatform) { + await macos.ensureReadyForPlatformSpecificTooling(); + } + if (windowsPlatform) { + await windows.ensureReadyForPlatformSpecificTooling(); + } + if (webPlatform) { + await web.ensureReadyForPlatformSpecificTooling(); + } + await injectPlugins( + this, + androidPlatform: androidPlatform, + iosPlatform: iosPlatform, + linuxPlatform: linuxPlatform, + macOSPlatform: macOSPlatform, + windowsPlatform: windowsPlatform, + allowedPlugins: allowedPlugins, + ); + } + + void checkForDeprecation({DeprecationBehavior deprecationBehavior = DeprecationBehavior.none}) { + if (android.existsSync() && pubspecFile.existsSync()) { + android.checkForDeprecation(deprecationBehavior: deprecationBehavior); + } + } + + /// Returns a json encoded string containing the [appName], [version], and [buildNumber] that is used to generate version.json + String getVersionInfo() { + final String? buildName = manifest.buildName; + final String? buildNumber = manifest.buildNumber; + final Map versionFileJson = { + 'app_name': manifest.appName, + if (buildName != null) + 'version': buildName, + if (buildNumber != null) + 'build_number': buildNumber, + 'package_name': manifest.appName, + }; + return jsonEncode(versionFileJson); + } +} + +/// Base class for projects per platform. +abstract class FlutterProjectPlatform { + + /// Plugin's platform config key, e.g., "macos", "ios". + String get pluginConfigKey; + + /// Whether the platform exists in the project. + bool existsSync(); +} + +/// Represents the Android sub-project of a Flutter project. +/// +/// Instances will reflect the contents of the `android/` sub-folder of +/// Flutter applications and the `.android/` sub-folder of Flutter module projects. +class AndroidProject extends FlutterProjectPlatform { + AndroidProject._(this.parent); + + // User facing string when java/gradle/agp versions are compatible. + @visibleForTesting + static const String validJavaGradleAgpString = 'compatible java/gradle/agp'; + + // User facing link that describes compatibility between gradle and + // android gradle plugin. + static const String gradleAgpCompatUrl = + 'https://developer.android.com/studio/releases/gradle-plugin#updating-gradle'; + + // User facing link that describes compatibility between java and the first + // version of gradle to support it. + static const String javaGradleCompatUrl = + 'https://docs.gradle.org/current/userguide/compatibility.html#java'; + + /// The parent of this project. + final FlutterProject parent; + + @override + String get pluginConfigKey => AndroidPlugin.kConfigKey; + + static final RegExp _androidNamespacePattern = RegExp('android {[\\S\\s]+namespace[\\s]+[\'"](.+)[\'"]'); + static final RegExp _applicationIdPattern = RegExp('^\\s*applicationId\\s+[\'"](.*)[\'"]\\s*\$'); + static final RegExp _imperativeKotlinPluginPattern = RegExp('^\\s*apply plugin\\:\\s+[\'"]kotlin-android[\'"]\\s*\$'); + static final RegExp _declarativeKotlinPluginPattern = RegExp('^\\s*id\\s+[\'"]kotlin-android[\'"]\\s*\$'); + static final RegExp _groupPattern = RegExp('^\\s*group\\s+[\'"](.*)[\'"]\\s*\$'); + + /// The Gradle root directory of the Android host app. This is the directory + /// containing the `app/` subdirectory and the `settings.gradle` file that + /// includes it in the overall Gradle project. + Directory get hostAppGradleRoot { + if (!isModule || _editableHostAppDirectory.existsSync()) { + return _editableHostAppDirectory; + } + return ephemeralDirectory; + } + + /// The Gradle root directory of the Android wrapping of Flutter and plugins. + /// This is the same as [hostAppGradleRoot] except when the project is + /// a Flutter module with an editable host app. + Directory get _flutterLibGradleRoot => isModule ? ephemeralDirectory : _editableHostAppDirectory; + + Directory get ephemeralDirectory => parent.directory.childDirectory('.android'); + Directory get _editableHostAppDirectory => parent.directory.childDirectory('android'); + + /// True if the parent Flutter project is a module. + bool get isModule => parent.isModule; + + /// True if the parent Flutter project is a plugin. + bool get isPlugin => parent.isPlugin; + + /// True if the Flutter project is using the AndroidX support library. + bool get usesAndroidX => parent.usesAndroidX; + + /// Returns true if the current version of the Gradle plugin is supported. + late final bool isSupportedVersion = _computeSupportedVersion(); + + /// Gets all build variants of this project. + Future> getBuildVariants() async { + if (!existsSync() || androidBuilder == null) { + return const []; + } + return androidBuilder!.getBuildVariants(project: parent); + } + + /// Outputs app link related settings into a json file. + /// + /// The return future resolves to the path of the json file. + /// + /// The future resolves to null if it fails to retrieve app link settings. + Future outputsAppLinkSettings({required String variant}) async { + if (!existsSync() || androidBuilder == null) { + throwToolExit('Target directory $hostAppGradleRoot is not an Android project'); + } + return androidBuilder!.outputsAppLinkSettings(variant, project: parent); + } + + bool _computeSupportedVersion() { + final FileSystem fileSystem = hostAppGradleRoot.fileSystem; + final File plugin = hostAppGradleRoot.childFile( + fileSystem.path.join('buildSrc', 'src', 'main', 'groovy', 'FlutterPlugin.groovy')); + if (plugin.existsSync()) { + return false; + } + try { + for (final String line in appGradleFile.readAsLinesSync()) { + // This syntax corresponds to applying the Flutter Gradle Plugin with a + // script. + // See https://docs.gradle.org/current/userguide/plugins.html#sec:script_plugins. + final bool fileBasedApply = line.contains(RegExp(r'apply from: .*/flutter.gradle')); + + // This syntax corresponds to applying the Flutter Gradle Plugin using + // the declarative "plugins {}" block after including it in the + // pluginManagement block of the settings.gradle file. + // See https://docs.gradle.org/current/userguide/composite_builds.html#included_plugin_builds, + // as well as the settings.gradle and build.gradle templates. + final bool declarativeApply = line.contains('dev.flutter.flutter-gradle-plugin'); + + // This case allows for flutter run/build to work for modules. It does + // not guarantee the Flutter Gradle Plugin is applied. + final bool managed = line.contains("def flutterPluginVersion = 'managed'"); + if (fileBasedApply || declarativeApply || managed) { + return true; + } + } + } on FileSystemException { + return false; + } + return false; + } + + /// True, if the app project is using Kotlin. + bool get isKotlin { + final bool imperativeMatch = firstMatchInFile(appGradleFile, _imperativeKotlinPluginPattern) != null; + final bool declarativeMatch = firstMatchInFile(appGradleFile, _declarativeKotlinPluginPattern) != null; + return imperativeMatch || declarativeMatch; + } + + /// Gets the module-level build.gradle file. + /// See https://developer.android.com/build#module-level. + File get appGradleFile => hostAppGradleRoot.childDirectory('app') + .childFile('build.gradle'); + + File get appManifestFile { + if (isUsingGradle) { + return hostAppGradleRoot + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + } + + return hostAppGradleRoot.childFile('AndroidManifest.xml'); + } + + File get gradleAppOutV1File => gradleAppOutV1Directory.childFile('app-debug.apk'); + + Directory get gradleAppOutV1Directory { + return globals.fs.directory(globals.fs.path.join(hostAppGradleRoot.path, 'app', 'build', 'outputs', 'apk')); + } + + /// Whether the current flutter project has an Android sub-project. + @override + bool existsSync() { + return parent.isModule || _editableHostAppDirectory.existsSync(); + } + + /// Check if the versions of Java, Gradle and AGP are compatible. + /// + /// This is expected to be called from + /// flutter_tools/lib/src/project_validator.dart. + Future validateJavaAndGradleAgpVersions() async { + // Constructing ProjectValidatorResult happens here and not in + // flutter_tools/lib/src/project_validator.dart because of the additional + // Complexity of variable status values and error string formatting. + const String visibleName = 'Java/Gradle/Android Gradle Plugin'; + final CompatibilityResult validJavaGradleAgpVersions = + await hasValidJavaGradleAgpVersions(); + + + return ProjectValidatorResult( + name: visibleName, + value: validJavaGradleAgpVersions.description, + status: validJavaGradleAgpVersions.success + ? StatusProjectValidator.success + : StatusProjectValidator.error, + ); + } + + /// Ensures Java SDK is compatible with the project's Gradle version and + /// the project's Gradle version is compatible with the AGP version used + /// in build.gradle. + Future hasValidJavaGradleAgpVersions() async { + final String? gradleVersion = await gradle.getGradleVersion( + hostAppGradleRoot, globals.logger, globals.processManager); + final String? agpVersion = + gradle.getAgpVersion(hostAppGradleRoot, globals.logger); + final String? javaVersion = versionToParsableString(globals.java?.version); + + // Assume valid configuration. + String description = validJavaGradleAgpString; + + final bool compatibleGradleAgp = gradle.validateGradleAndAgp(globals.logger, + gradleV: gradleVersion, agpV: agpVersion); + + final bool compatibleJavaGradle = gradle.validateJavaAndGradle( + globals.logger, + javaV: javaVersion, + gradleV: gradleVersion); + + // Begin description formatting. + if (!compatibleGradleAgp) { + final String gradleDescription = agpVersion != null + ? 'Update Gradle to at least "${gradle.getGradleVersionFor(agpVersion)}".' + : ''; + description = ''' +Incompatible Gradle/AGP versions. \n +Gradle Version: $gradleVersion, AGP Version: $agpVersion +$gradleDescription\n +See the link below for more information: +$gradleAgpCompatUrl +'''; + } + if (!compatibleJavaGradle) { + // Should contain the agp error (if present) but not the valid String. + description = ''' +${compatibleGradleAgp ? '' : description} +Incompatible Java/Gradle versions. +Java Version: $javaVersion, Gradle Version: $gradleVersion\n +See the link below for more information: +$javaGradleCompatUrl +'''; + } + return CompatibilityResult( + compatibleJavaGradle && compatibleGradleAgp, description); + } + + bool get isUsingGradle { + return hostAppGradleRoot.childFile('build.gradle').existsSync(); + } + + String? get applicationId { + return firstMatchInFile(appGradleFile, _applicationIdPattern)?.group(1); + } + + /// Get the namespace for newer Android projects, + /// which replaces the `package` attribute in the Manifest.xml. + String? get namespace { + try { + // firstMatchInFile() reads per line but `_androidNamespacePattern` matches a multiline pattern. + return _androidNamespacePattern.firstMatch(appGradleFile.readAsStringSync())?.group(1); + } on FileSystemException { + return null; + } + } + + String? get group { + final File gradleFile = hostAppGradleRoot.childFile('build.gradle'); + return firstMatchInFile(gradleFile, _groupPattern)?.group(1); + } + + /// The build directory where the Android artifacts are placed. + Directory get buildDirectory { + return parent.buildDirectory; + } + + Future ensureReadyForPlatformSpecificTooling({DeprecationBehavior deprecationBehavior = DeprecationBehavior.none}) async { + if (isModule && _shouldRegenerateFromTemplate()) { + await _regenerateLibrary(); + // Add ephemeral host app, if an editable host app does not already exist. + if (!_editableHostAppDirectory.existsSync()) { + await _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_common'), ephemeralDirectory); + await _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_ephemeral'), ephemeralDirectory); + } + } + if (!hostAppGradleRoot.existsSync()) { + return; + } + gradle.updateLocalProperties(project: parent, requireAndroidSdk: false); + } + + bool _shouldRegenerateFromTemplate() { + return globals.fsUtils.isOlderThanReference( + entity: ephemeralDirectory, + referenceFile: parent.pubspecFile, + ) || globals.cache.isOlderThanToolsStamp(ephemeralDirectory); + } + + File get localPropertiesFile => _flutterLibGradleRoot.childFile('local.properties'); + + Directory get pluginRegistrantHost => _flutterLibGradleRoot.childDirectory(isModule ? 'Flutter' : 'app'); + + Future _regenerateLibrary() async { + ErrorHandlingFileSystem.deleteIfExists(ephemeralDirectory, recursive: true); + await _overwriteFromTemplate( + globals.fs.path.join( + 'module', + 'android', + 'library_new_embedding', + ), + ephemeralDirectory); + await _overwriteFromTemplate(globals.fs.path.join( + 'module', + 'android', + 'gradle'), ephemeralDirectory); + globals.gradleUtils?.injectGradleWrapperIfNeeded(ephemeralDirectory); + } + + Future _overwriteFromTemplate(String path, Directory target) async { + final Template template = await Template.fromName( + path, + fileSystem: globals.fs, + templateManifest: null, + logger: globals.logger, + templateRenderer: globals.templateRenderer, + ); + final String androidIdentifier = parent.manifest.androidPackage ?? 'com.example.${parent.manifest.appName}'; + template.render( + target, + { + 'android': true, + 'projectName': parent.manifest.appName, + 'androidIdentifier': androidIdentifier, + 'androidX': usesAndroidX, + 'agpVersion': gradle.templateAndroidGradlePluginVersion, + 'agpVersionForModule': gradle.templateAndroidGradlePluginVersionForModule, + 'kotlinVersion': gradle.templateKotlinGradlePluginVersion, + 'gradleVersion': gradle.templateDefaultGradleVersion, + 'compileSdkVersion': gradle.compileSdkVersion, + 'minSdkVersion': gradle.minSdkVersion, + 'ndkVersion': gradle.ndkVersion, + 'targetSdkVersion': gradle.targetSdkVersion, + }, + printStatusWhenWriting: false, + ); + } + + void checkForDeprecation({DeprecationBehavior deprecationBehavior = DeprecationBehavior.none}) { + if (deprecationBehavior == DeprecationBehavior.none) { + return; + } + final AndroidEmbeddingVersionResult result = computeEmbeddingVersion(); + if (result.version != AndroidEmbeddingVersion.v1) { + return; + } + globals.printStatus( +''' +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Warning +────────────────────────────────────────────────────────────────────────────── +Your Flutter application is created using an older version of the Android +embedding. It is being deprecated in favor of Android embedding v2. To migrate +your project, follow the steps at: + +https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +The detected reason was: + + ${result.reason} +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +'''); + if (deprecationBehavior == DeprecationBehavior.ignore) { + BuildEvent('deprecated-v1-android-embedding-ignored', type: 'gradle', flutterUsage: globals.flutterUsage).send(); + globals.analytics.send( + Event.flutterBuildInfo( + label: 'deprecated-v1-android-embedding-ignored', + buildType: 'gradle', + )); + + } else { // DeprecationBehavior.exit + globals.analytics.send( + Event.flutterBuildInfo( + label: 'deprecated-v1-android-embedding-failed', + buildType: 'gradle', + )); + + throwToolExit( + 'Build failed due to use of deprecated Android v1 embedding.', + exitCode: 1, + ); + } + } + + AndroidEmbeddingVersion getEmbeddingVersion() { + return computeEmbeddingVersion().version; + } + + AndroidEmbeddingVersionResult computeEmbeddingVersion() { + if (isModule) { + // A module type's Android project is used in add-to-app scenarios and + // only supports the V2 embedding. + return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v2, 'Is add-to-app module'); + } + if (isPlugin) { + // Plugins do not use an appManifest, so we stop here. + // + // TODO(garyq): This method does not currently check for code references to + // the v1 embedding, we should check for this once removal is further along. + return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v2, 'Is plugin'); + } + if (!appManifestFile.existsSync()) { + return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, 'No `${appManifestFile.absolute.path}` file'); + } + XmlDocument document; + try { + document = XmlDocument.parse(appManifestFile.readAsStringSync()); + } on XmlException { + throwToolExit('Error parsing $appManifestFile ' + 'Please ensure that the android manifest is a valid XML document and try again.'); + } on FileSystemException { + throwToolExit('Error reading $appManifestFile even though it exists. ' + 'Please ensure that you have read permission to this file and try again.'); + } + for (final XmlElement application in document.findAllElements('application')) { + final String? applicationName = application.getAttribute('android:name'); + if (applicationName == 'io.flutter.app.FlutterApplication') { + return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, '${appManifestFile.absolute.path} uses `android:name="io.flutter.app.FlutterApplication"`'); + } + } + for (final XmlElement metaData in document.findAllElements('meta-data')) { + final String? name = metaData.getAttribute('android:name'); + if (name == 'flutterEmbedding') { + final String? embeddingVersionString = metaData.getAttribute('android:value'); + if (embeddingVersionString == '1') { + return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, '${appManifestFile.absolute.path} `` in ${appManifestFile.absolute.path}'); + } +} + +/// Iteration of the embedding Java API in the engine used by the Android project. +enum AndroidEmbeddingVersion { + /// V1 APIs based on io.flutter.app.FlutterActivity. + v1, + /// V2 APIs based on io.flutter.embedding.android.FlutterActivity. + v2, +} + +/// Data class that holds the results of checking for embedding version. +/// +/// This class includes the reason why a particular embedding was selected. +class AndroidEmbeddingVersionResult { + AndroidEmbeddingVersionResult(this.version, this.reason); + + /// The embedding version. + AndroidEmbeddingVersion version; + + /// The reason why the embedding version was selected. + String reason; +} + +// What the tool should do when encountering deprecated API in applications. +enum DeprecationBehavior { + // The command being run does not care about deprecation status. + none, + // The command should continue and ignore the deprecation warning. + ignore, + // The command should exit the tool. + exit, +} + +/// Represents the web sub-project of a Flutter project. +class WebProject extends FlutterProjectPlatform { + WebProject._(this.parent); + + final FlutterProject parent; + + @override + String get pluginConfigKey => WebPlugin.kConfigKey; + + /// Whether this flutter project has a web sub-project. + @override + bool existsSync() { + return parent.directory.childDirectory('web').existsSync() + && indexFile.existsSync(); + } + + /// The 'lib' directory for the application. + Directory get libDirectory => parent.directory.childDirectory('lib'); + + /// The directory containing additional files for the application. + Directory get directory => parent.directory.childDirectory('web'); + + /// The html file used to host the flutter web application. + File get indexFile => parent.directory + .childDirectory('web') + .childFile('index.html'); + + /// The .dart_tool/dartpad directory + Directory get dartpadToolDirectory => parent.directory + .childDirectory('.dart_tool') + .childDirectory('dartpad'); + + Future ensureReadyForPlatformSpecificTooling() async { + /// Create .dart_tool/dartpad/web_plugin_registrant.dart. + /// See: https://github.com/dart-lang/dart-services/pull/874 + await injectBuildTimePluginFiles( + parent, + destination: dartpadToolDirectory, + webPlatform: true, + ); + } +} + +/// The Fuchsia sub project. +class FuchsiaProject { + FuchsiaProject._(this.project); + + final FlutterProject project; + + Directory? _editableHostAppDirectory; + Directory get editableHostAppDirectory => + _editableHostAppDirectory ??= project.directory.childDirectory('fuchsia'); + + bool existsSync() => editableHostAppDirectory.existsSync(); + + Directory? _meta; + Directory get meta => + _meta ??= editableHostAppDirectory.childDirectory('meta'); +} + +// Combines success and a description into one object that can be returned +// together. +@visibleForTesting +class CompatibilityResult { + CompatibilityResult(this.success, this.description); + final bool success; + final String description; +} + +/// Converts a [Version] to a string that can be parsed by [Version.parse]. +String? versionToParsableString(Version? version) { + if (version == null) { + return null; + } + + return '${version.major}.${version.minor}.${version.patch}'; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/project_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/project_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..5749d009c17ea9c09159acfd80094695c8d17823 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/project_validator.dart @@ -0,0 +1,368 @@ +// 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:collection'; + +import 'package:process/process.dart'; + +import 'base/file_system.dart'; +import 'base/io.dart'; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'cache.dart'; +import 'convert.dart'; +import 'dart_pub_json_formatter.dart'; +import 'flutter_manifest.dart'; +import 'project.dart'; +import 'project_validator_result.dart'; +import 'version.dart'; + +abstract class ProjectValidator { + const ProjectValidator(); + String get title; + bool get machineOutput => false; + bool supportsProject(FlutterProject project); + /// Can return more than one result in case a file/command have a lot of info to share to the user + Future> start(FlutterProject project); +} + +abstract class MachineProjectValidator extends ProjectValidator { + const MachineProjectValidator(); + + @override + bool get machineOutput => true; +} + +/// Validator run for all platforms that extract information from the pubspec.yaml. +/// +/// Specific info from different platforms should be written in their own ProjectValidator. +class VariableDumpMachineProjectValidator extends MachineProjectValidator { + VariableDumpMachineProjectValidator({ + required this.logger, + required this.fileSystem, + required this.platform, + }); + + final Logger logger; + final FileSystem fileSystem; + final Platform platform; + + String _toJsonValue(Object? obj) { + String value = obj.toString(); + if (obj is String) { + value = '"$obj"'; + } + value = value.replaceAll(r'\', r'\\'); + return value; + } + + @override + Future> start(FlutterProject project) async { + final List result = []; + + result.add(ProjectValidatorResult( + name: 'FlutterProject.directory', + value: _toJsonValue(project.directory.absolute.path), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.metadataFile', + value: _toJsonValue(project.metadataFile.absolute.path), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.android.exists', + value: _toJsonValue(project.android.existsSync()), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.ios.exists', + value: _toJsonValue(project.ios.exists), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.web.exists', + value: _toJsonValue(project.web.existsSync()), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.macos.exists', + value: _toJsonValue(project.macos.existsSync()), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.linux.exists', + value: _toJsonValue(project.linux.existsSync()), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.windows.exists', + value: _toJsonValue(project.windows.existsSync()), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.fuchsia.exists', + value: _toJsonValue(project.fuchsia.existsSync()), + status: StatusProjectValidator.info, + )); + + result.add(ProjectValidatorResult( + name: 'FlutterProject.android.isKotlin', + value: _toJsonValue(project.android.isKotlin), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.ios.isSwift', + value: _toJsonValue(project.ios.isSwift), + status: StatusProjectValidator.info, + )); + + result.add(ProjectValidatorResult( + name: 'FlutterProject.isModule', + value: _toJsonValue(project.isModule), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'FlutterProject.isPlugin', + value: _toJsonValue(project.isPlugin), + status: StatusProjectValidator.info, + )); + + result.add(ProjectValidatorResult( + name: 'FlutterProject.manifest.appname', + value: _toJsonValue(project.manifest.appName), + status: StatusProjectValidator.info, + )); + + // FlutterVersion + final FlutterVersion version = FlutterVersion( + flutterRoot: Cache.flutterRoot!, + fs: fileSystem, + ); + result.add(ProjectValidatorResult( + name: 'FlutterVersion.frameworkRevision', + value: _toJsonValue(version.frameworkRevision), + status: StatusProjectValidator.info, + )); + + // Platform + result.add(ProjectValidatorResult( + name: 'Platform.operatingSystem', + value: _toJsonValue(platform.operatingSystem), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'Platform.isAndroid', + value: _toJsonValue(platform.isAndroid), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'Platform.isIOS', + value: _toJsonValue(platform.isIOS), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'Platform.isWindows', + value: _toJsonValue(platform.isWindows), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'Platform.isMacOS', + value: _toJsonValue(platform.isMacOS), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'Platform.isFuchsia', + value: _toJsonValue(platform.isFuchsia), + status: StatusProjectValidator.info, + )); + result.add(ProjectValidatorResult( + name: 'Platform.pathSeparator', + value: _toJsonValue(platform.pathSeparator), + status: StatusProjectValidator.info, + )); + + // Cache + result.add(ProjectValidatorResult( + name: 'Cache.flutterRoot', + value: _toJsonValue(Cache.flutterRoot), + status: StatusProjectValidator.info, + )); + return result; + } + + @override + bool supportsProject(FlutterProject project) { + // this validator will run for any type of project + return true; + } + + @override + String get title => 'Machine JSON variable dump'; +} + +/// Validator run for all platforms that extract information from the pubspec.yaml. +/// +/// Specific info from different platforms should be written in their own ProjectValidator. +class GeneralInfoProjectValidator extends ProjectValidator { + @override + Future> start(FlutterProject project) async { + final FlutterManifest flutterManifest = project.manifest; + final List result = []; + final ProjectValidatorResult appNameValidatorResult = _getAppNameResult(flutterManifest); + result.add(appNameValidatorResult); + final String supportedPlatforms = _getSupportedPlatforms(project); + if (supportedPlatforms.isEmpty) { + return result; + } + final ProjectValidatorResult supportedPlatformsResult = ProjectValidatorResult( + name: 'Supported Platforms', + value: supportedPlatforms, + status: StatusProjectValidator.success + ); + final ProjectValidatorResult isFlutterPackage = _isFlutterPackageValidatorResult(flutterManifest); + result.addAll([supportedPlatformsResult, isFlutterPackage]); + if (flutterManifest.flutterDescriptor.isNotEmpty) { + result.add(_materialDesignResult(flutterManifest)); + result.add(_pluginValidatorResult(flutterManifest)); + } + result.add(await project.android.validateJavaAndGradleAgpVersions()); + return result; + } + + ProjectValidatorResult _getAppNameResult(FlutterManifest flutterManifest) { + final String appName = flutterManifest.appName; + const String name = 'App Name'; + if (appName.isEmpty) { + return const ProjectValidatorResult( + name: name, + value: 'name not found', + status: StatusProjectValidator.error + ); + } + return ProjectValidatorResult( + name: name, + value: appName, + status: StatusProjectValidator.success + ); + } + + ProjectValidatorResult _isFlutterPackageValidatorResult(FlutterManifest flutterManifest) { + final String value; + final StatusProjectValidator status; + if (flutterManifest.flutterDescriptor.isNotEmpty) { + value = 'yes'; + status = StatusProjectValidator.success; + } else { + value = 'no'; + status = StatusProjectValidator.warning; + } + + return ProjectValidatorResult( + name: 'Is Flutter Package', + value: value, + status: status + ); + } + + ProjectValidatorResult _materialDesignResult(FlutterManifest flutterManifest) { + return ProjectValidatorResult( + name: 'Uses Material Design', + value: flutterManifest.usesMaterialDesign? 'yes' : 'no', + status: StatusProjectValidator.success + ); + } + + String _getSupportedPlatforms(FlutterProject project) { + return project.getSupportedPlatforms().map((SupportedPlatform platform) => platform.name).join(', '); + } + + ProjectValidatorResult _pluginValidatorResult(FlutterManifest flutterManifest) { + return ProjectValidatorResult( + name: 'Is Plugin', + value: flutterManifest.isPlugin? 'yes' : 'no', + status: StatusProjectValidator.success + ); + } + + @override + bool supportsProject(FlutterProject project) { + // this validator will run for any type of project + return true; + } + + @override + String get title => 'General Info'; +} + +class PubDependenciesProjectValidator extends ProjectValidator { + const PubDependenciesProjectValidator(this._processManager); + final ProcessManager _processManager; + + @override + Future> start(FlutterProject project) async { + const String name = 'Dart dependencies'; + final ProcessResult processResult = await _processManager.run(['dart', 'pub', 'deps', '--json']); + if (processResult.stdout is! String) { + return [ + _createProjectValidatorError(name, 'Command dart pub deps --json failed') + ]; + } + + final LinkedHashMap jsonResult; + final List result = []; + try { + jsonResult = json.decode( + processResult.stdout.toString() + ) as LinkedHashMap; + } on FormatException { + result.add(_createProjectValidatorError(name, processResult.stderr.toString())); + return result; + } + + final DartPubJson dartPubJson = DartPubJson(jsonResult); + final List dependencies = []; + + // Information retrieved from the pubspec.lock file if a dependency comes from + // the hosted url https://pub.dartlang.org we ignore it or if the package + // is the current directory being analyzed (root). + final Set hostedDependencies = {'hosted', 'root'}; + + for (final DartDependencyPackage package in dartPubJson.packages) { + if (!hostedDependencies.contains(package.source)) { + dependencies.addAll(package.dependencies); + } + } + + final String value; + if (dependencies.isNotEmpty) { + final String verb = dependencies.length == 1 ? 'is' : 'are'; + value = '${dependencies.join(', ')} $verb not hosted'; + } else { + value = 'All pub dependencies are hosted on https://pub.dartlang.org'; + } + + result.add( + ProjectValidatorResult( + name: name, + value: value, + status: StatusProjectValidator.info, + ) + ); + + return result; + } + + @override + bool supportsProject(FlutterProject project) { + return true; + } + + @override + String get title => 'Pub dependencies'; + + ProjectValidatorResult _createProjectValidatorError(String name, String value) { + return ProjectValidatorResult(name: name, value: value, status: StatusProjectValidator.error); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/project_validator_result.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/project_validator_result.dart new file mode 100644 index 0000000000000000000000000000000000000000..0dd8b78316b83a2da107756fed0cd29cfe53ec57 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/project_validator_result.dart @@ -0,0 +1,42 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +enum StatusProjectValidator { + error, + warning, + success, + crash, + info, +} + +class ProjectValidatorResult { + + const ProjectValidatorResult({ + required this.name, + required this.value, + required this.status, + this.warning, + }); + + final String name; + final String value; + final String? warning; + final StatusProjectValidator status; + + @override + String toString() { + if (warning != null) { + return '$name: $value (warning: $warning)'; + } + return '$name: $value'; + } + + static ProjectValidatorResult crash(Object exception, StackTrace trace) { + return ProjectValidatorResult( + name: exception.toString(), + value: trace.toString(), + status: StatusProjectValidator.crash + ); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/protocol_discovery.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/protocol_discovery.dart new file mode 100644 index 0000000000000000000000000000000000000000..578052bfb7888c6fde687a39997c71c737ebd0ac --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/protocol_discovery.dart @@ -0,0 +1,255 @@ +// 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 'base/io.dart'; +import 'base/logger.dart'; +import 'device.dart'; +import 'device_port_forwarder.dart'; +import 'globals.dart' as globals; + +/// Discovers a specific service protocol on a device, and forwards the service +/// protocol device port to the host. +class ProtocolDiscovery { + ProtocolDiscovery._( + this.logReader, + this.serviceName, { + this.portForwarder, + required this.throttleDuration, + this.hostPort, + this.devicePort, + required bool ipv6, + required Logger logger, + }) : _logger = logger, + _ipv6 = ipv6 { + _deviceLogSubscription = logReader.logLines.listen( + _handleLine, + onDone: _stopScrapingLogs, + ); + } + + factory ProtocolDiscovery.vmService( + DeviceLogReader logReader, { + DevicePortForwarder? portForwarder, + Duration? throttleDuration, + int? hostPort, + int? devicePort, + required bool ipv6, + required Logger logger, + }) { + const String kVmServiceService = 'VM Service'; + return ProtocolDiscovery._( + logReader, + kVmServiceService, + portForwarder: portForwarder, + throttleDuration: throttleDuration ?? const Duration(milliseconds: 200), + hostPort: hostPort, + devicePort: devicePort, + ipv6: ipv6, + logger: logger, + ); + } + + final DeviceLogReader logReader; + final String serviceName; + final DevicePortForwarder? portForwarder; + final int? hostPort; + final int? devicePort; + final bool _ipv6; + final Logger _logger; + + /// The time to wait before forwarding a new VM Service URIs from [logReader]. + final Duration throttleDuration; + + StreamSubscription? _deviceLogSubscription; + final _BufferedStreamController _uriStreamController = _BufferedStreamController(); + + /// The discovered service URL. + /// + /// Returns null if the log reader shuts down before any uri is found. + /// + /// Use [uris] instead. + // TODO(egarciad): replace `uri` for `uris`. + Future get uri async { + try { + return await uris.first; + } on StateError { + return null; + } + } + + /// The discovered service URLs. + /// + /// When a new VM Service URL: is available in [logReader], + /// the URLs are forwarded at most once every [throttleDuration]. + /// Returns when no event has been observed for [throttleTimeout]. + /// + /// Port forwarding is only attempted when this is invoked, + /// for each VM Service URL in the stream. + Stream get uris { + final Stream uriStream = _uriStreamController.stream + .transform(_throttle( + waitDuration: throttleDuration, + )); + return uriStream.asyncMap(_forwardPort); + } + + Future cancel() => _stopScrapingLogs(); + + Future _stopScrapingLogs() async { + await _uriStreamController.close(); + await _deviceLogSubscription?.cancel(); + _deviceLogSubscription = null; + } + + Match? _getPatternMatch(String line) { + return globals.kVMServiceMessageRegExp.firstMatch(line); + } + + Uri? _getVmServiceUri(String line) { + final Match? match = _getPatternMatch(line); + if (match != null) { + return Uri.parse(match[1]!); + } + return null; + } + + void _handleLine(String line) { + Uri? uri; + try { + uri = _getVmServiceUri(line); + } on FormatException catch (error, stackTrace) { + _uriStreamController.addError(error, stackTrace); + } + if (uri == null || uri.host.isEmpty) { + return; + } + if (devicePort != null && uri.port != devicePort) { + _logger.printTrace('skipping potential VM Service $uri due to device port mismatch'); + return; + } + _uriStreamController.add(uri); + } + + Future _forwardPort(Uri deviceUri) async { + _logger.printTrace('$serviceName URL on device: $deviceUri'); + Uri hostUri = deviceUri; + + final DevicePortForwarder? forwarder = portForwarder; + if (forwarder != null) { + final int actualDevicePort = deviceUri.port; + final int actualHostPort = await forwarder.forward(actualDevicePort, hostPort: hostPort); + _logger.printTrace('Forwarded host port $actualHostPort to device port $actualDevicePort for $serviceName'); + hostUri = deviceUri.replace(port: actualHostPort); + } + + if (InternetAddress(hostUri.host).isLoopback && _ipv6) { + hostUri = hostUri.replace(host: InternetAddress.loopbackIPv6.host); + } + return hostUri; + } +} + +/// Provides a broadcast stream controller that buffers the events +/// if there isn't a listener attached. +/// The events are then delivered when a listener is attached to the stream. +class _BufferedStreamController { + _BufferedStreamController() : _events = []; + + /// The stream that this controller is controlling. + Stream get stream { + return _streamController.stream; + } + + late final StreamController _streamController = () { + final StreamController streamControllerInstance = StreamController.broadcast(); + streamControllerInstance.onListen = () { + for (final dynamic event in _events) { + if (event is T) { + streamControllerInstance.add(event); + } else { + streamControllerInstance.addError( + (event as Iterable).first as Object, + event.last as StackTrace, + ); + } + } + _events.clear(); + }; + return streamControllerInstance; + }(); + + final List _events; + + /// Sends [event] if there is a listener attached to the broadcast stream. + /// Otherwise, it enqueues [event] until a listener is attached. + void add(T event) { + if (_streamController.hasListener) { + _streamController.add(event); + } else { + _events.add(event); + } + } + + /// Sends or enqueues an error event. + void addError(Object error, [StackTrace? stackTrace]) { + if (_streamController.hasListener) { + _streamController.addError(error, stackTrace); + } else { + _events.add([error, stackTrace]); + } + } + + /// Closes the stream. + Future close() { + return _streamController.close(); + } +} + +/// This transformer will produce an event at most once every [waitDuration]. +/// +/// For example, consider a `waitDuration` of `10ms`, and list of event names +/// and arrival times: `a (0ms), b (5ms), c (11ms), d (21ms)`. +/// The events `a`, `c`, and `d` will be produced as a result. +StreamTransformer _throttle({ + required Duration waitDuration, +}) { + + S latestLine; + int? lastExecution; + Future? throttleFuture; + bool done = false; + + return StreamTransformer + .fromHandlers( + handleData: (S value, EventSink sink) { + latestLine = value; + + final bool isFirstMessage = lastExecution == null; + final int currentTime = DateTime.now().millisecondsSinceEpoch; + lastExecution ??= currentTime; + final int remainingTime = currentTime - lastExecution!; + + // Always send the first event immediately. + final int nextExecutionTime = isFirstMessage || remainingTime > waitDuration.inMilliseconds + ? 0 + : waitDuration.inMilliseconds - remainingTime; + throttleFuture ??= Future + .delayed(Duration(milliseconds: nextExecutionTime)) + .whenComplete(() { + if (done) { + return; + } + sink.add(latestLine); + throttleFuture = null; + lastExecution = DateTime.now().millisecondsSinceEpoch; + }); + }, + handleDone: (EventSink sink) { + done = true; + sink.close(); + } + ); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/proxy_validator.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/proxy_validator.dart new file mode 100644 index 0000000000000000000000000000000000000000..b02fffaf77792aa4b5544234a54944b1386436f1 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/proxy_validator.dart @@ -0,0 +1,80 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'base/io.dart'; +import 'base/platform.dart'; +import 'doctor_validator.dart'; + +/// A validator that displays configured HTTP_PROXY environment variables. +/// +/// if the `HTTP_PROXY` environment variable is non-empty, the contents are +/// validated along with `NO_PROXY`. +class ProxyValidator extends DoctorValidator { + ProxyValidator({ + required Platform platform, + }) : shouldShow = _getEnv('HTTP_PROXY', platform).isNotEmpty, + _httpProxy = _getEnv('HTTP_PROXY', platform), + _noProxy = _getEnv('NO_PROXY', platform), + super('Proxy Configuration'); + + final bool shouldShow; + final String _httpProxy; + final String _noProxy; + + /// Gets a trimmed, non-null environment variable. If the variable is not set + /// an empty string will be returned. Checks for the lowercase version of the + /// environment variable first, then uppercase to match Dart's HTTP implementation. + static String _getEnv(String key, Platform platform) => + platform.environment[key.toLowerCase()]?.trim() ?? + platform.environment[key.toUpperCase()]?.trim() ?? + ''; + + @override + Future validate() async { + if (_httpProxy.isEmpty) { + return const ValidationResult( + ValidationType.success, []); + } + + final List messages = [ + const ValidationMessage('HTTP_PROXY is set'), + if (_noProxy.isEmpty) + const ValidationMessage.hint('NO_PROXY is not set') + else + ...[ + ValidationMessage('NO_PROXY is $_noProxy'), + for (final String host in await _getLoopbackAddresses()) + if (_noProxy.contains(host)) + ValidationMessage('NO_PROXY contains $host') + else + ValidationMessage.hint('NO_PROXY does not contain $host'), + ], + ]; + + final bool hasIssues = messages.any( + (ValidationMessage msg) => msg.isHint || msg.isError); + + return ValidationResult( + hasIssues ? ValidationType.partial : ValidationType.success, + messages, + ); + } + + Future> _getLoopbackAddresses() async { + final List loopBackAddresses = ['localhost']; + + final List networkInterfaces = + await listNetworkInterfaces(includeLinkLocal: true, includeLoopback: true); + + for (final NetworkInterface networkInterface in networkInterfaces) { + for (final InternetAddress internetAddress in networkInterface.addresses) { + if (internetAddress.isLoopback) { + loopBackAddresses.add(internetAddress.address); + } + } + } + + return loopBackAddresses; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/resident_devtools_handler.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/resident_devtools_handler.dart new file mode 100644 index 0000000000000000000000000000000000000000..5eac9320ac090becbd698410beb77251832629b5 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/resident_devtools_handler.dart @@ -0,0 +1,350 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:browser_launcher/browser_launcher.dart'; +import 'package:meta/meta.dart'; + +import 'base/logger.dart'; +import 'build_info.dart'; +import 'resident_runner.dart'; +import 'vmservice.dart'; + +typedef ResidentDevtoolsHandlerFactory = ResidentDevtoolsHandler Function(DevtoolsLauncher?, ResidentRunner, Logger); + +ResidentDevtoolsHandler createDefaultHandler(DevtoolsLauncher? launcher, ResidentRunner runner, Logger logger) { + return FlutterResidentDevtoolsHandler(launcher, runner, logger); +} + +/// Helper class to manage the life-cycle of devtools and its interaction with +/// the resident runner. +abstract class ResidentDevtoolsHandler { + /// The current devtools server, or null if one is not running. + DevToolsServerAddress? get activeDevToolsServer; + + /// Whether it's ok to announce the [activeDevToolsServer]. + /// + /// This should only return true once all the devices have been notified + /// of the DevTools. + bool get readyToAnnounce; + + Future hotRestart(List flutterDevices); + + Future serveAndAnnounceDevTools({ + Uri? devToolsServerAddress, + required List flutterDevices, + bool isStartPaused = false, + }); + + bool launchDevToolsInBrowser({required List flutterDevices}); + + Future shutdown(); +} + +class FlutterResidentDevtoolsHandler implements ResidentDevtoolsHandler { + FlutterResidentDevtoolsHandler(this._devToolsLauncher, this._residentRunner, this._logger); + + static const Duration launchInBrowserTimeout = Duration(seconds: 15); + + final DevtoolsLauncher? _devToolsLauncher; + final ResidentRunner _residentRunner; + final Logger _logger; + bool _shutdown = false; + bool _served = false; + + @visibleForTesting + bool launchedInBrowser = false; + + @override + DevToolsServerAddress? get activeDevToolsServer { + assert(!_readyToAnnounce || _devToolsLauncher?.activeDevToolsServer != null); + return _devToolsLauncher?.activeDevToolsServer; + } + + @override + bool get readyToAnnounce => _readyToAnnounce; + bool _readyToAnnounce = false; + + // This must be guaranteed not to return a Future that fails. + @override + Future serveAndAnnounceDevTools({ + Uri? devToolsServerAddress, + required List flutterDevices, + bool isStartPaused = false, + }) async { + assert(!_readyToAnnounce); + if (!_residentRunner.supportsServiceProtocol || _devToolsLauncher == null) { + return; + } + if (devToolsServerAddress != null) { + _devToolsLauncher.devToolsUrl = devToolsServerAddress; + } else { + await _devToolsLauncher.serve(); + _served = true; + } + await _devToolsLauncher.ready; + // Do not attempt to print debugger list if the connection has failed or if we're shutting down. + if (_devToolsLauncher.activeDevToolsServer == null || _shutdown) { + assert(!_readyToAnnounce); + return; + } + + final Uri? devToolsUrl = _devToolsLauncher.devToolsUrl; + if (devToolsUrl != null) { + for (final FlutterDevice? device in flutterDevices) { + if (device == null) { + continue; + } + // Notify the DDS instances that there's a DevTools instance available so they can correctly + // redirect DevTools related requests. + device.device?.dds.setExternalDevToolsUri(devToolsUrl); + } + } + + Future callServiceExtensions() async { + final List devicesWithExtension = await _devicesWithExtensions(flutterDevices); + await Future.wait( + >[ + _maybeCallDevToolsUriServiceExtension(devicesWithExtension), + _callConnectedVmServiceUriExtension(devicesWithExtension) + ] + ); + } + + // If the application is starting paused, we can't invoke service extensions + // as they're handled on the target app's paused isolate. Since invoking + // service extensions will block in this situation, we should wait to invoke + // them until after we've output the DevTools connection details. + if (!isStartPaused) { + await callServiceExtensions(); + } + + // This check needs to happen after the possible asynchronous call above, + // otherwise a shutdown event might be missed and the DevTools launcher may + // no longer be initialized. + if (_shutdown) { + // If we're shutting down, no point reporting the debugger list. + return; + } + + _readyToAnnounce = true; + assert(_devToolsLauncher.activeDevToolsServer != null); + if (_residentRunner.reportedDebuggers) { + // Since the DevTools only just became available, we haven't had a chance to + // report their URLs yet. Do so now. + _residentRunner.printDebuggerList(includeVmService: false); + } + + if (isStartPaused) { + await callServiceExtensions(); + } + } + + // This must be guaranteed not to return a Future that fails. + @override + bool launchDevToolsInBrowser({required List flutterDevices}) { + if (!_residentRunner.supportsServiceProtocol || _devToolsLauncher == null) { + return false; + } + if (_devToolsLauncher.devToolsUrl == null) { + _logger.startProgress('Waiting for Flutter DevTools to be served...'); + unawaited(_devToolsLauncher.ready.then((_) { + _launchDevToolsForDevices(flutterDevices); + })); + } else { + _launchDevToolsForDevices(flutterDevices); + } + return true; + } + + void _launchDevToolsForDevices(List flutterDevices) { + assert(activeDevToolsServer != null); + for (final FlutterDevice? device in flutterDevices) { + final String devToolsUrl = activeDevToolsServer!.uri!.replace( + queryParameters: {'uri': '${device!.vmService!.httpAddress}'}, + ).toString(); + _logger.printStatus('Launching Flutter DevTools for ${device.device!.name} at $devToolsUrl'); + unawaited(Chrome.start([devToolsUrl])); + } + launchedInBrowser = true; + } + + Future _maybeCallDevToolsUriServiceExtension( + List flutterDevices, + ) async { + if (_devToolsLauncher?.activeDevToolsServer == null) { + return; + } + await Future.wait(>[ + for (final FlutterDevice? device in flutterDevices) + if (device?.vmService != null) _callDevToolsUriExtension(device!), + ]); + } + + Future _callDevToolsUriExtension( + FlutterDevice device, + ) async { + try { + await _invokeRpcOnFirstView( + 'ext.flutter.activeDevToolsServerAddress', + device: device, + params: { + 'value': _devToolsLauncher!.activeDevToolsServer!.uri.toString(), + }, + ); + } on Exception catch (e) { + _logger.printError( + 'Failed to set DevTools server address: $e. Deep links to' + ' DevTools will not show in Flutter errors.', + ); + } + } + + Future> _devicesWithExtensions(List flutterDevices) async { + return Future.wait(>[ + for (final FlutterDevice? device in flutterDevices) _waitForExtensionsForDevice(device!), + ]); + } + + /// Returns null if the service extension cannot be found on the device. + Future _waitForExtensionsForDevice(FlutterDevice flutterDevice) async { + const String extension = 'ext.flutter.connectedVmServiceUri'; + try { + await flutterDevice.vmService?.findExtensionIsolate( + extension, + ); + return flutterDevice; + } on VmServiceDisappearedException { + _logger.printTrace( + 'The VM Service for ${flutterDevice.device} disappeared while trying to' + ' find the $extension service extension. Skipping subsequent DevTools ' + 'setup for this device.', + ); + return null; + } + } + + Future _callConnectedVmServiceUriExtension(List flutterDevices) async { + await Future.wait(>[ + for (final FlutterDevice? device in flutterDevices) + if (device?.vmService != null) _callConnectedVmServiceExtension(device!), + ]); + } + + Future _callConnectedVmServiceExtension(FlutterDevice device) async { + final Uri? uri = device.vmService!.httpAddress ?? device.vmService!.wsAddress; + if (uri == null) { + return; + } + try { + await _invokeRpcOnFirstView( + 'ext.flutter.connectedVmServiceUri', + device: device, + params: { + 'value': uri.toString(), + }, + ); + } on Exception catch (e) { + _logger.printError(e.toString()); + _logger.printError( + 'Failed to set vm service URI: $e. Deep links to DevTools' + ' will not show in Flutter errors.', + ); + } + } + + Future _invokeRpcOnFirstView( + String method, { + required FlutterDevice device, + required Map params, + }) async { + if (device.targetPlatform == TargetPlatform.web_javascript) { + await device.vmService!.callMethodWrapper( + method, + args: params, + ); + return; + } + final List views = await device.vmService!.getFlutterViews(); + if (views.isEmpty) { + return; + } + await device.vmService!.invokeFlutterExtensionRpcRaw( + method, + args: params, + isolateId: views.first.uiIsolate!.id!, + ); + } + + @override + Future hotRestart(List flutterDevices) async { + final List devicesWithExtension = await _devicesWithExtensions(flutterDevices); + await Future.wait(>[ + _maybeCallDevToolsUriServiceExtension(devicesWithExtension), + _callConnectedVmServiceUriExtension(devicesWithExtension), + ]); + } + + @override + Future shutdown() async { + if (_devToolsLauncher == null || _shutdown || !_served) { + return; + } + _shutdown = true; + _readyToAnnounce = false; + await _devToolsLauncher.close(); + } +} + +@visibleForTesting +NoOpDevtoolsHandler createNoOpHandler(DevtoolsLauncher? launcher, ResidentRunner runner, Logger logger) { + return NoOpDevtoolsHandler(); +} + +@visibleForTesting +class NoOpDevtoolsHandler implements ResidentDevtoolsHandler { + bool wasShutdown = false; + + @override + DevToolsServerAddress? get activeDevToolsServer => null; + + @override + bool get readyToAnnounce => false; + + @override + Future hotRestart(List flutterDevices) async { + return; + } + + @override + Future serveAndAnnounceDevTools({ + Uri? devToolsServerAddress, + List? flutterDevices, + bool isStartPaused = false, + }) async { + return; + } + + @override + bool launchDevToolsInBrowser({List? flutterDevices}) { + return false; + } + + @override + Future shutdown() async { + wasShutdown = true; + return; + } +} + +/// Convert a [URI] with query parameters into a display format instead +/// of the default URI encoding. +String urlToDisplayString(Uri uri) { + final StringBuffer base = StringBuffer(uri.replace( + queryParameters: {}, + ).toString()); + base.write(uri.queryParameters.keys.map((String key) => '$key=${uri.queryParameters[key]}').join('&')); + return base.toString(); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/resident_runner.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/resident_runner.dart new file mode 100644 index 0000000000000000000000000000000000000000..5422708de80a5d959cd8da1ed6664902e980a02f --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/resident_runner.dart @@ -0,0 +1,1970 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:dds/dds.dart' as dds; +import 'package:meta/meta.dart'; +import 'package:package_config/package_config.dart'; +import 'package:vm_service/vm_service.dart' as vm_service; + +import 'application_package.dart'; +import 'artifacts.dart'; +import 'asset.dart'; +import 'base/command_help.dart'; +import 'base/common.dart'; +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'base/io.dart' as io; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'base/signals.dart'; +import 'base/terminal.dart'; +import 'base/utils.dart'; +import 'build_info.dart'; +import 'build_system/build_system.dart'; +import 'build_system/targets/dart_plugin_registrant.dart'; +import 'build_system/targets/localizations.dart'; +import 'build_system/targets/scene_importer.dart'; +import 'build_system/targets/shader_compiler.dart'; +import 'bundle.dart'; +import 'cache.dart'; +import 'compile.dart'; +import 'convert.dart'; +import 'devfs.dart'; +import 'device.dart'; +import 'globals.dart' as globals; +import 'ios/application_package.dart'; +import 'ios/devices.dart'; +import 'project.dart'; +import 'resident_devtools_handler.dart'; +import 'run_cold.dart'; +import 'run_hot.dart'; +import 'sksl_writer.dart'; +import 'vmservice.dart'; + +class FlutterDevice { + FlutterDevice( + this.device, { + required this.buildInfo, + TargetModel targetModel = TargetModel.flutter, + this.targetPlatform, + ResidentCompiler? generator, + this.userIdentifier, + required this.developmentShaderCompiler, + this.developmentSceneImporter, + }) : generator = generator ?? ResidentCompiler( + globals.artifacts!.getArtifactPath( + Artifact.flutterPatchedSdkPath, + platform: targetPlatform, + mode: buildInfo.mode, + ), + buildMode: buildInfo.mode, + trackWidgetCreation: buildInfo.trackWidgetCreation, + fileSystemRoots: buildInfo.fileSystemRoots, + fileSystemScheme: buildInfo.fileSystemScheme, + targetModel: targetModel, + dartDefines: buildInfo.dartDefines, + packagesPath: buildInfo.packagesPath, + frontendServerStarterPath: buildInfo.frontendServerStarterPath, + extraFrontEndOptions: buildInfo.extraFrontEndOptions, + artifacts: globals.artifacts!, + processManager: globals.processManager, + logger: globals.logger, + platform: globals.platform, + fileSystem: globals.fs, + ); + + /// Create a [FlutterDevice] with optional code generation enabled. + static Future create( + Device device, { + required String? target, + required BuildInfo buildInfo, + required Platform platform, + TargetModel targetModel = TargetModel.flutter, + List? experimentalFlags, + String? userIdentifier, + }) async { + final TargetPlatform targetPlatform = await device.targetPlatform; + if (device.platformType == PlatformType.fuchsia) { + targetModel = TargetModel.flutterRunner; + } + final DevelopmentShaderCompiler shaderCompiler = DevelopmentShaderCompiler( + shaderCompiler: ShaderCompiler( + artifacts: globals.artifacts!, + logger: globals.logger, + processManager: globals.processManager, + fileSystem: globals.fs, + ), + fileSystem: globals.fs, + ); + + final DevelopmentSceneImporter sceneImporter = DevelopmentSceneImporter( + sceneImporter: SceneImporter( + artifacts: globals.artifacts!, + logger: globals.logger, + processManager: globals.processManager, + fileSystem: globals.fs, + ), + fileSystem: globals.fs, + ); + + final ResidentCompiler generator; + + // For both web and non-web platforms we initialize dill to/from + // a shared location for faster bootstrapping. If the compiler fails + // due to a kernel target or version mismatch, no error is reported + // and the compiler starts up as normal. Unexpected errors will print + // a warning message and dump some debug information which can be + // used to file a bug, but the compiler will still start up correctly. + if (targetPlatform == TargetPlatform.web_javascript) { + // TODO(zanderso): consistently provide these flags across platforms. + final String platformDillName; + final List extraFrontEndOptions = List.of(buildInfo.extraFrontEndOptions); + if (buildInfo.nullSafetyMode == NullSafetyMode.unsound) { + platformDillName = 'ddc_outline.dill'; + if (!extraFrontEndOptions.contains('--no-sound-null-safety')) { + extraFrontEndOptions.add('--no-sound-null-safety'); + } + } else if (buildInfo.nullSafetyMode == NullSafetyMode.sound) { + platformDillName = 'ddc_outline_sound.dill'; + if (!extraFrontEndOptions.contains('--sound-null-safety')) { + extraFrontEndOptions.add('--sound-null-safety'); + } + } else { + throw StateError('Expected buildInfo.nullSafetyMode to be one of unsound or sound, got ${buildInfo.nullSafetyMode}'); + } + + final String platformDillPath = globals.fs.path.join( + getWebPlatformBinariesDirectory(globals.artifacts!, buildInfo.webRenderer).path, + platformDillName, + ); + + generator = ResidentCompiler( + globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path, + buildMode: buildInfo.mode, + trackWidgetCreation: buildInfo.trackWidgetCreation, + fileSystemRoots: buildInfo.fileSystemRoots, + // Override the filesystem scheme so that the frontend_server can find + // the generated entrypoint code. + fileSystemScheme: 'org-dartlang-app', + initializeFromDill: buildInfo.initializeFromDill ?? getDefaultCachedKernelPath( + trackWidgetCreation: buildInfo.trackWidgetCreation, + dartDefines: buildInfo.dartDefines, + extraFrontEndOptions: extraFrontEndOptions, + ), + assumeInitializeFromDillUpToDate: buildInfo.assumeInitializeFromDillUpToDate, + targetModel: TargetModel.dartdevc, + frontendServerStarterPath: buildInfo.frontendServerStarterPath, + extraFrontEndOptions: extraFrontEndOptions, + platformDill: globals.fs.file(platformDillPath).absolute.uri.toString(), + dartDefines: buildInfo.dartDefines, + librariesSpec: globals.fs.file(globals.artifacts! + .getHostArtifact(HostArtifact.flutterWebLibrariesJson)).uri.toString(), + packagesPath: buildInfo.packagesPath, + artifacts: globals.artifacts!, + processManager: globals.processManager, + logger: globals.logger, + fileSystem: globals.fs, + platform: platform, + ); + } else { + List extraFrontEndOptions = buildInfo.extraFrontEndOptions; + extraFrontEndOptions = [ + '--enable-experiment=alternative-invalidation-strategy', + ...extraFrontEndOptions, + ]; + generator = ResidentCompiler( + globals.artifacts!.getArtifactPath( + Artifact.flutterPatchedSdkPath, + platform: targetPlatform, + mode: buildInfo.mode, + ), + buildMode: buildInfo.mode, + trackWidgetCreation: buildInfo.trackWidgetCreation, + fileSystemRoots: buildInfo.fileSystemRoots, + fileSystemScheme: buildInfo.fileSystemScheme, + targetModel: targetModel, + dartDefines: buildInfo.dartDefines, + frontendServerStarterPath: buildInfo.frontendServerStarterPath, + extraFrontEndOptions: extraFrontEndOptions, + initializeFromDill: buildInfo.initializeFromDill ?? getDefaultCachedKernelPath( + trackWidgetCreation: buildInfo.trackWidgetCreation, + dartDefines: buildInfo.dartDefines, + extraFrontEndOptions: extraFrontEndOptions, + ), + assumeInitializeFromDillUpToDate: buildInfo.assumeInitializeFromDillUpToDate, + packagesPath: buildInfo.packagesPath, + artifacts: globals.artifacts!, + processManager: globals.processManager, + logger: globals.logger, + platform: platform, + fileSystem: globals.fs, + ); + } + + return FlutterDevice( + device, + targetModel: targetModel, + targetPlatform: targetPlatform, + generator: generator, + buildInfo: buildInfo, + userIdentifier: userIdentifier, + developmentShaderCompiler: shaderCompiler, + developmentSceneImporter: sceneImporter, + ); + } + + final TargetPlatform? targetPlatform; + final Device? device; + final ResidentCompiler? generator; + final BuildInfo buildInfo; + final String? userIdentifier; + final DevelopmentShaderCompiler developmentShaderCompiler; + final DevelopmentSceneImporter? developmentSceneImporter; + + DevFSWriter? devFSWriter; + Stream? vmServiceUris; + FlutterVmService? vmService; + DevFS? devFS; + ApplicationPackage? package; + StreamSubscription? _loggingSubscription; + bool? _isListeningForVmServiceUri; + + /// Whether the stream [vmServiceUris] is still open. + bool get isWaitingForVmService => _isListeningForVmServiceUri ?? false; + + /// If the [reloadSources] parameter is not null the 'reloadSources' service + /// will be registered. + /// The 'reloadSources' service can be used by other Service Protocol clients + /// connected to the VM (e.g. VmService) to request a reload of the source + /// code of the running application (a.k.a. HotReload). + /// The 'compileExpression' service can be used to compile user-provided + /// expressions requested during debugging of the application. + /// This ensures that the reload process follows the normal orchestration of + /// the Flutter Tools and not just the VM internal service. + Future connect({ + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, + int? hostVmServicePort, + int? ddsPort, + bool disableServiceAuthCodes = false, + bool cacheStartupProfile = false, + bool enableDds = true, + required bool allowExistingDdsInstance, + bool ipv6 = false, + }) { + final Completer completer = Completer(); + late StreamSubscription subscription; + bool isWaitingForVm = false; + + subscription = vmServiceUris!.listen((Uri? vmServiceUri) async { + // FYI, this message is used as a sentinel in tests. + globals.printTrace('Connecting to service protocol: $vmServiceUri'); + isWaitingForVm = true; + bool existingDds = false; + FlutterVmService? service; + if (enableDds) { + void handleError(Exception e, StackTrace st) { + globals.printTrace('Fail to connect to service protocol: $vmServiceUri: $e'); + if (!completer.isCompleted) { + completer.completeError('failed to connect to $vmServiceUri', st); + } + } + // First check if the VM service is actually listening on vmServiceUri as + // this may not be the case when scraping logcat for URIs. If this URI is + // from an old application instance, we shouldn't try and start DDS. + try { + service = await connectToVmService(vmServiceUri!, logger: globals.logger); + await service.dispose(); + } on Exception catch (exception) { + globals.printTrace('Fail to connect to service protocol: $vmServiceUri: $exception'); + if (!completer.isCompleted && !_isListeningForVmServiceUri!) { + completer.completeError('failed to connect to $vmServiceUri'); + } + return; + } + + // This first try block is meant to catch errors that occur during DDS startup + // (e.g., failure to bind to a port, failure to connect to the VM service, + // attaching to a VM service with existing clients, etc.). + try { + await device!.dds.startDartDevelopmentService( + vmServiceUri, + hostPort: ddsPort, + ipv6: ipv6, + disableServiceAuthCodes: disableServiceAuthCodes, + logger: globals.logger, + cacheStartupProfile: cacheStartupProfile, + ); + } on dds.DartDevelopmentServiceException catch (e, st) { + if (!allowExistingDdsInstance || + (e.errorCode != dds.DartDevelopmentServiceException.existingDdsInstanceError)) { + handleError(e, st); + return; + } else { + existingDds = true; + } + } on ToolExit { + rethrow; + } on Exception catch (e, st) { + handleError(e, st); + return; + } + } + // This second try block handles cases where the VM service connection goes down + // before flutter_tools connects to DDS. The DDS `done` future completes when DDS + // shuts down, including after an error. If `done` completes before `connectToVmService`, + // something went wrong that caused DDS to shutdown early. + try { + service = await Future.any( + >[ + connectToVmService( + enableDds ? (device!.dds.uri ?? vmServiceUri!): vmServiceUri!, + reloadSources: reloadSources, + restart: restart, + compileExpression: compileExpression, + getSkSLMethod: getSkSLMethod, + flutterProject: FlutterProject.current(), + printStructuredErrorLogMethod: printStructuredErrorLogMethod, + device: device, + logger: globals.logger, + ), + if (!existingDds) + device!.dds.done.whenComplete(() => throw Exception('DDS shut down too early')), + ] + ) as FlutterVmService?; + } on Exception catch (exception) { + globals.printTrace('Fail to connect to service protocol: $vmServiceUri: $exception'); + if (!completer.isCompleted && !_isListeningForVmServiceUri!) { + completer.completeError('failed to connect to $vmServiceUri'); + } + return; + } + if (completer.isCompleted) { + return; + } + globals.printTrace('Successfully connected to service protocol: $vmServiceUri'); + + vmService = service; + (await device!.getLogReader(app: package)).connectedVMService = vmService; + completer.complete(); + await subscription.cancel(); + }, onError: (dynamic error) { + globals.printTrace('Fail to handle VM Service URI: $error'); + }, onDone: () { + _isListeningForVmServiceUri = false; + if (!completer.isCompleted && !isWaitingForVm) { + completer.completeError(Exception('connection to device ended too early')); + } + }); + _isListeningForVmServiceUri = true; + return completer.future; + } + + Future exitApps({ + @visibleForTesting Duration timeoutDelay = const Duration(seconds: 10), + }) async { + // TODO(zanderso): https://github.com/flutter/flutter/issues/83127 + // When updating `flutter attach` to support running without a device, + // this will need to be changed to fall back to io exit. + await device!.stopApp(package, userIdentifier: userIdentifier); + } + + Future setupDevFS( + String fsName, + Directory rootDirectory, + ) { + // One devFS per device. Shared by all running instances. + devFS = DevFS( + vmService!, + fsName, + rootDirectory, + osUtils: globals.os, + fileSystem: globals.fs, + logger: globals.logger, + ); + return devFS!.create(); + } + + Future startEchoingDeviceLog(DebuggingOptions debuggingOptions) async { + if (_loggingSubscription != null) { + return; + } + final Stream logStream; + if (device is IOSDevice) { + logStream = (device! as IOSDevice).getLogReader( + app: package as IOSApp?, + usingCISystem: debuggingOptions.usingCISystem, + ).logLines; + } else { + logStream = (await device!.getLogReader(app: package)).logLines; + } + _loggingSubscription = logStream.listen((String line) { + if (!line.contains(globals.kVMServiceMessageRegExp)) { + globals.printStatus(line, wrap: false); + } + }); + } + + Future stopEchoingDeviceLog() async { + if (_loggingSubscription == null) { + return; + } + await _loggingSubscription!.cancel(); + _loggingSubscription = null; + } + + Future initLogReader() async { + final vm_service.VM vm = await vmService!.service.getVM(); + final DeviceLogReader logReader = await device!.getLogReader(app: package); + logReader.appPid = vm.pid; + } + + Future runHot({ + required HotRunner hotRunner, + String? route, + }) async { + final bool prebuiltMode = hotRunner.applicationBinary != null; + final String modeName = hotRunner.debuggingOptions.buildInfo.friendlyModeName; + globals.printStatus( + 'Launching ${getDisplayPath(hotRunner.mainPath, globals.fs)} ' + 'on ${device!.name} in $modeName mode...', + ); + + final TargetPlatform targetPlatform = await device!.targetPlatform; + package = await ApplicationPackageFactory.instance!.getPackageForPlatform( + targetPlatform, + buildInfo: hotRunner.debuggingOptions.buildInfo, + applicationBinary: hotRunner.applicationBinary, + ); + final ApplicationPackage? applicationPackage = package; + + if (applicationPackage == null) { + String message = 'No application found for $targetPlatform.'; + final String? hint = await getMissingPackageHintForPlatform(targetPlatform); + if (hint != null) { + message += '\n$hint'; + } + globals.printError(message); + return 1; + } + devFSWriter = device!.createDevFSWriter(applicationPackage, userIdentifier); + + final Map platformArgs = { + 'multidex': hotRunner.multidexEnabled, + }; + + await startEchoingDeviceLog(hotRunner.debuggingOptions); + + // Start the application. + final Future futureResult = device!.startApp( + applicationPackage, + mainPath: hotRunner.mainPath, + debuggingOptions: hotRunner.debuggingOptions, + platformArgs: platformArgs, + route: route, + prebuiltApplication: prebuiltMode, + ipv6: hotRunner.ipv6!, + userIdentifier: userIdentifier, + ); + + final LaunchResult result = await futureResult; + + if (!result.started) { + globals.printError('Error launching application on ${device!.name}.'); + await stopEchoingDeviceLog(); + return 2; + } + if (result.hasVmService) { + vmServiceUris = Stream + .value(result.vmServiceUri) + .asBroadcastStream(); + } else { + vmServiceUris = const Stream + .empty() + .asBroadcastStream(); + } + return 0; + } + + Future runCold({ + required ColdRunner coldRunner, + String? route, + }) async { + final TargetPlatform targetPlatform = await device!.targetPlatform; + package = await ApplicationPackageFactory.instance!.getPackageForPlatform( + targetPlatform, + buildInfo: coldRunner.debuggingOptions.buildInfo, + applicationBinary: coldRunner.applicationBinary, + ); + final ApplicationPackage? applicationPackage = package; + + if (applicationPackage == null) { + String message = 'No application found for $targetPlatform.'; + final String? hint = await getMissingPackageHintForPlatform(targetPlatform); + if (hint != null) { + message += '\n$hint'; + } + globals.printError(message); + return 1; + } + + devFSWriter = device!.createDevFSWriter(applicationPackage, userIdentifier); + + final String modeName = coldRunner.debuggingOptions.buildInfo.friendlyModeName; + final bool prebuiltMode = coldRunner.applicationBinary != null; + globals.printStatus( + 'Launching ${getDisplayPath(coldRunner.mainPath, globals.fs)} ' + 'on ${device!.name} in $modeName mode...', + ); + + final Map platformArgs = {}; + platformArgs['trace-startup'] = coldRunner.traceStartup; + platformArgs['multidex'] = coldRunner.multidexEnabled; + + await startEchoingDeviceLog(coldRunner.debuggingOptions); + + final LaunchResult result = await device!.startApp( + applicationPackage, + mainPath: coldRunner.mainPath, + debuggingOptions: coldRunner.debuggingOptions, + platformArgs: platformArgs, + route: route, + prebuiltApplication: prebuiltMode, + ipv6: coldRunner.ipv6!, + userIdentifier: userIdentifier, + ); + + if (!result.started) { + globals.printError('Error running application on ${device!.name}.'); + await stopEchoingDeviceLog(); + return 2; + } + if (result.hasVmService) { + vmServiceUris = Stream + .value(result.vmServiceUri) + .asBroadcastStream(); + } else { + vmServiceUris = const Stream + .empty() + .asBroadcastStream(); + } + return 0; + } + + Future updateDevFS({ + required Uri mainUri, + String? target, + AssetBundle? bundle, + DateTime? firstBuildTime, + bool bundleFirstUpload = false, + bool bundleDirty = false, + bool fullRestart = false, + String? projectRootPath, + required String pathToReload, + required String dillOutputPath, + required List invalidatedFiles, + required PackageConfig packageConfig, + }) async { + final Status devFSStatus = globals.logger.startProgress( + 'Syncing files to device ${device!.name}...', + ); + UpdateFSReport report; + try { + report = await devFS!.update( + mainUri: mainUri, + target: target, + bundle: bundle, + firstBuildTime: firstBuildTime, + bundleFirstUpload: bundleFirstUpload, + generator: generator!, + fullRestart: fullRestart, + dillOutputPath: dillOutputPath, + trackWidgetCreation: buildInfo.trackWidgetCreation, + projectRootPath: projectRootPath, + pathToReload: pathToReload, + invalidatedFiles: invalidatedFiles, + packageConfig: packageConfig, + devFSWriter: devFSWriter, + shaderCompiler: developmentShaderCompiler, + sceneImporter: developmentSceneImporter, + dartPluginRegistrant: FlutterProject.current().dartPluginRegistrant, + ); + } on DevFSException { + devFSStatus.cancel(); + return UpdateFSReport(); + } + devFSStatus.stop(); + globals.printTrace('Synced ${getSizeAsMB(report.syncedBytes)}.'); + return report; + } + + Future updateReloadStatus(bool wasReloadSuccessful) async { + if (wasReloadSuccessful) { + generator?.accept(); + } else { + await generator?.reject(); + } + } +} + +/// A subset of the [ResidentRunner] for delegating to attached flutter devices. +abstract class ResidentHandlers { + List get flutterDevices; + + /// Whether the resident runner has hot reload and restart enabled. + bool get hotMode; + + /// Whether the resident runner is connect to the device's VM Service. + bool get supportsServiceProtocol; + + /// The application is running in debug mode. + bool get isRunningDebug; + + /// The application is running in profile mode. + bool get isRunningProfile; + + /// The application is running in release mode. + bool get isRunningRelease; + + /// The resident runner should stay resident after establishing a connection with the + /// application. + bool get stayResident; + + /// Whether all of the connected devices support hot restart. + /// + /// To prevent scenarios where only a subset of devices are hot restarted, + /// the runner requires that all attached devices can support hot restart + /// before enabling it. + bool get supportsRestart; + + /// Whether all of the connected devices support gathering SkSL. + bool get supportsWriteSkSL; + + /// Whether all of the connected devices support hot reload. + bool get canHotReload; + + ResidentDevtoolsHandler? get residentDevtoolsHandler; + + @protected + Logger get logger; + + @protected + FileSystem? get fileSystem; + + /// Called to print help to the terminal. + void printHelp({ required bool details }); + + /// Perform a hot reload or hot restart of all attached applications. + /// + /// If [fullRestart] is true, a hot restart is performed. Otherwise a hot reload + /// is run instead. On web devices, this only performs a hot restart regardless of + /// the value of [fullRestart]. + Future restart({ bool fullRestart = false, bool pause = false, String? reason }) { + final String mode = isRunningProfile ? 'profile' :isRunningRelease ? 'release' : 'this'; + throw Exception('${fullRestart ? 'Restart' : 'Reload'} is not supported in $mode mode'); + } + + /// Dump the application's current widget tree to the terminal. + Future debugDumpApp() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + final String data = await device.vmService!.flutterDebugDumpApp( + isolateId: view.uiIsolate!.id!, + ); + logger.printStatus(data); + } + } + return true; + } + + /// Dump the application's current render tree to the terminal. + Future debugDumpRenderTree() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + final String data = await device.vmService!.flutterDebugDumpRenderTree( + isolateId: view.uiIsolate!.id!, + ); + logger.printStatus(data); + } + } + return true; + } + + /// Dump frame rasterization metrics for the last rendered frame. + /// + /// The last frames gets re-painted while recording additional tracing info + /// pertaining to the various draw calls issued by the frame. The timings + /// recorded here are not indicative of production performance. The intended + /// use case is to look at the various layers in proportion to see what + /// contributes the most towards raster performance. + Future debugFrameJankMetrics() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + if (device?.targetPlatform == TargetPlatform.web_javascript) { + logger.printWarning('Unable to get jank metrics for web'); + continue; + } + final List views = await device!.vmService!.getFlutterViews(); + try { + for (final FlutterView view in views) { + final Map? rasterData = + await device.vmService!.renderFrameWithRasterStats( + viewId: view.id, + uiIsolateId: view.uiIsolate!.id, + ); + if (rasterData != null) { + final File tempFile = globals.fsUtils.getUniqueFile( + globals.fs.currentDirectory, + 'flutter_jank_metrics', + 'json', + ); + tempFile.writeAsStringSync(jsonEncode(rasterData), flush: true); + logger.printStatus('Wrote jank metrics to ${tempFile.absolute.path}'); + } else { + logger.printWarning('Unable to get jank metrics.'); + } + } + } on vm_service.RPCError catch (err) { + if (err.code != RPCErrorCodes.kServerError || !err.message.contains('Raster status not supported on Impeller backend')) { + rethrow; + } + logger.printWarning('Unable to get jank metrics for Impeller renderer'); + } + } + return true; + } + + /// Dump the application's current layer tree to the terminal. + Future debugDumpLayerTree() async { + if (!supportsServiceProtocol || !isRunningDebug) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + final String data = await device.vmService!.flutterDebugDumpLayerTree( + isolateId: view.uiIsolate!.id!, + ); + logger.printStatus(data); + } + } + return true; + } + + Future debugDumpFocusTree() async { + if (!supportsServiceProtocol || !isRunningDebug) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + final String data = await device.vmService!.flutterDebugDumpFocusTree( + isolateId: view.uiIsolate!.id!, + ); + logger.printStatus(data); + } + } + return true; + } + + /// Dump the application's current semantics tree to the terminal. + /// + /// If semantics are not enabled, nothing is returned. + Future debugDumpSemanticsTreeInTraversalOrder() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + final String data = await device.vmService!.flutterDebugDumpSemanticsTreeInTraversalOrder( + isolateId: view.uiIsolate!.id!, + ); + logger.printStatus(data); + } + } + return true; + } + + /// Dump the application's current semantics tree to the terminal. + /// + /// If semantics are not enabled, nothing is returned. + Future debugDumpSemanticsTreeInInverseHitTestOrder() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + final String data = await device.vmService!.flutterDebugDumpSemanticsTreeInInverseHitTestOrder( + isolateId: view.uiIsolate!.id!, + ); + logger.printStatus(data); + } + } + return true; + } + + /// Toggle the "paint size" debugging feature. + Future debugToggleDebugPaintSizeEnabled() async { + if (!supportsServiceProtocol || !isRunningDebug) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + await device.vmService!.flutterToggleDebugPaintSizeEnabled( + isolateId: view.uiIsolate!.id!, + ); + } + } + return true; + } + + /// Toggle the performance overlay. + /// + /// This is not supported in web mode. + Future debugTogglePerformanceOverlayOverride() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + if (device!.targetPlatform == TargetPlatform.web_javascript) { + continue; + } + final List views = await device.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + await device.vmService!.flutterTogglePerformanceOverlayOverride( + isolateId: view.uiIsolate!.id!, + ); + } + } + return true; + } + + /// Toggle the widget inspector. + Future debugToggleWidgetInspector() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + await device.vmService!.flutterToggleWidgetInspector( + isolateId: view.uiIsolate!.id!, + ); + } + } + return true; + } + + /// Toggle the "invert images" debugging feature. + Future debugToggleInvertOversizedImages() async { + if (!supportsServiceProtocol || !isRunningDebug) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + await device.vmService!.flutterToggleInvertOversizedImages( + isolateId: view.uiIsolate!.id!, + ); + } + } + return true; + } + + /// Toggle the "profile widget builds" debugging feature. + Future debugToggleProfileWidgetBuilds() async { + if (!supportsServiceProtocol) { + return false; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + await device.vmService!.flutterToggleProfileWidgetBuilds( + isolateId: view.uiIsolate!.id!, + ); + } + } + return true; + } + + /// Toggle the operating system brightness (light or dark). + Future debugToggleBrightness() async { + if (!supportsServiceProtocol) { + return false; + } + final List views = await flutterDevices.first!.vmService!.getFlutterViews(); + final Brightness? current = await flutterDevices.first!.vmService!.flutterBrightnessOverride( + isolateId: views.first.uiIsolate!.id!, + ); + Brightness next; + if (current == Brightness.light) { + next = Brightness.dark; + } else { + next = Brightness.light; + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + await device.vmService!.flutterBrightnessOverride( + isolateId: view.uiIsolate!.id!, + brightness: next, + ); + } + logger.printStatus('Changed brightness to $next.'); + } + return true; + } + + /// Rotate the application through different `defaultTargetPlatform` values. + Future debugTogglePlatform() async { + if (!supportsServiceProtocol || !isRunningDebug) { + return false; + } + final List views = await flutterDevices.first!.vmService!.getFlutterViews(); + final String from = await flutterDevices + .first!.vmService!.flutterPlatformOverride( + isolateId: views.first.uiIsolate!.id!, + ); + final String to = nextPlatform(from); + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + await device.vmService!.flutterPlatformOverride( + platform: to, + isolateId: view.uiIsolate!.id!, + ); + } + } + logger.printStatus('Switched operating system to $to'); + return true; + } + + /// Write the SkSL shaders to a zip file in build directory. + /// + /// Returns the name of the file, or `null` on failures. + Future writeSkSL() async { + if (!supportsWriteSkSL) { + throw Exception('writeSkSL is not supported by this runner.'); + } + final FlutterDevice flutterDevice = flutterDevices.first!; + final FlutterVmService vmService = flutterDevice.vmService!; + final List views = await vmService.getFlutterViews(); + final Map? data = await vmService.getSkSLs( + viewId: views.first.id, + ); + final Device device = flutterDevice.device!; + return sharedSkSlWriter(device, data); + } + + /// Take a screenshot on the provided [device]. + /// + /// If the device has a connected vmservice, this method will attempt to hide + /// and restore the debug banner before taking the screenshot. + /// + /// If the device type does not support a "native" screenshot, then this + /// will fallback to a rasterizer screenshot from the engine. This has the + /// downside of being unable to display the contents of platform views. + /// + /// This method will return without writing the screenshot file if any + /// RPC errors are encountered, printing them to stderr. This is true even + /// if an error occurs after the data has already been received, such as + /// from restoring the debug banner. + Future screenshot(FlutterDevice device) async { + if (!device.device!.supportsScreenshot && !supportsServiceProtocol) { + return; + } + final Status status = logger.startProgress( + 'Taking screenshot for ${device.device!.name}...', + ); + final File outputFile = getUniqueFile( + fileSystem!.currentDirectory, + 'flutter', + 'png', + ); + + try { + bool result; + if (device.device!.supportsScreenshot) { + result = await _toggleDebugBanner(device, () => device.device!.takeScreenshot(outputFile)); + } else { + result = await _takeVmServiceScreenshot(device, outputFile); + } + if (!result) { + return; + } + final int sizeKB = outputFile.lengthSync() ~/ 1024; + status.stop(); + logger.printStatus( + 'Screenshot written to ${fileSystem!.path.relative(outputFile.path)} (${sizeKB}kB).', + ); + } on Exception catch (error) { + status.cancel(); + logger.printError('Error taking screenshot: $error'); + } + } + + Future _takeVmServiceScreenshot(FlutterDevice device, File outputFile) async { + if (device.targetPlatform != TargetPlatform.web_javascript) { + return false; + } + assert(supportsServiceProtocol); + + return _toggleDebugBanner(device, () async { + final vm_service.Response? response = await device.vmService!.callMethodWrapper('ext.dwds.screenshot'); + if (response == null) { + throw Exception('Failed to take screenshot'); + } + final String data = response.json!['data'] as String; + outputFile.writeAsBytesSync(base64.decode(data)); + }); + } + + Future _toggleDebugBanner(FlutterDevice device, Future Function() cb) async { + List views = []; + if (supportsServiceProtocol) { + views = await device.vmService!.getFlutterViews(); + } + + Future setDebugBanner(bool value) async { + try { + for (final FlutterView view in views) { + await device.vmService!.flutterDebugAllowBanner( + value, + isolateId: view.uiIsolate!.id!, + ); + } + return true; + } on vm_service.RPCError catch (error) { + logger.printError('Error communicating with Flutter on the device: $error'); + return false; + } + } + if (!await setDebugBanner(false)) { + return false; + } + bool succeeded = true; + try { + await cb(); + } finally { + if (!await setDebugBanner(true)) { + succeeded = false; + } + } + return succeeded; + } + + + /// Remove sigusr signal handlers. + Future cleanupAfterSignal(); + + /// Tear down the runner and leave the application running. + /// + /// This is not supported on web devices where the runner is running + /// the application server as well. + Future detach(); + + /// Tear down the runner and exit the application. + Future exit(); + + /// Run any source generators, such as localizations. + /// + /// These are automatically run during hot restart, but can be + /// triggered manually to see the updated generated code. + Future runSourceGenerators(); +} + +// Shared code between different resident application runners. +abstract class ResidentRunner extends ResidentHandlers { + ResidentRunner( + this.flutterDevices, { + required this.target, + required this.debuggingOptions, + String? projectRootPath, + this.ipv6, + this.stayResident = true, + this.hotMode = true, + String? dillOutputPath, + this.machine = false, + ResidentDevtoolsHandlerFactory devtoolsHandler = createDefaultHandler, + }) : mainPath = globals.fs.file(target).absolute.path, + packagesFilePath = debuggingOptions.buildInfo.packagesPath, + projectRootPath = projectRootPath ?? globals.fs.currentDirectory.path, + _dillOutputPath = dillOutputPath, + artifactDirectory = dillOutputPath == null + ? globals.fs.systemTempDirectory.createTempSync('flutter_tool.') + : globals.fs.file(dillOutputPath).parent, + assetBundle = AssetBundleFactory.instance.createBundle(), + commandHelp = CommandHelp( + logger: globals.logger, + terminal: globals.terminal, + platform: globals.platform, + outputPreferences: globals.outputPreferences, + ) { + if (!artifactDirectory.existsSync()) { + artifactDirectory.createSync(recursive: true); + } + _residentDevtoolsHandler = devtoolsHandler(DevtoolsLauncher.instance, this, globals.logger); + } + + @override + Logger get logger => globals.logger; + + @override + FileSystem get fileSystem => globals.fs; + + @override + final List flutterDevices; + + final String target; + final DebuggingOptions debuggingOptions; + + @override + final bool stayResident; + final bool? ipv6; + final String? _dillOutputPath; + /// The parent location of the incremental artifacts. + final Directory artifactDirectory; + final String packagesFilePath; + final String projectRootPath; + final String mainPath; + final AssetBundle assetBundle; + + final CommandHelp commandHelp; + final bool machine; + + @override + ResidentDevtoolsHandler? get residentDevtoolsHandler => _residentDevtoolsHandler; + ResidentDevtoolsHandler? _residentDevtoolsHandler; + + bool _exited = false; + Completer _finished = Completer(); + BuildResult? _lastBuild; + Environment? _environment; + + @override + bool hotMode; + + /// Returns true if every device is streaming vmService URIs. + bool get isWaitingForVmService { + return flutterDevices.every((FlutterDevice? device) { + return device!.isWaitingForVmService; + }); + } + + String get dillOutputPath => _dillOutputPath ?? globals.fs.path.join(artifactDirectory.path, 'app.dill'); + String getReloadPath({ + bool fullRestart = false, + required bool swap, + }) { + if (!fullRestart) { + return 'main.dart.incremental.dill'; + } + return 'main.dart${swap ? '.swap' : ''}.dill'; + } + + bool get debuggingEnabled => debuggingOptions.debuggingEnabled; + + @override + bool get isRunningDebug => debuggingOptions.buildInfo.isDebug; + + @override + bool get isRunningProfile => debuggingOptions.buildInfo.isProfile; + + @override + bool get isRunningRelease => debuggingOptions.buildInfo.isRelease; + + @override + bool get supportsServiceProtocol => isRunningDebug || isRunningProfile; + + @override + bool get supportsWriteSkSL => supportsServiceProtocol; + + bool get trackWidgetCreation => debuggingOptions.buildInfo.trackWidgetCreation; + + /// True if the shared Dart plugin registry (which is different than the one + /// used for web) should be generated during source generation. + bool get generateDartPluginRegistry => true; + + // Returns the Uri of the first connected device for mobile, + // and only connected device for web. + // + // Would be null if there is no device connected or + // there is no devFS associated with the first device. + Uri? get uri => flutterDevices.first.devFS?.baseUri; + + /// Returns [true] if the resident runner exited after invoking [exit()]. + bool get exited => _exited; + + @override + bool get supportsRestart { + return isRunningDebug && flutterDevices.every((FlutterDevice? device) { + return device!.device!.supportsHotRestart; + }); + } + + @override + bool get canHotReload => hotMode; + + /// Start the app and keep the process running during its lifetime. + /// + /// Returns the exit code that we should use for the flutter tool process; 0 + /// for success, 1 for user error (e.g. bad arguments), 2 for other failures. + Future run({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool enableDevTools = false, + String? route, + }); + + /// Connect to a flutter application. + /// + /// [needsFullRestart] defaults to `true`, and controls if the frontend server should + /// compile a full dill. This should be set to `false` if this is called in [ResidentRunner.run], since that method already performs an initial compilation. + Future attach({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool allowExistingDdsInstance = false, + bool enableDevTools = false, + bool needsFullRestart = true, + }); + + @override + Future runSourceGenerators() async { + _environment ??= Environment( + artifacts: globals.artifacts!, + logger: globals.logger, + cacheDir: globals.cache.getRoot(), + engineVersion: globals.flutterVersion.engineRevision, + fileSystem: globals.fs, + flutterRootDir: globals.fs.directory(Cache.flutterRoot), + outputDir: globals.fs.directory(getBuildDirectory()), + processManager: globals.processManager, + platform: globals.platform, + usage: globals.flutterUsage, + analytics: globals.analytics, + projectDir: globals.fs.currentDirectory, + generateDartPluginRegistry: generateDartPluginRegistry, + defines: { + // Needed for Dart plugin registry generation. + kTargetFile: mainPath, + }, + ); + + final CompositeTarget compositeTarget = CompositeTarget([ + const GenerateLocalizationsTarget(), + const DartPluginRegistrantTarget(), + ]); + + _lastBuild = await globals.buildSystem.buildIncremental( + compositeTarget, + _environment!, + _lastBuild, + ); + if (!_lastBuild!.success) { + for (final ExceptionMeasurement exceptionMeasurement in _lastBuild!.exceptions.values) { + globals.printError( + exceptionMeasurement.exception.toString(), + stackTrace: globals.logger.isVerbose + ? exceptionMeasurement.stackTrace + : null, + ); + } + } + globals.printTrace('complete'); + } + + @protected + void writeVmServiceFile() { + if (debuggingOptions.vmserviceOutFile != null) { + try { + final String address = flutterDevices.first.vmService!.wsAddress.toString(); + final File vmserviceOutFile = globals.fs.file(debuggingOptions.vmserviceOutFile); + vmserviceOutFile.createSync(recursive: true); + vmserviceOutFile.writeAsStringSync(address); + } on FileSystemException { + globals.printError('Failed to write vmservice-out-file at ${debuggingOptions.vmserviceOutFile}'); + } + } + } + + @override + Future exit() async { + _exited = true; + await residentDevtoolsHandler!.shutdown(); + await stopEchoingDeviceLog(); + await preExit(); + await exitApp(); // calls appFinished + await shutdownDartDevelopmentService(); + } + + @override + Future detach() async { + await residentDevtoolsHandler!.shutdown(); + await stopEchoingDeviceLog(); + await preExit(); + await shutdownDartDevelopmentService(); + appFinished(); + } + + Future stopEchoingDeviceLog() async { + await Future.wait( + flutterDevices.map>((FlutterDevice? device) => device!.stopEchoingDeviceLog()) + ); + } + + Future shutdownDartDevelopmentService() async { + await Future.wait( + flutterDevices.map>( + (FlutterDevice? device) => device?.device?.dds.shutdown() ?? Future.value() + ) + ); + } + + @protected + void cacheInitialDillCompilation() { + if (_dillOutputPath != null) { + return; + } + globals.printTrace('Caching compiled dill'); + final File outputDill = globals.fs.file(dillOutputPath); + if (outputDill.existsSync()) { + final String copyPath = getDefaultCachedKernelPath( + trackWidgetCreation: trackWidgetCreation, + dartDefines: debuggingOptions.buildInfo.dartDefines, + extraFrontEndOptions: debuggingOptions.buildInfo.extraFrontEndOptions, + ); + globals.fs + .file(copyPath) + .parent + .createSync(recursive: true); + outputDill.copySync(copyPath); + } + } + + void printStructuredErrorLog(vm_service.Event event) { + if (event.extensionKind == 'Flutter.Error' && !machine) { + final Map? json = event.extensionData?.data; + if (json != null && json.containsKey('renderedErrorText')) { + final int errorsSinceReload; + if (json.containsKey('errorsSinceReload') && json['errorsSinceReload'] is int) { + errorsSinceReload = json['errorsSinceReload']! as int; + } else { + errorsSinceReload = 0; + } + if (errorsSinceReload == 0) { + // We print a blank line around the first error, to more clearly emphasize it + // in the output. (Other errors don't get this.) + globals.printStatus(''); + } + globals.printStatus('${json['renderedErrorText']}'); + if (errorsSinceReload == 0) { + globals.printStatus(''); + } + } else { + globals.printError('Received an invalid ${globals.logger.terminal.bolden("Flutter.Error")} message from app: $json'); + } + } + } + + /// If the [reloadSources] parameter is not null the 'reloadSources' service + /// will be registered. + // + // Failures should be indicated by completing the future with an error, using + // a string as the error object, which will be used by the caller (attach()) + // to display an error message. + Future connectToServiceProtocol({ + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + required bool allowExistingDdsInstance, + }) async { + if (!debuggingOptions.debuggingEnabled) { + throw Exception('The service protocol is not enabled.'); + } + _finished = Completer(); + // Listen for service protocol connection to close. + for (final FlutterDevice? device in flutterDevices) { + await device!.connect( + reloadSources: reloadSources, + restart: restart, + compileExpression: compileExpression, + enableDds: debuggingOptions.enableDds, + ddsPort: debuggingOptions.ddsPort, + allowExistingDdsInstance: allowExistingDdsInstance, + hostVmServicePort: debuggingOptions.hostVmServicePort, + getSkSLMethod: getSkSLMethod, + printStructuredErrorLogMethod: printStructuredErrorLog, + ipv6: ipv6 ?? false, + disableServiceAuthCodes: debuggingOptions.disableServiceAuthCodes, + cacheStartupProfile: debuggingOptions.cacheStartupProfile, + ); + await device.vmService!.getFlutterViews(); + + // This hooks up callbacks for when the connection stops in the future. + // We don't want to wait for them. We don't handle errors in those callbacks' + // futures either because they just print to logger and is not critical. + unawaited(device.vmService!.service.onDone.then( + _serviceProtocolDone, + onError: _serviceProtocolError, + ).whenComplete(_serviceDisconnected)); + } + } + + Future _serviceProtocolDone(dynamic object) async { + globals.printTrace('Service protocol connection closed.'); + } + + Future _serviceProtocolError(Object error, StackTrace stack) { + globals.printTrace('Service protocol connection closed with an error: $error\n$stack'); + return Future.error(error, stack); + } + + void _serviceDisconnected() { + if (_exited) { + // User requested the application exit. + return; + } + if (_finished.isCompleted) { + return; + } + globals.printStatus('Lost connection to device.'); + _finished.complete(0); + } + + Future enableObservatory() async { + assert(debuggingOptions.serveObservatory); + final List> serveObservatoryRequests = >[]; + for (final FlutterDevice? device in flutterDevices) { + if (device == null) { + continue; + } + // Notify the VM service if the user wants Observatory to be served. + serveObservatoryRequests.add( + device.vmService?.callMethodWrapper('_serveObservatory') ?? + Future.value(), + ); + } + try { + await Future.wait(serveObservatoryRequests); + } on vm_service.RPCError catch (e) { + globals.printWarning('Unable to enable Observatory: $e'); + } + } + + void appFinished() { + if (_finished.isCompleted) { + return; + } + globals.printStatus('Application finished.'); + _finished.complete(0); + } + + void appFailedToStart() { + if (!_finished.isCompleted) { + _finished.complete(1); + } + } + + Future waitForAppToFinish() async { + final int exitCode = await _finished.future; + await cleanupAtFinish(); + return exitCode; + } + + @mustCallSuper + Future preExit() async { + // If _dillOutputPath is null, the tool created a temporary directory for + // the dill. + if (_dillOutputPath == null && artifactDirectory.existsSync()) { + artifactDirectory.deleteSync(recursive: true); + } + } + + Future exitApp() async { + final List> futures = >[ + for (final FlutterDevice? device in flutterDevices) device!.exitApps(), + ]; + await Future.wait(futures); + appFinished(); + } + + bool get reportedDebuggers => _reportedDebuggers; + bool _reportedDebuggers = false; + + void printDebuggerList({ bool includeVmService = true, bool includeDevtools = true }) { + final DevToolsServerAddress? devToolsServerAddress = residentDevtoolsHandler!.activeDevToolsServer; + if (!residentDevtoolsHandler!.readyToAnnounce) { + includeDevtools = false; + } + assert(!includeDevtools || devToolsServerAddress != null); + for (final FlutterDevice? device in flutterDevices) { + if (device!.vmService == null) { + continue; + } + if (includeVmService) { + // Caution: This log line is parsed by device lab tests. + globals.printStatus( + 'A Dart VM Service on ${device.device!.name} is available at: ' + '${device.vmService!.httpAddress}', + ); + } + if (includeDevtools) { + final Uri? uri = devToolsServerAddress!.uri?.replace( + queryParameters: {'uri': '${device.vmService!.httpAddress}'}, + ); + if (uri != null) { + globals.printStatus( + 'The Flutter DevTools debugger and profiler ' + 'on ${device.device!.name} is available at: ${urlToDisplayString(uri)}', + ); + } + } + } + _reportedDebuggers = true; + } + + void printHelpDetails() { + commandHelp.v.print(); + if (flutterDevices.any((FlutterDevice? d) => d!.device!.supportsScreenshot)) { + commandHelp.s.print(); + } + if (supportsServiceProtocol) { + commandHelp.w.print(); + commandHelp.t.print(); + if (isRunningDebug) { + commandHelp.L.print(); + commandHelp.f.print(); + commandHelp.S.print(); + commandHelp.U.print(); + commandHelp.i.print(); + commandHelp.p.print(); + commandHelp.I.print(); + commandHelp.o.print(); + commandHelp.b.print(); + } else { + commandHelp.S.print(); + commandHelp.U.print(); + } + // Performance related features: `P` should precede `a`, which should precede `M`. + commandHelp.P.print(); + commandHelp.a.print(); + if (supportsWriteSkSL) { + commandHelp.M.print(); + } + if (isRunningDebug) { + commandHelp.g.print(); + } + commandHelp.j.print(); + } + } + + @override + Future cleanupAfterSignal(); + + /// Called right before we exit. + Future cleanupAtFinish(); +} + +class OperationResult { + OperationResult(this.code, this.message, { this.fatal = false, this.updateFSReport, this.extraTimings = const [] }); + + /// The result of the operation; a non-zero code indicates a failure. + final int code; + + /// A user facing message about the results of the operation. + final String message; + + /// User facing extra timing information about the operation. + final List extraTimings; + + /// Whether this error should cause the runner to exit. + final bool fatal; + + final UpdateFSReport? updateFSReport; + + bool get isOk => code == 0; + + static final OperationResult ok = OperationResult(0, ''); +} + +class OperationResultExtraTiming { + const OperationResultExtraTiming(this.description, this.timeInMs); + + /// A user facing short description of this timing. + final String description; + + /// The time this operation took in milliseconds. + final int timeInMs; +} + +Future getMissingPackageHintForPlatform(TargetPlatform platform) async { + switch (platform) { + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + final FlutterProject project = FlutterProject.current(); + final String manifestPath = globals.fs.path.relative(project.android.appManifestFile.path); + return 'Is your project missing an $manifestPath?\nConsider running "flutter create ." to create one.'; + case TargetPlatform.ios: + return 'Is your project missing an ios/Runner/Info.plist?\nConsider running "flutter create ." to create one.'; + case TargetPlatform.android: + case TargetPlatform.darwin: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.linux_arm64: + case TargetPlatform.linux_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case TargetPlatform.windows_x64: + return null; + } +} + +/// Redirects terminal commands to the correct resident runner methods. +class TerminalHandler { + TerminalHandler(this.residentRunner, { + required Logger logger, + required Terminal terminal, + required Signals signals, + required io.ProcessInfo processInfo, + required bool reportReady, + String? pidFile, + }) : _logger = logger, + _terminal = terminal, + _signals = signals, + _processInfo = processInfo, + _reportReady = reportReady, + _pidFile = pidFile; + + final Logger _logger; + final Terminal _terminal; + final Signals _signals; + final io.ProcessInfo _processInfo; + final bool _reportReady; + final String? _pidFile; + + final ResidentHandlers residentRunner; + bool _processingUserRequest = false; + StreamSubscription? subscription; + File? _actualPidFile; + + @visibleForTesting + String? lastReceivedCommand; + + /// This is only a buffer logger in unit tests + @visibleForTesting + BufferLogger get logger => _logger as BufferLogger; + + void setupTerminal() { + if (!_logger.quiet) { + _logger.printStatus(''); + residentRunner.printHelp(details: false); + } + _terminal.singleCharMode = true; + subscription = _terminal.keystrokes.listen(processTerminalInput); + } + + final Map _signalTokens = {}; + + void _addSignalHandler(io.ProcessSignal signal, SignalHandler handler) { + _signalTokens[signal] = _signals.addHandler(signal, handler); + } + + void registerSignalHandlers() { + assert(residentRunner.stayResident); + _addSignalHandler(io.ProcessSignal.sigint, _cleanUp); + _addSignalHandler(io.ProcessSignal.sigterm, _cleanUp); + if (residentRunner.supportsServiceProtocol && residentRunner.supportsRestart) { + _addSignalHandler(io.ProcessSignal.sigusr1, _handleSignal); + _addSignalHandler(io.ProcessSignal.sigusr2, _handleSignal); + if (_pidFile != null) { + _logger.printTrace('Writing pid to: $_pidFile'); + _actualPidFile = _processInfo.writePidFile(_pidFile); + } + } + } + + /// Unregisters terminal signal and keystroke handlers. + void stop() { + assert(residentRunner.stayResident); + if (_actualPidFile != null) { + try { + _logger.printTrace('Deleting pid file (${_actualPidFile!.path}).'); + _actualPidFile!.deleteSync(); + } on FileSystemException catch (error) { + _logger.printWarning('Failed to delete pid file (${_actualPidFile!.path}): ${error.message}'); + } + _actualPidFile = null; + } + for (final MapEntry entry in _signalTokens.entries) { + _signals.removeHandler(entry.key, entry.value); + } + _signalTokens.clear(); + subscription?.cancel(); + } + + /// Returns [true] if the input has been handled by this function. + Future _commonTerminalInputHandler(String character) async { + _logger.printStatus(''); // the key the user tapped might be on this line + switch (character) { + case 'a': + return residentRunner.debugToggleProfileWidgetBuilds(); + case 'b': + return residentRunner.debugToggleBrightness(); + case 'c': + _logger.clear(); + return true; + case 'd': + case 'D': + await residentRunner.detach(); + return true; + case 'f': + return residentRunner.debugDumpFocusTree(); + case 'g': + await residentRunner.runSourceGenerators(); + return true; + case 'h': + case 'H': + case '?': + // help + residentRunner.printHelp(details: true); + return true; + case 'i': + return residentRunner.debugToggleWidgetInspector(); + case 'I': + return residentRunner.debugToggleInvertOversizedImages(); + case 'j': + case 'J': + return residentRunner.debugFrameJankMetrics(); + case 'L': + return residentRunner.debugDumpLayerTree(); + case 'o': + case 'O': + return residentRunner.debugTogglePlatform(); + case 'M': + if (residentRunner.supportsWriteSkSL) { + await residentRunner.writeSkSL(); + return true; + } + return false; + case 'p': + return residentRunner.debugToggleDebugPaintSizeEnabled(); + case 'P': + return residentRunner.debugTogglePerformanceOverlayOverride(); + case 'q': + case 'Q': + // exit + await residentRunner.exit(); + return true; + case 'r': + if (!residentRunner.canHotReload) { + return false; + } + final OperationResult result = await residentRunner.restart(); + if (result.fatal) { + throwToolExit(result.message); + } + if (!result.isOk) { + _logger.printStatus('Try again after fixing the above error(s).', emphasis: true); + } + return true; + case 'R': + // If hot restart is not supported for all devices, ignore the command. + if (!residentRunner.supportsRestart || !residentRunner.hotMode) { + return false; + } + final OperationResult result = await residentRunner.restart(fullRestart: true); + if (result.fatal) { + throwToolExit(result.message); + } + if (!result.isOk) { + _logger.printStatus('Try again after fixing the above error(s).', emphasis: true); + } + return true; + case 's': + for (final FlutterDevice? device in residentRunner.flutterDevices) { + await residentRunner.screenshot(device!); + } + return true; + case 'S': + return residentRunner.debugDumpSemanticsTreeInTraversalOrder(); + case 't': + case 'T': + return residentRunner.debugDumpRenderTree(); + case 'U': + return residentRunner.debugDumpSemanticsTreeInInverseHitTestOrder(); + case 'v': + case 'V': + return residentRunner.residentDevtoolsHandler!.launchDevToolsInBrowser(flutterDevices: residentRunner.flutterDevices); + case 'w': + case 'W': + return residentRunner.debugDumpApp(); + } + return false; + } + + Future processTerminalInput(String command) async { + // When terminal doesn't support line mode, '\n' can sneak into the input. + command = command.trim(); + if (_processingUserRequest) { + _logger.printTrace('Ignoring terminal input: "$command" because we are busy.'); + return; + } + _processingUserRequest = true; + try { + lastReceivedCommand = command; + await _commonTerminalInputHandler(command); + // Catch all exception since this is doing cleanup and rethrowing. + } catch (error, st) { // ignore: avoid_catches_without_on_clauses + // Don't print stack traces for known error types. + if (error is! ToolExit) { + _logger.printError('$error\n$st'); + } + await _cleanUp(null); + rethrow; + } finally { + _processingUserRequest = false; + if (_reportReady) { + _logger.printStatus('ready'); + } + } + } + + Future _handleSignal(io.ProcessSignal signal) async { + if (_processingUserRequest) { + _logger.printTrace('Ignoring signal: "$signal" because we are busy.'); + return; + } + _processingUserRequest = true; + + final bool fullRestart = signal == io.ProcessSignal.sigusr2; + + try { + await residentRunner.restart(fullRestart: fullRestart); + } finally { + _processingUserRequest = false; + } + } + + Future _cleanUp(io.ProcessSignal? signal) async { + _terminal.singleCharMode = false; + await subscription?.cancel(); + await residentRunner.cleanupAfterSignal(); + } +} + +class DebugConnectionInfo { + DebugConnectionInfo({ this.httpUri, this.wsUri, this.baseUri }); + + final Uri? httpUri; + final Uri? wsUri; + final String? baseUri; +} + +/// Returns the next platform value for the switcher. +/// +/// These values must match what is available in +/// `packages/flutter/lib/src/foundation/binding.dart`. +String nextPlatform(String currentPlatform) { + const List platforms = [ + 'android', + 'iOS', + 'windows', + 'macOS', + 'linux', + 'fuchsia', + ]; + final int index = platforms.indexOf(currentPlatform); + assert(index >= 0, 'unknown platform "$currentPlatform"'); + return platforms[(index + 1) % platforms.length]; +} + +/// A launcher for the devtools debugger and analysis tool. +abstract class DevtoolsLauncher { + static DevtoolsLauncher? get instance => context.get(); + + /// Serve Dart DevTools and return the host and port they are available on. + /// + /// This method must return a future that is guaranteed not to fail, because it + /// will be used in unawaited contexts. It may, however, return null. + Future serve(); + + /// Launch a Dart DevTools process, optionally targeting a specific VM Service + /// URI if [vmServiceUri] is non-null. + /// + /// [additionalArguments] may be optionally specified and are passed directly + /// to the devtools run command. + /// + /// This method must return a future that is guaranteed not to fail, because it + /// will be used in unawaited contexts. + Future launch(Uri vmServiceUri, {List? additionalArguments}); + + Future close(); + + /// When measuring devtools memory via additional arguments, the launch process + /// will technically never complete. + /// + /// Us this as an indicator that the process has started. + Future? processStart; + + /// Returns a future that completes when the DevTools server is ready. + /// + /// Completes when [devToolsUrl] is set. That can be set either directly, or + /// by calling [serve]. + Future get ready => _readyCompleter.future; + Completer _readyCompleter = Completer(); + + Uri? get devToolsUrl => _devToolsUrl; + Uri? _devToolsUrl; + set devToolsUrl(Uri? value) { + assert((_devToolsUrl == null) != (value == null)); + _devToolsUrl = value; + if (_devToolsUrl != null) { + _readyCompleter.complete(); + } else { + _readyCompleter = Completer(); + } + } + + /// The URL of the current DevTools server. + /// + /// Returns null if [ready] is not complete. + DevToolsServerAddress? get activeDevToolsServer { + if (_devToolsUrl == null) { + return null; + } + return DevToolsServerAddress(devToolsUrl!.host, devToolsUrl!.port); + } +} + +class DevToolsServerAddress { + DevToolsServerAddress(this.host, this.port); + + final String host; + final int port; + + Uri? get uri { + return Uri(scheme: 'http', host: host, port: port); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/run_cold.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/run_cold.dart new file mode 100644 index 0000000000000000000000000000000000000000..cbd83bed033c1d3e36ec4c314e0223d4ca451d71 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/run_cold.dart @@ -0,0 +1,239 @@ +// 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 'base/file_system.dart'; +import 'base/logger.dart'; +import 'build_info.dart'; +import 'globals.dart' as globals; +import 'resident_runner.dart'; +import 'tracing.dart'; +import 'vmservice.dart'; + +const String kFlutterTestOutputsDirEnvName = 'FLUTTER_TEST_OUTPUTS_DIR'; +class ColdRunner extends ResidentRunner { + ColdRunner( + super.flutterDevices, { + required super.target, + required super.debuggingOptions, + this.traceStartup = false, + this.awaitFirstFrameWhenTracing = true, + this.applicationBinary, + this.multidexEnabled = false, + bool super.ipv6 = false, + super.stayResident, + super.machine, + super.devtoolsHandler, + }) : super( + hotMode: false, + ); + + final bool traceStartup; + final bool awaitFirstFrameWhenTracing; + final File? applicationBinary; + final bool multidexEnabled; + bool _didAttach = false; + + @override + bool get canHotReload => false; + + @override + Logger get logger => globals.logger; + + @override + FileSystem get fileSystem => globals.fs; + + @override + Future run({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool enableDevTools = false, + String? route, + }) async { + try { + for (final FlutterDevice? device in flutterDevices) { + final int result = await device!.runCold( + coldRunner: this, + route: route, + ); + if (result != 0) { + appFailedToStart(); + return result; + } + } + } on Exception catch (err, stack) { + globals.printError('$err\n$stack'); + appFailedToStart(); + return 1; + } + + // Connect to the VM Service. + if (debuggingEnabled) { + try { + await connectToServiceProtocol(allowExistingDdsInstance: false); + } on Exception catch (exception) { + globals.printError(exception.toString()); + appFailedToStart(); + return 2; + } + } + + if (debuggingEnabled) { + if (enableDevTools) { + // The method below is guaranteed never to return a failing future. + unawaited(residentDevtoolsHandler!.serveAndAnnounceDevTools( + devToolsServerAddress: debuggingOptions.devToolsServerAddress, + flutterDevices: flutterDevices, + isStartPaused: debuggingOptions.startPaused, + )); + } + if (debuggingOptions.serveObservatory) { + await enableObservatory(); + } + } + + if (flutterDevices.first.vmServiceUris != null) { + // For now, only support one debugger connection. + connectionInfoCompleter?.complete(DebugConnectionInfo( + httpUri: flutterDevices.first.vmService!.httpAddress, + wsUri: flutterDevices.first.vmService!.wsAddress, + )); + } + + globals.printTrace('Application running.'); + + for (final FlutterDevice? device in flutterDevices) { + if (device!.vmService == null) { + continue; + } + await device.initLogReader(); + globals.printTrace('Connected to ${device.device!.name}'); + } + + if (traceStartup) { + // Only trace startup for the first device. + final FlutterDevice device = flutterDevices.first; + if (device.vmService != null) { + globals.printStatus('Tracing startup on ${device.device!.name}.'); + final String outputPath = globals.platform.environment[kFlutterTestOutputsDirEnvName] ?? getBuildDirectory(); + await downloadStartupTrace( + device.vmService!, + awaitFirstFrame: awaitFirstFrameWhenTracing, + logger: globals.logger, + output: globals.fs.directory(outputPath), + ); + } + appFinished(); + } + + appStartedCompleter?.complete(); + + writeVmServiceFile(); + + if (stayResident && !traceStartup) { + return waitForAppToFinish(); + } + await cleanupAtFinish(); + return 0; + } + + @override + Future attach({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool allowExistingDdsInstance = false, + bool enableDevTools = false, + bool needsFullRestart = true, + }) async { + _didAttach = true; + try { + await connectToServiceProtocol( + getSkSLMethod: writeSkSL, + allowExistingDdsInstance: allowExistingDdsInstance, + ); + } on Exception catch (error) { + globals.printError('Error connecting to the service protocol: $error'); + return 2; + } + + for (final FlutterDevice? device in flutterDevices) { + await device!.initLogReader(); + } + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + globals.printTrace('Connected to $view.'); + } + } + + if (debuggingEnabled) { + if (enableDevTools) { + // The method below is guaranteed never to return a failing future. + unawaited(residentDevtoolsHandler!.serveAndAnnounceDevTools( + devToolsServerAddress: debuggingOptions.devToolsServerAddress, + flutterDevices: flutterDevices, + isStartPaused: debuggingOptions.startPaused, + )); + } + if (debuggingOptions.serveObservatory) { + await enableObservatory(); + } + } + + appStartedCompleter?.complete(); + if (stayResident) { + return waitForAppToFinish(); + } + await cleanupAtFinish(); + return 0; + } + + @override + Future cleanupAfterSignal() async { + await stopEchoingDeviceLog(); + if (_didAttach) { + appFinished(); + } + await exitApp(); + } + + @override + Future cleanupAtFinish() async { + for (final FlutterDevice? flutterDevice in flutterDevices) { + await flutterDevice!.device!.dispose(); + } + + await residentDevtoolsHandler!.shutdown(); + await stopEchoingDeviceLog(); + } + + @override + void printHelp({ required bool details }) { + globals.printStatus('Flutter run key commands.'); + if (details) { + printHelpDetails(); + commandHelp.hWithDetails.print(); + } else { + commandHelp.hWithoutDetails.print(); + } + if (_didAttach) { + commandHelp.d.print(); + } + commandHelp.c.print(); + commandHelp.q.print(); + printDebuggerList(); + } + + @override + Future preExit() async { + for (final FlutterDevice? device in flutterDevices) { + // If we're running in release mode, stop the app using the device logic. + if (device!.vmService == null) { + await device.device!.stopApp(device.package, userIdentifier: device.userIdentifier); + } + } + await super.preExit(); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/run_hot.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/run_hot.dart new file mode 100644 index 0000000000000000000000000000000000000000..740b18961e75e2cbf6b351a876d6f5daab01bfe3 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/run_hot.dart @@ -0,0 +1,1727 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:meta/meta.dart'; +import 'package:package_config/package_config.dart'; +import 'package:pool/pool.dart'; +import 'package:unified_analytics/unified_analytics.dart'; +import 'package:vm_service/vm_service.dart' as vm_service; + +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/platform.dart'; +import 'base/utils.dart'; +import 'build_info.dart'; +import 'compile.dart'; +import 'convert.dart'; +import 'dart/package_map.dart'; +import 'devfs.dart'; +import 'device.dart'; +import 'globals.dart' as globals; +import 'native_assets.dart'; +import 'project.dart'; +import 'reporting/reporting.dart'; +import 'resident_runner.dart'; +import 'vmservice.dart'; + +ProjectFileInvalidator get projectFileInvalidator => context.get() ?? ProjectFileInvalidator( + fileSystem: globals.fs, + platform: globals.platform, + logger: globals.logger, +); + +HotRunnerConfig? get hotRunnerConfig => context.get(); + +class HotRunnerConfig { + /// Should the hot runner assume that the minimal Dart dependencies do not change? + bool stableDartDependencies = false; + + /// Whether the hot runner should scan for modified files asynchronously. + bool asyncScanning = false; + + /// A hook for implementations to perform any necessary initialization prior + /// to a hot restart. Should return true if the hot restart should continue. + Future setupHotRestart() async { + return true; + } + + /// A hook for implementations to perform any necessary initialization prior + /// to a hot reload. Should return true if the hot restart should continue. + Future setupHotReload() async { + return true; + } + + /// A hook for implementations to perform any necessary cleanup after the + /// devfs sync is complete. At this point the flutter_tools no longer needs to + /// access the source files and assets. + void updateDevFSComplete() {} + + /// A hook for implementations to perform any necessary operations right + /// before the runner is about to be shut down. + Future runPreShutdownOperations() async { + return; + } +} + +const bool kHotReloadDefault = true; + +class DeviceReloadReport { + DeviceReloadReport(this.device, this.reports); + + FlutterDevice? device; + List reports; // List has one report per Flutter view. +} + +class HotRunner extends ResidentRunner { + HotRunner( + super.flutterDevices, { + required super.target, + required super.debuggingOptions, + this.benchmarkMode = false, + this.applicationBinary, + this.hostIsIde = false, + super.projectRootPath, + super.dillOutputPath, + super.stayResident, + bool super.ipv6 = false, + super.machine, + this.multidexEnabled = false, + super.devtoolsHandler, + StopwatchFactory stopwatchFactory = const StopwatchFactory(), + ReloadSourcesHelper reloadSourcesHelper = defaultReloadSourcesHelper, + ReassembleHelper reassembleHelper = _defaultReassembleHelper, + NativeAssetsBuildRunner? buildRunner, + required Analytics analytics, + }) : _stopwatchFactory = stopwatchFactory, + _reloadSourcesHelper = reloadSourcesHelper, + _reassembleHelper = reassembleHelper, + _buildRunner = buildRunner, + _analytics = analytics, + super( + hotMode: true, + ); + + final StopwatchFactory _stopwatchFactory; + final ReloadSourcesHelper _reloadSourcesHelper; + final ReassembleHelper _reassembleHelper; + final Analytics _analytics; + + final bool benchmarkMode; + final File? applicationBinary; + final bool hostIsIde; + final bool multidexEnabled; + + /// When performing a hot restart, the tool needs to upload a new main.dart.dill to + /// each attached device's devfs. Replacing the existing file is not safe and does + /// not work at all on the windows embedder, because the old dill file will still be + /// memory-mapped by the embedder. To work around this issue, the tool will alternate + /// names for the uploaded dill, sometimes inserting `.swap`. Since the active dill will + /// never be replaced, there is no risk of writing the file while the embedder is attempting + /// to read from it. This also avoids filling up the devfs, if a incrementing counter was + /// used instead. + /// + /// This is only used for hot restart, incremental dills uploaded as part of the hot + /// reload process do not have this issue. + bool _swap = false; + + /// Whether the resident runner has correctly attached to the running application. + bool _didAttach = false; + + final Map> benchmarkData = >{}; + + DateTime? firstBuildTime; + + String? _targetPlatform; + String? _sdkName; + bool? _emulator; + + NativeAssetsBuildRunner? _buildRunner; + + String? flavor; + + Future _calculateTargetPlatform() async { + if (_targetPlatform != null) { + return; + } + + if (flutterDevices.length == 1) { + final Device device = flutterDevices.first.device!; + _targetPlatform = getNameForTargetPlatform(await device.targetPlatform); + _sdkName = await device.sdkNameAndVersion; + _emulator = await device.isLocalEmulator; + } else if (flutterDevices.length > 1) { + _targetPlatform = 'multiple'; + _sdkName = 'multiple'; + _emulator = false; + } else { + _targetPlatform = 'unknown'; + _sdkName = 'unknown'; + _emulator = false; + } + } + + void _addBenchmarkData(String name, int value) { + benchmarkData[name] ??= []; + benchmarkData[name]!.add(value); + } + + Future _reloadSourcesService( + String isolateId, { + bool force = false, + bool pause = false, + }) async { + final OperationResult result = await restart(pause: pause); + if (!result.isOk) { + throw vm_service.RPCError( + 'Unable to reload sources', + RPCErrorCodes.kInternalError, + '', + ); + } + } + + Future _restartService({ bool pause = false }) async { + final OperationResult result = + await restart(fullRestart: true, pause: pause); + if (!result.isOk) { + throw vm_service.RPCError( + 'Unable to restart', + RPCErrorCodes.kInternalError, + '', + ); + } + } + + Future _compileExpressionService( + String isolateId, + String expression, + List definitions, + List definitionTypes, + List typeDefinitions, + List typeBounds, + List typeDefaults, + String libraryUri, + String? klass, + String? method, + bool isStatic, + ) async { + for (final FlutterDevice? device in flutterDevices) { + if (device!.generator != null) { + final CompilerOutput? compilerOutput = + await device.generator!.compileExpression(expression, definitions, + definitionTypes, typeDefinitions, typeBounds, typeDefaults, + libraryUri, klass, method, isStatic); + if (compilerOutput != null && compilerOutput.expressionData != null) { + return base64.encode(compilerOutput.expressionData!); + } + } + } + throw Exception('Failed to compile $expression'); + } + + // Returns the exit code of the flutter tool process, like [run]. + @override + Future attach({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool allowExistingDdsInstance = false, + bool enableDevTools = false, + bool needsFullRestart = true, + }) async { + _didAttach = true; + try { + await connectToServiceProtocol( + reloadSources: _reloadSourcesService, + restart: _restartService, + compileExpression: _compileExpressionService, + getSkSLMethod: writeSkSL, + allowExistingDdsInstance: allowExistingDdsInstance, + ); + // Catches all exceptions, non-Exception objects are rethrown. + } catch (error) { // ignore: avoid_catches_without_on_clauses + if (error is! Exception && error is! String) { + rethrow; + } + globals.printError('Error connecting to the service protocol: $error'); + return 2; + } + + if (debuggingOptions.serveObservatory) { + await enableObservatory(); + } + + if (enableDevTools) { + // The method below is guaranteed never to return a failing future. + unawaited(residentDevtoolsHandler!.serveAndAnnounceDevTools( + devToolsServerAddress: debuggingOptions.devToolsServerAddress, + flutterDevices: flutterDevices, + isStartPaused: debuggingOptions.startPaused, + )); + } + + for (final FlutterDevice? device in flutterDevices) { + await device!.initLogReader(); + device + .developmentShaderCompiler + .configureCompiler( + device.targetPlatform, + impellerStatus: debuggingOptions.enableImpeller, + ); + } + try { + final List baseUris = await _initDevFS(); + if (connectionInfoCompleter != null) { + // Only handle one debugger connection. + connectionInfoCompleter.complete( + DebugConnectionInfo( + httpUri: flutterDevices.first.vmService!.httpAddress, + wsUri: flutterDevices.first.vmService!.wsAddress, + baseUri: baseUris.first.toString(), + ), + ); + } + } on DevFSException catch (error) { + globals.printError('Error initializing DevFS: $error'); + return 3; + } + + final Stopwatch initialUpdateDevFSsTimer = Stopwatch()..start(); + final UpdateFSReport devfsResult = await _updateDevFS(fullRestart: needsFullRestart); + _addBenchmarkData( + 'hotReloadInitialDevFSSyncMilliseconds', + initialUpdateDevFSsTimer.elapsed.inMilliseconds, + ); + if (!devfsResult.success) { + return 3; + } + + for (final FlutterDevice? device in flutterDevices) { + // VM must have accepted the kernel binary, there will be no reload + // report, so we let incremental compiler know that source code was accepted. + if (device!.generator != null) { + device.generator!.accept(); + } + final List views = await device.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + globals.printTrace('Connected to $view.'); + } + } + + // In fast-start mode, apps are initialized from a placeholder splashscreen + // app. We must do a restart here to load the program and assets for the + // real app. + if (debuggingOptions.fastStart) { + await restart( + fullRestart: true, + reason: 'restart', + silent: true, + ); + } + + appStartedCompleter?.complete(); + + if (benchmarkMode) { + // Wait multiple seconds for the isolate to have fully started. + await Future.delayed(const Duration(seconds: 10)); + // We are running in benchmark mode. + globals.printStatus('Running in benchmark mode.'); + // Measure time to perform a hot restart. + globals.printStatus('Benchmarking hot restart'); + await restart(fullRestart: true); + // Wait multiple seconds to stabilize benchmark on slower device lab hardware. + // Hot restart finishes when the new isolate is started, not when the new isolate + // is ready. This process can actually take multiple seconds. + await Future.delayed(const Duration(seconds: 10)); + + globals.printStatus('Benchmarking hot reload'); + // Measure time to perform a hot reload. + await restart(); + if (stayResident) { + await waitForAppToFinish(); + } else { + globals.printStatus('Benchmark completed. Exiting application.'); + await _cleanupDevFS(); + await stopEchoingDeviceLog(); + await exitApp(); + } + final File benchmarkOutput = globals.fs.file('hot_benchmark.json'); + benchmarkOutput.writeAsStringSync(toPrettyJson(benchmarkData)); + return 0; + } + writeVmServiceFile(); + + int result = 0; + if (stayResident) { + result = await waitForAppToFinish(); + } + await cleanupAtFinish(); + return result; + } + + @override + Future run({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool enableDevTools = false, + String? route, + }) async { + await _calculateTargetPlatform(); + + final Uri projectUri = Uri.directory(projectRootPath); + _buildRunner ??= NativeAssetsBuildRunnerImpl( + projectUri, + debuggingOptions.buildInfo.packageConfig, + fileSystem, + globals.logger, + ); + final Uri? nativeAssetsYaml = await dryRunNativeAssets( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: _buildRunner!, + flutterDevices: flutterDevices, + ); + + final Stopwatch appStartedTimer = Stopwatch()..start(); + final File mainFile = globals.fs.file(mainPath); + firstBuildTime = DateTime.now(); + + Duration totalCompileTime = Duration.zero; + Duration totalLaunchAppTime = Duration.zero; + + final List> startupTasks = >[]; + for (final FlutterDevice? device in flutterDevices) { + // Here we initialize the frontend_server concurrently with the platform + // build, reducing overall initialization time. This is safe because the first + // invocation of the frontend server produces a full dill file that the + // subsequent invocation in devfs will not overwrite. + await runSourceGenerators(); + if (device!.generator != null) { + final Stopwatch compileTimer = Stopwatch()..start(); + startupTasks.add( + device.generator!.recompile( + mainFile.uri, + [], + // When running without a provided applicationBinary, the tool will + // simultaneously run the initial frontend_server compilation and + // the native build step. If there is a Dart compilation error, it + // should only be displayed once. + suppressErrors: applicationBinary == null, + checkDartPluginRegistry: true, + dartPluginRegistrant: FlutterProject.current().dartPluginRegistrant, + outputPath: dillOutputPath, + packageConfig: debuggingOptions.buildInfo.packageConfig, + projectRootPath: FlutterProject.current().directory.absolute.path, + fs: globals.fs, + nativeAssetsYaml: nativeAssetsYaml, + ).then((CompilerOutput? output) { + compileTimer.stop(); + totalCompileTime += compileTimer.elapsed; + return output?.errorCount == 0; + }) + ); + } + + final Stopwatch launchAppTimer = Stopwatch()..start(); + startupTasks.add(device.runHot( + hotRunner: this, + route: route, + ).then((int result) { + totalLaunchAppTime += launchAppTimer.elapsed; + return result == 0; + })); + } + + unawaited(appStartedCompleter?.future.then((_) { + HotEvent( + 'reload-ready', + targetPlatform: _targetPlatform!, + sdkName: _sdkName!, + emulator: _emulator!, + fullRestart: false, + overallTimeInMs: appStartedTimer.elapsed.inMilliseconds, + compileTimeInMs: totalCompileTime.inMilliseconds, + transferTimeInMs: totalLaunchAppTime.inMilliseconds, + ).send(); + + _analytics.send(Event.hotRunnerInfo( + label: 'reload-ready', + targetPlatform: _targetPlatform!, + sdkName: _sdkName!, + emulator: _emulator!, + fullRestart: false, + overallTimeInMs: appStartedTimer.elapsed.inMilliseconds, + compileTimeInMs: totalCompileTime.inMilliseconds, + transferTimeInMs: totalLaunchAppTime.inMilliseconds, + )); + })); + + try { + final List results = await Future.wait(startupTasks); + if (!results.every((bool passed) => passed)) { + appFailedToStart(); + return 1; + } + cacheInitialDillCompilation(); + } on Exception catch (err) { + globals.printError(err.toString()); + appFailedToStart(); + return 1; + } + + return attach( + connectionInfoCompleter: connectionInfoCompleter, + appStartedCompleter: appStartedCompleter, + enableDevTools: enableDevTools, + needsFullRestart: false, + ); + } + + Future> _initDevFS() async { + final String fsName = globals.fs.path.basename(projectRootPath); + return [ + for (final FlutterDevice? device in flutterDevices) + await device!.setupDevFS( + fsName, + globals.fs.directory(projectRootPath), + ), + ]; + } + + Future _updateDevFS({ bool fullRestart = false }) async { + final bool isFirstUpload = !assetBundle.wasBuiltOnce(); + final bool rebuildBundle = assetBundle.needsBuild(); + if (rebuildBundle) { + globals.printTrace('Updating assets'); + final int result = await assetBundle.build( + packagesPath: '.packages', + flavor: debuggingOptions.buildInfo.flavor, + ); + if (result != 0) { + return UpdateFSReport(); + } + } + + final Stopwatch findInvalidationTimer = _stopwatchFactory.createStopwatch('updateDevFS')..start(); + final DevFS devFS = flutterDevices[0].devFS!; + final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated( + lastCompiled: devFS.lastCompiled, + urisToMonitor: devFS.sources, + packagesPath: packagesFilePath, + asyncScanning: hotRunnerConfig!.asyncScanning, + packageConfig: devFS.lastPackageConfig + ?? debuggingOptions.buildInfo.packageConfig, + ); + findInvalidationTimer.stop(); + final File entrypointFile = globals.fs.file(mainPath); + if (!entrypointFile.existsSync()) { + globals.printError( + 'The entrypoint file (i.e. the file with main()) ${entrypointFile.path} ' + 'cannot be found. Moving or renaming this file will prevent changes to ' + 'its contents from being discovered during hot reload/restart until ' + 'flutter is restarted or the file is restored.' + ); + } + final UpdateFSReport results = UpdateFSReport( + success: true, + scannedSourcesCount: devFS.sources.length, + findInvalidatedDuration: findInvalidationTimer.elapsed, + ); + for (final FlutterDevice? device in flutterDevices) { + results.incorporateResults(await device!.updateDevFS( + mainUri: entrypointFile.absolute.uri, + target: target, + bundle: assetBundle, + firstBuildTime: firstBuildTime, + bundleFirstUpload: isFirstUpload, + bundleDirty: !isFirstUpload && rebuildBundle, + fullRestart: fullRestart, + projectRootPath: projectRootPath, + pathToReload: getReloadPath(fullRestart: fullRestart, swap: _swap), + invalidatedFiles: invalidationResult.uris!, + packageConfig: invalidationResult.packageConfig!, + dillOutputPath: dillOutputPath, + )); + } + return results; + } + + void _resetDirtyAssets() { + for (final FlutterDevice device in flutterDevices) { + final DevFS? devFS = device.devFS; + if (devFS == null) { + // This is sometimes null, however we don't know why and have not been + // able to reproduce, https://github.com/flutter/flutter/issues/108653 + continue; + } + devFS.assetPathsToEvict.clear(); + devFS.shaderPathsToEvict.clear(); + devFS.scenePathsToEvict.clear(); + } + } + + Future _cleanupDevFS() async { + final List> futures = >[]; + for (final FlutterDevice device in flutterDevices) { + if (device.devFS != null) { + // Cleanup the devFS, but don't wait indefinitely. + // We ignore any errors, because it's not clear what we would do anyway. + futures.add(device.devFS!.destroy() + .timeout(const Duration(milliseconds: 250)) + .then( + (Object? _) {}, + onError: (Object? error, StackTrace stackTrace) { + globals.printTrace('Ignored error while cleaning up DevFS: $error\n$stackTrace'); + } + ), + ); + } + device.devFS = null; + } + await Future.wait(futures); + } + + Future _launchInView( + FlutterDevice device, + Uri main, + Uri assetsDirectory, + ) async { + final List views = await device.vmService!.getFlutterViews(); + await Future.wait(>[ + for (final FlutterView view in views) + device.vmService!.runInView( + viewId: view.id, + main: main, + assetsDirectory: assetsDirectory, + ), + ]); + } + + Future _launchFromDevFS() async { + final List> futures = >[]; + for (final FlutterDevice? device in flutterDevices) { + final Uri deviceEntryUri = device!.devFS!.baseUri!.resolve(_swap ? 'main.dart.swap.dill' : 'main.dart.dill'); + final Uri deviceAssetsDirectoryUri = device.devFS!.baseUri!.resolveUri( + globals.fs.path.toUri(getAssetBuildDirectory())); + futures.add(_launchInView(device, + deviceEntryUri, + deviceAssetsDirectoryUri)); + } + await Future.wait(futures); + } + + Future _restartFromSources({ + String? reason, + }) async { + final Stopwatch restartTimer = Stopwatch()..start(); + UpdateFSReport updatedDevFS; + try { + updatedDevFS = await _updateDevFS(fullRestart: true); + } finally { + hotRunnerConfig!.updateDevFSComplete(); + } + if (!updatedDevFS.success) { + for (final FlutterDevice? device in flutterDevices) { + if (device!.generator != null) { + await device.generator!.reject(); + } + } + return OperationResult(1, 'DevFS synchronization failed'); + } + _resetDirtyAssets(); + for (final FlutterDevice? device in flutterDevices) { + // VM must have accepted the kernel binary, there will be no reload + // report, so we let incremental compiler know that source code was accepted. + if (device!.generator != null) { + device.generator!.accept(); + } + } + // Check if the isolate is paused and resume it. + final List> operations = >[]; + for (final FlutterDevice? device in flutterDevices) { + final Set uiIsolatesIds = {}; + final List views = await device!.vmService!.getFlutterViews(); + for (final FlutterView view in views) { + if (view.uiIsolate == null) { + continue; + } + uiIsolatesIds.add(view.uiIsolate!.id); + // Reload the isolate. + final Future reloadIsolate = device.vmService! + .getIsolateOrNull(view.uiIsolate!.id!); + operations.add(reloadIsolate.then((vm_service.Isolate? isolate) async { + if ((isolate != null) && isPauseEvent(isolate.pauseEvent!.kind!)) { + // The embedder requires that the isolate is unpaused, because the + // runInView method requires interaction with dart engine APIs that + // are not thread-safe, and thus must be run on the same thread that + // would be blocked by the pause. Simply un-pausing is not sufficient, + // because this does not prevent the isolate from immediately hitting + // a breakpoint (for example if the breakpoint was placed in a loop + // or in a frequently called method) or an exception. Instead, all + // breakpoints are first disabled and exception pause mode set to + // None, and then the isolate resumed. + // These settings to not need restoring as Hot Restart results in + // new isolates, which will be configured by the editor as they are + // started. + final List> breakpointAndExceptionRemoval = >[ + device.vmService!.service.setIsolatePauseMode(isolate.id!, + exceptionPauseMode: vm_service.ExceptionPauseMode.kNone), + for (final vm_service.Breakpoint breakpoint in isolate.breakpoints!) + device.vmService!.service.removeBreakpoint(isolate.id!, breakpoint.id!), + ]; + await Future.wait(breakpointAndExceptionRemoval); + await device.vmService!.service.resume(view.uiIsolate!.id!); + } + })); + } + + // The engine handles killing and recreating isolates that it has spawned + // ("uiIsolates"). The isolates that were spawned from these uiIsolates + // will not be restarted, and so they must be manually killed. + final vm_service.VM vm = await device.vmService!.service.getVM(); + for (final vm_service.IsolateRef isolateRef in vm.isolates!) { + if (uiIsolatesIds.contains(isolateRef.id)) { + continue; + } + operations.add( + device.vmService!.service.kill(isolateRef.id!) + // Since we never check the value of this Future, only await its + // completion, make its type nullable so we can return null when + // catching errors. + .then( + (vm_service.Success success) => success, + onError: (Object error, StackTrace stackTrace) { + if (error is vm_service.SentinelException || + (error is vm_service.RPCError && error.code == 105)) { + // Do nothing on a SentinelException since it means the isolate + // has already been killed. + // Error code 105 indicates the isolate is not yet runnable, and might + // be triggered if the tool is attempting to kill the asset parsing + // isolate before it has finished starting up. + return null; + } + return Future.error(error, stackTrace); + }, + ), + ); + } + } + await Future.wait(operations); + + await _launchFromDevFS(); + restartTimer.stop(); + globals.printTrace('Hot restart performed in ${getElapsedAsMilliseconds(restartTimer.elapsed)}.'); + _addBenchmarkData('hotRestartMillisecondsToFrame', + restartTimer.elapsed.inMilliseconds); + + // Send timing analytics. + final Duration elapsedDuration = restartTimer.elapsed; + globals.flutterUsage.sendTiming('hot', 'restart', elapsedDuration); + _analytics.send(Event.timing( + workflow: 'hot', + variableName: 'restart', + elapsedMilliseconds: elapsedDuration.inMilliseconds, + )); + + // Toggle the main dill name after successfully uploading. + _swap =! _swap; + + return OperationResult( + OperationResult.ok.code, + OperationResult.ok.message, + updateFSReport: updatedDevFS, + ); + } + + /// Returns [true] if the reload was successful. + /// Prints errors if [printErrors] is [true]. + static bool validateReloadReport( + vm_service.ReloadReport? reloadReport, { + bool printErrors = true, + }) { + if (reloadReport == null) { + if (printErrors) { + globals.printError('Hot reload did not receive reload report.'); + } + return false; + } + final ReloadReportContents contents = ReloadReportContents.fromReloadReport(reloadReport); + if (!reloadReport.success!) { + if (printErrors) { + globals.printError('Hot reload was rejected:'); + for (final ReasonForCancelling reason in contents.notices) { + globals.printError(reason.toString()); + } + } + return false; + } + return true; + } + + @override + Future restart({ + bool fullRestart = false, + String? reason, + bool silent = false, + bool pause = false, + }) async { + if (flutterDevices.any((FlutterDevice? device) => device!.devFS == null)) { + return OperationResult(1, 'Device initialization has not completed.'); + } + await _calculateTargetPlatform(); + final Stopwatch timer = Stopwatch()..start(); + + // Run source generation if needed. + await runSourceGenerators(); + + if (fullRestart) { + final OperationResult result = await _fullRestartHelper( + targetPlatform: _targetPlatform, + sdkName: _sdkName, + emulator: _emulator, + reason: reason, + silent: silent, + ); + if (!silent) { + globals.printStatus('Restarted application in ${getElapsedAsMilliseconds(timer.elapsed)}.'); + } + unawaited(residentDevtoolsHandler!.hotRestart(flutterDevices)); + return result; + } + final OperationResult result = await _hotReloadHelper( + targetPlatform: _targetPlatform, + sdkName: _sdkName, + emulator: _emulator, + reason: reason, + pause: pause, + ); + if (result.isOk) { + final String elapsed = getElapsedAsMilliseconds(timer.elapsed); + if (!silent) { + if (result.extraTimings.isNotEmpty) { + final String extraTimingsString = result.extraTimings + .map((OperationResultExtraTiming e) => '${e.description}: ${e.timeInMs} ms') + .join(', '); + globals.printStatus('${result.message} in $elapsed ($extraTimingsString).'); + } else { + globals.printStatus('${result.message} in $elapsed.'); + } + } + } + return result; + } + + Future _fullRestartHelper({ + String? targetPlatform, + String? sdkName, + bool? emulator, + String? reason, + bool? silent, + }) async { + if (!supportsRestart) { + return OperationResult(1, 'hotRestart not supported'); + } + Status? status; + if (!silent!) { + status = globals.logger.startProgress( + 'Performing hot restart...', + progressId: 'hot.restart', + ); + } + OperationResult result; + String? restartEvent; + try { + final Stopwatch restartTimer = _stopwatchFactory.createStopwatch('fullRestartHelper')..start(); + if ((await hotRunnerConfig!.setupHotRestart()) != true) { + return OperationResult(1, 'setupHotRestart failed'); + } + result = await _restartFromSources(reason: reason); + restartTimer.stop(); + if (!result.isOk) { + restartEvent = 'restart-failed'; + } else { + HotEvent('restart', + targetPlatform: targetPlatform!, + sdkName: sdkName!, + emulator: emulator!, + fullRestart: true, + reason: reason, + overallTimeInMs: restartTimer.elapsed.inMilliseconds, + syncedBytes: result.updateFSReport?.syncedBytes, + invalidatedSourcesCount: result.updateFSReport?.invalidatedSourcesCount, + transferTimeInMs: result.updateFSReport?.transferDuration.inMilliseconds, + compileTimeInMs: result.updateFSReport?.compileDuration.inMilliseconds, + findInvalidatedTimeInMs: result.updateFSReport?.findInvalidatedDuration.inMilliseconds, + scannedSourcesCount: result.updateFSReport?.scannedSourcesCount, + ).send(); + _analytics.send(Event.hotRunnerInfo( + label: 'restart', + targetPlatform: targetPlatform, + sdkName: sdkName, + emulator: emulator, + fullRestart: true, + reason: reason, + overallTimeInMs: restartTimer.elapsed.inMilliseconds, + syncedBytes: result.updateFSReport?.syncedBytes, + invalidatedSourcesCount: result.updateFSReport?.invalidatedSourcesCount, + transferTimeInMs: result.updateFSReport?.transferDuration.inMilliseconds, + compileTimeInMs: result.updateFSReport?.compileDuration.inMilliseconds, + findInvalidatedTimeInMs: result.updateFSReport?.findInvalidatedDuration.inMilliseconds, + scannedSourcesCount: result.updateFSReport?.scannedSourcesCount, + )); + } + } on vm_service.SentinelException catch (err, st) { + restartEvent = 'exception'; + return OperationResult(1, 'hot restart failed to complete: $err\n$st', fatal: true); + } on vm_service.RPCError catch (err, st) { + restartEvent = 'exception'; + return OperationResult(1, 'hot restart failed to complete: $err\n$st', fatal: true); + } finally { + // The `restartEvent` variable will be null if restart succeeded. We will + // only handle the case when it failed here. + if (restartEvent != null) { + HotEvent(restartEvent, + targetPlatform: targetPlatform!, + sdkName: sdkName!, + emulator: emulator!, + fullRestart: true, + reason: reason, + ).send(); + _analytics.send(Event.hotRunnerInfo( + label: restartEvent, + targetPlatform: targetPlatform, + sdkName: sdkName, + emulator: emulator, + fullRestart: true, + reason: reason, + )); + } + status?.cancel(); + } + return result; + } + + Future _hotReloadHelper({ + String? targetPlatform, + String? sdkName, + bool? emulator, + String? reason, + bool? pause, + }) async { + Status status = globals.logger.startProgress( + 'Performing hot reload...', + progressId: 'hot.reload', + ); + OperationResult result; + try { + result = await _reloadSources( + targetPlatform: targetPlatform, + sdkName: sdkName, + emulator: emulator, + reason: reason, + pause: pause, + onSlow: (String message) { + status.cancel(); + status = globals.logger.startProgress( + message, + progressId: 'hot.reload', + ); + }, + ); + } on vm_service.RPCError catch (error) { + String errorMessage = 'hot reload failed to complete'; + int errorCode = 1; + if (error.code == kIsolateReloadBarred) { + errorCode = error.code; + errorMessage = 'Unable to hot reload application due to an unrecoverable error in ' + 'the source code. Please address the error and then use "R" to ' + 'restart the app.\n' + '${error.message} (error code: ${error.code})'; + HotEvent('reload-barred', + targetPlatform: targetPlatform!, + sdkName: sdkName!, + emulator: emulator!, + fullRestart: false, + reason: reason, + ).send(); + _analytics.send(Event.hotRunnerInfo( + label: 'reload-barred', + targetPlatform: targetPlatform, + sdkName: sdkName, + emulator: emulator, + fullRestart: false, + reason: reason, + )); + } else { + HotEvent('exception', + targetPlatform: targetPlatform!, + sdkName: sdkName!, + emulator: emulator!, + fullRestart: false, + reason: reason, + ).send(); + _analytics.send(Event.hotRunnerInfo( + label: 'exception', + targetPlatform: targetPlatform, + sdkName: sdkName, + emulator: emulator, + fullRestart: false, + reason: reason, + )); + } + return OperationResult(errorCode, errorMessage, fatal: true); + } finally { + status.cancel(); + } + return result; + } + + Future _reloadSources({ + String? targetPlatform, + String? sdkName, + bool? emulator, + bool? pause = false, + String? reason, + void Function(String message)? onSlow, + }) async { + final Map> viewCache = >{}; + for (final FlutterDevice? device in flutterDevices) { + final List views = await device!.vmService!.getFlutterViews(); + viewCache[device] = views; + for (final FlutterView view in views) { + if (view.uiIsolate == null) { + return OperationResult(2, 'Application isolate not found', fatal: true); + } + } + } + + final Stopwatch reloadTimer = _stopwatchFactory.createStopwatch('reloadSources:reload')..start(); + if ((await hotRunnerConfig!.setupHotReload()) != true) { + return OperationResult(1, 'setupHotReload failed'); + } + final Stopwatch devFSTimer = Stopwatch()..start(); + UpdateFSReport updatedDevFS; + try { + updatedDevFS= await _updateDevFS(); + } finally { + hotRunnerConfig!.updateDevFSComplete(); + } + // Record time it took to synchronize to DevFS. + bool shouldReportReloadTime = true; + _addBenchmarkData('hotReloadDevFSSyncMilliseconds', devFSTimer.elapsed.inMilliseconds); + if (!updatedDevFS.success) { + return OperationResult(1, 'DevFS synchronization failed'); + } + + final List extraTimings = []; + extraTimings.add(OperationResultExtraTiming('compile', updatedDevFS.compileDuration.inMilliseconds)); + + String reloadMessage = 'Reloaded 0 libraries'; + final Stopwatch reloadVMTimer = _stopwatchFactory.createStopwatch('reloadSources:vm')..start(); + final Map firstReloadDetails = {}; + if (updatedDevFS.invalidatedSourcesCount > 0) { + final OperationResult result = await _reloadSourcesHelper( + this, + flutterDevices, + pause, + firstReloadDetails, + targetPlatform, + sdkName, + emulator, + reason, + globals.flutterUsage, + globals.analytics, + ); + if (result.code != 0) { + return result; + } + reloadMessage = result.message; + } else { + _addBenchmarkData('hotReloadVMReloadMilliseconds', 0); + } + reloadVMTimer.stop(); + extraTimings.add(OperationResultExtraTiming('reload', reloadVMTimer.elapsedMilliseconds)); + + await evictDirtyAssets(); + + final Stopwatch reassembleTimer = _stopwatchFactory.createStopwatch('reloadSources:reassemble')..start(); + + final ReassembleResult reassembleResult = await _reassembleHelper( + flutterDevices, + viewCache, + onSlow, + reloadMessage, + ); + shouldReportReloadTime = reassembleResult.shouldReportReloadTime; + if (reassembleResult.reassembleViews.isEmpty) { + return OperationResult(OperationResult.ok.code, reloadMessage); + } + // Record time it took for Flutter to reassemble the application. + reassembleTimer.stop(); + _addBenchmarkData('hotReloadFlutterReassembleMilliseconds', reassembleTimer.elapsed.inMilliseconds); + extraTimings.add(OperationResultExtraTiming('reassemble', reassembleTimer.elapsedMilliseconds)); + + reloadTimer.stop(); + final Duration reloadDuration = reloadTimer.elapsed; + final int reloadInMs = reloadDuration.inMilliseconds; + + // Collect stats that help understand scale of update for this hot reload request. + // For example, [syncedLibraryCount]/[finalLibraryCount] indicates how + // many libraries were affected by the hot reload request. + // Relation of [invalidatedSourcesCount] to [syncedLibraryCount] should help + // understand sync/transfer "overhead" of updating this number of source files. + HotEvent('reload', + targetPlatform: targetPlatform!, + sdkName: sdkName!, + emulator: emulator!, + fullRestart: false, + reason: reason, + overallTimeInMs: reloadInMs, + finalLibraryCount: firstReloadDetails['finalLibraryCount'] as int? ?? 0, + syncedLibraryCount: firstReloadDetails['receivedLibraryCount'] as int? ?? 0, + syncedClassesCount: firstReloadDetails['receivedClassesCount'] as int? ?? 0, + syncedProceduresCount: firstReloadDetails['receivedProceduresCount'] as int? ?? 0, + syncedBytes: updatedDevFS.syncedBytes, + invalidatedSourcesCount: updatedDevFS.invalidatedSourcesCount, + transferTimeInMs: updatedDevFS.transferDuration.inMilliseconds, + compileTimeInMs: updatedDevFS.compileDuration.inMilliseconds, + findInvalidatedTimeInMs: updatedDevFS.findInvalidatedDuration.inMilliseconds, + scannedSourcesCount: updatedDevFS.scannedSourcesCount, + reassembleTimeInMs: reassembleTimer.elapsed.inMilliseconds, + reloadVMTimeInMs: reloadVMTimer.elapsed.inMilliseconds, + ).send(); + _analytics.send(Event.hotRunnerInfo( + label: 'reload', + targetPlatform: targetPlatform, + sdkName: sdkName, + emulator: emulator, + fullRestart: false, + reason: reason, + overallTimeInMs: reloadInMs, + finalLibraryCount: firstReloadDetails['finalLibraryCount'] as int? ?? 0, + syncedLibraryCount: firstReloadDetails['receivedLibraryCount'] as int? ?? 0, + syncedClassesCount: firstReloadDetails['receivedClassesCount'] as int? ?? 0, + syncedProceduresCount: firstReloadDetails['receivedProceduresCount'] as int? ?? 0, + syncedBytes: updatedDevFS.syncedBytes, + invalidatedSourcesCount: updatedDevFS.invalidatedSourcesCount, + transferTimeInMs: updatedDevFS.transferDuration.inMilliseconds, + compileTimeInMs: updatedDevFS.compileDuration.inMilliseconds, + findInvalidatedTimeInMs: updatedDevFS.findInvalidatedDuration.inMilliseconds, + scannedSourcesCount: updatedDevFS.scannedSourcesCount, + reassembleTimeInMs: reassembleTimer.elapsed.inMilliseconds, + reloadVMTimeInMs: reloadVMTimer.elapsed.inMilliseconds, + )); + + if (shouldReportReloadTime) { + globals.printTrace('Hot reload performed in ${getElapsedAsMilliseconds(reloadDuration)}.'); + // Record complete time it took for the reload. + _addBenchmarkData('hotReloadMillisecondsToFrame', reloadInMs); + } + // Only report timings if we reloaded a single view without any errors. + if ((reassembleResult.reassembleViews.length == 1) && !reassembleResult.failedReassemble && shouldReportReloadTime) { + globals.flutterUsage.sendTiming('hot', 'reload', reloadDuration); + _analytics.send(Event.timing( + workflow: 'hot', + variableName: 'reload', + elapsedMilliseconds: reloadDuration.inMilliseconds, + )); + } + return OperationResult( + reassembleResult.failedReassemble ? 1 : OperationResult.ok.code, + reloadMessage, + extraTimings: extraTimings + ); + } + + @override + void printHelp({ required bool details }) { + globals.printStatus('Flutter run key commands.'); + commandHelp.r.print(); + if (supportsRestart) { + commandHelp.R.print(); + } + if (details) { + printHelpDetails(); + commandHelp.hWithDetails.print(); + } else { + commandHelp.hWithoutDetails.print(); + } + if (_didAttach) { + commandHelp.d.print(); + } + commandHelp.c.print(); + commandHelp.q.print(); + if (debuggingOptions.buildInfo.nullSafetyMode != NullSafetyMode.sound) { + globals.printStatus(''); + globals.printStatus( + 'Running without sound null safety ⚠️', + emphasis: true, + ); + globals.printStatus( + 'Dart 3 will only support sound null safety, see https://dart.dev/null-safety', + ); + } + globals.printStatus(''); + printDebuggerList(); + } + + @visibleForTesting + Future evictDirtyAssets() async { + final List> futures = >[]; + for (final FlutterDevice? device in flutterDevices) { + if (device!.devFS!.assetPathsToEvict.isEmpty && + device.devFS!.shaderPathsToEvict.isEmpty && + device.devFS!.scenePathsToEvict.isEmpty) { + continue; + } + final List views = await device.vmService!.getFlutterViews(); + + // If this is the first time we update the assets, make sure to call the setAssetDirectory + if (!device.devFS!.hasSetAssetDirectory) { + final Uri deviceAssetsDirectoryUri = device.devFS!.baseUri!.resolveUri(globals.fs.path.toUri(getAssetBuildDirectory())); + await Future.wait(views.map>( + (FlutterView view) => device.vmService!.setAssetDirectory( + assetsDirectory: deviceAssetsDirectoryUri, + uiIsolateId: view.uiIsolate!.id, + viewId: view.id, + windows: device.targetPlatform == TargetPlatform.windows_x64, + ) + )); + for (final FlutterView view in views) { + globals.printTrace('Set asset directory in $view.'); + } + device.devFS!.hasSetAssetDirectory = true; + } + + if (views.first.uiIsolate == null) { + globals.printError('Application isolate not found for $device'); + continue; + } + + if (device.devFS!.didUpdateFontManifest) { + futures.add(device.vmService!.reloadAssetFonts( + isolateId: views.first.uiIsolate!.id!, + viewId: views.first.id, + )); + } + + for (final String assetPath in device.devFS!.assetPathsToEvict) { + futures.add( + device.vmService! + .flutterEvictAsset( + assetPath, + isolateId: views.first.uiIsolate!.id!, + ) + ); + } + for (final String assetPath in device.devFS!.shaderPathsToEvict) { + futures.add( + device.vmService! + .flutterEvictShader( + assetPath, + isolateId: views.first.uiIsolate!.id!, + ) + ); + } + for (final String assetPath in device.devFS!.scenePathsToEvict) { + futures.add( + device.vmService! + .flutterEvictScene( + assetPath, + isolateId: views.first.uiIsolate!.id!, + ) + ); + } + device.devFS!.assetPathsToEvict.clear(); + device.devFS!.shaderPathsToEvict.clear(); + device.devFS!.scenePathsToEvict.clear(); + } + await Future.wait(futures); + } + + @override + Future cleanupAfterSignal() async { + await stopEchoingDeviceLog(); + await hotRunnerConfig!.runPreShutdownOperations(); + if (_didAttach) { + appFinished(); + } else { + await exitApp(); + } + } + + @override + Future preExit() async { + await _cleanupDevFS(); + await hotRunnerConfig!.runPreShutdownOperations(); + await super.preExit(); + } + + @override + Future cleanupAtFinish() async { + for (final FlutterDevice? flutterDevice in flutterDevices) { + await flutterDevice!.device!.dispose(); + } + await _cleanupDevFS(); + await residentDevtoolsHandler!.shutdown(); + await stopEchoingDeviceLog(); + } +} + +typedef ReloadSourcesHelper = Future Function( + HotRunner hotRunner, + List flutterDevices, + bool? pause, + Map firstReloadDetails, + String? targetPlatform, + String? sdkName, + bool? emulator, + String? reason, + Usage usage, + Analytics analytics, +); + +@visibleForTesting +Future defaultReloadSourcesHelper( + HotRunner hotRunner, + List flutterDevices, + bool? pause, + Map firstReloadDetails, + String? targetPlatform, + String? sdkName, + bool? emulator, + String? reason, + Usage usage, + Analytics analytics, +) async { + final Stopwatch vmReloadTimer = Stopwatch()..start(); + const String entryPath = 'main.dart.incremental.dill'; + final List> allReportsFutures = >[]; + + for (final FlutterDevice? device in flutterDevices) { + final List> reportFutures = await _reloadDeviceSources( + device!, + entryPath, + pause: pause, + ); + allReportsFutures.add(Future.wait(reportFutures).then( + (List reports) async { + // TODO(aam): Investigate why we are validating only first reload report, + // which seems to be current behavior + if (reports.isEmpty) { + return null; + } + final vm_service.ReloadReport firstReport = reports.first; + // Don't print errors because they will be printed further down when + // `validateReloadReport` is called again. + await device.updateReloadStatus( + HotRunner.validateReloadReport(firstReport, printErrors: false), + ); + return DeviceReloadReport(device, reports); + }, + )); + } + final Iterable reports = (await Future.wait(allReportsFutures)).whereType(); + final vm_service.ReloadReport? reloadReport = reports.isEmpty ? null : reports.first.reports[0]; + if (reloadReport == null || !HotRunner.validateReloadReport(reloadReport)) { + // Reload failed. + HotEvent('reload-reject', + targetPlatform: targetPlatform!, + sdkName: sdkName!, + emulator: emulator!, + fullRestart: false, + reason: reason, + usage: usage, + ).send(); + analytics.send(Event.hotRunnerInfo( + label: 'reload-reject', + targetPlatform: targetPlatform, + sdkName: sdkName, + emulator: emulator, + fullRestart: false, + reason: reason, + )); + // Reset devFS lastCompileTime to ensure the file will still be marked + // as dirty on subsequent reloads. + _resetDevFSCompileTime(flutterDevices); + if (reloadReport == null) { + return OperationResult(1, 'No Dart isolates found'); + } + final ReloadReportContents contents = ReloadReportContents.fromReloadReport(reloadReport); + return OperationResult(1, 'Reload rejected: ${contents.notices.join("\n")}'); + } + // Collect stats only from the first device. If/when run -d all is + // refactored, we'll probably need to send one hot reload/restart event + // per device to analytics. + firstReloadDetails.addAll(castStringKeyedMap(reloadReport.json!['details'])!); + final Map details = reloadReport.json!['details'] as Map; + final int? loadedLibraryCount = details['loadedLibraryCount'] as int?; + final int? finalLibraryCount = details['finalLibraryCount'] as int?; + globals.printTrace('reloaded $loadedLibraryCount of $finalLibraryCount libraries'); + // reloadMessage = 'Reloaded $loadedLibraryCount of $finalLibraryCount libraries'; + // Record time it took for the VM to reload the sources. + hotRunner._addBenchmarkData('hotReloadVMReloadMilliseconds', vmReloadTimer.elapsed.inMilliseconds); + return OperationResult(0, 'Reloaded $loadedLibraryCount of $finalLibraryCount libraries'); +} + +Future>> _reloadDeviceSources( + FlutterDevice device, + String entryPath, { + bool? pause = false, +}) async { + final String deviceEntryUri = device.devFS!.baseUri! + .resolve(entryPath).toString(); + final vm_service.VM vm = await device.vmService!.service.getVM(); + return >[ + for (final vm_service.IsolateRef isolateRef in vm.isolates!) + device.vmService!.service.reloadSources( + isolateRef.id!, + pause: pause, + rootLibUri: deviceEntryUri, + ), + ]; +} + +void _resetDevFSCompileTime(List flutterDevices) { + for (final FlutterDevice? device in flutterDevices) { + device!.devFS!.resetLastCompiled(); + } +} + +@visibleForTesting +class ReassembleResult { + ReassembleResult(this.reassembleViews, this.failedReassemble, this.shouldReportReloadTime); + final Map reassembleViews; + final bool failedReassemble; + final bool shouldReportReloadTime; +} + +typedef ReassembleHelper = Future Function( + List flutterDevices, + Map> viewCache, + void Function(String message)? onSlow, + String reloadMessage, +); + +Future _defaultReassembleHelper( + List flutterDevices, + Map> viewCache, + void Function(String message)? onSlow, + String reloadMessage, +) async { + // Check if any isolates are paused and reassemble those that aren't. + final Map reassembleViews = {}; + final List> reassembleFutures = >[]; + String? serviceEventKind; + int pausedIsolatesFound = 0; + bool failedReassemble = false; + bool shouldReportReloadTime = true; + for (final FlutterDevice? device in flutterDevices) { + final List views = viewCache[device]!; + for (final FlutterView view in views) { + // Check if the isolate is paused, and if so, don't reassemble. Ignore the + // PostPauseEvent event - the client requesting the pause will resume the app. + final vm_service.Event? pauseEvent = await device!.vmService! + .getIsolatePauseEventOrNull(view.uiIsolate!.id!); + if (pauseEvent != null + && isPauseEvent(pauseEvent.kind!) + && pauseEvent.kind != vm_service.EventKind.kPausePostRequest) { + pausedIsolatesFound += 1; + if (serviceEventKind == null) { + serviceEventKind = pauseEvent.kind; + } else if (serviceEventKind != pauseEvent.kind) { + serviceEventKind = ''; // many kinds + } + } else { + reassembleViews[view] = device.vmService; + // If the tool identified a change in a single widget, do a fast instead + // of a full reassemble. + final Future reassembleWork = device.vmService!.flutterReassemble( + isolateId: view.uiIsolate!.id!, + ); + reassembleFutures.add(reassembleWork.then( + (Object? obj) => obj, + onError: (Object error, StackTrace stackTrace) { + if (error is! Exception) { + return Future.error(error, stackTrace); + } + failedReassemble = true; + globals.printError('Reassembling ${view.uiIsolate!.name} failed: $error\n$stackTrace'); + }, + )); + } + } + } + if (pausedIsolatesFound > 0) { + if (onSlow != null) { + onSlow('${_describePausedIsolates(pausedIsolatesFound, serviceEventKind!)}; interface might not update.'); + } + if (reassembleViews.isEmpty) { + globals.printTrace('Skipping reassemble because all isolates are paused.'); + return ReassembleResult(reassembleViews, failedReassemble, shouldReportReloadTime); + } + } + assert(reassembleViews.isNotEmpty); + + globals.printTrace('Reassembling application'); + + final Future reassembleFuture = Future.wait(reassembleFutures).then((void _) => null); + await reassembleFuture.timeout( + const Duration(seconds: 2), + onTimeout: () async { + if (pausedIsolatesFound > 0) { + shouldReportReloadTime = false; + return ; // probably no point waiting, they're probably deadlocked and we've already warned. + } + // Check if any isolate is newly paused. + globals.printTrace('This is taking a long time; will now check for paused isolates.'); + int postReloadPausedIsolatesFound = 0; + String? serviceEventKind; + for (final FlutterView view in reassembleViews.keys) { + final vm_service.Event? pauseEvent = await reassembleViews[view]! + .getIsolatePauseEventOrNull(view.uiIsolate!.id!); + if (pauseEvent != null && isPauseEvent(pauseEvent.kind!)) { + postReloadPausedIsolatesFound += 1; + if (serviceEventKind == null) { + serviceEventKind = pauseEvent.kind; + } else if (serviceEventKind != pauseEvent.kind) { + serviceEventKind = ''; // many kinds + } + } + } + globals.printTrace('Found $postReloadPausedIsolatesFound newly paused isolate(s).'); + if (postReloadPausedIsolatesFound == 0) { + await reassembleFuture; // must just be taking a long time... keep waiting! + return; + } + shouldReportReloadTime = false; + if (onSlow != null) { + onSlow('${_describePausedIsolates(postReloadPausedIsolatesFound, serviceEventKind!)}.'); + } + return; + }, + ); + return ReassembleResult(reassembleViews, failedReassemble, shouldReportReloadTime); +} + +String _describePausedIsolates(int pausedIsolatesFound, String serviceEventKind) { + assert(pausedIsolatesFound > 0); + final StringBuffer message = StringBuffer(); + bool plural; + if (pausedIsolatesFound == 1) { + message.write('The application is '); + plural = false; + } else { + message.write('$pausedIsolatesFound isolates are '); + plural = true; + } + switch (serviceEventKind) { + case vm_service.EventKind.kPauseStart: + message.write('paused (probably due to --start-paused)'); + case vm_service.EventKind.kPauseExit: + message.write('paused because ${ plural ? 'they have' : 'it has' } terminated'); + case vm_service.EventKind.kPauseBreakpoint: + message.write('paused in the debugger on a breakpoint'); + case vm_service.EventKind.kPauseInterrupted: + message.write('paused due in the debugger'); + case vm_service.EventKind.kPauseException: + message.write('paused in the debugger after an exception was thrown'); + case vm_service.EventKind.kPausePostRequest: + message.write('paused'); + case '': + message.write('paused for various reasons'); + default: + message.write('paused'); + } + return message.toString(); +} + +/// The result of an invalidation check from [ProjectFileInvalidator]. +class InvalidationResult { + const InvalidationResult({ + this.uris, + this.packageConfig, + }); + + final List? uris; + final PackageConfig? packageConfig; +} + +/// The [ProjectFileInvalidator] track the dependencies for a running +/// application to determine when they are dirty. +class ProjectFileInvalidator { + ProjectFileInvalidator({ + required FileSystem fileSystem, + required Platform platform, + required Logger logger, + }): _fileSystem = fileSystem, + _platform = platform, + _logger = logger; + + final FileSystem _fileSystem; + final Platform _platform; + final Logger _logger; + + static const String _pubCachePathLinuxAndMac = '.pub-cache'; + static const String _pubCachePathWindows = 'Pub/Cache'; + + // As of writing, Dart supports up to 32 asynchronous I/O threads per + // isolate. We also want to avoid hitting platform limits on open file + // handles/descriptors. + // + // This value was chosen based on empirical tests scanning a set of + // ~2000 files. + static const int _kMaxPendingStats = 8; + + Future findInvalidated({ + required DateTime? lastCompiled, + required List urisToMonitor, + required String packagesPath, + required PackageConfig packageConfig, + bool asyncScanning = false, + }) async { + + if (lastCompiled == null) { + // Initial load. + assert(urisToMonitor.isEmpty); + return InvalidationResult( + packageConfig: packageConfig, + uris: [], + ); + } + + final Stopwatch stopwatch = Stopwatch()..start(); + final List urisToScan = [ + // Don't watch pub cache directories to speed things up a little. + for (final Uri uri in urisToMonitor) + if (_isNotInPubCache(uri)) uri, + ]; + final List invalidatedFiles = []; + if (asyncScanning) { + final Pool pool = Pool(_kMaxPendingStats); + final List> waitList = >[]; + for (final Uri uri in urisToScan) { + waitList.add(pool.withResource( + // Calling fs.stat() is more performant than fs.file().stat(), but + // uri.toFilePath() does not work with MultiRootFileSystem. + () => (uri.hasScheme && uri.scheme != 'file' + ? _fileSystem.file(uri).stat() + : _fileSystem.stat(uri.toFilePath(windows: _platform.isWindows))) + .then((FileStat stat) { + final DateTime updatedAt = stat.modified; + if (updatedAt.isAfter(lastCompiled)) { + invalidatedFiles.add(uri); + } + }) + )); + } + await Future.wait(waitList); + } else { + for (final Uri uri in urisToScan) { + // Calling fs.statSync() is more performant than fs.file().statSync(), but + // uri.toFilePath() does not work with MultiRootFileSystem. + final DateTime updatedAt = uri.hasScheme && uri.scheme != 'file' + ? _fileSystem.file(uri).statSync().modified + : _fileSystem.statSync(uri.toFilePath(windows: _platform.isWindows)).modified; + if (updatedAt.isAfter(lastCompiled)) { + invalidatedFiles.add(uri); + } + } + } + // We need to check the .packages file too since it is not used in compilation. + final File packageFile = _fileSystem.file(packagesPath); + final Uri packageUri = packageFile.uri; + final DateTime updatedAt = packageFile.statSync().modified; + if (updatedAt.isAfter(lastCompiled)) { + invalidatedFiles.add(packageUri); + packageConfig = await _createPackageConfig(packagesPath); + // The frontend_server might be monitoring the package_config.json file, + // Pub should always produce both files. + // TODO(zanderso): remove after https://github.com/flutter/flutter/issues/55249 + if (_fileSystem.path.basename(packagesPath) == '.packages') { + final File packageConfigFile = _fileSystem.file(packagesPath) + .parent.childDirectory('.dart_tool') + .childFile('package_config.json'); + if (packageConfigFile.existsSync()) { + invalidatedFiles.add(packageConfigFile.uri); + } + } + } + + _logger.printTrace( + 'Scanned through ${urisToScan.length} files in ' + '${stopwatch.elapsedMilliseconds}ms' + '${asyncScanning ? " (async)" : ""}', + ); + return InvalidationResult( + packageConfig: packageConfig, + uris: invalidatedFiles, + ); + } + + bool _isNotInPubCache(Uri uri) { + return !(_platform.isWindows && uri.path.contains(_pubCachePathWindows)) + && !uri.path.contains(_pubCachePathLinuxAndMac); + } + + Future _createPackageConfig(String packagesPath) { + return loadPackageConfigWithLogging( + _fileSystem.file(packagesPath), + logger: _logger, + ); + } +} + +/// Additional serialization logic for a hot reload response. +class ReloadReportContents { + factory ReloadReportContents.fromReloadReport(vm_service.ReloadReport report) { + final List reasons = []; + final Object? notices = report.json!['notices']; + if (notices is! List) { + return ReloadReportContents._(report.success, reasons, report); + } + for (final Object? obj in notices) { + if (obj is! Map) { + continue; + } + final Map notice = obj; + reasons.add(ReasonForCancelling( + message: notice['message'] is String + ? notice['message'] as String? + : 'Unknown Error', + )); + } + + return ReloadReportContents._(report.success, reasons, report); + } + + ReloadReportContents._( + this.success, + this.notices, + this.report, + ); + + final bool? success; + final List notices; + final vm_service.ReloadReport report; +} + +/// A serialization class for hot reload rejection reasons. +/// +/// Injects an additional error message that a hot restart will +/// resolve the issue. +class ReasonForCancelling { + ReasonForCancelling({ + this.message, + }); + + final String? message; + + @override + String toString() { + return '$message.\nTry performing a hot restart instead.'; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/sksl_writer.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/sksl_writer.dart new file mode 100644 index 0000000000000000000000000000000000000000..a0b2f863a808fd280c00978736700ca39eb48b15 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/sksl_writer.dart @@ -0,0 +1,68 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; + +import 'package:file/file.dart'; + +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'build_info.dart'; +import 'convert.dart'; +import 'device.dart'; +import 'globals.dart' as globals; + +Future sharedSkSlWriter(Device device, Map? data, { + File? outputFile, + Logger? logger, +}) async { + logger ??= globals.logger; + if (data == null || data.isEmpty) { + logger.printStatus( + 'No data was received. To ensure SkSL data can be generated use a ' + 'physical device then:\n' + ' 1. Pass "--cache-sksl" as an argument to flutter run.\n' + ' 2. Interact with the application to force shaders to be compiled.\n' + ); + return null; + } + if (outputFile == null) { + outputFile = globals.fsUtils.getUniqueFile( + globals.fs.currentDirectory, + 'flutter', + 'sksl.json', + ); + } else if (!outputFile.parent.existsSync()) { + outputFile.parent.createSync(recursive: true); + } + // Convert android sub-platforms to single target platform. + TargetPlatform targetPlatform = await device.targetPlatform; + switch (targetPlatform) { + case TargetPlatform.android_arm: + case TargetPlatform.android_arm64: + case TargetPlatform.android_x64: + case TargetPlatform.android_x86: + targetPlatform = TargetPlatform.android; + case TargetPlatform.android: + case TargetPlatform.darwin: + case TargetPlatform.ios: + case TargetPlatform.fuchsia_arm64: + case TargetPlatform.fuchsia_x64: + case TargetPlatform.linux_arm64: + case TargetPlatform.linux_x64: + case TargetPlatform.tester: + case TargetPlatform.web_javascript: + case TargetPlatform.windows_x64: + break; + } + final Map manifest = { + 'platform': getNameForTargetPlatform(targetPlatform), + 'name': device.name, + 'engineRevision': globals.flutterVersion.engineRevision, + 'data': data, + }; + outputFile.writeAsStringSync(json.encode(manifest)); + logger.printStatus('Wrote SkSL data to ${outputFile.path}.'); + return outputFile.path; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/src/template.dart b/novelforge-project/flutter/packages/flutter_tools/lib/src/template.dart new file mode 100644 index 0000000000000000000000000000000000000000..a6bc9291ca42c5045618ce2568fe31f0400248df --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/src/template.dart @@ -0,0 +1,428 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:file/file.dart'; +import 'package:package_config/package_config.dart'; +import 'package:package_config/package_config_types.dart'; + +import 'base/common.dart'; +import 'base/context.dart'; +import 'base/file_system.dart'; +import 'base/logger.dart'; +import 'base/template.dart'; +import 'cache.dart'; +import 'dart/package_map.dart'; + +/// The Kotlin keywords which are not Java keywords. +/// They are escaped in Kotlin files. +/// +/// https://kotlinlang.org/docs/keyword-reference.html +const List kReservedKotlinKeywords = ['when', 'in', 'is']; + +/// Provides the path where templates used by flutter_tools are stored. +class TemplatePathProvider { + const TemplatePathProvider(); + + /// Returns the directory containing the 'name' template directory. + Directory directoryInPackage(String name, FileSystem fileSystem) { + final String templatesDir = fileSystem.path.join(Cache.flutterRoot!, + 'packages', 'flutter_tools', 'templates'); + return fileSystem.directory(fileSystem.path.join(templatesDir, name)); + } + + /// Returns the directory containing the 'name' template directory in + /// flutter_template_images, to resolve image placeholder against. + /// if 'name' is null, return the parent template directory. + Future imageDirectory(String? name, FileSystem fileSystem, Logger logger) async { + final String toolPackagePath = fileSystem.path.join( + Cache.flutterRoot!, 'packages', 'flutter_tools'); + final String packageFilePath = fileSystem.path.join(toolPackagePath, '.dart_tool', 'package_config.json'); + final PackageConfig packageConfig = await loadPackageConfigWithLogging( + fileSystem.file(packageFilePath), + logger: logger, + ); + final Uri? imagePackageLibDir = packageConfig['flutter_template_images']?.packageUriRoot; + final Directory templateDirectory = fileSystem.directory(imagePackageLibDir) + .parent + .childDirectory('templates'); + return name == null ? templateDirectory : templateDirectory.childDirectory(name); + } +} + +TemplatePathProvider get templatePathProvider => context.get() ?? const TemplatePathProvider(); + +/// Expands templates in a directory to a destination. All files that must +/// undergo template expansion should end with the '.tmpl' extension. All files +/// that should be replaced with the corresponding image from +/// flutter_template_images should end with the '.img.tmpl' extension. All other +/// files are ignored. In case the contents of entire directories must be copied +/// as is, the directory itself can end with '.tmpl' extension. Files within +/// such a directory may also contain the '.tmpl' or '.img.tmpl' extensions and +/// will be considered for expansion. In case certain files need to be copied +/// but without template expansion (data files, etc.), the '.copy.tmpl' +/// extension may be used. Furthermore, templates may contain additional +/// test files intended to run on the CI. Test files must end in `.test.tmpl` +/// and are only included when the --implementation-tests flag is enabled. +/// +/// Folders with platform/language-specific content must be named +/// '-.tmpl'. +/// +/// Files in the destination will contain none of the '.tmpl', '.copy.tmpl', +/// 'img.tmpl', or '-.tmpl' extensions. +class Template { + factory Template(Directory templateSource, Directory? imageSourceDir, { + required FileSystem fileSystem, + required Logger logger, + required TemplateRenderer templateRenderer, + Set? templateManifest, + }) { + return Template._( + [templateSource], + imageSourceDir != null ? [imageSourceDir] : [], + fileSystem: fileSystem, + logger: logger, + templateRenderer: templateRenderer, + templateManifest: templateManifest, + ); + } + + Template._( + List templateSources, this.imageSourceDirectories, { + required FileSystem fileSystem, + required Logger logger, + required TemplateRenderer templateRenderer, + required Set? templateManifest, + }) : _fileSystem = fileSystem, + _logger = logger, + _templateRenderer = templateRenderer, + _templateManifest = templateManifest ?? {} { + for (final Directory sourceDirectory in templateSources) { + if (!sourceDirectory.existsSync()) { + throwToolExit('Template source directory does not exist: ${sourceDirectory.absolute.path}'); + } + } + + final Map templateFiles = { + for (final Directory sourceDirectory in templateSources) + for (final FileSystemEntity entity in sourceDirectory.listSync(recursive: true)) + entity: sourceDirectory, + }; + for (final FileSystemEntity entity in templateFiles.keys.whereType()) { + if (_templateManifest.isNotEmpty && !_templateManifest.contains(Uri.file(entity.absolute.path))) { + _logger.printTrace('Skipping ${entity.absolute.path}, missing from the template manifest.'); + // Skip stale files in the flutter_tools directory. + continue; + } + + final String relativePath = fileSystem.path.relative(entity.path, + from: templateFiles[entity]!.absolute.path); + if (relativePath.contains(templateExtension)) { + // If '.tmpl' appears anywhere within the path of this entity, it is + // a candidate for rendering. This catches cases where the folder + // itself is a template. + _templateFilePaths[relativePath] = fileSystem.path.absolute(entity.path); + } + } + } + + static Future