diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets index 25ac6c509779aba23fa2cb22f33548e140b0f4d0..ee0d9abe81e4c36a15a84a7b85c6ff5fab9fe471 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets @@ -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/ets/app/FlutterPluginRegistry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets index 346eb870a842992cf128395be51651f597238296..2a2a44964d3903c884f533e2bed115a4b624b745 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 @@ -15,7 +15,6 @@ 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 4a16a419d9c7a5df84379278cdc7fb113624d7f7..47ff37a1cf3e1af16dc6cfd4b42e17851abd9015 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 78db31cae3a9d154a09f9f85541115dc4452573f..7808dfd8afa1f7ad23e003028409cc18758dd616 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 @@ -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 7709ea8a31e98f794314a7e2f3b84e890f1eee9f..a596d2e25e9d8a52e564d63008663252c764b80e 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; @@ -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 { @@ -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: Record): AbilityConstant.OnSaveResult { - return this.abilityPluginBinding.onSaveState(reason, wantParam); + 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: 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 05e35aec1b7b6f50ab8df336bdd69fbbe21febc8..f9fab12dccc6fa576049e08c5e971bea1f4f67b7 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 @@ -37,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(); @@ -61,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] @@ -81,7 +81,7 @@ export default class FlutterEngineGroup { platformViewsController, this.activeEngines, engineToCleanUpOnDestroy); - engine.addEngineLifecycleListener(listener); + engine?.addEngineLifecycleListener(listener); return engine; } @@ -93,12 +93,12 @@ export default class FlutterEngineGroup { class EngineLifecycleListenerImpl implements EngineLifecycleListener { private platformViewsController: PlatformViewsController; private activeEngines: ArrayList = new ArrayList(); - private engine: FlutterEngine; + private engine: FlutterEngine | null; constructor( platformViewsController: PlatformViewsController, activeEngines: ArrayList, - engine: FlutterEngine) { + engine: FlutterEngine | null) { this.platformViewsController = platformViewsController; this.activeEngines = activeEngines; this.engine = engine; @@ -113,10 +113,10 @@ class EngineLifecycleListenerImpl implements EngineLifecycleListener { 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; @@ -128,7 +128,7 @@ export class Options { return this.context; } - getDartEntrypoint(): DartEntrypoint { + getDartEntrypoint(): DartEntrypoint | null { return this.dartEntrypoint; } @@ -148,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 34b251069ce950ee8a0fb3d2f08b723a2d1e6f78..645507a6d8a5fd2749a7ef3caf9a97ad1ec154eb 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 902699e44c585b355df699b78cca69b58f021055..4ec3580943e01308e76b67db671ae4e404455929 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: image.PixelMap = null; + let tempPixelMap: image.PixelMap | null = null; imageSourceApi.createPixelMap({ desiredPixelFormat: image.PixelMapFormat.RGBA_8888 }).then(pixelMap => { @@ -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 8d97b4835c0c87ed0c9d9260336b3a338392497f..46d08cd458b5795d1daaa1f4379a088b129d5dc7 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 @@ -35,9 +35,9 @@ export default class DartExecutor implements BinaryMessenger { 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); @@ -117,7 +117,7 @@ export default class DartExecutor implements BinaryMessenger { dartEntrypoint.dartEntrypointFunctionName, dartEntrypoint.dartEntrypointLibrary, this.assetManager, - dartEntrypointArgs); + dartEntrypointArgs ?? []); this.isApplicationRunning = true; } finally { @@ -146,7 +146,7 @@ export default class DartExecutor implements BinaryMessenger { dartCallback.callbackHandle.callbackName, dartCallback.callbackHandle.callbackLibraryPath, dartCallback.resourceManager, - null); + []); this.isApplicationRunning = true; } finally { @@ -271,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"); } } @@ -363,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 8b8695530d69f9e49063913d559702863490676a..862ca785b685f237a02a2edaf14844b69f95ad88 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,16 +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, null); + 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) { @@ -142,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/FlutterApplicationInfo.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterApplicationInfo.ets index a03814516ba2b9cc2aeebcefe51a44fb4838944e..272615d612c8d056fb3a58c280f9f2e69b02d502 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; @@ -47,4 +52,4 @@ export default class FlutterApplicationInfo { this.isDebugMode = false; this.isProfile = false; } -} +} \ No newline at end of file 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 114387d16e7a585188aedb535fa62b8671d7a7b7..8917880d499cbbf798ef199e2eb0c621bc893516 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 be4c9391bc48ec403e67b03196986823083988da..f2544f8e20b9041a7db93d99ba3e1a2db3da67a5 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 @@ -20,13 +20,13 @@ 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 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) { @@ -76,7 +76,7 @@ export class FlutterMutatorView { } 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) { @@ -93,6 +93,9 @@ 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(); @@ -112,7 +115,7 @@ export class FlutterMutatorView { params.matrix = matrix; } - public getDvModel(): DVModel { + public getDvModel(): DVModel | undefined { return this.model; } } 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 59da6edd6c86a74b2db936777ee43ba1df117a69..2f53c6c041bfd92ea74c3896d00a04f6b5590e2e 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 3045e2b8d7ddf48a11d96a642650c63a3f6c0025..6b0987a80677a337a548f4c876941dd13cfda266 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/systemchannels/AccessibilityChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/AccessibilityChannel.ets index ed96f236fb55a878ef4b03766a7751cf389e377a..804994eda64980ff6d23470994cf32cebfed977b 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,6 +20,7 @@ import HashMap from '@ohos.util.HashMap'; import FlutterNapi, {AccessibilityDelegate} from '../FlutterNapi'; import { Action } from '../../../view/AccessibilityBridge' import StandardMessageCodec from '../../../plugin/common/StandardMessageCodec'; +import StringUtils from '../../../util/StringUtils'; /** * 辅助功能channel @@ -29,13 +30,13 @@ export default class AccessibilityChannel implements MessageHandler{ private static CHANNEL_NAME = "flutter/accessibility"; 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; @@ -77,7 +78,7 @@ export default class AccessibilityChannel implements MessageHandler{ break; } } - reply.reply(null); + reply.reply(StringUtils.stringToArrayBuffer("")); } constructor(dartExecutor: DartExecutor, flutterNapi: FlutterNapi) { 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 c4b5b6cf7b8868145424897851dd734d7eff5b6a..d34d81816a6382de13bdef7a7690421c2363c318 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 210a7510a478d350cd38e89d7826e3a53290dfa8..3e8b3d4167c3aeb9c08e657e8c504e7c51f5214d 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) { @@ -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/PlatformChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets index 20e8db4b44690fd0e2bafbde4044a1f0724fba7f..e2ff4f357a38f835c002b785a7ab9d3464639792 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 @@ -26,12 +26,11 @@ 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); - let callback = new PlatformMethodCallback(); - callback.platform = this; + let callback = new PlatformMethodCallback(this); this.channel.setMethodCallHandler(callback); } @@ -130,6 +129,7 @@ export default class PlatformChannel { } } Log.e(PlatformChannel.TAG, "No such HapticFeedbackType:" + encodedName); + return HapticFeedbackType.STANDARD; } getClipboardContentFormatFromValue(encodedName: string): ClipboardContentFormat { @@ -140,6 +140,7 @@ export default class PlatformChannel { return ClipboardContentFormat[format]; } } + return ClipboardContentFormat.PLAIN_TEXT; } getSystemUiOverlayFromValue(encodedName: string): SystemUiOverlay { let systemUiOverlays : string[] = [SystemUiOverlay.TOP_OVERLAYS, SystemUiOverlay.BOTTOM_OVERLAYS]; @@ -302,6 +303,10 @@ 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"); @@ -318,7 +323,7 @@ class PlatformMethodCallback implements MethodCallHandler { case "HapticFeedback.vibrate": try { Log.d(PlatformMethodCallback.TAG, "HapticFeedback: " + args as string); - let feedbackType: HapticFeedbackType = this.platform.getFeedbackTypeFromValue(args as string); + let feedbackType = this.platform.getFeedbackTypeFromValue(args as string); this.platform.platformMessageHandler.vibrateHapticFeedback(feedbackType); result.success(null); } catch (e) { @@ -462,13 +467,13 @@ class PlatformMethodCallback implements MethodCallHandler { } private decodeSystemChromeStyle(encodedStyle: ESObject): 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; + 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; } 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 564a6df4c4d10c0bdd9dfe22a0b5ec2f3f8e9d5e..5da4a68f2f5101f6eb12f36a2921d3c93249ead8 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 @@ -24,7 +24,7 @@ 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(); /** @@ -45,7 +45,7 @@ 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; } @@ -82,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"); @@ -109,7 +109,7 @@ export default class PlatformViewsChannel { t:${request.logicalTop}, d:${request.direction}`); - const textureId = this.handler.createForTextureLayer(request); + const textureId = this.handler?.createForTextureLayer(request); if (textureId == NON_TEXTURE_FALLBACK) { if (!hybridFallback) { throw new Error( @@ -132,7 +132,7 @@ export default class PlatformViewsChannel { 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); @@ -150,7 +150,7 @@ export default class PlatformViewsChannel { try { let resizeCallback = new ResizeCallback(); resizeCallback.result = result; - this.handler.resize(resizeRequest, resizeCallback); + this.handler?.resize(resizeRequest, resizeCallback); } catch (err) { Log.e(TAG, "resize failed", err); result.error("error", err, null); @@ -160,7 +160,7 @@ export default class PlatformViewsChannel { offset(call: MethodCall, result: MethodResult): void { const offsetArgs: Map = call.args; try { - this.handler.offset( + this.handler?.offset( offsetArgs.get("id"), offsetArgs.get("top"), offsetArgs.get("left")); @@ -194,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); @@ -208,7 +208,7 @@ export default class PlatformViewsChannel { 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); @@ -219,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); @@ -230,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); @@ -488,8 +488,8 @@ export class PlatformViewTouch { } class ParsingCallback implements MethodCallHandler { - platformChannel : PlatformViewsChannel; - handler: PlatformViewsHandler; + platformChannel : PlatformViewsChannel | null = null; + handler: PlatformViewsHandler | null = null; onMethodCall(call: MethodCall, result: MethodResult) { if (this.handler == null) { @@ -499,35 +499,35 @@ class ParsingCallback implements MethodCallHandler { Log.i(TAG, "Received '" + call.method + "' message."); switch (call.method) { case "create": { - this.platformChannel.create(call, result); + this.platformChannel?.create(call, result); break; } case "dispose": { - this.platformChannel.dispose(call, result); + this.platformChannel?.dispose(call, result); break; } case "resize": { - this.platformChannel.resize(call, result); + this.platformChannel?.resize(call, result); break; } case "offset": { - this.platformChannel.offset(call, result); + this.platformChannel?.offset(call, result); break; } case "touch": { - this.platformChannel.touch(call, result); + this.platformChannel?.touch(call, result); break; } case "setDirection": { - this.platformChannel.setDirection(call, result); + this.platformChannel?.setDirection(call, result); break; } case "clearFocus": { - this.platformChannel.clearFocus(call, result); + this.platformChannel?.clearFocus(call, result); break; } case "synchronizeToNativeViewHierarchy": { - this.platformChannel.synchronizeToNativeViewHierarchy(call, result); + this.platformChannel?.synchronizeToNativeViewHierarchy(call, result); break; } default: @@ -537,15 +537,15 @@ class ParsingCallback implements MethodCallHandler { } class ResizeCallback extends PlatformViewBufferResized { - result : MethodResult; + result : MethodResult | null = null; run(bufferSize: PlatformViewBufferSize) { if (bufferSize == null) { - this.result.error("error", "Failed to resize the platform view", 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); + 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 bcf53050d567f4fc61237845d4019c669873540c..9ccbd2c3f5c9e40aaa97342a02b171ee54a6d4af 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,14 +53,14 @@ 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 = new Uint8Array(); - private channel: MethodChannel; - private pendingFrameworkRestorationChannelRequest: MethodResult; + 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); @@ -94,7 +94,7 @@ 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", RestorationChannelMethodCallHandler.packageData(data), { + this.channel?.invokeMethod("push", RestorationChannelMethodCallHandler.packageData(data), { success: (result: ESObject) :void => { this.restorationData = data; }, @@ -121,17 +121,17 @@ export default class RestorationChannel { * state prior to the hot restart will get restored. */ clearData() { - this.restorationData = null; + this.restorationData = new Uint8Array(); } } class RestorationChannelMethodCallHandler implements MethodCallHandler { - public waitForRestorationData: boolean; + public waitForRestorationData: boolean = false; private restorationData: Uint8Array; private engineHasProvidedData: boolean = false; private frameworkHasRequestedData: boolean = false; - private channel: MethodChannel; - private pendingFrameworkRestorationChannelRequest: MethodResult; + private channel: MethodChannel | null = null; + private pendingFrameworkRestorationChannelRequest: MethodResult | null = null; constructor(restorationData: Uint8Array) { this.restorationData = restorationData; 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 afdbecc9829a7520eef0c3409545572be381a96b..7e7d93c164f8852a90ad0fd4b0752258d1465062 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,17 +25,15 @@ const TAG = "TextInputChannel"; export default class TextInputChannel { private static CHANNEL_NAME = "flutter/textinput"; public channel: MethodChannel; - textInputMethodHandler: TextInputMethodHandler; + textInputMethodHandler: TextInputMethodHandler | null = null; constructor(dartExecutor: DartExecutor) { this.channel = new MethodChannel(dartExecutor, TextInputChannel.CHANNEL_NAME, JSONMethodCodec.INSTANCE); - let callback = new TextInputCallback(); - callback.textInputMethodHandler = this.textInputMethodHandler; - this.channel.setMethodCallHandler(callback); } setTextInputMethodHandler(textInputMethodHandler: TextInputMethodHandler): void { this.textInputMethodHandler = textInputMethodHandler; + this.channel.setMethodCallHandler(new TextInputCallback(this.textInputMethodHandler)); } requestExistingInputState(): void { @@ -136,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; @@ -149,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, @@ -305,6 +303,10 @@ export class TextEditState { class TextInputCallback implements MethodCallHandler { textInputMethodHandler: TextInputMethodHandler; + constructor(handler: TextInputMethodHandler) { + this.textInputMethodHandler = handler; + } + onMethodCall(call: MethodCall, result: MethodResult) { if (this.textInputMethodHandler == null) { return; @@ -325,7 +327,7 @@ class TextInputCallback implements MethodCallHandler { case "TextInput.setClient": const textInputClientId: number = args[0] as number; //TODO: parse configuration - const config: Configuration = null; + const config: Configuration | null = null; this.textInputMethodHandler.setClient(textInputClientId, config); result.success(null); 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 07a374a7109e9a1ffcd5680220534c9796681e64..00e9bcc2666e5801ec1fda6dc4397671a615307d 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 @@ -41,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 @@ -58,17 +58,17 @@ export class FlutterAbility extends UIAbility implements Host { Log.i(TAG, "bundleCodeDir=" + this.context.bundleCodeDir); // globalThis.flutterAbility = this this.displayInfo = display.getDefaultDisplaySync(); - this.viewportMetrics.devicePixelRatio = this.displayInfo.densityPixels + 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'); @@ -77,7 +77,7 @@ export class FlutterAbility extends UIAbility implements Host { onDestroy() { if (this.stillAttachedForEvent("onDestroy")) { - this.delegate.onDestroy(); + this?.delegate?.onDestroy(); } } @@ -88,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: // 切到前台 @@ -97,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: // 切到后台 @@ -114,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)); } @@ -137,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; @@ -146,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() } } @@ -158,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, @@ -181,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; } } @@ -216,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; } @@ -233,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(); } } @@ -254,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 { @@ -284,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. @@ -295,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 } /** @@ -307,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; } @@ -319,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 == null || !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() } @@ -362,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: 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 9046981a47219a7eb553dd4d3baeefa639069281..af0946ca03adcd28b6735e09ffcd05345c77c9eb 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,10 +360,10 @@ 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."); @@ -356,28 +373,28 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { 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()) { + if (this.host?.shouldAttachEngineToActivity()) { const plugins:Record = {} - const result = this.flutterEngine.getAbilityControlSurface().onSaveState(reason, plugins); + 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 1bdd7b6a809a77510f8942e81e0d91e7b4970893..a8eea36514d690e00aba5c987f61907cf4292515 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/Settings.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/Settings.ets index a435d2a45cc960a5d6a4eb49c3d131c83b4d2dcb..d8ced27e5a16fffa1be79bc836bb790bfc81d07e 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/plugin/PlatformPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets index 9910f14b6d71e2fc70e55eb8c7846ccbeffa0180..2fa7cbf589dda9215418d61b16c75bc921736233 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 @@ -39,7 +39,7 @@ export default class PlatformPlugin { constructor(platformChannel: PlatformChannel, context: common.Context, platformPluginDelegate?: PlatformPluginDelegate) { this.callback.platformChannel = platformChannel; this.callback.context = context; - this.callback.applicationContext = context.getApplicationContext(); + this.callback.applicationContext = context?.getApplicationContext(); this.callback.platform = this; try { @@ -53,13 +53,13 @@ export default class PlatformPlugin { } catch (err) { Log.e(PlatformPlugin.TAG, "Failed to obtain the top window. Cause: " + JSON.stringify(err)); } - this.callback.platformPluginDelegate = platformPluginDelegate; - this.callback.platformChannel.setPlatformMessageHandler(this.callback); + this.callback.platformPluginDelegate = platformPluginDelegate ?? null; + this.callback.platformChannel?.setPlatformMessageHandler(this.callback); } updateSystemUiOverlays(): void { - this.callback.windowClass.setWindowSystemBarEnable(this.callback.showBarOrNavigation); + this.callback.windowClass?.setWindowSystemBarEnable(this.callback.showBarOrNavigation); if (this.callback.currentTheme != null) { this.callback.setSystemChromeSystemUIOverlayStyle(this.callback.currentTheme); } @@ -72,10 +72,10 @@ export default class PlatformPlugin { setSystemChromeChangeListener(): void { if (this.callback.callbackId == null && this.callback.applicationContext != null) { let that = this; - this.callback.callbackId = this.callback.applicationContext.on('environment', { + 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')); + that.callback.platformChannel?.systemChromeChanged(that.callback.showBarOrNavigation.includes('status')); }, onMemoryLevel(level) { } @@ -90,16 +90,16 @@ export interface PlatformPluginDelegate { class PlatformPluginCallback implements PlatformMessageHandler { private static TAG = "PlatformPluginCallback"; - platform: PlatformPlugin; - windowClass: window.Window = null; - platformChannel: PlatformChannel; - platformPluginDelegate: PlatformPluginDelegate; - context: common.Context; + 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; - callbackId: number = null; - applicationContext: common.ApplicationContext = null; - currentTheme: SystemChromeStyle = null; + uiAbilityContext: common.UIAbilityContext | null = null; + callbackId: number | null = null; + applicationContext: common.ApplicationContext | null = null; + currentTheme: SystemChromeStyle | null = null; playSystemSound(soundType: SoundType) { } @@ -131,7 +131,7 @@ class PlatformPluginCallback implements PlatformMessageHandler { setPreferredOrientations(ohosOrientation: number) { Log.d(PlatformPluginCallback.TAG, "ohosOrientation: " + ohosOrientation); - this.windowClass.setPreferredOrientation(ohosOrientation); + this.windowClass?.setPreferredOrientation(ohosOrientation); } setApplicationSwitcherDescription(description: AppSwitcherDescription) { @@ -147,11 +147,11 @@ class PlatformPluginCallback implements PlatformMessageHandler { } setSystemUiChangeListener() { - this.platform.setSystemChromeChangeListener(); + this.platform?.setSystemChromeChangeListener(); } restoreSystemUiOverlays() { - this.platform.updateSystemUiOverlays(); + this.platform?.updateSystemUiOverlays(); } setSystemUiOverlayStyle(systemUiOverlayStyle: SystemChromeStyle) { @@ -160,7 +160,7 @@ class PlatformPluginCallback implements PlatformMessageHandler { } popSystemNavigator() { - if (this.platformPluginDelegate != null && this.platformPluginDelegate.popSystemNavigator()) { + if (this.platformPluginDelegate != null && this.platformPluginDelegate?.popSystemNavigator()) { return; } if (this.uiAbilityContext != null) { @@ -188,35 +188,35 @@ class PlatformPluginCallback implements PlatformMessageHandler { let uiConfig: ('status' | 'navigation')[] = []; 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) { //全屏显示,在应用程序上呈现状态和导航元素 - this.windowClass.setWindowLayoutFullScreen(false); + this.windowClass?.setWindowLayoutFullScreen(false); uiConfig = ['status', 'navigation']; } else { return; } this.showBarOrNavigation = uiConfig; - this.platform.updateSystemUiOverlays(); + this.platform?.updateSystemUiOverlays(); } 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; + let navigationBarContentColorValue: string | undefined = undefined; if (systemChromeStyle.statusBarIconBrightness != null) { switch (systemChromeStyle.statusBarIconBrightness) { case Brightness.DARK: @@ -262,7 +262,7 @@ class PlatformPluginCallback implements PlatformMessageHandler { systemBarProperties.isNavigationBarLightIcon = isNavigationBarLightIconValue; systemBarProperties.navigationBarContentColor = navigationBarContentColorValue; Log.d(PlatformPluginCallback.TAG, "systemBarProperties: " + JSON.stringify(systemBarProperties)); - this.windowClass.setWindowSystemBarProperties(systemBarProperties); + this.windowClass?.setWindowSystemBarProperties(systemBarProperties); } setSystemChromeEnabledSystemUIOverlays(overlays: SystemUiOverlay[]): void { @@ -282,7 +282,7 @@ class PlatformPluginCallback implements PlatformMessageHandler { } } this.showBarOrNavigation = uiConfig; - this.platform.updateSystemUiOverlays(); + this.platform?.updateSystemUiOverlays(); } } 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 a6e6f6bcfb5b863a2b5c65b9f398ec5e048f4ad6..796f8edb8936927b11819282e8721b41da55a103 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)); } } @@ -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 988c6a57092f7913f20b65bf6afa97b310385931..e0b55276beb3893f0347d9893ecaab9d2754174c 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 @@ -109,7 +109,7 @@ export interface BinaryMessenger { * @param callback a {@link BinaryReply} callback invoked when the Flutter application responds to * the message, possibly null. */ - 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 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 03af6b520acc908d9cb63914ca2236736218aa77..204dd8e3eabf85edcdecf84a78e86517f424f4cb 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,7 +16,7 @@ export default class FlutterException implements Error { stack?: string; message: string; - name: string; + name: string = ""; code: string; details: ESObject 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 4c289c6054e952a5cf7ed48b58fcfab6e343533b..6224740ed6d838efdeaea84a3f81d829a5e14ac1 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'; @@ -32,7 +33,7 @@ export default class JSONMessageCodec implements MessageCodec { encodeMessage(message: ESObject): ArrayBuffer { if (message == null) { - return null; + return StringUtils.stringToArrayBuffer(""); } return StringCodec.INSTANCE.encodeMessage(JSON.stringify(message)); } 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 e491ed5f7fec63ad1064c7e7ddbe468aaf3821df..31da9ff4890d7ca576e03a26a1c0bea2a49bd0c7 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 @@ -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)); } } @@ -205,7 +206,7 @@ class IncomingMethodCallHandler implements BinaryMessageHandler { 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/StandardMessageCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMessageCodec.ets index 3de7603e1f576a9af23be11b9f185c67730429b3..8650cfe643a400cfba7dd4b99b505f151fa82bd7 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 @@ -66,7 +66,7 @@ export default class StandardMessageCodec implements MessageCodec { encodeMessage(message: ESObject): ArrayBuffer { if (message == null) { - return null; + return StringUtils.stringToArrayBuffer(""); } const stream = ByteBuffer.from(new ArrayBuffer(1024)) this.writeValue(stream, message); 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 e43be76b5527f6180d9b30ede5c1c07dff84c729..b824ac1f901b1dc9d1ae36f49e7fc74954595f4f 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 72735c0a29a1e893e8bf986458cea0da82df0d2b..1ea2049bd252b4e54d9d5ce58a60b7a15989a653 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 c61296f6dae8b30fcb035f72d8457ca36d83a015..1aa1b2d87245f029c1b8a630fecf02bceb41ea8d 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; 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 6df66b9cfde51d0d47c80b693b28f1f049c38b09..16aa44aa78ec96be676109ad800c933999ce4586 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 @@ -23,33 +23,32 @@ import { EditingStateWatcher, ListenableEditingState } from './ListenableEditing export default class TextInputPlugin implements EditingStateWatcher{ private static TAG = "TextInputPlugin"; private textInputChannel: TextInputChannel; - private inputMethodController: inputMethod.InputMethodController; - private inputTarget: InputTarget; - private mEditable: ListenableEditingState; + private mTextInputHandler: TextInputMethodHandlerImpl; constructor(textInputChannel: TextInputChannel) { this.textInputChannel = textInputChannel; - this.mEditable = new ListenableEditingState(); - this.inputMethodController = inputMethod.getController(); - let textInputMethodHandler = new TextInputMethodHandlerImpl(this); - this.textInputChannel.setTextInputMethodHandler(textInputMethodHandler); + this.mTextInputHandler = new TextInputMethodHandlerImpl(this); + this.textInputChannel.setTextInputMethodHandler(this.mTextInputHandler); } public clearTextInputClient() { - this.textInputChannel.textInputMethodHandler.clearClient(); + this.textInputChannel.textInputMethodHandler?.clearClient(); } + 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()) + 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.inputMethodController.detach((err) => { + this.mTextInputHandler.inputMethodController.detach((err) => { if(err) { Log.e(TextInputPlugin.TAG, "Failed to detach: " + JSON.stringify(err)); } @@ -61,22 +60,25 @@ export default class TextInputPlugin implements EditingStateWatcher{ class TextInputMethodHandlerImpl implements TextInputMethodHandler { private static TAG = "TextInputMethodHandlerImpl"; private textConfig: inputMethod.TextConfig; - private inputMethodController: inputMethod.InputMethodController; - private inputTarget: InputTarget; - private configuration: Configuration; - private mEditable: ListenableEditingState; - private mRestartInputPending: boolean; + 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: EditingStateWatcher) { + constructor(plugin: TextInputPlugin) { this.textConfig = { inputAttribute: { textInputType: 0, enterKeyType: 1 }}; this.plugin = plugin; + this.mEditable = new ListenableEditingState(); + this.inputMethodController = inputMethod.getController(); + this.inputTarget = new InputTarget(Type.NO_TARGET, 0); } show(): void { @@ -95,7 +97,7 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { } - setClient(textInputClientId: number, configuration: Configuration): void { + setClient(textInputClientId: number, configuration: Configuration | null): void { Log.d(TextInputMethodHandlerImpl.TAG,"textInputClientId: " + textInputClientId); this.setTextInputClient(textInputClientId, configuration); } @@ -146,7 +148,7 @@ class TextInputMethodHandlerImpl implements TextInputMethodHandler { } } - setTextInputClient(client: number, configuration: Configuration): void { + setTextInputClient(client: number, configuration: Configuration | null): void { this.configuration = configuration; if(this.canShowTextInput()) { this.inputTarget = new InputTarget(Type.FRAMEWORK_CLIENT, client); 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 44c94a11aa2f132f6dd24b3484bb5ca9b59c940c..0f8bf873c41d36a2455442b857216b215418efbe 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; 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 faa3bc90e50c304744883689a532d0dc323bd714..ea9450d4aa0f140dceeb4a7925f46383a65d0ea3 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/PlatformViewWrapper.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewWrapper.ets index 6bcec97fd500a783d24977965863b543fa730eef..dcd57072c319129d0edba82cd9acbe91cf002b1a 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,13 +22,13 @@ 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 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( new DVModelParam("Column", [])); @@ -55,6 +55,9 @@ export class PlatformViewWrapper { } public setLayoutParams(parameters : DVModelParameters): void { + if (!this.model) { + return; + } if (this.model.params == null) { this.model.params = new DVModelParameters(); } @@ -76,7 +79,7 @@ export class PlatformViewWrapper { } public addDvModel(model: DVModel): void { - this.model.children.push(model); + this.model?.children.push(model); } } 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 2fac095a2a743d4e5039a1f69b3e944ae9eb6455..cddb97aa45a55ac7d800591d15d4f14bcad28f5d 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() { @@ -103,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; @@ -116,12 +115,12 @@ 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); } @@ -138,20 +137,20 @@ export default class PlatformViewsController implements PlatformViewsAccessibili 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) { + let viewWrapperLayoutParams: DVModelParameters | undefined = viewWrapper.getDvModel()?.getLayoutParams(); + if (physicalWidth && viewWrapperLayoutParams) { this.setParams(viewWrapperLayoutParams, "width", physicalWidth); // viewWrapperLayoutParams.width = physicalWidth; } - if (physicalHeight) { + if (physicalHeight && viewWrapperLayoutParams) { this.setParams(viewWrapperLayoutParams, "height", physicalHeight); // viewWrapperLayoutParams.height = physicalHeight; } @@ -175,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; @@ -183,17 +182,17 @@ export default class PlatformViewsController implements PlatformViewsAccessibili let physicalTop = this.toPhysicalPixels(top); let physicalLeft = this.toPhysicalPixels(left); - let params = viewWrapper.getDvModel().params; - this.setParams(params, "marginTop", physicalTop); - this.setParams(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; @@ -288,8 +287,10 @@ export default class PlatformViewsController implements PlatformViewsAccessibili 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) { @@ -346,14 +347,14 @@ export default class PlatformViewsController implements PlatformViewsAccessibili 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) { } @@ -375,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(); @@ -406,7 +407,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili } public detachTextInputPlugin(): void { - this.textInputPlugin == null; + this.textInputPlugin = null; } public getRegistry(): PlatformViewRegistry { @@ -457,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 ae74fda5859b59aea42c5104515ab74fbba94714..eec92e82e4c56679060d2be9003aece149b080c7 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 @@ -56,7 +56,7 @@ export class RootDvModeManager { build: BuildXComponentStruct }; - private static model : DVModel = createDVModelFromJson(new DVModelJson("Stack", [RootDvModeManager.xComponentModel], {alignContent: Alignment.TopStart},) + private static model: DVModel = createDVModelFromJson(new DVModelJson("Stack", [RootDvModeManager.xComponentModel], {alignContent: Alignment.TopStart},) ); 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 99a7d4b522caa6daf09b06e6feb40bcd6203abd3..6e0837f5de981501166a2f78067c37402a37bd3c 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. @@ -49,7 +50,7 @@ export class ByteBuffer { /** * The dataView. */ - private dataView: DataView + private dataView?: DataView /** * The byte offset. @@ -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.mByteOffset + return this.dataView ? this.dataView.byteLength - this.mByteOffset : 0; } hasRemaining(): boolean { - return this.mByteOffset < this.dataView.byteLength; + return this.dataView != undefined && this.mByteOffset < this.dataView.byteLength; } get buffer(): ArrayBuffer { const dataBuffer = new DataView(new ArrayBuffer(this.mByteOffset)); for (let i = 0; i < this.mByteOffset; i++) { - dataBuffer.setUint8(i, this.dataView.getUint8(i)); + dataBuffer.setUint8(i, this.dataView!.getUint8(i)); } return dataBuffer.buffer } @@ -104,7 +105,7 @@ export class ByteBuffer { * Resets the byte offset. */ reset(): void { - this.mByteOffset = 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.mByteOffset + slen > this.dataView.byteLength) { - let checkBuffer = new DataView(new ArrayBuffer(this.dataView.byteLength + slen + 512)); + 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)); + checkBuffer.setUint8(i, this.dataView!.getUint8(i)); } this.dataView = checkBuffer; } @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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 } /** @@ -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) } /** @@ -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) } /** @@ -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) } /** @@ -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) } /** @@ -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) } /** @@ -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) } /** @@ -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) } /** @@ -757,7 +762,7 @@ export class ByteBuffer { readString(byteLength?: number, byteEncoding?: string): string { const value = this.getString(this.mByteOffset, byteLength, byteEncoding) if (byteLength === undefined) { - this.mByteOffset = this.dataView.byteLength + this.mByteOffset = this.dataView?.byteLength ?? 0 } else { this.mByteOffset += byteLength } @@ -776,7 +781,7 @@ 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) } 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 aeb7c554c30b5d3625851afc214dda8d31da9917..595f870a3360cb140dbb0f92a003c85c462d28f0 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/view/DynamicView/dynamicViewJson.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets index 57498b70d0bb6121c7745bcc267ca46954015005..40b05299e8d204b9242b99a5cb1dfb7d1068b2b3 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 @@ -54,7 +54,7 @@ export function createDVModelFromJson(json: Object): DVModel { if (typeof json !== 'object') { console.error("createDVModelFromJson: input is not JSON"); - return undefined; + return new DVModel("", "", "", createChildrenFrom([])); } let jsonObject = json as Record; 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 f52152001a497e70586215af090b2a81190e1187..26202727fac9b327d8a4a024667ef30ea067a6e8 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); }