From b785173490121a9469bf4f2e4c5f646c3a52885d Mon Sep 17 00:00:00 2001 From: 18719058668 <718092089@qq.com> Date: Wed, 25 Oct 2023 12:15:59 +0800 Subject: [PATCH] typescript to arkts migration modify Signed-off-by: 18719058668 <718092089@qq.com> --- .../libflutter/{index.d.ts => index.d.ets} | 4 +- .../{index_actual.d.ts => index_actual.d.ets} | 0 .../cpp/types/libflutter/oh-package.json5 | 2 +- .../flutter/src/main/ets/FlutterInjector.ets | 6 +- .../main/ets/app/FlutterPluginRegistry.ets | 4 +- .../ets/embedding/engine/FlutterEngine.ets | 68 +-- .../embedding/engine/FlutterEngineCache.ets | 12 +- .../FlutterEngineConnectionRegistry.ets | 44 +- .../embedding/engine/FlutterEngineGroup.ets | 65 ++- .../engine/FlutterEngineGroupCache.ets | 4 +- .../main/ets/embedding/engine/FlutterNapi.ets | 34 +- .../embedding/engine/dart/DartExecutor.ets | 19 +- .../embedding/engine/dart/DartMessenger.ets | 12 +- .../engine/loader/ApplicationInfoLoader.ets | 4 +- .../engine/loader/FlutterApplicationInfo.ets | 9 +- .../embedding/engine/loader/FlutterLoader.ets | 68 +-- .../mutatorsstack/FlutterMutatorView.ets | 98 ++-- .../mutatorsstack/FlutterMutatorsStack.ets | 16 +- .../engine/plugins/FlutterPlugin.ets | 9 +- .../plugins/ability/AbilityControlSurface.ets | 2 +- .../plugins/ability/AbilityPluginBinding.ets | 4 +- .../systemchannels/AccessibilityChannel.ets | 18 +- .../engine/systemchannels/KeyEventChannel.ets | 2 +- .../systemchannels/LocalizationChannel.ets | 6 +- .../systemchannels/MouseCursorChannel.ets | 6 +- .../systemchannels/NavigationChannel.ets | 16 +- .../engine/systemchannels/PlatformChannel.ets | 478 +++++++++--------- .../systemchannels/PlatformViewsChannel.ets | 192 +++---- .../systemchannels/RestorationChannel.ets | 88 ++-- .../engine/systemchannels/SettingsChannel.ets | 4 +- .../engine/systemchannels/SystemChannel.ets | 6 +- .../engine/systemchannels/TestChannel.ets | 16 +- .../systemchannels/TextInputChannel.ets | 205 ++++---- .../ets/embedding/ohos/FlutterAbility.ets | 159 +++--- .../embedding/ohos/FlutterAbilityDelegate.ets | 167 +++--- .../embedding/ohos/FlutterEngineProvider.ets | 2 +- .../main/ets/embedding/ohos/FlutterPage.ets | 3 +- .../ets/embedding/ohos/OhosTouchProcessor.ets | 2 +- .../src/main/ets/embedding/ohos/Settings.ets | 6 +- .../ets/embedding/ohos/TouchEventTracker.ets | 11 +- .../src/main/ets/plugin/PlatformPlugin.ets | 342 +++++++------ .../ets/plugin/common/BasicMessageChannel.ets | 13 +- .../ets/plugin/common/BinaryMessenger.ets | 35 +- .../main/ets/plugin/common/EventChannel.ets | 16 +- .../ets/plugin/common/FlutterException.ets | 6 +- .../ets/plugin/common/JSONMessageCodec.ets | 9 +- .../ets/plugin/common/JSONMethodCodec.ets | 25 +- .../src/main/ets/plugin/common/MethodCall.ets | 12 +- .../main/ets/plugin/common/MethodChannel.ets | 21 +- .../main/ets/plugin/common/MethodCodec.ets | 8 +- .../plugin/common/StandardMessageCodec.ets | 30 +- .../ets/plugin/common/StandardMethodCodec.ets | 20 +- .../main/ets/plugin/common/StringCodec.ets | 4 +- .../plugin/editing/ListenableEditingState.ets | 26 +- .../ets/plugin/editing/TextEditingDelta.ets | 26 +- .../ets/plugin/editing/TextInputPlugin.ets | 207 ++++---- .../localization/LocalizationPlugin.ets | 19 +- .../ets/plugin/mouse/MouseCursorPlugin.ets | 4 +- .../platform/AccessibilityEventsDelegate.ets | 2 +- .../plugin/platform/PlatformOverlayView.ets | 2 +- .../plugin/platform/PlatformViewFactory.ets | 8 +- .../plugin/platform/PlatformViewWrapper.ets | 93 ++-- .../PlatformViewsAccessibilityDelegate.ets | 2 +- .../platform/PlatformViewsController.ets | 114 +++-- .../plugin/platform/RootDvModelManager.ets | 31 +- .../flutter/src/main/ets/util/ByteBuffer.ets | 213 ++++---- .../flutter/src/main/ets/util/Log.ets | 40 +- .../flutter/src/main/ets/util/StringUtils.ets | 2 +- .../flutter/src/main/ets/util/ToolUtils.ets | 6 +- .../src/main/ets/util/TraceSection.ets | 4 +- .../main/ets/view/DynamicView/dynamicView.ets | 88 ++-- .../ets/view/DynamicView/dynamicViewJson.ets | 29 +- .../ets/view/FlutterCallbackInformation.ets | 2 +- 73 files changed, 1772 insertions(+), 1558 deletions(-) rename shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/{index.d.ts => index.d.ets} (99%) rename shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/{index_actual.d.ts => index_actual.d.ets} (100%) diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ts b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets similarity index 99% rename from shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ts rename to shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets index 67f9580813..ee0d9abe81 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ts +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets @@ -31,7 +31,7 @@ export class napiContext { */ export const nativeUpdateRefreshRate: ( ate: number -) => {}; +) => void; /** * 初始化dart vm和flutter engine @@ -76,6 +76,6 @@ export const nativeSetViewportMetrics: (nativeShellHolderId: number, devicePixel , systemGestureInsetLeft: number, physicalTouchSlop: number, displayFeaturesBounds: Array , displayFeaturesType: Array, displayFeaturesState: Array) => void; -export const nativeImageDecodeCallback: (width: number, height: number, imageGeneratorPointer: number, pixelMap : image.PixelMap) => void; +export const nativeImageDecodeCallback: (width: number, height: number, imageGeneratorPointer: number, pixelMap : image.PixelMap | null) => void; export const nativeGetSystemLanguages: (nativeShellHolderId: number, languages: Array) => void; \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ts b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ets similarity index 100% rename from shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ts rename to shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ets diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 index 216ed0d720..5d1822ef86 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 @@ -15,7 +15,7 @@ { "name": "libflutter.so", - "types": "./index.d.ts", + "types": "./index.d.ets", "version": "", "description": "Please describe the basic information." } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets index db12ccb09d..4e6f2f8b0e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets @@ -26,10 +26,10 @@ export default class FlutterInjector { private flutterNapi: FlutterNapi; static getInstance(): FlutterInjector { - if (this.instance == null) { - this.instance = new FlutterInjector(); + if (FlutterInjector.instance == null) { + FlutterInjector.instance = new FlutterInjector(); } - return this.instance; + return FlutterInjector.instance; } /** * 初始化 diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets index 760659f83d..2a2a44964d 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets @@ -12,11 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import FlutterView from '../embedding/ohos/FlutterView'; +import { FlutterView } from '../view/FlutterView'; import common from '@ohos.app.ability.common'; import PlatformViewController from '../plugin/platform/PlatformViewsController' -import Log from '../util/Log'; export default class FlutterPluginRegistry { private mPlatformViewsController: PlatformViewController; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngine.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngine.ets index 4a16a419d9..47ff37a1cf 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngine.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngine.ets @@ -52,22 +52,22 @@ export default class FlutterEngine implements EngineLifecycleListener{ private flutterLoader: FlutterLoader; private assetManager: resourceManager.ResourceManager; //channel定义 - private lifecycleChannel: LifecycleChannel; - private navigationChannel: NavigationChannel; - private textInputChannel: TextInputChannel; - private testChannel: TestChannel; - private platformChannel: PlatformChannel; - private systemChannel: SystemChannel; - private mouseCursorChannel: MouseCursorChannel; - private restorationChannel: RestorationChannel; - - private accessibilityChannel: AccessibilityChannel; - private localeChannel: LocalizationChannel; + private lifecycleChannel: LifecycleChannel | null = null; + private navigationChannel: NavigationChannel | null = null; + private textInputChannel: TextInputChannel | null = null; + private testChannel: TestChannel | null = null; + private platformChannel: PlatformChannel | null = null; + private systemChannel: SystemChannel | null = null; + private mouseCursorChannel: MouseCursorChannel | null = null; + private restorationChannel: RestorationChannel | null = null; + + private accessibilityChannel: AccessibilityChannel | null = null; + private localeChannel: LocalizationChannel | null = null; private flutterNapi: FlutterNapi; - private pluginRegistry: FlutterEngineConnectionRegistry; - private textInputPlugin: TextInputPlugin; - private localizationPlugin: LocalizationPlugin; - private settingsChannel: SettingsChannel; + private pluginRegistry: FlutterEngineConnectionRegistry | null = null; + private textInputPlugin: TextInputPlugin | null = null; + private localizationPlugin: LocalizationPlugin | null = null; + private settingsChannel: SettingsChannel | null = null; private platformViewsController: PlatformViewsController; /** @@ -79,7 +79,7 @@ export default class FlutterEngine implements EngineLifecycleListener{ * 5、初始化flutterNapi * 6、engineLifecycleListeners */ - constructor(context: common.Context, flutterLoader: FlutterLoader, flutterNapi: FlutterNapi, platformViewsController: PlatformViewsController) { + constructor(context: common.Context, flutterLoader: FlutterLoader | null, flutterNapi: FlutterNapi | null, platformViewsController: PlatformViewsController) { const injector: FlutterInjector = FlutterInjector.getInstance(); if(flutterNapi == null){ @@ -103,8 +103,8 @@ export default class FlutterEngine implements EngineLifecycleListener{ this.platformViewsController.attach(context, null, this.dartExecutor); } - async init(context: common.Context, dartVmArgs: Array, automaticallyRegisterPlugins: boolean, - waitForRestorationData: boolean, group: FlutterEngineGroup) { + async init(context: common.Context, dartVmArgs: Array | null, automaticallyRegisterPlugins: boolean, + waitForRestorationData: boolean, group: FlutterEngineGroup | null) { if (!this.flutterNapi.isAttached()) { await this.flutterLoader.startInitialization(context) this.flutterLoader.ensureInitializationComplete(dartVmArgs); @@ -132,7 +132,7 @@ export default class FlutterEngine implements EngineLifecycleListener{ this.attachToNapi(); } - this.pluginRegistry = new FlutterEngineConnectionRegistry(context.getApplicationContext(), this, this.flutterLoader, group); + this.pluginRegistry = new FlutterEngineConnectionRegistry(context.getApplicationContext(), this, this.flutterLoader, group!); this.localizationPlugin.sendLocaleToFlutter(); } @@ -177,31 +177,31 @@ export default class FlutterEngine implements EngineLifecycleListener{ return this.flutterNapi.isAttached(); } - getLifecycleChannel(): LifecycleChannel { + getLifecycleChannel(): LifecycleChannel | null { return this.lifecycleChannel; } - getNavigationChannel(): NavigationChannel { + getNavigationChannel(): NavigationChannel | null { return this.navigationChannel; } - getTextInputChannel(): TextInputChannel { + getTextInputChannel(): TextInputChannel | null { return this.textInputChannel; } - getPlatformChannel(): PlatformChannel { + getPlatformChannel(): PlatformChannel | null { return this.platformChannel; } - getSystemChannel(): SystemChannel { + getSystemChannel(): SystemChannel | null { return this.systemChannel; } - getLocaleChannel(): LocalizationChannel { + getLocaleChannel(): LocalizationChannel | null { return this.localeChannel; } - getMouseCursorChannel(): MouseCursorChannel { + getMouseCursorChannel(): MouseCursorChannel | null { return this.mouseCursorChannel; } @@ -213,11 +213,11 @@ export default class FlutterEngine implements EngineLifecycleListener{ return this.dartExecutor } - getPlugins(): PluginRegistry { + getPlugins(): PluginRegistry | null { return this.pluginRegistry; } - getAbilityControlSurface(): AbilityControlSurface { + getAbilityControlSurface(): AbilityControlSurface | null { return this.pluginRegistry; } @@ -245,19 +245,19 @@ export default class FlutterEngine implements EngineLifecycleListener{ Log.d(TAG, "Destroying."); this.engineLifecycleListeners.forEach(listener => listener.onEngineWillDestroy()) this.flutterNapi.removeEngineLifecycleListener(this); - this.pluginRegistry.detachFromAbility(); - this.platformViewsController.onDetachedFromNapi(); + this.pluginRegistry?.detachFromAbility(); + this.platformViewsController?.onDetachedFromNapi(); } - getRestorationChannel(): RestorationChannel{ + getRestorationChannel(): RestorationChannel | null { return this.restorationChannel; } - getAccessibilityChannel(): AccessibilityChannel { + getAccessibilityChannel(): AccessibilityChannel | null { return this.accessibilityChannel; } - getLocalizationPlugin(): LocalizationPlugin { + getLocalizationPlugin(): LocalizationPlugin | null { return this.localizationPlugin; } @@ -265,7 +265,7 @@ export default class FlutterEngine implements EngineLifecycleListener{ return this.flutterNapi.getSystemLanguages(); } - getPlatformViewsController(): PlatformViewsController { + getPlatformViewsController(): PlatformViewsController | null { return this.platformViewsController; } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets index bfc0691b64..7808dfd8af 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets @@ -20,10 +20,10 @@ export default class FlutterEngineCache { private cachedEngines: Map = new Map(); static getInstance(): FlutterEngineCache { - if (this.instance == null) { - this.instance = new FlutterEngineCache(); + if (FlutterEngineCache.instance == null) { + FlutterEngineCache.instance = new FlutterEngineCache(); } - return this.instance; + return FlutterEngineCache.instance; } /** * 返回engineId对应的FlutterEngine是否存在 @@ -35,13 +35,13 @@ export default class FlutterEngineCache { /** * 返回engineId对应的FlutterEngine */ - get(engineId: String) : FlutterEngine { - return this.cachedEngines.get(engineId); + get(engineId: String) : FlutterEngine | null { + return this.cachedEngines.get(engineId) || null; } /** * 将传入的FlutterEngine与engineId放在缓存中 */ - put(engineId :String, engine: FlutterEngine): void { + put(engineId :String, engine: FlutterEngine | null): void { if(engine != null) { this.cachedEngines.set(engineId, engine); } else { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets index 3ca45c9f4c..a596d2e25e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets @@ -41,6 +41,8 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, // PluginRegistry private plugins = new Map(); + private defaultPlugin : FlutterPlugin = new EmptyPlugin(); + // Standard FlutterPlugin private flutterEngine: FlutterEngine; private pluginBinding: FlutterPluginBinding; @@ -48,8 +50,8 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, // AbilityAware private abilityAwarePlugins = new Map(); - private exclusiveAbility: ExclusiveAppComponent; - private abilityPluginBinding: FlutterEngineAbilityPluginBinding; + private exclusiveAbility: ExclusiveAppComponent | null = null; + private abilityPluginBinding: FlutterEngineAbilityPluginBinding | null = null; constructor(appContext: common.Context, flutterEngine: FlutterEngine, flutterLoader: FlutterLoader, group: FlutterEngineGroup) { this.flutterEngine = flutterEngine; @@ -80,7 +82,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, // plugins, and if this engine is currently attached to an Ability, // notify the AbilityAware plugin that it is now attached to an Ability. if (ToolUtils.implementsInterface(plugin, "onAttachedToAbility")) { - const abilityAware = plugin as any + const abilityAware: ESObject = plugin; this.abilityAwarePlugins.set(plugin.getUniqueClassName(), abilityAware); if (this.isAttachedToAbility()) { abilityAware.onAttachedToAbility(this.abilityPluginBinding); @@ -100,7 +102,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, } get(pluginClassName: string): FlutterPlugin { - return this.plugins.get(pluginClassName); + return this.plugins.get(pluginClassName) ?? this.defaultPlugin; } remove(pluginClassName: string): void { @@ -110,7 +112,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, } if (ToolUtils.implementsInterface(plugin, "onAttachedToAbility")) { if (this.isAttachedToAbility()) { - const abilityAware = plugin as any + const abilityAware: ESObject = plugin; abilityAware.onDetachedFromAbility(); } this.abilityAwarePlugins.delete(pluginClassName); @@ -154,15 +156,15 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, } onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void { - this.abilityPluginBinding.onNewWant(want, launchParams); + this.abilityPluginBinding?.onNewWant(want, launchParams); } onWindowFocusChanged(hasFocus: boolean): void { - this.abilityPluginBinding.onWindowFocusChanged(hasFocus); + this.abilityPluginBinding?.onWindowFocusChanged(hasFocus); } - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult { - return this.abilityPluginBinding.onSaveState(reason, wantParam); + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult { + return this.abilityPluginBinding?.onSaveState(reason, wantParam) ?? AbilityConstant.OnSaveResult.ALL_REJECT; } private detachFromAppComponent(): void { @@ -174,7 +176,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, private attachToAbilityInternal(ability: UIAbility): void { this.abilityPluginBinding = new FlutterEngineAbilityPluginBinding(ability); // Notify all AbilityAware plugins that they are now attached to a new Ability. - this.abilityAwarePlugins.forEach(abilityAware => abilityAware.onAttachedToAbility(this.abilityPluginBinding)); + this.abilityAwarePlugins.forEach(abilityAware => abilityAware.onAttachedToAbility(this.abilityPluginBinding!)); } private detachFromAbilityInternal(): void { @@ -230,19 +232,19 @@ class FlutterEngineAbilityPluginBinding implements AbilityPluginBinding { onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void { this.onNewWantListeners.forEach((listener, key) => { - listener.onNewWant(want, launchParams) + listener?.onNewWant(want, launchParams) }); } onWindowFocusChanged(hasFocus: boolean): void { this.onWindowFocusChangedListeners.forEach((listener, key) => { - listener.onWindowFocusChanged(hasFocus) + listener?.onWindowFocusChanged(hasFocus) }); } - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult { + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult { this.onSaveStateListeners.forEach((listener, key) => { - listener.onSaveState(reason, wantParam) + listener?.onSaveState(reason, wantParam) }); return AbilityConstant.OnSaveResult.ALL_AGREE; } @@ -262,4 +264,18 @@ class DefaultFlutterAssets implements FlutterAssets { getAssetFilePathBySubpath(assetSubpath: string, packageName?: string) { return this.flutterLoader.getLookupKeyForAsset(assetSubpath, packageName); } +} + +class EmptyPlugin implements FlutterPlugin { + getUniqueClassName(): string { + return ''; + } + + onAttachedToEngine(binding: FlutterPluginBinding) { + + } + + onDetachedFromEngine(binding: FlutterPluginBinding) { + + } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets index 5e5c069fcb..f9fab12dcc 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets @@ -13,22 +13,23 @@ * limitations under the License. */ -import FlutterEngine from "./FlutterEngine" +import FlutterEngine, { EngineLifecycleListener } from "./FlutterEngine" import common from '@ohos.app.ability.common' import FlutterLoader from './loader/FlutterLoader' import FlutterInjector from '../../FlutterInjector' import { DartEntrypoint } from './dart/DartExecutor' import PlatformViewsController from '../../plugin/platform/PlatformViewsController' +import ArrayList from '@ohos.util.ArrayList' export default class FlutterEngineGroup { - private activeEngines: Array = new Array(); + private activeEngines: ArrayList = new ArrayList(); constructor() { } async checkLoader(context: common.Context, args: Array) { - var loader: FlutterLoader = FlutterInjector.getInstance().getFlutterLoader(); + let loader: FlutterLoader = FlutterInjector.getInstance().getFlutterLoader(); if (!loader.initialized) { await loader.startInitialization(context.getApplicationContext()); loader.ensureInitializationComplete(args); @@ -36,12 +37,12 @@ export default class FlutterEngineGroup { } async createAndRunEngineByOptions(options: Options) { - let engine: FlutterEngine = null; + let engine: FlutterEngine | null = null; let context: common.Context = options.getContext(); - let dartEntrypoint: DartEntrypoint = options.getDartEntrypoint(); + let dartEntrypoint: DartEntrypoint | null = options.getDartEntrypoint(); let initialRoute: string = options.getInitialRoute(); let dartEntrypointArgs: Array = options.getDartEntrypointArgs(); - let platformViewsController: PlatformViewsController = options.getPlatformViewsController(); + let platformViewsController: PlatformViewsController | null = options.getPlatformViewsController(); let automaticallyRegisterPlugins: boolean = options.getAutomaticallyRegisterPlugins(); let waitForRestorationData: boolean = options.getWaitForRestorationData(); @@ -60,7 +61,7 @@ export default class FlutterEngineGroup { waitForRestorationData, // boolean. this) if (initialRoute != null) { - engine.getNavigationChannel().setInitialRoute(initialRoute); + engine.getNavigationChannel()?.setInitialRoute(initialRoute); } } else { engine = await this.activeEngines[0] @@ -73,17 +74,14 @@ export default class FlutterEngineGroup { automaticallyRegisterPlugins, waitForRestorationData); } - this.activeEngines.push(engine); + this.activeEngines.add(engine); const engineToCleanUpOnDestroy = engine; - engine.addEngineLifecycleListener({ - onPreEngineRestart(): void { - platformViewsController.onPreEngineRestart(); - }, - onEngineWillDestroy(): void { - this.activeEngines.remove(engineToCleanUpOnDestroy); - } - }); + let listener: EngineLifecycleListener = new EngineLifecycleListenerImpl( + platformViewsController, + this.activeEngines, + engineToCleanUpOnDestroy); + engine?.addEngineLifecycleListener(listener); return engine; } @@ -92,12 +90,33 @@ export default class FlutterEngineGroup { } } +class EngineLifecycleListenerImpl implements EngineLifecycleListener { + private platformViewsController: PlatformViewsController; + private activeEngines: ArrayList = new ArrayList(); + private engine: FlutterEngine | null; + + constructor( + platformViewsController: PlatformViewsController, + activeEngines: ArrayList, + engine: FlutterEngine | null) { + this.platformViewsController = platformViewsController; + this.activeEngines = activeEngines; + this.engine = engine; + } + onPreEngineRestart(): void { + this.platformViewsController.onPreEngineRestart(); + } + onEngineWillDestroy(): void { + this.activeEngines.remove(this.engine); + } +} + export class Options { private context: common.Context; - private dartEntrypoint: DartEntrypoint; - private initialRoute: string; - private dartEntrypointArgs: Array; - private platformViewsController: PlatformViewsController; + private dartEntrypoint: DartEntrypoint | null = null; + private initialRoute: string = ''; + private dartEntrypointArgs: Array = []; + private platformViewsController: PlatformViewsController | null = null; private automaticallyRegisterPlugins: boolean = true; private waitForRestorationData: boolean = false; @@ -105,11 +124,11 @@ export class Options { this.context = context; } - getContext(): any { + getContext(): common.Context { return this.context; } - getDartEntrypoint(): DartEntrypoint { + getDartEntrypoint(): DartEntrypoint | null { return this.dartEntrypoint; } @@ -129,7 +148,7 @@ export class Options { return this.waitForRestorationData; } - getPlatformViewsController(): PlatformViewsController { + getPlatformViewsController(): PlatformViewsController | null { return this.platformViewsController; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroupCache.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroupCache.ets index 34b251069c..645507a6d8 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroupCache.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroupCache.ets @@ -24,8 +24,8 @@ export default class FlutterEngineGroupCache { return this.cachedEngineGroups.has(engineGroupId); } - get(engineGroupId: string): FlutterEngineGroup { - return this.cachedEngineGroups.get(engineGroupId); + get(engineGroupId: string): FlutterEngineGroup | null { + return this.cachedEngineGroups.get(engineGroupId) ?? null; } put(engineGroupId: string, engineGroup?: FlutterEngineGroup) { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets index e074ff82ea..4ec3580943 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets @@ -41,11 +41,11 @@ export default class FlutterNapi { //是否已实现 hasImplemented: boolean = false; - nativeShellHolderId: number = null; - platformMessageHandler: PlatformMessageHandler; + nativeShellHolderId: number | null = null; + platformMessageHandler: PlatformMessageHandler | null = null; private engineLifecycleListeners = new Set(); - accessibilityDelegate: AccessibilityDelegate; - localizationPlugin: LocalizationPlugin; + accessibilityDelegate: AccessibilityDelegate | null = null; + localizationPlugin: LocalizationPlugin | null = null; /** * 更新刷新率 @@ -81,7 +81,7 @@ export default class FlutterNapi { assetManager: resourceManager.ResourceManager, entrypointArgs: Array) { Log.w(TAG, "init: bundlePath=" + bundlePath + " entrypointFunctionName=" + entrypointFunctionName + " pathToEntrypointFunction=" + pathToEntrypointFunction + " entrypointArgs=" + JSON.stringify(entrypointArgs)) - flutter.nativeRunBundleAndSnapshotFromLibrary(this.nativeShellHolderId, bundlePath, entrypointFunctionName, pathToEntrypointFunction, assetManager, entrypointArgs); + flutter.nativeRunBundleAndSnapshotFromLibrary(this.nativeShellHolderId!, bundlePath, entrypointFunctionName, pathToEntrypointFunction, assetManager, entrypointArgs); }; /** @@ -95,7 +95,7 @@ export default class FlutterNapi { return this.hasImplemented; } - setPlatformMessageHandler(platformMessageHandler: PlatformMessageHandler): void { + setPlatformMessageHandler(platformMessageHandler: PlatformMessageHandler | null): void { this.ensureRunningOnMainThread(); this.platformMessageHandler = platformMessageHandler; } @@ -111,14 +111,14 @@ export default class FlutterNapi { } - static nativeLookupCallbackInformation(handle: number): FlutterCallbackInformation { + static nativeLookupCallbackInformation(handle: number): FlutterCallbackInformation | null { return null; } notifyLowMemoryWarning(): void { this.ensureRunningOnMainThread(); this.ensureAttachedToNative(); - this.nativeNotifyLowMemoryWarning(this.nativeShellHolderId); + this.nativeNotifyLowMemoryWarning(this.nativeShellHolderId!); } isAttached(): boolean { @@ -132,7 +132,7 @@ export default class FlutterNapi { dispatchEmptyPlatformMessage(channel: String, responseId: number): void { this.ensureRunningOnMainThread(); if (this.isAttached()) { - flutter.nativeDispatchEmptyPlatformMessage(this.nativeShellHolderId, channel, responseId); + flutter.nativeDispatchEmptyPlatformMessage(this.nativeShellHolderId!, channel, responseId); } else { Log.w( TAG, @@ -154,7 +154,7 @@ export default class FlutterNapi { text += uintArrayBuff[i] + ',' } Log.w(TAG, "message=" + message.byteLength + ",text=" + text); - flutter.nativeDispatchPlatformMessage(this.nativeShellHolderId, channel, message, position, responseId); + flutter.nativeDispatchPlatformMessage(this.nativeShellHolderId!, channel, message, position, responseId); } else { Log.w( TAG, @@ -167,7 +167,7 @@ export default class FlutterNapi { invokePlatformMessageEmptyResponseCallback(responseId: number): void { if (this.isAttached()) { - flutter.nativeInvokePlatformMessageEmptyResponseCallback(this.nativeShellHolderId, responseId); + flutter.nativeInvokePlatformMessageEmptyResponseCallback(this.nativeShellHolderId!, responseId); } else { Log.w( TAG, @@ -179,7 +179,7 @@ export default class FlutterNapi { invokePlatformMessageResponseCallback(responseId: number, message: ArrayBuffer, position: number) { if (this.isAttached()) { flutter.nativeInvokePlatformMessageResponseCallback( - this.nativeShellHolderId, responseId, message, position); + this.nativeShellHolderId!, responseId, message, position); } else { Log.w( TAG, @@ -196,7 +196,7 @@ export default class FlutterNapi { , systemGestureInsetLeft: number, physicalTouchSlop: number, displayFeaturesBounds: Array , displayFeaturesType: Array, displayFeaturesState: Array): void { if (this.isAttached()) { - flutter.nativeSetViewportMetrics(this.nativeShellHolderId, devicePixelRatio, + flutter.nativeSetViewportMetrics(this.nativeShellHolderId!, devicePixelRatio, physicalWidth, physicalHeight, physicalPaddingTop, @@ -266,7 +266,7 @@ export default class FlutterNapi { decodeImage(buffer: ArrayBuffer, imageGeneratorAddress: number): void { Log.d(TAG, "called decodeImage=" + buffer.byteLength) const imageSourceApi = image.createImageSource(buffer); - let tempPixelMap = null; + let tempPixelMap: image.PixelMap | null = null; imageSourceApi.createPixelMap({ desiredPixelFormat: image.PixelMapFormat.RGBA_8888 }).then(pixelMap => { @@ -276,7 +276,7 @@ export default class FlutterNapi { }).then(imageInfo => { Log.d(TAG, `nativeImageHeaderCallback width=${imageInfo.size.width} height=${imageInfo.size.height} imageGeneratorAddress=${imageGeneratorAddress}`) flutter.nativeImageDecodeCallback(imageInfo.size.width, imageInfo.size.height, imageGeneratorAddress, tempPixelMap) - }).catch(error => { + }).catch((error: ESObject) => { Log.d(TAG, "decodeImage error=" + JSON.stringify(error)) flutter.nativeImageDecodeCallback(0, 0, imageGeneratorAddress, null); }) @@ -333,7 +333,7 @@ export default class FlutterNapi { } } - setLocalizationPlugin(localizationPlugin: LocalizationPlugin): void { + setLocalizationPlugin(localizationPlugin: LocalizationPlugin | null): void { this.localizationPlugin = localizationPlugin; } @@ -348,7 +348,7 @@ export default class FlutterNapi { for (index = 0; index < systemLanguages.length; index++) { Log.d(TAG, "systemlanguages "+ index + ":" + systemLanguages[index]); } - flutter.nativeGetSystemLanguages(this.nativeShellHolderId, systemLanguages); + flutter.nativeGetSystemLanguages(this.nativeShellHolderId!, systemLanguages); } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets index 4b952c42f8..46d08cd458 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets @@ -30,20 +30,19 @@ const TAG = "DartExecutor"; /** * dart代码执行器 */ -export default class DartExecutor extends BinaryMessenger { +export default class DartExecutor implements BinaryMessenger { flutterNapi: FlutterNapi; assetManager: resourceManager.ResourceManager; private dartMessenger: DartMessenger; private binaryMessenger: BinaryMessenger; - private isApplicationRunning: boolean; - private isolateServiceId: String = null; - private isolateServiceIdListener: IsolateServiceIdListener = null; + private isApplicationRunning: boolean = false; + private isolateServiceId: String = ""; + private isolateServiceIdListener: IsolateServiceIdListener | null = null; private isolateChannelMessageHandler: BinaryMessageHandler = new IsolateChannelMessageHandler(this.isolateServiceId, this.isolateServiceIdListener); constructor(flutterNapi: FlutterNapi, assetManager: resourceManager.ResourceManager) { - super(); this.flutterNapi = flutterNapi; this.assetManager = assetManager; this.dartMessenger = new DartMessenger(flutterNapi); @@ -118,7 +117,7 @@ export default class DartExecutor extends BinaryMessenger { dartEntrypoint.dartEntrypointFunctionName, dartEntrypoint.dartEntrypointLibrary, this.assetManager, - dartEntrypointArgs); + dartEntrypointArgs ?? []); this.isApplicationRunning = true; } finally { @@ -147,7 +146,7 @@ export default class DartExecutor extends BinaryMessenger { dartCallback.callbackHandle.callbackName, dartCallback.callbackHandle.callbackLibraryPath, dartCallback.resourceManager, - null); + []); this.isApplicationRunning = true; } finally { @@ -272,7 +271,7 @@ export class DartEntrypoint { throw new Error( "DartEntrypoints can only be created once a FlutterEngine is created."); } - return new DartEntrypoint(flutterLoader.findAppBundlePath(), null, "main"); + return new DartEntrypoint(flutterLoader.findAppBundlePath(), "", "main"); } } @@ -364,9 +363,9 @@ export class DefaultBinaryMessenger implements BinaryMessenger { class IsolateChannelMessageHandler implements BinaryMessageHandler { private isolateServiceId: String; - private isolateServiceIdListener: IsolateServiceIdListener; + private isolateServiceIdListener: IsolateServiceIdListener | null = null; - constructor(isolateServiceId: String, isolateServiceIdListener: IsolateServiceIdListener) { + constructor(isolateServiceId: String, isolateServiceIdListener: IsolateServiceIdListener | null) { this.isolateServiceId = isolateServiceId; this.isolateServiceIdListener = isolateServiceIdListener; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets index 0a2c32013c..862ca785b6 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets @@ -103,7 +103,7 @@ export class DartMessenger implements BinaryMessenger, PlatformMessageHandler { } } - invokeHandler(handlerInfo: HandlerInfo, message: ArrayBuffer, replyId: number): void { + invokeHandler(handlerInfo: HandlerInfo | null, message: ArrayBuffer, replyId: number): void { // Called from any thread. if (handlerInfo != null) { try { @@ -123,15 +123,15 @@ export class DartMessenger implements BinaryMessenger, PlatformMessageHandler { // Called from any thread. Log.d(TAG, "Received message from Dart over channel '" + channel + "'"); - let handlerInfo: HandlerInfo; + let handlerInfo: HandlerInfo | null = this.messageHandlers.get(channel) ?? null; let messageDeferred: boolean; - handlerInfo = this.messageHandlers.get(channel); + messageDeferred = (this.enableBufferingIncomingMessagesFlag && handlerInfo == null); if (messageDeferred) { if (!this.bufferedMessages.has(channel)) { - this.bufferedMessages.set(channel, new BufferedMessageInfo[0]); + this.bufferedMessages.set(channel, []); } - let buffer: BufferedMessageInfo[] = this.bufferedMessages.get(channel); + let buffer: BufferedMessageInfo[] = this.bufferedMessages.get(channel) ?? []; buffer.push(new BufferedMessageInfo(message, replyId, messageData)); } if (!messageDeferred) { @@ -141,7 +141,7 @@ export class DartMessenger implements BinaryMessenger, PlatformMessageHandler { handlePlatformMessageResponse(replyId: number, reply: ArrayBuffer): void { Log.d(TAG, "Received message reply from Dart."); - let callback: BinaryReply = this.pendingReplies.get(replyId); + let callback: BinaryReply | null = this.pendingReplies.get(replyId) ?? null; this.pendingReplies.delete(replyId); if (callback != null) { try { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets index b8af4f6fb7..3c5bca80d3 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets @@ -18,7 +18,7 @@ import common from '@ohos.app.ability.common'; export default class ApplicationInfoLoader { static load(context: common.Context) { - let applicatioinInfo = new FlutterApplicationInfo(null, null, null, null, null, context.bundleCodeDir + '/libs/arm64', true); - return applicatioinInfo + let applicationInfo = new FlutterApplicationInfo(null, null, null, null, null, context.bundleCodeDir + '/libs/arm64', true); + return applicationInfo } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterApplicationInfo.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterApplicationInfo.ets index 0db68ee9da..bdb9509d4d 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterApplicationInfo.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterApplicationInfo.ets @@ -35,8 +35,13 @@ export default class FlutterApplicationInfo { //是否是profile模式 isProfile: boolean; - constructor(aotSharedLibraryName: string, vmSnapshotData: string, isolateSnapshotData: string, flutterAssetsDir: string, domainNetworkPolicy: string, - nativeLibraryDir: string, automaticallyRegisterPlugins: boolean) { + constructor(aotSharedLibraryName: string | null, + vmSnapshotData: string | null, + isolateSnapshotData: string | null, + flutterAssetsDir: string | null, + domainNetworkPolicy: string | null, + nativeLibraryDir: string, + automaticallyRegisterPlugins: boolean) { this.aotSharedLibraryName = aotSharedLibraryName == null ? DEFAULT_AOT_SHARED_LIBRARY_NAME : aotSharedLibraryName; this.vmSnapshotData = vmSnapshotData == null ? DEFAULT_VM_SNAPSHOT_DATA : vmSnapshotData; this.isolateSnapshotData = isolateSnapshotData == null ? DEFAULT_ISOLATE_SNAPSHOT_DATA : isolateSnapshotData; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets index 114387d16e..8917880d49 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterLoader.ets @@ -54,12 +54,12 @@ const FILE_SEPARATOR = "/"; */ export default class FlutterLoader { flutterNapi: FlutterNapi; - initResult: InitResult; - flutterApplicationInfo: FlutterApplicationInfo; - context: common.Context; - initialized: boolean; + initResult: InitResult | null = null; + flutterApplicationInfo: FlutterApplicationInfo | null = null; + context: common.Context | null = null; + initialized: boolean = false; //初始化开始时间戳 - initStartTimestampMillis: number; + initStartTimestampMillis: number = 0; constructor(flutterNapi: FlutterNapi) { this.flutterNapi = flutterNapi; @@ -84,7 +84,7 @@ export default class FlutterLoader { Log.d(TAG, "context.filesDir=" + context.filesDir) Log.d(TAG, "context.cacheDir=" + context.cacheDir) Log.d(TAG, "context.bundleCodeDir=" + context.bundleCodeDir) - if (this.flutterApplicationInfo.isDebugMode) { + if (this.flutterApplicationInfo!.isDebugMode) { await this.copyResource(context) } this.initResult = new InitResult( @@ -96,25 +96,25 @@ export default class FlutterLoader { } private async copyResource(context: common.Context) { - let filePath = context.filesDir + FILE_SEPARATOR + this.flutterApplicationInfo.flutterAssetsDir - if (!fs.accessSync(filePath + FILE_SEPARATOR + DEFAULT_KERNEL_BLOB)) { + let filePath = context.filesDir + FILE_SEPARATOR + this.flutterApplicationInfo!.flutterAssetsDir + if (!fs.accessSync(filePath + FILE_SEPARATOR + DEFAULT_KERNEL_BLOB) && this.context != null) { Log.d(TAG, "start copyResource") fs.mkdirSync(filePath) - let icudtlBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo.flutterAssetsDir + "/icudtl.dat") + let icudtlBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo!.flutterAssetsDir + "/icudtl.dat") let icudtlFile = fs.openSync(filePath + FILE_SEPARATOR + "/icudtl.dat", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.writeSync(icudtlFile.fd, icudtlBuffer.buffer) - let kernelBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo.flutterAssetsDir + FILE_SEPARATOR + DEFAULT_KERNEL_BLOB) + let kernelBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo!.flutterAssetsDir + FILE_SEPARATOR + DEFAULT_KERNEL_BLOB) let kernelFile = fs.openSync(filePath + FILE_SEPARATOR + DEFAULT_KERNEL_BLOB, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.writeSync(kernelFile.fd, kernelBuffer.buffer) - let vmBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo.flutterAssetsDir + FILE_SEPARATOR + this.flutterApplicationInfo.vmSnapshotData) - let vmFile = fs.openSync(filePath + FILE_SEPARATOR + this.flutterApplicationInfo.vmSnapshotData, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) + let vmBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo!.flutterAssetsDir + FILE_SEPARATOR + this.flutterApplicationInfo!.vmSnapshotData) + let vmFile = fs.openSync(filePath + FILE_SEPARATOR + this.flutterApplicationInfo!.vmSnapshotData, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.writeSync(vmFile.fd, vmBuffer.buffer) - let isolateBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo.flutterAssetsDir + FILE_SEPARATOR + this.flutterApplicationInfo.isolateSnapshotData) - let isolateFile = fs.openSync(filePath + FILE_SEPARATOR + this.flutterApplicationInfo.isolateSnapshotData, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) + let isolateBuffer = await this.context.resourceManager.getRawFileContent(this.flutterApplicationInfo!.flutterAssetsDir + FILE_SEPARATOR + this.flutterApplicationInfo!.isolateSnapshotData) + let isolateFile = fs.openSync(filePath + FILE_SEPARATOR + this.flutterApplicationInfo!.isolateSnapshotData, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.writeSync(isolateFile.fd, isolateBuffer.buffer) Log.d(TAG, "copyResource end") } else { @@ -126,7 +126,7 @@ export default class FlutterLoader { * 初始化dart虚拟机方法 * @param flutterShellArgs */ - ensureInitializationComplete(shellArgs: Array) { + ensureInitializationComplete(shellArgs: Array | null) { if (this.initialized) { return; } @@ -136,37 +136,37 @@ export default class FlutterLoader { } shellArgs.push( "--icu-native-lib-path=" - + this.flutterApplicationInfo.nativeLibraryDir + + this.flutterApplicationInfo!.nativeLibraryDir + FILE_SEPARATOR + DEFAULT_LIBRARY ); let kernelPath: string = ""; - if (this.flutterApplicationInfo.isDebugMode) { - Log.d(TAG, "this.initResult.dataDirPath=" + this.initResult.dataDirPath) - const snapshotAssetPath = this.initResult.dataDirPath + FILE_SEPARATOR + this.flutterApplicationInfo.flutterAssetsDir; + if (this.flutterApplicationInfo!.isDebugMode) { + Log.d(TAG, "this.initResult!.dataDirPath=" + this.initResult!.dataDirPath) + const snapshotAssetPath = this.initResult!.dataDirPath + FILE_SEPARATOR + this.flutterApplicationInfo!.flutterAssetsDir; kernelPath = snapshotAssetPath + FILE_SEPARATOR + DEFAULT_KERNEL_BLOB; shellArgs.push("--icu-data-file-path=" + snapshotAssetPath + "/icudtl.dat") shellArgs.push("--" + SNAPSHOT_ASSET_PATH_KEY + "=" + snapshotAssetPath); - shellArgs.push("--" + VM_SNAPSHOT_DATA_KEY + "=" + this.flutterApplicationInfo.vmSnapshotData); + shellArgs.push("--" + VM_SNAPSHOT_DATA_KEY + "=" + this.flutterApplicationInfo!.vmSnapshotData); shellArgs.push( - "--" + ISOLATE_SNAPSHOT_DATA_KEY + "=" + this.flutterApplicationInfo.isolateSnapshotData); + "--" + ISOLATE_SNAPSHOT_DATA_KEY + "=" + this.flutterApplicationInfo!.isolateSnapshotData); } else { shellArgs.push( - "--" + AOT_SHARED_LIBRARY_NAME + "=" + this.flutterApplicationInfo.aotSharedLibraryName); + "--" + AOT_SHARED_LIBRARY_NAME + "=" + this.flutterApplicationInfo!.aotSharedLibraryName); shellArgs.push( "--" + AOT_SHARED_LIBRARY_NAME + "=" - + this.flutterApplicationInfo.nativeLibraryDir + + this.flutterApplicationInfo!.nativeLibraryDir + FILE_SEPARATOR - + this.flutterApplicationInfo.aotSharedLibraryName); - if (this.flutterApplicationInfo.isProfile) { + + this.flutterApplicationInfo!.aotSharedLibraryName); + if (this.flutterApplicationInfo!.isProfile) { shellArgs.push("--" + AOT_VMSERVICE_SHARED_LIBRARY_NAME + "=" + VMSERVICE_SNAPSHOT_LIBRARY); } } - shellArgs.push("--cache-dir-path=" + this.initResult.engineCachesPath); - if (StringUtils.isNotEmpty(this.flutterApplicationInfo.domainNetworkPolicy)) { - shellArgs.push("--domain-network-policy=" + this.flutterApplicationInfo.domainNetworkPolicy); + shellArgs.push("--cache-dir-path=" + this.initResult!.engineCachesPath); + if (StringUtils.isNotEmpty(this.flutterApplicationInfo!.domainNetworkPolicy)) { + shellArgs.push("--domain-network-policy=" + this.flutterApplicationInfo!.domainNetworkPolicy); } const resourceCacheMaxBytesThreshold = 1080 * 1920 * 12 * 4; @@ -180,19 +180,19 @@ export default class FlutterLoader { // //最终初始化操作 const costTime = Date.now() - this.initStartTimestampMillis; - this.flutterNapi.init( - this.context, + this.flutterNapi!.init( + this.context!, shellArgs, kernelPath, - this.initResult.appStoragePath, - this.initResult.engineCachesPath, + this.initResult!.appStoragePath, + this.initResult!.engineCachesPath!, costTime ); this.initialized = true; } findAppBundlePath(): string { - return this.flutterApplicationInfo.flutterAssetsDir; + return this.flutterApplicationInfo == null ? "" : this.flutterApplicationInfo!.flutterAssetsDir; } getLookupKeyForAsset(asset: string, packageName?: string): string { @@ -200,7 +200,7 @@ export default class FlutterLoader { } fullAssetPathFrom(filePath: string): string { - return this.flutterApplicationInfo.flutterAssetsDir + "/" + filePath; + return this.flutterApplicationInfo == null ? "" : this.flutterApplicationInfo!.flutterAssetsDir + "/" + filePath; } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorView.ets index f0d8581b18..f2544f8e20 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorView.ets @@ -12,32 +12,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import ArrayList from '@ohos.util.ArrayList'; -import { DVModel, DVModelParameters } from '../../../view/DynamicView/dynamicView'; +import matrix4 from '@ohos.matrix4'; +import { DVModel, DVModelEvents, DVModelParameters } from '../../../view/DynamicView/dynamicView'; import { createDVModelFromJson } from '../../../view/DynamicView/dynamicViewJson'; import OhosTouchProcessor from '../../ohos/OhosTouchProcessor'; import { FlutterMutator, FlutterMutatorsStack } from './FlutterMutatorsStack' export class FlutterMutatorView { - private mutatorsStack: FlutterMutatorsStack; - private screenDensity: number; - private left: number; - private top: number; - private prevLeft: number; - private prevTop: number; - private ohosTouchProcessor: OhosTouchProcessor; - private onTouch = (touchEvent) => { + private mutatorsStack: FlutterMutatorsStack | null = null; + private screenDensity: number = 0; + private left: number = 0; + private top: number = 0; + private prevLeft: number = 0; + private prevTop: number = 0; + + private onTouch = (touchEvent: ESObject) => { + let params = this.model.params as Record; switch (touchEvent.type) { case TouchType.Down: this.prevLeft = this.left; this.prevTop = this.top; - this.model.params["translateX"] = this.left; - this.model.params["translateY"] = this.top; + params.translateX = this.left; + params.translateY = this.top; break; case TouchType.Move: - this.model.params["translateX"] = this.prevLeft; - this.model.params["translateY"] = this.prevTop; + params.translateX = this.prevLeft; + params.translateY = this.prevTop; this.prevLeft = this.left; this.prevTop = this.top; break; @@ -47,41 +48,42 @@ export class FlutterMutatorView { break; } } + private model: DVModel = createDVModelFromJson( - { - compType: "Column", - children: [], - attributes: { backgroundColor: Color.Red }, - events: { onTouch: this.onTouch } - } + new DVModelParam("Column", [], { backgroundColor: Color.Red }, { onTouch: this.onTouch }) ); setOnDescendantFocusChangeListener(onFocus: () => void, onBlur: () => void) { - this.model.events["onFocus"] = onFocus; - this.model.events["onBlur"] = onBlur; + // this.model.events["onFocus"] = onFocus; + // this.model.events["onBlur"] = onBlur; + let events2 = this.model.events as Record; + events2.onFocus = onFocus; + events2.onBlur = onBlur; } public setLayoutParams(parameters: DVModelParameters): void { if (this.model.params == null) { this.model.params = new DVModelParameters(); } - this.model.params['marginLeft'] = parameters['marginLeft']; - this.model.params['marginTop'] = parameters['marginTop']; - this.model.params['width'] = parameters['width']; - this.model.params['height'] = parameters['height']; - this.left = parameters['marginLeft']; - this.top = parameters['marginTop']; + let params = this.model.params as Record | matrix4.Matrix4Transit>; + let parametersRecord = parameters as Record | matrix4.Matrix4Transit>; + params.marginLeft = parametersRecord['marginLeft']; + params.marginTop = parametersRecord['marginTop']; + params.width = parametersRecord['width']; + params.height = parametersRecord['height']; + this.left = parametersRecord.marginLeft as number; + this.top = parametersRecord.marginTop as number ; } public addDvModel(model: DVModel): void { - this.model.children.push(model); + this.model?.children.push(model); } public readyToDisplay(mutatorsStack: FlutterMutatorsStack, left: number, top: number, width: number, height: number) { this.mutatorsStack = mutatorsStack; this.left = left; this.top = top; - let parameters = new DVModelParameters(); + let parameters = new DVModelParameters() as Record | matrix4.Matrix4Transit>; parameters['marginLeft'] = left; parameters['marginTop'] = top; parameters['width'] = width; @@ -91,25 +93,43 @@ export class FlutterMutatorView { } private dealMutators() { + if (this.mutatorsStack == null) { + return; + } let paths = this.mutatorsStack.getFinalClippingPaths(); let rects = this.mutatorsStack.getFinalClippingRects(); let matrix = this.mutatorsStack.getFinalMatrix(); + let params = this.model.params as Record | matrix4.Matrix4Transit>; if (!paths.isEmpty()) { let path = paths.getLast(); - this.model.params["pathWidth"] = path.width; - this.model.params["pathHeight"] = path.height; - this.model.params["pathCommands"] = path.commands; + params.pathWidth = path.width; + params.pathHeight = path.height; + params.pathCommands = path.commands; } if (!rects.isEmpty()) { let rect = rects.getLast(); - this.model.params["rectWidth"] = rect.width; - this.model.params["rectHeight"] = rect.height; - this.model.params["rectRadius"] = rect.radius; + params.rectWidth = rect.width; + params.rectHeight = rect.height; + params.rectRadius = rect.radius; } - this.model.params["matrix"] = matrix; + params.matrix = matrix; } - public getDvModel(): DVModel { + public getDvModel(): DVModel | undefined { return this.model; } -} \ No newline at end of file +} + +class DVModelParam { + compType: string + children: [] + attributes: ESObject + events: ESObject + + constructor(compType: string, children: [], attributes: ESObject, events: ESObject) { + this.compType = compType; + this.children = children; + this.attributes = attributes; + this.events = events; + } +}; \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorsStack.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorsStack.ets index 59da6edd6c..2f53c6c041 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorsStack.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorsStack.ets @@ -26,31 +26,31 @@ export enum FlutterMutatorType { class Rect { width: number; height: number; - radius?: string | number | Array; + radius: string | number | Array; constructor(width:number, height:number, radius?:string | number | Array) { this.width = width; this.height = height; - this.radius = radius; + this.radius = radius ?? 0; } } class Path { width: number | string; height: number | string; - commands?: string; + commands: string; constructor(width:number | string, height:number | string, commands?:string) { this.width = width; this.height = height; - this.commands = commands; + this.commands = commands ?? ''; } } export class FlutterMutator { - private matrix: matrix4.Matrix4Transit; - private rect: Rect; - private path: Path; + private matrix: matrix4.Matrix4Transit | null = null; + private rect: Rect = new Rect(0, 0); + private path: Path = new Path(0, 0); constructor(args: matrix4.Matrix4Transit | Rect | Path) { if (args instanceof Rect) { @@ -62,7 +62,7 @@ export class FlutterMutator { } } - public getMatrix() { + public getMatrix() : matrix4.Matrix4Transit | null { return this.matrix; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/FlutterPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/FlutterPlugin.ets index 3045e2b8d7..6b0987a806 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/FlutterPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/FlutterPlugin.ets @@ -15,6 +15,7 @@ import common from '@ohos.app.ability.common'; import { BinaryMessenger } from '../../../plugin/common/BinaryMessenger'; +import PlatformViewFactory from '../../../plugin/platform/PlatformViewFactory'; import PlatformViewRegistry from '../../../plugin/platform/PlatformViewRegistry'; import FlutterEngineGroup from '../FlutterEngineGroup'; @@ -58,7 +59,7 @@ export class FlutterPluginBinding { this.binaryMessenger = binaryMessenger; this.flutterAssets = flutterAssets; this.group = group; - this.platformViewRegistry = platformViewRegistry; + this.platformViewRegistry = platformViewRegistry ?? new EmptyPlatformViewRegistry(); } getApplicationContext(): common.Context { @@ -115,4 +116,10 @@ export interface FlutterAssets { * Ohos {@code bundleName}. */ getAssetFilePathBySubpath(assetSubpath: string, bundleName: string): string; +} + +class EmptyPlatformViewRegistry implements PlatformViewRegistry { + registerViewFactory(viewTypeId: string, factory: PlatformViewFactory): boolean { + return false; + } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets index b93b7b14b5..947ccef4ba 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets @@ -23,5 +23,5 @@ export default interface ActivityControlSurface { detachFromAbility(): void; onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; onWindowFocusChanged(hasFocus: boolean): void; - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult; + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult; } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets index 613b69e0f4..349010b14e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets @@ -72,7 +72,7 @@ export interface NewWantListener { * ohos.app.ability.UIAbility}. */ export interface WindowFocusChangedListener { - onWindowFocusChanged(hasFocus): void; + onWindowFocusChanged(hasFocus: boolean): void; } export interface OnSaveStateListener { @@ -80,5 +80,5 @@ export interface OnSaveStateListener { * Invoked when the associated {@code UIAbility} or {@code Fragment} executes {@link * Activity#onSaveState(Bundle)}. */ - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult; + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult; } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/AccessibilityChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/AccessibilityChannel.ets index 6c930e1e74..804994eda6 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/AccessibilityChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/AccessibilityChannel.ets @@ -20,28 +20,28 @@ import HashMap from '@ohos.util.HashMap'; import FlutterNapi, {AccessibilityDelegate} from '../FlutterNapi'; import { Action } from '../../../view/AccessibilityBridge' import StandardMessageCodec from '../../../plugin/common/StandardMessageCodec'; -import { MethodCallHandler } from '../../../plugin/common/MethodChannel'; +import StringUtils from '../../../util/StringUtils'; /** * 辅助功能channel */ -export default class AccessibilityChannel implements MessageHandler{ +export default class AccessibilityChannel implements MessageHandler{ private static TAG = "AccessibilityChannel"; private static CHANNEL_NAME = "flutter/accessibility"; - private channel: BasicMessageChannel; + private channel: BasicMessageChannel; private flutterNapi: FlutterNapi; - private handler: AccessibilityMessageHandler; + private handler: AccessibilityMessageHandler | null = null; private nextReplyId: number = 1; onMessage(message: object, reply: Reply): void { if (this.handler == null) { Log.i(AccessibilityChannel.TAG, "NULL"); - reply.reply(null); + reply.reply(StringUtils.stringToArrayBuffer("")); return; } - let annotatedEvent: HashMap = message as HashMap; + let annotatedEvent: HashMap = message as HashMap; let type: string = annotatedEvent.get("type") as string; - let data: HashMap = annotatedEvent.get("data") as HashMap; + let data: HashMap = annotatedEvent.get("data") as HashMap; Log.i(AccessibilityChannel.TAG, "Received " + type + " message."); switch (type) { @@ -78,12 +78,12 @@ export default class AccessibilityChannel implements MessageHandler{ break; } } - reply.reply(null); + reply.reply(StringUtils.stringToArrayBuffer("")); } constructor(dartExecutor: DartExecutor, flutterNapi: FlutterNapi) { Log.i(AccessibilityChannel.TAG, "Channel entered"); - this.channel = new BasicMessageChannel(dartExecutor, AccessibilityChannel.CHANNEL_NAME, StandardMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel(dartExecutor, AccessibilityChannel.CHANNEL_NAME, StandardMessageCodec.INSTANCE); this.channel.setMessageHandler(this); this.flutterNapi = flutterNapi; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets index d397f363bc..8ac0e08bf3 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets @@ -26,7 +26,7 @@ export default class KeyEventChannel { private channel : BasicMessageChannel>; constructor(binaryMessenger: BinaryMessenger) { - this.channel = new BasicMessageChannel(binaryMessenger, KeyEventChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel>(binaryMessenger, KeyEventChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); } sendFlutterKeyEvent(keyEvent: FlutterKeyEvent, diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/LocalizationChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/LocalizationChannel.ets index c4b5b6cf7b..d34d81816a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/LocalizationChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/LocalizationChannel.ets @@ -26,7 +26,7 @@ export default class LocalizationChannel implements MethodCallHandler{ private static TAG = "LocalizationChannel"; private static CHANNEL_NAME = "flutter/localization"; private channel: MethodChannel; - private localizationMessageHandler: LocalizationMessageHandler; + private localizationMessageHandler: LocalizationMessageHandler | null = null; onMethodCall(call: MethodCall, result: MethodResult) :void { if (this.localizationMessageHandler == null) { @@ -38,11 +38,11 @@ export default class LocalizationChannel implements MethodCallHandler{ case "Localization.getStringResource": { Log.i(TAG, "Localization.getStringResource enter"); let key: string = call.argument("key"); - let localeString: string = null; + let localeString: string = ""; if (call.hasArgument("locale")) { localeString = call.argument("locale"); } - result.success(this.localizationMessageHandler.getStringResource(key, localeString)); + result.success(this.localizationMessageHandler?.getStringResource(key, localeString)); break; } default: { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/MouseCursorChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/MouseCursorChannel.ets index b6f1c89984..3e8b3d4167 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/MouseCursorChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/MouseCursorChannel.ets @@ -25,7 +25,7 @@ const TAG:string = 'MouseCursorChannel' export default class MouseCursorChannel implements MethodCallHandler { public channel: MethodChannel; - private mouseCursorMethodHandler: MouseCursorMethodHandler; + private mouseCursorMethodHandler: MouseCursorMethodHandler | null = null; onMethodCall(call: MethodCall, result: MethodResult): void { if (this.mouseCursorMethodHandler === null) { @@ -41,7 +41,7 @@ export default class MouseCursorChannel implements MethodCallHandler { // More methods are expected to be added here, hence the switch. switch (method) { case "activateSystemCursor": - let argument: HashMap = call.args; + let argument: HashMap = call.args; let kind: string = argument.get("kind"); try { this.mouseCursorMethodHandler.activateSystemCursor(kind); @@ -69,7 +69,7 @@ export default class MouseCursorChannel implements MethodCallHandler { * parsed from the underlying platform channel. * @param mouseCursorMethodHandler */ - public setMethodHandler(mouseCursorMethodHandler: MouseCursorMethodHandler): void { + public setMethodHandler(mouseCursorMethodHandler: MouseCursorMethodHandler | null): void { this.mouseCursorMethodHandler = mouseCursorMethodHandler; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets index 6d591e818f..f7ebcb6926 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets @@ -27,11 +27,7 @@ export default class NavigationChannel { this.channel = new MethodChannel(dartExecutor, "flutter/navigation", JSONMethodCodec.INSTANCE); // Provide a default handler that returns an empty response to any messages // on this channel. - this.channel.setMethodCallHandler({ - onMethodCall(call: MethodCall, result: MethodResult): void { - result.success(null); - } - }); + this.channel.setMethodCallHandler(new NavigationCallback()); } setInitialRoute(initialRoute: string): void { @@ -46,9 +42,7 @@ export default class NavigationChannel { pushRouteInformation(route: string): void { Log.i(NavigationChannel.TAG, "Sending message to push route information '" + route + "'"); - this.channel.invokeMethod("pushRouteInformation", { - "location": route - }); + this.channel.invokeMethod("pushRouteInformation", new Map().set("location", route) ); } popRoute(): void { @@ -59,4 +53,10 @@ export default class NavigationChannel { setMethodCallHandler(handler: MethodCallHandler) { this.channel.setMethodCallHandler(handler); } +} + +class NavigationCallback implements MethodCallHandler { + onMethodCall(call: MethodCall, result: MethodResult) { + result.success(null); + } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets index aeb7a8c5e1..e2ff4f357a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets @@ -15,7 +15,7 @@ import JSONMethodCodec from '../../../plugin/common/JSONMethodCodec'; import MethodCall from '../../../plugin/common/MethodCall'; -import MethodChannel, { MethodResult } from '../../../plugin/common/MethodChannel'; +import MethodChannel, { MethodCallHandler, MethodResult } from '../../../plugin/common/MethodChannel'; import Log from '../../../util/Log'; import DartExecutor from '../dart/DartExecutor'; import pasteboard from '@ohos.pasteboard'; @@ -26,149 +26,12 @@ export default class PlatformChannel { private static TAG = "PlatformChannel"; private static CHANNEL_NAME = "flutter/platform"; channel: MethodChannel; - platformMessageHandler: PlatformMessageHandler; + platformMessageHandler: PlatformMessageHandler | null = null; constructor(dartExecutor: DartExecutor) { this.channel = new MethodChannel(dartExecutor, PlatformChannel.CHANNEL_NAME, JSONMethodCodec.INSTANCE); - this.channel.setMethodCallHandler({ - onMethodCall: (call: MethodCall, result: MethodResult): void => { - if (this.platformMessageHandler == null) { - Log.w(PlatformChannel.TAG,"platformMessageHandler is null"); - return; - } - - let method: string = call.method; - let args: any = call.args; - Log.d(PlatformChannel.TAG, "Received '" + method + "' message."); - try { - switch (method) { - case "SystemSound.play": - break; - case "HapticFeedback.vibrate": - try { - Log.d(PlatformChannel.TAG, "HapticFeedback: "+args as string); - let feedbackType: HapticFeedbackType = this.getFeedbackTypeFromValue(args as string); - this.platformMessageHandler.vibrateHapticFeedback(feedbackType); - result.success(null); - } catch(e) { - Log.e(PlatformChannel.TAG, "HapticFeedback.vibrate error:" + JSON.stringify(e)); - } - break; - case "SystemChrome.setPreferredOrientations": - Log.d(PlatformChannel.TAG, "setPreferredOrientations: "+JSON.stringify(args)); - try { - let ohosOrientation = this.decodeOrientations(args as string[]); - this.platformMessageHandler.setPreferredOrientations(ohosOrientation); - result.success(null); - } catch (err) { - Log.e(PlatformChannel.TAG, "setPreferredOrientations err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - - break; - case "SystemChrome.setApplicationSwitcherDescription": - Log.d(PlatformChannel.TAG, "setApplicationSwitcherDescription: "+JSON.stringify(args)); - break; - case "SystemChrome.setEnabledSystemUIOverlays": - try { - let overlays: SystemUiOverlay[] = this.decodeSystemUiOverlays(args); - Log.d(PlatformChannel.TAG,"overlays: " + overlays); - this.platformMessageHandler.showSystemOverlays(overlays); - result.success(null); - } catch (err) { - Log.e(PlatformChannel.TAG, "setEnabledSystemUIOverlays err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - break; - case "SystemChrome.setEnabledSystemUIMode": - try{ - Log.d(PlatformChannel.TAG,"setEnabledSystemUIMode args:" + args as string); - let mode: SystemUiMode = this.decodeSystemUiMode(args as string) - this.platformMessageHandler.showSystemUiMode(mode); - } catch (err) { - Log.e(PlatformChannel.TAG, "setEnabledSystemUIMode err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - break; - case "SystemChrome.setSystemUIChangeListener": - this.platformMessageHandler.setSystemUiChangeListener(); - result.success(null); - break; - case "SystemChrome.restoreSystemUIOverlays": - this.platformMessageHandler.restoreSystemUiOverlays(); - result.success(null); - break; - case "SystemChrome.setSystemUIOverlayStyle": - try { - Log.d(PlatformChannel.TAG, "setSystemUIOverlayStyle asrgs: " + JSON.stringify(args)); - let systemChromeStyle: SystemChromeStyle = this.decodeSystemChromeStyle(args); - this.platformMessageHandler.setSystemUiOverlayStyle(systemChromeStyle); - result.success(null); - } catch (err) { - Log.e(PlatformChannel.TAG, "setSystemUIOverlayStyle err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - break; - case "SystemNavigator.pop": - this.platformMessageHandler.popSystemNavigator(); - result.success(null); - break; - case "Clipboard.getData": - let contentFormatName: string = args as string; - let clipboardFormat: ClipboardContentFormat = null; - if(contentFormatName != null) { - try{ - clipboardFormat = this.getClipboardContentFormatFromValue(contentFormatName); - } catch (err) { - Log.d(PlatformChannel.TAG, "No such clipboard content format: " + contentFormatName); - result.error("error", "No such clipboard content format: " + contentFormatName, null); - } - } - - let pasteBoard = pasteboard.getSystemPasteboard(); - pasteBoard.getData().then((pasteData) => { - let text = pasteData.getPrimaryText(); - let response = {text: ""}; - response.text = text; - result.success(response); - }).catch((err) => { - Log.e(PlatformChannel.TAG,"Failed to get PasteData. Cause: " + JSON.stringify(err)); - }); - break; - case "Clipboard.setData": - let clipboardContent = args.text; - this.platformMessageHandler.setClipboardData(clipboardContent); - result.success(null); - break; - case "Clipboard.hasStrings": - let hasStrings: boolean = false; - let response = {value: false}; - let systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.hasData().then((hasData) => { - if(!hasData) { - response.value = hasData; - result.success(response); - } - }).catch((err) => { - Log.e(PlatformChannel.TAG, "systemPasteboard.hasData err: " + JSON.stringify(err)); - }) - systemPasteboard.getData().then((pasteData) => { - hasStrings = pasteData.hasType(pasteboard.MIMETYPE_TEXT_PLAIN); - response.value = hasStrings; - result.success(response); - }).catch((err) => { - Log.e(PlatformChannel.TAG, "getData err: " + JSON.stringify(err)); - }) - break; - default: - result.notImplemented(); - break; - } - } catch (e) { - result.error("error", JSON.stringify(e), null); - } - } - }); + let callback = new PlatformMethodCallback(this); + this.channel.setMethodCallHandler(callback); } setPlatformMessageHandler(platformMessageHandler: PlatformMessageHandler): void { @@ -246,10 +109,18 @@ export default class PlatformChannel { } getFeedbackTypeFromValue(encodedName: string): HapticFeedbackType { - if(encodedName == null) { + if (encodedName == null) { return HapticFeedbackType.STANDARD; } - for (const feedbackType in HapticFeedbackType) { + let feedbackTypes: string[] = [ + HapticFeedbackType.STANDARD, + HapticFeedbackType.LIGHT_IMPACT, + HapticFeedbackType.MEDIUM_IMPACT, + HapticFeedbackType.HEAVY_IMPACT, + HapticFeedbackType.SELECTION_CLICK + ]; + for (let i = 0; i < feedbackTypes.length; i++) { + let feedbackType: string = feedbackTypes[i]; if ( (HapticFeedbackType[feedbackType] == encodedName) || (HapticFeedbackType[feedbackType] == null && encodedName == null) @@ -257,18 +128,24 @@ export default class PlatformChannel { return HapticFeedbackType[feedbackType]; } } - Log.e(PlatformChannel.TAG,"No such HapticFeedbackType:" + encodedName); + Log.e(PlatformChannel.TAG, "No such HapticFeedbackType:" + encodedName); + return HapticFeedbackType.STANDARD; } getClipboardContentFormatFromValue(encodedName: string): ClipboardContentFormat { - for (const format in ClipboardContentFormat) { + let clipboardFormats : string[]= [ClipboardContentFormat.PLAIN_TEXT]; + for (let i = 0; i < clipboardFormats.length; i++) { + let format = clipboardFormats[i]; if (ClipboardContentFormat[format] === encodedName) { return ClipboardContentFormat[format]; } } + return ClipboardContentFormat.PLAIN_TEXT; } getSystemUiOverlayFromValue(encodedName: string): SystemUiOverlay { - for (const overlay in SystemUiOverlay) { + let systemUiOverlays : string[] = [SystemUiOverlay.TOP_OVERLAYS, SystemUiOverlay.BOTTOM_OVERLAYS]; + for (let i = 0; i < systemUiOverlays.length; i++) { + let overlay = systemUiOverlays[i]; if (SystemUiOverlay[overlay] === encodedName) { return SystemUiOverlay[overlay]; } @@ -276,41 +153,38 @@ export default class PlatformChannel { throw new Error("No such SystemUiOverlay: " + encodedName); } - private decodeSystemUiOverlays(encodedSystemUiOverlay: any): SystemUiOverlay[] { - let overlays: SystemUiOverlay[] = []; - for(let i = 0; i < encodedSystemUiOverlay.length; i++) { - const encodedOverlay = encodedSystemUiOverlay[i]; - const overlay = this.getSystemUiOverlayFromValue(encodedOverlay); - switch (overlay) { - case SystemUiOverlay.TOP_OVERLAYS: - overlays.push(SystemUiOverlay.TOP_OVERLAYS); - break; - case SystemUiOverlay.BOTTOM_OVERLAYS: - overlays.push(SystemUiOverlay.BOTTOM_OVERLAYS); - break; - } - } - return overlays; - } - getSystemUiModeFromValue(encodedName: string): SystemUiMode { - for (const mode in SystemUiMode) { + let systemUiModes : string[] = [ + SystemUiMode.LEAN_BACK, SystemUiMode.IMMERSIVE, + SystemUiMode.IMMERSIVE_STICKY, SystemUiMode.EDGE_TO_EDGE + ]; + for (let i = 0; i < systemUiModes.length; i++) { + let mode = systemUiModes[i]; if (SystemUiMode[mode] === encodedName) { return SystemUiMode[mode]; } } throw new Error("No such SystemUiOverlay: " + encodedName); } + getBrightnessFromValue(encodedName: string): Brightness { - for (const brightness in Brightness) { + let brightnesses : string[] = [Brightness.LIGHT, Brightness.DARK]; + for (let i = 0; i < brightnesses.length; i++) { + let brightness = brightnesses[i]; if (Brightness[brightness] === encodedName) { return Brightness[brightness]; } } throw new Error("No such Brightness: " + encodedName); } + getDeviceOrientationFromValue(encodedName: string): DeviceOrientation { - for (const orientation in DeviceOrientation) { + let deviceOrientations: string[] = [ + DeviceOrientation.PORTRAIT_UP, DeviceOrientation.PORTRAIT_DOWN, + DeviceOrientation.LANDSCAPE_LEFT, DeviceOrientation.LANDSCAPE_RIGHT + ]; + for (let i = 0; i < deviceOrientations.length; i++) { + let orientation = deviceOrientations[i]; if (DeviceOrientation[orientation] === encodedName) { return DeviceOrientation[orientation]; } @@ -318,65 +192,8 @@ export default class PlatformChannel { throw new Error("No such DeviceOrientation: " + encodedName); } - private decodeSystemUiMode(encodedSystemUiMode: string): SystemUiMode { - let mode: SystemUiMode = this.getSystemUiModeFromValue(encodedSystemUiMode); - switch (mode) { - case SystemUiMode.LEAN_BACK: - return SystemUiMode.LEAN_BACK; - case SystemUiMode.IMMERSIVE: - return SystemUiMode.IMMERSIVE; - case SystemUiMode.IMMERSIVE_STICKY: - return SystemUiMode.IMMERSIVE_STICKY; - case SystemUiMode.EDGE_TO_EDGE: - return SystemUiMode.EDGE_TO_EDGE; - } - return SystemUiMode.EDGE_TO_EDGE; - - } - - private decodeSystemChromeStyle(encodedStyle: any): SystemChromeStyle { - let statusBarColor: number = null; - let statusBarIconBrightness: Brightness = null; - let systemStatusBarContrastEnforced: boolean = null; - let systemNavigationBarColor: number = null; - let systemNavigationBarIconBrightness: Brightness = null; - let systemNavigationBarDividerColor: number = null; - let systemNavigationBarContrastEnforced: boolean = null; - if(encodedStyle.statusBarColor != null) { - statusBarColor = encodedStyle.statusBarColor as number; - } - if(encodedStyle.statusBarIconBrightness != null) { - statusBarIconBrightness = - this.getBrightnessFromValue(encodedStyle.statusBarIconBrightness as string); - } - if(encodedStyle.systemStatusBarContrastEnforced != null) { - systemStatusBarContrastEnforced = encodedStyle.systemStatusBarContrastEnforced as boolean; - } - if(encodedStyle.systemNavigationBarColor != null) { - systemNavigationBarColor = encodedStyle.systemNavigationBarColor as number; - } - if(encodedStyle.systemNavigationBarIconBrightness != null) { - systemNavigationBarIconBrightness = - this.getBrightnessFromValue(encodedStyle.systemNavigationBarIconBrightness as string); - } - if(encodedStyle.systemNavigationBarDividerColor != null) { - systemNavigationBarDividerColor = encodedStyle.systemNavigationBarDividerColor as number; - } - if(encodedStyle.systemNavigationBarContrastEnforced != null) { - systemNavigationBarContrastEnforced = encodedStyle.systemNavigationBarContrastEnforced as boolean; - } - return new SystemChromeStyle( - statusBarColor, - statusBarIconBrightness, - systemStatusBarContrastEnforced, - systemNavigationBarColor, - systemNavigationBarIconBrightness, - systemNavigationBarDividerColor, - systemNavigationBarContrastEnforced - ); - } - } + export enum HapticFeedbackType { STANDARD = "STANDARD", LIGHT_IMPACT = "HapticFeedbackType.lightImpact", @@ -411,7 +228,6 @@ export interface PlatformMessageHandler { setClipboardData(text: string): void; clipboardHasStrings(): boolean; - } export enum ClipboardContentFormat { @@ -481,4 +297,214 @@ enum DeviceOrientation { PORTRAIT_DOWN = "DeviceOrientation.portraitDown", LANDSCAPE_LEFT = "DeviceOrientation.landscapeLeft", LANDSCAPE_RIGHT = "DeviceOrientation.landscapeRight", -} \ No newline at end of file +} + +class PlatformMethodCallback implements MethodCallHandler { + private static TAG = "PlatformMethodCallback" + platform: PlatformChannel; + + constructor(platform: PlatformChannel) { + this.platform = platform; + } + + onMethodCall(call: MethodCall, result: MethodResult) { + if (this.platform.platformMessageHandler == null) { + Log.w(PlatformMethodCallback.TAG, "platformMessageHandler is null"); + return; + } + + let method: string = call.method; + let args: ESObject = call.args; + Log.d(PlatformMethodCallback.TAG, "Received '" + method + "' message."); + try { + switch (method) { + case "SystemSound.play": + break; + case "HapticFeedback.vibrate": + try { + Log.d(PlatformMethodCallback.TAG, "HapticFeedback: " + args as string); + let feedbackType = this.platform.getFeedbackTypeFromValue(args as string); + this.platform.platformMessageHandler.vibrateHapticFeedback(feedbackType); + result.success(null); + } catch (e) { + Log.e(PlatformMethodCallback.TAG, "HapticFeedback.vibrate error:" + JSON.stringify(e)); + } + break; + case "SystemChrome.setPreferredOrientations": + Log.d(PlatformMethodCallback.TAG, "setPreferredOrientations: " + JSON.stringify(args)); + try { + let ohosOrientation = this.platform.decodeOrientations(args as string[]); + this.platform.platformMessageHandler.setPreferredOrientations(ohosOrientation); + result.success(null); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setPreferredOrientations err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + + break; + case "SystemChrome.setApplicationSwitcherDescription": + Log.d(PlatformMethodCallback.TAG, "setApplicationSwitcherDescription: " + JSON.stringify(args)); + break; + case "SystemChrome.setEnabledSystemUIOverlays": + try { + let overlays: SystemUiOverlay[] = this.decodeSystemUiOverlays(args); + Log.d(PlatformMethodCallback.TAG, "overlays: " + overlays); + this.platform.platformMessageHandler.showSystemOverlays(overlays); + result.success(null); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setEnabledSystemUIOverlays err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + break; + case "SystemChrome.setEnabledSystemUIMode": + try { + Log.d(PlatformMethodCallback.TAG, "setEnabledSystemUIMode args:" + args as string); + let mode: SystemUiMode = this.decodeSystemUiMode(args as string) + this.platform.platformMessageHandler.showSystemUiMode(mode); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setEnabledSystemUIMode err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + break; + case "SystemChrome.setSystemUIChangeListener": + this.platform.platformMessageHandler.setSystemUiChangeListener(); + result.success(null); + break; + case "SystemChrome.restoreSystemUIOverlays": + this.platform.platformMessageHandler.restoreSystemUiOverlays(); + result.success(null); + break; + case "SystemChrome.setSystemUIOverlayStyle": + try { + Log.d(PlatformMethodCallback.TAG, "setSystemUIOverlayStyle asrgs: " + JSON.stringify(args)); + let systemChromeStyle: SystemChromeStyle = this.decodeSystemChromeStyle(args); + this.platform.platformMessageHandler.setSystemUiOverlayStyle(systemChromeStyle); + result.success(null); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setSystemUIOverlayStyle err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + break; + case "SystemNavigator.pop": + this.platform.platformMessageHandler.popSystemNavigator(); + result.success(null); + break; + case "Clipboard.getData": + let pasteBoard = pasteboard.getSystemPasteboard(); + pasteBoard.getData().then((pasteData) => { + let text = pasteData.getPrimaryText(); + let response: ESObject = new Map().set("text", ""); + response.text = text; + result.success(response); + }).catch((err: ESObject) => { + Log.e(PlatformMethodCallback.TAG, "Failed to get PasteData. Cause: " + JSON.stringify(err)); + }); + break; + case "Clipboard.setData": + let clipboardContent: string = args.text; + this.platform.platformMessageHandler.setClipboardData(clipboardContent); + result.success(null); + break; + case "Clipboard.hasStrings": + let hasStrings: boolean = false; + let response: ESObject = new Map().set("value", false); + let systemPasteboard = pasteboard.getSystemPasteboard(); + systemPasteboard.hasData().then((hasData) => { + if (!hasData) { + response.value = hasData; + result.success(response); + } + }).catch((err: ESObject) => { + Log.e(PlatformMethodCallback.TAG, "systemPasteboard.hasData err: " + JSON.stringify(err)); + }) + systemPasteboard.getData().then((pasteData) => { + hasStrings = pasteData.hasType(pasteboard.MIMETYPE_TEXT_PLAIN); + response.value = hasStrings; + result.success(response); + }).catch((err: ESObject) => { + Log.e(PlatformMethodCallback.TAG, "getData err: " + JSON.stringify(err)); + }) + break; + default: + result.notImplemented(); + break; + } + } catch (e) { + result.error("error", JSON.stringify(e), null); + } + } + + private decodeSystemUiOverlays(encodedSystemUiOverlay: string[]): SystemUiOverlay[] { + let overlays: SystemUiOverlay[] = []; + for(let i = 0; i < encodedSystemUiOverlay.length; i++) { + const encodedOverlay = encodedSystemUiOverlay[i]; + const overlay = this.platform.getSystemUiOverlayFromValue(encodedOverlay); + switch (overlay) { + case SystemUiOverlay.TOP_OVERLAYS: + overlays.push(SystemUiOverlay.TOP_OVERLAYS); + break; + case SystemUiOverlay.BOTTOM_OVERLAYS: + overlays.push(SystemUiOverlay.BOTTOM_OVERLAYS); + break; + } + } + return overlays; + } + + private decodeSystemUiMode(encodedSystemUiMode: string): SystemUiMode { + let mode: SystemUiMode = this.platform.getSystemUiModeFromValue(encodedSystemUiMode); + switch (mode) { + case SystemUiMode.LEAN_BACK: + return SystemUiMode.LEAN_BACK; + case SystemUiMode.IMMERSIVE: + return SystemUiMode.IMMERSIVE; + case SystemUiMode.IMMERSIVE_STICKY: + return SystemUiMode.IMMERSIVE_STICKY; + case SystemUiMode.EDGE_TO_EDGE: + default: + return SystemUiMode.EDGE_TO_EDGE; + } + } + + private decodeSystemChromeStyle(encodedStyle: ESObject): SystemChromeStyle { + let statusBarColor: number | null = null; + let statusBarIconBrightness: Brightness | null = null; + let systemStatusBarContrastEnforced: boolean | null = null; + let systemNavigationBarColor: number | null = null; + let systemNavigationBarIconBrightness: Brightness | null = null; + let systemNavigationBarDividerColor: number | null = null; + let systemNavigationBarContrastEnforced: boolean | null = null; + if(encodedStyle.statusBarColor != null) { + statusBarColor = encodedStyle.statusBarColor as number; + } + if(encodedStyle.statusBarIconBrightness != null) { + statusBarIconBrightness = + this.platform.getBrightnessFromValue(encodedStyle.statusBarIconBrightness as string); + } + if(encodedStyle.systemStatusBarContrastEnforced != null) { + systemStatusBarContrastEnforced = encodedStyle.systemStatusBarContrastEnforced as boolean; + } + if(encodedStyle.systemNavigationBarColor != null) { + systemNavigationBarColor = encodedStyle.systemNavigationBarColor as number; + } + if(encodedStyle.systemNavigationBarIconBrightness != null) { + systemNavigationBarIconBrightness = + this.platform.getBrightnessFromValue(encodedStyle.systemNavigationBarIconBrightness as string); + } + if(encodedStyle.systemNavigationBarDividerColor != null) { + systemNavigationBarDividerColor = encodedStyle.systemNavigationBarDividerColor as number; + } + if(encodedStyle.systemNavigationBarContrastEnforced != null) { + systemNavigationBarContrastEnforced = encodedStyle.systemNavigationBarContrastEnforced as boolean; + } + return new SystemChromeStyle( + statusBarColor, + statusBarIconBrightness, + systemStatusBarContrastEnforced, + systemNavigationBarColor, + systemNavigationBarIconBrightness, + systemNavigationBarDividerColor, + systemNavigationBarContrastEnforced + ); + } +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets index cd717faa54..5da4a68f2f 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets @@ -21,10 +21,11 @@ import Log from '../../../util/Log'; import DartExecutor from '../dart/DartExecutor'; const TAG = "PlatformViewsChannel"; - +const NON_TEXTURE_FALLBACK = -2; export default class PlatformViewsChannel { private channel: MethodChannel; - private handler: PlatformViewsHandler; + private handler: PlatformViewsHandler | null = null; + private parsingHandler = new ParsingCallback(); /** * Constructs a {@code PlatformViewsChannel} that connects Android to the Dart code running in @@ -36,6 +37,7 @@ export default class PlatformViewsChannel { */ constructor(dartExecutor: DartExecutor) { this.channel = new MethodChannel(dartExecutor, "flutter/platform_views", StandardMethodCodec.INSTANCE); + this.parsingHandler.platformChannel = this; this.channel.setMethodCallHandler(this.parsingHandler); } @@ -43,8 +45,9 @@ export default class PlatformViewsChannel { * Sets the {@link PlatformViewsHandler} which receives all events and requests that are parsed * from the underlying platform views channel. */ - public setPlatformViewsHandler(handler: PlatformViewsHandler): void { + public setPlatformViewsHandler(handler: PlatformViewsHandler | null): void { this.handler = handler; + this.parsingHandler.handler = handler; } public invokeViewFocused(viewId: number): void { @@ -54,54 +57,8 @@ export default class PlatformViewsChannel { this.channel.invokeMethod("viewFocused", viewId); } - private parsingHandler: MethodCallHandler = { - onMethodCall: (call: MethodCall, result: MethodResult): void => { - if (this.handler == null) { - return; - } - - Log.i(TAG, "Received '" + call.method + "' message."); - switch (call.method) { - case "create": { - this.create(call, result); - break; - } - case "dispose": { - this.dispose(call, result); - break; - } - case "resize": { - this.resize(call, result); - break; - } - case "offset": { - this.offset(call, result); - break; - } - case "touch": { - this.touch(call, result); - break; - } - case "setDirection": { - this.setDirection(call, result); - break; - } - case "clearFocus": { - this.clearFocus(call, result); - break; - } - case "synchronizeToNativeViewHierarchy": { - this.synchronizeToNativeViewHierarchy(call, result); - break; - } - default: - result.notImplemented(); - } - } - } - create(call: MethodCall, result: MethodResult): void { - const createArgs: Map = call.args; + const createArgs: Map = call.args; const usesPlatformViewLayer: boolean = createArgs.has("hybrid") && createArgs.get("hybrid") as boolean; const additionalParams: ByteBuffer = createArgs.has("params") ? createArgs.get("params") : null; @@ -125,7 +82,7 @@ export default class PlatformViewsChannel { additionalParams, RequestedDisplayMode.HYBRID_ONLY ); - this.handler.createForPlatformViewLayer(request); + this.handler?.createForPlatformViewLayer(request); result.success(null); } else { const hybridFallback: boolean = createArgs.has("hybridFallback") && createArgs.get("hybridFallback"); @@ -152,8 +109,8 @@ export default class PlatformViewsChannel { t:${request.logicalTop}, d:${request.direction}`); - const textureId = this.handler.createForTextureLayer(request); - if (textureId == PlatformViewsHandler.NON_TEXTURE_FALLBACK) { + const textureId = this.handler?.createForTextureLayer(request); + if (textureId == NON_TEXTURE_FALLBACK) { if (!hybridFallback) { throw new Error( "Platform view attempted to fall back to hybrid mode when not requested."); @@ -172,10 +129,10 @@ export default class PlatformViewsChannel { } dispose(call: MethodCall, result: MethodResult): void { - const disposeArgs: Map = call.args; + const disposeArgs: Map = call.args; const viewId: number = disposeArgs.get("id"); try { - this.handler.dispose(viewId); + this.handler?.dispose(viewId); result.success(null); } catch (err) { Log.e(TAG, "dispose failed", err); @@ -184,25 +141,16 @@ export default class PlatformViewsChannel { } resize(call: MethodCall, result: MethodResult): void { - const resizeArgs: Map = call.args; + const resizeArgs: Map = call.args; const resizeRequest: PlatformViewResizeRequest = new PlatformViewResizeRequest( resizeArgs.get("id"), resizeArgs.get("width"), resizeArgs.get("height") ); try { - this.handler.resize(resizeRequest, { - run: (bufferSize: PlatformViewBufferSize) => { - if (bufferSize == null) { - result.error("error", "Failed to resize the platform view", null); - } else { - const response: Map = new Map(); - response.set("width", bufferSize.width); - response.set("height", bufferSize.height); - result.success(response); - } - } - }) + let resizeCallback = new ResizeCallback(); + resizeCallback.result = result; + this.handler?.resize(resizeRequest, resizeCallback); } catch (err) { Log.e(TAG, "resize failed", err); result.error("error", err, null); @@ -210,9 +158,9 @@ export default class PlatformViewsChannel { } offset(call: MethodCall, result: MethodResult): void { - const offsetArgs: Map = call.args; + const offsetArgs: Map = call.args; try { - this.handler.offset( + this.handler?.offset( offsetArgs.get("id"), offsetArgs.get("top"), offsetArgs.get("left")); @@ -224,7 +172,7 @@ export default class PlatformViewsChannel { } touch(call: MethodCall, result: MethodResult): void { - const args: Array = call.args; + const args: Array = call.args; let index = 0; const touch: PlatformViewTouch = new PlatformViewTouch( args[index++], @@ -246,7 +194,7 @@ export default class PlatformViewsChannel { ); try { - this.handler.onTouch(touch); + this.handler?.onTouch(touch); result.success(null); } catch (err) { Log.e(TAG, "offset failed", err); @@ -255,12 +203,12 @@ export default class PlatformViewsChannel { } setDirection(call: MethodCall, result: MethodResult): void { - const setDirectionArgs: Map = call.args; + const setDirectionArgs: Map = call.args; const newDirectionViewId: number = setDirectionArgs.get("id"); const direction: number = setDirectionArgs.get("direction"); try { - this.handler.setDirection(newDirectionViewId, direction); + this.handler?.setDirection(newDirectionViewId, direction); result.success(null); } catch (err) { Log.e(TAG, "setDirection failed", err); @@ -271,7 +219,7 @@ export default class PlatformViewsChannel { clearFocus(call: MethodCall, result: MethodResult): void { const viewId: number = call.args; try { - this.handler.clearFocus(viewId); + this.handler?.clearFocus(viewId); result.success(null); } catch (err) { Log.e(TAG, "clearFocus failed", err); @@ -282,7 +230,7 @@ export default class PlatformViewsChannel { synchronizeToNativeViewHierarchy(call: MethodCall, result: MethodResult): void { const yes: boolean = call.args; try { - this.handler.synchronizeToNativeViewHierarchy(yes); + this.handler?.synchronizeToNativeViewHierarchy(yes); result.success(null); } catch (err) { Log.e(TAG, "synchronizeToNativeViewHierarchy failed", err); @@ -298,7 +246,7 @@ export default class PlatformViewsChannel { *

To register a {@code PlatformViewsHandler} with a {@link PlatformViewsChannel}, see {@link * PlatformViewsChannel#setPlatformViewsHandler(PlatformViewsHandler)}. */ -export abstract class PlatformViewsHandler { +export interface PlatformViewsHandler { /* * The ID returned by {@code createForTextureLayer} to indicate that the requested texture mode * was not available and the view creation fell back to {@code PlatformViewLayer} mode. @@ -306,7 +254,6 @@ export abstract class PlatformViewsHandler { * This can only be returned if the {@link PlatformViewCreationRequest} sets * {@code TEXTURE_WITH_HYBRID_FALLBACK} as the requested display mode. */ - public static NON_TEXTURE_FALLBACK = -2; /** * The Flutter application would like to display a new Ohos {@code View}, i.e., platform @@ -317,7 +264,7 @@ export abstract class PlatformViewsHandler { * * @param request The metadata sent from the framework. */ - abstract createForPlatformViewLayer(request: PlatformViewCreationRequest): void; + createForPlatformViewLayer(request: PlatformViewCreationRequest): void; /** * The Flutter application would like to display a new Android {@code View}, i.e., platform @@ -329,10 +276,10 @@ export abstract class PlatformViewsHandler { * @param request The metadata sent from the framework. * @return The texture ID. */ - abstract createForTextureLayer(request: PlatformViewCreationRequest): number; + createForTextureLayer(request: PlatformViewCreationRequest): number; /** The Flutter application would like to dispose of an existing Android {@code View}. */ - abstract dispose(viewId: number): void; + dispose(viewId: number): void; /** * The Flutter application would like to resize an existing Android {@code View}. @@ -341,28 +288,28 @@ export abstract class PlatformViewsHandler { * @param onComplete Once the resize is completed, this is the handler to notify the size of the * platform view buffer. */ - abstract resize(request: PlatformViewResizeRequest, onComplete: PlatformViewBufferResized): void; + resize(request: PlatformViewResizeRequest, onComplete: PlatformViewBufferResized): void; /** * The Flutter application would like to change the offset of an existing Android {@code View}. */ - abstract offset(viewId: number, top: number, left: number): void; + offset(viewId: number, top: number, left: number): void; /** * The user touched a platform view within Flutter. * *

Touch data is reported in {@code touch}. */ - abstract onTouch(touch: PlatformViewTouch): void; + onTouch(touch: PlatformViewTouch): void; /** * The Flutter application would like to change the layout direction of an existing Android * {@code View}, i.e., platform view. */ - abstract setDirection(viewId: number, direction: number): void; + setDirection(viewId: number, direction: number): void; /** Clears the focus from the platform view with a give id if it is currently focused. */ - abstract clearFocus(viewId: number): void; + clearFocus(viewId: number): void; /** * Whether the render surface of {@code FlutterView} should be converted to a {@code @@ -371,7 +318,7 @@ export abstract class PlatformViewsHandler { *

This is done to syncronize the rendering of the PlatformView and the FlutterView. Defaults * to true. */ - abstract synchronizeToNativeViewHierarchy(yes: boolean): void; + synchronizeToNativeViewHierarchy(yes: boolean): void; } /** Platform view display modes that can be requested at creation time. */ @@ -480,10 +427,10 @@ export class PlatformViewTouch { public pointerCount: number; /** Properties for each pointer, encoded in a raw format. */ - public rawPointerPropertiesList: any; + public rawPointerPropertiesList: ESObject; /** Coordinates for each pointer, encoded in a raw format. */ - public rawPointerCoords: any; + public rawPointerCoords: ESObject; public metaState: number; @@ -510,8 +457,8 @@ export class PlatformViewTouch { eventTime: number, action: number, pointerCount: number, - rawPointerPropertiesList: any, - rawPointerCoords: any, + rawPointerPropertiesList: ESObject, + rawPointerCoords: ESObject, metaState: number, buttonState: number, xPrecision: number, @@ -538,4 +485,67 @@ export class PlatformViewTouch { this.flags = flags; this.motionEventId = motionEventId; } +} + +class ParsingCallback implements MethodCallHandler { + platformChannel : PlatformViewsChannel | null = null; + handler: PlatformViewsHandler | null = null; + + onMethodCall(call: MethodCall, result: MethodResult) { + if (this.handler == null) { + return; + } + + Log.i(TAG, "Received '" + call.method + "' message."); + switch (call.method) { + case "create": { + this.platformChannel?.create(call, result); + break; + } + case "dispose": { + this.platformChannel?.dispose(call, result); + break; + } + case "resize": { + this.platformChannel?.resize(call, result); + break; + } + case "offset": { + this.platformChannel?.offset(call, result); + break; + } + case "touch": { + this.platformChannel?.touch(call, result); + break; + } + case "setDirection": { + this.platformChannel?.setDirection(call, result); + break; + } + case "clearFocus": { + this.platformChannel?.clearFocus(call, result); + break; + } + case "synchronizeToNativeViewHierarchy": { + this.platformChannel?.synchronizeToNativeViewHierarchy(call, result); + break; + } + default: + result.notImplemented(); + } + } +} + +class ResizeCallback extends PlatformViewBufferResized { + result : MethodResult | null = null; + run(bufferSize: PlatformViewBufferSize) { + if (bufferSize == null) { + this.result?.error("error", "Failed to resize the platform view", null); + } else { + const response: Map = new Map(); + response.set("width", bufferSize.width); + response.set("height", bufferSize.height); + this.result?.success(response); + } + } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/RestorationChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/RestorationChannel.ets index 2d4440cdbb..9ccbd2c3f5 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/RestorationChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/RestorationChannel.ets @@ -53,16 +53,17 @@ export default class RestorationChannel { * itself to default values until the restoration data has been made available. Setting this flag * to true avoids that extra work. */ - public waitForRestorationData: boolean; + public waitForRestorationData: boolean = false; // Holds the most current restoration data which may have been provided by the engine // via "setRestorationData" or by the framework via the method channel. This is the data the // framework should be restored to in case the app is terminated. - private restorationData: Uint8Array; - private channel: MethodChannel; - private pendingFrameworkRestorationChannelRequest: MethodResult; + private restorationData: Uint8Array = new Uint8Array(); + private channel: MethodChannel | null = null; + private pendingFrameworkRestorationChannelRequest: MethodResult | null = null; private engineHasProvidedData: boolean = false; private frameworkHasRequestedData: boolean = false; + private handler: MethodCallHandler = new RestorationChannelMethodCallHandler(this.restorationData); constructor(channelOrExecutor: MethodChannel | DartExecutor, waitForRestorationData: boolean) { if (channelOrExecutor instanceof MethodChannel) { @@ -84,7 +85,7 @@ export default class RestorationChannel { this.engineHasProvidedData = true; if (this.pendingFrameworkRestorationChannelRequest != null) { // If their is a pending request from the framework, answer it. - this.pendingFrameworkRestorationChannelRequest.success(this.packageData(data)); + this.pendingFrameworkRestorationChannelRequest.success(RestorationChannelMethodCallHandler.packageData(data)); this.pendingFrameworkRestorationChannelRequest = null; this.restorationData = data; } else if (this.frameworkHasRequestedData) { @@ -93,12 +94,12 @@ export default class RestorationChannel { // framework retrieved the restoration state before it was set via this method. // Experimentally, this can also be used to restore a previously used engine to another state, // e.g. when the engine is attached to a new activity. - this.channel.invokeMethod("push", this.packageData(data), { - success: (result: any) :void => { + this.channel?.invokeMethod("push", RestorationChannelMethodCallHandler.packageData(data), { + success: (result: ESObject) :void => { this.restorationData = data; }, - error: (errorCode: string, errorMessage: string, errorDetails: any) :void => { + error: (errorCode: string, errorMessage: string, errorDetails: ESObject) :void => { Log.e(RestorationChannel.TAG, "Error " + errorCode + " while sending restoration data to framework: " + errorMessage); }, @@ -120,42 +121,53 @@ export default class RestorationChannel { * state prior to the hot restart will get restored. */ clearData() { - this.restorationData = null; + this.restorationData = new Uint8Array(); } +} - private handler: MethodCallHandler = { - onMethodCall: (call: MethodCall, result: MethodResult) :void => { - const method = call.method; - const args = call.args; - switch (method) { - case "put": { - this.restorationData = args; - result.success(null); - break; - } - case "get": { - this.frameworkHasRequestedData = true; - if (this.engineHasProvidedData || !this.waitForRestorationData) { - result.success(this.packageData(this.restorationData)); - // Do not delete the restoration data on the engine side after sending it to the - // framework. We may need to hand this data back to the operating system if the - // framework never modifies the data (and thus doesn't send us any - // data back). - } else { - this.pendingFrameworkRestorationChannelRequest = result; - } - break; - } - default: { - result.notImplemented(); - break; +class RestorationChannelMethodCallHandler implements MethodCallHandler { + public waitForRestorationData: boolean = false; + private restorationData: Uint8Array; + private engineHasProvidedData: boolean = false; + private frameworkHasRequestedData: boolean = false; + private channel: MethodChannel | null = null; + private pendingFrameworkRestorationChannelRequest: MethodResult | null = null; + + constructor(restorationData: Uint8Array) { + this.restorationData = restorationData; + } + + onMethodCall(call: MethodCall, result: MethodResult): void { + const method = call.method; + const args: ESObject = call.args; + switch (method) { + case "put": { + this.restorationData = args; + result.success(null); + break; + } + case "get": { + this.frameworkHasRequestedData = true; + if (this.engineHasProvidedData || !this.waitForRestorationData) { + result.success(RestorationChannelMethodCallHandler.packageData(this.restorationData)); + // Do not delete the restoration data on the engine side after sending it to the + // framework. We may need to hand this data back to the operating system if the + // framework never modifies the data (and thus doesn't send us any + // data back). + } else { + this.pendingFrameworkRestorationChannelRequest = result; } + break; + } + default: { + result.notImplemented(); + break; } } - }; + } - private packageData(data: Uint8Array): Map { - const packaged: Map = new Map(); + static packageData(data: Uint8Array): Map { + const packaged: Map = new Map(); packaged.set("enabled", true); packaged.set("data", data); return packaged; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets index 2b5021ca20..b40cd5536a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets @@ -35,7 +35,7 @@ export default class SettingsChannel { private channel: BasicMessageChannel; constructor(dartExecutor: DartExecutor) { - this.channel = new BasicMessageChannel(dartExecutor, SettingsChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel(dartExecutor, SettingsChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); } startMessage(): MessageBuilder { @@ -84,6 +84,6 @@ class MessageBuilder { + this.message.get(ALWAYS_USE_24_HOUR_FORMAT) + "platformBrightness: " + this.message.get(PLATFORM_BRIGHTNESS)) - this.channel.send(Object.fromEntries(this.message)) + this.channel.send(this.message) } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets index ded2507910..9f9ef28154 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets @@ -26,14 +26,12 @@ export default class SystemChannel { public channel: BasicMessageChannel; constructor(dartExecutor: DartExecutor) { - this.channel = new BasicMessageChannel(dartExecutor, "flutter/system", JSONMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel(dartExecutor, "flutter/system", JSONMessageCodec.INSTANCE); } public sendMemoryPressureWarning(): void { Log.i(TAG, "Sending memory pressure warning to Flutter"); - let message: any = { - "type":"memoryPressure" - }; + let message : Map = new Map().set("type", "memoryPressure"); this.channel.send(message); } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets index 5387e7fdc3..d54c448e02 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import BasicMessageChannel, { Reply } from '../../../plugin/common/BasicMessageChannel'; +import BasicMessageChannel, { MessageHandler, Reply } from '../../../plugin/common/BasicMessageChannel'; import JSONMessageCodec from '../../../plugin/common/JSONMessageCodec'; import DartExecutor from '../dart/DartExecutor'; import Log from '../../../util/Log'; @@ -25,12 +25,14 @@ export default class TestChannel { constructor(dartExecutor: DartExecutor) { this.channel = new BasicMessageChannel(dartExecutor, "flutter/test", JSONMessageCodec.INSTANCE); + let callback = new MessageCallback(); + this.channel.setMessageHandler(callback); + } +} - this.channel.setMessageHandler({ - onMessage(call: String, reply: Reply): void { - Log.d(TAG, "receive msg = " + call); - reply.reply("收到消息啦:" + call); - } - }); +class MessageCallback implements MessageHandler { + onMessage(message: string, reply: Reply) { + Log.d(TAG, "receive msg = " + message); + reply.reply("收到消息啦:" + message); } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TextInputChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TextInputChannel.ets index 266884717d..7e7d93c164 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TextInputChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TextInputChannel.ets @@ -25,75 +25,15 @@ const TAG = "TextInputChannel"; export default class TextInputChannel { private static CHANNEL_NAME = "flutter/textinput"; public channel: MethodChannel; - private textInputMethodHandler: TextInputMethodHandler; + textInputMethodHandler: TextInputMethodHandler | null = null; constructor(dartExecutor: DartExecutor) { this.channel = new MethodChannel(dartExecutor, TextInputChannel.CHANNEL_NAME, JSONMethodCodec.INSTANCE); - this.channel.setMethodCallHandler({ - onMethodCall: (call: MethodCall, result: MethodResult): void => { - if(this.textInputMethodHandler == null) { - return; - } - let method: string = call.method; - let args: any = call.args; - Log.d(TAG, "Received '" + method + "' message."); - switch (method) { - case "TextInput.show": - this.textInputMethodHandler.show(); - Log.d(TAG, "textInputMethodHandler.show()"); - result.success(null); - break; - case "TextInput.hide": - this.textInputMethodHandler.hide(); - result.success(null); - break; - case "TextInput.setClient": - const textInputClientId: number = args[0] as number; - //TODO: parse configuration - const config: Configuration = null; - this.textInputMethodHandler.setClient(textInputClientId, config); - result.success(null); - break; - case "TextInput.requestAutofill": - //TODO: requestAutofill - result.notImplemented(); - break; - case "TextInput.setPlatformViewClient": - //TODO: - result.notImplemented(); - break; - case "TextInput.setEditingState": - this.textInputMethodHandler.setEditingState(TextEditState.fromJson(args)); - result.success(null); - break; - case "TextInput.setEditableSizeAndTransform": - //TODO: - result.notImplemented(); - break; - case "TextInput.clearClient": - this.textInputMethodHandler.clearClient(); - result.success(null); - break; - case "TextInput.sendAppPrivateCommand": - //TODO: - result.notImplemented(); - break; - case "TextInput.finishAutofillContext": - //TODO: - result.notImplemented(); - break; - default: - result.notImplemented(); - break; - } - } - }); } - - setTextInputMethodHandler(textInputMethodHandler: TextInputMethodHandler): void { this.textInputMethodHandler = textInputMethodHandler; + this.channel.setMethodCallHandler(new TextInputCallback(this.textInputMethodHandler)); } requestExistingInputState(): void { @@ -104,15 +44,13 @@ export default class TextInputChannel { selectionStart: number, selectionEnd: number, composingStart: number, - composingEnd: number): any { - let state = { - "text": text, - "selectionBase": selectionStart, - "selectionExtent": selectionEnd, - "composingBase": composingStart, - "composingExtent": composingEnd - } - return state; + composingEnd: number): ESObject { + return new Map() + .set("text", text) + .set("selectionBase", selectionStart) + .set("selectionExtent", selectionEnd) + .set("composingBase", composingStart) + .set("composingExtent", composingEnd); } /** @@ -127,7 +65,7 @@ export default class TextInputChannel { Log.d(TAG, "updateEditingState:" + "Text: " + text + " Selection start: " + selectionStart + " Selection end: " + selectionEnd + " Composing start: " + composingStart + " Composing end: " + composingEnd); - const state: any = this.createEditingStateJSON(text, selectionStart, selectionEnd, composingStart, composingEnd); + const state: ESObject = this.createEditingStateJSON(text, selectionStart, selectionEnd, composingStart, composingEnd); this.channel.invokeMethod('TextInputClient.updateEditingState', [inputClientId, state]); Log.d(TAG,"updateEditingState end"); @@ -178,7 +116,7 @@ export default class TextInputChannel { this.channel.invokeMethod("TextInputClient.performAction", [inputClientId, "TextInputAction.commitContent"]); } - performPrivateCommand(inputClientId: number, action: string, data: any) { + performPrivateCommand(inputClientId: number, action: string, data: ESObject) { } @@ -196,7 +134,7 @@ export interface TextInputMethodHandler { finishAutofillContext(shouldSave: boolean): void; - setClient(textInputClientId: number, configuration: Configuration): void; + setClient(textInputClientId: number, configuration: Configuration | null): void; setPlatformViewClient(id: number, usesVirtualDisplay: boolean): void; @@ -209,17 +147,17 @@ export interface TextInputMethodHandler { } export class Configuration { - obscureText: boolean; - autocorrect: boolean; - enableSuggestions: boolean; - enableIMEPersonalizedLearning: boolean; - enableDeltaModel: boolean; - textCapitalization: TextCapitalization; - inputType:InputType; - inputAction: Number; - actionLabel: String; - contentCommitMimeTypes: String[]; - fields: Configuration[]; + obscureText: boolean = false; + autocorrect: boolean = false; + enableSuggestions: boolean = false; + enableIMEPersonalizedLearning: boolean = false; + enableDeltaModel: boolean = false; + textCapitalization: TextCapitalization | null = null; + inputType: InputType | null = null; + inputAction: Number = 0; + actionLabel: String = ""; + contentCommitMimeTypes: String[] = []; + fields: Configuration[] = []; constructor(obscureText: boolean, autocorrect: boolean, @@ -231,9 +169,14 @@ export class Configuration { actionLabel: String, ) { } getTextCapitalizationFromValue(encodedName: string): TextCapitalization { - for (const key in TextCapitalization) { + let textKeys = [ + TextCapitalization.CHARACTERS, TextCapitalization.WORDS, + TextCapitalization.SENTENCES, TextCapitalization.NONE + ]; + for (let i = 0; i < textKeys.length; i++) { + let key = textKeys[i]; if (TextCapitalization[key] === encodedName) { - return key; + return key; } } throw new Error("No such TextCapitalization: " + encodedName); @@ -272,15 +215,22 @@ export class InputType { this.isDecimal = isDecimal; } - static fromJson(json: any): InputType { - return new InputType(this.getTextInputTypeFromValue(json.name as string), + static fromJson(json: ESObject): InputType { + return new InputType(InputType.getTextInputTypeFromValue(json.name as string), json.signed as boolean, json.decimal as boolean) } - static getTextInputTypeFromValue(encodedName: string): TextInputType{ - for(const key in TextInputType) { - if(TextInputType[key] == encodedName) { - return key; + static getTextInputTypeFromValue(encodedName: string): TextInputType { + let textKeys = [ + TextInputType.TEXT, TextInputType.DATETIME, TextInputType.NAME, + TextInputType.POSTAL_ADDRESS, TextInputType.NUMBER, TextInputType.PHONE, + TextInputType.MULTILINE, TextInputType.EMAIL_ADDRESS, TextInputType.URL, + TextInputType.VISIBLE_PASSWORD, TextInputType.NONE + ]; + for (let i = 0; i < textKeys.length; i++) { + let key = textKeys[i]; + if (TextInputType[key] == encodedName) { + return key; } } throw new Error("No such TextInputType: " + encodedName); @@ -339,7 +289,7 @@ export class TextEditState { return this.composingStart >= 0 && this.composingEnd > this.composingStart; } - static fromJson(textEditState: any): TextEditState { + static fromJson(textEditState: ESObject): TextEditState { return new TextEditState( textEditState.text, textEditState.selectionBase, @@ -348,5 +298,70 @@ export class TextEditState { textEditState.composingExtent ) } +} + +class TextInputCallback implements MethodCallHandler { + textInputMethodHandler: TextInputMethodHandler; + + constructor(handler: TextInputMethodHandler) { + this.textInputMethodHandler = handler; + } -} \ No newline at end of file + onMethodCall(call: MethodCall, result: MethodResult) { + if (this.textInputMethodHandler == null) { + return; + } + let method: string = call.method; + let args: ESObject = call.args; + Log.d(TAG, "Received '" + method + "' message."); + switch (method) { + case "TextInput.show": + this.textInputMethodHandler.show(); + Log.d(TAG, "textInputMethodHandler.show()"); + result.success(null); + break; + case "TextInput.hide": + this.textInputMethodHandler.hide(); + result.success(null); + break; + case "TextInput.setClient": + const textInputClientId: number = args[0] as number; + //TODO: parse configuration + const config: Configuration | null = null; + this.textInputMethodHandler.setClient(textInputClientId, config); + result.success(null); + break; + case "TextInput.requestAutofill": + //TODO: requestAutofill + result.notImplemented(); + break; + case "TextInput.setPlatformViewClient": + //TODO: + result.notImplemented(); + break; + case "TextInput.setEditingState": + this.textInputMethodHandler.setEditingState(TextEditState.fromJson(args)); + result.success(null); + break; + case "TextInput.setEditableSizeAndTransform": + //TODO: + result.notImplemented(); + break; + case "TextInput.clearClient": + this.textInputMethodHandler.clearClient(); + result.success(null); + break; + case "TextInput.sendAppPrivateCommand": + //TODO: + result.notImplemented(); + break; + case "TextInput.finishAutofillContext": + //TODO: + result.notImplemented(); + break; + default: + result.notImplemented(); + break; + } + } +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets index dd91f36972..1fea226f6e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets @@ -31,6 +31,7 @@ import { PlatformBrightness } from '../engine/systemchannels/SettingsChannel'; import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; import { DVModelContainer } from '../../view/DynamicView/dynamicView'; import { RootDvModeManager } from '../../plugin/platform/RootDvModelManager'; +import { Configuration } from '@ohos.app.ability.Configuration'; const TAG = "FlutterAbility"; /** @@ -40,11 +41,11 @@ const TAG = "FlutterAbility"; * 2、生命周期传递; */ export class FlutterAbility extends UIAbility implements Host { - private delegate: FlutterAbilityDelegate; - private windowStage: window.WindowStage; - private mainWindow: window.Window; + private delegate?: FlutterAbilityDelegate | null; + private windowStage?: window.WindowStage; + private mainWindow?: window.Window; private viewportMetrics = new ViewportMetrics(); - private displayInfo: display.Display; + private displayInfo?: display.Display; /** * onCreate @@ -53,30 +54,30 @@ export class FlutterAbility extends UIAbility implements Host { * 3、lifecycle.onCreate * 4. setContentView() noNeed */ - async onCreate(want, launchParam) { + async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { Log.i(TAG, "bundleCodeDir=" + this.context.bundleCodeDir); - globalThis.flutterAbility = this - this.displayInfo = display.getDefaultDisplaySync() - this.viewportMetrics.devicePixelRatio = this.displayInfo.densityPixels + // globalThis.flutterAbility = this + this.displayInfo = display.getDefaultDisplaySync(); + this.viewportMetrics.devicePixelRatio = this.displayInfo?.densityPixels this.delegate = new FlutterAbilityDelegate(this); - await this.delegate.onAttach(this.context); + await this?.delegate?.onAttach(this.context); Log.i(TAG, 'onAttach end'); - this.delegate.platformPlugin.setUIAbilityContext(this.context); - this.delegate.onRestoreInstanceState(want); - this.delegate.sendSettings(); + this?.delegate?.platformPlugin?.setUIAbilityContext(this.context); + this?.delegate?.onRestoreInstanceState(want); + this?.delegate?.sendSettings(); if (this.stillAttachedForEvent("onCreate")) { - this.delegate.onCreate(); + this?.delegate?.onCreate(); } console.log('MyAbility onCreate'); - globalThis.applicationContext = this.context.getApplicationContext(); + // globalThis.applicationContext = this.context.getApplicationContext(); } onDestroy() { if (this.stillAttachedForEvent("onDestroy")) { - this.delegate.onDestroy(); + this?.delegate?.onDestroy(); } } @@ -87,7 +88,7 @@ export class FlutterAbility extends UIAbility implements Host { async onWindowStageCreate(windowStage: window.WindowStage) { this.windowStage = windowStage try { - windowStage.on('windowStageEvent', (data) => { + windowStage?.on('windowStageEvent', (data) => { let stageEventType: window.WindowStageEventType = data; switch (stageEventType) { case window.WindowStageEventType.SHOWN: // 切到前台 @@ -96,13 +97,13 @@ export class FlutterAbility extends UIAbility implements Host { case window.WindowStageEventType.ACTIVE: // 获焦状态 Log.i(TAG, 'windowStage active.'); if (this.stillAttachedForEvent("onWindowFocusChanged")) { - this.delegate.onWindowFocusChanged(true); + this?.delegate?.onWindowFocusChanged(true); } break; case window.WindowStageEventType.INACTIVE: // 失焦状态 Log.i(TAG, 'windowStage inactive.'); if (this.stillAttachedForEvent("onWindowFocusChanged")) { - this.delegate.onWindowFocusChanged(false); + this?.delegate?.onWindowFocusChanged(false); } break; case window.WindowStageEventType.HIDDEN: // 切到后台 @@ -113,21 +114,21 @@ export class FlutterAbility extends UIAbility implements Host { } }); - this.mainWindow = windowStage.getMainWindowSync() - this.mainWindow.on('windowSizeChange', (data) => { + this.mainWindow = windowStage?.getMainWindowSync() + this.mainWindow?.on('windowSizeChange', (data) => { this.onWindowPropertiesUpdated(); }); - this.mainWindow.on('avoidAreaChange', (data) => { + this.mainWindow?.on('avoidAreaChange', (data) => { this.onWindowPropertiesUpdated(); }); - this.mainWindow.on('keyboardHeightChange', (data) => { + this.mainWindow?.on('keyboardHeightChange', (data) => { this.onWindowPropertiesUpdated(); }); this.loadContent(); - this.mainWindow.setWindowLayoutFullScreen(true); + this.mainWindow?.setWindowLayoutFullScreen(true); } catch (exception) { Log.e(TAG, 'Failed to enable the listener for window stage event changes. Cause:' + JSON.stringify(exception)); } @@ -136,7 +137,7 @@ export class FlutterAbility extends UIAbility implements Host { loadContent() { if (this.windowStage != null && this.stillAttachedForEvent("loadContent")) { Log.i(TAG, 'loadContent'); - this.windowStage.loadContent('pages/Index', (err, data) => { + this.windowStage?.loadContent('pages/Index', (err, data) => { if (err.code) { Log.e(TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; @@ -145,9 +146,9 @@ export class FlutterAbility extends UIAbility implements Host { Log.i(TAG, 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); }); if (this.stillAttachedForEvent("onWindowStageCreate")) { - this.delegate.onWindowStageCreate(); + this?.delegate?.onWindowStageCreate(); } - this.delegate.getFlutterNapi().updateRefreshRate(this.displayInfo.refreshRate) + this?.delegate?.getFlutterNapi()?.updateRefreshRate(this.displayInfo!.refreshRate) this.onFlutterEngineReady() } } @@ -157,7 +158,7 @@ export class FlutterAbility extends UIAbility implements Host { } private updateViewportMetrics() { - this.delegate.getFlutterNapi().setViewportMetrics(this.viewportMetrics.devicePixelRatio, + this?.delegate?.getFlutterNapi()?.setViewportMetrics(this.viewportMetrics.devicePixelRatio, this.viewportMetrics.physicalWidth, this.viewportMetrics.physicalHeight, this.viewportMetrics.physicalViewPaddingTop, @@ -180,25 +181,25 @@ export class FlutterAbility extends UIAbility implements Host { onWindowStageDestroy() { if (this.stillAttachedForEvent("onWindowStageDestroy")) { - this.delegate.onWindowStageDestroy(); + this?.delegate?.onWindowStageDestroy(); } } onForeground() { if (this.stillAttachedForEvent("onForeground")) { - this.delegate.onForeground(); + this?.delegate?.onForeground(); } } onBackground() { if (this.stillAttachedForEvent("onBackground")) { - this.delegate.onBackground(); + this?.delegate?.onBackground(); } } release() { - if (this.delegate != null) { - this.delegate.release(); + if (this?.delegate != null) { + this?.delegate?.release(); this.delegate = null; } } @@ -215,7 +216,7 @@ export class FlutterAbility extends UIAbility implements Host { return true; } - provideFlutterEngine(context: common.Context): FlutterEngine { + provideFlutterEngine(context: common.Context): FlutterEngine | null { return null; } @@ -232,15 +233,15 @@ export class FlutterAbility extends UIAbility implements Host { } getDartEntrypointArgs(): Array { - if (this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT_ARGS]) { - return this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT_ARGS] as Array; + if (this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT_ARGS]) { + return this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT_ARGS] as Array; } return new Array() } detachFromFlutterEngine() { - if (this.delegate != null) { - this.delegate.onDetach(); + if (this?.delegate != null) { + this?.delegate?.onDetach(); } } @@ -253,25 +254,25 @@ export class FlutterAbility extends UIAbility implements Host { } getDartEntrypointLibraryUri(): string { - return null; + return ""; } getAppBundlePath(): string { - return null; + return ""; } getDartEntrypointFunctionName(): string { - if (this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT]) { - return this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT] as string; + if (this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT]) { + return this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_DART_ENTRYPOINT] as string; } return FlutterAbilityLaunchConfigs.DEFAULT_DART_ENTRYPOINT } getInitialRoute(): string { - if (this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_INITIAL_ROUTE]) { - return this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_INITIAL_ROUTE] as string; + if (this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_INITIAL_ROUTE]) { + return this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_INITIAL_ROUTE] as string; } - return null + return "" } getWant(): Want { @@ -283,8 +284,8 @@ export class FlutterAbility extends UIAbility implements Host { } shouldRestoreAndSaveState(): boolean{ - if (this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_ID] != undefined) { - return this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_ID] as boolean; + if (this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_ID] != undefined) { + return this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_ID] as boolean; } if (this.getCachedEngineId() != null) { // Prevent overwriting the existing state in a cached engine with restoration state. @@ -294,11 +295,11 @@ export class FlutterAbility extends UIAbility implements Host { } getCachedEngineId(): string { - return this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_ID] as string + return this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_ID] as string } getCachedEngineGroupId(): string { - return this.launchWant.parameters[FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_GROUP_ID] as string + return this.launchWant.parameters![FlutterAbilityLaunchConfigs.EXTRA_CACHED_ENGINE_GROUP_ID] as string } /** @@ -306,11 +307,11 @@ export class FlutterAbility extends UIAbility implements Host { */ private stillAttachedForEvent(event: string) { Log.i(TAG, 'Ability ' + event); - if (this.delegate == null) { + if (this?.delegate == null) { Log.w(TAG, "FlutterAbility " + event + " call after release."); return false; } - if (!this.delegate.isAttached) { + if (!this?.delegate?.isAttached) { Log.w(TAG, "FlutterAbility " + event + " call after detach."); return false; } @@ -318,42 +319,42 @@ export class FlutterAbility extends UIAbility implements Host { } addPlugin(plugin: FlutterPlugin): void { - if (this.delegate != null) { - this.delegate.addPlugin(plugin) + if (this?.delegate != null) { + this?.delegate?.addPlugin(plugin) } } removePlugin(plugin: FlutterPlugin): void { - if (this.delegate != null) { - this.delegate.removePlugin(plugin) + if (this?.delegate != null) { + this?.delegate?.removePlugin(plugin) } } private onWindowPropertiesUpdated(){ - if (!this.delegate.isAttached) { + if (this?.delegate!.isAttached) { return; } - let systemAvoidArea = this.mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); - let gestureAvoidArea = this.mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM_GESTURE); - let keyboardAvoidArea = this.mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD); - const properties = this.mainWindow.getWindowProperties(); - this.viewportMetrics.physicalWidth = properties.windowRect.width; - this.viewportMetrics.physicalHeight = properties.windowRect.height; - - this.viewportMetrics.physicalViewPaddingTop = systemAvoidArea.topRect.height - this.viewportMetrics.physicalViewPaddingLeft = systemAvoidArea.leftRect.width - this.viewportMetrics.physicalViewPaddingBottom = systemAvoidArea.bottomRect.height - this.viewportMetrics.physicalViewPaddingRight = systemAvoidArea.rightRect.width - - this.viewportMetrics.physicalViewInsetTop = keyboardAvoidArea.topRect.height - this.viewportMetrics.physicalViewInsetLeft = keyboardAvoidArea.leftRect.width - this.viewportMetrics.physicalViewInsetBottom = keyboardAvoidArea.bottomRect.height - this.viewportMetrics.physicalViewInsetRight = keyboardAvoidArea.rightRect.width - - this.viewportMetrics.systemGestureInsetTop = gestureAvoidArea.topRect.height - this.viewportMetrics.systemGestureInsetLeft = gestureAvoidArea.leftRect.width - this.viewportMetrics.systemGestureInsetBottom = gestureAvoidArea.bottomRect.height - this.viewportMetrics.systemGestureInsetRight = gestureAvoidArea.rightRect.width + let systemAvoidArea = this.mainWindow?.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); + let gestureAvoidArea = this.mainWindow?.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM_GESTURE); + let keyboardAvoidArea = this.mainWindow?.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD); + const properties = this.mainWindow?.getWindowProperties(); + this.viewportMetrics.physicalWidth = properties!.windowRect.width; + this.viewportMetrics.physicalHeight = properties!.windowRect.height; + + this.viewportMetrics.physicalViewPaddingTop = systemAvoidArea!.topRect.height + this.viewportMetrics.physicalViewPaddingLeft = systemAvoidArea!.leftRect.width + this.viewportMetrics.physicalViewPaddingBottom = systemAvoidArea!.bottomRect.height + this.viewportMetrics.physicalViewPaddingRight = systemAvoidArea!.rightRect.width + + this.viewportMetrics.physicalViewInsetTop = keyboardAvoidArea!.topRect.height + this.viewportMetrics.physicalViewInsetLeft = keyboardAvoidArea!.leftRect.width + this.viewportMetrics.physicalViewInsetBottom = keyboardAvoidArea!.bottomRect.height + this.viewportMetrics.physicalViewInsetRight = keyboardAvoidArea!.rightRect.width + + this.viewportMetrics.systemGestureInsetTop = gestureAvoidArea!.topRect.height + this.viewportMetrics.systemGestureInsetLeft = gestureAvoidArea!.leftRect.width + this.viewportMetrics.systemGestureInsetBottom = gestureAvoidArea!.bottomRect.height + this.viewportMetrics.systemGestureInsetRight = gestureAvoidArea!.rightRect.width this.updateViewportMetrics() } @@ -361,13 +362,13 @@ export class FlutterAbility extends UIAbility implements Host { onMemoryLevel(level: AbilityConstant.MemoryLevel): void { Log.i(TAG, 'onMemoryLevel: ' + level); if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) { - this.delegate.onLowMemory(); + this?.delegate?.onLowMemory(); } } - onConfigurationUpdated(config){ + onConfigurationUpdated(config: Configuration){ Log.i(TAG, 'onConfigurationUpdated config:' + JSON.stringify(config)); - this.delegate.flutterEngine.getSettingsChannel().startMessage() + this?.delegate?.flutterEngine?.getSettingsChannel()?.startMessage() .setAlwaysUse24HourFormat(I18n.System.is24HourClock()) .setPlatformBrightness(config.colorMode != ConfigurationConstant.ColorMode.COLOR_MODE_DARK ? PlatformBrightness.LIGHT : PlatformBrightness.DARK); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbilityDelegate.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbilityDelegate.ets index 5e29d78d0a..af0946ca03 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbilityDelegate.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbilityDelegate.ets @@ -34,6 +34,7 @@ import FlutterEngineGroupCache from '../engine/FlutterEngineGroupCache'; import FlutterEngineGroup, { Options } from '../engine/FlutterEngineGroup'; import MouseCursorPlugin, { MouseCursorViewDelegate } from '../../plugin/mouse/MouseCursorPlugin'; import Settings from './Settings'; +import FlutterNapi from '../engine/FlutterNapi'; const TAG = "FlutterAbilityDelegate"; const PLUGINS_RESTORATION_BUNDLE_KEY = "plugins"; @@ -45,15 +46,14 @@ const FRAMEWORK_RESTORATION_BUNDLE_KEY = "framework"; * 2、处理ability生命周期回调 */ class FlutterAbilityDelegate implements ExclusiveAppComponent { - private host: Host; - flutterEngine: FlutterEngine; - platformPlugin: PlatformPlugin; - private context: common.Context; - private textInputPlugin: TextInputPlugin; - private isFlutterEngineFromHost: boolean; - private engineGroup: FlutterEngineGroup; - private mouseCursorPlugin: MouseCursorPlugin; - private settings: Settings; + private host?: Host | null; + flutterEngine?: FlutterEngine | null; + platformPlugin?: PlatformPlugin; + private context?: common.Context; + private textInputPlugin?: TextInputPlugin; + private isFlutterEngineFromHost: boolean = false; + private engineGroup?: FlutterEngineGroup; + private settings?: Settings; constructor(host: Host) { this.host = host; @@ -71,11 +71,11 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { await this.setupFlutterEngine(); } //shouldAttachEngineToActivity - if (this.host.shouldAttachEngineToActivity()) { + if (this.host?.shouldAttachEngineToActivity()) { // Notify any plugins that are currently attached to our FlutterEngine that they // are now attached to an Ability. Log.d(TAG, "Attaching FlutterEngine to the Ability that owns this delegate."); - this.flutterEngine.getAbilityControlSurface().attachToAbility(this); + this.flutterEngine?.getAbilityControlSurface()?.attachToAbility(this); } //providePlatformPlugin @@ -83,47 +83,48 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { //configureFlutterEngine this.isAttached = true; Log.d(TAG, "onAttach end start loadcontent") - this.host.loadContent() - this.textInputPlugin = new TextInputPlugin(this.flutterEngine.getTextInputChannel()); - this.platformPlugin = new PlatformPlugin(this.flutterEngine.getPlatformChannel(), this.context); - this.mouseCursorPlugin = new MouseCursorPlugin(this.host, this.flutterEngine.getMouseCursorChannel()); - this.settings = new Settings(this.flutterEngine.getSettingsChannel()); - this.flutterEngine.getSystemLanguages(); + this.host?.loadContent() + if (this.flutterEngine) { + this.textInputPlugin = new TextInputPlugin(this.flutterEngine.getTextInputChannel()!); + this.platformPlugin = new PlatformPlugin(this.flutterEngine.getPlatformChannel()!, this.context); + this.settings = new Settings(this.flutterEngine.getSettingsChannel()!); + this.flutterEngine.getSystemLanguages(); + } } /** * 加载app.so资源或者snapshot */ private doInitialFlutterViewRun(): void { - let initialRoute = this.host.getInitialRoute(); - if (initialRoute == null) { + let initialRoute = this.host?.getInitialRoute(); + if (initialRoute == null && this.host != null) { initialRoute = this.maybeGetInitialRouteFromIntent(this.host.getWant()); if (initialRoute == null) { initialRoute = FlutterAbilityLaunchConfigs.DEFAULT_INITIAL_ROUTE; } } - const libraryUri = this.host.getDartEntrypointLibraryUri(); - Log.d(TAG, "Executing Dart entrypoint: " + this.host.getDartEntrypointFunctionName() + ", library uri: " + libraryUri == null ? "\"\"" : libraryUri + ", and sending initial route: " + initialRoute); + const libraryUri = this.host?.getDartEntrypointLibraryUri(); + Log.d(TAG, "Executing Dart entrypoint: " + this.host?.getDartEntrypointFunctionName() + ", library uri: " + libraryUri == null ? "\"\"" : libraryUri + ", and sending initial route: " + initialRoute); // The engine needs to receive the Flutter app's initial route before executing any // Dart code to ensure that the initial route arrives in time to be applied. - this.flutterEngine.getNavigationChannel().setInitialRoute(initialRoute); + this.flutterEngine?.getNavigationChannel()?.setInitialRoute(initialRoute ?? ''); - let appBundlePathOverride = this.host.getAppBundlePath(); + let appBundlePathOverride = this.host?.getAppBundlePath(); if (appBundlePathOverride == null || appBundlePathOverride == '') { appBundlePathOverride = FlutterInjector.getInstance().getFlutterLoader().findAppBundlePath(); } const dartEntrypoint: DartEntrypoint = new DartEntrypoint( appBundlePathOverride, - this.host.getDartEntrypointLibraryUri(), - this.host.getDartEntrypointFunctionName() + this.host?.getDartEntrypointLibraryUri() ?? '', + this.host?.getDartEntrypointFunctionName() ?? '' ); - this.flutterEngine.dartExecutor.executeDartEntrypoint(dartEntrypoint, this.host.getDartEntrypointArgs()); + this.flutterEngine?.dartExecutor.executeDartEntrypoint(dartEntrypoint, this.host?.getDartEntrypointArgs()); } private maybeGetInitialRouteFromIntent(want: Want): string { - return null; + return ''; } @@ -132,9 +133,11 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { * @param want */ onRestoreInstanceState(want: Want) { - let frameworkState: Uint8Array = want.parameters[FRAMEWORK_RESTORATION_BUNDLE_KEY] as Uint8Array; - if (this.host.shouldRestoreAndSaveState()) { - this.flutterEngine.getRestorationChannel().setRestorationData(frameworkState ?? null); + let frameworkState = want.parameters != null + ? want.parameters[FRAMEWORK_RESTORATION_BUNDLE_KEY] as Uint8Array + : new Uint8Array(); + if (this.host?.shouldRestoreAndSaveState()) { + this.flutterEngine?.getRestorationChannel()?.setRestorationData(frameworkState); } } @@ -143,7 +146,7 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { */ async setupFlutterEngine() { // First, check if the host wants to use a cached FlutterEngine. - const cachedEngineId = this.host.getCachedEngineId(); + const cachedEngineId = this.host?.getCachedEngineId(); Log.d(TAG, "cachedEngineId=" + cachedEngineId); if (cachedEngineId && cachedEngineId.length > 0) { this.flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId); @@ -158,7 +161,9 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { } // Second, defer to subclasses for a custom FlutterEngine. - this.flutterEngine = this.host.provideFlutterEngine(this.context); + if (this.host && this.context) { + this.flutterEngine = this.host.provideFlutterEngine(this.context); + } if (this.flutterEngine != null) { this.isFlutterEngineFromHost = true; return; @@ -166,7 +171,7 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { // Third, check if the host wants to use a cached FlutterEngineGroup // and create new FlutterEngine using FlutterEngineGroup#createAndRunEngine - const cachedEngineGroupId = this.host.getCachedEngineGroupId(); + const cachedEngineGroupId = this.host?.getCachedEngineGroupId(); Log.d(TAG, "cachedEngineGroupId=" + cachedEngineGroupId); if (cachedEngineGroupId != null) { const flutterEngineGroup = FlutterEngineGroupCache.instance.get(cachedEngineGroupId); @@ -177,7 +182,10 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { + "'"); } - this.flutterEngine = await flutterEngineGroup.createAndRunEngineByOptions(this.addEntrypointOptions(new Options(this.context))); + if (this.context != null) { + this.flutterEngine = await flutterEngineGroup.createAndRunEngineByOptions( + this.addEntrypointOptions(new Options(this.context))); + } this.isFlutterEngineFromHost = false; return; } @@ -189,24 +197,30 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { "No preferred FlutterEngine was provided. Creating a new FlutterEngine for this FlutterAbility."); let group = this.engineGroup; - if (group == null) { + if (group == null && this.context != null && this.host != null) { group = new FlutterEngineGroup(); - await group.checkLoader(this.context, this.host.getFlutterShellArgs().toArray()); + await group.checkLoader(this.context, this.host.getFlutterShellArgs().toArray() ?? []); + this.engineGroup = group; + } + if (this.context) { + this.flutterEngine = await group?.createAndRunEngineByOptions(this.addEntrypointOptions(new Options(this.context) + .setAutomaticallyRegisterPlugins(false) + .setWaitForRestorationData(this.host?.shouldRestoreAndSaveState() || false))); } - this.flutterEngine = await group.createAndRunEngineByOptions(this.addEntrypointOptions(new Options(this.context) - .setAutomaticallyRegisterPlugins(false).setWaitForRestorationData(this.host.shouldRestoreAndSaveState()))); this.isFlutterEngineFromHost = false; } addEntrypointOptions(options: Options): Options { - let appBundlePathOverride = this.host.getAppBundlePath(); + let appBundlePathOverride = this.host?.getAppBundlePath(); if (appBundlePathOverride == null || appBundlePathOverride.length == 0) { appBundlePathOverride = FlutterInjector.getInstance().getFlutterLoader().findAppBundlePath(); } - const dartEntrypoint = new DartEntrypoint(appBundlePathOverride, null, this.host.getDartEntrypointFunctionName()); - let initialRoute = this.host.getInitialRoute(); - if (initialRoute == null) { + const dartEntrypoint = new DartEntrypoint(appBundlePathOverride ?? '', + '', + this.host?.getDartEntrypointFunctionName() ?? ''); + let initialRoute = this.host?.getInitialRoute(); + if (initialRoute == null && this.host != null) { initialRoute = this.maybeGetInitialRouteFromIntent(this.host.getWant()); if (initialRoute == null) { initialRoute = FlutterAbilityLaunchConfigs.DEFAULT_INITIAL_ROUTE; @@ -214,8 +228,8 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { } return options .setDartEntrypoint(dartEntrypoint) - .setInitialRoute(initialRoute) - .setDartEntrypointArgs(this.host.getDartEntrypointArgs()); + .setInitialRoute(initialRoute ?? '') + .setDartEntrypointArgs(this.host?.getDartEntrypointArgs() ?? []); } /** @@ -227,16 +241,16 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { } onDetach() { - if (this.host.shouldAttachEngineToActivity()) { + if (this.host?.shouldAttachEngineToActivity()) { // Notify plugins that they are no longer attached to an Activity. Log.d(TAG, "Detaching FlutterEngine from the Ability"); - this.flutterEngine.getAbilityControlSurface().detachFromAbility(); + this.flutterEngine?.getAbilityControlSurface()?.detachFromAbility(); } } onLowMemory(): void { - this.getFlutterNapi().notifyLowMemoryWarning(); - this.flutterEngine.getSystemChannel().sendMemoryPressureWarning(); + this.getFlutterNapi()?.notifyLowMemoryWarning(); + this.flutterEngine?.getSystemChannel()?.sendMemoryPressureWarning(); } /** @@ -246,23 +260,23 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { onCreate() { this.ensureAlive(); if (this.shouldDispatchAppLifecycleState()) { - this.flutterEngine.getLifecycleChannel().appIsInactive(); + this.flutterEngine?.getLifecycleChannel()?.appIsInactive(); } } onDestroy() { this.ensureAlive(); if (this.shouldDispatchAppLifecycleState()) { - this.flutterEngine.getLifecycleChannel().appIsDetached(); + this.flutterEngine?.getLifecycleChannel()?.appIsDetached(); } - this.textInputPlugin.detach(); + this.textInputPlugin?.detach(); } onWindowStageCreate() { this.ensureAlive(); this.doInitialFlutterViewRun(); if (this.shouldDispatchAppLifecycleState()) { - this.flutterEngine.getLifecycleChannel().appIsResumed(); + this.flutterEngine?.getLifecycleChannel()?.appIsResumed(); } } @@ -272,11 +286,11 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { onWindowFocusChanged(hasFocus: boolean):void { if (this.shouldDispatchAppLifecycleState()) { - this.flutterEngine.getAbilityControlSurface().onWindowFocusChanged(hasFocus); + this.flutterEngine?.getAbilityControlSurface()?.onWindowFocusChanged(hasFocus); if (hasFocus) { - this.flutterEngine.getLifecycleChannel().aWindowIsFocused(); + this.flutterEngine?.getLifecycleChannel()?.aWindowIsFocused(); } else { - this.flutterEngine.getLifecycleChannel().noWindowsAreFocused(); + this.flutterEngine?.getLifecycleChannel()?.noWindowsAreFocused(); } } } @@ -284,13 +298,13 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { onForeground() { this.ensureAlive(); if (this.shouldDispatchAppLifecycleState()) { - this.flutterEngine.getLifecycleChannel().appIsResumed(); + this.flutterEngine?.getLifecycleChannel()?.appIsResumed(); } } onBackground() { if (this.shouldDispatchAppLifecycleState()) { - this.flutterEngine.getLifecycleChannel().appIsPaused(); + this.flutterEngine?.getLifecycleChannel()?.appIsPaused(); } } @@ -299,6 +313,9 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { */ shouldDispatchAppLifecycleState(): boolean { + if (this.host == null) { + return false; + } return this.host.shouldDispatchAppLifecycleState() && this.isAttached; } @@ -308,12 +325,12 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { } } - getFlutterNapi() { - return this.flutterEngine.getFlutterNapi() + getFlutterNapi() : FlutterNapi | null { + return this.flutterEngine?.getFlutterNapi() ?? null } detachFromFlutterEngine() { - if (this.host.shouldDestroyEngineWithHost()) { + if (this.host?.shouldDestroyEngineWithHost()) { // The host owns the engine and should never have its engine taken by another exclusive // activity. throw new Error( @@ -326,11 +343,11 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { // Default, but customizable, behavior is for the host to call {@link #onDetach} // deterministically as to not mix more events during the lifecycle of the next exclusive // activity. - this.host.detachFromFlutterEngine(); + this.host?.detachFromFlutterEngine(); } getAppComponent(): UIAbility { - const ability = this.host.getAbility(); + const ability = this.host?.getAbility(); if (ability == null) { throw new Error( "FlutterActivityAndFragmentDelegate's getAppComponent should only " @@ -343,41 +360,41 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { this.ensureAlive() if (this.flutterEngine != null) { Log.i(TAG, "Forwarding onNewWant() to FlutterEngine and sending pushRouteInformation message."); - this.flutterEngine.getAbilityControlSurface().onNewWant(want, launchParams); + this.flutterEngine?.getAbilityControlSurface()?.onNewWant(want, launchParams); const initialRoute = this.maybeGetInitialRouteFromIntent(want); if (initialRoute && initialRoute.length > 0) { - this.flutterEngine.getNavigationChannel().pushRouteInformation(initialRoute); + this.flutterEngine?.getNavigationChannel()?.pushRouteInformation(initialRoute); } } else { Log.w(TAG, "onNewIntent() invoked before FlutterFragment was attached to an Activity."); } } - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult { + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult { Log.i(TAG, "onSaveInstanceState. Giving framework and plugins an opportunity to save state."); this.ensureAlive(); - if (this.host.shouldRestoreAndSaveState()) { - wantParam[FRAMEWORK_RESTORATION_BUNDLE_KEY] = this.flutterEngine.getRestorationChannel().getRestorationData(); + if (this.host?.shouldRestoreAndSaveState()) { + wantParam[FRAMEWORK_RESTORATION_BUNDLE_KEY] = this.flutterEngine!.getRestorationChannel()!.getRestorationData(); } - if (this.host.shouldAttachEngineToActivity()) { - const plugins = {} - const result = this.flutterEngine.getAbilityControlSurface().onSaveState(reason, plugins); + if (this.host?.shouldAttachEngineToActivity()) { + const plugins:Record = {} + const result = this.flutterEngine?.getAbilityControlSurface()?.onSaveState(reason, plugins); wantParam[PLUGINS_RESTORATION_BUNDLE_KEY] = plugins; - return result + return result ?? AbilityConstant.OnSaveResult.ALL_REJECT } return AbilityConstant.OnSaveResult.ALL_REJECT } addPlugin(plugin: FlutterPlugin): void { - this.flutterEngine.getPlugins().add(plugin) + this.flutterEngine?.getPlugins()?.add(plugin) } removePlugin(plugin: FlutterPlugin): void { - this.flutterEngine.getPlugins().remove(plugin.getUniqueClassName()) + this.flutterEngine?.getPlugins()?.remove(plugin.getUniqueClassName()) } - + sendSettings(): void { - this.settings.sendSettings() + this.settings?.sendSettings() } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEngineProvider.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEngineProvider.ets index 1bdd7b6a80..a8eea36514 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEngineProvider.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterEngineProvider.ets @@ -17,5 +17,5 @@ import FlutterEngine from '../engine/FlutterEngine'; import common from '@ohos.app.ability.common'; export default interface FlutterEngineProvider { - provideFlutterEngine(context: common.Context): FlutterEngine; + provideFlutterEngine(context: common.Context): FlutterEngine | null; } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets index 3e5993c068..0569511193 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets @@ -36,7 +36,8 @@ export struct FlutterPage { params: this.rootDvModel.model.params as DVModelParameters, events: this.rootDvModel.model.events as DVModelEvents, children: this.rootDvModel.model.children as DVModelChildren, - customBuilder: this.rootDvModel.model.builder as ($$: { params: DVModelParameters }) => void + customBuilder: this.rootDvModel.model.builder as ($$: Record<"params",DVModelParameters >) => void + //customBuilder: this.rootDvModel.model.builder as ($$: { params: DVModelParameters }) => void }) } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets index 1c6d907c3a..53f0f0a6c8 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets @@ -22,7 +22,7 @@ export default class OhosTouchProcessor { private static POINTER_DATA_FLAG_BATCHED: number = 1; - public onTouchEvent(event: TouchEvent, transformMatrix: any): void { + public onTouchEvent(event: TouchEvent, transformMatrix: ESObject): void { } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets index a435d2a45c..d8ced27e5a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets @@ -17,14 +17,14 @@ import SettingsChannel, { PlatformBrightness } from '../engine/systemchannels/Se import I18n from '@ohos.i18n' export default class Settings { - settingsChannel: SettingsChannel; + settingsChannel: SettingsChannel | null; - constructor(settingsChannel: SettingsChannel) { + constructor(settingsChannel: SettingsChannel | null) { this.settingsChannel = settingsChannel; } sendSettings(): void { - this.settingsChannel.startMessage() + this.settingsChannel?.startMessage() .setAlwaysUse24HourFormat(I18n.System.is24HourClock()) .setTextScaleFactor(1.0) .setNativeSpellCheckServiceDefined(false) diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets index fb4d9b69fd..b51743116e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** Tracks the motion events received by the FlutterView. */ import PlainArray from '@ohos.util.PlainArray'; import { TouchEvent } from '@ohos.multimodalInput.touchEvent'; @@ -23,11 +22,11 @@ export class TouchEventTracker { private unusedEvents : Queue; private static INSTANCE:TouchEventTracker; - public static getInstance() : TouchEventTracker { - if (this.INSTANCE == null) { - this.INSTANCE = new TouchEventTracker(); + public static getInstance(): TouchEventTracker { + if (TouchEventTracker.INSTANCE == null) { + TouchEventTracker.INSTANCE = new TouchEventTracker(); } - return this.INSTANCE; + return TouchEventTracker.INSTANCE; } constructor() { @@ -79,7 +78,7 @@ export class TouchEventId { } public static createUnique() : TouchEventId { - return new TouchEventId(this.ID_COUNTER++); + return new TouchEventId(TouchEventId.ID_COUNTER++); } public getId() : number { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets index fd83576280..2fa7cbf589 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets @@ -34,178 +34,190 @@ import common from '@ohos.app.ability.common'; */ export default class PlatformPlugin { private static TAG = "PlatformPlugin"; - private platformChannel: PlatformChannel; - private platformPluginDelegate: PlatformPluginDelegate; - private context: common.Context; - private windowClass: window.Window = null; - private currentTheme: SystemChromeStyle = null; - private showBarOrNavigation: ('status' | 'navigation')[] = ['status','navigation']; - private uiAbilityContext:common.UIAbilityContext = null; - private callbackId :number = null; - private applicationContext: common.ApplicationContext = null; + private callback = new PlatformPluginCallback(); constructor(platformChannel: PlatformChannel, context: common.Context, platformPluginDelegate?: PlatformPluginDelegate) { - this.platformChannel = platformChannel; - this.context = context; - this.applicationContext = this.context.getApplicationContext(); + this.callback.platformChannel = platformChannel; + this.callback.context = context; + this.callback.applicationContext = context?.getApplicationContext(); + this.callback.platform = this; try { - window.getLastWindow(this.context, (err,data) => { - if(err.code) { + window.getLastWindow(context, (err, data) => { + if (err.code) { Log.e(PlatformPlugin.TAG, "Failed to obtain the top window. Cause: " + JSON.stringify(err)); return; } - this.windowClass = data; + this.callback.windowClass = data; }); } catch (err) { - Log.e(PlatformPlugin.TAG,"Failed to obtain the top window. Cause: " + JSON.stringify(err)); + Log.e(PlatformPlugin.TAG, "Failed to obtain the top window. Cause: " + JSON.stringify(err)); } - this.platformPluginDelegate = platformPluginDelegate; - - this.platformChannel.setPlatformMessageHandler({ - playSystemSound:(soundType: SoundType): void => { - - }, - - vibrateHapticFeedback: (feedbackType: HapticFeedbackType): void => { - switch (feedbackType) { - case HapticFeedbackType.STANDARD: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'touch'}); - break; - case HapticFeedbackType.LIGHT_IMPACT: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'notification'}).then(); - break; - case HapticFeedbackType.MEDIUM_IMPACT: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'ring'}); - break; - case HapticFeedbackType.HEAVY_IMPACT: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'alarm'}); - break; - case HapticFeedbackType.SELECTION_CLICK: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'physicalFeedback'}); - break; + this.callback.platformPluginDelegate = platformPluginDelegate ?? null; + this.callback.platformChannel?.setPlatformMessageHandler(this.callback); + } + + + updateSystemUiOverlays(): void { + this.callback.windowClass?.setWindowSystemBarEnable(this.callback.showBarOrNavigation); + if (this.callback.currentTheme != null) { + this.callback.setSystemChromeSystemUIOverlayStyle(this.callback.currentTheme); + } + } + + setUIAbilityContext(context: common.UIAbilityContext): void { + this.callback.uiAbilityContext = context; + } + + setSystemChromeChangeListener(): void { + if (this.callback.callbackId == null && this.callback.applicationContext != null) { + let that = this; + this.callback.callbackId = this.callback.applicationContext?.on('environment', { + onConfigurationUpdated(config) { + Log.d(PlatformPlugin.TAG, "onConfigurationUpdated: " + that.callback.showBarOrNavigation); + that.callback.platformChannel?.systemChromeChanged(that.callback.showBarOrNavigation.includes('status')); + }, + onMemoryLevel(level) { } - }, + }) + } + } +} - setPreferredOrientations:(ohosOrientation: number): void => { - Log.d(PlatformPlugin.TAG,"ohosOrientation: " + ohosOrientation); - this.windowClass.setPreferredOrientation(ohosOrientation); - }, +export interface PlatformPluginDelegate { + popSystemNavigator(): boolean; +} - setApplicationSwitcherDescription:(description: AppSwitcherDescription): void => { - // representation described in the given {@code description}. - }, +class PlatformPluginCallback implements PlatformMessageHandler { + private static TAG = "PlatformPluginCallback"; + platform: PlatformPlugin | null = null; + windowClass: window.Window | null = null; + platformChannel: PlatformChannel | null = null; + platformPluginDelegate: PlatformPluginDelegate | null = null; + context: common.Context | null = null; + showBarOrNavigation: ('status' | 'navigation')[] = ['status', 'navigation']; + uiAbilityContext: common.UIAbilityContext | null = null; + callbackId: number | null = null; + applicationContext: common.ApplicationContext | null = null; + currentTheme: SystemChromeStyle | null = null; + + playSystemSound(soundType: SoundType) { + } - showSystemOverlays:(overlays: SystemUiOverlay[]): void => { - this.setSystemChromeEnabledSystemUIOverlays(overlays); - }, + vibrateHapticFeedback(feedbackType: HapticFeedbackType) { + switch (feedbackType) { + case HapticFeedbackType.STANDARD: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'touch' }); + break; + case HapticFeedbackType.LIGHT_IMPACT: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'notification' }).then(); + break; + case HapticFeedbackType.MEDIUM_IMPACT: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'ring' }); + break; + case HapticFeedbackType.HEAVY_IMPACT: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'alarm' }); + break; + case HapticFeedbackType.SELECTION_CLICK: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'physicalFeedback' }); + break; + } + } - showSystemUiMode:(mode: SystemUiMode): void => { - this.setSystemChromeEnabledSystemUIMode(mode); - }, + setPreferredOrientations(ohosOrientation: number) { + Log.d(PlatformPluginCallback.TAG, "ohosOrientation: " + ohosOrientation); + this.windowClass?.setPreferredOrientation(ohosOrientation); + } - setSystemUiChangeListener:(): void => { - this.setSystemChromeChangeListener(); - }, + setApplicationSwitcherDescription(description: AppSwitcherDescription) { + // representation described in the given {@code description}. + } - restoreSystemUiOverlays:(): void => { - this.updateSystemUiOverlays(); - }, + showSystemOverlays(overlays: SystemUiOverlay[]) { + this.setSystemChromeEnabledSystemUIOverlays(overlays); + } - setSystemUiOverlayStyle:(systemUiOverlayStyle: SystemChromeStyle): void => { - Log.d(PlatformPlugin.TAG, "systemUiOverlayStyle:" + JSON.stringify(systemUiOverlayStyle)); - this.setSystemChromeSystemUIOverlayStyle(systemUiOverlayStyle); - }, + showSystemUiMode(mode: SystemUiMode) { + this.setSystemChromeEnabledSystemUIMode(mode); + } - popSystemNavigator:(): void => { - this.popSystemNavigator(); - }, + setSystemUiChangeListener() { + this.platform?.setSystemChromeChangeListener(); + } - getClipboardData:(format: ClipboardContentFormat): string => { - return this.getClipboardData(format); - }, + restoreSystemUiOverlays() { + this.platform?.updateSystemUiOverlays(); + } - setClipboardData:(text: string): void => { - this.setClipboardData(text); - }, + setSystemUiOverlayStyle(systemUiOverlayStyle: SystemChromeStyle) { + Log.d(PlatformPluginCallback.TAG, "systemUiOverlayStyle:" + JSON.stringify(systemUiOverlayStyle)); + this.setSystemChromeSystemUIOverlayStyle(systemUiOverlayStyle); + } - clipboardHasStrings:(): boolean => { - return; - } - }); + popSystemNavigator() { + if (this.platformPluginDelegate != null && this.platformPluginDelegate?.popSystemNavigator()) { + return; + } + if (this.uiAbilityContext != null) { + this.uiAbilityContext.terminateSelf(); + } } - private getClipboardData(format: ClipboardContentFormat): string { - return; + getClipboardData(format: ClipboardContentFormat): string { + // todo + return ""; } - private setClipboardData(text: string): void { - let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN,text); + setClipboardData(text: string) { + let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text); let clipboard = pasteboard.getSystemPasteboard(); clipboard.setData(pasteData); } - private setSystemChromeEnabledSystemUIMode(mode: SystemUiMode): void { - Log.d(PlatformPlugin.TAG,"mode: " + mode); + clipboardHasStrings(): boolean { + return false; + } + + setSystemChromeEnabledSystemUIMode(mode: SystemUiMode): void { + Log.d(PlatformPluginCallback.TAG, "mode: " + mode); let uiConfig: ('status' | 'navigation')[] = []; - if(mode == SystemUiMode.LEAN_BACK) { + if (mode == SystemUiMode.LEAN_BACK) { //全屏显示,通过点击显示器上的任何位置都可以显示状态和导航栏 - this.windowClass.setWindowLayoutFullScreen(false); + this.windowClass?.setWindowLayoutFullScreen(false); } else if (mode == SystemUiMode.IMMERSIVE) { //全屏显示,通过在显示器边缘的滑动手势可以显示状态和导航栏,应用程序不会接收到此手势 - this.windowClass.setWindowLayoutFullScreen(true); + this.windowClass?.setWindowLayoutFullScreen(true); } else if (mode == SystemUiMode.IMMERSIVE_STICKY) { //全屏显示,通过在显示器边缘的滑动手势可以显示状态和导航栏,此手势由应用程序接收 - this.windowClass.setWindowLayoutFullScreen(true); + this.windowClass?.setWindowLayoutFullScreen(true); - }else if (mode == SystemUiMode.EDGE_TO_EDGE) { + } else if (mode == SystemUiMode.EDGE_TO_EDGE) { //全屏显示,在应用程序上呈现状态和导航元素 - this.windowClass.setWindowLayoutFullScreen(false); - uiConfig = ['status','navigation']; + this.windowClass?.setWindowLayoutFullScreen(false); + uiConfig = ['status', 'navigation']; } else { return; } this.showBarOrNavigation = uiConfig; - this.updateSystemUiOverlays(); + this.platform?.updateSystemUiOverlays(); } - private setSystemChromeEnabledSystemUIOverlays(overlays: SystemUiOverlay[]): void { - let uiConfig:('status' | 'navigation')[] = []; - if(overlays.length == 0) { - - } - for(let index = 0; index < overlays.length; ++index) { - let overlayToShow = overlays[index]; - switch (overlayToShow) { - case SystemUiOverlay.TOP_OVERLAYS: - uiConfig.push('status');//hide navigation - break; - case SystemUiOverlay.BOTTOM_OVERLAYS: - uiConfig.push('navigation');//hide bar - break; - } - } - this.showBarOrNavigation = uiConfig; - this.updateSystemUiOverlays(); - - } - - private setSystemChromeSystemUIOverlayStyle(systemChromeStyle: SystemChromeStyle): void { + setSystemChromeSystemUIOverlayStyle(systemChromeStyle: SystemChromeStyle): void { let isStatusBarLightIconValue: boolean = false; - let statusBarColorValue:string = null; - let statusBarContentColorValue: string = null; - let navigationBarColorValue: string = null; + let statusBarColorValue: string | undefined = undefined; + let statusBarContentColorValue: string | undefined = undefined; + let navigationBarColorValue: string | undefined = undefined; let isNavigationBarLightIconValue: boolean = false; - let navigationBarContentColorValue: string = null; - if(systemChromeStyle.statusBarIconBrightness != null) { + let navigationBarContentColorValue: string | undefined = undefined; + if (systemChromeStyle.statusBarIconBrightness != null) { switch (systemChromeStyle.statusBarIconBrightness) { case Brightness.DARK: isStatusBarLightIconValue = false; @@ -216,15 +228,15 @@ export default class PlatformPlugin { } } - if(systemChromeStyle.statusBarColor != null) { + if (systemChromeStyle.statusBarColor != null) { statusBarColorValue = "#" + systemChromeStyle.statusBarColor.toString(16); } - if(systemChromeStyle.systemStatusBarContrastEnforced != null) { + if (systemChromeStyle.systemStatusBarContrastEnforced != null) { } - if(systemChromeStyle.systemNavigationBarIconBrightness != null) { + if (systemChromeStyle.systemNavigationBarIconBrightness != null) { switch (systemChromeStyle.systemNavigationBarIconBrightness) { case Brightness.DARK: isNavigationBarLightIconValue = true; @@ -234,62 +246,56 @@ export default class PlatformPlugin { } } - if(systemChromeStyle.systemNavigationBarColor != null) { + if (systemChromeStyle.systemNavigationBarColor != null) { navigationBarColorValue = "#" + systemChromeStyle.systemNavigationBarColor.toString(16); } - if(systemChromeStyle.systemNavigationBarContrastEnforced != null) { + if (systemChromeStyle.systemNavigationBarContrastEnforced != null) { } this.currentTheme = systemChromeStyle; - let systemBarProperties = { - statusBarColor: statusBarColorValue, - isStatusBarLightIcon: isStatusBarLightIconValue, - statusBarContentColor: statusBarContentColorValue, - navigationBarColor: navigationBarColorValue, - isNavigationBarLightIcon: isNavigationBarLightIconValue, - navigationBarContentColor: navigationBarContentColorValue, - } - Log.d(PlatformPlugin.TAG, "systemBarProperties: "+JSON.stringify(systemBarProperties)); - this.windowClass.setWindowSystemBarProperties(systemBarProperties); + let systemBarProperties = new SystemBarProperties(); + systemBarProperties.statusBarColor = statusBarColorValue; + systemBarProperties.isStatusBarLightIcon = isStatusBarLightIconValue; + systemBarProperties.statusBarContentColor = statusBarContentColorValue; + systemBarProperties.navigationBarColor = navigationBarColorValue; + systemBarProperties.isNavigationBarLightIcon = isNavigationBarLightIconValue; + systemBarProperties.navigationBarContentColor = navigationBarContentColorValue; + Log.d(PlatformPluginCallback.TAG, "systemBarProperties: " + JSON.stringify(systemBarProperties)); + this.windowClass?.setWindowSystemBarProperties(systemBarProperties); } - private popSystemNavigator(): void { - if(this.platformPluginDelegate != null && this.platformPluginDelegate.popSystemNavigator()) { - return; + setSystemChromeEnabledSystemUIOverlays(overlays: SystemUiOverlay[]): void { + let uiConfig: ('status' | 'navigation')[] = []; + if (overlays.length == 0) { + } - if(this.uiAbilityContext != null) { - this.uiAbilityContext.terminateSelf(); + for (let index = 0; index < overlays.length; ++index) { + let overlayToShow = overlays[index]; + switch (overlayToShow) { + case SystemUiOverlay.TOP_OVERLAYS: + uiConfig.push('status'); //hide navigation + break; + case SystemUiOverlay.BOTTOM_OVERLAYS: + uiConfig.push('navigation'); //hide bar + break; + } } + this.showBarOrNavigation = uiConfig; + this.platform?.updateSystemUiOverlays(); } +} - updateSystemUiOverlays(): void { - this.windowClass.setWindowSystemBarEnable(this.showBarOrNavigation); - if(this.currentTheme != null) { - this.setSystemChromeSystemUIOverlayStyle(this.currentTheme); - } - } +class SystemBarProperties { + statusBarColor?: string; - setUIAbilityContext(context: common.UIAbilityContext): void { - this.uiAbilityContext = context; - } + isStatusBarLightIcon?: boolean; - setSystemChromeChangeListener(): void { - if(this.callbackId == null && this.applicationContext != null) { - let that = this; - this.callbackId = this.applicationContext.on('environment',{ - onConfigurationUpdated(config) { - Log.d(PlatformPlugin.TAG, "onConfigurationUpdated: " + that.showBarOrNavigation); - that.platformChannel.systemChromeChanged(that.showBarOrNavigation.includes('status')); - }, - onMemoryLevel(level) { - } - }) - } - } + statusBarContentColor?: string; -} + navigationBarColor?: string; -export interface PlatformPluginDelegate { - popSystemNavigator(): boolean; + isNavigationBarLightIcon?: boolean; + + navigationBarContentColor?: string; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BasicMessageChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BasicMessageChannel.ets index d6ef6c6c26..796f8edb89 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BasicMessageChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BasicMessageChannel.ets @@ -20,6 +20,8 @@ import { BinaryReply } from './BinaryMessenger'; import { TaskQueue } from './BinaryMessenger'; import MessageCodec from './MessageCodec'; import { BinaryMessenger } from './BinaryMessenger'; +import StringUtils from '../../util/StringUtils'; + /** * A named channel for communicating with the Flutter application using basic, asynchronous message * passing. @@ -40,7 +42,7 @@ export default class BasicMessageChannel { private messenger: BinaryMessenger; private name: string; private codec: MessageCodec; - private taskQueue: TaskQueue; + private taskQueue?: TaskQueue; constructor(messenger: BinaryMessenger, name: string, codec: MessageCodec, taskQueue?: TaskQueue) { this.messenger = messenger @@ -77,10 +79,9 @@ export default class BasicMessageChannel { // mock verify calls. // See https://github.com/flutter/flutter/issues/92582. if (this.taskQueue != null) { - this.messenger.setMessageHandler( - this.name, handler == null ? null : new IncomingMessageHandler(handler, this.codec), this.taskQueue); + this.messenger.setMessageHandler(this.name, new IncomingMessageHandler(handler, this.codec), this.taskQueue); } else { - this.messenger.setMessageHandler(this.name, handler == null ? null : new IncomingMessageHandler(handler, this.codec)); + this.messenger.setMessageHandler(this.name, new IncomingMessageHandler(handler, this.codec)); } } @@ -101,7 +102,7 @@ export interface Reply { * * @param reply the reply, possibly null. */ - reply(reply: T): void; + reply: (reply: T) => void; } export interface MessageHandler { @@ -164,7 +165,7 @@ class IncomingMessageHandler implements BinaryMessageHandler { }); } catch (e) { Log.e(BasicMessageChannel.TAG, "Failed to handle message", e); - callback.reply(null); + callback.reply(StringUtils.stringToArrayBuffer("")); } } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets index aa44a4958e..e0b55276be 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets @@ -86,10 +86,8 @@ export interface BinaryMessageHandler { * @see MethodChannel , which supports communication using asynchronous method invocation. * @see EventChannel , which supports communication using event streams. */ -export abstract class BinaryMessenger { - makeBackgroundTaskQueue(options?: TaskQueueOptions): TaskQueue { - throw new Error("makeBackgroundTaskQueue not implemented.") - } +export interface BinaryMessenger { + makeBackgroundTaskQueue(options?: TaskQueueOptions): TaskQueue; /** * Sends a binary message to the Flutter application. @@ -98,7 +96,7 @@ export abstract class BinaryMessenger { * @param message the message payload, a direct-allocated {@link ByteBuffer} with the message * bytes between position zero and current position, or null. */ - abstract send(channel: String, message: ArrayBuffer): void; + send(channel: String, message: ArrayBuffer): void; /** * Sends a binary message to the Flutter application, optionally expecting a reply. @@ -111,7 +109,7 @@ export abstract class BinaryMessenger { * @param callback a {@link BinaryReply} callback invoked when the Flutter application responds to * the message, possibly null. */ - abstract send(channel: String, message: ArrayBuffer, callback?: BinaryReply): void; + send(channel: String, message: ArrayBuffer, callback?: BinaryReply | null): void; /** * Registers a handler to be invoked when the Flutter application sends a message to its host @@ -129,11 +127,12 @@ export abstract class BinaryMessenger { * the handler. Specifying null means execute on the platform thread. */ //setMessageHandler(channel: String, handler: BinaryMessageHandler) - setMessageHandler(channel: String, handler: BinaryMessageHandler, taskQueue?: TaskQueue): void { - if (taskQueue != null) { - throw new Error("setMessageHandler called with nonnull taskQueue is not supported.") - } - } + setMessageHandler(channel: String, handler: BinaryMessageHandler, taskQueue?: TaskQueue): void; + // { + // if (taskQueue != null) { + // throw new Error("setMessageHandler called with nonnull taskQueue is not supported.") + // } + // } /** * Enables the ability to queue messages received from Dart. @@ -142,16 +141,18 @@ export abstract class BinaryMessenger { * be initialized concurrently, and prior to the registration of the channel handlers. This * implies that Dart may start sending messages while plugins are being registered. */ - enableBufferingIncomingMessages(): void { - throw new Error("enableBufferingIncomingMessages not implemented."); - } + enableBufferingIncomingMessages(): void; + // { + // throw new Error("enableBufferingIncomingMessages not implemented."); + // } /** * Disables the ability to queue messages received from Dart. * *

This can be used after all pending channel handlers have been registered. */ - disableBufferingIncomingMessages(): void { - throw new Error("disableBufferingIncomingMessages not implemented."); - } + disableBufferingIncomingMessages(): void; + // { + // throw new Error("disableBufferingIncomingMessages not implemented."); + // } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/EventChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/EventChannel.ets index fcf725cf92..166659a32e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/EventChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/EventChannel.ets @@ -93,7 +93,7 @@ export interface StreamHandler { * @param arguments stream configuration arguments, possibly null. * @param events an {@link EventSink} for emitting events to the Flutter receiver. */ - onListen(args: any, events: EventSink): void; + onListen(args: ESObject, events: EventSink): void; /** * Handles a request to tear down the most recently created event stream. @@ -107,7 +107,7 @@ export interface StreamHandler { * * @param arguments stream configuration arguments, possibly null. */ - onCancel(args: any): void; + onCancel(args: ESObject): void; } /** @@ -121,7 +121,7 @@ export interface EventSink { * * @param event the event, possibly null. */ - success(event: any): void; + success(event: ESObject): void; /** * Consumes an error event. @@ -130,7 +130,7 @@ export interface EventSink { * @param errorMessage a human-readable error message String, possibly null. * @param errorDetails error details, possibly null */ - error(errorCode: string, errorMessage: string, errorDetails: any): void; + error(errorCode: string, errorMessage: string, errorDetails: ESObject): void; /** * Consumes end of stream. Ensuing calls to {@link #success(Object)} or {@link #error(String, @@ -164,7 +164,7 @@ class IncomingStreamRequestHandler implements BinaryMessageHandler { } } - onListen(args: any, callback: BinaryReply): void { + onListen(args: ESObject, callback: BinaryReply): void { const eventSink = new EventSinkImplementation(this.activeSink, this.name, this.codec, this.messenger); const oldSink = this.activeSink.getAndSet(eventSink); if (oldSink != null) { @@ -186,7 +186,7 @@ class IncomingStreamRequestHandler implements BinaryMessageHandler { } } - onCancel(args: any, callback: BinaryReply): void { + onCancel(args: ESObject, callback: BinaryReply): void { const oldSink = this.activeSink.getAndSet(null); if (oldSink != null) { try { @@ -216,14 +216,14 @@ class EventSinkImplementation implements EventSink { this.messenger = messenger; } - success(event: any): void { + success(event: ESObject): void { if (this.hasEnded || this.activeSink.get() != this) { return; } this.messenger.send(this.name, this.codec.encodeSuccessEnvelope(event)); } - error(errorCode: string, errorMessage: string, errorDetails: any) { + error(errorCode: string, errorMessage: string, errorDetails: ESObject) { if (this.hasEnded || this.activeSink.get() != this) { return; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/FlutterException.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/FlutterException.ets index e8e8d40354..204dd8e3ea 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/FlutterException.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/FlutterException.ets @@ -16,11 +16,11 @@ export default class FlutterException implements Error { stack?: string; message: string; - name: string; + name: string = ""; code: string; - details: any + details: ESObject - constructor(code: string, message: string, details: any) { + constructor(code: string, message: string, details: ESObject) { this.message = message; this.code = code; this.details =details; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets index bf6576f496..6224740ed6 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMessageCodec.ets @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import StringUtils from '../../util/StringUtils'; import MessageCodec from './MessageCodec'; import MethodCodec from './MethodCodec'; @@ -27,17 +28,17 @@ import StringCodec from './StringCodec'; *

On the Dart side, JSON messages are handled by the JSON facilities of the dart:convert package. */ -export default class JSONMessageCodec implements MessageCodec { +export default class JSONMessageCodec implements MessageCodec { static INSTANCE = new JSONMessageCodec(); - encodeMessage(message: any): ArrayBuffer { + encodeMessage(message: ESObject): ArrayBuffer { if (message == null) { - return null; + return StringUtils.stringToArrayBuffer(""); } return StringCodec.INSTANCE.encodeMessage(JSON.stringify(message)); } - decodeMessage(message: ArrayBuffer): any { + decodeMessage(message: ArrayBuffer): ESObject { if (message == null) { return null; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMethodCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMethodCodec.ets index 42a4f1ac6b..7b5bf1d089 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMethodCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/JSONMethodCodec.ets @@ -35,9 +35,10 @@ export default class JSONMethodCodec implements MethodCodec { encodeMethodCall(methodCall: MethodCall): ArrayBuffer { try { - const map = { + const map: Record = { "method": methodCall.method, "args": methodCall.args } + return JSONMessageCodec.INSTANCE.encodeMessage(map); } catch (e) { throw new Error("Invalid JSON"); @@ -46,10 +47,10 @@ export default class JSONMethodCodec implements MethodCodec { decodeMethodCall(message: ArrayBuffer): MethodCall { try { - const json = JSONMessageCodec.INSTANCE.decodeMessage(message); + const json: ESObject = JSONMessageCodec.INSTANCE.decodeMessage(message); if (ToolUtils.isObj(json)) { - const method = json["method"]; - const args = json["args"]; + const method: string = json["method"]; + const args: ESObject = json["args"]; if (typeof method == 'string') { return new MethodCall(method, args); } @@ -60,29 +61,29 @@ export default class JSONMethodCodec implements MethodCodec { } } - encodeSuccessEnvelope(result: any): ArrayBuffer { + encodeSuccessEnvelope(result: ESObject): ArrayBuffer { return JSONMessageCodec.INSTANCE.encodeMessage([result]); } - encodeErrorEnvelope(errorCode: any, errorMessage: string, errorDetails: any) { + encodeErrorEnvelope(errorCode: ESObject, errorMessage: string, errorDetails: ESObject) { return JSONMessageCodec.INSTANCE.encodeMessage([errorCode, errorMessage, errorDetails]); } - encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: any, errorStacktrace: string): ArrayBuffer { + encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: ESObject, errorStacktrace: string): ArrayBuffer { return JSONMessageCodec.INSTANCE.encodeMessage([errorCode, errorMessage, errorDetails, errorStacktrace]) } - decodeEnvelope(envelope: ArrayBuffer): any { + decodeEnvelope(envelope: ArrayBuffer): ESObject { try { - const json = JSONMessageCodec.INSTANCE.decodeMessage(envelope); + const json: ESObject = JSONMessageCodec.INSTANCE.decodeMessage(envelope); if (json instanceof Array) { if (json.length == 1) { return json[0]; } if (json.length == 3) { - const code = json[0]; - const message = json[1]; - const details = json[2]; + const code: string = json[0]; + const message: string = json[1]; + const details: ESObject = json[2]; if (typeof code == 'string' && (message == null || typeof message == 'string')) { throw new FlutterException(code, message, details); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCall.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCall.ets index 60de27310c..0042c25c3b 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCall.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCall.ets @@ -26,18 +26,18 @@ export default class MethodCall { * Consider using {@link #argument(String)} when that run-time type is {@link Map} or {@link * JSONObject}. */ - args: any; + args: ESObject; - constructor(method: string, args: any) { + constructor(method: string, args: ESObject) { this.method = method this.args = args } - argument(key: string): any { + argument(key: string): ESObject { if (this.args == null) { return null; } else if (this.args instanceof Map) { - return (this.args as Map).get(key); + return (this.args as Map).get(key); } else if (ToolUtils.isObj(this.args)) { return this.args[key] } else { @@ -49,9 +49,9 @@ export default class MethodCall { if (arguments == null) { return false; } else if (arguments instanceof Map) { - return (this.args as Map).has(key); + return (this.args as Map).has(key); } else if (ToolUtils.isObj(this.args)) { - return Object.prototype.hasOwnProperty.call(this.args, key); + return this.args.hasOwnProperty(key); } else { throw new Error("ClassCastException"); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodChannel.ets index 5a7de31d1d..31da9ff489 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodChannel.ets @@ -15,6 +15,7 @@ import Log from '../../util/Log'; import MessageChannelUtils from '../../util/MessageChannelUtils'; +import StringUtils from '../../util/StringUtils'; import { BinaryMessageHandler, BinaryMessenger, BinaryReply, TaskQueue } from './BinaryMessenger'; import MethodCall from './MethodCall'; import MethodCodec from './MethodCodec'; @@ -38,7 +39,7 @@ export default class MethodChannel { private messenger: BinaryMessenger; private name: string; private codec: MethodCodec; - private taskQueue: TaskQueue; + private taskQueue?: TaskQueue; constructor(messenger: BinaryMessenger, name: string, codec: MethodCodec = StandardMethodCodec.INSTANCE, taskQueue?: TaskQueue) { this.messenger = messenger @@ -56,7 +57,7 @@ export default class MethodChannel { * @param arguments the arguments for the invocation, possibly null. * @param callback a {@link Result} callback for the invocation result, or null. */ - invokeMethod(method: string, args: any, callback?: MethodResult): void { + invokeMethod(method: string, args: ESObject, callback?: MethodResult): void { this.messenger.send(this.name, this.codec.encodeMethodCall(new MethodCall(method, args)), callback == null ? null : new IncomingResultHandler(callback, this.codec)); } @@ -80,10 +81,10 @@ export default class MethodChannel { // See https://github.com/flutter/flutter/issues/92582. if (this.taskQueue != null) { this.messenger.setMessageHandler( - this.name, handler == null ? null : new IncomingMethodCallHandler(handler, this.codec), this.taskQueue); + this.name, new IncomingMethodCallHandler(handler, this.codec), this.taskQueue); } else { this.messenger.setMessageHandler( - this.name, handler == null ? null : new IncomingMethodCallHandler(handler, this.codec)); + this.name, new IncomingMethodCallHandler(handler, this.codec)); } } @@ -138,7 +139,7 @@ export interface MethodResult { * codec. For instance, if you are using {@link StandardMessageCodec} (default), please see * its documentation on what types are supported. */ - success(result: any): void; + success: (result: ESObject) => void; /** * Handles an error result. @@ -149,10 +150,10 @@ export interface MethodResult { * supported by the codec. For instance, if you are using {@link StandardMessageCodec} * (default), please see its documentation on what types are supported. */ - error(errorCode: string, errorMessage: string, errorDetails: any): void; + error: (errorCode: string, errorMessage: string, errorDetails: ESObject) => void; /** Handles a call to an unimplemented method. */ - notImplemented(): void; + notImplemented: () => void; } class IncomingResultHandler implements BinaryReply { @@ -195,17 +196,17 @@ class IncomingMethodCallHandler implements BinaryMessageHandler { try { this.handler.onMethodCall( call, { - success: (result: any): void => { + success: (result: ESObject): void => { reply.reply(this.codec.encodeSuccessEnvelope(result)); }, - error: (errorCode: string, errorMessage: string, errorDetails: any): void => { + error: (errorCode: string, errorMessage: string, errorDetails: ESObject): void => { reply.reply(this.codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails)); }, notImplemented: (): void => { Log.w(MethodChannel.TAG,"method not implemented"); - reply.reply(null); + reply.reply(StringUtils.stringToArrayBuffer("")); } }); } catch (e) { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCodec.ets index 7370d83460..86ed92aca6 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/MethodCodec.ets @@ -49,7 +49,7 @@ export default interface MethodCodec { * @return a {@link ByteBuffer} containing the encoding between position 0 and the current * position. */ - encodeSuccessEnvelope(result: any): ArrayBuffer; + encodeSuccessEnvelope(result: ESObject): ArrayBuffer; /** * Encodes an error result into a binary envelope message. @@ -61,7 +61,7 @@ export default interface MethodCodec { * @return a {@link ByteBuffer} containing the encoding between position 0 and the current * position. */ - encodeErrorEnvelope(errorCode: string, errorMessage: string, errorDetails: any): ArrayBuffer; + encodeErrorEnvelope(errorCode: string, errorMessage: string, errorDetails: ESObject): ArrayBuffer; /** * Encodes an error result into a binary envelope message with the native stacktrace. @@ -74,7 +74,7 @@ export default interface MethodCodec { * @return a {@link ByteBuffer} containing the encoding between position 0 and the current * position. */ - encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: any, errorStacktrace: string): ArrayBuffer + encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: ESObject, errorStacktrace: string): ArrayBuffer /** * Decodes a result envelope from binary. @@ -83,5 +83,5 @@ export default interface MethodCodec { * @return the enveloped result Object. * @throws FlutterException if the envelope was an error envelope. */ - decodeEnvelope(envelope: ArrayBuffer): any + decodeEnvelope(envelope: ArrayBuffer): ESObject } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets index 8dfb27153b..8650cfe643 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets @@ -60,20 +60,20 @@ import MessageCodec from './MessageCodec'; * *

To extend the codec, overwrite the writeValue and readValueOfType methods. */ -export default class StandardMessageCodec implements MessageCodec { +export default class StandardMessageCodec implements MessageCodec { private static TAG = "StandardMessageCodec#"; static INSTANCE = new StandardMessageCodec(); - encodeMessage(message: any): ArrayBuffer { + encodeMessage(message: ESObject): ArrayBuffer { if (message == null) { - return null; + return StringUtils.stringToArrayBuffer(""); } const stream = ByteBuffer.from(new ArrayBuffer(1024)) this.writeValue(stream, message); return stream.buffer } - decodeMessage(message: ArrayBuffer): any { + decodeMessage(message: ArrayBuffer): ESObject { const buffer = ByteBuffer.from(message) return this.readValue(buffer) } @@ -95,7 +95,7 @@ export default class StandardMessageCodec implements MessageCodec { private static FLOAT32_ARRAY = 14; - writeValue(stream: ByteBuffer, value: any): any { + writeValue(stream: ByteBuffer, value: ESObject): ESObject { if (value == null || value == undefined) { stream.writeInt8(StandardMessageCodec.NULL) } else if (typeof value === "boolean") { @@ -139,22 +139,22 @@ export default class StandardMessageCodec implements MessageCodec { } else if (value instanceof Array) { stream.writeInt8(StandardMessageCodec.LIST) this.writeSize(stream, value.length); - value.forEach(item => this.writeValue(stream, item)) + value.forEach((item: ESObject): void => this.writeValue(stream, item)) } else if (value instanceof Map) { stream.writeInt8(StandardMessageCodec.MAP) this.writeSize(stream, value.size); - value.forEach((value, key) => { + value.forEach((value: ESObject, key: ESObject) => { this.writeValue(stream, key); this.writeValue(stream, value); }) } else if (typeof value == 'object') { - this.writeValue(stream, new Map(Object.entries(value))) + this.writeValue(stream, new Map(value.entries())) } return stream } writeAlignment(stream: ByteBuffer, alignment: number) { - var mod = stream.byteOffset % alignment; + let mod: number = stream.byteOffset % alignment; if (mod != 0) { for (let i = 0; i < alignment - mod; i++) { stream.writeInt8(0); @@ -197,7 +197,7 @@ export default class StandardMessageCodec implements MessageCodec { } } - readValue(buffer: ByteBuffer): any { + readValue(buffer: ByteBuffer): ESObject { let type = buffer.readInt8() return this.readValueOfType(type, buffer); } @@ -211,8 +211,8 @@ export default class StandardMessageCodec implements MessageCodec { return bytes; } - readValueOfType(type: number, buffer: ByteBuffer): any { - var result + readValueOfType(type: number, buffer: ByteBuffer): ESObject { + let result: ESObject; switch (type) { case StandardMessageCodec.NULL: result = null; @@ -256,7 +256,7 @@ export default class StandardMessageCodec implements MessageCodec { } case StandardMessageCodec.INT64_ARRAY: { //这里是都城array 还是 bigint待定 let length = this.readSize(buffer); - let array = new Array(length) + let array: Array = new Array(length) this.readAlignment(buffer, 8); for (let i = 0; i < length; i++) { array[i] = buffer.readInt64(true) @@ -276,7 +276,7 @@ export default class StandardMessageCodec implements MessageCodec { } case StandardMessageCodec.LIST: { let length = this.readSize(buffer); - let array = new Array(length) + let array: Array = new Array(length) for (let i = 0; i < length; i++) { array[i] = this.readValue(buffer) } @@ -285,7 +285,7 @@ export default class StandardMessageCodec implements MessageCodec { } case StandardMessageCodec.MAP: { let size = this.readSize(buffer); - let map = new Map() + let map: Map = new Map() for (let i = 0; i < size; i++) { map.set(this.readValue(buffer), this.readValue(buffer)); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets index 4661aff7bb..d4417c54eb 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets @@ -49,22 +49,22 @@ export default class StandardMethodCodec implements MethodCodec { decodeMethodCall(methodCall: ArrayBuffer): MethodCall { const buffer = ByteBuffer.from(methodCall); - const method = this.messageCodec.readValue(buffer); - const args = this.messageCodec.readValue(buffer); + const method: ESObject = this.messageCodec.readValue(buffer); + const args: ESObject = this.messageCodec.readValue(buffer); if (typeof method == 'string' && !buffer.hasRemaining()) { return new MethodCall(method, args); } throw new Error("Method call corrupted"); } - encodeSuccessEnvelope(result: any): ArrayBuffer { + encodeSuccessEnvelope(result: ESObject): ArrayBuffer { const stream = ByteBuffer.from(new ArrayBuffer(1024)); stream.writeInt8(0); this.messageCodec.writeValue(stream, result); return stream.buffer; } - encodeErrorEnvelope(errorCode: string, errorMessage: string, errorDetails: any): ArrayBuffer { + encodeErrorEnvelope(errorCode: string, errorMessage: string, errorDetails: ESObject): ArrayBuffer { const stream = ByteBuffer.from(new ArrayBuffer(1024)); stream.writeInt8(1); this.messageCodec.writeValue(stream, errorCode); @@ -77,7 +77,7 @@ export default class StandardMethodCodec implements MethodCodec { return stream.buffer; } - encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: any, errorStacktrace: string): ArrayBuffer { + encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: ESObject, errorStacktrace: string): ArrayBuffer { const stream = ByteBuffer.from(new ArrayBuffer(1024)); stream.writeInt8(1); this.messageCodec.writeValue(stream, errorCode); @@ -91,21 +91,21 @@ export default class StandardMethodCodec implements MethodCodec { return stream.buffer; } - decodeEnvelope(envelope: ArrayBuffer): any { + decodeEnvelope(envelope: ArrayBuffer): ESObject { const buffer = ByteBuffer.from(envelope); const flag = buffer.readInt8(); switch (flag) { case 0: { - const result = this.messageCodec.readValue(buffer); + const result: ESObject = this.messageCodec.readValue(buffer); if (!buffer.hasRemaining()) { return result; } // Falls through intentionally. } case 1: { - const code = this.messageCodec.readValue(buffer); - const message = this.messageCodec.readValue(buffer); - const details = this.messageCodec.readValue(buffer); + const code: ESObject = this.messageCodec.readValue(buffer); + const message: ESObject = this.messageCodec.readValue(buffer); + const details: ESObject = this.messageCodec.readValue(buffer); if (typeof code == 'string' && (message == null || typeof message == 'string') && !buffer.hasRemaining()) { throw new FlutterException(code, message, details); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StringCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StringCodec.ets index e43be76b55..b824ac1f90 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StringCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StringCodec.ets @@ -28,14 +28,14 @@ export default class StringCodec implements MessageCodec { encodeMessage(message: string): ArrayBuffer { if (message == null) { - return null; + return StringUtils.stringToArrayBuffer(""); } return StringUtils.stringToArrayBuffer(message); } decodeMessage(message: ArrayBuffer): string { if (message == null) { - return null; + return ""; } return StringUtils.arrayBufferToString(message); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/ListenableEditingState.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/ListenableEditingState.ets index 72735c0a29..1ea2049bd2 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/ListenableEditingState.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/ListenableEditingState.ets @@ -23,27 +23,28 @@ const TAG = "ListenableEditingState"; export class ListenableEditingState { //Cache used to storage software keyboard input action private mStringCache: string; - private mSelectionStartCache: number; - private mSelectionEndCache: number; - private mComposingStartCache: number; - private mComposingEndCache: number; + private mSelectionStartCache: number = 0; + private mSelectionEndCache: number = 0; + private mComposingStartCache: number = 0; + private mComposingEndCache: number = 0; //used to compare with Cache - private mTextInputState: TextEditState; + private mListeners: ArrayList = new ArrayList(); private mPendingListeners: ArrayList = new ArrayList(); private mBatchTextEditingDeltas: ArrayList = new ArrayList(); - private mChangeNotificationDepth: number; - private mBatchEditNestDepth: number; + private mChangeNotificationDepth: number = 0; + private mBatchEditNestDepth: number = 0; private mTextWhenBeginBatchEdit: string; - private mSelectionStartWhenBeginBatchEdit: number; - private mSelectionEndWhenBeginBatchEdit: number; - private mComposingStartWhenBeginBatchEdit: number; - private mComposingEndWhenBeginBatchEdit: number; + private mSelectionStartWhenBeginBatchEdit: number = 0; + private mSelectionEndWhenBeginBatchEdit: number = 0; + private mComposingStartWhenBeginBatchEdit: number = 0; + private mComposingEndWhenBeginBatchEdit: number = 0; constructor() { this.mStringCache = ""; + this.mTextWhenBeginBatchEdit = ""; this.mSelectionStartCache = 0; this.mSelectionEndCache = 0; this.mComposingStartCache = -1; @@ -110,9 +111,6 @@ export class ListenableEditingState { } handleInsertTextEvent(text: string): void { - if(this.mTextInputState == null) { - Log.e(TAG, "mTextInputState is null"); - } if(this.mStringCache.length == this.mSelectionStartCache) { //Insert text one by one this.mStringCache += text; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextEditingDelta.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextEditingDelta.ets index 8b8064fbee..1aa1b2d872 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextEditingDelta.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextEditingDelta.ets @@ -17,10 +17,10 @@ import Log from '../../util/Log'; export class TextEditingDelta { private static TAG = "TextEditingDelta"; - private oldText: string; - private deltaText: string; - private deltaStart: number; - private deltaEnd: number; + private oldText: string = ""; + private deltaText: string = ""; + private deltaStart: number = 0; + private deltaEnd: number = 0; private newSelectionStart: number; private newSelectionEnd: number; private newComposingStart: number; @@ -58,22 +58,4 @@ export class TextEditingDelta { this.deltaStart = newStart; this.deltaEnd = newExtent; } - - toJSON(): any { - let delta; - try { - delta.oldText = this.oldText; - delta.deltaText = this.deltaText; - delta.deltaStart = this.deltaStart; - delta.deltaEnd = this.deltaEnd; - delta.selectionBase = this.newSelectionStart; - delta.selectionExtent = this.newSelectionEnd; - delta.composingBase = this.newComposingStart; - delta.composingExtent = this.newComposingEnd; - } catch (err) { - Log.e(TextEditingDelta.TAG,"unable to create JSONObject: " + JSON.stringify(err)); - } - - - } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets index f837940fa1..16aa44aa78 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets @@ -14,76 +14,110 @@ */ import TextInputChannel, { Configuration, TextEditState, + TextInputMethodHandler, TextInputType } from '../../embedding/engine/systemchannels/TextInputChannel'; import inputMethod from '@ohos.inputMethod'; import Log from '../../util/Log'; import { EditingStateWatcher, ListenableEditingState } from './ListenableEditingState'; -import { TextEditingDelta } from './TextEditingDelta'; export default class TextInputPlugin implements EditingStateWatcher{ private static TAG = "TextInputPlugin"; private textInputChannel: TextInputChannel; - private textConfig: inputMethod.TextConfig; - private inputMethodController: inputMethod.InputMethodController; - private inputTarget: InputTarget; - private configuration: Configuration; - private mEditable: ListenableEditingState; - private mRestartInputPending: boolean; + private mTextInputHandler: TextInputMethodHandlerImpl; - private imcFlag: boolean = false; + constructor(textInputChannel: TextInputChannel) { + this.textInputChannel = textInputChannel; + this.mTextInputHandler = new TextInputMethodHandlerImpl(this); + this.textInputChannel.setTextInputMethodHandler(this.mTextInputHandler); + } + + public clearTextInputClient() { + this.textInputChannel.textInputMethodHandler?.clearClient(); + } + setTextInputEditingState(state: TextEditState) { + } - constructor(textInputChannel: TextInputChannel) { - this.textInputChannel = textInputChannel; - this.mEditable = new ListenableEditingState(); + didChangeEditingState(textChanged: boolean, selectionChanged: boolean, composingRegionChanged: boolean): void { + let editable = this.mTextInputHandler.mEditable; + let inputTarget = this.mTextInputHandler.inputTarget; + this.textInputChannel.updateEditingState(inputTarget.id, editable.getStringCache(), + editable.getSelectionStart(), editable.getSelectionEnd(), + editable.getComposingStart(), editable.getComposingEnd()) + } + + detach(): void { + this.mTextInputHandler.inputMethodController.detach((err) => { + if(err) { + Log.e(TextInputPlugin.TAG, "Failed to detach: " + JSON.stringify(err)); + } + }) + } + +} + +class TextInputMethodHandlerImpl implements TextInputMethodHandler { + private static TAG = "TextInputMethodHandlerImpl"; + private textConfig: inputMethod.TextConfig; + inputMethodController: inputMethod.InputMethodController; + inputTarget: InputTarget; + private configuration: Configuration | null = null; + mEditable: ListenableEditingState; + private mRestartInputPending: boolean = false; + private plugin: EditingStateWatcher; + + private imcFlag: boolean = false; + + constructor(plugin: TextInputPlugin) { this.textConfig = { inputAttribute: { textInputType: 0, enterKeyType: 1 }}; + this.plugin = plugin; + this.mEditable = new ListenableEditingState(); this.inputMethodController = inputMethod.getController(); - this.textInputChannel.setTextInputMethodHandler({ - show:(): void => { - this.showTextInput(); - }, + this.inputTarget = new InputTarget(Type.NO_TARGET, 0); + } - hide:(): void => { - this.hideTextInput(); - }, + show(): void { + this.showTextInput(); + } - requestAutofill:(): void =>{ + hide(): void { + this.hideTextInput(); + } - }, + requestAutofill(): void { - finishAutofillContext:(shouldSave: boolean): void =>{ + } - }, + finishAutofillContext(shouldSave: boolean): void { - setClient:(textInputClientId: number, configuration: Configuration): void => { - Log.d(TextInputPlugin.TAG,"textInputClientId: " + textInputClientId); - this.setTextInputClient(textInputClientId, configuration); - }, + } - setPlatformViewClient:(id: number, usesVirtualDisplay: boolean): void => { + setClient(textInputClientId: number, configuration: Configuration | null): void { + Log.d(TextInputMethodHandlerImpl.TAG,"textInputClientId: " + textInputClientId); + this.setTextInputClient(textInputClientId, configuration); + } - }, + setPlatformViewClient(id: number, usesVirtualDisplay: boolean): void { - setEditableSizeAndTransform:(width: number, height: number, transform: number[]): void => { + } - }, + setEditableSizeAndTransform(width: number, height: number, transform: number[]): void { - setEditingState:(editingState: TextEditState): void => { - Log.d(TextInputPlugin.TAG, "text:" + editingState.text +" selectionStart:" + editingState.selectionStart + " selectionEnd:" - + editingState.selectionEnd + " composingStart:" + editingState.composingStart + " composingEnd" + editingState.composingEnd); - this.mEditable.updateTextInputState(editingState); - }, - clearClient:(): void =>{ - this.clearTextInputClient(); - } + } + setEditingState(editingState: TextEditState): void { + Log.d(TextInputMethodHandlerImpl.TAG, "text:" + editingState.text +" selectionStart:" + editingState.selectionStart + " selectionEnd:" + + editingState.selectionEnd + " composingStart:" + editingState.composingStart + " composingEnd" + editingState.composingEnd); + this.mEditable.updateTextInputState(editingState); + } - }); + clearClient(): void { + this.clearTextInputClient(); } private async showTextInput(): Promise { @@ -92,17 +126,17 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.listenKeyBoardEvent(); } this.inputMethodController.showTextInput().then(()=> { - Log.d(TextInputPlugin.TAG, "Succeeded in showing softKeyboard"); - }).catch((err) => { - Log.e(TextInputPlugin.TAG, "Failed to show softKeyboard:" + JSON.stringify(err)); + Log.d(TextInputMethodHandlerImpl.TAG, "Succeeded in showing softKeyboard"); + }).catch((err: ESObject) => { + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to show softKeyboard:" + JSON.stringify(err)); }); } private async hideTextInput(): Promise { this.inputMethodController.hideTextInput().then(() => { - Log.d(TextInputPlugin.TAG, "Succeeded in hide softKeyboard"); - }).catch((err) => { - Log.e(TextInputPlugin.TAG, "Failed to hide softKeyboard:" + JSON.stringify(err)); + Log.d(TextInputMethodHandlerImpl.TAG, "Succeeded in hide softKeyboard"); + }).catch((err: ESObject) => { + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to hide softKeyboard:" + JSON.stringify(err)); }) } @@ -110,18 +144,39 @@ export default class TextInputPlugin implements EditingStateWatcher{ try { await this.inputMethodController.attach(showKeyboard, this.textConfig); } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to attach:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to attach:" + JSON.stringify(err)); } } + + setTextInputClient(client: number, configuration: Configuration | null): void { + this.configuration = configuration; + if(this.canShowTextInput()) { + this.inputTarget = new InputTarget(Type.FRAMEWORK_CLIENT, client); + } else { + this.inputTarget = new InputTarget(Type.NO_TARGET, client); + } + this.mEditable.removeEditingStateListener(this.plugin); + this.mEditable = new ListenableEditingState(); + + this.mRestartInputPending = true; + this.mEditable.addEditingStateListener(this.plugin); + } + + canShowTextInput(): boolean { + if(this.configuration == null || this.configuration.inputType == null) { + return true; + } + return this.configuration.inputType.type != TextInputType.NONE; + } listenKeyBoardEvent(): void { try { this.inputMethodController.on('insertText', (text) => { - Log.d(TextInputPlugin.TAG, "insertText: " + text); + Log.d(TextInputMethodHandlerImpl.TAG, "insertText: " + text); this.mEditable.handleInsertTextEvent(text); }); } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe insertText:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe insertText:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } @@ -131,7 +186,7 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.mEditable.handleDeleteEvent(false, length); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe deleteLeft:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe deleteLeft:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } @@ -141,7 +196,7 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.mEditable.handleDeleteEvent(true, length); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe deleteRight:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe deleteRight:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } @@ -151,21 +206,21 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.mEditable.handleFunctionKey(functionKey); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe sendFunctionKey:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe sendFunctionKey:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } try { - this.inputMethodController.on('selectByRange', (range) => { + this.inputMethodController.on('selectByRange', (range: inputMethod.Range) => { this.mEditable.handleSelectByRange(range); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe selectByRange:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe selectByRange:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } - Log.d(TextInputPlugin.TAG, "listenKeyBoardEvent success"); + Log.d(TextInputMethodHandlerImpl.TAG, "listenKeyBoardEvent success"); this.imcFlag = true; } @@ -177,54 +232,14 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.inputMethodController.off('selectByRange'); } - setTextInputClient(client: number, configuration: Configuration): void { - this.configuration = configuration; - if(this.canShowTextInput()) { - this.inputTarget = new InputTarget(Type.FRAMEWORK_CLIENT, client); - } else { - this.inputTarget = new InputTarget(Type.NO_TARGET, client); - } - this.mEditable.removeEditingStateListener(this); - this.mEditable = new ListenableEditingState(); - - this.mRestartInputPending = true; - this.mEditable.addEditingStateListener(this); - } - - canShowTextInput(): boolean { - if(this.configuration == null || this.configuration.inputType == null) { - return true; - } - return this.configuration.inputType.type != TextInputType.NONE; - } - - setTextInputEditingState(state: TextEditState) { - - } - - didChangeEditingState(textChanged: boolean, selectionChanged: boolean, composingRegionChanged: boolean): void { - this.textInputChannel.updateEditingState(this.inputTarget.id, this.mEditable.getStringCache(), - this.mEditable.getSelectionStart(), this.mEditable.getSelectionEnd(), - this.mEditable.getComposingStart(), this.mEditable.getComposingEnd()) - } - - detach(): void { - this.inputMethodController.detach((err) => { - if(err) { - Log.e(TextInputPlugin.TAG, "Failed to detach: " + JSON.stringify(err)); - } - }) - } - - clearTextInputClient(): void { + public clearTextInputClient(): void { if(this.inputTarget.type == Type.VIRTUAL_DISPLAY_PLATFORM_VIEW) { return; } - this.mEditable.removeEditingStateListener(this); + this.mEditable.removeEditingStateListener(this.plugin); this.configuration = null; this.inputTarget = new InputTarget(Type.NO_TARGET, 0); } - } enum Type { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets index 662e087641..78ed1c7297 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets @@ -44,12 +44,10 @@ export default class LocalizationPlugin { return new intl.Locale(languageCode+'-'+ countryCode +'-' + scriptCode); } - private localizationMessageHandler: LocalizationMessageHandler = { - getStringResource(key: string, localeString: string): string { - Log.i(TAG, "getResource enter"); - return "" - } - } + private localizationMessageHandler: LocalizationMessageHandler =new enterGetStringResource(()=>{ + Log.i(TAG, "getResource enter"); + return "" + }) constructor(context: common.Context, localizationChannel: LocalizationChannel) { this.context = context; this.localizationChannel = localizationChannel; @@ -59,5 +57,12 @@ export default class LocalizationPlugin { sendLocaleToFlutter(): void { let systemLanguages = i18n.System.getSystemLanguages(); this.localizationChannel.sendLocales(systemLanguages); - } + } } +class enterGetStringResource{ + getStringResource : (key: string, localeString: string)=>string + + constructor(getStringResource: (key: string, localeString: string)=>string) { + this.getStringResource = getStringResource + } +} \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/mouse/MouseCursorPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/mouse/MouseCursorPlugin.ets index 4aa609f9cf..0f8bf873c4 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/mouse/MouseCursorPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/mouse/MouseCursorPlugin.ets @@ -25,7 +25,7 @@ export default class MouseCursorPlugin implements MouseCursorMethodHandler{ private mouseCursorChannel: MouseCursorChannel; - private systemCursorConstants: HashMap; + private systemCursorConstants: HashMap | null = null; constructor(mouseCursorView: MouseCursorViewDelegate, mouseCursorChannel: MouseCursorChannel) { this.mView = mouseCursorView; @@ -41,7 +41,7 @@ export default class MouseCursorPlugin implements MouseCursorMethodHandler{ } let pointStyle: pointer.PointerStyle = this.resolveSystemCursor(kind); try { - pointer.setPointerStyle(windowId, pointStyle, (err) => { + pointer.setPointerStyle(windowId, pointStyle, (err: ESObject) => { Log.i(TAG, "set point style success kind : " + kind); }) } catch (e) { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/AccessibilityEventsDelegate.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/AccessibilityEventsDelegate.ets index faa3bc90e5..ea9450d4aa 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/AccessibilityEventsDelegate.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/AccessibilityEventsDelegate.ets @@ -16,7 +16,7 @@ import AccessibilityBridge from '../../view/AccessibilityBridge'; export class AccessibilityEventsDelegate { - private accessibilityBridge: AccessibilityBridge; + private accessibilityBridge: AccessibilityBridge | null = null; requestSendAccessibilityEvent(accessibilityBridge: AccessibilityBridge): boolean { if (accessibilityBridge == null) { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets index 2f156cdcd2..64e8c7f780 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets @@ -17,7 +17,7 @@ import { AccessibilityEventsDelegate } from './AccessibilityEventsDelegate'; export class PlatformOverlayView { private accessibilityEventsDelegate: AccessibilityEventsDelegate; - // @ts-ignore + constructor(context: Context, width: Number, height: Number, accessibilityEventsDelegate: AccessibilityEventsDelegate) { this.accessibilityEventsDelegate= accessibilityEventsDelegate; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets index fe96017e00..373a7ea5a5 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets @@ -18,10 +18,10 @@ import PlatformView from './PlatformView' import common from '@ohos.app.ability.common'; export default abstract class PlatformViewFactory { - private createArgsCodec: MessageCodec; + private createArgsCodec: MessageCodec; /** @param createArgsCodec the codec used to decode the args parameter of {@link #create}. */ - constructor(createArgsCodec: MessageCodec) { + constructor(createArgsCodec: MessageCodec) { this.createArgsCodec = createArgsCodec; } @@ -35,10 +35,10 @@ export default abstract class PlatformViewFactory { * createArgsCodec argument passed to the constructor. This is null if createArgsCodec was * null, or no arguments were sent from the Flutter app. */ - public abstract create(context: common.Context, viewId: number, args: any): PlatformView; + public abstract create(context: common.Context, viewId: number, args: ESObject): PlatformView; /** Returns the codec to be used for decoding the args parameter of {@link #create}. */ - getCreateArgsCodec(): MessageCodec { + getCreateArgsCodec(): MessageCodec { return this.createArgsCodec; } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewWrapper.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewWrapper.ets index 5bd02dcc81..dcd57072c3 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewWrapper.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewWrapper.ets @@ -22,41 +22,16 @@ import Log from '../../util/Log'; const TAG: string = "PlatformViewWrapper"; export class PlatformViewWrapper { - private prevLeft: number; - private prevTop: number; - private left: number; - private top: number; - private bufferWidth: number; - private bufferHeight: number; - private touchProcessor: OhosTouchProcessor; - - private onTouch = (touchEvent) => { - switch (touchEvent.type) { - case TouchType.Down: - this.prevLeft = this.left; - this.prevTop = this.top; - this.model.params["translateX"] = this.left; - this.model.params["translateY"] = this.top; - break; - case TouchType.Move: - this.model.params["translateX"] = this.prevLeft; - this.model.params["translateY"] = this.prevTop; - this.prevLeft = this.left; - this.prevTop = this.top; - break; - case TouchType.Up: - case TouchType.Cancel: - default: - break; - } - } + private prevLeft: number = 0; + private prevTop: number = 0; + private left: number = 0; + private top: number = 0; + private bufferWidth: number = 0; + private bufferHeight: number = 0; + private touchProcessor: OhosTouchProcessor | null = null; - private model : DVModel = createDVModelFromJson( - { - compType: "Column", - children: [], - } - ); + + private model : DVModel = createDVModelFromJson( new DVModelParam("Column", [])); public setTouchProcessor(newTouchProcessor: OhosTouchProcessor): void { this.touchProcessor = newTouchProcessor; @@ -69,25 +44,51 @@ export class PlatformViewWrapper { return this.model; } + setParams: (params: DVModelParameters, key: string, element: ESObject ) => void = (params: DVModelParameters, key: string, element: ESObject): void => { + let params2 = params as Record; + params2[key] =element; + } + + getParams: (params: DVModelParameters, element: string) => string | ESObject = (params: DVModelParameters, element: string): string | ESObject => { + let params2 = params as Record; + return params2[element]; + } + public setLayoutParams(parameters : DVModelParameters): void { + if (!this.model) { + return; + } if (this.model.params == null) { this.model.params = new DVModelParameters(); } - this.model.params['marginLeft'] = parameters['marginLeft']; - this.model.params['marginTop'] = parameters['marginTop']; - this.left = parameters['marginLeft']; - this.top = parameters['marginTop']; + this.setParams(this.model.params, "marginLeft", this.getParams(parameters, "marginLeft")); + this.setParams(this.model.params, "marginTop", this.getParams(parameters, "marginTop")); + this.left = this.getParams(parameters, "marginLeft"); + this.top = this.getParams(parameters, "marginTop"); - if (parameters.hasOwnProperty('width')) { - this.model.params['width'] = parameters['width']; - } + this.setParams(this.model.params, "width", this.getParams(parameters, "width")); + this.setParams(this.model.params, "height", this.getParams(parameters, "height")); - if (parameters.hasOwnProperty('height')) { - this.model.params['height'] = parameters['height']; - } + // this.model.params.marginLeft = parameters.marginLeft; + // this.model.params.marginTop = parameters.marginTop; + // this.left = parameters.marginLeft; + // this.top = parameters.marginTop;; + + // this.model.params.width = parameters.width; + // this.model.params.height = parameters.height; } public addDvModel(model: DVModel): void { - this.model.children.push(model); + this.model?.children.push(model); + } +} + +class DVModelParam { + compType: string + children: [] + + constructor(compType: string, children: []) { + this.compType = compType; + this.children = children; } -} \ No newline at end of file +}; \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets index 10efaea686..62888046c5 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets @@ -20,7 +20,7 @@ export interface PlatformViewsAccessibilityDelegate { * Returns the root of the view hierarchy for the platform view with the requested id, or null if * there is no corresponding view. */ - getPlatformViewById(viewId: number): any; + getPlatformViewById(viewId: number): Object; /** Returns true if the platform view uses virtual displays. */ usesVirtualDisplay(id: number): boolean; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets index 5838afd27f..cddb97aa45 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets @@ -21,7 +21,7 @@ import PlatformViewsChannel, { PlatformViewsHandler, PlatformViewTouch, PlatformViewBufferSize } from '../../../ets/embedding/engine/systemchannels/PlatformViewsChannel'; import PlatformView from './PlatformView'; -import { DVModel, DVModelParameters, DynamicView } from '../../view/DynamicView/dynamicView'; +import { DVModel, DVModelContainer, DVModelParameters, DynamicView } from '../../view/DynamicView/dynamicView'; import display from '@ohos.display'; import { FlutterView } from '../../view/FlutterView'; import { TextureRegistry } from '../../view/TextureRegistry'; @@ -47,14 +47,13 @@ const TAG = "PlatformViewsController" export default class PlatformViewsController implements PlatformViewsAccessibilityDelegate, PlatformViewsHandler { private registry: PlatformViewRegistryImpl; - private context: Context; - private flutterView: FlutterView; - private textureRegistry: TextureRegistry; - private textInputPlugin: TextInputPlugin; - private platformViewsChannel: PlatformViewsChannel; + private context: Context | null = null; + private flutterView: FlutterView | null = null; + private textureRegistry: TextureRegistry | null = null; + private textInputPlugin: TextInputPlugin | null = null; + private platformViewsChannel: PlatformViewsChannel | null = null; private accessibilityEventsDelegate: AccessibilityEventsDelegate; private nextOverlayLayerId: number = 0; - private ohosTouchProcessor: OhosTouchProcessor; private usesSoftwareRendering: boolean = false; private platformViews: Map; @@ -62,7 +61,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili private viewWrappers: Map; private currentFrameUsedOverlayLayerIds: HashSet; private currentFrameUsedPlatformViewIds: HashSet; - private rootDvModel = RootDvModeManager.getRootDvMode(); + private rootDvModel: DVModelContainer | null = RootDvModeManager.getRootDvMode(); private platformViewParent: Map; constructor() { @@ -76,7 +75,8 @@ export default class PlatformViewsController implements PlatformViewsAccessibili this.platformViewParent = new Map(); } - getPlatformViewById(viewId: number) { + + getPlatformViewById(viewId: number): Object { throw new Error('Method not implemented.'); } @@ -102,7 +102,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili } dispose(viewId: number): void { - let platformView: PlatformView = this.platformViews.get(viewId); + let platformView: PlatformView | null = this.platformViews.get(viewId) || null; if (platformView == null) { Log.e(TAG, "Disposing unknown platform view with id: " + viewId); return; @@ -115,48 +115,57 @@ export default class PlatformViewsController implements PlatformViewsAccessibili Log.e(TAG, "Disposing platform view threw an exception", err); } - let viewWrapper: PlatformViewWrapper = this.viewWrappers.get(viewId); + let viewWrapper: PlatformViewWrapper | null = this.viewWrappers.get(viewId) || null; if (viewWrapper != null) { this.viewWrappers.delete(viewId); } - let parentView: FlutterMutatorView = this.platformViewParent.get(viewId); + let parentView: FlutterMutatorView | null = this.platformViewParent.get(viewId) || null; if (parentView != null) { this.platformViewParent.delete(viewId); } } + setParams: (params: DVModelParameters, key: string, element: ESObject ) => void = (params: DVModelParameters, key: string, element: ESObject): void => { + let params2 = params as Record; + params2[key] =element; + } + resize(request: PlatformViewResizeRequest, onComplete: PlatformViewBufferResized): void { let physicalWidth: number = this.toPhysicalPixels(request.newLogicalWidth); let physicalHeight: number = this.toPhysicalPixels(request.newLogicalHeight); let viewId: number = request.viewId; Log.i(TAG, `Resize viewId ${viewId}, pw:${physicalWidth}, ph:${physicalHeight},lw:${request.newLogicalWidth}, lh:${request.newLogicalHeight}`); - let platformView: PlatformView = this.platformViews.get(viewId); - let viewWrapper: PlatformViewWrapper = this.viewWrappers.get(viewId); + let platformView: PlatformView | null = this.platformViews.get(viewId) || null; + let viewWrapper: PlatformViewWrapper | null = this.viewWrappers.get(viewId) || null; if (platformView == null || viewWrapper == null) { Log.e(TAG, "Resizing unknown platform view with id: " + viewId); return; } - let viewWrapperLayoutParams: DVModelParameters = viewWrapper.getDvModel().getLayoutParams(); - if (physicalWidth) { - viewWrapperLayoutParams["width"] = physicalWidth; + let viewWrapperLayoutParams: DVModelParameters | undefined = viewWrapper.getDvModel()?.getLayoutParams(); + if (physicalWidth && viewWrapperLayoutParams) { + this.setParams(viewWrapperLayoutParams, "width", physicalWidth); + // viewWrapperLayoutParams.width = physicalWidth; } - if (physicalHeight) { - viewWrapperLayoutParams["height"] = physicalHeight; + if (physicalHeight && viewWrapperLayoutParams) { + this.setParams(viewWrapperLayoutParams, "height", physicalHeight); + // viewWrapperLayoutParams.height = physicalHeight; } let embeddedView: DVModel = platformView.getView(); if (embeddedView != null) { let embeddedViewLayoutParams = embeddedView.getLayoutParams(); if (physicalWidth) { - embeddedViewLayoutParams["width"] = physicalWidth; + this.setParams(embeddedViewLayoutParams, "width", physicalWidth); + // embeddedViewLayoutParams.width = physicalWidth; } if (physicalHeight) { - embeddedViewLayoutParams["height"] = physicalHeight; + this.setParams(embeddedViewLayoutParams, "height", physicalHeight); + // embeddedViewLayoutParams.height = physicalHeight; } } @@ -165,7 +174,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili offset(viewId: number, top: number, left: number): void { Log.i(TAG, `Offset is id${viewId}, t:${top}, l:${left}`); - let viewWrapper: PlatformViewWrapper = this.viewWrappers.get(viewId); + let viewWrapper: PlatformViewWrapper | null = this.viewWrappers.get(viewId) || null; if (viewWrapper == null) { Log.e(TAG, "Setting offset for an unknown platform view with id: " + viewId); return; @@ -173,17 +182,17 @@ export default class PlatformViewsController implements PlatformViewsAccessibili let physicalTop = this.toPhysicalPixels(top); let physicalLeft = this.toPhysicalPixels(left); - let params = viewWrapper.getDvModel().params; - params["marginTop"] = physicalTop; - params["marginLeft"] = physicalLeft; - viewWrapper.setLayoutParams(params); + let params = viewWrapper.getDvModel()!.params; + this.setParams(params!, "marginTop", physicalTop); + this.setParams(params!, "marginLeft", physicalLeft); + viewWrapper.setLayoutParams(params!); } onTouch(touch: PlatformViewTouch): void { let viewId: number = touch.viewId; let density: number = display.getDefaultDisplaySync().densityDPI; - let platformView: PlatformView = this.platformViews.get(viewId); + let platformView: PlatformView | null = this.platformViews.get(viewId) ?? null; if (platformView == null) { Log.e(TAG, "Sending touch to an unknown platform view with id: " + viewId); return; @@ -215,7 +224,8 @@ export default class PlatformViewsController implements PlatformViewsAccessibili Log.e(TAG, "Setting direction to a null view with id: " + viewId); return; } - embeddedView.params["direction"] = direction; + this.setParams(embeddedView.params, "direction", direction); + // embeddedView.params.direction = direction; } validateDirection(direction:number):boolean { @@ -271,21 +281,24 @@ export default class PlatformViewsController implements PlatformViewsAccessibili throw new Error("Trying to create a platform view of unregistered type: " + request.viewType) } - let createParams: any = null; + let createParams: ESObject = null; if (request.params != null) { let byteParas : ByteBuffer = request.params as ByteBuffer; createParams = viewFactory.getCreateArgsCodec().decodeMessage(byteParas.buffer); } - let mutableContext: common.Context = this.context; - let platformView = viewFactory.create(mutableContext, request.viewId, createParams); + if (this.context == null) { + throw new Error('PlatformView#context is null.'); + } + let platformView = viewFactory.create(this.context, request.viewId, createParams); let embeddedView: DVModel = platformView.getView(); if (embeddedView == null) { throw new Error("PlatformView#getView() returned null, but an dynamic view reference was expected."); } - embeddedView.params['direction'] = request.direction; + this.setParams(embeddedView.params, "direction", request.direction); + // embeddedView.params.direction = request.direction; this.platformViews.set(request.viewId, platformView); return platformView; @@ -308,33 +321,40 @@ export default class PlatformViewsController implements PlatformViewsAccessibili Log.i(TAG, `View pW:${request.logicalWidth}, pH:${request.logicalHeight}, pT:${physicalTop}, pL:${physicalLeft}`); let param: DVModelParameters = new DVModelParameters(); - param['marginLeft'] = physicalLeft; - param['marginTop'] = physicalTop; + + this.setParams(param, "marginLeft", physicalLeft); + this.setParams(param, "marginTop", physicalTop); + // param.marginLeft = physicalLeft; + // param.marginTop = physicalTop; let model = platformView.getView(); if (request.logicalWidth != null) { let physicalWidth: number = this.toPhysicalPixels(request.logicalWidth); - model.params['width'] = physicalWidth; - param['width'] = physicalWidth; + this.setParams(model.params, "width", physicalWidth); + this.setParams(param, "width", physicalWidth); + // model.params.width = physicalWidth; + // param.width = physicalWidth; } if (request.logicalHeight != null) { let physicalHeight: number = this.toPhysicalPixels(request.logicalHeight); - model.params['height'] = physicalHeight; - param['height'] = physicalHeight; + this.setParams(model.params, "height", physicalHeight); + this.setParams(param, "height", physicalHeight); + // model.params.height = physicalHeight; + // param.height = physicalHeight; } viewWrapper.setLayoutParams(param); viewWrapper.addDvModel(model); - RootDvModeManager.addDvModel(viewWrapper.getDvModel()); + RootDvModeManager.addDvModel(viewWrapper.getDvModel()!); this.viewWrappers.set(request.viewId, viewWrapper); Log.i(TAG, "Create platform view success"); return textureId; } - public attach(context: Context, textureRegistry: TextureRegistry, dartExecutor: DartExecutor): void { + public attach(context: Context, textureRegistry: TextureRegistry | null, dartExecutor: DartExecutor): void { if (this.context != null) { } @@ -356,22 +376,22 @@ export default class PlatformViewsController implements PlatformViewsAccessibili public attachToView() { for (let wrapper of this.viewWrappers.values()) { - this.rootDvModel.model.children.push(wrapper.getDvModel()); + this.rootDvModel?.model.children.push(wrapper.getDvModel()!); } for (let mutator of this.platformViewParent.values()) { - this.rootDvModel.model.children.push(mutator.getDvModel()); + this.rootDvModel?.model.children.push(mutator.getDvModel()!); } for (let platformView of this.platformViews.values()) { - platformView.onFlutterViewAttached(this.rootDvModel.model); + platformView.onFlutterViewAttached(this.rootDvModel!.model); } } public detachFromView(): void { for (let index = 0; index < this.viewWrappers.size; index++) { - this.rootDvModel.model.children.pop(); + this.rootDvModel?.model.children.pop(); } for (let index = 0; index < this.platformViewParent.size; index++) { - this.rootDvModel.model.children.pop(); + this.rootDvModel?.model.children.pop(); } this.destroyOverlaySurfaces(); this.removeOverlaySurfaces(); @@ -387,7 +407,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili } public detachTextInputPlugin(): void { - this.textInputPlugin == null; + this.textInputPlugin = null; } public getRegistry(): PlatformViewRegistry { @@ -438,7 +458,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili } let parentView: FlutterMutatorView = new FlutterMutatorView(); parentView.setOnDescendantFocusChangeListener(() => { - this.platformViewsChannel.invokeViewFocused(viewId); + this.platformViewsChannel?.invokeViewFocused(viewId); }, () => { if (this.textInputPlugin != null) { this.textInputPlugin.clearTextInputClient(); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets index 3b3a43bb3a..eec92e82e4 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets @@ -20,7 +20,7 @@ import { createDVModelFromJson } from '../../view/DynamicView/dynamicViewJson'; @Component struct XComponentStruct { - private context; + private context:ESObject; build() { XComponent({ id: 'flutterXComponent', type: 'texture', libraryname: 'flutter' }) @@ -31,24 +31,33 @@ struct XComponentStruct { }) } } - -@Builder function BuildXComponentStruct($$: {param: DVModelParameters}) { +interface $$type{ + param: DVModelParameters +} +@Builder function BuildXComponentStruct($$: $$type) { XComponentStruct(); } +class DVModelJson{ + compType: string + children:Array + attributes:ESObject + + constructor(compType:string , children:Array , attributes:ESObject) { + this.compType = compType + this.children = children + this.attributes = attributes + } +} export class RootDvModeManager { - private static xComponentModel = + private static xComponentModel:ESObject = { compType: "xComponent", build: BuildXComponentStruct }; - private static model : DVModel = createDVModelFromJson( - { - compType: "Stack", - children: [RootDvModeManager.xComponentModel], - attributes: {alignContent: Alignment.TopStart}, - } + private static model: DVModel = createDVModelFromJson(new DVModelJson("Stack", [RootDvModeManager.xComponentModel], {alignContent: Alignment.TopStart},) + ); private static container : DVModelContainer = new DVModelContainer(RootDvModeManager.model); @@ -60,4 +69,4 @@ export class RootDvModeManager { public static addDvModel(model: DVModel): void { RootDvModeManager.container.model.children.push(model); } -} \ No newline at end of file +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets index 5eed99c13c..6e0837f5de 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets @@ -14,6 +14,7 @@ */ import util from '@ohos.util' +import StringUtils from './StringUtils' /** * A byte buffer. @@ -37,31 +38,31 @@ export class ByteBuffer { * @returns A byte buffer. */ static from(source: ArrayBuffer, byteOffset?: number, byteLength?: number): ByteBuffer { - if (ArrayBuffer.isView(source)) { - byteOffset = source.byteOffset + (byteOffset || 0) - } + // if (ArrayBuffer.isView(source)) { + // byteOffset = source.byteOffset + (byteOffset || 0) + // } const byteBuffer = new ByteBuffer() byteBuffer.dataView = byteLength === undefined ? new DataView(source, byteOffset) : new DataView(source, byteOffset, Math.min(source.byteLength, byteLength)) - byteBuffer.#byteOffset = byteBuffer.dataView.byteOffset + byteBuffer.mByteOffset = byteBuffer.dataView.byteOffset return byteBuffer } /** * The dataView. */ - private dataView: DataView + private dataView?: DataView /** * The byte offset. */ - #byteOffset: number = 0 + mByteOffset: number = 0 /** * The byte offset. * @returns The byte offset. */ get byteOffset(): number { - return this.#byteOffset + return this.mByteOffset } /** @@ -69,7 +70,7 @@ export class ByteBuffer { * @returns The byte offset. */ get byteLength(): number { - return this.dataView.byteLength + return this.dataView?.byteLength ?? 0 } /** @@ -77,17 +78,17 @@ export class ByteBuffer { * @returns The number of bytes remaining. */ get bytesRemaining(): number { - return this.dataView.byteLength - this.#byteOffset + return this.dataView ? this.dataView.byteLength - this.mByteOffset : 0; } hasRemaining(): boolean { - return this.#byteOffset < this.dataView.byteLength; + return this.dataView != undefined && this.mByteOffset < this.dataView.byteLength; } get buffer(): ArrayBuffer { - const dataBuffer = new DataView(new ArrayBuffer(this.#byteOffset)); - for (var i = 0; i < this.#byteOffset; i++) { - dataBuffer.setUint8(i, this.dataView.getUint8(i)); + const dataBuffer = new DataView(new ArrayBuffer(this.mByteOffset)); + for (let i = 0; i < this.mByteOffset; i++) { + dataBuffer.setUint8(i, this.dataView!.getUint8(i)); } return dataBuffer.buffer } @@ -97,14 +98,14 @@ export class ByteBuffer { * @param byteLength The byte length. */ skip(byteLength: number): void { - this.#byteOffset += byteLength + this.mByteOffset += byteLength } /** * Resets the byte offset. */ reset(): void { - this.#byteOffset = this.dataView.byteOffset + this.mByteOffset = this.dataView?.byteOffset ?? 0 } /** @@ -118,10 +119,10 @@ export class ByteBuffer { * check buffer capacity. */ checkWriteCapacity(slen: number): void { - if (this.#byteOffset + slen > this.dataView.byteLength) { - var checkBuffer = new DataView(new ArrayBuffer(this.dataView.byteLength + slen + 512)); - for (var i = 0; i < this.#byteOffset; i++) { - checkBuffer.setUint8(i, this.dataView.getUint8(i)); + if (this.mByteOffset + slen > this.dataView!.byteLength) { + let checkBuffer = new DataView(new ArrayBuffer(this.dataView!.byteLength + slen + 512)); + for (let i = 0; i < this.mByteOffset; i++) { + checkBuffer.setUint8(i, this.dataView!.getUint8(i)); } this.dataView = checkBuffer; } @@ -139,7 +140,7 @@ export class ByteBuffer { * Reads the next boolean. */ readBool(): boolean { - return this.getInt8(this.#byteOffset++) !== 0 + return this.getInt8(this.mByteOffset++) !== 0 } /** @@ -148,7 +149,7 @@ export class ByteBuffer { * @param value The value. */ setBool(byteOffset: number, value: boolean): void { - this.dataView.setInt8(byteOffset, value ? 1 : 0) + this.dataView?.setInt8(byteOffset, value ? 1 : 0) } /** @@ -157,7 +158,7 @@ export class ByteBuffer { */ writeBool(value: boolean): void { this.checkWriteCapacity(1) - this.setInt8(this.#byteOffset++, value ? 1 : 0) + this.setInt8(this.mByteOffset++, value ? 1 : 0) } /** @@ -166,7 +167,7 @@ export class ByteBuffer { * @returns The value. */ getInt8(byteOffset: number): number { - return this.dataView.getInt8(byteOffset) + return this.dataView?.getInt8(byteOffset) || 0 } /** @@ -174,7 +175,7 @@ export class ByteBuffer { * @returns The value. */ readInt8(): number { - return this.getInt8(this.#byteOffset++) + return this.getInt8(this.mByteOffset++) } /** @@ -183,7 +184,7 @@ export class ByteBuffer { * @param value The value. */ setInt8(byteOffset: number, value: number): void { - this.dataView.setInt8(byteOffset, value) + this.dataView?.setInt8(byteOffset, value) } /** @@ -192,7 +193,7 @@ export class ByteBuffer { */ writeInt8(value: number): void { this.checkWriteCapacity(1) - this.setInt8(this.#byteOffset++, value) + this.setInt8(this.mByteOffset++, value) } /** @@ -201,7 +202,7 @@ export class ByteBuffer { * @returns The value. */ getUint8(byteOffset: number): number { - return this.dataView.getUint8(byteOffset) + return this.dataView?.getUint8(byteOffset) || 0 } /** @@ -209,7 +210,7 @@ export class ByteBuffer { * @returns The value. */ readUint8(): number { - return this.getUint8(this.#byteOffset++) + return this.getUint8(this.mByteOffset++) } /** @@ -218,7 +219,7 @@ export class ByteBuffer { * @param value The value. */ setUint8(byteOffset: number, value: number): void { - this.dataView.setUint8(byteOffset, value) + this.dataView?.setUint8(byteOffset, value) } /** @@ -227,7 +228,7 @@ export class ByteBuffer { */ writeUint8(value: number): void { this.checkWriteCapacity(1) - this.setUint8(this.#byteOffset++, value) + this.setUint8(this.mByteOffset++, value) } /** @@ -237,7 +238,7 @@ export class ByteBuffer { * @returns The value. */ getInt16(byteOffset: number, littleEndian?: boolean): number { - return this.dataView.getInt16(byteOffset, littleEndian) + return this.dataView?.getInt16(byteOffset, littleEndian) || 0 } /** @@ -246,8 +247,8 @@ export class ByteBuffer { * @returns The value. */ readInt16(littleEndian?: boolean): number { - const value = this.getInt16(this.#byteOffset, littleEndian) - this.#byteOffset += 2 + const value = this.getInt16(this.mByteOffset, littleEndian) + this.mByteOffset += 2 return value } @@ -258,7 +259,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setInt16(byteOffset: number, value: number, littleEndian?: boolean): void { - this.dataView.setInt16(byteOffset, value, littleEndian) + this.dataView?.setInt16(byteOffset, value, littleEndian) } /** @@ -268,8 +269,8 @@ export class ByteBuffer { */ writeInt16(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(2) - this.setInt16(this.#byteOffset, value, littleEndian) - this.#byteOffset += 2 + this.setInt16(this.mByteOffset, value, littleEndian) + this.mByteOffset += 2 } /** @@ -279,7 +280,7 @@ export class ByteBuffer { * @returns The value. */ getUint16(byteOffset: number, littleEndian?: boolean): number { - return this.dataView.getUint16(byteOffset, littleEndian) + return this.dataView?.getUint16(byteOffset, littleEndian) || 0 } /** @@ -288,8 +289,8 @@ export class ByteBuffer { * @returns The value. */ readUint16(littleEndian?: boolean): number { - const value = this.getUint16(this.#byteOffset, littleEndian) - this.#byteOffset += 2 + const value = this.getUint16(this.mByteOffset, littleEndian) + this.mByteOffset += 2 return value } @@ -300,7 +301,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setUint16(byteOffset: number, value: number, littleEndian?: boolean): void { - this.dataView.setUint16(byteOffset, value, littleEndian) + this.dataView?.setUint16(byteOffset, value, littleEndian) } /** @@ -310,8 +311,8 @@ export class ByteBuffer { */ writeUint16(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(2) - this.setUint16(this.#byteOffset, value, littleEndian) - this.#byteOffset += 2 + this.setUint16(this.mByteOffset, value, littleEndian) + this.mByteOffset += 2 } /** @@ -321,7 +322,7 @@ export class ByteBuffer { * @returns The value. */ getInt32(byteOffset: number, littleEndian?: boolean): number { - return this.dataView.getInt32(byteOffset, littleEndian) + return this.dataView?.getInt32(byteOffset, littleEndian) ?? 0 } /** @@ -330,8 +331,8 @@ export class ByteBuffer { * @returns The value. */ readInt32(littleEndian?: boolean): number { - const value = this.getInt32(this.#byteOffset, littleEndian) - this.#byteOffset += 4 + const value = this.getInt32(this.mByteOffset, littleEndian) + this.mByteOffset += 4 return value } @@ -342,7 +343,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setInt32(byteOffset: number, value: number, littleEndian?: boolean): void { - this.dataView.setInt32(byteOffset, value, littleEndian) + this.dataView?.setInt32(byteOffset, value, littleEndian) } /** @@ -352,8 +353,8 @@ export class ByteBuffer { */ writeInt32(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(4) - this.setInt32(this.#byteOffset, value, littleEndian) - this.#byteOffset += 4 + this.setInt32(this.mByteOffset, value, littleEndian) + this.mByteOffset += 4 } /** @@ -363,7 +364,7 @@ export class ByteBuffer { * @returns The value. */ getUint32(byteOffset: number, littleEndian?: boolean): number { - return this.dataView.getUint32(byteOffset, littleEndian) + return this.dataView?.getUint32(byteOffset, littleEndian) ?? 0 } /** @@ -372,8 +373,8 @@ export class ByteBuffer { * @returns The value. */ readUint32(littleEndian?: boolean): number { - const value = this.getUint32(this.#byteOffset, littleEndian) - this.#byteOffset += 4 + const value = this.getUint32(this.mByteOffset, littleEndian) + this.mByteOffset += 4 return value } @@ -384,7 +385,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setUint32(byteOffset: number, value: number, littleEndian?: boolean): void { - this.dataView.setUint32(byteOffset, value, littleEndian) + this.dataView?.setUint32(byteOffset, value, littleEndian) } /** @@ -394,8 +395,8 @@ export class ByteBuffer { */ writeUint32(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(4) - this.setUint32(this.#byteOffset, value, littleEndian) - this.#byteOffset += 4 + this.setUint32(this.mByteOffset, value, littleEndian) + this.mByteOffset += 4 } /** @@ -405,7 +406,7 @@ export class ByteBuffer { * @returns The value. */ getFloat32(byteOffset: number, littleEndian?: boolean): number { - return this.dataView.getFloat32(byteOffset, littleEndian) + return this.dataView?.getFloat32(byteOffset, littleEndian) ?? 0 } /** @@ -414,8 +415,8 @@ export class ByteBuffer { * @returns The value. */ readFloat32(littleEndian?: boolean): number { - const value = this.getFloat32(this.#byteOffset, littleEndian) - this.#byteOffset += 4 + const value = this.getFloat32(this.mByteOffset, littleEndian) + this.mByteOffset += 4 return value } @@ -426,7 +427,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void { - this.dataView.setFloat32(byteOffset, value, littleEndian) + this.dataView?.setFloat32(byteOffset, value, littleEndian) } /** @@ -436,8 +437,8 @@ export class ByteBuffer { */ writeFloat32(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(4) - this.setFloat32(this.#byteOffset, value, littleEndian) - this.#byteOffset += 4 + this.setFloat32(this.mByteOffset, value, littleEndian) + this.mByteOffset += 4 } /** @@ -447,7 +448,7 @@ export class ByteBuffer { * @returns The value. */ getFloat64(byteOffset: number, littleEndian?: boolean): number { - return this.dataView.getFloat64(byteOffset, littleEndian) + return this.dataView?.getFloat64(byteOffset, littleEndian) ?? 0 } /** @@ -456,8 +457,8 @@ export class ByteBuffer { * @returns The value. */ readFloat64(littleEndian?: boolean): number { - const value = this.getFloat64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getFloat64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -468,7 +469,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void { - this.dataView.setFloat64(byteOffset, value, littleEndian) + this.dataView?.setFloat64(byteOffset, value, littleEndian) } /** @@ -478,8 +479,8 @@ export class ByteBuffer { */ writeFloat64(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setFloat64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setFloat64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -489,7 +490,7 @@ export class ByteBuffer { * @returns The value. */ getBigInt64(byteOffset: number, littleEndian?: boolean): bigint { - return this.dataView.getBigInt64(byteOffset, littleEndian) + return this.dataView?.getBigInt64(byteOffset, littleEndian) ?? BigInt(0) } /** @@ -498,8 +499,8 @@ export class ByteBuffer { * @returns The value. */ readBigInt64(littleEndian?: boolean): bigint { - const value = this.getBigInt64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getBigInt64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -510,7 +511,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void { - this.dataView.setBigInt64(byteOffset, value, littleEndian) + this.dataView?.setBigInt64(byteOffset, value, littleEndian) } /** @@ -520,8 +521,8 @@ export class ByteBuffer { */ writeBigInt64(value: bigint, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setBigInt64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setBigInt64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -531,7 +532,7 @@ export class ByteBuffer { * @returns The value. */ getBigUint64(byteOffset: number, littleEndian?: boolean): bigint { - return this.dataView.getBigUint64(byteOffset, littleEndian) + return this.dataView?.getBigUint64(byteOffset, littleEndian) ?? BigInt(0) } /** @@ -540,8 +541,8 @@ export class ByteBuffer { * @returns The value. */ readBigUint64(littleEndian?: boolean): bigint { - const value = this.getBigUint64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getBigUint64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -552,7 +553,7 @@ export class ByteBuffer { * @param littleEndian If the value is little endian. */ setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void { - this.dataView.setBigUint64(byteOffset, value, littleEndian) + this.dataView?.setBigUint64(byteOffset, value, littleEndian) } /** @@ -562,8 +563,8 @@ export class ByteBuffer { */ writeBigUint64(value: bigint, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setBigUint64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setBigUint64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -582,8 +583,8 @@ export class ByteBuffer { * @returns The value. */ readInt64(littleEndian?: boolean): number { - const value = this.getInt64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getInt64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -604,8 +605,8 @@ export class ByteBuffer { */ writeInt64(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setInt64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setInt64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -624,8 +625,8 @@ export class ByteBuffer { * @returns The value. */ readUint64(littleEndian?: boolean): number { - const value = this.getUint64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getUint64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -646,8 +647,8 @@ export class ByteBuffer { */ writeUint64(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setUint64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setUint64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -657,7 +658,9 @@ export class ByteBuffer { * @returns The value. */ getUint8Array(byteOffset: number, byteLength?: number): Uint8Array { - return new Uint8Array(this.dataView.buffer, this.dataView.byteOffset + byteOffset, byteLength) + return this.dataView == null + ? new Uint8Array(StringUtils.stringToArrayBuffer(""), byteOffset, byteLength) + : new Uint8Array(this.dataView?.buffer, this.dataView?.byteOffset + byteOffset, byteLength) } /** @@ -666,8 +669,8 @@ export class ByteBuffer { * @returns The value. */ readUint8Array(byteLength?: number): Uint8Array { - const value = this.getUint8Array(this.#byteOffset, byteLength) - this.#byteOffset += value.byteLength + const value = this.getUint8Array(this.mByteOffset, byteLength) + this.mByteOffset += value.byteLength return value } @@ -687,8 +690,8 @@ export class ByteBuffer { */ writeUint8Array(value: Uint8Array): void { this.checkWriteCapacity(value.byteLength) - this.setUint8Array(this.#byteOffset, value) - this.#byteOffset += value.byteLength + this.setUint8Array(this.mByteOffset, value) + this.mByteOffset += value.byteLength } /** @@ -701,7 +704,9 @@ export class ByteBuffer { if (byteLength !== undefined) { byteLength = Math.floor(byteLength / 2) } - return new Uint16Array(this.dataView.buffer, this.dataView.byteOffset + byteOffset, byteLength) + return this.dataView == null + ? new Uint16Array(StringUtils.stringToArrayBuffer(""), byteOffset, byteLength) + : new Uint16Array(this.dataView.buffer, this.dataView.byteOffset + byteOffset, byteLength) } /** @@ -710,8 +715,8 @@ export class ByteBuffer { * @returns The value. */ readUint16Array(byteLength?: number): Uint16Array { - const value = this.getUint16Array(this.#byteOffset, byteLength) - this.#byteOffset += value.byteLength + const value = this.getUint16Array(this.mByteOffset, byteLength) + this.mByteOffset += value.byteLength return value } @@ -731,8 +736,8 @@ export class ByteBuffer { */ writeUint16Array(value: Uint16Array): void { this.checkWriteCapacity(value.byteLength) - this.setUint16Array(this.#byteOffset, value) - this.#byteOffset += value.byteLength + this.setUint16Array(this.mByteOffset, value) + this.mByteOffset += value.byteLength } /** @@ -755,11 +760,11 @@ export class ByteBuffer { * @returns The value. */ readString(byteLength?: number, byteEncoding?: string): string { - const value = this.getString(this.#byteOffset, byteLength, byteEncoding) + const value = this.getString(this.mByteOffset, byteLength, byteEncoding) if (byteLength === undefined) { - this.#byteOffset = this.dataView.byteLength + this.mByteOffset = this.dataView?.byteLength ?? 0 } else { - this.#byteOffset += byteLength + this.mByteOffset += byteLength } return value } @@ -776,12 +781,12 @@ export class ByteBuffer { throw new TypeError("String encoding '" + byteEncoding + "' is not supported") } const encoder = new util.TextEncoder() - const byteLength = Math.min(this.dataView.byteLength - byteOffset, value.length * 4) + const byteLength = Math.min(this.dataView!.byteLength - byteOffset, value.length * 4) if (write) { this.checkWriteCapacity(byteLength) } const destination = this.getUint8Array(byteOffset, byteLength) - const { written } = encoder.encodeInto(value, destination) + const written = encoder.encodeInto(value, destination).written return written || 0 } @@ -791,8 +796,8 @@ export class ByteBuffer { * @param byteEncoding The byte encoding. */ writeString(value: string, byteEncoding?: string): void { - const byteLength = this.setString(this.#byteOffset, value, byteEncoding, true) - this.#byteOffset += byteLength + const byteLength = this.setString(this.mByteOffset, value, byteEncoding, true) + this.mByteOffset += byteLength } /** @@ -801,7 +806,7 @@ export class ByteBuffer { * @returns The string. */ toString(format?: string): string { - return Array.prototype.map.call(this.getUint8Array(0), function(byte: number): string { + return [...this.getUint8Array(0)].map((byte: number) => { switch(format) { case "hex": return ("00" + byte.toString(16)).slice(-2) diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets index cdec09bb74..437b52f180 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets @@ -18,22 +18,22 @@ import HiLog from '@ohos.hilog'; const DOMAIN: number = 0x00FF; const TAG = "Flutter"; const SYMBOL = " --> "; -const FILTER_KEYS = [ - new RegExp('hide', "gi") -] +// const FILTER_KEYS = [ +// new RegExp('hide', "gi") +// ] -export function filterKey(target: any, propKey: string, descriptor: PropertyDescriptor) { - const original = descriptor.value; - descriptor.value = function (...args: string[]) { - let filterResult = args.map((str) => { - let tempStr = str - FILTER_KEYS.forEach((filterKey) => tempStr = tempStr.replace(filterKey, "**")) - return tempStr - }); - const result = original.call(this, ...filterResult); - return result; - }; -} +// export function filterKey(target: any, propKey: string, descriptor: PropertyDescriptor) { +// const original = descriptor.value; +// descriptor.value = function (...args: string[]) { +// let filterResult = args.map((str) => { +// let tempStr = str +// FILTER_KEYS.forEach((filterKey) => tempStr = tempStr.replace(filterKey, "**")) +// return tempStr +// }); +// const result = original.call(this, ...filterResult); +// return result; +// }; +// } /** * Basic log class @@ -47,7 +47,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static d(tag: string, format: string, ...args: any[]) { + static d(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.DEBUG)) { HiLog.debug(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -61,7 +61,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static i(tag: string, format: string, ...args: any[]) { + static i(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.INFO)) { HiLog.info(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -75,7 +75,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static w(tag: string, format: string, ...args: any[]) { + static w(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.WARN)) { HiLog.warn(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -89,7 +89,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static e(tag: string, format: string, ...args: any[]) { + static e(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.ERROR)) { HiLog.error(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -103,7 +103,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static f(tag: string, format: string, ...args: any[]) { + static f(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.FATAL)) { HiLog.fatal(DOMAIN, TAG, tag + SYMBOL + format, args); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets index aeb7c554c3..595f870a33 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/StringUtils.ets @@ -30,7 +30,7 @@ export default class StringUtils { } static isNotEmpty(str: string): boolean { - return str && str.length > 0; + return str != null && str.length > 0; } static isEmpty(str: string): boolean { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets index c7b5f9dc2f..c3879f4a40 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets @@ -14,11 +14,11 @@ */ export default class ToolUtils { - static isObj(object: any): boolean { - return object && typeof (object) == 'object' && Object.prototype.toString.call(object).toLowerCase() == "[object object]"; + static isObj(object: Object): boolean { + return object && typeof (object) == 'object'; } - static implementsInterface(obj: any, method: string): boolean { + static implementsInterface(obj: ESObject, method: string): boolean { return Reflect.has(obj, method) && typeof obj[method] === 'function' } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets index 7560012dc3..3caaadea7a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets @@ -29,11 +29,11 @@ export class TraceSection { * @param sectionName The string to display as the section name in the trace. */ public static begin(sectionName: string): void { - hiTraceMeter.startTrace(this.cropSectionName(sectionName), this.taskId++); + hiTraceMeter.startTrace(TraceSection.cropSectionName(sectionName), TraceSection.taskId++); } /** Wraps Trace.endSection. */ public static end(sectionName: string): void { - hiTraceMeter.finishTrace(this.cropSectionName(sectionName), this.taskId); + hiTraceMeter.finishTrace(TraceSection.cropSectionName(sectionName), TraceSection.taskId); } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets index 403ce9c865..c0780a438a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import matrix4 from '@ohos.matrix4'; /** * Dynamic View creation @@ -67,9 +68,9 @@ export class DVModel { params: DVModelParameters; events: DVModelEvents; children: DVModelChildren; - builder: any; + builder: ESObject; - constructor(compType: string, params: DVModelParameters, events: DVModelEvents, children: DVModelChildren, builder?: any) { + constructor(compType: string, params: DVModelParameters, events: DVModelEvents, children: DVModelChildren, builder?: ESObject) { this.id_ = nextId++; this.compType = compType; this.params = params ?? new DVModelParameters; @@ -127,52 +128,61 @@ export struct DynamicView { @ObjectLink children: DVModelChildren; @ObjectLink params: DVModelParameters; @ObjectLink events: DVModelEvents; - @BuilderParam customBuilder?: ($$: { params: DVModelParameters }) => void; + @BuilderParam customBuilder?: ($$: BuilderParams) => void; + getParams: (params: DVModelParameters, element: string) => string | ESObject = (params: DVModelParameters, element: string): string | ESObject => { + let params2 = params as Record; + return params2[element]; + } + + getEvents: (events: DVModelEvents, element: string) => ESObject = (events: DVModelEvents, element: string): ESObject => { + let events2 = events as Record; + return events2[element]; + } /* we use this @Styles member function to set all common attributes and event handlers and set component specific attribute and event handler functions in the @Builder function */ @Styles common_attrs() { - .width(this.params["width"]) - .height(this.params["height"]) - .backgroundColor(this.params["backgroundColor"]) - .onClick(this.events["onClick"]) + .width(this.getParams(this.params, "width")) + .height(this.getParams(this.params, "height")) + .backgroundColor(this.getParams(this.params, "backgroundColor")) + .onClick(this.getEvents(this.events, "onClick")) .margin({ - left: this.params["marginLeft"], - right: this.params["marginRight"], - top: this.params["marginTop"], - bottom: this.params["marginBottom"] + left: this.getParams(this.params, "marginLeft"), + right: this.getParams(this.params, "marginRight"), + top: this.getParams(this.params, "marginTop"), + bottom: this.getParams(this.params, "marginBottom") }) - .onTouch(this.events["onTouch"]) - .onFocus(this.events['onFocus']) - .onBlur(this.events["onBlur"]) + .onTouch(this.getEvents(this.events, "onTouch")) + .onFocus(this.getEvents(this.events, "onFocus")) + .onBlur(this.getEvents(this.events, "onBlur")) .translate({ - x: this.params["translateX"], - y: this.params["translateY"], - z: this.params["translateZ"] + x: this.getParams(this.params, "translateX"), + y: this.getParams(this.params, "translateY"), + z: this.getParams(this.params, "translateZ") }) - .transform(this.params["matrix"]) - .direction(this.params["direction"]) + .transform(this.getParams(this.params, "matrix")) + .direction(this.getParams(this.params, "direction")) } @Styles clip_attrs() { - .clip(this.params["rectWidth"] ? new Rect({ - width: this.params["rectWidth"], - height: this.params["rectHeight"], - radius: this.params["rectRadius"] + .clip(this.getParams(this.params, "rectWidth") ? new Rect({ + width: this.getParams(this.params, "rectWidth"), + height: this.getParams(this.params, "rectHeight"), + radius: this.getParams(this.params, "rectRadius") }) : null) - .clip(this.params["pathWidth"] ? new Path({ - width: this.params["pathWidth"], - height: this.params["pathHeight"], - commands: this.params["pathCommands"] + .clip(this.getParams(this.params, "pathWidth") ? new Path({ + width: this.getParams(this.params, "pathWidth"), + height: this.getParams(this.params, "pathHeight"), + commands: this.getParams(this.params, "pathCommands") }) : null) } @Builder buildChildren() { ForEach(this.children, - child => { + (child: ESObject) => { DynamicView({ model: child as DVModel, params: child.params, @@ -181,7 +191,7 @@ export struct DynamicView { customBuilder: child.builder }) }, - child => `${child.id_}` + (child: ESObject) => `${child.id_}` ) } @@ -207,29 +217,29 @@ export struct DynamicView { } .common_attrs() .clip_attrs() - .alignContent(this.params["alignContent"]) + .alignContent(this.getParams(this.params, "alignContent")) } @Builder buildText() { - Text(`${this.params["value"]}`) + Text(`${this.getParams(this.params, "value")}`) .common_attrs() - .fontColor(this.params["fontColor"]) + .fontColor(this.getParams(this.params, "fontColor")) } @Builder buildImage() { - Image(this.params["src"]) + Image(this.getParams(this.params, "src")) .common_attrs() } // Button with label @Builder buildButton() { - Button(this.params["value"]) + Button(this.getParams(this.params, "value")) .common_attrs() } @Builder buildCustom() { if (this.customBuilder) { - this.customBuilder({ params: this.params }); + this.customBuilder(new BuilderParams(this.params)); } } @@ -251,3 +261,11 @@ export struct DynamicView { } } } + +class BuilderParams { + params: DVModelParameters; + + constructor(params: DVModelParameters) { + this.params = params; + } +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets index b398c80222..40b05299e8 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets @@ -18,8 +18,7 @@ import { DVModel, DVModelParameters, DVModelEvents, DVModelChildren } from "./dy export function createDVModelFromJson(json: Object): DVModel { /* private use helper functions */ - - function createChildrenFrom(children: Array): DVModelChildren { + let createChildrenFrom: (children: Array) => DVModelChildren = (children: Array): DVModelChildren => { let result = new DVModelChildren(); if (Array.isArray(children)) { (children as Array).forEach(child => { @@ -32,32 +31,38 @@ export function createDVModelFromJson(json: Object): DVModel { return result; } - function createAttributesFrom(attributes: Object): DVModelParameters { + let setParams: (result: DVModelParameters | DVModelEvents, key: ESObject, element: Object ) => void = (result: DVModelParameters, key: ESObject, element: ESObject): void => { + let newResult = result as Record; + newResult[key] = element[key]; + } + + let createAttributesFrom: (attributes: Object) => DVModelParameters = (attributes: Object): DVModelParameters => { let result = new DVModelParameters(); if ((typeof attributes == "object") && (!Array.isArray(attributes))) { - Object.keys(attributes).forEach(k => result[k] = attributes[k]); + Object.keys(attributes).forEach(k => {setParams(result, k, attributes)}); } return result; } - function createEventsFrom(events: Object): DVModelEvents { + let createEventsFrom: (events: Object) => DVModelEvents = (events: Object): DVModelEvents => { let result = new DVModelEvents(); if ((typeof events == "object") && (!Array.isArray(events))) { - Object.keys(events).forEach(k => result[k] = events[k]); + Object.keys(events).forEach(k => {setParams(result, k, events)}); } return result; } if (typeof json !== 'object') { console.error("createDVModelFromJson: input is not JSON"); - return undefined; + return new DVModel("", "", "", createChildrenFrom([])); } + let jsonObject = json as Record; return new DVModel( - json["compType"], - createAttributesFrom(json["attributes"]), - createEventsFrom(json["events"]), - createChildrenFrom(json["children"]), - json["build"] + jsonObject["compType"], + createAttributesFrom(jsonObject["attributes"]), + createEventsFrom(jsonObject["events"]), + createChildrenFrom(jsonObject["children"]), + jsonObject["build"] ); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterCallbackInformation.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterCallbackInformation.ets index f52152001a..26202727fa 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterCallbackInformation.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/FlutterCallbackInformation.ets @@ -27,7 +27,7 @@ export class FlutterCallbackInformation { * `dart:ui`. * @return an instance of FlutterCallbackInformation for the provided handle. */ - static lookupCallbackInformation(handle: number): FlutterCallbackInformation { + static lookupCallbackInformation(handle: number): FlutterCallbackInformation | null { return FlutterNapi.nativeLookupCallbackInformation(handle); } -- Gitee