From 0a7e293c5e1f52ae3ed334535158fe975fad63e0 Mon Sep 17 00:00:00 2001 From: Leslie Date: Fri, 18 Jan 2019 16:04:06 +0800 Subject: [PATCH] udpate events related file --- cocos/core/platform/event-manager/CCEvent.js | 578 ------- cocos/core/platform/event-manager/CCEvent.ts | 510 ++++++ ...{CCEventListener.js => CCEventListener.ts} | 460 ++--- .../{CCEventManager.js => CCEventManager.ts} | 1538 +++++++++-------- .../platform/event-manager/CCInputManager.js | 759 -------- .../platform/event-manager/CCInputManager.ts | 786 +++++++++ .../event-manager/{CCTouch.js => CCTouch.ts} | 124 +- .../event-manager/{index.js => index.ts} | 3 +- wx.d.ts | 11 + 9 files changed, 2415 insertions(+), 2354 deletions(-) delete mode 100644 cocos/core/platform/event-manager/CCEvent.js create mode 100644 cocos/core/platform/event-manager/CCEvent.ts rename cocos/core/platform/event-manager/{CCEventListener.js => CCEventListener.ts} (50%) rename cocos/core/platform/event-manager/{CCEventManager.js => CCEventManager.ts} (58%) delete mode 100644 cocos/core/platform/event-manager/CCInputManager.js create mode 100644 cocos/core/platform/event-manager/CCInputManager.ts rename cocos/core/platform/event-manager/{CCTouch.js => CCTouch.ts} (64%) rename cocos/core/platform/event-manager/{index.js => index.ts} (97%) create mode 100644 wx.d.ts diff --git a/cocos/core/platform/event-manager/CCEvent.js b/cocos/core/platform/event-manager/CCEvent.js deleted file mode 100644 index 5bbeff5a8c..0000000000 --- a/cocos/core/platform/event-manager/CCEvent.js +++ /dev/null @@ -1,578 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 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 Event from '../../event/event'; - -/** - * !#en The mouse event - * !#zh 鼠标事件类型 - * @class Event.EventMouse - * @extends Event - */ -export class EventMouse extends Event { - /** - * @method constructor - * @param {Number} eventType - The mouse event type, UP, DOWN, MOVE, CANCELED - * @param {Boolean} [bubbles=false] - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (eventType, bubbles) { - super(Event.MOUSE, bubbles); - this._eventType = eventType; - this._button = 0; - this._x = 0; - this._y = 0; - this._prevX = 0; - this._prevY = 0; - this._scrollX = 0; - this._scrollY = 0; - } - - /** - * !#en Sets scroll data. - * !#zh 设置鼠标的滚动数据。 - * @method setScrollData - * @param {Number} scrollX - * @param {Number} scrollY - */ - setScrollData (scrollX, scrollY) { - this._scrollX = scrollX; - this._scrollY = scrollY; - } - - /** - * !#en Returns the x axis scroll value. - * !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 - * @method getScrollX - * @returns {Number} - */ - getScrollX () { - return this._scrollX; - } - - /** - * !#en Returns the y axis scroll value. - * !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 - * @method getScrollY - * @returns {Number} - */ - getScrollY () { - return this._scrollY; - } - - /** - * !#en Sets cursor location. - * !#zh 设置当前鼠标位置。 - * @method setLocation - * @param {Number} x - * @param {Number} y - */ - setLocation (x, y) { - this._x = x; - this._y = y; - } - - /** - * !#en Returns cursor location. - * !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 - * @method getLocation - * @return {Vec2} location - */ - getLocation () { - return cc.v2(this._x, this._y); - } - - /** - * !#en Returns the current cursor location in screen coordinates. - * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 - * @method getLocationInView - * @return {Vec2} - */ - getLocationInView() { - return cc.v2(this._x, cc.view._designResolutionSize.height - this._y); - } - - _setPrevCursor (x, y) { - this._prevX = x; - this._prevY = y; - } - - /** - * !#en Returns the previous touch location. - * !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} - */ - getPreviousLocation () { - return cc.v2(this._prevX, this._prevY); - } - - /** - * !#en Returns the delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} - */ - getDelta () { - return cc.v2(this._x - this._prevX, this._y - this._prevY); - } - - /** - * !#en Returns the X axis delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 - * @method getDeltaX - * @return {Number} - */ - getDeltaX () { - return this._x - this._prevX; - } - - /** - * !#en Returns the Y axis delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 - * @method getDeltaY - * @return {Number} - */ - getDeltaY () { - return this._y - this._prevY; - } - - /** - * !#en Sets mouse button. - * !#zh 设置鼠标按键。 - * @method setButton - * @param {Number} button - */ - setButton (button) { - this._button = button; - } - - /** - * !#en Returns mouse button. - * !#zh 获取鼠标按键。 - * @method getButton - * @returns {Number} - */ - getButton () { - return this._button; - } - - /** - * !#en Returns location X axis data. - * !#zh 获取鼠标当前位置 X 轴。 - * @method getLocationX - * @returns {Number} - */ - getLocationX () { - return this._x; - } - - /** - * !#en Returns location Y axis data. - * !#zh 获取鼠标当前位置 Y 轴。 - * @method getLocationY - * @returns {Number} - */ - getLocationY () { - return this._y; - } -} - -//Inner event types of MouseEvent -/** - * !#en The none event code of mouse event. - * !#zh 无。 - * @property NONE - * @static - * @type {Number} - */ -EventMouse.NONE = 0; -/** - * !#en The event type code of mouse down event. - * !#zh 鼠标按下事件。 - * @property DOWN - * @static - * @type {Number} - */ -EventMouse.DOWN = 1; -/** - * !#en The event type code of mouse up event. - * !#zh 鼠标按下后释放事件。 - * @property UP - * @static - * @type {Number} - */ -EventMouse.UP = 2; -/** - * !#en The event type code of mouse move event. - * !#zh 鼠标移动事件。 - * @property MOVE - * @static - * @type {Number} - */ -EventMouse.MOVE = 3; -/** - * !#en The event type code of mouse scroll event. - * !#zh 鼠标滚轮事件。 - * @property SCROLL - * @static - * @type {Number} - */ -EventMouse.SCROLL = 4; - -/** - * !#en The tag of Mouse left button. - * !#zh 鼠标左键的标签。 - * @property BUTTON_LEFT - * @static - * @type {Number} - */ -EventMouse.BUTTON_LEFT = 0; - -/** - * !#en The tag of Mouse right button (The right button number is 2 on browser). - * !#zh 鼠标右键的标签。 - * @property BUTTON_RIGHT - * @static - * @type {Number} - */ -EventMouse.BUTTON_RIGHT = 2; - -/** - * !#en The tag of Mouse middle button (The right button number is 1 on browser). - * !#zh 鼠标中键的标签。 - * @property BUTTON_MIDDLE - * @static - * @type {Number} - */ -EventMouse.BUTTON_MIDDLE = 1; - -/** - * !#en The tag of Mouse button 4. - * !#zh 鼠标按键 4 的标签。 - * @property BUTTON_4 - * @static - * @type {Number} - */ -EventMouse.BUTTON_4 = 3; - -/** - * !#en The tag of Mouse button 5. - * !#zh 鼠标按键 5 的标签。 - * @property BUTTON_5 - * @static - * @type {Number} - */ -EventMouse.BUTTON_5 = 4; - -/** - * !#en The tag of Mouse button 6. - * !#zh 鼠标按键 6 的标签。 - * @property BUTTON_6 - * @static - * @type {Number} - */ -EventMouse.BUTTON_6 = 5; - -/** - * !#en The tag of Mouse button 7. - * !#zh 鼠标按键 7 的标签。 - * @property BUTTON_7 - * @static - * @type {Number} - */ -EventMouse.BUTTON_7 = 6; - -/** - * !#en The tag of Mouse button 8. - * !#zh 鼠标按键 8 的标签。 - * @property BUTTON_8 - * @static - * @type {Number} - */ -EventMouse.BUTTON_8 = 7; - -/** - * !#en The touch event - * !#zh 触摸事件 - * @class Event.EventTouch - * @constructor - * @extends Event - */ -export class EventTouch extends Event { - /** - * @method constructor - * @param {Array} touchArr - The array of the touches - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (touchArr, bubbles) { - super(Event.TOUCH, bubbles); - this._eventCode = 0; - this._touches = touchArr || []; - /** - * !#en The current touch object - * !#zh 当前触点对象 - * @property touch - * @type {Touch} - */ - this.touch = null; - // Actually duplicated, because of history issue, currentTouch was in the original design, touch was added in creator engine - // They should point to the same object - this.currentTouch = null; - } - - /** - * !#en Returns event code. - * !#zh 获取事件类型。 - * @method getEventCode - * @returns {Number} - */ - getEventCode () { - return this._eventCode; - } - - /** - * !#en Returns touches of event. - * !#zh 获取触摸点的列表。 - * @method getTouches - * @returns {Array} - */ - getTouches () { - return this._touches; - } - - _setEventCode (eventCode) { - this._eventCode = eventCode; - } - - _setTouches (touches) { - this._touches = touches; - } - - /** - * !#en Sets touch location. - * !#zh 设置当前触点位置 - * @method setLocation - * @param {Number} x - * @param {Number} y - */ - setLocation (x, y) { - this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y); - } - - /** - * !#en Returns touch location. - * !#zh 获取触点位置。 - * @method getLocation - * @return {Vec2} location - */ - getLocation () { - return this.touch ? this.touch.getLocation() : cc.v2(); - } - - /** - * !#en Returns the current touch location in screen coordinates. - * !#zh 获取当前触点在游戏窗口中的位置。 - * @method getLocationInView - * @return {Vec2} - */ - getLocationInView() { - return this.touch ? this.touch.getLocationInView() : cc.v2(); - } - - /** - * !#en Returns the previous touch location. - * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} - */ - getPreviousLocation () { - return this.touch ? this.touch.getPreviousLocation() : cc.v2(); - } - - /** - * !#en Returns the start touch location. - * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 - * @method getStartLocation - * @returns {Vec2} - */ - getStartLocation() { - return this.touch ? this.touch.getStartLocation() : cc.v2(); - } - - /** - * !#en Returns the id of cc.Touch. - * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 - * @method getID - * @return {Number} - */ - getID () { - return this.touch ? this.touch.getID() : null; - } - - /** - * !#en Returns the delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} - */ - getDelta () { - return this.touch ? this.touch.getDelta() : cc.v2(); - } - - /** - * !#en Returns the X axis delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的 x 轴距离。 - * @method getDeltaX - * @return {Number} - */ - getDeltaX () { - return this.touch ? this.touch.getDelta().x : 0; - } - - /** - * !#en Returns the Y axis delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的 y 轴距离。 - * @method getDeltaY - * @return {Number} - */ - getDeltaY () { - return this.touch ? this.touch.getDelta().y : 0; - } - - /** - * !#en Returns location X axis data. - * !#zh 获取当前触点 X 轴位置。 - * @method getLocationX - * @returns {Number} - */ - getLocationX () { - return this.touch ? this.touch.getLocationX() : 0; - } - - /** - * !#en Returns location Y axis data. - * !#zh 获取当前触点 Y 轴位置。 - * @method getLocationY - * @returns {Number} - */ - getLocationY () { - return this.touch ? this.touch.getLocationY() : 0; - } -} - -/** - * !#en The maximum touch numbers - * !#zh 最大触摸数量。 - * @constant - * @type {Number} - */ -EventTouch.MAX_TOUCHES = 5; - -/** - * !#en The event type code of touch began event. - * !#zh 开始触摸事件 - * @constant - * @type {Number} - */ -EventTouch.BEGAN = 0; -/** - * !#en The event type code of touch moved event. - * !#zh 触摸后移动事件 - * @constant - * @type {Number} - */ -EventTouch.MOVED = 1; -/** - * !#en The event type code of touch ended event. - * !#zh 结束触摸事件 - * @constant - * @type {Number} - */ -EventTouch.ENDED = 2; -/** - * !#en The event type code of touch cancelled event. - * !#zh 取消触摸事件 - * @constant - * @type {Number} - */ -EventTouch.CANCELED = 3; - -/** - * !#en The acceleration event - * !#zh 加速度事件 - * @class Event.EventAcceleration - * @extends Event - */ -export class EventAcceleration extends Event { - /** - * @method constructor - * @param {Object} acc - The acceleration - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (acc, bubbles) { - super(Event.ACCELERATION, bubbles); - this.acc = acc; - } -} - -/** - * !#en The keyboard event - * !#zh 键盘事件 - * @class Event.EventKeyboard - * @extends Event - */ -export class EventKeyboard extends Event { - /** - * @method constructor - * @param {Number} keyCode - The key code of which triggered this event - * @param {Boolean} isPressed - A boolean indicating whether the key have been pressed - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (keyCode, isPressed, bubbles) { - super(Event.KEYBOARD, bubbles); - /** - * !#en - * The keyCode read-only property represents a system and implementation dependent numerical code identifying the unmodified value of the pressed key. - * This is usually the decimal ASCII (RFC 20) or Windows 1252 code corresponding to the key. - * If the key can't be identified, this value is 0. - * - * !#zh - * keyCode 是只读属性它表示一个系统和依赖于实现的数字代码,可以识别按键的未修改值。 - * 这通常是十进制 ASCII (RFC20) 或者 Windows 1252 代码,所对应的密钥。 - * 如果无法识别该键,则该值为 0。 - * - * @property keyCode - * @type {Number} - */ - this.keyCode = keyCode; - this.isPressed = isPressed; - } -} - -Event.EventMouse = EventMouse; -Event.EventTouch = EventTouch; -Event.EventAcceleration = EventAcceleration; -Event.EventKeyboard = EventKeyboard; diff --git a/cocos/core/platform/event-manager/CCEvent.ts b/cocos/core/platform/event-manager/CCEvent.ts new file mode 100644 index 0000000000..6133b23638 --- /dev/null +++ b/cocos/core/platform/event-manager/CCEvent.ts @@ -0,0 +1,510 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 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 Event from '../../event/event'; +import { v2 } from '../../value-types/vec2'; +import Touch from './CCTouch'; + +/** + * !#en The mouse event + * !#zh 鼠标事件类型 + * @class Event.EventMouse + * @extends Event + */ +export class EventMouse extends Event { + // Inner event types of MouseEvent + + /** + * !#en The none event code of mouse event. + * !#zh 无。 + */ + public static NONE = 0; + + /** + * !#en The event type code of mouse down event. + * !#zh 鼠标按下事件。 + */ + public static DOWN = 1; + + /** + * !#en The event type code of mouse up event. + * !#zh 鼠标按下后释放事件。 + */ + public static UP = 2; + + /** + * !#en The event type code of mouse move event. + * !#zh 鼠标移动事件。 + */ + public static MOVE = 3; + + /** + * !#en The event type code of mouse scroll event. + * !#zh 鼠标滚轮事件。 + */ + public static SCROLL = 4; + + /** + * !#en The tag of Mouse left button. + * !#zh 鼠标左键的标签。 + */ + public static BUTTON_LEFT = 0; + + /** + * !#en The tag of Mouse right button (The right button number is 2 on browser). + * !#zh 鼠标右键的标签。 + */ + public static BUTTON_RIGHT = 2; + + /** + * !#en The tag of Mouse middle button (The right button number is 1 on browser). + * !#zh 鼠标中键的标签。 + */ + public static BUTTON_MIDDLE = 1; + + /** + * !#en The tag of Mouse button 4. + * !#zh 鼠标按键 4 的标签。 + */ + public static BUTTON_4 = 3; + + /** + * !#en The tag of Mouse button 5. + * !#zh 鼠标按键 5 的标签。 + */ + public static BUTTON_5 = 4; + + /** + * !#en The tag of Mouse button 6. + * !#zh 鼠标按键 6 的标签。 + */ + public static BUTTON_6 = 5; + + /** + * !#en The tag of Mouse button 7. + * !#zh 鼠标按键 7 的标签。 + */ + public static BUTTON_7 = 6; + + /** + * !#en The tag of Mouse button 8. + * !#zh 鼠标按键 8 的标签。 + */ + public static BUTTON_8 = 7; + + public movementX: number = 0; + + public movementY: number = 0; + + private _eventType: number; + + private _button: number | null = 0; + + private _x: number = 0; + + private _y: number = 0; + + private _prevX: number = 0; + + private _prevY: number = 0; + + private _scrollX: number = 0; + + private _scrollY: number = 0; + + /** + * @param eventType - The mouse event type, UP, DOWN, MOVE, CANCELED + * @param [bubbles=false] - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (eventType: number, bubbles?: boolean) { + super(Event.MOUSE, bubbles); + this._eventType = eventType; + } + + /** + * !#en Sets scroll data. + * !#zh 设置鼠标的滚动数据。 + */ + public setScrollData (scrollX: number, scrollY: number) { + this._scrollX = scrollX; + this._scrollY = scrollY; + } + + /** + * !#en Returns the x axis scroll value. + * !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 + */ + public getScrollX () { + return this._scrollX; + } + + /** + * !#en Returns the y axis scroll value. + * !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 + */ + public getScrollY () { + return this._scrollY; + } + + /** + * !#en Sets cursor location. + * !#zh 设置当前鼠标位置。 + */ + public setLocation (x: number, y: number) { + this._x = x; + this._y = y; + } + + /** + * !#en Returns cursor location. + * !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 + */ + public getLocation () { + return v2(this._x, this._y); + } + + /** + * !#en Returns the current cursor location in screen coordinates. + * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 + */ + public getLocationInView () { + return v2(this._x, cc.view._designResolutionSize.height - this._y); + } + + public _setPrevCursor (x: number, y: number) { + this._prevX = x; + this._prevY = y; + } + + /** + * !#en Returns the previous touch location. + * !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 + */ + public getPreviousLocation () { + return v2(this._prevX, this._prevY); + } + + /** + * !#en Returns the delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + */ + public getDelta () { + return v2(this._x - this._prevX, this._y - this._prevY); + } + + /** + * !#en Returns the X axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 + */ + public getDeltaX () { + return this._x - this._prevX; + } + + /** + * !#en Returns the Y axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 + */ + public getDeltaY () { + return this._y - this._prevY; + } + + /** + * !#en Sets mouse button. + * !#zh 设置鼠标按键。 + */ + public setButton (button: number | null) { + this._button = button; + } + + /** + * !#en Returns mouse button. + * !#zh 获取鼠标按键。 + */ + public getButton () { + return this._button; + } + + /** + * !#en Returns location X axis data. + * !#zh 获取鼠标当前位置 X 轴。 + */ + public getLocationX () { + return this._x; + } + + /** + * !#en Returns location Y axis data. + * !#zh 获取鼠标当前位置 Y 轴。 + */ + public getLocationY () { + return this._y; + } +} + +/** + * !#en The touch event + * !#zh 触摸事件 + * @class Event.EventTouch + * @constructor + * @extends Event + */ +export class EventTouch extends Event { + /** + * !#en The maximum touch numbers + * !#zh 最大触摸数量。 + */ + public static MAX_TOUCHES = 5; + + /** + * !#en The event type code of touch began event. + * !#zh 开始触摸事件 + */ + public static BEGAN = 0; + /** + * !#en The event type code of touch moved event. + * !#zh 触摸后移动事件 + */ + public static MOVED = 1; + /** + * !#en The event type code of touch ended event. + * !#zh 结束触摸事件 + */ + public static ENDED = 2; + /** + * !#en The event type code of touch cancelled event. + * !#zh 取消触摸事件 + */ + public static CANCELLED = 3; + + /** + * !#en The current touch object + * !#zh 当前触点对象 + */ + public touch: Touch | null = null; + + // Actually duplicated, because of history issue, + // currentTouch was in the original design, touch was added in creator engine + // They should point to the same object + public currentTouch: Touch | null = null; + + public _eventCode: number = 0; + + private _touches: Touch[]; + + /** + * @param touches - The array of the touches + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (touches?: Touch[], bubbles?: boolean) { + super(Event.TOUCH, bubbles); + this._eventCode = 0; + this._touches = touches || []; + } + + /** + * !#en Returns event code. + * !#zh 获取事件类型。 + */ + public getEventCode () { + return this._eventCode; + } + + /** + * !#en Returns touches of event. + * !#zh 获取触摸点的列表。 + */ + public getTouches () { + return this._touches; + } + + public _setEventCode (eventCode: number) { + this._eventCode = eventCode; + } + + public _setTouches (touches: Touch[]) { + this._touches = touches; + } + + /** + * !#en Sets touch location. + * !#zh 设置当前触点位置 + */ + public setLocation (x: number, y: number) { + if (this.touch) { + this.touch.setTouchInfo(this.touch.getID(), x, y); + } + } + + /** + * !#en Returns touch location. + * !#zh 获取触点位置。 + */ + public getLocation () { + return this.touch ? this.touch.getLocation() : v2(); + } + + /** + * !#en Returns the current touch location in screen coordinates. + * !#zh 获取当前触点在游戏窗口中的位置。 + */ + public getLocationInView () { + return this.touch ? this.touch.getLocationInView() : v2(); + } + + /** + * !#en Returns the previous touch location. + * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 + */ + public getPreviousLocation () { + return this.touch ? this.touch.getPreviousLocation() : v2(); + } + + /** + * !#en Returns the start touch location. + * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 + */ + public getStartLocation () { + return this.touch ? this.touch.getStartLocation() : v2(); + } + + /** + * !#en Returns the id of cc.Touch. + * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 + */ + public getID () { + return this.touch ? this.touch.getID() : null; + } + + /** + * !#en Returns the delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + */ + public getDelta () { + return this.touch ? this.touch.getDelta() : v2(); + } + + /** + * !#en Returns the X axis delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的 x 轴距离。 + */ + public getDeltaX () { + return this.touch ? this.touch.getDelta().x : 0; + } + + /** + * !#en Returns the Y axis delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的 y 轴距离。 + */ + public getDeltaY () { + return this.touch ? this.touch.getDelta().y : 0; + } + + /** + * !#en Returns location X axis data. + * !#zh 获取当前触点 X 轴位置。 + */ + public getLocationX () { + return this.touch ? this.touch.getLocationX() : 0; + } + + /** + * !#en Returns location Y axis data. + * !#zh 获取当前触点 Y 轴位置。 + */ + public getLocationY () { + return this.touch ? this.touch.getLocationY() : 0; + } +} + +/** + * !#en The acceleration event + * !#zh 加速度事件 + * @class Event.EventAcceleration + * @extends Event + */ +export class EventAcceleration extends Event { + public acc: Object; + + /** + * @param acc - The acceleration + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (acc: Object, bubbles?: boolean) { + super(Event.ACCELERATION, bubbles); + this.acc = acc; + } +} + +/** + * !#en The keyboard event + * !#zh 键盘事件 + * @class Event.EventKeyboard + * @extends Event + */ +export class EventKeyboard extends Event { + /** + * !#en + * The keyCode read-only property represents a system and implementation dependent numerical code + * identifying the unmodified value of the pressed key. + * This is usually the decimal ASCII (RFC 20) or Windows 1252 code corresponding to the key. + * If the key can't be identified, this value is 0. + * + * !#zh + * keyCode 是只读属性它表示一个系统和依赖于实现的数字代码,可以识别按键的未修改值。 + * 这通常是十进制 ASCII (RFC20) 或者 Windows 1252 代码,所对应的密钥。 + * 如果无法识别该键,则该值为 0。 + */ + public keyCode: number; + + public isPressed: boolean; + + /** + * @param keyCode - The key code of which triggered this event + * @param isPressed - A boolean indicating whether the key have been pressed + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (keyCode: number, isPressed: boolean, bubbles?: boolean) { + super(Event.KEYBOARD, bubbles); + this.keyCode = keyCode; + this.isPressed = isPressed; + } +} + +// TODO +// @ts-ignore +Event.EventMouse = EventMouse; + +// TODO +// @ts-ignore +Event.EventTouch = EventTouch; + +// TODO +// @ts-ignore +Event.EventAcceleration = EventAcceleration; + +// TODO +// @ts-ignore +Event.EventKeyboard = EventKeyboard; diff --git a/cocos/core/platform/event-manager/CCEventListener.js b/cocos/core/platform/event-manager/CCEventListener.ts similarity index 50% rename from cocos/core/platform/event-manager/CCEventListener.js rename to cocos/core/platform/event-manager/CCEventListener.ts index 8ef379eead..2a1bb16e14 100644 --- a/cocos/core/platform/event-manager/CCEventListener.js +++ b/cocos/core/platform/event-manager/CCEventListener.ts @@ -24,6 +24,12 @@ THE SOFTWARE. ****************************************************************************/ +export interface IEventListenerCreateInfo { + event?: number; + + [x: string]: any; +} + /** * !#en *

@@ -36,32 +42,135 @@ * !#zh * 封装用户的事件处理逻辑。 * 注意:这是一个抽象类,开发者不应该直接实例化这个类,请参考 {{#crossLink "EventListener/create:method"}}cc.EventListener.create{{/crossLink}}。 - * - * @class EventListener - */ - -/** - * Constructor - * @method constructor - * @param {Number} type - * @param {Number} listenerID - * @param {Number} callback */ export class EventListener { - constructor(type, listenerID, callback) { - this._onEvent = callback; // Event callback function - this._type = type || 0; // Event listener type - this._listenerID = listenerID || ""; // Event listener ID - this._registered = false; // Whether the listener has been added to dispatcher. - this._fixedPriority = 0; // The higher the number, the higher the priority, 0 is for scene graph base priority. - this._node = null; // scene graph based priority - this._target = null; - this._paused = true; // Whether the listener is paused - this._isEnabled = true; // Whether the listener is enabled + public get onEvent () { + return this._onEvent; } + /** + * !#en The type code of unknown event listener. + * !#zh 未知的事件监听器类型 + */ + public static UNKNOWN = 0; /* + * !#en The type code of one by one touch event listener. + * !#zh 触摸事件监听器类型,触点会一个一个得分开被派发 + */ + public static TOUCH_ONE_BY_ONE = 1; + + /* + * !#en The type code of all at once touch event listener. + * !#zh 触摸事件监听器类型,触点会被一次性全部派发 + */ + public static TOUCH_ALL_AT_ONCE = 2; + + /** + * !#en The type code of keyboard event listener. + * !#zh 键盘事件监听器类型 + */ + public static KEYBOARD = 3; + + /* + * !#en The type code of mouse event listener. + * !#zh 鼠标事件监听器类型 + */ + public static MOUSE = 4; + + /** + * !#en The type code of acceleration event listener. + * !#zh 加速器事件监听器类型 + */ + public static ACCELERATION = 6; + + /* + * !#en The type code of custom event listener. + * !#zh 自定义事件监听器类型 + */ + public static CUSTOM = 8; + + public static ListenerID = { + MOUSE: '__cc_mouse', + TOUCH_ONE_BY_ONE: '__cc_touch_one_by_one', + TOUCH_ALL_AT_ONCE: '__cc_touch_all_at_once', + KEYBOARD: '__cc_keyboard', + ACCELERATION: '__cc_acceleration', + }; + + /** + * !#en + * Create a EventListener object with configuration including the event type, handlers and other parameters. + * In handlers, this refer to the event listener object itself. + * You can also pass custom parameters in the configuration object, + * all custom parameters will be polyfilled into the event listener object and can be accessed in handlers. + * !#zh 通过指定不同的 Event 对象来设置想要创建的事件监听器。 + * @param {Object} argObj a json object + * @example {@link cocos2d/core/event-manager/CCEventListener/create.js} + */ + public static create (argObj: IEventListenerCreateInfo): EventListener { + cc.assertID(argObj && argObj.event, 1900); + + const listenerType = argObj.event; + delete argObj.event; + + let listener: EventListener | null = null; + if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) { + listener = new TouchOneByOne(); + } else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) { + listener = new TouchAllAtOnce(); + } else if (listenerType === cc.EventListener.MOUSE) { + listener = new Mouse(); + } else if (listenerType === cc.EventListener.KEYBOARD) { + listener = new Keyboard(); + } else if (listenerType === cc.EventListener.ACCELERATION) { + listener = new Acceleration(argObj.callback); + delete argObj.callback; + } + + if (listener) { + for (const key of Object.keys(argObj)) { + listener[key] = argObj[key]; + } + } + + return listener!; + } + + public _target: any = null; + + // Event callback function + protected _onEvent: ((...args: any[]) => any) | null; + + // Event listener type + private _type: number; + + // Event listener ID + private _listenerID: string; + + // Whether the listener has been added to dispatcher. + private _registered = false; + + // The higher the number, the higher the priority, 0 is for scene graph base priority. + private _fixedPriority = 0; + + // scene graph based priority + // @type {Node} + private _node: any = null; // scene graph based priority + + // Whether the listener is paused + private _paused = true; // Whether the listener is paused + + // Whether the listener is enabled + private _isEnabled = true; // Whether the listener is enabled + + constructor (type: number, listenerID: string, callback: ((...args: any[]) => any) | null) { + this._onEvent = callback; + this._type = type || 0; + this._listenerID = listenerID || ''; + } + + /** *

* Sets paused state for the listener * The paused state is only used for scene graph priority listeners. @@ -69,247 +178,176 @@ export class EventListener { * while `EventDispatcher::pauseAllEventListenersForTarget(node)` will set it to `false`. * @note 1) Fixed priority listeners will never get paused. If a fixed priority doesn't want to receive events, * call `setEnabled(false)` instead. - * 2) In `Node`'s onEnter and onExit, the `paused state` of the listeners which associated with that node will be automatically updated. + * 2) In `Node`'s onEnter and onExit, the `paused state` of the listeners + * which associated with that node will be automatically updated. *

- * @param {Boolean} paused * @private */ - _setPaused(paused) { + public _setPaused (paused: boolean) { this._paused = paused; } - /* + /** * Checks whether the listener is paused. - * @returns {Boolean} * @private */ - _isPaused() { + public _isPaused () { return this._paused; } - /* + /** * Marks the listener was registered by EventDispatcher. - * @param {Boolean} registered * @private */ - _setRegistered(registered) { + public _setRegistered (registered: boolean) { this._registered = registered; } - /* + /** * Checks whether the listener was registered by EventDispatcher - * @returns {Boolean} * @private */ - _isRegistered() { + public _isRegistered () { return this._registered; } - /* + /** * Gets the type of this listener - * @note It's different from `EventType`, e.g. TouchEvent has two kinds of event listeners - EventListenerOneByOne, EventListenerAllAtOnce - * @returns {Number} + * @note It's different from `EventType`, e.g. + * TouchEvent has two kinds of event listeners - EventListenerOneByOne, EventListenerAllAtOnce * @private */ - _getType() { + public _getType () { return this._type; } - /* - * Gets the listener ID of this listener - * When event is being dispatched, listener ID is used as key for searching listeners according to event type. - * @returns {String} + /** + * Gets the listener ID of this listener + * When event is being dispatched, listener ID is used as key for searching listeners according to event type. * @private */ - _getListenerID() { + public _getListenerID () { return this._listenerID; } - /* + /** * Sets the fixed priority for this listener - * @note This method is only used for `fixed priority listeners`, it needs to access a non-zero value. 0 is reserved for scene graph priority listeners - * @param {Number} fixedPriority + * @note This method is only used for `fixed priority listeners`, + * it needs to access a non-zero value. 0 is reserved for scene graph priority listeners * @private */ - _setFixedPriority(fixedPriority) { + public _setFixedPriority (fixedPriority: number) { this._fixedPriority = fixedPriority; } - /* + /** * Gets the fixed priority of this listener - * @returns {Number} 0 if it's a scene graph priority listener, non-zero for fixed priority listener + * @return 0 if it's a scene graph priority listener, non-zero for fixed priority listener * @private */ - _getFixedPriority() { + public _getFixedPriority () { return this._fixedPriority; } - /* + /** * Sets scene graph priority for this listener - * @param {cc.Node} node * @private + * @param {Node} node */ - _setSceneGraphPriority(node) { + public _setSceneGraphPriority (node: any) { this._target = node; this._node = node; } - /* + /** * Gets scene graph priority of this listener - * @returns {cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener + * @return if it's a fixed priority listener, non-null for scene graph priority listener * @private */ - _getSceneGraphPriority() { + public _getSceneGraphPriority () { return this._node; } /** * !#en Checks whether the listener is available. * !#zh 检测监听器是否有效 - * @method checkAvailable - * @returns {Boolean} */ - checkAvailable() { + public checkAvailable () { return this._onEvent !== null; } /** * !#en Clones the listener, its subclasses have to override this method. * !#zh 克隆监听器,它的子类必须重写此方法。 - * @method clone - * @returns {EventListener} */ - clone() { + public clone (): EventListener | null { return null; } /** * !#en Enables or disables the listener * !#zh 启用或禁用监听器。 - * @method setEnabled - * @param {Boolean} enabled * @note Only listeners with `enabled` state will be able to receive events. * When an listener was initialized, it's enabled by default. * An event listener can receive events when it is enabled and is not paused. * paused state is always false when it is a fixed priority listener. */ - setEnabled(enabled) { + public setEnabled (enabled: boolean) { this._isEnabled = enabled; } /** * !#en Checks whether the listener is enabled * !#zh 检查监听器是否可用。 - * @method isEnabled - * @returns {Boolean} */ - isEnabled() { + public isEnabled () { return this._isEnabled; } } -// event listener type -/** - * !#en The type code of unknown event listener. - * !#zh 未知的事件监听器类型 - * @property UNKNOWN - * @type {Number} - * @static - */ -EventListener.UNKNOWN = 0; -/* - * !#en The type code of one by one touch event listener. - * !#zh 触摸事件监听器类型,触点会一个一个得分开被派发 - * @property TOUCH_ONE_BY_ONE - * @type {Number} - * @static - */ -EventListener.TOUCH_ONE_BY_ONE = 1; -/* - * !#en The type code of all at once touch event listener. - * !#zh 触摸事件监听器类型,触点会被一次性全部派发 - * @property TOUCH_ALL_AT_ONCE - * @type {Number} - * @static - */ -EventListener.TOUCH_ALL_AT_ONCE = 2; -/** - * !#en The type code of keyboard event listener. - * !#zh 键盘事件监听器类型 - * @property KEYBOARD - * @type {Number} - * @static - */ -EventListener.KEYBOARD = 3; -/* - * !#en The type code of mouse event listener. - * !#zh 鼠标事件监听器类型 - * @property MOUSE - * @type {Number} - * @static - */ -EventListener.MOUSE = 4; -/** - * !#en The type code of acceleration event listener. - * !#zh 加速器事件监听器类型 - * @property ACCELERATION - * @type {Number} - * @static - */ -EventListener.ACCELERATION = 6; -/* - * !#en The type code of custom event listener. - * !#zh 自定义事件监听器类型 - * @property CUSTOM - * @type {Number} - * @static - */ -EventListener.CUSTOM = 8; - -var ListenerID = EventListener.ListenerID = { - MOUSE: '__cc_mouse', - TOUCH_ONE_BY_ONE: '__cc_touch_one_by_one', - TOUCH_ALL_AT_ONCE: '__cc_touch_all_at_once', - KEYBOARD: '__cc_keyboard', - ACCELERATION: '__cc_acceleration', -}; +const ListenerID = EventListener.ListenerID; export class Mouse extends EventListener { - constructor() { - super(EventListener.MOUSE, ListenerID.MOUSE); + public onMouseDown: Function | null = null; + public onMouseUp: Function | null = null; + public onMouseMove: Function | null = null; + public onMouseScroll: Function | null = null; + + constructor () { + super(EventListener.MOUSE, ListenerID.MOUSE, null); this._onEvent = this._callback; - this.onMouseDown = null; - this.onMouseUp = null; - this.onMouseMove = null; - this.onMouseScroll = null; } - _callback(event) { - var eventType = cc.Event.EventMouse; + public _callback (event) { + const eventType = cc.Event.EventMouse; switch (event._eventType) { case eventType.DOWN: - if (this.onMouseDown) + if (this.onMouseDown) { this.onMouseDown(event); + } break; case eventType.UP: - if (this.onMouseUp) + if (this.onMouseUp) { this.onMouseUp(event); + } break; case eventType.MOVE: - if (this.onMouseMove) + if (this.onMouseMove) { this.onMouseMove(event); + } break; case eventType.SCROLL: - if (this.onMouseScroll) + if (this.onMouseScroll) { this.onMouseScroll(event); + } break; default: break; } } - clone() { - var eventListener = new Mouse(); + public clone () { + const eventListener = new Mouse(); eventListener.onMouseDown = this.onMouseDown; eventListener.onMouseUp = this.onMouseUp; eventListener.onMouseMove = this.onMouseMove; @@ -317,34 +355,34 @@ export class Mouse extends EventListener { return eventListener; } - checkAvailable() { + public checkAvailable () { return true; } } export class TouchOneByOne extends EventListener { - constructor() { - super(EventListener.TOUCH_ONE_BY_ONE, ListenerID.TOUCH_ONE_BY_ONE); - this._claimedTouches = []; + public swallowTouches = false; + public onTouchBegan: Function | null = null; + public onTouchMoved: Function | null = null; + public onTouchEnded: Function | null = null; + public onTouchCancelled: Function | null = null; - // this._claimedTouches = null; - this.swallowTouches = false; - this.onTouchBegan = null; - this.onTouchMoved = null; - this.onTouchEnded = null; - this.onTouchCancelled = null; + private _claimedTouches: any[] = []; + + constructor () { + super(EventListener.TOUCH_ONE_BY_ONE, ListenerID.TOUCH_ONE_BY_ONE, null); } - setSwallowTouches(needSwallow) { + public setSwallowTouches (needSwallow) { this.swallowTouches = needSwallow; } - isSwallowTouches() { + public isSwallowTouches () { return this.swallowTouches; } - clone() { - var eventListener = new TouchOneByOne(); + public clone () { + const eventListener = new TouchOneByOne(); eventListener.onTouchBegan = this.onTouchBegan; eventListener.onTouchMoved = this.onTouchMoved; eventListener.onTouchEnded = this.onTouchEnded; @@ -353,7 +391,7 @@ export class TouchOneByOne extends EventListener { return eventListener; } - checkAvailable() { + public checkAvailable () { if (!this.onTouchBegan) { cc.logID(1801); return false; @@ -363,17 +401,17 @@ export class TouchOneByOne extends EventListener { } export class TouchAllAtOnce extends EventListener { - constructor() { - super(EventListener.TOUCH_ALL_AT_ONCE, ListenerID.TOUCH_ALL_AT_ONCE); + public onTouchesBegan: Function | null = null; + public onTouchesMoved: Function | null = null; + public onTouchesEnded: Function | null = null; + public onTouchesCancelled: Function | null = null; - this.onTouchesBegan = null; - this.onTouchesMoved = null; - this.onTouchesEnded = null; - this.onTouchesCancelled = null; + constructor () { + super(EventListener.TOUCH_ALL_AT_ONCE, ListenerID.TOUCH_ALL_AT_ONCE, null); } - clone() { - var eventListener = new TouchAllAtOnce(); + public clone () { + const eventListener = new TouchAllAtOnce(); eventListener.onTouchesBegan = this.onTouchesBegan; eventListener.onTouchesMoved = this.onTouchesMoved; eventListener.onTouchesEnded = this.onTouchesEnded; @@ -381,7 +419,7 @@ export class TouchAllAtOnce extends EventListener { return eventListener; } - checkAvailable() { + public checkAvailable () { if (this.onTouchesBegan === null && this.onTouchesMoved === null && this.onTouchesEnded === null && this.onTouchesCancelled === null) { cc.logID(1802); @@ -391,57 +429,62 @@ export class TouchAllAtOnce extends EventListener { } } -//Acceleration +// Acceleration export class Acceleration extends EventListener { - constructor(callback) { - super(EventListener.ACCELERATION, ListenerID.ACCELERATION); + public _onAccelerationEvent: Function | null = null; + + constructor (callback: Function | null) { + super(EventListener.ACCELERATION, ListenerID.ACCELERATION, null); this._onEvent = this._callback; this._onAccelerationEvent = callback; - this_onAccelerationEvent = null; } - _callback(event) { - this._onAccelerationEvent(event.acc, event); + public _callback (event) { + if (this._onAccelerationEvent) { + this._onAccelerationEvent(event.acc, event); + } } - checkAvailable() { + public checkAvailable () { cc.assertID(this._onAccelerationEvent, 1803); return true; } - clone() { + public clone () { return new Acceleration(this._onAccelerationEvent); } } - -//Keyboard +// Keyboard export class Keyboard extends EventListener { - constructor() { - super(EventListener.KEYBOARD, ListenerID.KEYBOARD); + public onKeyPressed: Function | null = null; + public onKeyReleased: Function | null = null; + + constructor () { + super(EventListener.KEYBOARD, ListenerID.KEYBOARD, null); this._onEvent = this._callback; - this.onKeyPressed = null; - this.onKeyReleased = null; } - _callback(event) { + public _callback (event) { if (event.isPressed) { - if (this.onKeyPressed) + if (this.onKeyPressed) { this.onKeyPressed(event.keyCode, event); + } } else { - if (this.onKeyReleased) + if (this.onKeyReleased) { this.onKeyReleased(event.keyCode, event); + } } } - clone() { - var eventListener = new Keyboard(); + public clone () { + const eventListener = new Keyboard(); eventListener.onKeyPressed = this.onKeyPressed; eventListener.onKeyReleased = this.onKeyReleased; return eventListener; } - checkAvailable() { + public checkAvailable () { if (this.onKeyPressed === null && this.onKeyReleased === null) { cc.logID(1800); return false; @@ -450,43 +493,4 @@ export class Keyboard extends EventListener { } } -/** - * !#en - * Create a EventListener object with configuration including the event type, handlers and other parameters. - * In handlers, this refer to the event listener object itself. - * You can also pass custom parameters in the configuration object, - * all custom parameters will be polyfilled into the event listener object and can be accessed in handlers. - * !#zh 通过指定不同的 Event 对象来设置想要创建的事件监听器。 - * @method create - * @param {Object} argObj a json object - * @returns {EventListener} - * @static - * @example {@link cocos2d/core/event-manager/CCEventListener/create.js} - */ -EventListener.create = function (argObj) { - cc.assertID(argObj && argObj.event, 1900); - - var listenerType = argObj.event; - delete argObj.event; - - var listener = null; - if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) - listener = new TouchOneByOne(); - else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) - listener = new TouchAllAtOnce(); - else if (listenerType === cc.EventListener.MOUSE) - listener = new Mouse(); - else if (listenerType === cc.EventListener.KEYBOARD) - listener = new Keyboard(); - else if (listenerType === cc.EventListener.ACCELERATION) { - listener = new Acceleration(argObj.callback); - delete argObj.callback; - } - - for (var key in argObj) { - listener[key] = argObj[key]; - } - return listener; -} - cc.EventListener = EventListener; diff --git a/cocos/core/platform/event-manager/CCEventManager.js b/cocos/core/platform/event-manager/CCEventManager.ts similarity index 58% rename from cocos/core/platform/event-manager/CCEventManager.js rename to cocos/core/platform/event-manager/CCEventManager.ts index e3864fa397..835eeff35d 100644 --- a/cocos/core/platform/event-manager/CCEventManager.js +++ b/cocos/core/platform/event-manager/CCEventManager.ts @@ -24,689 +24,183 @@ THE SOFTWARE. ****************************************************************************/ +// tslint:disable:max-line-length + import * as js from '../../utils/js'; import { EventListener } from './CCEventListener'; const ListenerID = EventListener.ListenerID; +// tslint:disable-next-line class _EventListenerVector { - constructor() { - this._fixedListeners = []; - this._sceneGraphListeners = []; - this.gt0Index = 0; - } + private _fixedListeners: EventListener[] = []; + private _sceneGraphListeners: EventListener[] = []; + private gt0Index = 0; - size() { + public size () { return this._fixedListeners.length + this._sceneGraphListeners.length; } - empty() { + public empty () { return (this._fixedListeners.length === 0) && (this._sceneGraphListeners.length === 0); } - push(listener) { - if (listener._getFixedPriority() === 0) + public push (listener: EventListener) { + if (listener._getFixedPriority() === 0) { this._sceneGraphListeners.push(listener); - else + } else { this._fixedListeners.push(listener); + } } - clearSceneGraphListeners() { + public clearSceneGraphListeners () { this._sceneGraphListeners.length = 0; } - clearFixedListeners() { + public clearFixedListeners () { this._fixedListeners.length = 0; } - clear() { + public clear () { this._sceneGraphListeners.length = 0; this._fixedListeners.length = 0; } - getFixedPriorityListeners() { + public getFixedPriorityListeners () { return this._fixedListeners; } - getSceneGraphPriorityListeners() { + public getSceneGraphPriorityListeners () { return this._sceneGraphListeners; } } -var __getListenerID = function (event) { - var eventType = cc.Event, type = event.type; - if (type === eventType.ACCELERATION) +function __getListenerID (event) { + const eventType = cc.Event; + const type = event.type; + if (type === eventType.ACCELERATION) { return ListenerID.ACCELERATION; - if (type === eventType.KEYBOARD) + } + if (type === eventType.KEYBOARD) { return ListenerID.KEYBOARD; - if (type.startsWith(eventType.MOUSE)) + } + if (type.startsWith(eventType.MOUSE)) { return ListenerID.MOUSE; + } if (type.startsWith(eventType.TOUCH)) { - // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. + // Touch listener is very special, it contains two kinds of listeners: + // EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // return UNKNOWN instead. cc.logID(2000); } - return ""; -}; + return ''; +} - -//Priority dirty flag +// Priority dirty flag const DIRTY_NONE = 0; const DIRTY_FIXED_PRIORITY = 1 << 0; const DIRTY_SCENE_GRAPH_PRIORITY = 1 << 1; const DIRTY_ALL = 3; -/** - * !#en - * This class has been deprecated, please use cc.systemEvent or cc.EventTarget instead. See [Listen to and launch events](../../../manual/en/scripting/events.md) for details.
- *
- * cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching. - * The EventListener list is managed in such way so that event listeners can be added and removed - * while events are being dispatched. - * - * !#zh - * 该类已废弃,请使用 cc.systemEvent 或 cc.EventTarget 代替,详见 [监听和发射事件](../../../manual/zh/scripting/events.md)。
- *
- * 事件管理器,它主要管理事件监听器注册和派发系统事件。 - * - * @class eventManager - * @static - * @example {@link cocos2d/core/event-manager/CCEventManager/addListener.js} - * @deprecated - */ -var eventManager = { - _listenersMap: {}, - _priorityDirtyFlagMap: {}, - _nodeListenersMap: {}, - _nodePriorityMap: js.createMap(true), - _globalZOrderNodeMap: [], - _toAddedListeners: [], - _toRemovedListeners: [], - _dirtyNodes: [], - _inDispatch: 0, - _isEnabled: false, - _nodePriorityIndex: 0, - _internalCustomListenerIDs: [], - - _setDirtyForNode(node) { - // Mark the node dirty only when there is an event listener associated with it. - if (this._nodeListenersMap[node._id] !== undefined) { - this._dirtyNodes.push(node); - } - if (node.children.length > 0) { - var _children = node.children; - for (var i = 0, len = _children ? _children.length : 0; i < len; i++) - this._setDirtyForNode(_children[i]); - } - }, +class EventManager { + private _listenersMap = {}; + private _priorityDirtyFlagMap = {}; + private _nodeListenersMap = {}; + private _nodePriorityMap = js.createMap(true); + private _globalZOrderNodeMap: string[] = []; + private _toAddedListeners: EventListener[] = []; + private _toRemovedListeners: EventListener[] = []; + private _dirtyNodes: any[] = []; + private _inDispatch = 0; + private _isEnabled = false; + private _nodePriorityIndex = 0; + private _internalCustomListenerIDs: string[] = []; /** * !#en Pauses all listeners which are associated the specified target. * !#zh 暂停传入的 node 相关的所有监听器的事件响应。 - * @method pauseTarget * @param {Node} node - * @param {Boolean} [recursive=false] + * @param [recursive=false] */ - pauseTarget(node, recursive) { + public pauseTarget (node: any, recursive = false) { if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } - var listeners = this._nodeListenersMap[node._id], i, len; + const listeners = this._nodeListenersMap[node._id]; if (listeners) { - for (i = 0, len = listeners.length; i < len; i++) - listeners[i]._setPaused(true); + for (const listener of listeners) { + listener._setPaused(true); + } } if (recursive === true) { - var locChildren = node.children; - for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) - this.pauseTarget(locChildren[i], true); + const locChildren = node.children; + if (locChildren) { + for (const locChild of locChildren) { + this.pauseTarget(locChild, true); + } + } } - }, + } /** * !#en Resumes all listeners which are associated the specified target. * !#zh 恢复传入的 node 相关的所有监听器的事件响应。 - * @method resumeTarget * @param {Node} node - * @param {Boolean} [recursive=false] + * @param [recursive=false] */ - resumeTarget(node, recursive) { + public resumeTarget (node: any, recursive = false) { if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } - var listeners = this._nodeListenersMap[node._id], i, len; + const listeners = this._nodeListenersMap[node._id]; if (listeners) { - for (i = 0, len = listeners.length; i < len; i++) - listeners[i]._setPaused(false); + for (const listener of listeners) { + listener._setPaused(false); + } } this._setDirtyForNode(node); if (recursive === true && node.children.length > 0) { - var locChildren = node.children; - for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) - this.resumeTarget(locChildren[i], true); - } - }, - - _addListener(listener) { - if (this._inDispatch === 0) - this._forceAddEventListener(listener); - else - this._toAddedListeners.push(listener); - }, - - _forceAddEventListener(listener) { - var listenerID = listener._getListenerID(); - var listeners = this._listenersMap[listenerID]; - if (!listeners) { - listeners = new _EventListenerVector(); - this._listenersMap[listenerID] = listeners; - } - listeners.push(listener); - - if (listener._getFixedPriority() === 0) { - this._setDirty(listenerID, DIRTY_SCENE_GRAPH_PRIORITY); - - var node = listener._getSceneGraphPriority(); - if (node === null) - cc.logID(3507); - - this._associateNodeAndEventListener(node, listener); - if (node.activeInHierarchy) - this.resumeTarget(node); - } else - this._setDirty(listenerID, DIRTY_FIXED_PRIORITY); - }, - - _getListeners(listenerID) { - return this._listenersMap[listenerID]; - }, - - _updateDirtyFlagForSceneGraph() { - if (this._dirtyNodes.length === 0) - return; - - var locDirtyNodes = this._dirtyNodes, selListeners, selListener, locNodeListenersMap = this._nodeListenersMap; - for (var i = 0, len = locDirtyNodes.length; i < len; i++) { - selListeners = locNodeListenersMap[locDirtyNodes[i]._id]; - if (selListeners) { - for (var j = 0, listenersLen = selListeners.length; j < listenersLen; j++) { - selListener = selListeners[j]; - if (selListener) - this._setDirty(selListener._getListenerID(), DIRTY_SCENE_GRAPH_PRIORITY); + const locChildren = node.children; + if (locChildren) { + for (const locChild of locChildren) { + this.resumeTarget(locChild, true); } } } - this._dirtyNodes.length = 0; - }, + } - _removeAllListenersInVector(listenerVector) { - if (!listenerVector) - return; - var selListener; - for (var i = 0; i < listenerVector.length;) { - selListener = listenerVector[i]; - selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null) { - this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); - selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. - } - - if (this._inDispatch === 0) - cc.js.array.remove(listenerVector, selListener); - else - ++i; - } - }, - - _removeListenersForListenerID(listenerID) { - var listeners = this._listenersMap[listenerID], i; - if (listeners) { - var fixedPriorityListeners = listeners.getFixedPriorityListeners(); - var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - - this._removeAllListenersInVector(sceneGraphPriorityListeners); - this._removeAllListenersInVector(fixedPriorityListeners); - - // Remove the dirty flag according the 'listenerID'. - // No need to check whether the dispatcher is dispatching event. - delete this._priorityDirtyFlagMap[listenerID]; - - if (!this._inDispatch) { - listeners.clear(); - delete this._listenersMap[listenerID]; - } - } - - var locToAddedListeners = this._toAddedListeners, listener; - for (i = 0; i < locToAddedListeners.length;) { - listener = locToAddedListeners[i]; - if (listener && listener._getListenerID() === listenerID) - cc.js.array.remove(locToAddedListeners, listener); - else - ++i; - } - }, - - _sortEventListeners(listenerID) { - var dirtyFlag = DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap; - if (locFlagMap[listenerID]) - dirtyFlag = locFlagMap[listenerID]; - - if (dirtyFlag !== DIRTY_NONE) { - // Clear the dirty flag first, if `rootNode` is null, then set its dirty flag of scene graph priority - locFlagMap[listenerID] = DIRTY_NONE; - - if (dirtyFlag & DIRTY_FIXED_PRIORITY) - this._sortListenersOfFixedPriority(listenerID); - - if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY) { - var rootEntity = cc.director.getScene(); - if (rootEntity) - this._sortListenersOfSceneGraphPriority(listenerID, rootEntity); - } - } - }, - - _sortListenersOfSceneGraphPriority(listenerID, rootNode) { - var listeners = this._getListeners(listenerID); - if (!listeners) - return; - - var sceneGraphListener = listeners.getSceneGraphPriorityListeners(); - if (!sceneGraphListener || sceneGraphListener.length === 0) - return; - - // Reset priority index - this._nodePriorityIndex = 0; - this._nodePriorityMap = js.createMap(true); - - this._visitTarget(rootNode, true); - - // After sort: priority < 0, > 0 - listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); - }, - - _sortEventListenersOfSceneGraphPriorityDes(l1, l2) { - var locNodePriorityMap = eventManager._nodePriorityMap, - node1 = l1._getSceneGraphPriority(), - node2 = l2._getSceneGraphPriority(); - if (!l2 || !node2 || !locNodePriorityMap[node2._id]) - return -1; - else if (!l1 || !node1 || !locNodePriorityMap[node1._id]) - return 1; - return locNodePriorityMap[node2._id] - locNodePriorityMap[node1._id]; - }, - - _sortListenersOfFixedPriority(listenerID) { - var listeners = this._listenersMap[listenerID]; - if (!listeners) - return; - - var fixedListeners = listeners.getFixedPriorityListeners(); - if (!fixedListeners || fixedListeners.length === 0) - return; - // After sort: priority < 0, > 0 - fixedListeners.sort(this._sortListenersOfFixedPriorityAsc); - - // FIXME: Should use binary search - var index = 0; - for (var len = fixedListeners.length; index < len;) { - if (fixedListeners[index]._getFixedPriority() >= 0) - break; - ++index; - } - listeners.gt0Index = index; - }, - - _sortListenersOfFixedPriorityAsc(l1, l2) { - return l1._getFixedPriority() - l2._getFixedPriority(); - }, - - _onUpdateListeners(listeners) { - var fixedPriorityListeners = listeners.getFixedPriorityListeners(); - var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - var i, selListener, idx, toRemovedListeners = this._toRemovedListeners; - - if (sceneGraphPriorityListeners) { - for (i = 0; i < sceneGraphPriorityListeners.length;) { - selListener = sceneGraphPriorityListeners[i]; - if (!selListener._isRegistered()) { - cc.js.array.remove(sceneGraphPriorityListeners, selListener); - // if item in toRemove list, remove it from the list - idx = toRemovedListeners.indexOf(selListener); - if (idx !== -1) - toRemovedListeners.splice(idx, 1); - } else - ++i; - } - } - - if (fixedPriorityListeners) { - for (i = 0; i < fixedPriorityListeners.length;) { - selListener = fixedPriorityListeners[i]; - if (!selListener._isRegistered()) { - cc.js.array.remove(fixedPriorityListeners, selListener); - // if item in toRemove list, remove it from the list - idx = toRemovedListeners.indexOf(selListener); - if (idx !== -1) - toRemovedListeners.splice(idx, 1); - } - else - ++i; - } - } - - if (sceneGraphPriorityListeners && sceneGraphPriorityListeners.length === 0) - listeners.clearSceneGraphListeners(); - - if (fixedPriorityListeners && fixedPriorityListeners.length === 0) - listeners.clearFixedListeners(); - }, - - frameUpdateListeners() { - var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; - for (var selKey in locListenersMap) { + public frameUpdateListeners () { + const locListenersMap = this._listenersMap; + const locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; + for (const selKey in locListenersMap) { if (locListenersMap[selKey].empty()) { delete locPriorityDirtyFlagMap[selKey]; delete locListenersMap[selKey]; } } - var locToAddedListeners = this._toAddedListeners; + const locToAddedListeners = this._toAddedListeners; if (locToAddedListeners.length !== 0) { - for (var i = 0, len = locToAddedListeners.length; i < len; i++) + for (let i = 0, len = locToAddedListeners.length; i < len; i++) { this._forceAddEventListener(locToAddedListeners[i]); + } locToAddedListeners.length = 0; } if (this._toRemovedListeners.length !== 0) { this._cleanToRemovedListeners(); } - }, - - _updateTouchListeners(event) { - var locInDispatch = this._inDispatch; - cc.assertID(locInDispatch > 0, 3508); - - if (locInDispatch > 1) - return; - - var listeners; - listeners = this._listenersMap[ListenerID.TOUCH_ONE_BY_ONE]; - if (listeners) { - this._onUpdateListeners(listeners); - } - listeners = this._listenersMap[ListenerID.TOUCH_ALL_AT_ONCE]; - if (listeners) { - this._onUpdateListeners(listeners); - } - - cc.assertID(locInDispatch === 1, 3509); - - var locToAddedListeners = this._toAddedListeners; - if (locToAddedListeners.length !== 0) { - for (var i = 0, len = locToAddedListeners.length; i < len; i++) - this._forceAddEventListener(locToAddedListeners[i]); - this._toAddedListeners.length = 0; - } - - if (this._toRemovedListeners.length !== 0) { - this._cleanToRemovedListeners(); - } - }, - - //Remove all listeners in _toRemoveListeners list and cleanup - _cleanToRemovedListeners() { - var toRemovedListeners = this._toRemovedListeners; - for (var i = 0; i < toRemovedListeners.length; i++) { - var selListener = toRemovedListeners[i]; - var listeners = this._listenersMap[selListener._getListenerID()]; - if (!listeners) - continue; - - var idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(), - sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - - if (sceneGraphPriorityListeners) { - idx = sceneGraphPriorityListeners.indexOf(selListener); - if (idx !== -1) { - sceneGraphPriorityListeners.splice(idx, 1); - } - } - if (fixedPriorityListeners) { - idx = fixedPriorityListeners.indexOf(selListener); - if (idx !== -1) { - fixedPriorityListeners.splice(idx, 1); - } - } - } - toRemovedListeners.length = 0; - }, - - _onTouchEventCallback(listener, argsObj) { - // Skip if the listener was removed. - if (!listener._isRegistered) - return false; - - var event = argsObj.event, selTouch = event.currentTouch; - event.currentTarget = listener._node; - - var isClaimed = false, removedIdx; - var getCode = event.getEventCode(), EventTouch = cc.Event.EventTouch; - if (getCode === EventTouch.BEGAN) { - if (listener.onTouchBegan) { - isClaimed = listener.onTouchBegan(selTouch, event); - if (isClaimed && listener._registered) - listener._claimedTouches.push(selTouch); - } - } else if (listener._claimedTouches.length > 0 - && ((removedIdx = listener._claimedTouches.indexOf(selTouch)) !== -1)) { - isClaimed = true; - if (getCode === EventTouch.MOVED && listener.onTouchMoved) { - listener.onTouchMoved(selTouch, event); - } else if (getCode === EventTouch.ENDED) { - if (listener.onTouchEnded) - listener.onTouchEnded(selTouch, event); - if (listener._registered) - listener._claimedTouches.splice(removedIdx, 1); - } else if (getCode === EventTouch.CANCELLED) { - if (listener.onTouchCancelled) - listener.onTouchCancelled(selTouch, event); - if (listener._registered) - listener._claimedTouches.splice(removedIdx, 1); - } - } - - // If the event was stopped, return directly. - if (event.isStopped()) { - eventManager._updateTouchListeners(event); - return true; - } - - if (isClaimed && listener._registered && listener.swallowTouches) { - if (argsObj.needsMutableSet) - argsObj.touches.splice(selTouch, 1); - return true; - } - return false; - }, - - _dispatchTouchEvent(event) { - this._sortEventListeners(ListenerID.TOUCH_ONE_BY_ONE); - this._sortEventListeners(ListenerID.TOUCH_ALL_AT_ONCE); - - var oneByOneListeners = this._getListeners(ListenerID.TOUCH_ONE_BY_ONE); - var allAtOnceListeners = this._getListeners(ListenerID.TOUCH_ALL_AT_ONCE); - - // If there aren't any touch listeners, return directly. - if (null === oneByOneListeners && null === allAtOnceListeners) - return; - - var originalTouches = event.getTouches(), mutableTouches = cc.js.array.copy(originalTouches); - var oneByOneArgsObj = { event: event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null }; - - // - // process the target handlers 1st - // - if (oneByOneListeners) { - for (var i = 0; i < originalTouches.length; i++) { - event.currentTouch = originalTouches[i]; - event._propagationStopped = event._propagationImmediateStopped = false; - this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj); - } - } - - // - // process standard handlers 2nd - // - if (allAtOnceListeners && mutableTouches.length > 0) { - this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, { event: event, touches: mutableTouches }); - if (event.isStopped()) - return; - } - this._updateTouchListeners(event); - }, - - _onTouchesEventCallback(listener, callbackParams) { - // Skip if the listener was removed. - if (!listener._registered) - return false; - - var EventTouch = cc.Event.EventTouch, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode(); - event.currentTarget = listener._node; - if (getCode === EventTouch.BEGAN && listener.onTouchesBegan) - listener.onTouchesBegan(touches, event); - else if (getCode === EventTouch.MOVED && listener.onTouchesMoved) - listener.onTouchesMoved(touches, event); - else if (getCode === EventTouch.ENDED && listener.onTouchesEnded) - listener.onTouchesEnded(touches, event); - else if (getCode === EventTouch.CANCELLED && listener.onTouchesCancelled) - listener.onTouchesCancelled(touches, event); - - // If the event was stopped, return directly. - if (event.isStopped()) { - eventManager._updateTouchListeners(event); - return true; - } - return false; - }, - - _associateNodeAndEventListener(node, listener) { - var listeners = this._nodeListenersMap[node._id]; - if (!listeners) { - listeners = []; - this._nodeListenersMap[node._id] = listeners; - } - listeners.push(listener); - }, - - _dissociateNodeAndEventListener(node, listener) { - var listeners = this._nodeListenersMap[node._id]; - if (listeners) { - cc.js.array.remove(listeners, listener); - if (listeners.length === 0) - delete this._nodeListenersMap[node._id]; - } - }, - - _dispatchEventToListeners(listeners, onEvent, eventOrArgs) { - var shouldStopPropagation = false; - var fixedPriorityListeners = listeners.getFixedPriorityListeners(); - var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - - var i = 0, j, selListener; - if (fixedPriorityListeners) { // priority < 0 - if (fixedPriorityListeners.length !== 0) { - for (; i < listeners.gt0Index; ++i) { - selListener = fixedPriorityListeners[i]; - if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { - shouldStopPropagation = true; - break; - } - } - } - } - - if (sceneGraphPriorityListeners && !shouldStopPropagation) { // priority == 0, scene graph priority - for (j = 0; j < sceneGraphPriorityListeners.length; j++) { - selListener = sceneGraphPriorityListeners[j]; - if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { - shouldStopPropagation = true; - break; - } - } - } - - if (fixedPriorityListeners && !shouldStopPropagation) { // priority > 0 - for (; i < fixedPriorityListeners.length; ++i) { - selListener = fixedPriorityListeners[i]; - if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { - shouldStopPropagation = true; - break; - } - } - } - }, - - _setDirty(listenerID, flag) { - var locDirtyFlagMap = this._priorityDirtyFlagMap; - if (locDirtyFlagMap[listenerID] == null) - locDirtyFlagMap[listenerID] = flag; - else - locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID]; - }, - - _visitTarget(node, isRootNode) { - // sortAllChildren is performed the next frame, but the event is executed immediately. - if (node._reorderChildDirty) { - node.sortAllChildren(); - } - var children = node.children, i = 0; - var childrenCount = children.length, locGlobalZOrderNodeMap = this._globalZOrderNodeMap, locNodeListenersMap = this._nodeListenersMap; - - if (childrenCount > 0) { - if (locNodeListenersMap[node._id] !== undefined) { - if (!locGlobalZOrderNodeMap) - locGlobalZOrderNodeMap = []; - locGlobalZOrderNodeMap.push(node._id); - } - - var child; - for (; i < childrenCount; i++) { - child = children[i]; - if (child) - this._visitTarget(child, false); - } - } else { - if (locNodeListenersMap[node._id] !== undefined) { - if (!locGlobalZOrderNodeMap) - locGlobalZOrderNodeMap = []; - locGlobalZOrderNodeMap.push(node._id); - } - } - - if (isRootNode) { - let locNodePriorityMap = this._nodePriorityMap; - for (let j = 0; j < locGlobalZOrderNodeMap.length; j++) - locNodePriorityMap[locGlobalZOrderNodeMap[j]] = ++this._nodePriorityIndex; - this._globalZOrderNodeMap.length = 0; - } - }, - - _sortNumberAsc(a, b) { - return a - b; - }, + } /** * !#en Query whether the specified event listener id has been added. * !#zh 查询指定的事件 ID 是否存在 - * @method hasEventListener - * @param {String|Number} listenerID - The listener id. - * @return {Boolean} true or false + * @param listenerID - The listener id. + * @return true or false */ - hasEventListener(listenerID) { + public hasEventListener (listenerID: string | number) { return !!this._getListeners(listenerID); - }, + } /** * !#en @@ -723,15 +217,15 @@ var eventManager = { * 如果参数 “nodeOrPriority” 是数字,优先级则固定为该参数的数值,数字越小,优先级越高。
* * @method addListener - * @param {EventListener|Object} listener - The listener of a specified event or a object of some event parameters. - * @param {Node|Number} nodeOrPriority - The priority of the listener is based on the draw order of this node or fixedPriority The fixed priority of the listener. + * @param listener - The listener of a specified event or a object of some event parameters. + * @param nodeOrPriority - The priority of the listener is based on the draw order of this node or fixedPriority The fixed priority of the listener. * @note The priority of scene graph will be fixed value 0. So the order of listener item in the vector will be ' <0, scene graph (0 priority), >0'. * A lower priority will be called before the ones that have a higher value. 0 priority is forbidden for fixed priority since it's used for scene graph based priority. * The listener must be a cc.EventListener object when adding a fixed priority listener, because we can't remove a fixed priority listener without the listener handler, * except calls removeAllListeners(). * @return {EventListener} Return the listener. Needed in order to remove the event from the dispatcher. */ - addListener(listener, nodeOrPriority) { + public addListener (listener: EventListener, nodeOrPriority: any | number): any { cc.assertID(listener && nodeOrPriority, 3503); if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode)) { cc.warnID(3506); @@ -747,8 +241,9 @@ var eventManager = { } } - if (!listener.checkAvailable()) + if (!listener.checkAvailable()) { return; + } if (cc.js.isNumber(nodeOrPriority)) { if (nodeOrPriority === 0) { @@ -769,41 +264,42 @@ var eventManager = { } return listener; - }, + } - /* + /** * !#en Adds a Custom event listener. It will use a fixed priority of 1. * !#zh 向事件管理器添加一个自定义事件监听器。 - * @method addCustomListener - * @param {String} eventName - * @param {Function} callback - * @return {EventListener} the generated event. Needed in order to remove the event from the dispatcher + * @param eventName + * @param callback + * @return the generated event. Needed in order to remove the event from the dispatcher */ - addCustomListener(eventName, callback) { - var listener = new cc.EventListener.create({ + public addCustomListener (eventName: string, callback: Function) { + const listener = EventListener.create({ event: cc.EventListener.CUSTOM, - eventName: eventName, - callback: callback + eventName, + callback, }); this.addListener(listener, 1); return listener; - }, + } /** * !#en Remove a listener. * !#zh 移除一个已添加的监听器。 - * @method removeListener - * @param {EventListener} listener - an event listener or a registered node target + * @param listener - an event listener or a registered node target * @example {@link cocos2d/core/event-manager/CCEventManager/removeListener.js} */ - removeListener(listener) { - if (listener == null) + public removeListener (listener: EventListener) { + if (listener == null) { return; + } - var isFound, locListener = this._listenersMap; - for (var selKey in locListener) { - var listeners = locListener[selKey]; - var fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + let isFound = false; + const locListener = this._listenersMap; + for (const selKey of Object.keys(locListener)) { + const listeners = locListener[selKey]; + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener); if (isFound) { @@ -811,8 +307,9 @@ var eventManager = { this._setDirty(listener._getListenerID(), DIRTY_SCENE_GRAPH_PRIORITY); } else { isFound = this._removeListenerInVector(fixedPriorityListeners, listener); - if (isFound) + if (isFound) { this._setDirty(listener._getListenerID(), DIRTY_FIXED_PRIORITY); + } } if (listeners.empty()) { @@ -820,14 +317,15 @@ var eventManager = { delete locListener[selKey]; } - if (isFound) + if (isFound) { break; + } } if (!isFound) { - var locToAddedListeners = this._toAddedListeners; - for (var i = 0, len = locToAddedListeners.length; i < len; i++) { - var selListener = locToAddedListeners[i]; + const locToAddedListeners = this._toAddedListeners; + for (let i = 0, len = locToAddedListeners.length; i < len; i++) { + const selListener = locToAddedListeners[i]; if (selListener === listener) { cc.js.array.remove(locToAddedListeners, selListener); selListener._setRegistered(false); @@ -835,53 +333,7 @@ var eventManager = { } } } - }, - - _removeListenerInCallback(listeners, callback) { - if (listeners == null) - return false; - - for (var i = 0, len = listeners.length; i < len; i++) { - var selListener = listeners[i]; - if (selListener._onCustomEvent === callback || selListener._onEvent === callback) { - selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null) { - this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); - selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. - } - - if (this._inDispatch === 0) - cc.js.array.remove(listeners, selListener); - else - this._toRemovedListeners.push(selListener); - return true; - } - } - return false; - }, - - _removeListenerInVector(listeners, listener) { - if (listeners == null) - return false; - - for (var i = 0, len = listeners.length; i < len; i++) { - var selListener = listeners[i]; - if (selListener === listener) { - selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null) { - this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); - selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. - } - - if (this._inDispatch === 0) - cc.js.array.remove(listeners, selListener); - else - this._toRemovedListeners.push(selListener); - return true; - } - } - return false; - }, + } /** * !#en Removes all listeners with the same event listener type or removes all listeners of a node. @@ -899,10 +351,9 @@ var eventManager = { * * @method removeListeners * @param {Number|Node} listenerType - listenerType or a node - * @param {Boolean} [recursive=false] + * @param [recursive=false] */ - removeListeners(listenerType, recursive) { - var i, _t = this; + public removeListeners (listenerType: number | any, recursive = false) { if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) { cc.warnID(3506); return; @@ -910,14 +361,15 @@ var eventManager = { if (listenerType._id !== undefined) { // Ensure the node is removed from these immediately also. // Don't want any dangling pointers or the possibility of dealing with deleted objects.. - delete _t._nodePriorityMap[listenerType._id]; - cc.js.array.remove(_t._dirtyNodes, listenerType); - var listeners = _t._nodeListenersMap[listenerType._id], i; + delete this._nodePriorityMap[listenerType._id]; + cc.js.array.remove(this._dirtyNodes, listenerType); + const listeners = this._nodeListenersMap[listenerType._id]; if (listeners) { - var listenersCopy = cc.js.array.copy(listeners); - for (i = 0; i < listenersCopy.length; i++) - _t.removeListener(listenersCopy[i]); - delete _t._nodeListenersMap[listenerType._id]; + const listenersCopy = cc.js.array.copy(listeners); + for (const listenerCopy of listenersCopy) { + this.removeListener(listenerCopy); + } + delete this._nodeListenersMap[listenerType._id]; } // Bug fix: ensure there are no references to the node in the list of listeners to be added. @@ -925,37 +377,41 @@ var eventManager = { // This is to catch the scenario where the node gets destroyed before it's listener // is added into the event dispatcher fully. This could happen if a node registers a listener // and gets destroyed while we are dispatching an event (touch etc.) - var locToAddedListeners = _t._toAddedListeners; - for (i = 0; i < locToAddedListeners.length;) { - var listener = locToAddedListeners[i]; + const locToAddedListeners = this._toAddedListeners; + for (let i = 0; i < locToAddedListeners.length;) { + const listener = locToAddedListeners[i]; if (listener._getSceneGraphPriority() === listenerType) { - listener._setSceneGraphPriority(null); // Ensure no dangling ptr to the target node. + // Ensure no dangling ptr to the target node. + listener._setSceneGraphPriority(null); listener._setRegistered(false); locToAddedListeners.splice(i, 1); - } else + } else { ++i; + } } if (recursive === true) { - var locChildren = listenerType.getChildren(), len; - for (i = 0, len = locChildren.length; i < len; i++) - _t.removeListeners(locChildren[i], true); + const locChildren = listenerType.getChildren(); + for (const locChild of locChildren) { + this.removeListeners(locChild, true); + } } } else { - if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) - _t._removeListenersForListenerID(ListenerID.TOUCH_ONE_BY_ONE); - else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) - _t._removeListenersForListenerID(ListenerID.TOUCH_ALL_AT_ONCE); - else if (listenerType === cc.EventListener.MOUSE) - _t._removeListenersForListenerID(ListenerID.MOUSE); - else if (listenerType === cc.EventListener.ACCELERATION) - _t._removeListenersForListenerID(ListenerID.ACCELERATION); - else if (listenerType === cc.EventListener.KEYBOARD) - _t._removeListenersForListenerID(ListenerID.KEYBOARD); - else + if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) { + this._removeListenersForListenerID(ListenerID.TOUCH_ONE_BY_ONE); + } else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) { + this._removeListenersForListenerID(ListenerID.TOUCH_ALL_AT_ONCE); + } else if (listenerType === cc.EventListener.MOUSE) { + this._removeListenersForListenerID(ListenerID.MOUSE); + } else if (listenerType === cc.EventListener.ACCELERATION) { + this._removeListenersForListenerID(ListenerID.ACCELERATION); + } else if (listenerType === cc.EventListener.KEYBOARD) { + this._removeListenersForListenerID(ListenerID.KEYBOARD); + } else { cc.logID(3501); + } } - }, + } /* * !#en Removes all custom listeners with the same event name. @@ -963,22 +419,24 @@ var eventManager = { * @method removeCustomListeners * @param {String} customEventName */ - removeCustomListeners(customEventName) { + public removeCustomListeners (customEventName) { this._removeListenersForListenerID(customEventName); - }, + } /** * !#en Removes all listeners * !#zh 移除所有事件监听器。 * @method removeAllListeners */ - removeAllListeners() { - var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs; - for (var selKey in locListeners) { - if (locInternalCustomEventIDs.indexOf(selKey) === -1) + public removeAllListeners () { + const locListeners = this._listenersMap; + const locInternalCustomEventIDs = this._internalCustomListenerIDs; + for (const selKey in locListeners) { + if (locInternalCustomEventIDs.indexOf(selKey) === -1) { this._removeListenersForListenerID(selKey); + } } - }, + } /** * !#en Sets listener's priority with fixed value. @@ -987,19 +445,21 @@ var eventManager = { * @param {EventListener} listener * @param {Number} fixedPriority */ - setPriority(listener, fixedPriority) { - if (listener == null) + public setPriority (listener, fixedPriority) { + if (listener == null) { return; + } - var locListeners = this._listenersMap; - for (var selKey in locListeners) { - var selListeners = locListeners[selKey]; - var fixedPriorityListeners = selListeners.getFixedPriorityListeners(); + const locListeners = this._listenersMap; + for (const selKey of Object.keys(locListeners)) { + const selListeners = locListeners[selKey]; + const fixedPriorityListeners = selListeners.getFixedPriorityListeners(); if (fixedPriorityListeners) { - var found = fixedPriorityListeners.indexOf(listener); + const found = fixedPriorityListeners.indexOf(listener); if (found !== -1) { - if (listener._getSceneGraphPriority() != null) + if (listener._getSceneGraphPriority() != null) { cc.logID(3502); + } if (listener._getFixedPriority() !== fixedPriority) { listener._setFixedPriority(fixedPriority); this._setDirty(listener._getListenerID(), DIRTY_FIXED_PRIORITY); @@ -1008,7 +468,7 @@ var eventManager = { } } } - }, + } /** * !#en Whether to enable dispatching events @@ -1016,9 +476,9 @@ var eventManager = { * @method setEnabled * @param {Boolean} enabled */ - setEnabled(enabled) { + public setEnabled (enabled) { this._isEnabled = enabled; - }, + } /** * !#en Checks whether dispatching events is enabled @@ -1026,9 +486,9 @@ var eventManager = { * @method isEnabled * @returns {Boolean} */ - isEnabled() { + public isEnabled () { return this._isEnabled; - }, + } /* * !#en Dispatches the event, also removes all EventListeners marked for deletion from the event dispatcher list. @@ -1036,9 +496,10 @@ var eventManager = { * @method dispatchEvent * @param {Event} event */ - dispatchEvent(event) { - if (!this._isEnabled) + public dispatchEvent (event) { + if (!this._isEnabled) { return; + } this._updateDirtyFlagForSceneGraph(); this._inDispatch++; @@ -1052,22 +513,25 @@ var eventManager = { return; } - var listenerID = __getListenerID(event); + const listenerID = __getListenerID(event); this._sortEventListeners(listenerID); - var selListeners = this._listenersMap[listenerID]; + const selListeners = this._listenersMap[listenerID]; if (selListeners != null) { this._dispatchEventToListeners(selListeners, this._onListenerCallback, event); this._onUpdateListeners(selListeners); } this._inDispatch--; - }, + } - _onListenerCallback(listener, event) { + public _onListenerCallback (listener: EventListener, event) { event.currentTarget = listener._target; - listener._onEvent(event); + const onEvent = listener.onEvent; + if (onEvent) { + onEvent(event); + } return event.isStopped(); - }, + } /* * !#en Dispatches a Custom Event with a event name an optional user data @@ -1076,13 +540,643 @@ var eventManager = { * @param {String} eventName * @param {*} optionalUserData */ - dispatchCustomEvent(eventName, optionalUserData) { - var ev = new cc.Event.EventCustom(eventName); + public dispatchCustomEvent (eventName, optionalUserData) { + const ev = new cc.Event.EventCustom(eventName); ev.setUserData(optionalUserData); this.dispatchEvent(ev); } + + private _setDirtyForNode (node) { + // Mark the node dirty only when there is an event listener associated with it. + if (this._nodeListenersMap[node._id] !== undefined) { + this._dirtyNodes.push(node); + } + if (node.children.length > 0) { + const _children = node.children; + for (let i = 0, len = _children ? _children.length : 0; i < len; i++) { + this._setDirtyForNode(_children[i]); + } + } + } + + private _addListener (listener) { + if (this._inDispatch === 0) { + this._forceAddEventListener(listener); + } else { + this._toAddedListeners.push(listener); + } + } + + private _forceAddEventListener (listener) { + const listenerID = listener._getListenerID(); + let listeners = this._listenersMap[listenerID]; + if (!listeners) { + listeners = new _EventListenerVector(); + this._listenersMap[listenerID] = listeners; + } + listeners.push(listener); + + if (listener._getFixedPriority() === 0) { + this._setDirty(listenerID, DIRTY_SCENE_GRAPH_PRIORITY); + + const node = listener._getSceneGraphPriority(); + if (node === null) { + cc.logID(3507); + } + + this._associateNodeAndEventListener(node, listener); + if (node.activeInHierarchy) { + this.resumeTarget(node); + } + } else { + this._setDirty(listenerID, DIRTY_FIXED_PRIORITY); + } + } + + private _getListeners (listenerID) { + return this._listenersMap[listenerID]; + } + + private _updateDirtyFlagForSceneGraph () { + if (this._dirtyNodes.length === 0) { + return; + } + + const locDirtyNodes = this._dirtyNodes; + const locNodeListenersMap = this._nodeListenersMap; + for (let i = 0, len = locDirtyNodes.length; i < len; i++) { + const selListeners = locNodeListenersMap[locDirtyNodes[i]._id]; + if (selListeners) { + for (let j = 0, listenersLen = selListeners.length; j < listenersLen; j++) { + const selListener = selListeners[j]; + if (selListener) { + this._setDirty(selListener._getListenerID(), DIRTY_SCENE_GRAPH_PRIORITY); + } + } + } + } + this._dirtyNodes.length = 0; + } + + private _removeAllListenersInVector (listenerVector) { + if (!listenerVector) { + return; + } + let selListener; + for (let i = 0; i < listenerVector.length;) { + selListener = listenerVector[i]; + selListener._setRegistered(false); + if (selListener._getSceneGraphPriority() != null) { + this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); + selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. + } + + if (this._inDispatch === 0) { + cc.js.array.remove(listenerVector, selListener); + } else { + ++i; + } + } + } + + private _removeListenersForListenerID (listenerID) { + const listeners = this._listenersMap[listenerID]; + if (listeners) { + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + + this._removeAllListenersInVector(sceneGraphPriorityListeners); + this._removeAllListenersInVector(fixedPriorityListeners); + + // Remove the dirty flag according the 'listenerID'. + // No need to check whether the dispatcher is dispatching event. + delete this._priorityDirtyFlagMap[listenerID]; + + if (!this._inDispatch) { + listeners.clear(); + delete this._listenersMap[listenerID]; + } + } + + const locToAddedListeners = this._toAddedListeners; + for (let i = 0; i < locToAddedListeners.length;) { + const listener = locToAddedListeners[i]; + if (listener && listener._getListenerID() === listenerID) { + cc.js.array.remove(locToAddedListeners, listener); + } else { + ++i; + } + } + } + + private _sortEventListeners (listenerID) { + let dirtyFlag = DIRTY_NONE; + const locFlagMap = this._priorityDirtyFlagMap; + if (locFlagMap[listenerID]) { + dirtyFlag = locFlagMap[listenerID]; + } + + if (dirtyFlag !== DIRTY_NONE) { + // Clear the dirty flag first, if `rootNode` is null, then set its dirty flag of scene graph priority + locFlagMap[listenerID] = DIRTY_NONE; + + if (dirtyFlag & DIRTY_FIXED_PRIORITY) { + this._sortListenersOfFixedPriority(listenerID); + } + + if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY) { + const rootEntity = cc.director.getScene(); + if (rootEntity) { + this._sortListenersOfSceneGraphPriority(listenerID, rootEntity); + } + } + } + } + + private _sortListenersOfSceneGraphPriority (listenerID, rootNode) { + const listeners = this._getListeners(listenerID); + if (!listeners) { + return; + } + + const sceneGraphListener = listeners.getSceneGraphPriorityListeners(); + if (!sceneGraphListener || sceneGraphListener.length === 0) { + return; + } + + // Reset priority index + this._nodePriorityIndex = 0; + this._nodePriorityMap = js.createMap(true); + + this._visitTarget(rootNode, true); + + // After sort: priority < 0, > 0 + listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); + } + + private _sortEventListenersOfSceneGraphPriorityDes (l1: EventListener, l2: EventListener) { + const locNodePriorityMap = eventManager._nodePriorityMap; + const node1 = l1._getSceneGraphPriority(); + const node2 = l2._getSceneGraphPriority(); + if (!l2 || !node2 || !locNodePriorityMap[node2._id]) { + return -1; + } else if (!l1 || !node1 || !locNodePriorityMap[node1._id]) { + return 1; + } + return locNodePriorityMap[node2._id] - locNodePriorityMap[node1._id]; + } + + private _sortListenersOfFixedPriority (listenerID) { + const listeners = this._listenersMap[listenerID]; + if (!listeners) { + return; + } + + const fixedListeners = listeners.getFixedPriorityListeners(); + if (!fixedListeners || fixedListeners.length === 0) { + return; + } + // After sort: priority < 0, > 0 + fixedListeners.sort(this._sortListenersOfFixedPriorityAsc); + + // FIXME: Should use binary search + let index = 0; + for (const len = fixedListeners.length; index < len;) { + if (fixedListeners[index]._getFixedPriority() >= 0) { + break; + } + ++index; + } + listeners.gt0Index = index; + } + + private _sortListenersOfFixedPriorityAsc (l1, l2) { + return l1._getFixedPriority() - l2._getFixedPriority(); + } + + private _onUpdateListeners (listeners) { + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + const toRemovedListeners = this._toRemovedListeners; + + if (sceneGraphPriorityListeners) { + for (let i = 0; i < sceneGraphPriorityListeners.length;) { + const selListener = sceneGraphPriorityListeners[i]; + if (!selListener._isRegistered()) { + cc.js.array.remove(sceneGraphPriorityListeners, selListener); + // if item in toRemove list, remove it from the list + const idx = toRemovedListeners.indexOf(selListener); + if (idx !== -1) { + toRemovedListeners.splice(idx, 1); + } + } else { + ++i; + } + } + } + + if (fixedPriorityListeners) { + for (let i = 0; i < fixedPriorityListeners.length;) { + const selListener = fixedPriorityListeners[i]; + if (!selListener._isRegistered()) { + cc.js.array.remove(fixedPriorityListeners, selListener); + // if item in toRemove list, remove it from the list + const idx = toRemovedListeners.indexOf(selListener); + if (idx !== -1) { + toRemovedListeners.splice(idx, 1); + } + } else { + ++i; + } + } + } + + if (sceneGraphPriorityListeners && sceneGraphPriorityListeners.length === 0) { + listeners.clearSceneGraphListeners(); + } + + if (fixedPriorityListeners && fixedPriorityListeners.length === 0) { + listeners.clearFixedListeners(); + } + } + + private _updateTouchListeners (event) { + const locInDispatch = this._inDispatch; + cc.assertID(locInDispatch > 0, 3508); + + if (locInDispatch > 1) { + return; + } + + let listeners; + listeners = this._listenersMap[ListenerID.TOUCH_ONE_BY_ONE]; + if (listeners) { + this._onUpdateListeners(listeners); + } + listeners = this._listenersMap[ListenerID.TOUCH_ALL_AT_ONCE]; + if (listeners) { + this._onUpdateListeners(listeners); + } + + cc.assertID(locInDispatch === 1, 3509); + + const locToAddedListeners = this._toAddedListeners; + if (locToAddedListeners.length !== 0) { + for (let i = 0, len = locToAddedListeners.length; i < len; i++) { + this._forceAddEventListener(locToAddedListeners[i]); + } + this._toAddedListeners.length = 0; + } + + if (this._toRemovedListeners.length !== 0) { + this._cleanToRemovedListeners(); + } + } + + // Remove all listeners in _toRemoveListeners list and cleanup + private _cleanToRemovedListeners () { + const toRemovedListeners = this._toRemovedListeners; + for (const selListener of toRemovedListeners) { + const listeners = this._listenersMap[selListener._getListenerID()]; + if (!listeners) { + continue; + } + + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + + if (sceneGraphPriorityListeners) { + const idx = sceneGraphPriorityListeners.indexOf(selListener); + if (idx !== -1) { + sceneGraphPriorityListeners.splice(idx, 1); + } + } + if (fixedPriorityListeners) { + const idx = fixedPriorityListeners.indexOf(selListener); + if (idx !== -1) { + fixedPriorityListeners.splice(idx, 1); + } + } + } + toRemovedListeners.length = 0; + } + + private _onTouchEventCallback (listener, argsObj) { + // Skip if the listener was removed. + if (!listener._isRegistered) { + return false; + } + + const event = argsObj.event; + const selTouch = event.currentTouch; + event.currentTarget = listener._node; + + let isClaimed = false; + let removedIdx; + const getCode = event.getEventCode(); + const EventTouch = cc.Event.EventTouch; + if (getCode === EventTouch.BEGAN) { + if (listener.onTouchBegan) { + isClaimed = listener.onTouchBegan(selTouch, event); + if (isClaimed && listener._registered) { + listener._claimedTouches.push(selTouch); + } + } + } else if (listener._claimedTouches.length > 0) { + removedIdx = listener._claimedTouches.indexOf(selTouch); + if (removedIdx !== -1) { + isClaimed = true; + if (getCode === EventTouch.MOVED && listener.onTouchMoved) { + listener.onTouchMoved(selTouch, event); + } else if (getCode === EventTouch.ENDED) { + if (listener.onTouchEnded) { + listener.onTouchEnded(selTouch, event); + } + if (listener._registered) { + listener._claimedTouches.splice(removedIdx, 1); + } + } else if (getCode === EventTouch.CANCELLED) { + if (listener.onTouchCancelled) { + listener.onTouchCancelled(selTouch, event); + } + if (listener._registered) { + listener._claimedTouches.splice(removedIdx, 1); + } + } + } + } + + // If the event was stopped, return directly. + if (event.isStopped()) { + eventManager._updateTouchListeners(event); + return true; + } + + if (isClaimed && listener._registered && listener.swallowTouches) { + if (argsObj.needsMutableSet) { + argsObj.touches.splice(selTouch, 1); + } + return true; + } + return false; + } + + private _dispatchTouchEvent (event) { + this._sortEventListeners(ListenerID.TOUCH_ONE_BY_ONE); + this._sortEventListeners(ListenerID.TOUCH_ALL_AT_ONCE); + + const oneByOneListeners = this._getListeners(ListenerID.TOUCH_ONE_BY_ONE); + const allAtOnceListeners = this._getListeners(ListenerID.TOUCH_ALL_AT_ONCE); + + // If there aren't any touch listeners, return directly. + if (null === oneByOneListeners && null === allAtOnceListeners) { + return; + } + + const originalTouches = event.getTouches(); + const mutableTouches = cc.js.array.copy(originalTouches); + const oneByOneArgsObj = { event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null }; + + // + // process the target handlers 1st + // + if (oneByOneListeners) { + for (const originalTouch of originalTouches) { + event.currentTouch = originalTouch; + event._propagationStopped = event._propagationImmediateStopped = false; + this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj); + } + } + + // + // process standard handlers 2nd + // + if (allAtOnceListeners && mutableTouches.length > 0) { + this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, { event, touches: mutableTouches }); + if (event.isStopped()) { + return; + } + } + this._updateTouchListeners(event); + } + + private _onTouchesEventCallback (listener, callbackParams) { + // Skip if the listener was removed. + if (!listener._registered) { + return false; + } + + const EventTouch = cc.Event.EventTouch; + const event = callbackParams.event; + const touches = callbackParams.touches; + const getCode = event.getEventCode(); + event.currentTarget = listener._node; + if (getCode === EventTouch.BEGAN && listener.onTouchesBegan) { + listener.onTouchesBegan(touches, event); + } else if (getCode === EventTouch.MOVED && listener.onTouchesMoved) { + listener.onTouchesMoved(touches, event); + } else if (getCode === EventTouch.ENDED && listener.onTouchesEnded) { + listener.onTouchesEnded(touches, event); + } else if (getCode === EventTouch.CANCELLED && listener.onTouchesCancelled) { + listener.onTouchesCancelled(touches, event); + } + + // If the event was stopped, return directly. + if (event.isStopped()) { + eventManager._updateTouchListeners(event); + return true; + } + return false; + } + + private _associateNodeAndEventListener (node, listener) { + let listeners = this._nodeListenersMap[node._id]; + if (!listeners) { + listeners = []; + this._nodeListenersMap[node._id] = listeners; + } + listeners.push(listener); + } + + private _dissociateNodeAndEventListener (node, listener) { + const listeners = this._nodeListenersMap[node._id]; + if (listeners) { + cc.js.array.remove(listeners, listener); + if (listeners.length === 0) { + delete this._nodeListenersMap[node._id]; + } + } + } + + private _dispatchEventToListeners (listeners, onEvent, eventOrArgs) { + let shouldStopPropagation = false; + const fixedPriorityListeners = listeners.getFixedPriorityListeners(); + const sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); + + let i = 0; + if (fixedPriorityListeners) { // priority < 0 + if (fixedPriorityListeners.length !== 0) { + for (; i < listeners.gt0Index; ++i) { + const selListener = fixedPriorityListeners[i]; + if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { + shouldStopPropagation = true; + break; + } + } + } + } + + if (sceneGraphPriorityListeners && !shouldStopPropagation) { // priority == 0, scene graph priority + for (const selListener of sceneGraphPriorityListeners) { + if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { + shouldStopPropagation = true; + break; + } + } + } + + if (fixedPriorityListeners && !shouldStopPropagation) { // priority > 0 + for (; i < fixedPriorityListeners.length; ++i) { + const selListener = fixedPriorityListeners[i]; + if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { + shouldStopPropagation = true; + break; + } + } + } + } + + private _setDirty (listenerID, flag) { + const locDirtyFlagMap = this._priorityDirtyFlagMap; + if (locDirtyFlagMap[listenerID] == null) { + locDirtyFlagMap[listenerID] = flag; + } else { + locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID]; + } + } + + private _visitTarget (node, isRootNode) { + // sortAllChildren is performed the next frame, but the event is executed immediately. + if (node._reorderChildDirty) { + node.sortAllChildren(); + } + const children = node.children; + let i = 0; + const childrenCount = children.length; + let locGlobalZOrderNodeMap = this._globalZOrderNodeMap; + const locNodeListenersMap = this._nodeListenersMap; + + if (childrenCount > 0) { + if (locNodeListenersMap[node._id] !== undefined) { + if (!locGlobalZOrderNodeMap) { + locGlobalZOrderNodeMap = []; + } + locGlobalZOrderNodeMap.push(node._id); + } + + let child; + for (; i < childrenCount; i++) { + child = children[i]; + if (child) { + this._visitTarget(child, false); + } + } + } else { + if (locNodeListenersMap[node._id] !== undefined) { + if (!locGlobalZOrderNodeMap) { + locGlobalZOrderNodeMap = []; + } + locGlobalZOrderNodeMap.push(node._id); + } + } + + if (isRootNode) { + const locNodePriorityMap = this._nodePriorityMap; + for (const locGlobalZOrderNode of locGlobalZOrderNodeMap) { + locNodePriorityMap[locGlobalZOrderNode] = ++this._nodePriorityIndex; + } + this._globalZOrderNodeMap.length = 0; + } + } + + private _sortNumberAsc (a, b) { + return a - b; + } + + private _removeListenerInCallback (listeners: EventListener[], callback) { + if (listeners == null) { + return false; + } + + for (let i = 0, len = listeners.length; i < len; i++) { + const selListener = listeners[i]; + if (selListener._onCustomEvent === callback || selListener.onEvent === callback) { + selListener._setRegistered(false); + if (selListener._getSceneGraphPriority() != null) { + this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); + // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. + selListener._setSceneGraphPriority(null); + } + + if (this._inDispatch === 0) { + cc.js.array.remove(listeners, selListener); + } else { + this._toRemovedListeners.push(selListener); + } + return true; + } + } + return false; + } + + private _removeListenerInVector (listeners: EventListener[], listener: EventListener) { + if (listeners == null) { + return false; + } + + for (let i = 0, len = listeners.length; i < len; i++) { + const selListener = listeners[i]; + if (selListener === listener) { + selListener._setRegistered(false); + if (selListener._getSceneGraphPriority() != null) { + this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); + // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. + selListener._setSceneGraphPriority(null); + } + + if (this._inDispatch === 0) { + cc.js.array.remove(listeners, selListener); + } else { + this._toRemovedListeners.push(selListener); + } + return true; + } + } + return false; + } } +/** + * !#en + * This class has been deprecated, please use cc.systemEvent or cc.EventTarget instead. + * See [Listen to and launch events](../../../manual/en/scripting/events.md) for details.
+ *
+ * cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching. + * The EventListener list is managed in such way so that event listeners can be added and removed + * while events are being dispatched. + * + * !#zh + * 该类已废弃,请使用 cc.systemEvent 或 cc.EventTarget 代替,详见 [监听和发射事件](../../../manual/zh/scripting/events.md)。
+ *
+ * 事件管理器,它主要管理事件监听器注册和派发系统事件。 + * + * @class eventManager + * @static + * @example {@link cocos2d/core/event-manager/CCEventManager/addListener.js} + * @deprecated + */ +export const eventManager = new EventManager(); + cc.eventManager = eventManager; -export default eventManager +export default eventManager; diff --git a/cocos/core/platform/event-manager/CCInputManager.js b/cocos/core/platform/event-manager/CCInputManager.js deleted file mode 100644 index af56dcff40..0000000000 --- a/cocos/core/platform/event-manager/CCInputManager.js +++ /dev/null @@ -1,759 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - 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 macro from '../CCMacro'; -import sys from '../CCSys'; -import eventManager from './CCEventManager'; - -const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; - -const PORTRAIT = 0; -const LANDSCAPE_LEFT = -90; -const PORTRAIT_UPSIDE_DOWN = 180; -const LANDSCAPE_RIGHT = 90; - -let _didAccelerateFun; -let _vec2 = cc.v2(); - -/** - * !#en the device accelerometer reports values for each axis in units of g-force. - * !#zh 设备重力传感器传递的各个轴的数据。 - * @class Acceleration - * @method constructor - * @param {Number} x - * @param {Number} y - * @param {Number} z - * @param {Number} timestamp - */ -let Acceleration = function (x, y, z, timestamp) { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.timestamp = timestamp || 0; -}; - -/** - * This class manages all events of input. include: touch, mouse, accelerometer, keyboard - */ -let inputManager = { - _mousePressed: false, - - _isRegisterEvent: false, - - _preTouchPoint: cc.v2(0,0), - _prevMousePoint: cc.v2(0,0), - - _preTouchPool: [], - _preTouchPoolPointer: 0, - - _touches: [], - _touchesIntegerDict:{}, - - _indexBitsUsed: 0, - _maxTouches: 8, - - _accelEnabled: false, - _accelInterval: 1/5, - _accelMinus: 1, - _accelCurTime: 0, - _acceleration: null, - _accelDeviceEvent: null, - - _getUnUsedIndex () { - let temp = this._indexBitsUsed; - let now = cc.sys.now(); - - for (let i = 0; i < this._maxTouches; i++) { - if (!(temp & 0x00000001)) { - this._indexBitsUsed |= (1 << i); - return i; - } - else { - let touch = this._touches[i]; - if (now - touch._lastModified > TOUCH_TIMEOUT) { - this._removeUsedIndexBit(i); - delete this._touchesIntegerDict[touch.getID()]; - return i; - } - } - temp >>= 1; - } - - // all bits are used - return -1; - }, - - _removeUsedIndexBit (index) { - if (index < 0 || index >= this._maxTouches) - return; - - let temp = 1 << index; - temp = ~temp; - this._indexBitsUsed &= temp; - }, - - _glView: null, - - /** - * @method handleTouchesBegin - * @param {Array} touches - */ - handleTouchesBegin (touches) { - let selTouch, index, curTouch, touchID, - handleTouches = [], locTouchIntDict = this._touchesIntegerDict, - now = sys.now(); - for (let i = 0, len = touches.length; i < len; i ++) { - selTouch = touches[i]; - touchID = selTouch.getID(); - index = locTouchIntDict[touchID]; - - if (index == null) { - let unusedIndex = this._getUnUsedIndex(); - if (unusedIndex === -1) { - cc.logID(2300, unusedIndex); - continue; - } - //curTouch = this._touches[unusedIndex] = selTouch; - curTouch = this._touches[unusedIndex] = new cc.Touch(selTouch._point.x, selTouch._point.y, selTouch.getID()); - curTouch._lastModified = now; - curTouch._setPrevPoint(selTouch._prevPoint); - locTouchIntDict[touchID] = unusedIndex; - handleTouches.push(curTouch); - } - } - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.BEGAN; - eventManager.dispatchEvent(touchEvent); - } - }, - - /** - * @method handleTouchesMove - * @param {Array} touches - */ - handleTouchesMove (touches) { - let selTouch, index, touchID, - handleTouches = [], locTouches = this._touches, - now = sys.now(); - for (let i = 0, len = touches.length; i < len; i++) { - selTouch = touches[i]; - touchID = selTouch.getID(); - index = this._touchesIntegerDict[touchID]; - - if (index == null) { - //cc.log("if the index doesn't exist, it is an error"); - continue; - } - if (locTouches[index]) { - locTouches[index]._setPoint(selTouch._point); - locTouches[index]._setPrevPoint(selTouch._prevPoint); - locTouches[index]._lastModified = now; - handleTouches.push(locTouches[index]); - } - } - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.MOVED; - eventManager.dispatchEvent(touchEvent); - } - }, - - /** - * @method handleTouchesEnd - * @param {Array} touches - */ - handleTouchesEnd (touches) { - let handleTouches = this.getSetOfTouchesEndOrCancel(touches); - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.ENDED; - eventManager.dispatchEvent(touchEvent); - } - this._preTouchPool.length = 0; - }, - - /** - * @method handleTouchesCancel - * @param {Array} touches - */ - handleTouchesCancel (touches) { - let handleTouches = this.getSetOfTouchesEndOrCancel(touches); - if (handleTouches.length > 0) { - this._glView._convertTouchesWithScale(handleTouches); - let touchEvent = new cc.Event.EventTouch(handleTouches); - touchEvent._eventCode = cc.Event.EventTouch.CANCELLED; - eventManager.dispatchEvent(touchEvent); - } - this._preTouchPool.length = 0; - }, - - /** - * @method getSetOfTouchesEndOrCancel - * @param {Array} touches - * @returns {Array} - */ - getSetOfTouchesEndOrCancel (touches) { - let selTouch, index, touchID, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict; - for (let i = 0, len = touches.length; i< len; i ++) { - selTouch = touches[i]; - touchID = selTouch.getID(); - index = locTouchesIntDict[touchID]; - - if (index == null) { - continue; //cc.log("if the index doesn't exist, it is an error"); - } - if (locTouches[index]) { - locTouches[index]._setPoint(selTouch._point); - locTouches[index]._setPrevPoint(selTouch._prevPoint); - handleTouches.push(locTouches[index]); - this._removeUsedIndexBit(index); - delete locTouchesIntDict[touchID]; - } - } - return handleTouches; - }, - - /** - * @method getHTMLElementPosition - * @param {HTMLElement} element - * @return {Object} - */ - getHTMLElementPosition (element) { - if (sys.platform === sys.WECHAT_GAME) { - return { - left: 0, - top: 0, - width: window.innerWidth, - height: window.innerHeight - }; - } - - let docElem = document.documentElement; - let leftOffset = window.pageXOffset - docElem.clientLeft; - let topOffset = window.pageYOffset - docElem.clientTop; - if (element.getBoundingClientRect) { - let box = element.getBoundingClientRect(); - return { - left: box.left + leftOffset, - top: box.top + topOffset, - width: box.width, - height: box.height - }; - } - else { - if (element instanceof HTMLCanvasElement) { - return { - left: leftOffset, - top: topOffset, - width: element.width, - height: element.height - }; - } - else { - return { - left: leftOffset, - top: topOffset, - width: parseInt(element.style.width), - height: parseInt(element.style.height) - }; - } - } - }, - - /** - * @method getPreTouch - * @param {Touch} touch - * @return {Touch} - */ - getPreTouch (touch) { - let preTouch = null; - let locPreTouchPool = this._preTouchPool; - let id = touch.getID(); - for (let i = locPreTouchPool.length - 1; i >= 0; i--) { - if (locPreTouchPool[i].getID() === id) { - preTouch = locPreTouchPool[i]; - break; - } - } - if (!preTouch) - preTouch = touch; - return preTouch; - }, - - /** - * @method setPreTouch - * @param {Touch} touch - */ - setPreTouch (touch) { - let find = false; - let locPreTouchPool = this._preTouchPool; - let id = touch.getID(); - for (let i = locPreTouchPool.length - 1; i >= 0; i--) { - if (locPreTouchPool[i].getID() === id) { - locPreTouchPool[i] = touch; - find = true; - break; - } - } - if (!find) { - if (locPreTouchPool.length <= 50) { - locPreTouchPool.push(touch); - } else { - locPreTouchPool[this._preTouchPoolPointer] = touch; - this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50; - } - } - }, - - /** - * @method getTouchByXY - * @param {Number} tx - * @param {Number} ty - * @param {Vec2} pos - * @return {Touch} - */ - getTouchByXY (tx, ty, pos) { - let locPreTouch = this._preTouchPoint; - let location = this._glView.convertToLocationInView(tx, ty, pos); - let touch = new cc.Touch(location.x, location.y, 0); - touch._setPrevPoint(locPreTouch.x, locPreTouch.y); - locPreTouch.x = location.x; - locPreTouch.y = location.y; - return touch; - }, - - /** - * @method getMouseEvent - * @param {Vec2} location - * @param {Vec2} pos - * @param {Number} eventType - * @returns {Event.EventMouse} - */ - getMouseEvent (location, pos, eventType) { - let locPreMouse = this._prevMousePoint; - let mouseEvent = new cc.Event.EventMouse(eventType); - mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y); - locPreMouse.x = location.x; - locPreMouse.y = location.y; - this._glView._convertMouseToLocationInView(locPreMouse, pos); - mouseEvent.setLocation(locPreMouse.x, locPreMouse.y); - return mouseEvent; - }, - - /** - * @method getPointByEvent - * @param {Touch} event - * @param {Vec2} pos - * @return {Vec2} - */ - getPointByEvent (event, pos) { - if (event.pageX != null) //not avalable in <= IE8 - return {x: event.pageX, y: event.pageY}; - - if (sys.platform === sys.WECHAT_GAME) { - pos.left = 0; - pos.top = 0; - } - else { - pos.left -= document.body.scrollLeft; - pos.top -= document.body.scrollTop; - } - return {x: event.clientX, y: event.clientY}; - }, - - /** - * @method getTouchesByEvent - * @param {Touch} event - * @param {Vec2} pos - * @returns {Array} - */ - getTouchesByEvent (event, pos) { - let touchArr = [], locView = this._glView; - let touch_event, touch, preLocation; - let locPreTouch = this._preTouchPoint; - - let length = event.changedTouches.length; - for (let i = 0; i < length; i++) { - touch_event = event.changedTouches[i]; - if (touch_event) { - let location; - if (sys.BROWSER_TYPE_FIREFOX === sys.browserType) - location = locView.convertToLocationInView(touch_event.pageX, touch_event.pageY, pos, _vec2); - else - location = locView.convertToLocationInView(touch_event.clientX, touch_event.clientY, pos, _vec2); - if (touch_event.identifier != null) { - touch = new cc.Touch(location.x, location.y, touch_event.identifier); - //use Touch Pool - preLocation = this.getPreTouch(touch).getLocation(); - touch._setPrevPoint(preLocation.x, preLocation.y); - this.setPreTouch(touch); - } else { - touch = new cc.Touch(location.x, location.y); - touch._setPrevPoint(locPreTouch.x, locPreTouch.y); - } - locPreTouch.x = location.x; - locPreTouch.y = location.y; - touchArr.push(touch); - } - } - return touchArr; - }, - - /** - * @method registerSystemEvent - * @param {HTMLElement} element - */ - registerSystemEvent (element) { - if(this._isRegisterEvent) return; - - this._glView = cc.view; - let selfPointer = this; - - let prohibition = sys.isMobile; - let supportMouse = ('mouse' in sys.capabilities); - let supportTouches = ('touches' in sys.capabilities); - - if (sys.platform === sys.WECHAT_GAME) { - prohibition = false; - supportTouches = true; - supportMouse = false; - } - - if (supportMouse) { - //HACK - // - At the same time to trigger the ontouch event and onmouse event - // - The function will execute 2 times - //The known browser: - // liebiao - // miui - // WECHAT - if (!prohibition) { - window.addEventListener('mousedown', function () { - selfPointer._mousePressed = true; - }, false); - - window.addEventListener('mouseup', function (event) { - if (!selfPointer._mousePressed) - return; - - selfPointer._mousePressed = false; - - let pos = selfPointer.getHTMLElementPosition(element); - let location = selfPointer.getPointByEvent(event, pos); - if (!cc.rect(pos.left, pos.top, pos.width, pos.height).contains(location)){ - selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]); - - let mouseEvent = selfPointer.getMouseEvent(location,pos,cc.Event.EventMouse.UP); - mouseEvent.setButton(event.button); - eventManager.dispatchEvent(mouseEvent); - } - }, false); - } - - // register canvas mouse event - let EventMouse = cc.Event.EventMouse; - let _mouseEventsOnElement = [ - !prohibition && ["mousedown", EventMouse.DOWN, function (event, mouseEvent, location, pos) { - selfPointer._mousePressed = true; - selfPointer.handleTouchesBegin([selfPointer.getTouchByXY(location.x, location.y, pos)]); - element.focus(); - }], - !prohibition && ["mouseup", EventMouse.UP, function (event, mouseEvent, location, pos) { - selfPointer._mousePressed = false; - selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]); - }], - !prohibition && ["mousemove", EventMouse.MOVE, function (event, mouseEvent, location, pos) { - selfPointer.handleTouchesMove([selfPointer.getTouchByXY(location.x, location.y, pos)]); - if (!selfPointer._mousePressed) { - mouseEvent.setButton(null); - } - if (event.movementX !== undefined && event.movementY !== undefined) { - mouseEvent.movementX = event.movementX; - mouseEvent.movementY = event.movementY; - } - }], - ["mousewheel", EventMouse.SCROLL, function (event, mouseEvent) { - mouseEvent.setScrollData(0, event.wheelDelta); - }], - /* firefox fix */ - ["DOMMouseScroll", EventMouse.SCROLL, function (event, mouseEvent) { - mouseEvent.setScrollData(0, event.detail * -120); - }] - ]; - for (let i = 0; i < _mouseEventsOnElement.length; ++i) { - let entry = _mouseEventsOnElement[i]; - if (entry) { - let name = entry[0]; - let type = entry[1]; - let handler = entry[2]; - element.addEventListener(name, function (event) { - let pos = selfPointer.getHTMLElementPosition(element); - let location = selfPointer.getPointByEvent(event, pos); - let mouseEvent = selfPointer.getMouseEvent(location, pos, type); - mouseEvent.setButton(event.button); - - handler(event, mouseEvent, location, pos); - - eventManager.dispatchEvent(mouseEvent); - event.stopPropagation(); - event.preventDefault(); - }, false); - } - } - } - - if (window.navigator.msPointerEnabled) { - let _pointerEventsMap = { - "MSPointerDown" : selfPointer.handleTouchesBegin, - "MSPointerMove" : selfPointer.handleTouchesMove, - "MSPointerUp" : selfPointer.handleTouchesEnd, - "MSPointerCancel" : selfPointer.handleTouchesCancel - }; - for (let eventName in _pointerEventsMap) { - let touchEvent = _pointerEventsMap[eventName]; - element.addEventListener(eventName, function (event){ - let pos = selfPointer.getHTMLElementPosition(element); - pos.left -= document.documentElement.scrollLeft; - pos.top -= document.documentElement.scrollTop; - - touchEvent.call(selfPointer, [selfPointer.getTouchByXY(event.clientX, event.clientY, pos)]); - event.stopPropagation(); - }, false); - } - } - - //register touch event - if (supportTouches) { - let _touchEventsMap = { - "touchstart": function (touchesToHandle) { - selfPointer.handleTouchesBegin(touchesToHandle); - if (sys.platform !== sys.WECHAT_GAME) { - element.focus(); - } - }, - "touchmove": function (touchesToHandle) { - selfPointer.handleTouchesMove(touchesToHandle); - }, - "touchend": function (touchesToHandle) { - selfPointer.handleTouchesEnd(touchesToHandle); - }, - "touchcancel": function (touchesToHandle) { - selfPointer.handleTouchesCancel(touchesToHandle); - } - }; - - let registerTouchEvent; - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - _touchEventsMap = { - onTouchStart: _touchEventsMap.touchstart, - onTouchMove: _touchEventsMap.touchmove, - onTouchEnd: _touchEventsMap.touchend, - onTouchCancel: _touchEventsMap.touchcancel, - }; - registerTouchEvent = function(eventName) { - let handler = _touchEventsMap[eventName]; - wx[eventName](function(event) { - if (!event.changedTouches) return; - let pos = selfPointer.getHTMLElementPosition(element); - let body = document.body; - pos.left -= body.scrollLeft || 0; - pos.top -= body.scrollTop || 0; - handler(selfPointer.getTouchesByEvent(event, pos)); - }); - }; - } - else { - registerTouchEvent = function(eventName) { - let handler = _touchEventsMap[eventName]; - element.addEventListener(eventName, (function(event) { - if (!event.changedTouches) return; - let pos = selfPointer.getHTMLElementPosition(element); - let body = document.body; - pos.left -= body.scrollLeft || 0; - pos.top -= body.scrollTop || 0; - handler(selfPointer.getTouchesByEvent(event, pos)); - event.stopPropagation(); - event.preventDefault(); - }), false); - }; - } - for (let eventName in _touchEventsMap) { - registerTouchEvent(eventName); - } - } - - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - //register keyboard event - this._registerKeyboardEvent(); - } - - this._isRegisterEvent = true; - }, - - /** - * whether enable accelerometer event - * @method setAccelerometerEnabled - * @param {Boolean} isEnable - */ - setAccelerometerEnabled (isEnable) { - let _t = this; - if(_t._accelEnabled === isEnable) - return; - - _t._accelEnabled = isEnable; - let scheduler = cc.director.getScheduler(); - scheduler.enableForTarget(_t); - if (_t._accelEnabled) { - _t._registerAccelerometerEvent(); - _t._accelCurTime = 0; - scheduler.scheduleUpdate(_t); - } else { - _t._unregisterAccelerometerEvent(); - _t._accelCurTime = 0; - scheduler.unscheduleUpdate(_t); - } - }, - - /** - * set accelerometer interval value - * @method setAccelerometerInterval - * @param {Number} interval - */ - setAccelerometerInterval (interval) { - if (this._accelInterval !== interval) { - this._accelInterval = interval; - } - }, - - _registerKeyboardEvent () { - cc.game.canvas.addEventListener("keydown", function (e) { - eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, true)); - e.stopPropagation(); - e.preventDefault(); - }, false); - cc.game.canvas.addEventListener("keyup", function (e) { - eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, false)); - e.stopPropagation(); - e.preventDefault(); - }, false); - }, - - _registerAccelerometerEvent () { - let w = window, _t = this; - _t._acceleration = new Acceleration(); - _t._accelDeviceEvent = w.DeviceMotionEvent || w.DeviceOrientationEvent; - - //TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) - _t._accelDeviceEvent = window.DeviceOrientationEvent; - - let _deviceEventType = (_t._accelDeviceEvent === w.DeviceMotionEvent) ? "devicemotion" : "deviceorientation"; - let ua = navigator.userAgent; - if (/Android/.test(ua) || (/Adr/.test(ua) && cc.sys.browserType === cc.BROWSER_TYPE_UC)) { - _t._minus = -1; - } - - _didAccelerateFun = _t.didAccelerate.bind(_t); - w.addEventListener(_deviceEventType, _didAccelerateFun, false); - }, - - _unregisterAccelerometerEvent () { - let w = window, _t = this; - let _deviceEventType = (_t._accelDeviceEvent === w.DeviceMotionEvent) ? "devicemotion" : "deviceorientation"; - if (_didAccelerateFun) { - w.removeEventListener(_deviceEventType, _didAccelerateFun, false); - } - }, - - didAccelerate (eventData) { - let _t = this, w = window; - if (!_t._accelEnabled) - return; - - let mAcceleration = _t._acceleration; - - let x, y, z; - - if (_t._accelDeviceEvent === window.DeviceMotionEvent) { - let eventAcceleration = eventData["accelerationIncludingGravity"]; - x = _t._accelMinus * eventAcceleration.x * 0.1; - y = _t._accelMinus * eventAcceleration.y * 0.1; - z = eventAcceleration.z * 0.1; - } else { - x = (eventData["gamma"] / 90) * 0.981; - y = -(eventData["beta"] / 90) * 0.981; - z = (eventData["alpha"] / 90) * 0.981; - } - - if (cc.view._isRotated) { - let tmp = x; - x = -y; - y = tmp; - } - mAcceleration.x = x; - mAcceleration.y = y; - mAcceleration.z = z; - - mAcceleration.timestamp = eventData.timeStamp || Date.now(); - - let tmpX = mAcceleration.x; - if (w.orientation === LANDSCAPE_RIGHT) { - mAcceleration.x = -mAcceleration.y; - mAcceleration.y = tmpX; - } else if (w.orientation === LANDSCAPE_LEFT) { - mAcceleration.x = mAcceleration.y; - mAcceleration.y = -tmpX; - } else if (w.orientation === PORTRAIT_UPSIDE_DOWN) { - mAcceleration.x = -mAcceleration.x; - mAcceleration.y = -mAcceleration.y; - } - // fix android acc values are opposite - if (cc.sys.os === cc.sys.OS_ANDROID && - cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ) { - mAcceleration.x = -mAcceleration.x; - mAcceleration.y = -mAcceleration.y; - } - }, - - /** - * @method update - * @param {Number} dt - */ - update (dt) { - if (this._accelCurTime > this._accelInterval) { - this._accelCurTime -= this._accelInterval; - eventManager.dispatchEvent(new cc.Event.EventAcceleration(this._acceleration)); - } - this._accelCurTime += dt; - } -}; - -_cc.inputManager = inputManager; -export default inputManager; \ No newline at end of file diff --git a/cocos/core/platform/event-manager/CCInputManager.ts b/cocos/core/platform/event-manager/CCInputManager.ts new file mode 100644 index 0000000000..9820040367 --- /dev/null +++ b/cocos/core/platform/event-manager/CCInputManager.ts @@ -0,0 +1,786 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + 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 { rect } from '../../value-types/rect'; +import Vec2, { v2 } from '../../value-types/vec2'; +import macro from '../CCMacro'; +import sys from '../CCSys'; +import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './CCEvent'; +import eventManager from './CCEventManager'; +import CCTouch from './CCTouch'; + +const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; + +const PORTRAIT = 0; +const LANDSCAPE_LEFT = -90; +const PORTRAIT_UPSIDE_DOWN = 180; +const LANDSCAPE_RIGHT = 90; + +let _didAccelerateFun; + +const _vec2 = v2(); + +interface IHTMLElementPosition { + left: number; + top: number; + width: number; + height: number; +} + +interface IView { + convertToLocationInView (tx: number, ty: number, elementPosition: IHTMLElementPosition, out?: Vec2): Vec2; + + _convertMouseToLocationInView (point: Vec2, elementPosition: IHTMLElementPosition): void; + + _convertTouchesWithScale (touches: CCTouch[]): void; +} + +/** + * !#en the device accelerometer reports values for each axis in units of g-force. + * !#zh 设备重力传感器传递的各个轴的数据。 + */ +class Acceleration { + public x: number; + public y: number; + public z: number; + public timestamp: number; + constructor (x = 0, y = 0, z = 0, timestamp = 0) { + this.x = x; + this.y = y; + this.z = z; + this.timestamp = timestamp; + } +} + +/** + * This class manages all events of input. include: touch, mouse, accelerometer, keyboard + */ +class InputManager { + private _mousePressed = false; + + private _isRegisterEvent = false; + + private _preTouchPoint = v2(0, 0); + private _prevMousePoint = v2(0, 0); + + private _preTouchPool: CCTouch[] = []; + private _preTouchPoolPointer = 0; + + private _touches: CCTouch[] = []; + private _touchesIntegerDict: { [index: number]: number | undefined; } = { }; + + private _indexBitsUsed = 0; + private _maxTouches = 8; + + private _accelEnabled = false; + private _accelInterval = 1 / 5; + private _accelMinus = 1; + private _accelCurTime = 0; + private _acceleration: Acceleration | null = null; + private _accelDeviceEvent = null; + + private _glView: IView | null = null; + + private _minus = 0; + + public handleTouchesBegin (touches: CCTouch[]) { + const handleTouches: CCTouch[] = []; + const locTouchIntDict = this._touchesIntegerDict; + const now = sys.now(); + for (const touch of touches) { + const touchID = touch.getID(); + if (touchID === null) { + continue; + } + const index = locTouchIntDict[touchID]; + if (index === undefined) { + continue; + } + const unusedIndex = this._getUnUsedIndex(); + if (unusedIndex === -1) { + cc.logID(2300, unusedIndex); + continue; + } + // curTouch = this._touches[unusedIndex] = touch; + const curTouch = new CCTouch(touch._point.x, touch._point.y, touch.getID()); + this._touches[unusedIndex] = curTouch; + curTouch._lastModified = now; + curTouch._setPrevPoint(touch._prevPoint); + locTouchIntDict[touchID] = unusedIndex; + handleTouches.push(curTouch); + } + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.BEGAN; + eventManager.dispatchEvent(touchEvent); + } + } + + public handleTouchesMove (touches: CCTouch[]) { + const handleTouches: CCTouch[] = []; + const locTouches = this._touches; + const now = sys.now(); + for (const touch of touches) { + const touchID = touch.getID(); + if (touchID === null) { + continue; + } + const index = this._touchesIntegerDict[touchID]; + if (index === undefined) { + // cc.log("if the index doesn't exist, it is an error"); + continue; + } + if (locTouches[index]) { + locTouches[index]._setPoint(touch._point); + locTouches[index]._setPrevPoint(touch._prevPoint); + locTouches[index]._lastModified = now; + handleTouches.push(locTouches[index]); + } + } + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.MOVED; + eventManager.dispatchEvent(touchEvent); + } + } + + public handleTouchesEnd (touches: CCTouch[]) { + const handleTouches = this.getSetOfTouchesEndOrCancel(touches); + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.ENDED; + eventManager.dispatchEvent(touchEvent); + } + this._preTouchPool.length = 0; + } + + public handleTouchesCancel (touches: CCTouch[]) { + const handleTouches = this.getSetOfTouchesEndOrCancel(touches); + if (handleTouches.length > 0) { + this._glView!._convertTouchesWithScale(handleTouches); + const touchEvent = new EventTouch(handleTouches); + touchEvent._eventCode = EventTouch.CANCELLED; + eventManager.dispatchEvent(touchEvent); + } + this._preTouchPool.length = 0; + } + + public getSetOfTouchesEndOrCancel (touches: CCTouch[]) { + const handleTouches: CCTouch[] = []; + const locTouches = this._touches; + const locTouchesIntDict = this._touchesIntegerDict; + for (const touch of touches) { + const touchID = touch.getID(); + if (touchID === null) { + continue; + } + const index = locTouchesIntDict[touchID]; + if (index === undefined) { + // cc.log("if the index doesn't exist, it is an error"); + continue; + } + if (locTouches[index]) { + locTouches[index]._setPoint(touch._point); + locTouches[index]._setPrevPoint(touch._prevPoint); + handleTouches.push(locTouches[index]); + this._removeUsedIndexBit(index); + delete locTouchesIntDict[touchID]; + } + } + return handleTouches; + } + + public getHTMLElementPosition (element: HTMLElement): IHTMLElementPosition { + if (sys.platform === sys.WECHAT_GAME) { + return { + left: 0, + top: 0, + width: window.innerWidth, + height: window.innerHeight, + }; + } + + const docElem = document.documentElement; + const leftOffset = window.pageXOffset - docElem.clientLeft; + const topOffset = window.pageYOffset - docElem.clientTop; + if (element.getBoundingClientRect) { + const box = element.getBoundingClientRect(); + return { + left: box.left + leftOffset, + top: box.top + topOffset, + width: box.width, + height: box.height, + }; + } else { + if (element instanceof HTMLCanvasElement) { + return { + left: leftOffset, + top: topOffset, + width: element.width, + height: element.height, + }; + } else { + return { + left: leftOffset, + top: topOffset, + width: parseInt(element.style.width || '0', undefined), + height: parseInt(element.style.height || '0', undefined), + }; + } + } + } + + public getPreTouch (touch: CCTouch) { + let preTouch: CCTouch | null = null; + const locPreTouchPool = this._preTouchPool; + const id = touch.getID(); + for (let i = locPreTouchPool.length - 1; i >= 0; i--) { + if (locPreTouchPool[i].getID() === id) { + preTouch = locPreTouchPool[i]; + break; + } + } + if (!preTouch) { + preTouch = touch; + } + return preTouch; + } + + public setPreTouch (touch: CCTouch) { + let find = false; + const locPreTouchPool = this._preTouchPool; + const id = touch.getID(); + for (let i = locPreTouchPool.length - 1; i >= 0; i--) { + if (locPreTouchPool[i].getID() === id) { + locPreTouchPool[i] = touch; + find = true; + break; + } + } + if (!find) { + if (locPreTouchPool.length <= 50) { + locPreTouchPool.push(touch); + } else { + locPreTouchPool[this._preTouchPoolPointer] = touch; + this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50; + } + } + } + + public getTouchByXY (tx: number, ty: number, pos: IHTMLElementPosition) { + const locPreTouch = this._preTouchPoint; + const location = this._glView!.convertToLocationInView(tx, ty, pos); + const touch = new CCTouch(location.x, location.y, 0); + touch._setPrevPoint(locPreTouch.x, locPreTouch.y); + locPreTouch.x = location.x; + locPreTouch.y = location.y; + return touch; + } + + public getMouseEvent ( + location: { x: number; y: number; }, pos: IHTMLElementPosition, eventType: number): EventMouse { + const locPreMouse = this._prevMousePoint; + const mouseEvent = new EventMouse(eventType); + mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y); + locPreMouse.x = location.x; + locPreMouse.y = location.y; + this._glView!._convertMouseToLocationInView(locPreMouse, pos); + mouseEvent.setLocation(locPreMouse.x, locPreMouse.y); + return mouseEvent; + } + + public getPointByEvent (event: MouseEvent, pos: IHTMLElementPosition) { + if (event.pageX != null) { // not avalable in <= IE8 + return {x: event.pageX, y: event.pageY}; + } + + if (sys.platform === sys.WECHAT_GAME) { + pos.left = 0; + pos.top = 0; + } else { + pos.left -= document.body.scrollLeft; + pos.top -= document.body.scrollTop; + } + return {x: event.clientX, y: event.clientY}; + } + + public getTouchesByEvent (event: TouchEvent, position: IHTMLElementPosition) { + const touches: CCTouch[] = []; + const locView = this._glView; + const locPreTouch = this._preTouchPoint; + + const length = event.changedTouches.length; + for (let i = 0; i < length; i++) { + const changedTouch = event.changedTouches.item(i); + if (!changedTouch) { + continue; + } + let location; + if (sys.BROWSER_TYPE_FIREFOX === sys.browserType) { + location = locView!.convertToLocationInView( + changedTouch.pageX, changedTouch.pageY, position, _vec2); + } else { + location = locView!.convertToLocationInView( + changedTouch.clientX, changedTouch.clientY, position, _vec2); + } + let touch: CCTouch; + if (changedTouch.identifier != null) { + touch = new CCTouch(location.x, location.y, changedTouch.identifier); + // use Touch Pool + const preLocation = this.getPreTouch(touch).getLocation(); + touch._setPrevPoint(preLocation.x, preLocation.y); + this.setPreTouch(touch); + } else { + touch = new CCTouch(location.x, location.y); + touch._setPrevPoint(locPreTouch.x, locPreTouch.y); + } + locPreTouch.x = location.x; + locPreTouch.y = location.y; + touches.push(touch); + } + return touches; + } + + public registerSystemEvent (element: HTMLElement) { + if (this._isRegisterEvent) { + return; + } + + this._glView = cc.view; + + let prohibition = sys.isMobile; + let supportMouse = ('mouse' in sys.capabilities); + let supportTouches = ('touches' in sys.capabilities); + if (sys.platform === sys.WECHAT_GAME) { + prohibition = false; + supportTouches = true; + supportMouse = false; + } + + // Register mouse events. + if (supportMouse) { + this._registerMouseEvents(element, prohibition); + } + + // Register mouse pointer events. + if (window.navigator.msPointerEnabled) { + this._registerMousePointerEvents(element); + } + + // Register touch events. + if (supportTouches) { + this._registerTouchEvents(element); + } + + // Register keyboard events. + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + this._registerKeyboardEvent(); + } + + this._isRegisterEvent = true; + } + + /** + * Whether enable accelerometer event. + */ + public setAccelerometerEnabled (isEnable: boolean) { + if (this._accelEnabled === isEnable) { + return; + } + + this._accelEnabled = isEnable; + const scheduler = cc.director.getScheduler(); + scheduler.enableForTarget(this); + if (this._accelEnabled) { + this._registerAccelerometerEvent(); + this._accelCurTime = 0; + scheduler.scheduleUpdate(this); + } else { + this._unregisterAccelerometerEvent(); + this._accelCurTime = 0; + scheduler.unscheduleUpdate(this); + } + } + + public didAccelerate (eventData: DeviceMotionEvent | DeviceOrientationEvent) { + if (!this._accelEnabled) { + return; + } + + const mAcceleration = this._acceleration!; + + let x = 0; + let y = 0; + let z = 0; + + // TODO + // @ts-ignore + if (this._accelDeviceEvent === window.DeviceMotionEvent) { + const deviceMotionEvent = eventData as DeviceMotionEvent; + const eventAcceleration = deviceMotionEvent.accelerationIncludingGravity; + if (eventAcceleration) { + x = this._accelMinus * (eventAcceleration.x || 0) * 0.1; + y = this._accelMinus * (eventAcceleration.y || 0) * 0.1; + z = (eventAcceleration.z || 0) * 0.1; + } + } else { + const deviceOrientationEvent = eventData as DeviceOrientationEvent; + x = ((deviceOrientationEvent.gamma || 0) / 90) * 0.981; + y = -((deviceOrientationEvent.beta || 0) / 90) * 0.981; + z = ((deviceOrientationEvent.alpha || 0) / 90) * 0.981; + } + + if (cc.view._isRotated) { + const tmp = x; + x = -y; + y = tmp; + } + mAcceleration.x = x; + mAcceleration.y = y; + mAcceleration.z = z; + + mAcceleration.timestamp = eventData.timeStamp || Date.now(); + + const tmpX = mAcceleration.x; + if (window.orientation === LANDSCAPE_RIGHT) { + mAcceleration.x = -mAcceleration.y; + mAcceleration.y = tmpX; + } else if (window.orientation === LANDSCAPE_LEFT) { + mAcceleration.x = mAcceleration.y; + mAcceleration.y = -tmpX; + } else if (window.orientation === PORTRAIT_UPSIDE_DOWN) { + mAcceleration.x = -mAcceleration.x; + mAcceleration.y = -mAcceleration.y; + } + // fix android acc values are opposite + if (cc.sys.os === cc.sys.OS_ANDROID && + cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ) { + mAcceleration.x = -mAcceleration.x; + mAcceleration.y = -mAcceleration.y; + } + } + + public update (dt: number) { + if (this._accelCurTime > this._accelInterval) { + this._accelCurTime -= this._accelInterval; + eventManager.dispatchEvent(new EventAcceleration(this._acceleration!)); + } + this._accelCurTime += dt; + } + + private _getUnUsedIndex () { + let temp = this._indexBitsUsed; + const now = cc.sys.now(); + + for (let i = 0; i < this._maxTouches; i++) { + if (!(temp & 0x00000001)) { + this._indexBitsUsed |= (1 << i); + return i; + } else { + const touch = this._touches[i]; + if (now - touch._lastModified > TOUCH_TIMEOUT) { + this._removeUsedIndexBit(i); + const touchID = touch.getID(); + if (touchID !== null) { + delete this._touchesIntegerDict[touchID]; + } + return i; + } + } + temp >>= 1; + } + + // all bits are used + return -1; + } + + private _removeUsedIndexBit (index) { + if (index < 0 || index >= this._maxTouches) { + return; + } + + let temp = 1 << index; + temp = ~temp; + this._indexBitsUsed &= temp; + } + + /** + * set accelerometer interval value + * @method setAccelerometerInterval + * @param {Number} interval + */ + private setAccelerometerInterval (interval) { + if (this._accelInterval !== interval) { + this._accelInterval = interval; + } + } + + private _registerMouseEvents (element: HTMLElement, prohibition: boolean) { + // HACK + // - At the same time to trigger the ontouch event and onmouse event + // - The function will execute 2 times + // The known browser: + // liebiao + // miui + // WECHAT + if (!prohibition) { + this._registerWindowMouseEvents(element); + } + this._registerElementMouseEvents(element, prohibition); + } + + private _registerWindowMouseEvents (element: HTMLElement) { + window.addEventListener('mousedown', () => { + this._mousePressed = true; + }, false); + window.addEventListener('mouseup', (event: MouseEvent) => { + if (!this._mousePressed) { + return; + } + this._mousePressed = false; + const position = this.getHTMLElementPosition(element); + const location = this.getPointByEvent(event, position); + const positionRect = rect(position.left, position.top, position.width, position.height); + if (!positionRect.contains(v2(location.x, location.y))) { + this.handleTouchesEnd([this.getTouchByXY(location.x, location.y, position)]); + const mouseEvent = this.getMouseEvent(location, position, EventMouse.UP); + mouseEvent.setButton(event.button); + eventManager.dispatchEvent(mouseEvent); + } + }, false); + } + + private _registerElementMouseEvents (element: HTMLElement, prohibition: boolean) { + // Register canvas mouse events. + type Handler = ( + event: MouseEvent, + mouseEvent: EventMouse, + location: { x: number; y: number; }, + elementPosition: IHTMLElementPosition, + ) => void; + + type MouseEventNames = 'mousedown' | 'mouseup' | 'mousemove'; + + const listenDOMMouseEvent = (eventName: MouseEventNames, type: number, handler: Handler) => { + element.addEventListener(eventName, (event) => { + const pos = this.getHTMLElementPosition(element); + const location = this.getPointByEvent(event, pos); + const mouseEvent = this.getMouseEvent(location, pos, type); + mouseEvent.setButton(event.button); + + handler(event, mouseEvent, location, pos); + + eventManager.dispatchEvent(mouseEvent); + event.stopPropagation(); + event.preventDefault(); + }); + }; + + if (!prohibition) { + listenDOMMouseEvent('mousedown', EventMouse.DOWN, (event, mouseEvent, location, pos) => { + this._mousePressed = true; + this.handleTouchesBegin([this.getTouchByXY(location.x, location.y, pos)]); + element.focus(); + }); + + listenDOMMouseEvent('mouseup', EventMouse.UP, (event, mouseEvent, location, pos) => { + this._mousePressed = false; + this.handleTouchesEnd([this.getTouchByXY(location.x, location.y, pos)]); + }); + + listenDOMMouseEvent('mousemove', EventMouse.MOVE, (event, mouseEvent, location, pos) => { + this.handleTouchesMove([this.getTouchByXY(location.x, location.y, pos)]); + if (!this._mousePressed) { + mouseEvent.setButton(null); + } + if (event.movementX !== undefined && event.movementY !== undefined) { + mouseEvent.movementX = event.movementX; + mouseEvent.movementY = event.movementY; + } + }); + } + + // @ts-ignore + listenDOMMouseEvent('mousewheel', EventMouse.SCROLL, (event, mouseEvent, location, pos) => { + mouseEvent.setScrollData(0, event.wheelDelta); + }); + + /* firefox fix */ + // @ts-ignore + listenDOMMouseEvent('DOMMouseScroll', EventMouse.SCROLL, (event, mouseEvent, location, pos) => { + mouseEvent.setScrollData(0, event.detail * -120); + }); + } + + private _registerMousePointerEvents (element: HTMLElement) { + const _pointerEventsMap = { + MSPointerDown : this.handleTouchesBegin, + MSPointerMove : this.handleTouchesMove, + MSPointerUp : this.handleTouchesEnd, + MSPointerCancel : this.handleTouchesCancel, + }; + for (const eventName of Object.keys(_pointerEventsMap)) { + const touchEvent = _pointerEventsMap[eventName]; + // @ts-ignore + element.addEventListener(eventName as MSPointerEventNames, (event: MSPointerEvent) => { + const pos = this.getHTMLElementPosition(element); + pos.left -= document.documentElement.scrollLeft; + pos.top -= document.documentElement.scrollTop; + touchEvent.call(this, [this.getTouchByXY(event.clientX, event.clientY, pos)]); + event.stopPropagation(); + }, false); + } + } + + private _registerTouchEvents (element: HTMLElement) { + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + this._registerWXGameTouchEvents(element); + } else { + this._registerHTMLTouchEvents(element); + } + } + + private _registerWXGameTouchEvents (element: HTMLElement) { + const makeTouchListener = (touchesHandler: (touchesToHandle: any) => void) => { + return (event: TouchEvent) => { + const pos = this.getHTMLElementPosition(element); + const body = document.body; + pos.left -= body.scrollLeft || 0; + pos.top -= body.scrollTop || 0; + touchesHandler(this.getTouchesByEvent(event, pos)); + }; + }; + + wx.onTouchStart(makeTouchListener((touchesToHandle) => { + this.handleTouchesBegin(touchesToHandle); + })); + wx.onTouchEnd(makeTouchListener((touchesToHandle) => { + this.handleTouchesEnd(touchesToHandle); + })); + wx.onTouchMove(makeTouchListener((touchesToHandle) => { + this.handleTouchesMove(touchesToHandle); + })); + wx.onTouchCancel(makeTouchListener((touchesToHandle) => { + this.handleTouchesCancel(touchesToHandle); + })); + } + + private _registerHTMLTouchEvents (element: HTMLElement) { + const makeTouchListener = (touchesHandler: (touchesToHandle: any) => void) => { + return (event: TouchEvent) => { + if (!event.changedTouches) { + return; + } + const pos = this.getHTMLElementPosition(element); + const body = document.body; + pos.left -= body.scrollLeft || 0; + pos.top -= body.scrollTop || 0; + touchesHandler(this.getTouchesByEvent(event, pos)); + event.stopPropagation(); + event.preventDefault(); + }; + }; + + element.addEventListener('touchstart', makeTouchListener((touchesToHandle) => { + this.handleTouchesBegin(touchesToHandle); + if (sys.platform !== sys.WECHAT_GAME) { + element.focus(); + } + }), false); + + element.addEventListener('touchmove', makeTouchListener((touchesToHandle) => { + this.handleTouchesMove(touchesToHandle); + }), false); + + element.addEventListener('touchend', makeTouchListener((touchesToHandle) => { + this.handleTouchesEnd(touchesToHandle); + }), false); + + element.addEventListener('touchcancel', makeTouchListener((touchesToHandle) => { + this.handleTouchesCancel(touchesToHandle); + }), false); + } + + private _registerKeyboardEvent () { + const canvas = cc.game.canvas as HTMLCanvasElement; + canvas.addEventListener('keydown', (event: KeyboardEvent) => { + eventManager.dispatchEvent(new EventKeyboard(event.keyCode, true)); + event.stopPropagation(); + event.preventDefault(); + }, false); + canvas.addEventListener('keyup', (event: KeyboardEvent) => { + eventManager.dispatchEvent(new EventKeyboard(event.keyCode, false)); + event.stopPropagation(); + event.preventDefault(); + }, false); + } + + private _registerAccelerometerEvent () { + this._acceleration = new Acceleration(); + // TODO + // @ts-ignore + this._accelDeviceEvent = window.DeviceMotionEvent || window.DeviceOrientationEvent; + + // TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) { + // TODO + // @ts-ignore + this._accelDeviceEvent = window.DeviceOrientationEvent; + } + + const _deviceEventType = + // TODO + // @ts-ignore + this._accelDeviceEvent === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation'; + const ua = navigator.userAgent; + if (/Android/.test(ua) || (/Adr/.test(ua) && cc.sys.browserType === cc.BROWSER_TYPE_UC)) { + this._minus = -1; + } + + // @ts-ignore + _didAccelerateFun = (...args: any[]) => this.didAccelerate(...args); + window.addEventListener(_deviceEventType, _didAccelerateFun, false); + } + + private _unregisterAccelerometerEvent () { + const _deviceEventType = + // TODO + // @ts-ignore + this._accelDeviceEvent === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation'; + if (_didAccelerateFun) { + window.removeEventListener(_deviceEventType, _didAccelerateFun, false); + } + } +} + +const inputManager = new InputManager(); + +export default inputManager; + +_cc.inputManager = inputManager; diff --git a/cocos/core/platform/event-manager/CCTouch.js b/cocos/core/platform/event-manager/CCTouch.ts similarity index 64% rename from cocos/core/platform/event-manager/CCTouch.js rename to cocos/core/platform/event-manager/CCTouch.ts index 29e6967121..c53614c582 100644 --- a/cocos/core/platform/event-manager/CCTouch.js +++ b/cocos/core/platform/event-manager/CCTouch.ts @@ -1,3 +1,6 @@ +import { Vec2 } from '../../value-types'; +import { v2 } from '../../value-types/vec2'; + /**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. @@ -34,145 +37,136 @@ * @param {Number} id */ export default class Touch { - constructor (x, y, id) { - this._lastModified = 0; + public _point: Vec2 = v2(); + public _prevPoint: Vec2 = v2(); + public _lastModified = 0; + private _id: number | null = null; + private _startPoint: Vec2 = v2(); + private _startPointCaptured: boolean = false; + + constructor (x: number, y: number, id: number | null = null) { this.setTouchInfo(id, x, y); } /** * !#en Returns the current touch location in OpenGL coordinates.、 * !#zh 获取当前触点位置。 - * @method getLocation - * @return {Vec2} */ - getLocation () { - return cc.v2(this._point.x, this._point.y); + public getLocation () { + return v2(this._point.x, this._point.y); } - /** - * !#en Returns X axis location value. + /** + * !#en Returns X axis location value. * !#zh 获取当前触点 X 轴位置。 - * @method getLocationX - * @returns {Number} - */ - getLocationX () { - return this._point.x; - } + */ + public getLocationX () { + return this._point.x; + } - /** + /** * !#en Returns Y axis location value. * !#zh 获取当前触点 Y 轴位置。 - * @method getLocationY - * @returns {Number} - */ - getLocationY () { - return this._point.y; - } + */ + public getLocationY () { + return this._point.y; + } /** * !#en Returns the previous touch location in OpenGL coordinates. * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} */ - getPreviousLocation () { - return cc.v2(this._prevPoint.x, this._prevPoint.y); + public getPreviousLocation () { + return v2(this._prevPoint.x, this._prevPoint.y); } /** * !#en Returns the start touch location in OpenGL coordinates. * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 - * @method getStartLocation - * @returns {Vec2} */ - getStartLocation () { - return cc.v2(this._startPoint.x, this._startPoint.y); + public getStartLocation () { + return v2(this._startPoint.x, this._startPoint.y); } /** * !#en Returns the delta distance from the previous touche to the current one in screen coordinates. * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} */ - getDelta () { + public getDelta () { return this._point.sub(this._prevPoint); } /** * !#en Returns the current touch location in screen coordinates. * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 - * @method getLocationInView - * @return {Vec2} */ - getLocationInView () { - return cc.v2(this._point.x, cc.view._designResolutionSize.height - this._point.y); + public getLocationInView () { + return v2(this._point.x, cc.view._designResolutionSize.height - this._point.y); } /** * !#en Returns the previous touch location in screen coordinates. * !#zh 获取触点在上一次事件时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocationInView - * @return {Vec2} */ - getPreviousLocationInView () { - return cc.v2(this._prevPoint.x, cc.view._designResolutionSize.height - this._prevPoint.y); + public getPreviousLocationInView () { + return v2(this._prevPoint.x, cc.view._designResolutionSize.height - this._prevPoint.y); } /** * !#en Returns the start touch location in screen coordinates. * !#zh 获取触点落下时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 - * @method getStartLocationInView - * @return {Vec2} */ - getStartLocationInView () { - return cc.v2(this._startPoint.x, cc.view._designResolutionSize.height - this._startPoint.y); + public getStartLocationInView () { + return v2(this._startPoint.x, cc.view._designResolutionSize.height - this._startPoint.y); } /** * !#en Returns the id of cc.Touch. * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 - * @method getID - * @return {Number} */ - getID () { + public getID () { return this._id; } /** * !#en Sets information to touch. * !#zh 设置触摸相关的信息。用于监控触摸事件。 - * @method setTouchInfo - * @param {Number} id - * @param {Number} x - * @param {Number} y */ - setTouchInfo (id, x, y) { + public setTouchInfo (id: number | null = null, x?: number, y?: number) { this._prevPoint = this._point; - this._point = cc.v2(x || 0, y || 0); + this._point = v2(x || 0, y || 0); this._id = id; - if(!this._startPointCaptured){ - this._startPoint = cc.v2(this._point); + if (!this._startPointCaptured) { + this._startPoint = v2(this._point); cc.view._convertPointWithScale(this._startPoint); this._startPointCaptured = true; } } - _setPoint (x, y) { - if(y === undefined){ + public _setPoint (point: Vec2): void; + + public _setPoint (x: number, y: number): void; + + public _setPoint (x: number | Vec2, y?: number) { + if (typeof x === 'object') { this._point.x = x.x; this._point.y = x.y; - }else{ - this._point.x = x; - this._point.y = y; + } else { + this._point.x = x || 0; + this._point.y = y || 0; } } - _setPrevPoint (x, y) { - if(y === undefined) - this._prevPoint = cc.v2(x.x, x.y); - else - this._prevPoint = cc.v2(x || 0, y || 0); + public _setPrevPoint (point: Vec2): void; + + public _setPrevPoint (x: number, y: number): void; + + public _setPrevPoint (x: number | Vec2, y?: number) { + if (typeof x === 'object') { + this._prevPoint = v2(x.x, x.y); + } else { + this._prevPoint = v2(x || 0, y || 0); + } } } diff --git a/cocos/core/platform/event-manager/index.js b/cocos/core/platform/event-manager/index.ts similarity index 97% rename from cocos/core/platform/event-manager/index.js rename to cocos/core/platform/event-manager/index.ts index e420c8fb0c..fef8f81d68 100644 --- a/cocos/core/platform/event-manager/index.js +++ b/cocos/core/platform/event-manager/index.ts @@ -31,6 +31,5 @@ export * from './CCEvent'; export * from './CCTouch'; if (CC_TEST) { - cc._Test.eventManager = eventManager; + // cc._Test.eventManager = eventManager; } - diff --git a/wx.d.ts b/wx.d.ts new file mode 100644 index 0000000000..12434cc7fc --- /dev/null +++ b/wx.d.ts @@ -0,0 +1,11 @@ + +declare interface IWXEventManager { + (listener: (event: Event) => void): void; +} + +declare namespace wx { + const onTouchStart: IWXEventManager; + const onTouchMove: IWXEventManager; + const onTouchEnd: IWXEventManager; + const onTouchCancel: IWXEventManager; +}