diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index ad053bba9e..3d354cbf9c 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -853,6 +853,7 @@ FILE: ../../../flutter/lib/web_ui/lib/pointer.dart FILE: ../../../flutter/lib/web_ui/lib/semantics.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/alarm_clock.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/app_bootstrap.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/assets.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/browser_detection.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvas_pool.dart @@ -937,6 +938,8 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/transform.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/html_image_codec.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/initialization.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/js_interop/js_loader.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/js_interop/js_promise.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/key_map.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/keyboard.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart diff --git a/engine/src/flutter/lib/web_ui/lib/initialization.dart b/engine/src/flutter/lib/web_ui/lib/initialization.dart index c1da62120c..75f1f24e65 100644 --- a/engine/src/flutter/lib/web_ui/lib/initialization.dart +++ b/engine/src/flutter/lib/web_ui/lib/initialization.dart @@ -30,6 +30,72 @@ Future webOnlyInitializePlatform() async { await engine.initializeEngine(); } +/// Initializes essential bits of the engine before it fully initializes. +/// When [didCreateEngineInitializer] is set, it delegates engine initialization +/// and app startup to the programmer. +/// Else, it immediately triggers the full engine + app bootstrap. +/// +/// This method is called by the flutter_tools package, from the entrypoint that +/// it generates around the main method provided by the programmer. See: +/// * https://github.com/flutter/flutter/blob/2bd3e0d914854aa8c12e933f25c5fd8532ae5571/packages/flutter_tools/lib/src/build_system/targets/web.dart#L135-L163 +/// * https://github.com/flutter/flutter/blob/61fb2de52c7bdac19b7f2f74eaf3f11237e1e91d/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart#L460-L485 +/// +/// This function first calls [engine.initializeEngineServices] so the engine +/// can prepare the js-interop layer that is used by web apps (instead of the +/// old `ui.webOnlyFoo` methods/getters). +/// +/// It then creates a JsObject that is passed to the [didCreateEngineInitializer] +/// JS callback, to delegate bootstrapping the app to the programmer. +/// +/// If said callback is not defined, this assumes that the Flutter Web app is +/// initializing "automatically", as was normal before this feature was +/// introduced. This will immediately run the initEngine and runApp methods +/// (via [engine.AppBootstrap.now]). +/// +/// This is the only bit of `dart:ui` that should be directly called by Flutter +/// web apps. Everything else should go through the JS-interop layer created in +/// `engine.warmup`. +/// +/// This method should NOT trigger the download of any additional resources +/// (except when the app is in "autoStart" mode). +Future webOnlyWarmupEngine({ + Function? registerPlugins, + Function? runApp, +}) async { + // Create the object that knows how to bootstrap an app from JS and Dart. + final engine.AppBootstrap bootstrap = engine.AppBootstrap( + initEngine: () async { + await engine.initializeEngineServices(); + }, runApp: () async { + if (registerPlugins != null) { + registerPlugins(); + } + await engine.initializeEngineUi(); + if (runApp != null) { + runApp(); + } + }, + ); + + // Should the app "autoStart"? + bool autoStart = true; + try { + autoStart = engine.didCreateEngineInitializer == null; + } catch (e) { + // Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'loader') + autoStart = true; + } + if (autoStart) { + // The user does not want control of the app, bootstrap immediately. + print('Flutter Web Bootstrap: Auto'); + await bootstrap.autoStart(); + } else { + // Yield control of the bootstrap procedure to the user. + print('Flutter Web Bootstrap: Programmatic'); + engine.didCreateEngineInitializer!(bootstrap.prepareEngineInitializer()); + } +} + /// Emulates the `flutter test` environment. /// /// When set to true, the engine will emulate a specific screen size, and always diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine.dart b/engine/src/flutter/lib/web_ui/lib/src/engine.dart index f2128eac51..fedb0846f9 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine.dart @@ -16,6 +16,7 @@ library engine; export 'engine/alarm_clock.dart'; +export 'engine/app_bootstrap.dart'; export 'engine/assets.dart'; export 'engine/browser_detection.dart'; export 'engine/canvas_pool.dart'; @@ -98,6 +99,8 @@ export 'engine/html/surface_stats.dart'; export 'engine/html/transform.dart'; export 'engine/html_image_codec.dart'; export 'engine/initialization.dart'; +export 'engine/js_interop/js_loader.dart'; +export 'engine/js_interop/js_promise.dart'; export 'engine/key_map.dart'; export 'engine/keyboard.dart'; export 'engine/keyboard_binding.dart'; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/app_bootstrap.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/app_bootstrap.dart new file mode 100644 index 0000000000..b9d971e6a0 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/app_bootstrap.dart @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:js/js.dart'; + +import 'js_interop/js_loader.dart'; +import 'js_interop/js_promise.dart'; + +/// A class that controls the coarse lifecycle of a Flutter app. +class AppBootstrap { + /// Construct a FlutterLoader + AppBootstrap({required Function initEngine, required Function runApp}) : + _initEngine = initEngine, _runApp = runApp; + + // TODO(dit): Be more strict with the below typedefs, so we can add incoming params for each function. + + // A function to initialize the engine + final Function _initEngine; + + // A function to run the app + final Function _runApp; + + /// Immediately bootstraps the app. + /// + /// This calls `initEngine` and `runApp` in succession. + Future autoStart() async { + await _initEngine(); + await _runApp(); + } + + /// Creates an engine initializer that runs our encapsulated initEngine function. + FlutterEngineInitializer prepareEngineInitializer() { + return FlutterEngineInitializer( + // This is a convenience method that lets the programmer call "autoStart" + // from JavaScript immediately after the main.dart.js has loaded. + // Returns a promise that resolves to the Flutter app that was started. + autoStart: allowInterop(() { + return Promise(allowInterop(( + PromiseResolver resolve, + PromiseRejecter _, + ) async { + await autoStart(); + // Return the App that was just started + resolve(_prepareFlutterApp()); + })); + }), + // Calls [_initEngine], and returns a JS Promise that resolves to an + // app runner object. + initializeEngine: allowInterop(([InitializeEngineFnParameters? params]) { + // `params` coming from Javascript may be used to configure the engine intialization. + // The internal `initEngine` function must accept those params, and then this + // code needs to be slightly modified to pass them to the initEngine call below. + return Promise(allowInterop(( + PromiseResolver resolve, + PromiseRejecter _, + ) async { + await _initEngine(); + // Return an app runner object + resolve(_prepareAppRunner()); + })); + }), + ); + } + + /// Creates an appRunner that runs our encapsulated runApp function. + FlutterAppRunner _prepareAppRunner() { + return FlutterAppRunner(runApp: allowInterop(([RunAppFnParameters? params]) { + // `params` coming from JS may be used to configure the run app method. + return Promise(allowInterop(( + PromiseResolver resolve, + PromiseRejecter _, + ) async { + await _runApp(); + // Return the App that was just started + resolve(_prepareFlutterApp()); + })); + })); + } + + /// Represents the App that was just started, and its JS API. + FlutterApp _prepareFlutterApp() { + return FlutterApp(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/js_interop/js_loader.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/js_interop/js_loader.dart new file mode 100644 index 0000000000..97b3a6e4c4 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/js_interop/js_loader.dart @@ -0,0 +1,103 @@ +// Copyright 2013 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. + +@JS() +library js_loader; + +import 'package:js/js.dart'; + +import 'js_promise.dart'; + +/// Typedef for the function that notifies JS that the main entrypoint is up and running. +/// As a parameter, a [FlutterEngineInitializer] instance is passed to JS, so the +/// programmer can control the initialization sequence. +typedef DidCreateEngineInitializerFn = void Function(FlutterEngineInitializer); + +// A JS-interop representation of `_flutter?.loader?.didCreateEngineInitializer?`: + +@JS('_flutter.loader.didCreateEngineInitializer') +external DidCreateEngineInitializerFn? get didCreateEngineInitializer; + +// /// window._flutter +// @JS('_flutter') +// external FlutterJsNamespace? get flutterjs; + +// /// window._flutter.loader +// @JS() +// @anonymous +// class FlutterJsNamespace { +// external FlutterJsLoaderNamespace? get loader; +// } + +// /// The bits of window._flutter.loader that the Flutter Engine cares about. +// @JS() +// @anonymous +// class FlutterJsLoaderNamespace { +// /// A hook to notify JavaScript that Flutter is up and running! +// /// This is setup by flutter.js when the main entrypoint bundle is injected. +// external DidCreateEngineInitializerFn? get didCreateEngineInitializer; +// } + +// FlutterEngineInitializer + +/// An object that allows the user to initialize the Engine of a Flutter App. +/// +/// As a convenience method, [autoStart] allows the user to immediately initialize +/// and run a Flutter Web app, from JavaScript. +@JS() +@anonymous +abstract class FlutterEngineInitializer{ + external factory FlutterEngineInitializer({ + required InitializeEngineFn initializeEngine, + required ImmediateRunAppFn autoStart, + }); +} + +/// The shape of the object that can be passed as parameter to the +/// initializeEngine function of the FlutterEngineInitializer object +/// (when called from JS). +@JS() +@anonymous +abstract class InitializeEngineFnParameters { +} + +/// Typedef for the function that initializes the flutter engine. +typedef InitializeEngineFn = Promise Function([InitializeEngineFnParameters?]); + +/// Typedef for the `autoStart` function that can be called straight from an engine initializer instance. +/// (Similar to [RunAppFn], but taking no specific "runApp" parameters). +typedef ImmediateRunAppFn = Promise Function(); + +// FlutterAppRunner + +/// A class that exposes a function that runs the Flutter app, +/// and returns a promise of a FlutterAppCleaner. +@JS() +@anonymous +abstract class FlutterAppRunner { + /// Runs a flutter app + external factory FlutterAppRunner({ + required RunAppFn runApp, // Returns an App + }); +} + +/// The shape of the object that can be passed as parameter to the +/// runApp function of the FlutterAppRunner object (from JS). +@JS() +@anonymous +abstract class RunAppFnParameters { +} + +/// Typedef for the function that runs the flutter app main entrypoint. +typedef RunAppFn = Promise Function([RunAppFnParameters?]); + +// FlutterApp + +/// A class that exposes the public API of a running Flutter Web App running. +@JS() +@anonymous +abstract class FlutterApp { + /// Cleans a Flutter app + external factory FlutterApp(); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/js_interop/js_promise.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/js_interop/js_promise.dart new file mode 100644 index 0000000000..13327158ae --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/js_interop/js_promise.dart @@ -0,0 +1,22 @@ +// Copyright 2013 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. + +@JS() +library js_promise; + +import 'package:js/js.dart'; + +/// Type-safe JS Promises +@JS('Promise') +abstract class Promise { + /// A constructor for a JS promise + external factory Promise(PromiseExecutor executor); +} + +/// The type of function that is used to create a Promise +typedef PromiseExecutor = void Function(PromiseResolver resolve, PromiseRejecter reject); +/// The type of function used to resolve a Promise +typedef PromiseResolver = void Function(T result); +/// The type of function used to reject a Promise (of any ) +typedef PromiseRejecter = void Function(Object? error); diff --git a/engine/src/flutter/lib/web_ui/test/engine/app_bootstrap_test.dart b/engine/src/flutter/lib/web_ui/test/engine/app_bootstrap_test.dart new file mode 100644 index 0000000000..3bf509f6ee --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/engine/app_bootstrap_test.dart @@ -0,0 +1,97 @@ +// Copyright 2013 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. + +@TestOn('browser') + +import 'dart:js_util'; + +import 'package:test/bootstrap/browser.dart'; +import 'package:test/test.dart'; +import 'package:ui/src/engine.dart'; + +void main() { + internalBootstrapBrowserTest(() => testMain); +} + +void testMain() { + + int callOrder = 1; + int initCalled = 0; + int runCalled = 0; + + setUp(() { + callOrder = 1; + initCalled = 0; + runCalled = 0; + }); + + Future mockInit () async { + initCalled = callOrder++; + await Future.delayed(const Duration(milliseconds: 1)); + } + + void mockRunApp () { + runCalled = callOrder++; + } + + test('autoStart() immediately calls init and run', () async { + final AppBootstrap bootstrap = AppBootstrap( + initEngine: mockInit, + runApp: mockRunApp, + ); + + await bootstrap.autoStart(); + + expect(initCalled, 1, reason: 'initEngine should be called first.'); + expect(runCalled, 2, reason: 'runApp should be called after init.'); + }); + + test('engineInitializer autoStart() does the same as Dart autoStart()', () async { + final AppBootstrap bootstrap = AppBootstrap( + initEngine: mockInit, + runApp: mockRunApp, + ); + + final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer(); + + expect(engineInitializer, isNotNull); + + final Object maybeApp = await promiseToFuture(callMethod(engineInitializer, 'autoStart', [])); + + expect(maybeApp, isA()); + expect(initCalled, 1, reason: 'initEngine should be called first.'); + expect(runCalled, 2, reason: 'runApp should be called after init.'); + }); + + test('engineInitializer initEngine() calls init and returns an appRunner', () async { + final AppBootstrap bootstrap = AppBootstrap( + initEngine: mockInit, + runApp: mockRunApp, + ); + + final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer(); + + final Object maybeAppInitializer = await promiseToFuture(callMethod(engineInitializer, 'initializeEngine', [])); + + expect(maybeAppInitializer, isA()); + expect(initCalled, 1, reason: 'initEngine should have been called.'); + expect(runCalled, 0, reason: 'runApp should not have been called.'); + }); + + test('appRunner runApp() calls run and returns a FlutterApp', () async { + final AppBootstrap bootstrap = AppBootstrap( + initEngine: mockInit, + runApp: mockRunApp, + ); + + final FlutterEngineInitializer engineInitializer = bootstrap.prepareEngineInitializer(); + + final Object appInitializer = await promiseToFuture(callMethod(engineInitializer, 'initializeEngine', [])); + final Object maybeApp = await promiseToFuture(callMethod(appInitializer, 'runApp', [])); + + expect(maybeApp, isA()); + expect(initCalled, 1, reason: 'initEngine should have been called.'); + expect(runCalled, 2, reason: 'runApp should have been called.'); + }); +} diff --git a/engine/src/flutter/lib/web_ui/test/initialization_test.dart b/engine/src/flutter/lib/web_ui/test/initialization_test.dart new file mode 100644 index 0000000000..93806b77ed --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/initialization_test.dart @@ -0,0 +1,73 @@ +// Copyright 2013 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:js' as js; + +import 'package:test/bootstrap/browser.dart'; +import 'package:test/test.dart'; +import 'package:ui/src/engine.dart' as engine; +import 'package:ui/ui.dart' as ui; + +void main() { + // Prepare _flutter.loader.didCreateEngineInitializer, so it's ready in the page ASAP. + js.context['_flutter'] = js.JsObject.jsify({ + 'loader': { + 'didCreateEngineInitializer': js.allowInterop(() { print('not mocked'); }), + }, + }); + internalBootstrapBrowserTest(() => testMain); +} + +void testMain() { + test('webOnlyWarmupEngine calls _flutter.loader.didCreateEngineInitializer callback', () async { + js.JsObject? engineInitializer; + + void didCreateEngineInitializerMock (js.JsObject obj) { + engineInitializer = obj; + } + + // Prepare the DOM for: _flutter.loader.didCreateEngineInitializer + js.context['_flutter']['loader']['didCreateEngineInitializer'] = js.allowInterop(didCreateEngineInitializerMock); + + // Reset the engine + engine.debugResetEngineInitializationState(); + + await ui.webOnlyWarmupEngine( + registerPlugins: () {}, + runApp: () {}, + ); + + // Check that the object we captured is actually a loader + expect(engineInitializer, isNotNull); + expect(engineInitializer!.hasProperty('initializeEngine'), isTrue, reason: 'Missing FlutterEngineInitializer method: initializeEngine.'); + expect(engineInitializer!.hasProperty('autoStart'), isTrue, reason: 'Missing FlutterEngineInitializer method: autoStart.'); + }); + + test('webOnlyWarmupEngine does auto-start when _flutter.loader.didCreateEngineInitializer does not exist', () async { + js.context['_flutter']['loader'] = null; + + bool pluginsRegistered = false; + bool appRan = false; + void registerPluginsMock() { + pluginsRegistered = true; + } + void runAppMock() { + appRan = true; + } + + // Reset the engine + engine.debugResetEngineInitializationState(); + + await ui.webOnlyWarmupEngine( + registerPlugins: registerPluginsMock, + runApp: runAppMock, + ); + + // Check that the object we captured is actually a loader + expect(pluginsRegistered, isTrue, reason: 'Plugins should be immediately registered in autoStart mode.'); + expect(appRan, isTrue, reason: 'App should run immediately in autoStart mode'); + }); + // We cannot test anymore, because by now the engine has registered some stuff that can't be rewound back. + // Like the `ext.flutter.disassemble` developer extension. +}