From 106ddb5e9d100cb8bc9729c32fe92793fea51bf5 Mon Sep 17 00:00:00 2001 From: 18719058668 <718092089@qq.com> Date: Wed, 25 Oct 2023 12:15:59 +0800 Subject: [PATCH] typescript to arkts migration modify Signed-off-by: 18719058668 <718092089@qq.com> --- .../flutter_embedding/build-profile.json5 | 5 +- .../flutter/build-profile.json5 | 2 +- .../libflutter/{index.d.ts => index.d.ets} | 2 +- .../{index_actual.d.ts => index_actual.d.ets} | 0 .../cpp/types/libflutter/oh-package.json5 | 2 +- .../flutter/src/main/ets/FlutterInjector.ets | 6 +- .../main/ets/app/FlutterPluginRegistry.ets | 3 +- .../embedding/engine/FlutterEngineCache.ets | 6 +- .../FlutterEngineConnectionRegistry.ets | 8 +- .../embedding/engine/FlutterEngineGroup.ets | 45 +- .../main/ets/embedding/engine/FlutterNapi.ets | 4 +- .../embedding/engine/dart/DartExecutor.ets | 3 +- .../embedding/engine/dart/DartMessenger.ets | 3 +- .../engine/loader/ApplicationInfoLoader.ets | 4 +- .../engine/loader/FlutterApplicationInfo.ets | 4 +- .../mutatorsstack/FlutterMutatorView.ets | 77 +-- .../plugins/ability/AbilityControlSurface.ets | 2 +- .../plugins/ability/AbilityPluginBinding.ets | 4 +- .../systemchannels/AccessibilityChannel.ets | 11 +- .../engine/systemchannels/KeyEventChannel.ets | 2 +- .../systemchannels/MouseCursorChannel.ets | 2 +- .../systemchannels/NavigationChannel.ets | 16 +- .../engine/systemchannels/PlatformChannel.ets | 471 +++++++++--------- .../systemchannels/PlatformViewsChannel.ets | 172 ++++--- .../systemchannels/RestorationChannel.ets | 80 +-- .../engine/systemchannels/SettingsChannel.ets | 4 +- .../engine/systemchannels/SystemChannel.ets | 6 +- .../engine/systemchannels/TestChannel.ets | 16 +- .../systemchannels/TextInputChannel.ets | 179 ++++--- .../ets/embedding/ohos/FlutterAbility.ets | 11 +- .../embedding/ohos/FlutterAbilityDelegate.ets | 4 +- .../main/ets/embedding/ohos/FlutterPage.ets | 3 +- .../ets/embedding/ohos/OhosTouchProcessor.ets | 2 +- .../ets/embedding/ohos/TouchEventTracker.ets | 11 +- .../src/main/ets/plugin/PlatformPlugin.ets | 326 ++++++------ .../ets/plugin/common/BasicMessageChannel.ets | 2 +- .../ets/plugin/common/BinaryMessenger.ets | 35 +- .../main/ets/plugin/common/EventChannel.ets | 16 +- .../ets/plugin/common/FlutterException.ets | 4 +- .../ets/plugin/common/JSONMessageCodec.ets | 6 +- .../ets/plugin/common/JSONMethodCodec.ets | 25 +- .../src/main/ets/plugin/common/MethodCall.ets | 12 +- .../main/ets/plugin/common/MethodChannel.ets | 12 +- .../main/ets/plugin/common/MethodCodec.ets | 8 +- .../plugin/common/StandardMessageCodec.ets | 28 +- .../ets/plugin/common/StandardMethodCodec.ets | 20 +- .../ets/plugin/editing/TextEditingDelta.ets | 18 - .../ets/plugin/editing/TextInputPlugin.ets | 197 ++++---- .../localization/LocalizationPlugin.ets | 19 +- .../ets/plugin/mouse/MouseCursorPlugin.ets | 2 +- .../plugin/platform/PlatformOverlayView.ets | 2 +- .../plugin/platform/PlatformViewFactory.ets | 8 +- .../plugin/platform/PlatformViewWrapper.ets | 72 ++- .../PlatformViewsAccessibilityDelegate.ets | 2 +- .../platform/PlatformViewsController.ets | 51 +- .../plugin/platform/RootDvModelManager.ets | 31 +- .../flutter/src/main/ets/util/ByteBuffer.ets | 152 +++--- .../flutter/src/main/ets/util/Log.ets | 40 +- .../flutter/src/main/ets/util/ToolUtils.ets | 6 +- .../src/main/ets/util/TraceSection.ets | 4 +- .../main/ets/view/DynamicView/dynamicView.ets | 89 ++-- .../ets/view/DynamicView/dynamicViewJson.ets | 27 +- 62 files changed, 1267 insertions(+), 1117 deletions(-) rename shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/{index.d.ts => index.d.ets} (99%) rename shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/{index_actual.d.ts => index_actual.d.ets} (100%) diff --git a/shell/platform/ohos/flutter_embedding/build-profile.json5 b/shell/platform/ohos/flutter_embedding/build-profile.json5 index d4ad640974..4c7fb9d2b2 100755 --- a/shell/platform/ohos/flutter_embedding/build-profile.json5 +++ b/shell/platform/ohos/flutter_embedding/build-profile.json5 @@ -16,12 +16,13 @@ { "app": { "signingConfigs": [], - "compileSdkVersion": 9, - "compatibleSdkVersion": 9, "products": [ { "name": "default", "signingConfig": "default", + "compileSdkVersion": "4.0.0(10)", + "compatibleSdkVersion": "4.0.0(10)", + "runtimeOS": "HarmonyOS", } ] }, diff --git a/shell/platform/ohos/flutter_embedding/flutter/build-profile.json5 b/shell/platform/ohos/flutter_embedding/flutter/build-profile.json5 index d6bbb9768e..95e376706d 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/build-profile.json5 +++ b/shell/platform/ohos/flutter_embedding/flutter/build-profile.json5 @@ -20,7 +20,7 @@ "targets": [ { "name": "default", - "runtimeOS": "OpenHarmony" + "runtimeOS": "HarmonyOS" } ], } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ts b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets similarity index 99% rename from shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ts rename to shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets index 67f9580813..25ac6c5097 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ts +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index.d.ets @@ -31,7 +31,7 @@ export class napiContext { */ export const nativeUpdateRefreshRate: ( ate: number -) => {}; +) => void; /** * 初始化dart vm和flutter engine diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ts b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ets similarity index 100% rename from shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ts rename to shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/index_actual.d.ets diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 index 216ed0d720..5d1822ef86 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/cpp/types/libflutter/oh-package.json5 @@ -15,7 +15,7 @@ { "name": "libflutter.so", - "types": "./index.d.ts", + "types": "./index.d.ets", "version": "", "description": "Please describe the basic information." } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets index db12ccb09d..4e6f2f8b0e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/FlutterInjector.ets @@ -26,10 +26,10 @@ export default class FlutterInjector { private flutterNapi: FlutterNapi; static getInstance(): FlutterInjector { - if (this.instance == null) { - this.instance = new FlutterInjector(); + if (FlutterInjector.instance == null) { + FlutterInjector.instance = new FlutterInjector(); } - return this.instance; + return FlutterInjector.instance; } /** * 初始化 diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets index 760659f83d..346eb870a8 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/app/FlutterPluginRegistry.ets @@ -12,8 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import FlutterView from '../embedding/ohos/FlutterView'; +import { FlutterView } from '../view/FlutterView'; import common from '@ohos.app.ability.common'; import PlatformViewController from '../plugin/platform/PlatformViewsController' import Log from '../util/Log'; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets index bfc0691b64..78db31cae3 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineCache.ets @@ -20,10 +20,10 @@ export default class FlutterEngineCache { private cachedEngines: Map = new Map(); static getInstance(): FlutterEngineCache { - if (this.instance == null) { - this.instance = new FlutterEngineCache(); + if (FlutterEngineCache.instance == null) { + FlutterEngineCache.instance = new FlutterEngineCache(); } - return this.instance; + return FlutterEngineCache.instance; } /** * 返回engineId对应的FlutterEngine是否存在 diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineConnectionRegistry.ets index 3ca45c9f4c..7709ea8a31 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 @@ -80,7 +80,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, // plugins, and if this engine is currently attached to an Ability, // notify the AbilityAware plugin that it is now attached to an Ability. if (ToolUtils.implementsInterface(plugin, "onAttachedToAbility")) { - const abilityAware = plugin as any + const abilityAware: ESObject = plugin; this.abilityAwarePlugins.set(plugin.getUniqueClassName(), abilityAware); if (this.isAttachedToAbility()) { abilityAware.onAttachedToAbility(this.abilityPluginBinding); @@ -110,7 +110,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, } if (ToolUtils.implementsInterface(plugin, "onAttachedToAbility")) { if (this.isAttachedToAbility()) { - const abilityAware = plugin as any + const abilityAware: ESObject = plugin; abilityAware.onDetachedFromAbility(); } this.abilityAwarePlugins.delete(pluginClassName); @@ -161,7 +161,7 @@ export default class FlutterEngineConnectionRegistry implements PluginRegistry, this.abilityPluginBinding.onWindowFocusChanged(hasFocus); } - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult { + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult { return this.abilityPluginBinding.onSaveState(reason, wantParam); } @@ -240,7 +240,7 @@ class FlutterEngineAbilityPluginBinding implements AbilityPluginBinding { }); } - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult { + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult { this.onSaveStateListeners.forEach((listener, key) => { listener.onSaveState(reason, wantParam) }); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets index 5e5c069fcb..05e35aec1b 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterEngineGroup.ets @@ -13,22 +13,23 @@ * limitations under the License. */ -import FlutterEngine from "./FlutterEngine" +import FlutterEngine, { EngineLifecycleListener } from "./FlutterEngine" import common from '@ohos.app.ability.common' import FlutterLoader from './loader/FlutterLoader' import FlutterInjector from '../../FlutterInjector' import { DartEntrypoint } from './dart/DartExecutor' import PlatformViewsController from '../../plugin/platform/PlatformViewsController' +import ArrayList from '@ohos.util.ArrayList' export default class FlutterEngineGroup { - private activeEngines: Array = new Array(); + private activeEngines: ArrayList = new ArrayList(); constructor() { } async checkLoader(context: common.Context, args: Array) { - var loader: FlutterLoader = FlutterInjector.getInstance().getFlutterLoader(); + let loader: FlutterLoader = FlutterInjector.getInstance().getFlutterLoader(); if (!loader.initialized) { await loader.startInitialization(context.getApplicationContext()); loader.ensureInitializationComplete(args); @@ -73,17 +74,14 @@ export default class FlutterEngineGroup { automaticallyRegisterPlugins, waitForRestorationData); } - this.activeEngines.push(engine); + this.activeEngines.add(engine); const engineToCleanUpOnDestroy = engine; - engine.addEngineLifecycleListener({ - onPreEngineRestart(): void { - platformViewsController.onPreEngineRestart(); - }, - onEngineWillDestroy(): void { - this.activeEngines.remove(engineToCleanUpOnDestroy); - } - }); + let listener: EngineLifecycleListener = new EngineLifecycleListenerImpl( + platformViewsController, + this.activeEngines, + engineToCleanUpOnDestroy); + engine.addEngineLifecycleListener(listener); return engine; } @@ -92,6 +90,27 @@ export default class FlutterEngineGroup { } } +class EngineLifecycleListenerImpl implements EngineLifecycleListener { + private platformViewsController: PlatformViewsController; + private activeEngines: ArrayList = new ArrayList(); + private engine: FlutterEngine; + + constructor( + platformViewsController: PlatformViewsController, + activeEngines: ArrayList, + engine: FlutterEngine) { + this.platformViewsController = platformViewsController; + this.activeEngines = activeEngines; + this.engine = engine; + } + onPreEngineRestart(): void { + this.platformViewsController.onPreEngineRestart(); + } + onEngineWillDestroy(): void { + this.activeEngines.remove(this.engine); + } +} + export class Options { private context: common.Context; private dartEntrypoint: DartEntrypoint; @@ -105,7 +124,7 @@ export class Options { this.context = context; } - getContext(): any { + getContext(): common.Context { return this.context; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/FlutterNapi.ets index e074ff82ea..902699e44c 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 @@ -266,7 +266,7 @@ export default class FlutterNapi { decodeImage(buffer: ArrayBuffer, imageGeneratorAddress: number): void { Log.d(TAG, "called decodeImage=" + buffer.byteLength) const imageSourceApi = image.createImageSource(buffer); - let tempPixelMap = null; + let tempPixelMap: image.PixelMap = null; imageSourceApi.createPixelMap({ desiredPixelFormat: image.PixelMapFormat.RGBA_8888 }).then(pixelMap => { @@ -276,7 +276,7 @@ export default class FlutterNapi { }).then(imageInfo => { Log.d(TAG, `nativeImageHeaderCallback width=${imageInfo.size.width} height=${imageInfo.size.height} imageGeneratorAddress=${imageGeneratorAddress}`) flutter.nativeImageDecodeCallback(imageInfo.size.width, imageInfo.size.height, imageGeneratorAddress, tempPixelMap) - }).catch(error => { + }).catch((error: ESObject) => { Log.d(TAG, "decodeImage error=" + JSON.stringify(error)) flutter.nativeImageDecodeCallback(0, 0, imageGeneratorAddress, null); }) diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets index 4b952c42f8..8d97b4835c 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartExecutor.ets @@ -30,7 +30,7 @@ const TAG = "DartExecutor"; /** * dart代码执行器 */ -export default class DartExecutor extends BinaryMessenger { +export default class DartExecutor implements BinaryMessenger { flutterNapi: FlutterNapi; assetManager: resourceManager.ResourceManager; private dartMessenger: DartMessenger; @@ -43,7 +43,6 @@ export default class DartExecutor extends BinaryMessenger { new IsolateChannelMessageHandler(this.isolateServiceId, this.isolateServiceIdListener); constructor(flutterNapi: FlutterNapi, assetManager: resourceManager.ResourceManager) { - super(); this.flutterNapi = flutterNapi; this.assetManager = assetManager; this.dartMessenger = new DartMessenger(flutterNapi); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/dart/DartMessenger.ets index 0a2c32013c..8b8695530d 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 @@ -129,7 +129,8 @@ export class DartMessenger implements BinaryMessenger, PlatformMessageHandler { messageDeferred = (this.enableBufferingIncomingMessagesFlag && handlerInfo == null); if (messageDeferred) { if (!this.bufferedMessages.has(channel)) { - this.bufferedMessages.set(channel, new BufferedMessageInfo[0]); + // this.bufferedMessages.set(channel, new BufferedMessageInfo[0]); + this.bufferedMessages.set(channel, null); } let buffer: BufferedMessageInfo[] = this.bufferedMessages.get(channel); buffer.push(new BufferedMessageInfo(message, replyId, messageData)); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets index b8af4f6fb7..3c5bca80d3 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/ApplicationInfoLoader.ets @@ -18,7 +18,7 @@ import common from '@ohos.app.ability.common'; export default class ApplicationInfoLoader { static load(context: common.Context) { - let applicatioinInfo = new FlutterApplicationInfo(null, null, null, null, null, context.bundleCodeDir + '/libs/arm64', true); - return applicatioinInfo + let applicationInfo = new FlutterApplicationInfo(null, null, null, null, null, context.bundleCodeDir + '/libs/arm64', true); + return applicationInfo } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterApplicationInfo.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/loader/FlutterApplicationInfo.ets index 0db68ee9da..a03814516b 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 @@ -44,7 +44,7 @@ export default class FlutterApplicationInfo { this.domainNetworkPolicy = domainNetworkPolicy == null ? "" : domainNetworkPolicy; this.nativeLibraryDir = nativeLibraryDir; this.automaticallyRegisterPlugins = automaticallyRegisterPlugins; - this.isDebugMode = true; + 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/mutatorsstack/FlutterMutatorView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorView.ets index f0d8581b18..be4c9391bc 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/mutatorsstack/FlutterMutatorView.ets @@ -12,9 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import ArrayList from '@ohos.util.ArrayList'; -import { DVModel, DVModelParameters } from '../../../view/DynamicView/dynamicView'; +import matrix4 from '@ohos.matrix4'; +import { DVModel, DVModelEvents, DVModelParameters } from '../../../view/DynamicView/dynamicView'; import { createDVModelFromJson } from '../../../view/DynamicView/dynamicViewJson'; import OhosTouchProcessor from '../../ohos/OhosTouchProcessor'; import { FlutterMutator, FlutterMutatorsStack } from './FlutterMutatorsStack' @@ -27,17 +27,18 @@ export class FlutterMutatorView { private prevLeft: number; private prevTop: number; private ohosTouchProcessor: OhosTouchProcessor; - private onTouch = (touchEvent) => { + private onTouch = (touchEvent: ESObject) => { + let params = this.model.params as Record; switch (touchEvent.type) { case TouchType.Down: this.prevLeft = this.left; this.prevTop = this.top; - this.model.params["translateX"] = this.left; - this.model.params["translateY"] = this.top; + params.translateX = this.left; + params.translateY = this.top; break; case TouchType.Move: - this.model.params["translateX"] = this.prevLeft; - this.model.params["translateY"] = this.prevTop; + params.translateX = this.prevLeft; + params.translateY = this.prevTop; this.prevLeft = this.left; this.prevTop = this.top; break; @@ -47,30 +48,31 @@ export class FlutterMutatorView { break; } } + private model: DVModel = createDVModelFromJson( - { - compType: "Column", - children: [], - attributes: { backgroundColor: Color.Red }, - events: { onTouch: this.onTouch } - } + new DVModelParam("Column", [], { backgroundColor: Color.Red }, { onTouch: this.onTouch }) ); setOnDescendantFocusChangeListener(onFocus: () => void, onBlur: () => void) { - this.model.events["onFocus"] = onFocus; - this.model.events["onBlur"] = onBlur; + // this.model.events["onFocus"] = onFocus; + // this.model.events["onBlur"] = onBlur; + let events2 = this.model.events as Record; + events2.onFocus = onFocus; + events2.onBlur = onBlur; } public setLayoutParams(parameters: DVModelParameters): void { if (this.model.params == null) { this.model.params = new DVModelParameters(); } - this.model.params['marginLeft'] = parameters['marginLeft']; - this.model.params['marginTop'] = parameters['marginTop']; - this.model.params['width'] = parameters['width']; - this.model.params['height'] = parameters['height']; - this.left = parameters['marginLeft']; - this.top = parameters['marginTop']; + let params = this.model.params as Record | matrix4.Matrix4Transit>; + let parametersRecord = parameters as Record | matrix4.Matrix4Transit>; + params.marginLeft = parametersRecord['marginLeft']; + params.marginTop = parametersRecord['marginTop']; + params.width = parametersRecord['width']; + params.height = parametersRecord['height']; + this.left = parametersRecord.marginLeft as number; + this.top = parametersRecord.marginTop as number ; } public addDvModel(model: DVModel): void { @@ -81,7 +83,7 @@ export class FlutterMutatorView { this.mutatorsStack = mutatorsStack; this.left = left; this.top = top; - let parameters = new DVModelParameters(); + let parameters = new DVModelParameters() as Record | matrix4.Matrix4Transit>; parameters['marginLeft'] = left; parameters['marginTop'] = top; parameters['width'] = width; @@ -94,22 +96,37 @@ export class FlutterMutatorView { let paths = this.mutatorsStack.getFinalClippingPaths(); let rects = this.mutatorsStack.getFinalClippingRects(); let matrix = this.mutatorsStack.getFinalMatrix(); + let params = this.model.params as Record | matrix4.Matrix4Transit>; if (!paths.isEmpty()) { let path = paths.getLast(); - this.model.params["pathWidth"] = path.width; - this.model.params["pathHeight"] = path.height; - this.model.params["pathCommands"] = path.commands; + params.pathWidth = path.width; + params.pathHeight = path.height; + params.pathCommands = path.commands; } if (!rects.isEmpty()) { let rect = rects.getLast(); - this.model.params["rectWidth"] = rect.width; - this.model.params["rectHeight"] = rect.height; - this.model.params["rectRadius"] = rect.radius; + params.rectWidth = rect.width; + params.rectHeight = rect.height; + params.rectRadius = rect.radius; } - this.model.params["matrix"] = matrix; + params.matrix = matrix; } public getDvModel(): DVModel { return this.model; } -} \ No newline at end of file +} + +class DVModelParam { + compType: string + children: [] + attributes: ESObject + events: ESObject + + constructor(compType: string, children: [], attributes: ESObject, events: ESObject) { + this.compType = compType; + this.children = children; + this.attributes = attributes; + this.events = events; + } +}; \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets index b93b7b14b5..947ccef4ba 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityControlSurface.ets @@ -23,5 +23,5 @@ export default interface ActivityControlSurface { detachFromAbility(): void; onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; onWindowFocusChanged(hasFocus: boolean): void; - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult; + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult; } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets index 613b69e0f4..349010b14e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding.ets @@ -72,7 +72,7 @@ export interface NewWantListener { * ohos.app.ability.UIAbility}. */ export interface WindowFocusChangedListener { - onWindowFocusChanged(hasFocus): void; + onWindowFocusChanged(hasFocus: boolean): void; } export interface OnSaveStateListener { @@ -80,5 +80,5 @@ export interface OnSaveStateListener { * Invoked when the associated {@code UIAbility} or {@code Fragment} executes {@link * Activity#onSaveState(Bundle)}. */ - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult; + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult; } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/AccessibilityChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/AccessibilityChannel.ets index 6c930e1e74..ed96f236fb 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,15 +20,14 @@ import HashMap from '@ohos.util.HashMap'; import FlutterNapi, {AccessibilityDelegate} from '../FlutterNapi'; import { Action } from '../../../view/AccessibilityBridge' import StandardMessageCodec from '../../../plugin/common/StandardMessageCodec'; -import { MethodCallHandler } from '../../../plugin/common/MethodChannel'; /** * 辅助功能channel */ -export default class AccessibilityChannel implements MessageHandler{ +export default class AccessibilityChannel implements MessageHandler{ private static TAG = "AccessibilityChannel"; private static CHANNEL_NAME = "flutter/accessibility"; - private channel: BasicMessageChannel; + private channel: BasicMessageChannel; private flutterNapi: FlutterNapi; private handler: AccessibilityMessageHandler; private nextReplyId: number = 1; @@ -39,9 +38,9 @@ export default class AccessibilityChannel implements MessageHandler{ reply.reply(null); return; } - let annotatedEvent: HashMap = message as HashMap; + let annotatedEvent: HashMap = message as HashMap; let type: string = annotatedEvent.get("type") as string; - let data: HashMap = annotatedEvent.get("data") as HashMap; + let data: HashMap = annotatedEvent.get("data") as HashMap; Log.i(AccessibilityChannel.TAG, "Received " + type + " message."); switch (type) { @@ -83,7 +82,7 @@ export default class AccessibilityChannel implements MessageHandler{ constructor(dartExecutor: DartExecutor, flutterNapi: FlutterNapi) { Log.i(AccessibilityChannel.TAG, "Channel entered"); - this.channel = new BasicMessageChannel(dartExecutor, AccessibilityChannel.CHANNEL_NAME, StandardMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel(dartExecutor, AccessibilityChannel.CHANNEL_NAME, StandardMessageCodec.INSTANCE); this.channel.setMessageHandler(this); this.flutterNapi = flutterNapi; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets index d397f363bc..8ac0e08bf3 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/KeyEventChannel.ets @@ -26,7 +26,7 @@ export default class KeyEventChannel { private channel : BasicMessageChannel>; constructor(binaryMessenger: BinaryMessenger) { - this.channel = new BasicMessageChannel(binaryMessenger, KeyEventChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel>(binaryMessenger, KeyEventChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); } sendFlutterKeyEvent(keyEvent: FlutterKeyEvent, diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/MouseCursorChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/MouseCursorChannel.ets index b6f1c89984..210a7510a4 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 @@ -41,7 +41,7 @@ export default class MouseCursorChannel implements MethodCallHandler { // More methods are expected to be added here, hence the switch. switch (method) { case "activateSystemCursor": - let argument: HashMap = call.args; + let argument: HashMap = call.args; let kind: string = argument.get("kind"); try { this.mouseCursorMethodHandler.activateSystemCursor(kind); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets index 6d591e818f..f7ebcb6926 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/NavigationChannel.ets @@ -27,11 +27,7 @@ export default class NavigationChannel { this.channel = new MethodChannel(dartExecutor, "flutter/navigation", JSONMethodCodec.INSTANCE); // Provide a default handler that returns an empty response to any messages // on this channel. - this.channel.setMethodCallHandler({ - onMethodCall(call: MethodCall, result: MethodResult): void { - result.success(null); - } - }); + this.channel.setMethodCallHandler(new NavigationCallback()); } setInitialRoute(initialRoute: string): void { @@ -46,9 +42,7 @@ export default class NavigationChannel { pushRouteInformation(route: string): void { Log.i(NavigationChannel.TAG, "Sending message to push route information '" + route + "'"); - this.channel.invokeMethod("pushRouteInformation", { - "location": route - }); + this.channel.invokeMethod("pushRouteInformation", new Map().set("location", route) ); } popRoute(): void { @@ -59,4 +53,10 @@ export default class NavigationChannel { setMethodCallHandler(handler: MethodCallHandler) { this.channel.setMethodCallHandler(handler); } +} + +class NavigationCallback implements MethodCallHandler { + onMethodCall(call: MethodCall, result: MethodResult) { + result.success(null); + } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets index aeb7a8c5e1..20e8db4b44 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformChannel.ets @@ -15,7 +15,7 @@ import JSONMethodCodec from '../../../plugin/common/JSONMethodCodec'; import MethodCall from '../../../plugin/common/MethodCall'; -import MethodChannel, { MethodResult } from '../../../plugin/common/MethodChannel'; +import MethodChannel, { MethodCallHandler, MethodResult } from '../../../plugin/common/MethodChannel'; import Log from '../../../util/Log'; import DartExecutor from '../dart/DartExecutor'; import pasteboard from '@ohos.pasteboard'; @@ -30,145 +30,9 @@ export default class PlatformChannel { constructor(dartExecutor: DartExecutor) { this.channel = new MethodChannel(dartExecutor, PlatformChannel.CHANNEL_NAME, JSONMethodCodec.INSTANCE); - this.channel.setMethodCallHandler({ - onMethodCall: (call: MethodCall, result: MethodResult): void => { - if (this.platformMessageHandler == null) { - Log.w(PlatformChannel.TAG,"platformMessageHandler is null"); - return; - } - - let method: string = call.method; - let args: any = call.args; - Log.d(PlatformChannel.TAG, "Received '" + method + "' message."); - try { - switch (method) { - case "SystemSound.play": - break; - case "HapticFeedback.vibrate": - try { - Log.d(PlatformChannel.TAG, "HapticFeedback: "+args as string); - let feedbackType: HapticFeedbackType = this.getFeedbackTypeFromValue(args as string); - this.platformMessageHandler.vibrateHapticFeedback(feedbackType); - result.success(null); - } catch(e) { - Log.e(PlatformChannel.TAG, "HapticFeedback.vibrate error:" + JSON.stringify(e)); - } - break; - case "SystemChrome.setPreferredOrientations": - Log.d(PlatformChannel.TAG, "setPreferredOrientations: "+JSON.stringify(args)); - try { - let ohosOrientation = this.decodeOrientations(args as string[]); - this.platformMessageHandler.setPreferredOrientations(ohosOrientation); - result.success(null); - } catch (err) { - Log.e(PlatformChannel.TAG, "setPreferredOrientations err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - - break; - case "SystemChrome.setApplicationSwitcherDescription": - Log.d(PlatformChannel.TAG, "setApplicationSwitcherDescription: "+JSON.stringify(args)); - break; - case "SystemChrome.setEnabledSystemUIOverlays": - try { - let overlays: SystemUiOverlay[] = this.decodeSystemUiOverlays(args); - Log.d(PlatformChannel.TAG,"overlays: " + overlays); - this.platformMessageHandler.showSystemOverlays(overlays); - result.success(null); - } catch (err) { - Log.e(PlatformChannel.TAG, "setEnabledSystemUIOverlays err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - break; - case "SystemChrome.setEnabledSystemUIMode": - try{ - Log.d(PlatformChannel.TAG,"setEnabledSystemUIMode args:" + args as string); - let mode: SystemUiMode = this.decodeSystemUiMode(args as string) - this.platformMessageHandler.showSystemUiMode(mode); - } catch (err) { - Log.e(PlatformChannel.TAG, "setEnabledSystemUIMode err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - break; - case "SystemChrome.setSystemUIChangeListener": - this.platformMessageHandler.setSystemUiChangeListener(); - result.success(null); - break; - case "SystemChrome.restoreSystemUIOverlays": - this.platformMessageHandler.restoreSystemUiOverlays(); - result.success(null); - break; - case "SystemChrome.setSystemUIOverlayStyle": - try { - Log.d(PlatformChannel.TAG, "setSystemUIOverlayStyle asrgs: " + JSON.stringify(args)); - let systemChromeStyle: SystemChromeStyle = this.decodeSystemChromeStyle(args); - this.platformMessageHandler.setSystemUiOverlayStyle(systemChromeStyle); - result.success(null); - } catch (err) { - Log.e(PlatformChannel.TAG, "setSystemUIOverlayStyle err:" + JSON.stringify(err)); - result.error("error", JSON.stringify(err), null); - } - break; - case "SystemNavigator.pop": - this.platformMessageHandler.popSystemNavigator(); - result.success(null); - break; - case "Clipboard.getData": - let contentFormatName: string = args as string; - let clipboardFormat: ClipboardContentFormat = null; - if(contentFormatName != null) { - try{ - clipboardFormat = this.getClipboardContentFormatFromValue(contentFormatName); - } catch (err) { - Log.d(PlatformChannel.TAG, "No such clipboard content format: " + contentFormatName); - result.error("error", "No such clipboard content format: " + contentFormatName, null); - } - } - - let pasteBoard = pasteboard.getSystemPasteboard(); - pasteBoard.getData().then((pasteData) => { - let text = pasteData.getPrimaryText(); - let response = {text: ""}; - response.text = text; - result.success(response); - }).catch((err) => { - Log.e(PlatformChannel.TAG,"Failed to get PasteData. Cause: " + JSON.stringify(err)); - }); - break; - case "Clipboard.setData": - let clipboardContent = args.text; - this.platformMessageHandler.setClipboardData(clipboardContent); - result.success(null); - break; - case "Clipboard.hasStrings": - let hasStrings: boolean = false; - let response = {value: false}; - let systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.hasData().then((hasData) => { - if(!hasData) { - response.value = hasData; - result.success(response); - } - }).catch((err) => { - Log.e(PlatformChannel.TAG, "systemPasteboard.hasData err: " + JSON.stringify(err)); - }) - systemPasteboard.getData().then((pasteData) => { - hasStrings = pasteData.hasType(pasteboard.MIMETYPE_TEXT_PLAIN); - response.value = hasStrings; - result.success(response); - }).catch((err) => { - Log.e(PlatformChannel.TAG, "getData err: " + JSON.stringify(err)); - }) - break; - default: - result.notImplemented(); - break; - } - } catch (e) { - result.error("error", JSON.stringify(e), null); - } - } - }); + let callback = new PlatformMethodCallback(); + callback.platform = this; + this.channel.setMethodCallHandler(callback); } setPlatformMessageHandler(platformMessageHandler: PlatformMessageHandler): void { @@ -246,10 +110,18 @@ export default class PlatformChannel { } getFeedbackTypeFromValue(encodedName: string): HapticFeedbackType { - if(encodedName == null) { + if (encodedName == null) { return HapticFeedbackType.STANDARD; } - for (const feedbackType in HapticFeedbackType) { + let feedbackTypes: string[] = [ + HapticFeedbackType.STANDARD, + HapticFeedbackType.LIGHT_IMPACT, + HapticFeedbackType.MEDIUM_IMPACT, + HapticFeedbackType.HEAVY_IMPACT, + HapticFeedbackType.SELECTION_CLICK + ]; + for (let i = 0; i < feedbackTypes.length; i++) { + let feedbackType: string = feedbackTypes[i]; if ( (HapticFeedbackType[feedbackType] == encodedName) || (HapticFeedbackType[feedbackType] == null && encodedName == null) @@ -257,18 +129,22 @@ export default class PlatformChannel { return HapticFeedbackType[feedbackType]; } } - Log.e(PlatformChannel.TAG,"No such HapticFeedbackType:" + encodedName); + Log.e(PlatformChannel.TAG, "No such HapticFeedbackType:" + encodedName); } getClipboardContentFormatFromValue(encodedName: string): ClipboardContentFormat { - for (const format in ClipboardContentFormat) { + let clipboardFormats : string[]= [ClipboardContentFormat.PLAIN_TEXT]; + for (let i = 0; i < clipboardFormats.length; i++) { + let format = clipboardFormats[i]; if (ClipboardContentFormat[format] === encodedName) { return ClipboardContentFormat[format]; } } } getSystemUiOverlayFromValue(encodedName: string): SystemUiOverlay { - for (const overlay in SystemUiOverlay) { + let systemUiOverlays : string[] = [SystemUiOverlay.TOP_OVERLAYS, SystemUiOverlay.BOTTOM_OVERLAYS]; + for (let i = 0; i < systemUiOverlays.length; i++) { + let overlay = systemUiOverlays[i]; if (SystemUiOverlay[overlay] === encodedName) { return SystemUiOverlay[overlay]; } @@ -276,41 +152,38 @@ export default class PlatformChannel { throw new Error("No such SystemUiOverlay: " + encodedName); } - private decodeSystemUiOverlays(encodedSystemUiOverlay: any): SystemUiOverlay[] { - let overlays: SystemUiOverlay[] = []; - for(let i = 0; i < encodedSystemUiOverlay.length; i++) { - const encodedOverlay = encodedSystemUiOverlay[i]; - const overlay = this.getSystemUiOverlayFromValue(encodedOverlay); - switch (overlay) { - case SystemUiOverlay.TOP_OVERLAYS: - overlays.push(SystemUiOverlay.TOP_OVERLAYS); - break; - case SystemUiOverlay.BOTTOM_OVERLAYS: - overlays.push(SystemUiOverlay.BOTTOM_OVERLAYS); - break; - } - } - return overlays; - } - getSystemUiModeFromValue(encodedName: string): SystemUiMode { - for (const mode in SystemUiMode) { + let systemUiModes : string[] = [ + SystemUiMode.LEAN_BACK, SystemUiMode.IMMERSIVE, + SystemUiMode.IMMERSIVE_STICKY, SystemUiMode.EDGE_TO_EDGE + ]; + for (let i = 0; i < systemUiModes.length; i++) { + let mode = systemUiModes[i]; if (SystemUiMode[mode] === encodedName) { return SystemUiMode[mode]; } } throw new Error("No such SystemUiOverlay: " + encodedName); } + getBrightnessFromValue(encodedName: string): Brightness { - for (const brightness in Brightness) { + let brightnesses : string[] = [Brightness.LIGHT, Brightness.DARK]; + for (let i = 0; i < brightnesses.length; i++) { + let brightness = brightnesses[i]; if (Brightness[brightness] === encodedName) { return Brightness[brightness]; } } throw new Error("No such Brightness: " + encodedName); } + getDeviceOrientationFromValue(encodedName: string): DeviceOrientation { - for (const orientation in DeviceOrientation) { + let deviceOrientations: string[] = [ + DeviceOrientation.PORTRAIT_UP, DeviceOrientation.PORTRAIT_DOWN, + DeviceOrientation.LANDSCAPE_LEFT, DeviceOrientation.LANDSCAPE_RIGHT + ]; + for (let i = 0; i < deviceOrientations.length; i++) { + let orientation = deviceOrientations[i]; if (DeviceOrientation[orientation] === encodedName) { return DeviceOrientation[orientation]; } @@ -318,65 +191,8 @@ export default class PlatformChannel { throw new Error("No such DeviceOrientation: " + encodedName); } - private decodeSystemUiMode(encodedSystemUiMode: string): SystemUiMode { - let mode: SystemUiMode = this.getSystemUiModeFromValue(encodedSystemUiMode); - switch (mode) { - case SystemUiMode.LEAN_BACK: - return SystemUiMode.LEAN_BACK; - case SystemUiMode.IMMERSIVE: - return SystemUiMode.IMMERSIVE; - case SystemUiMode.IMMERSIVE_STICKY: - return SystemUiMode.IMMERSIVE_STICKY; - case SystemUiMode.EDGE_TO_EDGE: - return SystemUiMode.EDGE_TO_EDGE; - } - return SystemUiMode.EDGE_TO_EDGE; - - } - - private decodeSystemChromeStyle(encodedStyle: any): SystemChromeStyle { - let statusBarColor: number = null; - let statusBarIconBrightness: Brightness = null; - let systemStatusBarContrastEnforced: boolean = null; - let systemNavigationBarColor: number = null; - let systemNavigationBarIconBrightness: Brightness = null; - let systemNavigationBarDividerColor: number = null; - let systemNavigationBarContrastEnforced: boolean = null; - if(encodedStyle.statusBarColor != null) { - statusBarColor = encodedStyle.statusBarColor as number; - } - if(encodedStyle.statusBarIconBrightness != null) { - statusBarIconBrightness = - this.getBrightnessFromValue(encodedStyle.statusBarIconBrightness as string); - } - if(encodedStyle.systemStatusBarContrastEnforced != null) { - systemStatusBarContrastEnforced = encodedStyle.systemStatusBarContrastEnforced as boolean; - } - if(encodedStyle.systemNavigationBarColor != null) { - systemNavigationBarColor = encodedStyle.systemNavigationBarColor as number; - } - if(encodedStyle.systemNavigationBarIconBrightness != null) { - systemNavigationBarIconBrightness = - this.getBrightnessFromValue(encodedStyle.systemNavigationBarIconBrightness as string); - } - if(encodedStyle.systemNavigationBarDividerColor != null) { - systemNavigationBarDividerColor = encodedStyle.systemNavigationBarDividerColor as number; - } - if(encodedStyle.systemNavigationBarContrastEnforced != null) { - systemNavigationBarContrastEnforced = encodedStyle.systemNavigationBarContrastEnforced as boolean; - } - return new SystemChromeStyle( - statusBarColor, - statusBarIconBrightness, - systemStatusBarContrastEnforced, - systemNavigationBarColor, - systemNavigationBarIconBrightness, - systemNavigationBarDividerColor, - systemNavigationBarContrastEnforced - ); - } - } + export enum HapticFeedbackType { STANDARD = "STANDARD", LIGHT_IMPACT = "HapticFeedbackType.lightImpact", @@ -411,7 +227,6 @@ export interface PlatformMessageHandler { setClipboardData(text: string): void; clipboardHasStrings(): boolean; - } export enum ClipboardContentFormat { @@ -481,4 +296,210 @@ enum DeviceOrientation { PORTRAIT_DOWN = "DeviceOrientation.portraitDown", LANDSCAPE_LEFT = "DeviceOrientation.landscapeLeft", LANDSCAPE_RIGHT = "DeviceOrientation.landscapeRight", -} \ No newline at end of file +} + +class PlatformMethodCallback implements MethodCallHandler { + private static TAG = "PlatformMethodCallback" + platform: PlatformChannel; + + onMethodCall(call: MethodCall, result: MethodResult) { + if (this.platform.platformMessageHandler == null) { + Log.w(PlatformMethodCallback.TAG, "platformMessageHandler is null"); + return; + } + + let method: string = call.method; + let args: ESObject = call.args; + Log.d(PlatformMethodCallback.TAG, "Received '" + method + "' message."); + try { + switch (method) { + case "SystemSound.play": + break; + case "HapticFeedback.vibrate": + try { + Log.d(PlatformMethodCallback.TAG, "HapticFeedback: " + args as string); + let feedbackType: HapticFeedbackType = this.platform.getFeedbackTypeFromValue(args as string); + this.platform.platformMessageHandler.vibrateHapticFeedback(feedbackType); + result.success(null); + } catch (e) { + Log.e(PlatformMethodCallback.TAG, "HapticFeedback.vibrate error:" + JSON.stringify(e)); + } + break; + case "SystemChrome.setPreferredOrientations": + Log.d(PlatformMethodCallback.TAG, "setPreferredOrientations: " + JSON.stringify(args)); + try { + let ohosOrientation = this.platform.decodeOrientations(args as string[]); + this.platform.platformMessageHandler.setPreferredOrientations(ohosOrientation); + result.success(null); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setPreferredOrientations err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + + break; + case "SystemChrome.setApplicationSwitcherDescription": + Log.d(PlatformMethodCallback.TAG, "setApplicationSwitcherDescription: " + JSON.stringify(args)); + break; + case "SystemChrome.setEnabledSystemUIOverlays": + try { + let overlays: SystemUiOverlay[] = this.decodeSystemUiOverlays(args); + Log.d(PlatformMethodCallback.TAG, "overlays: " + overlays); + this.platform.platformMessageHandler.showSystemOverlays(overlays); + result.success(null); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setEnabledSystemUIOverlays err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + break; + case "SystemChrome.setEnabledSystemUIMode": + try { + Log.d(PlatformMethodCallback.TAG, "setEnabledSystemUIMode args:" + args as string); + let mode: SystemUiMode = this.decodeSystemUiMode(args as string) + this.platform.platformMessageHandler.showSystemUiMode(mode); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setEnabledSystemUIMode err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + break; + case "SystemChrome.setSystemUIChangeListener": + this.platform.platformMessageHandler.setSystemUiChangeListener(); + result.success(null); + break; + case "SystemChrome.restoreSystemUIOverlays": + this.platform.platformMessageHandler.restoreSystemUiOverlays(); + result.success(null); + break; + case "SystemChrome.setSystemUIOverlayStyle": + try { + Log.d(PlatformMethodCallback.TAG, "setSystemUIOverlayStyle asrgs: " + JSON.stringify(args)); + let systemChromeStyle: SystemChromeStyle = this.decodeSystemChromeStyle(args); + this.platform.platformMessageHandler.setSystemUiOverlayStyle(systemChromeStyle); + result.success(null); + } catch (err) { + Log.e(PlatformMethodCallback.TAG, "setSystemUIOverlayStyle err:" + JSON.stringify(err)); + result.error("error", JSON.stringify(err), null); + } + break; + case "SystemNavigator.pop": + this.platform.platformMessageHandler.popSystemNavigator(); + result.success(null); + break; + case "Clipboard.getData": + let pasteBoard = pasteboard.getSystemPasteboard(); + pasteBoard.getData().then((pasteData) => { + let text = pasteData.getPrimaryText(); + let response: ESObject = new Map().set("text", ""); + response.text = text; + result.success(response); + }).catch((err: ESObject) => { + Log.e(PlatformMethodCallback.TAG, "Failed to get PasteData. Cause: " + JSON.stringify(err)); + }); + break; + case "Clipboard.setData": + let clipboardContent: string = args.text; + this.platform.platformMessageHandler.setClipboardData(clipboardContent); + result.success(null); + break; + case "Clipboard.hasStrings": + let hasStrings: boolean = false; + let response: ESObject = new Map().set("value", false); + let systemPasteboard = pasteboard.getSystemPasteboard(); + systemPasteboard.hasData().then((hasData) => { + if (!hasData) { + response.value = hasData; + result.success(response); + } + }).catch((err: ESObject) => { + Log.e(PlatformMethodCallback.TAG, "systemPasteboard.hasData err: " + JSON.stringify(err)); + }) + systemPasteboard.getData().then((pasteData) => { + hasStrings = pasteData.hasType(pasteboard.MIMETYPE_TEXT_PLAIN); + response.value = hasStrings; + result.success(response); + }).catch((err: ESObject) => { + Log.e(PlatformMethodCallback.TAG, "getData err: " + JSON.stringify(err)); + }) + break; + default: + result.notImplemented(); + break; + } + } catch (e) { + result.error("error", JSON.stringify(e), null); + } + } + + private decodeSystemUiOverlays(encodedSystemUiOverlay: string[]): SystemUiOverlay[] { + let overlays: SystemUiOverlay[] = []; + for(let i = 0; i < encodedSystemUiOverlay.length; i++) { + const encodedOverlay = encodedSystemUiOverlay[i]; + const overlay = this.platform.getSystemUiOverlayFromValue(encodedOverlay); + switch (overlay) { + case SystemUiOverlay.TOP_OVERLAYS: + overlays.push(SystemUiOverlay.TOP_OVERLAYS); + break; + case SystemUiOverlay.BOTTOM_OVERLAYS: + overlays.push(SystemUiOverlay.BOTTOM_OVERLAYS); + break; + } + } + return overlays; + } + + private decodeSystemUiMode(encodedSystemUiMode: string): SystemUiMode { + let mode: SystemUiMode = this.platform.getSystemUiModeFromValue(encodedSystemUiMode); + switch (mode) { + case SystemUiMode.LEAN_BACK: + return SystemUiMode.LEAN_BACK; + case SystemUiMode.IMMERSIVE: + return SystemUiMode.IMMERSIVE; + case SystemUiMode.IMMERSIVE_STICKY: + return SystemUiMode.IMMERSIVE_STICKY; + case SystemUiMode.EDGE_TO_EDGE: + default: + return SystemUiMode.EDGE_TO_EDGE; + } + } + + private decodeSystemChromeStyle(encodedStyle: ESObject): SystemChromeStyle { + let statusBarColor: number = null; + let statusBarIconBrightness: Brightness = null; + let systemStatusBarContrastEnforced: boolean = null; + let systemNavigationBarColor: number = null; + let systemNavigationBarIconBrightness: Brightness = null; + let systemNavigationBarDividerColor: number = null; + let systemNavigationBarContrastEnforced: boolean = null; + if(encodedStyle.statusBarColor != null) { + statusBarColor = encodedStyle.statusBarColor as number; + } + if(encodedStyle.statusBarIconBrightness != null) { + statusBarIconBrightness = + this.platform.getBrightnessFromValue(encodedStyle.statusBarIconBrightness as string); + } + if(encodedStyle.systemStatusBarContrastEnforced != null) { + systemStatusBarContrastEnforced = encodedStyle.systemStatusBarContrastEnforced as boolean; + } + if(encodedStyle.systemNavigationBarColor != null) { + systemNavigationBarColor = encodedStyle.systemNavigationBarColor as number; + } + if(encodedStyle.systemNavigationBarIconBrightness != null) { + systemNavigationBarIconBrightness = + this.platform.getBrightnessFromValue(encodedStyle.systemNavigationBarIconBrightness as string); + } + if(encodedStyle.systemNavigationBarDividerColor != null) { + systemNavigationBarDividerColor = encodedStyle.systemNavigationBarDividerColor as number; + } + if(encodedStyle.systemNavigationBarContrastEnforced != null) { + systemNavigationBarContrastEnforced = encodedStyle.systemNavigationBarContrastEnforced as boolean; + } + return new SystemChromeStyle( + statusBarColor, + statusBarIconBrightness, + systemStatusBarContrastEnforced, + systemNavigationBarColor, + systemNavigationBarIconBrightness, + systemNavigationBarDividerColor, + systemNavigationBarContrastEnforced + ); + } +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets index cd717faa54..564a6df4c4 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/PlatformViewsChannel.ets @@ -21,10 +21,11 @@ import Log from '../../../util/Log'; import DartExecutor from '../dart/DartExecutor'; const TAG = "PlatformViewsChannel"; - +const NON_TEXTURE_FALLBACK = -2; export default class PlatformViewsChannel { private channel: MethodChannel; private handler: PlatformViewsHandler; + private parsingHandler = new ParsingCallback(); /** * Constructs a {@code PlatformViewsChannel} that connects Android to the Dart code running in @@ -36,6 +37,7 @@ export default class PlatformViewsChannel { */ constructor(dartExecutor: DartExecutor) { this.channel = new MethodChannel(dartExecutor, "flutter/platform_views", StandardMethodCodec.INSTANCE); + this.parsingHandler.platformChannel = this; this.channel.setMethodCallHandler(this.parsingHandler); } @@ -45,6 +47,7 @@ export default class PlatformViewsChannel { */ public setPlatformViewsHandler(handler: PlatformViewsHandler): void { this.handler = handler; + this.parsingHandler.handler = handler; } public invokeViewFocused(viewId: number): void { @@ -54,54 +57,8 @@ export default class PlatformViewsChannel { this.channel.invokeMethod("viewFocused", viewId); } - private parsingHandler: MethodCallHandler = { - onMethodCall: (call: MethodCall, result: MethodResult): void => { - if (this.handler == null) { - return; - } - - Log.i(TAG, "Received '" + call.method + "' message."); - switch (call.method) { - case "create": { - this.create(call, result); - break; - } - case "dispose": { - this.dispose(call, result); - break; - } - case "resize": { - this.resize(call, result); - break; - } - case "offset": { - this.offset(call, result); - break; - } - case "touch": { - this.touch(call, result); - break; - } - case "setDirection": { - this.setDirection(call, result); - break; - } - case "clearFocus": { - this.clearFocus(call, result); - break; - } - case "synchronizeToNativeViewHierarchy": { - this.synchronizeToNativeViewHierarchy(call, result); - break; - } - default: - result.notImplemented(); - } - } - } - create(call: MethodCall, result: MethodResult): void { - const createArgs: Map = call.args; + const createArgs: Map = call.args; const usesPlatformViewLayer: boolean = createArgs.has("hybrid") && createArgs.get("hybrid") as boolean; const additionalParams: ByteBuffer = createArgs.has("params") ? createArgs.get("params") : null; @@ -153,7 +110,7 @@ export default class PlatformViewsChannel { d:${request.direction}`); const textureId = this.handler.createForTextureLayer(request); - if (textureId == PlatformViewsHandler.NON_TEXTURE_FALLBACK) { + if (textureId == NON_TEXTURE_FALLBACK) { if (!hybridFallback) { throw new Error( "Platform view attempted to fall back to hybrid mode when not requested."); @@ -172,7 +129,7 @@ export default class PlatformViewsChannel { } dispose(call: MethodCall, result: MethodResult): void { - const disposeArgs: Map = call.args; + const disposeArgs: Map = call.args; const viewId: number = disposeArgs.get("id"); try { this.handler.dispose(viewId); @@ -184,25 +141,16 @@ export default class PlatformViewsChannel { } resize(call: MethodCall, result: MethodResult): void { - const resizeArgs: Map = call.args; + const resizeArgs: Map = call.args; const resizeRequest: PlatformViewResizeRequest = new PlatformViewResizeRequest( resizeArgs.get("id"), resizeArgs.get("width"), resizeArgs.get("height") ); try { - this.handler.resize(resizeRequest, { - run: (bufferSize: PlatformViewBufferSize) => { - if (bufferSize == null) { - result.error("error", "Failed to resize the platform view", null); - } else { - const response: Map = new Map(); - response.set("width", bufferSize.width); - response.set("height", bufferSize.height); - result.success(response); - } - } - }) + let resizeCallback = new ResizeCallback(); + resizeCallback.result = result; + this.handler.resize(resizeRequest, resizeCallback); } catch (err) { Log.e(TAG, "resize failed", err); result.error("error", err, null); @@ -210,7 +158,7 @@ export default class PlatformViewsChannel { } offset(call: MethodCall, result: MethodResult): void { - const offsetArgs: Map = call.args; + const offsetArgs: Map = call.args; try { this.handler.offset( offsetArgs.get("id"), @@ -224,7 +172,7 @@ export default class PlatformViewsChannel { } touch(call: MethodCall, result: MethodResult): void { - const args: Array = call.args; + const args: Array = call.args; let index = 0; const touch: PlatformViewTouch = new PlatformViewTouch( args[index++], @@ -255,7 +203,7 @@ export default class PlatformViewsChannel { } setDirection(call: MethodCall, result: MethodResult): void { - const setDirectionArgs: Map = call.args; + const setDirectionArgs: Map = call.args; const newDirectionViewId: number = setDirectionArgs.get("id"); const direction: number = setDirectionArgs.get("direction"); @@ -298,7 +246,7 @@ export default class PlatformViewsChannel { *

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

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

This is done to syncronize the rendering of the PlatformView and the FlutterView. Defaults * to true. */ - abstract synchronizeToNativeViewHierarchy(yes: boolean): void; + synchronizeToNativeViewHierarchy(yes: boolean): void; } /** Platform view display modes that can be requested at creation time. */ @@ -480,10 +427,10 @@ export class PlatformViewTouch { public pointerCount: number; /** Properties for each pointer, encoded in a raw format. */ - public rawPointerPropertiesList: any; + public rawPointerPropertiesList: ESObject; /** Coordinates for each pointer, encoded in a raw format. */ - public rawPointerCoords: any; + public rawPointerCoords: ESObject; public metaState: number; @@ -510,8 +457,8 @@ export class PlatformViewTouch { eventTime: number, action: number, pointerCount: number, - rawPointerPropertiesList: any, - rawPointerCoords: any, + rawPointerPropertiesList: ESObject, + rawPointerCoords: ESObject, metaState: number, buttonState: number, xPrecision: number, @@ -538,4 +485,67 @@ export class PlatformViewTouch { this.flags = flags; this.motionEventId = motionEventId; } +} + +class ParsingCallback implements MethodCallHandler { + platformChannel : PlatformViewsChannel; + handler: PlatformViewsHandler; + + onMethodCall(call: MethodCall, result: MethodResult) { + if (this.handler == null) { + return; + } + + Log.i(TAG, "Received '" + call.method + "' message."); + switch (call.method) { + case "create": { + this.platformChannel.create(call, result); + break; + } + case "dispose": { + this.platformChannel.dispose(call, result); + break; + } + case "resize": { + this.platformChannel.resize(call, result); + break; + } + case "offset": { + this.platformChannel.offset(call, result); + break; + } + case "touch": { + this.platformChannel.touch(call, result); + break; + } + case "setDirection": { + this.platformChannel.setDirection(call, result); + break; + } + case "clearFocus": { + this.platformChannel.clearFocus(call, result); + break; + } + case "synchronizeToNativeViewHierarchy": { + this.platformChannel.synchronizeToNativeViewHierarchy(call, result); + break; + } + default: + result.notImplemented(); + } + } +} + +class ResizeCallback extends PlatformViewBufferResized { + result : MethodResult; + run(bufferSize: PlatformViewBufferSize) { + if (bufferSize == null) { + this.result.error("error", "Failed to resize the platform view", null); + } else { + const response: Map = new Map(); + response.set("width", bufferSize.width); + response.set("height", bufferSize.height); + this.result.success(response); + } + } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/RestorationChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/RestorationChannel.ets index 2d4440cdbb..bcf53050d5 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 @@ -58,11 +58,12 @@ export default class RestorationChannel { // Holds the most current restoration data which may have been provided by the engine // via "setRestorationData" or by the framework via the method channel. This is the data the // framework should be restored to in case the app is terminated. - private restorationData: Uint8Array; + private restorationData: Uint8Array = new Uint8Array(); private channel: MethodChannel; private pendingFrameworkRestorationChannelRequest: MethodResult; private engineHasProvidedData: boolean = false; private frameworkHasRequestedData: boolean = false; + private handler: MethodCallHandler = new RestorationChannelMethodCallHandler(this.restorationData); constructor(channelOrExecutor: MethodChannel | DartExecutor, waitForRestorationData: boolean) { if (channelOrExecutor instanceof MethodChannel) { @@ -84,7 +85,7 @@ export default class RestorationChannel { this.engineHasProvidedData = true; if (this.pendingFrameworkRestorationChannelRequest != null) { // If their is a pending request from the framework, answer it. - this.pendingFrameworkRestorationChannelRequest.success(this.packageData(data)); + this.pendingFrameworkRestorationChannelRequest.success(RestorationChannelMethodCallHandler.packageData(data)); this.pendingFrameworkRestorationChannelRequest = null; this.restorationData = data; } else if (this.frameworkHasRequestedData) { @@ -93,12 +94,12 @@ export default class RestorationChannel { // framework retrieved the restoration state before it was set via this method. // Experimentally, this can also be used to restore a previously used engine to another state, // e.g. when the engine is attached to a new activity. - this.channel.invokeMethod("push", this.packageData(data), { - success: (result: any) :void => { + this.channel.invokeMethod("push", RestorationChannelMethodCallHandler.packageData(data), { + success: (result: ESObject) :void => { this.restorationData = data; }, - error: (errorCode: string, errorMessage: string, errorDetails: any) :void => { + error: (errorCode: string, errorMessage: string, errorDetails: ESObject) :void => { Log.e(RestorationChannel.TAG, "Error " + errorCode + " while sending restoration data to framework: " + errorMessage); }, @@ -122,40 +123,51 @@ export default class RestorationChannel { clearData() { this.restorationData = null; } +} - private handler: MethodCallHandler = { - onMethodCall: (call: MethodCall, result: MethodResult) :void => { - const method = call.method; - const args = call.args; - switch (method) { - case "put": { - this.restorationData = args; - result.success(null); - break; - } - case "get": { - this.frameworkHasRequestedData = true; - if (this.engineHasProvidedData || !this.waitForRestorationData) { - result.success(this.packageData(this.restorationData)); - // Do not delete the restoration data on the engine side after sending it to the - // framework. We may need to hand this data back to the operating system if the - // framework never modifies the data (and thus doesn't send us any - // data back). - } else { - this.pendingFrameworkRestorationChannelRequest = result; - } - break; - } - default: { - result.notImplemented(); - break; +class RestorationChannelMethodCallHandler implements MethodCallHandler { + public waitForRestorationData: boolean; + private restorationData: Uint8Array; + private engineHasProvidedData: boolean = false; + private frameworkHasRequestedData: boolean = false; + private channel: MethodChannel; + private pendingFrameworkRestorationChannelRequest: MethodResult; + + constructor(restorationData: Uint8Array) { + this.restorationData = restorationData; + } + + onMethodCall(call: MethodCall, result: MethodResult): void { + const method = call.method; + const args: ESObject = call.args; + switch (method) { + case "put": { + this.restorationData = args; + result.success(null); + break; + } + case "get": { + this.frameworkHasRequestedData = true; + if (this.engineHasProvidedData || !this.waitForRestorationData) { + result.success(RestorationChannelMethodCallHandler.packageData(this.restorationData)); + // Do not delete the restoration data on the engine side after sending it to the + // framework. We may need to hand this data back to the operating system if the + // framework never modifies the data (and thus doesn't send us any + // data back). + } else { + this.pendingFrameworkRestorationChannelRequest = result; } + break; + } + default: { + result.notImplemented(); + break; } } - }; + } - private packageData(data: Uint8Array): Map { - const packaged: Map = new Map(); + static packageData(data: Uint8Array): Map { + const packaged: Map = new Map(); packaged.set("enabled", true); packaged.set("data", data); return packaged; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets index 2b5021ca20..b40cd5536a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SettingsChannel.ets @@ -35,7 +35,7 @@ export default class SettingsChannel { private channel: BasicMessageChannel; constructor(dartExecutor: DartExecutor) { - this.channel = new BasicMessageChannel(dartExecutor, SettingsChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel(dartExecutor, SettingsChannel.CHANNEL_NAME, JSONMessageCodec.INSTANCE); } startMessage(): MessageBuilder { @@ -84,6 +84,6 @@ class MessageBuilder { + this.message.get(ALWAYS_USE_24_HOUR_FORMAT) + "platformBrightness: " + this.message.get(PLATFORM_BRIGHTNESS)) - this.channel.send(Object.fromEntries(this.message)) + this.channel.send(this.message) } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets index ded2507910..9f9ef28154 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/SystemChannel.ets @@ -26,14 +26,12 @@ export default class SystemChannel { public channel: BasicMessageChannel; constructor(dartExecutor: DartExecutor) { - this.channel = new BasicMessageChannel(dartExecutor, "flutter/system", JSONMessageCodec.INSTANCE); + this.channel = new BasicMessageChannel(dartExecutor, "flutter/system", JSONMessageCodec.INSTANCE); } public sendMemoryPressureWarning(): void { Log.i(TAG, "Sending memory pressure warning to Flutter"); - let message: any = { - "type":"memoryPressure" - }; + let message : Map = new Map().set("type", "memoryPressure"); this.channel.send(message); } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets index 5387e7fdc3..d54c448e02 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TestChannel.ets @@ -13,7 +13,7 @@ * limitations under the License. */ -import BasicMessageChannel, { Reply } from '../../../plugin/common/BasicMessageChannel'; +import BasicMessageChannel, { MessageHandler, Reply } from '../../../plugin/common/BasicMessageChannel'; import JSONMessageCodec from '../../../plugin/common/JSONMessageCodec'; import DartExecutor from '../dart/DartExecutor'; import Log from '../../../util/Log'; @@ -25,12 +25,14 @@ export default class TestChannel { constructor(dartExecutor: DartExecutor) { this.channel = new BasicMessageChannel(dartExecutor, "flutter/test", JSONMessageCodec.INSTANCE); + let callback = new MessageCallback(); + this.channel.setMessageHandler(callback); + } +} - this.channel.setMessageHandler({ - onMessage(call: String, reply: Reply): void { - Log.d(TAG, "receive msg = " + call); - reply.reply("收到消息啦:" + call); - } - }); +class MessageCallback implements MessageHandler { + onMessage(message: string, reply: Reply) { + Log.d(TAG, "receive msg = " + message); + reply.reply("收到消息啦:" + message); } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TextInputChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/engine/systemchannels/TextInputChannel.ets index 266884717d..afdbecc982 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,73 +25,15 @@ const TAG = "TextInputChannel"; export default class TextInputChannel { private static CHANNEL_NAME = "flutter/textinput"; public channel: MethodChannel; - private textInputMethodHandler: TextInputMethodHandler; + textInputMethodHandler: TextInputMethodHandler; constructor(dartExecutor: DartExecutor) { this.channel = new MethodChannel(dartExecutor, TextInputChannel.CHANNEL_NAME, JSONMethodCodec.INSTANCE); - this.channel.setMethodCallHandler({ - onMethodCall: (call: MethodCall, result: MethodResult): void => { - if(this.textInputMethodHandler == null) { - return; - } - let method: string = call.method; - let args: any = call.args; - Log.d(TAG, "Received '" + method + "' message."); - switch (method) { - case "TextInput.show": - this.textInputMethodHandler.show(); - Log.d(TAG, "textInputMethodHandler.show()"); - result.success(null); - break; - case "TextInput.hide": - this.textInputMethodHandler.hide(); - result.success(null); - break; - case "TextInput.setClient": - const textInputClientId: number = args[0] as number; - //TODO: parse configuration - const config: Configuration = null; - this.textInputMethodHandler.setClient(textInputClientId, config); - result.success(null); - break; - case "TextInput.requestAutofill": - //TODO: requestAutofill - result.notImplemented(); - break; - case "TextInput.setPlatformViewClient": - //TODO: - result.notImplemented(); - break; - case "TextInput.setEditingState": - this.textInputMethodHandler.setEditingState(TextEditState.fromJson(args)); - result.success(null); - break; - case "TextInput.setEditableSizeAndTransform": - //TODO: - result.notImplemented(); - break; - case "TextInput.clearClient": - this.textInputMethodHandler.clearClient(); - result.success(null); - break; - case "TextInput.sendAppPrivateCommand": - //TODO: - result.notImplemented(); - break; - case "TextInput.finishAutofillContext": - //TODO: - result.notImplemented(); - break; - default: - result.notImplemented(); - break; - } - } - }); + let callback = new TextInputCallback(); + callback.textInputMethodHandler = this.textInputMethodHandler; + this.channel.setMethodCallHandler(callback); } - - setTextInputMethodHandler(textInputMethodHandler: TextInputMethodHandler): void { this.textInputMethodHandler = textInputMethodHandler; } @@ -104,15 +46,13 @@ export default class TextInputChannel { selectionStart: number, selectionEnd: number, composingStart: number, - composingEnd: number): any { - let state = { - "text": text, - "selectionBase": selectionStart, - "selectionExtent": selectionEnd, - "composingBase": composingStart, - "composingExtent": composingEnd - } - return state; + composingEnd: number): ESObject { + return new Map() + .set("text", text) + .set("selectionBase", selectionStart) + .set("selectionExtent", selectionEnd) + .set("composingBase", composingStart) + .set("composingExtent", composingEnd); } /** @@ -127,7 +67,7 @@ export default class TextInputChannel { Log.d(TAG, "updateEditingState:" + "Text: " + text + " Selection start: " + selectionStart + " Selection end: " + selectionEnd + " Composing start: " + composingStart + " Composing end: " + composingEnd); - const state: any = this.createEditingStateJSON(text, selectionStart, selectionEnd, composingStart, composingEnd); + const state: ESObject = this.createEditingStateJSON(text, selectionStart, selectionEnd, composingStart, composingEnd); this.channel.invokeMethod('TextInputClient.updateEditingState', [inputClientId, state]); Log.d(TAG,"updateEditingState end"); @@ -178,7 +118,7 @@ export default class TextInputChannel { this.channel.invokeMethod("TextInputClient.performAction", [inputClientId, "TextInputAction.commitContent"]); } - performPrivateCommand(inputClientId: number, action: string, data: any) { + performPrivateCommand(inputClientId: number, action: string, data: ESObject) { } @@ -231,9 +171,14 @@ export class Configuration { actionLabel: String, ) { } getTextCapitalizationFromValue(encodedName: string): TextCapitalization { - for (const key in TextCapitalization) { + let textKeys = [ + TextCapitalization.CHARACTERS, TextCapitalization.WORDS, + TextCapitalization.SENTENCES, TextCapitalization.NONE + ]; + for (let i = 0; i < textKeys.length; i++) { + let key = textKeys[i]; if (TextCapitalization[key] === encodedName) { - return key; + return key; } } throw new Error("No such TextCapitalization: " + encodedName); @@ -272,15 +217,22 @@ export class InputType { this.isDecimal = isDecimal; } - static fromJson(json: any): InputType { - return new InputType(this.getTextInputTypeFromValue(json.name as string), + static fromJson(json: ESObject): InputType { + return new InputType(InputType.getTextInputTypeFromValue(json.name as string), json.signed as boolean, json.decimal as boolean) } - static getTextInputTypeFromValue(encodedName: string): TextInputType{ - for(const key in TextInputType) { - if(TextInputType[key] == encodedName) { - return key; + static getTextInputTypeFromValue(encodedName: string): TextInputType { + let textKeys = [ + TextInputType.TEXT, TextInputType.DATETIME, TextInputType.NAME, + TextInputType.POSTAL_ADDRESS, TextInputType.NUMBER, TextInputType.PHONE, + TextInputType.MULTILINE, TextInputType.EMAIL_ADDRESS, TextInputType.URL, + TextInputType.VISIBLE_PASSWORD, TextInputType.NONE + ]; + for (let i = 0; i < textKeys.length; i++) { + let key = textKeys[i]; + if (TextInputType[key] == encodedName) { + return key; } } throw new Error("No such TextInputType: " + encodedName); @@ -339,7 +291,7 @@ export class TextEditState { return this.composingStart >= 0 && this.composingEnd > this.composingStart; } - static fromJson(textEditState: any): TextEditState { + static fromJson(textEditState: ESObject): TextEditState { return new TextEditState( textEditState.text, textEditState.selectionBase, @@ -348,5 +300,66 @@ export class TextEditState { textEditState.composingExtent ) } +} -} \ No newline at end of file +class TextInputCallback implements MethodCallHandler { + textInputMethodHandler: TextInputMethodHandler; + + onMethodCall(call: MethodCall, result: MethodResult) { + if (this.textInputMethodHandler == null) { + return; + } + let method: string = call.method; + let args: ESObject = call.args; + Log.d(TAG, "Received '" + method + "' message."); + switch (method) { + case "TextInput.show": + this.textInputMethodHandler.show(); + Log.d(TAG, "textInputMethodHandler.show()"); + result.success(null); + break; + case "TextInput.hide": + this.textInputMethodHandler.hide(); + result.success(null); + break; + case "TextInput.setClient": + const textInputClientId: number = args[0] as number; + //TODO: parse configuration + const config: Configuration = null; + this.textInputMethodHandler.setClient(textInputClientId, config); + result.success(null); + break; + case "TextInput.requestAutofill": + //TODO: requestAutofill + result.notImplemented(); + break; + case "TextInput.setPlatformViewClient": + //TODO: + result.notImplemented(); + break; + case "TextInput.setEditingState": + this.textInputMethodHandler.setEditingState(TextEditState.fromJson(args)); + result.success(null); + break; + case "TextInput.setEditableSizeAndTransform": + //TODO: + result.notImplemented(); + break; + case "TextInput.clearClient": + this.textInputMethodHandler.clearClient(); + result.success(null); + break; + case "TextInput.sendAppPrivateCommand": + //TODO: + result.notImplemented(); + break; + case "TextInput.finishAutofillContext": + //TODO: + result.notImplemented(); + break; + default: + result.notImplemented(); + break; + } + } +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets index dd91f36972..07a374a710 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbility.ets @@ -31,6 +31,7 @@ import { PlatformBrightness } from '../engine/systemchannels/SettingsChannel'; import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; import { DVModelContainer } from '../../view/DynamicView/dynamicView'; import { RootDvModeManager } from '../../plugin/platform/RootDvModelManager'; +import { Configuration } from '@ohos.app.ability.Configuration'; const TAG = "FlutterAbility"; /** @@ -53,10 +54,10 @@ export class FlutterAbility extends UIAbility implements Host { * 3、lifecycle.onCreate * 4. setContentView() noNeed */ - async onCreate(want, launchParam) { + async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { Log.i(TAG, "bundleCodeDir=" + this.context.bundleCodeDir); - globalThis.flutterAbility = this - this.displayInfo = display.getDefaultDisplaySync() + // globalThis.flutterAbility = this + this.displayInfo = display.getDefaultDisplaySync(); this.viewportMetrics.devicePixelRatio = this.displayInfo.densityPixels this.delegate = new FlutterAbilityDelegate(this); @@ -71,7 +72,7 @@ export class FlutterAbility extends UIAbility implements Host { } console.log('MyAbility onCreate'); - globalThis.applicationContext = this.context.getApplicationContext(); + // globalThis.applicationContext = this.context.getApplicationContext(); } onDestroy() { @@ -365,7 +366,7 @@ export class FlutterAbility extends UIAbility implements Host { } } - onConfigurationUpdated(config){ + onConfigurationUpdated(config: Configuration){ Log.i(TAG, 'onConfigurationUpdated config:' + JSON.stringify(config)); this.delegate.flutterEngine.getSettingsChannel().startMessage() .setAlwaysUse24HourFormat(I18n.System.is24HourClock()) diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbilityDelegate.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterAbilityDelegate.ets index 5e29d78d0a..9046981a47 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 @@ -353,14 +353,14 @@ class FlutterAbilityDelegate implements ExclusiveAppComponent { } } - onSaveState(reason: AbilityConstant.StateType, wantParam: { [key: string]: Object; }): AbilityConstant.OnSaveResult { + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult { Log.i(TAG, "onSaveInstanceState. Giving framework and plugins an opportunity to save state."); this.ensureAlive(); if (this.host.shouldRestoreAndSaveState()) { wantParam[FRAMEWORK_RESTORATION_BUNDLE_KEY] = this.flutterEngine.getRestorationChannel().getRestorationData(); } if (this.host.shouldAttachEngineToActivity()) { - const plugins = {} + const plugins:Record = {} const result = this.flutterEngine.getAbilityControlSurface().onSaveState(reason, plugins); wantParam[PLUGINS_RESTORATION_BUNDLE_KEY] = plugins; return result diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets index 3e5993c068..0569511193 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/FlutterPage.ets @@ -36,7 +36,8 @@ export struct FlutterPage { params: this.rootDvModel.model.params as DVModelParameters, events: this.rootDvModel.model.events as DVModelEvents, children: this.rootDvModel.model.children as DVModelChildren, - customBuilder: this.rootDvModel.model.builder as ($$: { params: DVModelParameters }) => void + customBuilder: this.rootDvModel.model.builder as ($$: Record<"params",DVModelParameters >) => void + //customBuilder: this.rootDvModel.model.builder as ($$: { params: DVModelParameters }) => void }) } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets index 1c6d907c3a..53f0f0a6c8 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/OhosTouchProcessor.ets @@ -22,7 +22,7 @@ export default class OhosTouchProcessor { private static POINTER_DATA_FLAG_BATCHED: number = 1; - public onTouchEvent(event: TouchEvent, transformMatrix: any): void { + public onTouchEvent(event: TouchEvent, transformMatrix: ESObject): void { } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets index fb4d9b69fd..b51743116e 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/embedding/ohos/TouchEventTracker.ets @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** Tracks the motion events received by the FlutterView. */ import PlainArray from '@ohos.util.PlainArray'; import { TouchEvent } from '@ohos.multimodalInput.touchEvent'; @@ -23,11 +22,11 @@ export class TouchEventTracker { private unusedEvents : Queue; private static INSTANCE:TouchEventTracker; - public static getInstance() : TouchEventTracker { - if (this.INSTANCE == null) { - this.INSTANCE = new TouchEventTracker(); + public static getInstance(): TouchEventTracker { + if (TouchEventTracker.INSTANCE == null) { + TouchEventTracker.INSTANCE = new TouchEventTracker(); } - return this.INSTANCE; + return TouchEventTracker.INSTANCE; } constructor() { @@ -79,7 +78,7 @@ export class TouchEventId { } public static createUnique() : TouchEventId { - return new TouchEventId(this.ID_COUNTER++); + return new TouchEventId(TouchEventId.ID_COUNTER++); } public getId() : number { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets index fd83576280..9910f14b6d 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/PlatformPlugin.ets @@ -34,126 +34,159 @@ import common from '@ohos.app.ability.common'; */ export default class PlatformPlugin { private static TAG = "PlatformPlugin"; - private platformChannel: PlatformChannel; - private platformPluginDelegate: PlatformPluginDelegate; - private context: common.Context; - private windowClass: window.Window = null; - private currentTheme: SystemChromeStyle = null; - private showBarOrNavigation: ('status' | 'navigation')[] = ['status','navigation']; - private uiAbilityContext:common.UIAbilityContext = null; - private callbackId :number = null; - private applicationContext: common.ApplicationContext = null; + private callback = new PlatformPluginCallback(); constructor(platformChannel: PlatformChannel, context: common.Context, platformPluginDelegate?: PlatformPluginDelegate) { - this.platformChannel = platformChannel; - this.context = context; - this.applicationContext = this.context.getApplicationContext(); + this.callback.platformChannel = platformChannel; + this.callback.context = context; + this.callback.applicationContext = context.getApplicationContext(); + this.callback.platform = this; try { - window.getLastWindow(this.context, (err,data) => { - if(err.code) { + window.getLastWindow(context, (err, data) => { + if (err.code) { Log.e(PlatformPlugin.TAG, "Failed to obtain the top window. Cause: " + JSON.stringify(err)); return; } - this.windowClass = data; + this.callback.windowClass = data; }); } catch (err) { - Log.e(PlatformPlugin.TAG,"Failed to obtain the top window. Cause: " + JSON.stringify(err)); + Log.e(PlatformPlugin.TAG, "Failed to obtain the top window. Cause: " + JSON.stringify(err)); } - this.platformPluginDelegate = platformPluginDelegate; - - this.platformChannel.setPlatformMessageHandler({ - playSystemSound:(soundType: SoundType): void => { - - }, - - vibrateHapticFeedback: (feedbackType: HapticFeedbackType): void => { - switch (feedbackType) { - case HapticFeedbackType.STANDARD: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'touch'}); - break; - case HapticFeedbackType.LIGHT_IMPACT: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'notification'}).then(); - break; - case HapticFeedbackType.MEDIUM_IMPACT: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'ring'}); - break; - case HapticFeedbackType.HEAVY_IMPACT: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'alarm'}); - break; - case HapticFeedbackType.SELECTION_CLICK: - vibrator.startVibration({type:'time',duration:100}, - {id:0, usage:'physicalFeedback'}); - break; + this.callback.platformPluginDelegate = platformPluginDelegate; + this.callback.platformChannel.setPlatformMessageHandler(this.callback); + } + + + updateSystemUiOverlays(): void { + this.callback.windowClass.setWindowSystemBarEnable(this.callback.showBarOrNavigation); + if (this.callback.currentTheme != null) { + this.callback.setSystemChromeSystemUIOverlayStyle(this.callback.currentTheme); + } + } + + setUIAbilityContext(context: common.UIAbilityContext): void { + this.callback.uiAbilityContext = context; + } + + setSystemChromeChangeListener(): void { + if (this.callback.callbackId == null && this.callback.applicationContext != null) { + let that = this; + this.callback.callbackId = this.callback.applicationContext.on('environment', { + onConfigurationUpdated(config) { + Log.d(PlatformPlugin.TAG, "onConfigurationUpdated: " + that.callback.showBarOrNavigation); + that.callback.platformChannel.systemChromeChanged(that.callback.showBarOrNavigation.includes('status')); + }, + onMemoryLevel(level) { } - }, + }) + } + } +} - setPreferredOrientations:(ohosOrientation: number): void => { - Log.d(PlatformPlugin.TAG,"ohosOrientation: " + ohosOrientation); - this.windowClass.setPreferredOrientation(ohosOrientation); - }, +export interface PlatformPluginDelegate { + popSystemNavigator(): boolean; +} - setApplicationSwitcherDescription:(description: AppSwitcherDescription): void => { - // representation described in the given {@code description}. - }, +class PlatformPluginCallback implements PlatformMessageHandler { + private static TAG = "PlatformPluginCallback"; + platform: PlatformPlugin; + windowClass: window.Window = null; + platformChannel: PlatformChannel; + platformPluginDelegate: PlatformPluginDelegate; + context: common.Context; + showBarOrNavigation: ('status' | 'navigation')[] = ['status', 'navigation']; + uiAbilityContext: common.UIAbilityContext = null; + callbackId: number = null; + applicationContext: common.ApplicationContext = null; + currentTheme: SystemChromeStyle = null; + + playSystemSound(soundType: SoundType) { + } - showSystemOverlays:(overlays: SystemUiOverlay[]): void => { - this.setSystemChromeEnabledSystemUIOverlays(overlays); - }, + vibrateHapticFeedback(feedbackType: HapticFeedbackType) { + switch (feedbackType) { + case HapticFeedbackType.STANDARD: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'touch' }); + break; + case HapticFeedbackType.LIGHT_IMPACT: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'notification' }).then(); + break; + case HapticFeedbackType.MEDIUM_IMPACT: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'ring' }); + break; + case HapticFeedbackType.HEAVY_IMPACT: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'alarm' }); + break; + case HapticFeedbackType.SELECTION_CLICK: + vibrator.startVibration({ type: 'time', duration: 100 }, + { id: 0, usage: 'physicalFeedback' }); + break; + } + } - showSystemUiMode:(mode: SystemUiMode): void => { - this.setSystemChromeEnabledSystemUIMode(mode); - }, + setPreferredOrientations(ohosOrientation: number) { + Log.d(PlatformPluginCallback.TAG, "ohosOrientation: " + ohosOrientation); + this.windowClass.setPreferredOrientation(ohosOrientation); + } - setSystemUiChangeListener:(): void => { - this.setSystemChromeChangeListener(); - }, + setApplicationSwitcherDescription(description: AppSwitcherDescription) { + // representation described in the given {@code description}. + } - restoreSystemUiOverlays:(): void => { - this.updateSystemUiOverlays(); - }, + showSystemOverlays(overlays: SystemUiOverlay[]) { + this.setSystemChromeEnabledSystemUIOverlays(overlays); + } - setSystemUiOverlayStyle:(systemUiOverlayStyle: SystemChromeStyle): void => { - Log.d(PlatformPlugin.TAG, "systemUiOverlayStyle:" + JSON.stringify(systemUiOverlayStyle)); - this.setSystemChromeSystemUIOverlayStyle(systemUiOverlayStyle); - }, + showSystemUiMode(mode: SystemUiMode) { + this.setSystemChromeEnabledSystemUIMode(mode); + } - popSystemNavigator:(): void => { - this.popSystemNavigator(); - }, + setSystemUiChangeListener() { + this.platform.setSystemChromeChangeListener(); + } - getClipboardData:(format: ClipboardContentFormat): string => { - return this.getClipboardData(format); - }, + restoreSystemUiOverlays() { + this.platform.updateSystemUiOverlays(); + } - setClipboardData:(text: string): void => { - this.setClipboardData(text); - }, + setSystemUiOverlayStyle(systemUiOverlayStyle: SystemChromeStyle) { + Log.d(PlatformPluginCallback.TAG, "systemUiOverlayStyle:" + JSON.stringify(systemUiOverlayStyle)); + this.setSystemChromeSystemUIOverlayStyle(systemUiOverlayStyle); + } - clipboardHasStrings:(): boolean => { - return; - } - }); + popSystemNavigator() { + if (this.platformPluginDelegate != null && this.platformPluginDelegate.popSystemNavigator()) { + return; + } + if (this.uiAbilityContext != null) { + this.uiAbilityContext.terminateSelf(); + } } - private getClipboardData(format: ClipboardContentFormat): string { - return; + getClipboardData(format: ClipboardContentFormat): string { + // todo + return ""; } - private setClipboardData(text: string): void { - let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN,text); + setClipboardData(text: string) { + let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text); let clipboard = pasteboard.getSystemPasteboard(); clipboard.setData(pasteData); } - private setSystemChromeEnabledSystemUIMode(mode: SystemUiMode): void { - Log.d(PlatformPlugin.TAG,"mode: " + mode); + clipboardHasStrings(): boolean { + return false; + } + + setSystemChromeEnabledSystemUIMode(mode: SystemUiMode): void { + Log.d(PlatformPluginCallback.TAG, "mode: " + mode); let uiConfig: ('status' | 'navigation')[] = []; - if(mode == SystemUiMode.LEAN_BACK) { + if (mode == SystemUiMode.LEAN_BACK) { //全屏显示,通过点击显示器上的任何位置都可以显示状态和导航栏 this.windowClass.setWindowLayoutFullScreen(false); @@ -165,47 +198,26 @@ export default class PlatformPlugin { //全屏显示,通过在显示器边缘的滑动手势可以显示状态和导航栏,此手势由应用程序接收 this.windowClass.setWindowLayoutFullScreen(true); - }else if (mode == SystemUiMode.EDGE_TO_EDGE) { + } else if (mode == SystemUiMode.EDGE_TO_EDGE) { //全屏显示,在应用程序上呈现状态和导航元素 this.windowClass.setWindowLayoutFullScreen(false); - uiConfig = ['status','navigation']; + uiConfig = ['status', 'navigation']; } else { return; } this.showBarOrNavigation = uiConfig; - this.updateSystemUiOverlays(); + this.platform.updateSystemUiOverlays(); } - private setSystemChromeEnabledSystemUIOverlays(overlays: SystemUiOverlay[]): void { - let uiConfig:('status' | 'navigation')[] = []; - if(overlays.length == 0) { - - } - for(let index = 0; index < overlays.length; ++index) { - let overlayToShow = overlays[index]; - switch (overlayToShow) { - case SystemUiOverlay.TOP_OVERLAYS: - uiConfig.push('status');//hide navigation - break; - case SystemUiOverlay.BOTTOM_OVERLAYS: - uiConfig.push('navigation');//hide bar - break; - } - } - this.showBarOrNavigation = uiConfig; - this.updateSystemUiOverlays(); - - } - - private setSystemChromeSystemUIOverlayStyle(systemChromeStyle: SystemChromeStyle): void { + setSystemChromeSystemUIOverlayStyle(systemChromeStyle: SystemChromeStyle): void { let isStatusBarLightIconValue: boolean = false; - let statusBarColorValue:string = null; + let statusBarColorValue: string = null; let statusBarContentColorValue: string = null; let navigationBarColorValue: string = null; let isNavigationBarLightIconValue: boolean = false; let navigationBarContentColorValue: string = null; - if(systemChromeStyle.statusBarIconBrightness != null) { + if (systemChromeStyle.statusBarIconBrightness != null) { switch (systemChromeStyle.statusBarIconBrightness) { case Brightness.DARK: isStatusBarLightIconValue = false; @@ -216,15 +228,15 @@ export default class PlatformPlugin { } } - if(systemChromeStyle.statusBarColor != null) { + if (systemChromeStyle.statusBarColor != null) { statusBarColorValue = "#" + systemChromeStyle.statusBarColor.toString(16); } - if(systemChromeStyle.systemStatusBarContrastEnforced != null) { + if (systemChromeStyle.systemStatusBarContrastEnforced != null) { } - if(systemChromeStyle.systemNavigationBarIconBrightness != null) { + if (systemChromeStyle.systemNavigationBarIconBrightness != null) { switch (systemChromeStyle.systemNavigationBarIconBrightness) { case Brightness.DARK: isNavigationBarLightIconValue = true; @@ -234,62 +246,56 @@ export default class PlatformPlugin { } } - if(systemChromeStyle.systemNavigationBarColor != null) { + if (systemChromeStyle.systemNavigationBarColor != null) { navigationBarColorValue = "#" + systemChromeStyle.systemNavigationBarColor.toString(16); } - if(systemChromeStyle.systemNavigationBarContrastEnforced != null) { + if (systemChromeStyle.systemNavigationBarContrastEnforced != null) { } this.currentTheme = systemChromeStyle; - let systemBarProperties = { - statusBarColor: statusBarColorValue, - isStatusBarLightIcon: isStatusBarLightIconValue, - statusBarContentColor: statusBarContentColorValue, - navigationBarColor: navigationBarColorValue, - isNavigationBarLightIcon: isNavigationBarLightIconValue, - navigationBarContentColor: navigationBarContentColorValue, - } - Log.d(PlatformPlugin.TAG, "systemBarProperties: "+JSON.stringify(systemBarProperties)); + let systemBarProperties = new SystemBarProperties(); + systemBarProperties.statusBarColor = statusBarColorValue; + systemBarProperties.isStatusBarLightIcon = isStatusBarLightIconValue; + systemBarProperties.statusBarContentColor = statusBarContentColorValue; + systemBarProperties.navigationBarColor = navigationBarColorValue; + systemBarProperties.isNavigationBarLightIcon = isNavigationBarLightIconValue; + systemBarProperties.navigationBarContentColor = navigationBarContentColorValue; + Log.d(PlatformPluginCallback.TAG, "systemBarProperties: " + JSON.stringify(systemBarProperties)); this.windowClass.setWindowSystemBarProperties(systemBarProperties); } - private popSystemNavigator(): void { - if(this.platformPluginDelegate != null && this.platformPluginDelegate.popSystemNavigator()) { - return; + setSystemChromeEnabledSystemUIOverlays(overlays: SystemUiOverlay[]): void { + let uiConfig: ('status' | 'navigation')[] = []; + if (overlays.length == 0) { + } - if(this.uiAbilityContext != null) { - this.uiAbilityContext.terminateSelf(); + for (let index = 0; index < overlays.length; ++index) { + let overlayToShow = overlays[index]; + switch (overlayToShow) { + case SystemUiOverlay.TOP_OVERLAYS: + uiConfig.push('status'); //hide navigation + break; + case SystemUiOverlay.BOTTOM_OVERLAYS: + uiConfig.push('navigation'); //hide bar + break; + } } + this.showBarOrNavigation = uiConfig; + this.platform.updateSystemUiOverlays(); } +} - updateSystemUiOverlays(): void { - this.windowClass.setWindowSystemBarEnable(this.showBarOrNavigation); - if(this.currentTheme != null) { - this.setSystemChromeSystemUIOverlayStyle(this.currentTheme); - } - } +class SystemBarProperties { + statusBarColor?: string; - setUIAbilityContext(context: common.UIAbilityContext): void { - this.uiAbilityContext = context; - } + isStatusBarLightIcon?: boolean; - setSystemChromeChangeListener(): void { - if(this.callbackId == null && this.applicationContext != null) { - let that = this; - this.callbackId = this.applicationContext.on('environment',{ - onConfigurationUpdated(config) { - Log.d(PlatformPlugin.TAG, "onConfigurationUpdated: " + that.showBarOrNavigation); - that.platformChannel.systemChromeChanged(that.showBarOrNavigation.includes('status')); - }, - onMemoryLevel(level) { - } - }) - } - } + statusBarContentColor?: string; -} + navigationBarColor?: string; -export interface PlatformPluginDelegate { - popSystemNavigator(): boolean; + isNavigationBarLightIcon?: boolean; + + navigationBarContentColor?: string; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BasicMessageChannel.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BasicMessageChannel.ets index d6ef6c6c26..a6e6f6bcfb 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 @@ -101,7 +101,7 @@ export interface Reply { * * @param reply the reply, possibly null. */ - reply(reply: T): void; + reply: (reply: T) => void; } export interface MessageHandler { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets index aa44a4958e..988c6a5709 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/BinaryMessenger.ets @@ -86,10 +86,8 @@ export interface BinaryMessageHandler { * @see MethodChannel , which supports communication using asynchronous method invocation. * @see EventChannel , which supports communication using event streams. */ -export abstract class BinaryMessenger { - makeBackgroundTaskQueue(options?: TaskQueueOptions): TaskQueue { - throw new Error("makeBackgroundTaskQueue not implemented.") - } +export interface BinaryMessenger { + makeBackgroundTaskQueue(options?: TaskQueueOptions): TaskQueue; /** * Sends a binary message to the Flutter application. @@ -98,7 +96,7 @@ export abstract class BinaryMessenger { * @param message the message payload, a direct-allocated {@link ByteBuffer} with the message * bytes between position zero and current position, or null. */ - abstract send(channel: String, message: ArrayBuffer): void; + send(channel: String, message: ArrayBuffer): void; /** * Sends a binary message to the Flutter application, optionally expecting a reply. @@ -111,7 +109,7 @@ export abstract class BinaryMessenger { * @param callback a {@link BinaryReply} callback invoked when the Flutter application responds to * the message, possibly null. */ - abstract send(channel: String, message: ArrayBuffer, callback?: BinaryReply): void; + send(channel: String, message: ArrayBuffer, callback?: BinaryReply): void; /** * Registers a handler to be invoked when the Flutter application sends a message to its host @@ -129,11 +127,12 @@ export abstract class BinaryMessenger { * the handler. Specifying null means execute on the platform thread. */ //setMessageHandler(channel: String, handler: BinaryMessageHandler) - setMessageHandler(channel: String, handler: BinaryMessageHandler, taskQueue?: TaskQueue): void { - if (taskQueue != null) { - throw new Error("setMessageHandler called with nonnull taskQueue is not supported.") - } - } + setMessageHandler(channel: String, handler: BinaryMessageHandler, taskQueue?: TaskQueue): void; + // { + // if (taskQueue != null) { + // throw new Error("setMessageHandler called with nonnull taskQueue is not supported.") + // } + // } /** * Enables the ability to queue messages received from Dart. @@ -142,16 +141,18 @@ export abstract class BinaryMessenger { * be initialized concurrently, and prior to the registration of the channel handlers. This * implies that Dart may start sending messages while plugins are being registered. */ - enableBufferingIncomingMessages(): void { - throw new Error("enableBufferingIncomingMessages not implemented."); - } + enableBufferingIncomingMessages(): void; + // { + // throw new Error("enableBufferingIncomingMessages not implemented."); + // } /** * Disables the ability to queue messages received from Dart. * *

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

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

To extend the codec, overwrite the writeValue and readValueOfType methods. */ -export default class StandardMessageCodec implements MessageCodec { +export default class StandardMessageCodec implements MessageCodec { private static TAG = "StandardMessageCodec#"; static INSTANCE = new StandardMessageCodec(); - encodeMessage(message: any): ArrayBuffer { + encodeMessage(message: ESObject): ArrayBuffer { if (message == null) { return null; } @@ -73,7 +73,7 @@ export default class StandardMessageCodec implements MessageCodec { return stream.buffer } - decodeMessage(message: ArrayBuffer): any { + decodeMessage(message: ArrayBuffer): ESObject { const buffer = ByteBuffer.from(message) return this.readValue(buffer) } @@ -95,7 +95,7 @@ export default class StandardMessageCodec implements MessageCodec { private static FLOAT32_ARRAY = 14; - writeValue(stream: ByteBuffer, value: any): any { + writeValue(stream: ByteBuffer, value: ESObject): ESObject { if (value == null || value == undefined) { stream.writeInt8(StandardMessageCodec.NULL) } else if (typeof value === "boolean") { @@ -139,22 +139,22 @@ export default class StandardMessageCodec implements MessageCodec { } else if (value instanceof Array) { stream.writeInt8(StandardMessageCodec.LIST) this.writeSize(stream, value.length); - value.forEach(item => this.writeValue(stream, item)) + value.forEach((item: ESObject): void => this.writeValue(stream, item)) } else if (value instanceof Map) { stream.writeInt8(StandardMessageCodec.MAP) this.writeSize(stream, value.size); - value.forEach((value, key) => { + value.forEach((value: ESObject, key: ESObject) => { this.writeValue(stream, key); this.writeValue(stream, value); }) } else if (typeof value == 'object') { - this.writeValue(stream, new Map(Object.entries(value))) + this.writeValue(stream, new Map(value.entries())) } return stream } writeAlignment(stream: ByteBuffer, alignment: number) { - var mod = stream.byteOffset % alignment; + let mod: number = stream.byteOffset % alignment; if (mod != 0) { for (let i = 0; i < alignment - mod; i++) { stream.writeInt8(0); @@ -197,7 +197,7 @@ export default class StandardMessageCodec implements MessageCodec { } } - readValue(buffer: ByteBuffer): any { + readValue(buffer: ByteBuffer): ESObject { let type = buffer.readInt8() return this.readValueOfType(type, buffer); } @@ -211,8 +211,8 @@ export default class StandardMessageCodec implements MessageCodec { return bytes; } - readValueOfType(type: number, buffer: ByteBuffer): any { - var result + readValueOfType(type: number, buffer: ByteBuffer): ESObject { + let result: ESObject; switch (type) { case StandardMessageCodec.NULL: result = null; @@ -256,7 +256,7 @@ export default class StandardMessageCodec implements MessageCodec { } case StandardMessageCodec.INT64_ARRAY: { //这里是都城array 还是 bigint待定 let length = this.readSize(buffer); - let array = new Array(length) + let array: Array = new Array(length) this.readAlignment(buffer, 8); for (let i = 0; i < length; i++) { array[i] = buffer.readInt64(true) @@ -276,7 +276,7 @@ export default class StandardMessageCodec implements MessageCodec { } case StandardMessageCodec.LIST: { let length = this.readSize(buffer); - let array = new Array(length) + let array: Array = new Array(length) for (let i = 0; i < length; i++) { array[i] = this.readValue(buffer) } @@ -285,7 +285,7 @@ export default class StandardMessageCodec implements MessageCodec { } case StandardMessageCodec.MAP: { let size = this.readSize(buffer); - let map = new Map() + let map: Map = new Map() for (let i = 0; i < size; i++) { map.set(this.readValue(buffer), this.readValue(buffer)); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets index 4661aff7bb..d4417c54eb 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/common/StandardMethodCodec.ets @@ -49,22 +49,22 @@ export default class StandardMethodCodec implements MethodCodec { decodeMethodCall(methodCall: ArrayBuffer): MethodCall { const buffer = ByteBuffer.from(methodCall); - const method = this.messageCodec.readValue(buffer); - const args = this.messageCodec.readValue(buffer); + const method: ESObject = this.messageCodec.readValue(buffer); + const args: ESObject = this.messageCodec.readValue(buffer); if (typeof method == 'string' && !buffer.hasRemaining()) { return new MethodCall(method, args); } throw new Error("Method call corrupted"); } - encodeSuccessEnvelope(result: any): ArrayBuffer { + encodeSuccessEnvelope(result: ESObject): ArrayBuffer { const stream = ByteBuffer.from(new ArrayBuffer(1024)); stream.writeInt8(0); this.messageCodec.writeValue(stream, result); return stream.buffer; } - encodeErrorEnvelope(errorCode: string, errorMessage: string, errorDetails: any): ArrayBuffer { + encodeErrorEnvelope(errorCode: string, errorMessage: string, errorDetails: ESObject): ArrayBuffer { const stream = ByteBuffer.from(new ArrayBuffer(1024)); stream.writeInt8(1); this.messageCodec.writeValue(stream, errorCode); @@ -77,7 +77,7 @@ export default class StandardMethodCodec implements MethodCodec { return stream.buffer; } - encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: any, errorStacktrace: string): ArrayBuffer { + encodeErrorEnvelopeWithStacktrace(errorCode: string, errorMessage: string, errorDetails: ESObject, errorStacktrace: string): ArrayBuffer { const stream = ByteBuffer.from(new ArrayBuffer(1024)); stream.writeInt8(1); this.messageCodec.writeValue(stream, errorCode); @@ -91,21 +91,21 @@ export default class StandardMethodCodec implements MethodCodec { return stream.buffer; } - decodeEnvelope(envelope: ArrayBuffer): any { + decodeEnvelope(envelope: ArrayBuffer): ESObject { const buffer = ByteBuffer.from(envelope); const flag = buffer.readInt8(); switch (flag) { case 0: { - const result = this.messageCodec.readValue(buffer); + const result: ESObject = this.messageCodec.readValue(buffer); if (!buffer.hasRemaining()) { return result; } // Falls through intentionally. } case 1: { - const code = this.messageCodec.readValue(buffer); - const message = this.messageCodec.readValue(buffer); - const details = this.messageCodec.readValue(buffer); + const code: ESObject = this.messageCodec.readValue(buffer); + const message: ESObject = this.messageCodec.readValue(buffer); + const details: ESObject = this.messageCodec.readValue(buffer); if (typeof code == 'string' && (message == null || typeof message == 'string') && !buffer.hasRemaining()) { throw new FlutterException(code, message, details); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextEditingDelta.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextEditingDelta.ets index 8b8064fbee..c61296f6da 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 @@ -58,22 +58,4 @@ export class TextEditingDelta { this.deltaStart = newStart; this.deltaEnd = newExtent; } - - toJSON(): any { - let delta; - try { - delta.oldText = this.oldText; - delta.deltaText = this.deltaText; - delta.deltaStart = this.deltaStart; - delta.deltaEnd = this.deltaEnd; - delta.selectionBase = this.newSelectionStart; - delta.selectionExtent = this.newSelectionEnd; - delta.composingBase = this.newComposingStart; - delta.composingExtent = this.newComposingEnd; - } catch (err) { - Log.e(TextEditingDelta.TAG,"unable to create JSONObject: " + JSON.stringify(err)); - } - - - } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets index f837940fa1..6df66b9cfd 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/editing/TextInputPlugin.ets @@ -14,76 +14,108 @@ */ import TextInputChannel, { Configuration, TextEditState, + TextInputMethodHandler, TextInputType } from '../../embedding/engine/systemchannels/TextInputChannel'; import inputMethod from '@ohos.inputMethod'; import Log from '../../util/Log'; import { EditingStateWatcher, ListenableEditingState } from './ListenableEditingState'; -import { TextEditingDelta } from './TextEditingDelta'; export default class TextInputPlugin implements EditingStateWatcher{ private static TAG = "TextInputPlugin"; private textInputChannel: TextInputChannel; + private inputMethodController: inputMethod.InputMethodController; + private inputTarget: InputTarget; + private mEditable: ListenableEditingState; + + constructor(textInputChannel: TextInputChannel) { + this.textInputChannel = textInputChannel; + this.mEditable = new ListenableEditingState(); + this.inputMethodController = inputMethod.getController(); + let textInputMethodHandler = new TextInputMethodHandlerImpl(this); + this.textInputChannel.setTextInputMethodHandler(textInputMethodHandler); + } + + public clearTextInputClient() { + 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()) + } + + detach(): void { + this.inputMethodController.detach((err) => { + if(err) { + Log.e(TextInputPlugin.TAG, "Failed to detach: " + JSON.stringify(err)); + } + }) + } + +} + +class TextInputMethodHandlerImpl implements TextInputMethodHandler { + private static TAG = "TextInputMethodHandlerImpl"; private textConfig: inputMethod.TextConfig; private inputMethodController: inputMethod.InputMethodController; private inputTarget: InputTarget; private configuration: Configuration; private mEditable: ListenableEditingState; private mRestartInputPending: boolean; + private plugin: EditingStateWatcher; private imcFlag: boolean = false; - - - constructor(textInputChannel: TextInputChannel) { - this.textInputChannel = textInputChannel; - this.mEditable = new ListenableEditingState(); + constructor(plugin: EditingStateWatcher) { this.textConfig = { inputAttribute: { textInputType: 0, enterKeyType: 1 }}; - this.inputMethodController = inputMethod.getController(); - this.textInputChannel.setTextInputMethodHandler({ - show:(): void => { - this.showTextInput(); - }, + this.plugin = plugin; + } - hide:(): void => { - this.hideTextInput(); - }, + show(): void { + this.showTextInput(); + } - requestAutofill:(): void =>{ + hide(): void { + this.hideTextInput(); + } - }, + requestAutofill(): void { - finishAutofillContext:(shouldSave: boolean): void =>{ + } - }, + finishAutofillContext(shouldSave: boolean): void { - setClient:(textInputClientId: number, configuration: Configuration): void => { - Log.d(TextInputPlugin.TAG,"textInputClientId: " + textInputClientId); - this.setTextInputClient(textInputClientId, configuration); - }, + } - setPlatformViewClient:(id: number, usesVirtualDisplay: boolean): void => { + setClient(textInputClientId: number, configuration: Configuration): void { + Log.d(TextInputMethodHandlerImpl.TAG,"textInputClientId: " + textInputClientId); + this.setTextInputClient(textInputClientId, configuration); + } - }, + setPlatformViewClient(id: number, usesVirtualDisplay: boolean): void { - setEditableSizeAndTransform:(width: number, height: number, transform: number[]): void => { + } - }, + setEditableSizeAndTransform(width: number, height: number, transform: number[]): void { - setEditingState:(editingState: TextEditState): void => { - Log.d(TextInputPlugin.TAG, "text:" + editingState.text +" selectionStart:" + editingState.selectionStart + " selectionEnd:" - + editingState.selectionEnd + " composingStart:" + editingState.composingStart + " composingEnd" + editingState.composingEnd); - this.mEditable.updateTextInputState(editingState); - }, - clearClient:(): void =>{ - this.clearTextInputClient(); - } + } + setEditingState(editingState: TextEditState): void { + Log.d(TextInputMethodHandlerImpl.TAG, "text:" + editingState.text +" selectionStart:" + editingState.selectionStart + " selectionEnd:" + + editingState.selectionEnd + " composingStart:" + editingState.composingStart + " composingEnd" + editingState.composingEnd); + this.mEditable.updateTextInputState(editingState); + } - }); + clearClient(): void { + this.clearTextInputClient(); } private async showTextInput(): Promise { @@ -92,17 +124,17 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.listenKeyBoardEvent(); } this.inputMethodController.showTextInput().then(()=> { - Log.d(TextInputPlugin.TAG, "Succeeded in showing softKeyboard"); - }).catch((err) => { - Log.e(TextInputPlugin.TAG, "Failed to show softKeyboard:" + JSON.stringify(err)); + Log.d(TextInputMethodHandlerImpl.TAG, "Succeeded in showing softKeyboard"); + }).catch((err: ESObject) => { + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to show softKeyboard:" + JSON.stringify(err)); }); } private async hideTextInput(): Promise { this.inputMethodController.hideTextInput().then(() => { - Log.d(TextInputPlugin.TAG, "Succeeded in hide softKeyboard"); - }).catch((err) => { - Log.e(TextInputPlugin.TAG, "Failed to hide softKeyboard:" + JSON.stringify(err)); + Log.d(TextInputMethodHandlerImpl.TAG, "Succeeded in hide softKeyboard"); + }).catch((err: ESObject) => { + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to hide softKeyboard:" + JSON.stringify(err)); }) } @@ -110,18 +142,39 @@ export default class TextInputPlugin implements EditingStateWatcher{ try { await this.inputMethodController.attach(showKeyboard, this.textConfig); } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to attach:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to attach:" + JSON.stringify(err)); + } + } + + setTextInputClient(client: number, configuration: Configuration): void { + this.configuration = configuration; + if(this.canShowTextInput()) { + this.inputTarget = new InputTarget(Type.FRAMEWORK_CLIENT, client); + } else { + this.inputTarget = new InputTarget(Type.NO_TARGET, client); + } + this.mEditable.removeEditingStateListener(this.plugin); + this.mEditable = new ListenableEditingState(); + + this.mRestartInputPending = true; + this.mEditable.addEditingStateListener(this.plugin); + } + + canShowTextInput(): boolean { + if(this.configuration == null || this.configuration.inputType == null) { + return true; } + return this.configuration.inputType.type != TextInputType.NONE; } listenKeyBoardEvent(): void { try { this.inputMethodController.on('insertText', (text) => { - Log.d(TextInputPlugin.TAG, "insertText: " + text); + Log.d(TextInputMethodHandlerImpl.TAG, "insertText: " + text); this.mEditable.handleInsertTextEvent(text); }); } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe insertText:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe insertText:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } @@ -131,7 +184,7 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.mEditable.handleDeleteEvent(false, length); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe deleteLeft:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe deleteLeft:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } @@ -141,7 +194,7 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.mEditable.handleDeleteEvent(true, length); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe deleteRight:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe deleteRight:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } @@ -151,21 +204,21 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.mEditable.handleFunctionKey(functionKey); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe sendFunctionKey:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe sendFunctionKey:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } try { - this.inputMethodController.on('selectByRange', (range) => { + this.inputMethodController.on('selectByRange', (range: inputMethod.Range) => { this.mEditable.handleSelectByRange(range); }) } catch (err) { - Log.e(TextInputPlugin.TAG, "Failed to subscribe selectByRange:" + JSON.stringify(err)); + Log.e(TextInputMethodHandlerImpl.TAG, "Failed to subscribe selectByRange:" + JSON.stringify(err)); this.cancelListenKeyBoardEvent(); return; } - Log.d(TextInputPlugin.TAG, "listenKeyBoardEvent success"); + Log.d(TextInputMethodHandlerImpl.TAG, "listenKeyBoardEvent success"); this.imcFlag = true; } @@ -177,54 +230,14 @@ export default class TextInputPlugin implements EditingStateWatcher{ this.inputMethodController.off('selectByRange'); } - setTextInputClient(client: number, configuration: Configuration): void { - this.configuration = configuration; - if(this.canShowTextInput()) { - this.inputTarget = new InputTarget(Type.FRAMEWORK_CLIENT, client); - } else { - this.inputTarget = new InputTarget(Type.NO_TARGET, client); - } - this.mEditable.removeEditingStateListener(this); - this.mEditable = new ListenableEditingState(); - - this.mRestartInputPending = true; - this.mEditable.addEditingStateListener(this); - } - - canShowTextInput(): boolean { - if(this.configuration == null || this.configuration.inputType == null) { - return true; - } - return this.configuration.inputType.type != TextInputType.NONE; - } - - setTextInputEditingState(state: TextEditState) { - - } - - didChangeEditingState(textChanged: boolean, selectionChanged: boolean, composingRegionChanged: boolean): void { - this.textInputChannel.updateEditingState(this.inputTarget.id, this.mEditable.getStringCache(), - this.mEditable.getSelectionStart(), this.mEditable.getSelectionEnd(), - this.mEditable.getComposingStart(), this.mEditable.getComposingEnd()) - } - - detach(): void { - this.inputMethodController.detach((err) => { - if(err) { - Log.e(TextInputPlugin.TAG, "Failed to detach: " + JSON.stringify(err)); - } - }) - } - - clearTextInputClient(): void { + public clearTextInputClient(): void { if(this.inputTarget.type == Type.VIRTUAL_DISPLAY_PLATFORM_VIEW) { return; } - this.mEditable.removeEditingStateListener(this); + this.mEditable.removeEditingStateListener(this.plugin); this.configuration = null; this.inputTarget = new InputTarget(Type.NO_TARGET, 0); } - } enum Type { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets index 662e087641..78ed1c7297 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/localization/LocalizationPlugin.ets @@ -44,12 +44,10 @@ export default class LocalizationPlugin { return new intl.Locale(languageCode+'-'+ countryCode +'-' + scriptCode); } - private localizationMessageHandler: LocalizationMessageHandler = { - getStringResource(key: string, localeString: string): string { - Log.i(TAG, "getResource enter"); - return "" - } - } + private localizationMessageHandler: LocalizationMessageHandler =new enterGetStringResource(()=>{ + Log.i(TAG, "getResource enter"); + return "" + }) constructor(context: common.Context, localizationChannel: LocalizationChannel) { this.context = context; this.localizationChannel = localizationChannel; @@ -59,5 +57,12 @@ export default class LocalizationPlugin { sendLocaleToFlutter(): void { let systemLanguages = i18n.System.getSystemLanguages(); this.localizationChannel.sendLocales(systemLanguages); - } + } } +class enterGetStringResource{ + getStringResource : (key: string, localeString: string)=>string + + constructor(getStringResource: (key: string, localeString: string)=>string) { + this.getStringResource = getStringResource + } +} \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/mouse/MouseCursorPlugin.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/mouse/MouseCursorPlugin.ets index 4aa609f9cf..44c94a11aa 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 @@ -41,7 +41,7 @@ export default class MouseCursorPlugin implements MouseCursorMethodHandler{ } let pointStyle: pointer.PointerStyle = this.resolveSystemCursor(kind); try { - pointer.setPointerStyle(windowId, pointStyle, (err) => { + pointer.setPointerStyle(windowId, pointStyle, (err: ESObject) => { Log.i(TAG, "set point style success kind : " + kind); }) } catch (e) { diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets index 2f156cdcd2..64e8c7f780 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformOverlayView.ets @@ -17,7 +17,7 @@ import { AccessibilityEventsDelegate } from './AccessibilityEventsDelegate'; export class PlatformOverlayView { private accessibilityEventsDelegate: AccessibilityEventsDelegate; - // @ts-ignore + constructor(context: Context, width: Number, height: Number, accessibilityEventsDelegate: AccessibilityEventsDelegate) { this.accessibilityEventsDelegate= accessibilityEventsDelegate; } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets index fe96017e00..373a7ea5a5 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewFactory.ets @@ -18,10 +18,10 @@ import PlatformView from './PlatformView' import common from '@ohos.app.ability.common'; export default abstract class PlatformViewFactory { - private createArgsCodec: MessageCodec; + private createArgsCodec: MessageCodec; /** @param createArgsCodec the codec used to decode the args parameter of {@link #create}. */ - constructor(createArgsCodec: MessageCodec) { + constructor(createArgsCodec: MessageCodec) { this.createArgsCodec = createArgsCodec; } @@ -35,10 +35,10 @@ export default abstract class PlatformViewFactory { * createArgsCodec argument passed to the constructor. This is null if createArgsCodec was * null, or no arguments were sent from the Flutter app. */ - public abstract create(context: common.Context, viewId: number, args: any): PlatformView; + public abstract create(context: common.Context, viewId: number, args: ESObject): PlatformView; /** Returns the codec to be used for decoding the args parameter of {@link #create}. */ - getCreateArgsCodec(): MessageCodec { + getCreateArgsCodec(): MessageCodec { return this.createArgsCodec; } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewWrapper.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewWrapper.ets index 5bd02dcc81..6bcec97fd5 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 @@ -30,33 +30,8 @@ export class PlatformViewWrapper { private bufferHeight: number; private touchProcessor: OhosTouchProcessor; - private onTouch = (touchEvent) => { - switch (touchEvent.type) { - case TouchType.Down: - this.prevLeft = this.left; - this.prevTop = this.top; - this.model.params["translateX"] = this.left; - this.model.params["translateY"] = this.top; - break; - case TouchType.Move: - this.model.params["translateX"] = this.prevLeft; - this.model.params["translateY"] = this.prevTop; - this.prevLeft = this.left; - this.prevTop = this.top; - break; - case TouchType.Up: - case TouchType.Cancel: - default: - break; - } - } - private model : DVModel = createDVModelFromJson( - { - compType: "Column", - children: [], - } - ); + private model : DVModel = createDVModelFromJson( new DVModelParam("Column", [])); public setTouchProcessor(newTouchProcessor: OhosTouchProcessor): void { this.touchProcessor = newTouchProcessor; @@ -69,25 +44,48 @@ export class PlatformViewWrapper { return this.model; } + setParams: (params: DVModelParameters, key: string, element: ESObject ) => void = (params: DVModelParameters, key: string, element: ESObject): void => { + let params2 = params as Record; + params2[key] =element; + } + + getParams: (params: DVModelParameters, element: string) => string | ESObject = (params: DVModelParameters, element: string): string | ESObject => { + let params2 = params as Record; + return params2[element]; + } + public setLayoutParams(parameters : DVModelParameters): void { if (this.model.params == null) { this.model.params = new DVModelParameters(); } - this.model.params['marginLeft'] = parameters['marginLeft']; - this.model.params['marginTop'] = parameters['marginTop']; - this.left = parameters['marginLeft']; - this.top = parameters['marginTop']; + this.setParams(this.model.params, "marginLeft", this.getParams(parameters, "marginLeft")); + this.setParams(this.model.params, "marginTop", this.getParams(parameters, "marginTop")); + this.left = this.getParams(parameters, "marginLeft"); + this.top = this.getParams(parameters, "marginTop"); - if (parameters.hasOwnProperty('width')) { - this.model.params['width'] = parameters['width']; - } + this.setParams(this.model.params, "width", this.getParams(parameters, "width")); + this.setParams(this.model.params, "height", this.getParams(parameters, "height")); - if (parameters.hasOwnProperty('height')) { - this.model.params['height'] = parameters['height']; - } + // this.model.params.marginLeft = parameters.marginLeft; + // this.model.params.marginTop = parameters.marginTop; + // this.left = parameters.marginLeft; + // this.top = parameters.marginTop;; + + // this.model.params.width = parameters.width; + // this.model.params.height = parameters.height; } public addDvModel(model: DVModel): void { this.model.children.push(model); } -} \ No newline at end of file +} + +class DVModelParam { + compType: string + children: [] + + constructor(compType: string, children: []) { + this.compType = compType; + this.children = children; + } +}; \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets index 10efaea686..62888046c5 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsAccessibilityDelegate.ets @@ -20,7 +20,7 @@ export interface PlatformViewsAccessibilityDelegate { * Returns the root of the view hierarchy for the platform view with the requested id, or null if * there is no corresponding view. */ - getPlatformViewById(viewId: number): any; + getPlatformViewById(viewId: number): Object; /** Returns true if the platform view uses virtual displays. */ usesVirtualDisplay(id: number): boolean; diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/PlatformViewsController.ets index 5838afd27f..2fac095a2a 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 @@ -76,7 +76,8 @@ export default class PlatformViewsController implements PlatformViewsAccessibili this.platformViewParent = new Map(); } - getPlatformViewById(viewId: number) { + + getPlatformViewById(viewId: number): Object { throw new Error('Method not implemented.'); } @@ -126,6 +127,11 @@ export default class PlatformViewsController implements PlatformViewsAccessibili } } + setParams: (params: DVModelParameters, key: string, element: ESObject ) => void = (params: DVModelParameters, key: string, element: ESObject): void => { + let params2 = params as Record; + params2[key] =element; + } + resize(request: PlatformViewResizeRequest, onComplete: PlatformViewBufferResized): void { let physicalWidth: number = this.toPhysicalPixels(request.newLogicalWidth); let physicalHeight: number = this.toPhysicalPixels(request.newLogicalHeight); @@ -141,22 +147,26 @@ export default class PlatformViewsController implements PlatformViewsAccessibili let viewWrapperLayoutParams: DVModelParameters = viewWrapper.getDvModel().getLayoutParams(); if (physicalWidth) { - viewWrapperLayoutParams["width"] = physicalWidth; + this.setParams(viewWrapperLayoutParams, "width", physicalWidth); + // viewWrapperLayoutParams.width = physicalWidth; } if (physicalHeight) { - viewWrapperLayoutParams["height"] = physicalHeight; + this.setParams(viewWrapperLayoutParams, "height", physicalHeight); + // viewWrapperLayoutParams.height = physicalHeight; } let embeddedView: DVModel = platformView.getView(); if (embeddedView != null) { let embeddedViewLayoutParams = embeddedView.getLayoutParams(); if (physicalWidth) { - embeddedViewLayoutParams["width"] = physicalWidth; + this.setParams(embeddedViewLayoutParams, "width", physicalWidth); + // embeddedViewLayoutParams.width = physicalWidth; } if (physicalHeight) { - embeddedViewLayoutParams["height"] = physicalHeight; + this.setParams(embeddedViewLayoutParams, "height", physicalHeight); + // embeddedViewLayoutParams.height = physicalHeight; } } @@ -174,8 +184,8 @@ export default class PlatformViewsController implements PlatformViewsAccessibili let physicalTop = this.toPhysicalPixels(top); let physicalLeft = this.toPhysicalPixels(left); let params = viewWrapper.getDvModel().params; - params["marginTop"] = physicalTop; - params["marginLeft"] = physicalLeft; + this.setParams(params, "marginTop", physicalTop); + this.setParams(params, "marginLeft", physicalLeft); viewWrapper.setLayoutParams(params); } @@ -215,7 +225,8 @@ export default class PlatformViewsController implements PlatformViewsAccessibili Log.e(TAG, "Setting direction to a null view with id: " + viewId); return; } - embeddedView.params["direction"] = direction; + this.setParams(embeddedView.params, "direction", direction); + // embeddedView.params.direction = direction; } validateDirection(direction:number):boolean { @@ -271,7 +282,7 @@ export default class PlatformViewsController implements PlatformViewsAccessibili throw new Error("Trying to create a platform view of unregistered type: " + request.viewType) } - let createParams: any = null; + let createParams: ESObject = null; if (request.params != null) { let byteParas : ByteBuffer = request.params as ByteBuffer; createParams = viewFactory.getCreateArgsCodec().decodeMessage(byteParas.buffer); @@ -285,7 +296,8 @@ export default class PlatformViewsController implements PlatformViewsAccessibili throw new Error("PlatformView#getView() returned null, but an dynamic view reference was expected."); } - embeddedView.params['direction'] = request.direction; + this.setParams(embeddedView.params, "direction", request.direction); + // embeddedView.params.direction = request.direction; this.platformViews.set(request.viewId, platformView); return platformView; @@ -308,20 +320,27 @@ export default class PlatformViewsController implements PlatformViewsAccessibili Log.i(TAG, `View pW:${request.logicalWidth}, pH:${request.logicalHeight}, pT:${physicalTop}, pL:${physicalLeft}`); let param: DVModelParameters = new DVModelParameters(); - param['marginLeft'] = physicalLeft; - param['marginTop'] = physicalTop; + + this.setParams(param, "marginLeft", physicalLeft); + this.setParams(param, "marginTop", physicalTop); + // param.marginLeft = physicalLeft; + // param.marginTop = physicalTop; let model = platformView.getView(); if (request.logicalWidth != null) { let physicalWidth: number = this.toPhysicalPixels(request.logicalWidth); - model.params['width'] = physicalWidth; - param['width'] = physicalWidth; + this.setParams(model.params, "width", physicalWidth); + this.setParams(param, "width", physicalWidth); + // model.params.width = physicalWidth; + // param.width = physicalWidth; } if (request.logicalHeight != null) { let physicalHeight: number = this.toPhysicalPixels(request.logicalHeight); - model.params['height'] = physicalHeight; - param['height'] = physicalHeight; + this.setParams(model.params, "height", physicalHeight); + this.setParams(param, "height", physicalHeight); + // model.params.height = physicalHeight; + // param.height = physicalHeight; } viewWrapper.setLayoutParams(param); diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets index 3b3a43bb3a..ae74fda585 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/plugin/platform/RootDvModelManager.ets @@ -20,7 +20,7 @@ import { createDVModelFromJson } from '../../view/DynamicView/dynamicViewJson'; @Component struct XComponentStruct { - private context; + private context:ESObject; build() { XComponent({ id: 'flutterXComponent', type: 'texture', libraryname: 'flutter' }) @@ -31,24 +31,33 @@ struct XComponentStruct { }) } } - -@Builder function BuildXComponentStruct($$: {param: DVModelParameters}) { +interface $$type{ + param: DVModelParameters +} +@Builder function BuildXComponentStruct($$: $$type) { XComponentStruct(); } +class DVModelJson{ + compType: string + children:Array + attributes:ESObject + + constructor(compType:string , children:Array , attributes:ESObject) { + this.compType = compType + this.children = children + this.attributes = attributes + } +} export class RootDvModeManager { - private static xComponentModel = + private static xComponentModel:ESObject = { compType: "xComponent", build: BuildXComponentStruct }; - private static model : DVModel = createDVModelFromJson( - { - compType: "Stack", - children: [RootDvModeManager.xComponentModel], - attributes: {alignContent: Alignment.TopStart}, - } + private static model : DVModel = createDVModelFromJson(new DVModelJson("Stack", [RootDvModeManager.xComponentModel], {alignContent: Alignment.TopStart},) + ); private static container : DVModelContainer = new DVModelContainer(RootDvModeManager.model); @@ -60,4 +69,4 @@ export class RootDvModeManager { public static addDvModel(model: DVModel): void { RootDvModeManager.container.model.children.push(model); } -} \ No newline at end of file +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ByteBuffer.ets index 5eed99c13c..99a7d4b522 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 @@ -37,12 +37,12 @@ export class ByteBuffer { * @returns A byte buffer. */ static from(source: ArrayBuffer, byteOffset?: number, byteLength?: number): ByteBuffer { - if (ArrayBuffer.isView(source)) { - byteOffset = source.byteOffset + (byteOffset || 0) - } + // if (ArrayBuffer.isView(source)) { + // byteOffset = source.byteOffset + (byteOffset || 0) + // } const byteBuffer = new ByteBuffer() byteBuffer.dataView = byteLength === undefined ? new DataView(source, byteOffset) : new DataView(source, byteOffset, Math.min(source.byteLength, byteLength)) - byteBuffer.#byteOffset = byteBuffer.dataView.byteOffset + byteBuffer.mByteOffset = byteBuffer.dataView.byteOffset return byteBuffer } @@ -54,14 +54,14 @@ export class ByteBuffer { /** * The byte offset. */ - #byteOffset: number = 0 + mByteOffset: number = 0 /** * The byte offset. * @returns The byte offset. */ get byteOffset(): number { - return this.#byteOffset + return this.mByteOffset } /** @@ -77,16 +77,16 @@ export class ByteBuffer { * @returns The number of bytes remaining. */ get bytesRemaining(): number { - return this.dataView.byteLength - this.#byteOffset + return this.dataView.byteLength - this.mByteOffset } hasRemaining(): boolean { - return this.#byteOffset < this.dataView.byteLength; + return this.mByteOffset < this.dataView.byteLength; } get buffer(): ArrayBuffer { - const dataBuffer = new DataView(new ArrayBuffer(this.#byteOffset)); - for (var i = 0; i < this.#byteOffset; i++) { + const dataBuffer = new DataView(new ArrayBuffer(this.mByteOffset)); + for (let i = 0; i < this.mByteOffset; i++) { dataBuffer.setUint8(i, this.dataView.getUint8(i)); } return dataBuffer.buffer @@ -97,14 +97,14 @@ export class ByteBuffer { * @param byteLength The byte length. */ skip(byteLength: number): void { - this.#byteOffset += byteLength + this.mByteOffset += byteLength } /** * Resets the byte offset. */ reset(): void { - this.#byteOffset = this.dataView.byteOffset + this.mByteOffset = this.dataView.byteOffset } /** @@ -118,9 +118,9 @@ export class ByteBuffer { * check buffer capacity. */ checkWriteCapacity(slen: number): void { - if (this.#byteOffset + slen > this.dataView.byteLength) { - var checkBuffer = new DataView(new ArrayBuffer(this.dataView.byteLength + slen + 512)); - for (var i = 0; i < this.#byteOffset; i++) { + if (this.mByteOffset + slen > this.dataView.byteLength) { + let checkBuffer = new DataView(new ArrayBuffer(this.dataView.byteLength + slen + 512)); + for (let i = 0; i < this.mByteOffset; i++) { checkBuffer.setUint8(i, this.dataView.getUint8(i)); } this.dataView = checkBuffer; @@ -139,7 +139,7 @@ export class ByteBuffer { * Reads the next boolean. */ readBool(): boolean { - return this.getInt8(this.#byteOffset++) !== 0 + return this.getInt8(this.mByteOffset++) !== 0 } /** @@ -157,7 +157,7 @@ export class ByteBuffer { */ writeBool(value: boolean): void { this.checkWriteCapacity(1) - this.setInt8(this.#byteOffset++, value ? 1 : 0) + this.setInt8(this.mByteOffset++, value ? 1 : 0) } /** @@ -174,7 +174,7 @@ export class ByteBuffer { * @returns The value. */ readInt8(): number { - return this.getInt8(this.#byteOffset++) + return this.getInt8(this.mByteOffset++) } /** @@ -192,7 +192,7 @@ export class ByteBuffer { */ writeInt8(value: number): void { this.checkWriteCapacity(1) - this.setInt8(this.#byteOffset++, value) + this.setInt8(this.mByteOffset++, value) } /** @@ -209,7 +209,7 @@ export class ByteBuffer { * @returns The value. */ readUint8(): number { - return this.getUint8(this.#byteOffset++) + return this.getUint8(this.mByteOffset++) } /** @@ -227,7 +227,7 @@ export class ByteBuffer { */ writeUint8(value: number): void { this.checkWriteCapacity(1) - this.setUint8(this.#byteOffset++, value) + this.setUint8(this.mByteOffset++, value) } /** @@ -246,8 +246,8 @@ export class ByteBuffer { * @returns The value. */ readInt16(littleEndian?: boolean): number { - const value = this.getInt16(this.#byteOffset, littleEndian) - this.#byteOffset += 2 + const value = this.getInt16(this.mByteOffset, littleEndian) + this.mByteOffset += 2 return value } @@ -268,8 +268,8 @@ export class ByteBuffer { */ writeInt16(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(2) - this.setInt16(this.#byteOffset, value, littleEndian) - this.#byteOffset += 2 + this.setInt16(this.mByteOffset, value, littleEndian) + this.mByteOffset += 2 } /** @@ -288,8 +288,8 @@ export class ByteBuffer { * @returns The value. */ readUint16(littleEndian?: boolean): number { - const value = this.getUint16(this.#byteOffset, littleEndian) - this.#byteOffset += 2 + const value = this.getUint16(this.mByteOffset, littleEndian) + this.mByteOffset += 2 return value } @@ -310,8 +310,8 @@ export class ByteBuffer { */ writeUint16(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(2) - this.setUint16(this.#byteOffset, value, littleEndian) - this.#byteOffset += 2 + this.setUint16(this.mByteOffset, value, littleEndian) + this.mByteOffset += 2 } /** @@ -330,8 +330,8 @@ export class ByteBuffer { * @returns The value. */ readInt32(littleEndian?: boolean): number { - const value = this.getInt32(this.#byteOffset, littleEndian) - this.#byteOffset += 4 + const value = this.getInt32(this.mByteOffset, littleEndian) + this.mByteOffset += 4 return value } @@ -352,8 +352,8 @@ export class ByteBuffer { */ writeInt32(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(4) - this.setInt32(this.#byteOffset, value, littleEndian) - this.#byteOffset += 4 + this.setInt32(this.mByteOffset, value, littleEndian) + this.mByteOffset += 4 } /** @@ -372,8 +372,8 @@ export class ByteBuffer { * @returns The value. */ readUint32(littleEndian?: boolean): number { - const value = this.getUint32(this.#byteOffset, littleEndian) - this.#byteOffset += 4 + const value = this.getUint32(this.mByteOffset, littleEndian) + this.mByteOffset += 4 return value } @@ -394,8 +394,8 @@ export class ByteBuffer { */ writeUint32(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(4) - this.setUint32(this.#byteOffset, value, littleEndian) - this.#byteOffset += 4 + this.setUint32(this.mByteOffset, value, littleEndian) + this.mByteOffset += 4 } /** @@ -414,8 +414,8 @@ export class ByteBuffer { * @returns The value. */ readFloat32(littleEndian?: boolean): number { - const value = this.getFloat32(this.#byteOffset, littleEndian) - this.#byteOffset += 4 + const value = this.getFloat32(this.mByteOffset, littleEndian) + this.mByteOffset += 4 return value } @@ -436,8 +436,8 @@ export class ByteBuffer { */ writeFloat32(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(4) - this.setFloat32(this.#byteOffset, value, littleEndian) - this.#byteOffset += 4 + this.setFloat32(this.mByteOffset, value, littleEndian) + this.mByteOffset += 4 } /** @@ -456,8 +456,8 @@ export class ByteBuffer { * @returns The value. */ readFloat64(littleEndian?: boolean): number { - const value = this.getFloat64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getFloat64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -478,8 +478,8 @@ export class ByteBuffer { */ writeFloat64(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setFloat64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setFloat64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -498,8 +498,8 @@ export class ByteBuffer { * @returns The value. */ readBigInt64(littleEndian?: boolean): bigint { - const value = this.getBigInt64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getBigInt64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -520,8 +520,8 @@ export class ByteBuffer { */ writeBigInt64(value: bigint, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setBigInt64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setBigInt64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -540,8 +540,8 @@ export class ByteBuffer { * @returns The value. */ readBigUint64(littleEndian?: boolean): bigint { - const value = this.getBigUint64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getBigUint64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -562,8 +562,8 @@ export class ByteBuffer { */ writeBigUint64(value: bigint, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setBigUint64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setBigUint64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -582,8 +582,8 @@ export class ByteBuffer { * @returns The value. */ readInt64(littleEndian?: boolean): number { - const value = this.getInt64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getInt64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -604,8 +604,8 @@ export class ByteBuffer { */ writeInt64(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setInt64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setInt64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -624,8 +624,8 @@ export class ByteBuffer { * @returns The value. */ readUint64(littleEndian?: boolean): number { - const value = this.getUint64(this.#byteOffset, littleEndian) - this.#byteOffset += 8 + const value = this.getUint64(this.mByteOffset, littleEndian) + this.mByteOffset += 8 return value } @@ -646,8 +646,8 @@ export class ByteBuffer { */ writeUint64(value: number, littleEndian?: boolean): void { this.checkWriteCapacity(8) - this.setUint64(this.#byteOffset, value, littleEndian) - this.#byteOffset += 8 + this.setUint64(this.mByteOffset, value, littleEndian) + this.mByteOffset += 8 } /** @@ -666,8 +666,8 @@ export class ByteBuffer { * @returns The value. */ readUint8Array(byteLength?: number): Uint8Array { - const value = this.getUint8Array(this.#byteOffset, byteLength) - this.#byteOffset += value.byteLength + const value = this.getUint8Array(this.mByteOffset, byteLength) + this.mByteOffset += value.byteLength return value } @@ -687,8 +687,8 @@ export class ByteBuffer { */ writeUint8Array(value: Uint8Array): void { this.checkWriteCapacity(value.byteLength) - this.setUint8Array(this.#byteOffset, value) - this.#byteOffset += value.byteLength + this.setUint8Array(this.mByteOffset, value) + this.mByteOffset += value.byteLength } /** @@ -710,8 +710,8 @@ export class ByteBuffer { * @returns The value. */ readUint16Array(byteLength?: number): Uint16Array { - const value = this.getUint16Array(this.#byteOffset, byteLength) - this.#byteOffset += value.byteLength + const value = this.getUint16Array(this.mByteOffset, byteLength) + this.mByteOffset += value.byteLength return value } @@ -731,8 +731,8 @@ export class ByteBuffer { */ writeUint16Array(value: Uint16Array): void { this.checkWriteCapacity(value.byteLength) - this.setUint16Array(this.#byteOffset, value) - this.#byteOffset += value.byteLength + this.setUint16Array(this.mByteOffset, value) + this.mByteOffset += value.byteLength } /** @@ -755,11 +755,11 @@ export class ByteBuffer { * @returns The value. */ readString(byteLength?: number, byteEncoding?: string): string { - const value = this.getString(this.#byteOffset, byteLength, byteEncoding) + const value = this.getString(this.mByteOffset, byteLength, byteEncoding) if (byteLength === undefined) { - this.#byteOffset = this.dataView.byteLength + this.mByteOffset = this.dataView.byteLength } else { - this.#byteOffset += byteLength + this.mByteOffset += byteLength } return value } @@ -781,7 +781,7 @@ export class ByteBuffer { this.checkWriteCapacity(byteLength) } const destination = this.getUint8Array(byteOffset, byteLength) - const { written } = encoder.encodeInto(value, destination) + const written = encoder.encodeInto(value, destination).written return written || 0 } @@ -791,8 +791,8 @@ export class ByteBuffer { * @param byteEncoding The byte encoding. */ writeString(value: string, byteEncoding?: string): void { - const byteLength = this.setString(this.#byteOffset, value, byteEncoding, true) - this.#byteOffset += byteLength + const byteLength = this.setString(this.mByteOffset, value, byteEncoding, true) + this.mByteOffset += byteLength } /** @@ -801,7 +801,7 @@ export class ByteBuffer { * @returns The string. */ toString(format?: string): string { - return Array.prototype.map.call(this.getUint8Array(0), function(byte: number): string { + return [...this.getUint8Array(0)].map((byte: number) => { switch(format) { case "hex": return ("00" + byte.toString(16)).slice(-2) diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets index cdec09bb74..437b52f180 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/Log.ets @@ -18,22 +18,22 @@ import HiLog from '@ohos.hilog'; const DOMAIN: number = 0x00FF; const TAG = "Flutter"; const SYMBOL = " --> "; -const FILTER_KEYS = [ - new RegExp('hide', "gi") -] +// const FILTER_KEYS = [ +// new RegExp('hide', "gi") +// ] -export function filterKey(target: any, propKey: string, descriptor: PropertyDescriptor) { - const original = descriptor.value; - descriptor.value = function (...args: string[]) { - let filterResult = args.map((str) => { - let tempStr = str - FILTER_KEYS.forEach((filterKey) => tempStr = tempStr.replace(filterKey, "**")) - return tempStr - }); - const result = original.call(this, ...filterResult); - return result; - }; -} +// export function filterKey(target: any, propKey: string, descriptor: PropertyDescriptor) { +// const original = descriptor.value; +// descriptor.value = function (...args: string[]) { +// let filterResult = args.map((str) => { +// let tempStr = str +// FILTER_KEYS.forEach((filterKey) => tempStr = tempStr.replace(filterKey, "**")) +// return tempStr +// }); +// const result = original.call(this, ...filterResult); +// return result; +// }; +// } /** * Basic log class @@ -47,7 +47,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static d(tag: string, format: string, ...args: any[]) { + static d(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.DEBUG)) { HiLog.debug(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -61,7 +61,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static i(tag: string, format: string, ...args: any[]) { + static i(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.INFO)) { HiLog.info(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -75,7 +75,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static w(tag: string, format: string, ...args: any[]) { + static w(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.WARN)) { HiLog.warn(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -89,7 +89,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static e(tag: string, format: string, ...args: any[]) { + static e(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.ERROR)) { HiLog.error(DOMAIN, TAG, tag + SYMBOL + format, args); } @@ -103,7 +103,7 @@ export default class Log { * @param args Indicates the log parameters. * @since 7 */ - static f(tag: string, format: string, ...args: any[]) { + static f(tag: string, format: string, ...args: ESObject[]) { if (Log.isLoggable(HiLog.LogLevel.FATAL)) { HiLog.fatal(DOMAIN, TAG, tag + SYMBOL + format, args); } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets index c7b5f9dc2f..c3879f4a40 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/ToolUtils.ets @@ -14,11 +14,11 @@ */ export default class ToolUtils { - static isObj(object: any): boolean { - return object && typeof (object) == 'object' && Object.prototype.toString.call(object).toLowerCase() == "[object object]"; + static isObj(object: Object): boolean { + return object && typeof (object) == 'object'; } - static implementsInterface(obj: any, method: string): boolean { + static implementsInterface(obj: ESObject, method: string): boolean { return Reflect.has(obj, method) && typeof obj[method] === 'function' } } \ No newline at end of file diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets index 7560012dc3..3caaadea7a 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/util/TraceSection.ets @@ -29,11 +29,11 @@ export class TraceSection { * @param sectionName The string to display as the section name in the trace. */ public static begin(sectionName: string): void { - hiTraceMeter.startTrace(this.cropSectionName(sectionName), this.taskId++); + hiTraceMeter.startTrace(TraceSection.cropSectionName(sectionName), TraceSection.taskId++); } /** Wraps Trace.endSection. */ public static end(sectionName: string): void { - hiTraceMeter.finishTrace(this.cropSectionName(sectionName), this.taskId); + hiTraceMeter.finishTrace(TraceSection.cropSectionName(sectionName), TraceSection.taskId); } } diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets index 403ce9c865..1c5f696e9f 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicView.ets @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import matrix4 from '@ohos.matrix4'; +import Log from '../../util/Log'; /** * Dynamic View creation @@ -67,9 +69,9 @@ export class DVModel { params: DVModelParameters; events: DVModelEvents; children: DVModelChildren; - builder: any; + builder: ESObject; - constructor(compType: string, params: DVModelParameters, events: DVModelEvents, children: DVModelChildren, builder?: any) { + constructor(compType: string, params: DVModelParameters, events: DVModelEvents, children: DVModelChildren, builder?: ESObject) { this.id_ = nextId++; this.compType = compType; this.params = params ?? new DVModelParameters; @@ -127,52 +129,61 @@ export struct DynamicView { @ObjectLink children: DVModelChildren; @ObjectLink params: DVModelParameters; @ObjectLink events: DVModelEvents; - @BuilderParam customBuilder?: ($$: { params: DVModelParameters }) => void; + @BuilderParam customBuilder?: ($$: BuilderParams) => void; + getParams: (params: DVModelParameters, element: string) => string | ESObject = (params: DVModelParameters, element: string): string | ESObject => { + let params2 = params as Record; + return params2[element]; + } + + getEvents: (events: DVModelEvents, element: string) => ESObject = (events: DVModelEvents, element: string): ESObject => { + let events2 = events as Record; + return events2[element]; + } /* we use this @Styles member function to set all common attributes and event handlers and set component specific attribute and event handler functions in the @Builder function */ @Styles common_attrs() { - .width(this.params["width"]) - .height(this.params["height"]) - .backgroundColor(this.params["backgroundColor"]) - .onClick(this.events["onClick"]) + .width(this.getParams(this.params, "width")) + .height(this.getParams(this.params, "height")) + .backgroundColor(this.getParams(this.params, "backgroundColor")) + .onClick(this.getEvents(this.events, "onClick")) .margin({ - left: this.params["marginLeft"], - right: this.params["marginRight"], - top: this.params["marginTop"], - bottom: this.params["marginBottom"] + left: this.getParams(this.params, "marginLeft"), + right: this.getParams(this.params, "marginRight"), + top: this.getParams(this.params, "marginTop"), + bottom: this.getParams(this.params, "marginBottom") }) - .onTouch(this.events["onTouch"]) - .onFocus(this.events['onFocus']) - .onBlur(this.events["onBlur"]) + .onTouch(this.getEvents(this.events, "onTouch")) + .onFocus(this.getEvents(this.events, "onFocus")) + .onBlur(this.getEvents(this.events, "onBlur")) .translate({ - x: this.params["translateX"], - y: this.params["translateY"], - z: this.params["translateZ"] + x: this.getParams(this.params, "translateX"), + y: this.getParams(this.params, "translateY"), + z: this.getParams(this.params, "translateZ") }) - .transform(this.params["matrix"]) - .direction(this.params["direction"]) + .transform(this.getParams(this.params, "matrix")) + .direction(this.getParams(this.params, "direction")) } @Styles clip_attrs() { - .clip(this.params["rectWidth"] ? new Rect({ - width: this.params["rectWidth"], - height: this.params["rectHeight"], - radius: this.params["rectRadius"] + .clip(this.getParams(this.params, "rectWidth") ? new Rect({ + width: this.getParams(this.params, "rectWidth"), + height: this.getParams(this.params, "rectHeight"), + radius: this.getParams(this.params, "rectRadius") }) : null) - .clip(this.params["pathWidth"] ? new Path({ - width: this.params["pathWidth"], - height: this.params["pathHeight"], - commands: this.params["pathCommands"] + .clip(this.getParams(this.params, "pathWidth") ? new Path({ + width: this.getParams(this.params, "pathWidth"), + height: this.getParams(this.params, "pathHeight"), + commands: this.getParams(this.params, "pathCommands") }) : null) } @Builder buildChildren() { ForEach(this.children, - child => { + (child: ESObject) => { DynamicView({ model: child as DVModel, params: child.params, @@ -181,7 +192,7 @@ export struct DynamicView { customBuilder: child.builder }) }, - child => `${child.id_}` + (child: ESObject) => `${child.id_}` ) } @@ -207,29 +218,29 @@ export struct DynamicView { } .common_attrs() .clip_attrs() - .alignContent(this.params["alignContent"]) + .alignContent(this.getParams(this.params, "alignContent")) } @Builder buildText() { - Text(`${this.params["value"]}`) + Text(`${this.getParams(this.params, "value")}`) .common_attrs() - .fontColor(this.params["fontColor"]) + .fontColor(this.getParams(this.params, "fontColor")) } @Builder buildImage() { - Image(this.params["src"]) + Image(this.getParams(this.params, "src")) .common_attrs() } // Button with label @Builder buildButton() { - Button(this.params["value"]) + Button(this.getParams(this.params, "value")) .common_attrs() } @Builder buildCustom() { if (this.customBuilder) { - this.customBuilder({ params: this.params }); + this.customBuilder(new BuilderParams(this.params)); } } @@ -251,3 +262,11 @@ export struct DynamicView { } } } + +export class BuilderParams { + params: DVModelParameters; + + constructor(params: DVModelParameters) { + this.params = params; + } +} diff --git a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets index b398c80222..57498b70d0 100644 --- a/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets +++ b/shell/platform/ohos/flutter_embedding/flutter/src/main/ets/view/DynamicView/dynamicViewJson.ets @@ -18,8 +18,7 @@ import { DVModel, DVModelParameters, DVModelEvents, DVModelChildren } from "./dy export function createDVModelFromJson(json: Object): DVModel { /* private use helper functions */ - - function createChildrenFrom(children: Array): DVModelChildren { + let createChildrenFrom: (children: Array) => DVModelChildren = (children: Array): DVModelChildren => { let result = new DVModelChildren(); if (Array.isArray(children)) { (children as Array).forEach(child => { @@ -32,18 +31,23 @@ export function createDVModelFromJson(json: Object): DVModel { return result; } - function createAttributesFrom(attributes: Object): DVModelParameters { + let setParams: (result: DVModelParameters | DVModelEvents, key: ESObject, element: Object ) => void = (result: DVModelParameters, key: ESObject, element: ESObject): void => { + let newResult = result as Record; + newResult[key] = element[key]; + } + + let createAttributesFrom: (attributes: Object) => DVModelParameters = (attributes: Object): DVModelParameters => { let result = new DVModelParameters(); if ((typeof attributes == "object") && (!Array.isArray(attributes))) { - Object.keys(attributes).forEach(k => result[k] = attributes[k]); + Object.keys(attributes).forEach(k => {setParams(result, k, attributes)}); } return result; } - function createEventsFrom(events: Object): DVModelEvents { + let createEventsFrom: (events: Object) => DVModelEvents = (events: Object): DVModelEvents => { let result = new DVModelEvents(); if ((typeof events == "object") && (!Array.isArray(events))) { - Object.keys(events).forEach(k => result[k] = events[k]); + Object.keys(events).forEach(k => {setParams(result, k, events)}); } return result; } @@ -53,11 +57,12 @@ export function createDVModelFromJson(json: Object): DVModel { return undefined; } + let jsonObject = json as Record; return new DVModel( - json["compType"], - createAttributesFrom(json["attributes"]), - createEventsFrom(json["events"]), - createChildrenFrom(json["children"]), - json["build"] + jsonObject["compType"], + createAttributesFrom(jsonObject["attributes"]), + createEventsFrom(jsonObject["events"]), + createChildrenFrom(jsonObject["children"]), + jsonObject["build"] ); } -- Gitee