Remove outdated Fuchsia concepts (#107335)

Fuchsia will soon remove all support for Component Framework version 1
components (recognized by component manifests ending in `.cmx`).
Notably, some of the `flutter` tool commands for Fuchsia devices--
notably, but not limited to, those related to CFv1--are outdated, and
either do not work today or soon won't work.

This PR removes the outdated components and commands, replacing some
with the newer version, or simply removing the non-working features,
in some cases.
This commit is contained in:
Rich Kadel
2022-07-22 16:42:48 -07:00
committed by GitHub
parent a3b531ddc9
commit 549f70c914
22 changed files with 647 additions and 1361 deletions

View File

@@ -14,7 +14,6 @@ import 'build_aar.dart';
import 'build_apk.dart';
import 'build_appbundle.dart';
import 'build_bundle.dart';
import 'build_fuchsia.dart';
import 'build_ios.dart';
import 'build_ios_framework.dart';
import 'build_macos_framework.dart';
@@ -43,7 +42,6 @@ class BuildCommand extends FlutterCommand {
verboseHelp: verboseHelp
));
_addSubcommand(BuildWindowsCommand(verboseHelp: verboseHelp));
_addSubcommand(BuildFuchsiaCommand(verboseHelp: verboseHelp));
}
void _addSubcommand(BuildSubCommand command) {
@@ -83,8 +81,11 @@ abstract class BuildSubCommand extends FlutterCommand {
@protected
void displayNullSafetyMode(BuildInfo buildInfo) {
globals.printStatus('');
if (buildInfo.nullSafetyMode == NullSafetyMode.sound) {
globals.printStatus('💪 Building with sound null safety 💪', emphasis: true);
if (buildInfo.nullSafetyMode == NullSafetyMode.sound) {
globals.printStatus(
'💪 Building with sound null safety 💪',
emphasis: true,
);
} else {
globals.printStatus(
'Building without sound null safety',

View File

@@ -1,88 +0,0 @@
// 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';
import '../cache.dart';
import '../features.dart';
import '../fuchsia/fuchsia_build.dart';
import '../fuchsia/fuchsia_pm.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../runner/flutter_command.dart' show FlutterCommandResult;
import 'build.dart';
/// A command to build a Fuchsia target.
class BuildFuchsiaCommand extends BuildSubCommand {
BuildFuchsiaCommand({
required bool verboseHelp,
}) : super(verboseHelp: verboseHelp) {
addTreeShakeIconsFlag();
usesTargetOption();
usesDartDefineOption();
addBuildModeFlags(verboseHelp: verboseHelp);
addNullSafetyModeOptions(hide: !verboseHelp);
addEnableExperimentation(hide: !verboseHelp);
argParser.addOption(
'runner-source',
help: 'The package source to use for the flutter_runner. '
'"${FuchsiaPackageServer.deviceHost}" implies using a runner already on the device. '
'"${FuchsiaPackageServer.toolHost}" implies using a runner distributed with Flutter.',
allowed: <String>[
FuchsiaPackageServer.deviceHost,
FuchsiaPackageServer.toolHost,
],
defaultsTo: FuchsiaPackageServer.toolHost,
);
argParser.addOption('target-platform',
defaultsTo: 'fuchsia-x64',
allowed: <String>['fuchsia-arm64', 'fuchsia-x64'],
help: 'The target platform for which the app is compiled.',
);
}
@override
final String name = 'fuchsia';
@override
bool hidden = true;
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{
DevelopmentArtifact.fuchsia,
};
@override
String get description => 'Build the Fuchsia target (Experimental).';
@override
bool get supported => globals.platform.isLinux || globals.platform.isMacOS;
@override
Future<FlutterCommandResult> runCommand() async {
if (!featureFlags.isFuchsiaEnabled) {
throwToolExit(
'"build fuchsia" is currently disabled. See "flutter config" for more '
'information.'
);
}
final BuildInfo buildInfo = await getBuildInfo();
final FlutterProject flutterProject = FlutterProject.current();
if (!supported) {
throwToolExit('"build fuchsia" is only supported on Linux and MacOS hosts.');
}
if (!flutterProject.fuchsia.existsSync()) {
throwToolExit('No Fuchsia project is configured.');
}
displayNullSafetyMode(buildInfo);
await buildFuchsia(
fuchsiaProject: flutterProject.fuchsia,
target: targetFile,
targetPlatform: getTargetPlatformForName(stringArgDeprecated('target-platform')!),
buildInfo: buildInfo,
runnerPackageSource: stringArgDeprecated('runner-source')!,
);
return FlutterCommandResult.success();
}
}

View File

@@ -1,230 +0,0 @@
// 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 '../artifacts.dart';
import '../asset.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../bundle_builder.dart';
import '../convert.dart';
import '../devfs.dart';
import '../globals.dart' as globals;
import '../project.dart';
import 'fuchsia_pm.dart';
Future<void> _timedBuildStep(String name, Future<void> Function() action) async {
final Stopwatch sw = Stopwatch()..start();
await action();
globals.printTrace('$name: ${sw.elapsedMilliseconds} ms.');
globals.flutterUsage.sendTiming('build', name, Duration(milliseconds: sw.elapsedMilliseconds));
}
Future<void> _validateCmxFile(FuchsiaProject fuchsiaProject) async {
final String appName = fuchsiaProject.project.manifest.appName;
final String cmxPath = globals.fs.path.join(fuchsiaProject.meta.path, '$appName.cmx');
final File cmxFile = globals.fs.file(cmxPath);
if (!await cmxFile.exists()) {
throwToolExit('The Fuchsia build requires a .cmx file at $cmxPath for the app: $appName.');
}
}
// Building a Fuchsia package has a few steps:
// 1. Do the custom kernel compile using the kernel compiler from the Fuchsia
// SDK. This produces .dilp files (among others) and a manifest file.
// 2. Create a manifest file for assets.
// 3. Using these manifests, use the Fuchsia SDK 'pm' tool to create the
// Fuchsia package.
Future<void> buildFuchsia({
required FuchsiaProject fuchsiaProject,
required TargetPlatform targetPlatform,
String? target, // E.g., lib/main.dart
BuildInfo buildInfo = BuildInfo.debug,
String runnerPackageSource = FuchsiaPackageServer.toolHost,
}) async {
final String targetPath = target ??= 'lib/main.dart';
await _validateCmxFile(fuchsiaProject);
final Directory outDir = globals.fs.directory(getFuchsiaBuildDirectory());
if (!outDir.existsSync()) {
outDir.createSync(recursive: true);
}
await _timedBuildStep('fuchsia-kernel-compile',
() => globals.fuchsiaSdk!.fuchsiaKernelCompiler.build(
fuchsiaProject: fuchsiaProject, target: targetPath, buildInfo: buildInfo));
if (buildInfo.usesAot) {
await _timedBuildStep('fuchsia-gen-snapshot',
() => _genSnapshot(fuchsiaProject, targetPath, buildInfo, targetPlatform));
}
await _timedBuildStep('fuchsia-build-assets',
() => _buildAssets(fuchsiaProject, targetPath, buildInfo));
await _timedBuildStep('fuchsia-build-package',
() => _buildPackage(fuchsiaProject, targetPath, buildInfo, runnerPackageSource));
}
Future<void> _genSnapshot(
FuchsiaProject fuchsiaProject,
String target, // lib/main.dart
BuildInfo buildInfo,
TargetPlatform targetPlatform,
) async {
final String outDir = getFuchsiaBuildDirectory();
final String appName = fuchsiaProject.project.manifest.appName;
final String dilPath = globals.fs.path.join(outDir, '$appName.dil');
final String elf = globals.fs.path.join(outDir, 'elf.aotsnapshot');
final String genSnapshot = globals.artifacts!.getArtifactPath(
Artifact.genSnapshot,
platform: targetPlatform,
mode: buildInfo.mode,
);
final List<String> command = <String>[
genSnapshot,
'--deterministic',
'--snapshot_kind=app-aot-elf',
'--elf=$elf',
if (buildInfo.isDebug) '--enable-asserts',
dilPath,
];
int result;
final Status status = globals.logger.startProgress(
'Compiling Fuchsia application to native code...',
);
try {
result = await globals.processUtils.stream(command, trace: true);
} finally {
status.cancel();
}
if (result != 0) {
throwToolExit('Build process failed');
}
}
Future<void> _buildAssets(
FuchsiaProject fuchsiaProject,
String target, // lib/main.dart
BuildInfo buildInfo,
) async {
final String assetDir = getAssetBuildDirectory();
final AssetBundle? assets = await buildAssets(
manifestPath: fuchsiaProject.project.pubspecFile.path,
packagesPath: fuchsiaProject.project.packagesFile.path,
assetDirPath: assetDir,
);
if (assets == null) {
throwToolExit('Unable to find assets.', exitCode: 1);
}
final Map<String, DevFSContent> assetEntries = Map<String, DevFSContent>.of(
assets.entries,
);
await writeBundle(globals.fs.directory(assetDir), assetEntries, assets.entryKinds);
final String appName = fuchsiaProject.project.manifest.appName;
final String outDir = getFuchsiaBuildDirectory();
final String assetManifest = globals.fs.path.join(outDir, '${appName}_pkgassets');
final File destFile = globals.fs.file(assetManifest);
await destFile.create(recursive: true);
final IOSink outFile = destFile.openWrite();
for (final String path in assets.entries.keys) {
outFile.write('data/$appName/$path=$assetDir/$path\n');
}
await outFile.flush();
await outFile.close();
}
void _rewriteCmx(BuildMode mode, String runnerPackageSource, File src, File dst) {
final Map<String, Object?> cmx = castStringKeyedMap(json.decode(src.readAsStringSync())) ?? <String, Object?>{};
// If the app author has already specified the runner in the cmx file, then
// do not override it with something else.
if (cmx.containsKey('runner')) {
dst.writeAsStringSync(json.encode(cmx));
return;
}
String runner;
switch (mode) {
case BuildMode.debug:
runner = 'flutter_jit_runner';
break;
case BuildMode.profile:
runner = 'flutter_aot_runner';
break;
case BuildMode.jitRelease:
runner = 'flutter_jit_product_runner';
break;
case BuildMode.release:
runner = 'flutter_aot_product_runner';
break;
default:
throwToolExit('Fuchsia does not support build mode "$mode"');
}
cmx['runner'] = 'fuchsia-pkg://$runnerPackageSource/$runner#meta/$runner.cmx';
dst.writeAsStringSync(json.encode(cmx));
}
// TODO(zanderso): Allow supplying a signing key.
Future<void> _buildPackage(
FuchsiaProject fuchsiaProject,
String target, // lib/main.dart
BuildInfo buildInfo,
String runnerPackageSource,
) async {
final String outDir = getFuchsiaBuildDirectory();
final String pkgDir = globals.fs.path.join(outDir, 'pkg');
final String appName = fuchsiaProject.project.manifest.appName;
final String pkgassets = globals.fs.path.join(outDir, '${appName}_pkgassets');
final String packageManifest = globals.fs.path.join(pkgDir, 'package_manifest');
final Directory pkg = globals.fs.directory(pkgDir);
if (!pkg.existsSync()) {
pkg.createSync(recursive: true);
}
final File srcCmx =
globals.fs.file(globals.fs.path.join(fuchsiaProject.meta.path, '$appName.cmx'));
final File dstCmx = globals.fs.file(globals.fs.path.join(outDir, '$appName.cmx'));
_rewriteCmx(buildInfo.mode, runnerPackageSource, srcCmx, dstCmx);
final File manifestFile = globals.fs.file(packageManifest);
if (buildInfo.usesAot) {
final String elf = globals.fs.path.join(outDir, 'elf.aotsnapshot');
manifestFile.writeAsStringSync(
'data/$appName/app_aot_snapshot.so=$elf\n');
} else {
final String dilpmanifest = globals.fs.path.join(outDir, '$appName.dilpmanifest');
manifestFile.writeAsStringSync(globals.fs.file(dilpmanifest).readAsStringSync());
}
manifestFile.writeAsStringSync(globals.fs.file(pkgassets).readAsStringSync(),
mode: FileMode.append);
manifestFile.writeAsStringSync('meta/$appName.cmx=${dstCmx.path}\n',
mode: FileMode.append);
manifestFile.writeAsStringSync('meta/package=$pkgDir/meta/package\n',
mode: FileMode.append);
final FuchsiaPM? fuchsiaPM = globals.fuchsiaSdk?.fuchsiaPM;
if (fuchsiaPM == null) {
return;
}
if (!await fuchsiaPM.init(pkgDir, appName)) {
return;
}
if (!await fuchsiaPM.build(pkgDir, packageManifest)) {
return;
}
if (!await fuchsiaPM.archive(pkgDir, packageManifest)) {
return;
}
}

View File

@@ -23,16 +23,15 @@ import '../device.dart';
import '../device_port_forwarder.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../runner/flutter_command.dart';
import '../vmservice.dart';
import 'application_package.dart';
import 'fuchsia_build.dart';
import 'fuchsia_ffx.dart';
import 'fuchsia_pm.dart';
import 'fuchsia_sdk.dart';
import 'fuchsia_workflow.dart';
import 'pkgctl.dart';
import 'session_control.dart';
import 'tiles_ctl.dart';
/// The [FuchsiaDeviceTools] instance.
FuchsiaDeviceTools get fuchsiaDeviceTools => context.get<FuchsiaDeviceTools>()!;
@@ -40,8 +39,7 @@ FuchsiaDeviceTools get fuchsiaDeviceTools => context.get<FuchsiaDeviceTools>()!;
/// Fuchsia device-side tools.
class FuchsiaDeviceTools {
late final FuchsiaPkgctl pkgctl = FuchsiaPkgctl();
late final FuchsiaTilesCtl tilesCtl = FuchsiaTilesCtl();
late final FuchsiaSessionControl sessionControl = FuchsiaSessionControl();
late final FuchsiaFfx ffx = FuchsiaFfx();
}
final String _ipv4Loopback = InternetAddress.loopbackIPv4.address;
@@ -100,7 +98,7 @@ class _FuchsiaLogReader extends DeviceLogReader {
final ApplicationPackage? app = _app;
final RegExp matchRegExp = app == null
? _flutterLogOutput
: RegExp('INFO: ${app.name}(\\.cmx)?\\(flutter\\): ');
: RegExp('INFO: ${app.name}(\\.cm)?\\(flutter\\): ');
return Stream<String>.eventTransformed(
lines,
(EventSink<String> output) => _FuchsiaLogSink(output, matchRegExp, startTime),
@@ -212,7 +210,7 @@ class FuchsiaDevices extends PollingDeviceDiscovery {
}
final String name = words[1];
// TODO(omerlevran): Add support for resolve on the FuchsiaSdk Object.
// TODO(omerlevran): Add support for resolve on the FuchsiaSdk Object.
final String? resolvedHost = await _fuchsiaSdk.fuchsiaFfx.resolve(name);
if (resolvedHost == null) {
_logger.printError('Failed to resolve host for Fuchsia device `$name`');
@@ -225,13 +223,13 @@ class FuchsiaDevices extends PollingDeviceDiscovery {
List<String> get wellKnownIds => const <String>[];
}
class FuchsiaDevice extends Device {
FuchsiaDevice(super.id, {required this.name}) : super(
platformType: PlatformType.fuchsia,
category: null,
ephemeral: true,
);
FuchsiaDevice(super.id, {required this.name})
: super(
platformType: PlatformType.fuchsia,
category: null,
ephemeral: true,
);
@override
bool get supportsHotReload => true;
@@ -258,14 +256,11 @@ class FuchsiaDevice extends Device {
/// Determine if the Fuchsia device is running a session based build.
///
/// If the device is running a session based build, `session_control` should be
/// used to launch apps, otherwise `tiles_ctl` should be used.
/// If the device is running a session based build, `ffx session` should be
/// used to launch apps. Fuchsia flutter apps cannot currently be launched
/// without a session.
Future<bool> _initIsSession() async {
final RunResult result = await shell('which session_control');
if (result.exitCode != 0) {
return false;
}
return true;
return await globals.fuchsiaSdk?.fuchsiaFfx.sessionShow() != null;
}
@override
@@ -293,7 +288,8 @@ class FuchsiaDevice extends Device {
bool isSupported() => true;
@override
bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease;
bool supportsRuntimeMode(BuildMode buildMode) =>
buildMode != BuildMode.jitRelease;
@override
Future<LaunchResult> startApp(
@@ -313,10 +309,11 @@ class FuchsiaDevice extends Device {
}
if (!prebuiltApplication) {
await buildFuchsia(fuchsiaProject: FlutterProject.current().fuchsia,
targetPlatform: await targetPlatform,
target: mainPath,
buildInfo: debuggingOptions.buildInfo);
throwToolExit(
'This tool does not currently build apps for fuchsia.\n'
'Build the app using a supported Fuchsia workflow.\n'
'Then use the --${FlutterOptions.kUseApplicationBinary} flag.'
);
}
// Stop the app if it's currently running.
await stopApp(package);
@@ -330,8 +327,8 @@ class FuchsiaDevice extends Device {
// Try Start with a fresh package repo in case one was left over from a
// previous run.
final Directory packageRepo =
globals.fs.directory(globals.fs.path.join(getFuchsiaBuildDirectory(), '.pkg-repo'));
final Directory packageRepo = globals.fs.directory(
globals.fs.path.join(getFuchsiaBuildDirectory(), '.pkg-repo'));
try {
if (packageRepo.existsSync()) {
packageRepo.deleteSync(recursive: true);
@@ -339,7 +336,7 @@ class FuchsiaDevice extends Device {
packageRepo.createSync(recursive: true);
} on Exception catch (e) {
globals.printError('Failed to create Fuchsia package repo directory '
'at ${packageRepo.path}: $e');
'at ${packageRepo.path}: $e');
return LaunchResult.failed();
}
@@ -419,29 +416,20 @@ class FuchsiaDevice extends Device {
return LaunchResult.failed();
}
fuchsiaUrl =
'fuchsia-pkg://$packageServerName/$appName#meta/$appName.cmx';
fuchsiaUrl = 'fuchsia-pkg://$packageServerName/$appName#meta/$appName.cm';
if (await isSession) {
// Instruct session_control to start the app
if (!await fuchsiaDeviceTools.sessionControl.add(this, fuchsiaUrl)) {
globals.printError('Failed to add the app to session_control');
// Instruct ffx session to start the app
final bool addedApp =
await globals.fuchsiaSdk?.fuchsiaFfx.sessionAdd(fuchsiaUrl) ?? false;
if (!addedApp) {
globals.printError('Failed to add the app via `ffx session add`');
return LaunchResult.failed();
}
} else {
// Ensure tiles_ctl is started, and start the app.
if (!await FuchsiaTilesCtl.ensureStarted(this)) {
globals.printError(
'Failed to ensure that tiles is started on the device');
return LaunchResult.failed();
}
// Instruct tiles_ctl to start the app.
if (!await fuchsiaDeviceTools.tilesCtl
.add(this, fuchsiaUrl, <String>[])) {
globals.printError('Failed to add the app to tiles');
return LaunchResult.failed();
}
globals.printError(
'Fuchsia flutter apps can only be launched within a session');
return LaunchResult.failed();
}
} finally {
// Try to un-teach the package controller about the package server if
@@ -491,13 +479,8 @@ class FuchsiaDevice extends Device {
// using the session framework afaik. So this is a no-op.
return true;
}
final int appKey = await FuchsiaTilesCtl.findAppKey(this, app.id);
if (appKey != -1) {
if (!await fuchsiaDeviceTools.tilesCtl.remove(this, appKey)) {
globals.printError('tiles_ctl remove on ${app.id} failed.');
return false;
}
}
// Fuchsia flutter apps currently require a session, but if that changes,
// add the relevant "stopApp" code here.
return true;
}
@@ -537,12 +520,15 @@ class FuchsiaDevice extends Device {
if (outputFile.basename.split('.').last != 'ppm') {
throw Exception('${outputFile.path} must be a .ppm file');
}
final RunResult screencapResult = await shell('screencap > /tmp/screenshot.ppm');
final RunResult screencapResult =
await shell('screencap > /tmp/screenshot.ppm');
if (screencapResult.exitCode != 0) {
throw Exception('Could not take a screenshot on device $name:\n$screencapResult');
throw Exception(
'Could not take a screenshot on device $name:\n$screencapResult');
}
try {
final RunResult scpResult = await scp('/tmp/screenshot.ppm', outputFile.path);
final RunResult scpResult =
await scp('/tmp/screenshot.ppm', outputFile.path);
if (scpResult.exitCode != 0) {
throw Exception('Failed to copy screenshot from device:\n$scpResult');
}
@@ -551,13 +537,11 @@ class FuchsiaDevice extends Device {
final RunResult deleteResult = await shell('rm /tmp/screenshot.ppm');
if (deleteResult.exitCode != 0) {
globals.printError(
'Failed to delete screenshot.ppm from the device:\n$deleteResult'
);
'Failed to delete screenshot.ppm from the device:\n$deleteResult');
}
} on Exception catch (e) {
globals.printError(
'Failed to delete screenshot.ppm from the device: $e'
);
globals
.printError('Failed to delete screenshot.ppm from the device: $e');
}
}
}
@@ -570,7 +554,7 @@ class FuchsiaDevice extends Device {
const String defaultName = 'Fuchsia';
if (!globals.fuchsiaArtifacts!.hasSshConfig) {
globals.printTrace('Could not determine Fuchsia sdk name or version '
'because Fuchsia ssh configuration is missing.');
'because Fuchsia ssh configuration is missing.');
return defaultName;
}
const String versionPath = '/pkgfs/packages/build-info/0/data/version';
@@ -595,6 +579,7 @@ class FuchsiaDevice extends Device {
assert(!includePastLogs, 'Past log reading not supported on Fuchsia.');
return _logReader ??= _FuchsiaLogReader(this, globals.systemClock, app);
}
_FuchsiaLogReader? _logReader;
@override
@@ -620,6 +605,7 @@ class FuchsiaDevice extends Device {
void fail() {
throwToolExit('Failed to get local address, aborting.\n$result');
}
if (result.exitCode != 0) {
fail();
}
@@ -639,7 +625,8 @@ class FuchsiaDevice extends Device {
const String findCommand = 'find /hub -name vmservice-port';
final RunResult findResult = await shell(findCommand);
if (findResult.exitCode != 0) {
throwToolExit("'$findCommand' on device $name failed. stderr: '${findResult.stderr}'");
throwToolExit(
"'$findCommand' on device $name failed. stderr: '${findResult.stderr}'");
}
final String findOutput = findResult.stdout;
if (findOutput.trim() == '') {
@@ -675,7 +662,7 @@ class FuchsiaDevice extends Device {
final File? sshConfig = globals.fuchsiaArtifacts?.sshConfig;
if (sshConfig == null) {
throwToolExit('Cannot interact with device. No ssh config.\n'
'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
}
return globals.processUtils.run(<String>[
'ssh',
@@ -691,7 +678,7 @@ class FuchsiaDevice extends Device {
final File? sshConfig = globals.fuchsiaArtifacts!.sshConfig;
if (sshConfig == null) {
throwToolExit('Cannot interact with device. No ssh config.\n'
'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
}
return globals.processUtils.run(<String>[
'scp',
@@ -714,15 +701,18 @@ class FuchsiaDevice extends Device {
// netstat shows that the local port is actually being used on the IPv6
// loopback (::1).
final Uri uri = Uri.parse('http://[$_ipv6Loopback]:$port');
final FlutterVmService vmService = await connectToVmService(uri, logger: globals.logger);
final List<FlutterView> flutterViews = await vmService.getFlutterViews();
final FlutterVmService vmService =
await connectToVmService(uri, logger: globals.logger);
final List<FlutterView> flutterViews =
await vmService.getFlutterViews();
for (final FlutterView flutterView in flutterViews) {
final vm_service.IsolateRef? uiIsolate = flutterView.uiIsolate;
if (uiIsolate == null) {
continue;
}
final int? port = vmService.httpAddress?.port;
if (port != null && (uiIsolate.name?.contains(isolateName) ?? false)) {
if (port != null &&
(uiIsolate.name?.contains(isolateName) ?? false)) {
return port;
}
}
@@ -733,7 +723,8 @@ class FuchsiaDevice extends Device {
throwToolExit('No ports found running $isolateName');
}
FuchsiaIsolateDiscoveryProtocol getIsolateDiscoveryProtocol(String isolateName) {
FuchsiaIsolateDiscoveryProtocol getIsolateDiscoveryProtocol(
String isolateName) {
return FuchsiaIsolateDiscoveryProtocol(this, isolateName);
}
@@ -776,7 +767,7 @@ class FuchsiaIsolateDiscoveryProtocol {
_status ??= globals.logger.startProgress(
'Waiting for a connection from $_isolateName on ${_device.name}...',
);
unawaited(_findIsolate()); // Completes the _foundUri Future.
unawaited(_findIsolate()); // Completes the _foundUri Future.
return _foundUri.future.then((Uri uri) {
_uri = uri;
return uri;
@@ -813,7 +804,8 @@ class FuchsiaIsolateDiscoveryProtocol {
continue;
}
}
final List<FlutterView> flutterViews = await service?.getFlutterViews() ?? <FlutterView>[];
final List<FlutterView> flutterViews =
await service?.getFlutterViews() ?? <FlutterView>[];
for (final FlutterView flutterView in flutterViews) {
final vm_service.IsolateRef? uiIsolate = flutterView.uiIsolate;
if (uiIsolate == null) {
@@ -848,7 +840,8 @@ class _FuchsiaPortForwarder extends DevicePortForwarder {
Future<int> forward(int devicePort, {int? hostPort}) async {
hostPort ??= await globals.os.findFreePort();
if (hostPort == 0) {
throwToolExit('Failed to forward port $devicePort. No free host-side ports');
throwToolExit(
'Failed to forward port $devicePort. No free host-side ports');
}
final File? sshConfig = globals.fuchsiaArtifacts?.sshConfig;
if (sshConfig == null) {
@@ -911,7 +904,7 @@ class _FuchsiaPortForwarder extends DevicePortForwarder {
throwToolExit(
'Unforward command failed:\n'
'stdout: ${result.stdout}\n'
'stderr: ${result.stderr}'
'stderr: ${result.stderr}',
);
}
}
@@ -919,7 +912,7 @@ class _FuchsiaPortForwarder extends DevicePortForwarder {
@override
Future<void> dispose() async {
final List<ForwardedPort> forwardedPortsCopy =
List<ForwardedPort>.of(forwardedPorts);
List<ForwardedPort>.of(forwardedPorts);
for (final ForwardedPort port in forwardedPortsCopy) {
await unforward(port);
}

View File

@@ -8,6 +8,7 @@ import 'package:process/process.dart';
import '../base/common.dart';
import '../base/logger.dart';
import '../base/process.dart';
import '../globals.dart' as globals;
import 'fuchsia_sdk.dart';
// Usage: ffx [-c <config>] [-e <env>] [-t <target>] [-T <timeout>] [-v] [<command>] [<args>]
@@ -26,17 +27,21 @@ import 'fuchsia_sdk.dart';
// config View and switch default and user configurations
// daemon Interact with/control the ffx daemon
// target Interact with a target device or emulator
// session Control the current session. See
// https://fuchsia.dev/fuchsia-src/concepts/session/introduction
// for details.
/// A simple wrapper for the Fuchsia SDK's 'ffx' tool.
class FuchsiaFfx {
FuchsiaFfx({
required FuchsiaArtifacts? fuchsiaArtifacts,
required Logger logger,
required ProcessManager processManager,
}) : _fuchsiaArtifacts = fuchsiaArtifacts,
_logger = logger,
_processUtils =
ProcessUtils(logger: logger, processManager: processManager);
FuchsiaArtifacts? fuchsiaArtifacts,
Logger? logger,
ProcessManager? processManager,
}) : _fuchsiaArtifacts = fuchsiaArtifacts ?? globals.fuchsiaArtifacts,
_logger = logger ?? globals.logger,
_processUtils = ProcessUtils(
logger: logger ?? globals.logger,
processManager: processManager ?? globals.processManager);
final FuchsiaArtifacts? _fuchsiaArtifacts;
final Logger _logger;
@@ -53,8 +58,7 @@ class FuchsiaFfx {
}
final List<String> command = <String>[
ffx.path,
if (timeout != null)
...<String>['-T', '${timeout.inSeconds}'],
if (timeout != null) ...<String>['-T', '${timeout.inSeconds}'],
'target',
'list',
// TODO(akbiggs): Revert -f back to --format once we've verified that
@@ -97,4 +101,50 @@ class FuchsiaFfx {
}
return result.stdout.trim();
}
/// Show information about the current session
///
/// Returns `null` if the command failed, which can be interpreted as there is
/// no usable session.
Future<String?> sessionShow() async {
final File? ffx = _fuchsiaArtifacts?.ffx;
if (ffx == null || !ffx.existsSync()) {
throwToolExit('Fuchsia ffx tool not found.');
}
final List<String> command = <String>[
ffx.path,
'session',
'show',
];
final RunResult result = await _processUtils.run(command);
if (result.exitCode != 0) {
_logger.printError('ffx failed: ${result.stderr}');
return null;
}
return result.stdout;
}
/// Add an element to the current session
///
/// [url] should be formatted as a Fuchsia-style package URL, e.g.:
/// fuchsia-pkg://fuchsia.com/flutter_gallery#meta/flutter_gallery.cmx
/// Returns true on success and false on failure.
Future<bool> sessionAdd(String url) async {
final File? ffx = _fuchsiaArtifacts?.ffx;
if (ffx == null || !ffx.existsSync()) {
throwToolExit('Fuchsia ffx tool not found.');
}
final List<String> command = <String>[
ffx.path,
'session',
'add',
url,
];
final RunResult result = await _processUtils.run(command);
if (result.exitCode != 0) {
_logger.printError('ffx failed: ${result.stderr}');
return false;
}
return true;
}
}

View File

@@ -41,7 +41,7 @@ class FuchsiaPM {
/// which describe the contents of the Fuchsia package. It must also contain
/// two other entries:
///
/// meta/$APPNAME.cmx=/path/to/cmx/on/the/host/$APPNAME.cmx
/// meta/$APPNAME.cm=/path/to/cm/on/the/host/$APPNAME.cm
/// meta/package=/path/to/package/file/from/init/package
///
/// where $APPNAME is the same [appName] passed to [init], and meta/package
@@ -232,12 +232,14 @@ class FuchsiaPackageServer {
if (_process == null) {
return false;
}
return (await globals.fuchsiaSdk?.fuchsiaPM.publish(_repo, package.path)) ?? false;
return (await globals.fuchsiaSdk?.fuchsiaPM.publish(_repo, package.path)) ??
false;
}
@override
String toString() {
final String p = (_process == null) ? 'stopped' : 'running ${_process?.pid}';
final String p =
(_process == null) ? 'stopped' : 'running ${_process?.pid}';
return 'FuchsiaPackageServer at $_host:$_port ($p)';
}
}

View File

@@ -31,11 +31,7 @@ class FuchsiaSdk {
late final FuchsiaKernelCompiler fuchsiaKernelCompiler = FuchsiaKernelCompiler();
/// Interface to the 'ffx' tool.
late final FuchsiaFfx fuchsiaFfx = FuchsiaFfx(
fuchsiaArtifacts: globals.fuchsiaArtifacts,
logger: globals.logger,
processManager: globals.processManager,
);
late final FuchsiaFfx fuchsiaFfx = FuchsiaFfx();
/// Returns any attached devices is a newline-denominated String.
///

View File

@@ -1,54 +0,0 @@
// 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/process.dart';
import 'fuchsia_device.dart';
// Usage: session_control <command> [<args>]
//
// Various operations to control sessions.
//
// Options:
// --help display usage information
//
// Commands:
// launch Launch a new session.
// restart Restart the current session.
// add Add an element to the current session.
//
// Usage: session_control launch <session_url>
//
// Launch a new session.
//
// Options:
// --help display usage information
//
// Usage: session_control restart
//
// Restart the current session.
//
// Options:
// --help display usage information
//
//
// Usage: session_control add <element_url>
//
// Add an element to the current session.
//
// Options:
// --help display usage information
/// A simple wrapper around the 'session_control' tool running on the Fuchsia device.
class FuchsiaSessionControl {
/// Instructs session_control on the device to add the app at [url] as an element.
///
/// [url] should be formatted as a Fuchsia-style package URL, e.g.:
/// fuchsia-pkg://fuchsia.com/flutter_gallery#meta/flutter_gallery.cmx
/// Returns true on success and false on failure.
Future<bool> add(FuchsiaDevice device, String url) async {
final RunResult result = await device.shell('session_control add $url');
return result.exitCode == 0;
}
}

View File

@@ -1,115 +0,0 @@
// 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/process.dart';
import '../globals.dart' as globals;
import 'fuchsia_device.dart';
// Usage: tiles_ctl <command>
// Supported commands:
// start
// add [--disable-focus] <url> [<args>...]
// remove <key>
// list
// quit
/// A simple wrapper around the 'tiles_ctl' tool running on the Fuchsia device.
class FuchsiaTilesCtl {
/// Finds the key for the app called [appName], or returns -1 if it can't be
/// found.
static Future<int> findAppKey(FuchsiaDevice device, String appName) async {
final FuchsiaTilesCtl tilesCtl = fuchsiaDeviceTools.tilesCtl;
final Map<int, String>? runningApps = await tilesCtl.list(device);
if (runningApps == null) {
globals.printTrace('tiles_ctl is not running');
return -1;
}
for (final MapEntry<int, String> entry in runningApps.entries) {
if (entry.value.contains('$appName#meta')) {
return entry.key;
}
}
return -1;
}
/// Ensures that tiles is running on the device.
static Future<bool> ensureStarted(FuchsiaDevice device) async {
final FuchsiaTilesCtl tilesCtl = fuchsiaDeviceTools.tilesCtl;
final Map<int, String>? runningApps = await tilesCtl.list(device);
if (runningApps == null) {
return tilesCtl.start(device);
}
return true;
}
/// Instructs 'tiles' to start on the device.
///
/// Returns true on success and false on failure.
Future<bool> start(FuchsiaDevice device) async {
final RunResult result = await device.shell('tiles_ctl start');
return result.exitCode == 0;
}
/// Returns a mapping of tile keys to app URLs.
///
/// Returns an empty mapping if tiles_ctl is running but no apps are running.
/// Returns null if tiles_ctl is not running.
Future<Map<int, String>?> list(FuchsiaDevice device) async {
// Output of tiles_ctl list has the format:
// Found 1 tiles:
// Tile key 1 url fuchsia-pkg://fuchsia.com/stocks#meta/stocks.cmx ...
final Map<int, String> tiles = <int, String>{};
final RunResult result = await device.shell('tiles_ctl list');
if (result.exitCode != 0) {
return null;
}
// Look for evidence that tiles_ctl is not running.
if (result.stdout.contains("Couldn't find tiles component in realm")) {
return null;
}
// Find lines beginning with 'Tile'
for (final String line in result.stdout.split('\n')) {
final List<String> words = line.split(' ');
if (words.isNotEmpty && words[0] == 'Tile') {
final int? key = int.tryParse(words[2]);
if (key != null) {
final String url = words[4];
tiles[key] = url;
}
}
}
return tiles;
}
/// Instructs tiles on the device to begin running the app at [url] in a new
/// tile.
///
/// The app is passed the arguments in [args]. Flutter apps receive these
/// arguments as arguments to `main()`. [url] should be formatted as a
/// Fuchsia-style package URL, e.g.:
/// fuchsia-pkg://fuchsia.com/flutter_gallery#meta/flutter_gallery.cmx
/// Returns true on success and false on failure.
Future<bool> add(FuchsiaDevice device, String url, List<String> args) async {
final RunResult result = await device.shell(
'tiles_ctl add $url ${args.join(" ")}');
return result.exitCode == 0;
}
/// Instructs tiles on the device to remove the app with key [key].
///
/// Returns true on success and false on failure.
Future<bool> remove(FuchsiaDevice device, int key) async {
final RunResult result = await device.shell('tiles_ctl remove $key');
return result.exitCode == 0;
}
/// Instructs tiles on the device to quit.
///
/// Returns true on success and false on failure.
Future<bool> quit(FuchsiaDevice device) async {
final RunResult result = await device.shell('tiles_ctl quit');
return result.exitCode == 0;
}
}