flutter/dev/integration_tests/ios_host_app/flutterapp/lib/main
Daco Harkes aa36db1d29
Native assets support for MacOS and iOS (#130494)
Support for FFI calls with `@Native external` functions through Native assets on MacOS and iOS. This enables bundling native code without any build-system boilerplate code.

For more info see:

* https://github.com/flutter/flutter/issues/129757

### Implementation details for MacOS and iOS.

Dylibs are bundled by (1) making them fat binaries if multiple architectures are targeted, (2) code signing these, and (3) copying them to the frameworks folder. These steps are done manual rather than via CocoaPods. CocoaPods would have done the same steps, but (a) needs the dylibs to be there before the `xcodebuild` invocation (we could trick it, by having a minimal dylib in the place and replace it during the build process, that works), and (b) can't deal with having no dylibs to be bundled (we'd have to bundle a dummy dylib or include some dummy C code in the build file).

The dylibs are build as a new target inside flutter assemble, as that is the moment we know what build-mode and architecture to target.

The mapping from asset id to dylib-path is passed in to every kernel compilation path. The interesting case is hot-restart where the initial kernel file is compiled by the "inner" flutter assemble, while after hot restart the "outer" flutter run compiled kernel file is pushed to the device. Both kernel files need to contain the mapping. The "inner" flutter assemble gets its mapping from the NativeAssets target which builds the native assets. The "outer" flutter run get its mapping from a dry-run invocation. Since this hot restart can be used for multiple target devices (`flutter run -d all`) it contains the mapping for all known targets.

### Example vs template

The PR includes a new template that uses the new native assets in a package and has an app importing that. Separate discussion in: https://github.com/flutter/flutter/issues/131209.

### Tests

This PR adds new tests to cover the various use cases.

* dev/devicelab/bin/tasks/native_assets_ios.dart
  * Runs an example app with native assets in all build modes, doing hot reload and hot restart in debug mode.
* dev/devicelab/bin/tasks/native_assets_ios_simulator.dart
  * Runs an example app with native assets, doing hot reload and hot restart.
* packages/flutter_tools/test/integration.shard/native_assets_test.dart
  * Runs (incl hot reload/hot restart), builds, builds frameworks for iOS, MacOS and flutter-tester.
* packages/flutter_tools/test/general.shard/build_system/targets/native_assets_test.dart
  * Unit tests the new Target in the backend.
* packages/flutter_tools/test/general.shard/ios/native_assets_test.dart
* packages/flutter_tools/test/general.shard/macos/native_assets_test.dart
  * Unit tests the native assets being packaged on a iOS/MacOS build.

It also extends various existing tests:

* dev/devicelab/bin/tasks/module_test_ios.dart
   * Exercises the add2app scenario.
* packages/flutter_tools/test/general.shard/features_test.dart
   * Unit test the new feature flag.
2023-09-10 08:07:13 +00:00

204 lines
6.3 KiB
Plaintext

// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ffi_package/ffi_package.dart';
import 'marquee.dart';
/// Route names. (See [main] for more details.)
///
/// The route names must match those sent by the platform-specific component.
const String greenMarqueeRouteName = 'marquee_green';
const String purpleMarqueeRouteName = 'marquee_purple';
const String fullscreenRouteName = 'full';
const String hybridRouteName = 'hybrid';
/// Channel used to let the Flutter app know to reset the app to a specific
/// route. See the [run] method.
///
/// We shouldn't use the `setInitialRoute` method on the system
/// navigation channel, as that never gets propagated back to Flutter
/// after the initial call.
const String _kReloadChannelName = 'reload';
const BasicMessageChannel<String> _kReloadChannel =
BasicMessageChannel<String>(_kReloadChannelName, StringCodec());
void main() {
// Ensures bindings are initialized before doing anything.
WidgetsFlutterBinding.ensureInitialized();
// Start listening immediately for messages from the iOS side. ObjC calls
// will be made to let us know when we should be changing the app state.
_kReloadChannel.setMessageHandler(run);
// Start off with whatever the initial route is supposed to be.
run(ui.window.defaultRouteName);
}
Future<String> run(String? name) async {
// The platform-specific component will call [setInitialRoute] on the Flutter
// view (or view controller for iOS) to set [ui.window.defaultRouteName].
// We then dispatch based on the route names to show different Flutter
// widgets.
// Since we don't really care about Flutter-side navigation in this app, we're
// not using a regular routes map.
name ??= '';
switch (name) {
case greenMarqueeRouteName:
runApp(Marquee(color: Colors.green[400]));
break;
case purpleMarqueeRouteName:
runApp(Marquee(color: Colors.purple[400]));
break;
case fullscreenRouteName:
case hybridRouteName:
default:
runApp(FlutterView(initialRoute: name));
break;
}
return '';
}
class FlutterView extends StatelessWidget {
const FlutterView({required this.initialRoute});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter View',
home: MyHomePage(initialRoute: initialRoute),
);
}
final String initialRoute;
}
class MyHomePage extends StatefulWidget {
const MyHomePage({required this.initialRoute});
@override
_MyHomePageState createState() => _MyHomePageState();
final String initialRoute;
/// Whether we should display the home page in fullscreen mode.
///
/// If in full screen mode, we will use an [AppBar] widget to show our own
/// title.
bool get isFullscreen => initialRoute == fullscreenRouteName;
/// Whether tapping the Flutter button should notify an external source.
///
/// If false, the button will increments our own internal counter.
bool get hasExternalTarget => initialRoute == hybridRouteName;
}
class _MyHomePageState extends State<MyHomePage> {
// The name of the message channel used to communicate with the
// platform-specific component.
//
// This string must match the one used on the platform side.
static const String _channel = 'increment';
// The message to send to the platform-specific component when our button
// is tapped.
static const String _pong = 'pong';
// Used to pass messages between the platform-specific component and the
// Flutter component.
static const BasicMessageChannel<String> _platform =
BasicMessageChannel<String>(_channel, StringCodec());
// An internal count. Normally this represents the number of times that the
// button on the Flutter page has been tapped.
int _counter = 0;
late int sumResult;
late Future<int> sumAsyncResult;
@override
void initState() {
super.initState();
_platform.setMessageHandler(_handlePlatformIncrement);
sumResult = sum(1, 2);
sumAsyncResult = sumAsync(3, 4);
}
/// Directly increments our internal counter and rebuilds the UI.
void _incrementCounter() {
setState(() {
_counter++;
});
}
/// Callback for messages sent by the platform-specific component.
///
/// Increments our internal counter.
Future<String> _handlePlatformIncrement(String? message) async {
// Normally we'd dispatch based on the value of [message], but in this
// sample, there is only one message that is sent to us.
_incrementCounter();
return '';
}
/// Sends a message to the platform-specific component to increment its
/// counter.
void _sendFlutterIncrement() {
_platform.send(_pong);
}
@override
Widget build(BuildContext context) {
final String buttonName =
widget.hasExternalTarget ? 'Platform button' : 'Button';
return Scaffold(
appBar: widget.isFullscreen
? AppBar(title: const Text('Fullscreen Flutter'))
: null,
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text(
'$buttonName tapped $_counter time${_counter == 1 ? '' : 's'}.',
style: const TextStyle(fontSize: 17.0),
),
),
const TextButton(
child: Text('POP'),
onPressed: SystemNavigator.pop,
),
],
),
),
Container(
padding: const EdgeInsets.only(bottom: 15.0, left: 5.0),
child: Row(
children: const <Widget>[
Text('Flutter', style: TextStyle(fontSize: 30.0)),
],
),
),
],
),
floatingActionButton: Semantics(
label: 'Increment via Flutter',
child: FloatingActionButton(
onPressed: widget.hasExternalTarget
? _sendFlutterIncrement
: _incrementCounter,
child: const Icon(Icons.add),
),
),
);
}
}