From a285de2ab2a6947f8cd02df6ea74b4f93534bef7 Mon Sep 17 00:00:00 2001 From: Jason Huang Date: Mon, 2 Jun 2025 11:49:51 +0800 Subject: [PATCH 1/5] release: upgrade to flutter 3.29.3 and add new author The release artifacts for Flutter 3.29.2 have been removed from GitHub --- AUTHORS | 1 + bin/internal/engine.version | 2 +- bin/internal/flutter.version | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/AUTHORS b/AUTHORS index 4086612..90592cb 100644 --- a/AUTHORS +++ b/AUTHORS @@ -11,3 +11,4 @@ Taha Firoz (mtahafiroz@gmail.com) Weiwei Duan (duanweiwei1982@gmail.com) Anton Sakhon (kofhein@gmail.com) Burak Karahan (burak.karahan@mail.ru) +Jason Huang (zxcv1884@gmail.com) diff --git a/bin/internal/engine.version b/bin/internal/engine.version index 309ba6c..f05b7a4 100644 --- a/bin/internal/engine.version +++ b/bin/internal/engine.version @@ -1 +1 @@ -18b71d647a292a980abb405ac7d16fe1f0b20434 +cf56914b326edb0ccb123ffdc60f00060bd513fa diff --git a/bin/internal/flutter.version b/bin/internal/flutter.version index 5ae9238..44eff10 100644 --- a/bin/internal/flutter.version +++ b/bin/internal/flutter.version @@ -1,2 +1,2 @@ -c23637390482d4cf9598c3ce3f2be31aa7332daf -3.29.2 +ea121f8859e4b13e47a8f845e4586164519588bc +3.29.3 From 1fec5017ff882ab870a24805b8ae996fa72761ef Mon Sep 17 00:00:00 2001 From: Jason Huang Date: Mon, 2 Jun 2025 11:51:58 +0800 Subject: [PATCH 2/5] fix: stub provideVmService to avoid UnimplementedError flutter run was crashing on eLinux because provideVmService threw UnimplementedError. Replaced it with an empty async method body (`{}`) to prevent the crash. --- lib/elinux_device.dart | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/elinux_device.dart b/lib/elinux_device.dart index b4602d8..202f616 100644 --- a/lib/elinux_device.dart +++ b/lib/elinux_device.dart @@ -522,7 +522,5 @@ class ELinuxLogReader extends DeviceLogReader { void dispose() {} @override - Future provideVmService(FlutterVmService connectedVmService) { - throw UnimplementedError(); - } + Future provideVmService(FlutterVmService? connectedVmService) async {} } From 014a0abd881908cf4ae62f944df5d4363836e28b Mon Sep 17 00:00:00 2001 From: Jason Huang Date: Mon, 2 Jun 2025 17:48:11 +0800 Subject: [PATCH 3/5] chore: format code --- lib/elinux_doctor.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/elinux_doctor.dart b/lib/elinux_doctor.dart index a419ff5..6681cd0 100644 --- a/lib/elinux_doctor.dart +++ b/lib/elinux_doctor.dart @@ -206,7 +206,7 @@ class ELinuxValidator extends DoctorValidator { } return (result?.exitCode ?? 1) == 0; } - + @override Future validateImpl() { throw UnimplementedError(); From b263ef0d691e411b4b691b953a160ad704b29d89 Mon Sep 17 00:00:00 2001 From: Jason Huang Date: Thu, 5 Jun 2025 16:27:07 +0800 Subject: [PATCH 4/5] chore: format code --- lib/commands/build.dart | 18 +-- lib/commands/create.dart | 17 +-- lib/commands/drive.dart | 3 +- lib/commands/packages.dart | 48 +++---- lib/commands/run.dart | 9 +- lib/commands/upgrade.dart | 46 +++---- lib/elinux_artifacts.dart | 7 +- lib/elinux_build_target.dart | 126 +++++++----------- lib/elinux_builder.dart | 35 ++--- lib/elinux_cache.dart | 19 +-- lib/elinux_cmake_project.dart | 18 +-- lib/elinux_device.dart | 60 +++------ lib/elinux_device_discovery.dart | 9 +- lib/elinux_doctor.dart | 46 +++---- lib/elinux_package.dart | 3 +- lib/elinux_plugins.dart | 110 +++++---------- lib/elinux_remote_device_config.dart | 45 +++---- lib/elinux_remote_devices_config.dart | 17 +-- lib/executable.dart | 6 +- lib/vscode_helper.dart | 21 +-- .../lib/src/rendering/platform_view.dart | 6 +- .../lib/src/services/platform_views.dart | 124 ++++++----------- .../lib/src/widgets/platform_view.dart | 30 ++--- 23 files changed, 291 insertions(+), 532 deletions(-) diff --git a/lib/commands/build.dart b/lib/commands/build.dart index 55052c6..a815743 100644 --- a/lib/commands/build.dart +++ b/lib/commands/build.dart @@ -34,8 +34,7 @@ class ELinuxBuildCommand extends BuildCommand { } } -class BuildPackageCommand extends BuildSubCommand - with ELinuxExtension, ELinuxRequiredArtifacts { +class BuildPackageCommand extends BuildSubCommand with ELinuxExtension, ELinuxRequiredArtifacts { /// See: [BuildApkCommand] in `build_apk.dart` BuildPackageCommand({bool verboseHelp = false}) : super( @@ -73,8 +72,7 @@ class BuildPackageCommand extends BuildSubCommand ); argParser.addOption( 'system-include-directories', - help: - 'The additional system include paths to cross-compile for target platform. ' + help: 'The additional system include paths to cross-compile for target platform. ' 'This option is valid only ' 'if the current host and target architectures are different.', ); @@ -88,13 +86,11 @@ class BuildPackageCommand extends BuildSubCommand final String name = 'elinux'; @override - Future> get requiredArtifacts async => - { + Future> get requiredArtifacts async => { // Use gen_snapshot of the arm64 linux-desktop when self-building // on arm64 hosts. This is because elinux's artifacts for arm64 // doesn't support self-build as of now. - if (_getCurrentHostPlatformArchName() == 'arm64') - DevelopmentArtifact.linux, + if (_getCurrentHostPlatformArchName() == 'arm64') DevelopmentArtifact.linux, ELinuxDevelopmentArtifact.elinux, }; @@ -103,8 +99,7 @@ class BuildPackageCommand extends BuildSubCommand /// See: [android.validateBuild] in `build_validation.dart` void validateBuild(ELinuxBuildInfo eLinuxBuildInfo) { - if (eLinuxBuildInfo.buildInfo.mode.isPrecompiled && - eLinuxBuildInfo.targetArch == 'x86') { + if (eLinuxBuildInfo.buildInfo.mode.isPrecompiled && eLinuxBuildInfo.targetArch == 'x86') { throwToolExit('x86 ABI does not support AOT compilation.'); } } @@ -116,8 +111,7 @@ class BuildPackageCommand extends BuildSubCommand final String? targetArch = stringArg('target-arch'); final String hostArch = _getCurrentHostPlatformArchName(); if (hostArch != targetArch && hostArch == 'arm64') { - globals.logger - .printError('Not supported cross-building for x64 on arm64.'); + globals.logger.printError('Not supported cross-building for x64 on arm64.'); return FlutterCommandResult.fail(); } diff --git a/lib/commands/create.dart b/lib/commands/create.dart index a9b172c..29a0907 100644 --- a/lib/commands/create.dart +++ b/lib/commands/create.dart @@ -152,10 +152,8 @@ class ELinuxCreateCommand extends CreateCommand { // The template directory that the flutter tools search for available // templates cannot be overriden because the implementation is private. // So we have to copy eLinux templates into the directory manually. - final Directory eLinuxTemplates = globals.fs - .directory(Cache.flutterRoot) - .parent - .childDirectory('templates'); + final Directory eLinuxTemplates = + globals.fs.directory(Cache.flutterRoot).parent.childDirectory('templates'); if (!eLinuxTemplates.existsSync()) { throwToolExit('Could not locate eLinux templates.'); } @@ -167,19 +165,16 @@ class ELinuxCreateCommand extends CreateCommand { _runGitClean(templates); try { - for (final Directory projectType - in eLinuxTemplates.listSync().whereType()) { - final Directory dest = templates - .childDirectory(projectType.basename) - .childDirectory('elinux.tmpl'); + for (final Directory projectType in eLinuxTemplates.listSync().whereType()) { + final Directory dest = + templates.childDirectory(projectType.basename).childDirectory('elinux.tmpl'); if (dest.existsSync()) { dest.deleteSync(recursive: true); } copyDirectory(projectType, dest); if (projectType.basename == 'app') { - final Directory sourceRunnerCommon = - projectType.childDirectory('runner'); + final Directory sourceRunnerCommon = projectType.childDirectory('runner'); if (!sourceRunnerCommon.existsSync()) { continue; } diff --git a/lib/commands/drive.dart b/lib/commands/drive.dart index 32814c6..178a76c 100644 --- a/lib/commands/drive.dart +++ b/lib/commands/drive.dart @@ -9,8 +9,7 @@ import 'package:flutter_tools/src/globals.dart' as globals; import '../elinux_cache.dart'; import '../elinux_plugins.dart'; -class ELinuxDriveCommand extends DriveCommand - with ELinuxExtension, ELinuxRequiredArtifacts { +class ELinuxDriveCommand extends DriveCommand with ELinuxExtension, ELinuxRequiredArtifacts { ELinuxDriveCommand({super.verboseHelp}) : super( fileSystem: globals.fs, diff --git a/lib/commands/packages.dart b/lib/commands/packages.dart index 61c1ab9..41f9407 100644 --- a/lib/commands/packages.dart +++ b/lib/commands/packages.dart @@ -22,37 +22,28 @@ class ELinuxPackagesCommand extends FlutterCommand { ELinuxPackagesCommand() { addSubcommand(ELinuxPackagesGetCommand( 'get', "Get the current package's dependencies.", PubContext.pubGet)); + addSubcommand(ELinuxPackagesGetCommand('upgrade', + "Upgrade the current package's dependencies to latest versions.", PubContext.pubUpgrade)); + addSubcommand( + ELinuxPackagesGetCommand('add', 'Add a dependency to pubspec.yaml.', PubContext.pubAdd)); addSubcommand(ELinuxPackagesGetCommand( - 'upgrade', - "Upgrade the current package's dependencies to latest versions.", - PubContext.pubUpgrade)); - addSubcommand(ELinuxPackagesGetCommand( - 'add', 'Add a dependency to pubspec.yaml.', PubContext.pubAdd)); - addSubcommand(ELinuxPackagesGetCommand( - 'remove', - 'Removes a dependency from the current package.', - PubContext.pubRemove)); + 'remove', 'Removes a dependency from the current package.', PubContext.pubRemove)); addSubcommand(PackagesTestCommand()); addSubcommand(PackagesForwardCommand( 'publish', 'Publish the current package to pub.dartlang.org', requiresPubspec: true)); - addSubcommand(PackagesForwardCommand( - 'downgrade', 'Downgrade packages in a Flutter project', - requiresPubspec: true)); - addSubcommand(PackagesForwardCommand('deps', 'Print package dependencies', - requiresPubspec: true)); - addSubcommand(PackagesForwardCommand( - 'run', 'Run an executable from a package', + addSubcommand(PackagesForwardCommand('downgrade', 'Downgrade packages in a Flutter project', requiresPubspec: true)); addSubcommand( - PackagesForwardCommand('cache', 'Work with the Pub system cache')); + PackagesForwardCommand('deps', 'Print package dependencies', requiresPubspec: true)); + addSubcommand( + PackagesForwardCommand('run', 'Run an executable from a package', requiresPubspec: true)); + addSubcommand(PackagesForwardCommand('cache', 'Work with the Pub system cache')); addSubcommand(PackagesForwardCommand('version', 'Print Pub version')); - addSubcommand(PackagesForwardCommand( - 'uploader', 'Manage uploaders for a package on pub.dev')); + addSubcommand(PackagesForwardCommand('uploader', 'Manage uploaders for a package on pub.dev')); addSubcommand(PackagesForwardCommand('login', 'Log into pub.dev.')); addSubcommand(PackagesForwardCommand('logout', 'Log out of pub.dev.')); - addSubcommand( - PackagesForwardCommand('global', 'Work with Pub global packages')); + addSubcommand(PackagesForwardCommand('global', 'Work with Pub global packages')); addSubcommand(PackagesForwardCommand( 'outdated', 'Analyze dependencies to find which ones can be upgraded', requiresPubspec: true)); @@ -69,12 +60,10 @@ class ELinuxPackagesCommand extends FlutterCommand { final String description = 'Commands for managing Flutter packages.'; @override - Future runCommand() async => - FlutterCommandResult.fail(); + Future runCommand() async => FlutterCommandResult.fail(); } -class ELinuxPackagesGetCommand extends PackagesGetCommand - with _PostRunPluginInjection { +class ELinuxPackagesGetCommand extends PackagesGetCommand with _PostRunPluginInjection { ELinuxPackagesGetCommand(super.commandName, super.description, super.context); } @@ -85,17 +74,14 @@ mixin _PostRunPluginInjection on FlutterCommand { final FlutterCommandResult result = await super.runCommand(); if (result == FlutterCommandResult.success()) { - final String? workingDirectory = - argResults!.rest.isNotEmpty ? argResults!.rest[0] : null; + final String? workingDirectory = argResults!.rest.isNotEmpty ? argResults!.rest[0] : null; final String? target = findProjectRoot(globals.fs, workingDirectory); if (target == null) { return result; } - final FlutterProject rootProject = - FlutterProject.fromDirectory(globals.fs.directory(target)); + final FlutterProject rootProject = FlutterProject.fromDirectory(globals.fs.directory(target)); await ensureReadyForELinuxTooling(rootProject); - if (rootProject.hasExampleApp && - rootProject.example.pubspecFile.existsSync()) { + if (rootProject.hasExampleApp && rootProject.example.pubspecFile.existsSync()) { await ensureReadyForELinuxTooling(rootProject.example); } } diff --git a/lib/commands/run.dart b/lib/commands/run.dart index 3113081..06a56ba 100644 --- a/lib/commands/run.dart +++ b/lib/commands/run.dart @@ -11,18 +11,15 @@ import 'package:flutter_tools/src/commands/run.dart'; import '../elinux_cache.dart'; import '../elinux_plugins.dart'; -class ELinuxRunCommand extends RunCommand - with ELinuxExtension, ELinuxRequiredArtifacts { +class ELinuxRunCommand extends RunCommand with ELinuxExtension, ELinuxRequiredArtifacts { ELinuxRunCommand({super.verboseHelp}); @override - Future> get requiredArtifacts async => - { + Future> get requiredArtifacts async => { // Use gen_snapshot of the arm64 linux-desktop when self-building // on arm64 hosts. This is because elinux's artifacts for arm64 // doesn't support self-build as of now. - if (_getCurrentHostPlatformArchName() == 'arm64') - DevelopmentArtifact.linux, + if (_getCurrentHostPlatformArchName() == 'arm64') DevelopmentArtifact.linux, ELinuxDevelopmentArtifact.elinux, }; diff --git a/lib/commands/upgrade.dart b/lib/commands/upgrade.dart index 539acef..e3be16b 100644 --- a/lib/commands/upgrade.dart +++ b/lib/commands/upgrade.dart @@ -27,10 +27,9 @@ class ELinuxUpgradeCommand extends UpgradeCommand { @override Future runCommand() { - final ELinuxUpgradeCommandRunner commandRunner = - ELinuxUpgradeCommandRunner(); - commandRunner.workingDirectory = stringArg('working-directory') ?? - globals.fs.directory(Cache.flutterRoot).parent.path; + final ELinuxUpgradeCommandRunner commandRunner = ELinuxUpgradeCommandRunner(); + commandRunner.workingDirectory = + stringArg('working-directory') ?? globals.fs.directory(Cache.flutterRoot).parent.path; return commandRunner.runCommand( force: boolArg('force'), continueFlow: boolArg('continue'), @@ -110,10 +109,8 @@ class ELinuxUpgradeCommandRunner { globals.printStatus( 'Your current version: ${currentVersion.gitTag} (revision ${currentVersion.hashShort})\n'); } else { - globals.printStatus('The latest revision: ${upstreamVersion.hashShort}', - emphasis: true); - globals - .printStatus('Your current revision: ${currentVersion.hashShort}\n'); + globals.printStatus('The latest revision: ${upstreamVersion.hashShort}', emphasis: true); + globals.printStatus('Your current revision: ${currentVersion.hashShort}\n'); } globals.printStatus('To upgrade now, run "flutter-elinux upgrade".'); @@ -150,8 +147,7 @@ class ELinuxUpgradeCommandRunner { throwOnError: true, workingDirectory: workingDirectory, ); - final List tags = - const LineSplitter().convert(result.stdout.trim()); + final List tags = const LineSplitter().convert(result.stdout.trim()); if (tags.isEmpty) { throwToolExit( 'Unable to upgrade flutter-elinux: Your flutter-elinux checkout does not have any tags.\n' @@ -167,13 +163,11 @@ class ELinuxUpgradeCommandRunner { ); latestRevision = result.stdout.trim(); } on Exception catch (_) { - throwToolExit( - 'Unable to upgrade flutter-elinux: The current flutter-elinux branch is ' + throwToolExit('Unable to upgrade flutter-elinux: The current flutter-elinux branch is ' 'not tracking any remote repository.\n' 'Re-install re-install flutter-elinux.'); } - return ELinuxGitTagVersion( - latestRevision, latestRevision.substring(0, 10), latestTag); + return ELinuxGitTagVersion(latestRevision, latestRevision.substring(0, 10), latestTag); } Future fetchCurrentBranchLatestVersion() async { @@ -187,8 +181,7 @@ class ELinuxUpgradeCommandRunner { // Gets the hash of the latest version. // e.g. commit 13d148c1980913b68f55032dc37ae6026b71a2a1 (HEAD -> main, origin/main, origin/HEAD) - final List lines = - const LineSplitter().convert(result.stdout.trim()); + final List lines = const LineSplitter().convert(result.stdout.trim()); if (lines.isEmpty) { throwToolExit( 'Unable to upgrade flutter-elinux: Your flutter-elinux checkout does not have any logs.\n' @@ -196,13 +189,11 @@ class ELinuxUpgradeCommandRunner { } latestRevision = lines[0].split(' ')[1]; } on Exception catch (_) { - throwToolExit( - 'Unable to upgrade flutter-elinux: The current flutter-elinux branch is ' + throwToolExit('Unable to upgrade flutter-elinux: The current flutter-elinux branch is ' 'not tracking any remote repository.\n' 'Re-install re-install flutter-elinux.'); } - return ELinuxGitTagVersion( - latestRevision, latestRevision.substring(0, 10), null); + return ELinuxGitTagVersion(latestRevision, latestRevision.substring(0, 10), null); } Future fetchCurrentVersion() async { @@ -226,24 +217,20 @@ class ELinuxUpgradeCommandRunner { final String errorString = e.toString(); if (errorString.contains('fatal: no tag exactly matches')) { tag = null; - } else if (errorString - .contains('fatal: HEAD does not point to a branch')) { + } else if (errorString.contains('fatal: HEAD does not point to a branch')) { throwToolExit( 'Unable to upgrade flutter-elinux: Your flutter-elinux checkout is currently not ' 'on a release branch.\n' 'Re-install re-install flutter-elinux.'); - } else if (errorString - .contains('fatal: no upstream configured for branch')) { - throwToolExit( - 'Unable to upgrade flutter-elinux: The current flutter-elinux branch is ' + } else if (errorString.contains('fatal: no upstream configured for branch')) { + throwToolExit('Unable to upgrade flutter-elinux: The current flutter-elinux branch is ' 'not tracking any remote repository.\n' 'Re-install re-install flutter-elinux.'); } else { throwToolExit(errorString); } } - return ELinuxGitTagVersion( - latestRevision, latestRevision!.substring(0, 10), tag); + return ELinuxGitTagVersion(latestRevision, latestRevision!.substring(0, 10), tag); } /// Source: [attemptReset] in `upgrade.dart` (exact copy) @@ -316,8 +303,7 @@ class ELinuxUpgradeCommandRunner { globals.printStatus(''); await pub.get( context: PubContext.pubUpgrade, - project: - FlutterProject.fromDirectory(globals.fs.directory(projectRoot)), + project: FlutterProject.fromDirectory(globals.fs.directory(projectRoot)), upgrade: true, ); } diff --git a/lib/elinux_artifacts.dart b/lib/elinux_artifacts.dart index dfe3085..7af0d86 100644 --- a/lib/elinux_artifacts.dart +++ b/lib/elinux_artifacts.dart @@ -21,9 +21,7 @@ class ELinuxArtifacts extends CachedArtifacts { /// See: [CachedArtifacts._getEngineArtifactsPath] Directory _getEngineArtifactsDirectory(String arch, BuildMode mode) { - return _cache - .getArtifactDirectory('engine') - .childDirectory('elinux-$arch-${mode.name}'); + return _cache.getArtifactDirectory('engine').childDirectory('elinux-$arch-${mode.name}'); } /// See: [CachedArtifacts._getAndroidArtifactPath] in `artifacts.dart` @@ -43,8 +41,7 @@ class ELinuxArtifacts extends CachedArtifacts { platform != null && getNameForTargetPlatform(platform).startsWith('linux')) { assert(mode != null, 'Need to specify a build mode.'); - assert(mode != BuildMode.debug, - 'Artifact $artifact only available in non-debug mode.'); + assert(mode != BuildMode.debug, 'Artifact $artifact only available in non-debug mode.'); final String arch = _getArchForTargetPlatform(platform); return _getEngineArtifactsDirectory(arch, mode!) diff --git a/lib/elinux_build_target.dart b/lib/elinux_build_target.dart index 1ffb44b..0befdd1 100644 --- a/lib/elinux_build_target.dart +++ b/lib/elinux_build_target.dart @@ -62,16 +62,14 @@ abstract class ELinuxAssetBundle extends Target { if (environment.defines[kBuildMode] == null) { throw MissingDefineException(kBuildMode, name); } - final BuildMode buildMode = - BuildMode.fromCliName(environment.defines[kBuildMode]!); - final Directory outputDirectory = environment.outputDir - .childDirectory('flutter_assets') + final BuildMode buildMode = BuildMode.fromCliName(environment.defines[kBuildMode]!); + final Directory outputDirectory = environment.outputDir.childDirectory('flutter_assets') ..createSync(recursive: true); // Only copy the prebuilt runtimes and kernel blob in debug mode. if (buildMode == BuildMode.debug) { - final String vmSnapshotData = environment.artifacts - .getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug); + final String vmSnapshotData = + environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug); final String isolateSnapshotData = environment.artifacts .getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug); environment.buildDir @@ -84,9 +82,8 @@ abstract class ELinuxAssetBundle extends Target { .file(isolateSnapshotData) .copySync(outputDirectory.childFile('isolate_snapshot_data').path); } - final TargetPlatform tp = buildInfo.targetArch == 'arm64' - ? TargetPlatform.linux_arm64 - : TargetPlatform.linux_x64; + final TargetPlatform tp = + buildInfo.targetArch == 'arm64' ? TargetPlatform.linux_arm64 : TargetPlatform.linux_x64; final Depfile assetDepfile = await copyAssets( environment, outputDirectory, @@ -116,16 +113,14 @@ class DebugELinuxApplication extends ELinuxAssetBundle { List get inputs => [ ...super.inputs, const Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug), - const Source.artifact(Artifact.isolateSnapshotData, - mode: BuildMode.debug), + const Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug), ]; @override List get outputs => [ ...super.outputs, const Source.pattern('{OUTPUT_DIR}/flutter_assets/vm_snapshot_data'), - const Source.pattern( - '{OUTPUT_DIR}/flutter_assets/isolate_snapshot_data'), + const Source.pattern('{OUTPUT_DIR}/flutter_assets/isolate_snapshot_data'), const Source.pattern('{OUTPUT_DIR}/flutter_assets/kernel_blob.bin'), ]; @@ -227,12 +222,11 @@ class NativeBundle { final ELinuxBuildInfo? buildInfo; final String? targetFile; - final ProcessUtils _processUtils = ProcessUtils( - logger: globals.logger, processManager: globals.processManager); + final ProcessUtils _processUtils = + ProcessUtils(logger: globals.logger, processManager: globals.processManager); Future build(Environment environment) async { - final FlutterProject project = - FlutterProject.fromDirectory(environment.projectDir); + final FlutterProject project = FlutterProject.fromDirectory(environment.projectDir); final ELinuxProject eLinuxProject = ELinuxProject.fromFlutter(project); // Clean up the intermediate and output directories. @@ -258,72 +252,63 @@ class NativeBundle { } outputBundleLibDir.createSync(recursive: true); - final Directory outputBundleDataDir = - outputBundleDir.childDirectory('data'); + final Directory outputBundleDataDir = outputBundleDir.childDirectory('data'); if (outputBundleDataDir.existsSync()) { outputBundleDataDir.deleteSync(recursive: true); } outputBundleDataDir.createSync(recursive: true); // Copy necessary files - final Directory engineDir = - _getEngineArtifactsDirectory(buildInfo!.targetArch, buildMode); - final Directory commonDir = - engineDir.parent.childDirectory('elinux-common'); + final Directory engineDir = _getEngineArtifactsDirectory(buildInfo!.targetArch, buildMode); + final Directory commonDir = engineDir.parent.childDirectory('elinux-common'); final File engineBinary = engineDir.childFile('libflutter_engine.so'); // libflutter_elinux_*.so in profile mode is under the debug mode's directory. final Directory embedderDir = _getEngineArtifactsDirectory( - buildInfo!.targetArch, - buildMode.isRelease ? buildMode : BuildMode.fromCliName('debug')); - final File embedder = - embedderDir.childFile(buildInfo!.targetBackendType == 'gbm' - ? 'libflutter_elinux_gbm.so' - : buildInfo!.targetBackendType == 'eglstream' - ? 'libflutter_elinux_eglstream.so' - : buildInfo!.targetBackendType == 'x11' - ? 'libflutter_elinux_x11.so' - : 'libflutter_elinux_wayland.so'); - final Directory clientWrapperDir = - commonDir.childDirectory('cpp_client_wrapper'); - - final Directory pluginsDir = - environment.buildDir.childDirectory('elinux_plugins'); + buildInfo!.targetArch, buildMode.isRelease ? buildMode : BuildMode.fromCliName('debug')); + final File embedder = embedderDir.childFile(buildInfo!.targetBackendType == 'gbm' + ? 'libflutter_elinux_gbm.so' + : buildInfo!.targetBackendType == 'eglstream' + ? 'libflutter_elinux_eglstream.so' + : buildInfo!.targetBackendType == 'x11' + ? 'libflutter_elinux_x11.so' + : 'libflutter_elinux_wayland.so'); + final Directory clientWrapperDir = commonDir.childDirectory('cpp_client_wrapper'); + + final Directory pluginsDir = environment.buildDir.childDirectory('elinux_plugins'); final File pluginsLib = pluginsDir.childFile('libflutter_plugins.so'); if (pluginsLib.existsSync()) { - pluginsLib - .copySync(outputBundleLibDir.childFile(pluginsLib.basename).path); + pluginsLib.copySync(outputBundleLibDir.childFile(pluginsLib.basename).path); } final Directory pluginsUserLibDir = pluginsDir.childDirectory('lib'); if (pluginsUserLibDir.existsSync()) { - pluginsUserLibDir.listSync().whereType().forEach((File lib) => - lib.copySync(outputBundleLibDir.childFile(lib.basename).path)); + pluginsUserLibDir + .listSync() + .whereType() + .forEach((File lib) => lib.copySync(outputBundleLibDir.childFile(lib.basename).path)); } final Directory flutterDir = eLinuxDir.childDirectory('flutter'); - final Directory flutterEphemeralDir = - flutterDir.childDirectory('ephemeral'); + final Directory flutterEphemeralDir = flutterDir.childDirectory('ephemeral'); // Copy necessary files. { flutterEphemeralDir.createSync(recursive: true); - flutterEphemeralDir - .childDirectory('cpp_client_wrapper') - .createSync(recursive: true); + flutterEphemeralDir.childDirectory('cpp_client_wrapper').createSync(recursive: true); copyDirectory( clientWrapperDir, flutterEphemeralDir.childDirectory('cpp_client_wrapper'), ); - commonDir.listSync().whereType().forEach((File lib) => - lib.copySync(flutterEphemeralDir.childFile(lib.basename).path)); + commonDir + .listSync() + .whereType() + .forEach((File lib) => lib.copySync(flutterEphemeralDir.childFile(lib.basename).path)); - engineBinary - .copySync(flutterEphemeralDir.childFile(engineBinary.basename).path); + engineBinary.copySync(flutterEphemeralDir.childFile(engineBinary.basename).path); embedder.copySync(flutterEphemeralDir.childFile(embedder.basename).path); - final File icuData = - commonDir.childDirectory('icu').childFile('icudtl.dat'); + final File icuData = commonDir.childDirectory('icu').childFile('icudtl.dat'); icuData.copySync(flutterEphemeralDir.childFile(icuData.basename).path); if (buildMode.isPrecompiled) { @@ -335,11 +320,9 @@ class NativeBundle { // Build the environment that needs to be set for the re-entrant flutter build // step. { - final Map environmentConfig = - buildInfo!.buildInfo.toEnvironmentConfig(); + final Map environmentConfig = buildInfo!.buildInfo.toEnvironmentConfig(); environmentConfig['FLUTTER_TARGET'] = targetFile!; - final LocalEngineInfo? localEngineInfo = - globals.artifacts?.localEngineInfo; + final LocalEngineInfo? localEngineInfo = globals.artifacts?.localEngineInfo; if (localEngineInfo != null) { final String targetOutPath = localEngineInfo.targetOutPath; // $ENGINE/src/out/foo_bar_baz -> $ENGINE/src @@ -348,21 +331,19 @@ class NativeBundle { environmentConfig['LOCAL_ENGINE'] = localEngineInfo.localTargetName; environmentConfig['LOCAL_ENGINE_HOST'] = localEngineInfo.localHostName; } - writeGeneratedCmakeConfig(Cache.flutterRoot!, eLinuxProject, - buildInfo!.buildInfo, environmentConfig, environment.logger); + writeGeneratedCmakeConfig(Cache.flutterRoot!, eLinuxProject, buildInfo!.buildInfo, + environmentConfig, environment.logger); } // Run the native build. final String cmakeBuildType = buildMode.isPrecompiled ? 'Release' : 'Debug'; - final String targetArch = - buildInfo!.targetArch == 'arm64' ? 'aarch64' : 'x86_64'; + final String targetArch = buildInfo!.targetArch == 'arm64' ? 'aarch64' : 'x86_64'; final String hostArch = _getCurrentHostPlatformArchName(); final String? targetCompilerTriple = buildInfo!.targetCompilerTriple; final String targetSysroot = buildInfo!.targetSysroot; final String? targetCompilerFlags = buildInfo!.targetCompilerFlags; final String? targetToolchain = buildInfo!.targetToolchain; - final String? systemIncludeDirectories = - buildInfo!.systemIncludeDirectories; + final String? systemIncludeDirectories = buildInfo!.systemIncludeDirectories; RunResult result = await _processUtils.run( [ 'cmake', @@ -370,17 +351,13 @@ class NativeBundle { '-DFLUTTER_TARGET_BACKEND_TYPE=${buildInfo!.targetBackendType}', '-DFLUTTER_TARGET_PLATFORM=elinux-${buildInfo!.targetArch}', if (targetSysroot != '/') '-DCMAKE_SYSROOT=$targetSysroot', - if (buildInfo!.targetArch != hostArch) - '-DCMAKE_SYSTEM_PROCESSOR=$targetArch', + if (buildInfo!.targetArch != hostArch) '-DCMAKE_SYSTEM_PROCESSOR=$targetArch', if (systemIncludeDirectories != null) '-DFLUTTER_SYSTEM_INCLUDE_DIRECTORIES=$systemIncludeDirectories', - if (targetCompilerTriple != null) - '-DCMAKE_C_COMPILER_TARGET=$targetCompilerTriple', - if (targetCompilerTriple != null) - '-DCMAKE_CXX_COMPILER_TARGET=$targetCompilerTriple', + if (targetCompilerTriple != null) '-DCMAKE_C_COMPILER_TARGET=$targetCompilerTriple', + if (targetCompilerTriple != null) '-DCMAKE_CXX_COMPILER_TARGET=$targetCompilerTriple', if (targetCompilerFlags != null) '-DCMAKE_C_FLAGS=$targetCompilerFlags', - if (targetCompilerFlags != null) - '-DCMAKE_CXX_FLAGS=$targetCompilerFlags', + if (targetCompilerFlags != null) '-DCMAKE_CXX_FLAGS=$targetCompilerFlags', eLinuxDir.path, ], workingDirectory: outputDir.path, @@ -422,8 +399,7 @@ class NativeBundle { throwToolExit('Failed to cmake install:\n$result'); } { - final Directory flutterAssetsDir = - outputBundleDataDir.childDirectory('flutter_assets'); + final Directory flutterAssetsDir = outputBundleDataDir.childDirectory('flutter_assets'); copyDirectory( environment.outputDir.childDirectory('flutter_assets'), flutterAssetsDir, @@ -477,7 +453,5 @@ String getDefaultPathVariable() { /// See: [CachedArtifacts._getEngineArtifactsPath] Directory _getEngineArtifactsDirectory(String arch, BuildMode? mode) { assert(mode != null, 'Need to specify a build mode.'); - return globals.cache - .getArtifactDirectory('engine') - .childDirectory('elinux-$arch-${mode!.name}'); + return globals.cache.getArtifactDirectory('engine').childDirectory('elinux-$arch-${mode!.name}'); } diff --git a/lib/elinux_builder.dart b/lib/elinux_builder.dart index 3392026..bedcdb0 100644 --- a/lib/elinux_builder.dart +++ b/lib/elinux_builder.dart @@ -73,13 +73,12 @@ class ELinuxBuilder { ); } - final Directory outputDir = - project.directory.childDirectory('build').childDirectory('elinux'); + final Directory outputDir = project.directory.childDirectory('build').childDirectory('elinux'); final BuildInfo buildInfo = eLinuxBuildInfo.buildInfo; final String buildModeName = buildInfo.mode.cliName; // Used by AotElfBase to generate an AOT snapshot. - final String targetPlatformName = getNameForTargetPlatform( - _getTargetPlatformForArch(eLinuxBuildInfo.targetArch)); + final String targetPlatformName = + getNameForTargetPlatform(_getTargetPlatformForArch(eLinuxBuildInfo.targetArch)); final Environment environment = Environment( projectDir: project.directory, @@ -113,11 +112,9 @@ class ELinuxBuilder { final Status status = globals.logger.startProgress( 'Building an eLinux application with ${eLinuxBuildInfo.targetBackendType} backend in $buildModeName mode for ${eLinuxBuildInfo.targetArch} target...'); try { - final BuildResult result = - await globals.buildSystem.build(target, environment); + final BuildResult result = await globals.buildSystem.build(target, environment); if (!result.success) { - for (final ExceptionMeasurement measurement - in result.exceptions.values) { + for (final ExceptionMeasurement measurement in result.exceptions.values) { globals.printError(measurement.exception.toString()); } throwToolExit('The build failed.'); @@ -128,8 +125,7 @@ class ELinuxBuilder { await NativeBundle(eLinuxBuildInfo, targetFile).build(environment); if (buildInfo.performanceMeasurementFile != null) { - final File outFile = - globals.fs.file(buildInfo.performanceMeasurementFile); + final File outFile = globals.fs.file(buildInfo.performanceMeasurementFile); // ignore: invalid_use_of_visible_for_testing_member writePerformanceData(result.performance.values, outFile); } @@ -139,8 +135,8 @@ class ELinuxBuilder { if (buildInfo.codeSizeDirectory != null && sizeAnalyzer != null) { final String arch = eLinuxBuildInfo.targetArch; - final String genSnapshotPlatform = _getTargetPlatformPlatformName( - _getTargetPlatformForArch(eLinuxBuildInfo.targetArch)); + final String genSnapshotPlatform = + _getTargetPlatformPlatformName(_getTargetPlatformForArch(eLinuxBuildInfo.targetArch)); final File codeSizeFile = globals.fs .directory(buildInfo.codeSizeDirectory) .childFile('snapshot.$genSnapshotPlatform.json'); @@ -157,9 +153,7 @@ class ELinuxBuilder { type: 'linux', ); final File outputFile = globals.fsUtils.getUniqueFile( - globals.fs - .directory(globals.fsUtils.homeDirPath) - .childDirectory('.flutter-devtools'), + globals.fs.directory(globals.fsUtils.homeDirPath).childDirectory('.flutter-devtools'), 'elinux-code-size-analysis', 'json', )..writeAsStringSync(jsonEncode(output)); @@ -169,12 +163,11 @@ class ELinuxBuilder { ); // DevTools expects a file path relative to the .flutter-devtools/ dir. - final String relativeAppSizePath = - outputFile.path.split('.flutter-devtools/').last.trim(); - globals.printStatus( - '\nTo analyze your app size in Dart DevTools, run the following command:\n' - 'flutter pub global activate devtools; flutter pub global run devtools ' - '--appSizeBase=$relativeAppSizePath'); + final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim(); + globals + .printStatus('\nTo analyze your app size in Dart DevTools, run the following command:\n' + 'flutter pub global activate devtools; flutter pub global run devtools ' + '--appSizeBase=$relativeAppSizePath'); } } } diff --git a/lib/elinux_cache.dart b/lib/elinux_cache.dart index 5964bfa..e333c2c 100644 --- a/lib/elinux_cache.dart +++ b/lib/elinux_cache.dart @@ -18,8 +18,7 @@ import 'package:process/process.dart'; mixin ELinuxRequiredArtifacts on FlutterCommand { @override - Future> get requiredArtifacts async => - { + Future> get requiredArtifacts async => { ...await super.requiredArtifacts, ELinuxDevelopmentArtifact.elinux, }; @@ -36,8 +35,7 @@ class ELinuxDevelopmentArtifact implements DevelopmentArtifact { @override final Feature? feature; - static const DevelopmentArtifact elinux = - ELinuxDevelopmentArtifact._('elinux'); + static const DevelopmentArtifact elinux = ELinuxDevelopmentArtifact._('elinux'); } /// Extends [FlutterCache] to register [ELinuxEngineArtifacts]. @@ -65,8 +63,7 @@ class ELinuxEngineArtifacts extends EngineCachedArtifact { required ProcessManager processManager, }) : _logger = logger, _platform = platform, - _processUtils = - ProcessUtils(processManager: processManager, logger: logger), + _processUtils = ProcessUtils(processManager: processManager, logger: logger), super( 'elinux-sdk', cache, @@ -85,15 +82,12 @@ class ELinuxEngineArtifacts extends EngineCachedArtifact { .childDirectory('bin') .childDirectory('internal') .childFile('engine.version'); - return versionFile.existsSync() - ? versionFile.readAsStringSync().trim() - : null; + return versionFile.existsSync() ? versionFile.readAsStringSync().trim() : null; } String get shortVersion { if (version == null) { - throwToolExit( - 'Failed to get the short revision of the eLinux engine artifact.'); + throwToolExit('Failed to get the short revision of the eLinux engine artifact.'); } if (version!.length >= 10) { @@ -141,8 +135,7 @@ class ELinuxEngineArtifacts extends EngineCachedArtifact { ) async { String? downloadUrl; - final String? overrideLocal = - _platform.environment['ELINUX_ENGINE_BASE_LOCAL_DIRECTORY']; + final String? overrideLocal = _platform.environment['ELINUX_ENGINE_BASE_LOCAL_DIRECTORY']; if (overrideLocal != null) { await _downloadArtifactsFromLocal(operatingSystemUtils, overrideLocal); return; diff --git a/lib/elinux_cmake_project.dart b/lib/elinux_cmake_project.dart index e2f055d..9734f1e 100644 --- a/lib/elinux_cmake_project.dart +++ b/lib/elinux_cmake_project.dart @@ -9,8 +9,7 @@ import 'package:flutter_tools/src/project.dart'; import 'elinux_plugins.dart'; /// The eLinux sub project. -class ELinuxProject extends FlutterProjectPlatform - implements CmakeBasedProject { +class ELinuxProject extends FlutterProjectPlatform implements CmakeBasedProject { ELinuxProject.fromFlutter(this.parent); @override @@ -31,24 +30,19 @@ class ELinuxProject extends FlutterProjectPlatform File get managedCmakeFile => managedDirectory.childFile('CMakeLists.txt'); @override - File get generatedCmakeConfigFile => - ephemeralDirectory.childFile('generated_config.cmake'); + File get generatedCmakeConfigFile => ephemeralDirectory.childFile('generated_config.cmake'); @override - File get generatedPluginCmakeFile => - managedDirectory.childFile('generated_plugins.cmake'); + File get generatedPluginCmakeFile => managedDirectory.childFile('generated_plugins.cmake'); @override - Directory get pluginSymlinkDirectory => - ephemeralDirectory.childDirectory('.plugin_symlinks'); + Directory get pluginSymlinkDirectory => ephemeralDirectory.childDirectory('.plugin_symlinks'); - Directory get editableDirectory => - parent.directory.childDirectory(_childDirectory); + Directory get editableDirectory => parent.directory.childDirectory(_childDirectory); Directory get managedDirectory => editableDirectory.childDirectory('flutter'); - Directory get ephemeralDirectory => - managedDirectory.childDirectory('ephemeral'); + Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral'); Future ensureReadyForPlatformSpecificTooling() async { await refreshELinuxPluginsList(parent); diff --git a/lib/elinux_device.dart b/lib/elinux_device.dart index 202f616..ed052b1 100644 --- a/lib/elinux_device.dart +++ b/lib/elinux_device.dart @@ -47,8 +47,7 @@ class ELinuxDevice extends Device { _sdkNameAndVersion = sdkNameAndVersion, _logger = logger, _processManager = processManager, - _processUtils = - ProcessUtils(processManager: processManager, logger: logger), + _processUtils = ProcessUtils(processManager: processManager, logger: logger), _operatingSystemUtils = operatingSystemUtils, portForwarder = config != null && config.usesPortForwarding ? CustomDevicePortForwarder( @@ -107,8 +106,7 @@ class ELinuxDevice extends Device { String get name => 'eLinux'; @override - Future isAppInstalled(covariant ELinuxApp app, - {String? userIdentifier}) async { + Future isAppInstalled(covariant ELinuxApp app, {String? userIdentifier}) async { return false; } @@ -118,22 +116,19 @@ class ELinuxDevice extends Device { } @override - Future installApp(covariant ELinuxApp app, - {String? userIdentifier}) async { + Future installApp(covariant ELinuxApp app, {String? userIdentifier}) async { if (!await tryUninstall(appName: app.name!)) { return false; } final String bundlePath = app.outputDirectory(_buildMode, _targetArch); - final bool result = - await tryInstall(localPath: bundlePath, appName: app.name!); + final bool result = await tryInstall(localPath: bundlePath, appName: app.name!); return result; } @override - Future uninstallApp(covariant ELinuxApp app, - {String? userIdentifier}) async { + Future uninstallApp(covariant ELinuxApp app, {String? userIdentifier}) async { return tryUninstall(appName: app.name!); } @@ -154,8 +149,7 @@ class ELinuxDevice extends Device { return LaunchResult.failed(); } - final List interpolated = interpolateCommand( - _config!.runDebugCommand, + final List interpolated = interpolateCommand(_config!.runDebugCommand, {'remotePath': '/tmp/', 'appName': package.name!}); _logger.printStatus('Launch $package.name on ${_config.id}'); @@ -258,22 +252,20 @@ class ELinuxDevice extends Device { } @override - Future stopApp(covariant ELinuxApp? app, - {String? userIdentifier}) async { + Future stopApp(covariant ELinuxApp? app, {String? userIdentifier}) async { _maybeUnforwardPort(); // Stop app for remote devices. if (!_desktop && _config!.stopAppCommand.isNotEmpty) { - final List interpolated = interpolateCommand( - _config.stopAppCommand, {'appName': app!.name!}); + final List interpolated = + interpolateCommand(_config.stopAppCommand, {'appName': app!.name!}); try { _logger.printStatus('Stop ${app.name!} for custom device.'); await _processUtils.run(interpolated, throwOnError: true, timeout: const Duration(seconds: 10)); _logger.printStatus('Stop Success.'); } on ProcessException catch (e) { - _logger.printError( - 'Error executing Stop app command for custom device $id: $e'); + _logger.printError('Error executing Stop app command for custom device $id: $e'); } } @@ -434,8 +426,7 @@ class ELinuxDevice extends Device { Future tryUninstall( {required String appName, Duration? timeout, - Map additionalReplacementValues = - const {}}) async { + Map additionalReplacementValues = const {}}) async { if (_config == null || _config.uninstallCommand.isEmpty) { // do nothing if uninstall command is not defined. _logger.printTrace('uninstall command is not defined.'); @@ -448,13 +439,11 @@ class ELinuxDevice extends Device { try { _logger.printStatus('Uninstall $appName from ${_config.id}.'); - await _processUtils.run(interpolated, - throwOnError: true, timeout: timeout); + await _processUtils.run(interpolated, throwOnError: true, timeout: timeout); _logger.printStatus('Uninstallation Success'); return true; } on ProcessException catch (e) { - _logger.printError( - 'Error executing uninstall command for custom device $id: $e'); + _logger.printError('Error executing uninstall command for custom device $id: $e'); return false; } } @@ -464,22 +453,18 @@ class ELinuxDevice extends Device { {required String localPath, required String appName, Duration? timeout, - Map additionalReplacementValues = - const {}}) async { + Map additionalReplacementValues = const {}}) async { final List interpolated = interpolateCommand( - _config!.installCommand, - {'localPath': localPath, 'appName': appName}, + _config!.installCommand, {'localPath': localPath, 'appName': appName}, additionalReplacementValues: additionalReplacementValues); try { _logger.printStatus('Install $appName ($localPath) to ${_config.id}'); - await _processUtils.run(interpolated, - throwOnError: true, timeout: timeout); + await _processUtils.run(interpolated, throwOnError: true, timeout: timeout); _logger.printStatus('Installation Success'); return true; } on ProcessException catch (e) { - _logger.printError( - 'Error executing install command for custom device $id: $e'); + _logger.printError('Error executing install command for custom device $id: $e'); return false; } } @@ -487,8 +472,8 @@ class ELinuxDevice extends Device { /// Source: [_maybeUnforwardPort] in `custom_device.dart` void _maybeUnforwardPort() { if (_forwardedHostPort != null) { - final ForwardedPort forwardedPort = portForwarder.forwardedPorts - .singleWhere((ForwardedPort forwardedPort) { + final ForwardedPort forwardedPort = + portForwarder.forwardedPorts.singleWhere((ForwardedPort forwardedPort) { return forwardedPort.hostPort == _forwardedHostPort; }); @@ -499,8 +484,7 @@ class ELinuxDevice extends Device { } class ELinuxLogReader extends DeviceLogReader { - final StreamController> _inputController = - StreamController>.broadcast(); + final StreamController> _inputController = StreamController>.broadcast(); void initializeProcess(Process process) { process.stdout.listen(_inputController.add); @@ -510,9 +494,7 @@ class ELinuxLogReader extends DeviceLogReader { @override Stream get logLines { - return _inputController.stream - .transform(utf8.decoder) - .transform(const LineSplitter()); + return _inputController.stream.transform(utf8.decoder).transform(const LineSplitter()); } @override diff --git a/lib/elinux_device_discovery.dart b/lib/elinux_device_discovery.dart index 1bb97f4..f6a671c 100644 --- a/lib/elinux_device_discovery.dart +++ b/lib/elinux_device_discovery.dart @@ -78,8 +78,7 @@ class ELinuxDeviceDiscovery extends PollingDeviceDiscovery { }) : _eLinuxWorkflow = eLinuxWorkflow, _logger = logger, _processManager = processManager, - _processUtils = - ProcessUtils(logger: logger, processManager: processManager), + _processUtils = ProcessUtils(logger: logger, processManager: processManager), _eLinuxRemoteDevicesConfig = ELinuxRemoteDevicesConfig( platform: globals.platform, fileSystem: globals.fs, @@ -140,8 +139,7 @@ class ELinuxDeviceDiscovery extends PollingDeviceDiscovery { ); // Adds remote devices. - for (final ELinuxRemoteDeviceConfig remoteDevice - in _eLinuxRemoteDevicesConfig.devices) { + for (final ELinuxRemoteDeviceConfig remoteDevice in _eLinuxRemoteDevicesConfig.devices) { if (!remoteDevice.enabled) { continue; } @@ -157,8 +155,7 @@ class ELinuxDeviceDiscovery extends PollingDeviceDiscovery { continue; } - if (result.exitCode == 0 && - stdout.contains(remoteDevice.pingSuccessRegex!)) { + if (result.exitCode == 0 && stdout.contains(remoteDevice.pingSuccessRegex!)) { final ELinuxDevice device = ELinuxDevice(remoteDevice.id, config: remoteDevice, desktop: false, diff --git a/lib/elinux_doctor.dart b/lib/elinux_doctor.dart index 6681cd0..5b0af63 100644 --- a/lib/elinux_doctor.dart +++ b/lib/elinux_doctor.dart @@ -21,13 +21,8 @@ ELinuxValidator? get eLinuxValidator => context.get(); class ELinuxDoctorValidatorsProvider implements DoctorValidatorsProvider { @override List get validators { - final List validators = - DoctorValidatorsProvider.defaultInstance.validators; - return [ - validators.first, - eLinuxValidator!, - ...validators.sublist(1) - ]; + final List validators = DoctorValidatorsProvider.defaultInstance.validators; + return [validators.first, eLinuxValidator!, ...validators.sublist(1)]; } @override @@ -40,9 +35,8 @@ class ELinuxDoctorValidatorsProvider implements DoctorValidatorsProvider { /// See: [_VersionInfo] in `linux_doctor.dart` class _VersionInfo { _VersionInfo(this.description) { - final String? versionString = RegExp(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?') - .firstMatch(description) - ?.group(0); + final String? versionString = + RegExp(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?').firstMatch(description)?.group(0); number = Version.parse(versionString); } @@ -85,20 +79,17 @@ class ELinuxValidator extends DoctorValidator { ValidationType validationType = ValidationType.success; final List messages = []; - final Map installedVersions = - { + final Map installedVersions = { // Sort the check to make the call order predictable for unit tests. for (String binary in _requiredBinaryVersions.keys.toList()..sort()) binary: await _getBinaryVersion(binary) }; // Determine overall validation level. - if (installedVersions.values - .any((_VersionInfo? versionInfo) => versionInfo?.number == null)) { + if (installedVersions.values.any((_VersionInfo? versionInfo) => versionInfo?.number == null)) { validationType = ValidationType.missing; - } else if (installedVersions.keys.any((String binary) => - installedVersions[binary]!.number! < - _requiredBinaryVersions[binary]!)) { + } else if (installedVersions.keys.any( + (String binary) => installedVersions[binary]!.number! < _requiredBinaryVersions[binary]!)) { validationType = ValidationType.partial; } @@ -112,8 +103,8 @@ class ELinuxValidator extends DoctorValidator { messages.add(ValidationMessage(version.description)); final Version requiredVersion = _requiredBinaryVersions[kClangBinary]!; if (version.number! < requiredVersion) { - messages.add(ValidationMessage.error( - _userMessages.clangTooOld(requiredVersion.toString()))); + messages + .add(ValidationMessage.error(_userMessages.clangTooOld(requiredVersion.toString()))); } } } @@ -128,8 +119,8 @@ class ELinuxValidator extends DoctorValidator { messages.add(ValidationMessage(version.description)); final Version requiredVersion = _requiredBinaryVersions[kCmakeBinary]!; if (version.number! < requiredVersion) { - messages.add(ValidationMessage.error( - _userMessages.cmakeTooOld(requiredVersion.toString()))); + messages + .add(ValidationMessage.error(_userMessages.cmakeTooOld(requiredVersion.toString()))); } } } @@ -142,13 +133,11 @@ class ELinuxValidator extends DoctorValidator { } else { assert(_requiredBinaryVersions.containsKey(kPkgConfigBinary)); // The full version description is just the number, so add context. - messages.add(ValidationMessage( - _userMessages.pkgConfigVersion(version.description))); - final Version requiredVersion = - _requiredBinaryVersions[kPkgConfigBinary]!; + messages.add(ValidationMessage(_userMessages.pkgConfigVersion(version.description))); + final Version requiredVersion = _requiredBinaryVersions[kPkgConfigBinary]!; if (version.number! < requiredVersion) { - messages.add(ValidationMessage.error( - _userMessages.pkgConfigTooOld(requiredVersion.toString()))); + messages.add( + ValidationMessage.error(_userMessages.pkgConfigTooOld(requiredVersion.toString()))); } } } @@ -164,8 +153,7 @@ class ELinuxValidator extends DoctorValidator { } if (libraryMissing) { validationType = ValidationType.missing; - messages.add( - const ValidationMessage.error(kRequredCommonLibrariesErrorMessage)); + messages.add(const ValidationMessage.error(kRequredCommonLibrariesErrorMessage)); } } diff --git a/lib/elinux_package.dart b/lib/elinux_package.dart index 829de0d..1d7729b 100644 --- a/lib/elinux_package.dart +++ b/lib/elinux_package.dart @@ -79,8 +79,7 @@ class PrebuiltELinuxApp extends ELinuxApp { String executable(BuildMode buildMode, String targetArch) => _executable; @override - String outputDirectory(BuildMode buildMode, String targetArch) => - _outputDirectory; + String outputDirectory(BuildMode buildMode, String targetArch) => _outputDirectory; @override String get name => _executable; diff --git a/lib/elinux_plugins.dart b/lib/elinux_plugins.dart index 2463dad..47bd0b0 100644 --- a/lib/elinux_plugins.dart +++ b/lib/elinux_plugins.dart @@ -42,8 +42,8 @@ class ELinuxPlugin extends PluginPlatform implements NativeOrDartPlugin { (ffiPlugin ?? false) || defaultPackage != null); - factory ELinuxPlugin.fromYaml(String name, Directory directory, YamlMap yaml, - List dependencies) { + factory ELinuxPlugin.fromYaml( + String name, Directory directory, YamlMap yaml, List dependencies) { assert(validate(yaml)); // Treat 'none' as not present. See https://github.com/flutter/flutter/issues/57497. String? pluginClass = yaml[kPluginClass] as String?; @@ -136,8 +136,7 @@ mixin ELinuxExtension on FlutterCommand { await ensureReadyForELinuxTooling(FlutterProject.current()); } if (_usesTargetOption) { - _entrypoint = - await _createEntrypoint(FlutterProject.current(), super.targetFile); + _entrypoint = await _createEntrypoint(FlutterProject.current(), super.targetFile); } return super.verifyThenRunCommand(commandPath); } @@ -150,10 +149,8 @@ mixin ELinuxExtension on FlutterCommand { /// This effectively adds support for Dart plugins. /// /// Source: [WebEntrypointTarget.build] in `web.dart` -Future _createEntrypoint( - FlutterProject project, String targetFile) async { - final List dartPlugins = - await findELinuxPlugins(project, dartOnly: true); +Future _createEntrypoint(FlutterProject project, String targetFile) async { + final List dartPlugins = await findELinuxPlugins(project, dartOnly: true); if (dartPlugins.isEmpty) { return targetFile; } @@ -177,8 +174,7 @@ Future _createEntrypoint( ); final Uri mainUri = globals.fs.file(targetFile).absolute.uri; - final String mainImport = - packageConfig.toPackageUri(mainUri)?.toString() ?? mainUri.toString(); + final String mainImport = packageConfig.toPackageUri(mainUri)?.toString() ?? mainUri.toString(); entrypoint.writeAsStringSync(''' // @@ -226,9 +222,7 @@ const List _knownPlugins = [ /// /// See: [FlutterProject.ensureReadyForPlatformSpecificTooling] in `project.dart` Future ensureReadyForELinuxTooling(FlutterProject project) async { - if (!project.directory.existsSync() || - project.hasExampleApp || - project.isPlugin) { + if (!project.directory.existsSync() || project.hasExampleApp || project.isPlugin) { return; } final ELinuxProject eLinuxProject = ELinuxProject.fromFlutter(project); @@ -241,12 +235,10 @@ Future ensureReadyForELinuxTooling(FlutterProject project) async { Future refreshELinuxPluginsList(FlutterProject project) async { final List plugins = await findELinuxPlugins(project); // Sort the plugins by name to keep ordering stable in generated files. - plugins.sort((ELinuxPlugin left, ELinuxPlugin right) => - left.name.compareTo(right.name)); + plugins.sort((ELinuxPlugin left, ELinuxPlugin 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 = - _writeELinuxFlutterPluginsListLegacy(project, plugins); + final bool legacyChanged = _writeELinuxFlutterPluginsListLegacy(project, plugins); final bool changed = await _writeELinuxFlutterPluginsList(project, plugins); if (changed || legacyChanged) { @@ -255,20 +247,17 @@ Future refreshELinuxPluginsList(FlutterProject project) async { } /// See: [_writeFlutterPluginsListLegacy] in `flutter_plugins.dart` -bool _writeELinuxFlutterPluginsListLegacy( - FlutterProject project, List plugins) { +bool _writeELinuxFlutterPluginsListLegacy(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.'; + const String info = 'This is a generated file; do not edit or check into version control.'; final StringBuffer flutterPluginsBuffer = StringBuffer('# $info\n'); for (final ELinuxPlugin plugin in plugins) { - flutterPluginsBuffer - .write('${plugin.name}=${globals.fsUtils.escapePath(plugin.path)}\n'); + flutterPluginsBuffer.write('${plugin.name}=${globals.fsUtils.escapePath(plugin.path)}\n'); } final String? oldPluginFileContent = _readFileContent(pluginsFile); final String pluginFileContent = flutterPluginsBuffer.toString(); @@ -312,8 +301,7 @@ Future _writeELinuxFlutterPluginsList( pluginsMap[elinuxKey] = _filterELinuxPluginsByPlatform(plugins, elinuxKey); final Map result = {}; - result['info'] = - 'This is a generated file; do not edit or check into version control.'; + 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 @@ -338,22 +326,18 @@ Future _writeELinuxFlutterPluginsList( } /// See: [_filterPluginsByPlatform] in `plugins.dart` (exact copy) -List> _filterPluginsByPlatform( - List plugins, String 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 Set pluginNames = platformPlugins.map((Plugin plugin) => plugin.name).toSet(); final List> pluginInfo = >[]; for (final Plugin plugin in platformPlugins) { pluginInfo.add({ _kFlutterPluginsNameKey: plugin.name, _kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path), - _kFlutterPluginsDependenciesKey: [ - ...plugin.dependencies.where(pluginNames.contains) - ], + _kFlutterPluginsDependenciesKey: [...plugin.dependencies.where(pluginNames.contains)], }); } return pluginInfo; @@ -362,8 +346,7 @@ List> _filterPluginsByPlatform( /// See: [_filterPluginsByPlatform] in `plugins.dart` List> _filterELinuxPluginsByPlatform( List plugins, String platformKey) { - final Set pluginNames = - plugins.map((ELinuxPlugin plugin) => plugin.name).toSet(); + final Set pluginNames = plugins.map((ELinuxPlugin plugin) => plugin.name).toSet(); final List> pluginInfo = >[]; for (final ELinuxPlugin plugin in plugins) { pluginInfo.add({ @@ -380,16 +363,13 @@ List> _filterELinuxPluginsByPlatform( /// See: [_createPluginLegacyDependencyGraph] in `flutter_plugins.dart` List _createPluginLegacyDependencyGraph(List plugins) { final List directAppDependencies = []; - final Set pluginNames = - plugins.map((ELinuxPlugin plugin) => plugin.name).toSet(); + final Set pluginNames = plugins.map((ELinuxPlugin plugin) => plugin.name).toSet(); for (final ELinuxPlugin plugin in plugins) { directAppDependencies.add({ 'name': plugin.name, // Extract the plugin dependencies which happen to be plugins. - 'dependencies': [ - ...plugin.dependencies!.where(pluginNames.contains) - ], + 'dependencies': [...plugin.dependencies!.where(pluginNames.contains)], }); } return directAppDependencies; @@ -399,18 +379,14 @@ List _createPluginLegacyDependencyGraph(List plugins) { Future injectELinuxPlugins(FlutterProject project) async { final ELinuxProject eLinuxProject = ELinuxProject.fromFlutter(project); if (eLinuxProject.existsSync()) { - final List dartPlugins = - await findELinuxPlugins(project, dartOnly: true); - final List nativePlugins = - await findELinuxPlugins(project, nativeOnly: true); + final List dartPlugins = await findELinuxPlugins(project, dartOnly: true); + final List nativePlugins = await findELinuxPlugins(project, nativeOnly: true); _writeDartPluginRegistrant(eLinuxProject.managedDirectory, dartPlugins); - _writePluginCmakefileTemplate( - eLinuxProject, eLinuxProject.managedDirectory, nativePlugins); + _writePluginCmakefileTemplate(eLinuxProject, eLinuxProject.managedDirectory, nativePlugins); } - final List plugins = (await findELinuxPlugins(project)) - .map((ELinuxPlugin p) => p.name) - .toList(); + final List plugins = + (await findELinuxPlugins(project)).map((ELinuxPlugin p) => p.name).toList(); for (final String plugin in plugins) { final String eLinuxPlugin = '${plugin}_elinux'; if (_knownPlugins.contains(plugin) && !plugins.contains(eLinuxPlugin)) { @@ -445,9 +421,7 @@ Future> findELinuxPlugins( final bool isFfi = plugin.ffiPlugin ?? false; - if (nativeOnly && - ((plugin.pluginClass == null || plugin.pluginClass == 'none') && - !isFfi)) { + if (nativeOnly && ((plugin.pluginClass == null || plugin.pluginClass == 'none') && !isFfi)) { continue; } @@ -462,8 +436,7 @@ Future> findELinuxPlugins( /// Source: [_pluginFromPackage] in `plugins.dart` ELinuxPlugin? _pluginFromPackage(String name, Uri packageRoot) { - final String pubspecPath = - globals.fs.path.fromUri(packageRoot.resolve('pubspec.yaml')); + final String pubspecPath = globals.fs.path.fromUri(packageRoot.resolve('pubspec.yaml')); if (!globals.fs.isFileSync(pubspecPath)) { return null; } @@ -559,15 +532,12 @@ void _writePluginCmakefileTemplate( Directory registryDirectory, List plugins, ) { - final List methodChannelPlugins = - _filterMethodChannelPlugins(plugins); + final List methodChannelPlugins = _filterMethodChannelPlugins(plugins); final List ffiPlugins = _filterFfiPlugins(plugins) ..removeWhere(methodChannelPlugins.contains); final List> methodChannelPluginsMap = - methodChannelPlugins - .map((ELinuxPlugin plugin) => plugin.toMap()) - .toList(); + methodChannelPlugins.map((ELinuxPlugin plugin) => plugin.toMap()).toList(); final List> ffiPluginsMap = ffiPlugins.map((ELinuxPlugin plugin) => plugin.toMap()).toList(); @@ -663,8 +633,7 @@ String _cmakeRelativePluginSymlinkDirectoryPath(CmakeBasedProject project) { 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( + final List relativePathComponents = fileSystem.path.split(fileSystem.path.relative( project.pluginSymlinkDirectory.absolute.path, from: makefileDirPath, )); @@ -673,8 +642,8 @@ String _cmakeRelativePluginSymlinkDirectoryPath(CmakeBasedProject project) { /// Source: [_renderTemplateToFile] in `plugins.dart` (exact copy) void _renderTemplateToFile(String template, dynamic context, String filePath) { - final String renderedTemplate = globals.templateRenderer - .renderString(template, context, htmlEscapeValues: false); + final String renderedTemplate = + globals.templateRenderer.renderString(template, context, htmlEscapeValues: false); final File file = globals.fs.file(filePath); file.createSync(recursive: true); file.writeAsStringSync(renderedTemplate); @@ -683,13 +652,11 @@ void _renderTemplateToFile(String template, dynamic context, String filePath) { /// Source: [createPluginSymlinks] in `flutter_plugins.dart` void createPluginSymlinks(FlutterProject project, {bool force = false}) { Map? platformPlugins; - final String? pluginFileContent = - _readFileContent(project.flutterPluginsDependenciesFile); + final String? pluginFileContent = _readFileContent(project.flutterPluginsDependenciesFile); if (pluginFileContent != null) { final Map? pluginInfo = json.decode(pluginFileContent) as Map?; - platformPlugins = - pluginInfo?[_kFlutterPluginsPluginListKey] as Map?; + platformPlugins = pluginInfo?[_kFlutterPluginsPluginListKey] as Map?; } platformPlugins ??= {}; @@ -711,8 +678,7 @@ String? _readFileContent(File file) { /// 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, +void _createPlatformPluginSymlinks(Directory symlinkDirectory, List? platformPlugins, {bool force = false}) { if (force && symlinkDirectory.existsSync()) { // Start fresh to avoid stale links. @@ -722,8 +688,7 @@ void _createPlatformPluginSymlinks( if (platformPlugins == null) { return; } - for (final Map pluginInfo - in platformPlugins.cast>()) { + 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); @@ -735,10 +700,7 @@ void _createPlatformPluginSymlinks( } on FileSystemException catch (e) { // ignore: invalid_use_of_visible_for_testing_member handleSymlinkException(e, - platform: globals.platform, - os: globals.os, - destination: 'dest', - source: 'source'); + platform: globals.platform, os: globals.os, destination: 'dest', source: 'source'); rethrow; } } diff --git a/lib/elinux_remote_device_config.dart b/lib/elinux_remote_device_config.dart index a47ce3d..1d3230d 100644 --- a/lib/elinux_remote_device_config.dart +++ b/lib/elinux_remote_device_config.dart @@ -17,10 +17,7 @@ bool _listsEqual(List? a, List? b) { return false; } - return a - .asMap() - .entries - .every((MapEntry e) => e.value == b[e.key]); + return a.asMap().entries.every((MapEntry e) => e.value == b[e.key]); } /// See: [_regexesEqual] in `custom_device_config.dart` (exact copy) @@ -57,8 +54,7 @@ class ELinuxRemoteDeviceRevivalException implements Exception { @override bool operator ==(Object other) { - return (other is ELinuxRemoteDeviceRevivalException) && - (other.message == message); + return (other is ELinuxRemoteDeviceRevivalException) && (other.message == message); } @override @@ -91,10 +87,8 @@ class ELinuxRemoteDeviceConfig { final Map typedMap = _castJsonObject(json, 'device configuration', 'a JSON object'); - final List? forwardPortCommand = _castStringListOrNull( - typedMap[_kForwardPortCommand], - _kForwardPortCommand, - 'null or array of strings with at least one element', + final List? forwardPortCommand = _castStringListOrNull(typedMap[_kForwardPortCommand], + _kForwardPortCommand, 'null or array of strings with at least one element', minLength: 1); final RegExp? forwardPortSuccessRegex = _convertToRegexOrNull( @@ -110,15 +104,16 @@ class ELinuxRemoteDeviceConfig { return ELinuxRemoteDeviceConfig( id: _castString(typedMap[_kId], _kId, 'a string'), label: _castString(typedMap[_kLabel], _kLabel, 'a string'), - sdkNameAndVersion: _castString( - typedMap[_kSdkNameAndVersion], _kSdkNameAndVersion, 'a string'), + sdkNameAndVersion: + _castString(typedMap[_kSdkNameAndVersion], _kSdkNameAndVersion, 'a string'), enabled: _castBool(typedMap[_kEnabled], _kEnabled, 'a boolean'), platform: _castString(typedMap[_kPlatform], _kPlatform, 'arm64'), backend: _castString(typedMap[_kBackend], _kBackend, 'wayland'), - pingCommand: _castStringList(typedMap[_kPingCommand], _kPingCommand, - 'array of strings with at least one element', minLength: 1), - pingSuccessRegex: _convertToRegexOrNull(typedMap[_kPingSuccessRegex], - _kPingSuccessRegex, 'null or string-ified regex'), + pingCommand: _castStringList( + typedMap[_kPingCommand], _kPingCommand, 'array of strings with at least one element', + minLength: 1), + pingSuccessRegex: _convertToRegexOrNull( + typedMap[_kPingSuccessRegex], _kPingSuccessRegex, 'null or string-ified regex'), postBuildCommand: _castStringListOrNull( typedMap[_kPostBuildCommand], _kPostBuildCommand, @@ -128,13 +123,13 @@ class ELinuxRemoteDeviceConfig { installCommand: _castStringList( typedMap[_kInstallCommand], _kInstallCommand, 'array of strings with at least one element', minLength: 1), - uninstallCommand: _castStringList(typedMap[_kUninstallCommand], - _kUninstallCommand, 'array of strings with at least one element', - minLength: 1), + uninstallCommand: _castStringList(typedMap[_kUninstallCommand], _kUninstallCommand, + 'array of strings with at least one element', minLength: 1), runDebugCommand: _castStringList( typedMap[_kRunDebugCommand], _kRunDebugCommand, 'array of strings with at least one element', minLength: 1), - stopAppCommand: _castStringList(typedMap[_kStopAppCommand], _kStopAppCommand, 'array of strings with at least one element', minLength: 1), + stopAppCommand: + _castStringList(typedMap[_kStopAppCommand], _kStopAppCommand, 'array of strings with at least one element', minLength: 1), forwardPortCommand: forwardPortCommand, forwardPortSuccessRegex: forwardPortSuccessRegex, screenshotCommand: _castStringListOrNull(typedMap[_kScreenshotCommand], _kScreenshotCommand, 'array of strings with at least one element', minLength: 1)); @@ -178,8 +173,8 @@ class ELinuxRemoteDeviceConfig { bool get supportsScreenshotting => screenshotCommand != null; - static T _maybeRethrowAsRevivalException(T Function() closure, - String fieldDescription, String expectedValueDescription) { + static T _maybeRethrowAsRevivalException( + T Function() closure, String fieldDescription, String expectedValueDescription) { try { return closure(); } on Object { @@ -202,8 +197,7 @@ class ELinuxRemoteDeviceConfig { ); } - static bool _castBool( - dynamic value, String fieldDescription, String expectedValueDescription) { + static bool _castBool(dynamic value, String fieldDescription, String expectedValueDescription) { if (value == null) { throw ELinuxRemoteDeviceRevivalException.fromDescriptions( fieldDescription, expectedValueDescription); @@ -265,8 +259,7 @@ class ELinuxRemoteDeviceConfig { return null; } - return _castStringList(value, fieldDescription, expectedValueDescription, - minLength: minLength); + return _castStringList(value, fieldDescription, expectedValueDescription, minLength: minLength); } static RegExp? _convertToRegexOrNull( diff --git a/lib/elinux_remote_devices_config.dart b/lib/elinux_remote_devices_config.dart index 4cf24de..e072d29 100644 --- a/lib/elinux_remote_devices_config.dart +++ b/lib/elinux_remote_devices_config.dart @@ -100,29 +100,24 @@ class ELinuxRemoteDevicesConfig { } set devices(List configs) { - _config.setValue( - _kCustomDevicesConfigKey, - configs - .map((ELinuxRemoteDeviceConfig c) => c.toJson()) - .toList()); + _config.setValue(_kCustomDevicesConfigKey, + configs.map((ELinuxRemoteDeviceConfig c) => c.toJson()).toList()); } void add(ELinuxRemoteDeviceConfig config) { - _config.setValue(_kCustomDevicesConfigKey, - [...?_getDevicesJsonValue(), config.toJson()]); + _config + .setValue(_kCustomDevicesConfigKey, [...?_getDevicesJsonValue(), config.toJson()]); } bool contains(String deviceId) { - return devices - .any((ELinuxRemoteDeviceConfig device) => device.id == deviceId); + return devices.any((ELinuxRemoteDeviceConfig device) => device.id == deviceId); } bool remove(String deviceId) { final List modifiedDevices = devices; final ELinuxRemoteDeviceConfig? device = modifiedDevices .cast() - .firstWhere((ELinuxRemoteDeviceConfig? d) => d!.id == deviceId, - orElse: () => null); + .firstWhere((ELinuxRemoteDeviceConfig? d) => d!.id == deviceId, orElse: () => null); if (device == null) { return false; diff --git a/lib/executable.dart b/lib/executable.dart index 60413a0..564dd9b 100644 --- a/lib/executable.dart +++ b/lib/executable.dart @@ -56,8 +56,7 @@ import 'elinux_package.dart'; /// Source: [flutter.main] in `executable.dart` (some commands and options were omitted) Future main(List args) async { final bool veryVerbose = args.contains('-vv'); - final bool verbose = - args.contains('-v') || args.contains('--verbose') || veryVerbose; + final bool verbose = args.contains('-v') || args.contains('--verbose') || veryVerbose; final bool doctor = (args.isNotEmpty && args.first == 'doctor') || (args.length == 2 && verbose && args.last == 'doctor'); @@ -68,8 +67,7 @@ Future main(List args) async { final bool muteCommandLogging = (help || doctor) && !veryVerbose; final bool verboseHelp = help && verbose; - final bool hasSpecifiedDeviceId = - args.contains('-d') || args.contains('--device-id'); + final bool hasSpecifiedDeviceId = args.contains('-d') || args.contains('--device-id'); args = [ '--suppress-analytics', // Suppress flutter analytics by default. diff --git a/lib/vscode_helper.dart b/lib/vscode_helper.dart index 0d576da..e3d0cc3 100644 --- a/lib/vscode_helper.dart +++ b/lib/vscode_helper.dart @@ -15,26 +15,20 @@ const String kConfigNameAttach = 'flutter-elinux: Attach'; String _processJson(String jsonString) { // The extended JSON format used by launch.json files allows comments and // trailing commas. Remove them to prevent decoding errors. - final RegExp comments = - RegExp(r'(?[]; final List configs = decoded['configurations']! as List; - if (!configs.any((Object? config) => - config is Map && config['name'] == kConfigNameAttach)) { + if (!configs.any((Object? config) => config is Map && config['name'] == kConfigNameAttach)) { configs.add({ 'name': kConfigNameAttach, 'request': 'attach', @@ -66,9 +59,7 @@ void updateLaunchJsonFile(FlutterProject project, Uri vmServiceUri) { if (config is! Map || config['name'] != kConfigNameAttach) { continue; } - config['cwd'] = project.hasExampleApp - ? r'${workspaceFolder}/example' - : r'${workspaceFolder}'; + config['cwd'] = project.hasExampleApp ? r'${workspaceFolder}/example' : r'${workspaceFolder}'; config['vmServiceUri'] = vmServiceUri.toString(); } diff --git a/packages/flutter_elinux/lib/src/rendering/platform_view.dart b/packages/flutter_elinux/lib/src/rendering/platform_view.dart index 6217fe5..9990c70 100644 --- a/packages/flutter_elinux/lib/src/rendering/platform_view.dart +++ b/packages/flutter_elinux/lib/src/rendering/platform_view.dart @@ -167,8 +167,7 @@ class RenderELinuxView extends PlatformViewRenderBox { // This guarantees that the size of the texture frame we're painting is always // _currentELinuxTextureSize. final bool isTextureLargerThanWidget = - _currentTextureSize!.width > size.width || - _currentTextureSize!.height > size.height; + _currentTextureSize!.width > size.width || _currentTextureSize!.height > size.height; if (isTextureLargerThanWidget && clipBehavior != Clip.none) { _clipRectLayer.layer = context.pushClipRect( true, @@ -184,8 +183,7 @@ class RenderELinuxView extends PlatformViewRenderBox { _paintTexture(context, offset); } - final LayerHandle _clipRectLayer = - LayerHandle(); + final LayerHandle _clipRectLayer = LayerHandle(); @override void dispose() { diff --git a/packages/flutter_elinux/lib/src/services/platform_views.dart b/packages/flutter_elinux/lib/src/services/platform_views.dart index d6c1e92..52f1156 100644 --- a/packages/flutter_elinux/lib/src/services/platform_views.dart +++ b/packages/flutter_elinux/lib/src/services/platform_views.dart @@ -20,8 +20,7 @@ class PlatformViewsServiceELinux { SystemChannels.platform_views.setMethodCallHandler(_onMethodCall); } - static final PlatformViewsServiceELinux _instance = - PlatformViewsServiceELinux._(); + static final PlatformViewsServiceELinux _instance = PlatformViewsServiceELinux._(); Future _onMethodCall(MethodCall call) { switch (call.method) { @@ -83,8 +82,7 @@ class PlatformViewsServiceELinux { }) { assert(creationParams == null || creationParamsCodec != null); - final TextureELinuxViewController controller = - TextureELinuxViewController._( + final TextureELinuxViewController controller = TextureELinuxViewController._( viewId: id, viewType: viewType, layoutDirection: layoutDirection, @@ -112,8 +110,7 @@ class PlatformViewsServiceELinux { }) { assert(creationParams == null || creationParamsCodec != null); - final SurfaceELinuxViewController controller = - SurfaceELinuxViewController._( + final SurfaceELinuxViewController controller = SurfaceELinuxViewController._( viewId: id, viewType: viewType, layoutDirection: layoutDirection, @@ -140,8 +137,7 @@ class PlatformViewsServiceELinux { MessageCodec? creationParamsCodec, VoidCallback? onFocus, }) { - final ExpensiveELinuxViewController controller = - ExpensiveELinuxViewController._( + final ExpensiveELinuxViewController controller = ExpensiveELinuxViewController._( viewId: id, viewType: viewType, layoutDirection: layoutDirection, @@ -373,12 +369,8 @@ class ELinuxMotionEvent { eventTime, action, pointerCount, - pointerProperties - .map>((ELinuxPointerProperties p) => p._asList()) - .toList(), - pointerCoords - .map>((ELinuxPointerCoords p) => p._asList()) - .toList(), + pointerProperties.map>((ELinuxPointerProperties p) => p._asList()).toList(), + pointerCoords.map>((ELinuxPointerCoords p) => p._asList()).toList(), metaState, buttonState, xPrecision, @@ -409,10 +401,8 @@ enum _ELinuxViewState { class _ELinuxMotionEventConverter { _ELinuxMotionEventConverter(); - final Map pointerPositions = - {}; - final Map pointerProperties = - {}; + final Map pointerPositions = {}; + final Map pointerProperties = {}; final Set usedELinuxPointerIds = {}; late PointTransformer pointTransformer; @@ -489,13 +479,11 @@ class _ELinuxMotionEventConverter { if (event is PointerDownEvent) { action = numPointers == 1 ? ELinuxViewController.kActionDown - : ELinuxViewController.pointerAction( - pointerIdx, ELinuxViewController.kActionPointerDown); + : ELinuxViewController.pointerAction(pointerIdx, ELinuxViewController.kActionPointerDown); } else if (event is PointerUpEvent) { action = numPointers == 1 ? ELinuxViewController.kActionUp - : ELinuxViewController.pointerAction( - pointerIdx, ELinuxViewController.kActionPointerUp); + : ELinuxViewController.pointerAction(pointerIdx, ELinuxViewController.kActionPointerUp); } else if (event is PointerMoveEvent) { action = ELinuxViewController.kActionMove; } else if (event is PointerCancelEvent) { @@ -509,12 +497,9 @@ class _ELinuxMotionEventConverter { eventTime: event.timeStamp.inMilliseconds, action: action, pointerCount: pointerPositions.length, - pointerProperties: pointers - .map((int i) => pointerProperties[i]!) - .toList(), - pointerCoords: pointers - .map((int i) => pointerPositions[i]!) - .toList(), + pointerProperties: + pointers.map((int i) => pointerProperties[i]!).toList(), + pointerCoords: pointers.map((int i) => pointerPositions[i]!).toList(), metaState: 0, buttonState: 0, xPrecision: 1.0, @@ -572,9 +557,8 @@ abstract class ELinuxViewController extends PlatformViewController { }) : assert(creationParams == null || creationParamsCodec != null), _viewType = viewType, _layoutDirection = layoutDirection, - _creationParams = creationParams == null - ? null - : _CreationParams(creationParams, creationParamsCodec!); + _creationParams = + creationParams == null ? null : _CreationParams(creationParams, creationParamsCodec!); /// Action code for when a primary pointer touched the screen. /// @@ -619,8 +603,7 @@ abstract class ELinuxViewController extends PlatformViewController { final String _viewType; // Helps convert PointerEvents to ELinuxMotionEvents. - final _ELinuxMotionEventConverter _motionEventConverter = - _ELinuxMotionEventConverter(); + final _ELinuxMotionEventConverter _motionEventConverter = _ELinuxMotionEventConverter(); TextDirection _layoutDirection; @@ -655,8 +638,7 @@ abstract class ELinuxViewController extends PlatformViewController { /// /// If [_createRequiresSize] is true, `size` is non-nullable, and the call /// should instead be deferred until the size is available. - Future _sendCreateMessage( - {required covariant Size? size, Offset? position}); + Future _sendCreateMessage({required covariant Size? size, Offset? position}); /// Sends the message to resize the platform view to [size]. Future _sendResizeMessage(Size size); @@ -666,8 +648,7 @@ abstract class ELinuxViewController extends PlatformViewController { @override Future create({Size? size, Offset? position}) async { - assert(_state != _ELinuxViewState.disposed, - 'trying to create a disposed ELinux view'); + assert(_state != _ELinuxViewState.disposed, 'trying to create a disposed ELinux view'); assert(_state == _ELinuxViewState.waitingForSize, 'ELinux view is already sized. View id: $viewId'); @@ -680,8 +661,7 @@ abstract class ELinuxViewController extends PlatformViewController { await _sendCreateMessage(size: size, position: position); _state = _ELinuxViewState.created; - for (final PlatformViewCreatedCallback callback - in _platformViewCreatedCallbacks) { + for (final PlatformViewCreatedCallback callback in _platformViewCreatedCallbacks) { callback(viewId); } } @@ -701,8 +681,7 @@ abstract class ELinuxViewController extends PlatformViewController { /// As a result, consumers are expected to clip the texture using [size], while using /// the return value to size the texture. Future setSize(Size size) async { - assert(_state != _ELinuxViewState.disposed, - 'ELinux view is disposed. View id: $viewId'); + assert(_state != _ELinuxViewState.disposed, 'ELinux view is disposed. View id: $viewId'); if (_state == _ELinuxViewState.waitingForSize) { // Either `create` hasn't been called, or it couldn't run due to missing // size information, so create the view now. @@ -755,8 +734,7 @@ abstract class ELinuxViewController extends PlatformViewController { /// /// This is required to convert a [PointerEvent] to an [ELinuxMotionEvent]. /// It is typically provided by using [RenderBox.globalToLocal]. - PointTransformer get pointTransformer => - _motionEventConverter.pointTransformer; + PointTransformer get pointTransformer => _motionEventConverter.pointTransformer; set pointTransformer(PointTransformer transformer) { _motionEventConverter.pointTransformer = transformer; } @@ -772,8 +750,7 @@ abstract class ELinuxViewController extends PlatformViewController { } /// Removes a callback added with [addOnPlatformViewCreatedListener]. - void removeOnPlatformViewCreatedListener( - PlatformViewCreatedCallback listener) { + void removeOnPlatformViewCreatedListener(PlatformViewCreatedCallback listener) { assert(_state != _ELinuxViewState.disposed); _platformViewCreatedCallbacks.remove(listener); } @@ -781,8 +758,7 @@ abstract class ELinuxViewController extends PlatformViewController { /// The created callbacks that are invoked after the platform view has been /// created. @visibleForTesting - List get createdCallbacks => - _platformViewCreatedCallbacks; + List get createdCallbacks => _platformViewCreatedCallbacks; /// Sets the layout direction for the ELinux view. Future setLayoutDirection(TextDirection layoutDirection) async { @@ -803,8 +779,7 @@ abstract class ELinuxViewController extends PlatformViewController { return; } - await SystemChannels.platform_views - .invokeMethod('setDirection', { + await SystemChannels.platform_views.invokeMethod('setDirection', { 'id': viewId, 'direction': _getELinuxDirection(layoutDirection), }); @@ -833,8 +808,7 @@ abstract class ELinuxViewController extends PlatformViewController { _motionEventConverter.updatePointerPositions(event); - final ELinuxMotionEvent? ELinuxEvent = - _motionEventConverter.toELinuxMotionEvent(event); + final ELinuxMotionEvent? ELinuxEvent = _motionEventConverter.toELinuxMotionEvent(event); if (event is PointerUpEvent) { _motionEventConverter.handlePointerUpEvent(event); @@ -853,8 +827,7 @@ abstract class ELinuxViewController extends PlatformViewController { if (_state != _ELinuxViewState.created) { return Future.value(); } - return SystemChannels.platform_views - .invokeMethod('clearFocus', viewId); + return SystemChannels.platform_views.invokeMethod('clearFocus', viewId); } /// Disposes the ELinux view. @@ -868,8 +841,7 @@ abstract class ELinuxViewController extends PlatformViewController { _state = _ELinuxViewState.disposed; _platformViewCreatedCallbacks.clear(); PlatformViewsServiceELinux._instance._focusCallbacks.remove(viewId); - if (state == _ELinuxViewState.creating || - state == _ELinuxViewState.created) { + if (state == _ELinuxViewState.creating || state == _ELinuxViewState.created) { await _sendDisposeMessage(); } } @@ -886,20 +858,17 @@ class SurfaceELinuxViewController extends ELinuxViewController { }) : super._(); // By default, assume the implementation will be texture-based. - _ELinuxViewControllerInternals _internals = - _TextureELinuxViewControllerInternals(); + _ELinuxViewControllerInternals _internals = _TextureELinuxViewControllerInternals(); @override bool get _createRequiresSize => true; @override - Future _sendCreateMessage( - {required Size size, Offset? position}) async { + Future _sendCreateMessage({required Size size, Offset? position}) async { assert(!size.isEmpty, 'trying to create $TextureELinuxViewController without setting a valid size.'); - final dynamic response = - await _ELinuxViewControllerInternals.sendCreateMessage( + final dynamic response = await _ELinuxViewControllerInternals.sendCreateMessage( viewId: viewId, viewType: _viewType, hybrid: false, @@ -910,8 +879,7 @@ class SurfaceELinuxViewController extends ELinuxViewController { position: position, ); if (response is int) { - (_internals as _TextureELinuxViewControllerInternals).textureId = - response; + (_internals as _TextureELinuxViewControllerInternals).textureId = response; } else { // A null response indicates fallback to Hybrid Composition, so swap out // the implementation. @@ -956,15 +924,13 @@ class ExpensiveELinuxViewController extends ELinuxViewController { super.creationParamsCodec, }) : super._(); - final _ELinuxViewControllerInternals _internals = - _HybridELinuxViewControllerInternals(); + final _ELinuxViewControllerInternals _internals = _HybridELinuxViewControllerInternals(); @override bool get _createRequiresSize => false; @override - Future _sendCreateMessage( - {required Size? size, Offset? position}) async { + Future _sendCreateMessage({required Size? size, Offset? position}) async { await _ELinuxViewControllerInternals.sendCreateMessage( viewId: viewId, viewType: _viewType, @@ -1011,20 +977,17 @@ class TextureELinuxViewController extends ELinuxViewController { super.creationParamsCodec, }) : super._(); - final _TextureELinuxViewControllerInternals _internals = - _TextureELinuxViewControllerInternals(); + final _TextureELinuxViewControllerInternals _internals = _TextureELinuxViewControllerInternals(); @override bool get _createRequiresSize => true; @override - Future _sendCreateMessage( - {required Size size, Offset? position}) async { + Future _sendCreateMessage({required Size size, Offset? position}) async { assert(!size.isEmpty, 'trying to create $TextureELinuxViewController without setting a valid size.'); - _internals.textureId = - await _ELinuxViewControllerInternals.sendCreateMessage( + _internals.textureId = await _ELinuxViewControllerInternals.sendCreateMessage( viewId: viewId, viewType: _viewType, hybrid: false, @@ -1090,8 +1053,7 @@ abstract class _ELinuxViewControllerInternals { if (position != null) 'top': position.dy, }; if (creationParams != null) { - final ByteData paramsByteData = - creationParams.codec.encodeMessage(creationParams.data)!; + final ByteData paramsByteData = creationParams.codec.encodeMessage(creationParams.data)!; args['params'] = Uint8List.view( paramsByteData.buffer, 0, @@ -1121,8 +1083,7 @@ abstract class _ELinuxViewControllerInternals { } /// See: [_TextureAndroidViewControllerInternals] in `src/services/platform_view.dart` -class _TextureELinuxViewControllerInternals - extends _ELinuxViewControllerInternals { +class _TextureELinuxViewControllerInternals extends _ELinuxViewControllerInternals { _TextureELinuxViewControllerInternals(); /// The current offset of the platform view. @@ -1190,8 +1151,7 @@ class _TextureELinuxViewControllerInternals @override Future sendDisposeMessage({required int viewId}) { - return SystemChannels.platform_views - .invokeMethod('dispose', { + return SystemChannels.platform_views.invokeMethod('dispose', { 'id': viewId, 'hybrid': false, }); @@ -1199,8 +1159,7 @@ class _TextureELinuxViewControllerInternals } /// See: [_HybridAndroidViewControllerInternals] in `src/services/platform_view.dart` -class _HybridELinuxViewControllerInternals - extends _ELinuxViewControllerInternals { +class _HybridELinuxViewControllerInternals extends _ELinuxViewControllerInternals { @override int get textureId { throw UnimplementedError('Not supported for hybrid composition.'); @@ -1229,8 +1188,7 @@ class _HybridELinuxViewControllerInternals @override Future sendDisposeMessage({required int viewId}) { - return SystemChannels.platform_views - .invokeMethod('dispose', { + return SystemChannels.platform_views.invokeMethod('dispose', { 'id': viewId, 'hybrid': true, }); diff --git a/packages/flutter_elinux/lib/src/widgets/platform_view.dart b/packages/flutter_elinux/lib/src/widgets/platform_view.dart index 16791a1..1ab0652 100644 --- a/packages/flutter_elinux/lib/src/widgets/platform_view.dart +++ b/packages/flutter_elinux/lib/src/widgets/platform_view.dart @@ -77,8 +77,7 @@ class _ELinuxViewState extends State { void didChangeDependencies() { super.didChangeDependencies(); final TextDirection newLayoutDirection = _findLayoutDirection(); - final bool didChangeLayoutDirection = - _layoutDirection != newLayoutDirection; + final bool didChangeLayoutDirection = _layoutDirection != newLayoutDirection; _layoutDirection = newLayoutDirection; _initializeOnce(); @@ -94,8 +93,7 @@ class _ELinuxViewState extends State { super.didUpdateWidget(oldWidget); final TextDirection newLayoutDirection = _findLayoutDirection(); - final bool didChangeLayoutDirection = - _layoutDirection != newLayoutDirection; + final bool didChangeLayoutDirection = _layoutDirection != newLayoutDirection; _layoutDirection = newLayoutDirection; if (widget.viewType != oldWidget.viewType) { @@ -111,8 +109,7 @@ class _ELinuxViewState extends State { } TextDirection _findLayoutDirection() { - assert( - widget.layoutDirection != null || debugCheckHasDirectionality(context)); + assert(widget.layoutDirection != null || debugCheckHasDirectionality(context)); return widget.layoutDirection ?? Directionality.of(context); } @@ -137,8 +134,7 @@ class _ELinuxViewState extends State { }, ); if (widget.onPlatformViewCreated != null) { - _controller - .addOnPlatformViewCreatedListener(widget.onPlatformViewCreated!); + _controller.addOnPlatformViewCreatedListener(widget.onPlatformViewCreated!); } } @@ -221,15 +217,13 @@ class _ELinuxViewSurfaceState extends State { void initState() { super.initState(); if (!widget.controller.isCreated) { - widget.controller - .addOnPlatformViewCreatedListener(_onPlatformViewCreated); + widget.controller.addOnPlatformViewCreatedListener(_onPlatformViewCreated); } } @override void dispose() { - widget.controller - .removeOnPlatformViewCreatedListener(_onPlatformViewCreated); + widget.controller.removeOnPlatformViewCreatedListener(_onPlatformViewCreated); super.dispose(); } @@ -265,8 +259,7 @@ class _TextureBasedELinuxViewSurface extends PlatformViewSurface { @override RenderObject createRenderObject(BuildContext context) { - final ELinuxViewController viewController = - controller as ELinuxViewController; + final ELinuxViewController viewController = controller as ELinuxViewController; // Use GL texture based composition. // App should use GL texture unless they require to embed a SurfaceView. final RenderELinuxView renderBox = RenderELinuxView( @@ -274,8 +267,7 @@ class _TextureBasedELinuxViewSurface extends PlatformViewSurface { gestureRecognizers: gestureRecognizers, hitTestBehavior: hitTestBehavior, ); - viewController.pointTransformer = - (Offset position) => renderBox.globalToLocal(position); + viewController.pointTransformer = (Offset position) => renderBox.globalToLocal(position); return renderBox; } } @@ -290,12 +282,10 @@ class _PlatformLayerBasedELinuxViewSurface extends PlatformViewSurface { @override RenderObject createRenderObject(BuildContext context) { - final ELinuxViewController viewController = - controller as ELinuxViewController; + final ELinuxViewController viewController = controller as ELinuxViewController; final PlatformViewRenderBox renderBox = super.createRenderObject(context) as PlatformViewRenderBox; - viewController.pointTransformer = - (Offset position) => renderBox.globalToLocal(position); + viewController.pointTransformer = (Offset position) => renderBox.globalToLocal(position); return renderBox; } } From 048e42c70065dbae6182820e4f36f6252ddc64f8 Mon Sep 17 00:00:00 2001 From: Jason Huang Date: Mon, 23 Jun 2025 13:54:26 +0800 Subject: [PATCH 5/5] refactor: Remove unused feature parameter The `unused_element_parameter` lint warning for the `feature` parameter was causing failures in the GitHub Actions CI workflow. --- lib/elinux_cache.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/elinux_cache.dart b/lib/elinux_cache.dart index e333c2c..9d21f0a 100644 --- a/lib/elinux_cache.dart +++ b/lib/elinux_cache.dart @@ -27,13 +27,13 @@ mixin ELinuxRequiredArtifacts on FlutterCommand { /// See: [DevelopmentArtifact] in `cache.dart` class ELinuxDevelopmentArtifact implements DevelopmentArtifact { // ignore: unused_element - const ELinuxDevelopmentArtifact._(this.name, {this.feature}); + const ELinuxDevelopmentArtifact._(this.name); @override final String name; @override - final Feature? feature; + final Feature? feature = null; static const DevelopmentArtifact elinux = ELinuxDevelopmentArtifact._('elinux'); }