diff --git a/templates/harmonyos-next/entry/src/main/ets/common/CallbacksInvoker.ts b/templates/harmonyos-next/entry/src/main/ets/common/CallbacksInvoker.ts new file mode 100644 index 0000000000..6b56e52616 --- /dev/null +++ b/templates/harmonyos-next/entry/src/main/ets/common/CallbacksInvoker.ts @@ -0,0 +1,406 @@ +/* + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { Pool } from './Pool'; +import { createMap } from './Utils'; + + +enum MessageType { + SYNC = 0, + ASYNC = 1 +} +/** + * @zh + * 移除指定索引的数组元素。 + * 此函数十分高效,但会改变数组的元素次序。 + * @en + * Removes the array item at the specified index. + * It's faster but the order of the array will be changed. + * @param array @zh 被操作的数组。@en The array to be operated. + * @param index @zh 待移除元素的索引。@en The index of the element to be removed. + */ +export function fastRemoveAt(array: T[], index: number): void { + const length = array.length; + if (index < 0 || index >= length) { + return; + } + array[index] = array[length - 1]; + array.length = length - 1; +} + + +function empty(): void { } +type AnyFunction = Function; + +class CallbackInfo { + public callback: AnyFunction = empty; + public target: unknown = undefined; + public once = false; + + constructor() { } + + public set(callback: AnyFunction, target?: unknown, once?: boolean): void { + this.callback = callback || empty; + this.target = target; + this.once = !!once; + } + + public reset(): void { + this.target = undefined; + this.callback = empty; + this.once = false; + } +} + +const callbackInfoPool = new Pool(() => new CallbackInfo(), 32); +/** + * @zh 事件监听器列表的简单封装。 + * @en A simple list of event callbacks + */ +export class CallbackList { + public callbackInfos: Array = []; + public isInvoking = false; + public containCanceled = false; + + constructor() { } + + /** + * @zh 从列表中移除与指定目标相同回调函数的事件。 + * @en Remove the event listeners with the given callback from the list + * + * @param cb - The callback to be removed + */ + public removeByCallback(cb: AnyFunction): void { + for (let i = 0; i < this.callbackInfos.length; ++i) { + const info = this.callbackInfos[i]; + if (info && info.callback === cb) { + info.reset(); + callbackInfoPool.free(info); + fastRemoveAt(this.callbackInfos, i); + --i; + } + } + } + /** + * @zh 从列表中移除与指定目标相同调用者的事件。 + * @en Remove the event listeners with the given target from the list + * @param target + */ + public removeByTarget(target: unknown): void { + for (let i = 0; i < this.callbackInfos.length; ++i) { + const info = this.callbackInfos[i]; + if (info && info.target === target) { + info.reset(); + callbackInfoPool.free(info); + fastRemoveAt(this.callbackInfos, i); + --i; + } + } + } + + /** + * @zh 移除指定编号事件。 + * @en Remove the event listener at the given index + * @param index + */ + public cancel(index: number): void { + const info = this.callbackInfos[index]; + if (info) { + info.reset(); + if (this.isInvoking) { + this.callbackInfos[index] = null; + } else { + fastRemoveAt(this.callbackInfos, index); + } + callbackInfoPool.free(info); + } + this.containCanceled = true; + } + + /** + * @zh 注销所有事件。 + * @en Cancel all event listeners + */ + public cancelAll(): void { + for (let i = 0; i < this.callbackInfos.length; i++) { + const info = this.callbackInfos[i]; + if (info) { + info.reset(); + callbackInfoPool.free(info); + this.callbackInfos[i] = null; + } + } + this.containCanceled = true; + } + + /** + * @zh 立即删除所有取消的回调。(在移除过程中会更加紧凑的排列数组) + * @en Delete all canceled callbacks and compact array + */ + public purgeCanceled(): void { + for (let i = this.callbackInfos.length - 1; i >= 0; --i) { + const info = this.callbackInfos[i]; + if (!info) { + fastRemoveAt(this.callbackInfos, i); + } + } + this.containCanceled = false; + } + + /** + * @zh 清除并重置所有数据。 + * @en Clear all data + */ + public clear(): void { + this.cancelAll(); + this.callbackInfos.length = 0; + this.isInvoking = false; + this.containCanceled = false; + } +} + +const MAX_SIZE = 16; +const callbackListPool = new Pool(() => new CallbackList(), MAX_SIZE); + +export interface ICallbackTable { + [x: string]: CallbackList | undefined; +} + +export interface ISyncCallbackTable { + [x: string]: CallbackInfo | undefined; +} + +type EventType = string | number; +/** + * @zh CallbacksInvoker 用来根据事件名(Key)管理事件监听器列表并调用回调方法。 + * @en CallbacksInvoker is used to manager and invoke event listeners with different event keys, + * each key is mapped to a CallbackList. + * @engineInternal + */ +export class CallbacksInvoker { + /** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ + public _callbackTable: ICallbackTable = createMap(true); + private _offCallback?: () => void; + + constructor() { } + + /** + * @zh 向一个事件名注册一个新的事件监听器,包含回调函数和调用者 + * @en Register an event listener to a given event key with callback and target. + * + * @param key - Event type + * @param callback - Callback function when event triggered + * @param target - Callback callee + * @param once - Whether invoke the callback only once (and remove it) + */ + public on(key: EventTypeClass, callback: AnyFunction, target?: unknown, once?: boolean): AnyFunction { + if (!this.hasEventListener(key, callback, target)) { + let list = this._callbackTable[key]; + if (!list) { + list = this._callbackTable[key] = callbackListPool.alloc(); + } + const info = callbackInfoPool.alloc(); + info.set(callback, target, once); + list.callbackInfos.push(info); + } + return callback; + } + + /** + * @zh 检查指定事件是否已注册回调。 + * @en Checks whether there is correspond event listener registered on the given event + * @param key - Event type + * @param callback - Callback function when event triggered + * @param target - Callback callee + */ + public hasEventListener(key: EventTypeClass, callback?: AnyFunction, target?: unknown): boolean { + const list = this._callbackTable && this._callbackTable[key]; + if (!list) { + return false; + } + + // check any valid callback + const infos = list.callbackInfos; + if (!callback) { + // Make sure no cancelled callbacks + if (list.isInvoking) { + for (let i = 0; i < infos.length; ++i) { + if (infos[i]) { + return true; + } + } + return false; + } else { + return infos.length > 0; + } + } + + for (let i = 0; i < infos.length; ++i) { + const info = infos[i]; + if (info && info.callback === callback && info.target === target) { + return true; + } + } + return false; + } + + /** + * @zh 移除在特定事件类型中注册的所有回调或在某个目标中注册的所有回调。 + * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target + * @param keyOrTarget - The event type or target with which the listeners will be removed + */ + public removeAll(keyOrTarget: unknown): void { + const type = typeof keyOrTarget; + if (type === 'string' || type === 'number') { + // remove by key + const list = this._callbackTable && this._callbackTable[keyOrTarget as string | number]; + if (list) { + if (list.isInvoking) { + list.cancelAll(); + } else { + list.clear(); + callbackListPool.free(list); + delete this._callbackTable[keyOrTarget as string | number]; + } + } + } else if (keyOrTarget) { + // remove by target + for (const key in this._callbackTable) { + const list = this._callbackTable[key]!; + if (list.isInvoking) { + const infos = list.callbackInfos; + for (let i = 0; i < infos.length; ++i) { + const info = infos[i]; + if (info && info.target === keyOrTarget) { + list.cancel(i); + } + } + } else { + list.removeByTarget(keyOrTarget); + } + } + } + } + + /** + * @zh 删除以指定事件,回调函数,目标注册的回调。 + * @en Remove event listeners registered with the given event key, callback and target + * @param key - Event type + * @param callback - The callback function of the event listener, if absent all event listeners for the given type will be removed + * @param target - The callback callee of the event listener + */ + public off(key: EventTypeClass, callback?: AnyFunction, target?: unknown): void { + const list = this._callbackTable && this._callbackTable[key]; + if (list) { + const infos = list.callbackInfos; + if (callback) { + for (let i = 0; i < infos.length; ++i) { + const info = infos[i]; + if (info && info.callback === callback && info.target === target) { + list.cancel(i); + break; + } + } + } else { + this.removeAll(key); + } + } + this._offCallback?.(); + } + + /** + * @zh 派发一个指定事件,并传递需要的参数 + * @en Trigger an event directly with the event name and necessary arguments. + * @param key - event type + * @param arg0 - The first argument to be passed to the callback + * @param arg1 - The second argument to be passed to the callback + * @param arg2 - The third argument to be passed to the callback + * @param arg3 - The fourth argument to be passed to the callback + * @param arg4 - The fifth argument to be passed to the callback + */ + public emit(key: EventTypeClass, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any, arg9?: any, + arg10?: any, arg11?: any, arg12?: any, arg13?: any, arg14?: any, arg15?: any, arg16?: any, arg17?: any, arg18?: any): any { + const list: CallbackList = this._callbackTable && this._callbackTable[key]!; + let result = null; + if (list) { + const rootInvoker = !list.isInvoking; + list.isInvoking = true; + const infos = list.callbackInfos; + for (let i = 0, len = infos.length; i < len; ++i) { + const info = infos[i]; + if (info) { + const callback = info.callback; + const target = info.target; + // Pre off once callbacks to avoid influence on logic in callback + if (info.once) { + this.off(key, callback, target); + } + + if (target) { + result = callback.call(target, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18); + } else { + result = callback(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18); + } + } + } + + if (result != undefined && infos.length > 1) { + console.warn("If we listen to multiple callbacks with return values, only the last callback's return value is valid."); + } + + if (rootInvoker) { + list.isInvoking = false; + if (list.containCanceled) { + list.purgeCanceled(); + } + } + } + return result; + } + + /** + * 移除所有回调。 + */ + public clear(): void { + for (const key in this._callbackTable) { + const list = this._callbackTable[key]; + if (list) { + list.clear(); + callbackListPool.free(list); + delete this._callbackTable[key]; + } + } + } + + /** + * @engineInternal + * @mangle + */ + public _registerOffCallback(cb: () => void): void { + this._offCallback = cb; + } +} diff --git a/templates/harmonyos-next/entry/src/main/ets/common/EventTarget.ts b/templates/harmonyos-next/entry/src/main/ets/common/EventTarget.ts new file mode 100644 index 0000000000..fef1ed7773 --- /dev/null +++ b/templates/harmonyos-next/entry/src/main/ets/common/EventTarget.ts @@ -0,0 +1,43 @@ +/* + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { Eventify } from './Eventify'; + +class Empty { } + +/** + * @en + * EventTarget is an object to which an event is dispatched when something has occurred. + * [[Node]]s are the most common event targets, but other objects can be event targets too. + * If a class cannot extend from EventTarget, it can consider using [[Eventify]]. + * + * @zh + * 事件目标是具有注册监听器、派发事件能力的类,[[Node]] 是最常见的事件目标, + * 但是其他类也可以继承自事件目标以获得管理监听器和派发事件的能力。 + * 如果无法继承自 EventTarget,也可以使用 [[Eventify]] + */ +export const EventTarget = Eventify(Empty); + +export type EventTarget = InstanceType; diff --git a/templates/harmonyos-next/entry/src/main/ets/common/Eventify.ts b/templates/harmonyos-next/entry/src/main/ets/common/Eventify.ts new file mode 100644 index 0000000000..4f2a7795ed --- /dev/null +++ b/templates/harmonyos-next/entry/src/main/ets/common/Eventify.ts @@ -0,0 +1,189 @@ +/* + Copyright (c) 2020-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { CallbacksInvoker } from './CallbacksInvoker'; +import { createMap } from './Utils'; + +type Constructor = new (...args: any[]) => T; + +type EventType = string | number; + +/** + * @zh + * 实现该接口的对象具有处理事件的能力。 + * @en + * Objects those implement this interface have essentially the capability to process events. + */ +export interface IEventified { + /** + * @zh 检查指定事件是否已注册回调。 + * @en Checks whether there is correspond event listener registered on the given event. + * @param type - Event type. + * @param callback - Callback function when event triggered. + * @param target - Callback callee. + */ + hasEventListener(type: string, callback?: (...args: any[]) => void, target?: any): boolean; + + /** + * @en + * Register an callback of a specific event type on the EventTarget. + * This type of event should be triggered via `emit`. + * @zh + * 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。 + * + * @param type - A string representing the event type to listen for. + * @param callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param thisArg - The target (this object) to invoke the callback, can be null + * @return - Just returns the incoming callback so you can save the anonymous function easier. + * @example + * import { log } from 'cc'; + * eventTarget.on('fire', function () { + * log("fire in the hole"); + * }, node); + */ + on void>(type: EventType, callback: TFunction, thisArg?: any, once?: boolean): typeof callback; + + /** + * @en + * Register an callback of a specific event type on the EventTarget, + * the callback will remove itself after the first time it is triggered. + * @zh + * 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 + * + * @param type - A string representing the event type to listen for. + * @param callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param target - The target (this object) to invoke the callback, can be null + * @example + * import { log } from 'cc'; + * eventTarget.once('fire', function () { + * log("this is the callback and will be invoked only once"); + * }, node); + */ + once void>(type: EventType, callback: TFunction, thisArg?: any): typeof callback; + + /** + * @en + * Removes the listeners previously registered with the same type, callback, target and or useCapture, + * if only type is passed as parameter, all listeners registered with that type will be removed. + * @zh + * 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 + * + * @param type - A string representing the event type being removed. + * @param callback - The callback to remove. + * @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed + * @example + * import { log } from 'cc'; + * // register fire eventListener + * var callback = eventTarget.on('fire', function () { + * log("fire in the hole"); + * }, target); + * // remove fire event listener + * eventTarget.off('fire', callback, target); + * // remove all fire event listeners + * eventTarget.off('fire'); + */ + off void>(type: EventType, callback?: TFunction, thisArg?: any): void; + + /** + * @en Removes all callbacks previously registered with the same target (passed as parameter). + * This is not for removing all listeners in the current event target, + * and this is not for removing all listeners the target parameter have registered. + * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. + * @zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 + * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 + * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 + * @param typeOrTarget - The target to be searched for all related listeners + */ + targetOff(typeOrTarget: any): void; + + /** + * @zh 移除在特定事件类型中注册的所有回调或在某个目标中注册的所有回调。 + * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target + * @param typeOrTarget - The event type or target with which the listeners will be removed + */ + removeAll(typeOrTarget: any): void; + + /** + * @zh 派发一个指定事件,并传递需要的参数 + * @en Trigger an event directly with the event name and necessary arguments. + * @param type - event type + * @param args - Arguments when the event triggered + */ + emit(type: EventType, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any, arg9?: any, + arg10?: any, arg11?: any, arg12?: any, arg13?: any, arg14?: any, arg15?: any, arg16?: any, arg17?: any, arg18?: any): any; +} + +/** + * @en Generate a new class from the given base class, after polyfill all functionalities in [[IEventified]] as if it's extended from [[EventTarget]] + * @zh 生成一个类,该类继承自指定的基类,并以和 [[EventTarget]] 等同的方式实现了 [[IEventified]] 的所有接口。 + * @param base The base class + * @example + * ```ts + * class Base { say() { console.log('Hello!'); } } + * class MyClass extends Eventify(Base) { } + * function (o: MyClass) { + * o.say(); // Ok: Extend from `Base` + * o.emit('sing', 'The ghost'); // Ok: `MyClass` implements IEventified + * } + * ``` + */ +export function Eventify(base: Constructor): Constructor { + class Eventified extends (base as unknown as any) { + /** + * @dontmangle + * NOTE: Eventified mixins all properties from CallbacksInvoker.prototype in the following code. + * After invoking `Eventify` for a class, CallbacksInvoker's constructor will not be called, + * but its functions may invoke `this._callbackTable` which is declared as `public` in CallbacksInvoker. + * Marking it as dontmangle is a workaround to avoid the issue that `this._callbackTable` is not defined. + */ + protected _callbackTable = createMap(true); + + public once void>(type: EventType, callback: Callback, target?: any): Callback { + return this.on(type, callback, target, true) as Callback; + } + + public targetOff(typeOrTarget: any): void { + this.removeAll(typeOrTarget); + } + } + + // Mixin with `CallbacksInvokers`'s prototype + const callbacksInvokerPrototype = CallbacksInvoker.prototype; + const propertyKeys: (string | symbol)[] = (Object.getOwnPropertyNames(callbacksInvokerPrototype) as (string | symbol)[]).concat( + Object.getOwnPropertySymbols(callbacksInvokerPrototype), + ); + for (let iPropertyKey = 0; iPropertyKey < propertyKeys.length; ++iPropertyKey) { + const propertyKey = propertyKeys[iPropertyKey]; + if (!(propertyKey in Eventified.prototype)) { + const propertyDescriptor = Object.getOwnPropertyDescriptor(callbacksInvokerPrototype, propertyKey); + if (propertyDescriptor) { + Object.defineProperty(Eventified.prototype, propertyKey, propertyDescriptor); + } + } + } + + return Eventified as unknown as Constructor; +} diff --git a/templates/harmonyos-next/entry/src/main/ets/common/Pool.ts b/templates/harmonyos-next/entry/src/main/ets/common/Pool.ts new file mode 100644 index 0000000000..3019a38964 --- /dev/null +++ b/templates/harmonyos-next/entry/src/main/ets/common/Pool.ts @@ -0,0 +1,152 @@ +/* + Copyright (c) 2020-2023 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * @en Typed object pool. + * It's a traditional design, you can get elements out of the pool or recycle elements by putting back into the pool. + * @zh 支持类型的对象池。这是一个传统设计的对象池,你可以从对象池中取出对象或是放回不再需要对象来复用。 + * @see [[RecyclePool]] + */ +export class Pool { + private declare _ctor: () => T; + private declare _elementsPerBatch: number; + private declare _shrinkThreshold: number; + private declare _nextAvail: number; + private _freePool: T[] = []; + private declare _dtor: ((obj: T) => void) | null; + + /** + * @en Constructor with the allocator of elements and initial pool size. + * @zh 使用元素的构造器和初始大小的构造函数。 + * @param ctor @en The allocator of elements in pool, it's invoked directly without `new` in Pool. + * @zh 元素的构造器,Pool 内部使用该构造器直接创建实例。 + * @param elementsPerBatch @en Initial pool size, this size will also be the incremental size when + * the pool is overloaded. + * @zh 对象池的初始大小。当对象池扩容时,也会使用该值。 + * @param dtor @en The finalizer of element, it's invoked when this Pool is destroyed or shrunk if + * it is valid. + * @zh 元素的析构器。如果存在的话,当对象池销毁或者缩容时,会使用该析构器。 + * @param shrinkThreshold @en The container is shrink only if the size of the container exceeds the shrinkThreshold, + * and the size of the container after reduction is greater than or equal to the shrinkThreshold. The value equals elementsPerBatch + * if not value is passed. + * @zh 只有容器的数量大于 shrinkThreshold 时才缩容,缩减后的容器大小小于等于 shrinkThreshold。如果没有传入值,那么它的值和 elementsPerBatch 相同。 + */ + constructor (ctor: () => T, elementsPerBatch: number, dtor?: (obj: T) => void, shrinkThreshold?: number) { + this._ctor = ctor; + this._dtor = dtor || null; + this._elementsPerBatch = Math.max(elementsPerBatch, 1); + this._shrinkThreshold = shrinkThreshold ? Math.max(shrinkThreshold, 1) : this._elementsPerBatch; + this._nextAvail = this._elementsPerBatch - 1; + + for (let i = 0; i < this._elementsPerBatch; ++i) { + this._freePool.push(ctor()); + } + } + + /** + * @en Take an object out of the object pool. + * @zh 从对象池中取出一个对象。 + * @returns @en An object ready for use. This function always returns an object. + * @zh 该函数总是返回一个可用的对象。 + */ + public alloc (): T { + if (this._nextAvail < 0) { + this._freePool.length = this._elementsPerBatch; + for (let i = 0; i < this._elementsPerBatch; i++) { + this._freePool[i] = this._ctor(); + } + this._nextAvail = this._elementsPerBatch - 1; + } + + return this._freePool[this._nextAvail--]; + } + + /** + * @en Put an object back into the object pool. + * @zh 将一个对象放回对象池中。 + * @param obj @en The object to be put back into the pool. + * @zh 放回对象池中的对象。 + */ + public free (obj: T): void { + this._freePool[++this._nextAvail] = obj; + } + + /** + * @en Put multiple objects back into the object pool. + * @zh 将一组对象放回对象池中。 + * @param objs @en An array of objects to be put back into the pool. + * @zh 放回对象池中的一组对象。 + */ + public freeArray (objs: T[]): void { + this._freePool.length = this._nextAvail + 1; + Array.prototype.push.apply(this._freePool, objs); + this._nextAvail += objs.length; + } + + /** + * @en Try to shrink the object pool to reduce memory usage. + * @zh 尝试缩容对象池,以释放内存。 + */ + public tryShrink (): void { + const freeObjectNumber = this._nextAvail + 1; + if (freeObjectNumber <= this._shrinkThreshold) { + return; + } + + let objectNumberToShrink = 0; + if (freeObjectNumber >> 1 >= this._shrinkThreshold) { + objectNumberToShrink = freeObjectNumber >> 1; + } else { + objectNumberToShrink = Math.floor((freeObjectNumber - this._shrinkThreshold + 1) / 2); + } + + if (this._dtor) { + for (let i = this._nextAvail - objectNumberToShrink + 1; i <= this._nextAvail; ++i) { + this._dtor(this._freePool[i]); + } + } + this._nextAvail -= objectNumberToShrink; + this._freePool.length = this._nextAvail + 1; + } + + /** + * @en Destroy all elements and clear the pool. + * @zh 释放对象池中所有资源并清空缓存池。 + */ + public destroy (): void { + const dtor = arguments.length > 0 ? arguments[0] : null; + if (dtor) { + console.warn("Pool.destroy no longer take a function as parameter, Please specify destruct function in the construction of Pool instead"); + return; + } + const readDtor = dtor || this._dtor; + if (readDtor) { + for (let i = 0; i <= this._nextAvail; i++) { + readDtor(this._freePool[i]); + } + } + this._freePool.length = 0; + this._nextAvail = -1; + } +} diff --git a/templates/harmonyos-next/entry/src/main/ets/common/Utils.ts b/templates/harmonyos-next/entry/src/main/ets/common/Utils.ts new file mode 100644 index 0000000000..6ec0246646 --- /dev/null +++ b/templates/harmonyos-next/entry/src/main/ets/common/Utils.ts @@ -0,0 +1,29 @@ +/** + * @en + * A simple wrapper of `Object.create(null)` which ensures the return object have no prototype (and thus no inherited members). + * This eliminates the need to make `hasOwnProperty` judgments when we look for values by key on the object, + * which is helpful for performance in this case. + * @zh + * 该方法是对 `Object.create(null)` 的简单封装。 + * `Object.create(null)` 用于创建无 prototype (也就无继承)的空对象。 + * 这样我们在该对象上查找属性时,就不用进行 `hasOwnProperty` 判断,此时对性能提升有帮助。 + * + * @param forceDictMode @en Apply the delete operator to newly created map object. This will let V8 put the object in + * "dictionary mode" and disables creation of hidden classes. This will improve the performance of objects that are + * constantly changing shape. + * @zh 对新创建的地图对象应用删除操作。这将让V8将对象置于 "字典模式",并禁止创建隐藏类。这将提高那些不断变化形状对象的性能。 + * @returns @en A newly map object. @zh 一个新的 map 对象。 + */ +export function createMap (forceDictMode?: boolean): any { + const map = Object.create(null); + if (forceDictMode) { + const INVALID_IDENTIFIER_1 = '.'; + const INVALID_IDENTIFIER_2 = '/'; + // assign dummy values on the object + map[INVALID_IDENTIFIER_1] = 1; + map[INVALID_IDENTIFIER_2] = 1; + delete map[INVALID_IDENTIFIER_1]; + delete map[INVALID_IDENTIFIER_2]; + } + return map; +} diff --git a/templates/harmonyos-next/entry/src/main/ets/common/PortProxy.ts b/templates/harmonyos-next/entry/src/main/ets/common/WorkerPort.ts similarity index 59% rename from templates/harmonyos-next/entry/src/main/ets/common/PortProxy.ts rename to templates/harmonyos-next/entry/src/main/ets/common/WorkerPort.ts index 0c06ca5c95..88ede53a48 100644 --- a/templates/harmonyos-next/entry/src/main/ets/common/PortProxy.ts +++ b/templates/harmonyos-next/entry/src/main/ets/common/WorkerPort.ts @@ -22,55 +22,87 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import { ThreadWorkerGlobalScope } from '@ohos.worker'; +import worker, { ThreadWorkerGlobalScope } from '@ohos.worker'; import { MessageEvent } from '@ohos.worker'; +import { MessageEvents } from '@kit.ArkTS'; +import { EventTarget } from './EventTarget' -export class PortProxy { +let port: WorkerPort; + +export class WorkerPort extends EventTarget { private autoId: number = 0; public actionHandleMap = {} - private port: ThreadWorkerGlobalScope = null; + private port: worker.ThreadWorker = null; public _messageHandle?: (e: MessageEvent) => void; - constructor(worker) { + constructor() { + super(); + } + + static getInstance (): WorkerPort { + if (!port) { + port = new WorkerPort(); + } + return port; + } + + public initPort(worker: worker.ThreadWorker) { this.port = worker; this.port.onmessage = this.onMessage.bind(this); } - public onMessage(e) { + public getPort() : worker.ThreadWorker { + return this.port; + } + + public onMessage(e: MessageEvents) { let data = e['data']; - if (data.type != "syncResult" && this._messageHandle) { - this._messageHandle(e); - } else if (data.type == "syncResult") { + if (data.type == "syncResult") { const { id, response } = data.data; if (!this.actionHandleMap[id]) { return; } this.actionHandleMap[id].call(this, response); delete this.actionHandleMap[id]; + } else { + let params = []; + if (data.data.param === null || data.data.param === undefined) { + params = []; + } else if (Array.isArray(data.data.param)) { + params = data.data.param; + } else if (typeof data.data.param === 'object') { + params = Object.values(data.data.param); + } else { + params = [data.data.param]; + } + const result = this.emit(data.data.name, ...params); + if(result != null && result != undefined && data.type == "sync") { + this.postReturnMessage(data.data.cbId, result); + } } } - public postReturnMessage(e: any, res: any) { - if (e.type == "sync" && res != null && res != undefined) { - this.port.postMessage({ type: "syncResult", data: { id: e.data.cbId, response: res } }); + public postReturnMessage(cbId: number, res: any) { + if (res != null && res != undefined) { + this.port.postMessage({ type: "syncResult", data: { id: cbId, response: res } }); } } - public postMessage(msgName: string, msgData: any) { - this.port.postMessage({ type: "async", data: { name: msgName, param: msgData } }); + public postMessage(msgName: string, msgData?: any) { + this.port.postMessage({ type: "async", data: { name: msgName, param: msgData ?? null } }); } - public postSyncMessage(msgName: string, msgData: any) { + public postSyncMessage(msgName: string, msgData: any): Promise { const id = this.autoId++; return new Promise((resolve, reject) => { + this.actionHandleMap[id] = (response) => { + resolve(response) + } const message = { type: "sync", data: { cbId: id, name: msgName, param: msgData } } this.port.postMessage(message); - this.actionHandleMap[id] = (response) => { - resolve(response) - } }) } } \ No newline at end of file diff --git a/templates/harmonyos-next/entry/src/main/ets/components/CocosVideoPlayer.ets b/templates/harmonyos-next/entry/src/main/ets/components/CocosVideoPlayer.ets index 679d4799ce..0a522b51f7 100644 --- a/templates/harmonyos-next/entry/src/main/ets/components/CocosVideoPlayer.ets +++ b/templates/harmonyos-next/entry/src/main/ets/components/CocosVideoPlayer.ets @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import { PortProxy } from '../common/PortProxy'; +import { WorkerPort } from '../common/WorkerPort'; enum EventType { PLAYING = 0, @@ -76,7 +76,7 @@ export class VideoInfo { @Component export struct CocosVideoPlayer { @ObjectLink videoInfo: VideoInfo; - public workPort: PortProxy | null = null; + public workPort: WorkerPort | null = null; build() { Video({ diff --git a/templates/harmonyos-next/entry/src/main/ets/components/CocosWebView.ets b/templates/harmonyos-next/entry/src/main/ets/components/CocosWebView.ets index 9368735ca1..8b20ba6f99 100644 --- a/templates/harmonyos-next/entry/src/main/ets/components/CocosWebView.ets +++ b/templates/harmonyos-next/entry/src/main/ets/components/CocosWebView.ets @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import { PortProxy } from '../common/PortProxy'; +import { WorkerPort } from '../common/WorkerPort'; import web from '@ohos.web.webview'; interface param { @@ -30,6 +30,12 @@ interface param { url: string, } +export enum LoadType { + URL, + HTML_STRING, + DATA, +} + @Observed export class WebViewInfo { // position @@ -39,11 +45,18 @@ export class WebViewInfo { public w: number = 0; public h: number = 0; // url - public url: string = ''; + public url?: string; // tag public viewTag: number = 0; // Whether to display public visible: boolean = true; + public isInited: boolean = false; + public contents?: string; + public baseUrl?: string; + public mimeType?: string; + public encoding?: string; + public loadType: LoadType = LoadType.URL; + public jsContents?: string; /* * doc : https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md#webcontroller */ @@ -57,9 +70,27 @@ export class WebViewInfo { this.viewTag = viewTag; web.once("webInited", () => { - if (this.url != '') { - this.controller.loadUrl(this.url); - } + this.isInited = true; + if(this.loadType == LoadType.URL) { + this.controller.loadUrl(this.url); + } else if(this.loadType == LoadType.DATA) { + this.controller.loadData( + this.contents, + this.mimeType, + this.encoding, + this.baseUrl + ); + } else if(this.loadType == LoadType. HTML_STRING) { + this.controller.loadData( + this.contents, + "text/html", + "UTF-8", + this.baseUrl + ); + } + if(this.jsContents && this.jsContents?.length > 0) { + this.controller.runJavaScript(this.jsContents); + } }); } } @@ -67,7 +98,7 @@ export class WebViewInfo { @Component export struct CocosWebView { @ObjectLink viewInfo: WebViewInfo; - public workPort: PortProxy | null = null; + public workPort: WorkerPort | null = null; build() { Web({ src: this.viewInfo.url, controller: this.viewInfo.controller }) diff --git a/templates/harmonyos-next/entry/src/main/ets/components/EditBoxDialog.ets b/templates/harmonyos-next/entry/src/main/ets/components/EditBoxDialog.ets index f8f587a441..5a8636f884 100644 --- a/templates/harmonyos-next/entry/src/main/ets/components/EditBoxDialog.ets +++ b/templates/harmonyos-next/entry/src/main/ets/components/EditBoxDialog.ets @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +import { WorkerPort } from '../common/WorkerPort'; @Observed export class EditboxShowInfo { public backgroundColor: number = 0xFFFFFFFF; @@ -40,18 +41,15 @@ export class EditboxShowInfo { export struct EditBoxDialog { private inputMessage: string = '' @ObjectLink showInfo: EditboxShowInfo; - onTextChange?: (msg: string) => void; - accept?: (msg: string) => void; + controller?: CustomDialogController; - cancel?: () => void; - confirm?: (msg: string) => void; + workPort?: WorkerPort; build() { Column() { Row() { TextInput({ text: this.showInfo.defaultMessage }) .defaultFocus(true) - .backgroundColor('#ffffff') .backgroundColor(this.showInfo.backgroundColor) .type(this.showInfo.type) .maxLength(this.showInfo.maxLength) @@ -60,22 +58,20 @@ export struct EditBoxDialog { .enterKeyType(this.showInfo.enterKeyType) .layoutWeight(1) .onChange((value) => { - if (this.onTextChange) { - this.onTextChange(value); - } + this.showInfo.defaultMessage = value; + this.workPort?.postMessage('onTextInput', value); this.inputMessage = value; }) .onSubmit((value) => { - if(this.confirm) { - this.confirm(this.inputMessage); - } + this.showInfo.defaultMessage = this.inputMessage; + this.workPort?.postMessage('onConfirm', this.inputMessage); + this.workPort?.postMessage('onComplete', this.inputMessage); this.controller?.close(); }) Blank(8).width(16) Button('完成').onClick(() => { - if (this.accept) { - this.accept(this.inputMessage); - } + this.showInfo.defaultMessage = this.inputMessage; + this.workPort?.postMessage('onComplete', this.inputMessage); this.controller?.close(); }) }.padding({ left: 8, right: 8, top: 8, bottom: 8 }) diff --git a/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ets b/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ets index c5fbeeabc3..5f054c726d 100644 --- a/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ets +++ b/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ets @@ -15,7 +15,6 @@ export default class EntryAbility extends UIAbility { private windowStageType: windowStageType = windowStageType.hide; onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { - globalThis.abilityWant = want; nativeAppLifecycle.onCreate(); nativeContext.resourceManagerInit(this.context.resourceManager); } diff --git a/templates/harmonyos-next/entry/src/main/ets/pages/index.ets b/templates/harmonyos-next/entry/src/main/ets/pages/index.ets index f63686155d..d4d32baf37 100644 --- a/templates/harmonyos-next/entry/src/main/ets/pages/index.ets +++ b/templates/harmonyos-next/entry/src/main/ets/pages/index.ets @@ -27,10 +27,10 @@ import nativerender,{context} from 'libcocos.so'; import { WorkerManager } from '../cocos/WorkerManager'; import { ContextType } from '../common/Constants'; import { EditBoxDialog, EditboxShowInfo } from '../components/EditBoxDialog'; -import { CocosWebView, WebViewInfo } from '../components/CocosWebView'; +import { CocosWebView, LoadType, WebViewInfo } from '../components/CocosWebView'; import { CocosVideoPlayer, VideoInfo } from '../components/CocosVideoPlayer'; import { MessageEvent } from '@ohos.worker'; -import { PortProxy } from '../common/PortProxy'; +import { WorkerPort } from '../common/WorkerPort'; import { common } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -46,57 +46,7 @@ function executeMethodSync(nativeFunc: Function, funcData: string): string|boole } engineUtils.registerFunction("executeMethodAsync", executeMethodAsync); engineUtils.registerFunction("executeMethodSync", executeMethodSync); - -interface WorkerMessage { - type: string; - data: data; -} - -interface data { - id: string, - name: string, - param: number | string | param -} - -interface param { - tag?: number, - url?: string, - contents?: string, - mimeType?: string, - encoding?: string, - baseUrl?: string, - jsContents?: string, - x?: number, - y?: number, - w?: number, - h?: number, - visible?: boolean, - resourceType?: number, - time?: number, - fullScreen?: boolean -} - -interface editboxShowInfo { - defaultValue?: string; - confirmType?: string; - inputType?: string; - maxLength?: number; - x?:number; - y?:number; - width?:number; - height?:number; - confirmHold?: boolean; - isMultiline?: boolean; - fontSize?: number; - fontColor?: number; - backColor?: number; - backgroundColor?: number; - isBold?: boolean; - isItalic?: boolean; - isUnderline?: boolean; - underlineColor?: number; - textAlignment?: number; -} +WorkerPort.getInstance().initPort(WorkerManager.getInstance().getWorker()); @Entry @Component @@ -106,28 +56,13 @@ struct Index { @State videoArray: VideoInfo[] = []; private webViewIndexMap: Map = new Map(); private videoIndexMap: Map = new Map(); - private workPort: PortProxy = new PortProxy(WorkerManager.getInstance().getWorker()); + private workPort: WorkerPort = WorkerPort.getInstance(); private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down}); dialogController: CustomDialogController = new CustomDialogController({ builder: EditBoxDialog({ showInfo: this.showInfo, - onTextChange: (msg: string): void => { - this.showInfo.defaultMessage = msg; - this.workPort.postMessage('onTextInput', msg); - }, - accept: (msg: string): void => { - this.showInfo.defaultMessage = msg; - this.workPort.postMessage('onComplete', msg); - }, - confirm: (msg: string): void => { - this.showInfo.defaultMessage = msg; - this.workPort.postMessage('onConfirm', msg); - this.workPort.postMessage('onComplete', msg); - }, + workPort: this.workPort, }), - cancel: (): void => { - this.workPort.postMessage('onComplete', this.showInfo.defaultMessage); - }, autoCancel: true, alignment: DialogAlignment.Bottom, customStyle: true, @@ -135,262 +70,278 @@ struct Index { aboutToAppear(): void { console.log('[LIFECYCLE-Index] cocos aboutToAppear'); - this.workPort._messageHandle = async (e: MessageEvent): Promise => { - let data: WorkerMessage = e.data; - let msg = data.data; - let result: boolean | string | number | null = null; - switch (msg.name) { - // EditBox - case "showEditBox": { - let param = msg.param as editboxShowInfo; - this.showInfo.defaultMessage = param?.defaultValue as string; - this.showInfo.backgroundColor = param?.backColor as number; - if(param?.confirmType == 'done') { - this.showInfo.enterKeyType = EnterKeyType.Done; - } else if(param?.confirmType == 'send') { - this.showInfo.enterKeyType = EnterKeyType.Send; - } else if(param?.confirmType == 'search') { - this.showInfo.enterKeyType = EnterKeyType.Search; - } else if(param?.confirmType == 'go') { - this.showInfo.enterKeyType = EnterKeyType.Go; - } else if(param?.confirmType == 'next') { - this.showInfo.enterKeyType = EnterKeyType.Next; - } else { - this.showInfo.enterKeyType = EnterKeyType.Done; - } - if(param?.inputType == 'password') { - this.showInfo.type = InputType.Password; - } else if(param?.inputType === 'email') { - this.showInfo.type = InputType.Email; - } else if(param?.inputType === 'number') { - this.showInfo.type = InputType.Number; - } else if(param?.inputType === 'digit') { - this.showInfo.type = InputType.NUMBER_DECIMAL; - } else if(param?.inputType === 'tel') { - this.showInfo.type = InputType.PhoneNumber; - } else if(param?.inputType === 'url') { - // No url support - } else { - this.showInfo.type = InputType.Normal; - } - if(param?.maxLength != undefined && param?.maxLength > 0) { - this.showInfo.maxLength = param.maxLength; - } else { - this.showInfo.maxLength = 65536; - } - if(param?.isUnderline != undefined) { - this.showInfo.showUnderline = param?.isUnderline; - this.showInfo.underLineColor = param?.underlineColor as number; - } else { - this.showInfo.showUnderline = false; - } - - if(param?.textAlignment == 0) { - this.showInfo.textAlign = TextAlign.Start; - } else if(param?.textAlignment == 1) { - this.showInfo.textAlign = TextAlign.Center; - } else if(param?.textAlignment == 2) { - this.showInfo.textAlign = TextAlign.End; - } else { - this.showInfo.textAlign = TextAlign.Start; - } - this.dialogController.open(); - break; - } - case "hideEditBox": { - this.showInfo.defaultMessage = ''; - this.dialogController.close(); - break; - } - // WebView - case "createWebView": { - this.webViewArray.push(new WebViewInfo(0, 0, 0, 0, msg.param as number)); - this.webViewIndexMap.set(msg.param as number, this.webViewArray.length - 1); - break; - } - case "removeWebView": { - if (this.webViewArray.length > 0) { - this.webViewArray.splice(this.webViewIndexMap.get(msg?.param as number) as number, 1); - } - break; - } - case "loadUrl": { - let web = msg.param as param; - let index = this.webViewIndexMap.get(web?.tag as number) as number; - this.webViewArray[index].url = web?.url as string; - this.webViewArray[index].controller.loadUrl(web?.url as string); - break; - } - case "loadHTMLString": { - let web = msg.param as param; - let index = this.webViewIndexMap.get(web?.tag as number) as number; - this.webViewArray[index].controller.loadData( - web?.contents as string, - "text/html", - "UTF-8", - web?.baseUrl - ); - break; - } - case "loadData": { - let web = msg.param as param; - let index = this.webViewIndexMap.get(web?.tag as number) as number; - this.webViewArray[index].controller.loadData( - web?.contents as string, - web?.mimeType as string, - web?.encoding as string, - web?.baseUrl as string - ); - break; - } - case "evaluateJS": { - let web = msg.param as param; - let index = this.webViewIndexMap.get(web?.tag as number) as number; - this.webViewArray[index].controller.runJavaScript(web?.jsContents as string); - break; - } - case "reload": { - let index = this.webViewIndexMap.get(msg.param as number) as number; - this.webViewArray[index].controller.refresh(); - break; - } - case "stopLoading": { - let index = this.webViewIndexMap.get(msg.param as number) as number; - this.webViewArray[index].controller.stop(); - break; - } - case "canGoForward": { - let index = this.webViewIndexMap.get(msg.param as number) as number; - result = this.webViewArray[index].controller.accessForward(); - break; - } - case "canGoBack": { - let index = this.webViewIndexMap.get(msg.param as number) as number; - result = this.webViewArray[index].controller.accessBackward(); - break; - } - case "goForward": { - let index = this.webViewIndexMap.get(msg.param as number) as number; - this.webViewArray[index].controller.forward(); - break; - } - case "goBack": { - let index = this.webViewIndexMap.get(msg.param as number) as number; - this.webViewArray[index].controller.backward(); - break; - } - case "setWebViewRect": { - let web = msg.param as param - let index = this.webViewIndexMap.get(web?.tag as number) as number; - this.webViewArray[index].x = px2vp(web?.x as number) as number; - this.webViewArray[index].y = px2vp(web?.y as number) as number; - this.webViewArray[index].w = px2vp(web?.w as number) as number; - this.webViewArray[index].h = px2vp(web?.h as number) as number; - break; - } - case "setVisible": { - let web = msg.param as param; - let index = this.webViewIndexMap.get(web?.tag as number) as number; - this.webViewArray[index].visible = web?.visible as boolean; - break; - } - // video - case "createVideo": { - this.videoArray.push(new VideoInfo(0, 0, 0, 0, msg.param as number)); - this.videoIndexMap.set(msg.param as number, this.videoArray.length - 1); - break; - } - case "removeVideo": { - if (this.videoArray.length > 0) { - this.videoArray.splice(this.videoIndexMap.get(msg.param as number) as number, 1); - } - break; - } - case "setVideoUrl": - let video = msg.param as param; - let index = this.videoIndexMap.get(video?.tag as number) as number; - let resourceType = video.resourceType; - if (resourceType == 1) { - video.url = 'Resources/' + video.url; - this.videoArray[index].url = $rawfile(video.url as string); - } else { - this.videoArray[index].url = video.url as string; - } - break; - case "setVideoRect": { - let video = msg.param as param; - let index = this.videoIndexMap.get(video?.tag as number) as number; - this.videoArray[index].x = px2vp(video?.x as number) as number; - this.videoArray[index].y = px2vp(video?.y as number) as number; - this.videoArray[index].w = px2vp(video?.w as number) as number; - this.videoArray[index].h = px2vp(video?.h as number) as number; - break; - } - case "startVideo": { - let index = this.videoIndexMap.get(msg.param as number) as number; - if(this.videoArray[index].duration){ - this.videoArray[index].controller.start(); - }else{ - this.videoArray[index].isPreparedStart = true; - } - break; - } - case "pauseVideo": { - let index = this.videoIndexMap.get(msg.param as number) as number; - this.videoArray[index].controller.pause(); - break; - } - case "stopVideo": { - let index = this.videoIndexMap.get(msg.param as number) as number; - this.videoArray[index].controller.stop(); - break; - } - case "resumeVideo": { - let index = this.videoIndexMap.get(msg.param as number) as number; - this.videoArray[index].controller.start(); - break; - } - case "getVideoDuration": { - let index = this.videoIndexMap.get(msg.param as number) as number; - result = this.videoArray[index].duration; - break; - } - case "seekVideoTo": { - let video = msg.param as param; - let index = this.videoIndexMap.get(video?.tag as number) as number; - this.videoArray[index].controller.setCurrentTime(video?.time as number, SeekMode.Accurate); - break; - } - case "setVideoVisible": { - let video = msg.param as param; - let index = this.videoIndexMap.get(video?.tag as number) as number; - this.videoArray[index].visible = video.visible as boolean; - break; - } - case "setFullScreenEnabled": { - let video = msg.param as param; - let index = this.videoIndexMap.get(video?.tag as number) as number; - this.videoArray[index].isFullScreen = video.fullScreen as boolean; - break; - } - case "currentTime": { - let index = this.videoIndexMap.get(msg.param as number) as number; - result = this.videoArray[index].currentTime; - break; - } - case "exitGame": { - this.terminateSelf(); - break; - } - default: { - - } + this.workPort?.on("showEditBox", (defaultValue?: string, + confirmType?: string, + inputType?: string, + maxLength?: number, + x?:number, + y?:number, + width?:number, + height?:number, + confirmHold?: boolean, + isMultiline?: boolean, + fontSize?: number, + fontColor?: number, + backColor?: number, + backgroundColor?: number, + isBold?: boolean, + isItalic?: boolean, + isUnderline?: boolean, + underlineColor?: number, + textAlignment?: number) => { + //let param = msg.param as editboxShowInfo; + this.showInfo.defaultMessage = defaultValue!; + this.showInfo.backgroundColor = backColor!; + if(confirmType == 'done') { + this.showInfo.enterKeyType = EnterKeyType.Done; + } else if(confirmType == 'send') { + this.showInfo.enterKeyType = EnterKeyType.Send; + } else if(confirmType == 'search') { + this.showInfo.enterKeyType = EnterKeyType.Search; + } else if(confirmType == 'go') { + this.showInfo.enterKeyType = EnterKeyType.Go; + } else if(confirmType == 'next') { + this.showInfo.enterKeyType = EnterKeyType.Next; + } else { + this.showInfo.enterKeyType = EnterKeyType.Done; } - if (result != null || result != undefined) { - this.workPort.postReturnMessage(data, result); + if(inputType == 'password') { + this.showInfo.type = InputType.Password; + } else if(inputType === 'email') { + this.showInfo.type = InputType.Email; + } else if(inputType === 'number') { + this.showInfo.type = InputType.Number; + } else if(inputType === 'digit') { + this.showInfo.type = InputType.NUMBER_DECIMAL; + } else if(inputType === 'tel') { + this.showInfo.type = InputType.PhoneNumber; + } else if(inputType === 'url') { + // No url support + } else { + this.showInfo.type = InputType.Normal; } - } + if(maxLength != undefined && maxLength > 0) { + this.showInfo.maxLength = maxLength; + } else { + this.showInfo.maxLength = 65536; + } + + if(isUnderline != undefined) { + this.showInfo.showUnderline = isUnderline; + this.showInfo.underLineColor = underlineColor as number; + } else { + this.showInfo.showUnderline = false; + } + + if(textAlignment == 0) { + this.showInfo.textAlign = TextAlign.Start; + } else if(textAlignment == 1) { + this.showInfo.textAlign = TextAlign.Center; + } else if(textAlignment == 2) { + this.showInfo.textAlign = TextAlign.End; + } else { + this.showInfo.textAlign = TextAlign.Start; + } + this.dialogController?.open(); + }); + + this.workPort?.on("hideEditBox",() => { + this.showInfo.defaultMessage = ''; + this.dialogController?.close(); + }); + + this.workPort?.on("createWebView",(tag: number) => { + this.webViewArray.push(new WebViewInfo(0, 0, 0, 0, tag)); + this.webViewIndexMap.set(tag, this.webViewArray.length - 1); + }); + this.workPort?.on("removeWebView",(tag: number) => { + if (this.webViewArray.length > 0) { + this.webViewArray.splice(this.webViewIndexMap.get(tag) as number, 1); + } + }); + this.workPort?.on("loadUrl",(tag: number, url: string) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.loadUrl(url); + } else { + this.webViewArray[index].url = url; + this.webViewArray[index].loadType = LoadType.URL; + } + }); + this.workPort?.on("loadHTMLString",(tag: number, contents: string, baseUrl: string) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.loadData( + contents, + "text/html", + "UTF-8", + baseUrl + ); + } else { + this.webViewArray[index].contents = contents; + this.webViewArray[index].baseUrl = baseUrl; + this.webViewArray[index].loadType = LoadType.HTML_STRING; + } + }); + this.workPort?.on("loadData",(tag: number, + contents: string, + mimeType: string, + encoding: string, + baseUrl: string) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.loadData( + contents as string, + mimeType as string, + encoding as string, + baseUrl as string + ); + } else { + this.webViewArray[index].contents = contents; + this.webViewArray[index].mimeType = mimeType; + this.webViewArray[index].encoding = encoding; + this.webViewArray[index].baseUrl = baseUrl; + this.webViewArray[index].loadType = LoadType.DATA; + } + + }); + this.workPort?.on("evaluateJS",(tag: number, jsContents: string) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.runJavaScript(jsContents); + } else { + this.webViewArray[index].jsContents = jsContents; + } + + }); + + this.workPort?.on("reload",(tag: number) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.refresh(); + } else { + console.warn('The webview is not initialized.'); + } + }); + + this.workPort?.on("stopLoading",(tag: number) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.stop(); + } else { + console.warn('The webview is not initialized.'); + } + }); + this.workPort?.on("canGoForward",(tag: number) => { + let index = this.webViewIndexMap.get(tag) as number; + this.webViewArray[index].controller.accessForward(); + }); + this.workPort?.on("canGoBack",(tag: number) => { + let index = this.webViewIndexMap.get(tag) as number; + this.webViewArray[index].controller.accessBackward(); + }); + this.workPort?.on("goForward",(tag: number) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.forward(); + } else { + console.warn('The webview is not initialized.'); + } + }); + this.workPort?.on("goBack",(tag: number) => { + let index = this.webViewIndexMap.get(tag) as number; + if(this.webViewArray[index].isInited) { + this.webViewArray[index].controller.backward(); + } else { + console.warn('The webview is not initialized.'); + } + }); + this.workPort?.on("setWebViewRect",(tag: number, x: number,y: number,w: number,h: number) => { + let index = this.webViewIndexMap.get(tag as number) as number; + this.webViewArray[index].x = px2vp(x as number) as number; + this.webViewArray[index].y = px2vp(y as number) as number; + this.webViewArray[index].w = px2vp(w as number) as number; + this.webViewArray[index].h = px2vp(h as number) as number; + }); + this.workPort?.on("setVisible",(tag: number, visible: boolean) => { + let index = this.webViewIndexMap.get(tag) as number; + this.webViewArray[index].visible = visible as boolean; + }); + + this.workPort?.on("createVideo",(tag: number) => { + this.videoArray.push(new VideoInfo(0, 0, 0, 0, tag)); + this.videoIndexMap.set(tag, this.videoArray.length - 1); + }); + this.workPort?.on("removeVideo",(tag: number) => { + if (this.videoArray.length > 0) { + this.videoArray.splice(this.videoIndexMap.get(tag) as number, 1); + } + }); + this.workPort?.on("setVideoUrl",(tag: number, resourceType:number, url: string) => { + let index = this.videoIndexMap.get(tag) as number; + if (resourceType == 1) { + url = 'Resources/' + url; + this.videoArray[index].url = $rawfile(url); + } else { + this.videoArray[index].url = url; + } + }); + + this.workPort?.on("setVideoRect",(tag: number, x: number,y: number,w: number,h: number) => { + let index = this.videoIndexMap.get(tag as number) as number; + this.videoArray[index].x = px2vp(x as number) as number; + this.videoArray[index].y = px2vp(y as number) as number; + this.videoArray[index].w = px2vp(w as number) as number; + this.videoArray[index].h = px2vp(h as number) as number; + }); + this.workPort?.on("startVideo",(tag: number) => { + let index = this.videoIndexMap.get(tag) as number; + if(this.videoArray[index].duration){ + this.videoArray[index].controller.start(); + }else{ + this.videoArray[index].isPreparedStart = true; + } + }); + this.workPort?.on("pauseVideo",(tag: number) => { + let index = this.videoIndexMap.get(tag) as number; + this.videoArray[index].controller.pause(); + }); + this.workPort?.on("pauseVideo",(tag: number) => { + let index = this.videoIndexMap.get(tag) as number; + this.videoArray[index].controller.stop(); + }); + this.workPort?.on("resumeVideo",(tag: number) => { + let index = this.videoIndexMap.get(tag) as number; + this.videoArray[index].controller.start(); + }); + this.workPort?.on("getVideoDuration",(tag: number) => { + let index = this.videoIndexMap.get(tag) as number; + return this.videoArray[index].duration; + }); + this.workPort?.on("seekVideoTo",(tag: number, time: number) => { + let index = this.videoIndexMap.get(tag) as number; + this.videoArray[index].controller.setCurrentTime(time, SeekMode.Accurate); + }); + + this.workPort?.on("setVideoVisible",(tag: number, visible: boolean) => { + let index = this.videoIndexMap.get(tag) as number; + this.videoArray[index].visible = visible as boolean; + }); + + this.workPort?.on("setFullScreenEnabled",(tag: number, fullScreen: boolean) => { + let index = this.videoIndexMap.get(tag) as number; + this.videoArray[index].isFullScreen = fullScreen; + }); + + this.workPort?.on("currentTime",(tag: number) => { + let index = this.videoIndexMap.get(tag) as number; + return this.videoArray[index].currentTime; + }); + + this.workPort?.on("exitGame",() => { + this.terminateSelf(); + }); } aboutToDisappear(): void { @@ -411,7 +362,7 @@ struct Index { onBackPress() { console.log("[LIFECYCLE-Page] cocos onBackPress"); - this.workPort.postMessage("backPress", ""); + this.workPort.postMessage("backPress"); // If disable system exit needed, remove comment "return true" // return true; } @@ -461,7 +412,7 @@ struct Index { ) .onLoad((context) => { // Set the cache directory in the ts layer. - this.workPort.postMessage("onXCLoad", "XComponent"); + this.workPort.postMessage("onXCLoad"); }) .onDestroy(() => { console.log('cocos onDestroy') diff --git a/templates/harmonyos-next/entry/src/main/ets/workers/cocos_worker.ts b/templates/harmonyos-next/entry/src/main/ets/workers/cocos_worker.ts index a6d81a3274..f888e4fc82 100644 --- a/templates/harmonyos-next/entry/src/main/ets/workers/cocos_worker.ts +++ b/templates/harmonyos-next/entry/src/main/ets/workers/cocos_worker.ts @@ -31,7 +31,7 @@ import { ContextType } from '../common/Constants'; <% if(!useV8) { %> import { launchEngine } from '../cocos/game'; <% } %> -import { PortProxy } from '../common/PortProxy'; +import { UiPort } from './ui_port'; <% if(useV8) { %> globalThis.importPolyfill = async function () { @@ -42,11 +42,11 @@ import { PortProxy } from '../common/PortProxy'; <% } %> if (!(console as any).assert) { - (console as any).assert = function(cond, msg) { - if (!cond) { - throw new Error(msg); - } - }; + (console as any).assert = function (cond, msg) { + if (!cond) { + throw new Error(msg); + } + }; } const nativeContext = cocos.getContext(ContextType.WORKER_INIT); @@ -57,72 +57,75 @@ const nativeWebView = cocos.getContext(ContextType.WEBVIEW_UTILS); const appLifecycle = cocos.getContext(ContextType.APP_LIFECYCLE); const nativeVideo = cocos.getContext(ContextType.VIDEO_UTILS); -let uiPort = new PortProxy(worker.workerPort); -nativeContext.postMessage = function (msgType: string, msgData: string): void { +UiPort.getInstance().initPort(worker.workerPort); + +const uiPort = UiPort.getInstance(); +nativeContext.postMessage = (msgType: string, msgData: string): void => { uiPort.postMessage(msgType, msgData); } -nativeContext.postSyncMessage = async function (msgType: string, msgData: string): Promise { - const result = await uiPort.postSyncMessage(msgType, msgData) as boolean | string | number; - return result; +nativeContext.postSyncMessage = async (msgType: string, msgData: string): Promise => { + return uiPort.postSyncMessage(msgType, msgData); } // The purpose of this is to avoid being GC nativeContext.setPostMessageFunction.call(nativeContext, nativeContext.postMessage) nativeContext.setPostSyncMessageFunction.call(nativeContext, nativeContext.postSyncMessage) -globalThis.terminateProcess = function () { - uiPort.postMessage("exitGame",0); +globalThis.terminateProcess = () => { + uiPort.postMessage("exitGame", 0); } -uiPort._messageHandle = function (e) { - var data = e.data; - var msg = data.data; - - switch (msg.name) { - case "onXCLoad": - const renderContext = cocos.getContext(ContextType.NATIVE_RENDER_API); - renderContext.nativeEngineInit(); - <% if(!useV8) { %> - launchEngine().then(() => { - console.info('launch CC engine finished'); - }).catch(e => { - console.error('launch CC engine failed'); - }); - <% } %> - // @ts-ignore - globalThis.oh.postMessage = nativeContext.postMessage; - // @ts-ignore - globalThis.oh.postSyncMessage = nativeContext.postSyncMessage; - renderContext.nativeEngineStart(); - break; - case "onTextInput": - nativeEditBox.onTextChange(msg.param); - break; - case "onComplete": - nativeEditBox.onComplete(msg.param); - break; - case "onConfirm": - nativeEditBox.onConfirm(msg.param); - break; - case "onPageBegin": - nativeWebView.shouldStartLoading(msg.param.viewTag, msg.param.url); - break; - case "onPageEnd": - nativeWebView.finishLoading(msg.param.viewTag, msg.param.url); - break; - case "onErrorReceive": - nativeWebView.failLoading(msg.param.viewTag, msg.param.url); - break; - case "onVideoEvent": - nativeVideo.onVideoEvent(JSON.stringify(msg.param)); - break; - case "backPress": - appLifecycle.onBackPress(); - break; - default: - console.error("cocos worker: message type unknown"); - break; - } +globalThis.openUrl = (url: string) => { + uiPort.postMessage("openUrl", url); } + +uiPort.on("onXCLoad", () => { + const renderContext = cocos.getContext(ContextType.NATIVE_RENDER_API); + renderContext.nativeEngineInit(); + <% if(!useV8) { %> + launchEngine().then(() => { + console.info('launch CC engine finished'); + }).catch(e => { + console.error('launch CC engine failed'); + }); + <% } %> + // @ts-ignore + globalThis.oh.postMessage = nativeContext.postMessage; + // @ts-ignore + globalThis.oh.postSyncMessage = nativeContext.postSyncMessage; + renderContext.nativeEngineStart(); +}); + +uiPort.on("onTextInput", (txt: string) => { + nativeEditBox.onTextChange(txt); +}) + +uiPort.on("onComplete", (txt: string) => { + nativeEditBox.onComplete(txt); +}) + +uiPort.on("onConfirm", (txt: string) => { + nativeEditBox.onConfirm(txt); +}) + +uiPort.on("onPageBegin", (viewTag: number, url: string) => { + nativeWebView.shouldStartLoading(viewTag, url); +}) + +uiPort.on("onPageEnd", (viewTag: number, url: string) => { + nativeWebView.finishLoading(viewTag, url); +}) + +uiPort.on("onErrorReceive", (viewTag: number, url: string) => { + nativeWebView.failLoading(viewTag, url); +}) + +uiPort.on("onVideoEvent", (videoTag: number, videoEvent: number, arg?: any) => { + nativeVideo.onVideoEvent(JSON.stringify({videoTag: videoTag, videoEvent: videoEvent, arg: arg ?? null})); +}) + +uiPort.on("backPress", () => { + appLifecycle.onBackPress(); +}) \ No newline at end of file diff --git a/templates/harmonyos-next/entry/src/main/ets/workers/ui_port.ts b/templates/harmonyos-next/entry/src/main/ets/workers/ui_port.ts new file mode 100644 index 0000000000..d916260dfc --- /dev/null +++ b/templates/harmonyos-next/entry/src/main/ets/workers/ui_port.ts @@ -0,0 +1,108 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import worker, { ThreadWorkerGlobalScope } from '@ohos.worker'; +import { MessageEvent } from '@ohos.worker'; +import { MessageEvents } from '@kit.ArkTS'; +import { EventTarget } from '../common/EventTarget' + +let port: UiPort; + +export class UiPort extends EventTarget { + private autoId: number = 0; + public actionHandleMap = {} + private port: ThreadWorkerGlobalScope | worker.ThreadWorker = null; + + public _messageHandle?: (e: MessageEvent) => void; + + constructor() { + super(); + } + + static getInstance (): UiPort { + if (!port) { + port = new UiPort(); + } + return port; + } + + public initPort(worker: ThreadWorkerGlobalScope | worker.ThreadWorker) { + this.port = worker; + this.port.onmessage = this.onMessage.bind(this); + } + + public getPort() : ThreadWorkerGlobalScope | worker.ThreadWorker { + return this.port; + } + + public onMessage(e: MessageEvents) { + let data = e['data']; + if (data.type == "syncResult") { + const { id, response } = data.data; + if (!this.actionHandleMap[id]) { + return; + } + this.actionHandleMap[id].call(this, response); + delete this.actionHandleMap[id]; + } else { + let params = []; + if (data.data.param === null || data.data.param === undefined) { + params = []; + } else if (Array.isArray(data.data.param)) { + params = data.data.param; + } else if (typeof data.data.param === 'object') { + params = Object.values(data.data.param); + } else { + params = [data.data.param]; + } + const result = this.emit(data.data.name, ...params); + if(result != null && result != undefined && data.type == "sync") { + this.postReturnMessage(data.data.cbId, result); + } + } + } + + public postReturnMessage(cbId: number, res: any) { + if (res != null && res != undefined) { + this.port.postMessage({ type: "syncResult", data: { id: cbId, response: res } }); + } + } + + public postMessage(msgName: string, msgData?: any) { + this.port.postMessage({ type: "async", data: { name: msgName, param: msgData ?? null } }); + } + + public postSyncMessage(msgName: string, msgData: any): Promise { + const id = this.autoId++; + return new Promise((resolve, reject) => { + this.actionHandleMap[id] = (response) => { + resolve(response) + } + const message = { + type: "sync", data: { cbId: id, name: msgName, param: msgData } + } + this.port.postMessage(message); + }) + } +} \ No newline at end of file